Files
SupplierSystem/server/src/services/afterSaleLifecycleService.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

531 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { PoolClient } from 'pg';
import { pool } from '../db';
import { voidAfterSaleRefundCost } from './afterSaleCostPostingService';
import { notifyRoleUsers, notifyUser } from './notificationService';
import { writeAuditLog } from './auditService';
type Db = Pick<PoolClient, 'query'>;
export const AFTERSALE_TYPE_ORDER_RETURN = 'order_return';
export const AFTERSALE_HANDLE_ORDER_ITEM_RETURN = 'order_item_return';
export const AFTERSALE_TYPE_SPI_VOID = 'spi_void';
export const AFTERSALE_HANDLE_SPI_VOID = 'spi_void';
export const AFTERSALE_TYPE_INBOUND_SWITCH = 'inbound_switch';
export const AFTERSALE_HANDLE_INBOUND_SWITCH = 'inbound_switch';
/** 取消履约:无入库的行(商品直送 / 供应商免入库 / 未入库自采)被删除时的留痕(2026-09-24) */
export const AFTERSALE_TYPE_CANCEL_FULFILLMENT = 'cancel_fulfillment';
export const AFTERSALE_HANDLE_CANCEL_FULFILLMENT = 'cancel_fulfillment';
export function isOrderItemReturnAfterSale(row: { aftersale_type?: string | null }): boolean {
return String(row.aftersale_type || '').trim() === AFTERSALE_TYPE_ORDER_RETURN;
}
export function isSpiVoidAfterSale(row: { aftersale_type?: string | null }): boolean {
return String(row.aftersale_type || '').trim() === AFTERSALE_TYPE_SPI_VOID;
}
export function isInboundSwitchAfterSale(row: { aftersale_type?: string | null }): boolean {
return String(row.aftersale_type || '').trim() === AFTERSALE_TYPE_INBOUND_SWITCH;
}
export function isCancelFulfillmentAfterSale(row: { aftersale_type?: string | null }): boolean {
return String(row.aftersale_type || '').trim() === AFTERSALE_TYPE_CANCEL_FULFILLMENT;
}
export function isLockedCompletedAfterSale(row: { aftersale_type?: string | null }): boolean {
return (
isOrderItemReturnAfterSale(row) ||
isSpiVoidAfterSale(row) ||
isInboundSwitchAfterSale(row) ||
isCancelFulfillmentAfterSale(row)
);
}
/**
* 建单即终态、**按类型锁定**(与 status 无关)的三类售后自动单。
*
* ⚠️ 待办口径必须按**类型**判,不能只看 `status`:`after_sales` 不在网关禁写名单里,
* 一旦有人经 `/api/data` 把 status 裸改成 10/20(H8),只按 status 的计数就会把这三类
* 已完成的自动单算成「待处理/进行中」而虚高(看板 KPI + 售后列表「待处理」页签)。
* 权威判定用 `isLockedCompletedAfterSale`,SQL 侧用本常量。
*/
export const LOCKED_COMPLETED_AFTERSALE_TYPES = [
AFTERSALE_TYPE_ORDER_RETURN,
AFTERSALE_TYPE_SPI_VOID,
AFTERSALE_TYPE_INBOUND_SWITCH,
AFTERSALE_TYPE_CANCEL_FULFILLMENT,
] as const;
/**
* 订单 PATCH 删行/打退货标入口用:该明细有未审人工售后则 409,避免再插 OIR_。
* 不按 sku 模糊匹配。售后「处理」路径不要调用本函数。
*/
export async function assertNoPendingManualAfterSaleForOrderItem(
db: Db,
itemId: string
): Promise<void> {
const id = String(itemId || '').trim();
if (!id) return;
const locked = LOCKED_COMPLETED_AFTERSALE_TYPES as readonly string[];
const result = await db.query(
`SELECT aftersale_code
FROM after_sales
WHERE order_item_id = $1::uuid
AND status IN (10, 20)
AND COALESCE(aftersale_type, '') <> ALL($2::text[])
LIMIT 1`,
[id, locked]
);
if (result.rowCount) {
throw Object.assign(new Error('该商品有未处理售后,须先在售后管理审理'), {
status: 409,
code: 'aftersale_pending_item',
});
}
}
export function rejectOrderReturnAfterSaleMutation(): never {
throw Object.assign(new Error('订单明细退货单已红冲完成,不可再受理、驳回或处理'), {
status: 409,
code: 'order_return_locked',
});
}
export function rejectLockedCompletedAfterSaleMutation(row?: { aftersale_type?: string | null }): never {
if (isSpiVoidAfterSale(row || {})) {
throw Object.assign(new Error('独立入库作废核查单已完成,不可再受理、驳回或处理'), {
status: 409,
code: 'spi_void_locked',
});
}
if (isInboundSwitchAfterSale(row || {})) {
throw Object.assign(new Error('改派退供核查单已完成,不可再受理、驳回或处理'), {
status: 409,
code: 'inbound_switch_locked',
});
}
rejectOrderReturnAfterSaleMutation();
}
/**
* 取消履约售后留痕:无入库明细(商品直送 / 供应商免入库)被删除时建单,
* **建单即终态**(status=30 + handled_at/closed_at),且按类型锁定、不可受理 —— 与三类自动单同一套口径。
*
* 为什么需要:这类删除按设计不冲库存、也不走退货,但操作员在售后管理里应当看得见
* (开发者 2026-09-24 选 A);财务冲回由 `order_item_returns` + 既有红冲 SQL 完成。
* 见 docs/design/20260924-delete-item-supplier-statement-recalc.md
*/
export async function insertAfterSaleForCancelFulfillment(
db: Db,
args: {
orderCode: string;
customerCode?: string | null;
branchCode: string;
skuCode?: string | null;
skuName?: string | null;
itemId: string;
qty: number;
amount: number;
returnCode: string;
}
): Promise<string> {
const orderCode = String(args.orderCode || '').trim();
const itemId = String(args.itemId || '').trim();
const afterSaleCode = `OCF_${itemId.replace(/-/g, '').slice(0, 24)}`.slice(0, 50);
const name = String(args.skuName || args.skuCode || '').trim();
const reason = `取消履约:免入库/直送明细删除${name ? `(${name})` : ''},不冲库存、应付已冲回`;
let customerCode = String(args.customerCode || '').trim() || null;
if (!customerCode && orderCode) {
const order = await db.query(`SELECT customer_code FROM orders WHERE order_code = $1 LIMIT 1`, [orderCode]);
customerCode = String((order.rows[0] as { customer_code?: string | null } | undefined)?.customer_code || '').trim() || null;
}
await db.query(
`INSERT INTO after_sales (
aftersale_code, order_code, customer_code, aftersale_type, reason,
amount, handle_amount, status, branch_code, responsibility, handle_method,
sku_code, quantity, order_item_id, fulfillment_ref_type, fulfillment_ref_id,
handled_at, closed_at
) VALUES (
$1, $2, $3, $4, $5,
$6, $6, 30, $7, 'platform', $8,
$9, $10, $11::uuid, 'order_item_return', $12,
NOW(), NOW()
)
ON CONFLICT (aftersale_code) DO NOTHING`,
[
afterSaleCode,
orderCode || null,
customerCode,
AFTERSALE_TYPE_CANCEL_FULFILLMENT,
reason,
Number(args.amount) || 0,
args.branchCode || null,
AFTERSALE_HANDLE_CANCEL_FULFILLMENT,
String(args.skuCode || '').trim() || null,
Number(args.qty) || 0,
itemId || null,
String(args.returnCode || '').trim() || null,
]
);
return afterSaleCode;
}
export async function insertAfterSaleForSpiVoid(
db: Db,
args: {
spiId: string;
branchCode: string;
skuCode?: string | null;
skuName?: string | null;
qty: number;
amount: number;
}
): Promise<string> {
const spiId = String(args.spiId || '').trim();
const aftersaleCode = `SIV_${spiId.replace(/-/g, '').slice(0, 24)}`.slice(0, 50);
const name = String(args.skuName || args.skuCode || '').trim();
const reason = `独立入库未领用作废核查${name ? `(${name})` : ''},持有成本已冲减`;
await db.query(
`INSERT INTO after_sales (
aftersale_code, order_code, customer_code, aftersale_type, reason,
amount, handle_amount, status, branch_code, responsibility, handle_method,
sku_code, quantity, fulfillment_ref_type, fulfillment_ref_id,
handled_at, closed_at
) VALUES (
$1, NULL, NULL, $2, $3,
$4, $4, 30, $5, 'platform', $6,
$7, $8, 'spi_void', $9,
NOW(), NOW()
)
ON CONFLICT (aftersale_code) DO NOTHING`,
[
aftersaleCode,
AFTERSALE_TYPE_SPI_VOID,
reason,
Number(args.amount) || 0,
args.branchCode || null,
AFTERSALE_HANDLE_SPI_VOID,
String(args.skuCode || '').trim() || null,
Number(args.qty) || 0,
spiId,
]
);
return aftersaleCode;
}
export async function insertAfterSaleForInboundSwitch(
db: Db,
args: {
orderCode: string;
itemId: string;
returnCode: string;
skuCode?: string | null;
skuName?: string | null;
qty: number;
purchaseAmount: number;
previousSupplierCode?: string | null;
}
): Promise<void> {
const returnCode = String(args.returnCode || '').trim();
const itemId = String(args.itemId || '').trim();
const orderCode = String(args.orderCode || '').trim();
if (!returnCode || !itemId || !orderCode) return;
const order = await db.query(
`SELECT customer_code, branch_code FROM orders WHERE order_code = $1 LIMIT 1`,
[orderCode]
);
const name = String(args.skuName || args.skuCode || '').trim();
const supplier = String(args.previousSupplierCode || '').trim();
const reason = `原供应商已入库退货红冲(改派退供${supplier ? `,原供 ${supplier}` : ''}),客户订单行保留、销售额不变${name ? `(${name})` : ''}`;
await db.query(
`INSERT INTO after_sales (
aftersale_code, order_code, customer_code, aftersale_type, reason,
amount, handle_amount, status, branch_code, responsibility, handle_method,
sku_code, quantity, order_item_id, fulfillment_ref_type, fulfillment_ref_id,
handled_at, closed_at
) VALUES (
$1, $2, $3, $4, $5,
$6, $6, 30, $7, 'platform', $8,
$9, $10, $11::uuid, 'inbound_switch', $1,
NOW(), NOW()
)
ON CONFLICT (aftersale_code) DO NOTHING`,
[
returnCode,
orderCode,
String(order.rows[0]?.customer_code || '').trim() || null,
AFTERSALE_TYPE_INBOUND_SWITCH,
reason,
Number(args.purchaseAmount) || 0,
order.rows[0]?.branch_code || null,
AFTERSALE_HANDLE_INBOUND_SWITCH,
String(args.skuCode || '').trim() || null,
Number(args.qty) || 0,
itemId,
]
);
}
function dbOf(client?: PoolClient): Db {
return client || pool;
}
/** 建单上下文:订单头 + 明细 */
export async function getAfterSaleOrderContext(orderCode: string) {
const code = String(orderCode || '').trim();
if (!code) throw Object.assign(new Error('缺少订单号'), { status: 400 });
const order = await pool.query(
`SELECT o.order_code, o.customer_code, o.branch_code, o.cycle_code, o.order_status, o.delivery_date,
o.total_amount, o.deleted_at,
c.company_name AS customer_name,
(SELECT MAX(sr.created_at) FROM sign_records sr WHERE sr.order_code = o.order_code) AS sign_time
FROM orders o
LEFT JOIN customers c ON c.customer_code = o.customer_code
WHERE o.order_code = $1
LIMIT 1`,
[code]
);
const row = order.rows[0];
if (!row) throw Object.assign(new Error('订单不存在'), { status: 404 });
if (row.deleted_at) throw Object.assign(new Error('订单已在垃圾桶'), { status: 409 });
const items = await pool.query(
`SELECT id, sku_code, item_name, quantity, unit, price, amount, sort_order
FROM order_items
WHERE order_code = $1
ORDER BY sort_order ASC NULLS LAST, id ASC`,
[code]
);
const signTime = row.sign_time ? new Date(row.sign_time) : null;
const hoursSinceSign = signTime ? (Date.now() - signTime.getTime()) / 3600000 : null;
return {
order_code: row.order_code,
customer_code: row.customer_code,
customer_name: row.customer_name || null,
branch_code: row.branch_code,
cycle_code: row.cycle_code,
order_status: Number(row.order_status) || 0,
delivery_date: row.delivery_date,
total_amount: Number(row.total_amount) || 0,
sign_time: signTime ? signTime.toISOString() : null,
hours_since_sign: hoursSinceSign,
within_24h: hoursSinceSign == null || hoursSinceSign <= 24,
items: items.rows.map((it) => ({
id: it.id,
sku_code: it.sku_code,
item_name: it.item_name,
quantity: Number(it.quantity) || 0,
unit: it.unit,
price: Number(it.price) || 0,
amount: Number(it.amount) || 0,
})),
};
}
export async function acceptAfterSale(input: {
aftersaleId: string;
handlerId?: string | null;
}) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const existing = await client.query(
`SELECT * FROM after_sales WHERE id::text = $1 OR aftersale_code = $1 LIMIT 1 FOR UPDATE`,
[input.aftersaleId]
);
const row = existing.rows[0];
if (!row) throw Object.assign(new Error('售后单不存在'), { status: 404 });
if (isLockedCompletedAfterSale(row)) rejectLockedCompletedAfterSaleMutation(row);
const st = Number(row.status) || 0;
if (st === 20) {
await client.query('COMMIT');
return row;
}
if (st !== 10) throw Object.assign(new Error('仅待受理可受理'), { status: 409 });
const updated = await client.query(
`UPDATE after_sales
SET status = 20, handler_id = COALESCE($2, handler_id), handled_at = NOW()
WHERE id = $1
RETURNING *`,
[row.id, input.handlerId || null]
);
await client.query('COMMIT');
await writeAuditLog({
operatorId: input.handlerId || null,
operationType: 'aftersale_accept',
actionCategory: 'aftersale',
targetTable: 'after_sales',
targetId: String(row.aftersale_code),
branchCode: row.branch_code || null,
newValue: { status: 20 },
}).catch(() => undefined);
return updated.rows[0];
} catch (e) {
await client.query('ROLLBACK').catch(() => undefined);
throw e;
} finally {
client.release();
}
}
export async function rejectAfterSale(input: {
aftersaleId: string;
reason: string;
handlerId?: string | null;
}) {
const reason = String(input.reason || '').trim();
if (!reason) throw Object.assign(new Error('请填写驳回原因'), { status: 400 });
const client = await pool.connect();
try {
await client.query('BEGIN');
const existing = await client.query(
`SELECT * FROM after_sales WHERE id::text = $1 OR aftersale_code = $1 LIMIT 1 FOR UPDATE`,
[input.aftersaleId]
);
const row = existing.rows[0];
if (!row) throw Object.assign(new Error('售后单不存在'), { status: 404 });
if (isLockedCompletedAfterSale(row)) rejectLockedCompletedAfterSaleMutation(row);
const st = Number(row.status) || 0;
if (st >= 30) throw Object.assign(new Error('售后单已办结'), { status: 409 });
if (st !== 10 && st !== 20) throw Object.assign(new Error('当前状态不可驳回'), { status: 409 });
const voided = await voidAfterSaleRefundCost(String(row.aftersale_code), client);
const updated = await client.query(
`UPDATE after_sales
SET status = 40,
reject_reason = $2,
handler_id = COALESCE($3, handler_id),
handled_at = NOW(),
closed_at = NOW()
WHERE id = $1
RETURNING *`,
[row.id, reason, input.handlerId || null]
);
await client.query('COMMIT');
if (row.created_by) {
await notifyUser({
userId: String(row.created_by),
notifyType: 'aftersale_rejected',
title: '售后已驳回',
content: `售后单 ${row.aftersale_code} 已驳回:${reason}`,
relatedOrderCode: row.order_code || null,
branchCode: row.branch_code || null,
}).catch(() => undefined);
}
await writeAuditLog({
operatorId: input.handlerId || null,
operationType: 'aftersale_reject',
actionCategory: 'aftersale',
targetTable: 'after_sales',
targetId: String(row.aftersale_code),
branchCode: row.branch_code || null,
newValue: { status: 40, reject_reason: reason, cost_voided: voided.voided },
}).catch(() => undefined);
return { ...updated.rows[0], cost_voided: voided.voided };
} catch (e) {
await client.query('ROLLBACK').catch(() => undefined);
throw e;
} finally {
client.release();
}
}
/** 换货备注跟踪 / 退货登记 */
export async function attachAfterSaleFulfillment(
db: Db,
input: {
aftersaleCode: string;
aftersaleId: string;
handleMethod: string;
orderCode?: string | null;
skuCode?: string | null;
quantity?: number | null;
reason?: string | null;
branchCode?: string | null;
}
): Promise<{ fulfillment_ref_type: string | null; fulfillment_ref_id: string | null }> {
const method = String(input.handleMethod || '').trim();
if (method === 'replace') {
const noteId = `RN${Date.now()}`;
await db.query(
`UPDATE after_sales
SET fulfillment_ref_type = 'replace_note', fulfillment_ref_id = $2
WHERE id = $1`,
[input.aftersaleId, noteId]
);
return { fulfillment_ref_type: 'replace_note', fulfillment_ref_id: noteId };
}
if (method === 'return') {
const returnCode = `AR${Date.now()}`;
await db.query(
`INSERT INTO after_sale_returns (
return_code, aftersale_code, after_sale_id, order_code, sku_code, quantity, reason, status, branch_code
) VALUES ($1,$2,$3,$4,$5,$6,$7,'10',$8)`,
[
returnCode,
input.aftersaleCode,
input.aftersaleId,
input.orderCode || null,
input.skuCode || null,
Number(input.quantity) || 0,
input.reason || null,
input.branchCode || null,
]
);
await db.query(
`UPDATE after_sales
SET fulfillment_ref_type = 'return', fulfillment_ref_id = $2
WHERE id = $1`,
[input.aftersaleId, returnCode]
);
return { fulfillment_ref_type: 'return', fulfillment_ref_id: returnCode };
}
return { fulfillment_ref_type: null, fulfillment_ref_id: null };
}
export async function notifyAfterSaleCreated(row: {
aftersale_code: string;
order_code?: string | null;
branch_code?: string | null;
created_by?: string | null;
}) {
await notifyRoleUsers({
roles: ['admin', 'finance', 'operator'],
notifyType: 'aftersale_created',
title: '新售后单',
content: `售后单 ${row.aftersale_code} 待受理(订单 ${row.order_code || '-'})`,
relatedOrderCode: row.order_code || null,
branchCode: row.branch_code || null,
skipIfRecent: false,
}).catch(() => undefined);
}
export async function notifyAfterSaleClosed(row: {
aftersale_code: string;
order_code?: string | null;
branch_code?: string | null;
created_by?: string | null;
status: number;
}) {
if (!row.created_by) return;
const done = Number(row.status) === 30;
await notifyUser({
userId: String(row.created_by),
notifyType: done ? 'aftersale_completed' : 'aftersale_rejected',
title: done ? '售后已完成' : '售后已驳回',
content: `售后单 ${row.aftersale_code} 已${done ? '完成' : '驳回'}`,
relatedOrderCode: row.order_code || null,
branchCode: row.branch_code || null,
}).catch(() => undefined);
}