Files
SupplierSystem/server/src/services/orderWorkflowService.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

173 lines
6.1 KiB
TypeScript

import { pool } from '../db';
import type { PoolClient } from 'pg';
import type { TenantContext } from './tenantScope';
import { assertValidTransition } from '../modules/kernel/orderStatus';
import { getWorkflowTransitionHandler } from '../modules/workflowTransitionRegistry';
import type { AdvanceOrderResult, OrderRow } from '../modules/types';
import {
countPendingPurchases,
ensureInspectionsForOrder,
tryAdvanceOrderToInspection,
} from './preparationFulfillmentService';
import { finalizeOrderFulfillment } from './orderWorkflowFulfillmentService';
import { writeAuditLog } from './auditService';
import { withOrderTransitionLock } from '../modules/kernel/withOrderLock';
export type { AdvanceOrderResult } from '../modules/types';
async function loadOrderRow(orderCode: string) {
const result = await pool.query(
`SELECT order_code, order_status, customer_code, branch_code, total_amount, delivery_date FROM orders WHERE order_code = $1`,
[orderCode]
);
return result.rows[0] as OrderRow | undefined;
}
export async function getOrderWorkflowStatus(orderCode: string, ctx: TenantContext) {
const order = await loadOrderRow(orderCode);
if (!order) throw Object.assign(new Error('订单不存在'), { status: 404 });
assertOrderAccess(ctx, order);
return {
order_code: order.order_code,
order_status: Number(order.order_status),
branch_code: order.branch_code,
total_amount: Number(order.total_amount || 0),
};
}
export function assertOrderAccess(ctx: TenantContext, order: { branch_code: string | null }) {
if (ctx.isSuperAdmin) return;
if (!ctx.branchCode) {
throw Object.assign(new Error('当前账号未绑定分公司,无法操作订单'), { status: 403 });
}
if (order.branch_code && order.branch_code !== ctx.branchCode) {
throw Object.assign(new Error('无权操作其他分公司的订单'), { status: 403 });
}
}
export async function assertOrderCodeAccess(orderCode: string, ctx: TenantContext): Promise<OrderRow> {
const order = await loadOrderRow(orderCode);
if (!order) throw Object.assign(new Error('订单不存在'), { status: 404 });
assertOrderAccess(ctx, order);
return order;
}
export async function advanceOrderWorkflow(
orderCode: string,
targetStatus: number,
ctx: TenantContext
): Promise<AdvanceOrderResult> {
const order = await loadOrderRow(orderCode);
if (!order) throw new Error('订单不存在');
assertOrderAccess(ctx, order);
const fromStatus = Number(order.order_status);
assertValidTransition(fromStatus, targetStatus);
const handler = getWorkflowTransitionHandler(fromStatus);
if (!handler) {
throw new Error(`状态 ${fromStatus} 暂无推进处理器`);
}
try {
const result = await withOrderTransitionLock(orderCode, fromStatus, () =>
handler({ orderCode, targetStatus, order, tenant: ctx })
);
await writeAuditLog({
operatorId: ctx.userId,
operatorRole: ctx.roles.join(','),
operationType: 'order_status_transition',
targetTable: 'orders',
targetId: orderCode,
oldValue: { order_status: fromStatus },
newValue: { order_status: result.newStatus, message: result.message },
branchCode: order.branch_code,
actionCategory: 'workflow',
}).catch((auditError) => {
console.error('[workflow] 写入订单状态审计失败:', auditError);
});
return result;
} catch (error) {
await writeAuditLog({
operatorId: ctx.userId,
operatorRole: ctx.roles.join(','),
operationType: 'order_status_transition_failed',
targetTable: 'orders',
targetId: orderCode,
oldValue: { order_status: fromStatus },
newValue: {
target_status: targetStatus,
error: error instanceof Error ? error.message : String(error),
},
branchCode: order.branch_code,
actionCategory: 'workflow',
}).catch(() => undefined);
throw error;
}
}
export async function syncPreparationInspections(
orderCodes: string[],
ctx: TenantContext
): Promise<{ inspectionsCreated: number; ordersAdvanced: number }> {
const codes = [...new Set(orderCodes.map((code) => String(code || '').trim()).filter(Boolean))];
if (!codes.length) return { inspectionsCreated: 0, ordersAdvanced: 0 };
if (codes.length > 50) {
throw Object.assign(new Error('单次最多处理 50 个订单'), { status: 400 });
}
let inspectionsCreated = 0;
let ordersAdvanced = 0;
for (const orderCode of codes) {
const order = await loadOrderRow(orderCode);
if (!order) continue;
assertOrderAccess(ctx, order);
inspectionsCreated += await ensureInspectionsForOrder(orderCode, order.branch_code);
const advanced = await tryAdvanceOrderToInspection(orderCode);
if (advanced.advanced) ordersAdvanced += 1;
}
return { inspectionsCreated, ordersAdvanced };
}
export async function completeOrderSignOff(
orderCode: string,
ctx: TenantContext,
options?: { allowUnpriced?: boolean }
): Promise<{ costGenerated: boolean }> {
const order = await loadOrderRow(orderCode);
if (!order) throw Object.assign(new Error('订单不存在'), { status: 404 });
assertOrderAccess(ctx, order);
const client = await pool.connect();
try {
await client.query('BEGIN');
const locked = await client.query(
`SELECT order_status FROM orders WHERE order_code = $1 FOR UPDATE`,
[orderCode]
);
if (!locked.rowCount) {
throw Object.assign(new Error('订单不存在'), { status: 404 });
}
if (Number(locked.rows[0].order_status) >= 90) {
await client.query('COMMIT');
return { costGenerated: false };
}
// 只有配送中(60)的订单才能结案为完成(90)
if (Number(locked.rows[0].order_status) !== 60) {
throw Object.assign(
new Error(`订单当前状态 ${locked.rows[0].order_status},不能直接结案,请先开始配送`),
{ status: 400, code: 'invalid_state' }
);
}
await finalizeOrderFulfillment(orderCode, client, { allowUnpriced: options?.allowUnpriced === true });
await client.query('COMMIT');
return { costGenerated: false };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}