来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
617 lines
22 KiB
TypeScript
617 lines
22 KiB
TypeScript
import { pool } from '../db';
|
|
import { formatChinaDate } from '../utils/chinaDate';
|
|
|
|
// 按单竞价的触发方式:界面上只提供「自动发标」一个可选项。
|
|
// 历史值 'manual' 仍在类型内(旧数据/旧客户端可能带着它),但手动发起从未实现入口,
|
|
// 选了等于竞价静默失效;各分公司重新保存一次配置即改写为 auto。
|
|
export type BidPerOrderMode = 'auto' | 'manual';
|
|
export type BidScopeMode = 'sku' | 'category';
|
|
export type BidCycleType = 'per_order' | 'day' | 'week' | 'month' | 'custom';
|
|
export type BidAwardMode = 'lowest' | 'composite';
|
|
|
|
export type BidSkuScopeItem = {
|
|
sku_code: string;
|
|
supplier_code: string;
|
|
};
|
|
|
|
export type BidCategoryScopeItem = {
|
|
category_code: string;
|
|
supplier_code: string;
|
|
};
|
|
|
|
export interface BidSettings {
|
|
enabled: boolean;
|
|
/** 顶层互斥:按每单 / 天 / 周 / 月 / 自定义时间段(中标有效周期) */
|
|
cycle_type: BidCycleType;
|
|
/** 仅 cycle_type=custom */
|
|
custom_period_start: string | null;
|
|
custom_period_end: string | null;
|
|
/** 仅 cycle_type=per_order 生效 */
|
|
per_order_mode: BidPerOrderMode;
|
|
/**
|
|
* 无固定报价窗时:开标后倒计时分钟。
|
|
* 有 quote_window_* 时发标截止改用窗结束时刻。
|
|
*/
|
|
respond_minutes: number;
|
|
/** 固定报价时间段起止(东八区 HH:MM);成对填写才生效 */
|
|
quote_window_start: string;
|
|
quote_window_end: string;
|
|
/**
|
|
* 按建议中标自动确认(最低价或综合分,取决于 award_mode):
|
|
* - true:全员报价或超时后自动 confirm 并触发分配(受 hold 影响)
|
|
* - false:须在历史竞价人工确认中标
|
|
*/
|
|
auto_award_lowest: boolean;
|
|
/** 建议中标策略 */
|
|
award_mode: BidAwardMode;
|
|
award_weight_price: number;
|
|
award_weight_quality: number;
|
|
award_weight_response: number;
|
|
/**
|
|
* 中标确认后暂停自动分配的手调窗口(分钟)。
|
|
* 0 = 立即分配(兼容现网);>0 时写 hold,到点或管理员点「手调完成」后再分配。
|
|
*/
|
|
post_award_hold_allocation_minutes: number;
|
|
/** 兼容字段:有分类无商品时记 category,否则 sku */
|
|
scope_mode: BidScopeMode;
|
|
/** 派生:参与商品编码 */
|
|
sku_codes: string[];
|
|
/** 派生:参与分类编码 */
|
|
category_codes: string[];
|
|
/** 商品竞价项(含默认/首选供应商) */
|
|
sku_items: BidSkuScopeItem[];
|
|
/** 分类竞价项(含默认/首选供应商) */
|
|
category_items: BidCategoryScopeItem[];
|
|
}
|
|
|
|
const CONFIG_KEY = 'bid_settings';
|
|
|
|
const DEFAULT_SETTINGS: BidSettings = {
|
|
enabled: false,
|
|
cycle_type: 'per_order',
|
|
custom_period_start: null,
|
|
custom_period_end: null,
|
|
per_order_mode: 'manual',
|
|
respond_minutes: 30,
|
|
quote_window_start: '',
|
|
quote_window_end: '',
|
|
auto_award_lowest: false,
|
|
award_mode: 'lowest',
|
|
award_weight_price: 0.5,
|
|
award_weight_quality: 0.3,
|
|
award_weight_response: 0.2,
|
|
post_award_hold_allocation_minutes: 0,
|
|
scope_mode: 'sku',
|
|
sku_codes: [],
|
|
category_codes: [],
|
|
sku_items: [],
|
|
category_items: [],
|
|
};
|
|
|
|
function normalizeCodeList(raw: unknown): string[] {
|
|
if (!Array.isArray(raw)) return [];
|
|
const out: string[] = [];
|
|
const seen = new Set<string>();
|
|
for (const item of raw) {
|
|
const code = String(item || '').trim();
|
|
if (!code || seen.has(code)) continue;
|
|
seen.add(code);
|
|
out.push(code);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function normalizeSkuItems(raw: unknown, fallbackCodes?: unknown): BidSkuScopeItem[] {
|
|
if (Array.isArray(raw)) {
|
|
const out: BidSkuScopeItem[] = [];
|
|
const seen = new Set<string>();
|
|
for (const item of raw) {
|
|
if (!item || typeof item !== 'object') continue;
|
|
const row = item as Record<string, unknown>;
|
|
const sku_code = String(row.sku_code || '').trim();
|
|
if (!sku_code || seen.has(sku_code)) continue;
|
|
seen.add(sku_code);
|
|
out.push({
|
|
sku_code,
|
|
supplier_code: String(row.supplier_code || '').trim(),
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
return normalizeCodeList(fallbackCodes).map((sku_code) => ({
|
|
sku_code,
|
|
supplier_code: '',
|
|
}));
|
|
}
|
|
|
|
function normalizeCategoryItems(raw: unknown, fallbackCodes?: unknown): BidCategoryScopeItem[] {
|
|
if (Array.isArray(raw)) {
|
|
const out: BidCategoryScopeItem[] = [];
|
|
const seen = new Set<string>();
|
|
for (const item of raw) {
|
|
if (!item || typeof item !== 'object') continue;
|
|
const row = item as Record<string, unknown>;
|
|
const category_code = String(row.category_code || '').trim();
|
|
if (!category_code || seen.has(category_code)) continue;
|
|
seen.add(category_code);
|
|
out.push({
|
|
category_code,
|
|
supplier_code: String(row.supplier_code || '').trim(),
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
return normalizeCodeList(fallbackCodes).map((category_code) => ({
|
|
category_code,
|
|
supplier_code: '',
|
|
}));
|
|
}
|
|
|
|
function normalizeCycleType(raw: unknown): BidCycleType {
|
|
const t = String(raw || '').trim();
|
|
if (t === 'day' || t === 'week' || t === 'month' || t === 'custom') return t;
|
|
return 'per_order';
|
|
}
|
|
|
|
function normalizeDateOnly(raw: unknown): string | null {
|
|
const s = String(raw || '').trim().slice(0, 10);
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
|
|
return s;
|
|
}
|
|
|
|
function addDaysYmd(ymd: string, days: number): string {
|
|
const [y, m, d] = ymd.split('-').map(Number);
|
|
const dt = new Date(Date.UTC(y, m - 1, d));
|
|
dt.setUTCDate(dt.getUTCDate() + days);
|
|
return `${dt.getUTCFullYear()}-${String(dt.getUTCMonth() + 1).padStart(2, '0')}-${String(
|
|
dt.getUTCDate()
|
|
).padStart(2, '0')}`;
|
|
}
|
|
|
|
function daysBetweenYmd(start: string, end: string): number {
|
|
const [y1, m1, d1] = start.split('-').map(Number);
|
|
const [y2, m2, d2] = end.split('-').map(Number);
|
|
const a = Date.UTC(y1, m1 - 1, d1);
|
|
const b = Date.UTC(y2, m2 - 1, d2);
|
|
return Math.round((b - a) / 86400000);
|
|
}
|
|
|
|
function startOfWeekMonday(ymd: string): string {
|
|
const [y, m, d] = ymd.split('-').map(Number);
|
|
const dt = new Date(Date.UTC(y, m - 1, d));
|
|
const dow = dt.getUTCDay(); // 0=Sun
|
|
const offset = dow === 0 ? -6 : 1 - dow;
|
|
return addDaysYmd(ymd, offset);
|
|
}
|
|
|
|
function endOfMonth(ymd: string): string {
|
|
const [y, m] = ymd.split('-').map(Number);
|
|
const last = new Date(Date.UTC(y, m, 0)).getUTCDate();
|
|
return `${y}-${String(m).padStart(2, '0')}-${String(last).padStart(2, '0')}`;
|
|
}
|
|
|
|
function startOfMonth(ymd: string): string {
|
|
const [y, m] = ymd.split('-').map(Number);
|
|
return `${y}-${String(m).padStart(2, '0')}-01`;
|
|
}
|
|
|
|
function nextMonthWindow(start: string): { start: string; end: string } {
|
|
const [y, m] = start.split('-').map(Number);
|
|
const ny = m === 12 ? y + 1 : y;
|
|
const nm = m === 12 ? 1 : m + 1;
|
|
const nextStart = `${ny}-${String(nm).padStart(2, '0')}-01`;
|
|
return { start: nextStart, end: endOfMonth(nextStart) };
|
|
}
|
|
|
|
/** 按设置解析本期竞价窗(东八区日历) */
|
|
export function resolveBidPeriodWindow(
|
|
settings: Pick<BidSettings, 'cycle_type' | 'custom_period_start' | 'custom_period_end'>,
|
|
now = new Date()
|
|
): { start: string; end: string } {
|
|
const today = formatChinaDate(now);
|
|
switch (settings.cycle_type) {
|
|
case 'day':
|
|
return { start: today, end: today };
|
|
case 'week': {
|
|
const start = startOfWeekMonday(today);
|
|
return { start, end: addDaysYmd(start, 6) };
|
|
}
|
|
case 'month':
|
|
return { start: startOfMonth(today), end: endOfMonth(today) };
|
|
case 'custom': {
|
|
const start = normalizeDateOnly(settings.custom_period_start);
|
|
const end = normalizeDateOnly(settings.custom_period_end);
|
|
if (!start || !end || start > end) {
|
|
throw Object.assign(new Error('自定义时间段须填写有效起止日期'), {
|
|
status: 400,
|
|
code: 'invalid_request',
|
|
});
|
|
}
|
|
return { start, end };
|
|
}
|
|
default:
|
|
throw Object.assign(new Error('按每单模式无周期窗'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
}
|
|
|
|
/** 由本期起止推下一窗(沿用) */
|
|
export function computeNextBidPeriodWindow(
|
|
periodStart: string,
|
|
periodEnd: string,
|
|
cycleType: BidCycleType
|
|
): { start: string; end: string } {
|
|
const start = normalizeDateOnly(periodStart);
|
|
const end = normalizeDateOnly(periodEnd);
|
|
if (!start || !end || start > end) {
|
|
throw Object.assign(new Error('原轮次周期日期无效'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
if (cycleType === 'month') {
|
|
return nextMonthWindow(start);
|
|
}
|
|
if (cycleType === 'week') {
|
|
return { start: addDaysYmd(start, 7), end: addDaysYmd(end, 7) };
|
|
}
|
|
// day / custom / fallback:等长平移
|
|
const len = daysBetweenYmd(start, end);
|
|
const nextStart = addDaysYmd(end, 1);
|
|
return { start: nextStart, end: addDaysYmd(nextStart, len) };
|
|
}
|
|
|
|
/** HH:MM → {h,m};非法返回 null */
|
|
export function parseQuoteWindowHm(raw: unknown): { h: number; m: number } | null {
|
|
const s = String(raw || '').trim();
|
|
const m = /^(\d{1,2}):(\d{2})$/.exec(s);
|
|
if (!m) return null;
|
|
const h = Number(m[1]);
|
|
const min = Number(m[2]);
|
|
if (!Number.isFinite(h) || !Number.isFinite(min) || h < 0 || h > 23 || min < 0 || min > 59) {
|
|
return null;
|
|
}
|
|
return { h, m: min };
|
|
}
|
|
|
|
function normalizeQuoteWindowHm(raw: unknown): string {
|
|
const p = parseQuoteWindowHm(raw);
|
|
if (!p) return '';
|
|
return `${String(p.h).padStart(2, '0')}:${String(p.m).padStart(2, '0')}`;
|
|
}
|
|
|
|
function chinaAtHmOnYmd(ymd: string, h: number, m: number): Date {
|
|
const hh = String(h).padStart(2, '0');
|
|
const mm = String(m).padStart(2, '0');
|
|
return new Date(`${ymd}T${hh}:${mm}:00+08:00`);
|
|
}
|
|
|
|
/**
|
|
* 自动发标预约开标时刻:
|
|
* - 无有效窗 → null(立即开标)
|
|
* - 未到当日 start → 当日 start
|
|
* - 窗内 → null(立即开标)
|
|
* - 已过当日 end → 次日 start
|
|
*/
|
|
export function resolveScheduledOpenAt(
|
|
settings: Pick<BidSettings, 'quote_window_start' | 'quote_window_end'>,
|
|
now: Date = new Date()
|
|
): Date | null {
|
|
const startHm = parseQuoteWindowHm(settings.quote_window_start);
|
|
const endHm = parseQuoteWindowHm(settings.quote_window_end);
|
|
if (!startHm || !endHm) return null;
|
|
const startMin = startHm.h * 60 + startHm.m;
|
|
const endMin = endHm.h * 60 + endHm.m;
|
|
if (startMin >= endMin) return null;
|
|
const ymd = formatChinaDate(now);
|
|
const start = chinaAtHmOnYmd(ymd, startHm.h, startHm.m);
|
|
const end = chinaAtHmOnYmd(ymd, endHm.h, endHm.m);
|
|
const t = now.getTime();
|
|
if (t < start.getTime()) return start;
|
|
if (t < end.getTime()) return null;
|
|
return chinaAtHmOnYmd(addDaysYmd(ymd, 1), startHm.h, startHm.m);
|
|
}
|
|
|
|
/** 排队草稿且未到预约开标时刻 */
|
|
export function isQueuedDraftWaiting(scheduledOpenAt: unknown, now: Date = new Date()): boolean {
|
|
if (scheduledOpenAt == null || scheduledOpenAt === '') return false;
|
|
const t = new Date(String(scheduledOpenAt)).getTime();
|
|
return Number.isFinite(t) && t > now.getTime();
|
|
}
|
|
|
|
/**
|
|
* 发标响应截止:
|
|
* - 配置了有效报价窗 → 东八区当日窗结束;若已过结束则次日结束
|
|
* - 否则 → openedAt + respond_minutes
|
|
*/
|
|
export function resolveQuoteRespondDeadline(
|
|
settings: Pick<
|
|
BidSettings,
|
|
'quote_window_start' | 'quote_window_end' | 'respond_minutes'
|
|
>,
|
|
openedAt: Date = new Date()
|
|
): Date {
|
|
const startHm = parseQuoteWindowHm(settings.quote_window_start);
|
|
const endHm = parseQuoteWindowHm(settings.quote_window_end);
|
|
if (startHm && endHm) {
|
|
const startMin = startHm.h * 60 + startHm.m;
|
|
const endMin = endHm.h * 60 + endHm.m;
|
|
if (startMin < endMin) {
|
|
const ymd = formatChinaDate(openedAt);
|
|
let end = chinaAtHmOnYmd(ymd, endHm.h, endHm.m);
|
|
if (openedAt.getTime() >= end.getTime()) {
|
|
end = chinaAtHmOnYmd(addDaysYmd(ymd, 1), endHm.h, endHm.m);
|
|
}
|
|
return end;
|
|
}
|
|
}
|
|
const minutes =
|
|
Number.isFinite(settings.respond_minutes) && settings.respond_minutes > 0
|
|
? settings.respond_minutes
|
|
: DEFAULT_SETTINGS.respond_minutes;
|
|
return new Date(openedAt.getTime() + minutes * 60 * 1000);
|
|
}
|
|
|
|
function normalizeAwardWeights(raw: {
|
|
price?: unknown;
|
|
quality?: unknown;
|
|
response?: unknown;
|
|
}): { price: number; quality: number; response: number } {
|
|
let price = Number(raw.price);
|
|
let quality = Number(raw.quality);
|
|
let response = Number(raw.response);
|
|
if (!Number.isFinite(price) || price < 0) price = DEFAULT_SETTINGS.award_weight_price;
|
|
if (!Number.isFinite(quality) || quality < 0) quality = DEFAULT_SETTINGS.award_weight_quality;
|
|
if (!Number.isFinite(response) || response < 0) response = DEFAULT_SETTINGS.award_weight_response;
|
|
const sum = price + quality + response;
|
|
if (sum <= 0) {
|
|
return {
|
|
price: DEFAULT_SETTINGS.award_weight_price,
|
|
quality: DEFAULT_SETTINGS.award_weight_quality,
|
|
response: DEFAULT_SETTINGS.award_weight_response,
|
|
};
|
|
}
|
|
return {
|
|
price: Math.round((price / sum) * 1000) / 1000,
|
|
quality: Math.round((quality / sum) * 1000) / 1000,
|
|
response: Math.round((response / sum) * 1000) / 1000,
|
|
};
|
|
}
|
|
|
|
function parseSettings(raw: unknown): BidSettings {
|
|
if (!raw || typeof raw !== 'object') {
|
|
return {
|
|
...DEFAULT_SETTINGS,
|
|
sku_codes: [],
|
|
category_codes: [],
|
|
sku_items: [],
|
|
category_items: [],
|
|
};
|
|
}
|
|
const obj = raw as Record<string, unknown>;
|
|
const minutes = Number(obj.respond_minutes);
|
|
const holdMinutes = Number(obj.post_award_hold_allocation_minutes);
|
|
const sku_items = normalizeSkuItems(obj.sku_items, obj.sku_codes);
|
|
const category_items = normalizeCategoryItems(obj.category_items, obj.category_codes);
|
|
const sku_codes = sku_items.map((i) => i.sku_code);
|
|
const category_codes = category_items.map((i) => i.category_code);
|
|
const quote_window_start = normalizeQuoteWindowHm(obj.quote_window_start);
|
|
const quote_window_end = normalizeQuoteWindowHm(obj.quote_window_end);
|
|
const weights = normalizeAwardWeights({
|
|
price: obj.award_weight_price,
|
|
quality: obj.award_weight_quality,
|
|
response: obj.award_weight_response,
|
|
});
|
|
return {
|
|
enabled: obj.enabled === true,
|
|
cycle_type: normalizeCycleType(obj.cycle_type),
|
|
custom_period_start: normalizeDateOnly(obj.custom_period_start),
|
|
custom_period_end: normalizeDateOnly(obj.custom_period_end),
|
|
per_order_mode: obj.per_order_mode === 'auto' ? 'auto' : 'manual',
|
|
respond_minutes:
|
|
Number.isFinite(minutes) && minutes > 0 && minutes <= 10080
|
|
? Math.round(minutes)
|
|
: DEFAULT_SETTINGS.respond_minutes,
|
|
quote_window_start,
|
|
quote_window_end,
|
|
auto_award_lowest: obj.auto_award_lowest === true,
|
|
award_mode: obj.award_mode === 'composite' ? 'composite' : 'lowest',
|
|
award_weight_price: weights.price,
|
|
award_weight_quality: weights.quality,
|
|
award_weight_response: weights.response,
|
|
post_award_hold_allocation_minutes:
|
|
Number.isFinite(holdMinutes) && holdMinutes >= 0 && holdMinutes <= 10080
|
|
? Math.round(holdMinutes)
|
|
: DEFAULT_SETTINGS.post_award_hold_allocation_minutes,
|
|
scope_mode: obj.scope_mode === 'category' ? 'category' : 'sku',
|
|
sku_codes,
|
|
category_codes,
|
|
sku_items,
|
|
category_items,
|
|
};
|
|
}
|
|
|
|
/** @internal 单测用 */
|
|
export function parseBidSettingsForTest(raw: unknown): BidSettings {
|
|
return parseSettings(raw);
|
|
}
|
|
|
|
export async function getBidSettings(branchCode?: string | null): Promise<BidSettings> {
|
|
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 parseSettings(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 parseSettings(globalRow.rows[0].config_value);
|
|
}
|
|
return {
|
|
...DEFAULT_SETTINGS,
|
|
sku_codes: [],
|
|
category_codes: [],
|
|
sku_items: [],
|
|
category_items: [],
|
|
};
|
|
}
|
|
|
|
export async function saveBidSettings(
|
|
branchCode: string | null | undefined,
|
|
patch: Partial<BidSettings>,
|
|
updatedBy?: string | null
|
|
): Promise<BidSettings> {
|
|
const code = String(branchCode || '').trim() || null;
|
|
const current = await getBidSettings(code);
|
|
const merged: Record<string, unknown> = {
|
|
enabled: current.enabled,
|
|
cycle_type: current.cycle_type,
|
|
custom_period_start: current.custom_period_start,
|
|
custom_period_end: current.custom_period_end,
|
|
per_order_mode: current.per_order_mode,
|
|
respond_minutes: current.respond_minutes,
|
|
quote_window_start: current.quote_window_start,
|
|
quote_window_end: current.quote_window_end,
|
|
auto_award_lowest: current.auto_award_lowest,
|
|
award_mode: current.award_mode,
|
|
award_weight_price: current.award_weight_price,
|
|
award_weight_quality: current.award_weight_quality,
|
|
award_weight_response: current.award_weight_response,
|
|
post_award_hold_allocation_minutes: current.post_award_hold_allocation_minutes,
|
|
scope_mode: current.scope_mode,
|
|
sku_items: current.sku_items,
|
|
category_items: current.category_items,
|
|
};
|
|
if (patch.enabled !== undefined) merged.enabled = patch.enabled;
|
|
if (patch.cycle_type !== undefined) merged.cycle_type = patch.cycle_type;
|
|
if (patch.custom_period_start !== undefined) merged.custom_period_start = patch.custom_period_start;
|
|
if (patch.custom_period_end !== undefined) merged.custom_period_end = patch.custom_period_end;
|
|
if (patch.per_order_mode !== undefined) merged.per_order_mode = patch.per_order_mode;
|
|
if (patch.respond_minutes !== undefined) merged.respond_minutes = patch.respond_minutes;
|
|
if (patch.quote_window_start !== undefined) merged.quote_window_start = patch.quote_window_start;
|
|
if (patch.quote_window_end !== undefined) merged.quote_window_end = patch.quote_window_end;
|
|
if (patch.auto_award_lowest !== undefined) merged.auto_award_lowest = patch.auto_award_lowest;
|
|
if (patch.award_mode !== undefined) merged.award_mode = patch.award_mode;
|
|
if (patch.award_weight_price !== undefined) merged.award_weight_price = patch.award_weight_price;
|
|
if (patch.award_weight_quality !== undefined) {
|
|
merged.award_weight_quality = patch.award_weight_quality;
|
|
}
|
|
if (patch.award_weight_response !== undefined) {
|
|
merged.award_weight_response = patch.award_weight_response;
|
|
}
|
|
if (patch.post_award_hold_allocation_minutes !== undefined) {
|
|
merged.post_award_hold_allocation_minutes = patch.post_award_hold_allocation_minutes;
|
|
}
|
|
if (patch.scope_mode !== undefined) merged.scope_mode = patch.scope_mode;
|
|
if (patch.sku_items !== undefined) {
|
|
merged.sku_items = patch.sku_items;
|
|
} else if (patch.sku_codes !== undefined) {
|
|
const supplierMap = new Map(current.sku_items.map((i) => [i.sku_code, i.supplier_code]));
|
|
merged.sku_items = normalizeCodeList(patch.sku_codes).map((sku_code) => ({
|
|
sku_code,
|
|
supplier_code: supplierMap.get(sku_code) || '',
|
|
}));
|
|
}
|
|
if (patch.category_items !== undefined) {
|
|
merged.category_items = patch.category_items;
|
|
} else if (patch.category_codes !== undefined) {
|
|
const supplierMap = new Map(
|
|
current.category_items.map((i) => [i.category_code, i.supplier_code])
|
|
);
|
|
merged.category_items = normalizeCodeList(patch.category_codes).map((category_code) => ({
|
|
category_code,
|
|
supplier_code: supplierMap.get(category_code) || '',
|
|
}));
|
|
}
|
|
const next = parseSettings(merged);
|
|
if (next.quote_window_start || next.quote_window_end) {
|
|
if (!next.quote_window_start || !next.quote_window_end) {
|
|
throw Object.assign(new Error('报价时间段须同时填写起止时刻'), {
|
|
status: 400,
|
|
code: 'invalid_request',
|
|
});
|
|
}
|
|
const a = parseQuoteWindowHm(next.quote_window_start)!;
|
|
const b = parseQuoteWindowHm(next.quote_window_end)!;
|
|
if (a.h * 60 + a.m >= b.h * 60 + b.m) {
|
|
throw Object.assign(new Error('报价时间段开始须早于结束(不支持跨午夜)'), {
|
|
status: 400,
|
|
code: 'invalid_request',
|
|
});
|
|
}
|
|
}
|
|
if (next.cycle_type === 'custom') {
|
|
if (
|
|
!next.custom_period_start ||
|
|
!next.custom_period_end ||
|
|
next.custom_period_start > next.custom_period_end
|
|
) {
|
|
throw Object.assign(new Error('自定义时间段须填写有效起止日期'), {
|
|
status: 400,
|
|
code: 'invalid_request',
|
|
});
|
|
}
|
|
}
|
|
|
|
if (code) {
|
|
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.rowCount) {
|
|
await pool.query(
|
|
`UPDATE system_configs
|
|
SET config_value = $1::jsonb, updated_by = $2, updated_at = NOW()
|
|
WHERE id = $3`,
|
|
[JSON.stringify(next), updatedBy || null, existing.rows[0].id]
|
|
);
|
|
} else {
|
|
await pool.query(
|
|
`INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code, updated_by)
|
|
VALUES ($1, $2::jsonb, 'order', '竞价设置', $3, $4)`,
|
|
[CONFIG_KEY, JSON.stringify(next), code, updatedBy || null]
|
|
);
|
|
}
|
|
} else {
|
|
const existing = await pool.query(
|
|
`SELECT id FROM system_configs WHERE config_key = $1 AND branch_code IS NULL LIMIT 1`,
|
|
[CONFIG_KEY]
|
|
);
|
|
if (existing.rowCount) {
|
|
await pool.query(
|
|
`UPDATE system_configs
|
|
SET config_value = $1::jsonb, updated_by = $2, updated_at = NOW()
|
|
WHERE id = $3`,
|
|
[JSON.stringify(next), updatedBy || null, existing.rows[0].id]
|
|
);
|
|
} else {
|
|
await pool.query(
|
|
`INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code, updated_by)
|
|
VALUES ($1, $2::jsonb, 'order', '竞价设置', NULL, $3)`,
|
|
[CONFIG_KEY, JSON.stringify(next), updatedBy || null]
|
|
);
|
|
}
|
|
}
|
|
|
|
return next;
|
|
}
|
|
|
|
export async function assertBidEnabled(branchCode?: string | null): Promise<BidSettings> {
|
|
const settings = await getBidSettings(branchCode);
|
|
if (!settings.enabled) {
|
|
throw Object.assign(new Error('竞价功能未开启,请先在竞价设置中开启'), {
|
|
status: 400,
|
|
code: 'bid_disabled',
|
|
});
|
|
}
|
|
return settings;
|
|
}
|