import { err, ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core"; import type { DB } from "../generated/kysely-tailordb"; import { InvalidDateError, WorkScheduleNotFoundError } from "../lib/errors.generated"; export interface GetWorkScheduleAsOfInput { assignmentId: string; asOf: Date; } /** * Function: getWorkScheduleAsOf * Description: Resolves which WorkSchedule generation was in force for an Assignment on a given * date. Effective-dated generations form a non-overlapping timeline (`effectiveStart` inclusive, * `effectiveEnd` inclusive, null = still current), so at most one generation covers `asOf`. This * effective-dated resolution is the workforce domain's rule and lives in the module rather than * being re-derived in the app layer (issue #38). Returns WORK_SCHEDULE_NOT_FOUND when no * generation covers the date. */ export async function run(db: ReadonlyDB, input: GetWorkScheduleAsOfInput) { if (Number.isNaN(input.asOf.getTime())) { return err(new InvalidDateError("asOf")); } const workSchedule = await db .selectFrom("WorkSchedule") .selectAll() .where("assignmentId", "=", input.assignmentId) .where("effectiveStart", "<=", input.asOf) .where((eb) => eb.or([eb("effectiveEnd", "is", null), eb("effectiveEnd", ">=", input.asOf)])) .executeTakeFirst(); if (!workSchedule) { return err(new WorkScheduleNotFoundError(`${input.assignmentId}@${input.asOf.toISOString()}`)); } return ok({ workSchedule }); }