Skip to content

Commit

Permalink
Merge pull request #146 from boostcampwm-2024/be/feature/order
Browse files Browse the repository at this point in the history
[Be/feature] 주문 취소, 주문 조회 API 수정
  • Loading branch information
HBLEEEEE authored Dec 2, 2024
2 parents 48aed4b + 2ce0b29 commit 26254c9
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 9 deletions.
8 changes: 7 additions & 1 deletion apps/backend/src/global/filter/errorExceptionFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,15 @@ export class ErrorExceptionFilter implements ExceptionFilter {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
const exceptionResponse = exception.getResponse() as { message: string; data?: any }; // 타입 단언

const message = exceptionResponse.message;
const data = exceptionResponse.data;

response.status(status).json({
code: status,
message: exception.message
message,
data // 추가 데이터 포함
});
}
}
3 changes: 3 additions & 0 deletions apps/backend/src/order/dto/pendingOrder.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export class PendingOrderDto {
@ApiProperty({ description: '주문 타입', example: 'buy' })
orderType: string;

@ApiProperty({ description: '거래 타입', example: 'limit' })
tradingType: string;

@ApiProperty({ description: '주문 가격', example: 100 })
price: number;

Expand Down
9 changes: 9 additions & 0 deletions apps/backend/src/order/enums/orderType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,12 @@ export function toTradingType(tradingType: string): TradingType {

throw new Error(`잘못된 트레이딩 타입입니다. ${tradingType}`);
}

export function toOrderStatus(orderStatus: string): OrderStatus {
if (orderStatus === 'pending') return OrderStatus.PENDING;
if (orderStatus === 'partially_filled') return OrderStatus.PARTIALLY_FILLED;
if (orderStatus === 'completed') return OrderStatus.COMPLETED;
if (orderStatus === 'canceled') return OrderStatus.CANCELED;

throw new Error(`잘못된 오더 상태입니다. ${orderStatus}`);
}
43 changes: 37 additions & 6 deletions apps/backend/src/order/order.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, HttpException, HttpStatus, Post, UseGuards } from '@nestjs/common';
import { OrderService } from './order.service';
import { OrderBookService } from './orderBook.service';
import DtoTransformer from './utils/dtoTransformer';
import { LimitOrderDto } from './dto/limitOrder.dto';
import { ApiOperation } from '@nestjs/swagger';
import { MatchingService } from './matching.service';
import { successhandler, successMessage } from '../global/successhandler';
import { cancelOrderResponseDecorator, orderResponseDecorator } from './decorator/order.decorator';
import { orderResponseDecorator } from './decorator/order.decorator';
import { transactionResponseDecorator } from './decorator/getTransactions.decorator';
import { HasSufficientCashGuard } from '../account/guards/hasSufficientCashGuard';
import { AccountService } from '../account/account.service';
Expand All @@ -15,6 +15,7 @@ import { MarketOrderDto } from './dto/marketOrder.dto';
import { User } from '../global/utils/memberData';
import { CancelOrderDto } from './dto/cancelOrder.dto';
import { pendingOrdersDecorator } from './decorator/getPendingOrders.decorator';
import { OrderStatus } from './enums/orderType';

@Controller('api/order')
export class OrderController {
Expand Down Expand Up @@ -129,13 +130,43 @@ export class OrderController {

@Post('cancel')
@ApiOperation({ summary: '주문 취소' })
@cancelOrderResponseDecorator()
@pendingOrdersDecorator()
async cancelOrder(@User() user: { memberId: number }, @Body() cancelOrderDto: CancelOrderDto) {
const { memberId } = user;
const { cropId, orderId, orderType, tradingType } = cancelOrderDto;

await this.orderBookService.removeOrder(memberId, cropId, orderId, orderType, tradingType);
await this.orderService.cancelOrder(memberId, orderId, cropId, orderType);
return successhandler(successMessage.DELETE_ORDER_SUCCESS);
try {
const orderStatus = await this.orderService.getOrderStatus(memberId, orderId);
if (orderStatus === OrderStatus.CANCELED || orderStatus === OrderStatus.COMPLETED) {
const pendingOrders = await this.orderService.getPendingOrdersByMemberId(memberId);
throw new HttpException(
{
message: '이미 취소되었거나 완료된 주문입니다.',
data: pendingOrders
},
HttpStatus.BAD_REQUEST
);
}

await this.orderBookService.removeOrder(memberId, cropId, orderId, orderType, tradingType);
await this.orderService.cancelOrder(memberId, orderId, cropId, orderType);
const pendingOrders = await this.orderService.getPendingOrdersByMemberId(memberId);

return {
code: 200,
message: successMessage.DELETE_ORDER_SUCCESS,
data: pendingOrders
};
} catch (error) {
if (error instanceof HttpException && error.getStatus() === HttpStatus.NOT_FOUND) {
const pendingOrders = await this.orderService.getPendingOrdersByMemberId(memberId);
return {
code: HttpStatus.NOT_FOUND,
message: '주문이 존재하지 않습니다.',
data: pendingOrders
};
}
throw error;
}
}
}
21 changes: 19 additions & 2 deletions apps/backend/src/order/order.repository.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { OrderDto } from './dto/order.dto';
import { OrderStatus, TradingType } from './enums/orderType';
import { OrderStatus, toOrderStatus, TradingType } from './enums/orderType';
import { OrderBookDto } from './dto/orderBook.dto';
import { TransactionDto } from './dto/transaction.dto';
import { Client } from 'pg';
Expand Down Expand Up @@ -178,6 +178,7 @@ export class OrderRepository {
orderId: data.order_id,
cropId: data.crop_id,
orderType: data.order_type,
tradingType: data.trading_type,
price: data.price,
quantity: data.quantity,
filledQuantity: data.filled_quantity,
Expand Down Expand Up @@ -228,4 +229,20 @@ export class OrderRepository {
async runInTransaction(callback: (client: Client) => Promise<void>): Promise<void> {
await this.databaseService.runInTransaction(callback);
}

async getOrderStatus(memberId: number, orderId: number): Promise<OrderStatus> {
const query = `
SELECT status
FROM orders
WHERE order_id = $1
AND member_id = $2
`;
const values = [orderId, memberId];
const result = await this.databaseService.query(query, values);

if (result.rows.length === 0) {
throw new HttpException('주문이 존재하지 않습니다.', HttpStatus.NOT_FOUND);
}
return toOrderStatus(result.rows[0]?.status);
}
}
4 changes: 4 additions & 0 deletions apps/backend/src/order/order.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,8 @@ export class OrderService {
async getPendingOrdersByMemberId(memberId: number): Promise<PendingOrderDto[]> {
return await this.orderRepository.getPendingOrdersByMemberId(memberId);
}

async getOrderStatus(memberId: number, orderId: number): Promise<OrderStatus> {
return await this.orderRepository.getOrderStatus(memberId, orderId);
}
}

0 comments on commit 26254c9

Please sign in to comment.