import { pool } from '../db'; /** * 「分配完成后直接待配送」极简流转开关(按分公司)。 * * 业务:某分公司的流程是「录单 → 智能分配 → 直接待配送」,中间不走验收与分拣。 * 与 `smartAllocationConfigService` 同构(专用接口按分公司 upsert),区别: * 1) **默认关闭**(关闭时行为与现状逐字一致); * 2) **所有读写都显式写 `public.system_configs`** —— ⚠️ 2026-10-07 实测踩到的坑: * 写接口跑在租户上下文里(`search_path` 指向 `tenant_brXXX`),而分配完成后的读取是裸 `pool` * 查询(`search_path = "$user", public`)。不写全 schema 的话,**界面保存成功、后端却读不到**: * 实测行落在 `tenant_br002.system_configs`,而服务读到的是 public(0 行)⇒ 开关永远显示关闭, * 功能静默不生效。同类开关(智能分配/分拣)也存在这个 schema 不一致,只是当前两边取值恰好相同 * 才没暴露。 * * 见 docs/design/20261007-direct-to-delivery-mode.md */ export interface DirectToDeliveryConfig { enabled: boolean; } /** 默认**关闭**:没配过的分公司一律走老流程 */ const DEFAULT_CONFIG: DirectToDeliveryConfig = { enabled: false, }; const CONFIG_KEY = 'direct_to_delivery_enabled'; function parseConfigValue(raw: unknown): DirectToDeliveryConfig { if (!raw || typeof raw !== 'object') return { ...DEFAULT_CONFIG }; const obj = raw as Record; if (obj.enabled === true) return { enabled: true }; if (obj.enabled === false) return { enabled: false }; return { ...DEFAULT_CONFIG }; } /** * 只按**分公司**取值:没有分公司就等于关闭,**不回退全局行**。 * * 理由(2026-10-07 核查):这个开关一旦为真会把该分公司的订单直接推到待配送。若存在全局行 * (`branch_code IS NULL`)并被回退命中,就会「一行影响所有分公司」。写入侧已经拒绝无分公司写入, * 这里再把读取侧也收紧,双保险。 */ export async function getDirectToDeliveryConfig( branchCode?: string | null ): Promise { const code = String(branchCode || '').trim(); if (!code) return { ...DEFAULT_CONFIG }; const branchRow = await pool.query( `SELECT config_value FROM public.system_configs WHERE config_key = $1 AND branch_code = $2 LIMIT 1`, [CONFIG_KEY, code] ); if (branchRow.rows[0]?.config_value != null) { return parseConfigValue(branchRow.rows[0].config_value); } return { ...DEFAULT_CONFIG }; } type CacheEntry = { value: boolean; expiresAt: number }; const CACHE_MS = 5_000; const enabledCache = new Map(); function cacheKey(branchCode?: string | null): string { return String(branchCode || '').trim() || '__none__'; } /** * 开关是否开启(带 5 秒缓存)。 * 缓存是必要的:分配流程里要**逐条明细**判断(决定建不建备货单/采购单), * 每条查一次库太浪费;写法与 `pickingConfigService` 的开关缓存一致。 */ export async function isDirectToDeliveryEnabled(branchCode?: string | null): Promise { const key = cacheKey(branchCode); const hit = enabledCache.get(key); if (hit && hit.expiresAt > Date.now()) return hit.value; const cfg = await getDirectToDeliveryConfig(branchCode); const value = cfg.enabled === true; enabledCache.set(key, { value, expiresAt: Date.now() + CACHE_MS }); return value; } /** 写入开关后调用:立刻让缓存失效,避免「保存了但 5 秒内仍是旧值」 */ export function invalidateDirectToDeliveryCache(branchCode?: string | null): void { if (branchCode) enabledCache.delete(cacheKey(branchCode)); else enabledCache.clear(); } /** * 按分公司写入开关(upsert)。仅写分公司行,不影响全局缺省。 * 注意:**没有分公司时直接报错**,避免误写成"全局开启"影响所有分公司。 */ export async function setDirectToDeliveryConfig( 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: DirectToDeliveryConfig = { enabled: enabled === true }; const existing = await pool.query( `SELECT id FROM public.system_configs WHERE config_key = $1 AND branch_code = $2 LIMIT 1`, [CONFIG_KEY, code] ); if (existing.rows[0]?.id) { await pool.query( `UPDATE public.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 public.system_configs ( config_key, config_value, config_group, description, branch_code, updated_at, updated_by ) VALUES ( $1, $2::jsonb, 'delivery', '分配完成后直接待配送:enabled=录单+智能分配完成即进入待配送,不经过验收与分拣环节(配送时照常核货拍照);缺省/关闭时流程不变', $3, NOW(), $4 )`, [CONFIG_KEY, JSON.stringify(value), code, updatedBy || null] ); } invalidateDirectToDeliveryCache(code); return value; }