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"; type ReportedBlockOrderByField = "workDate"; export interface ListCurrentReportedBlocksInput extends PaginationInput { assignmentId: string; startDate?: Date; endDate?: Date; } /** * Function: listCurrentReportedBlocks * Lists the current (non-superseded) ReportedTimeBlocks for an Assignment over * an optional workDate range, paginated — the input set Time Calculation * consumes to derive CalculatedTimeBlocks. */ export async function run(db: ReadonlyDB, input: ListCurrentReportedBlocksInput) { if (!input.assignmentId) { return err(new InvalidQueryParamsError("assignmentId")); } if ( input.startDate !== undefined && input.endDate !== undefined && input.endDate < input.startDate ) { return err( new InvalidQueryParamsError( `${input.startDate.toISOString()}..${input.endDate.toISOString()}`, ), ); } const limit = input.limit ?? DEFAULT_PAGE_SIZE; const offset = input.offset ?? 0; const orderBy = input.orderBy ?? "id"; const orderDirection = input.orderDirection ?? "asc"; let query = db .selectFrom("ReportedTimeBlock") .selectAll() .where("assignmentId", "=", input.assignmentId) .where("supersededByBlockId", "is", null); if (input.startDate !== undefined) { query = query.where("workDate", ">=", input.startDate); } if (input.endDate !== undefined) { query = query.where("workDate", "<=", input.endDate); } const items = await query .orderBy(orderBy, orderDirection) .limit(limit + 1) .offset(offset) .execute(); return ok(buildPaginatedResult(items, limit)); }