Files
points-mall/supplied-service/netlify/functions/order-cancel-main.ts
T

133 lines
3.2 KiB
TypeScript

import type { Context } from '@netlify/functions'
import { guardMethod } from '../utils/method.js'
import { fail, ok } from '../utils/http.js'
import { readJson } from '../utils/request.js'
import { prisma } from '../utils/prisma.js'
import { withErrorBoundary } from '../utils/handler.js'
type OrderCancelMainRequest = {
supplierId?: string
token?: string
userId?: string
orderId?: string
mainOrderId?: string
}
type BridgeOrderResponse = {
resultCode?: number
message?: string
}
const normalizeBase = (base: string) => base.replace(/\/$/, '')
export default withErrorBoundary(async (request: Request, _context: Context) => {
const methodResponse = guardMethod(request, ['POST'])
if (methodResponse) return methodResponse
const body = await readJson<OrderCancelMainRequest>(request)
const supplierId = String(body.supplierId || '').trim()
const token = String(body.token || '').trim()
const userId = String(body.userId || '').trim()
const mainOrderId = String(body.mainOrderId || body.orderId || '').trim()
const orderId = String(body.orderId || mainOrderId).trim()
if (!supplierId || !token || !userId || !mainOrderId) {
return fail('供应商、用户、授权或订单信息不能为空')
}
const apiBase = normalizeBase(process.env.POINTS_MALL_OPEN_API_BASE || '')
if (!apiBase) {
return fail('平台积分商城接口地址未配置', 500, 'OPEN_API_BASE_MISSING')
}
const order = await prisma.supplierOrderMain.findFirst({
where: {
orderId: mainOrderId,
supplierId,
userId,
deleted: 0
}
})
if (!order) {
return fail('主单不存在或已取消', 404, 'MAIN_ORDER_NOT_FOUND')
}
const bridgeResponse = await fetch(`${apiBase}/pointOrder/pushOrderInfoMsg`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
token
},
body: JSON.stringify({
supplierId,
orderType: 1,
orderId,
mainOrderId,
userId,
time: Date.now(),
token
})
})
const bridgePayload = (await bridgeResponse.json().catch(() => ({}))) as BridgeOrderResponse
if (!bridgeResponse.ok || bridgePayload.resultCode !== 0) {
return fail(bridgePayload.message || '取消主单推送失败', 502, 'BRIDGE_CANCEL_MAIN_FAILED')
}
const subOrders = await prisma.supplierOrderSub.findMany({
where: {
mainOrderId,
supplierId,
userId,
deleted: 0
},
select: {
orderId: true
}
})
const subOrderIds = subOrders.map(item => item.orderId)
await prisma.$transaction(async tx => {
await tx.supplierOrderMain.update({
where: { orderId: mainOrderId },
data: {
deleted: 1,
updateTime: new Date()
}
})
await tx.supplierOrderSub.updateMany({
where: {
mainOrderId,
supplierId,
userId,
deleted: 0
},
data: {
deleted: 1,
updateTime: new Date()
}
})
await tx.supplierOrderProduct.updateMany({
where: {
subOrderId: { in: subOrderIds },
deleted: 0
},
data: {
deleted: 1
}
})
})
return ok({
supplierId,
orderType: 1,
orderId,
mainOrderId,
userId
})
})