Files
SupplierSystem/server/src/services/purchaserAssignmentService.ts
T
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

288 lines
9.9 KiB
TypeScript

import type { PoolClient } from 'pg';
import { pool } from '../db';
import { formatChinaDate } from './orderDeliveryDate';
import { getPurchaseAssignDefaultConfig } from './purchaseAssignDefaultConfigService';
import { lookupMappedPurchaserCode } from './purchaseCategoryPurchaserMapService';
import {
listBranchPurchasers,
PENDING_PURCHASE_STATUS_SQL,
type PurchaserCandidate,
} from './purchasePurchaserAssignService';
import { purchaseOrderBranchWhereSql } from './purchaserBranchScope';
import { orderNotDeletedSql } from './orderTrashScope';
export interface PurchaserInfo {
purchaser_code: string;
purchaser_name: string;
}
/** 建自采解析结果:assigned / 自由池 / 无法挂人 */
export type NewPurchasePurchaserResolution =
| { kind: 'assigned'; purchaser_code: string; purchaser_name: string }
| { kind: 'free_pool' }
| { kind: 'unavailable' };
export async function fetchPrimaryPurchaserForBranch(
branchCode?: string | null
): Promise<PurchaserInfo | null> {
const normalized = String(branchCode || '').trim();
if (normalized) {
const branchResult = await pool.query(
`SELECT pu.purchaser_code, pu.purchaser_name
FROM purchaser_users pu
JOIN profiles p ON p.id = pu.user_id
WHERE p.branch_code = $1 AND pu.status = 1
ORDER BY pu.is_primary DESC NULLS LAST, pu.created_at ASC
LIMIT 1`,
[normalized]
);
if (branchResult.rows[0]?.purchaser_code) {
return {
purchaser_code: String(branchResult.rows[0].purchaser_code),
purchaser_name: String(branchResult.rows[0].purchaser_name || branchResult.rows[0].purchaser_code),
};
}
}
const globalResult = await pool.query(
`SELECT purchaser_code, purchaser_name
FROM purchaser_users
WHERE status = 1
ORDER BY is_primary DESC NULLS LAST, created_at ASC
LIMIT 1`
);
const row = globalResult.rows[0];
if (!row?.purchaser_code) return null;
return {
purchaser_code: String(row.purchaser_code),
purchaser_name: String(row.purchaser_name || row.purchaser_code),
};
}
export async function resolvePurchaserForOrder(input: {
orderCode: string;
branchCode?: string | null;
}): Promise<PurchaserInfo> {
let branchCode = input.branchCode?.trim() || null;
if (!branchCode) {
const orderResult = await pool.query(`SELECT branch_code FROM orders WHERE order_code = $1`, [
input.orderCode,
]);
branchCode = orderResult.rows[0]?.branch_code ? String(orderResult.rows[0].branch_code) : null;
}
const purchaser = await fetchPrimaryPurchaserForBranch(branchCode);
if (!purchaser) {
throw Object.assign(new Error('未配置采购员,请先在采购员管理中创建主采购员'), {
status: 400,
code: 'purchaser_missing',
});
}
return purchaser;
}
function varietyKeyFromParts(skuCode?: string | null, itemName?: string | null): string {
const sku = String(skuCode || '').trim();
if (sku) return `sku:${sku}`;
const name = String(itemName || '').trim();
if (name) return `name:${name}`;
return 'name:__unknown__';
}
function categoryKeyFromCode(categoryCode?: string | null): string {
const code = String(categoryCode || '').trim();
return code ? `cat:${code}` : 'cat:__uncategorized__';
}
export function pickLeastLoadedPurchaserPure(
purchasers: PurchaserCandidate[],
groupKey: string,
/** purchaser_code → set of group keys already held */
heldByPurchaser: Map<string, Set<string>>
): PurchaserCandidate | null {
if (!purchasers.length) return null;
for (const p of purchasers) {
if (heldByPurchaser.get(p.purchaser_code)?.has(groupKey)) return p;
}
let best: PurchaserCandidate | null = null;
let bestCount = Number.POSITIVE_INFINITY;
for (const p of purchasers) {
const count = heldByPurchaser.get(p.purchaser_code)?.size || 0;
if (!best || count < bestCount) {
best = p;
bestCount = count;
continue;
}
if (count > bestCount) continue;
const pPrimary = Boolean(p.is_primary);
const bPrimary = Boolean(best.is_primary);
if (pPrimary && !bPrimary) {
best = p;
} else if (pPrimary === bPrimary && p.purchaser_code < best.purchaser_code) {
best = p;
}
}
return best;
}
async function loadHeldGroupsForDeliveryDay(
db: typeof pool | PoolClient,
input: {
branchCode: string;
deliveryDate: string;
mode: 'by_sku' | 'by_category';
}
): Promise<Map<string, Set<string>>> {
const result = await db.query(
`SELECT po.purchaser_code,
po.sku_code,
COALESCE(
NULLIF(TRIM(oi.item_name), ''),
NULLIF(TRIM(po.sku_code), ''),
''
) AS item_name,
COALESCE(NULLIF(TRIM(oi.category_code), ''), '') AS category_code
FROM purchase_orders po
LEFT JOIN orders o ON o.order_code = po.order_code
LEFT JOIN order_items oi ON oi.id::text = po.source_id AND oi.order_code = po.order_code
WHERE ${purchaseOrderBranchWhereSql('po', '$1')}
AND ${PENDING_PURCHASE_STATUS_SQL}
AND NULLIF(TRIM(po.purchaser_code), '') IS NOT NULL
AND (po.order_code IS NULL OR TRIM(po.order_code) = '' OR ${orderNotDeletedSql('o')})
AND COALESCE(
o.delivery_date::date,
(po.created_at AT TIME ZONE 'Asia/Shanghai')::date
) = $2::date`,
[input.branchCode, input.deliveryDate]
);
const map = new Map<string, Set<string>>();
for (const row of result.rows) {
const code = String(row.purchaser_code || '').trim();
if (!code) continue;
const key =
input.mode === 'by_category'
? categoryKeyFromCode(row.category_code)
: varietyKeyFromParts(row.sku_code, row.item_name);
let set = map.get(code);
if (!set) {
set = new Set();
map.set(code, set);
}
set.add(key);
}
return map;
}
async function resolveDeliveryDateYmd(
db: typeof pool | PoolClient,
orderCode: string
): Promise<string> {
const result = await db.query(
`SELECT delivery_date::date::text AS d FROM orders WHERE order_code = $1 LIMIT 1`,
[orderCode]
);
const d = String(result.rows[0]?.d || '').trim();
if (/^\d{4}-\d{2}-\d{2}$/.test(d)) return d;
return formatChinaDate();
}
/** 分类绑定命中且采购员仍启用时返回;否则 null(停用则 warn)。 */
export async function resolveMappedPurchaserForCategory(input: {
branchCode?: string | null;
categoryCode?: string | null;
client?: PoolClient | null;
}): Promise<PurchaserInfo | null> {
const db = input.client || pool;
const branchCode = String(input.branchCode || '').trim();
const mappedCode = await lookupMappedPurchaserCode(branchCode || null, input.categoryCode, db);
if (!mappedCode || !branchCode) return null;
const purchasers = await listBranchPurchasers(db, branchCode);
const hit = purchasers.find((p) => p.purchaser_code === mappedCode);
if (!hit) {
console.warn('[purchase-category-map] 绑定采购员不在分公司启用列表,忽略', mappedCode);
return null;
}
return { purchaser_code: hit.purchaser_code, purchaser_name: hit.purchaser_name };
}
/**
* 建自采单时解析采购员(分公司默认配置优先,见 20260818-purchase-assign-default-on-create)。
*/
export async function resolvePurchaserForNewPurchaseOrder(input: {
orderCode: string;
branchCode?: string | null;
skuCode?: string | null;
itemName?: string | null;
categoryCode?: string | null;
client?: PoolClient | null;
}): Promise<NewPurchasePurchaserResolution> {
const db = input.client || pool;
let branchCode = String(input.branchCode || '').trim() || null;
if (!branchCode) {
const orderResult = await db.query(`SELECT branch_code FROM orders WHERE order_code = $1`, [
input.orderCode,
]);
branchCode = orderResult.rows[0]?.branch_code ? String(orderResult.rows[0].branch_code) : null;
}
const cfg = await getPurchaseAssignDefaultConfig(branchCode, db);
if (!cfg.mode) {
const primary = await fetchPrimaryPurchaserForBranch(branchCode);
if (!primary) return { kind: 'unavailable' };
return { kind: 'assigned', ...primary };
}
if (cfg.mode === 'free_pool') {
return { kind: 'free_pool' };
}
if (cfg.mode === 'to_purchaser') {
const code = cfg.purchaser_code;
if (!code || !branchCode) {
console.warn('[purchase-assign-default] to_purchaser 缺编码,回退主采购员');
const primary = await fetchPrimaryPurchaserForBranch(branchCode);
if (!primary) return { kind: 'unavailable' };
return { kind: 'assigned', ...primary };
}
const purchasers = await listBranchPurchasers(db, branchCode);
const hit = purchasers.find((p) => p.purchaser_code === code);
if (!hit) {
console.warn('[purchase-assign-default] 指定采购员不在分公司启用列表,回退主采购员', code);
const primary = await fetchPrimaryPurchaserForBranch(branchCode);
if (!primary) return { kind: 'unavailable' };
return { kind: 'assigned', ...primary };
}
return {
kind: 'assigned',
purchaser_code: hit.purchaser_code,
purchaser_name: hit.purchaser_name,
};
}
if (!branchCode) {
const primary = await fetchPrimaryPurchaserForBranch(branchCode);
if (!primary) return { kind: 'unavailable' };
return { kind: 'assigned', ...primary };
}
const purchasers = await listBranchPurchasers(db, branchCode);
if (!purchasers.length) return { kind: 'unavailable' };
const deliveryDate = await resolveDeliveryDateYmd(db, input.orderCode);
const groupKey =
cfg.mode === 'by_category'
? categoryKeyFromCode(input.categoryCode)
: varietyKeyFromParts(input.skuCode, input.itemName);
const held = await loadHeldGroupsForDeliveryDay(db, {
branchCode,
deliveryDate,
mode: cfg.mode,
});
const picked = pickLeastLoadedPurchaserPure(purchasers, groupKey, held);
if (!picked) return { kind: 'unavailable' };
return {
kind: 'assigned',
purchaser_code: picked.purchaser_code,
purchaser_name: picked.purchaser_name,
};
}