import { pool } from '../db'; export interface SmartAllocationConfig { enabled: boolean; } /** 默认开启,兼容现网自动分配行为 */ const DEFAULT_CONFIG: SmartAllocationConfig = { enabled: true, }; function parseConfigValue(raw: unknown): SmartAllocationConfig { if (!raw || typeof raw !== 'object') return { ...DEFAULT_CONFIG }; const obj = raw as Record; // 显式 false 才关闭;缺省 / 非布尔按默认 true if (obj.enabled === false) return { enabled: false }; if (obj.enabled === true) return { enabled: true }; return { ...DEFAULT_CONFIG }; } export async function getSmartAllocationConfig( branchCode?: string | null ): Promise { const code = String(branchCode || '').trim(); if (code) { const branchRow = await pool.query( `SELECT config_value FROM system_configs WHERE config_key = 'smart_allocation_enabled' AND branch_code = $1 LIMIT 1`, [code] ); if (branchRow.rows[0]?.config_value != null) { return parseConfigValue(branchRow.rows[0].config_value); } } const globalRow = await pool.query( `SELECT config_value FROM system_configs WHERE config_key = 'smart_allocation_enabled' AND branch_code IS NULL LIMIT 1` ); if (globalRow.rows[0]?.config_value != null) { return parseConfigValue(globalRow.rows[0].config_value); } return { ...DEFAULT_CONFIG }; } export async function isSmartAllocationEnabled(branchCode?: string | null): Promise { const cfg = await getSmartAllocationConfig(branchCode); return cfg.enabled !== false; } /** * 按分公司写入智能分配开关(upsert)。 * 仅写分公司行,不影响全局缺省。 */ export async function setSmartAllocationConfig( branchCode: string, enabled: boolean, updatedBy?: string | null ): Promise { const code = String(branchCode || '').trim(); if (!code) { throw Object.assign(new Error('请先选择操作分公司'), { status: 400, code: 'operating_branch_required', }); } const value = { enabled: enabled !== false }; const existing = await pool.query( `SELECT id FROM system_configs WHERE config_key = 'smart_allocation_enabled' AND branch_code = $1 LIMIT 1`, [code] ); if (existing.rows[0]?.id) { await pool.query( `UPDATE system_configs SET config_value = $1::jsonb, updated_at = NOW(), updated_by = $2 WHERE id = $3`, [JSON.stringify(value), updatedBy || null, existing.rows[0].id] ); } else { await pool.query( `INSERT INTO system_configs ( config_key, config_value, config_group, description, branch_code, updated_at, updated_by ) VALUES ( 'smart_allocation_enabled', $1::jsonb, 'order', '智能分配:enabled=开启后录单/推进自动按规则分配供应商;关闭后需手动分配', $2, NOW(), $3 )`, [JSON.stringify(value), code, updatedBy || null] ); } return value; }