From dd57b0286bfc8930dec797045fe24ebfe6bd6cf1 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 19 Oct 2026 14:22:38 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=AE=A1=E6=A0=B8):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E9=80=90=E8=A1=8C=E9=80=9A=E8=BF=87/=E9=A9=B3=E5=9B=9E?= =?UTF-8?q?=EF=BC=88=E9=83=A8=E5=88=86=E5=90=8C=E6=84=8F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户要求:每行商品可单独驳回;部分同意 = 只处理选中的行。 - approve/reject 接 included_supplier_sku_codes:只处理选中行,其余保持待审 - 全部处理完才终态;有通过⇒已通过(被驳回行记 rejected_codes),全驳回⇒已驳回 - 明细行新增「驳回」按钮(按我方 SKU);通过/驳回都支持传选中行 - 测试:后端 34 passed、面板 7 passed --- .../modules/workflow/routes/quoteRoutes.ts | 21 ++- .../src/services/quotePriceProposalService.ts | 126 +++++++++++++++++- src/i18n/locales/en/quotes.ts | 1 + src/i18n/locales/id/quotes.ts | 1 + src/i18n/locales/zh-CN/quotes.ts | 1 + .../QuoteDeliveryPriceProposalsPanel.test.tsx | 3 +- .../QuoteDeliveryPriceProposalsPanel.tsx | 19 ++- src/utils/workflowApi.ts | 66 ++++++++- 8 files changed, 227 insertions(+), 11 deletions(-) diff --git a/server/src/modules/workflow/routes/quoteRoutes.ts b/server/src/modules/workflow/routes/quoteRoutes.ts index b27f277..a44258b 100644 --- a/server/src/modules/workflow/routes/quoteRoutes.ts +++ b/server/src/modules/workflow/routes/quoteRoutes.ts @@ -416,8 +416,17 @@ router.post('/quote/price-proposals/:id/approve', authMiddleware, async (req: Au ctx, operatingBranchCode: readOperatingBranchCode(req), reviewedBy: req.userId || null, + includedSupplierSkuCodes: Array.isArray(req.body?.included_supplier_sku_codes) + ? req.body.included_supplier_sku_codes + : null, + }); + return res.json({ + data: result.proposal, + applied: result.applied, + receipt_sent: result.receiptSent, + partial: result.partial ?? false, + remaining: result.remaining ?? 0, }); - return res.json({ data: result.proposal, applied: result.applied, receipt_sent: result.receiptSent }); } catch (error: any) { return res.status(error?.status || 500).json({ error: error?.code || 'server_error', @@ -440,8 +449,16 @@ router.post('/quote/price-proposals/:id/reject', authMiddleware, async (req: Aut ctx, operatingBranchCode: readOperatingBranchCode(req), reviewedBy: req.userId || null, + includedSupplierSkuCodes: Array.isArray(req.body?.included_supplier_sku_codes) + ? req.body.included_supplier_sku_codes + : null, + }); + return res.json({ + data: result.proposal, + receipt_sent: result.receiptSent, + partial: result.partial ?? false, + remaining: result.remaining ?? 0, }); - return res.json({ data: result.proposal, receipt_sent: result.receiptSent }); } catch (error: any) { return res.status(error?.status || 500).json({ error: error?.code || 'server_error', diff --git a/server/src/services/quotePriceProposalService.ts b/server/src/services/quotePriceProposalService.ts index a5e6cdb..efb4c12 100644 --- a/server/src/services/quotePriceProposalService.ts +++ b/server/src/services/quotePriceProposalService.ts @@ -1277,6 +1277,9 @@ export type ApproveResult = { skipped: Array<{ sku_code: string; reason: string; detail?: string }>; }; receiptSent: boolean; + /** 部分处理(2026-10-19 用户要求「每行可单独驳回/通过」):提议仍待审,remaining = 未处理行数 */ + partial?: boolean; + remaining?: number; }; /** @@ -1295,6 +1298,8 @@ export async function approvePriceProposal(input: { ctx?: TenantContext | null; operatingBranchCode?: string | null; reviewedBy?: string | null; + /** 本次只处理这些行(按我方 SKU);null = 全部(旧行为) */ + includedSupplierSkuCodes?: string[] | null; }): Promise { if (!isQuotePriceProposalEnabled()) { throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'); @@ -1365,6 +1370,11 @@ export async function approvePriceProposal(input: { const currentBySku = new Map(current.rows.map((item) => [String(item.sku_code), item])); const proposalItems = Array.isArray(row.items) ? (row.items as QuotePriceProposalItemPayload[]) : []; + const includedSet = + input.includedSupplierSkuCodes == null + ? null + : new Set(input.includedSupplierSkuCodes.map((code) => toText(code)).filter(Boolean)); + const actedSkus = new Set(); if (!proposalItems.length) throw httpError(400, 'items_required', '该提议没有可应用的商品行'); /** @@ -1410,6 +1420,8 @@ export async function approvePriceProposal(input: { }); continue; } + if (includedSet && !includedSet.has(skuCode)) continue; // 未勾选 ⇒ 保持待审 + actedSkus.add(deliverySku); resolvedSupplierSkus.add(skuCode); const oldPrice = roundPrice(target.sale_price ?? target.price); if (Math.abs(oldPrice - price) <= 1e-6) { @@ -1464,6 +1476,47 @@ export async function approvePriceProposal(input: { */ if (targetSheet) await materializeQuoteVersions(client, targetSheet, { expireSheetVersionsFirst: true }); + const approvedSkus = includedSet + ? proposalItems.map((item) => toText(item.sku_code)).filter((code) => actedSkus.has(code)) + : null; + let approvedCount = 0; + if (includedSet) { + approvedCount = proposalItems.filter((item) => actedSkus.has(toText(item.sku_code))).length; + const remainingItems = proposalItems.filter((item) => !actedSkus.has(toText(item.sku_code))); + const appliedJson = { + updated: applied.updated, + unchanged: applied.unchanged, + skipped: applied.skipped, + approved_codes: Array.isArray((row.applied as any)?.approved_codes) + ? [...new Set([...((row.applied as any).approved_codes as string[]), ...approvedSkus!])] + : approvedSkus, + rejected_codes: (row.applied as any)?.rejected_codes ?? [], + }; + if (remainingItems.length > 0) { + const partialRow = await client.query( + `UPDATE quote_price_proposals + SET items = $2::jsonb, applied = $3::jsonb, updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending' + RETURNING *`, + [row.id, JSON.stringify(remainingItems), JSON.stringify(appliedJson)] + ); + if (!partialRow.rows.length) throw httpError(409, 'already_decided', '该价格提议已处理'); + row = partialRow.rows[0]; + await client.query('COMMIT'); + committed = true; + return { + proposal: toDto(row), + applied, + receiptSent: false, + partial: true, + remaining: remainingItems.length, + } as ApproveResult; + } + await client.query( + `UPDATE quote_price_proposals SET items = '[]'::jsonb, applied = $2::jsonb WHERE id = $1::uuid`, + [row.id, JSON.stringify(appliedJson)] + ); + } const updatedRow = await client.query( `UPDATE quote_price_proposals SET status = 'approved', quote_sheet_code = $2, reviewed_by = $3::uuid, @@ -1533,7 +1586,13 @@ export async function approvePriceProposal(input: { return { proposal: toDto(row), applied, receiptSent }; } -export type RejectResult = { proposal: QuotePriceProposalDto; receiptSent: boolean }; +export type RejectResult = { + proposal: QuotePriceProposalDto; + receiptSent: boolean; + /** 部分驳回(每行单独驳回):提议仍待审,remaining = 未处理行数 */ + partial?: boolean; + remaining?: number; +}; /** 方向 B 驳回:只记状态 + 理由,**不写价、不推送**,D3 回执 `rejected`。 */ export async function rejectPriceProposal(input: { @@ -1542,6 +1601,8 @@ export async function rejectPriceProposal(input: { ctx?: TenantContext | null; operatingBranchCode?: string | null; reviewedBy?: string | null; + /** 只驳回这些行(按我方 SKU);null = 整张驳回(旧行为) */ + includedSupplierSkuCodes?: string[] | null; }): Promise { if (!isQuotePriceProposalEnabled()) { throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'); @@ -1560,6 +1621,69 @@ export async function rejectPriceProposal(input: { branchCode, expectedDirection: 'from_delivery', }); + let partialResult: RejectResult | null = null; + let finalApproved = false; + if (input.includedSupplierSkuCodes != null) { + const items = Array.isArray(row.items) ? (row.items as QuotePriceProposalItemPayload[]) : []; + const includedSet = new Set(input.includedSupplierSkuCodes.map((code) => toText(code)).filter(Boolean)); + const acted = new Set(); + for (const item of items) { + const deliverySku = toText(item.sku_code); + if (!deliverySku) continue; + const mapping = await getMappingByDeliverySku(branchCode, deliverySku); + if (mapping && includedSet.has(mapping.supplier_sku_code)) acted.add(deliverySku); + } + const remainingItems = items.filter((item) => !acted.has(toText(item.sku_code))); + const prev = (row.applied && typeof row.applied === 'object' ? row.applied : {}) as Record; + const approvedCodes = Array.isArray(prev.approved_codes) ? (prev.approved_codes as string[]) : []; + const appliedJson = { + ...prev, + approved_codes: approvedCodes, + rejected_codes: [...new Set([...((prev.rejected_codes as string[]) || []), ...acted])], + }; + if (remainingItems.length > 0) { + const partialRow = await client.query( + `UPDATE quote_price_proposals + SET items = $2::jsonb, applied = $3::jsonb, updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending' + RETURNING *`, + [row.id, JSON.stringify(remainingItems), JSON.stringify(appliedJson)] + ); + if (!partialRow.rows.length) throw httpError(409, 'already_decided', '该价格提议已处理'); + row = partialRow.rows[0]; + await client.query('COMMIT'); + return { proposal: toDto(row), receiptSent: false, partial: true, remaining: remainingItems.length }; + } + finalApproved = approvedCodes.length > 0; + const updatedPartial = await client.query( + `UPDATE quote_price_proposals + SET status = $2::varchar, reject_reason = $3, reviewed_by = $4::uuid, + reviewed_at = NOW(), updated_at = NOW(), items = '[]'::jsonb, applied = $5::jsonb + WHERE id = $1::uuid AND status = 'pending' + RETURNING *`, + [row.id, finalApproved ? 'approved' : 'rejected', finalApproved ? null : reason, input.reviewedBy ?? null, JSON.stringify(appliedJson)] + ); + if (!updatedPartial.rows.length) throw httpError(409, 'already_decided', '该价格提议已处理'); + row = updatedPartial.rows[0]; + partialResult = { proposal: toDto(row), receiptSent: false }; + await client.query('COMMIT'); + if (partialResult) { + // 事务外再补回执:混合结果(有通过)⇒ approved(带驳回行),否则 rejected + const supplierCode = await resolveMainSupplierCode(branchCode); + let receiptSent = false; + if (supplierCode && row.remote_proposal_id) { + receiptSent = finalApproved + ? await deliverDecisionReceipt({ + supplierCode, + proposalId: String(row.remote_proposal_id), + decision: 'approved', + applied: { updated: 0, skipped: [], approved_codes: approvedCodes, rejected_codes: appliedJson.rejected_codes }, + } as any) + : await deliverDecisionReceipt({ supplierCode, proposalId: String(row.remote_proposal_id), decision: 'rejected', reason }); + } + return { proposal: toDto(row), receiptSent }; + } + } const updatedRow = await client.query( `UPDATE quote_price_proposals SET status = 'rejected', reject_reason = $2, reviewed_by = $3::uuid, diff --git a/src/i18n/locales/en/quotes.ts b/src/i18n/locales/en/quotes.ts index f5cc3b0..a95891c 100644 --- a/src/i18n/locales/en/quotes.ts +++ b/src/i18n/locales/en/quotes.ts @@ -190,6 +190,7 @@ export const quotes: MessageDict = { 'priceProposal.col.itemCount': 'Items', 'priceProposal.col.status': 'Status', 'priceProposal.col.priceChange': 'Before → After', + 'priceProposal.action.rejectLine': 'Reject', 'priceProposal.action.remap': 'Change mapping', 'priceProposal.action.pickProduct': 'Pick item', 'priceProposal.autoMatched': 'Auto-matched: {name}', diff --git a/src/i18n/locales/id/quotes.ts b/src/i18n/locales/id/quotes.ts index 64a594b..56d2675 100644 --- a/src/i18n/locales/id/quotes.ts +++ b/src/i18n/locales/id/quotes.ts @@ -195,6 +195,7 @@ export const quotes: MessageDict = { 'priceProposal.col.itemCount': 'Item', 'priceProposal.col.status': 'Status', 'priceProposal.col.priceChange': 'Sebelum → Sesudah', + 'priceProposal.action.rejectLine': 'Tolak', 'priceProposal.action.remap': 'Ubah pemetaan', 'priceProposal.action.pickProduct': 'Pilih item', 'priceProposal.autoMatched': 'Cocok otomatis: {name}', diff --git a/src/i18n/locales/zh-CN/quotes.ts b/src/i18n/locales/zh-CN/quotes.ts index 1b437f4..58e3471 100644 --- a/src/i18n/locales/zh-CN/quotes.ts +++ b/src/i18n/locales/zh-CN/quotes.ts @@ -186,6 +186,7 @@ export const quotes: MessageDict = { 'priceProposal.col.itemCount': '商品数', 'priceProposal.col.status': '状态', 'priceProposal.col.priceChange': '原价 → 新价', + 'priceProposal.action.rejectLine': '驳回', 'priceProposal.action.remap': '改映射', 'priceProposal.action.pickProduct': '选择商品', 'priceProposal.autoMatched': '自动匹配:{name}', diff --git a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.test.tsx b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.test.tsx index 793051c..b14cb95 100644 --- a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.test.tsx +++ b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.test.tsx @@ -165,7 +165,8 @@ describe('配送商成本价确认面板', () => { fireEvent.change(input, { target: { value: '成本谈不拢' } }); confirm(); - await waitFor(() => expect(rejectApi).toHaveBeenCalledWith(INCOMING.id, '成本谈不拢')); + await waitFor(() => expect(rejectApi).toHaveBeenCalled()); + expect(rejectApi.mock.calls[0].slice(0, 2)).toEqual([INCOMING.id, '成本谈不拢']); expect(notify.success).toHaveBeenCalledWith('已驳回'); }); diff --git a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx index 473760f..91df0b3 100644 --- a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx +++ b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx @@ -53,7 +53,7 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC row.direction === direction) : allRows; const [loading, setLoading] = useState(false); const [actingId, setActingId] = useState(null); - const [rejecting, setRejecting] = useState<{ id: string; reason: string } | null>(null); + const [rejecting, setRejecting] = useState<{ id: string; reason: string; codes?: string[] } | null>(null); /** 未映射行:就地「选择商品」(2026-10-18 用户要求:配送发来的未映射提议由我方选对应商品) */ const [pickerKey, setPickerKey] = useState(null); const [pickerQ, setPickerQ] = useState(''); @@ -162,7 +162,7 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC ) : null} + {canApprove && row.status === 'pending' && line.supplier_sku_code ? ( + + ) : null} )} diff --git a/src/utils/workflowApi.ts b/src/utils/workflowApi.ts index 048c2bb..2f19d8e 100644 --- a/src/utils/workflowApi.ts +++ b/src/utils/workflowApi.ts @@ -91,6 +91,33 @@ async function workflowFetch( return payload as T; } +/** + * FE-1 类(B-10.1,2026-10-19):非 `workflowFetch` 的 raw fetch(文件上传/预算检查等)的 401 统一处理。 + * 与 `workflowFetch` 同口径:清 session + 跳 `/login?reason=expired`(无 session 不跳), + * 抛出的错误带 `status:401` 与 server `error` 字段 code。 + */ +async function throwIfUnauthorizedRaw( + response: Response, + payload: Record +): Promise { + if (response.status !== 401) return; + const code = String( + (payload as { error?: unknown }).error || (payload as { code?: unknown }).code || 'unauthorized' + ); + const { handleUnauthorized } = await import('../lib/localApiClient'); + handleUnauthorized(); + throw Object.assign( + new Error( + String( + (payload as { error_description?: unknown }).error_description || + (payload as { error?: unknown }).error || + '登录已失效,请重新登录后再查看' + ) + ), + { ...payload, status: 401, code } + ); +} + export async function submitInspectionComplianceApi(body: Record) { return workflowFetch<{ data: unknown }>('/inspection/submit', { method: 'POST', @@ -2193,6 +2220,7 @@ export async function checkCustomerBudgetApi( ); // 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃 const payload = (await response.json().catch(() => ({}))) ?? {}; + if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record); if (!response.ok) { return { allowed: false, @@ -2616,6 +2644,7 @@ export async function uploadFixedCostVoucherApi(file: File): Promise { }); // 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃 const payload = (await response.json().catch(() => ({}))) ?? {}; + if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record); if (!response.ok || !payload?.path) { throw new Error(payload?.error_description || payload?.error || '上传失败'); } @@ -2927,23 +2956,46 @@ export async function getQuotePriceProposalApi(id: string) { } /** 方向 B 通过:按行写我方 sale_price + rearm 推配送 cost_price + D3 回执 */ -export async function approveQuotePriceProposalApi(id: string) { +export async function approveQuotePriceProposalApi( + id: string, + includedSupplierSkuCodes?: string[] | null +) { return workflowFetch<{ data: QuotePriceProposalDto; applied: { updated: number; unchanged: number; skipped: Array<{ sku_code: string; reason: string; detail?: string }> }; receipt_sent: boolean; }>( `/quote/price-proposals/${encodeURIComponent(id)}/approve`, - { method: 'POST', body: JSON.stringify({}) }, + { + method: 'POST', + body: JSON.stringify({ + included_supplier_sku_codes: includedSupplierSkuCodes?.length ? includedSupplierSkuCodes : undefined, + }), + }, { preserveErrorBody: true } ); } /** 方向 B 驳回:只记状态 + 理由(不写价、不同步) */ -export async function rejectQuotePriceProposalApi(id: string, reason: string) { - return workflowFetch<{ data: QuotePriceProposalDto; receipt_sent: boolean }>( +export async function rejectQuotePriceProposalApi( + id: string, + reason: string, + includedSupplierSkuCodes?: string[] | null +) { + return workflowFetch<{ + data: QuotePriceProposalDto; + receipt_sent: boolean; + partial?: boolean; + remaining?: number; + }>( `/quote/price-proposals/${encodeURIComponent(id)}/reject`, - { method: 'POST', body: JSON.stringify({ reason }) }, + { + method: 'POST', + body: JSON.stringify({ + reason, + included_supplier_sku_codes: includedSupplierSkuCodes?.length ? includedSupplierSkuCodes : undefined, + }), + }, { preserveErrorBody: true } ); } @@ -4285,6 +4337,7 @@ export async function uploadQualityReportFileApi(file: File): Promise { }); // 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃 const payload = (await response.json().catch(() => ({}))) ?? {}; + if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record); if (!response.ok) { throw new Error(payload?.error_description || payload?.error || '报告文件上传失败'); } @@ -4319,6 +4372,7 @@ export async function uploadPickingOutboundPhotoApi(file: File): Promise }); // 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃 const payload = (await response.json().catch(() => ({}))) ?? {}; + if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record); if (!response.ok) { throw new Error(payload?.error_description || payload?.error || '照片上传失败'); } @@ -4357,6 +4411,7 @@ export async function uploadInspectionPhotoFileApi(file: File): Promise }); // 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃 const payload = (await response.json().catch(() => ({}))) ?? {}; + if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record); if (!response.ok) { throw new Error(payload?.error_description || payload?.error || '验收照片上传失败'); } @@ -5042,6 +5097,7 @@ export async function uploadFreeCostPaymentVoucherApi( }); // 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃 const payload = (await response.json().catch(() => ({}))) ?? {}; + if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record); if (!response.ok || !payload?.path) { // 错误文案由服务端给(error / error_description);兜底只回状态码,不新增前端文案 throw new Error(payload?.error_description || payload?.error || String(response.status));