63 lines
2.2 KiB
TypeScript
63 lines
2.2 KiB
TypeScript
/**
|
||
* 仓内加工原料自动采购开关(阶段 1)
|
||
*
|
||
* 默认开启:只在成品配置了 processing_bom 时才触发,未配置的商品完全无行为变化。
|
||
* 关闭方式:system_configs.config_key='warehouse_processing_raw_purchase_enabled',
|
||
* 支持分公司级(branch_code)与全局(branch_code IS NULL)。
|
||
*/
|
||
import { pool } from '../db';
|
||
|
||
export const PROCESSING_RAW_PURCHASE_ENABLED_KEY = 'warehouse_processing_raw_purchase_enabled';
|
||
|
||
export interface ProcessingRawPurchaseConfig {
|
||
enabled: boolean;
|
||
}
|
||
|
||
export function parseProcessingRawPurchaseConfig(raw: unknown): ProcessingRawPurchaseConfig {
|
||
if (raw == null) return { enabled: true };
|
||
if (typeof raw === 'boolean') return { enabled: raw };
|
||
if (typeof raw === 'object') {
|
||
const obj = raw as Record<string, unknown>;
|
||
if (typeof obj.enabled === 'boolean') return { enabled: obj.enabled };
|
||
}
|
||
return { enabled: true };
|
||
}
|
||
|
||
export async function getProcessingRawPurchaseConfig(
|
||
branchCode?: string | null
|
||
): Promise<ProcessingRawPurchaseConfig> {
|
||
const code = String(branchCode || '').trim();
|
||
try {
|
||
if (code) {
|
||
const branchRow = await pool.query(
|
||
`SELECT config_value FROM system_configs
|
||
WHERE config_key = $1 AND branch_code = $2
|
||
LIMIT 1`,
|
||
[PROCESSING_RAW_PURCHASE_ENABLED_KEY, code]
|
||
);
|
||
if (branchRow.rows[0]?.config_value != null) {
|
||
return parseProcessingRawPurchaseConfig(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`,
|
||
[PROCESSING_RAW_PURCHASE_ENABLED_KEY]
|
||
);
|
||
if (globalRow.rows[0]?.config_value != null) {
|
||
return parseProcessingRawPurchaseConfig(globalRow.rows[0].config_value);
|
||
}
|
||
} catch (error: any) {
|
||
// 配置表不可用时不阻断业务:按默认开启(有 BOM 才触发)
|
||
console.warn('[processing-raw] 读取自动采购开关失败,按默认开启处理', error?.message || error);
|
||
}
|
||
return { enabled: true };
|
||
}
|
||
|
||
export async function isProcessingRawPurchaseEnabled(
|
||
branchCode?: string | null
|
||
): Promise<boolean> {
|
||
return (await getProcessingRawPurchaseConfig(branchCode)).enabled;
|
||
}
|