import { buildPaginatedResult, DEFAULT_PAGE_SIZE, err, ok, type PaginationInput, type ReadonlyDB, } from "@tailor-platform/erp-kit/core"; import type { DB } from "../generated/kysely-tailordb"; import { InvalidQueryParamsError } from "../lib/errors.generated"; export interface ListCalculatedBlocksByWorkDateInput extends PaginationInput { assignmentId: string; workDate: Date; } /** * Function: listCalculatedBlocksByWorkDate * Description: Lists the CalculatedTimeBlocks for a given Assignment on a * single workday, paginated. This is the primary way to inspect "what did * calculation produce for this worker on this day" — the categorized * (regular/overtime/late-night/holiday/premium) breakdown of a day's derived * time. */ export async function run(db: ReadonlyDB, input: ListCalculatedBlocksByWorkDateInput) { if (!input.assignmentId) { return err(new InvalidQueryParamsError("assignmentId is missing")); } if (!input.workDate || Number.isNaN(input.workDate.getTime())) { return err(new InvalidQueryParamsError(`workDate=${String(input.workDate)}`)); } const limit = input.limit ?? DEFAULT_PAGE_SIZE; const offset = input.offset ?? 0; const orderBy = input.orderBy ?? "id"; const orderDirection = input.orderDirection ?? "asc"; const calculatedTimeBlocks = await db .selectFrom("CalculatedTimeBlock") .selectAll() .where("assignmentId", "=", input.assignmentId) .where("workDate", "=", input.workDate) .orderBy(orderBy, orderDirection) .limit(limit + 1) .offset(offset) .execute(); return ok(buildPaginatedResult(calculatedTimeBlocks, limit)); }