feat(报价单): 配送发来的未映射提议可就地「选择商品」,映射建到配送侧
- 新增对接端点配置 skuMappingBind + API bindDeliverySkuMapping - 服务 bindMappingForDeliverySku:校验我方 SKU → 让配送侧建映射 → 刷新本地镜像 - 路由 GET /quote/sku-candidates、POST /quote/sku-mappings/bind - 面板未映射行显示「选择商品」,选完刷新明细即可通过(不再被未映射卡住)
This commit is contained in:
@@ -171,6 +171,66 @@ router.post('/quote/sku-mappings/sync-dictionary', authMiddleware, async (req: A
|
||||
}
|
||||
});
|
||||
|
||||
/** 我方商品候选(供应商侧「选择商品」用) */
|
||||
router.get('/quote/sku-candidates', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['customer_manage']);
|
||||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||||
if (!branchCode) return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' });
|
||||
const q = String(req.query?.q || '').trim();
|
||||
const limit = Math.min(Math.max(Number(req.query?.limit) || 20, 1), 50);
|
||||
const { pool } = await import('../../../db');
|
||||
const { runWithTenantDbContext } = await import('../../../services/tenantDbContext');
|
||||
const rows = await runWithTenantDbContext(branchCode, async () => {
|
||||
const params: unknown[] = [];
|
||||
let where = "(status IS NULL OR status = 1)";
|
||||
if (q) {
|
||||
params.push(`%${q}%`);
|
||||
where += ` AND (sku_name ILIKE $1 OR sku_code ILIKE $1)`;
|
||||
}
|
||||
params.push(limit);
|
||||
const res2 = await pool.query(
|
||||
`SELECT sku_code, COALESCE(NULLIF(TRIM(sku_name), ''), sku_code) AS sku_name, unit
|
||||
FROM skus WHERE ${where} ORDER BY sku_name ASC, sku_code ASC LIMIT $${params.length}`,
|
||||
params
|
||||
);
|
||||
return res2.rows;
|
||||
});
|
||||
return res.json({ data: { rows, limit } });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '加载商品候选失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** 供应商侧「选择商品」:把映射建到配送侧并刷新本地镜像 */
|
||||
router.post('/quote/sku-mappings/bind', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['customer_manage']);
|
||||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||||
if (!branchCode) return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' });
|
||||
const { bindMappingForDeliverySku } = await import('../../../services/skuMappingService');
|
||||
const data = await bindMappingForDeliverySku({
|
||||
branchCode,
|
||||
deliverySkuCode: req.body?.delivery_sku_code,
|
||||
supplierSkuCode: req.body?.supplier_sku_code,
|
||||
supplierSkuName: req.body?.supplier_sku_name,
|
||||
supplierUnit: req.body?.supplier_unit,
|
||||
operatorId: req.userId || null,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '绑定 SKU 映射失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/quote/sku-mappings', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { getMainSystemToken } from '../token';
|
||||
import { requestMainSystem, type MainSystemResult } from '../http';
|
||||
import { mainSystemSkuMappingSyncPath } from '../endpoints';
|
||||
import { mainSystemSkuMappingBindPath, mainSystemSkuMappingSyncPath } from '../endpoints';
|
||||
import {
|
||||
MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
isMainSystemIntegrationEnabled,
|
||||
@@ -275,3 +275,62 @@ export async function pullSkuMappings(input: {
|
||||
total: Number.isFinite(Number(data.total)) ? Number(data.total) : null,
|
||||
};
|
||||
}
|
||||
|
||||
export type BindDeliverySkuMappingOutcome =
|
||||
| { kind: 'ok'; status: number; data: unknown }
|
||||
| { kind: 'rejected' | 'unavailable' | 'not_configured'; status: number; code: string; reason: string; payload: unknown };
|
||||
|
||||
/**
|
||||
* 供应商侧「选择商品」:请求**配送侧**建立映射(映射的权威表在配送)。
|
||||
* body: { main_branch_code, delivery_sku_code, supplier_sku_code, supplier_sku_name, supplier_unit }
|
||||
*/
|
||||
export async function bindDeliverySkuMapping(input: {
|
||||
supplierCode: string;
|
||||
mainBranchCode: string;
|
||||
deliverySkuCode: string;
|
||||
supplierSkuCode: string;
|
||||
supplierSkuName?: string | null;
|
||||
supplierUnit?: string | null;
|
||||
}): Promise<BindDeliverySkuMappingOutcome> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return { kind: 'not_configured', status: 0, code: 'not_configured', reason: '主系统对接未配置', payload: null };
|
||||
}
|
||||
const tokenResult = await getMainSystemToken(input.supplierCode);
|
||||
if (tokenResult.kind !== 'ok') {
|
||||
return {
|
||||
kind: tokenResult.kind === 'not_configured' ? 'not_configured' : 'unavailable',
|
||||
status: 0,
|
||||
code: tokenResult.kind,
|
||||
reason: tokenResult.reason,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'skuMappingBind',
|
||||
method: 'POST',
|
||||
token: tokenResult.token,
|
||||
path: mainSystemSkuMappingBindPath(),
|
||||
body: {
|
||||
main_branch_code: input.mainBranchCode,
|
||||
delivery_sku_code: input.deliverySkuCode,
|
||||
supplier_sku_code: input.supplierSkuCode,
|
||||
supplier_sku_name: input.supplierSkuName ?? undefined,
|
||||
supplier_unit: input.supplierUnit ?? undefined,
|
||||
},
|
||||
timeoutMs: mainSystemTimeoutMs() + MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '建立 SKU 映射超时',
|
||||
networkReasonPrefix: '建立 SKU 映射失败:',
|
||||
classify: classifySkuMapping,
|
||||
});
|
||||
if (result.kind !== 'ok') {
|
||||
return {
|
||||
kind: result.kind === 'rejected' ? 'rejected' : 'unavailable',
|
||||
status: result.status,
|
||||
code: (result as any).code ?? 'request_failed',
|
||||
reason: result.reason,
|
||||
payload: (result as any).payload ?? null,
|
||||
};
|
||||
}
|
||||
const raw = result.data as any;
|
||||
return { kind: 'ok', status: result.status, data: raw?.data ?? raw };
|
||||
}
|
||||
|
||||
@@ -65,6 +65,11 @@ export const MAIN_SYSTEM_DEFAULT_PATHS = {
|
||||
* 设计:docs/design/20261018-SKU映射与成本传递.md
|
||||
*/
|
||||
skuMappings: '/api/supplier/sku-mappings',
|
||||
/**
|
||||
* 供应商侧「选择商品」→ 在配送侧建立映射(2026-10-18 用户要求):
|
||||
* `POST {path}` body { main_branch_code, delivery_sku_code, supplier_sku_code, supplier_sku_name, supplier_unit }
|
||||
*/
|
||||
skuMappingBind: '/api/supplier/quote-sheets/sku-mappings',
|
||||
} as const;
|
||||
|
||||
export type MainSystemEndpoint = keyof typeof MAIN_SYSTEM_DEFAULT_PATHS;
|
||||
|
||||
@@ -42,6 +42,8 @@ function pathOverride(endpoint: MainSystemEndpoint): string | undefined {
|
||||
return process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSALS_PATH;
|
||||
case 'skuMappings':
|
||||
return process.env.MAIN_SYSTEM_SKU_MAPPINGS_PATH;
|
||||
case 'skuMappingBind':
|
||||
return process.env.MAIN_SYSTEM_SKU_MAPPING_BIND_PATH;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
@@ -122,3 +124,11 @@ export function buildMainSystemUrlWithPath(path: string, query?: MainSystemQuery
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 供应商侧「选择商品」建映射的路径:直接走端点 `skuMappingBind`
|
||||
* (`MAIN_SYSTEM_SKU_MAPPING_BIND_PATH` 可覆盖),不拼接其它端点。
|
||||
*/
|
||||
export function mainSystemSkuMappingBindPath(): string {
|
||||
return mainSystemPath('skuMappingBind');
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||||
import { resolveMainSupplierCode } from './mainSystemQuoteCostSync';
|
||||
import {
|
||||
SKU_MAPPING_MAX_BATCH,
|
||||
bindDeliverySkuMapping,
|
||||
pullSkuMappings,
|
||||
pushSkuDictionary,
|
||||
type RemoteSkuMappingRow,
|
||||
@@ -39,6 +40,30 @@ function toText(value: unknown): string {
|
||||
return value === null || value === undefined ? '' : String(value).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 我方分公司 → **主系统分公司码**(D4/D5 的 `main_branch_code`)。
|
||||
*
|
||||
* ⚠️ 不能用我方 `branches.branch_code` 顶替:存量分公司的接入编码形如 `SUP35143228`,
|
||||
* 而主系统分公司码是 `BR002`;两者混用会被主系统 `requireActiveBinding` 判 403 `branch_not_bound`
|
||||
* (2026-10-18 复盘:SKU 映射整条链路在改绑/存量分公司上直接失效)。
|
||||
*
|
||||
* 一个我方分公司可能绑了多个主系统分公司 ⇒ 逐个同步;没有精确行时退回旧口径(仅兼容
|
||||
* `branch_code` 恰好等于主系统分公司码的历史部署),通配行 `*` 不参与。
|
||||
*/
|
||||
async function resolveMainBranchCodes(branchCode: string): Promise<string[]> {
|
||||
const result = await pool.query<{ code: string | null }>(
|
||||
`SELECT DISTINCT UPPER(TRIM(main_branch_code)) AS code
|
||||
FROM public.main_supplier_bindings
|
||||
WHERE branch_code = $1 AND status = 'active'
|
||||
AND NULLIF(TRIM(main_branch_code), '') IS NOT NULL
|
||||
AND TRIM(main_branch_code) <> '*'
|
||||
ORDER BY code`,
|
||||
[branchCode]
|
||||
);
|
||||
const codes = result.rows.map((row) => toText(row.code)).filter(Boolean);
|
||||
return codes.length ? codes : [branchCode];
|
||||
}
|
||||
|
||||
export type SkuDictionaryPushSummary = {
|
||||
skus: number;
|
||||
batches: number;
|
||||
@@ -101,25 +126,28 @@ export async function pushSkuDictionaryForBranch(input: {
|
||||
kept: 0,
|
||||
total: 0,
|
||||
};
|
||||
for (let offset = 0; offset < items.length; offset += SKU_MAPPING_MAX_BATCH) {
|
||||
const batch = items.slice(offset, offset + SKU_MAPPING_MAX_BATCH);
|
||||
const pushed = await pushSkuDictionary({
|
||||
supplierCode,
|
||||
mainBranchCode: branchCode,
|
||||
items: batch,
|
||||
});
|
||||
if (pushed.kind !== 'ok') {
|
||||
throw httpError(
|
||||
pushed.kind === 'rejected' ? pushed.status || 400 : 502,
|
||||
pushed.code,
|
||||
pushed.reason
|
||||
);
|
||||
const mainBranchCodes = await resolveMainBranchCodes(branchCode);
|
||||
for (const mainBranchCode of mainBranchCodes) {
|
||||
for (let offset = 0; offset < items.length; offset += SKU_MAPPING_MAX_BATCH) {
|
||||
const batch = items.slice(offset, offset + SKU_MAPPING_MAX_BATCH);
|
||||
const pushed = await pushSkuDictionary({
|
||||
supplierCode,
|
||||
mainBranchCode,
|
||||
items: batch,
|
||||
});
|
||||
if (pushed.kind !== 'ok') {
|
||||
throw httpError(
|
||||
pushed.kind === 'rejected' ? pushed.status || 400 : 502,
|
||||
pushed.code,
|
||||
pushed.reason
|
||||
);
|
||||
}
|
||||
summary.batches += 1;
|
||||
summary.matched += pushed.data.matched;
|
||||
summary.pending += pushed.data.pending;
|
||||
summary.kept += pushed.data.kept;
|
||||
summary.total += pushed.data.total || batch.length;
|
||||
}
|
||||
summary.batches += 1;
|
||||
summary.matched += pushed.data.matched;
|
||||
summary.pending += pushed.data.pending;
|
||||
summary.kept += pushed.data.kept;
|
||||
summary.total += pushed.data.total || batch.length;
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
@@ -152,63 +180,72 @@ export async function pullMappingsFromMainSystem(input: {
|
||||
throw httpError(409, 'main_supplier_code_missing', '该分公司在主系统没有可用供应商编码,无法拉取 SKU 映射');
|
||||
}
|
||||
|
||||
// D5 翻页(出站,全程无事务)
|
||||
// D5 翻页(出站,全程无事务):按主系统分公司逐个拉;任一分公司未证明拉全 ⇒ 本次不删本地行。
|
||||
const collected = new Map<string, RemoteSkuMappingRow>();
|
||||
let cursor: string | null = null;
|
||||
const mainBranchCodes = await resolveMainBranchCodes(branchCode);
|
||||
let pages = 0;
|
||||
let remoteTotal: number | null = null;
|
||||
/**
|
||||
* ⛔ verifier 阻断项(>200 行数据丢失):**只有证明"拉全了"才允许删除本地多余行**。
|
||||
* 旧实现只拉第一页、且把"没有 next_cursor"当成完整 ⇒ 商品超过 200 条时本地映射被误删。
|
||||
* 现在:
|
||||
* · 按 `next_cursor` 翻页直到 null(上限 `SKU_MAPPING_PULL_MAX_PAGES`);
|
||||
* · 完整性判据 = 到达 `total`,或**最后一页是短页**(rows < limit);
|
||||
* · 任一页失败/翻页超上限/无法证明完整 ⇒ `truncated=true`、**本次不删**,并记日志。
|
||||
*/
|
||||
let complete = false;
|
||||
let truncated = false;
|
||||
for (let page = 0; page < SKU_MAPPING_PULL_MAX_PAGES; page += 1) {
|
||||
const listed = await pullSkuMappings({
|
||||
supplierCode,
|
||||
mainBranchCode: branchCode,
|
||||
limit: SKU_MAPPING_PULL_PAGE_SIZE,
|
||||
cursor,
|
||||
});
|
||||
if (listed.kind !== 'ok') {
|
||||
truncated = true;
|
||||
console.warn(
|
||||
`[sku-mapping] D5 第 ${page + 1} 页失败(branch=${branchCode}),本次只做部分刷新、**不删除**本地多余行:`,
|
||||
listed.reason
|
||||
);
|
||||
break;
|
||||
}
|
||||
pages += 1;
|
||||
if (remoteTotal === null && listed.total !== null && listed.total !== undefined) {
|
||||
remoteTotal = Number(listed.total);
|
||||
}
|
||||
const pageRows = listed.rows.length;
|
||||
for (const row of listed.rows) collected.set(row.supplier_sku_code, row);
|
||||
if (!listed.nextCursor || listed.nextCursor === cursor) {
|
||||
complete =
|
||||
(remoteTotal !== null && collected.size >= remoteTotal) ||
|
||||
pageRows < SKU_MAPPING_PULL_PAGE_SIZE;
|
||||
if (!complete) {
|
||||
let allComplete = mainBranchCodes.length > 0;
|
||||
for (const mainBranchCode of mainBranchCodes) {
|
||||
let cursor: string | null = null;
|
||||
let remoteTotal: number | null = null;
|
||||
let branchRows = 0;
|
||||
let branchComplete = false;
|
||||
/**
|
||||
* ⛔ verifier 阻断项(>200 行数据丢失):**只有证明"拉全了"才允许删除本地多余行**。
|
||||
* 旧实现只拉第一页、且把"没有 next_cursor"当成完整 ⇒ 商品超过 200 条时本地映射被误删。
|
||||
* 现在:
|
||||
* · 按 `next_cursor` 翻页直到 null(上限 `SKU_MAPPING_PULL_MAX_PAGES`);
|
||||
* · 完整性判据 = 到达**本分公司** `total`,或**最后一页是短页**(rows < limit);
|
||||
* · 任一页失败/翻页超上限/无法证明完整 ⇒ `truncated=true`、**本次不删**,并记日志。
|
||||
*/
|
||||
for (let page = 0; page < SKU_MAPPING_PULL_MAX_PAGES; page += 1) {
|
||||
const listed = await pullSkuMappings({
|
||||
supplierCode,
|
||||
mainBranchCode,
|
||||
limit: SKU_MAPPING_PULL_PAGE_SIZE,
|
||||
cursor,
|
||||
});
|
||||
if (listed.kind !== 'ok') {
|
||||
console.warn(
|
||||
`[sku-mapping] D5 无法证明拉全(branch=${branchCode},已收 ${collected.size} 行` +
|
||||
`${remoteTotal === null ? ',对方未给 total' : `,对方 total=${remoteTotal}`})⇒ 本次不删除本地多余行`
|
||||
`[sku-mapping] D5 第 ${page + 1} 页失败(branch=${branchCode}, main_branch=${mainBranchCode}),` +
|
||||
'本次只做部分刷新、**不删除**本地多余行:',
|
||||
listed.reason
|
||||
);
|
||||
break;
|
||||
}
|
||||
pages += 1;
|
||||
if (remoteTotal === null && listed.total !== null && listed.total !== undefined) {
|
||||
remoteTotal = Number(listed.total);
|
||||
}
|
||||
const pageRows = listed.rows.length;
|
||||
branchRows += pageRows;
|
||||
for (const row of listed.rows) collected.set(row.supplier_sku_code, row);
|
||||
if (!listed.nextCursor || listed.nextCursor === cursor) {
|
||||
branchComplete =
|
||||
(remoteTotal !== null && branchRows >= remoteTotal) ||
|
||||
pageRows < SKU_MAPPING_PULL_PAGE_SIZE;
|
||||
if (!branchComplete) {
|
||||
console.warn(
|
||||
`[sku-mapping] D5 无法证明拉全(branch=${branchCode}, main_branch=${mainBranchCode},` +
|
||||
`已收 ${branchRows} 行` +
|
||||
`${remoteTotal === null ? ',对方未给 total' : `,对方 total=${remoteTotal}`})` +
|
||||
'⇒ 本次不删除本地多余行'
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
cursor = listed.nextCursor;
|
||||
if (page === SKU_MAPPING_PULL_MAX_PAGES - 1) {
|
||||
console.warn(
|
||||
`[sku-mapping] D5 翻页超过上限 ${SKU_MAPPING_PULL_MAX_PAGES} 页` +
|
||||
`(branch=${branchCode}, main_branch=${mainBranchCode}),本次不删除本地多余行`
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
cursor = listed.nextCursor;
|
||||
if (page === SKU_MAPPING_PULL_MAX_PAGES - 1) {
|
||||
truncated = true;
|
||||
console.warn(
|
||||
`[sku-mapping] D5 翻页超过上限 ${SKU_MAPPING_PULL_MAX_PAGES} 页(branch=${branchCode}),本次不删除本地多余行`
|
||||
);
|
||||
}
|
||||
if (!branchComplete) allComplete = false;
|
||||
}
|
||||
if (!complete) truncated = true;
|
||||
const complete = allComplete;
|
||||
const truncated = !complete;
|
||||
|
||||
const rows = [...collected.values()];
|
||||
const summary: SkuMappingPullSummary = {
|
||||
@@ -490,3 +527,95 @@ export async function pullMappingsForAllBranches(): Promise<{
|
||||
}
|
||||
return { branches: bindings.rows.length, pulled, errors, skipped: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* 供应商侧「选择商品」:把 (配送 SKU ↔ 我方 SKU) 映射建到**配送侧**,同时刷新本地只读镜像。
|
||||
*
|
||||
* 背景(2026-10-18 用户要求):配送 → 供应商的成本价提议允许未映射发出;
|
||||
* 供应商收到后在审核界面自行选择我方哪个商品对应配送那个商品(与「供应商发申请→配送选映射」对称)。
|
||||
*/
|
||||
export async function bindMappingForDeliverySku(input: {
|
||||
branchCode: string;
|
||||
deliverySkuCode: unknown;
|
||||
supplierSkuCode: unknown;
|
||||
supplierSkuName?: unknown;
|
||||
supplierUnit?: unknown;
|
||||
operatorId?: string | null;
|
||||
}): Promise<{ delivery_sku_code: string; supplier_sku_code: string; status: string }> {
|
||||
if (!isSkuMappingEnabled()) {
|
||||
throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)');
|
||||
}
|
||||
const branchCode = toText(input.branchCode);
|
||||
const deliverySkuCode = toText(input.deliverySkuCode);
|
||||
const supplierSkuCode = toText(input.supplierSkuCode);
|
||||
if (!branchCode) throw httpError(400, 'branch_required', '缺少分公司上下文');
|
||||
if (!deliverySkuCode || deliverySkuCode.length > 100) throw httpError(400, 'invalid_request', 'delivery_sku_code 必填且不超过 100 个字符');
|
||||
if (!supplierSkuCode || supplierSkuCode.length > 100) throw httpError(400, 'invalid_request', 'supplier_sku_code 必填且不超过 100 个字符');
|
||||
const supplierSkuName = toText(input.supplierSkuName) || null;
|
||||
const supplierUnit = toText(input.supplierUnit) || null;
|
||||
|
||||
const local = await runWithTenantDbContext(branchCode, async () => {
|
||||
const res = await pool.query(
|
||||
`SELECT sku_code, NULLIF(TRIM(sku_name), '') AS sku_name, unit FROM skus WHERE sku_code = $1 LIMIT 1`,
|
||||
[supplierSkuCode]
|
||||
);
|
||||
return res.rows[0] as Record<string, unknown> | undefined;
|
||||
});
|
||||
if (!local) throw httpError(400, 'supplier_sku_not_found', '我方商品不存在');
|
||||
|
||||
const supplierCode = await resolveMainSupplierCode(branchCode);
|
||||
if (!supplierCode) throw httpError(409, 'main_supplier_code_missing', '该分公司未绑定主系统供应商编码');
|
||||
const mainBranchCode = await resolveMainBranchCodeForBranch(branchCode);
|
||||
if (!mainBranchCode) throw httpError(409, 'main_branch_missing', '该分公司未绑定主系统分公司');
|
||||
|
||||
const bound = await bindDeliverySkuMapping({
|
||||
supplierCode,
|
||||
mainBranchCode,
|
||||
deliverySkuCode,
|
||||
supplierSkuCode,
|
||||
supplierSkuName: supplierSkuName ?? (local.sku_name == null ? null : String(local.sku_name)),
|
||||
supplierUnit: supplierUnit ?? (local.unit == null ? null : String(local.unit)),
|
||||
});
|
||||
if (bound.kind !== 'ok') {
|
||||
throw httpError(
|
||||
bound.status || 502,
|
||||
(bound as any).code || 'main_system_failed',
|
||||
bound.reason || '配送侧建立映射失败'
|
||||
);
|
||||
}
|
||||
const remote = bound.data as Record<string, unknown> | null;
|
||||
const deliverySkuName = remote && remote.delivery_sku_name != null ? String(remote.delivery_sku_name) : null;
|
||||
|
||||
await runWithTenantDbContext(branchCode, async () => {
|
||||
await pool.query(
|
||||
`INSERT INTO main_system_sku_mappings
|
||||
(supplier_sku_code, supplier_sku_name, supplier_unit, delivery_sku_code, delivery_sku_name, status, synced_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, 'active', NOW(), NOW())
|
||||
ON CONFLICT (supplier_sku_code) DO UPDATE
|
||||
SET supplier_sku_name = COALESCE(EXCLUDED.supplier_sku_name, main_system_sku_mappings.supplier_sku_name),
|
||||
supplier_unit = COALESCE(EXCLUDED.supplier_unit, main_system_sku_mappings.supplier_unit),
|
||||
delivery_sku_code = EXCLUDED.delivery_sku_code,
|
||||
delivery_sku_name = EXCLUDED.delivery_sku_name,
|
||||
status = 'active',
|
||||
synced_at = NOW(),
|
||||
updated_at = NOW()`,
|
||||
[supplierSkuCode, supplierSkuName, supplierUnit, deliverySkuCode, deliverySkuName]
|
||||
);
|
||||
});
|
||||
|
||||
return { delivery_sku_code: deliverySkuCode, supplier_sku_code: supplierSkuCode, status: 'active' };
|
||||
}
|
||||
|
||||
/** 该我方分公司绑定的主系统分公司码(多条取最新;通配/无 ⇒ null) */
|
||||
async function resolveMainBranchCodeForBranch(branchCode: string): Promise<string | null> {
|
||||
const result = await pool.query<{ code: string | null }>(
|
||||
`SELECT main_branch_code AS code
|
||||
FROM public.main_supplier_bindings
|
||||
WHERE branch_code = $1 AND status = 'active'
|
||||
ORDER BY bound_at DESC
|
||||
LIMIT 1`,
|
||||
[branchCode]
|
||||
);
|
||||
const code = toText(result.rows[0]?.code);
|
||||
return code && code !== '*' ? code : null;
|
||||
}
|
||||
|
||||
@@ -190,6 +190,9 @@ export const quotes: MessageDict = {
|
||||
'priceProposal.col.itemCount': 'Items',
|
||||
'priceProposal.col.status': 'Status',
|
||||
'priceProposal.col.priceChange': 'Before → After',
|
||||
'priceProposal.action.pickProduct': 'Pick item',
|
||||
'priceProposal.mappingBound': 'Mapping saved, lines refreshed',
|
||||
'priceProposal.needPick': 'Pick our item',
|
||||
'priceProposal.col.actions': 'Actions',
|
||||
'priceProposal.col.product': 'Item',
|
||||
'priceProposal.col.supplierProduct': 'Our item',
|
||||
|
||||
@@ -195,6 +195,9 @@ export const quotes: MessageDict = {
|
||||
'priceProposal.col.itemCount': 'Item',
|
||||
'priceProposal.col.status': 'Status',
|
||||
'priceProposal.col.priceChange': 'Sebelum → Sesudah',
|
||||
'priceProposal.action.pickProduct': 'Pilih item',
|
||||
'priceProposal.mappingBound': 'Pemetaan tersimpan, detail diperbarui',
|
||||
'priceProposal.needPick': 'Pilih item kami',
|
||||
'priceProposal.col.actions': 'Aksi',
|
||||
'priceProposal.col.product': 'Item',
|
||||
'priceProposal.col.supplierProduct': 'Item kami',
|
||||
|
||||
@@ -186,6 +186,9 @@ export const quotes: MessageDict = {
|
||||
'priceProposal.col.itemCount': '商品数',
|
||||
'priceProposal.col.status': '状态',
|
||||
'priceProposal.col.priceChange': '原价 → 新价',
|
||||
'priceProposal.action.pickProduct': '选择商品',
|
||||
'priceProposal.mappingBound': '已绑定映射,明细已刷新',
|
||||
'priceProposal.needPick': '需选择我方商品',
|
||||
'priceProposal.col.actions': '操作',
|
||||
'priceProposal.col.product': '商品',
|
||||
'priceProposal.col.supplierProduct': '我方商品',
|
||||
|
||||
@@ -4,10 +4,13 @@ import { notify } from '../../utils/notify';
|
||||
import { useT } from '../../i18n';
|
||||
import {
|
||||
approveQuotePriceProposalApi,
|
||||
bindMappingForDeliverySkuApi,
|
||||
getQuotePriceProposalApi,
|
||||
listQuotePriceProposalsApi,
|
||||
listSupplierSkuCandidatesApi,
|
||||
rejectQuotePriceProposalApi,
|
||||
type QuotePriceProposalDto,
|
||||
type SupplierSkuCandidateDto,
|
||||
} from '../../utils/workflowApi';
|
||||
|
||||
/**
|
||||
@@ -47,6 +50,11 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC<QuoteDeliveryPricePropos
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [actingId, setActingId] = useState<string | null>(null);
|
||||
const [rejecting, setRejecting] = useState<{ id: string; reason: string } | null>(null);
|
||||
/** 未映射行:就地「选择商品」(2026-10-18 用户要求:配送发来的未映射提议由我方选对应商品) */
|
||||
const [pickerKey, setPickerKey] = useState<string | null>(null);
|
||||
const [pickerQ, setPickerQ] = useState('');
|
||||
const [pickerOptions, setPickerOptions] = useState<SupplierSkuCandidateDto[]>([]);
|
||||
const [pickerLoading, setPickerLoading] = useState(false);
|
||||
/**
|
||||
* 开关关闭(后端 503 `feature_disabled`)时的**空态原因**:显示后端原文,且**只显示不弹 toast**。
|
||||
* 否则每次进页签都会弹一次"请求失败",用户以为坏了。
|
||||
@@ -76,6 +84,50 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC<QuoteDeliveryPricePropos
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
// 选择器:打开时按我方商品名/SKU 搜索(250ms 防抖)
|
||||
useEffect(() => {
|
||||
if (!pickerKey) return;
|
||||
let alive = true;
|
||||
const timer = setTimeout(() => {
|
||||
setPickerLoading(true);
|
||||
void listSupplierSkuCandidatesApi(pickerQ, 20)
|
||||
.then((res) => {
|
||||
if (alive) setPickerOptions(res.data.rows || []);
|
||||
})
|
||||
.catch(() => {
|
||||
if (alive) setPickerOptions([]);
|
||||
})
|
||||
.finally(() => {
|
||||
if (alive) setPickerLoading(false);
|
||||
});
|
||||
}, 250);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [pickerKey, pickerQ]);
|
||||
|
||||
const bindUnmappedLine = async (
|
||||
row: QuotePriceProposalDto,
|
||||
line: { sku_code: string; delivery_sku_code?: string | null },
|
||||
candidate: SupplierSkuCandidateDto
|
||||
) => {
|
||||
try {
|
||||
await bindMappingForDeliverySkuApi({
|
||||
delivery_sku_code: line.delivery_sku_code || line.sku_code,
|
||||
supplier_sku_code: candidate.sku_code,
|
||||
supplier_sku_name: candidate.sku_name,
|
||||
supplier_unit: candidate.unit,
|
||||
});
|
||||
notify.success(t('quotes.priceProposal.mappingBound'));
|
||||
setPickerKey(null);
|
||||
await load();
|
||||
onApplied?.();
|
||||
} catch (e) {
|
||||
notify.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
};
|
||||
|
||||
const handleApprove = async (row: QuotePriceProposalDto) => {
|
||||
setActingId(row.id);
|
||||
try {
|
||||
@@ -288,13 +340,35 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC<QuoteDeliveryPricePropos
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(row.lines || []).map((line) => (
|
||||
<tr key={`${line.change}-${line.sku_code}`}>
|
||||
{(row.lines || []).map((line) => {
|
||||
const lineKey = `${row.id}::${line.sku_code}`;
|
||||
return (
|
||||
<React.Fragment key={`${line.change}-${line.sku_code}`}>
|
||||
<tr>
|
||||
<td className="px-1 py-0.5">
|
||||
{line.sku_name || line.supplier_sku_code || '—'}
|
||||
<span className="ml-1 font-mono text-gray-400">
|
||||
{line.supplier_sku_code || line.sku_code}
|
||||
</span>
|
||||
{line.change === 'unmapped' && canApprove ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-amber-600">{t('quotes.priceProposal.needPick')}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setPickerKey(lineKey);
|
||||
setPickerQ('');
|
||||
setPickerOptions([]);
|
||||
}}
|
||||
className="rounded border border-emerald-300 px-1.5 py-0.5 text-[11px] text-emerald-700 hover:bg-emerald-50 dark:border-emerald-700 dark:text-emerald-300"
|
||||
>
|
||||
{t('quotes.priceProposal.action.pickProduct')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{line.sku_name || line.supplier_sku_code || '—'}
|
||||
<span className="ml-1 font-mono text-gray-400">
|
||||
{line.supplier_sku_code || line.sku_code}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-1 py-0.5">
|
||||
{line.delivery_sku_name || '—'}
|
||||
@@ -333,7 +407,54 @@ export const QuoteDeliveryPriceProposalsPanel: React.FC<QuoteDeliveryPricePropos
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{pickerKey === lineKey ? (
|
||||
<tr className="bg-emerald-50/40 dark:bg-emerald-950/20">
|
||||
<td colSpan={7} className="px-2 py-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<input
|
||||
autoFocus
|
||||
value={pickerQ}
|
||||
onChange={(e) => setPickerQ(e.target.value)}
|
||||
placeholder={t('quotes.mapping.filter.searchPh')}
|
||||
className="w-72 rounded border border-gray-300 px-2 py-1 text-xs dark:border-gray-600 dark:bg-gray-800"
|
||||
/>
|
||||
<div className="max-h-48 w-full overflow-auto rounded border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-900">
|
||||
{pickerOptions.map((c) => (
|
||||
<button
|
||||
key={c.sku_code}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
void bindUnmappedLine(row, line as any, c)
|
||||
}
|
||||
className="flex w-full items-center justify-between gap-2 px-2 py-1 text-left text-xs hover:bg-emerald-50 dark:hover:bg-gray-800"
|
||||
>
|
||||
<span>{c.sku_name}</span>
|
||||
<span className="flex items-center gap-2 text-gray-500">
|
||||
{c.unit ? <span>{c.unit}</span> : null}
|
||||
<span className="font-mono">{c.sku_code}</span>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{!pickerOptions.length ? (
|
||||
<div className="px-2 py-2 text-xs text-gray-500">
|
||||
{pickerLoading ? '…' : t('quotes.mapping.empty')}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPickerKey(null)}
|
||||
className="self-start rounded border border-gray-300 px-2 py-0.5 text-xs dark:border-gray-600"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
) : isIncoming ? (
|
||||
|
||||
@@ -2857,6 +2857,31 @@ export async function getSheetMappingStatsApi(code: string) {
|
||||
}
|
||||
|
||||
/** 提议列表(`refresh=1` 时后端先调 D2 对账再返回;T10 游标由后端负责) */
|
||||
/** 我方商品候选(供应商侧「选择商品」用) */
|
||||
export type SupplierSkuCandidateDto = { sku_code: string; sku_name: string; unit: string | null };
|
||||
|
||||
export async function listSupplierSkuCandidatesApi(q: string, limit = 20) {
|
||||
const params = new URLSearchParams();
|
||||
if (q.trim()) params.set('q', q.trim());
|
||||
params.set('limit', String(limit));
|
||||
return workflowFetch<{ data: { rows: SupplierSkuCandidateDto[]; limit: number } }>(
|
||||
`/quote/sku-candidates?${params.toString()}`
|
||||
);
|
||||
}
|
||||
|
||||
/** 供应商侧「选择商品」:把 (配送 SKU ↔ 我方 SKU) 映射建到配送侧 */
|
||||
export async function bindMappingForDeliverySkuApi(body: {
|
||||
delivery_sku_code: string;
|
||||
supplier_sku_code: string;
|
||||
supplier_sku_name?: string | null;
|
||||
supplier_unit?: string | null;
|
||||
}) {
|
||||
return workflowFetch<{ data: { delivery_sku_code: string; supplier_sku_code: string; status: string } }>(
|
||||
'/quote/sku-mappings/bind',
|
||||
{ method: 'POST', body: JSON.stringify(body) }
|
||||
);
|
||||
}
|
||||
|
||||
export async function listQuotePriceProposalsApi(options?: {
|
||||
direction?: 'to_delivery' | 'from_delivery';
|
||||
status?: string;
|
||||
|
||||
Reference in New Issue
Block a user