fix(报价单): 修红队二轮高危——拆单预检排除源单(防静默删客户)、版本行显式挂新单号、锁键带分公司、幂等SQL移入service、按建立时间保留首客户
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

This commit is contained in:
Ubuntu
2026-10-19 18:09:30 +08:00
parent 9922d20240
commit bb8acfc0ba
4 changed files with 57 additions and 24 deletions
@@ -72,7 +72,7 @@ async function findMultiCustomerSheets(client: any, schema: string): Promise<Mul
for (const sheet of sheets) {
const { rows: customers } = await client.query<{ customer_code: string }>(
`SELECT customer_code FROM ${schema}.customer_quote_sheet_customers
WHERE quote_sheet_code = $1 ORDER BY customer_code`,
WHERE quote_sheet_code = $1 ORDER BY created_at NULLS LAST, customer_code`,
[sheet.quote_sheet_code]
);
const { rows: items } = await client.query<{ n: number }>(
@@ -151,11 +151,12 @@ async function main() {
* 红队 #6(e):该客户名下若已有**生效**报价单,则不再拆出(避免两张生效单)。
* 红队 #6(c):同时复制该客户在版本表里的行并挂到新单,否则新单查不到报价价。
*/
// 红队 #13:必须排除源单自身,否则源单 status=1 时每个追加客户都"命中自己"→全部跳过、随后又被删关联(客户彻底失去报价)
const active = await client.query(
`SELECT 1 FROM ${schema}.customer_quote_sheets s
JOIN ${schema}.customer_quote_sheet_customers c ON c.quote_sheet_code = s.quote_sheet_code
WHERE c.customer_code = $1 AND s.status = 1 LIMIT 1`,
[extra]
WHERE c.customer_code = $1 AND s.status = 1 AND s.quote_sheet_code <> $2 LIMIT 1`,
[extra, row.code]
);
if (active.rowCount) {
console.log(` ⚠ 跳过客户 ${extra}:名下已有生效报价单`);
@@ -188,17 +189,17 @@ async function main() {
const { rows: vcols } = await client.query<{ column_name: string }>(
`SELECT column_name FROM information_schema.columns
WHERE table_schema = $1 AND table_name = 'customer_quote_versions'
AND column_name NOT IN ('id', 'created_at', 'quote_version_code')
AND column_name NOT IN ('id', 'created_at', 'quote_version_code', 'quote_sheet_code')
ORDER BY ordinal_position`,
[schema]
);
const vList = vcols.map((c) => `"${c.column_name}"`).join(', ');
await client.query(
`INSERT INTO ${schema}.customer_quote_versions (quote_version_code, ${vList})
SELECT 'QV' || to_char(now(), 'YYYYMMDDHH24MISS') || substr(md5(random()::text), 1, 6), ${vList}
`INSERT INTO ${schema}.customer_quote_versions (quote_version_code, quote_sheet_code, ${vList})
SELECT 'QV' || to_char(now(), 'YYYYMMDDHH24MISS') || substr(md5(random()::text), 1, 6), $3, ${vList}
FROM ${schema}.customer_quote_versions
WHERE quote_sheet_code = $1 AND customer_code = $2`,
[row.code, extra]
[row.code, extra, nextCode]
);
// 强制生效 + 互斥该客户其它生效单
await client.query(
@@ -49,18 +49,14 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon
.digest('hex');
let idemClient: any = null;
if (idemKey) {
const { pool } = await import('../../../db');
idemClient = pool;
const existing = await pool.query(
`SELECT request_hash, response_json FROM public.quote_sheet_idempotency WHERE branch_code = $1 AND idem_key = $2`,
[operatingBranch || '', idemKey]
);
if (existing.rowCount) {
const row = existing.rows[0] as { request_hash: string; response_json: any };
if (row.request_hash !== requestHash) {
const { readQuoteSheetIdempotency } = await import('../../../services/quoteSheetService');
idemClient = true;
const existing = await readQuoteSheetIdempotency({ branchCode: operatingBranch || '', idemKey });
if (existing) {
if (existing.request_hash !== requestHash) {
return res.status(409).json({ error: 'idempotency_conflict', error_description: '相同幂等键但请求内容不同,请更换幂等键' });
}
return res.json(row.response_json);
return res.json(existing.response_json as any);
}
}
@@ -94,12 +90,9 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon
failed_count: failed.length,
failed,
};
if (idemClient && idemKey && (created.length > 0 || failed.length === 0)) {
await idemClient.query(
`INSERT INTO public.quote_sheet_idempotency (branch_code, idem_key, request_hash, response_json)
VALUES ($1, $2, $3, $4::jsonb) ON CONFLICT (branch_code, idem_key) DO NOTHING`,
[operatingBranch || '', idemKey, requestHash, JSON.stringify(payload)]
);
if (idemClient && idemKey) {
const { writeQuoteSheetIdempotency } = await import('../../../services/quoteSheetService');
await writeQuoteSheetIdempotency({ branchCode: operatingBranch || '', idemKey, requestHash, response: payload });
}
if (!created.length && failed.length) {
return res.status(500).json({ error: 'all_failed', error_description: '全部客户建单失败', failed });
+25 -1
View File
@@ -195,6 +195,30 @@ export async function resolveEditCustomerSplit(input: {
};
}
/** 读取幂等记录(routeLayerBoundary:路由层禁止裸 SQL,故放 service) */
export async function readQuoteSheetIdempotency(input: { branchCode: string; idemKey: string }) {
const { rows } = await pool.query<{ request_hash: string; response_json: unknown }>(
`SELECT request_hash, response_json FROM public.quote_sheet_idempotency
WHERE branch_code = $1 AND idem_key = $2`,
[input.branchCode || '', input.idemKey]
);
return rows[0] ?? null;
}
/** 写入幂等记录(同 key 并发时 ON CONFLICT DO NOTHING,先写者胜) */
export async function writeQuoteSheetIdempotency(input: {
branchCode: string;
idemKey: string;
requestHash: string;
response: unknown;
}) {
await pool.query(
`INSERT INTO public.quote_sheet_idempotency (branch_code, idem_key, request_hash, response_json)
VALUES ($1, $2, $3, $4::jsonb) ON CONFLICT (branch_code, idem_key) DO NOTHING`,
[input.branchCode || '', input.idemKey, input.requestHash, JSON.stringify(input.response)]
);
}
export async function createQuoteSheet(input: {
title?: string;
customerCodes: string[];
@@ -229,7 +253,7 @@ export async function createQuoteSheet(input: {
*/
for (const code of customerCodes) {
await client.query(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
`quote-sheet:${input.branchCode || ''}:${String(code).toUpperCase()}`,
`quote-sheet:${input.branchCode || input.operatingBranchCode || ''}:${String(code).toUpperCase()}`,
]);
}
await client.query(
+15
View File
@@ -40,6 +40,21 @@ vi.mock('../src/services/tenantScope', async (importOriginal) => {
vi.mock('../src/services/quoteSheetService', () => ({
createQuoteSheet: (...args: unknown[]) => H.createQuoteSheet(...args),
// 幂等读写也在 service(红队 #10:路由层禁止裸 SQL)
readQuoteSheetIdempotency: async (input: { branchCode: string; idemKey: string }) => {
return H.idemStore.get(`${input.branchCode}::${input.idemKey}`) ?? null;
},
writeQuoteSheetIdempotency: async (input: {
branchCode: string;
idemKey: string;
requestHash: string;
response: unknown;
}) => {
H.idemStore.set(`${input.branchCode}::${input.idemKey}`, {
request_hash: input.requestHash,
response_json: input.response,
});
},
// 真实实现在 service 里(路由不再裸 SQL);测试里用同一套 SQL 断言脚本复刻
resolveEditCustomerSplit: async (input: { quoteSheetCode: string; requestedCustomerCodes: string[] }) => {
const ownRes = await H.poolQuery(