迁移 20261031 两处回填的 source 由 manual 改 backfill(与超管手工登记可区分,符合设计 V10),新增迁移 20261041 回标存量行(按 note 精确识别、幂等),服务层 source 类型同步;BranchManagement 绑定弹层时间改本地时区(原按 UTC 截断,差 8 小时)。
429 lines
18 KiB
TypeScript
429 lines
18 KiB
TypeScript
import { pool } from '../db';
|
||
|
||
/**
|
||
* 分公司「接入编码」与「主系统 (分公司 × 供应商) → 我方分公司」绑定(2026-10-27 设计)。
|
||
*
|
||
* 背景(为什么要这个文件):此前的做法是 `branches.branch_code` **等于** 主系统的 `supplier_code`
|
||
* (见 `mainSystemIntegration.ts` 旧注释),于是入站只能拿 `payload.supplier_code` 当分公司编码 ⇒
|
||
* · 编码权在对方手里;
|
||
* · 无法表达"一个编码被主系统 A/B/C 三个分公司各绑一次";
|
||
* · 「编码未被绑定就收不到」无处落地。
|
||
* 现在改成:我方每家非平台分公司发一个**自己的接入编码**,主系统在它的授权行
|
||
* `supplier_integration_client_suppliers (client_id, branch_code, supplier_code)` 上绑定该编码;
|
||
* 我们这边把绑定**镜像**到 `public.main_supplier_bindings`,入站/出站都按它路由。
|
||
*
|
||
* ⚠️ SQL 一律放本文件:路由层有裸 SQL 棘轮(`tests/routeLayerBoundary.test.ts`)。
|
||
* 设计:docs/design/20261027-分公司接入编码与主系统供应商绑定.md
|
||
*/
|
||
|
||
/** 接入编码字符集:**31 个**字符 —— 数字 2-9 + 字母去 `I O L`(去掉易混的 `0 O 1 I L`,要能口头/手抄转达给主系统) */
|
||
export const ACCESS_CODE_ALPHABET = '23456789ABCDEFGHJKMNPQRSTUVWXYZ';
|
||
const ACCESS_CODE_PREFIX = 'SC';
|
||
const ACCESS_CODE_BODY_LENGTH = 10;
|
||
const ACCESS_CODE_RE = new RegExp(`^${ACCESS_CODE_PREFIX}[${ACCESS_CODE_ALPHABET}]{${ACCESS_CODE_BODY_LENGTH}}$`);
|
||
|
||
export function isBranchAccessCode(value: unknown): boolean {
|
||
return ACCESS_CODE_RE.test(String(value || '').trim().toUpperCase());
|
||
}
|
||
|
||
function randomAccessCode(): string {
|
||
let body = '';
|
||
for (let i = 0; i < ACCESS_CODE_BODY_LENGTH; i += 1) {
|
||
body += ACCESS_CODE_ALPHABET[Math.floor(Math.random() * ACCESS_CODE_ALPHABET.length)];
|
||
}
|
||
return `${ACCESS_CODE_PREFIX}${body}`;
|
||
}
|
||
|
||
/**
|
||
* 生成一个**未被占用**的接入编码(撞唯一键就重试,上限 20 次)。
|
||
*
|
||
* 查重范围**同时**包含:
|
||
* ① `branches.access_code` —— 当前在用的;
|
||
* ② `main_supplier_bindings.access_code` —— **历史**(这张表只转 `unbound`、从不删行)。
|
||
* 为什么要查②:分公司被删掉后,它的编码不该被"回收再利用" —— 否则主系统那边**遗留的绑定**
|
||
* 会静默指向新分公司(货走错门,且极难排查)。⇒ **编码一旦发出,终生不复用**。
|
||
*
|
||
* 唯一性另有 `uq_branches_access_code` 兜底:真并发下 INSERT/UPDATE 撞键会抛错,调用方按错误处理即可。
|
||
*/
|
||
export async function generateUniqueBranchAccessCode(): Promise<string> {
|
||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||
const candidate = randomAccessCode();
|
||
const exists = await pool.query(
|
||
`SELECT 1 FROM public.branches WHERE access_code = $1
|
||
UNION ALL
|
||
SELECT 1 FROM public.main_supplier_bindings WHERE access_code = $1
|
||
LIMIT 1`,
|
||
[candidate]
|
||
);
|
||
if (!exists.rowCount) return candidate;
|
||
}
|
||
throw new Error('接入编码生成失败:连续 20 次撞唯一键');
|
||
}
|
||
|
||
export type BranchAccessCodeRow = {
|
||
branch_code: string;
|
||
branch_name: string;
|
||
access_code: string;
|
||
};
|
||
|
||
/**
|
||
* 按作用域列出**接入编码**(Web「账号信息」浮层展示用)。
|
||
*
|
||
* - 超管:**全部在用**的分公司(平台分公司不生成接入编码,自然被空值排除);
|
||
* - 分公司管理员:**仅本分公司**一条;
|
||
* - 其余(无权限/无分公司):返回空数组 —— 绝不越权返回别家编码。
|
||
*
|
||
* 说明:接入编码是「交主系统去绑定的标识」,不是密码;但仍按最小可见面收口(只给管理员与超管)。
|
||
*/
|
||
export async function listBranchAccessCodes(scope: {
|
||
isSuperAdmin: boolean;
|
||
branchCode?: string | null;
|
||
}): Promise<BranchAccessCodeRow[]> {
|
||
if (scope.isSuperAdmin) {
|
||
const result = await pool.query<BranchAccessCodeRow>(
|
||
`SELECT branch_code, branch_name, access_code
|
||
FROM public.branches
|
||
WHERE COALESCE(NULLIF(TRIM(access_code), ''), '') <> ''
|
||
ORDER BY branch_code`
|
||
);
|
||
return result.rows;
|
||
}
|
||
const code = String(scope.branchCode || '').trim();
|
||
if (!code) return [];
|
||
const result = await pool.query<BranchAccessCodeRow>(
|
||
`SELECT branch_code, branch_name, access_code
|
||
FROM public.branches
|
||
WHERE branch_code = $1
|
||
LIMIT 1`,
|
||
[code]
|
||
);
|
||
return result.rows.filter((row) => String(row.access_code || '').trim() !== '');
|
||
}
|
||
|
||
export type MainSupplierBindingStatus = 'active' | 'unbound';
|
||
|
||
export type MainSupplierBinding = {
|
||
/** 我方分公司(= access_code 的归属) */
|
||
branchCode: string;
|
||
accessCode: string;
|
||
/** 主系统分公司(BRxxx);`*` = 通配行 */
|
||
mainBranchCode: string;
|
||
/** 主系统供应商编码(SUPxxxxx) */
|
||
mainSupplierCode: string;
|
||
status: MainSupplierBindingStatus;
|
||
source: string;
|
||
boundAt: string;
|
||
unboundAt: string | null;
|
||
};
|
||
|
||
type BindingRow = {
|
||
branch_code: string;
|
||
access_code: string;
|
||
main_branch_code: string;
|
||
main_supplier_code: string;
|
||
status: string;
|
||
source: string;
|
||
bound_at: Date | string;
|
||
unbound_at: Date | string | null;
|
||
};
|
||
|
||
function mapBinding(row: BindingRow): MainSupplierBinding {
|
||
return {
|
||
branchCode: String(row.branch_code || '').trim(),
|
||
accessCode: String(row.access_code || '').trim(),
|
||
mainBranchCode: String(row.main_branch_code || '').trim(),
|
||
mainSupplierCode: String(row.main_supplier_code || '').trim(),
|
||
status: row.status === 'unbound' ? 'unbound' : 'active',
|
||
source: String(row.source || '').trim(),
|
||
boundAt: row.bound_at instanceof Date ? row.bound_at.toISOString() : String(row.bound_at || ''),
|
||
unboundAt: row.unbound_at
|
||
? row.unbound_at instanceof Date
|
||
? row.unbound_at.toISOString()
|
||
: String(row.unbound_at)
|
||
: null,
|
||
};
|
||
}
|
||
|
||
const BINDING_COLUMNS = `branch_code, access_code, main_branch_code, main_supplier_code,
|
||
status, source, bound_at, unbound_at`;
|
||
|
||
/** 某分公司的全部绑定行(含已解绑的历史,按主系统分公司/供应商排序,供界面展示与排查) */
|
||
export async function listBindingsForBranch(branchCode: string): Promise<MainSupplierBinding[]> {
|
||
const code = String(branchCode || '').trim();
|
||
if (!code) return [];
|
||
const result = await pool.query<BindingRow>(
|
||
`SELECT ${BINDING_COLUMNS} FROM public.main_supplier_bindings
|
||
WHERE branch_code = $1
|
||
ORDER BY (status = 'active') DESC, main_branch_code, main_supplier_code`,
|
||
[code]
|
||
);
|
||
return result.rows.map(mapBinding);
|
||
}
|
||
|
||
/** 某分公司**生效中**的绑定(出站拉单/提交/回传都读它) */
|
||
export async function listActiveBindingsForBranch(branchCode: string): Promise<MainSupplierBinding[]> {
|
||
const code = String(branchCode || '').trim();
|
||
if (!code) return [];
|
||
const result = await pool.query<BindingRow>(
|
||
`SELECT ${BINDING_COLUMNS} FROM public.main_supplier_bindings
|
||
WHERE branch_code = $1 AND status = 'active'
|
||
ORDER BY main_branch_code, main_supplier_code`,
|
||
[code]
|
||
);
|
||
return result.rows.map(mapBinding);
|
||
}
|
||
|
||
/** 按接入编码反查我方分公司(入站首选路径:主系统把我们的编码原样带回来) */
|
||
export async function findBranchCodeByAccessCode(accessCode: string): Promise<string | null> {
|
||
const code = String(accessCode || '').trim().toUpperCase();
|
||
if (!code) return null;
|
||
const result = await pool.query<{ branch_code: string }>(
|
||
`SELECT branch_code FROM public.branches WHERE access_code = $1 LIMIT 1`,
|
||
[code]
|
||
);
|
||
return result.rows[0]?.branch_code ? String(result.rows[0].branch_code).trim() : null;
|
||
}
|
||
|
||
export type UpsertBindingInput = {
|
||
branchCode: string;
|
||
accessCode: string;
|
||
mainBranchCode: string;
|
||
mainSupplierCode: string;
|
||
source?: 'main_push' | 'main_pull' | 'manual' | 'backfill';
|
||
note?: string | null;
|
||
};
|
||
|
||
export type UpsertBindingResult = {
|
||
branchCode: string;
|
||
/** 该 (main_branch_code, main_supplier_code) 之前指向的**另一家**我方分公司(有 ⇒ 这是一次"改绑") */
|
||
previousBranchCode: string | null;
|
||
};
|
||
|
||
/**
|
||
* 登记/更新一条绑定(**绑定即生效**):
|
||
* · 同一 (主系统分公司 + 供应商) 若原本 active 指向**别家**我方分公司 ⇒ 先把旧行转 `unbound`(留痕),再写新行;
|
||
* · 同键已存在(哪怕 unbound)⇒ 原地刷成 active(`bound_at` 刷新、`unbound_at` 清空)。
|
||
* 唯一键 `uq_main_supplier_bindings_key` 保证同键只有一行。
|
||
*/
|
||
export async function upsertBinding(input: UpsertBindingInput): Promise<UpsertBindingResult> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const accessCode = String(input.accessCode || '').trim().toUpperCase();
|
||
const mainBranchCode = String(input.mainBranchCode || '').trim().toUpperCase() || '*';
|
||
const mainSupplierCode = String(input.mainSupplierCode || '').trim().toUpperCase();
|
||
const source = input.source || 'main_push';
|
||
if (!branchCode || !accessCode || !mainSupplierCode) {
|
||
throw new Error('upsertBinding:branch_code / access_code / main_supplier_code 均不能为空');
|
||
}
|
||
|
||
const previous = await pool.query<{ branch_code: string }>(
|
||
`SELECT branch_code FROM public.main_supplier_bindings
|
||
WHERE main_branch_code = $1 AND main_supplier_code = $2
|
||
AND status = 'active' AND branch_code <> $3
|
||
LIMIT 1`,
|
||
[mainBranchCode, mainSupplierCode, branchCode]
|
||
);
|
||
const previousBranchCode = previous.rows[0]?.branch_code ? String(previous.rows[0].branch_code).trim() : null;
|
||
|
||
if (previousBranchCode) {
|
||
await pool.query(
|
||
`UPDATE public.main_supplier_bindings
|
||
SET status = 'unbound', unbound_at = NOW(),
|
||
note = COALESCE(note, '') || ' [改绑:' || $3 || ' → ' || $4 || ']'
|
||
WHERE main_branch_code = $1 AND main_supplier_code = $2
|
||
AND status = 'active' AND branch_code <> $4`,
|
||
[mainBranchCode, mainSupplierCode, previousBranchCode, branchCode]
|
||
);
|
||
}
|
||
|
||
await pool.query(
|
||
`INSERT INTO public.main_supplier_bindings
|
||
(branch_code, access_code, main_branch_code, main_supplier_code, status, source, bound_at, unbound_at, note)
|
||
VALUES ($1, $2, $3, $4, 'active', $5, NOW(), NULL, $6)
|
||
ON CONFLICT (main_branch_code, main_supplier_code) DO UPDATE
|
||
SET branch_code = EXCLUDED.branch_code,
|
||
access_code = EXCLUDED.access_code,
|
||
status = 'active',
|
||
source = EXCLUDED.source,
|
||
bound_at = NOW(),
|
||
unbound_at = NULL,
|
||
note = EXCLUDED.note`,
|
||
[branchCode, accessCode, mainBranchCode, mainSupplierCode, source, input.note ?? null]
|
||
);
|
||
|
||
return { branchCode, previousBranchCode };
|
||
}
|
||
|
||
/** 解绑(保留历史行,只转 `unbound`);返回是否真的解绑了一条 active 行 */
|
||
export async function unbindBinding(params: {
|
||
mainBranchCode: string;
|
||
mainSupplierCode: string;
|
||
note?: string | null;
|
||
}): Promise<boolean> {
|
||
const mainBranchCode = String(params.mainBranchCode || '').trim().toUpperCase() || '*';
|
||
const mainSupplierCode = String(params.mainSupplierCode || '').trim().toUpperCase();
|
||
if (!mainSupplierCode) return false;
|
||
const result = await pool.query(
|
||
`UPDATE public.main_supplier_bindings
|
||
SET status = 'unbound', unbound_at = NOW(),
|
||
note = COALESCE($3, note)
|
||
WHERE main_branch_code = $1 AND main_supplier_code = $2 AND status = 'active'`,
|
||
[mainBranchCode, mainSupplierCode, params.note ?? null]
|
||
);
|
||
return (result.rowCount ?? 0) > 0;
|
||
}
|
||
|
||
/**
|
||
* 超管在分公司管理里手工登记/取消一条绑定(对方绑定接口上线前的兜底)。
|
||
* `mainBranchCode` 空 ⇒ 记**通配**行(`*`):不区分主系统分公司。
|
||
*/
|
||
export async function setManualBinding(params: {
|
||
branchCode: string;
|
||
accessCode: string;
|
||
mainBranchCode?: string | null;
|
||
mainSupplierCode: string;
|
||
bound: boolean;
|
||
}): Promise<void> {
|
||
const mainBranchCode = String(params.mainBranchCode || '').trim().toUpperCase() || '*';
|
||
const mainSupplierCode = String(params.mainSupplierCode || '').trim().toUpperCase();
|
||
if (!mainSupplierCode) return;
|
||
if (!params.bound) {
|
||
await unbindBinding({
|
||
mainBranchCode,
|
||
mainSupplierCode,
|
||
note: '超管手工解绑',
|
||
});
|
||
return;
|
||
}
|
||
await upsertBinding({
|
||
branchCode: params.branchCode,
|
||
accessCode: params.accessCode,
|
||
mainBranchCode,
|
||
mainSupplierCode,
|
||
source: 'manual',
|
||
note: '超管手工登记',
|
||
});
|
||
}
|
||
|
||
export type BindingVia = 'access_code' | 'exact' | 'unique_supplier' | 'wildcard';
|
||
export type BindingResolution =
|
||
| {
|
||
ok: true;
|
||
branchCode: string;
|
||
/** 命中的绑定(按接入编码命中时为 null:编码本身已确定分公司) */
|
||
binding: { mainBranchCode: string; mainSupplierCode: string } | null;
|
||
via: BindingVia;
|
||
}
|
||
| {
|
||
ok: false;
|
||
/**
|
||
* 失败原因(都会原样回给主系统的投递日志,所以要能直接指导排查):
|
||
* · `unknown_access_code` —— 带了我们的编码但**查不到**(几乎总是抄错一位/大小写/漏字符);
|
||
* · `not_bound` —— 编码/供应商没问题,但这家主系统分公司没绑我们(或已解绑);
|
||
* · `ambiguous` —— 多个我方分公司都绑了这个供应商,而载荷没带主系统分公司 ⇒ 拒收;
|
||
* · `missing_supplier_code` —— 载荷连供应商编码都没有。
|
||
*/
|
||
reason: 'missing_supplier_code' | 'not_bound' | 'ambiguous' | 'unknown_access_code';
|
||
};
|
||
|
||
/**
|
||
* 入站路由的**唯一判定点**(设计 §3.3):
|
||
* 0. 带了我们的 `subsystem_code` ⇒ 直接按**我方编码**定位分公司(最稳);
|
||
* 1. 否则按 `supplier_code`(+ 已知的 `main_branch_code`)查镜像表:
|
||
* 精确命中 → 用;该主系统分公司有行但已解绑 → 忽略(尊重显式解绑);
|
||
* 分公司未知时:该供应商只有**一家**我方分公司在绑 → 唯一命中;
|
||
* 否则看通配行;再否则**拒收**(ambiguous,宁可漏一单也不猜)。
|
||
*/
|
||
export async function resolveOurBranchByBinding(input: {
|
||
subsystemCode?: string | null;
|
||
supplierCode?: string | null;
|
||
mainBranchCode?: string | null;
|
||
}): Promise<BindingResolution> {
|
||
const subsystemCode = String(input.subsystemCode || '').trim().toUpperCase();
|
||
if (subsystemCode) {
|
||
const branchCode = await findBranchCodeByAccessCode(subsystemCode);
|
||
if (branchCode) return { ok: true, branchCode, binding: null, via: 'access_code' };
|
||
/**
|
||
* 编码不认识:**不回落去猜**(可能是别的子系统实例的码)。
|
||
* 单列一个 reason:真机上这一条 99% 是"编码抄错一位",运维看投递日志要能立刻分辨 ——
|
||
* 与"这家没绑我们"(`not_bound`,语义正常)完全不是一回事。
|
||
*/
|
||
return { ok: false, reason: 'unknown_access_code' };
|
||
}
|
||
|
||
const supplierCode = String(input.supplierCode || '').trim().toUpperCase();
|
||
if (!supplierCode) return { ok: false, reason: 'missing_supplier_code' };
|
||
const mainBranchCode = String(input.mainBranchCode || '').trim().toUpperCase();
|
||
|
||
const result = await pool.query<Pick<BindingRow, 'branch_code' | 'main_branch_code' | 'main_supplier_code' | 'status'>>(
|
||
`SELECT branch_code, main_branch_code, main_supplier_code, status
|
||
FROM public.main_supplier_bindings
|
||
WHERE main_supplier_code = $1`,
|
||
[supplierCode]
|
||
);
|
||
const rows = result.rows.map((row) => ({
|
||
branchCode: String(row.branch_code || '').trim(),
|
||
mainBranchCode: String(row.main_branch_code || '').trim().toUpperCase(),
|
||
status: row.status === 'unbound' ? ('unbound' as const) : ('active' as const),
|
||
}));
|
||
const active = rows.filter((row) => row.status === 'active');
|
||
const hit = (row: { branchCode: string; mainBranchCode: string }, via: BindingVia): BindingResolution => ({
|
||
ok: true,
|
||
branchCode: row.branchCode,
|
||
binding: { mainBranchCode: row.mainBranchCode, mainSupplierCode: supplierCode },
|
||
via,
|
||
});
|
||
|
||
if (mainBranchCode) {
|
||
const exactActive = active.find((row) => row.mainBranchCode === mainBranchCode);
|
||
if (exactActive) return hit(exactActive, 'exact');
|
||
// 该主系统分公司有这个供应商的行、但不是 active ⇒ 尊重显式解绑
|
||
if (rows.some((row) => row.mainBranchCode === mainBranchCode)) return { ok: false, reason: 'not_bound' };
|
||
const wildcardActive = active.find((row) => row.mainBranchCode === '*');
|
||
if (wildcardActive) return hit(wildcardActive, 'wildcard');
|
||
// 分公司已知但没绑我们 ⇒ 这批货不是给我们的
|
||
return { ok: false, reason: 'not_bound' };
|
||
}
|
||
|
||
const branches = [...new Set(active.map((row) => row.branchCode))];
|
||
if (branches.length === 1 && active.length) return hit(active[0], 'unique_supplier');
|
||
const wildcardActive = active.find((row) => row.mainBranchCode === '*');
|
||
if (wildcardActive) {
|
||
console.warn(
|
||
`[binding] supplier=${supplierCode} 有多家我方分公司在绑(${branches.join(',')})且载荷缺 main_branch_code ⇒ 按通配行落到 ${wildcardActive.branchCode}`
|
||
);
|
||
return hit(wildcardActive, 'wildcard');
|
||
}
|
||
if (!active.length) return { ok: false, reason: 'not_bound' };
|
||
return { ok: false, reason: 'ambiguous' };
|
||
}
|
||
|
||
/**
|
||
* **出站**用:这条备货行该用哪个 `supplier_code` 回主系统(2026-10-27)。
|
||
*
|
||
* 改前各处直接写 `supplierCode: branchCode`(那时两者恰好相等);接入编码落地后不再相等,
|
||
* 于是改成"**先查行级台账**(导入时逐行落的 `main_supplier_code`)",
|
||
* 查不到再退"该分公司唯一的生效绑定",都取不到 ⇒ null(调用方按"未绑定"报错,不要瞎猜)。
|
||
*/
|
||
export async function resolveSupplierCodeForPrep(params: {
|
||
branchCode: string;
|
||
prepId: string;
|
||
}): Promise<string | null> {
|
||
const branchCode = String(params.branchCode || '').trim();
|
||
const prepId = String(params.prepId || '').trim();
|
||
if (!branchCode || !prepId) return null;
|
||
|
||
const ledger = await pool.query<{ main_supplier_code: string | null }>(
|
||
`SELECT main_supplier_code
|
||
FROM public.main_system_order_import_items
|
||
WHERE branch_code = $1 AND prep_id = $2
|
||
LIMIT 1`,
|
||
[branchCode, prepId]
|
||
);
|
||
const fromLedger = String(ledger.rows[0]?.main_supplier_code || '').trim();
|
||
if (fromLedger) return fromLedger;
|
||
|
||
const active = await listActiveBindingsForBranch(branchCode);
|
||
const codes = [...new Set(active.map((item) => item.mainSupplierCode).filter(Boolean))];
|
||
return codes.length === 1 ? codes[0] : null;
|
||
}
|