来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
444 lines
14 KiB
TypeScript
444 lines
14 KiB
TypeScript
import { pool } from '../db';
|
||
import { addCalendarDaysYmd, formatChinaDate } from '../utils/chinaDate';
|
||
|
||
export type DemandForecastModel = 'ma' | 'weekly';
|
||
export type DemandForecastConfidence = 'high' | 'medium' | 'low';
|
||
|
||
/** 计算时间(历史样本窗口),中国日历日闭区间 */
|
||
export interface DemandForecastWindow {
|
||
from: string;
|
||
to: string;
|
||
/** `MM-DD ~ MM-DD`,供界面展示 */
|
||
label: string;
|
||
}
|
||
|
||
export interface DemandForecastRow {
|
||
customer_code: string;
|
||
customer_name: string | null;
|
||
sku_code: string;
|
||
sku_name: string | null;
|
||
/** 商品规格(skus.spec) */
|
||
specification: string | null;
|
||
/** 单位(skus.unit) */
|
||
unit: string | null;
|
||
avg_daily_qty: number;
|
||
/** 预测目标区间内的需求总量 */
|
||
suggested_qty: number;
|
||
/** 当前可用库存(branch+sku 汇总;无库存记录为 0) */
|
||
available_qty: number;
|
||
/** suggested_qty > available_qty */
|
||
stockout_risk: boolean;
|
||
confidence: DemandForecastConfidence;
|
||
sample_days: number;
|
||
order_lines: number;
|
||
}
|
||
|
||
export interface DemandForecastBucket {
|
||
index: number;
|
||
date_from: string;
|
||
date_to: string;
|
||
label: string;
|
||
qty: number;
|
||
}
|
||
|
||
export interface DemandForecastResult {
|
||
days: number;
|
||
horizon_days: number;
|
||
model: DemandForecastModel;
|
||
/** 实际生效的计算时间窗口(显式区间被夹取后也以本字段为准) */
|
||
window: DemandForecastWindow;
|
||
target: { from: string; to: string; label: string };
|
||
/** 仅 horizon=30:明天起 4 个周分桶(7/7/7/9 天)的全量合计 */
|
||
buckets?: DemandForecastBucket[];
|
||
rows: DemandForecastRow[];
|
||
}
|
||
|
||
function pad2(n: number) {
|
||
return String(n).padStart(2, '0');
|
||
}
|
||
|
||
function ymd(d: Date): string {
|
||
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
||
}
|
||
|
||
function md(d: Date): string {
|
||
return `${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
||
}
|
||
|
||
function addDays(base: Date, n: number): Date {
|
||
const d = new Date(base);
|
||
d.setDate(d.getDate() + n);
|
||
return d;
|
||
}
|
||
|
||
function parseCodeList(raw: unknown, max = 200): string[] {
|
||
const parts = Array.isArray(raw)
|
||
? raw.map((x) => String(x || '').trim())
|
||
: String(raw || '')
|
||
.split(',')
|
||
.map((s) => s.trim());
|
||
const out: string[] = [];
|
||
const seen = new Set<string>();
|
||
for (const p of parts) {
|
||
if (!p || seen.has(p)) continue;
|
||
seen.add(p);
|
||
out.push(p);
|
||
if (out.length >= max) break;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** 计算时间窗口长度下限/上限(天) */
|
||
const MIN_WINDOW_DAYS = 7;
|
||
const MAX_WINDOW_DAYS = 90;
|
||
|
||
function parseDay(raw: unknown): string | null {
|
||
const s = String(raw ?? '').trim();
|
||
return /^\d{4}-\d{2}-\d{2}$/.test(s) ? s : null;
|
||
}
|
||
|
||
function daySpanInclusive(from: string, to: string): number {
|
||
const a = Date.parse(`${from}T00:00:00Z`);
|
||
const b = Date.parse(`${to}T00:00:00Z`);
|
||
if (!Number.isFinite(a) || !Number.isFinite(b)) return 0;
|
||
return Math.round((b - a) / 86400000) + 1;
|
||
}
|
||
|
||
interface ResolvedWindow {
|
||
days: number;
|
||
from: string;
|
||
to: string;
|
||
/** 用户显式选定的中国日历日闭区间;未选则 null(沿用滚动窗口 SQL) */
|
||
explicit: { from: string; to: string } | null;
|
||
}
|
||
|
||
/**
|
||
* 计算时间(历史样本窗口):
|
||
* - 显式区间:中国日历日闭区间,夹到 7–90 天(超长保留末端),结束日不晚于今天;
|
||
* - 未选:沿用滚动窗口(`NOW() - days 天`),数值与改动前一致。
|
||
*/
|
||
function resolveWindow(
|
||
input: { days?: unknown; dateFrom?: unknown; dateTo?: unknown },
|
||
defaultDays: number
|
||
): ResolvedWindow {
|
||
const today = formatChinaDate();
|
||
const rawFrom = parseDay(input.dateFrom);
|
||
const rawTo = parseDay(input.dateTo);
|
||
if (rawFrom && rawTo) {
|
||
const ordered = rawFrom <= rawTo;
|
||
let from = ordered ? rawFrom : rawTo;
|
||
let to = ordered ? rawTo : rawFrom;
|
||
if (to > today) to = today;
|
||
if (from > to) from = to;
|
||
let days = daySpanInclusive(from, to);
|
||
if (days > MAX_WINDOW_DAYS) {
|
||
from = addCalendarDaysYmd(to, -(MAX_WINDOW_DAYS - 1));
|
||
days = MAX_WINDOW_DAYS;
|
||
} else if (days < MIN_WINDOW_DAYS) {
|
||
from = addCalendarDaysYmd(to, -(MIN_WINDOW_DAYS - 1));
|
||
days = MIN_WINDOW_DAYS;
|
||
}
|
||
return { days, from, to, explicit: { from, to } };
|
||
}
|
||
const days = Math.min(
|
||
Math.max(Number(input.days) || defaultDays, MIN_WINDOW_DAYS),
|
||
MAX_WINDOW_DAYS
|
||
);
|
||
return {
|
||
days,
|
||
from: addCalendarDaysYmd(today, -(days - 1)),
|
||
to: today,
|
||
explicit: null,
|
||
};
|
||
}
|
||
|
||
/** 勾选分类展开为自身 + 全部子孙 category_code */
|
||
async function expandCategoryCodes(
|
||
codes: string[],
|
||
branchCode?: string | null
|
||
): Promise<string[]> {
|
||
if (!codes.length) return [];
|
||
const params: unknown[] = [codes];
|
||
let branchSql = '';
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
branchSql = ` AND branch_code = $2`;
|
||
}
|
||
const rows = await pool.query(
|
||
`WITH RECURSIVE tree AS (
|
||
SELECT category_code, parent_code
|
||
FROM categories
|
||
WHERE category_code = ANY($1::text[])${branchSql}
|
||
UNION
|
||
SELECT c.category_code, c.parent_code
|
||
FROM categories c
|
||
INNER JOIN tree t ON c.parent_code = t.category_code
|
||
WHERE ($2::text IS NULL OR c.branch_code = $2)
|
||
)
|
||
SELECT DISTINCT category_code FROM tree`,
|
||
branchCode ? [codes, branchCode] : [codes, null]
|
||
);
|
||
const expanded = rows.rows.map((r) => String(r.category_code));
|
||
return expanded.length ? expanded : [...codes];
|
||
}
|
||
|
||
/**
|
||
* 客户×SKU 需求预测。
|
||
* 数据源:有效订单行(order_items × orders,剔除回收站软删单),按分公司隔离。
|
||
* 模型(由调用方自选,不再按 horizon 强制):
|
||
* - ma 平均值预测:计算窗口内日均 × 预测天数
|
||
* - weekly 同周期预测:目标日按星期几取窗口内同 weekday 日均(适配食堂周末效应)
|
||
* 计算时间:dateFrom/dateTo 中国日历日闭区间(夹 7–90 天);不传则沿用滚动窗口 days 天
|
||
* 范围(可选):categoryCodes / skuCodes 并集,与 customerCodes 取交集;都不传则全量
|
||
* (兼容异常页等旧调用)
|
||
*/
|
||
export async function getDemandForecast(input?: {
|
||
branchCode?: string | null;
|
||
days?: number;
|
||
horizonDays?: number;
|
||
limit?: number;
|
||
model?: string;
|
||
categoryCodes?: string[] | string | null;
|
||
skuCodes?: string[] | string | null;
|
||
customerCodes?: string[] | string | null;
|
||
dateFrom?: string | null;
|
||
dateTo?: string | null;
|
||
}): Promise<DemandForecastResult> {
|
||
const horizon = Math.min(Math.max(Number(input?.horizonDays) || 1, 1), 30);
|
||
const defaultDays = horizon > 7 ? 28 : 14;
|
||
const window = resolveWindow(
|
||
{ days: input?.days, dateFrom: input?.dateFrom, dateTo: input?.dateTo },
|
||
defaultDays
|
||
);
|
||
const days = window.days;
|
||
const limit = Math.min(Math.max(Number(input?.limit) || 100, 1), 500);
|
||
const model: DemandForecastModel = input?.model === 'weekly' ? 'weekly' : 'ma';
|
||
const branch = String(input?.branchCode || '').trim() || null;
|
||
|
||
const selectedCategories = parseCodeList(input?.categoryCodes);
|
||
const selectedSkus = parseCodeList(input?.skuCodes);
|
||
const selectedCustomers = parseCodeList(input?.customerCodes);
|
||
const hasScopeFilter = selectedCategories.length > 0 || selectedSkus.length > 0;
|
||
const expandedCategories = hasScopeFilter
|
||
? await expandCategoryCodes(selectedCategories, branch)
|
||
: [];
|
||
|
||
const params: unknown[] = [];
|
||
let windowSql = '';
|
||
if (window.explicit) {
|
||
params.push(window.explicit.from, window.explicit.to);
|
||
const toIdx = params.length;
|
||
const fromIdx = toIdx - 1;
|
||
windowSql = `(o.created_at AT TIME ZONE 'Asia/Shanghai')::date >= $${fromIdx}::date
|
||
AND (o.created_at AT TIME ZONE 'Asia/Shanghai')::date <= $${toIdx}::date`;
|
||
} else {
|
||
params.push(days);
|
||
windowSql = `o.created_at >= NOW() - ($${params.length}::int * INTERVAL '1 day')`;
|
||
}
|
||
|
||
let branchSql = '';
|
||
if (branch) {
|
||
params.push(branch);
|
||
branchSql = ` AND o.branch_code = $${params.length}`;
|
||
}
|
||
|
||
let scopeSql = '';
|
||
if (hasScopeFilter) {
|
||
const parts: string[] = [];
|
||
if (selectedSkus.length) {
|
||
params.push(selectedSkus);
|
||
parts.push(`oi.sku_code = ANY($${params.length}::text[])`);
|
||
}
|
||
if (expandedCategories.length) {
|
||
params.push(expandedCategories);
|
||
parts.push(`COALESCE(s.category_code, '') = ANY($${params.length}::text[])`);
|
||
}
|
||
scopeSql = parts.length ? ` AND (${parts.join(' OR ')})` : ' AND FALSE';
|
||
}
|
||
|
||
// 客户筛选:与分类/商品取交集;不传 = 全部客户
|
||
let customerSql = '';
|
||
if (selectedCustomers.length) {
|
||
params.push(selectedCustomers);
|
||
customerSql = ` AND o.customer_code = ANY($${params.length}::text[])`;
|
||
}
|
||
|
||
// 按 客户×SKU×星期几 聚合:一套中间数据同时支撑 ma 与 weekly
|
||
const sales = await pool.query(
|
||
`SELECT
|
||
o.customer_code,
|
||
MAX(c.company_name) AS customer_name,
|
||
oi.sku_code,
|
||
MAX(COALESCE(oi.item_name, s.sku_name)) AS sku_name,
|
||
MAX(NULLIF(TRIM(COALESCE(s.spec, '')), '')) AS specification,
|
||
MAX(NULLIF(TRIM(COALESCE(s.unit, '')), '')) AS unit,
|
||
EXTRACT(DOW FROM o.created_at)::int AS dow,
|
||
SUM(oi.quantity)::float AS qty,
|
||
COUNT(*)::int AS lines
|
||
FROM order_items oi
|
||
JOIN orders o ON o.order_code = oi.order_code
|
||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||
LEFT JOIN skus s ON s.sku_code = oi.sku_code
|
||
WHERE ${windowSql}
|
||
AND o.deleted_at IS NULL
|
||
AND oi.sku_code IS NOT NULL
|
||
AND TRIM(oi.sku_code) <> ''
|
||
${branchSql}
|
||
${scopeSql}
|
||
${customerSql}
|
||
GROUP BY o.customer_code, oi.sku_code, EXTRACT(DOW FROM o.created_at)`,
|
||
params
|
||
);
|
||
|
||
const invParams: unknown[] = [];
|
||
let invBranchSql = '';
|
||
if (branch) {
|
||
invParams.push(branch);
|
||
invBranchSql = ' AND branch_code = $1';
|
||
}
|
||
const inv = await pool.query(
|
||
`SELECT sku_code, SUM(available_qty)::float AS available_qty
|
||
FROM inventory
|
||
WHERE sku_code IS NOT NULL AND TRIM(sku_code) <> ''${invBranchSql}
|
||
GROUP BY sku_code`,
|
||
invParams
|
||
);
|
||
const availableBySku = new Map<string, number>(
|
||
inv.rows.map((r) => [String(r.sku_code), Number(r.available_qty) || 0])
|
||
);
|
||
|
||
interface Agg {
|
||
customer_code: string;
|
||
customer_name: string | null;
|
||
sku_code: string;
|
||
sku_name: string | null;
|
||
specification: string | null;
|
||
unit: string | null;
|
||
dowQty: number[]; // 0..6
|
||
totalQty: number;
|
||
lines: number;
|
||
}
|
||
const aggMap = new Map<string, Agg>();
|
||
for (const r of sales.rows) {
|
||
const key = `${r.customer_code}::${r.sku_code}`;
|
||
let agg = aggMap.get(key);
|
||
if (!agg) {
|
||
agg = {
|
||
customer_code: String(r.customer_code),
|
||
customer_name: r.customer_name ? String(r.customer_name) : null,
|
||
sku_code: String(r.sku_code),
|
||
sku_name: r.sku_name ? String(r.sku_name) : null,
|
||
specification: r.specification ? String(r.specification) : null,
|
||
unit: r.unit ? String(r.unit) : null,
|
||
dowQty: [0, 0, 0, 0, 0, 0, 0],
|
||
totalQty: 0,
|
||
lines: 0,
|
||
};
|
||
aggMap.set(key, agg);
|
||
} else {
|
||
if (!agg.specification && r.specification) agg.specification = String(r.specification);
|
||
if (!agg.unit && r.unit) agg.unit = String(r.unit);
|
||
}
|
||
const qty = Number(r.qty) || 0;
|
||
agg.dowQty[Number(r.dow) % 7] += qty;
|
||
agg.totalQty += qty;
|
||
agg.lines += Number(r.lines) || 0;
|
||
}
|
||
|
||
const today = new Date();
|
||
const targetFrom = addDays(today, 1);
|
||
const targetTo = addDays(today, horizon);
|
||
// 窗口内某 weekday 出现次数 ≈ days/7(含未下单的零日,避免按活跃日平均造成高估)
|
||
const weeksInWindow = days / 7;
|
||
|
||
const dailyPrediction = (agg: Agg, date: Date): number => {
|
||
if (model === 'weekly') return agg.dowQty[date.getDay()] / weeksInWindow;
|
||
return agg.totalQty / days;
|
||
};
|
||
|
||
const horizonDates: Date[] = [];
|
||
for (let i = 1; i <= horizon; i++) horizonDates.push(addDays(today, i));
|
||
|
||
let bucketRanges: Array<{ from: Date; to: Date }> | null = null;
|
||
if (horizon === 30) {
|
||
bucketRanges = [
|
||
{ from: addDays(today, 1), to: addDays(today, 7) },
|
||
{ from: addDays(today, 8), to: addDays(today, 14) },
|
||
{ from: addDays(today, 15), to: addDays(today, 21) },
|
||
{ from: addDays(today, 22), to: addDays(today, 30) },
|
||
];
|
||
}
|
||
|
||
const rows: DemandForecastRow[] = [];
|
||
const bucketTotals = bucketRanges ? bucketRanges.map(() => 0) : null;
|
||
|
||
for (const agg of aggMap.values()) {
|
||
if (agg.totalQty <= 0) continue;
|
||
const avgDaily = agg.totalQty / days;
|
||
let suggested = 0;
|
||
for (const d of horizonDates) suggested += dailyPrediction(agg, d);
|
||
|
||
if (bucketRanges && bucketTotals) {
|
||
horizonDates.forEach((d, i) => {
|
||
const b = Math.min(3, Math.floor(i / 7));
|
||
bucketTotals[b] += dailyPrediction(agg, d);
|
||
});
|
||
}
|
||
|
||
const available = availableBySku.get(agg.sku_code) ?? 0;
|
||
const confidence: DemandForecastConfidence =
|
||
agg.lines >= 10 && days >= 14 ? 'high' : agg.lines >= 4 ? 'medium' : 'low';
|
||
|
||
rows.push({
|
||
customer_code: agg.customer_code,
|
||
customer_name: agg.customer_name,
|
||
sku_code: agg.sku_code,
|
||
sku_name: agg.sku_name,
|
||
specification: agg.specification,
|
||
unit: agg.unit,
|
||
avg_daily_qty: Math.round(avgDaily * 100) / 100,
|
||
suggested_qty: Math.round(suggested * 100) / 100,
|
||
available_qty: Math.round(available * 100) / 100,
|
||
stockout_risk: suggested > available,
|
||
confidence,
|
||
sample_days: days,
|
||
order_lines: agg.lines,
|
||
});
|
||
}
|
||
|
||
rows.sort((a, b) => b.suggested_qty - a.suggested_qty);
|
||
const limited = rows.slice(0, limit);
|
||
|
||
const targetLabel =
|
||
horizon === 1
|
||
? `明天(${md(targetFrom)})`
|
||
: horizon === 7
|
||
? `未来一周(${md(targetFrom)} ~ ${md(targetTo)})`
|
||
: `未来一个月(${md(targetFrom)} ~ ${md(targetTo)})`;
|
||
|
||
const buckets: DemandForecastBucket[] | undefined =
|
||
bucketRanges && bucketTotals
|
||
? bucketRanges.map((r, i) => ({
|
||
index: i + 1,
|
||
date_from: ymd(r.from),
|
||
date_to: ymd(r.to),
|
||
label: `第${i + 1}周(${md(r.from)} ~ ${md(r.to)})`,
|
||
qty: Math.round(bucketTotals[i] * 100) / 100,
|
||
}))
|
||
: undefined;
|
||
|
||
return {
|
||
days,
|
||
horizon_days: horizon,
|
||
model,
|
||
window: {
|
||
from: window.from,
|
||
to: window.to,
|
||
label: `${window.from.slice(5)} ~ ${window.to.slice(5)}`,
|
||
},
|
||
target: { from: ymd(targetFrom), to: ymd(targetTo), label: targetLabel },
|
||
buckets,
|
||
rows: limited,
|
||
};
|
||
}
|