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

175 lines
5.4 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 { pool } from '../db';
import { notifyRoleUsers } from './notificationService';
export interface SubstitutionValidation {
ok: boolean;
errors: string[];
original?: { sku_code: string; category_code: string; sale_price: number; sku_name: string };
substitute?: { sku_code: string; category_code: string; sale_price: number; sku_name: string };
}
/** V9 换品:同二级分类、价≤原品(档案销售价已移除,不再用档案价作质量参考) */
export async function validateProductSubstitution(input: {
originalSkuCode: string;
substituteSkuCode: string;
originalPrice: number;
substitutePrice: number;
}): Promise<SubstitutionValidation> {
const errors: string[] = [];
const result = await pool.query(
`SELECT sku_code, sku_name, category_code
FROM skus WHERE sku_code = ANY($1) AND status = 1`,
[[input.originalSkuCode, input.substituteSkuCode]]
);
const map = new Map(result.rows.map((row) => [row.sku_code, row]));
const original = map.get(input.originalSkuCode);
const substitute = map.get(input.substituteSkuCode);
if (!original) errors.push('原品 SKU 不存在或已停用');
if (!substitute) errors.push('换品 SKU 不存在或已停用');
if (input.substituteSkuCode === input.originalSkuCode) errors.push('换品不能与原品相同');
if (input.substitutePrice > input.originalPrice) errors.push('换品价格不能高于原品(V9 铁律)');
if (original && substitute) {
if (original.category_code !== substitute.category_code) {
errors.push('换品须与原品同二级分类');
}
}
return {
ok: errors.length === 0,
errors,
original: original
? {
sku_code: original.sku_code,
sku_name: original.sku_name,
category_code: original.category_code,
sale_price: Number(input.originalPrice) || 0,
}
: undefined,
substitute: substitute
? {
sku_code: substitute.sku_code,
sku_name: substitute.sku_name,
category_code: substitute.category_code,
sale_price: Number(input.substitutePrice) || 0,
}
: undefined,
};
}
export async function listSubstituteCandidates(originalSkuCode: string, maxPrice: number, limit = 20) {
const result = await pool.query(
`SELECT s.sku_code, s.sku_name, s.category_code, s.unit
FROM skus s
WHERE s.status = 1
AND s.sku_code <> $1
AND s.category_code = (SELECT category_code FROM skus WHERE sku_code = $1)
ORDER BY s.sku_name ASC
LIMIT $2`,
[originalSkuCode, limit]
);
return result.rows.map((row) => ({
...row,
sale_price: 0,
eligible: true,
}));
}
export async function listPendingSubstitutions(orderCode?: string, limit = 50) {
const params: unknown[] = [10];
let orderSql = '';
if (orderCode) {
params.push(orderCode);
orderSql = `AND ps.order_code = $${params.length}`;
}
params.push(limit);
const result = await pool.query(
`SELECT ps.*,
o.customer_code,
os.sku_name AS original_sku_name,
ss.sku_name AS substitute_sku_name
FROM product_substitutions ps
LEFT JOIN orders o ON o.order_code = ps.order_code
LEFT JOIN skus os ON os.sku_code = ps.original_sku_code
LEFT JOIN skus ss ON ss.sku_code = ps.substitute_sku_code
WHERE ps.status = $1 ${orderSql}
ORDER BY ps.created_at DESC
LIMIT $${params.length}`,
params
);
return result.rows;
}
export async function createSubstitutionWithValidation(input: {
orderCode: string;
prepId?: string;
originalSkuCode: string;
substituteSkuCode: string;
originalPrice: number;
substitutePrice: number;
reason?: string;
branchCode?: string | null;
createdBy?: string | null;
}) {
const validation = await validateProductSubstitution(input);
if (!validation.ok) {
throw new Error(validation.errors.join(';'));
}
if (input.prepId) {
const pending = await pool.query(
`SELECT substitution_code
FROM product_substitutions
WHERE prep_id = $1::uuid AND status = 10
LIMIT 1`,
[input.prepId]
);
if (pending.rowCount) {
throw Object.assign(new Error('该备货已有待确认换品申请,请勿重复提交'), {
status: 409,
code: 'substitution_pending',
});
}
}
const code = `SUB${Date.now()}`;
const result = await pool.query(
`INSERT INTO product_substitutions
(substitution_code, order_code, prep_id, original_sku_code, substitute_sku_code,
original_price, substitute_price, reason, branch_code, created_by, status)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,10)
RETURNING *`,
[
code,
input.orderCode,
input.prepId || null,
input.originalSkuCode,
input.substituteSkuCode,
input.originalPrice,
input.substitutePrice,
input.reason || null,
input.branchCode || null,
input.createdBy || null,
]
);
const orderResult = await pool.query(
`SELECT customer_code, branch_code FROM orders WHERE order_code = $1`,
[input.orderCode]
);
const order = orderResult.rows[0];
if (order?.customer_code) {
await notifyRoleUsers({
roles: ['operator', 'admin'],
notifyType: 'substitution_pending',
title: '换品待客户确认',
content: `订单 ${input.orderCode} 申请换品:${input.originalSkuCode} → ${input.substituteSkuCode}`,
relatedOrderCode: input.orderCode,
branchCode: order.branch_code,
});
}
return result.rows[0];
}