import { pool } from '../db'; import { DEFAULT_ALLOCATION_RULES, type AllocationRules, } from './allocationRules'; const CONFIG_KEY = 'allocation_rules'; function parseRules(raw: unknown): AllocationRules { if (!raw || typeof raw !== 'object') return { ...DEFAULT_ALLOCATION_RULES }; const obj = raw as Record; return { noSkuToPurchaser: obj.noSkuToPurchaser === undefined ? DEFAULT_ALLOCATION_RULES.noSkuToPurchaser : Boolean(obj.noSkuToPurchaser), uncategorizedToPurchaser: obj.uncategorizedToPurchaser === undefined ? DEFAULT_ALLOCATION_RULES.uncategorizedToPurchaser : Boolean(obj.uncategorizedToPurchaser), categoryMatchToSupplier: obj.categoryMatchToSupplier === undefined ? DEFAULT_ALLOCATION_RULES.categoryMatchToSupplier : Boolean(obj.categoryMatchToSupplier), noCategorySupplierToPurchaser: obj.noCategorySupplierToPurchaser === undefined ? DEFAULT_ALLOCATION_RULES.noCategorySupplierToPurchaser : Boolean(obj.noCategorySupplierToPurchaser), preferPrimarySupplier: obj.preferPrimarySupplier === undefined ? DEFAULT_ALLOCATION_RULES.preferPrimarySupplier : Boolean(obj.preferPrimarySupplier), autoSwitchOnFulfillmentRisk: obj.autoSwitchOnFulfillmentRisk === undefined ? DEFAULT_ALLOCATION_RULES.autoSwitchOnFulfillmentRisk : Boolean(obj.autoSwitchOnFulfillmentRisk), }; } export async function getAllocationRulesConfig( 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 = $1 AND branch_code = $2 LIMIT 1`, [CONFIG_KEY, code] ); if (branchRow.rows[0]?.config_value != null) { return parseRules(branchRow.rows[0].config_value); } } const globalRow = await pool.query( `SELECT config_value FROM system_configs WHERE config_key = $1 AND branch_code IS NULL LIMIT 1`, [CONFIG_KEY] ); if (globalRow.rows[0]?.config_value != null) { return parseRules(globalRow.rows[0].config_value); } return { ...DEFAULT_ALLOCATION_RULES }; } export async function setAllocationRulesConfig( branchCode: string, rules: Partial ): Promise { const branch = String(branchCode || '').trim(); if (!branch) { throw Object.assign(new Error('缺少分公司编码'), { status: 400 }); } const current = await getAllocationRulesConfig(branch); const next = parseRules({ ...current, ...rules }); const payload = JSON.stringify(next); const updated = await pool.query( `UPDATE system_configs SET config_value = $1::jsonb, updated_at = NOW() WHERE config_key = $2 AND branch_code = $3`, [payload, CONFIG_KEY, branch] ); if (!updated.rowCount) { await pool.query( `INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code) VALUES ($1, $2::jsonb, 'allocation', '智能分配规则(无SKU/分类供应商匹配等)', $3)`, [CONFIG_KEY, payload, branch] ); } return next; }