From 492ae97cc61e71a4fd27274e5d002e6fef2bd771 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 19 Oct 2026 11:17:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=8A=A5=E4=BB=B7=E5=8D=95):=20=E9=85=8D?= =?UTF-8?q?=E9=80=81=E5=95=86=E9=94=80=E5=94=AE=E4=BB=B7=E7=A1=AE=E8=AE=A4?= =?UTF-8?q?=E2=80=94=E2=80=94=E5=B1=95=E5=BC=80=E3=80=8C=E6=88=91=E6=96=B9?= =?UTF-8?q?=E6=8F=90=E4=BA=A4=E3=80=8D=E5=BE=85=E5=AE=A1=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E5=8F=AF=E8=A7=81=E5=95=86=E5=93=81=E6=98=8E=E7=BB=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原来展开只显示摘要(提交人/时间/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 白名单与测试就不一致),非本次引入,未动。 --- .../modules/workflow/routes/quoteRoutes.ts | 43 ++++ .../src/services/quotePriceProposalService.ts | 187 +++++++++++++- .../quotePriceProposalDetailRoute.test.ts | 158 ++++++++++++ src/i18n/locales/en/quotes.ts | 6 + src/i18n/locales/id/quotes.ts | 6 + src/i18n/locales/zh-CN/quotes.ts | 6 + ...riceProposalsPanel.detail.contract.test.ts | 127 +++++++++ ...eliveryPriceProposalsPanel.detail.test.tsx | 241 ++++++++++++++++++ .../QuoteDeliveryPriceProposalsPanel.tsx | 135 +++++++++- src/utils/workflowApi.ts | 11 + 10 files changed, 905 insertions(+), 15 deletions(-) create mode 100644 server/tests/quotePriceProposalDetailRoute.test.ts create mode 100644 src/pages/customers/QuoteDeliveryPriceProposalsPanel.detail.contract.test.ts create mode 100644 src/pages/customers/QuoteDeliveryPriceProposalsPanel.detail.test.tsx diff --git a/server/src/modules/workflow/routes/quoteRoutes.ts b/server/src/modules/workflow/routes/quoteRoutes.ts index 06ce046..1b6ce21 100644 --- a/server/src/modules/workflow/routes/quoteRoutes.ts +++ b/server/src/modules/workflow/routes/quoteRoutes.ts @@ -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); diff --git a/server/src/services/quotePriceProposalService.ts b/server/src/services/quotePriceProposalService.ts index 1ec5600..28c5c2e 100644 --- a/server/src/services/quotePriceProposalService.ts +++ b/server/src/services/quotePriceProposalService.ts @@ -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 { + 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 { + 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( + `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>(); + 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(); + 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 { + await attachIncomingLines(rows, { pendingOnly: false }); + await attachOutgoingLines(rows); +} + +/** + * 单条提议 + 明细行(**只读**,展开行用)。 + * 列表默认只给 B 方向的 `lines`;A 方向(我方提交)不展开明细 ⇒ 这里按 id 补。 + * 不存在 / 不属于该分公司 ⇒ null(路由 404)。 + */ +export async function getPriceProposalDetail(input: { + id: string; + branchCode: string; +}): Promise { + const id = toText(input.id); + const branchCode = toText(input.branchCode); + if (!id || !branchCode) return null; + const result = await pool.query( + // ⚠️ 展示名在 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[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( `UPDATE quote_price_proposals SET status = 'approved', quote_sheet_code = $2, reviewed_by = $3::uuid, diff --git a/server/tests/quotePriceProposalDetailRoute.test.ts b/server/tests/quotePriceProposalDetailRoute.test.ts new file mode 100644 index 0000000..003a38b --- /dev/null +++ b/server/tests/quotePriceProposalDetailRoute.test.ts @@ -0,0 +1,158 @@ +import express from 'express'; +import request from 'supertest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 「按 proposal id 取明细」路由层边界(2026-10-19 增量,只读): + * · `GET /api/workflow/quote/price-proposals/:id` 仅查看权限 `customer_manage | order_manage`; + * · 开关关闭 ⇒ 503 `feature_disabled`,且服务零调用; + * · 非法 id ⇒ 400 `invalid_request`,服务零调用; + * · 缺分公司上下文 ⇒ 400 `branch_required`; + * · 服务层返回 null(不存在 / 不属于本分公司)⇒ 404 `not_found`; + * · 成功 ⇒ 200 `{ data }`,服务只收到 `{ id, branchCode }`(body/query 一律不采信)。 + * + * 鉴权/租户上下文/服务层都 mock,数据库不参与。 + */ + +const H = vi.hoisted(() => ({ + ctx: null as Record | null, + enabled: true, + getPriceProposalDetail: vi.fn(), +})); + +vi.mock('../src/middleware/auth', () => ({ + authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => { + req.userId = 'user-1'; + next(); + }, +})); + +vi.mock('../src/modules/workflow/context', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getWorkflowCtx: async () => H.ctx }; +}); + +vi.mock('../src/services/quotePriceProposalService', () => ({ + isQuotePriceProposalEnabled: () => H.enabled, + getPriceProposalDetail: (...args: unknown[]) => H.getPriceProposalDetail(...args), +})); + +const { mountQuoteWorkflowRoutes } = await import('../src/modules/workflow/routes/quoteRoutes'); + +const ID = '11111111-1111-4111-8111-111111111111'; + +function buildApp() { + const app = express(); + app.use(express.json()); + const router = express.Router(); + mountQuoteWorkflowRoutes(router); + app.use('/api/workflow', router); + return app; +} + +const app = buildApp(); + +function ctxWith(permissions: string[], patch: Record = {}) { + return { + userId: 'user-1', + roles: ['admin'], + permissions, + branchCode: 'BR002', + supplierCode: null, + purchaserCode: null, + isSuperAdmin: false, + isBranchAdmin: false, + isInternalStaff: true, + isSupplierAccount: false, + ...patch, + }; +} + +const detail = { + id: ID, + branch_code: 'BR002', + quote_sheet_code: 'QS1', + main_branch_code: 'BR002', + direction: 'to_delivery', + items: [ + { sku_code: 'SKU1', unit: '斤', price: 11.125 }, + { sku_code: 'SKU2', unit: '袋', price: 9.9 }, + ], + status: 'pending', + lines: [ + { + sku_code: 'SKU1', + sku_name: '草鱼', + unit: '斤', + before_sale_price: 10, + after_sale_price: 11.125, + change: 'updated', + status: 'pending', + }, + ], +}; + +beforeEach(() => { + H.ctx = ctxWith(['customer_manage', 'order_manage']); + H.enabled = true; + H.getPriceProposalDetail.mockReset(); + H.getPriceProposalDetail.mockResolvedValue(detail); +}); + +describe('GET /quote/price-proposals/:id(只读明细)', () => { + it('有查看权限 ⇒ 200,只把 { id, branchCode } 传给服务', async () => { + const res = await request(app).get(`/api/workflow/quote/price-proposals/${ID}`); + expect(res.status).toBe(200); + expect(res.body.data).toMatchObject({ id: ID, direction: 'to_delivery' }); + expect(res.body.data.lines[0]).toMatchObject({ sku_name: '草鱼', status: 'pending' }); + expect(H.getPriceProposalDetail).toHaveBeenCalledTimes(1); + expect(H.getPriceProposalDetail).toHaveBeenCalledWith({ id: ID, branchCode: 'BR002' }); + // body/query 里的花招不采信 + const args = H.getPriceProposalDetail.mock.calls[0][0] as Record; + expect(Object.keys(args).sort()).toEqual(['branchCode', 'id']); + }); + + it('只有 order_manage ⇒ 也可查看(与列表同权限)', async () => { + H.ctx = ctxWith(['order_manage']); + const res = await request(app).get(`/api/workflow/quote/price-proposals/${ID}`); + expect(res.status).toBe(200); + expect(H.getPriceProposalDetail).toHaveBeenCalledTimes(1); + }); + + it('无查看权限 ⇒ 403,服务零调用', async () => { + H.ctx = ctxWith([]); + const res = await request(app).get(`/api/workflow/quote/price-proposals/${ID}`); + expect(res.status).toBe(403); + expect(H.getPriceProposalDetail).not.toHaveBeenCalled(); + }); + + it('开关关闭 ⇒ 503 feature_disabled,服务零调用', async () => { + H.enabled = false; + const res = await request(app).get(`/api/workflow/quote/price-proposals/${ID}`); + expect(res.status).toBe(503); + expect(res.body.error).toBe('feature_disabled'); + expect(H.getPriceProposalDetail).not.toHaveBeenCalled(); + }); + + it('非法 id ⇒ 400 invalid_request,服务零调用', async () => { + const res = await request(app).get('/api/workflow/quote/price-proposals/not-a-uuid'); + expect(res.status).toBe(400); + expect(res.body.error).toBe('invalid_request'); + expect(H.getPriceProposalDetail).not.toHaveBeenCalled(); + }); + + it('缺分公司上下文 ⇒ 400 branch_required,服务零调用', async () => { + H.ctx = ctxWith(['customer_manage'], { branchCode: null }); + const res = await request(app).get(`/api/workflow/quote/price-proposals/${ID}`); + expect(res.status).toBe(400); + expect(res.body.error).toBe('branch_required'); + expect(H.getPriceProposalDetail).not.toHaveBeenCalled(); + }); + + it('提议不存在 / 不属于本分公司 ⇒ 404 not_found', async () => { + H.getPriceProposalDetail.mockResolvedValue(null); + const res = await request(app).get(`/api/workflow/quote/price-proposals/${ID}`); + expect(res.status).toBe(404); + expect(res.body.error).toBe('not_found'); + }); +}); diff --git a/src/i18n/locales/en/quotes.ts b/src/i18n/locales/en/quotes.ts index f202774..a6baf64 100644 --- a/src/i18n/locales/en/quotes.ts +++ b/src/i18n/locales/en/quotes.ts @@ -201,6 +201,12 @@ export const quotes: MessageDict = { 'priceProposal.col.unit': 'Unit', 'priceProposal.col.before': 'Before', 'priceProposal.col.after': 'After', + 'priceProposal.col.productName': 'Item name', + 'priceProposal.col.ourPrice': 'Our price', + 'priceProposal.col.suggestedPrice': 'Suggested price', + 'priceProposal.detailCount': '{n} item(s) in total', + 'priceProposal.detailLoading': 'Loading…', + 'priceProposal.detailLoadFail': 'Failed to load', 'priceProposal.expand': 'Expand', 'priceProposal.collapse': 'Collapse', 'priceProposal.title': 'Delivery sale price confirmation', diff --git a/src/i18n/locales/id/quotes.ts b/src/i18n/locales/id/quotes.ts index 8d77092..740482f 100644 --- a/src/i18n/locales/id/quotes.ts +++ b/src/i18n/locales/id/quotes.ts @@ -206,6 +206,12 @@ export const quotes: MessageDict = { 'priceProposal.col.unit': 'Satuan', 'priceProposal.col.before': 'Sebelum', 'priceProposal.col.after': 'Sesudah', + 'priceProposal.col.productName': 'Nama barang', + 'priceProposal.col.ourPrice': 'Harga kami', + 'priceProposal.col.suggestedPrice': 'Harga saran', + 'priceProposal.detailCount': 'Total {n} barang', + 'priceProposal.detailLoading': 'Memuat…', + 'priceProposal.detailLoadFail': 'Gagal memuat', 'priceProposal.expand': 'Buka', 'priceProposal.collapse': 'Tutup', 'priceProposal.title': 'Konfirmasi harga jual pengiriman', diff --git a/src/i18n/locales/zh-CN/quotes.ts b/src/i18n/locales/zh-CN/quotes.ts index acfb315..11bcbf4 100644 --- a/src/i18n/locales/zh-CN/quotes.ts +++ b/src/i18n/locales/zh-CN/quotes.ts @@ -197,6 +197,12 @@ export const quotes: MessageDict = { 'priceProposal.col.unit': '单位', 'priceProposal.col.before': '原价', 'priceProposal.col.after': '新价', + 'priceProposal.col.productName': '商品名', + 'priceProposal.col.ourPrice': '我方售价', + 'priceProposal.col.suggestedPrice': '建议售价', + 'priceProposal.detailCount': '共 {n} 条', + 'priceProposal.detailLoading': '加载中…', + 'priceProposal.detailLoadFail': '加载失败', 'priceProposal.expand': '展开', 'priceProposal.collapse': '收起', 'priceProposal.title': '配送商销售价确认', diff --git a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.detail.contract.test.ts b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.detail.contract.test.ts new file mode 100644 index 0000000..1748123 --- /dev/null +++ b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.detail.contract.test.ts @@ -0,0 +1,127 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +/** + * 「配送商销售价确认 → 展开我方提交待审记录」的**接线契约**(2026-10-19): + * · 后端新增只读端点 `GET /api/workflow/quote/price-proposals/:id`(仅查看权限、开关关 503、 + * 不存在 404),服务层按 `branch_code` 收口并补齐 A 方向明细行; + * · 前端 API 走 `preserveErrorBody` 新增 `getQuotePriceProposalApi`; + * · 面板展开 A 方向时按 id 取明细,渲染 `商品名 / 我方售价 / 建议售价 / 差额 / 状态`, + * 差额保留 4 位小数、44 行放进 `max-h-72 + overflow-y-auto` 容器并显示「共 N 条」; + * · 文案只用给定中文(en/id 直译)。 + * + * 渲染行为在 `QuoteDeliveryPriceProposalsPanel.detail.test.tsx`(jsdom)里验证,这里钉接线与文案。 + */ +const read = (relative: string) => readFileSync(new URL(relative, import.meta.url), 'utf8'); + +const panel = read('./QuoteDeliveryPriceProposalsPanel.tsx'); +const api = read('../../utils/workflowApi.ts'); +const routes = read('../../../server/src/modules/workflow/routes/quoteRoutes.ts'); +const service = read('../../../server/src/services/quotePriceProposalService.ts'); +const zh = read('../../i18n/locales/zh-CN/quotes.ts'); +const en = read('../../i18n/locales/en/quotes.ts'); +const idLocale = read('../../i18n/locales/id/quotes.ts'); + +describe('后端:按 proposal id 取明细(只读)', () => { + it('新增 GET /quote/price-proposals/:id,权限同列表,开关关 503、无分公司 400、不存在 404', () => { + const start = routes.indexOf("router.get('/quote/price-proposals/:id'"); + expect(start).toBeGreaterThan(-1); + const block = routes.slice(start, start + 1600); + expect(block).toContain('authMiddleware'); + expect(block).toContain("requireWorkflowPermission(ctx, ['customer_manage', 'order_manage'])"); + expect(block).toContain('getPriceProposalDetail'); + expect(block).toContain("error: 'feature_disabled'"); + expect(block).toContain("error: 'branch_required'"); + expect(block).toContain("error: 'not_found'"); + // 只读:这一段里不得出现会改库的服务调用 + expect(block).not.toContain('approvePriceProposal'); + expect(block).not.toContain('rejectPriceProposal'); + expect(block).not.toContain('submitPriceProposal'); + }); + + it('服务层按 id + 分公司取一条,按方向补 lines;A 方向行带「我方售价 / 建议售价 / 状态」', () => { + expect(service).toContain('export async function getPriceProposalDetail'); + expect(service).toContain('WHERE p.id = $1::uuid AND p.branch_code = $2'); + expect(service).toContain('async function attachOutgoingLines'); + expect(service).toContain('async function attachProposalLines'); + // 建议售价 = 提议价;我方售价 = 当前报价单明细价 + expect(service).toMatch(/after_sale_price: roundPrice\(item\.price\)/); + expect(service).toMatch(/before_sale_price: sheetRow \? readSheetPrice\(sheetRow\) : null/); + // 行状态沿用提议状态 + expect(service).toMatch(/status: row\.status/); + // 仅对 to_delivery 生效(不改变 B 方向的既有 lines 计算) + expect(service).toMatch(/rows\.filter\(\(row\) => row\.direction === 'to_delivery'\)/); + }); +}); + +describe('前端 API 契约', () => { + it('getQuotePriceProposalApi 调只读详情端点并透出后端原文', () => { + expect(api).toContain('export async function getQuotePriceProposalApi'); + expect(api).toContain('/quote/price-proposals/${encodeURIComponent(id)}'); + expect(api).toContain('preserveErrorBody: true'); + // lines DTO 增加行状态 + expect(api).toMatch(/status\?: 'pending' \| 'approved' \| 'rejected' \| 'cancelled' \| 'superseded'/); + }); +}); + +describe('面板:展开 A 方向时加载并渲染明细表', () => { + it('只在展开「我方提交」行时请求明细(B 方向沿用列表 lines)', () => { + expect(panel).toContain('getQuotePriceProposalApi'); + expect(panel).toMatch(/if \(willOpen && row\.direction !== 'from_delivery'\) void loadDetail\(row\.id\);/); + }); + + it('五列表头 + 共 N 条 + 加载中/加载失败文案', () => { + for (const key of [ + 'col.productName', + 'col.ourPrice', + 'col.suggestedPrice', + 'col.diff', + 'col.status', + ]) { + expect(panel).toContain(`t('quotes.priceProposal.${key}')`); + } + expect(panel).toContain("t('quotes.priceProposal.detailCount', { n: lines.length })"); + expect(panel).toContain("t('quotes.priceProposal.detailLoading')"); + expect(panel).toContain("t('quotes.priceProposal.detailLoadFail')"); + }); + + it('差额 = 建议 − 我方、保留 4 位小数、正负着色沿用既有风格', () => { + expect(panel).toContain('after - before'); + expect(panel).toContain('diff.toFixed(4)'); + expect(panel).toContain("diff > 0\n"); + // 与既有明细同一套颜色:涨红 / 跌绿 + expect(panel).toContain('text-red-600'); + expect(panel).toContain('text-emerald-600'); + }); + + it('44 行放进最大高度 + 纵向滚动容器(不撑爆弹窗)', () => { + expect(panel).toContain('data-testid="proposal-detail-scroll"'); + expect(panel).toContain('max-h-72'); + expect(panel).toContain('overflow-y-auto'); + }); +}); + +describe('i18n:只用给定中文,en/id 直译', () => { + it('zh-CN 六个新文案逐字一致', () => { + expect(zh).toContain("'priceProposal.col.productName': '商品名'"); + expect(zh).toContain("'priceProposal.col.ourPrice': '我方售价'"); + expect(zh).toContain("'priceProposal.col.suggestedPrice': '建议售价'"); + expect(zh).toContain("'priceProposal.detailCount': '共 {n} 条'"); + expect(zh).toContain("'priceProposal.detailLoading': '加载中…'"); + expect(zh).toContain("'priceProposal.detailLoadFail': '加载失败'"); + // 「差额 / 状态」复用既有 key,未另造文案 + expect(zh).toContain("'priceProposal.col.diff': '差额'"); + expect(zh).toContain("'priceProposal.col.status': '状态'"); + }); + + it('en / id 同步直译(同一组 key,无缺项)', () => { + for (const locale of [en, idLocale]) { + expect(locale).toContain("'priceProposal.col.productName':"); + expect(locale).toContain("'priceProposal.col.ourPrice':"); + expect(locale).toContain("'priceProposal.col.suggestedPrice':"); + expect(locale).toContain("'priceProposal.detailCount':"); + expect(locale).toContain("'priceProposal.detailLoading':"); + expect(locale).toContain("'priceProposal.detailLoadFail':"); + } + }); +}); diff --git a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.detail.test.tsx b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.detail.test.tsx new file mode 100644 index 0000000..c4984a8 --- /dev/null +++ b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.detail.test.tsx @@ -0,0 +1,241 @@ +// @vitest-environment jsdom +import React from 'react'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 「配送商销售价确认」展开行:**我方提交(A 方向)待审提议的商品明细**(2026-10-19)。 + * + * 背景:列表接口只给 B 方向(配送商发起)的 `lines`,A 方向只显示摘要(提交人/时间/44 个商品)。 + * 现在展开 A 方向时按 id 调只读明细接口,渲染 + * `商品名 / 我方售价 / 建议售价 / 差额 / 状态`,44 行放进最大高度 + 纵向滚动容器,并显示「共 N 条」。 + * + * 契约: + * · 展开 ⇒ 调 `getQuotePriceProposalApi(id)`,字段按行渲染,差额 = 建议 − 我方(4 位小数、正负着色); + * · 明细区有 `max-h-72 + overflow-y-auto` 滚动容器(不把弹窗撑爆); + * · 加载中 ⇒ 「加载中…」;失败 ⇒ 「加载失败」(摘要仍在,不白屏、不弹 toast); + * · 配送商发起行沿用列表 `lines`,**不**额外请求明细接口(不改既有审批面)。 + */ + +const listApi = vi.fn(); +const detailApi = vi.fn(); + +const notify = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() })); +vi.mock('../../utils/notify', () => ({ notify })); + +vi.mock('../../utils/workflowApi', () => ({ + listQuotePriceProposalsApi: (...args: unknown[]) => listApi(...args), + getQuotePriceProposalApi: (...args: unknown[]) => detailApi(...args), + approveQuotePriceProposalApi: vi.fn(), + rejectQuotePriceProposalApi: vi.fn(), +})); + +vi.mock('../../i18n', async () => { + const { quotes } = (await import('../../i18n/locales/zh-CN/quotes')) as unknown as { + quotes: Record; + }; + const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as { + common: Record; + }; + const dict: Record = {}; + 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) => { + 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 { QuoteDeliveryPriceProposalsPanel } from './QuoteDeliveryPriceProposalsPanel'; + +const LINES = Array.from({ length: 44 }, (_, index) => { + if (index === 0) { + return { + sku_code: 'SKU1', + sku_name: '草鱼', + unit: '斤', + before_sale_price: 10, + after_sale_price: 11.125, + change: 'updated' as const, + status: 'pending' as const, + }; + } + if (index === 1) { + return { + sku_code: 'SKU2', + sku_name: '鲤鱼', + unit: '袋', + before_sale_price: 10.1, + after_sale_price: 9.9, + change: 'updated' as const, + status: 'pending' as const, + }; + } + return { + sku_code: `SKU${index + 1}`, + sku_name: `商品${index + 1}`, + unit: '斤', + before_sale_price: 10, + after_sale_price: 10, + change: 'updated' as const, + status: 'pending' as const, + }; +}); + +/** 我方提交、待审、44 个商品:列表只给摘要(修复前展开只看得到「44 个商品」) */ +const OUTGOING = { + id: '22222222-2222-4222-8222-222222222222', + branch_code: 'BR002', + quote_sheet_code: 'QS2492200796033OTHER', + main_branch_code: 'BR002', + direction: 'to_delivery' as const, + items: LINES.map((line) => ({ sku_code: line.sku_code, unit: line.unit, price: line.after_sale_price })), + status: 'pending' as const, + reject_reason: null, + remote_proposal_id: 'remote-2', + requested_by_name: '张三', + requested_at: '2026-10-15T02:00:00.000Z', + reviewed_by_name: null, + reviewed_at: null, + applied_at: null, + waited_days: 3, +}; + +const INCOMING = { + id: '11111111-1111-4111-8111-111111111111', + branch_code: 'BR002', + quote_sheet_code: 'QS1792200796033LUTV', + main_branch_code: 'BR002', + direction: 'from_delivery' as const, + items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }], + status: 'pending' as const, + reject_reason: null, + remote_proposal_id: 'remote-1', + requested_by_name: '配送商甲', + requested_at: '2026-10-15T02:00:00.000Z', + reviewed_by_name: null, + reviewed_at: null, + applied_at: null, + waited_days: 3, + lines: [ + { + sku_code: 'SKU1', + sku_name: '草鱼', + unit: '斤', + before_sale_price: 10, + after_sale_price: 11, + change: 'updated' as const, + }, + ], +}; + +const expandButton = () => screen.getByRole('button', { name: '展开' }); + +beforeEach(() => { + listApi.mockReset(); + detailApi.mockReset(); + notify.error.mockReset(); + notify.success.mockReset(); + listApi.mockResolvedValue({ data: [OUTGOING], sync: null }); + detailApi.mockResolvedValue({ data: { ...OUTGOING, lines: LINES } }); +}); + +afterEach(() => { + cleanup(); +}); + +describe('我方提交待审提议 · 展开显示商品明细', () => { + it('展开 ⇒ 调只读明细接口,渲染 44 行「商品名 / 我方售价 / 建议售价 / 差额 / 状态」', async () => { + render(); + await screen.findByText('QS2492200796033OTHER'); + fireEvent.click(expandButton()); + + expect(await screen.findByText('草鱼')).toBeTruthy(); + expect(detailApi).toHaveBeenCalledTimes(1); + expect(detailApi).toHaveBeenCalledWith(OUTGOING.id); + + // 共 N 条 + 表头(只用给定中文文案) + expect(screen.getByText('共 44 条')).toBeTruthy(); + expect(screen.getByText('商品名')).toBeTruthy(); + expect(screen.getByText('我方售价')).toBeTruthy(); + expect(screen.getByText('建议售价')).toBeTruthy(); + expect(screen.getByText('差额')).toBeTruthy(); + + // 字段渲染:我方售价 / 建议售价(沿用面板既有 2 位小数格式) + expect(screen.getAllByText('10.00').length).toBeGreaterThan(1); + expect(screen.getByText('11.13')).toBeTruthy(); + expect(screen.getByText('10.10')).toBeTruthy(); + expect(screen.getByText('9.90')).toBeTruthy(); + + // 差额 = 建议 − 我方,保留 4 位小数,正负着色沿用页面既有风格 + const plus = screen.getByText('+1.1250'); + const minus = screen.getByText('-0.2000'); + expect(plus.className).toContain('text-red-600'); + expect(minus.className).toContain('text-emerald-600'); + + // 行状态(列表行状态还带「已等待」,明细行 44 条都是「待审」) + expect(screen.getAllByText('待审')).toHaveLength(44); + }); + + it('44 行明细放在最大高度 + 纵向滚动容器里(不撑爆弹窗)', async () => { + render(); + await screen.findByText('QS2492200796033OTHER'); + fireEvent.click(expandButton()); + + await screen.findByText('草鱼'); + const scroll = screen.getByTestId('proposal-detail-scroll'); + expect(scroll.className).toContain('max-h-72'); + expect(scroll.className).toContain('overflow-y-auto'); + // 44 行都在同一个滚动容器内(靠 max-height 裁切 + 滚动,而不是分页丢行) + expect(screen.getAllByTestId('proposal-detail-row')).toHaveLength(44); + expect(scroll.contains(screen.getAllByTestId('proposal-detail-row')[43])).toBe(true); + }); + + it('加载中 ⇒ 显示「加载中…」,返回后替换为明细表', async () => { + let resolveDetail: (value: unknown) => void = () => {}; + detailApi.mockImplementation( + () => + new Promise((resolve) => { + resolveDetail = resolve; + }) + ); + render(); + await screen.findByText('QS2492200796033OTHER'); + fireEvent.click(expandButton()); + + expect(await screen.findByText('加载中…')).toBeTruthy(); + resolveDetail({ data: { ...OUTGOING, lines: LINES } }); + expect(await screen.findByText('草鱼')).toBeTruthy(); + expect(screen.queryByText('加载中…')).toBeNull(); + }); + + it('明细接口失败 ⇒ 展开区显示「加载失败」,摘要仍在、不白屏、不弹 toast', async () => { + detailApi.mockRejectedValue(new Error('加载提议明细失败')); + render(); + await screen.findByText('QS2492200796033OTHER'); + fireEvent.click(expandButton()); + + expect(await screen.findByText('加载失败')).toBeTruthy(); + // 摘要(提交人/提交时间)没有被错误态吞掉 + expect(screen.getByText(/提交人/)).toBeTruthy(); + expect(screen.getByText(/张三/)).toBeTruthy(); + // 展开失败不该弹全局 toast(复用列表页的错误处理风格,只在本行显示) + expect(notify.error).not.toHaveBeenCalled(); + }); + + it('配送商发起行沿用列表 lines,不额外请求明细接口(既有审批面不变)', async () => { + listApi.mockResolvedValue({ data: [INCOMING], sync: null }); + render(); + await screen.findByText('QS1792200796033LUTV'); + fireEvent.click(expandButton()); + + expect(await screen.findByText('草鱼')).toBeTruthy(); + expect(screen.getByText('11.00')).toBeTruthy(); + expect(detailApi).not.toHaveBeenCalled(); + }); +}); diff --git a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx index 644673d..41fcbe3 100644 --- a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx +++ b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx @@ -4,6 +4,7 @@ import { notify } from '../../utils/notify'; import { useT } from '../../i18n'; import { approveQuotePriceProposalApi, + getQuotePriceProposalApi, listQuotePriceProposalsApi, rejectQuotePriceProposalApi, type QuotePriceProposalDto, @@ -132,7 +133,39 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC>({}); - const toggle = (id: string) => setExpanded((prev) => ({ ...prev, [id]: !prev[id] })); + /** + * 展开行明细:列表只给 B 方向(配送商发起)的 `lines`;A 方向(我方提交)按 id 现取。 + * 只读展示,失败只在展开区内显示「加载失败」,不弹 toast、不白屏。 + */ + const [details, setDetails] = useState< + Record + >({}); + + const loadDetail = useCallback( + async (id: string) => { + setDetails((prev) => ({ ...prev, [id]: { loading: true, error: null, data: null } })); + try { + const { data } = await getQuotePriceProposalApi(id); + setDetails((prev) => ({ ...prev, [id]: { loading: false, error: null, data: data || null } })); + } catch (error: any) { + setDetails((prev) => ({ + ...prev, + [id]: { + loading: false, + error: error?.message || t('quotes.priceProposal.detailLoadFail'), + data: null, + }, + })); + } + }, + [t] + ); + + const toggle = (row: QuotePriceProposalDto) => { + const willOpen = !expanded[row.id]; + setExpanded((prev) => ({ ...prev, [row.id]: willOpen })); + if (willOpen && row.direction !== 'from_delivery') void loadDetail(row.id); + }; return (
@@ -182,7 +215,7 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC