72 lines
2.3 KiB
TypeScript
72 lines
2.3 KiB
TypeScript
import { Body, Controller, Post } from '@nestjs/common';
|
|
import { TradeService } from '../modules/trade/trade.service';
|
|
import { CourierService } from '../integrations/courier/courier.service';
|
|
import { PrismaService } from '../common/prisma/prisma.module';
|
|
import { logCourierCall } from '../integrations/courier/courier-log.util';
|
|
|
|
@Controller('callbacks/delivery')
|
|
export class DeliveryCallbackController {
|
|
constructor(
|
|
private readonly tradeService: TradeService,
|
|
private readonly courier: CourierService,
|
|
private readonly prisma: PrismaService,
|
|
) {}
|
|
|
|
@Post('track')
|
|
async track(@Body() body: { orderNo?: string; orderId?: string; status?: string }) {
|
|
const baseLog = {
|
|
scene: 'TRACK_CALLBACK',
|
|
requestUrl: '/api/v1/callbacks/delivery/track',
|
|
requestBody: body as Record<string, unknown>,
|
|
};
|
|
|
|
if (!body.orderId && !body.orderNo) {
|
|
await logCourierCall(this.prisma, {
|
|
...baseLog,
|
|
status: 'FAILED',
|
|
errorMessage: '缺少 orderId / orderNo',
|
|
});
|
|
return this.courier.buildTrackCallbackResponse(false);
|
|
}
|
|
|
|
const order = body.orderId
|
|
? await this.prisma.order.findUnique({ where: { id: BigInt(body.orderId) } })
|
|
: await this.prisma.order.findUnique({ where: { orderNo: body.orderNo! } });
|
|
|
|
if (!order) {
|
|
await logCourierCall(this.prisma, {
|
|
...baseLog,
|
|
status: 'FAILED',
|
|
errorMessage: '订单不存在',
|
|
externalNo: body.orderNo,
|
|
});
|
|
return this.courier.buildTrackCallbackResponse(false);
|
|
}
|
|
|
|
const statusMap: Record<string, string> = {
|
|
SHIPPED: 'SHIPPING',
|
|
OUT_WAREHOUSE: 'OUT_WAREHOUSE',
|
|
DELIVERED: 'COMPLETED',
|
|
COMPLETED: 'COMPLETED',
|
|
};
|
|
const target = statusMap[body.status ?? ''] ?? body.status;
|
|
let applied = false;
|
|
if (target && target !== order.status) {
|
|
await this.tradeService.applyStatusTransition(order.id, order.status, target, 'DELIVERY_CALLBACK');
|
|
applied = true;
|
|
}
|
|
|
|
const response = this.courier.buildTrackCallbackResponse(true);
|
|
await logCourierCall(this.prisma, {
|
|
...baseLog,
|
|
responseBody: response,
|
|
status: 'SUCCESS',
|
|
externalNo: order.orderNo,
|
|
ref: { refType: 'ORDER', refId: order.id },
|
|
errorMessage: applied ? undefined : '状态未变更',
|
|
});
|
|
|
|
return response;
|
|
}
|
|
}
|