import { formatInTimeZone, fromZonedTime } from "date-fns-tz"; import { publishOutboxEvent, type OutboxPublisherTransaction } from "./outbox.js"; import type { DbTransactionClient } from "./transactions.server.js"; const AUTOMATION_TIME_ZONE = "Europe/Berlin"; const DEFAULT_LOOKBACK_MINUTES = 5; const MAX_SCHEDULED_TARGETS_PER_RULE = 500; type SchedulerRule = { readonly id: string; readonly triggerKey: string; readonly steps: readonly { readonly stepKind: string; readonly nodeType: string; readonly config: unknown; }[]; }; export type AutomationSchedulerResult = { readonly inspectedRules: number; readonly scheduledEvents: number; readonly skippedInvalidRules: number; readonly truncatedRules: number; }; export async function runAutomationSchedulerForTenantWithTx( tx: DbTransactionClient, input: { readonly tenantId: string; readonly now?: Date; readonly lookbackMinutes?: number } ): Promise { const now = input.now ?? new Date(); const lookbackMinutes = positiveInteger(input.lookbackMinutes, DEFAULT_LOOKBACK_MINUTES); const rules = (await tx.automationRule.findMany({ where: { tenantId: input.tenantId, triggerKey: { in: ["time.schedule", "projects.deadline_soon"] }, status: "active", enabled: true, archivedAt: null, }, orderBy: [{ createdAt: "asc" }, { id: "asc" }], select: { id: true, triggerKey: true, steps: { where: { stepKind: "trigger" }, orderBy: [{ sortOrder: "asc" }, { id: "asc" }], select: { stepKind: true, nodeType: true, config: true }, }, }, })) as unknown as SchedulerRule[]; let scheduledEvents = 0; let skippedInvalidRules = 0; let truncatedRules = 0; for (const rule of rules) { const trigger = rule.steps.find((step) => step.stepKind === "trigger" && step.nodeType === rule.triggerKey); const config = record(trigger?.config); if (rule.triggerKey === "time.schedule") { const result = await scheduleTimeRule(tx, { tenantId: input.tenantId, ruleId: rule.id, config, now, lookbackMinutes }); scheduledEvents += result.scheduled; skippedInvalidRules += result.valid ? 0 : 1; continue; } if (rule.triggerKey === "projects.deadline_soon") { const result = await scheduleDeadlineRule(tx, { tenantId: input.tenantId, ruleId: rule.id, config, now, lookbackMinutes }); scheduledEvents += result.scheduled; skippedInvalidRules += result.valid ? 0 : 1; truncatedRules += result.truncated ? 1 : 0; } } return { inspectedRules: rules.length, scheduledEvents, skippedInvalidRules, truncatedRules }; } async function scheduleTimeRule( tx: DbTransactionClient, input: { tenantId: string; ruleId: string; config: Record; now: Date; lookbackMinutes: number; } ): Promise<{ valid: boolean; scheduled: number }> { const recurrence = text(input.config.wiederholung); const time = parseClock(text(input.config.uhrzeit)); if (!time || !recurrence || !["taeglich", "woechentlich", "monatlich"].includes(recurrence)) { return { valid: false, scheduled: 0 }; } const cutoff = new Date(input.now.getTime() - input.lookbackMinutes * 60_000); const localDates = new Set([formatInTimeZone(input.now, AUTOMATION_TIME_ZONE, "yyyy-MM-dd"), formatInTimeZone(cutoff, AUTOMATION_TIME_ZONE, "yyyy-MM-dd")]); let scheduled = 0; for (const localDate of localDates) { const scheduledAt = fromZonedTime(`${localDate}T${time}:00`, AUTOMATION_TIME_ZONE); if (scheduledAt <= cutoff || scheduledAt > input.now || !recurrenceMatches(recurrence, scheduledAt, input.config)) continue; await publishWorkflowTrigger(tx, { tenantId: input.tenantId, event: "time.schedule", sourceId: `automation-time:${input.ruleId}:${localDate}:${time.replace(":", "-")}`, data: { automationRuleId: input.ruleId, recurrence, wiederholung: recurrence, time, uhrzeit: time, timezone: AUTOMATION_TIME_ZONE, scheduledFor: scheduledAt.toISOString(), }, }); scheduled += 1; } return { valid: true, scheduled }; } async function scheduleDeadlineRule( tx: DbTransactionClient, input: { tenantId: string; ruleId: string; config: Record; now: Date; lookbackMinutes: number; } ): Promise<{ valid: boolean; scheduled: number; truncated: boolean }> { const deadlineType = text(input.config.fristtyp); const leadTime = positiveNumber(input.config.leadTime); const leadTimeUnit = text(input.config.leadTimeUnit); const unitMs = leadTimeUnit === "stunden" ? 60 * 60_000 : leadTimeUnit === "tage" ? 24 * 60 * 60_000 : leadTimeUnit === "wochen" ? 7 * 24 * 60 * 60_000 : null; if (!deadlineType || leadTime === null || unitMs === null) { return { valid: false, scheduled: 0, truncated: false }; } const leadMs = leadTime * unitMs; const deadlineGte = new Date(input.now.getTime() - input.lookbackMinutes * 60_000 + leadMs); const deadlineLte = new Date(input.now.getTime() + leadMs); const common = { tenantId: input.tenantId, archivedAt: null, deadline: { gte: deadlineGte, lte: deadlineLte } }; let targets: Array<{ entityType: "task" | "project" | "invoice"; entityId: string; projectId: string | null; deadline: Date }>; if (deadlineType === "aufgabenFaelligkeit") { const rows = await tx.task.findMany({ where: { ...common, status: { notIn: ["done", "cancelled"] } }, orderBy: [{ deadline: "asc" }, { id: "asc" }], take: MAX_SCHEDULED_TARGETS_PER_RULE + 1, select: { id: true, deadline: true, linkedEntityType: true, linkedEntityId: true }, }); targets = rows.flatMap((row) => row.deadline ? [{ entityType: "task" as const, entityId: row.id, projectId: row.linkedEntityType === "project" ? row.linkedEntityId : null, deadline: row.deadline }] : [] ); } else if (deadlineType === "projektDeadline") { const rows = await tx.projekt.findMany({ where: common, orderBy: [{ deadline: "asc" }, { id: "asc" }], take: MAX_SCHEDULED_TARGETS_PER_RULE + 1, select: { id: true, deadline: true }, }); targets = rows.flatMap((row) => (row.deadline ? [{ entityType: "project" as const, entityId: row.id, projectId: row.id, deadline: row.deadline }] : [])); } else if (deadlineType === "zahlungsziel") { const rows = await tx.rechnung.findMany({ where: { tenantId: input.tenantId, archivedAt: null, status: { notIn: ["bezahlt", "storniert"] }, faelligAm: { gte: deadlineGte, lte: deadlineLte }, }, orderBy: [{ faelligAm: "asc" }, { id: "asc" }], take: MAX_SCHEDULED_TARGETS_PER_RULE + 1, select: { id: true, projektId: true, faelligAm: true }, }); targets = rows.flatMap((row) => row.faelligAm ? [{ entityType: "invoice" as const, entityId: row.id, projectId: row.projektId, deadline: row.faelligAm }] : [] ); } else { return { valid: false, scheduled: 0, truncated: false }; } const truncated = targets.length > MAX_SCHEDULED_TARGETS_PER_RULE; targets = targets.slice(0, MAX_SCHEDULED_TARGETS_PER_RULE); for (const target of targets) { await publishWorkflowTrigger(tx, { tenantId: input.tenantId, event: "projects.deadline_soon", sourceId: `automation-deadline:${input.ruleId}:${deadlineType}:${target.entityId}:${target.deadline.getTime()}`, data: { automationRuleId: input.ruleId, deadlineType, fristtyp: deadlineType, leadTime, leadTimeUnit, entityType: target.entityType, entityId: target.entityId, projectId: target.projectId, taskId: target.entityType === "task" ? target.entityId : null, invoiceId: target.entityType === "invoice" ? target.entityId : null, deadlineAt: target.deadline.toISOString(), }, }); } return { valid: true, scheduled: targets.length, truncated }; } async function publishWorkflowTrigger( tx: DbTransactionClient, input: { tenantId: string; event: string; sourceId: string; data: Record } ): Promise { await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, { tenantId: input.tenantId, type: "workflow.trigger.event", payload: { event: input.event, data: input.data, userId: null } as never, dispatchKey: `workflow-trigger:${input.sourceId}`, }); } function recurrenceMatches(recurrence: string, scheduledAt: Date, config: Record): boolean { if (recurrence === "taeglich") return true; if (recurrence === "woechentlich") { const configuredWeekday = text(config.wochentag) ?? "montag"; const weekday = Number(formatInTimeZone(scheduledAt, AUTOMATION_TIME_ZONE, "i")); return weekday === ({ montag: 1, dienstag: 2, mittwoch: 3, donnerstag: 4, freitag: 5, samstag: 6, sonntag: 7 }[configuredWeekday] ?? -1); } const configuredDay = positiveInteger(config.monatstag, 1); return Number(formatInTimeZone(scheduledAt, AUTOMATION_TIME_ZONE, "d")) === Math.min(configuredDay, 31); } function parseClock(value: string | null): string | null { if (!value || !/^(?:[01]\d|2[0-3]):[0-5]\d$/u.test(value)) return null; return value; } function record(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } function text(value: unknown): string | null { return typeof value === "string" && value.trim() ? value.trim() : null; } function positiveNumber(value: unknown): number | null { const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value.replace(",", ".")) : Number.NaN; return Number.isFinite(parsed) && parsed > 0 ? parsed : null; } function positiveInteger(value: unknown, fallback: number): number { const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN; return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback; }