来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
492 lines
16 KiB
TypeScript
492 lines
16 KiB
TypeScript
/**
|
|
* 自采待采单分配采购员:按品种数 / 按分类数均分(整组不拆);自由采购清空归属。
|
|
* 设计:docs/design/20260817-purchase-assign-purchasers.md
|
|
* docs/design/20260817-purchase-free-pool.md
|
|
*/
|
|
import type { Pool, PoolClient } from 'pg';
|
|
import { writeAuditLog } from './auditService';
|
|
import {
|
|
PURCHASE_CATEGORY_CODE_EXPR,
|
|
PURCHASE_ORDER_ITEM_JOINS,
|
|
PURCHASE_REMARK_ITEM_NAME_EXPR,
|
|
} from './purchaseOrderQuery';
|
|
import { purchaseOrderBranchWhereSql } from './purchaserBranchScope';
|
|
import {
|
|
normalizePurchaseDateField,
|
|
purchaseFilterDaySql,
|
|
type PurchaseDateField,
|
|
} from './purchaseOrderQueryService';
|
|
import { orderNotDeletedSql } from './orderTrashScope';
|
|
|
|
export type PurchaserAssignMode = 'by_sku' | 'by_category' | 'to_purchaser' | 'free_pool';
|
|
export type PurchaserBatchAssignMode = PurchaserAssignMode | 'to_category_purchaser';
|
|
|
|
export interface PurchaserCandidate {
|
|
purchaser_code: string;
|
|
purchaser_name: string;
|
|
is_primary?: boolean;
|
|
}
|
|
|
|
export interface PendingPurchaseAssignRow {
|
|
purchase_code: string;
|
|
sku_code: string;
|
|
item_name: string;
|
|
category_code: string;
|
|
purchase_qty: number;
|
|
purchaser_code: string | null;
|
|
purchaser_name: string | null;
|
|
}
|
|
|
|
export interface AssignPlanItem {
|
|
purchase_code: string;
|
|
purchaser_code: string | null;
|
|
purchaser_name: string | null;
|
|
group_key: string;
|
|
}
|
|
|
|
/** 未完成(与自采列表「进行中」一致):可展示/分配/改挂;已完成不纳入 */
|
|
export const PENDING_PURCHASE_STATUS_SQL = `(po.purchase_status < 30 OR po.purchase_status = 32)`;
|
|
|
|
export function isAssignablePurchaseStatus(status: unknown): boolean {
|
|
const n = Number(status);
|
|
return Number.isFinite(n) && (n < 30 || n === 32);
|
|
}
|
|
|
|
export function normalizeAssignMode(value: unknown): PurchaserBatchAssignMode {
|
|
const raw = String(value || '').trim();
|
|
if (raw === 'by_category') return 'by_category';
|
|
if (raw === 'to_purchaser') return 'to_purchaser';
|
|
if (raw === 'free_pool') return 'free_pool';
|
|
if (raw === 'to_category_purchaser') return 'to_category_purchaser';
|
|
return 'by_sku';
|
|
}
|
|
|
|
/** 勾选/范围内待采清空采购员,进入自由采购池 */
|
|
export function planFreePool(rows: PendingPurchaseAssignRow[]): AssignPlanItem[] {
|
|
return rows.map((row) => ({
|
|
purchase_code: row.purchase_code,
|
|
purchaser_code: null,
|
|
purchaser_name: null,
|
|
group_key: 'free_pool',
|
|
}));
|
|
}
|
|
|
|
function varietyKey(row: PendingPurchaseAssignRow): string {
|
|
const sku = String(row.sku_code || '').trim();
|
|
if (sku) return `sku:${sku}`;
|
|
const name = String(row.item_name || '').trim();
|
|
if (name) return `name:${name}`;
|
|
return `po:${row.purchase_code}`;
|
|
}
|
|
|
|
function categoryKey(row: PendingPurchaseAssignRow): string {
|
|
const code = String(row.category_code || '').trim();
|
|
return code ? `cat:${code}` : 'cat:__uncategorized__';
|
|
}
|
|
|
|
/**
|
|
* 贪心均分:组按 weight 降序,依次派给当前持有组数最少的采购员。
|
|
* 仅 `by_sku` / `by_category`;指定一人见 `planToSinglePurchaser`。
|
|
*/
|
|
export function planPurchaserAssignment(
|
|
rows: PendingPurchaseAssignRow[],
|
|
purchasers: PurchaserCandidate[],
|
|
mode: 'by_sku' | 'by_category'
|
|
): AssignPlanItem[] {
|
|
if (!rows.length || !purchasers.length) return [];
|
|
|
|
type Group = {
|
|
key: string;
|
|
rows: PendingPurchaseAssignRow[];
|
|
varietyCount: number;
|
|
lineCount: number;
|
|
qtySum: number;
|
|
};
|
|
|
|
const groupMap = new Map<string, Group>();
|
|
for (const row of rows) {
|
|
const key = mode === 'by_category' ? categoryKey(row) : varietyKey(row);
|
|
let g = groupMap.get(key);
|
|
if (!g) {
|
|
g = { key, rows: [], varietyCount: 0, lineCount: 0, qtySum: 0 };
|
|
groupMap.set(key, g);
|
|
}
|
|
g.rows.push(row);
|
|
g.lineCount += 1;
|
|
g.qtySum += Number(row.purchase_qty) || 0;
|
|
}
|
|
|
|
if (mode === 'by_category') {
|
|
for (const g of groupMap.values()) {
|
|
const skus = new Set(g.rows.map((r) => varietyKey(r)));
|
|
g.varietyCount = skus.size;
|
|
}
|
|
} else {
|
|
for (const g of groupMap.values()) {
|
|
g.varietyCount = 1;
|
|
}
|
|
}
|
|
|
|
const groups = [...groupMap.values()].sort((a, b) => {
|
|
if (mode === 'by_category') {
|
|
if (b.varietyCount !== a.varietyCount) return b.varietyCount - a.varietyCount;
|
|
}
|
|
if (b.lineCount !== a.lineCount) return b.lineCount - a.lineCount;
|
|
if (b.qtySum !== a.qtySum) return b.qtySum - a.qtySum;
|
|
return a.key.localeCompare(b.key, 'zh-CN');
|
|
});
|
|
|
|
const load = purchasers.map(() => 0);
|
|
const plan: AssignPlanItem[] = [];
|
|
|
|
for (const g of groups) {
|
|
let best = 0;
|
|
for (let i = 1; i < purchasers.length; i++) {
|
|
if (load[i] < load[best]) best = i;
|
|
}
|
|
const p = purchasers[best];
|
|
load[best] += 1;
|
|
for (const row of g.rows) {
|
|
plan.push({
|
|
purchase_code: row.purchase_code,
|
|
purchaser_code: p.purchaser_code,
|
|
purchaser_name: p.purchaser_name,
|
|
group_key: g.key,
|
|
});
|
|
}
|
|
}
|
|
|
|
return plan;
|
|
}
|
|
|
|
/** 勾选/范围内待采全部挂到同一采购员 */
|
|
export function planToSinglePurchaser(
|
|
rows: PendingPurchaseAssignRow[],
|
|
target: PurchaserCandidate
|
|
): AssignPlanItem[] {
|
|
return rows.map((row) => ({
|
|
purchase_code: row.purchase_code,
|
|
purchaser_code: target.purchaser_code,
|
|
purchaser_name: target.purchaser_name,
|
|
group_key: `to:${target.purchaser_code}`,
|
|
}));
|
|
}
|
|
|
|
/** 范围内仅该分类整组挂到同一采购员 */
|
|
export function planToCategoryPurchaser(
|
|
rows: PendingPurchaseAssignRow[],
|
|
target: PurchaserCandidate,
|
|
categoryCode: string
|
|
): AssignPlanItem[] {
|
|
const want = categoryKey({
|
|
purchase_code: '',
|
|
sku_code: '',
|
|
item_name: '',
|
|
category_code: categoryCode,
|
|
purchase_qty: 0,
|
|
purchaser_code: null,
|
|
purchaser_name: null,
|
|
});
|
|
return planToSinglePurchaser(
|
|
rows.filter((row) => categoryKey(row) === want),
|
|
target
|
|
);
|
|
}
|
|
|
|
export async function listBranchPurchasers(
|
|
db: Pool | PoolClient,
|
|
branchCode: string
|
|
): Promise<PurchaserCandidate[]> {
|
|
const result = await db.query(
|
|
`SELECT pu.purchaser_code, pu.purchaser_name, pu.is_primary
|
|
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`,
|
|
[branchCode]
|
|
);
|
|
return result.rows.map((row) => ({
|
|
purchaser_code: String(row.purchaser_code),
|
|
purchaser_name: String(row.purchaser_name || row.purchaser_code),
|
|
is_primary: Boolean(row.is_primary),
|
|
}));
|
|
}
|
|
|
|
function purchaseDateRangeSql(dateField: PurchaseDateField, startParam: number, endParam: number): string {
|
|
const dayExpr = purchaseFilterDaySql(dateField);
|
|
return `${dayExpr} BETWEEN ($${startParam}::timestamptz AT TIME ZONE 'Asia/Shanghai')::date
|
|
AND ($${endParam}::timestamptz AT TIME ZONE 'Asia/Shanghai')::date`;
|
|
}
|
|
|
|
export async function loadPendingPurchasesForAssign(
|
|
db: Pool | PoolClient,
|
|
input: {
|
|
branchCode: string;
|
|
dateField?: PurchaseDateField | string | null;
|
|
dateFrom?: string | null;
|
|
dateTo?: string | null;
|
|
purchaseCodes?: string[] | null;
|
|
}
|
|
): Promise<PendingPurchaseAssignRow[]> {
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const params: unknown[] = [branchCode];
|
|
const where: string[] = [
|
|
purchaseOrderBranchWhereSql('po', '$1'),
|
|
PENDING_PURCHASE_STATUS_SQL,
|
|
`(po.order_code IS NULL OR TRIM(po.order_code) = '' OR ${orderNotDeletedSql('o')})`,
|
|
];
|
|
|
|
const codes = (input.purchaseCodes || []).map((c) => String(c || '').trim()).filter(Boolean);
|
|
if (codes.length) {
|
|
params.push(codes);
|
|
where.push(`po.purchase_code = ANY($${params.length}::text[])`);
|
|
} else {
|
|
const dateField = normalizePurchaseDateField(input.dateField);
|
|
const from = String(input.dateFrom || '').trim();
|
|
const to = String(input.dateTo || '').trim();
|
|
if (/^\d{4}-\d{2}-\d{2}$/.test(from) && /^\d{4}-\d{2}-\d{2}$/.test(to)) {
|
|
params.push(`${from}T00:00:00+08:00`, `${to}T23:59:59.999+08:00`);
|
|
where.push(purchaseDateRangeSql(dateField, params.length - 1, params.length));
|
|
}
|
|
}
|
|
|
|
const itemNameExpr = `COALESCE(
|
|
NULLIF(TRIM(oi.item_name), ''),
|
|
NULLIF(TRIM(sp_src.item_name), ''),
|
|
NULLIF(TRIM(s.sku_name), ''),
|
|
${PURCHASE_REMARK_ITEM_NAME_EXPR},
|
|
NULLIF(TRIM(po.sku_code), ''),
|
|
''
|
|
)`;
|
|
|
|
const result = await db.query(
|
|
`SELECT po.purchase_code,
|
|
COALESCE(NULLIF(TRIM(po.sku_code), ''), '') AS sku_code,
|
|
${itemNameExpr} AS item_name,
|
|
${PURCHASE_CATEGORY_CODE_EXPR} AS category_code,
|
|
COALESCE(po.purchase_qty, 0)::float8 AS purchase_qty,
|
|
NULLIF(TRIM(po.purchaser_code), '') AS purchaser_code,
|
|
NULLIF(TRIM(po.purchaser_name), '') AS purchaser_name
|
|
FROM purchase_orders po
|
|
LEFT JOIN skus s ON s.sku_code = po.sku_code
|
|
LEFT JOIN orders o ON o.order_code = po.order_code
|
|
${PURCHASE_ORDER_ITEM_JOINS}
|
|
WHERE ${where.join(' AND ')}
|
|
ORDER BY po.created_at ASC`,
|
|
params
|
|
);
|
|
|
|
return result.rows.map((row) => ({
|
|
purchase_code: String(row.purchase_code),
|
|
sku_code: String(row.sku_code || ''),
|
|
item_name: String(row.item_name || ''),
|
|
category_code: String(row.category_code || ''),
|
|
purchase_qty: Number(row.purchase_qty) || 0,
|
|
purchaser_code: row.purchaser_code ? String(row.purchaser_code) : null,
|
|
purchaser_name: row.purchaser_name ? String(row.purchaser_name) : null,
|
|
}));
|
|
}
|
|
|
|
export async function applyPurchaserAssignment(
|
|
db: Pool | PoolClient,
|
|
input: {
|
|
branchCode: string;
|
|
mode: PurchaserBatchAssignMode;
|
|
dateField?: string | null;
|
|
dateFrom?: string | null;
|
|
dateTo?: string | null;
|
|
purchaseCodes?: string[] | null;
|
|
purchaserCode?: string | null;
|
|
categoryCode?: string | null;
|
|
operatorId?: string | null;
|
|
}
|
|
) {
|
|
const rows = await loadPendingPurchasesForAssign(db, {
|
|
branchCode: input.branchCode,
|
|
dateField: input.dateField,
|
|
dateFrom: input.dateFrom,
|
|
dateTo: input.dateTo,
|
|
purchaseCodes: input.purchaseCodes,
|
|
});
|
|
if (!rows.length) {
|
|
return {
|
|
updated: 0,
|
|
mode: input.mode,
|
|
by_purchaser: [] as Array<{ purchaser_code: string; purchaser_name: string; count: number }>,
|
|
};
|
|
}
|
|
|
|
let plan: AssignPlanItem[];
|
|
if (input.mode === 'free_pool') {
|
|
plan = planFreePool(rows);
|
|
} else {
|
|
const purchasers = await listBranchPurchasers(db, input.branchCode);
|
|
if (!purchasers.length) {
|
|
throw Object.assign(new Error('本分公司未配置启用中的采购员'), {
|
|
status: 400,
|
|
code: 'purchaser_missing',
|
|
});
|
|
}
|
|
if (input.mode === 'to_purchaser' || input.mode === 'to_category_purchaser') {
|
|
const code = String(input.purchaserCode || '').trim();
|
|
const target = purchasers.find((p) => p.purchaser_code === code);
|
|
if (!target) {
|
|
throw Object.assign(new Error('请选择有效采购员'), {
|
|
status: 400,
|
|
code: 'purchaser_required',
|
|
});
|
|
}
|
|
if (input.mode === 'to_category_purchaser') {
|
|
const categoryCode = String(input.categoryCode || '').trim();
|
|
if (!categoryCode) {
|
|
throw Object.assign(new Error('请选择商品分类'), {
|
|
status: 400,
|
|
code: 'invalid_request',
|
|
});
|
|
}
|
|
plan = planToCategoryPurchaser(rows, target, categoryCode);
|
|
} else {
|
|
plan = planToSinglePurchaser(rows, target);
|
|
}
|
|
} else {
|
|
plan = planPurchaserAssignment(rows, purchasers, input.mode);
|
|
}
|
|
}
|
|
let updated = 0;
|
|
const countMap = new Map<string, { purchaser_code: string; purchaser_name: string; count: number }>();
|
|
|
|
for (const item of plan) {
|
|
const result = await db.query(
|
|
`UPDATE purchase_orders
|
|
SET purchaser_code = $2,
|
|
purchaser_name = $3
|
|
WHERE purchase_code = $1
|
|
AND (purchase_status < 30 OR purchase_status = 32)
|
|
AND ${purchaseOrderBranchWhereSql('purchase_orders', '$4')}
|
|
RETURNING purchase_code`,
|
|
[item.purchase_code, item.purchaser_code, item.purchaser_name, input.branchCode]
|
|
);
|
|
if (result.rowCount) {
|
|
updated += 1;
|
|
const mapKey = item.purchaser_code || '__free_pool__';
|
|
const cur = countMap.get(mapKey) || {
|
|
purchaser_code: item.purchaser_code || '',
|
|
purchaser_name: item.purchaser_name || '自由采购',
|
|
count: 0,
|
|
};
|
|
cur.count += 1;
|
|
countMap.set(mapKey, cur);
|
|
}
|
|
}
|
|
|
|
await writeAuditLog({
|
|
operatorId: input.operatorId,
|
|
operationType: 'purchase_assign_purchaser',
|
|
targetTable: 'purchase_orders',
|
|
targetId: input.branchCode,
|
|
branchCode: input.branchCode,
|
|
actionCategory: 'purchase',
|
|
newValue: {
|
|
mode: input.mode,
|
|
updated,
|
|
date_from: input.dateFrom,
|
|
date_to: input.dateTo,
|
|
purchase_codes: input.purchaseCodes || null,
|
|
purchaser_code: input.purchaserCode || null,
|
|
category_code: input.categoryCode || null,
|
|
by_purchaser: [...countMap.values()],
|
|
},
|
|
}).catch(() => undefined);
|
|
|
|
return {
|
|
updated,
|
|
mode: input.mode,
|
|
by_purchaser: [...countMap.values()].sort((a, b) => a.purchaser_code.localeCompare(b.purchaser_code)),
|
|
};
|
|
}
|
|
|
|
export async function reassignSinglePurchasePurchaser(
|
|
db: Pool | PoolClient,
|
|
input: {
|
|
branchCode: string;
|
|
purchaseCode: string;
|
|
purchaserCode: string;
|
|
operatorId?: string | null;
|
|
}
|
|
) {
|
|
const purchaseCode = String(input.purchaseCode || '').trim();
|
|
const purchaserCode = String(input.purchaserCode || '').trim();
|
|
if (!purchaseCode) {
|
|
throw Object.assign(new Error('缺少 purchase_code'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
if (!purchaserCode) {
|
|
throw Object.assign(new Error('缺少 purchaser_code'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
|
|
const purchasers = await listBranchPurchasers(db, input.branchCode);
|
|
const target = purchasers.find((p) => p.purchaser_code === purchaserCode);
|
|
if (!target) {
|
|
throw Object.assign(new Error('采购员不存在或不属于本分公司'), {
|
|
status: 400,
|
|
code: 'purchaser_invalid',
|
|
});
|
|
}
|
|
|
|
const before = await db.query(
|
|
`SELECT purchase_code, purchase_status, purchaser_code, purchaser_name
|
|
FROM purchase_orders po
|
|
WHERE po.purchase_code = $1
|
|
AND ${purchaseOrderBranchWhereSql('po', '$2')}
|
|
LIMIT 1`,
|
|
[purchaseCode, input.branchCode]
|
|
);
|
|
const row = before.rows[0];
|
|
if (!row) {
|
|
throw Object.assign(new Error('采购单不存在'), { status: 404, code: 'not_found' });
|
|
}
|
|
const { purchaseLinkedToWarehouseDemand } = await import('./processingDemandSheetService');
|
|
if (await purchaseLinkedToWarehouseDemand(purchaseCode, db)) {
|
|
throw Object.assign(new Error('仓内加工成品自采只读,不能改挂采购员'), {
|
|
status: 409,
|
|
code: 'warehouse_demand_readonly',
|
|
});
|
|
}
|
|
const status = Number(row.purchase_status) || 0;
|
|
if (!isAssignablePurchaseStatus(status)) {
|
|
throw Object.assign(new Error('仅未完成采购单可改挂采购员'), {
|
|
status: 400,
|
|
code: 'invalid_status',
|
|
});
|
|
}
|
|
|
|
await db.query(
|
|
`UPDATE purchase_orders
|
|
SET purchaser_code = $2, purchaser_name = $3
|
|
WHERE purchase_code = $1`,
|
|
[purchaseCode, target.purchaser_code, target.purchaser_name]
|
|
);
|
|
|
|
await writeAuditLog({
|
|
operatorId: input.operatorId,
|
|
operationType: 'purchase_assign_purchaser',
|
|
targetTable: 'purchase_orders',
|
|
targetId: purchaseCode,
|
|
branchCode: input.branchCode,
|
|
actionCategory: 'purchase',
|
|
oldValue: {
|
|
purchaser_code: row.purchaser_code,
|
|
purchaser_name: row.purchaser_name,
|
|
},
|
|
newValue: {
|
|
purchaser_code: target.purchaser_code,
|
|
purchaser_name: target.purchaser_name,
|
|
},
|
|
}).catch(() => undefined);
|
|
|
|
return {
|
|
purchase_code: purchaseCode,
|
|
purchaser_code: target.purchaser_code,
|
|
purchaser_name: target.purchaser_name,
|
|
};
|
|
}
|