import { pool } from '../db'; import { formatChinaDate } from '../utils/chinaDate'; export interface OrderSubmitWindowConfig { /** true=全天不限制(默认) */ all_day: boolean; /** HH:MM,中国时区 */ start_hm: string; /** HH:MM,中国时区;可等于 start 表示全天;可小于 start 表示跨夜 */ end_hm: string; } const CONFIG_KEY = 'order_submit_window'; const DEFAULT_CONFIG: OrderSubmitWindowConfig = { all_day: true, start_hm: '00:00', end_hm: '23:59', }; const HM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/; export function normalizeHm(raw: unknown, fallback: string): string { const s = String(raw || '').trim(); if (HM_RE.test(s)) return s; return fallback; } function hmToMinutes(hm: string): number { const [h, m] = hm.split(':').map((x) => Number(x)); return h * 60 + m; } function parseConfigValue(raw: unknown): OrderSubmitWindowConfig { if (!raw || typeof raw !== 'object') return { ...DEFAULT_CONFIG }; const obj = raw as Record; if (obj.all_day === false || obj.all_day === 'false' || obj.all_day === 0) { return { all_day: false, start_hm: normalizeHm(obj.start_hm, DEFAULT_CONFIG.start_hm), end_hm: normalizeHm(obj.end_hm, DEFAULT_CONFIG.end_hm), }; } return { ...DEFAULT_CONFIG, all_day: true }; } /** 当前中国时区是否在下单窗内(含端点) */ export function isNowWithinOrderSubmitWindow( cfg: OrderSubmitWindowConfig, now: Date = new Date() ): boolean { if (cfg.all_day !== false) return true; const start = hmToMinutes(normalizeHm(cfg.start_hm, '00:00')); const end = hmToMinutes(normalizeHm(cfg.end_hm, '23:59')); const parts = new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit', hour12: false, }).formatToParts(now); const hour = Number(parts.find((p) => p.type === 'hour')?.value || 0); const minute = Number(parts.find((p) => p.type === 'minute')?.value || 0); const cur = hour * 60 + minute; if (start === end) return true; // 起止相同视为全天 if (start < end) return cur >= start && cur <= end; // 跨夜:如 22:00–06:00 return cur >= start || cur <= end; } export async function getOrderSubmitWindowConfig( 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 parseConfigValue(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 parseConfigValue(globalRow.rows[0].config_value); } return { ...DEFAULT_CONFIG }; } export async function setOrderSubmitWindowConfig( branchCode: string, input: { all_day?: boolean; start_hm?: string; end_hm?: string }, updatedBy?: string | null ): Promise { const code = String(branchCode || '').trim(); if (!code) { throw Object.assign(new Error('请先选择操作分公司'), { status: 400, code: 'operating_branch_required', }); } const allDay = input.all_day !== false; const value: OrderSubmitWindowConfig = allDay ? { ...DEFAULT_CONFIG, all_day: true } : { all_day: false, start_hm: normalizeHm(input.start_hm, '00:00'), end_hm: normalizeHm(input.end_hm, '23:59'), }; if (!allDay && !HM_RE.test(value.start_hm)) { throw Object.assign(new Error('开始时刻格式须为 HH:MM'), { status: 400, code: 'invalid_request' }); } if (!allDay && !HM_RE.test(value.end_hm)) { throw Object.assign(new Error('结束时刻格式须为 HH:MM'), { status: 400, code: 'invalid_request' }); } const existing = await pool.query( `SELECT id FROM system_configs WHERE config_key = $1 AND branch_code = $2 LIMIT 1`, [CONFIG_KEY, 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 ( $1, $2::jsonb, 'order', '下单时段:all_day=全天;否则中国时区 start_hm–end_hm(可跨夜);窗外仅 admin 可录单', $3, NOW(), $4 )`, [CONFIG_KEY, JSON.stringify(value), code, updatedBy || null] ); } return value; } /** * 非管理员在窗外禁止新建订单。管理员放行。 */ export async function assertOrderSubmitWindowAllowed(options: { branchCode?: string | null; isAdmin: boolean; now?: Date; }): Promise { const cfg = await getOrderSubmitWindowConfig(options.branchCode); if (options.isAdmin) return cfg; if (isNowWithinOrderSubmitWindow(cfg, options.now)) return cfg; const day = formatChinaDate(options.now || new Date()); const tip = cfg.all_day ? '' : `(当前限制 ${cfg.start_hm}–${cfg.end_hm},中国时区;今天 ${day})`; throw Object.assign( new Error(`当前不在允许下单时段内${tip},请在规定时间内下单或联系管理员`), { status: 403, code: 'order_window_closed' } ); }