Skip to content

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.

fix(erp): close the timezone gaps self-review found

Sidwebworks92c041c48e57
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 5b41cb1720..2f361ff43f 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -623,3 +623,13 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** When applying a uniform transformation across N sibling branches, diff each branch against its own pre-change body — don't assume they were symmetric. A branch that posted no ledger, sent no email, fired no event before your change must still post/send/fire nothing after, unless the spec explicitly says otherwise. "It typechecks and the other four branches do it" is not evidence the fifth should. Preserve per-branch behavior; the flip's mandate was which id departs, not to newly introduce inventory movements.
**Applies to:** `packages/database/supabase/functions/post-shipment/index.ts` (PO vs SO split blocks); any refactor threading a shared record-builder through multiple writers (`post-*`, `issue`, sync handlers).
+
+## A conformance check is only as good as its source glob — route modules are server AND client in one file
+
+**Context:** The timezone audit (branch `sid/timezone-tz-audit`, PR #1339) added the `no-local-timezone` conformance check to ban process-timezone day derivation in server code. Self-review then found 26 surviving violations in route files, plus more in files the check DID scan using idioms it didn't match.
+
+**Problem:** Two independent under-coverages compounded. (1) The check's source globs (`sources/server-files.ts`) listed services, jobs, and edge functions but not `apps/*/app/routes` — and collected only `.ts`, never `.tsx` — so route loaders/actions (server code!) were never scanned. (2) The banned-pattern list encoded only the idioms already found (`getLocalTimeZone(`, UTC-slicing), not the bug class — `new Date().getDay()` shift rosters and `setHours(0,0,0,0)` week boundaries sailed through in files that WERE scanned. Naively adding the route glob would over-flag: a route module's default export, `clientLoader`/`clientAction`, and hooks run in the browser where the local timezone is correct. Masking IN loader/action bodies also failed — module-level helpers a loader calls (e.g. `getExpiredItemIds`) are server code outside those bodies.
+
+**Rule:** When authoring a conformance check, verify the checker actually loads every file class the rule applies to (run it, count the files, grep one known-bad file into the scan). Ban the bug class, not just the instances you found — then run the widened pattern over the full source set and fix or baseline everything it surfaces before landing. For React Router route modules, path-level globs are the wrong granularity: mask OUT the client regions by declaration shape (`maskClientCode` blanks default export / `clientLoader` / `clientAction` / PascalCase and `use*` declarations) so server helpers stay covered; masking IN named exports under-covers.
+
+**Applies to:** `packages/checks/src/sources/server-files.ts` + `conformance/no-local-timezone.ts`; any new `SERVER_CHECKS` rule; any lint/conformance gate keyed on file paths over `apps/*/app/routes`.
diff --git a/.ai/plans/2026-08-06-timezone-audit-review-fixes.md b/.ai/plans/2026-08-06-timezone-audit-review-fixes.md
new file mode 100644
index 0000000000..c698cd8525
--- /dev/null
+++ b/.ai/plans/2026-08-06-timezone-audit-review-fixes.md
@@ -0,0 +1,92 @@
+# Fix all 18 self-review findings on sid/timezone-tz-audit
+
+## Context
+
+Self-review of PR #1339 (timezone audit) found 18 issues: 4 must-fix timezone bugs the branch's own conformance check failed to catch, 4 risks, 5 code-quality items, and 5 docs-freshness gaps. The root cause of the must-fixes is that `no-local-timezone` only bans `getLocalTimeZone()` and UTC-slicing — it misses local date-part getters (`new Date().getDay()`) and local-midnight boundaries (`setHours(0,0,0,0)`), so the same bug class survived in people/timecard code. Fix the sites, then widen the check so they can't return.
+
+A blast-radius scan of the widened patterns over all scanned server files found exactly these sites needing fixes (no baseline additions needed once fixed): `people.service.ts:772,842-845`, `person+/$personId.timecard.tsx:70-79` (loader-called), `mes/timecard.tsx:53-61` (loader-called), `update-purchased-prices/index.ts:219`.
+
+**Design decisions (flagging for approval):**
+- **Weekly timecard windows use company TZ** (one payroll calendar per books), not per-employee location — consistent across `getWeeklyHoursForEmployees` and both timecard routes.
+- **`company_today`/`location_today` stay SECURITY INVOKER** (#7): making them DEFINER would expose a cross-tenant "what's company X's local date" RPC via PostgREST. Instead document the invariant (every current caller is SECURITY DEFINER or service-role, so the silent-UTC fallback path is unreachable) in the migration.
+- **#12 (hook stale across midnight) is acknowledged, not fixed** — forms are short-lived; a comment notes the tradeoff.
+
+## Fixes
+
+### 1. Widen the conformance check (#4) — do this first, it gates the rest
+
+`packages/checks/src/conformance/no-local-timezone.ts` — add two BANNED patterns:
+- `/new Date\(\)\s*\.get(?:Day|Date|Month|FullYear|Hours|Minutes)\(/g` — "local date-part of now on a server"
+- `/\.setHours\(\s*0\s*,\s*0\s*,\s*0\s*,\s*0\s*\)/g` — "local midnight boundary; derive the day in an explicit tz"
+
+Extend `no-local-timezone.test.ts` with cases for both (flagged) and for safe idioms (UTC getters, `new Date(y, m, d).getFullYear()` roundtrips are NOT banned — patterns are anchored to `new Date().` / the 0,0,0,0 literal, so `shared.server.ts` `dateToString` and client helpers stay clean).
+
+### 2. people.service.ts (#2, #3)
+
+`apps/erp/app/modules/people/people.service.ts` — both are MCP-exposed with `(client, companyId)` already in scope; resolve tz via the **raw** `getCompanyTimeZone` from `@carbon/database` (services must not import the Redis wrapper — client-bundle leak):
+- `getScheduledEmployeesToday:772` — replace `dayNames[new Date().getDay()]` with `getDayOfWeek(today(tz), "en-US")` (0=Sun, matches `dayNames` order).
+- `getWeeklyHoursForEmployees:841-845` — replace the `getDay/setDate/setHours(0,0,0,0)` Monday computation with `startOfWeek(today(tz), "en-GB").toDate(tz)` (en-GB = Monday-first), `.gte("clockIn", monday.toISOString())`.
+
+### 3. Timecard week bounds (flagged by widened check)
+
+Same pattern in two loader-called helpers — give `getWeekBounds` a `tz: string` param, resolve company TZ in the loader (routes may use the cached `~/modules/shared/timezone.server` resolver; MES has no such module — use raw `@carbon/database` resolver there):
+- `apps/erp/app/routes/x+/person+/$personId.timecard.tsx:70-79` (loader at :148)
+- `apps/mes/app/routes/x+/timecard.tsx:53-61` (loader at :125)
+
+`from` = `startOfWeek(today(tz).add({weeks: offset}), "en-GB").toDate(tz).toISOString()`; `to` = next Monday's midnight minus 1ms (preserves the current lte semantics). Do NOT touch `getShiftTimesForDate` / `toLocalDatetimeInput` — verified client-called only (datetime-local input prefill; browser tz is correct there).
+
+### 4. Sequence preview tz (#1, #10)
+
+- `apps/erp/app/modules/settings/settings.service.ts:312-313` (`getCurrentSequence`, also MCP tool): resolve company tz (raw `@carbon/database` resolver) and pass to both `interpolateSequenceDate` calls.
+- `apps/erp/app/utils/string.ts` — change signature default to `timezone = "UTC"` to match the Deno copy exactly; update its comment.
+- Client previews pass the real tz: `SequenceForm.tsx:42-43` and `ItemSerialSequenceForm.tsx:52-53` pass `useCompanyTimeZone()` (new hook already exists in `~/hooks`).
+
+### 5. Intercompany source-company day (#5)
+
+- `apps/erp/app/modules/accounting/accounting.service.ts:349-355` (`getCompaniesInGroup`): add `timezone` to the select.
+- `apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx`: add a `SourcePostingDateSync` component mirroring the existing `SourceCurrencySync` pattern — when `sourceCompanyId` changes, set the `postingDate` field to `today(sourceCompany.timezone).toString()` via `useControlField`. Initial default (no source picked yet) stays `useCompanyToday()` from the route.
+- The action-side fallback at `accounting.service.ts:2986` stays as defense-in-depth.
+
+### 6. Honest null handling for locationId (#6)
+
+- `apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx` — replace `shipmentForSurface?.locationId as string` with an explicit branch: `locId ? getLocationTimeZone(serviceRole, locId, companyId) : getCompanyTimeZone(serviceRole, companyId)`.
+- `apps/erp/app/routes/api+/kanban.$id.tsx` — same for `kanban.data.locationId!`.
+
+### 7. SECURITY INVOKER invariant comment (#7)
+
+Edit `packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql` (committed but not yet supabase-tracked; idempotent CREATE OR REPLACE) — comment on both helpers: callers must be SECURITY DEFINER or service-role; under RLS denial these silently return UTC, and we deliberately do NOT make them SECURITY DEFINER to avoid exposing a cross-tenant date/timezone probe via PostgREST RPC.
+
+### 8. Jobs-package local-day fixes (#8, #13, + flagged)
+
+- `packages/jobs/src/inngest/functions/extraction/extract-document.ts:24` — use `getUTCFullYear/getUTCMonth/getUTCDate` (document-intrinsic date; UTC makes parse→format roundtrip stable under any process tz).
+- `packages/jobs/src/inngest/functions/scheduled/audit-archive.ts:52-54` — same UTC getters for the archive path (storage key, comment it).
+- `packages/database/supabase/functions/update-purchased-prices/index.ts:219` — replace the `setFullYear(getFullYear()-1)` construction with instant arithmetic (`new Date(Date.now() - 365 * 86400_000)`) — rolling window, day-precision irrelevant.
+
+### 9. ISO-week dedup (#9)
+
+- `packages/database/supabase/functions/lib/datetime.ts` — delete the inline `weekNumber` body; implement via `isoWeekFromYmd` imported from `./utils.ts` (utils is dependency-free, so this is safe for the node-side `@carbon/database` build — the reverse direction would drag `npm:` imports into the node graph).
+- `apps/erp/app/utils/string.ts` — delete the local `getISOWeek` algorithm; derive via `datetime.weekNumber(new CalendarDate(y, m, d))` from `@carbon/utils`.
+- Leave: the two datetime.ts mirrors (documented keep-in-sync policy) and `quality.kpi.$key.ts`'s `getISOWeekYear` (needs the ISO week-**year** pair, already UTC-correct).
+
+### 10. Hook consistency (#11, #12)
+
+`apps/erp/app/hooks/useCompanyTimeZone.tsx` — use `datetime.today(tz)` from `@carbon/utils` instead of bare `today()`; add a comment acknowledging the value is computed at render and a form left open across midnight keeps the stale day (accepted).
+
+## Docs (#14–#18)
+
+- `packages/checks/AGENTS.md:34` — update the `noLocalTimezone` line: scans server TS **plus route loaders/actions** in both apps; route files are masked (`maskClientCode`) so components/hooks/clientLoader/clientAction are exempt while module-level server helpers are covered.
+- `packages/database/AGENTS.md` — Key Exports: add `getCompanyTimeZone`/`getLocationTimeZone` (`src/timezone.ts`, overloaded Supabase/Kysely), `AnyPostgresClient`/`isKysely` (`src/utils.ts`), and note SQL helpers `company_today()`/`location_today()`.
+- `.ai/lessons.md` — new entry (Context → Problem → Rule → Applies to): a conformance check is only as good as its source glob — route modules are server AND client in one file, so path-keyed checks must mask by declaration, and you must verify the checker actually loads the files you think it does.
+- Write this plan to `.ai/plans/2026-08-06-timezone-audit-review-fixes.md` (AGENTS.md convention).
+- After commit: `gh pr edit 1339` — refresh body (39 route files not 16; conformance-check gap + route sweep; `get_next_sequence`/`location_today` migration; HQ-timezone clobber fix; `useCompanyToday`). Push still gated on explicit approval.
+
+## Verification
+
+1. `pnpm --filter @carbon/checks test` — extended pattern tests green.
+2. Conformance scan (`newViolations()` via tsx) — **0 new violations, 0 baseline additions** (proves every widened-pattern site was actually fixed).
+3. `pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/checks --filter=@carbon/database --filter=@carbon/utils --filter=@carbon/jobs`.
+4. `pnpm run lint`.
+5. `TZ=America/Chicago pnpm run test` — suite green under non-UTC process tz (the regression gate).
+6. `pnpm run build:erp` — catches any client-bundle leak from new service imports.
+7. DB spot-check (read-only psql against the India company, currently a day ahead of UTC): `getScheduledEmployeesToday` day-of-week and sequence preview vs `get_next_sequence` output agree with `company_today()`.
+8. Commit (no AI attribution), update PR body; push only on explicit approval.
diff --git a/apps/erp/app/hooks/useCompanyTimeZone.tsx b/apps/erp/app/hooks/useCompanyTimeZone.tsx
index 04e2c00d66..d3713b2fed 100644
--- a/apps/erp/app/hooks/useCompanyTimeZone.tsx
+++ b/apps/erp/app/hooks/useCompanyTimeZone.tsx
@@ -1,5 +1,5 @@
import { useRouteData } from "@carbon/react";
-import { today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { Company } from "~/modules/settings";
import { path } from "~/utils/path";
@@ -14,7 +14,11 @@ export function useCompanyTimeZone(): string {
return data?.company?.timezone ?? "UTC";
}
-/** Today's `YYYY-MM-DD` on the company's calendar — a form-ready default. */
+/**
+ * Today's `YYYY-MM-DD` on the company's calendar — a form-ready default.
+ * Computed at render: a form left open across the company's midnight keeps the
+ * stale day (accepted — create forms are short-lived).
+ */
export function useCompanyToday(): string {
- return today(useCompanyTimeZone()).toString();
+ return datetime.today(useCompanyTimeZone()).toString();
}
diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.ts
index 164c256f41..de1dcc6cce 100644
--- a/apps/erp/app/modules/accounting/accounting.service.ts
+++ b/apps/erp/app/modules/accounting/accounting.service.ts
@@ -348,7 +348,9 @@ export async function getCompaniesInGroup(
) {
return client
.from("company")
- .select("id, name, baseCurrencyCode, parentCompanyId, isEliminationEntity")
+ .select(
+ "id, name, baseCurrencyCode, timezone, parentCompanyId, isEliminationEntity"
+ )
.eq("companyGroupId", companyGroupId)
.eq("active", true)
.eq("isEliminationEntity", false)
diff --git a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx
index 1525e44205..3887a4a216 100644
--- a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx
+++ b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx
@@ -10,6 +10,7 @@ import {
ModalDrawerTitle,
VStack
} from "@carbon/react";
+import { today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect } from "react";
import type { z } from "zod";
@@ -26,7 +27,12 @@ import { intercompanyTransactionValidator } from "../../accounting.models";
type IntercompanyTransactionFormProps = {
initialValues: z.infer<typeof intercompanyTransactionValidator>;
- companies: { id: string; name: string; baseCurrencyCode: string | null }[];
+ companies: {
+ id: string;
+ name: string;
+ baseCurrencyCode: string | null;
+ timezone: string | null;
+ }[];
open?: boolean;
onClose: () => void;
};
@@ -98,6 +104,7 @@ const IntercompanyTransactionForm = ({
termId="intercompany-posting-date"
type="date"
/>
+ <SourcePostingDateSync companies={companies} />
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
@@ -114,6 +121,29 @@ const IntercompanyTransactionForm = ({
);
};
+// The journal posts to the SOURCE company's books, so the default posting date
+// is that company's calendar day — which can differ from the acting company's
+// (and the browser's) around midnight. Only overwrites while the user hasn't
+// picked a source yet or switches it; an explicit date edit stays theirs until
+// the next source change.
+function SourcePostingDateSync({
+ companies
+}: {
+ companies: { id: string; timezone: string | null }[];
+}) {
+ const [sourceCompanyId] = useControlField<string>("sourceCompanyId");
+ const [, setPostingDate] = useControlField<string>("postingDate");
+
+ const timezone =
+ companies.find((c) => c.id === sourceCompanyId)?.timezone ?? null;
+
+ useEffect(() => {
+ if (timezone) setPostingDate(today(timezone).toString());
+ }, [timezone, setPostingDate]);
+
+ return null;
+}
+
function SourceCurrencySync({
companies
}: {
diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.ts
index f09e748b1f..8e1859058d 100644
--- a/apps/erp/app/modules/people/people.service.ts
+++ b/apps/erp/app/modules/people/people.service.ts
@@ -1,4 +1,6 @@
import type { Database, Json } from "@carbon/database";
+import { getCompanyTimeZone } from "@carbon/database";
+import { getDayOfWeek, startOfWeek, today } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
import type { DataType } from "~/modules/shared";
@@ -769,11 +771,14 @@ export async function getScheduledEmployeesToday(
"friday",
"saturday"
] as const;
- const today = dayNames[new Date().getDay()];
+ // "Today" on the company calendar — at 01:00 Monday local, UTC is still on
+ // Sunday and must not roster Sunday's shift. en-US: 0 = Sunday.
+ const tz = await getCompanyTimeZone(client, companyId);
+ const dayName = dayNames[getDayOfWeek(today(tz), "en-US")];
return data.filter((ej) => {
const shift = ej.shift as Record<string, unknown> | null;
- return shift && shift[today] === true;
+ return shift && shift[dayName] === true;
});
}
@@ -838,11 +843,10 @@ export async function getWeeklyHoursForEmployees(
companyId: string,
employeeIds: string[]
): Promise<Record<string, number>> {
- const now = new Date();
- const dayOfWeek = now.getDay();
- const monday = new Date(now);
- monday.setDate(now.getDate() - ((dayOfWeek + 6) % 7));
- monday.setHours(0, 0, 0, 0);
+ // Week starts Monday 00:00 on the company calendar (one payroll boundary
+ // per books), not the server's. en-GB: weeks start Monday.
+ const tz = await getCompanyTimeZone(client, companyId);
+ const monday = startOfWeek(today(tz), "en-GB").toDate(tz);
const { data: entries } = await client
.from("timeCardEntry")
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index b6fbd82008..15f43edc04 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -1,5 +1,6 @@
import { SUPABASE_URL } from "@carbon/auth";
import type { Database, Json } from "@carbon/database";
+import { getCompanyTimeZone } from "@carbon/database";
import type {
DocumentBlock,
DocumentSectionPlacement,
@@ -309,8 +310,11 @@ export async function getCurrentSequence(
const { prefix, suffix, next, size } = sequence.data;
const currentSequence = next.toString().padStart(size, "0");
- const derivedPrefix = interpolateSequenceDate(prefix);
- const derivedSuffix = interpolateSequenceDate(suffix);
+ // Same calendar as get_next_sequence (SQL): tokens roll over at the
+ // company's midnight, or the preview disagrees with the issued number.
+ const timezone = await getCompanyTimeZone(client, companyId);
+ const derivedPrefix = interpolateSequenceDate(prefix, timezone);
+ const derivedSuffix = interpolateSequenceDate(suffix, timezone);
return {
data: `${derivedPrefix}${currentSequence}${derivedSuffix}`,
diff --git a/apps/erp/app/modules/settings/ui/Sequences/SequenceForm.tsx b/apps/erp/app/modules/settings/ui/Sequences/SequenceForm.tsx
index 856c3cd7c3..7189216989 100644
--- a/apps/erp/app/modules/settings/ui/Sequences/SequenceForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Sequences/SequenceForm.tsx
@@ -16,7 +16,7 @@ import { useState } from "react";
import { useNavigate } from "react-router";
import type { z } from "zod";
import { Hidden, Input, Number, Submit } from "~/components/Form";
-import { usePermissions } from "~/hooks";
+import { useCompanyTimeZone, usePermissions } from "~/hooks";
import { sequenceValidator } from "~/modules/settings";
import { path } from "~/utils/path";
import { interpolateSequenceDate } from "~/utils/string";
@@ -38,9 +38,12 @@ const SequenceForm = ({ initialValues }: SequenceFormProps) => {
const [next, setNext] = useState(initialValues.next ?? "1");
const [size, setSize] = useState(initialValues.size ?? 5);
+ // Preview in the company timezone — the same calendar get_next_sequence
+ // issues numbers in — not the browser's.
+ const timezone = useCompanyTimeZone();
const makePreview = () => {
- const p = interpolateSequenceDate(prefix);
- const s = interpolateSequenceDate(suffix);
+ const p = interpolateSequenceDate(prefix, timezone);
+ const s = interpolateSequenceDate(suffix, timezone);
return `${p}${next.toString().padStart(size, "0")}${s}`;
};
@@ -105,7 +108,6 @@ const SequenceForm = ({ initialValues }: SequenceFormProps) => {
<p className="text-muted-foreground text-sm">{`%{mm} = Month`}</p>
<p className="text-muted-foreground text-sm">{`%{dd} = Day`}</p>
<p className="text-muted-foreground text-sm">{`%{hh} = Hour`}</p>
- <p className="text-muted-foreground text-sm">{`%{mm} = Minute`}</p>
<p className="text-muted-foreground text-sm">{`%{ss} = Second`}</p>
</VStack>
</VStack>
diff --git a/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequenceForm.tsx b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequenceForm.tsx
index acb635a466..bcee33239e 100644
--- a/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequenceForm.tsx
+++ b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequenceForm.tsx
@@ -16,7 +16,7 @@ import { useState } from "react";
import { useNavigate } from "react-router";
import type { z } from "zod";
import { Hidden, Input, Item, Number, Submit } from "~/components/Form";
-import { usePermissions } from "~/hooks";
+import { useCompanyTimeZone, usePermissions } from "~/hooks";
import { itemSerialSequenceValidator } from "~/modules/settings";
import { path } from "~/utils/path";
import { interpolateSequenceDate } from "~/utils/string";
@@ -45,12 +45,21 @@ const ItemSerialSequenceForm = ({
const [size, setSize] = useState(initialValues.size ?? 5);
const [step, setStep] = useState(initialValues.step ?? 1);
+ // Preview in the company timezone — the same calendar serial numbers are
+ // issued in — not the browser's.
+ const timezone = useCompanyTimeZone();
const makePreview = () => {
// %{location} is resolved at issue time from the item's location; for the
// preview we stand in a sample location code ("HQ") so the token doesn't
// show through literally.
- const p = interpolateSequenceDate(prefix).replace(/%{location}/g, "HQ");
- const s = interpolateSequenceDate(suffix).replace(/%{location}/g, "HQ");
+ const p = interpolateSequenceDate(prefix, timezone).replace(
+ /%{location}/g,
+ "HQ"
+ );
+ const s = interpolateSequenceDate(suffix, timezone).replace(
+ /%{location}/g,
+ "HQ"
+ );
// Preview the NEXT number that will be issued (current counter + step),
// not the current counter itself — so a fresh sequence shows "00001".
return `${p}${(next + step).toString().padStart(size, "0")}${s}`;
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index 890f2a5e47..cecccb1603 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -25,7 +25,10 @@ import {
insertPurchaseOrder,
upsertPurchaseOrderLine
} from "~/modules/purchasing";
-import { getLocationTimeZone } from "~/modules/shared/timezone.server";
+import {
+ getCompanyTimeZone,
+ getLocationTimeZone
+} from "~/modules/shared/timezone.server";
import { path } from "~/utils/path";
const logger = getLogger("erp", "kanban");
@@ -87,8 +90,11 @@ async function handleKanban({
]);
const leadTime = manufacturing.data?.leadTime ?? 7;
+ // No location on the kanban → the company calendar.
const startDate = datetime.today(
- await getLocationTimeZone(client, kanban.data.locationId!, companyId)
+ kanban.data.locationId
+ ? await getLocationTimeZone(client, kanban.data.locationId, companyId)
+ : await getCompanyTimeZone(client, companyId)
);
const dueDate = startDate.add({ days: leadTime }).toString();
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index e773de38b5..7cc857aa9d 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-05T19:39:38.408Z",
+ "generated": "2026-08-05T20:59:07.360Z",
"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.tsx
index e5a39de58b..69defa7623 100644
--- a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx
+++ b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx
@@ -29,6 +29,7 @@ import {
Thead,
Tr
} from "@carbon/react";
+import { startOfWeek, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
import { useEffect, useState } from "react";
@@ -65,24 +66,18 @@ import {
updateTimeCardEntryValidator
} from "~/modules/people";
import { getCompanySettings } from "~/modules/settings";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { path } from "~/utils/path";
-function getWeekBounds(offset: number = 0) {
- const now = new Date();
- const dayOfWeek = now.getDay(); // 0 = Sunday
- const monday = new Date(now);
- monday.setDate(now.getDate() - ((dayOfWeek + 6) % 7) + offset * 7);
- monday.setHours(0, 0, 0, 0);
-
- const sunday = new Date(monday);
- sunday.setDate(monday.getDate() + 6);
- sunday.setHours(23, 59, 59, 999);
+// 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.toISOString(),
- to: sunday.toISOString(),
- monday,
- sunday
+ from: monday.toDate(tz).toISOString(),
+ to: new Date(nextMonday.getTime() - 1).toISOString()
};
}
@@ -145,7 +140,10 @@ 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(weekOffset);
+ const { from, to } = getWeekBounds(
+ await getCompanyTimeZone(client, companyId),
+ weekOffset
+ );
const [entries, openEntry, companySettings, employeeShift] =
await Promise.all([
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
index c592008911..d3a2edc94c 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
@@ -15,7 +15,10 @@ import { parseDate } from "@internationalized/date";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { upsertDocument } from "~/modules/documents";
-import { getLocationTimeZone } from "~/modules/shared/timezone.server";
+import {
+ getCompanyTimeZone,
+ getLocationTimeZone
+} from "~/modules/shared/timezone.server";
import { loader as pdfLoader } from "~/routes/file+/shipment+/$id[.]pdf";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
@@ -135,12 +138,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Expiry is judged on the shipping site's calendar, not the server's — a lot
// that expires today must not read as expired at a plant still on yesterday.
+ // No location on the shipment → the company calendar.
+ const shipmentLocationId = shipmentForSurface?.locationId as string | null;
const todayLocal = datetime.today(
- await getLocationTimeZone(
- serviceRole,
- shipmentForSurface?.locationId as string,
- companyId
- )
+ shipmentLocationId
+ ? await getLocationTimeZone(serviceRole, shipmentLocationId, companyId)
+ : await getCompanyTimeZone(serviceRole, companyId)
);
const expiredEntities = (shipmentTrackedEntities ?? []).filter((e) => {
if (!e.expirationDate) return false;
diff --git a/apps/erp/app/utils/string.ts b/apps/erp/app/utils/string.ts
index 6fdef74c2b..73137571af 100644
--- a/apps/erp/app/utils/string.ts
+++ b/apps/erp/app/utils/string.ts
@@ -1,4 +1,6 @@
import { getLogger } from "@carbon/logger";
+import { datetime } from "@carbon/utils";
+import { CalendarDate } from "@internationalized/date";
export { stripSpecialCharacters } from "@carbon/utils";
@@ -52,17 +54,6 @@ export const copyToClipboard = async (
}
};
-// ISO 8601 week number (1-53). Week 1 is the week containing the year's first Thursday.
-export const getISOWeek = (date: Date): number => {
- const d = new Date(
- Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())
- );
- const dayNum = d.getUTCDay() || 7; // Sunday → 7
- d.setUTCDate(d.getUTCDate() + 4 - dayNum); // shift to the week's Thursday
- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
- return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
-};
-
// Current wall-clock parts in an explicit timezone (for server callers that
// derive sequence tokens in the company's business timezone).
const datePartsInTimeZone = (timezone: string) => {
@@ -86,30 +77,20 @@ const datePartsInTimeZone = (timezone: string) => {
};
};
-// used to generate sequences. Server callers pass the company timezone so
-// tokens roll over at the company's midnight; the client-side sequence-preview
-// forms omit it and preview in the browser's timezone.
+// used to generate sequences — date tokens derive in the company's business
+// timezone so document prefixes roll over at the company's midnight, not the
+// process's. Mirrors functions/lib/utils.ts; keep the two in sync.
export const interpolateSequenceDate = (
value: string | null,
- timezone?: string
+ timezone = "UTC"
) => {
// replace all instances of %{year} with the current year
if (!value) return "";
let result = value;
if (result.includes("%{")) {
- const date = new Date();
- const parts = timezone
- ? datePartsInTimeZone(timezone)
- : {
- year: date.getFullYear(),
- month: date.getMonth() + 1,
- day: date.getDate(),
- hours: date.getHours(),
- seconds: date.getSeconds()
- };
- const { year, month, day, hours, seconds } = parts;
- const week = getISOWeek(new Date(year, month - 1, day));
+ const { year, month, day, hours, seconds } = datePartsInTimeZone(timezone);
+ const week = datetime.weekNumber(new CalendarDate(year, month, day));
result = result.replace(/%{yyyy}/g, year.toString());
result = result.replace(/%{yy}/g, year.toString().slice(-2));
diff --git a/apps/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsx
index 3e3e9f8191..2cbcbf7062 100644
--- a/apps/mes/app/routes/x+/timecard.tsx
+++ b/apps/mes/app/routes/x+/timecard.tsx
@@ -1,4 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCompanyTimeZone } from "@carbon/database";
import {
Badge,
Button,
@@ -28,6 +29,7 @@ import {
Thead,
Tr
} from "@carbon/react";
+import { startOfWeek, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
import { useEffect, useState } from "react";
@@ -50,22 +52,15 @@ import {
} from "~/services/people.service";
import { path } from "~/utils/path";
-function getWeekBounds(offset: number = 0) {
- const now = new Date();
- const dayOfWeek = now.getDay();
- const monday = new Date(now);
- monday.setDate(now.getDate() - ((dayOfWeek + 6) % 7) + offset * 7);
- monday.setHours(0, 0, 0, 0);
-
- const sunday = new Date(monday);
- sunday.setDate(monday.getDate() + 6);
- sunday.setHours(23, 59, 59, 999);
+// 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.toISOString(),
- to: sunday.toISOString(),
- monday,
- sunday
+ from: monday.toDate(tz).toISOString(),
+ to: new Date(nextMonday.getTime() - 1).toISOString()
};
}
@@ -122,7 +117,10 @@ 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(weekOffset);
+ const { from, to } = getWeekBounds(
+ await getCompanyTimeZone(client, companyId),
+ weekOffset
+ );
const [entries, openEntry] = await Promise.all([
client
diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.md
index 5dd0ff2740..8d34323c76 100644
--- a/packages/checks/AGENTS.md
+++ b/packages/checks/AGENTS.md
@@ -31,7 +31,7 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
## Key Patterns
-- **Conformance checks**: `noNumericPrecision`, `noLegacyRls` — scan SQL migrations for anti-patterns; `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()` / UTC day-slicing
+- **Conformance checks**: `noNumericPrecision`, `noLegacyRls` — scan SQL migrations for anti-patterns; `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call
- **Structure checks**: `moduleShape` — validates ERP modules have `types.ts`, `ui/`, `index.ts`, `<name>.service.ts`, `<name>.models.ts`
- **Clobber detection**: `findClobbers(branch, main)` — identifies DB objects redefined on both sides
- **Baseline**: `src/baseline.ts` — grandfathered violations keyed by `checkId + file + line + snippet`
diff --git a/packages/checks/src/conformance/no-local-timezone.test.ts b/packages/checks/src/conformance/no-local-timezone.test.ts
index ee0b9be4fc..bdf024cf2b 100644
--- a/packages/checks/src/conformance/no-local-timezone.test.ts
+++ b/packages/checks/src/conformance/no-local-timezone.test.ts
@@ -21,11 +21,41 @@ describe("noLocalTimezone", () => {
expect(v).toHaveLength(1);
});
+ it("flags local date-parts of now", () => {
+ const cases = [
+ "const today = dayNames[new Date().getDay()];",
+ "const year = new Date().getFullYear();",
+ "const dom = new Date().getDate();"
+ ];
+ for (const ts of cases) {
+ expect(noLocalTimezone.scan("f.ts", ts)).toHaveLength(1);
+ }
+ });
+
+ it("flags local-midnight boundaries via setHours(0,0,0,0)", () => {
+ const ts = "monday.setHours(0, 0, 0, 0);";
+ expect(noLocalTimezone.scan("f.ts", ts)).toHaveLength(1);
+ });
+
it("allows full-instant timestamps", () => {
const ts = "const at = new Date().toISOString();";
expect(noLocalTimezone.scan("f.ts", ts)).toHaveLength(0);
});
+ it("allows UTC getters and local-roundtrip getters", () => {
+ const cases = [
+ "const dow = d.getUTCDay() || 7;",
+ "const y = new Date(Date.UTC(2026, 0, 1)).getUTCFullYear();",
+ // pg DATE parsed to local midnight → local getters roundtrip the parts
+ "const y = value.getFullYear();",
+ // non-midnight setHours (shift wall-times, client prefill) stays legal
+ "clockIn.setHours(startH, startM, 0, 0);"
+ ];
+ for (const ts of cases) {
+ expect(noLocalTimezone.scan("f.ts", ts)).toHaveLength(0);
+ }
+ });
+
it("allows the datetime API", () => {
const ts =
"const d = datetime.today(await getCompanyTimeZone(client, companyId)).toString();";
diff --git a/packages/checks/src/conformance/no-local-timezone.ts b/packages/checks/src/conformance/no-local-timezone.ts
index 3e4eae6c45..6423809db0 100644
--- a/packages/checks/src/conformance/no-local-timezone.ts
+++ b/packages/checks/src/conformance/no-local-timezone.ts
@@ -5,10 +5,14 @@ import type { ConformanceCheck, Violation } from "../check";
* banned idioms silently disagree with each other whenever TZ ≠ UTC:
* - getLocalTimeZone() on a server = the server's zone, not the user's
* - new Date().toISOString().split("T")[0] / .slice(0, 10) = the UTC day
+ * - new Date().getDay()/getDate()/... = date parts of "now" in the process zone
+ * - d.setHours(0, 0, 0, 0) = midnight in the process zone
* Use datetime.today(tz) / datetime.businessDay(instant, tz) with a timezone
* resolved from company.timezone (ledger-scoped) or location.timezone
* (operational). Full-instant new Date().toISOString() stays allowed —
- * timestamps are timezone-free.
+ * timestamps are timezone-free. UTC getters (getUTCDay etc.) and local getters
+ * on a locally-constructed date (new Date(y, m, d).getFullYear() roundtrips)
+ * are also fine and deliberately not matched.
*/
const BANNED = [
{
@@ -21,6 +25,16 @@ const BANNED = [
/new Date\(\)\s*\.toISOString\(\)\s*\.(?:split\(\s*["']T["']\s*\)\s*\[0\]|slice\(\s*0,\s*10\s*\))/g,
message:
"Server code: this is the UTC calendar day — use datetime.today(tz) with the company/location timezone."
+ },
+ {
+ pattern: /new Date\(\)\s*\.get(?:Day|Date|Month|FullYear|Hours|Minutes)\(/g,
+ message:
+ 'Server code: this is a date part of "now" in the process zone — use datetime.today(tz) / getDayOfWeek with the company/location timezone.'
+ },
+ {
+ pattern: /\.setHours\(\s*0\s*,\s*0\s*,\s*0\s*,\s*0\s*\)/g,
+ message:
+ "Server code: this is midnight in the process zone — derive the day boundary via today(tz)/startOfWeek(...).toDate(tz) instead."
}
];
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index e89b418eb7..930e641d81 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -41,6 +41,7 @@ pnpm --filter @carbon/database typecheck
| `./sampling` | Node-side re-export of `supabase/functions/shared/sampling-engine.ts` (Z1.4 / ISO 2859-1 resolvers) |
| `./audit` | Audit-log functions (`getEntityAuditLog`, `enableAuditLog`, `syncAuditSubscriptions`, …); `auditConfig` + `AuditEntityType` come from the separate `./audit.config` subpath |
| `./ratelimit` | `checkApiKeyRateLimit` (Postgres RPC wrapper) |
+| `.` (timezone) | `getCompanyTimeZone(db, companyId)` / `getLocationTimeZone(db, locationId, companyId)` (`src/timezone.ts`) — business-timezone resolvers, overloaded for Supabase client or Kysely handle; `AnyPostgresClient` + `isKysely` guard (`src/utils.ts`) for writing such overloads. SQL siblings: `company_today(companyId)` / `location_today(locationId, companyId)` replace `CURRENT_DATE` for business dates in DB functions (SECURITY INVOKER — callers must be SECURITY DEFINER or service-role). ERP routes should prefer the Redis-cached wrappers in `~/modules/shared/timezone.server` |
## Cross-References
diff --git a/packages/database/supabase/functions/lib/datetime.ts b/packages/database/supabase/functions/lib/datetime.ts
index a10b34bf19..c41bb33565 100644
--- a/packages/database/supabase/functions/lib/datetime.ts
+++ b/packages/database/supabase/functions/lib/datetime.ts
@@ -11,19 +11,15 @@ import {
import type { SupabaseClient } from "@supabase/supabase-js";
import type { Kysely } from "kysely";
import type { DB } from "./database.ts";
-import { type AnyPostgresClient, isKysely } from "./utils.ts";
+import { type AnyPostgresClient, isKysely, isoWeekFromYmd } from "./utils.ts";
import type { Database } from "./types.ts";
/**
* ISO 8601 week number (1-53). Week 1 is the week containing the year's first
- * Thursday. Pure UTC arithmetic on the date parts — no timezone dependency.
+ * Thursday. Delegates to the single algorithm in ./utils.ts.
*/
function weekNumber(date: CalendarDate): number {
- const d = new Date(Date.UTC(date.year, date.month - 1, date.day));
- const dayNum = d.getUTCDay() || 7; // Sunday → 7
- d.setUTCDate(d.getUTCDate() + 4 - dayNum); // shift to the week's Thursday
- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
- return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
+ return isoWeekFromYmd(date.year, date.month, date.day);
}
/**
diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.ts
index 96227f1bb1..9b560db1a3 100644
--- a/packages/database/supabase/functions/lib/utils.ts
+++ b/packages/database/supabase/functions/lib/utils.ts
@@ -40,8 +40,14 @@ export interface TrackedEntityAttributes {
Shelf?: string;
}
-// ISO 8601 week number (1-53). Week 1 is the week containing the year's first Thursday.
-const isoWeekFromYmd = (year: number, month: number, day: number): number => {
+// ISO 8601 week number (1-53). Week 1 is the week containing the year's first
+// Thursday. The one copy of the algorithm in the functions lib — datetime.ts
+// delegates here.
+export const isoWeekFromYmd = (
+ year: number,
+ month: number,
+ day: number
+): number => {
const d = new Date(Date.UTC(year, month - 1, day));
const dayNum = d.getUTCDay() || 7; // Sunday → 7
d.setUTCDate(d.getUTCDate() + 4 - dayNum); // shift to the week's Thursday
@@ -49,9 +55,6 @@ const isoWeekFromYmd = (year: number, month: number, day: number): number => {
return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
};
-export const getISOWeek = (date: Date): number =>
- isoWeekFromYmd(date.getFullYear(), date.getMonth() + 1, date.getDate());
-
// Current wall-clock parts in an explicit timezone. Intl-based so this module
// stays importable from both Deno and Node (no npm:/workspace deps).
const datePartsInTimeZone = (timezone: string) => {
diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.ts
index 4c001aadf8..b04780a98c 100644
--- a/packages/database/supabase/functions/update-purchased-prices/index.ts
+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts
@@ -1,6 +1,5 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import { sql } from "kysely";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
@@ -215,10 +214,12 @@ serve(async (req: Request) => {
)
);
- const dateOneYearAgo = format(
- new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
- "yyyy-MM-dd"
- );
+ // Rolling one-year window over postingDate, anchored on the company's
+ // calendar day (postingDate itself is company-tz derived).
+ const dateOneYearAgo = datetime
+ .today(await getCompanyTimeZone(db, companyId))
+ .subtract({ years: 1 })
+ .toString();
const itemCostUpdates: Database["public"]["Tables"]["itemCost"]["Update"][] =
[];
diff --git a/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql b/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql
index 536d6cbfeb..21690cf557 100644
--- a/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql
+++ b/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql
@@ -11,6 +11,14 @@
-- Operational sibling of company_today(): a physical site's calendar day, for
-- expiry and scheduling. Falls back to the company timezone, then UTC — the
-- same precedence as getLocationTimeZone() in the app.
+--
+-- SECURITY INVOKER (like company_today), deliberately: every caller today is
+-- either SECURITY DEFINER (get_next_sequence, set_shelf_life_for_operation) or
+-- runs service-role (edge functions), so the timezone rows are always readable.
+-- Under an RLS denial these would silently fall back to UTC — keep new callers
+-- privileged. Do NOT flip these to SECURITY DEFINER: public definer functions
+-- are auto-exposed as PostgREST RPCs, and that would hand any authenticated
+-- user a cross-tenant "what is company X's local date" probe.
CREATE OR REPLACE FUNCTION public.location_today(
p_location_id TEXT,
p_company_id TEXT
diff --git a/packages/jobs/src/inngest/functions/extraction/extract-document.ts b/packages/jobs/src/inngest/functions/extraction/extract-document.ts
index c63534d407..0989b5a1bb 100644
--- a/packages/jobs/src/inngest/functions/extraction/extract-document.ts
+++ b/packages/jobs/src/inngest/functions/extraction/extract-document.ts
@@ -20,8 +20,10 @@ function parseDateToISO8601(value: unknown): string | null {
const parsed = Date.parse(cleaned);
if (isNaN(parsed)) return null;
+ // UTC parts: the date is document-intrinsic, and Date.parse of a bare date
+ // lands on UTC midnight — local getters would shift it a day under TZ ≠ UTC.
const d = new Date(parsed);
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}`;
}
export const extractDocumentFunction = inngest.createFunction(
diff --git a/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts b/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts
index 11fd17e53f..ee1df16185 100644
--- a/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts
@@ -47,11 +47,12 @@ async function archiveCompanyLogs(
const jsonl = records.map((r) => JSON.stringify(r)).join("\n");
const gzipped = gzipSync(Buffer.from(jsonl));
- // Generate archive path
+ // Generate archive path — a storage key, so the UTC calendar is fine; UTC
+ // parts keep the path deterministic under any process timezone.
const nowDate = new Date();
- const year = nowDate.getFullYear();
- const month = String(nowDate.getMonth() + 1).padStart(2, "0");
- const day = String(nowDate.getDate()).padStart(2, "0");
+ const year = nowDate.getUTCFullYear();
+ const month = String(nowDate.getUTCMonth() + 1).padStart(2, "0");
+ const day = String(nowDate.getUTCDate()).padStart(2, "0");
const timestamp = `${year}-${month}-${day}`;
const archivePath = `audit-logs/${companyId}/${year}/${month}/${timestamp}.jsonl.gz`;