Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Some checks failed
ci / test (push) Failing after 20s
ci / deploy (push) Has been skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 09:44:50 +03:00
commit ebb1cb7950
101 changed files with 4971 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
import { buildCalendarRows, importHolidays, stateHolidays, type NagerHoliday } from "./import.js";
const sample: NagerHoliday[] = [
{ date: "2026-11-26", name: "Thanksgiving Day", global: true, counties: null },
{ date: "2026-02-12", name: "Lincoln's Birthday", global: false, counties: ["US-CA", "US-NY"] },
{ date: "2026-03-02", name: "Florida only", global: false, counties: ["US-FL"] },
];
describe("holidays", () => {
it("stateHolidays: федеральные и штата FL, без чужих штатов", () => {
expect(stateHolidays(sample, "FL").map((h) => h.name)).toEqual(["Thanksgiving Day", "Florida only"]);
});
it("buildCalendarRows: выходные и праздники нерабочие", () => {
const rows = buildCalendarRows(stateHolidays(sample, "FL"), "2026-11-25", "2026-11-30");
expect(rows.map((r) => [r.day, r.is_workday])).toEqual([
["2026-11-25", true], ["2026-11-26", false], ["2026-11-27", true],
["2026-11-28", false], ["2026-11-29", false], ["2026-11-30", true],
]);
expect(rows[1]!.holiday_name).toBe("Thanksgiving Day");
});
});
const url = testDatabaseUrl();
(url ? describe : describe.skip)("импорт календаря (временная БД)", () => {
let db: TestDb;
beforeAll(async () => { db = await createTestDb(url!); });
afterAll(async () => { await db?.drop(); });
const fakeFetch = (async () => new Response(JSON.stringify(sample), { status: 200 })) as unknown as typeof fetch;
it("загружает дни и не перезаписывает ручные правки", async () => {
await db.pool.query("insert into calendar_day (day, is_workday, holiday_name, source) values ('2026-11-26', true, 'llmtest-manual', 'manual')");
const r = await importHolidays(db.pool, { country: "US", state: "FL", yearsAhead: 0, now: new Date("2026-06-01T00:00:00Z"), fetchFn: fakeFetch });
expect(r.days).toBe(365);
const { rows } = await db.pool.query("select is_workday, holiday_name, source from calendar_day where day = '2026-11-26'");
expect(rows[0]).toEqual({ is_workday: true, holiday_name: "llmtest-manual", source: "manual" });
expect((await db.pool.query("select is_workday from calendar_day where day = '2026-03-02'")).rows[0].is_workday).toBe(false);
});
});

View File

@@ -0,0 +1,68 @@
import { addDays, isWorkday, type Pool } from "khb_common";
export interface NagerHoliday {
date: string;
name: string;
global: boolean;
counties: string[] | null;
types?: string[];
}
export interface CalendarRow {
day: string;
is_workday: boolean;
holiday_name: string | null;
}
/** Праздники, относящиеся к штату (федеральные и именно этого штата), без региональных праздников других штатов. */
export function stateHolidays(all: NagerHoliday[], state: string): NagerHoliday[] {
return all.filter((h) => h.global || (h.counties ?? []).includes(`US-${state}`));
}
/** Строки календаря на каждый день диапазона [from, to]: выходные и праздники - нерабочие. */
export function buildCalendarRows(holidays: NagerHoliday[], from: string, to: string): CalendarRow[] {
const byDate = new Map<string, string>();
for (const h of holidays) byDate.set(h.date, byDate.has(h.date) ? `${byDate.get(h.date)} / ${h.name}` : h.name);
const nonWork = new Set(byDate.keys());
const rows: CalendarRow[] = [];
for (let d = from; d <= to; d = addDays(d, 1)) {
rows.push({ day: d, is_workday: isWorkday(d, nonWork), holiday_name: byDate.get(d) ?? null });
}
return rows;
}
export async function fetchHolidays(year: number, country: string, fetchFn: typeof fetch = fetch): Promise<NagerHoliday[]> {
const res = await fetchFn(`https://date.nager.at/api/v3/PublicHolidays/${year}/${country}`);
if (!res.ok) throw new Error(`Nager.Date ${year}/${country}: HTTP ${res.status}`);
return (await res.json()) as NagerHoliday[];
}
/**
* Импорт календаря в native-таблицу calendar_day (не зеркало). Строки с source='manual' не перезаписываются.
* Загружает текущий год и yearsAhead следующих.
*/
export async function importHolidays(
pool: Pool,
opts: { country: string; state: string; yearsAhead: number; now?: Date; fetchFn?: typeof fetch },
): Promise<{ days: number }> {
const year = (opts.now ?? new Date()).getUTCFullYear();
const holidays: NagerHoliday[] = [];
for (let y = year; y <= year + opts.yearsAhead; y++) holidays.push(...stateHolidays(await fetchHolidays(y, opts.country, opts.fetchFn), opts.state));
const rows = buildCalendarRows(holidays, `${year}-01-01`, `${year + opts.yearsAhead}-12-31`);
for (let i = 0; i < rows.length; i += 500) {
const chunk = rows.slice(i, i + 500);
const params: unknown[] = [];
const values = chunk.map((r) => {
params.push(r.day, r.is_workday, r.holiday_name);
const n = params.length;
return `($${n - 2}, $${n - 1}, $${n}, 'nager')`;
});
await pool.query(
`insert into calendar_day (day, is_workday, holiday_name, source) values ${values.join(",")}
on conflict (day) do update set is_workday = excluded.is_workday, holiday_name = excluded.holiday_name, loaded_at = now()
where calendar_day.source = 'nager'`,
params,
);
}
return { days: rows.length };
}