import type { WarehousePlanEntry } from "../config/types.js";
|
import { formatDateKey } from "../utils/calendarMonth.js";
|
import { executeDataSourceById } from "./sqlDataSource.js";
|
|
export const WAREHOUSE_CALENDAR_DATASRC_ID = "warehouse_calendar_events";
|
|
function rowVal(
|
row: Record<string, unknown>,
|
...names: string[]
|
): unknown {
|
const keys = Object.keys(row);
|
for (const name of names) {
|
const k = keys.find((x) => x.toLowerCase() === name.toLowerCase());
|
if (k !== undefined) {
|
return row[k];
|
}
|
}
|
return undefined;
|
}
|
|
function dateKeyFromDatestr(v: unknown): string | null {
|
if (v instanceof Date) {
|
return formatDateKey(v.getFullYear(), v.getMonth() + 1, v.getDate());
|
}
|
if (typeof v === "string") {
|
const t = v.trim();
|
if (/^\d{4}-\d{2}-\d{2}/.test(t)) {
|
return t.slice(0, 10);
|
}
|
const d = new Date(t);
|
if (!Number.isNaN(d.getTime())) {
|
return formatDateKey(d.getFullYear(), d.getMonth() + 1, d.getDate());
|
}
|
}
|
return null;
|
}
|
|
function strOpt(v: unknown): string | undefined {
|
if (v == null) {
|
return undefined;
|
}
|
const s = String(v).trim();
|
return s === "" ? undefined : s;
|
}
|
|
function rowToPlanEntry(
|
row: Record<string, unknown>
|
): WarehousePlanEntry {
|
const datestrRaw = rowVal(row, "datestr", "DispatchDate");
|
const key = dateKeyFromDatestr(datestrRaw);
|
const datestr = key ?? String(datestrRaw ?? "");
|
return {
|
datestr,
|
eventstr: strOpt(rowVal(row, "eventstr", "ShipmentCode")) ?? "(无单号)",
|
note_a: strOpt(rowVal(row, "note_a", "C1")),
|
note_b: strOpt(rowVal(row, "note_b")),
|
event_status: strOpt(rowVal(row, "event_status")),
|
event_src: strOpt(rowVal(row, "event_src", "CustomerShortName")),
|
event_to: strOpt(rowVal(row, "event_to", "ShippingToCountry")),
|
};
|
}
|
|
/**
|
* 从 SQL Server(经 datasrc 配置)读取指定年月的计划,按 YYYY-MM-DD 分组。
|
*/
|
export async function loadWarehousePlansGroupedByDate(
|
year: number,
|
month: number
|
): Promise<Record<string, WarehousePlanEntry[]>> {
|
const startDate = new Date(year, month - 1, 1);
|
const endDate = new Date(year, month, 1);
|
const rows = await executeDataSourceById(WAREHOUSE_CALENDAR_DATASRC_ID, {
|
startDate,
|
endDate,
|
});
|
const map: Record<string, WarehousePlanEntry[]> = {};
|
for (const r of rows) {
|
const key = dateKeyFromDatestr(
|
rowVal(r, "datestr", "DispatchDate")
|
);
|
if (!key) {
|
continue;
|
}
|
if (!map[key]) {
|
map[key] = [];
|
}
|
const entry = rowToPlanEntry(r);
|
entry.datestr = key;
|
map[key].push(entry);
|
}
|
return map;
|
}
|