feat(审核): 支持逐行通过/驳回(部分同意)
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

用户要求:每行商品可单独驳回;部分同意 = 只处理选中的行。
- approve/reject 接 included_supplier_sku_codes:只处理选中行,其余保持待审
- 全部处理完才终态;有通过⇒已通过(被驳回行记 rejected_codes),全驳回⇒已驳回
- 明细行新增「驳回」按钮(按我方 SKU);通过/驳回都支持传选中行
- 测试:后端 34 passed、面板 7 passed
This commit is contained in:
Ubuntu
2026-10-19 14:22:38 +08:00
parent e5bd52de33
commit dd57b0286b
8 changed files with 227 additions and 11 deletions
@@ -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',
@@ -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<ApproveResult> {
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<string>();
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<LocalRow>(
`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<LocalRow>(
`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<RejectResult> {
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<string>();
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<string, unknown>;
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<LocalRow>(
`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<LocalRow>(
`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<LocalRow>(
`UPDATE quote_price_proposals
SET status = 'rejected', reject_reason = $2, reviewed_by = $3::uuid,
+1
View File
@@ -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}',
+1
View File
@@ -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}',
+1
View File
@@ -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}',
@@ -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('已驳回');
});
@@ -53,7 +53,7 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC<QuoteDeliveryPricePropos
const rows = direction ? allRows.filter((row) => row.direction === direction) : allRows;
const [loading, setLoading] = useState(false);
const [actingId, setActingId] = useState<string | null>(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<string | null>(null);
const [pickerQ, setPickerQ] = useState('');
@@ -162,7 +162,7 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC<QuoteDeliveryPricePropos
}
setActingId(rejecting.id);
try {
await rejectQuotePriceProposalApi(rejecting.id, reason);
await rejectQuotePriceProposalApi(rejecting.id, reason, rejecting.codes);
notify.success(t('quotes.priceProposal.rejected'));
setRejecting(null);
await load();
@@ -422,6 +422,21 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC<QuoteDeliveryPricePropos
{t('quotes.priceProposal.action.remap')}
</button>
) : null}
{canApprove && row.status === 'pending' && line.supplier_sku_code ? (
<button
type="button"
onClick={() =>
setRejecting({
id: row.id,
reason: '',
codes: [line.supplier_sku_code as string],
})
}
className="ml-1 rounded border border-red-300 px-1.5 py-0.5 text-[11px] text-red-600 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/30"
>
{t('quotes.priceProposal.action.rejectLine')}
</button>
) : null}
</>
)}
</td>
+61 -5
View File
@@ -91,6 +91,33 @@ async function workflowFetch<T>(
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<string, unknown>
): Promise<void> {
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<string, unknown>) {
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<string, unknown>);
if (!response.ok) {
return {
allowed: false,
@@ -2616,6 +2644,7 @@ export async function uploadFixedCostVoucherApi(file: File): Promise<string> {
});
// 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃
const payload = (await response.json().catch(() => ({}))) ?? {};
if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record<string, unknown>);
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<string> {
});
// 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃
const payload = (await response.json().catch(() => ({}))) ?? {};
if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record<string, unknown>);
if (!response.ok) {
throw new Error(payload?.error_description || payload?.error || '报告文件上传失败');
}
@@ -4319,6 +4372,7 @@ export async function uploadPickingOutboundPhotoApi(file: File): Promise<string>
});
// 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃
const payload = (await response.json().catch(() => ({}))) ?? {};
if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record<string, unknown>);
if (!response.ok) {
throw new Error(payload?.error_description || payload?.error || '照片上传失败');
}
@@ -4357,6 +4411,7 @@ export async function uploadInspectionPhotoFileApi(file: File): Promise<string>
});
// 401/错误体可能是 JSON null(如网关 401 无 envelope)——统一兜底成对象,避免读 payload.error 崩溃
const payload = (await response.json().catch(() => ({}))) ?? {};
if (response.status === 401) await throwIfUnauthorizedRaw(response, payload as Record<string, unknown>);
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<string, unknown>);
if (!response.ok || !payload?.path) {
// 错误文案由服务端给(error / error_description);兜底只回状态码,不新增前端文案
throw new Error(payload?.error_description || payload?.error || String(response.status));