来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
284 lines
9.7 KiB
TypeScript
284 lines
9.7 KiB
TypeScript
import { pool } from '../db';
|
|
import type { PoolClient } from 'pg';
|
|
import type { TenantContext } from './tenantScope';
|
|
import { UNCATEGORIZED_SCOPE_KEY } from './pickingConfigService';
|
|
|
|
type Db = Pick<PoolClient, 'query'>;
|
|
|
|
export type PickingAssignRuleType = 'category' | 'customer';
|
|
|
|
export interface PickingAssignRuleRow {
|
|
id: string;
|
|
branch_code: string;
|
|
rule_type: PickingAssignRuleType;
|
|
scope_key: string;
|
|
picker_id: string;
|
|
is_active: boolean;
|
|
scope_label?: string | null;
|
|
picker_name?: string | null;
|
|
}
|
|
|
|
export interface PickingAssignRuleInput {
|
|
rule_type: PickingAssignRuleType;
|
|
scope_key: string;
|
|
picker_id: string;
|
|
is_active?: boolean;
|
|
}
|
|
|
|
function businessError(message: string, status = 400): Error {
|
|
return Object.assign(new Error(message), { status });
|
|
}
|
|
|
|
function normalizeRuleType(raw: unknown): PickingAssignRuleType {
|
|
const value = String(raw || '').trim().toLowerCase();
|
|
if (value === 'category' || value === 'customer') return value;
|
|
throw businessError('规则类型无效');
|
|
}
|
|
|
|
async function validatePicker(branchCode: string, pickerId: string) {
|
|
const result = await pool.query(
|
|
`SELECT p.id, p.branch_code
|
|
FROM profiles p
|
|
JOIN user_roles ur ON ur.user_id = p.id
|
|
JOIN role_permissions rp ON rp.role::text = ur.role::text
|
|
JOIN permissions perm ON perm.id = rp.permission_id AND perm.permission_code = 'picking_manage'
|
|
WHERE p.id = $1::uuid AND COALESCE(p.status, 1) = 1
|
|
AND ur.role::text = ANY(ARRAY['picker', 'warehouse', 'delivery']::text[])
|
|
LIMIT 1`,
|
|
[pickerId]
|
|
);
|
|
if (!result.rowCount) throw businessError('分拣员不存在或未开通分拣出库权限');
|
|
const rowBranch = result.rows[0]?.branch_code ? String(result.rows[0].branch_code) : '';
|
|
if (rowBranch && rowBranch !== branchCode) {
|
|
throw businessError('分拣员不属于当前分公司');
|
|
}
|
|
}
|
|
|
|
export async function resolvePickerFromAssignRules(
|
|
db: Db,
|
|
input: {
|
|
branchCode: string | null;
|
|
scopeType: string;
|
|
scopeKey: string | null;
|
|
orderCode?: string | null;
|
|
}
|
|
): Promise<string | null> {
|
|
const branch = input.branchCode ? String(input.branchCode).trim() : '';
|
|
if (!branch) return null;
|
|
|
|
const scopeType = String(input.scopeType || 'order').trim().toLowerCase();
|
|
const scopeKey = input.scopeKey ? String(input.scopeKey).trim() : '';
|
|
|
|
if (scopeType === 'category' && scopeKey) {
|
|
const categoryRule = await db.query(
|
|
`SELECT picker_id::text AS picker_id
|
|
FROM picking_assign_rules
|
|
WHERE branch_code = $1 AND rule_type = 'category' AND scope_key = $2 AND is_active = true
|
|
LIMIT 1`,
|
|
[branch, scopeKey]
|
|
);
|
|
if (categoryRule.rows[0]?.picker_id) return String(categoryRule.rows[0].picker_id);
|
|
}
|
|
|
|
let customerCode: string | null = null;
|
|
if (scopeType === 'customer' && scopeKey) {
|
|
customerCode = scopeKey;
|
|
} else if (input.orderCode) {
|
|
const orderRow = await db.query(
|
|
`SELECT customer_code FROM orders WHERE order_code = $1 LIMIT 1`,
|
|
[String(input.orderCode).trim()]
|
|
);
|
|
customerCode = orderRow.rows[0]?.customer_code ? String(orderRow.rows[0].customer_code).trim() : null;
|
|
}
|
|
|
|
if (customerCode) {
|
|
const customerRule = await db.query(
|
|
`SELECT picker_id::text AS picker_id
|
|
FROM picking_assign_rules
|
|
WHERE branch_code = $1 AND rule_type = 'customer' AND scope_key = $2 AND is_active = true
|
|
LIMIT 1`,
|
|
[branch, customerCode]
|
|
);
|
|
if (customerRule.rows[0]?.picker_id) return String(customerRule.rows[0].picker_id);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
export async function tryAutoAssignPickerOnTask(
|
|
db: Db,
|
|
input: {
|
|
pickCode: string;
|
|
branchCode: string | null;
|
|
scopeType: string;
|
|
scopeKey: string | null;
|
|
orderCode?: string | null;
|
|
}
|
|
): Promise<boolean> {
|
|
let scopeType = String(input.scopeType || 'order').trim().toLowerCase();
|
|
let scopeKey = input.scopeKey;
|
|
if (scopeType === 'sku') {
|
|
const cat = await db.query(
|
|
`SELECT COALESCE(NULLIF(TRIM(s.category_code), ''), $2) AS category_code
|
|
FROM picking_items pi
|
|
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
|
|
LEFT JOIN skus s
|
|
ON s.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
|
|
WHERE pi.pick_code = $1
|
|
LIMIT 1`,
|
|
[input.pickCode, UNCATEGORIZED_SCOPE_KEY]
|
|
);
|
|
scopeType = 'category';
|
|
scopeKey = cat.rows[0]?.category_code ? String(cat.rows[0].category_code) : UNCATEGORIZED_SCOPE_KEY;
|
|
}
|
|
const pickerId = await resolvePickerFromAssignRules(db, {
|
|
...input,
|
|
scopeType,
|
|
scopeKey,
|
|
});
|
|
if (!pickerId) return false;
|
|
const updated = await db.query(
|
|
`UPDATE picking_tasks
|
|
SET picker_id = $1::uuid
|
|
WHERE pick_code = $2 AND picker_id IS NULL AND pick_status < 40
|
|
RETURNING pick_code`,
|
|
[pickerId, input.pickCode]
|
|
);
|
|
return (updated.rowCount || 0) > 0;
|
|
}
|
|
|
|
export async function listPickingAssignRules(
|
|
branchCode: string,
|
|
ctx?: TenantContext | null
|
|
): Promise<PickingAssignRuleRow[]> {
|
|
const branch = String(branchCode || '').trim();
|
|
if (!branch) throw businessError('请切换到具体分公司');
|
|
if (ctx?.branchCode && !ctx.isSuperAdmin && ctx.branchCode !== branch) {
|
|
throw businessError('无权查看其他分公司分配规则', 403);
|
|
}
|
|
|
|
const result = await pool.query(
|
|
`SELECT r.id, r.branch_code, r.rule_type, r.scope_key, r.picker_id::text AS picker_id, r.is_active,
|
|
CASE
|
|
WHEN r.rule_type = 'category' AND r.scope_key = 'UNCATEGORIZED' THEN '未分类'
|
|
WHEN r.rule_type = 'category' THEN COALESCE(cat.category_name, r.scope_key)
|
|
WHEN r.rule_type = 'customer' THEN COALESCE(cust.company_name, r.scope_key)
|
|
ELSE r.scope_key
|
|
END AS scope_label,
|
|
COALESCE(NULLIF(TRIM(p.full_name), ''), NULLIF(TRIM(p.username), ''), p.id::text) AS picker_name
|
|
FROM picking_assign_rules r
|
|
LEFT JOIN categories cat
|
|
ON r.rule_type = 'category' AND cat.category_code = r.scope_key
|
|
AND (cat.branch_code = r.branch_code OR cat.branch_code IS NULL)
|
|
LEFT JOIN customers cust
|
|
ON r.rule_type = 'customer' AND cust.customer_code = r.scope_key
|
|
LEFT JOIN profiles p ON p.id = r.picker_id
|
|
WHERE r.branch_code = $1
|
|
ORDER BY r.rule_type ASC, scope_label ASC NULLS LAST, r.scope_key ASC`,
|
|
[branch]
|
|
);
|
|
return result.rows.map((row) => ({
|
|
id: String(row.id),
|
|
branch_code: String(row.branch_code),
|
|
rule_type: row.rule_type as PickingAssignRuleType,
|
|
scope_key: String(row.scope_key),
|
|
picker_id: String(row.picker_id),
|
|
is_active: Boolean(row.is_active),
|
|
scope_label: row.scope_label ? String(row.scope_label) : null,
|
|
picker_name: row.picker_name ? String(row.picker_name) : null,
|
|
}));
|
|
}
|
|
|
|
export async function savePickingAssignRules(
|
|
branchCode: string,
|
|
rules: PickingAssignRuleInput[],
|
|
ctx?: TenantContext | null
|
|
): Promise<PickingAssignRuleRow[]> {
|
|
const branch = String(branchCode || '').trim();
|
|
if (!branch) throw businessError('请切换到具体分公司');
|
|
if (ctx?.branchCode && !ctx.isSuperAdmin && ctx.branchCode !== branch) {
|
|
throw businessError('无权修改其他分公司分配规则', 403);
|
|
}
|
|
if (!Array.isArray(rules)) throw businessError('规则列表无效');
|
|
|
|
const normalized: Array<{
|
|
rule_type: PickingAssignRuleType;
|
|
scope_key: string;
|
|
picker_id: string;
|
|
is_active: boolean;
|
|
}> = [];
|
|
const seen = new Set<string>();
|
|
|
|
for (const raw of rules) {
|
|
const ruleType = normalizeRuleType(raw.rule_type);
|
|
const scopeKey = String(raw.scope_key || '').trim();
|
|
const pickerId = String(raw.picker_id || '').trim();
|
|
if (!scopeKey) throw businessError('请选择分类或客户');
|
|
if (!pickerId) throw businessError('请选择分拣员');
|
|
const dedupeKey = `${ruleType}::${scopeKey}`;
|
|
if (seen.has(dedupeKey)) continue;
|
|
seen.add(dedupeKey);
|
|
await validatePicker(branch, pickerId);
|
|
normalized.push({
|
|
rule_type: ruleType,
|
|
scope_key: scopeKey,
|
|
picker_id: pickerId,
|
|
is_active: raw.is_active !== false,
|
|
});
|
|
}
|
|
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query('BEGIN');
|
|
await client.query(`DELETE FROM picking_assign_rules WHERE branch_code = $1`, [branch]);
|
|
for (const row of normalized) {
|
|
await client.query(
|
|
`INSERT INTO picking_assign_rules (branch_code, rule_type, scope_key, picker_id, is_active, updated_at)
|
|
VALUES ($1, $2, $3, $4::uuid, $5, NOW())`,
|
|
[branch, row.rule_type, row.scope_key, row.picker_id, row.is_active]
|
|
);
|
|
}
|
|
await client.query('COMMIT');
|
|
} catch (error) {
|
|
await client.query('ROLLBACK').catch(() => undefined);
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
|
|
return listPickingAssignRules(branch, ctx);
|
|
}
|
|
|
|
export async function applyPickingAssignRules(
|
|
branchCode: string,
|
|
ctx?: TenantContext | null
|
|
): Promise<{ updated: number }> {
|
|
const branch = String(branchCode || '').trim();
|
|
if (!branch) throw businessError('请切换到具体分公司');
|
|
if (ctx?.branchCode && !ctx.isSuperAdmin && ctx.branchCode !== branch) {
|
|
throw businessError('无权操作其他分公司', 403);
|
|
}
|
|
|
|
const tasks = await pool.query(
|
|
`SELECT pick_code, branch_code, scope_type, scope_key, order_code
|
|
FROM picking_tasks
|
|
WHERE branch_code = $1 AND picker_id IS NULL AND pick_status < 40
|
|
ORDER BY created_at ASC`,
|
|
[branch]
|
|
);
|
|
|
|
let updated = 0;
|
|
for (const task of tasks.rows) {
|
|
const assigned = await tryAutoAssignPickerOnTask(pool, {
|
|
pickCode: String(task.pick_code),
|
|
branchCode: task.branch_code ? String(task.branch_code) : branch,
|
|
scopeType: String(task.scope_type || 'order'),
|
|
scopeKey: task.scope_key ? String(task.scope_key) : null,
|
|
orderCode: task.order_code ? String(task.order_code) : null,
|
|
});
|
|
if (assigned) updated += 1;
|
|
}
|
|
|
|
return { updated };
|
|
}
|