Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
test(utils): stress DST — wall-clock scheduling, skipped midnights, odd offsets
Sidwebworks1b23b9f07fdd
diff --git a/.claude/rules/date-handling.md b/.claude/rules/date-handling.mdindex dbca1be615..2a40c7a957 100644--- a/.claude/rules/date-handling.md+++ b/.claude/rules/date-handling.md@@ -75,9 +75,40 @@ calendar, not to whichever zone the person filling the form happens to be in.`@internationalized/date`.- **Day boundaries in a timezone:** `fromDate(jsDate, timeZone).set({ hour: 0, … })`(`apps/mes/app/utils/display.ts` `startOfDay`/`endOfDay`).+- **Week windows (payroll/timecards):** `datetime.weekBounds(tz, offset?)` —+ Monday→Sunday UTC-instant bounds on the business calendar (used by+ `getWeeklyHoursForEmployees` and both timecard routes). Don't hand-roll+ `startOfWeek(...).toDate(tz)`; the helper is the tested copy.- **Recurring-date arithmetic:** carry a `ZonedDateTime` and `.add({ … })`(`packages/jobs/.../scheduled/dispatch.ts` `advanceByFrequency`).+## DST: wall-clock times are not instants++Deriving a *day* in a tz is always safe; constructing an *instant from a local+wall time* (a shift start, a job's scheduled start, a day/week boundary) is+where DST bites. The stress suite pinning all of this lives in+`packages/utils/src/datetime.test.ts` ("DST and exotic-zone stress").++- **Spring-forward gap** (02:30 doesn't exist): `toZoned` with the default+ `disambiguation: "compatible"` shifts forward into the post-gap hour — a+ 02:30 job start fires at 03:30 local, never crashes. **Fall-back overlap**+ (01:30 happens twice): `"compatible"` picks the first occurrence — the job+ fires once, not twice. Pass an explicit disambiguation only when the domain+ demands the other choice.+- **Some zones transition AT midnight** (America/Santiago): on spring-forward+ day 00:00 doesn't exist and `CalendarDate.toDate(tz)` resolves to the day's+ true first instant (01:00). Never construct "midnight" by string-building+ `T00:00:00` + an offset.+- **Transition weeks are 167h/169h** (Lord Howe: ±30min, and offsets like+ Kathmandu's +05:45 exist) — never assume 24h days or 168h weeks; duration+ arithmetic on instants and calendar arithmetic on `CalendarDate` are both+ fine, mixing them is not.+- **Cron schedules cannot express a local wall time.** "02:30 local" is a+ different UTC instant before vs after a transition, so Inngest crons stay on+ UTC schedules and compute per-company/location *days* inside the run. If a+ job must ever fire at an exact local wall time, compute the next-run instant+ via `toZoned(...)` per zone — don't fake it with a fixed UTC cron.+## Narrow exceptionA raw `new Date()`/epoch-ms is only acceptable for comparing **absolute instants**diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.tsindex 8e1859058d..97fd9a9147 100644--- a/apps/erp/app/modules/people/people.service.ts+++ b/apps/erp/app/modules/people/people.service.ts@@ -1,6 +1,7 @@import type { Database, Json } from "@carbon/database";import { getCompanyTimeZone } from "@carbon/database";-import { getDayOfWeek, startOfWeek, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";+import { getDayOfWeek, today } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import type { DataType } from "~/modules/shared";@@ -844,16 +845,16 @@ export async function getWeeklyHoursForEmployees(employeeIds: string[]): Promise<Record<string, number>> {// Week starts Monday 00:00 on the company calendar (one payroll boundary- // per books), not the server's. en-GB: weeks start Monday.+ // per books), not the server's.const tz = await getCompanyTimeZone(client, companyId);- const monday = startOfWeek(today(tz), "en-GB").toDate(tz);+ const { from } = datetime.weekBounds(tz);const { data: entries } = await client.from("timeCardEntry").select("employeeId, clockIn, clockOut").eq("companyId", companyId).in("employeeId", employeeIds)- .gte("clockIn", monday.toISOString());+ .gte("clockIn", from);const weeklyMs: Record<string, number> = {};for (const entry of entries ?? []) {diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 7cc857aa9d..8dbdf8f07f 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-08-05T20:59:07.360Z",+ "generated": "2026-08-05T21:09:52.331Z","totalTools": 1414,"modules": 15,"tools": [diff --git a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx b/apps/erp/app/routes/x+/person+/$personId.timecard.tsxindex 69defa7623..fd369a1783 100644--- a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx+++ b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx@@ -29,7 +29,7 @@ import {Thead,Tr} from "@carbon/react";-import { startOfWeek, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import { useEffect, useState } from "react";@@ -69,18 +69,6 @@ import { getCompanySettings } from "~/modules/settings";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { path } from "~/utils/path";-// Week runs Monday 00:00 → Sunday 23:59:59.999 on the company calendar (one-// payroll boundary per books, not the server's zone). en-GB: Monday-first.-function getWeekBounds(tz: string, offset: number = 0) {- const monday = startOfWeek(today(tz).add({ weeks: offset }), "en-GB");- const nextMonday = monday.add({ weeks: 1 }).toDate(tz);-- return {- from: monday.toDate(tz).toISOString(),- to: new Date(nextMonday.getTime() - 1).toISOString()- };-}-function formatDuration(clockIn: string, clockOut: string | null) {const end = clockOut ? new Date(clockOut).getTime() : Date.now();const ms = end - new Date(clockIn).getTime();@@ -140,7 +128,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const weekOffset = parseInt(url.searchParams.get("week") ?? "0", 10);- const { from, to } = getWeekBounds(+ // Week runs Monday → Sunday on the company calendar (one payroll boundary+ // per books, not the server's zone).+ const { from, to } = datetime.weekBounds(await getCompanyTimeZone(client, companyId),weekOffset);diff --git a/apps/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsxindex 2cbcbf7062..ffe49db668 100644--- a/apps/mes/app/routes/x+/timecard.tsx+++ b/apps/mes/app/routes/x+/timecard.tsx@@ -29,7 +29,7 @@ import {Thead,Tr} from "@carbon/react";-import { startOfWeek, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import { useEffect, useState } from "react";@@ -52,18 +52,6 @@ import {} from "~/services/people.service";import { path } from "~/utils/path";-// Week runs Monday 00:00 → Sunday 23:59:59.999 on the company calendar (one-// payroll boundary per books, not the server's zone). en-GB: Monday-first.-function getWeekBounds(tz: string, offset: number = 0) {- const monday = startOfWeek(today(tz).add({ weeks: offset }), "en-GB");- const nextMonday = monday.add({ weeks: 1 }).toDate(tz);-- return {- from: monday.toDate(tz).toISOString(),- to: new Date(nextMonday.getTime() - 1).toISOString()- };-}-function formatDuration(clockInStr: string, clockOutStr: string | null) {const end = clockOutStr ? new Date(clockOutStr).getTime() : Date.now();const ms = end - new Date(clockInStr).getTime();@@ -117,7 +105,9 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const weekOffset = parseInt(url.searchParams.get("week") ?? "0", 10);- const { from, to } = getWeekBounds(+ // Week runs Monday → Sunday on the company calendar (one payroll boundary+ // per books, not the server's zone).+ const { from, to } = datetime.weekBounds(await getCompanyTimeZone(client, companyId),weekOffset);diff --git a/packages/database/supabase/functions/lib/datetime.ts b/packages/database/supabase/functions/lib/datetime.tsindex c41bb33565..6eaabd0d61 100644--- a/packages/database/supabase/functions/lib/datetime.ts+++ b/packages/database/supabase/functions/lib/datetime.ts@@ -5,6 +5,7 @@ import {type CalendarDate,now,parseAbsolute,+ startOfWeek,toCalendarDate,today} from "npm:@internationalized/date";@@ -45,6 +46,32 @@ export const datetime = {businessDay: (instant: string, tz: string) =>toCalendarDate(parseAbsolute(instant, tz)),+ /**+ * The ISO week (Monday 00:00 → Sunday 23:59:59.999) containing `anchor`+ * (default: today on the given business calendar) as UTC instant strings.+ * `offset` shifts whole weeks (-1 = last week).+ *+ * DST-safe by construction: boundaries are derived per-day via+ * `CalendarDate.toDate(tz)`, so a transition week is genuinely 167h/169h+ * (Lord Howe: ±30min) rather than a fixed 168, consecutive weeks tile with+ * no gap or double-count, and in zones that spring forward AT midnight+ * (America/Santiago) a boundary that lands on the skipped midnight resolves+ * to that day's true first instant (01:00) instead of crashing or drifting+ * a day.+ */+ weekBounds: (+ tz: string,+ offset = 0,+ anchor?: CalendarDate+ ): { from: string; to: string } => {+ const monday = startOfWeek((anchor ?? today(tz)).add({ weeks: offset }), "en-GB");+ const nextMonday = monday.add({ weeks: 1 }).toDate(tz);+ return {+ from: monday.toDate(tz).toISOString(),+ to: new Date(nextMonday.getTime() - 1).toISOString()+ };+ },+weekNumber};diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.mdindex 5ce4e1eb54..710b8aa820 100644--- a/packages/utils/AGENTS.md+++ b/packages/utils/AGENTS.md@@ -36,7 +36,7 @@ pnpm --filter @carbon/utils typecheck| `arrays` | Array manipulation, grouping, deduplication || `bom` | Bill of Materials traversal and level computation || `date` | Date formatting, parsing, range helpers (uses `@internationalized/date`) |-| `datetime` | Server-side date derivation with mandatory explicit timezone: `timestamp()`, `today(tz)`, `now(tz)`, `businessDay(instant, tz)`, `weekNumber(date)`. Mirrored for Deno at `packages/database/supabase/functions/lib/datetime.ts` — keep in sync |+| `datetime` | Server-side date derivation with mandatory explicit timezone: `timestamp()`, `today(tz)`, `now(tz)`, `businessDay(instant, tz)`, `weekBounds(tz, offset?, anchor?)` (DST-safe Monday→Sunday instant bounds), `weekNumber(date)`. DST/exotic-zone stress suite in `datetime.test.ts` (gap/overlap disambiguation, midnight-skipping zones, 167/169h weeks, ±30/45-min offsets). Mirrored for Deno at `packages/database/supabase/functions/lib/datetime.ts` — keep in sync || `math` | Rounding, precision, numeric utilities || `string` | Slugify, truncate, camelCase/titleCase conversions || `status` | Status resolution, status color mapping |diff --git a/packages/utils/src/datetime.test.ts b/packages/utils/src/datetime.test.tsindex dd7d520eaf..a7a31d2e51 100644--- a/packages/utils/src/datetime.test.ts+++ b/packages/utils/src/datetime.test.ts@@ -1,3 +1,8 @@+import {+ CalendarDate,+ CalendarDateTime,+ toZoned+} from "@internationalized/date";import { describe, expect, it } from "vitest";import { datetime } from "./datetime";@@ -52,6 +57,112 @@ describe("datetime.timestamp", () => {});});+// DST is where "derive the day in a tz" and "construct an instant from a wall+// time" diverge. Scheduling a job for a specific local start time in a+// DST-enabled zone is the canonical stress case: the wall time may not exist+// (spring-forward gap), may exist twice (fall-back overlap), or — in zones+// that transition AT midnight — the day boundary itself may be skipped.+describe("DST and exotic-zone stress", () => {+ const wb = (tz: string, y: number, m: number, d: number) =>+ datetime.weekBounds(tz, 0, new CalendarDate(y, m, d));+ const hours = (b: { from: string; to: string }) =>+ (Date.parse(b.to) + 1 - Date.parse(b.from)) / 3600000;++ it("spring-forward week is 167h, fall-back week is 169h (America/Chicago)", () => {+ // 2026-03-08 02:00 → 03:00 CST→CDT; 2026-11-01 02:00 → 01:00 CDT→CST.+ expect(hours(wb("America/Chicago", 2026, 3, 8))).toBe(167);+ expect(hours(wb("America/Chicago", 2026, 11, 1))).toBe(169);+ // A week with no transition stays 168h.+ expect(hours(wb("America/Chicago", 2026, 6, 15))).toBe(168);+ });++ it("half-hour DST shift yields a 167.5h week (Australia/Lord_Howe)", () => {+ // Lord Howe shifts +10:30 → +11:00 on 2026-10-04.+ expect(hours(wb("Australia/Lord_Howe", 2026, 10, 4))).toBe(167.5);+ });++ it("survives a zone that springs forward AT midnight (America/Santiago)", () => {+ // Chile DST starts 2026-09-06: 00:00 does not exist; the day begins 01:00.+ // The day-start conversion resolves to the day's true first instant+ // instead of crashing or sliding into Sep 5.+ const dayStart = new CalendarDate(2026, 9, 6).toDate("America/Santiago");+ expect(dayStart.toISOString()).toBe("2026-09-06T04:00:00.000Z"); // 01:00 -03+ expect(+ datetime+ .businessDay(dayStart.toISOString(), "America/Santiago")+ .toString()+ ).toBe("2026-09-06");+ // 1ms earlier is still the previous day.+ expect(+ datetime+ .businessDay(+ new Date(dayStart.getTime() - 1).toISOString(),+ "America/Santiago"+ )+ .toString()+ ).toBe("2026-09-05");+ // The week containing the skipped midnight is 167h.+ expect(hours(wb("America/Santiago", 2026, 9, 6))).toBe(167);+ });++ it("consecutive weeks tile exactly across a transition — no gap, no double-count", () => {+ for (const [tz, y, m, d] of [+ ["America/Chicago", 2026, 3, 8],+ ["America/Chicago", 2026, 11, 1],+ ["America/Santiago", 2026, 9, 6]+ ] as const) {+ const week = wb(tz, y, m, d);+ const next = datetime.weekBounds(tz, 1, new CalendarDate(y, m, d));+ expect(Date.parse(week.to) + 1).toBe(Date.parse(next.from));+ }+ });++ it("a fixed local start time in the spring-forward gap resolves forward, never crashes", () => {+ // "Start the job at 02:30 local" on the day 02:30 doesn't exist:+ // default disambiguation ('compatible') shifts into the post-gap hour.+ const z = toZoned(+ new CalendarDateTime(2026, 3, 8, 2, 30),+ "America/Chicago"+ );+ expect(z.toAbsoluteString()).toBe("2026-03-08T08:30:00.000Z"); // 03:30 CDT+ });++ it("a fixed local start time in the fall-back overlap resolves to the first occurrence", () => {+ // 01:30 happens twice on 2026-11-01; 'compatible' picks the earlier+ // (CDT) one — the job fires once, not twice.+ const z = toZoned(+ new CalendarDateTime(2026, 11, 1, 1, 30),+ "America/Chicago"+ );+ expect(z.toAbsoluteString()).toBe("2026-11-01T06:30:00.000Z"); // 01:30 CDT+ });++ it("a fixed local wall time maps to different UTC instants across the transition", () => {+ // WHY Carbon's Inngest crons stay on UTC schedules: "02:30 local" is+ // 08:30Z before the transition and 07:30Z after — a fixed UTC cron+ // cannot track a local wall time across DST.+ const before = toZoned(+ new CalendarDateTime(2026, 3, 7, 2, 30),+ "America/Chicago"+ );+ const after = toZoned(+ new CalendarDateTime(2026, 3, 9, 2, 30),+ "America/Chicago"+ );+ expect(before.toAbsoluteString()).toBe("2026-03-07T08:30:00.000Z");+ expect(after.toAbsoluteString()).toBe("2026-03-09T07:30:00.000Z");+ });++ it("handles 45-minute offsets (Asia/Kathmandu, +05:45)", () => {+ expect(+ datetime.businessDay("2026-08-05T18:14:00Z", "Asia/Kathmandu").toString()+ ).toBe("2026-08-05");+ expect(+ datetime.businessDay("2026-08-05T18:16:00Z", "Asia/Kathmandu").toString()+ ).toBe("2026-08-06");+ });+});+describe("datetime.weekNumber", () => {it("matches known ISO 8601 week numbers", () => {expect(diff --git a/packages/utils/src/datetime.ts b/packages/utils/src/datetime.tsindex 88a090027c..eab8f0f0ed 100644--- a/packages/utils/src/datetime.ts+++ b/packages/utils/src/datetime.ts@@ -2,6 +2,7 @@ import {type CalendarDate,now,parseAbsolute,+ startOfWeek,toCalendarDate,today} from "@internationalized/date";@@ -42,5 +43,34 @@ export const datetime = {businessDay: (instant: string, tz: string) =>toCalendarDate(parseAbsolute(instant, tz)),+ /**+ * The ISO week (Monday 00:00 → Sunday 23:59:59.999) containing `anchor`+ * (default: today on the given business calendar) as UTC instant strings.+ * `offset` shifts whole weeks (-1 = last week).+ *+ * DST-safe by construction: boundaries are derived per-day via+ * `CalendarDate.toDate(tz)`, so a transition week is genuinely 167h/169h+ * (Lord Howe: ±30min) rather than a fixed 168, consecutive weeks tile with+ * no gap or double-count, and in zones that spring forward AT midnight+ * (America/Santiago) a boundary that lands on the skipped midnight resolves+ * to that day's true first instant (01:00) instead of crashing or drifting+ * a day.+ */+ weekBounds: (+ tz: string,+ offset = 0,+ anchor?: CalendarDate+ ): { from: string; to: string } => {+ const monday = startOfWeek(+ (anchor ?? today(tz)).add({ weeks: offset }),+ "en-GB"+ );+ const nextMonday = monday.add({ weeks: 1 }).toDate(tz);+ return {+ from: monday.toDate(tz).toISOString(),+ to: new Date(nextMonday.getTime() - 1).toISOString()+ };+ },+weekNumber};