refactor(报价单): 彻底删除内部待审改价,改价一律发申请由配送商审核
用户裁定(2026-10-18):两个系统只能交流数据、不能直接修改对方数据;自己只能改自己的。 - 删除「待审改价」:service / 4 个路由 / 面板 / 相关测试;新增迁移 drop 该租户表(含 legacy_public) - 编辑生效单:立即落本系统 + 自动发「配送商销售价确认」申请(quoteSheetEditService) - 报价单生效/提交/审批:不再 triggerQuoteCostSync 直推对方成本价,改为发提议由对方审核 - 删除定时重试直推任务(runQuoteCostSyncReconcile)
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
-- 删除「供应商内部待审改价」特性(2026-10-18 用户裁定:改价由配送商审核,供应商不做自审)
|
||||
--
|
||||
-- 口径:两个系统只能交换数据,不能直接修改对方数据;供应商改自己的销售价后发提议给对方审。
|
||||
-- 本迁移只删这张已废弃的租户表;`tenant_business_tables()` 保留旧条目不影响一致性断言
|
||||
-- (断言只检查「template 表是否都在名单里」,名单多一条不会报错)。
|
||||
--
|
||||
-- 可重放:DROP TABLE IF EXISTS。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
s TEXT;
|
||||
BEGIN
|
||||
FOR s IN
|
||||
SELECT schema_name FROM information_schema.schemata
|
||||
WHERE schema_name LIKE 'tenant\_%' ESCAPE '\'
|
||||
LOOP
|
||||
EXECUTE format('DROP TABLE IF EXISTS %I.quote_sheet_change_requests', s);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- 旧版遗留 schema(legacy_public)里也有一份同名表;本地/新环境一并清掉。
|
||||
DROP TABLE IF EXISTS legacy_public.quote_sheet_change_requests;
|
||||
@@ -89,7 +89,7 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res:
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
const operatingBranch = readOperatingBranchCode(req);
|
||||
requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']);
|
||||
const { applyQuoteSheetEditAndRequestDeliveryReview } = await import('../../../services/quoteSheetChangeRequestService');
|
||||
const { applyQuoteSheetEditAndRequestDeliveryReview } = await import('../../../services/quoteSheetEditService');
|
||||
const customerCodes = Array.isArray(req.body?.customer_codes)
|
||||
? req.body.customer_codes.map(String)
|
||||
: undefined;
|
||||
@@ -132,81 +132,9 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res:
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
const CHANGE_REQUEST_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
/** 待审改价列表(查看:`customer_manage | order_manage`;审批操作才要求 `customer_manage`) */
|
||||
router.get('/quote/change-requests', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']);
|
||||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' });
|
||||
}
|
||||
const { listQuoteSheetChangeRequests } = await import('../../../services/quoteSheetChangeRequestService');
|
||||
const data = await listQuoteSheetChangeRequests({
|
||||
branchCode,
|
||||
status: req.query?.status ? String(req.query.status) : 'pending',
|
||||
limit: Number(req.query?.limit) || 50,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '加载待审改价失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** 审核通过:单事务应用变更 → 提交后触发成本价同步(rearm 路径);权限只认 `customer_manage` */
|
||||
router.post('/quote/change-requests/:id/approve', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['customer_manage']);
|
||||
if (!CHANGE_REQUEST_ID_RE.test(String(req.params.id || ''))) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '变更单 ID 无效' });
|
||||
}
|
||||
const { approveQuoteSheetChangeRequest } = await import('../../../services/quoteSheetChangeRequestService');
|
||||
const result = await approveQuoteSheetChangeRequest({
|
||||
id: String(req.params.id),
|
||||
ctx,
|
||||
operatingBranchCode: readOperatingBranchCode(req),
|
||||
reviewedBy: req.userId || null,
|
||||
});
|
||||
return res.json({ data: result.data, change_request: result.changeRequest });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '审核通过失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** 审核驳回:只改变更单状态(报价单不变、零推送);权限只认 `customer_manage` */
|
||||
router.post('/quote/change-requests/:id/reject', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['customer_manage']);
|
||||
if (!CHANGE_REQUEST_ID_RE.test(String(req.params.id || ''))) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '变更单 ID 无效' });
|
||||
}
|
||||
const { rejectQuoteSheetChangeRequest } = await import('../../../services/quoteSheetChangeRequestService');
|
||||
const result = await rejectQuoteSheetChangeRequest({
|
||||
id: String(req.params.id),
|
||||
reason: String(req.body?.reason || ''),
|
||||
ctx,
|
||||
operatingBranchCode: readOperatingBranchCode(req),
|
||||
reviewedBy: req.userId || null,
|
||||
});
|
||||
return res.json({ change_request: result.changeRequest });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '审核驳回失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* **SKU 映射**(2026-10-18 冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §5)—— 三条内部只读/同步端点。
|
||||
*
|
||||
|
||||
@@ -1,929 +0,0 @@
|
||||
import { pool } from '../db';
|
||||
import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||||
import {
|
||||
applyQuoteSheetUpdate,
|
||||
assertCustomersInBranch,
|
||||
getQuoteSheet,
|
||||
loadQuoteSheetForUpdate,
|
||||
normalizeQuoteSheetUpdatePayload,
|
||||
updateQuoteSheet,
|
||||
type QuoteSheetItemInput,
|
||||
type QuoteSheetUpdateInput,
|
||||
} from './quoteSheetService';
|
||||
import { quoteCostSyncItemsFingerprint, triggerQuoteCostSync } from './mainSystemQuoteCostSync';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { submitPriceProposal } from './quotePriceProposalService';
|
||||
|
||||
/**
|
||||
* 编辑**生效中**报价单的「待审变更」(2026-10-18 增量需求):
|
||||
* 用户原话「编辑生效单改价需要有同步审核,审核通过就同步」。
|
||||
*
|
||||
* 口径(brief §3 + Lead 2026-10-18 裁定,逐条照做):
|
||||
* · **只审价格相关变化**(D5):入参含 `items`(增删改明细)或 `auto_sale_price_by_cost` 真的变了 ⇒ 待审;
|
||||
* 只改标题/周期/生效日/客户 ⇒ 维持现有直接保存;
|
||||
* · **整单一次审核**(D2):保存时整单入参作为一条变更单;
|
||||
* · 一张单只留一条 `pending`(D4):新提交把旧的置 `superseded`;
|
||||
* · **未审期间零副作用**:报价单三张表与配送系统都不动;
|
||||
* · 审核通过:**单事务**内应用(复用抽出的 `applyQuoteSheetUpdate(..., { client })`)→ 提交后
|
||||
* 调既有 `triggerQuoteCostSync`(走 rearm:指纹变了会换号重推);**绝不**走
|
||||
* `approveQuoteSheet`/`activateQuoteSheet`(后者会把同分公司共享客户的其它生效单置 `status=3`);
|
||||
* · 驳回:只改变更单状态,报价单不变、**零推送**;
|
||||
* · 重复决策 ⇒ `409 already_decided`(幂等,不重复应用);
|
||||
* · 开关 `QUOTE_EDIT_APPROVAL` **默认开**;`0/false/off` 回滚成"直接保存"且**不写**变更单表。
|
||||
*
|
||||
* 设计:docs/design/20261018-报价单改价审核与成本同步.md
|
||||
*/
|
||||
|
||||
/** 开关:默认开;只有显式 `0/false/off` 才关(回滚成改造前的「直接保存」) */
|
||||
export function isQuoteEditApprovalEnabled(): boolean {
|
||||
const raw = String(process.env.QUOTE_EDIT_APPROVAL ?? '').trim().toLowerCase();
|
||||
return !(raw === '0' || raw === 'false' || raw === 'off');
|
||||
}
|
||||
|
||||
/**
|
||||
* 变更单业务审计(A26):提交 / 通过 / 驳回三条路径各写一条 `operation_logs`
|
||||
* (`operationType = quote_sheet_change_request_<action>`,四要素:变更单 id、报价单 code、
|
||||
* 旧状态→新状态、理由/操作人)。
|
||||
*
|
||||
* ⚠️ **best-effort**:审计在**事务提交之后**调用(避免审计失败把主事务带进 aborted 状态),
|
||||
* 任何异常只记日志,绝不影响提交/审批结果。
|
||||
*/
|
||||
async function auditChangeRequest(input: {
|
||||
operatorId?: string | null;
|
||||
operatorRole?: string | null;
|
||||
action: 'submit' | 'approve' | 'reject';
|
||||
branchCode: string;
|
||||
changeRequestId: string;
|
||||
quoteSheetCode: string;
|
||||
oldStatus: string;
|
||||
newStatus: string;
|
||||
reason?: string | null;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await writeAuditLog({
|
||||
operatorId: input.operatorId || null,
|
||||
operatorRole: input.operatorRole || null,
|
||||
operationType: `quote_sheet_change_request_${input.action}`,
|
||||
targetTable: 'quote_sheet_change_requests',
|
||||
targetId: input.changeRequestId,
|
||||
oldValue: {
|
||||
change_request_id: input.changeRequestId,
|
||||
quote_sheet_code: input.quoteSheetCode,
|
||||
status: input.oldStatus,
|
||||
},
|
||||
newValue: {
|
||||
change_request_id: input.changeRequestId,
|
||||
quote_sheet_code: input.quoteSheetCode,
|
||||
status: input.newStatus,
|
||||
action: input.action,
|
||||
reason: input.reason ?? null,
|
||||
},
|
||||
branchCode: input.branchCode,
|
||||
actionCategory: 'quote_edit_approval',
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.warn(
|
||||
'[quote-change-request] 审计写入失败(best-effort,不影响主流程):',
|
||||
error?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function httpError(status: number, code: string, message: string) {
|
||||
return Object.assign(new Error(message), { status, code });
|
||||
}
|
||||
|
||||
/**
|
||||
* 审批路径专用:把「目标单不可用」的普通 Error 映射成 409 `target_unavailable`(A12 修订)。
|
||||
*
|
||||
* 只认这三句既有文案(来源 `quoteSheetService` 的三连守卫 / `assertQuoteSheetAccessible`)——
|
||||
* 其它错误(数据库/网络)原样返回,仍按 500 处理。**不改编辑路径的抛错语义**:
|
||||
* `updateQuoteSheet` 仍抛普通 Error(= 改造前行为),只有这里做映射。
|
||||
*/
|
||||
function mapTargetUnavailable(error: any): Error | null {
|
||||
const message = String(error?.message || '');
|
||||
if (
|
||||
message === '报价单不存在' ||
|
||||
message === '仅执行中的报价单可修改' ||
|
||||
message === '报价单已过期,无法修改'
|
||||
) {
|
||||
return httpError(409, 'target_unavailable', message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 变更单里存的整单编辑入参(D2:整单一次审核) */
|
||||
export type QuoteChangePayload = {
|
||||
title?: string;
|
||||
customer_codes?: string[];
|
||||
items?: QuoteSheetItemInput[];
|
||||
auto_sale_price_by_cost?: boolean;
|
||||
quote_cycle?: string;
|
||||
effective_at?: string;
|
||||
};
|
||||
|
||||
export type QuoteChangeLine = {
|
||||
sku_code: string;
|
||||
sku_name: string | null;
|
||||
unit: string | null;
|
||||
before_sale_price: number | null;
|
||||
after_sale_price: number | null;
|
||||
before_cost_price: number | null;
|
||||
after_cost_price: number | null;
|
||||
change: 'added' | 'removed' | 'updated';
|
||||
};
|
||||
|
||||
export type QuoteChangeSummary = {
|
||||
title: string | null;
|
||||
quote_cycle: string | null;
|
||||
effective_at: string | null;
|
||||
auto_sale_price_by_cost: boolean | null;
|
||||
customer_codes: string[] | null;
|
||||
items_provided: boolean;
|
||||
item_count: number;
|
||||
added: number;
|
||||
removed: number;
|
||||
updated: number;
|
||||
lines: QuoteChangeLine[];
|
||||
truncated: boolean;
|
||||
};
|
||||
|
||||
export type QuoteChangeRequestDto = {
|
||||
id: string;
|
||||
branch_code: string;
|
||||
quote_sheet_code: string;
|
||||
payload: QuoteChangePayload;
|
||||
base_version_no: number | null;
|
||||
base_items_fingerprint: string | null;
|
||||
status: 'pending' | 'approved' | 'rejected' | 'superseded';
|
||||
requested_by: string | null;
|
||||
requested_by_name: string | null;
|
||||
requested_at: string | Date | null;
|
||||
reviewed_by: string | null;
|
||||
reviewed_by_name: string | null;
|
||||
reviewed_at: string | Date | null;
|
||||
reject_reason: string | null;
|
||||
applied_at: string | Date | null;
|
||||
updated_at: string | Date | null;
|
||||
summary?: QuoteChangeSummary;
|
||||
};
|
||||
|
||||
type ItemLike = {
|
||||
sku_code?: unknown;
|
||||
sku_name?: unknown;
|
||||
unit?: unknown;
|
||||
sale_price?: unknown;
|
||||
price?: unknown;
|
||||
cost_price?: unknown;
|
||||
};
|
||||
|
||||
function toText(value: unknown): string {
|
||||
return value === null || value === undefined ? '' : String(value).trim();
|
||||
}
|
||||
|
||||
function readItemSale(row: ItemLike): number {
|
||||
const raw = row?.sale_price ?? row?.price;
|
||||
const value = Number(raw);
|
||||
return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
|
||||
}
|
||||
|
||||
function readItemCost(row: ItemLike): number {
|
||||
const value = Number(row?.cost_price);
|
||||
return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交时的**同一 SKU 重复**闸门(Lead 裁定 #2):不去重、不落库,直接 400 `duplicate_sku`。
|
||||
* 只按非空 `sku_code` 判;空行本来就会被 `normalizeQuoteSheetUpdatePayload` 过滤掉。
|
||||
*/
|
||||
export function assertNoDuplicateSku(items: QuoteSheetItemInput[] | undefined): void {
|
||||
if (!Array.isArray(items) || !items.length) return;
|
||||
const seen = new Set<string>();
|
||||
const duplicates = new Set<string>();
|
||||
for (const item of items) {
|
||||
const code = toText(item?.sku_code);
|
||||
if (!code) continue;
|
||||
if (seen.has(code)) duplicates.add(code);
|
||||
seen.add(code);
|
||||
}
|
||||
if (duplicates.size) {
|
||||
throw httpError(400, 'duplicate_sku', `同一商品重复出现:${[...duplicates].slice(0, 5).join('、')}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 「这次编辑是否价格相关」(D5):入参含 `items`(增删改明细)⇒ 是;
|
||||
* `auto_sale_price_by_cost` **真的变了** ⇒ 是;只改标题/周期/生效日/客户 ⇒ 否。
|
||||
*/
|
||||
export function isPriceRelatedQuoteEdit(
|
||||
input: { items?: unknown; autoSalePriceByCost?: unknown },
|
||||
existing: { auto_sale_price_by_cost?: unknown }
|
||||
): boolean {
|
||||
if (input.items !== undefined) return true;
|
||||
if (input.autoSalePriceByCost !== undefined) {
|
||||
return Boolean(input.autoSalePriceByCost) !== Boolean(existing?.auto_sale_price_by_cost);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 报价单明细指纹:**复用成本价同步的同一套算法**(`sku_code` / `unit` / `sale_price` 排序后 sha256,
|
||||
* 见 `quoteCostSyncItemsFingerprint`)。用于"提交后目标单是否被改过"(`base_changed`)判据。
|
||||
*
|
||||
* ⚠️ `base_version_no` 只留痕、不作判据:`version_no` 编辑时不涨,`setQuoteSheetAutoSalePriceByCost`
|
||||
* 连 `updated_at` 都不更新 ⇒ 用版本号判"变没变"会永远判不出变化(Lead 裁定 #4)。
|
||||
*/
|
||||
export function quoteSheetItemsFingerprint(rows: ItemLike[]): string {
|
||||
return quoteCostSyncItemsFingerprint(
|
||||
(rows || [])
|
||||
.map((row) => ({
|
||||
sku_code: toText(row?.sku_code),
|
||||
unit: toText(row?.unit) || null,
|
||||
sale_price: readItemSale(row),
|
||||
}))
|
||||
.filter((row) => Boolean(row.sku_code))
|
||||
);
|
||||
}
|
||||
|
||||
function changeLine(before: ItemLike | null, after: ItemLike | null, change: QuoteChangeLine['change']): QuoteChangeLine {
|
||||
const source = after || before || {};
|
||||
return {
|
||||
sku_code: toText(source.sku_code),
|
||||
sku_name: toText(source.sku_name) || null,
|
||||
unit: toText(source.unit) || null,
|
||||
before_sale_price: before ? readItemSale(before) : null,
|
||||
after_sale_price: after ? readItemSale(after) : null,
|
||||
before_cost_price: before ? readItemCost(before) : null,
|
||||
after_cost_price: after ? readItemCost(after) : null,
|
||||
change,
|
||||
};
|
||||
}
|
||||
|
||||
/** 明细前后比对(纯函数,供审核摘要与单测) */
|
||||
export function diffQuoteSheetItems(
|
||||
before: ItemLike[],
|
||||
after: ItemLike[]
|
||||
): Pick<QuoteChangeSummary, 'item_count' | 'added' | 'removed' | 'updated' | 'lines' | 'truncated'> {
|
||||
const index = (rows: ItemLike[]) => {
|
||||
const map = new Map<string, ItemLike>();
|
||||
for (const row of rows || []) {
|
||||
const code = toText(row?.sku_code);
|
||||
if (code) map.set(code, row);
|
||||
}
|
||||
return map;
|
||||
};
|
||||
const beforeMap = index(before);
|
||||
const afterMap = index(after);
|
||||
const keys = [...new Set([...beforeMap.keys(), ...afterMap.keys()])].sort();
|
||||
const lines: QuoteChangeLine[] = [];
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
let updated = 0;
|
||||
for (const key of keys) {
|
||||
const oldRow = beforeMap.get(key) || null;
|
||||
const newRow = afterMap.get(key) || null;
|
||||
if (!oldRow && newRow) {
|
||||
added += 1;
|
||||
lines.push(changeLine(null, newRow, 'added'));
|
||||
continue;
|
||||
}
|
||||
if (oldRow && !newRow) {
|
||||
removed += 1;
|
||||
lines.push(changeLine(oldRow, null, 'removed'));
|
||||
continue;
|
||||
}
|
||||
const changed =
|
||||
Math.abs(readItemSale(oldRow!) - readItemSale(newRow!)) > 1e-6 ||
|
||||
Math.abs(readItemCost(oldRow!) - readItemCost(newRow!)) > 1e-6 ||
|
||||
toText(oldRow!.unit).toLowerCase() !== toText(newRow!.unit).toLowerCase();
|
||||
if (changed) {
|
||||
updated += 1;
|
||||
lines.push(changeLine(oldRow, newRow, 'updated'));
|
||||
}
|
||||
}
|
||||
return {
|
||||
item_count: afterMap.size,
|
||||
added,
|
||||
removed,
|
||||
updated,
|
||||
lines: lines.slice(0, 30),
|
||||
truncated: lines.length > 30,
|
||||
};
|
||||
}
|
||||
|
||||
/** 从「当前报价单明细 + 变更 payload」生成审核摘要 */
|
||||
export function buildChangeSummaryFromItems(
|
||||
payload: QuoteChangePayload | null | undefined,
|
||||
beforeRows: ItemLike[]
|
||||
): QuoteChangeSummary {
|
||||
const body = (payload || {}) as QuoteChangePayload;
|
||||
const itemsProvided = Array.isArray(body.items);
|
||||
const diff = itemsProvided
|
||||
? diffQuoteSheetItems(beforeRows, body.items as ItemLike[])
|
||||
: { item_count: 0, added: 0, removed: 0, updated: 0, lines: [], truncated: false };
|
||||
return {
|
||||
title: typeof body.title === 'string' ? body.title : null,
|
||||
quote_cycle: typeof body.quote_cycle === 'string' ? body.quote_cycle : null,
|
||||
effective_at: typeof body.effective_at === 'string' ? body.effective_at : null,
|
||||
auto_sale_price_by_cost:
|
||||
typeof body.auto_sale_price_by_cost === 'boolean' ? body.auto_sale_price_by_cost : null,
|
||||
customer_codes: Array.isArray(body.customer_codes) ? body.customer_codes.map(String) : null,
|
||||
items_provided: itemsProvided,
|
||||
...diff,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadSheetItems(quoteSheetCode: string): Promise<ItemLike[]> {
|
||||
const result = await pool.query<ItemLike>(
|
||||
`SELECT sku_code, sku_name, unit, sale_price, price, cost_price
|
||||
FROM customer_quote_sheet_items
|
||||
WHERE quote_sheet_code = $1
|
||||
ORDER BY sort_order ASC, sku_code ASC`,
|
||||
[quoteSheetCode]
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
/** 审核摘要(查当前明细后生成;提交响应与列表都用它) */
|
||||
export async function buildQuoteChangeSummary(
|
||||
quoteSheetCode: string,
|
||||
payload: QuoteChangePayload | null | undefined
|
||||
): Promise<QuoteChangeSummary> {
|
||||
return buildChangeSummaryFromItems(payload, await loadSheetItems(quoteSheetCode));
|
||||
}
|
||||
|
||||
function toDto(row: Record<string, any>): QuoteChangeRequestDto {
|
||||
return {
|
||||
id: String(row.id),
|
||||
branch_code: String(row.branch_code),
|
||||
quote_sheet_code: String(row.quote_sheet_code),
|
||||
payload: (row.payload || {}) as QuoteChangePayload,
|
||||
base_version_no: row.base_version_no === null || row.base_version_no === undefined ? null : Number(row.base_version_no),
|
||||
base_items_fingerprint: row.base_items_fingerprint ? String(row.base_items_fingerprint) : null,
|
||||
status: row.status,
|
||||
requested_by: row.requested_by ? String(row.requested_by) : null,
|
||||
requested_by_name: row.requested_by_name ? String(row.requested_by_name) : null,
|
||||
requested_at: row.requested_at ?? null,
|
||||
reviewed_by: row.reviewed_by ? String(row.reviewed_by) : null,
|
||||
reviewed_by_name: row.reviewed_by_name ? String(row.reviewed_by_name) : null,
|
||||
reviewed_at: row.reviewed_at ?? null,
|
||||
reject_reason: row.reject_reason ? String(row.reject_reason) : null,
|
||||
applied_at: row.applied_at ?? null,
|
||||
updated_at: row.updated_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildChangePayload(
|
||||
input: QuoteSheetUpdateInput,
|
||||
normalized: { customerCodes: string[] | null; items: QuoteSheetItemInput[] | null }
|
||||
): QuoteChangePayload {
|
||||
const payload: QuoteChangePayload = {};
|
||||
if (input.title !== undefined) payload.title = String(input.title ?? '');
|
||||
if (normalized.customerCodes) payload.customer_codes = normalized.customerCodes;
|
||||
if (normalized.items) payload.items = normalized.items;
|
||||
if (input.autoSalePriceByCost !== undefined) payload.auto_sale_price_by_cost = Boolean(input.autoSalePriceByCost);
|
||||
if (input.quoteCycle !== undefined) payload.quote_cycle = String(input.quoteCycle ?? '');
|
||||
if (input.effectiveAt !== undefined) payload.effective_at = String(input.effectiveAt);
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* 落一条 pending 变更单(D4):先把该单旧的 pending 置 `superseded`,再插入新的。
|
||||
*
|
||||
* 并发两次提交会撞 partial unique index(23505)⇒ 回滚后**重跑一次**(重跑时旧 pending 已可见可覆盖)。
|
||||
*/
|
||||
async function supersedeAndInsertPending(input: {
|
||||
branchCode: string;
|
||||
quoteSheetCode: string;
|
||||
payload: QuoteChangePayload;
|
||||
baseVersionNo: number | null;
|
||||
baseItemsFingerprint: string;
|
||||
requestedBy: string | null;
|
||||
}): Promise<{ changeRequest: QuoteChangeRequestDto; supersededId: string | null }> {
|
||||
let lastError: any = null;
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
// 先取旧 pending 的 id(D4 覆盖留痕 + 审计要记"旧状态→新状态")
|
||||
const previous = await client.query<{ id: string }>(
|
||||
`SELECT id::text AS id FROM quote_sheet_change_requests
|
||||
WHERE branch_code = $1 AND quote_sheet_code = $2 AND status = 'pending'
|
||||
FOR UPDATE`,
|
||||
[input.branchCode, input.quoteSheetCode]
|
||||
);
|
||||
const supersededId = previous.rows[0] ? String(previous.rows[0].id) : null;
|
||||
await client.query(
|
||||
`UPDATE quote_sheet_change_requests
|
||||
SET status = 'superseded', updated_at = NOW()
|
||||
WHERE branch_code = $1 AND quote_sheet_code = $2 AND status = 'pending'`,
|
||||
[input.branchCode, input.quoteSheetCode]
|
||||
);
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO quote_sheet_change_requests
|
||||
(branch_code, quote_sheet_code, payload, base_version_no, base_items_fingerprint,
|
||||
status, requested_by, requested_at, updated_at)
|
||||
VALUES ($1, $2, $3::jsonb, $4, $5, 'pending', $6::uuid, NOW(), NOW())
|
||||
RETURNING *`,
|
||||
[
|
||||
input.branchCode,
|
||||
input.quoteSheetCode,
|
||||
JSON.stringify(input.payload),
|
||||
input.baseVersionNo,
|
||||
input.baseItemsFingerprint,
|
||||
input.requestedBy,
|
||||
]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return { changeRequest: toDto(inserted.rows[0] as Record<string, any>), supersededId };
|
||||
} catch (error: any) {
|
||||
try {
|
||||
await client.query('ROLLBACK');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
lastError = error;
|
||||
if (error?.code === '23505' && attempt === 0) continue;
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
throw lastError || httpError(500, 'change_request_conflict', '提交待审变更失败');
|
||||
}
|
||||
|
||||
|
||||
export type SaveQuoteSheetEditResult =
|
||||
| { applied: true; data: unknown }
|
||||
| { applied: false; data: unknown; changeRequest: QuoteChangeRequestDto };
|
||||
|
||||
/**
|
||||
* 编辑保存入口(`PUT /quote/sheets/:code` 的唯一分流点):
|
||||
* 价格相关 + 开关开 ⇒ 写/覆盖 pending 变更单,**不落报价单**,`applied:false`;
|
||||
* 非价格 或 开关关 ⇒ 走现有 `updateQuoteSheet`(逐字不变),`applied:true`。
|
||||
*/
|
||||
export async function saveQuoteSheetEdit(
|
||||
input: QuoteSheetUpdateInput & { requestedBy?: string | null }
|
||||
): Promise<SaveQuoteSheetEditResult> {
|
||||
const existing = await loadQuoteSheetForUpdate(
|
||||
input.quoteSheetCode,
|
||||
input.ctx,
|
||||
input.operatingBranchCode
|
||||
);
|
||||
const priceRelated = isPriceRelatedQuoteEdit(input, existing as { auto_sale_price_by_cost?: unknown });
|
||||
const branchCode = String(existing.branch_code || '').trim();
|
||||
|
||||
if (!isQuoteEditApprovalEnabled() || !priceRelated) {
|
||||
const data = await updateQuoteSheet(input);
|
||||
// Lead 裁定 #6:非价格编辑若新增了 MAIN_<分公司> 客户,也要触发一次成本价同步。
|
||||
// 触发入口自带「指纹判重 + (单,分公司) 唯一键」⇒ 明细没变就是 duplicate 零出站;目标分公司集合变了则自然补推。
|
||||
if (!priceRelated) {
|
||||
triggerQuoteCostSync({ branchCode, quoteSheetCode: input.quoteSheetCode });
|
||||
}
|
||||
return { applied: true, data };
|
||||
}
|
||||
|
||||
// 价格相关:先做提交期校验(失败即 400,一条变更单都不写、报价单也不动)
|
||||
assertNoDuplicateSku(input.items);
|
||||
const normalized = normalizeQuoteSheetUpdatePayload({
|
||||
customerCodes: input.customerCodes,
|
||||
items: input.items,
|
||||
});
|
||||
if (normalized.customerCodes) await assertCustomersInBranch(normalized.customerCodes, branchCode);
|
||||
|
||||
const baseItemsFingerprint = quoteSheetItemsFingerprint(await loadSheetItems(input.quoteSheetCode));
|
||||
const { changeRequest, supersededId } = await supersedeAndInsertPending({
|
||||
branchCode,
|
||||
quoteSheetCode: input.quoteSheetCode,
|
||||
payload: buildChangePayload(input, normalized),
|
||||
baseVersionNo: Number(existing.version_no) || null,
|
||||
baseItemsFingerprint,
|
||||
requestedBy: input.requestedBy ?? null,
|
||||
});
|
||||
// 审计(A26):提交/覆盖都记一条;事务**提交之后**写,best-effort,失败只记日志
|
||||
await auditChangeRequest({
|
||||
operatorId: input.ctx?.userId || input.requestedBy || null,
|
||||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||||
action: 'submit',
|
||||
branchCode,
|
||||
changeRequestId: changeRequest.id,
|
||||
quoteSheetCode: input.quoteSheetCode,
|
||||
oldStatus: supersededId ? 'pending' : '(none)',
|
||||
newStatus: 'pending',
|
||||
reason: supersededId ? `superseded:${supersededId}` : null,
|
||||
});
|
||||
const data = await getQuoteSheet(input.quoteSheetCode, input.ctx, input.operatingBranchCode);
|
||||
return {
|
||||
applied: false,
|
||||
data,
|
||||
changeRequest: {
|
||||
...changeRequest,
|
||||
summary: buildChangeSummaryFromItems(changeRequest.payload, await loadSheetItems(input.quoteSheetCode)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type DeliveryHandoffResult = {
|
||||
ok: boolean;
|
||||
/** 无需传递时的原因:not_price_related / no_usage_company */
|
||||
skipped?: string | null;
|
||||
proposal_id?: string | null;
|
||||
status?: string | null;
|
||||
code?: string | null;
|
||||
message?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 新口径(2026-10-18 用户裁定「方案 A + 自己只能改自己的」):
|
||||
* · 供应商改**自己**报价单的销售价 ⇒ **立即落本系统**(自己的数据自己改);
|
||||
* · 然后**自动发一条「配送商销售价确认」申请**给对方审核(A 方向 `submitPriceProposal`);
|
||||
* · 本系统**不再**做内部待审改价,也**不再**直接推对方成本价(对方成本价只能由对方审核通过后自己写)。
|
||||
*
|
||||
* 传递失败**不回滚**已生效的改价(那是本系统自己的数据),只把失败原因回给前端提示重试。
|
||||
*/
|
||||
export async function applyQuoteSheetEditAndRequestDeliveryReview(
|
||||
input: QuoteSheetUpdateInput & { requestedBy?: string | null }
|
||||
): Promise<{ applied: true; data: unknown; delivery_handoff: DeliveryHandoffResult }> {
|
||||
const existing = await loadQuoteSheetForUpdate(
|
||||
input.quoteSheetCode,
|
||||
input.ctx,
|
||||
input.operatingBranchCode
|
||||
);
|
||||
const priceRelated = isPriceRelatedQuoteEdit(input, existing as { auto_sale_price_by_cost?: unknown });
|
||||
const data = await updateQuoteSheet(input);
|
||||
if (!priceRelated) {
|
||||
return {
|
||||
applied: true,
|
||||
data,
|
||||
delivery_handoff: { ok: true, skipped: 'not_price_related' },
|
||||
};
|
||||
}
|
||||
try {
|
||||
const res = await submitPriceProposal({
|
||||
quoteSheetCode: input.quoteSheetCode,
|
||||
note: null,
|
||||
ctx: input.ctx ?? null,
|
||||
operatingBranchCode: input.operatingBranchCode ?? null,
|
||||
requestedBy: input.requestedBy ?? null,
|
||||
});
|
||||
return {
|
||||
applied: true,
|
||||
data,
|
||||
delivery_handoff: {
|
||||
ok: true,
|
||||
proposal_id: res.proposal?.id ? String(res.proposal.id) : null,
|
||||
status: res.proposal?.status ? String(res.proposal.status) : null,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
const code = String(error?.code || '');
|
||||
// 没有绑定主系统使用公司(MAIN_*)的报价单,本来就不需要传递
|
||||
if (code === 'not_usage_company') {
|
||||
return { applied: true, data, delivery_handoff: { ok: true, skipped: 'no_usage_company' } };
|
||||
}
|
||||
return {
|
||||
applied: true,
|
||||
data,
|
||||
delivery_handoff: {
|
||||
ok: false,
|
||||
code: code || 'handoff_failed',
|
||||
message: error?.message || '改价已生效,但传递配送商审核失败',
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export type ListQuoteChangeRequestsInput = {
|
||||
branchCode: string;
|
||||
status?: string;
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
/** 待审/历史列表(按分公司;`pending` 行带审核摘要) */
|
||||
export async function listQuoteSheetChangeRequests(
|
||||
input: ListQuoteChangeRequestsInput
|
||||
): Promise<QuoteChangeRequestDto[]> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
if (!branchCode) return [];
|
||||
const status = ['pending', 'approved', 'rejected', 'superseded'].includes(String(input.status || ''))
|
||||
? String(input.status)
|
||||
: 'pending';
|
||||
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
|
||||
const result = await pool.query(
|
||||
// ⚠️ 展示名在 **public.profiles**(`full_name`/`username`),不在 `auth.users`
|
||||
// (auth.users 是 Supabase 兼容表的子集,没有这两列;写错会让列表 GET 直接 500 —— 真库复现过)。
|
||||
// 仓库既有惯例见 `server/src/middleware/auth.ts` 的 `LEFT JOIN public.profiles p ON p.id = u.id`。
|
||||
`SELECT cr.*,
|
||||
COALESCE(NULLIF(TRIM(ru.full_name), ''), NULLIF(TRIM(ru.username), ''), '') AS requested_by_name,
|
||||
COALESCE(NULLIF(TRIM(vu.full_name), ''), NULLIF(TRIM(vu.username), ''), '') AS reviewed_by_name
|
||||
FROM quote_sheet_change_requests cr
|
||||
LEFT JOIN public.profiles ru ON ru.id = cr.requested_by
|
||||
LEFT JOIN public.profiles vu ON vu.id = cr.reviewed_by
|
||||
WHERE cr.branch_code = $1 AND cr.status = $2
|
||||
ORDER BY cr.requested_at DESC
|
||||
LIMIT $3`,
|
||||
[branchCode, status, limit]
|
||||
);
|
||||
const rows = result.rows.map((row) => toDto(row as Record<string, any>));
|
||||
const pendingCodes = [...new Set(rows.filter((row) => row.status === 'pending').map((row) => row.quote_sheet_code))];
|
||||
if (pendingCodes.length) {
|
||||
const items = await pool.query<ItemLike & { quote_sheet_code: string }>(
|
||||
`SELECT quote_sheet_code, sku_code, sku_name, unit, sale_price, price, cost_price
|
||||
FROM customer_quote_sheet_items
|
||||
WHERE quote_sheet_code = ANY($1)`,
|
||||
[pendingCodes]
|
||||
);
|
||||
const bySheet = new Map<string, ItemLike[]>();
|
||||
for (const row of items.rows) {
|
||||
const code = String((row as any).quote_sheet_code);
|
||||
if (!bySheet.has(code)) bySheet.set(code, []);
|
||||
bySheet.get(code)!.push(row);
|
||||
}
|
||||
for (const dto of rows) {
|
||||
if (dto.status !== 'pending') continue;
|
||||
dto.summary = buildChangeSummaryFromItems(dto.payload, bySheet.get(dto.quote_sheet_code) || []);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** payload → `applyQuoteSheetUpdate` 入参(审批通过时使用;只认存下来的字段) */
|
||||
export function payloadToUpdateInput(
|
||||
row: { quote_sheet_code: string; payload: QuoteChangePayload | null },
|
||||
options?: { ctx?: TenantContext | null; operatingBranchCode?: string | null }
|
||||
): QuoteSheetUpdateInput {
|
||||
const payload = (row.payload || {}) as QuoteChangePayload;
|
||||
return {
|
||||
quoteSheetCode: String(row.quote_sheet_code),
|
||||
ctx: options?.ctx,
|
||||
operatingBranchCode: options?.operatingBranchCode,
|
||||
title: typeof payload.title === 'string' ? payload.title : undefined,
|
||||
customerCodes: Array.isArray(payload.customer_codes) ? payload.customer_codes.map(String) : undefined,
|
||||
items: Array.isArray(payload.items) ? payload.items.map(normalizeStoredItem) : undefined,
|
||||
autoSalePriceByCost:
|
||||
typeof payload.auto_sale_price_by_cost === 'boolean' ? payload.auto_sale_price_by_cost : undefined,
|
||||
quoteCycle: typeof payload.quote_cycle === 'string' ? payload.quote_cycle : undefined,
|
||||
effectiveAt: typeof payload.effective_at === 'string' ? payload.effective_at : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeStoredItem(raw: unknown): QuoteSheetItemInput {
|
||||
const item = (raw || {}) as Record<string, unknown>;
|
||||
const sale = Number(item.sale_price ?? item.price);
|
||||
return {
|
||||
sku_code: toText(item.sku_code),
|
||||
unit: item.unit === null || item.unit === undefined ? undefined : String(item.unit),
|
||||
price: Number.isFinite(sale) ? sale : 0,
|
||||
sale_price: Number.isFinite(sale) ? sale : 0,
|
||||
cost_price: Number(item.cost_price) || 0,
|
||||
markup_ratio: item.markup_ratio === null || item.markup_ratio === undefined ? null : Number(item.markup_ratio),
|
||||
sku_name: item.sku_name === null || item.sku_name === undefined ? undefined : String(item.sku_name),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用前校验:SKU 必须仍存活(`skus.status = 1`)、客户必须仍属该分公司。
|
||||
*
|
||||
* 为什么非查不可:真库 `customer_quote_sheet_items` **零外键**(只有 `legacy_public` 有),
|
||||
* 直接 INSERT 会造出孤儿行且**没有任何报错**。校验失败 ⇒ 409,变更单保持 pending(不悄悄丢掉),
|
||||
* 由审核人决定驳回。
|
||||
*/
|
||||
async function assertPayloadStillApplicable(
|
||||
client: import('pg').PoolClient,
|
||||
row: { quote_sheet_code: string; payload: QuoteChangePayload | null; branch_code: string }
|
||||
): Promise<void> {
|
||||
const payload = (row.payload || {}) as QuoteChangePayload;
|
||||
const skuCodes = [
|
||||
...new Set((payload.items || []).map((item) => toText(item?.sku_code)).filter(Boolean)),
|
||||
];
|
||||
if (skuCodes.length) {
|
||||
const alive = await client.query<{ sku_code: string }>(
|
||||
`SELECT sku_code FROM skus WHERE sku_code = ANY($1) AND status = 1`,
|
||||
[skuCodes]
|
||||
);
|
||||
const aliveSet = new Set(alive.rows.map((item) => String(item.sku_code)));
|
||||
const missing = skuCodes.filter((code) => !aliveSet.has(code));
|
||||
if (missing.length) {
|
||||
throw httpError(409, 'sku_unavailable', `商品已停用或不存在:${missing.slice(0, 5).join('、')}`);
|
||||
}
|
||||
}
|
||||
const customerCodes = Array.isArray(payload.customer_codes) ? payload.customer_codes.map(String) : [];
|
||||
if (customerCodes.length) {
|
||||
const found = await client.query<{ customer_code: string }>(
|
||||
`SELECT customer_code FROM customers WHERE customer_code = ANY($1) AND branch_code = $2`,
|
||||
[customerCodes, row.branch_code]
|
||||
);
|
||||
const foundSet = new Set(found.rows.map((item) => String(item.customer_code)));
|
||||
const missing = customerCodes.filter((code) => !foundSet.has(code));
|
||||
if (missing.length) {
|
||||
throw httpError(409, 'invalid_customer', `客户不属于本分公司或已不存在:${missing.slice(0, 5).join('、')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type ApproveQuoteChangeRequestInput = {
|
||||
id: string;
|
||||
ctx?: TenantContext | null;
|
||||
operatingBranchCode?: string | null;
|
||||
reviewedBy?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 审核通过:**单事务**内应用变更 + 记审批 → 提交后再触发成本价同步(rearm 路径)。
|
||||
*
|
||||
* ⚠️ 绝不走 `approveQuoteSheet`/`activateQuoteSheet`:那会把**同分公司共享客户的其它生效单**置 `status=3`
|
||||
* 并重写审批字段;本路径只复用 `applyQuoteSheetUpdate`,报价单的 4 个审批字段一个都不碰。
|
||||
*/
|
||||
export async function approveQuoteSheetChangeRequest(
|
||||
input: ApproveQuoteChangeRequestInput
|
||||
): Promise<{ data: unknown; changeRequest: QuoteChangeRequestDto }> {
|
||||
const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode);
|
||||
if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司');
|
||||
|
||||
const client = await pool.connect();
|
||||
let committed = false;
|
||||
let row: Record<string, any>;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const locked = await client.query(
|
||||
`SELECT * FROM quote_sheet_change_requests WHERE id = $1::uuid FOR UPDATE`,
|
||||
[input.id]
|
||||
);
|
||||
if (!locked.rows.length) throw httpError(404, 'change_request_not_found', '变更单不存在');
|
||||
row = locked.rows[0] as Record<string, any>;
|
||||
if (String(row.branch_code) !== branchCode) {
|
||||
throw httpError(403, 'branch_mismatch', '无权操作其它分公司的变更单');
|
||||
}
|
||||
if (String(row.status) !== 'pending') {
|
||||
throw httpError(409, 'already_decided', '该变更单已处理');
|
||||
}
|
||||
|
||||
/**
|
||||
* **校验顺序(P3-1,红队第三轮)**:目标单**可用性**必须排在**指纹**之前。
|
||||
*
|
||||
* 为什么:目标报价单被**硬删除**时,`customer_quote_sheet_items` 查出来是空集
|
||||
* ⇒ 指纹必然"不一致" ⇒ 会走 `base_changed` 的**自动 rejected** 分支;
|
||||
* 而 A12③ 修订版要求这种情况是 **409 `target_unavailable` + 变更单保持 pending**(人工可驳回)。
|
||||
*
|
||||
* ⚠️ 只动顺序,不动语义:
|
||||
* · 目标不存在/非执行中/已过期 ⇒ `loadQuoteSheetForUpdate` 抛既有普通 Error ⇒ `mapTargetUnavailable`
|
||||
* 映射成 409 `target_unavailable`(变更单保持 pending,零应用、零推送);
|
||||
* · 目标**仍可用但指纹变了** ⇒ 仍然 409 `base_changed` + 自动 `rejected`(下一段,不回退)。
|
||||
*/
|
||||
try {
|
||||
await loadQuoteSheetForUpdate(row.quote_sheet_code, input.ctx, input.operatingBranchCode);
|
||||
} catch (error: any) {
|
||||
throw mapTargetUnavailable(error) || error;
|
||||
}
|
||||
|
||||
// 目标单在提交后是否被改过(base_changed):指纹不一致 ⇒ 整单拒绝,零应用、零推送
|
||||
const currentItems = await client.query(
|
||||
`SELECT sku_code, unit, sale_price, price FROM customer_quote_sheet_items
|
||||
WHERE quote_sheet_code = $1`,
|
||||
[row.quote_sheet_code]
|
||||
);
|
||||
if (quoteSheetItemsFingerprint(currentItems.rows as ItemLike[]) !== String(row.base_items_fingerprint || '')) {
|
||||
const rejected = await client.query(
|
||||
`UPDATE quote_sheet_change_requests
|
||||
SET status = 'rejected', reviewed_by = $2::uuid, reviewed_at = NOW(),
|
||||
reject_reason = 'base_changed', updated_at = NOW()
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
RETURNING *`,
|
||||
[row.id, input.reviewedBy ?? null]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
committed = true;
|
||||
if (rejected.rows.length) row = rejected.rows[0] as Record<string, any>;
|
||||
// 系统自动驳回也留审计(A26)
|
||||
await auditChangeRequest({
|
||||
operatorId: input.ctx?.userId || input.reviewedBy || null,
|
||||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||||
action: 'reject',
|
||||
branchCode,
|
||||
changeRequestId: String(row.id),
|
||||
quoteSheetCode: String(row.quote_sheet_code),
|
||||
oldStatus: 'pending',
|
||||
newStatus: 'rejected',
|
||||
reason: 'base_changed',
|
||||
});
|
||||
throw httpError(409, 'base_changed', '报价单在提交后被修改,本条变更已整单拒绝(未应用、未同步)');
|
||||
}
|
||||
|
||||
// 应用前守卫:SKU 存活 + 客户归属(零外键 ⇒ 必须自己查);目标可用性已在上方校验过
|
||||
await assertPayloadStillApplicable(client, row as any);
|
||||
|
||||
let data: unknown;
|
||||
try {
|
||||
data = await applyQuoteSheetUpdate(payloadToUpdateInput(row as any, {
|
||||
ctx: input.ctx,
|
||||
operatingBranchCode: input.operatingBranchCode,
|
||||
}), { client });
|
||||
} catch (error: any) {
|
||||
// 同上:apply 内部的三连守卫也是普通 Error(并发下目标单状态可能在这一刻变化)
|
||||
throw mapTargetUnavailable(error) || error;
|
||||
}
|
||||
|
||||
const approved = await client.query(
|
||||
`UPDATE quote_sheet_change_requests
|
||||
SET status = 'approved', reviewed_by = $2::uuid, reviewed_at = NOW(),
|
||||
applied_at = NOW(), reject_reason = NULL, updated_at = NOW()
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
RETURNING *`,
|
||||
[row.id, input.reviewedBy ?? null]
|
||||
);
|
||||
if (!approved.rows.length) throw httpError(409, 'already_decided', '该变更单已处理');
|
||||
row = approved.rows[0] as Record<string, any>;
|
||||
await client.query('COMMIT');
|
||||
committed = true;
|
||||
|
||||
// 事务提交之后:先留审计(A26),再触发成本价同步(既有 rearm 路径)
|
||||
await auditChangeRequest({
|
||||
operatorId: input.ctx?.userId || input.reviewedBy || null,
|
||||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||||
action: 'approve',
|
||||
branchCode,
|
||||
changeRequestId: String(row.id),
|
||||
quoteSheetCode: String(row.quote_sheet_code),
|
||||
oldStatus: 'pending',
|
||||
newStatus: 'approved',
|
||||
});
|
||||
triggerQuoteCostSync({
|
||||
branchCode: String(row.branch_code),
|
||||
quoteSheetCode: String(row.quote_sheet_code),
|
||||
});
|
||||
|
||||
const detail = await getQuoteSheet(
|
||||
String(row.quote_sheet_code),
|
||||
input.ctx,
|
||||
input.operatingBranchCode
|
||||
);
|
||||
return {
|
||||
data: detail,
|
||||
changeRequest: {
|
||||
...toDto(row),
|
||||
summary: buildChangeSummaryFromItems(row.payload as QuoteChangePayload, await loadSheetItems(String(row.quote_sheet_code))),
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
if (!committed) {
|
||||
try {
|
||||
await client.query('ROLLBACK');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
export type RejectQuoteChangeRequestInput = {
|
||||
id: string;
|
||||
reason: string;
|
||||
ctx?: TenantContext | null;
|
||||
operatingBranchCode?: string | null;
|
||||
reviewedBy?: string | null;
|
||||
};
|
||||
|
||||
/** 审核驳回:只改变更单状态(`rejected` + 理由),报价单不变、**零推送**。 */
|
||||
export async function rejectQuoteSheetChangeRequest(
|
||||
input: RejectQuoteChangeRequestInput
|
||||
): Promise<{ changeRequest: QuoteChangeRequestDto }> {
|
||||
const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode);
|
||||
if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司');
|
||||
const reason = toText(input.reason);
|
||||
if (!reason) throw httpError(400, 'reject_reason_required', '请填写驳回理由');
|
||||
|
||||
const found = await pool.query(
|
||||
`SELECT id, branch_code, status FROM quote_sheet_change_requests WHERE id = $1::uuid`,
|
||||
[input.id]
|
||||
);
|
||||
if (!found.rows.length) throw httpError(404, 'change_request_not_found', '变更单不存在');
|
||||
if (String(found.rows[0].branch_code) !== branchCode) {
|
||||
throw httpError(403, 'branch_mismatch', '无权操作其它分公司的变更单');
|
||||
}
|
||||
const updated = await pool.query(
|
||||
`UPDATE quote_sheet_change_requests
|
||||
SET status = 'rejected', reviewed_by = $2::uuid, reviewed_at = NOW(),
|
||||
reject_reason = $3, updated_at = NOW()
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
RETURNING *`,
|
||||
[input.id, input.reviewedBy ?? null, reason]
|
||||
);
|
||||
if (!updated.rows.length) throw httpError(409, 'already_decided', '该变更单已处理');
|
||||
const changeRequest = toDto(updated.rows[0] as Record<string, any>);
|
||||
// 审计(A26):驳回路径,best-effort
|
||||
await auditChangeRequest({
|
||||
operatorId: input.ctx?.userId || input.reviewedBy || null,
|
||||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||||
action: 'reject',
|
||||
branchCode,
|
||||
changeRequestId: changeRequest.id,
|
||||
quoteSheetCode: changeRequest.quote_sheet_code,
|
||||
oldStatus: 'pending',
|
||||
newStatus: 'rejected',
|
||||
reason,
|
||||
});
|
||||
return { changeRequest };
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
loadQuoteSheetForUpdate,
|
||||
updateQuoteSheet,
|
||||
type QuoteSheetUpdateInput,
|
||||
} from './quoteSheetService';
|
||||
import { submitPriceProposal } from './quotePriceProposalService';
|
||||
import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||||
|
||||
/**
|
||||
* 编辑/生效报价单后的**跨系统**价格传递(2026-10-18 用户裁定):
|
||||
* · 「自己只能改自己的」:供应商改价只写**本系统** `customer_quote_sheet_items`;
|
||||
* · 改价后**自动发一条「配送商销售价确认」申请**(A 方向 `submitPriceProposal`),
|
||||
* 由配送商在他自己的系统里审核,通过后才由**配送商**写他自己的 `cost_price`;
|
||||
* · 本系统**不再**直接推/写对方的成本价(旧的 `triggerQuoteCostSync` 直推链路已停用)。
|
||||
*
|
||||
* 传递失败**不回滚**已生效的改价(那是本系统的数据),只把原因回给前端提示重试。
|
||||
*/
|
||||
|
||||
export type DeliveryHandoffResult = {
|
||||
ok: boolean;
|
||||
/** 无需传递时的原因:not_price_related / no_usage_company */
|
||||
skipped?: string | null;
|
||||
proposal_id?: string | null;
|
||||
status?: string | null;
|
||||
code?: string | null;
|
||||
message?: string | null;
|
||||
};
|
||||
|
||||
/** 判断这次编辑是否动了价格(含明细或「按成本自动定价」开关变化) */
|
||||
export function isPriceRelatedQuoteEdit(
|
||||
input: Pick<QuoteSheetUpdateInput, 'items' | 'autoSalePriceByCost'>,
|
||||
existing: { auto_sale_price_by_cost?: unknown } | null
|
||||
): boolean {
|
||||
if (Array.isArray(input.items)) return true;
|
||||
if (input.autoSalePriceByCost === undefined) return false;
|
||||
return Boolean(input.autoSalePriceByCost) !== Boolean(existing?.auto_sale_price_by_cost);
|
||||
}
|
||||
|
||||
/** 对一张报价单发起「请配送商审核销售价」;失败不抛(调用方自行决定是否提示) */
|
||||
export async function requestDeliveryReviewForSheet(input: {
|
||||
quoteSheetCode: string;
|
||||
branchCode?: string | null;
|
||||
ctx?: TenantContext | null;
|
||||
operatingBranchCode?: string | null;
|
||||
requestedBy?: string | null;
|
||||
}): Promise<DeliveryHandoffResult> {
|
||||
const branchCode =
|
||||
input.branchCode || getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode || null);
|
||||
if (!branchCode) return { ok: false, code: 'branch_required', message: '请选择当前操作分公司' };
|
||||
try {
|
||||
const res = await submitPriceProposal({
|
||||
quoteSheetCode: input.quoteSheetCode,
|
||||
note: null,
|
||||
ctx: input.ctx ?? null,
|
||||
operatingBranchCode: input.operatingBranchCode ?? branchCode,
|
||||
requestedBy: input.requestedBy ?? null,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
proposal_id: res.proposal?.id ? String(res.proposal.id) : null,
|
||||
status: res.proposal?.status ? String(res.proposal.status) : null,
|
||||
};
|
||||
} catch (error: any) {
|
||||
const code = String(error?.code || '');
|
||||
// 没有绑定主系统使用公司(MAIN_*)的报价单,本来就不需要传递
|
||||
if (code === 'not_usage_company') {
|
||||
return { ok: true, skipped: 'no_usage_company' };
|
||||
}
|
||||
// 开关关闭 / 主系统不可用:只记录,不阻断本系统自己的改价
|
||||
return {
|
||||
ok: false,
|
||||
code: code || 'handoff_failed',
|
||||
message: error?.message || '传递配送商审核失败',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** 编辑生效报价单:先落本系统,再自动发申请给对方审核 */
|
||||
export async function applyQuoteSheetEditAndRequestDeliveryReview(
|
||||
input: QuoteSheetUpdateInput & { requestedBy?: string | null }
|
||||
): Promise<{ applied: true; data: unknown; delivery_handoff: DeliveryHandoffResult }> {
|
||||
const existing = await loadQuoteSheetForUpdate(
|
||||
input.quoteSheetCode,
|
||||
input.ctx,
|
||||
input.operatingBranchCode
|
||||
);
|
||||
const priceRelated = isPriceRelatedQuoteEdit(input, existing as { auto_sale_price_by_cost?: unknown });
|
||||
const data = await updateQuoteSheet(input);
|
||||
if (!priceRelated) {
|
||||
return { applied: true, data, delivery_handoff: { ok: true, skipped: 'not_price_related' } };
|
||||
}
|
||||
const delivery_handoff = await requestDeliveryReviewForSheet({
|
||||
quoteSheetCode: input.quoteSheetCode,
|
||||
branchCode: String(existing.branch_code || ''),
|
||||
ctx: input.ctx ?? null,
|
||||
operatingBranchCode: input.operatingBranchCode ?? null,
|
||||
requestedBy: input.requestedBy ?? null,
|
||||
});
|
||||
return { applied: true, data, delivery_handoff };
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pool } from '../db';
|
||||
import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||||
import { notifyRoleUsers } from './notificationService';
|
||||
import { triggerQuoteCostSync } from './mainSystemQuoteCostSync';
|
||||
|
||||
export const QUOTE_CYCLE_OPTIONS = {
|
||||
week: { label: '周', days: 7 },
|
||||
@@ -249,11 +248,11 @@ export async function createQuoteSheet(input: {
|
||||
|
||||
const detail = await loadSheetDetail(quoteSheetCode);
|
||||
/**
|
||||
* 报价单已生效 ⇒ **事务提交之后**把销售价推给主系统(成本价同步,开关默认关)。
|
||||
* 旁路异步 + 内部吞异常:任何推送失败都不得让建单失败;出网也绝不在事务内。
|
||||
* 设计:docs/design/20261018-报价单成本价同步推送.md §3
|
||||
* 报价单已生效 ⇒ **事务提交之后**发一条「配送商销售价确认」申请(A 方向)。
|
||||
* 旁路异步 + 吞异常:传递失败不得让建单失败;出网也绝不在事务内。
|
||||
* 口径(2026-10-18):本系统**不再**直接写对方成本价,由配送商审核通过后写他自己的。
|
||||
*/
|
||||
triggerQuoteCostSync({ branchCode: detail?.branch_code, quoteSheetCode });
|
||||
requestDeliveryReviewInBackground(detail?.branch_code, quoteSheetCode);
|
||||
return detail;
|
||||
}
|
||||
|
||||
@@ -356,8 +355,8 @@ export async function submitQuoteSheetForApproval(input: {
|
||||
}
|
||||
|
||||
const detail = await loadSheetDetail(input.quoteSheetCode);
|
||||
// 提交报价单(旧接口:提交即生效)⇒ 事务提交之后再推送销售价(旁路,失败不影响审批)
|
||||
triggerQuoteCostSync({ branchCode: detail?.branch_code, quoteSheetCode: input.quoteSheetCode });
|
||||
// 提交报价单(旧接口:提交即生效)⇒ 事务提交之后发申请给配送商审核(旁路,失败不影响审批)
|
||||
requestDeliveryReviewInBackground(detail?.branch_code, input.quoteSheetCode);
|
||||
return detail;
|
||||
}
|
||||
|
||||
@@ -1016,8 +1015,8 @@ export async function approveQuoteSheet(input: {
|
||||
client.release();
|
||||
}
|
||||
const detail = await loadSheetDetail(input.quoteSheetCode);
|
||||
// 审批通过 ⇒ 事务提交之后再推送销售价(旁路,失败不影响审批结论)
|
||||
triggerQuoteCostSync({ branchCode: detail?.branch_code, quoteSheetCode: input.quoteSheetCode });
|
||||
// 审批通过 ⇒ 事务提交之后再发申请给配送商审核(旁路,失败不影响审批结论)
|
||||
requestDeliveryReviewInBackground(detail?.branch_code, input.quoteSheetCode);
|
||||
return detail;
|
||||
}
|
||||
|
||||
@@ -1250,3 +1249,17 @@ async function archiveQuoteSheetSnapshotForRollover(
|
||||
|
||||
return archiveCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 报价单生效/提交/审批后:**请配送商审核销售价**(A 方向提议),不再直接推对方成本价。
|
||||
* 旁路异步 + 吞异常:传递失败不影响本系统自己的生效动作(对方审核通过后才写他自己的成本价)。
|
||||
*/
|
||||
function requestDeliveryReviewInBackground(branchCode: string | null | undefined, quoteSheetCode: string) {
|
||||
void import('./quoteSheetEditService')
|
||||
.then(({ requestDeliveryReviewForSheet }) =>
|
||||
requestDeliveryReviewForSheet({ quoteSheetCode, branchCode: branchCode || null })
|
||||
)
|
||||
.catch(() => {
|
||||
// 开关关闭 / 主系统不可用 / 无 MAIN_ 客户:都不影响本系统的报价单状态
|
||||
});
|
||||
}
|
||||
|
||||
@@ -556,29 +556,6 @@ async function runSkuMappingSync() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 报价单销售价 → 主系统成本价:**失败行定时重试**(2026-10-18)。
|
||||
*
|
||||
* 口径(冻结):只重试 `status='failed'` 且 `attempts < 5` 的台账行;**复用原 `client_request_id`**
|
||||
* (对方按请求号幂等);`forbidden` / `sent` / `skipped` 永不重试。
|
||||
* 开关 `MAIN_SYSTEM_QUOTE_COST_SYNC` 默认关 ⇒ 函数内部直接返回(零查库、零出站)。
|
||||
* 单行失败只记日志,不中断其它行;本函数自己不抛(不得阻塞同轮其它跨系统任务)。
|
||||
*/
|
||||
async function runQuoteCostSyncReconcile() {
|
||||
try {
|
||||
const { retryQuoteCostSyncPushes } = await import('./mainSystemQuoteCostSync');
|
||||
const summary = await retryQuoteCostSyncPushes({ limit: 20 });
|
||||
if (summary.rows) {
|
||||
console.log(
|
||||
`[scheduler] 报价单成本价同步重试:选中 ${summary.rows} 行,成功 ${summary.sent}、` +
|
||||
`仍失败 ${summary.failed}、对方拒绝(forbidden) ${summary.forbidden}、转跳过 ${summary.skipped}` +
|
||||
`${summary.errors ? `、异常 ${summary.errors}` : ''}`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[scheduler] 报价单成本价同步重试失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 库存抵扣 ⇒ 批次计划兜底(2026-10-12):给"已抵扣但还没有批次计划"的订单补 FIFO 批次。
|
||||
@@ -1098,8 +1075,6 @@ export function startScheduledJobs() {
|
||||
runDeferredUnitResendSweep(),
|
||||
// 批次报告推送对账(开关默认关 ⇒ 直接返回)
|
||||
runReportPushReconcile(),
|
||||
// 报价单销售价 → 主系统成本价:失败行重试(开关默认关 ⇒ 直接返回)
|
||||
runQuoteCostSyncReconcile(),
|
||||
// 报价单双向价格传递:D2 对账 + B 提议拉取 + D3 回执补发(开关默认关 ⇒ 直接返回)
|
||||
runQuotePriceProposalSync(),
|
||||
// SKU 映射:每天拉一次 D5(开关默认关 ⇒ 直接返回;进程内按日期去重)
|
||||
|
||||
@@ -1,999 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 「编辑生效报价单改价 → 待审变更 → 审核通过才应用 + 才同步」—— 服务层契约守卫(2026-10-18 增量)。
|
||||
*
|
||||
* 钉住(brief §3 + Lead 裁定):
|
||||
* ① 价格相关改动**不落报价单**、只写/覆盖 pending 变更单,响应 `applied:false`;
|
||||
* ② 非价格改动(只改标题/周期/生效日/客户)走现有直接保存,`applied:true`;
|
||||
* ③ 开关 `QUOTE_EDIT_APPROVAL` 默认开;`0/false/off` 回滚成直接保存且**不写变更单表**;
|
||||
* ④ 同一 SKU 重复 ⇒ 400 `duplicate_sku`(不去重、不落库);
|
||||
* ⑤ D4:新提交把旧 pending 置 `superseded`,一张单只留一条 pending;
|
||||
* ⑥ 审核通过:**单事务**(BEGIN → 应用 → 记审批 → COMMIT)→ **提交后**才 `triggerQuoteCostSync`;
|
||||
* **绝不**走 `approveQuoteSheet`/`activateQuoteSheet`(不置其它共享单为 3、不动审批字段);
|
||||
* ⑦ base 已变 ⇒ 409 `base_changed` + 变更单置 rejected + 零应用零推送;
|
||||
* ⑧ 驳回 ⇒ 只改状态、报价单不变、零推送;重复决策 ⇒ 409 `already_decided`;
|
||||
* ⑨ 应用前守卫:SKU 存活(`skus.status=1`)、客户归属分公司(真库零外键)。
|
||||
*/
|
||||
|
||||
/* ── mock:DP ────────────────────────────────────────────────────────────── */
|
||||
|
||||
const poolQuery = vi.hoisted(() => vi.fn());
|
||||
const clientQuery = vi.hoisted(() => vi.fn());
|
||||
const clientRelease = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: {
|
||||
query: (...args: unknown[]) => poolQuery(...args),
|
||||
connect: async () => ({
|
||||
query: (...args: unknown[]) => clientQuery(...args),
|
||||
release: () => clientRelease(),
|
||||
}),
|
||||
},
|
||||
getRawPoolQuery: () => poolQuery,
|
||||
}));
|
||||
|
||||
// 报价单服务:只替换「应用/读取/客户校验」,`normalizeQuoteSheetUpdatePayload` 用真实现
|
||||
const applyQuoteSheetUpdate = vi.hoisted(() => vi.fn());
|
||||
const updateQuoteSheet = vi.hoisted(() => vi.fn());
|
||||
const loadQuoteSheetForUpdate = vi.hoisted(() => vi.fn());
|
||||
const getQuoteSheet = vi.hoisted(() => vi.fn());
|
||||
const assertCustomersInBranch = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/quoteSheetService', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/quoteSheetService')>();
|
||||
return {
|
||||
...actual,
|
||||
applyQuoteSheetUpdate: (...args: unknown[]) => applyQuoteSheetUpdate(...args),
|
||||
updateQuoteSheet: (...args: unknown[]) => updateQuoteSheet(...args),
|
||||
loadQuoteSheetForUpdate: (...args: unknown[]) => loadQuoteSheetForUpdate(...args),
|
||||
getQuoteSheet: (...args: unknown[]) => getQuoteSheet(...args),
|
||||
assertCustomersInBranch: (...args: unknown[]) => assertCustomersInBranch(...args),
|
||||
};
|
||||
});
|
||||
|
||||
// 业务审计(A26):断言三条路径各写一条
|
||||
const writeAuditLog = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/auditService', () => ({
|
||||
writeAuditLog: (...args: unknown[]) => writeAuditLog(...args),
|
||||
}));
|
||||
|
||||
// 成本价同步:指纹算法用真实现(base 判据复用同一算法),触发入口 mock
|
||||
const triggerQuoteCostSync = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/mainSystemQuoteCostSync')>();
|
||||
return { ...actual, triggerQuoteCostSync: (...args: unknown[]) => triggerQuoteCostSync(...args) };
|
||||
});
|
||||
|
||||
import {
|
||||
approveQuoteSheetChangeRequest,
|
||||
assertNoDuplicateSku,
|
||||
diffQuoteSheetItems,
|
||||
isPriceRelatedQuoteEdit,
|
||||
isQuoteEditApprovalEnabled,
|
||||
listQuoteSheetChangeRequests,
|
||||
payloadToUpdateInput,
|
||||
quoteSheetItemsFingerprint,
|
||||
rejectQuoteSheetChangeRequest,
|
||||
saveQuoteSheetEdit,
|
||||
} from '../src/services/quoteSheetChangeRequestService';
|
||||
|
||||
/* ── 脚本化 DB(内存台账)──────────────────────────────────────────────── */
|
||||
|
||||
type MockChangeRequest = Record<string, any>;
|
||||
|
||||
type DbState = {
|
||||
sheet: Record<string, any>;
|
||||
items: Array<Record<string, any>>;
|
||||
sheetCustomers: string[];
|
||||
changeRequests: Map<string, MockChangeRequest>;
|
||||
aliveSkus: Set<string>;
|
||||
branchCustomers: Set<string>;
|
||||
events: string[];
|
||||
};
|
||||
|
||||
const SHEET = 'QS1';
|
||||
const BRANCH = 'BR002';
|
||||
|
||||
function seedSheet(overrides: Partial<Record<string, any>> = {}) {
|
||||
return {
|
||||
quote_sheet_code: SHEET,
|
||||
branch_code: BRANCH,
|
||||
title: '报价单 V1',
|
||||
version_no: 1,
|
||||
status: 1,
|
||||
approval_status: 30,
|
||||
approved_by: 'u-approver',
|
||||
approved_at: '2026-10-17T00:00:00.000Z',
|
||||
effective_at: '2026-10-17T00:00:00.000Z',
|
||||
expires_at: new Date(Date.now() + 86400_000).toISOString(),
|
||||
auto_sale_price_by_cost: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeState(overrides: Partial<DbState> = {}): DbState {
|
||||
return {
|
||||
sheet: seedSheet(),
|
||||
items: [
|
||||
{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', sale_price: '10.00', price: '10.00', cost_price: '5.00' },
|
||||
{ sku_code: 'SKU2', sku_name: '鲤鱼', unit: '斤', sale_price: '12.00', price: '12.00', cost_price: '6.00' },
|
||||
],
|
||||
sheetCustomers: ['MAIN_BR002'],
|
||||
changeRequests: new Map(),
|
||||
aliveSkus: new Set(['SKU1', 'SKU2']),
|
||||
branchCustomers: new Set(['MAIN_BR002', 'CUS_A']),
|
||||
events: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function seedChangeRequest(state: DbState, patch: MockChangeRequest = {}): MockChangeRequest {
|
||||
const row: MockChangeRequest = {
|
||||
id: patch.id ?? '11111111-1111-4111-8111-111111111111',
|
||||
branch_code: patch.branch_code ?? BRANCH,
|
||||
quote_sheet_code: patch.quote_sheet_code ?? SHEET,
|
||||
payload: patch.payload ?? { items: [] },
|
||||
base_version_no: patch.base_version_no ?? 1,
|
||||
base_items_fingerprint: patch.base_items_fingerprint ?? quoteSheetItemsFingerprint(state.items),
|
||||
status: patch.status ?? 'pending',
|
||||
requested_by: patch.requested_by ?? 'u-requester',
|
||||
requested_by_name: patch.requested_by_name ?? '提交人甲',
|
||||
requested_at: patch.requested_at ?? '2026-10-18T01:00:00.000Z',
|
||||
reviewed_by: patch.reviewed_by ?? null,
|
||||
reviewed_by_name: patch.reviewed_by_name ?? null,
|
||||
reviewed_at: patch.reviewed_at ?? null,
|
||||
reject_reason: patch.reject_reason ?? null,
|
||||
applied_at: patch.applied_at ?? null,
|
||||
updated_at: patch.updated_at ?? '2026-10-18T01:00:00.000Z',
|
||||
};
|
||||
state.changeRequests.set(row.id, row);
|
||||
return row;
|
||||
}
|
||||
|
||||
function installDb(state: DbState): void {
|
||||
const handler = async (sql: string, params: unknown[] = [], fromClient: boolean) => {
|
||||
const text = String(sql);
|
||||
if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) {
|
||||
if (fromClient) state.events.push(text.trim().toUpperCase());
|
||||
return { rows: [], rowCount: 0 };
|
||||
}
|
||||
// ── 变更单 ──
|
||||
if (text.includes('UPDATE quote_sheet_change_requests') && text.includes("SET status = 'superseded'")) {
|
||||
state.events.push('CR_SUPERSEDE');
|
||||
let count = 0;
|
||||
for (const row of state.changeRequests.values()) {
|
||||
if (row.branch_code === params[0] && row.quote_sheet_code === params[1] && row.status === 'pending') {
|
||||
row.status = 'superseded';
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return { rows: [], rowCount: count };
|
||||
}
|
||||
if (text.includes('INSERT INTO quote_sheet_change_requests')) {
|
||||
state.events.push('CR_INSERT');
|
||||
const id = `11111111-1111-4111-8111-${String(state.changeRequests.size + 1).padStart(12, '0')}`;
|
||||
const row: MockChangeRequest = {
|
||||
id,
|
||||
branch_code: params[0],
|
||||
quote_sheet_code: params[1],
|
||||
payload: JSON.parse(String(params[2])),
|
||||
base_version_no: params[3],
|
||||
base_items_fingerprint: params[4],
|
||||
status: 'pending',
|
||||
requested_by: params[5],
|
||||
requested_by_name: '提交人甲',
|
||||
requested_at: '2026-10-18T02:00:00.000Z',
|
||||
reviewed_by: null,
|
||||
reviewed_by_name: null,
|
||||
reviewed_at: null,
|
||||
reject_reason: null,
|
||||
applied_at: null,
|
||||
updated_at: '2026-10-18T02:00:00.000Z',
|
||||
};
|
||||
state.changeRequests.set(id, row);
|
||||
return { rows: [row], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM quote_sheet_change_requests') && text.includes('FOR UPDATE')) {
|
||||
// 两种锁:① 提交时找旧 pending(按 branch+sheet);② 审批时按 id 锁行
|
||||
if (text.includes('WHERE branch_code = $1 AND quote_sheet_code = $2')) {
|
||||
state.events.push('CR_PREVIOUS_LOCK');
|
||||
const previous = [...state.changeRequests.values()].filter(
|
||||
(row) => row.branch_code === params[0] && row.quote_sheet_code === params[1] && row.status === 'pending'
|
||||
);
|
||||
return { rows: previous.map((row) => ({ id: row.id })), rowCount: previous.length };
|
||||
}
|
||||
state.events.push('CR_LOCK');
|
||||
const row = state.changeRequests.get(String(params[0]));
|
||||
return { rows: row ? [row] : [], rowCount: row ? 1 : 0 };
|
||||
}
|
||||
if (text.includes('SELECT id, branch_code, status FROM quote_sheet_change_requests')) {
|
||||
const row = state.changeRequests.get(String(params[0]));
|
||||
return { rows: row ? [row] : [], rowCount: row ? 1 : 0 };
|
||||
}
|
||||
if (text.includes('UPDATE quote_sheet_change_requests') && text.includes("SET status = 'rejected'")) {
|
||||
const row = state.changeRequests.get(String(params[0]));
|
||||
state.events.push('CR_REJECT');
|
||||
if (!row || row.status !== 'pending') return { rows: [], rowCount: 0 };
|
||||
row.status = 'rejected';
|
||||
row.reviewed_by = params[1] ?? null;
|
||||
row.reviewed_at = '2026-10-18T03:00:00.000Z';
|
||||
row.reject_reason = text.includes("reject_reason = 'base_changed'") ? 'base_changed' : params[2];
|
||||
row.updated_at = '2026-10-18T03:00:00.000Z';
|
||||
return { rows: [row], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('UPDATE quote_sheet_change_requests') && text.includes("SET status = 'approved'")) {
|
||||
const row = state.changeRequests.get(String(params[0]));
|
||||
state.events.push('CR_APPROVED');
|
||||
if (!row || row.status !== 'pending') return { rows: [], rowCount: 0 };
|
||||
row.status = 'approved';
|
||||
row.reviewed_by = params[1] ?? null;
|
||||
row.reviewed_at = '2026-10-18T03:00:00.000Z';
|
||||
row.applied_at = '2026-10-18T03:00:00.000Z';
|
||||
row.updated_at = '2026-10-18T03:00:00.000Z';
|
||||
return { rows: [row], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('FROM quote_sheet_change_requests cr')) {
|
||||
state.events.push('CR_LIST');
|
||||
const status = params[1];
|
||||
const rows = [...state.changeRequests.values()]
|
||||
.filter((row) => row.branch_code === params[0] && row.status === status)
|
||||
.sort((a, b) => String(b.requested_at).localeCompare(String(a.requested_at)));
|
||||
return { rows, rowCount: rows.length };
|
||||
}
|
||||
// ── 报价单明细 / 客户 ──
|
||||
if (text.includes('FROM customer_quote_sheet_items') && text.includes('= ANY($1)')) {
|
||||
return {
|
||||
rows: state.items.map((item) => ({ ...item, quote_sheet_code: SHEET })),
|
||||
rowCount: state.items.length,
|
||||
};
|
||||
}
|
||||
if (text.includes('FROM customer_quote_sheet_items')) {
|
||||
return { rows: state.items, rowCount: state.items.length };
|
||||
}
|
||||
if (text.includes('FROM skus WHERE sku_code = ANY($1) AND status = 1')) {
|
||||
state.events.push('CHECK_SKUS');
|
||||
const codes = (params[0] as string[]) || [];
|
||||
return { rows: codes.filter((code) => state.aliveSkus.has(code)).map((sku_code) => ({ sku_code })) };
|
||||
}
|
||||
if (text.includes('FROM customers WHERE customer_code = ANY($1) AND branch_code = $2')) {
|
||||
state.events.push('CHECK_CUSTOMERS');
|
||||
const codes = (params[0] as string[]) || [];
|
||||
return {
|
||||
rows: codes
|
||||
.filter((code) => state.branchCustomers.has(code))
|
||||
.map((customer_code) => ({ customer_code })),
|
||||
};
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
};
|
||||
|
||||
poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], false));
|
||||
clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], true));
|
||||
}
|
||||
|
||||
const okDetail = () => ({ quote_sheet_code: SHEET, items: [], customers: [] });
|
||||
|
||||
beforeEach(() => {
|
||||
poolQuery.mockReset();
|
||||
clientQuery.mockReset();
|
||||
clientRelease.mockReset();
|
||||
applyQuoteSheetUpdate.mockReset();
|
||||
updateQuoteSheet.mockReset();
|
||||
loadQuoteSheetForUpdate.mockReset();
|
||||
getQuoteSheet.mockReset();
|
||||
assertCustomersInBranch.mockReset();
|
||||
triggerQuoteCostSync.mockReset();
|
||||
writeAuditLog.mockReset();
|
||||
writeAuditLog.mockResolvedValue(undefined);
|
||||
|
||||
delete process.env.QUOTE_EDIT_APPROVAL;
|
||||
loadQuoteSheetForUpdate.mockResolvedValue(seedSheet());
|
||||
getQuoteSheet.mockResolvedValue(okDetail());
|
||||
updateQuoteSheet.mockResolvedValue(okDetail());
|
||||
applyQuoteSheetUpdate.mockImplementation(async () => {
|
||||
// 模拟"应用成功",并记录与事务相关的事件顺序
|
||||
return okDetail();
|
||||
});
|
||||
assertCustomersInBranch.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
/* ── 纯函数 ─────────────────────────────────────────────────────────────── */
|
||||
|
||||
describe('开关(默认开)', () => {
|
||||
it('未设置 / 1 / true / on ⇒ 开;0 / false / off(大小写不敏感)⇒ 关', () => {
|
||||
expect(isQuoteEditApprovalEnabled()).toBe(true);
|
||||
for (const value of ['1', 'true', 'on', 'TRUE']) {
|
||||
process.env.QUOTE_EDIT_APPROVAL = value;
|
||||
expect(isQuoteEditApprovalEnabled(), value).toBe(true);
|
||||
}
|
||||
for (const value of ['0', 'false', 'off', 'OFF', 'Off']) {
|
||||
process.env.QUOTE_EDIT_APPROVAL = value;
|
||||
expect(isQuoteEditApprovalEnabled(), value).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('价格相关性判定(D5)', () => {
|
||||
it('含 items ⇒ 价格相关;只改标题/周期/生效日/客户 ⇒ 不相关', () => {
|
||||
expect(isPriceRelatedQuoteEdit({ items: [] }, { auto_sale_price_by_cost: false })).toBe(true);
|
||||
expect(isPriceRelatedQuoteEdit({ items: [{ sku_code: 'SKU1' }] }, {})).toBe(true);
|
||||
expect(isPriceRelatedQuoteEdit({ title: 'x', customerCodes: ['CUS_A'] }, {})).toBe(false);
|
||||
expect(isPriceRelatedQuoteEdit({}, {})).toBe(false);
|
||||
});
|
||||
|
||||
it('auto_sale_price_by_cost:真的变了才算价格相关', () => {
|
||||
expect(isPriceRelatedQuoteEdit({ autoSalePriceByCost: true }, { auto_sale_price_by_cost: false })).toBe(true);
|
||||
expect(isPriceRelatedQuoteEdit({ autoSalePriceByCost: false }, { auto_sale_price_by_cost: false })).toBe(false);
|
||||
expect(isPriceRelatedQuoteEdit({ autoSalePriceByCost: true }, { auto_sale_price_by_cost: true })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('重复 SKU 闸门(Lead 裁定 #2)', () => {
|
||||
it('重复(trim 后同名)⇒ 抛 400 duplicate_sku;空 sku 行不算', () => {
|
||||
expect(() =>
|
||||
assertNoDuplicateSku([
|
||||
{ sku_code: 'SKU1' },
|
||||
{ sku_code: ' SKU1 ' },
|
||||
{ sku_code: '' },
|
||||
{ sku_code: '' },
|
||||
])
|
||||
).toThrowError(/同一商品重复出现/);
|
||||
try {
|
||||
assertNoDuplicateSku([{ sku_code: 'A' }, { sku_code: 'A' }]);
|
||||
} catch (error: any) {
|
||||
expect(error.status).toBe(400);
|
||||
expect(error.code).toBe('duplicate_sku');
|
||||
}
|
||||
expect(() => assertNoDuplicateSku([{ sku_code: 'A' }, { sku_code: 'B' }])).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('明细指纹 / 摘要(复用成本价同步同一算法)', () => {
|
||||
it('指纹按 sku_code/unit/sale_price 排序后 sha256,与顺序无关', () => {
|
||||
const a = quoteSheetItemsFingerprint([
|
||||
{ sku_code: 'SKU1', unit: '斤', sale_price: '10' },
|
||||
{ sku_code: 'SKU2', unit: '袋', sale_price: '12.5' },
|
||||
]);
|
||||
const b = quoteSheetItemsFingerprint([
|
||||
{ sku_code: 'SKU2', unit: '袋', sale_price: '12.5' },
|
||||
{ sku_code: 'SKU1', unit: '斤', sale_price: '10' },
|
||||
]);
|
||||
expect(a).toBe(b);
|
||||
expect(a).toMatch(/^[0-9a-f]{64}$/);
|
||||
// 价格/单位变化 ⇒ 指纹变化
|
||||
expect(quoteSheetItemsFingerprint([{ sku_code: 'SKU1', unit: '斤', sale_price: '11' }])).not.toBe(
|
||||
quoteSheetItemsFingerprint([{ sku_code: 'SKU1', unit: '斤', sale_price: '10' }])
|
||||
);
|
||||
});
|
||||
|
||||
it('摘要:增/删/改分桶,改前→改后都在,未变不进 lines', () => {
|
||||
const summary = diffQuoteSheetItems(
|
||||
[
|
||||
{ sku_code: 'SKU1', unit: '斤', sale_price: '10.00', cost_price: '5.00' },
|
||||
{ sku_code: 'SKU2', unit: '斤', sale_price: '12.00', cost_price: '6.00' },
|
||||
{ sku_code: 'SKU3', unit: '袋', sale_price: '3.00', cost_price: '1.00' },
|
||||
],
|
||||
[
|
||||
{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', sale_price: '11.00', cost_price: '5.00' },
|
||||
{ sku_code: 'SKU2', unit: '斤', sale_price: '12.00', cost_price: '6.00' },
|
||||
{ sku_code: 'SKU4', unit: '盒', sale_price: '9.00', cost_price: '4.00' },
|
||||
]
|
||||
);
|
||||
expect(summary).toMatchObject({ item_count: 3, added: 1, removed: 1, updated: 1, truncated: false });
|
||||
const byChange = Object.fromEntries(summary.lines.map((line) => [line.change, line]));
|
||||
expect(byChange.updated.before_sale_price).toBe(10);
|
||||
expect(byChange.updated.after_sale_price).toBe(11);
|
||||
expect(byChange.added.sku_code).toBe('SKU4');
|
||||
expect(byChange.removed.sku_code).toBe('SKU3');
|
||||
expect(summary.lines.some((line) => line.sku_code === 'SKU2')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/* ── 提交分流 ───────────────────────────────────────────────────────────── */
|
||||
|
||||
describe('PUT 分流:价格相关 ⇒ 待审;非价格 ⇒ 直接保存', () => {
|
||||
it('价格相关 ⇒ 不落报价单(updateQuoteSheet 不被调用),写 pending 变更单并返回 applied:false', async () => {
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
|
||||
const result = await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }],
|
||||
requestedBy: 'u-requester',
|
||||
});
|
||||
|
||||
expect(result.applied).toBe(false);
|
||||
expect(updateQuoteSheet).not.toHaveBeenCalled();
|
||||
expect(state.events).toContain('CR_INSERT');
|
||||
const created = [...state.changeRequests.values()][0];
|
||||
expect(created.status).toBe('pending');
|
||||
expect(created.branch_code).toBe(BRANCH);
|
||||
expect(created.payload.items).toHaveLength(1);
|
||||
expect(created.payload.items[0]).toMatchObject({ sku_code: 'SKU1', sale_price: 11 });
|
||||
expect(created.base_items_fingerprint).toBe(quoteSheetItemsFingerprint(state.items));
|
||||
if (result.applied === false) {
|
||||
expect(result.changeRequest.status).toBe('pending');
|
||||
expect(result.changeRequest.summary?.updated).toBe(1);
|
||||
}
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('非价格(只改标题/客户)⇒ 直接保存 applied:true,并按 Lead #6 触发一次成本价同步(自带指纹判重)', async () => {
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
|
||||
const result = await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
title: '新标题',
|
||||
customerCodes: ['MAIN_BR002'],
|
||||
});
|
||||
|
||||
expect(result.applied).toBe(true);
|
||||
expect(updateQuoteSheet).toHaveBeenCalledTimes(1);
|
||||
expect(state.events).not.toContain('CR_INSERT');
|
||||
expect(triggerQuoteCostSync).toHaveBeenCalledWith({ branchCode: BRANCH, quoteSheetCode: SHEET });
|
||||
});
|
||||
|
||||
it('价格相关但开关关 ⇒ 直接保存、不写变更单表、不推送(= 改造前)', async () => {
|
||||
process.env.QUOTE_EDIT_APPROVAL = '0';
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
|
||||
const result = await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11 }],
|
||||
});
|
||||
|
||||
expect(result.applied).toBe(true);
|
||||
expect(updateQuoteSheet).toHaveBeenCalledTimes(1);
|
||||
expect(state.events).not.toContain('CR_INSERT');
|
||||
expect(state.changeRequests.size).toBe(0);
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('同一 SKU 重复 ⇒ 400 duplicate_sku,一条变更单都不写', async () => {
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
await expect(
|
||||
saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [
|
||||
{ sku_code: 'SKU1', unit: '斤', sale_price: 11 },
|
||||
{ sku_code: 'SKU1', unit: '斤', sale_price: 12 },
|
||||
],
|
||||
})
|
||||
).rejects.toMatchObject({ status: 400, code: 'duplicate_sku' });
|
||||
expect(state.changeRequests.size).toBe(0);
|
||||
expect(updateQuoteSheet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('D4:二次提交把旧 pending 置 superseded,只留一条 pending', async () => {
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }],
|
||||
});
|
||||
await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 13 }],
|
||||
});
|
||||
const rows = [...state.changeRequests.values()];
|
||||
expect(rows.filter((row) => row.status === 'pending')).toHaveLength(1);
|
||||
expect(rows.filter((row) => row.status === 'superseded')).toHaveLength(1);
|
||||
expect(rows.find((row) => row.status === 'pending')!.payload.items[0].sale_price).toBe(13);
|
||||
});
|
||||
});
|
||||
|
||||
/* ── 审核通过 ───────────────────────────────────────────────────────────── */
|
||||
|
||||
describe('审核通过:单事务应用 + 提交后才推送', () => {
|
||||
const pendingPayload = {
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }],
|
||||
};
|
||||
|
||||
it('事件顺序 BEGIN → 应用 → 记审批 → COMMIT → trigger;且传入同一事务 client', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, { payload: pendingPayload });
|
||||
installDb(state);
|
||||
|
||||
const result = await approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
reviewedBy: 'u-reviewer',
|
||||
});
|
||||
|
||||
expect(applyQuoteSheetUpdate).toHaveBeenCalledTimes(1);
|
||||
const [, options] = applyQuoteSheetUpdate.mock.calls[0] as [any, any];
|
||||
expect(options?.client).toBeTruthy();
|
||||
const applyArg = applyQuoteSheetUpdate.mock.calls[0][0] as any;
|
||||
expect(applyArg.quoteSheetCode).toBe(SHEET);
|
||||
expect(applyArg.items[0]).toMatchObject({ sku_code: 'SKU1', sale_price: 11 });
|
||||
|
||||
const order = state.events.filter((event) =>
|
||||
['BEGIN', 'CR_LOCK', 'CHECK_SKUS', 'CHECK_CUSTOMERS', 'CR_APPROVED', 'COMMIT'].includes(event)
|
||||
);
|
||||
expect(order[0]).toBe('BEGIN');
|
||||
expect(order).toContain('CR_APPROVED');
|
||||
expect(order[order.length - 1]).toBe('COMMIT');
|
||||
// 推送必须在 COMMIT 之后(trigger 在 mock 里不记事件,靠下面的调用顺序断言)
|
||||
expect(triggerQuoteCostSync).toHaveBeenCalledWith({ branchCode: BRANCH, quoteSheetCode: SHEET });
|
||||
expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.status).toBe('approved');
|
||||
expect(result.changeRequest.status).toBe('approved');
|
||||
expect(result.changeRequest.applied_at).toBeTruthy();
|
||||
expect(result.changeRequest.reviewed_by).toBe('u-reviewer');
|
||||
});
|
||||
|
||||
it('推送发生在 COMMIT 之后(用事件顺序钉住)', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, { payload: pendingPayload });
|
||||
installDb(state);
|
||||
triggerQuoteCostSync.mockImplementation(() => {
|
||||
state.events.push('TRIGGER');
|
||||
});
|
||||
await approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
});
|
||||
expect(state.events.indexOf('COMMIT')).toBeLessThan(state.events.indexOf('TRIGGER'));
|
||||
});
|
||||
|
||||
it('base 已变 ⇒ 409 base_changed:变更单置 rejected + 理由,零应用、零推送', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, {
|
||||
payload: pendingPayload,
|
||||
// 提交时指纹:价格 10;随后目标单被改成 10.5
|
||||
base_items_fingerprint: quoteSheetItemsFingerprint(state.items),
|
||||
});
|
||||
state.items = [
|
||||
{ sku_code: 'SKU1', unit: '斤', sale_price: '10.50', price: '10.50', cost_price: '5.00' },
|
||||
];
|
||||
installDb(state);
|
||||
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'base_changed' });
|
||||
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
const row = state.changeRequests.get('11111111-1111-4111-8111-111111111111')!;
|
||||
expect(row.status).toBe('rejected');
|
||||
expect(row.reject_reason).toBe('base_changed');
|
||||
});
|
||||
|
||||
it('SKU 已停用 ⇒ 409 sku_unavailable:零应用、零推送、变更单仍 pending(人工决定驳回)', async () => {
|
||||
const state = makeState({ aliveSkus: new Set(['SKU2']) });
|
||||
seedChangeRequest(state, { payload: pendingPayload });
|
||||
installDb(state);
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'sku_unavailable' });
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.status).toBe('pending');
|
||||
});
|
||||
|
||||
it('客户不属本分公司 ⇒ 409 invalid_customer:零应用、零推送', async () => {
|
||||
const state = makeState({ branchCustomers: new Set(['MAIN_BR002']) });
|
||||
seedChangeRequest(state, {
|
||||
payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }], customer_codes: ['CUS_OTHER'] },
|
||||
});
|
||||
installDb(state);
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'invalid_customer' });
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('重复决策 ⇒ 409 already_decided(不重复应用、不重复推送)', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, { payload: pendingPayload, status: 'approved' });
|
||||
installDb(state);
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'already_decided' });
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('变更单所属分公司与当前 ctx 不符 ⇒ 403 branch_mismatch', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, { payload: pendingPayload, branch_code: 'BR999' });
|
||||
installDb(state);
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 403, code: 'branch_mismatch' });
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('找不到变更单 ⇒ 404', async () => {
|
||||
installDb(makeState());
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '22222222-2222-4222-8222-222222222222',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404, code: 'change_request_not_found' });
|
||||
});
|
||||
});
|
||||
|
||||
/* ── 驳回 / 列表 ────────────────────────────────────────────────────────── */
|
||||
|
||||
describe('审核驳回', () => {
|
||||
it('驳回 ⇒ rejected + 理由,报价单不变、零推送', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, { payload: { items: [] } });
|
||||
installDb(state);
|
||||
const result = await rejectQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
reason: '价格谈不拢',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
reviewedBy: 'u-reviewer',
|
||||
});
|
||||
expect(result.changeRequest.status).toBe('rejected');
|
||||
expect(result.changeRequest.reject_reason).toBe('价格谈不拢');
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
expect(updateQuoteSheet).not.toHaveBeenCalled();
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('驳回必须给理由(400 reject_reason_required)', async () => {
|
||||
installDb(makeState());
|
||||
await expect(
|
||||
rejectQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
reason: ' ',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 400, code: 'reject_reason_required' });
|
||||
});
|
||||
|
||||
it('已处理的变更单再驳回 ⇒ 409 already_decided', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, { status: 'rejected' });
|
||||
installDb(state);
|
||||
await expect(
|
||||
rejectQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
reason: '再驳一次',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'already_decided' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('待审列表', () => {
|
||||
it('返回 pending 行 + 提交人 + 审核摘要(改前 → 改后)', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, {
|
||||
payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }] },
|
||||
});
|
||||
installDb(state);
|
||||
const rows = await listQuoteSheetChangeRequests({ branchCode: BRANCH, status: 'pending' });
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].requested_by_name).toBe('提交人甲');
|
||||
expect(rows[0].summary?.updated).toBe(1);
|
||||
expect(rows[0].summary?.lines[0]).toMatchObject({
|
||||
sku_code: 'SKU1',
|
||||
before_sale_price: 10,
|
||||
after_sale_price: 11,
|
||||
change: 'updated',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/* ── payload 往返 ───────────────────────────────────────────────────────── */
|
||||
|
||||
describe('payload → apply 入参', () => {
|
||||
it('只映射存下来的字段(未提供的不传给 apply)', () => {
|
||||
expect(
|
||||
payloadToUpdateInput({
|
||||
quote_sheet_code: SHEET,
|
||||
payload: { items: [{ sku_code: 'SKU1', sale_price: 11, cost_price: 5 }] },
|
||||
})
|
||||
).toMatchObject({ quoteSheetCode: SHEET, items: [{ sku_code: 'SKU1', sale_price: 11, cost_price: 5 }] });
|
||||
const onlyTitle = payloadToUpdateInput({ quote_sheet_code: SHEET, payload: { title: 'x' } });
|
||||
expect(onlyTitle.customerCodes).toBeUndefined();
|
||||
expect(onlyTitle.items).toBeUndefined();
|
||||
expect(onlyTitle.autoSalePriceByCost).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
/* ── ⑧ verifier 复核后修复:A29 列表 SQL / A26 业务审计 / A12 目标失效映射 ────────────── */
|
||||
|
||||
describe('A29:待审列表必须用 public.profiles(auth.users 没有 full_name/username)', () => {
|
||||
beforeEach(() => {
|
||||
process.env.QUOTE_EDIT_APPROVAL = '1';
|
||||
});
|
||||
|
||||
it('列表 SQL 只 join public.profiles,且不出现 auth.users', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, { payload: { items: [] } });
|
||||
installDb(state);
|
||||
await listQuoteSheetChangeRequests({ branchCode: BRANCH, status: 'pending' });
|
||||
const call = poolQuery.mock.calls.find(([sql]) =>
|
||||
String(sql).includes('FROM quote_sheet_change_requests cr')
|
||||
);
|
||||
expect(call).toBeTruthy();
|
||||
const sql = String(call![0]);
|
||||
expect(sql).toContain('LEFT JOIN public.profiles ru ON ru.id = cr.requested_by');
|
||||
expect(sql).toContain('LEFT JOIN public.profiles vu ON vu.id = cr.reviewed_by');
|
||||
expect(sql).not.toContain('auth.users');
|
||||
});
|
||||
});
|
||||
|
||||
describe('A26:提交 / 通过 / 驳回各一条业务审计(best-effort)', () => {
|
||||
beforeEach(() => {
|
||||
process.env.QUOTE_EDIT_APPROVAL = '1';
|
||||
});
|
||||
|
||||
function auditCalls() {
|
||||
return writeAuditLog.mock.calls.map(([arg]) => arg as any);
|
||||
}
|
||||
|
||||
it('提交(新 pending)⇒ quote_sheet_change_request_submit,记 id / 单号 / (none)→pending / 操作人', async () => {
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
const result = await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }],
|
||||
requestedBy: 'u-requester',
|
||||
ctx: { branchCode: BRANCH, userId: 'u-requester', roles: ['operator'] } as any,
|
||||
});
|
||||
const calls = auditCalls();
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]).toMatchObject({
|
||||
operatorId: 'u-requester',
|
||||
operatorRole: 'operator',
|
||||
operationType: 'quote_sheet_change_request_submit',
|
||||
targetTable: 'quote_sheet_change_requests',
|
||||
branchCode: BRANCH,
|
||||
actionCategory: 'quote_edit_approval',
|
||||
});
|
||||
expect(calls[0].targetId).toBe(result.applied === false ? result.changeRequest.id : '');
|
||||
expect(calls[0].oldValue).toMatchObject({ status: '(none)', quote_sheet_code: SHEET });
|
||||
expect(calls[0].newValue).toMatchObject({ status: 'pending', action: 'submit' });
|
||||
});
|
||||
|
||||
it('覆盖旧 pending ⇒ 审计 oldStatus=pending 且 reason 记被覆盖的变更单 id', async () => {
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
const first = await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }],
|
||||
});
|
||||
writeAuditLog.mockClear();
|
||||
await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 13 }],
|
||||
});
|
||||
const calls = auditCalls();
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].oldValue.status).toBe('pending');
|
||||
expect(String(calls[0].newValue.reason)).toBe(
|
||||
`superseded:${first.applied === false ? first.changeRequest.id : ''}`
|
||||
);
|
||||
});
|
||||
|
||||
it('通过 ⇒ quote_sheet_change_request_approve(pending → approved)', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, {
|
||||
payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }] },
|
||||
});
|
||||
installDb(state);
|
||||
await approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH, userId: 'u-reviewer', roles: ['admin'] } as any,
|
||||
reviewedBy: 'u-reviewer',
|
||||
});
|
||||
const calls = auditCalls();
|
||||
expect(calls.some((arg) => arg.operationType === 'quote_sheet_change_request_approve')).toBe(true);
|
||||
const approveAudit = calls.find((arg) => arg.operationType === 'quote_sheet_change_request_approve');
|
||||
expect(approveAudit).toMatchObject({
|
||||
operatorId: 'u-reviewer',
|
||||
operatorRole: 'admin',
|
||||
targetId: '11111111-1111-4111-8111-111111111111',
|
||||
branchCode: BRANCH,
|
||||
});
|
||||
expect(approveAudit.oldValue).toMatchObject({ status: 'pending', quote_sheet_code: SHEET });
|
||||
expect(approveAudit.newValue).toMatchObject({ status: 'approved', action: 'approve' });
|
||||
});
|
||||
|
||||
it('驳回 ⇒ quote_sheet_change_request_reject(带理由)', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, { payload: { items: [] } });
|
||||
installDb(state);
|
||||
await rejectQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
reason: '价格谈不拢',
|
||||
ctx: { branchCode: BRANCH, userId: 'u-reviewer', roles: ['admin'] } as any,
|
||||
reviewedBy: 'u-reviewer',
|
||||
});
|
||||
const calls = auditCalls();
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]).toMatchObject({
|
||||
operationType: 'quote_sheet_change_request_reject',
|
||||
targetId: '11111111-1111-4111-8111-111111111111',
|
||||
});
|
||||
expect(calls[0].newValue).toMatchObject({ status: 'rejected', action: 'reject', reason: '价格谈不拢' });
|
||||
});
|
||||
|
||||
it('base_changed 自动驳回也留 reject 审计(理由 base_changed)', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, {
|
||||
payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }] },
|
||||
base_items_fingerprint: quoteSheetItemsFingerprint(state.items),
|
||||
});
|
||||
state.items = [{ sku_code: 'SKU1', unit: '斤', sale_price: '10.50', price: '10.50', cost_price: '5.00' }];
|
||||
installDb(state);
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH, userId: 'u-reviewer', roles: ['admin'] } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'base_changed' });
|
||||
const calls = auditCalls();
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]).toMatchObject({ operationType: 'quote_sheet_change_request_reject' });
|
||||
expect(calls[0].newValue).toMatchObject({ status: 'rejected', reason: 'base_changed' });
|
||||
});
|
||||
|
||||
it('审计失败不得影响主流程(writeAuditLog 抛错时提交/通过仍成功)', async () => {
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
writeAuditLog.mockRejectedValueOnce(new Error('audit down'));
|
||||
const submit = await saveQuoteSheetEdit({
|
||||
quoteSheetCode: SHEET,
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }],
|
||||
});
|
||||
expect(submit.applied).toBe(false);
|
||||
|
||||
seedChangeRequest(state, {
|
||||
payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }] },
|
||||
});
|
||||
writeAuditLog.mockRejectedValueOnce(new Error('audit down'));
|
||||
const approved = await approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
});
|
||||
expect(approved.changeRequest.status).toBe('approved');
|
||||
});
|
||||
});
|
||||
|
||||
describe('A12(修订):审批时目标单不可用 ⇒ 409 target_unavailable,变更单保持 pending', () => {
|
||||
beforeEach(() => {
|
||||
process.env.QUOTE_EDIT_APPROVAL = '1';
|
||||
});
|
||||
|
||||
it.each([
|
||||
['报价单不存在', '报价单不存在'],
|
||||
['仅执行中的报价单可修改', '仅执行中的报价单可修改'],
|
||||
['报价单已过期,无法修改', '报价单已过期,无法修改'],
|
||||
])('目标单「%s」⇒ 409 target_unavailable(不改编辑路径的抛错语义)', async (_label, message) => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, {
|
||||
payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }] },
|
||||
});
|
||||
installDb(state);
|
||||
loadQuoteSheetForUpdate.mockRejectedValueOnce(new Error(message));
|
||||
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'target_unavailable', message });
|
||||
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.status).toBe('pending');
|
||||
});
|
||||
|
||||
it('目标单失效是「审批路径映射」:编辑路径仍抛普通 Error(无 status/code)', async () => {
|
||||
const state = makeState();
|
||||
installDb(state);
|
||||
loadQuoteSheetForUpdate.mockRejectedValueOnce(new Error('仅执行中的报价单可修改'));
|
||||
await expect(
|
||||
saveQuoteSheetEdit({ quoteSheetCode: SHEET, items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }] })
|
||||
).rejects.toMatchObject({ message: '仅执行中的报价单可修改' });
|
||||
});
|
||||
});
|
||||
|
||||
/* ── ⑨ 红队第三轮 P3-1:目标单硬删时的校验顺序(可用性必须先于指纹)────────────── */
|
||||
|
||||
describe('P3-1:目标单「硬删」⇒ 409 target_unavailable + 变更单保持 pending(不回退成 base_changed)', () => {
|
||||
beforeEach(() => {
|
||||
process.env.QUOTE_EDIT_APPROVAL = '1';
|
||||
});
|
||||
|
||||
const payload = {
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }],
|
||||
};
|
||||
|
||||
it('目标单被硬删(明细也空了 ⇒ 旧代码会误判指纹不一致)⇒ 409 target_unavailable,零应用/零推送/零台账,变更单 pending', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, {
|
||||
payload,
|
||||
// 提交时指纹来自"当时存在的明细"
|
||||
base_items_fingerprint: quoteSheetItemsFingerprint(state.items),
|
||||
});
|
||||
// 硬删:报价单与明细一起消失(真库无外键 ⇒ 明细可能是空集,也可能残留孤儿行;两种都试)
|
||||
state.items = [];
|
||||
installDb(state);
|
||||
loadQuoteSheetForUpdate.mockRejectedValueOnce(new Error('报价单不存在'));
|
||||
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'target_unavailable', message: '报价单不存在' });
|
||||
|
||||
// 关键:**不得**走 base_changed 的自动驳回分支
|
||||
expect(state.events).not.toContain('CR_REJECT');
|
||||
expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.status).toBe('pending');
|
||||
expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.reject_reason).toBeNull();
|
||||
// 零应用 / 零推送 / 零台账(pushOneBranch 都没机会跑)
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
expect(poolQuery.mock.calls.some(([sql]) => String(sql).includes('INSERT INTO public.main_system_quote_cost_pushes'))).toBe(false);
|
||||
});
|
||||
|
||||
it('防回退:目标**仍可用**但指纹变了 ⇒ 仍然 409 base_changed + 自动 rejected(不许改成 pending)', async () => {
|
||||
const state = makeState();
|
||||
seedChangeRequest(state, {
|
||||
payload,
|
||||
base_items_fingerprint: quoteSheetItemsFingerprint(state.items),
|
||||
});
|
||||
state.items = [{ sku_code: 'SKU1', unit: '斤', sale_price: '10.50', price: '10.50', cost_price: '5.00' }];
|
||||
installDb(state);
|
||||
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'base_changed' });
|
||||
|
||||
expect(state.events).toContain('CR_REJECT');
|
||||
const row = state.changeRequests.get('11111111-1111-4111-8111-111111111111')!;
|
||||
expect(row.status).toBe('rejected');
|
||||
expect(row.reject_reason).toBe('base_changed');
|
||||
expect(applyQuoteSheetUpdate).not.toHaveBeenCalled();
|
||||
expect(triggerQuoteCostSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('顺序断言:目标不可用时连指纹查询都不该发生(先可用性、后指纹)', async () => {
|
||||
const state = makeState({ items: [] });
|
||||
seedChangeRequest(state, { payload, base_items_fingerprint: 'stale-fp' });
|
||||
installDb(state);
|
||||
loadQuoteSheetForUpdate.mockRejectedValueOnce(new Error('仅执行中的报价单可修改'));
|
||||
|
||||
await expect(
|
||||
approveQuoteSheetChangeRequest({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ctx: { branchCode: BRANCH } as any,
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, code: 'target_unavailable' });
|
||||
|
||||
// 指纹查询 = `SELECT sku_code, unit, sale_price, price FROM customer_quote_sheet_items`
|
||||
const fingerprintQueries = poolQuery.mock.calls
|
||||
.concat(clientQuery.mock.calls)
|
||||
.filter(([sql]) => String(sql).includes('SELECT sku_code, unit, sale_price, price FROM customer_quote_sheet_items'));
|
||||
expect(fingerprintQueries).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,341 +0,0 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 「待审改价」列��**真库**验证(默认跳过;`QUOTE_EDIT_APPROVAL_DB_TEST=1` 才跑)。
|
||||
*
|
||||
* 为什么必须有这一份(verifier A29 阻断项的回归):列表 SQL 曾写成
|
||||
* `LEFT JOIN auth.users ru ... ru.full_name`,而 **`auth.users` 没有 `full_name`/`username`**
|
||||
* (展示名在 `public.profiles`)⇒ 真库上 `GET /quote/change-requests` 直接 500,前端面板加载不出来。
|
||||
* 单测里 DB 是脚本化 mock,**永远发现不了这种"列不存在"** —— 所以这里连真 Postgres。
|
||||
*
|
||||
* 覆盖:
|
||||
* ① 前提复现:`auth.users` 确实没有那两列(旧写法必炸,防止有人改回去);
|
||||
* ② 列表走 `public.profiles`:`requested_by_name` / `reviewed_by_name` **非空**;
|
||||
* ③ pending 行带审核摘要(items 比对);
|
||||
* ④ 按 `branch_code` 过滤(别的分公司 code 取不到这批测试行)。
|
||||
*
|
||||
* 纪律:只碰本地 `supplier_delivery` 的 `tenant_br002.quote_sheet_change_requests`,
|
||||
* 且只碰 `quote_sheet_code LIKE 'QS_TESTQCR_%'` 的临时行,跑完删干净。
|
||||
*
|
||||
* 跑法(本地):
|
||||
* cd server && QUOTE_EDIT_APPROVAL_DB_TEST=1 npx vitest run tests/quoteSheetChangeRequestDb.integration.test.ts
|
||||
*/
|
||||
|
||||
const RUN = process.env.QUOTE_EDIT_APPROVAL_DB_TEST === '1';
|
||||
const BRANCH = 'BR002';
|
||||
const SCHEMA = 'tenant_br002';
|
||||
const OTHER_BRANCH = 'BR_TESTQCR_OTHER';
|
||||
const SHEET_APPROVED = 'QS_TESTQCR_APPROVED';
|
||||
const SHEET_PENDING = 'QS_TESTQCR_PENDING';
|
||||
const SHEET_FALLBACK = 'QS_TESTQCR_FALLBACK';
|
||||
const SHEET_SUMMARY = 'QS_TESTQCR_SUMMARY';
|
||||
|
||||
// 默认(未设开关)连 src/db 都不加载,保证常规套件不受影响
|
||||
const real = RUN
|
||||
? {
|
||||
db: await import('../src/db'),
|
||||
tenant: await import('../src/services/tenantDbContext'),
|
||||
service: await import('../src/services/quoteSheetChangeRequestService'),
|
||||
}
|
||||
: null;
|
||||
|
||||
const pool = () => real!.db.pool;
|
||||
|
||||
let profileA: { id: string; name: string } = { id: '', name: '' };
|
||||
let profileB: { id: string; name: string } = { id: '', name: '' };
|
||||
let realSheetCode = SHEET_FALLBACK;
|
||||
|
||||
async function cleanup() {
|
||||
// marker 兜住全部本次插入行(含当初误用真实单号插的那条),前缀是双保险
|
||||
await pool().query(
|
||||
`DELETE FROM ${SCHEMA}.quote_sheet_change_requests
|
||||
WHERE base_items_fingerprint = 'fp-test-integration' OR quote_sheet_code LIKE 'QS_TESTQCR_%'`
|
||||
);
|
||||
// P3-1 临时报价单(正常用例会先删;失败时兜底)
|
||||
await pool().query(
|
||||
`DELETE FROM ${SCHEMA}.customer_quote_sheet_items WHERE quote_sheet_code LIKE 'QS_TESTQCR_%'`
|
||||
).catch(() => undefined);
|
||||
await pool().query(
|
||||
`DELETE FROM ${SCHEMA}.customer_quote_sheets WHERE quote_sheet_code LIKE 'QS_TESTQCR_%'`
|
||||
).catch(() => undefined);
|
||||
// A26 审计行:本次测试的驳回审计(按 target_table + 目标单号兜底清理)
|
||||
await pool().query(
|
||||
`DELETE FROM ${SCHEMA}.operation_logs
|
||||
WHERE target_table = 'quote_sheet_change_requests'
|
||||
AND target_id IN (
|
||||
SELECT id::text FROM ${SCHEMA}.quote_sheet_change_requests WHERE quote_sheet_code LIKE 'QS_TESTQCR_%'
|
||||
)`
|
||||
).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** 在租户上下文里插临时行(未限定 schema ⇒ 命中 tenant_br002) */
|
||||
async function insertChangeRequest(input: {
|
||||
sheetCode: string;
|
||||
status: 'pending' | 'approved';
|
||||
requestedBy: string;
|
||||
reviewedBy: string | null;
|
||||
payload: Record<string, unknown>;
|
||||
}) {
|
||||
return real!.tenant.runWithTenantDbContext(BRANCH, async () => {
|
||||
const result = await pool().query<{ id: string }>(
|
||||
`INSERT INTO quote_sheet_change_requests
|
||||
(branch_code, quote_sheet_code, payload, base_version_no, base_items_fingerprint,
|
||||
status, requested_by, requested_at, reviewed_by, reviewed_at, applied_at, updated_at)
|
||||
VALUES ($1, $2, $3::jsonb, 1, 'fp-test-integration', $4,
|
||||
$5::uuid, NOW() - INTERVAL '1 hour', $6::uuid, NOW() - INTERVAL '30 minutes', NOW(), NOW())
|
||||
RETURNING id::text AS id`,
|
||||
[
|
||||
BRANCH,
|
||||
input.sheetCode,
|
||||
JSON.stringify(input.payload),
|
||||
input.status,
|
||||
input.requestedBy,
|
||||
input.reviewedBy,
|
||||
]
|
||||
);
|
||||
return String(result.rows[0].id);
|
||||
});
|
||||
}
|
||||
|
||||
describe.skipIf(!RUN)('待审改价列表 · 真库(A29 回归)', () => {
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
const profiles = await pool().query<{ id: string; name: string }>(
|
||||
`SELECT id::text AS id,
|
||||
COALESCE(NULLIF(TRIM(full_name), ''), NULLIF(TRIM(username), '')) AS name
|
||||
FROM public.profiles
|
||||
ORDER BY id
|
||||
LIMIT 2`
|
||||
);
|
||||
expect(profiles.rows.length, '需要至少 2 个 public.profiles 用户').toBeGreaterThanOrEqual(2);
|
||||
profileA = profiles.rows[0];
|
||||
profileB = profiles.rows[1];
|
||||
|
||||
const sheet = await pool().query<{ quote_sheet_code: string }>(
|
||||
`SELECT quote_sheet_code FROM ${SCHEMA}.customer_quote_sheets
|
||||
WHERE status = 1 AND approval_status = 30
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1`
|
||||
);
|
||||
realSheetCode = sheet.rows[0]?.quote_sheet_code || SHEET_FALLBACK;
|
||||
|
||||
await insertChangeRequest({
|
||||
sheetCode: SHEET_APPROVED,
|
||||
status: 'approved',
|
||||
requestedBy: profileA.id,
|
||||
reviewedBy: profileB.id,
|
||||
payload: { title: '改标题', items: [{ sku_code: 'SKU_TESTQCR_1', unit: '斤', sale_price: 11 }] },
|
||||
});
|
||||
await insertChangeRequest({
|
||||
sheetCode: SHEET_PENDING,
|
||||
status: 'pending',
|
||||
requestedBy: profileA.id,
|
||||
reviewedBy: null,
|
||||
payload: {
|
||||
items: [
|
||||
{ sku_code: 'SKU_TESTQCR_1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 },
|
||||
{ sku_code: 'SKU_TESTQCR_2', unit: '袋', sale_price: 20, price: 20, cost_price: 9 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await pool().end();
|
||||
});
|
||||
|
||||
it('前提复现:auth.users 没有 full_name / username(旧写法必炸 42703)', async () => {
|
||||
const columns = await pool().query<{ column_name: string }>(
|
||||
`SELECT column_name FROM information_schema.columns
|
||||
WHERE table_schema = 'auth' AND table_name = 'users'`
|
||||
);
|
||||
const names = columns.rows.map((row) => String(row.column_name));
|
||||
expect(names).not.toContain('full_name');
|
||||
expect(names).not.toContain('username');
|
||||
// 直接证伪旧 SQL:走 auth.users 取 full_name 必然报错(这就是 500 的来源)
|
||||
await expect(
|
||||
pool().query(`SELECT ru.full_name FROM auth.users ru LIMIT 1`)
|
||||
).rejects.toThrow(/full_name/);
|
||||
});
|
||||
|
||||
it('GET 列表(approved):requested_by_name / reviewed_by_name 都非空,且带回 payload', async () => {
|
||||
const rows = await real!.tenant.runWithTenantDbContext(BRANCH, () =>
|
||||
real!.service.listQuoteSheetChangeRequests({ branchCode: BRANCH, status: 'approved' })
|
||||
);
|
||||
const row = rows.find((item) => item.quote_sheet_code === SHEET_APPROVED);
|
||||
expect(row, 'approved 临时行应出现在列表里').toBeTruthy();
|
||||
expect(row!.requested_by_name).toBe(profileA.name);
|
||||
expect(row!.reviewed_by_name).toBe(profileB.name);
|
||||
expect(row!.requested_by_name && row!.requested_by_name.length).toBeGreaterThan(0);
|
||||
expect(row!.reviewed_by_name && row!.reviewed_by_name.length).toBeGreaterThan(0);
|
||||
expect(row!.payload.title).toBe('改标题');
|
||||
expect(row!.applied_at).toBeTruthy();
|
||||
});
|
||||
|
||||
it('GET 列表(pending):提交人非空 + 审核摘要(真库行上算得出来)', async () => {
|
||||
// ⚠️ 用**独立测试单号**建 pending:绝不在真实报价单号上建 pending ——
|
||||
// ① 会污染真实单的待审列表;② partial unique 让重复跑第二次直接 23505(踩过)。
|
||||
await insertChangeRequest({
|
||||
sheetCode: SHEET_SUMMARY,
|
||||
status: 'pending',
|
||||
requestedBy: profileA.id,
|
||||
reviewedBy: null,
|
||||
payload: {
|
||||
items: [
|
||||
{ sku_code: 'SKU_TESTQCR_1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 },
|
||||
{ sku_code: 'SKU_TESTQCR_2', unit: '袋', sale_price: 20, price: 20, cost_price: 9 },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const rows = await real!.tenant.runWithTenantDbContext(BRANCH, () =>
|
||||
real!.service.listQuoteSheetChangeRequests({ branchCode: BRANCH, status: 'pending' })
|
||||
);
|
||||
const row = rows.find((item) => item.quote_sheet_code === SHEET_SUMMARY);
|
||||
expect(row).toBeTruthy();
|
||||
expect(row!.requested_by_name).toBe(profileA.name);
|
||||
expect(row!.summary?.items_provided).toBe(true);
|
||||
expect(row!.summary?.item_count).toBe(2);
|
||||
expect(Array.isArray(row!.summary?.lines)).toBe(true);
|
||||
expect(row!.summary!.lines.length).toBe(2);
|
||||
// 该测试单号在库里没有明细 ⇒ 两行都是"新增"(改前为 null、改后有值)
|
||||
for (const line of row!.summary!.lines) {
|
||||
expect(line.change).toBe('added');
|
||||
expect(line.before_sale_price).toBeNull();
|
||||
expect(line.after_sale_price).not.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('A26 驳回路径:真库真的写入 operation_logs(四要素),失败不影响主流程', async () => {
|
||||
const sheetCode = 'QS_TESTQCR_AUDIT';
|
||||
const changeRequestId = await insertChangeRequest({
|
||||
sheetCode,
|
||||
status: 'pending',
|
||||
requestedBy: profileA.id,
|
||||
reviewedBy: null,
|
||||
payload: { items: [] },
|
||||
});
|
||||
|
||||
await real!.tenant.runWithTenantDbContext(BRANCH, () =>
|
||||
real!.service.rejectQuoteSheetChangeRequest({
|
||||
id: changeRequestId,
|
||||
reason: '集成测试驳回',
|
||||
ctx: { branchCode: BRANCH, userId: profileB.id, roles: ['admin'] } as any,
|
||||
reviewedBy: profileB.id,
|
||||
})
|
||||
);
|
||||
|
||||
const audit = await pool().query<{
|
||||
operator_id: string;
|
||||
operation_type: string;
|
||||
target_table: string;
|
||||
target_id: string;
|
||||
branch_code: string;
|
||||
new_value: any;
|
||||
}>(
|
||||
`SELECT operator_id::text AS operator_id, operation_type, target_table, target_id::text AS target_id,
|
||||
branch_code, new_value
|
||||
FROM ${SCHEMA}.operation_logs
|
||||
WHERE target_table = 'quote_sheet_change_requests' AND target_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 5`,
|
||||
[changeRequestId]
|
||||
);
|
||||
const row = audit.rows.find((item) => item.operation_type === 'quote_sheet_change_request_reject');
|
||||
expect(row, '驳回必须留下 operation_logs 业务审计').toBeTruthy();
|
||||
expect(row!.operator_id).toBe(profileB.id);
|
||||
expect(row!.branch_code).toBe(BRANCH);
|
||||
expect(row!.new_value).toMatchObject({ status: 'rejected', action: 'reject', reason: '集成测试驳回' });
|
||||
|
||||
// 清理本用例的审计行(不留测试噪声)
|
||||
await pool().query(
|
||||
`DELETE FROM ${SCHEMA}.operation_logs WHERE target_table = 'quote_sheet_change_requests' AND target_id = $1`,
|
||||
[changeRequestId]
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* 红队第三轮 P3-1 真库复现:**目标单被硬删除**(单 + 明细都不在了)。
|
||||
* 旧实现先比指纹 ⇒ 空集让指纹"必然不一致" ⇒ 误走 `base_changed` 自动驳回;正确行为是
|
||||
* 409 `target_unavailable` + 变更单保持 pending + 零应用、零推送、零台账。
|
||||
*/
|
||||
it('P3-1 真库:目标单被硬删 ⇒ 409 target_unavailable + 变更单 pending + 零推送/零台账', async () => {
|
||||
const code = 'QS_TESTQCR_HARDDEL';
|
||||
await real!.tenant.runWithTenantDbContext(BRANCH, async () => {
|
||||
await pool().query(
|
||||
`INSERT INTO customer_quote_sheets
|
||||
(quote_sheet_code, title, version_no, quote_cycle, effective_at, status, approval_status, branch_code, created_at, updated_at)
|
||||
VALUES ($1, '硬删测试单', 1, 'month', NOW(), 1, 30, $2, NOW(), NOW())`,
|
||||
[code, BRANCH]
|
||||
);
|
||||
await pool().query(
|
||||
`INSERT INTO customer_quote_sheet_items
|
||||
(quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order)
|
||||
VALUES ($1, 'SKU_TESTQCR_HARD', '硬删商品', '斤', 10, 5, 10, 0)`,
|
||||
[code]
|
||||
);
|
||||
});
|
||||
const changeRequestId = await insertChangeRequest({
|
||||
sheetCode: code,
|
||||
status: 'pending',
|
||||
requestedBy: profileA.id,
|
||||
reviewedBy: null,
|
||||
payload: {
|
||||
items: [{ sku_code: 'SKU_TESTQCR_HARD', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }],
|
||||
},
|
||||
});
|
||||
// 提交时指纹 = 当时明细(硬删前)
|
||||
const submittedFingerprint = real!.service.quoteSheetItemsFingerprint([
|
||||
{ sku_code: 'SKU_TESTQCR_HARD', unit: '斤', sale_price: 10 },
|
||||
]);
|
||||
await pool().query(
|
||||
`UPDATE ${SCHEMA}.quote_sheet_change_requests SET base_items_fingerprint = $2 WHERE id = $1::uuid`,
|
||||
[changeRequestId, submittedFingerprint]
|
||||
);
|
||||
|
||||
// 硬删:报价单 + 明细一起消失(不经软删)
|
||||
await real!.tenant.runWithTenantDbContext(BRANCH, async () => {
|
||||
await pool().query(`DELETE FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [code]);
|
||||
await pool().query(`DELETE FROM customer_quote_sheets WHERE quote_sheet_code = $1`, [code]);
|
||||
});
|
||||
|
||||
await expect(
|
||||
real!.tenant.runWithTenantDbContext(BRANCH, () =>
|
||||
real!.service.approveQuoteSheetChangeRequest({
|
||||
id: changeRequestId,
|
||||
ctx: { branchCode: BRANCH, userId: profileB.id, roles: ['admin'] } as any,
|
||||
reviewedBy: profileB.id,
|
||||
})
|
||||
)
|
||||
).rejects.toMatchObject({ status: 409, code: 'target_unavailable', message: '报价单不存在' });
|
||||
|
||||
const cr = await pool().query<{ status: string; reject_reason: string | null }>(
|
||||
`SELECT status, reject_reason FROM ${SCHEMA}.quote_sheet_change_requests WHERE id = $1::uuid`,
|
||||
[changeRequestId]
|
||||
);
|
||||
expect(cr.rows[0].status, '变更单必须保持 pending(不能自动 rejected)').toBe('pending');
|
||||
expect(cr.rows[0].reject_reason).toBeNull();
|
||||
|
||||
const ledger = await pool().query<{ n: number }>(
|
||||
`SELECT count(*)::int AS n FROM public.main_system_quote_cost_pushes WHERE quote_sheet_code = $1`,
|
||||
[code]
|
||||
);
|
||||
expect(Number(ledger.rows[0].n), '零推送(台账不得出现该单的分公司行)').toBe(0);
|
||||
|
||||
const sheet = await pool().query(
|
||||
`SELECT 1 FROM ${SCHEMA}.customer_quote_sheets WHERE quote_sheet_code = $1`,
|
||||
[code]
|
||||
);
|
||||
expect(sheet.rows).toHaveLength(0); // 报价单没被"复活"
|
||||
|
||||
await pool().query(`DELETE FROM ${SCHEMA}.quote_sheet_change_requests WHERE id = $1::uuid`, [changeRequestId]);
|
||||
});
|
||||
|
||||
it('按 branch_code 过滤:别的分公司 code 取不到这批测试行', async () => {
|
||||
const rows = await real!.tenant.runWithTenantDbContext(BRANCH, () =>
|
||||
real!.service.listQuoteSheetChangeRequests({ branchCode: OTHER_BRANCH, status: 'pending' })
|
||||
);
|
||||
expect(rows).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,282 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 报价单**生效之后**的推送接线(`quoteSheetService.ts` 三处 `activateQuoteSheet` 调用点)。
|
||||
*
|
||||
* 钉住四条纪律(做反就要返工):
|
||||
* ① 出网必须在 `COMMIT` **之后**(HTTP 永远不在数据库事务里);
|
||||
* ② 推送失败(对方 403 / 5xx / 网络抛错)**不得**让审批/建单失败;
|
||||
* ③ 开关默认关 ⇒ 零出站、零台账写入;
|
||||
* ④ 推送的 body 来自该单明细(`sku_code` / `unit` / `sale_price`),请求号取自台账那行。
|
||||
*/
|
||||
|
||||
/* ── mock:DB(脚本化 fake client)────────────────────────────────────────── */
|
||||
|
||||
const poolQuery = vi.hoisted(() => vi.fn());
|
||||
const clientQuery = vi.hoisted(() => vi.fn());
|
||||
const clientRelease = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: {
|
||||
query: (...args: unknown[]) => poolQuery(...args),
|
||||
connect: async () => ({
|
||||
query: (...args: unknown[]) => clientQuery(...args),
|
||||
release: () => clientRelease(),
|
||||
}),
|
||||
},
|
||||
getRawPoolQuery: () => poolQuery,
|
||||
}));
|
||||
|
||||
// 旁路任务自带租户上下文(本测试不需要真 schema,直接执行回调)
|
||||
vi.mock('../src/services/tenantDbContext', () => ({
|
||||
runWithTenantDbContext: async (_code: string, fn: () => Promise<unknown>) => fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/mainSystem/token', () => ({
|
||||
getMainSystemToken: async () => ({
|
||||
kind: 'ok',
|
||||
token: 'tok-1',
|
||||
branchCode: 'BR002',
|
||||
expiresAt: Date.now() + 60_000,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/mainSystem/config', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/mainSystem/config')>();
|
||||
return {
|
||||
...actual,
|
||||
isMainSystemIntegrationEnabled: () => true,
|
||||
mainSystemBaseUrl: () => 'http://main-system.example',
|
||||
};
|
||||
});
|
||||
|
||||
const fetchMock = vi.hoisted(() => vi.fn());
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
import { approveQuoteSheet, createQuoteSheet } from '../src/services/quoteSheetService';
|
||||
|
||||
/** 事件顺序:BEGIN / COMMIT / LEDGER_* / FETCH 都记在这里 */
|
||||
const events: string[] = [];
|
||||
|
||||
function activeSheet() {
|
||||
return {
|
||||
quote_sheet_code: 'QS1',
|
||||
branch_code: 'BR002',
|
||||
title: '报价单 V1',
|
||||
version_no: 1,
|
||||
status: 1,
|
||||
approval_status: 30,
|
||||
approved_at: '2026-10-18T01:00:00.000Z',
|
||||
effective_at: '2026-10-18T01:00:00.000Z',
|
||||
expires_at: new Date(Date.now() + 86400_000).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function ledgerInsertParams(): unknown[] | null {
|
||||
const call = poolQuery.mock.calls.find(([sql]) => String(sql).includes('RETURNING id::text AS id'));
|
||||
return call ? (call[1] as unknown[]) : null;
|
||||
}
|
||||
|
||||
function setupDb(): void {
|
||||
events.length = 0;
|
||||
poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
|
||||
if (String(sql).includes('RETURNING id::text AS id')) {
|
||||
events.push('LEDGER_INSERT');
|
||||
return { rows: [{ id: 'lid-1', client_request_id: params[3] }], rowCount: 1 };
|
||||
}
|
||||
if (String(sql).includes('UPDATE public.main_system_quote_cost_pushes')) {
|
||||
events.push(`LEDGER_${String(params[1])}`);
|
||||
return { rows: [], rowCount: 1 };
|
||||
}
|
||||
if (String(sql).includes('AS code')) return { rows: [{ code: 'SUP37831443' }] };
|
||||
if (String(sql).includes('SELECT quote_sheet_code, branch_code, status, approval_status')) {
|
||||
return { rows: [activeSheet()] };
|
||||
}
|
||||
if (String(sql).includes('ORDER BY customer_code ASC')) {
|
||||
return { rows: [{ customer_code: 'MAIN_BR002' }] };
|
||||
}
|
||||
if (String(sql).includes('FROM customer_quote_sheet_items') && String(sql).includes('sale_price')) {
|
||||
return { rows: [{ sku_code: 'SKU1', unit: '斤', sale_price: '8.80', price: '8.80' }] };
|
||||
}
|
||||
if (String(sql).includes('SELECT * FROM customer_quote_sheets')) return { rows: [activeSheet()] };
|
||||
if (String(sql).includes('RETURNING quote_sheet_code')) {
|
||||
return { rows: [{ quote_sheet_code: 'QS1' }], rowCount: 1 };
|
||||
}
|
||||
if (String(sql).includes('SELECT quote_sheet_code FROM customer_quote_sheets')) {
|
||||
return { rows: [{ quote_sheet_code: 'QS1' }] };
|
||||
}
|
||||
if (String(sql).includes('FROM customers WHERE customer_code = ANY')) {
|
||||
const codes = (params[0] as string[]) || [];
|
||||
return { rows: codes.map((customer_code) => ({ customer_code })) };
|
||||
}
|
||||
// loadSheetDetail 的 items/customers(带 sort_order / JOIN customers 的两种)
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
clientQuery.mockImplementation(async (sql: string) => {
|
||||
const text = String(sql).trim().toUpperCase();
|
||||
if (text === 'BEGIN') {
|
||||
events.push('BEGIN');
|
||||
return { rows: [] };
|
||||
}
|
||||
if (text === 'COMMIT') {
|
||||
events.push('COMMIT');
|
||||
return { rows: [] };
|
||||
}
|
||||
if (text === 'ROLLBACK') {
|
||||
events.push('ROLLBACK');
|
||||
return { rows: [] };
|
||||
}
|
||||
if (String(sql).includes('UPDATE customer_quote_sheets') && String(sql).includes('RETURNING *')) {
|
||||
return { rows: [activeSheet()] };
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
}
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return { ok: status >= 200 && status < 300, status, json: async () => body };
|
||||
}
|
||||
|
||||
const OK_PAYLOAD = {
|
||||
success: true,
|
||||
data: {
|
||||
client_request_id: 'x',
|
||||
replayed: false,
|
||||
main_branch_code: 'BR002',
|
||||
updated: 1,
|
||||
sheets: ['QS-THEIR'],
|
||||
skipped: [],
|
||||
warnings: [],
|
||||
},
|
||||
};
|
||||
|
||||
async function waitFor(check: () => void, timeoutMs = 2000): Promise<void> {
|
||||
const started = Date.now();
|
||||
while (Date.now() - started < timeoutMs) {
|
||||
try {
|
||||
check();
|
||||
return;
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
check();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
poolQuery.mockReset();
|
||||
clientQuery.mockReset();
|
||||
clientRelease.mockReset();
|
||||
fetchMock.mockReset();
|
||||
delete process.env.MAIN_SYSTEM_QUOTE_COST_SYNC;
|
||||
setupDb();
|
||||
fetchMock.mockImplementation(async () => {
|
||||
events.push('FETCH');
|
||||
return jsonResponse(200, OK_PAYLOAD);
|
||||
});
|
||||
});
|
||||
|
||||
describe('审批生效 ⇒ 事务提交之后才出网', () => {
|
||||
beforeEach(() => {
|
||||
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
|
||||
});
|
||||
|
||||
it('approveQuoteSheet:COMMIT 早于 FETCH,body 来自明细、请求号取自台账', async () => {
|
||||
const detail = await approveQuoteSheet({
|
||||
quoteSheetCode: 'QS1',
|
||||
approved: true,
|
||||
ctx: { branchCode: 'BR002', isSuperAdmin: false } as any,
|
||||
});
|
||||
// 审批本身正常返回(不被旁路推送影响)
|
||||
expect(detail?.quote_sheet_code).toBe('QS1');
|
||||
|
||||
await waitFor(() => expect(events).toContain('FETCH'));
|
||||
expect(events).toContain('COMMIT');
|
||||
expect(events.indexOf('COMMIT')).toBeGreaterThan(-1);
|
||||
expect(events.indexOf('COMMIT')).toBeLessThan(events.indexOf('FETCH'));
|
||||
expect(events).toContain('LEDGER_INSERT');
|
||||
expect(events).toContain('LEDGER_sent');
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, any];
|
||||
expect(url).toBe('http://main-system.example/api/supplier/quote-sheets/cost-sync');
|
||||
const body = JSON.parse(init.body);
|
||||
expect(body.supplier_quote_sheet_code).toBe('QS1');
|
||||
expect(body.main_branch_code).toBe('BR002');
|
||||
expect(body.items).toEqual([{ sku_code: 'SKU1', unit: '斤', sale_price: 8.8 }]);
|
||||
// 请求号 = 落台账时的那个(重试复用同一个,不是每次新生成)
|
||||
expect(body.client_request_id).toBe(ledgerInsertParams()?.[3]);
|
||||
});
|
||||
|
||||
it('createQuoteSheet(旧接口:建单即生效)同样在 COMMIT 之后出网', async () => {
|
||||
const detail = await createQuoteSheet({
|
||||
customerCodes: ['MAIN_BR002'],
|
||||
items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 8.8 }],
|
||||
branchCode: 'BR002',
|
||||
});
|
||||
expect(detail?.quote_sheet_code).toBe('QS1');
|
||||
await waitFor(() => expect(events).toContain('FETCH'));
|
||||
expect(events.indexOf('COMMIT')).toBeLessThan(events.indexOf('FETCH'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('推送失败不得影响审批/建单', () => {
|
||||
beforeEach(() => {
|
||||
process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1';
|
||||
});
|
||||
|
||||
it('对方 403 ⇒ 审批照常成功,台账记 forbidden', async () => {
|
||||
events.length = 0;
|
||||
fetchMock.mockImplementation(async () => {
|
||||
events.push('FETCH');
|
||||
return jsonResponse(403, { error: 'branch_not_bound', error_description: '未绑定' });
|
||||
});
|
||||
const detail = await approveQuoteSheet({
|
||||
quoteSheetCode: 'QS1',
|
||||
approved: true,
|
||||
ctx: { branchCode: 'BR002', isSuperAdmin: false } as any,
|
||||
});
|
||||
expect(detail?.quote_sheet_code).toBe('QS1');
|
||||
await waitFor(() => expect(events).toContain('LEDGER_forbidden'));
|
||||
});
|
||||
|
||||
it('出站网络抛错 ⇒ 审批照常成功,台账记 failed(可重试),无未处理拒绝', async () => {
|
||||
events.length = 0;
|
||||
fetchMock.mockImplementation(async () => {
|
||||
events.push('FETCH');
|
||||
throw new Error('ECONNRESET');
|
||||
});
|
||||
const detail = await approveQuoteSheet({
|
||||
quoteSheetCode: 'QS1',
|
||||
approved: true,
|
||||
ctx: { branchCode: 'BR002', isSuperAdmin: false } as any,
|
||||
});
|
||||
expect(detail?.quote_sheet_code).toBe('QS1');
|
||||
await waitFor(() => expect(events).toContain('LEDGER_failed'));
|
||||
});
|
||||
|
||||
it('驳回(approved:false)不推送、不写台账', async () => {
|
||||
const detail = await approveQuoteSheet({
|
||||
quoteSheetCode: 'QS1',
|
||||
approved: false,
|
||||
ctx: { branchCode: 'BR002', isSuperAdmin: false } as any,
|
||||
});
|
||||
expect(detail?.quote_sheet_code).toBe('QS1');
|
||||
await new Promise((resolve) => setTimeout(resolve, 80));
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(events).not.toContain('LEDGER_INSERT');
|
||||
});
|
||||
});
|
||||
|
||||
describe('开关默认关 ⇒ 零出站、零台账', () => {
|
||||
it('开关未设时,审批成功但一个外部请求都不发', async () => {
|
||||
const detail = await approveQuoteSheet({
|
||||
quoteSheetCode: 'QS1',
|
||||
approved: true,
|
||||
ctx: { branchCode: 'BR002', isSuperAdmin: false } as any,
|
||||
});
|
||||
expect(detail?.quote_sheet_code).toBe('QS1');
|
||||
await new Promise((resolve) => setTimeout(resolve, 80));
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(events).not.toContain('LEDGER_INSERT');
|
||||
});
|
||||
});
|
||||
@@ -49,7 +49,7 @@ vi.mock('../src/services/quotePriceProposalService', async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
import { applyQuoteSheetEditAndRequestDeliveryReview } from '../src/services/quoteSheetChangeRequestService';
|
||||
import { applyQuoteSheetEditAndRequestDeliveryReview } from '../src/services/quoteSheetEditService';
|
||||
|
||||
const baseInput = {
|
||||
quoteSheetCode: 'QS1',
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import React from 'react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 「待审改价」面板(2026-10-18 增量需求)版式与权限契约:
|
||||
* · 列表展示:单号 / 提交人 / 提交时间 / 变更摘要(改前 → 改后);
|
||||
* · `canApprove=false`(没有 `customer_manage`)⇒ **只读**,不渲染通过/驳回按钮;
|
||||
* · 通过 ⇒ 调审核接口 + 成功提示 + 刷新 + `onApplied` 回调(页面据此刷新报价单);
|
||||
* · 驳回 ⇒ 必须先填理由(空理由不调接口),调驳回接口后刷新;
|
||||
* · 空列表 ⇒ 「暂无待审改价」。
|
||||
*/
|
||||
|
||||
const listApi = vi.fn();
|
||||
const approveApi = vi.fn();
|
||||
const rejectApi = vi.fn();
|
||||
|
||||
vi.mock('../../utils/workflowApi', () => ({
|
||||
listQuoteChangeRequestsApi: (...args: unknown[]) => listApi(...args),
|
||||
approveQuoteChangeRequestApi: (...args: unknown[]) => approveApi(...args),
|
||||
rejectQuoteChangeRequestApi: (...args: unknown[]) => rejectApi(...args),
|
||||
}));
|
||||
|
||||
const notify = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }));
|
||||
vi.mock('../../utils/notify', () => ({ notify }));
|
||||
|
||||
// 用真实 zh-CN 报价单文案做 t()
|
||||
vi.mock('../../i18n', async () => {
|
||||
const { quotes } = (await import('../../i18n/locales/zh-CN/quotes')) as unknown as {
|
||||
quotes: Record<string, string>;
|
||||
};
|
||||
const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as {
|
||||
common: Record<string, string>;
|
||||
};
|
||||
const dict: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(quotes)) dict[`quotes.${key}`] = value;
|
||||
for (const [key, value] of Object.entries(common)) dict[`common.${key}`] = value;
|
||||
const t = (key: string, vars?: Record<string, unknown>) => {
|
||||
const raw = dict[key] ?? key;
|
||||
if (!vars) return raw;
|
||||
return Object.entries(vars).reduce(
|
||||
(acc, [name, value]) => acc.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value)),
|
||||
raw
|
||||
);
|
||||
};
|
||||
return { useT: () => t };
|
||||
});
|
||||
|
||||
import { QuoteChangeRequestsPanel } from './QuoteChangeRequestsPanel';
|
||||
|
||||
const ROW = {
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
branch_code: 'BR002',
|
||||
quote_sheet_code: 'QS1792200796033LUTV',
|
||||
payload: { items: [{ sku_code: 'SKU1' }] },
|
||||
base_version_no: 1,
|
||||
base_items_fingerprint: 'fp',
|
||||
status: 'pending',
|
||||
requested_by: 'u1',
|
||||
requested_by_name: '张三',
|
||||
requested_at: '2026-10-18T02:00:00.000Z',
|
||||
reviewed_by: null,
|
||||
reviewed_by_name: null,
|
||||
reviewed_at: null,
|
||||
reject_reason: null,
|
||||
applied_at: null,
|
||||
updated_at: '2026-10-18T02:00:00.000Z',
|
||||
summary: {
|
||||
title: null,
|
||||
quote_cycle: null,
|
||||
effective_at: null,
|
||||
auto_sale_price_by_cost: null,
|
||||
customer_codes: null,
|
||||
items_provided: true,
|
||||
item_count: 2,
|
||||
added: 0,
|
||||
removed: 0,
|
||||
updated: 2,
|
||||
lines: [
|
||||
{
|
||||
sku_code: 'SKU1',
|
||||
sku_name: '草鱼',
|
||||
unit: '斤',
|
||||
before_sale_price: 10,
|
||||
after_sale_price: 11,
|
||||
before_cost_price: 5,
|
||||
after_cost_price: 5,
|
||||
change: 'updated' as const,
|
||||
},
|
||||
{
|
||||
sku_code: 'SKU2',
|
||||
sku_name: '鲤鱼',
|
||||
unit: '袋',
|
||||
before_sale_price: null,
|
||||
after_sale_price: 20,
|
||||
before_cost_price: null,
|
||||
after_cost_price: 9,
|
||||
change: 'added' as const,
|
||||
},
|
||||
],
|
||||
truncated: false,
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
listApi.mockReset();
|
||||
approveApi.mockReset();
|
||||
rejectApi.mockReset();
|
||||
notify.success.mockReset();
|
||||
notify.error.mockReset();
|
||||
listApi.mockResolvedValue({ data: [ROW] });
|
||||
approveApi.mockResolvedValue({ data: { quote_sheet_code: ROW.quote_sheet_code }, change_request: { ...ROW, status: 'approved' } });
|
||||
rejectApi.mockResolvedValue({ change_request: { ...ROW, status: 'rejected' } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe('待审改价面板', () => {
|
||||
it('渲染单号 / 提交人 / 提交时间 / 变更摘要(改前 → 改后)与操作按钮', async () => {
|
||||
render(<QuoteChangeRequestsPanel canApprove />);
|
||||
expect(await screen.findByText('QS1792200796033LUTV')).toBeTruthy();
|
||||
expect(screen.getByText(/张三/)).toBeTruthy();
|
||||
expect(screen.getByText('待审改价')).toBeTruthy();
|
||||
expect(screen.getByText('变更摘要')).toBeTruthy();
|
||||
// 草鱼:10.00 → 11.00;鲤鱼:新增 + 20.00
|
||||
expect(screen.getByText('10.00 → 11.00')).toBeTruthy();
|
||||
expect(screen.getByText('+ 20.00')).toBeTruthy();
|
||||
expect(screen.getByText('草鱼')).toBeTruthy();
|
||||
expect(screen.getByText('鲤鱼')).toBeTruthy();
|
||||
expect(screen.getByText('通过')).toBeTruthy();
|
||||
expect(screen.getByText('驳回')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('无审批权 ⇒ 只读(不渲染通过/驳回)', async () => {
|
||||
render(<QuoteChangeRequestsPanel canApprove={false} />);
|
||||
expect(await screen.findByText('QS1792200796033LUTV')).toBeTruthy();
|
||||
expect(screen.queryByText('通过')).toBeNull();
|
||||
expect(screen.queryByText('驳回')).toBeNull();
|
||||
});
|
||||
|
||||
it('空列表 ⇒ 暂无待审改价', async () => {
|
||||
listApi.mockResolvedValue({ data: [] });
|
||||
render(<QuoteChangeRequestsPanel canApprove />);
|
||||
expect(await screen.findByText('暂无待审改价')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('通过 ⇒ 调审核接口、成功提示、刷新列表并回调 onApplied', async () => {
|
||||
const onApplied = vi.fn();
|
||||
render(<QuoteChangeRequestsPanel canApprove onApplied={onApplied} />);
|
||||
await screen.findByText('QS1792200796033LUTV');
|
||||
fireEvent.click(screen.getByText('通过'));
|
||||
await waitFor(() => expect(approveApi).toHaveBeenCalledWith(ROW.id));
|
||||
await waitFor(() => expect(notify.success).toHaveBeenCalledWith('审核通过'));
|
||||
expect(onApplied).toHaveBeenCalledTimes(1);
|
||||
expect(listApi.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('驳回:空理由不调接口;填理由后调驳回接口', async () => {
|
||||
render(<QuoteChangeRequestsPanel canApprove />);
|
||||
await screen.findByText('QS1792200796033LUTV');
|
||||
fireEvent.click(screen.getByText('驳回'));
|
||||
const input = await screen.findByLabelText('驳回理由');
|
||||
// 行内「驳回」打开输入条后,页面上会出现第二个「驳回」(= 确认按钮),取最后一个
|
||||
const clickConfirmReject = () => {
|
||||
const buttons = screen.getAllByText('驳回');
|
||||
fireEvent.click(buttons[buttons.length - 1]);
|
||||
};
|
||||
clickConfirmReject();
|
||||
await waitFor(() => expect(notify.error).toHaveBeenCalledWith('请填写驳回理由'));
|
||||
expect(rejectApi).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.change(input, { target: { value: '价格谈不拢' } });
|
||||
clickConfirmReject();
|
||||
await waitFor(() => expect(rejectApi).toHaveBeenCalledWith(ROW.id, '价格谈不拢'));
|
||||
expect(notify.success).toHaveBeenCalledWith('审核驳回');
|
||||
});
|
||||
|
||||
it('加载失败 ⇒ 错误提示(不是静默空白)', async () => {
|
||||
listApi.mockRejectedValue(new Error('加载失败'));
|
||||
render(<QuoteChangeRequestsPanel canApprove />);
|
||||
await waitFor(() => expect(notify.error).toHaveBeenCalledWith('加载失败'));
|
||||
});
|
||||
});
|
||||
@@ -1,250 +0,0 @@
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { Check, RefreshCw, X } from 'lucide-react';
|
||||
import { notify } from '../../utils/notify';
|
||||
import { useT } from '../../i18n';
|
||||
import {
|
||||
approveQuoteChangeRequestApi,
|
||||
listQuoteChangeRequestsApi,
|
||||
rejectQuoteChangeRequestApi,
|
||||
type QuoteChangeLineDto,
|
||||
type QuoteChangeRequestDto,
|
||||
} from '../../utils/workflowApi';
|
||||
|
||||
/**
|
||||
* 「待审改价」面板(2026-10-18 增量需求):
|
||||
* 编辑**生效中**报价单里价格相关的改动,保存时只落「待审变更」,**审核通过才真正改单并同步成本价**。
|
||||
*
|
||||
* 放在报价单页内(`QuoteVersionManagement` 的 chrome tab),不新增独立菜单。
|
||||
* 权限一分为二(Lead 裁定):查看 = `customer_manage | order_manage`;**通过/驳回只认 `customer_manage`**
|
||||
* ⇒ 没有 `customer_manage` 的人是**只读**(不渲染操作按钮,不额外加提示文案)。
|
||||
*/
|
||||
|
||||
function formatPrice(value: number | null | undefined): string {
|
||||
if (value === null || value === undefined) return '—';
|
||||
return Number(value).toFixed(2);
|
||||
}
|
||||
|
||||
function formatTime(value: string | null | undefined): string {
|
||||
if (!value) return '—';
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString();
|
||||
}
|
||||
|
||||
function lineText(line: QuoteChangeLineDto): string {
|
||||
if (line.change === 'added') return `+ ${formatPrice(line.after_sale_price)}`;
|
||||
if (line.change === 'removed') return `− ${formatPrice(line.before_sale_price)}`;
|
||||
return `${formatPrice(line.before_sale_price)} → ${formatPrice(line.after_sale_price)}`;
|
||||
}
|
||||
|
||||
function lineCostText(line: QuoteChangeLineDto): string | null {
|
||||
if (line.before_cost_price === null && line.after_cost_price === null) return null;
|
||||
const changed =
|
||||
Math.abs(Number(line.before_cost_price ?? 0) - Number(line.after_cost_price ?? 0)) > 1e-6;
|
||||
if (!changed) return null;
|
||||
return `${formatPrice(line.before_cost_price)} → ${formatPrice(line.after_cost_price)}`;
|
||||
}
|
||||
|
||||
export type QuoteChangeRequestsPanelProps = {
|
||||
/** 是否有审批权(`customer_manage`);false = 只读 */
|
||||
canApprove: boolean;
|
||||
/** 审核通过后回调(页面用来刷新报价单列表/详情) */
|
||||
onApplied?: () => void;
|
||||
};
|
||||
|
||||
export const QuoteChangeRequestsPanel: React.FC<QuoteChangeRequestsPanelProps> = ({
|
||||
canApprove,
|
||||
onApplied,
|
||||
}) => {
|
||||
const t = useT();
|
||||
const [rows, setRows] = useState<QuoteChangeRequestDto[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [actingId, setActingId] = useState<string | null>(null);
|
||||
const [rejecting, setRejecting] = useState<{ id: string; reason: string } | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const { data } = await listQuoteChangeRequestsApi({ status: 'pending' });
|
||||
setRows(Array.isArray(data) ? data : []);
|
||||
} catch (error: any) {
|
||||
notify.error(error?.message || t('quotes.changeRequest.loadFail'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const handleApprove = async (row: QuoteChangeRequestDto) => {
|
||||
setActingId(row.id);
|
||||
try {
|
||||
await approveQuoteChangeRequestApi(row.id);
|
||||
notify.success(t('quotes.changeRequest.approved'));
|
||||
setRejecting(null);
|
||||
await load();
|
||||
onApplied?.();
|
||||
} catch (error: any) {
|
||||
// 409 base_changed / already_decided / sku_unavailable 等后端会带中文说明,直接透出
|
||||
notify.error(error?.message || t('quotes.changeRequest.approveFail'));
|
||||
} finally {
|
||||
setActingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReject = async () => {
|
||||
if (!rejecting) return;
|
||||
const reason = rejecting.reason.trim();
|
||||
if (!reason) {
|
||||
notify.error(t('quotes.changeRequest.rejectReasonPh'));
|
||||
return;
|
||||
}
|
||||
setActingId(rejecting.id);
|
||||
try {
|
||||
await rejectQuoteChangeRequestApi(rejecting.id, reason);
|
||||
notify.success(t('quotes.changeRequest.rejected'));
|
||||
setRejecting(null);
|
||||
await load();
|
||||
} catch (error: any) {
|
||||
notify.error(error?.message || t('quotes.changeRequest.rejectFail'));
|
||||
} finally {
|
||||
setActingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-gray-800 dark:text-gray-100">
|
||||
{t('quotes.changeRequest.title')}
|
||||
{rows.length ? <span className="ml-2 text-gray-500">({rows.length})</span> : null}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void load()}
|
||||
className="p-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
title={t('common.refresh')}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!loading && rows.length === 0 ? (
|
||||
<div className="app-surface rounded-2xl border border-gray-200 dark:border-gray-700 p-8 text-center text-sm text-gray-500">
|
||||
{t('quotes.changeRequest.empty')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => {
|
||||
const summary = row.summary;
|
||||
const busy = actingId === row.id;
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="app-surface rounded-2xl border border-gray-200 dark:border-gray-700 p-4 space-y-3"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-gray-900 dark:text-gray-100">
|
||||
{row.quote_sheet_code}
|
||||
{summary ? (
|
||||
<span className="ml-2 text-xs text-gray-500">
|
||||
{t('quotes.changeRequest.itemCount', { count: summary.item_count })}
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t('quotes.changeRequest.submittedBy')}:{row.requested_by_name || '—'} ·{' '}
|
||||
{t('quotes.changeRequest.submittedAt')}:{formatTime(row.requested_at)}
|
||||
</p>
|
||||
</div>
|
||||
{canApprove ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void handleApprove(row)}
|
||||
className="app-button-primary inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm disabled:opacity-50"
|
||||
>
|
||||
<Check className="w-4 h-4" />
|
||||
{t('quotes.changeRequest.approve')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setRejecting({ id: row.id, reason: '' })}
|
||||
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm border border-red-300 text-red-600 hover:bg-red-50 disabled:opacity-50"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
{t('quotes.changeRequest.reject')}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{summary ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-gray-500">{t('quotes.changeRequest.summary')}</p>
|
||||
<ul className="space-y-1 text-sm text-gray-700 dark:text-gray-200">
|
||||
{summary.lines.map((line) => (
|
||||
<li key={`${line.change}-${line.sku_code}`} className="flex flex-wrap items-center gap-2">
|
||||
<span className="app-product-name">{line.sku_name || line.sku_code}</span>
|
||||
{line.unit ? <span className="text-xs text-gray-500">{line.unit}</span> : null}
|
||||
<span className="tabular-nums">{lineText(line)}</span>
|
||||
{lineCostText(line) ? (
|
||||
<span className="text-xs text-gray-500 tabular-nums">
|
||||
{t('quotes.export.col.cost_price')} {lineCostText(line)}
|
||||
</span>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
{summary.lines.length === 0 ? (
|
||||
<li className="text-xs text-gray-500">
|
||||
{t('quotes.changeRequest.itemCount', { count: summary.item_count })}
|
||||
</li>
|
||||
) : null}
|
||||
{summary.truncated ? <li className="text-xs text-gray-500">…</li> : null}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{rejecting?.id === row.id ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
value={rejecting.reason}
|
||||
onChange={(event) =>
|
||||
setRejecting((current) =>
|
||||
current ? { ...current, reason: event.target.value } : current
|
||||
)
|
||||
}
|
||||
placeholder={t('quotes.changeRequest.rejectReasonPh')}
|
||||
aria-label={t('quotes.changeRequest.rejectReason')}
|
||||
className="app-input app-focus-ring flex-1 min-w-[12rem] px-3 py-1.5 text-sm rounded-lg border border-slate-200 dark:border-slate-600"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void handleReject()}
|
||||
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm bg-red-600 text-white hover:bg-red-700 disabled:opacity-50"
|
||||
>
|
||||
{t('quotes.changeRequest.reject')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setRejecting(null)}
|
||||
className="px-3 py-1.5 rounded-lg text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,53 +0,0 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 报价单页接入「改价需审核」的**接线契约**(2026-10-18 增量需求)。
|
||||
*
|
||||
* 为什么用源码断言而不是整页渲染:这一页有 1700 行、十几个异步数据源(客户/商品/分类/权限/导出),
|
||||
* 整页 render 的失败面与本次改动无关;而这里要钉的恰恰是**接线**:
|
||||
* · 保存响应 `applied === false` ⇒ 必须提示「已提交审核」并切到「待审改价」页签(不能提示"已更新");
|
||||
* · 「待审改价」是页内 chrome tab(不新增独立菜单),只对有报价单编辑权的人可见;
|
||||
* · 面板的审批按钮按 `customer_manage` 再收一次(无权限只读);
|
||||
* · 审核通过后刷新报价单列表。
|
||||
*/
|
||||
const page = readFileSync(new URL('./QuoteVersionManagement.tsx', import.meta.url), 'utf8');
|
||||
|
||||
describe('报价单页 · 改价审核接线', () => {
|
||||
it('保存响应 applied === false ⇒ 提示「已提交审核」+ 切到待审页签 + 关弹窗(不得提示"已更新")', () => {
|
||||
const start = page.indexOf('const handleSave = async () => {');
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const end = page.indexOf('const toggleExpand', start);
|
||||
expect(end).toBeGreaterThan(start);
|
||||
const handler = page.slice(start, end);
|
||||
|
||||
expect(handler).toMatch(/const response = await updateQuoteSheetApi\(editingCode, payload\);/);
|
||||
expect(handler).toMatch(/if \(response\.applied === false\)/);
|
||||
expect(handler).toContain("notify.success(t('quotes.toast.submittedForApproval'))");
|
||||
expect(handler).toMatch(/closeFormModal\(\);\s*\n\s*setPageTab\('pending'\);/);
|
||||
// 「已提交审核」分支必须在「已更新」之前 return,不能两个提示都弹
|
||||
expect(handler.indexOf("t('quotes.toast.submittedForApproval')")).toBeLessThan(
|
||||
handler.indexOf("t('quotes.toast.updated')")
|
||||
);
|
||||
});
|
||||
|
||||
it('「待审改价」是页内页签(不新增菜单),且只对有报价单编辑权的人可见', () => {
|
||||
expect(page).toContain("t('quotes.tab.pendingCharges')");
|
||||
expect(page).toMatch(/id: 'pending', label: t\('quotes\.tab\.pendingCharges'\), hidden: !canManageQuotes/);
|
||||
// 页签值参与 chromeTab 映射('pending' 不能被吞成 active/history;2026-10-18 后又加了 deliveryPrice)
|
||||
expect(page).toMatch(/pageTab === 'pending'[\s\S]{0,80}?'pending'/);
|
||||
});
|
||||
|
||||
it('待审页签渲染面板;审批权按 customer_manage 收窄;通过后刷新报价单列表', () => {
|
||||
expect(page).toContain('<QuoteChangeRequestsPanel');
|
||||
expect(page).toMatch(/canApprove=\{canManageCustomerLibrary\}/);
|
||||
expect(page).toMatch(/onApplied=\{\(\) => \{[\s\S]{0,240}?void loadSheets\(\);/);
|
||||
});
|
||||
|
||||
it('待审页签不显示客户筛选(避免误导"按客户筛待审")', () => {
|
||||
// 2026-10-18 增加「配送商成本价确认」「商品映射」两个页签后,非报价单列表页签都不显示客户筛选
|
||||
expect(page).toMatch(
|
||||
/\{pageTab !== 'pending' && pageTab !== 'deliveryPrice' && pageTab !== 'skuMappings' \? \(/
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user