import { pool } from '../db'; import type { Pool, PoolClient } from 'pg'; import type { PurchaserAssignMode } from './purchasePurchaserAssignService'; export type PurchaseAssignDefaultConfig = { /** null = 未配置,建单回退主采购员 */ mode: PurchaserAssignMode | null; purchaser_code: string; }; type Db = Pool | PoolClient; const CONFIG_KEY = 'purchase_assign_default'; const CONFIG_GROUP = 'purchase'; const CONFIG_DESCRIPTION = '自采默认分配:建单时挂采购员。mode=by_sku|by_category|to_purchaser|free_pool;to_purchaser 需 purchaser_code'; const MODES = new Set(['by_sku', 'by_category', 'to_purchaser', 'free_pool']); export function parsePurchaseAssignDefaultConfig(raw: unknown): PurchaseAssignDefaultConfig { if (raw == null || typeof raw !== 'object') { return { mode: null, purchaser_code: '' }; } const obj = raw as Record; const modeRaw = String(obj.mode || '').trim() as PurchaserAssignMode; if (!MODES.has(modeRaw)) { return { mode: null, purchaser_code: '' }; } return { mode: modeRaw, purchaser_code: String(obj.purchaser_code || '').trim(), }; } export async function getPurchaseAssignDefaultConfig( branchCode?: string | null, db: Db = pool ): Promise { const code = String(branchCode || '').trim(); if (!code) return { mode: null, purchaser_code: '' }; const branchRow = await db.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 parsePurchaseAssignDefaultConfig(branchRow.rows[0].config_value); } return { mode: null, purchaser_code: '' }; } export async function setPurchaseAssignDefaultConfig( branchCode: string, input: { mode: unknown; purchaser_code?: unknown } ): Promise { const branch = String(branchCode || '').trim(); if (!branch) { throw Object.assign(new Error('缺少分公司编码'), { status: 400, code: 'invalid_request' }); } const modeRaw = String(input.mode || '').trim() as PurchaserAssignMode; if (!MODES.has(modeRaw)) { throw Object.assign(new Error('无效的分配方式'), { status: 400, code: 'invalid_request' }); } let purchaser_code = String(input.purchaser_code || '').trim(); if (modeRaw === 'to_purchaser') { if (!purchaser_code) { throw Object.assign(new Error('指定采购员时请选择采购员'), { status: 400, code: 'invalid_request', }); } } else { purchaser_code = modeRaw === 'free_pool' ? '' : purchaser_code; } const next: PurchaseAssignDefaultConfig = { mode: modeRaw, purchaser_code }; const payload = JSON.stringify(next); const updated = await pool.query( `UPDATE system_configs SET config_value = $1::jsonb, updated_at = NOW(), description = $4 WHERE config_key = $2 AND branch_code = $3`, [payload, CONFIG_KEY, branch, CONFIG_DESCRIPTION] ); if (!updated.rowCount) { await pool.query( `INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code) VALUES ($1, $2::jsonb, $4, $5, $3)`, [CONFIG_KEY, payload, branch, CONFIG_GROUP, CONFIG_DESCRIPTION] ); } return next; }