accounting_automation: этап 1 бухгалтерской автоматизации (инвойсы из почты, категоризация, ручной разбор, MCP), интервальные задания scheduler, миграции 033/034/038
All checks were successful
ci / test (push) Successful in 40s
ci / deploy (push) Successful in 2m41s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 08:05:28 +03:00
parent 12e331efe9
commit b422309148
62 changed files with 4278 additions and 148 deletions

View File

@@ -46,3 +46,31 @@ describe("decide", () => {
expect(decide(null, false, new Date(), 60)).toBe("none");
});
});
describe("lastDue: интервальный режим (everyMinutes)", () => {
const job = { name: "j", everyMinutes: 15, days: "daily" as const };
it("узел сетки 15 минут от полуночи", () => {
// 12:07:30Z = 08:07:30 EDT -> 08:00 EDT = 12:00Z
expect(lastDue(job, new Date("2026-10-11T12:07:30Z"), TZ, none)?.toISOString()).toBe("2026-10-11T12:00:00.000Z");
});
it("ровно в узле сетки", () => {
expect(lastDue(job, new Date("2026-10-11T12:15:00Z"), TZ, none)?.toISOString()).toBe("2026-10-11T12:15:00.000Z");
});
it("окно from-to: вне окна берётся конец окна", () => {
const w = { name: "j", everyMinutes: 30, days: "daily" as const, from: "08:00", to: "18:00" };
// 23:10 EDT (03:10Z следующего дня) -> последний узел окна 18:00 EDT = 22:00Z
expect(lastDue(w, new Date("2026-10-12T03:10:00Z"), TZ, none)?.toISOString()).toBe("2026-10-11T22:00:00.000Z");
});
it("окно from-to: ночью до начала окна - вчерашний конец окна", () => {
const w = { name: "j", everyMinutes: 30, days: "daily" as const, from: "08:00", to: "18:00" };
// 05:00 EDT = 09:00Z -> вчера 18:00 EDT = 22:00Z
expect(lastDue(w, new Date("2026-10-11T09:00:00Z"), TZ, none)?.toISOString()).toBe("2026-10-10T22:00:00.000Z");
});
it("workdays: в субботу последний узел - в пятницу в конце окна", () => {
const w = { name: "j", everyMinutes: 60, days: "workdays" as const, from: "08:00", to: "17:00" };
expect(lastDue(w, new Date("2026-10-10T15:00:00Z"), TZ, none)?.toISOString()).toBe("2026-10-09T21:00:00.000Z");
});
it("без at и everyMinutes - null", () => {
expect(lastDue({ name: "j", days: "daily" }, new Date(), TZ, none)).toBeNull();
});
});

View File

@@ -4,8 +4,36 @@ export type DaysSpec = "daily" | "workdays" | string[];
export interface JobSchedule {
name: string;
at: string; // HH:MM по часовому поясу tz
at?: string; // HH:MM по часовому поясу tz (ежедневный режим)
days: DaysSpec;
/** Интервальный режим: каждые N минут от полуночи по tz, в окне from-to (HH:MM, включительно). */
everyMinutes?: number;
from?: string;
to?: string;
}
const minutesOf = (hhmm: string): number => Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3, 5));
/** Последняя сетка «каждые N минут» не позже now с учётом дней и окна. */
function lastDueInterval(job: JobSchedule, now: Date, tz: string, nonWorkdays: ReadonlySet<string>, lookbackDays: number): Date | null {
const step = job.everyMinutes! * 60_000;
const from = job.from ? minutesOf(job.from) : 0;
const to = job.to ? minutesOf(job.to) : 24 * 60;
let cursor = now.getTime();
const limit = now.getTime() - lookbackDays * 86_400_000;
while (cursor >= limit) {
const date = localDate(new Date(cursor), tz);
const dayStart = zonedToUtc(date, "00:00", tz).getTime();
const k = Math.floor((cursor - dayStart) / step);
const due = dayStart + k * step;
const minuteOfDay = Math.round((due - dayStart) / 60_000);
if (dayMatches(date, job.days, nonWorkdays) && minuteOfDay >= from && minuteOfDay <= to) return new Date(due);
// не подходит: идём к предыдущему узлу сетки (или к концу окна предыдущего дня)
cursor = due - 1;
if (minuteOfDay > to) cursor = dayStart + to * 60_000; // после окна - конец окна этого дня
else if (minuteOfDay < from || !dayMatches(date, job.days, nonWorkdays)) cursor = dayStart - 1; // раньше окна или не тот день - вчера
}
return null;
}
function dayMatches(date: string, days: DaysSpec, nonWorkdays: ReadonlySet<string>): boolean {
@@ -25,6 +53,8 @@ export function lastDue(
nonWorkdays: ReadonlySet<string>,
lookbackDays = 8,
): Date | null {
if (job.everyMinutes) return lastDueInterval(job, now, tz, nonWorkdays, lookbackDays);
if (!job.at) return null;
let date = localDate(now, tz);
for (let i = 0; i <= lookbackDays; i++) {
if (dayMatches(date, job.days, nonWorkdays)) {

View File

@@ -39,7 +39,7 @@ export function buildApi(deps: SchedulerApiDeps): FastifyInstance {
const last = (
await deps.pool.query("select scheduled_minute, status, noticed_at, message from sched_run where job_name = $1 order by scheduled_minute desc limit 1", [j.name])
).rows[0] ?? null;
jobs.push({ name: j.name, at: j.at, days: j.days, lastDue: lastDue(j, now, deps.tz, nonWork)?.toISOString() ?? null, lastRun: last });
jobs.push({ name: j.name, at: j.at ?? null, everyMinutes: j.everyMinutes ?? null, days: j.days, lastDue: lastDue(j, now, deps.tz, nonWork)?.toISOString() ?? null, lastRun: last });
}
return { jobs };
});

View File

@@ -10,9 +10,15 @@ export const jobSchema = z.object({
path: z.string(),
body: z.unknown().optional(),
}),
at: z.string().regex(/^\d{2}:\d{2}$/),
/** Ежедневный режим: время запуска HH:MM (по common.timezone). Не задавать вместе с everyMinutes. */
at: z.string().regex(/^\d{2}:\d{2}$/).optional(),
days: daysSchema,
});
/** Интервальный режим: запуск каждые N минут от полуночи (по common.timezone), в днях `days` и окне from-to. */
everyMinutes: z.number().int().min(1).max(720).optional(),
/** Окно интервального режима (HH:MM, включительно); по умолчанию весь день. */
from: z.string().regex(/^\d{2}:\d{2}$/).optional(),
to: z.string().regex(/^\d{2}:\d{2}$/).optional(),
}).refine((j) => (j.at !== undefined) !== (j.everyMinutes !== undefined), { message: "у задания должно быть ровно одно из: at, everyMinutes" });
export const schedulerSchema = z.object({
tickSeconds: z.number().default(10),