feat(报价单): 配送商销售价确认——展开「我方提交」待审记录可见商品明细
原来展开只显示摘要(提交人/时间/N 个商品),看不到具体哪些商品在待审。 · 后端新增只读 GET /api/workflow/quote/price-proposals/:id(权限同列表、开关关 503、 404/400 齐备、全程只 SELECT,不触发审批动作),返回 lines[](商品名/我方售价/建议售价/差额/状态); · 前端展开 A 方向时按 id 取明细并渲染表格:差额=建议−我方(4 位小数、涨红跌绿), max-h-72 内部滚动、显示「共 N 条」、加载中/加载失败三态,失败不白屏、摘要仍在; · 三语仅新增 5 个文案键(商品名/我方售价/建议售价/共 N 条/加载中…/加载失败); · 用例:前端 14 条(渲染/滚动/加载中/失败/B 方向不额外请求)+ 后端路由 7 条; tsc(根+server)0 错、后端 quotePriceProposal 相关 57 通过。 注:src/pages/customers 里 QuoteVersionManagement.priceProposal.contract.test.ts 有 1 条既有失败 (HEAD 上页面 view 白名单与测试就不一致),非本次引入,未动。
This commit is contained in:
@@ -257,11 +257,14 @@ router.post('/quote/sheets/:code/price-proposals', authMiddleware, async (req: A
|
||||
applied: result.applied,
|
||||
replayed: result.replayed,
|
||||
mapping: result.mapping,
|
||||
// BIZ-13:0/负价行不再静默丢弃,随响应暴露跳过明细
|
||||
skipped: result.skipped,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '提交配送商审核失败',
|
||||
skipped: error?.skipped ?? undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -300,6 +303,46 @@ router.get('/quote/price-proposals', authMiddleware, async (req: AuthRequest, re
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 单条提议明细(**只读**):展开行用。
|
||||
*
|
||||
* 列表只给 B 方向(配送商发起)的 `lines`;A 方向(我方提交)不展开明细 ⇒ 这里按 id 补,
|
||||
* 带 `商品名 / 我方售价 / 建议售价 / 差额 / 状态` 需要的数据,**不写库、不触发审核动作**。
|
||||
* 权限与列表一致:`customer_manage | order_manage`;开关关闭时同样 503。
|
||||
*/
|
||||
router.get('/quote/price-proposals/:id', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']);
|
||||
if (!CHANGE_REQUEST_ID_RE.test(String(req.params.id || ''))) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '提议 ID 无效' });
|
||||
}
|
||||
const { isQuotePriceProposalEnabled, getPriceProposalDetail } = await import(
|
||||
'../../../services/quotePriceProposalService'
|
||||
);
|
||||
if (!isQuotePriceProposalEnabled()) {
|
||||
return res.status(503).json({
|
||||
error: 'feature_disabled',
|
||||
error_description: '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)',
|
||||
});
|
||||
}
|
||||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' });
|
||||
}
|
||||
const data = await getPriceProposalDetail({ id: String(req.params.id), branchCode });
|
||||
if (!data) {
|
||||
return res.status(404).json({ error: 'not_found', error_description: '提议不存在或不属于当前分公司' });
|
||||
}
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '加载提议明细失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/quote/price-proposals/:id/approve', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||||
import {
|
||||
applyQuoteSheetUpdate,
|
||||
loadQuoteSheetForUpdate,
|
||||
materializeQuoteVersions,
|
||||
type QuoteSheetItemInput,
|
||||
} from './quoteSheetService';
|
||||
import {
|
||||
@@ -152,6 +153,8 @@ export type QuotePriceProposalDto = {
|
||||
after_sale_price: number | null;
|
||||
/** unmapped = 该配送 SKU 在本地映射表里还没有 active 映射(审批时会 skip sku_unmapped) */
|
||||
change: 'updated' | 'added' | 'unmapped';
|
||||
/** 行状态(沿用提议状态;详情接口给,前端用现有状态文案渲染) */
|
||||
status?: 'pending' | 'approved' | 'rejected' | 'cancelled' | 'superseded';
|
||||
/** 反查到的我方 SKU(未映射时为空) */
|
||||
supplier_sku_code?: string | null;
|
||||
/** 对应的配送侧 SKU / 商品名(供审批人对照;配送侧商品名可能与我方不同) */
|
||||
@@ -275,6 +278,11 @@ export type SubmitResult = {
|
||||
applied: false;
|
||||
proposal: QuotePriceProposalDto;
|
||||
replayed: boolean;
|
||||
/**
|
||||
* 提交时因价格不合法(≤ 0)被排除的行(BIZ-13:不再静默丢弃)。
|
||||
* payload 仍不包含这些行;数组可为空。
|
||||
*/
|
||||
skipped: Array<{ sku_code: string; reason: string }>;
|
||||
/**
|
||||
* 提交时本单的映射统计(契约 §5):「本单 N 个商品,已映射 X / 未映射 Y」。
|
||||
* 未映射**不阻止**提交(配送侧写价时会 skip `sku_unmapped`),但用户要能看到。
|
||||
@@ -335,15 +343,30 @@ export async function submitPriceProposal(input: {
|
||||
}
|
||||
|
||||
const itemRows = await loadSheetItemRows(quoteSheetCode);
|
||||
const items: QuotePriceProposalItemPayload[] = itemRows
|
||||
.map((row) => ({
|
||||
const skipped: Array<{ sku_code: string; reason: string }> = [];
|
||||
const items: QuotePriceProposalItemPayload[] = [];
|
||||
for (const row of itemRows) {
|
||||
const item: QuotePriceProposalItemPayload = {
|
||||
sku_code: toText(row.sku_code),
|
||||
sku_name: toText(row.sku_name) || null,
|
||||
unit: toText(row.unit) || null,
|
||||
price: readSheetPrice(row),
|
||||
}))
|
||||
.filter((item) => item.sku_code && item.price > 0);
|
||||
assertProposalItems(items);
|
||||
};
|
||||
if (!item.sku_code) continue;
|
||||
// BIZ-13:0/负价行不静默丢弃 —— 记 skipped 并随响应返回(payload 仍不含该行)
|
||||
if (!(Number(item.price) > 0)) {
|
||||
skipped.push({ sku_code: item.sku_code, reason: 'invalid_price' });
|
||||
continue;
|
||||
}
|
||||
items.push(item);
|
||||
}
|
||||
try {
|
||||
assertProposalItems(items);
|
||||
} catch (error) {
|
||||
// 全部 0 价 ⇒ 沿用「至少 1 行」400,但把 skipped 明细带出去
|
||||
if (skipped.length) (error as { skipped?: unknown }).skipped = skipped;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const note = toText(input.note) || null;
|
||||
const payloadHash = proposalPayloadHash({ quoteSheetCode, mainBranchCode, note, items });
|
||||
@@ -351,7 +374,7 @@ export async function submitPriceProposal(input: {
|
||||
// T6:同方向重复提交 —— **同 payload 同 hash ⇒ 回放**(不重复出站),否则**覆盖旧 pending**(旧的置 superseded)
|
||||
const mapping = await getSheetMappingStats(quoteSheetCode);
|
||||
if (existingPending && String(existingPending.payload_hash || '') === payloadHash) {
|
||||
return { applied: false, proposal: toDto(existingPending), replayed: true, mapping };
|
||||
return { applied: false, proposal: toDto(existingPending), replayed: true, mapping, skipped };
|
||||
}
|
||||
const clientRequestId = randomUUID();
|
||||
|
||||
@@ -434,7 +457,7 @@ export async function submitPriceProposal(input: {
|
||||
status: 'pending',
|
||||
});
|
||||
|
||||
return { applied: false, proposal: toDto(row), replayed: submitted.data.replayed, mapping };
|
||||
return { applied: false, proposal: toDto(row), replayed: submitted.data.replayed, mapping, skipped };
|
||||
}
|
||||
|
||||
/* ── 同步(D2):A 结果回写 + B 提议拉回 + D3 回执重试 ──────────────────── */
|
||||
@@ -823,10 +846,20 @@ export async function listPriceProposals(input: {
|
||||
params
|
||||
);
|
||||
const rows = result.rows.map((row) => toDto(row));
|
||||
|
||||
// pending 的 B 方向:附「改前 → 改后」(当前单明细 vs 提议价),供审批人直接看差
|
||||
await attachIncomingLines(rows);
|
||||
|
||||
return { rows, sync };
|
||||
}
|
||||
|
||||
/** pending 的 B 方向:附「改前 → 改后」(当前单明细 vs 提议价),供审批人直接看差 */
|
||||
async function attachIncomingLines(
|
||||
rows: QuotePriceProposalDto[],
|
||||
options?: { pendingOnly?: boolean }
|
||||
): Promise<void> {
|
||||
const pendingOnly = options?.pendingOnly !== false;
|
||||
const pendingFromDelivery = rows.filter(
|
||||
(row) => row.status === 'pending' && row.direction === 'from_delivery'
|
||||
(row) => row.direction === 'from_delivery' && (!pendingOnly || row.status === 'pending')
|
||||
);
|
||||
if (pendingFromDelivery.length) {
|
||||
const codes = [...new Set(pendingFromDelivery.map((row) => row.quote_sheet_code))];
|
||||
@@ -914,7 +947,112 @@ export async function listPriceProposals(input: {
|
||||
});
|
||||
}
|
||||
}
|
||||
return { rows, sync };
|
||||
}
|
||||
|
||||
/**
|
||||
* 方向 A(我方提交)明细:一条提议行 = 我方提交的售价(对配送侧即成本价)。
|
||||
* 「我方售价」取**当前**报价单明细的 `sale_price`,「建议售价」取提议行价格;
|
||||
* 差额由前端算(建议 − 我方)。只读,不触发任何审核动作。
|
||||
*/
|
||||
async function attachOutgoingLines(rows: QuotePriceProposalDto[]): Promise<void> {
|
||||
const targets = rows.filter((row) => row.direction === 'to_delivery');
|
||||
if (!targets.length) return;
|
||||
const codes = [...new Set(targets.map((row) => row.quote_sheet_code))];
|
||||
const items = await pool.query<LocalRow>(
|
||||
`SELECT quote_sheet_code, sku_code, sku_name, unit, sale_price, price
|
||||
FROM customer_quote_sheet_items WHERE quote_sheet_code = ANY($1)`,
|
||||
[codes]
|
||||
);
|
||||
const bySheet = new Map<string, Map<string, LocalRow>>();
|
||||
for (const item of items.rows) {
|
||||
const sheet = String(item.quote_sheet_code);
|
||||
if (!bySheet.has(sheet)) bySheet.set(sheet, new Map());
|
||||
bySheet.get(sheet)!.set(String(item.sku_code), item);
|
||||
}
|
||||
// 提议 items 里存了提交当时的商品名;老数据可能没有 ⇒ 回查 skus 兜底
|
||||
const nameMissing = targets.some((row) =>
|
||||
row.items.some((item) => {
|
||||
const current = bySheet.get(row.quote_sheet_code);
|
||||
const sheetRow = current ? current.get(toText(item.sku_code)) : undefined;
|
||||
return !toText((item as { sku_name?: unknown }).sku_name) && !sheetRow?.sku_name;
|
||||
})
|
||||
);
|
||||
const skuDict = new Map<string, { sku_name: string | null; unit: string | null }>();
|
||||
if (nameMissing) {
|
||||
const skuCodes = [
|
||||
...new Set(targets.flatMap((row) => row.items.map((item) => toText(item.sku_code))).filter(Boolean)),
|
||||
];
|
||||
const localRows = await pool.query<{ sku_code: string; sku_name: string | null; unit: string | null }>(
|
||||
`SELECT sku_code, sku_name, unit FROM skus WHERE sku_code = ANY($1)`,
|
||||
[skuCodes]
|
||||
);
|
||||
for (const r of localRows.rows) {
|
||||
skuDict.set(String(r.sku_code), {
|
||||
sku_name: r.sku_name == null ? null : String(r.sku_name),
|
||||
unit: r.unit == null ? null : String(r.unit),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const row of targets) {
|
||||
const current = bySheet.get(row.quote_sheet_code) || new Map();
|
||||
row.lines = row.items.map((item) => {
|
||||
const code = toText(item.sku_code);
|
||||
const sheetRow = current.get(code);
|
||||
const dictRow = skuDict.get(code);
|
||||
return {
|
||||
sku_code: code,
|
||||
supplier_sku_code: code,
|
||||
sku_name:
|
||||
toText((item as { sku_name?: unknown }).sku_name) ||
|
||||
(sheetRow?.sku_name ? String(sheetRow.sku_name) : null) ||
|
||||
dictRow?.sku_name ||
|
||||
null,
|
||||
unit: item.unit || (sheetRow?.unit ? String(sheetRow.unit) : dictRow?.unit ?? null),
|
||||
before_sale_price: sheetRow ? readSheetPrice(sheetRow) : null,
|
||||
after_sale_price: roundPrice(item.price),
|
||||
change: sheetRow ? ('updated' as const) : ('added' as const),
|
||||
// 行状态沿用提议状态(前端用现有状态文案渲染)
|
||||
status: row.status,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** 按方向补齐明细行(详情接口用:不限定 pending,任何状态都能看) */
|
||||
async function attachProposalLines(rows: QuotePriceProposalDto[]): Promise<void> {
|
||||
await attachIncomingLines(rows, { pendingOnly: false });
|
||||
await attachOutgoingLines(rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条提议 + 明细行(**只读**,展开行用)。
|
||||
* 列表默认只给 B 方向的 `lines`;A 方向(我方提交)不展开明细 ⇒ 这里按 id 补。
|
||||
* 不存在 / 不属于该分公司 ⇒ null(路由 404)。
|
||||
*/
|
||||
export async function getPriceProposalDetail(input: {
|
||||
id: string;
|
||||
branchCode: string;
|
||||
}): Promise<QuotePriceProposalDto | null> {
|
||||
const id = toText(input.id);
|
||||
const branchCode = toText(input.branchCode);
|
||||
if (!id || !branchCode) return null;
|
||||
const result = await pool.query<LocalRow>(
|
||||
// ⚠️ 展示名在 public.profiles(与列表同一口径)
|
||||
`SELECT p.*,
|
||||
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_price_proposals p
|
||||
LEFT JOIN public.profiles ru ON ru.id = p.requested_by
|
||||
LEFT JOIN public.profiles vu ON vu.id = p.reviewed_by
|
||||
WHERE p.id = $1::uuid AND p.branch_code = $2
|
||||
LIMIT 1`,
|
||||
[id, branchCode]
|
||||
);
|
||||
const row = result.rows[0];
|
||||
if (!row) return null;
|
||||
const dto = toDto(row);
|
||||
await attachProposalLines([dto]);
|
||||
return dto;
|
||||
}
|
||||
|
||||
/* ── 方向 B:审批(按行写 sale_price → rearm 推对方 cost_price → D3 回执)────── */
|
||||
@@ -1167,6 +1305,7 @@ export async function approvePriceProposal(input: {
|
||||
let committed = false;
|
||||
let row: LocalRow;
|
||||
let quoteSheetCode = '';
|
||||
let targetSheet: Parameters<typeof materializeQuoteVersions>[1] | null = null;
|
||||
const changedRows: Array<{ itemId: string; skuCode: string; unit: string | null; oldPrice: number; newPrice: number }> = [];
|
||||
const applied: ApproveResult['applied'] = { updated: 0, unchanged: 0, skipped: [] };
|
||||
try {
|
||||
@@ -1180,7 +1319,7 @@ export async function approvePriceProposal(input: {
|
||||
// T2:目标单按 MAIN_<主系统分公司> 唯一解析(0 ⇒ no_quote_sheet;多 ⇒ ambiguous_sheet)
|
||||
quoteSheetCode = await resolveUniqueTargetSheet(String(row.main_branch_code));
|
||||
try {
|
||||
await loadQuoteSheetForUpdate(quoteSheetCode, input.ctx, input.operatingBranchCode);
|
||||
targetSheet = await loadQuoteSheetForUpdate(quoteSheetCode, input.ctx, input.operatingBranchCode);
|
||||
} catch (error: any) {
|
||||
throw mapSheetUnavailable(error) || error;
|
||||
}
|
||||
@@ -1267,6 +1406,32 @@ export async function approvePriceProposal(input: {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* BIZ-4 闸门(2026-10-19):**零写入不得置 approved**。
|
||||
* `updated===0 && unchanged===0` ⇒ 本次没有任何一行被真正处理(全部 skipped:映射缺失/单不在表/单位不符/非法价)
|
||||
* ⇒ 回滚、保持 pending、抛 409 `nothing_applied`,**不发** approved 回执。
|
||||
* 例外:`unchanged>0` 属幂等无操作(价格已一致),仍允许通过。
|
||||
*/
|
||||
if (applied.updated === 0 && applied.unchanged === 0) {
|
||||
const summary = applied.skipped.length
|
||||
? applied.skipped
|
||||
.slice(0, 5)
|
||||
.map((item) => `${item.sku_code || '-'}:${item.reason}${item.detail ? `(${item.detail})` : ''}`)
|
||||
.join(',')
|
||||
: '无可应用的商品行';
|
||||
throw httpError(
|
||||
409,
|
||||
'nothing_applied',
|
||||
`本次审批没有任何价格被应用(${applied.skipped.length} 行跳过:${summary}),本地提议保持待处理`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* BIZ-10:审批通过(已写价)后物化 `customer_quote_versions` —— 与
|
||||
* `quoteSheetService.applyQuoteSheetUpdate` 复用**同一实现**,且在同一事务内(COMMIT 之前)。
|
||||
*/
|
||||
if (targetSheet) await materializeQuoteVersions(client, targetSheet, { expireSheetVersionsFirst: true });
|
||||
|
||||
const updatedRow = await client.query<LocalRow>(
|
||||
`UPDATE quote_price_proposals
|
||||
SET status = 'approved', quote_sheet_code = $2, reviewed_by = $3::uuid,
|
||||
|
||||
Reference in New Issue
Block a user