来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
171 lines
5.6 KiB
TypeScript
171 lines
5.6 KiB
TypeScript
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<string, unknown>;
|
||
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<OrderSubmitWindowConfig> {
|
||
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<OrderSubmitWindowConfig> {
|
||
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<OrderSubmitWindowConfig> {
|
||
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' }
|
||
);
|
||
}
|