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
feat(settings): derive business dates in company and location timezones (#1339)
Sid2476fb317b6a
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 5b41cb1720..5cf756a6e1 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. And when masking by line shape, the region CLOSER is as bug-prone as the opener: a `)` closer that also matches a multi-line signature's `) {` line ends the region before the body and un-masks client code (only statement-terminating `)`/`);` lines close a region), while an expression-bodied one-liner (`const X = () => null;`) must never OPEN a region at all — pin both shapes as regression tests.++**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.mdnew file mode 100644index 0000000000..b6a69ce69c--- /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)++Both consume `datetime.weekBounds(tz, offset?)` — the tested Monday→Sunday helper in `@carbon/utils` (Deno mirror in `functions/lib/datetime.ts`) — rather than hand-rolling `startOfWeek(...).toDate(tz)` per site. 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` — non-ISO text is parsed by `Date.parse` in the PROCESS zone, so local getters are the symmetric round-trip (ISO forms short-circuit earlier); UTC getters would shift the written date west of UTC.+- `packages/jobs/src/inngest/functions/scheduled/audit-archive.ts:52-54` — archive path (storage key) derives from `datetime.today("UTC")` — explicit UTC calendar via the sanctioned API.+- `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/.ai/playbooks/company-timezone-differential.md b/.ai/playbooks/company-timezone-differential.mdnew file mode 100644index 0000000000..ac29c1d760--- /dev/null+++ b/.ai/playbooks/company-timezone-differential.md@@ -0,0 +1,74 @@+# Company Timezone — differential date test++Last tested: 2026-08-05+Route: /x/settings/company (+ /x/purchase-order/new, inventory adjustment)++## Purpose+Prove business dates (orderDate, itemLedger postingDate) derive in the COMPANY+timezone, not UTC — by setting a timezone whose calendar day differs from UTC.++## Prerequisites+- Migrations through 20260805152353 applied (company.timezone, get_timezone_names, validity CHECKs)+- A supplier and a part exist (create inline/SQL if missing)+- Company address fields filled — the settings form validates city/postal/country,+ so an incomplete seed company blocks saving ANY settings change until filled++## Steps+### 1. Pick a differential zone+- If UTC time is 10:00 OR LATER, `Pacific/Kiritimati` (UTC+14) is already tomorrow.+- If UTC time is BEFORE 11:00, `Pacific/Niue` (UTC-11) is still yesterday.+- (So one of the two always differs; between 10:00-11:00 UTC both do.)+- Confirm in SQL: `SELECT now()::date, company_today('<companyId>');` — they must differ.++### 2. Set company timezone+- Settings → Company; timezone field is a searchable combobox (options come from+ the DB via api/timezones — labels look like "Pacific/Kiritimati (UTC+14:00)").+- Open the picker, type into the popover's "Search..." input, click the single match.+- requestSubmit the form whose button reads "Save" (NOT a click).+- Verify: `SELECT timezone FROM company WHERE id='<companyId>';`++### 3. Create a PO+- /x/purchase-order/new → select supplier (first combobox) → requestSubmit "Save".+- Verify: `SELECT "orderDate", "createdAt" FROM "purchaseOrder" WHERE "companyId"='<companyId>' ORDER BY "createdAt" DESC LIMIT 1;`+ → orderDate must be the COMPANY's day, createdAt shows the UTC instant.++### 4. Post an inventory adjustment (Deno edge-fn path)+- /x/inventory/quantities → click the item row → "Update Inventory" button →+ modal is prefilled (Set Quantity, HQ location) → requestSubmit "Save".+- Verify: `SELECT "postingDate", "createdAt" FROM "itemLedger" WHERE "companyId"='<companyId>' ORDER BY "createdAt" DESC LIMIT 1;`+ → postingDate = company day (proves functions/lib/datetime.ts + getCompanyTimeZoneDb).++### 5. Accounting period + journal (accounting enabled)+- Enable: `UPDATE "companySettings" SET "accountingEnabled"=true WHERE id='<companyId>';`+- The item's `itemCost.costingMethod` must be 'Average' with a non-zero `unitCost`+ for the adjustment to post a non-zero journal (FIFO/LIFO increases cost from+ empty layers = 0 = no journal). `UPDATE "itemCost" SET "costingMethod"='Average',"unitCost"=25 WHERE ...`.+- Post an Increase adjustment (as in step 4).+- Verify: `SELECT j."postingDate", ap."startDate", ap."endDate", ap."periodNumber", j.status FROM journal j JOIN "accountingPeriod" ap ON ap.id=j."accountingPeriodId" AND ap."companyId"=j."companyId" WHERE j."companyId"='<companyId>' ORDER BY j."createdAt" DESC LIMIT 1;`+ → journal.postingDate = company day; the period is lazily created for the+ company's month (proves getCurrentAccountingPeriod uses companyToday.year/month).+- **costLedger must match itemLedger**: `SELECT "postingDate" FROM "costLedger" WHERE "companyId"='<companyId>' ORDER BY "createdAt" DESC LIMIT 1;`+ must equal the itemLedger postingDate (both = company day). If costLedger shows+ the UTC day, a costLedger insert is missing `postingDate:` and fell back to+ `DEFAULT CURRENT_DATE` — regression guard.++### 6. Revert+- Set the company timezone back (UI or constraint-checked SQL UPDATE).+- `UPDATE "companySettings" SET "accountingEnabled"=false WHERE id='<companyId>';` if you enabled it.++## Selector Notes+- Timezone/search comboboxes are cmdk: popover search input has placeholder "Search...";+ set its value via the native-setter + input-event trick if fill misses.+- Company settings comboboxes (in order): country ("Select"/country name),+ Base Currency (disabled), Timezone.+- The AddressAutocomplete combobox on the company form is EXPANDED by default —+ stray typing lands in it (writes addressLine1). Check input[name=addressLine1] after.+- Adjustment modal: all fields prefilled via hidden inputs; just requestSubmit its Save.++## Common Failures+- Save "does nothing" on Settings → Company: the seed company has empty+ city/postalCode/countryCode → validation errors below the fields. Fill address first.+- `agent-browser type "text"` without a ref treats the text as a selector and+ times out — always pass the element ref, or use the native-setter eval.+- Constraint check: `UPDATE company SET timezone='Fake/Zone' WHERE id='<companyId>'`+ must FAIL (company_timezone_valid) — use this as a negative test.diff --git a/.claude/rules/date-handling.md b/.claude/rules/date-handling.mdindex e617aabe19..2a40c7a957 100644--- a/.claude/rules/date-handling.md+++ b/.claude/rules/date-handling.md@@ -34,8 +34,33 @@ must not do.| `d.setHours(0,0,0,0)` for start-of-day | `fromDate(d, tz).set({ hour: 0, minute: 0, second: 0, millisecond: 0 })` || `d1 <= d2` on `Date`s | `a.compare(b) <= 0` on `ZonedDateTime`/`CalendarDate` || `d.getDay()` | `getDayOfWeek(date, "en-US")` (0 = Sun … 6 = Sat) |-| `d.toISOString()` for a column write | `zdt.toAbsoluteString()` |-| `"now"` as `new Date()` in server code | `now(getLocalTimeZone())` → `ZonedDateTime` |+| `d.toISOString()` for a column write | `zdt.toAbsoluteString()`, or `datetime.timestamp()` for "now" |+| `"now"` / "today" in SERVER code | `datetime.*` (`@carbon/utils`) — see below; `getLocalTimeZone()` is BANNED server-side |++## Server code: the `datetime` API (mandatory)++`getLocalTimeZone()` on a server is the SERVER's zone, not the user's, and+`new Date().toISOString().split("T")[0]` is the UTC day — both are banned in+server paths (`*.service.ts`, `*.server.ts`, `packages/jobs`,+`supabase/functions`, and **route `loader`/`action` bodies** under+`apps/{erp,mes}/app/routes`) and enforced by the `no-local-timezone` conformance+check in `@carbon/checks`. Route modules are server AND client in one file, so+`sources/server-files.ts` masks out the default export, `clientLoader`/+`clientAction`, and PascalCase/`use*` declarations before scanning — module-level+helpers a loader calls ARE scanned. Instead:++- `datetime.timestamp()` — UTC instant string for `createdAt`/`updatedAt`/instant columns (the only tz-free method).+- `datetime.today(tz)` / `datetime.now(tz)` — calendar day / zoned now in an explicit IANA timezone.+- `datetime.businessDay(instantStr, tz)` — which day a stored instant falls on in tz.+- Resolve `tz` with `getCompanyTimeZone(client, companyId)` (ledger-scoped: posting dates, accounting periods, sequences, aging) or `getLocationTimeZone(client, locationId, companyId)` (operational: scheduling, shifts, MES, expiry) from `@carbon/database`. Deno edge functions use the mirror in `functions/lib/datetime.ts` (`getCompanyTimeZoneDb`/`getLocationTimeZoneDb` for Kysely).+- SQL functions use `company_today(p_company_id)` (migration `20260805023439`) or `location_today(p_location_id, p_company_id)` (migration `20260805201623`) instead of `CURRENT_DATE` for business dates. Read-only "is it overdue?" views still compare against `CURRENT_DATE` — they render a status rather than storing one.++Client components keep `today(getLocalTimeZone())` etc. for **display** — in the+browser the local timezone IS the user's and is correct for pickers and+formatting. But a form default that will be **persisted as a business date**+(`postingDate`, `orderDate`, `dateIssued`, `openDate`, …) must use+`useCompanyToday()` from `~/hooks`: the stored value belongs to the company's+calendar, not to whichever zone the person filling the form happens to be in.## Repo patterns to copy@@ -50,9 +75,40 @@ must not do.`@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/Dockerfile b/Dockerfileindex c8cc23ac4f..2d1791e96e 100644--- a/Dockerfile+++ b/Dockerfile@@ -24,6 +24,8 @@ ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0RUN corepack enableENV NODE_ENV=productionENV PORT=3000+# Date derivation assumes UTC until company/location timezones are threaded everywhere+ENV TZ=UTCCOPY --from=deps /repo/package.json /repo/pnpm-lock.yaml /repo/pnpm-workspace.yaml /repo/.npmrc ./COPY --from=deps /repo/node_modules ./node_modulesCOPY --from=deps /repo/packages ./packagesdiff --git a/apps/assembler/Dockerfile b/apps/assembler/Dockerfileindex 5f36a0089a..44982448a7 100644--- a/apps/assembler/Dockerfile+++ b/apps/assembler/Dockerfile@@ -134,6 +134,7 @@ COPY --from=build /usr/local/bin/assembler /usr/local/bin/assemblerCOPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.9.1 /lambda-adapter /opt/extensions/lambda-adapter# Both the app and the Lambda Web Adapter read PORT (LWA falls back to it).ENV PORT=8000+ENV TZ=UTC# Non-HTTP (Event) invokes — the self-dispatch worker path — are POSTed by the# adapter to this app route instead of being translated as HTTP requests.ENV AWS_LWA_PASS_THROUGH_PATH=/eventsdiff --git a/apps/assembler/sst.config.ts b/apps/assembler/sst.config.tsindex 59438c86df..115d5d8045 100644--- a/apps/assembler/sst.config.ts+++ b/apps/assembler/sst.config.ts@@ -43,6 +43,7 @@ export default $config({ASSEMBLER_SERVICE_API_KEY: process.env.ASSEMBLER_SERVICE_API_KEY,// Job/result store — REQUIRED; the assembler refuses to boot without it.REDIS_URL: process.env.REDIS_URL,+ TZ: "UTC",// Optimize time budget + dispatch mode are AUTO-DETECTED in-service from// AWS_LAMBDA_FUNCTION_NAME (720s ladder budget on Lambda; self-invoke// dispatch) — no env needed here.diff --git a/apps/erp/app/components/Form/Timezone.tsx b/apps/erp/app/components/Form/Timezone.tsxnew file mode 100644index 0000000000..84d5e21da5--- /dev/null+++ b/apps/erp/app/components/Form/Timezone.tsx@@ -0,0 +1,71 @@+import { Timezone as TimezoneBase } from "@carbon/form";+import { useMount } from "@carbon/react";+import type { TimezoneGroup } from "@carbon/utils";+import type { ComponentProps } from "react";+import { useMemo } from "react";+import { useFetcher } from "react-router";+import type { getTimezoneNames } from "~/modules/shared/shared.service";+import { path } from "~/utils/path";++/**+ * Timezone picker fed by the DATABASE's tzdata (pg_timezone_names via+ * api/timezones) — the authoritative list for what AT TIME ZONE resolves.+ * While loading (or if the fetch fails) the base component falls back to the+ * runtime's Intl list.+ */+const Timezone = (props: ComponentProps<typeof TimezoneBase>) => {+ const fetcher = useFetcher<Awaited<ReturnType<typeof getTimezoneNames>>>();++ useMount(() => {+ fetcher.load(path.to.api.timezones);+ });++ const options = useMemo<TimezoneGroup[] | undefined>(() => {+ const zones = fetcher.data?.data;+ if (!zones?.length) return undefined;++ const groups = new Map<string, TimezoneGroup["options"]>();+ for (const { name, utcOffset } of zones) {+ const [region = "Other", ...rest] = name.split("/");+ const city = rest.join("/").replace(/_/g, " ");+ const group = rest.length === 0 ? "Other" : region;+ // pg interval text: "05:30:00" / "-06:00:00" / "00:00:00"+ const offset = utcOffset.startsWith("-")+ ? `UTC-${utcOffset.slice(1, 6)}`+ : `UTC+${utcOffset.slice(0, 5)}`;+ const label = `${city || name} (${offset})`;+ const list = groups.get(group) ?? [];+ list.push({ label, value: name });+ groups.set(group, list);+ }++ const regionOrder = [+ "America",+ "Europe",+ "Asia",+ "Africa",+ "Australia",+ "Pacific",+ "Atlantic",+ "Indian",+ "Antarctica",+ "Arctic",+ "Other"+ ];++ return [...groups.entries()]+ .sort(+ ([a], [b]) =>+ (regionOrder.indexOf(a) + 1 || 99) -+ (regionOrder.indexOf(b) + 1 || 99)+ )+ .map(([label, list]) => ({+ label,+ options: list.sort((a, b) => a.label.localeCompare(b.label))+ }));+ }, [fetcher.data]);++ return <TimezoneBase {...props} options={options} />;+};++export default Timezone;diff --git a/apps/erp/app/components/Form/index.ts b/apps/erp/app/components/Form/index.tsindex cc18726ade..46ad72eb8e 100644--- a/apps/erp/app/components/Form/index.ts+++ b/apps/erp/app/components/Form/index.ts@@ -22,8 +22,7 @@ import {SelectControlled,Submit,TextArea,- TimePicker,- Timezone+ TimePicker} from "@carbon/form";import Abilities from "./Abilities";@@ -83,6 +82,7 @@ import SupplierStatus from "./SupplierStatus";import Suppliers from "./Suppliers";import SupplierType from "./SupplierType";import Tags from "./Tags";+import Timezone from "./Timezone";import Tool from "./Tool";import UnitHint from "./UnitHint";import UnitOfMeasure from "./UnitOfMeasure";diff --git a/apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsx b/apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsxindex 6ab25dbaf6..6d351b0a01 100644--- a/apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsx+++ b/apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsx@@ -24,6 +24,7 @@ import {useMode,VStack} from "@carbon/react";+import { getLocalTimeZone } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import type { ReactNode } from "react";import { useMemo } from "react";@@ -41,7 +42,8 @@ import {AddressAutocomplete,Currency,Input,- Submit+ Submit,+ Timezone} from "~/components/Form";import { useRouteData, useUser } from "~/hooks";import type { Company } from "~/modules/settings";@@ -280,7 +282,8 @@ function CompanyBreadcrumb() {onSubmit={companyForm.onClose}defaultValues={{countryCode: "US",- baseCurrencyCode: "USD"+ baseCurrencyCode: "USD",+ timezone: getLocalTimeZone()}}><ModalHeader>@@ -292,6 +295,7 @@ function CompanyBreadcrumb() {<VStack spacing={4}><Input autoFocus name="name" label={t`Company Name`} /><AddressAutocomplete variant="grid" />+ <Timezone name="timezone" label={t`Timezone`} /><Currencyname="baseCurrencyCode"label={t`Base Currency`}diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.tsindex a2b5461766..f8badf6c88 100644--- a/apps/erp/app/hooks/index.ts+++ b/apps/erp/app/hooks/index.ts@@ -6,6 +6,7 @@ import {useUrlParams} from "@carbon/react";import { useCompanySettings } from "./useCompanySettings";+import { useCompanyTimeZone, useCompanyToday } from "./useCompanyTimeZone";import { useCurrencyFormatter } from "./useCurrencyFormatter";import { useDateFormatter } from "./useDateFormatter";import { useFlags } from "./useFlags";@@ -31,6 +32,8 @@ import { useUser } from "./useUser";export {useCompanySettings,+ useCompanyTimeZone,+ useCompanyToday,useCurrencyFormatter,useDateFormatter,useFlags,diff --git a/apps/erp/app/hooks/useCompanyTimeZone.tsx b/apps/erp/app/hooks/useCompanyTimeZone.tsxnew file mode 100644index 0000000000..d3713b2fed--- /dev/null+++ b/apps/erp/app/hooks/useCompanyTimeZone.tsx@@ -0,0 +1,24 @@+import { useRouteData } from "@carbon/react";+import { datetime } from "@carbon/utils";+import type { Company } from "~/modules/settings";+import { path } from "~/utils/path";++/**+ * The company's IANA timezone — the ledger calendar. Use it to seed any date a+ * form will persist as a business date (postingDate, orderDate, dateIssued, …)+ * so the stored value matches the books, not whichever zone the browser is in.+ * Falls back to UTC before the layout route data is available.+ */+export function useCompanyTimeZone(): string {+ const data = useRouteData<{ company: Company }>(path.to.authenticatedRoot);+ return data?.company?.timezone ?? "UTC";+}++/**+ * 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 datetime.today(useCompanyTimeZone()).toString();+}diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex b91770536d..ec72b3898c 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -1,7 +1,9 @@import type { Database, Json } from "@carbon/database";+import { getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import type { PeriodPostingSource } from "@carbon/utils";import {+ datetime,fiscalYearAndPeriodFor,getDateNYearsAgo,MONTH_NUMBER,@@ -9,6 +11,7 @@ import {toDisplayDebit,toStoredAmount} from "@carbon/utils";+import { endOfMonth, parseDate, startOfMonth } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import { sql } from "kysely";import type { z } from "zod";@@ -345,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)@@ -656,18 +661,22 @@ export async function getOrCreateAccountingPeriod(return { data: existing.data.id, error: null };}- // Create a new period for the month of the given date- const d = new Date(date);- const year = d.getFullYear();- const month = d.getMonth(); // 0-indexed- const startDate = new Date(year, month, 1).toISOString().split("T")[0];- const endDate = new Date(year, month + 1, 0).toISOString().split("T")[0];+ // Create a new period for the month of the given date. Pure calendar math on+ // the date string — a JS Date round-trip shifts the month near midnight on+ // non-UTC processes.+ const d = parseDate(date.slice(0, 10));+ const startDate = startOfMonth(d).toString();+ const endDate = endOfMonth(d).toString();const settings = await getFiscalYearSettings(client, companyId);const startMonth = settings.data?.startMonth? (MONTH_NUMBER[settings.data.startMonth] ?? 1): 1;- const { fiscalYear, periodNumber } = fiscalYearAndPeriodFor(d, startMonth);+ const { fiscalYear, periodNumber } = fiscalYearAndPeriodFor(+ d.year,+ d.month,+ startMonth+ );await client.from("accountingPeriod")@@ -1256,7 +1265,9 @@ async function computePeriodReadiness(// document with no postingDate can only land in this period if the period is// still running (or in the future) when it posts — closing an already-ended// period is not blocked by new drafts, which would post into a later period.- const todayDate = new Date().toISOString().slice(0, 10);+ const todayDate = datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString();const unpostedDateFilter =endDate >= todayDate? `postingDate.is.null,and(postingDate.gte.${startDate},postingDate.lte.${endDate})`@@ -2971,7 +2982,9 @@ export async function createIntercompanyTransaction(userId: string;}) {- const today = new Date().toISOString().split("T")[0];+ const today = datetime+ .today(await getCompanyTimeZone(client, input.sourceCompanyId))+ .toString();const postingDate = input.postingDate || today;const nextSequence = await getNextSequence(@@ -3407,10 +3420,17 @@ export async function postJournalEntry(// 2b. Enforce the period lifecycle. A manual JE posts as an "accounting"// source, so a Locked period still accepts it (adjustments are allowed);// only a Closed period rejects. Stamp the resolved period on the entry.+ // The fallback date is persisted with the flip below so the posted journal+ // can never carry a period from one day and a postingDate from another.+ const postingDate =+ entry.data.postingDate ??+ datetime+ .today(await getCompanyTimeZone(client, entry.data.companyId))+ .toString();const period = await getOrCreateAccountingPeriod(client,entry.data.companyId,- entry.data.postingDate ?? new Date().toISOString().split("T")[0],+ postingDate,"accounting");if (period.error) {@@ -3425,6 +3445,7 @@ export async function postJournalEntry(postedAt: new Date().toISOString(),postedBy: userId,accountingPeriodId: period.data,+ postingDate,updatedBy: userId}).eq("id", id)@@ -3474,7 +3495,9 @@ export async function reverseJournalEntry(// 2b. The reversing entry is dated today and posts as an "accounting" source,// so it lands in the current period (never the original's, which may be// Closed). A Closed current period rejects; a Locked one still accepts.- const postingDate = new Date().toISOString().split("T")[0];+ const postingDate = datetime+ .today(await getCompanyTimeZone(client, data.companyId))+ .toString();const period = await getOrCreateAccountingPeriod(client,data.companyId,diff --git a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsxindex 1525e44205..d12dea3b83 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,32 @@ 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;++ // Keyed on sourceCompanyId (not just timezone) so switching between two+ // companies in the SAME zone still re-defaults a manually edited date.+ useEffect(() => {+ if (timezone) setPostingDate(today(timezone).toString());+ // biome-ignore lint/correctness/useExhaustiveDependencies: sourceCompanyId intentionally re-triggers the default+ }, [sourceCompanyId, timezone, setPostingDate]);++ return null;+}+function SourceCurrencySync({companies}: {diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 1f2859d224..38ae4ea9fa 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -2,7 +2,7 @@ import type { Database, Json } from "@carbon/database";import { fetchAllFromTable } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import type { TrackedEntityAttributes } from "@carbon/utils";-import { getLocalTimeZone, now, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";import type { z } from "zod";@@ -1443,7 +1443,7 @@ export async function updateTrackedEntityExpiry(reason: args.reason,source: args.source ?? null,userId: args.userId,- at: now(getLocalTimeZone()).toAbsoluteString()+ at: datetime.timestamp()}]};@@ -2125,7 +2125,7 @@ export async function upsertKanban(.from("kanban").update({...sanitize(kanban),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", kanban.id).select("id")@@ -2155,7 +2155,7 @@ export async function upsertReceipt(.from("receipt").update({...sanitize(receipt),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", receipt.id).select("id")@@ -2190,7 +2190,7 @@ export async function upsertStorageUnit(.from("storageUnit").update({...sanitize(storageUnit),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", storageUnit.id).select("id")@@ -2249,7 +2249,7 @@ export async function upsertShipment(.from("shipment").update({...sanitize(shipment),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", shipment.id).select("id")@@ -2367,7 +2367,7 @@ export async function upsertWarehouseTransfer(.from("warehouseTransfer").update({...sanitize(transfer),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", transfer.id).select("id")@@ -2613,7 +2613,7 @@ export async function upsertStorageType(.from("storageType").update({...sanitize(storageType),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", storageType.id).select("id")@@ -3364,7 +3364,7 @@ export async function generatePickingList(// UTC calendar date ((now() AT TIME ZONE 'UTC')::date) — so generation and// those RPCs never resolve a different effective successor at a timezone// boundary.- const asOfDate = today("UTC").toString();+ const asOfDate = datetime.today("UTC").toString();// Cache per-item on-hand-by-bin so a supersession redirect doesn't refetch.const onHandCache = new Map<string, Map<string, number>>();@@ -3924,7 +3924,7 @@ export async function updateWarehouseTransfer(...fields,customFields,updatedBy,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()})).eq("id", id)diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 55fd8160df..9556cb6e63 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -1,11 +1,8 @@import type { Database, Json } from "@carbon/database";+import { getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";-import {- endOfMonth,- getLocalTimeZone,- parseDate,- today-} from "@internationalized/date";+import { datetime } from "@carbon/utils";+import { endOfMonth, parseDate } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import {@@ -571,7 +568,11 @@ export async function insertPurchaseInvoice(exchangeRate,exchangeRateUpdatedAt,paymentTermId: input.paymentTermId ?? paymentTermId,- dateIssued: input.dateIssued ?? today(getLocalTimeZone()).toString(),+ dateIssued:+ input.dateIssued ??+ datetime+ .today(await getCompanyTimeZone(client, input.companyId))+ .toString(),dateDue: input.dateDue ?? null,locationId,customFields: input.customFields,@@ -635,7 +636,7 @@ export async function updatePurchaseInvoice(.from("purchaseInvoice").update({...sanitize(rest),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", id).select("id")@@ -668,7 +669,7 @@ export async function upsertPurchaseInvoice(.from("purchaseInvoice").update({...sanitize(purchaseInvoice),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", purchaseInvoice.id).select("id, invoiceId");@@ -945,7 +946,11 @@ export async function insertSalesInvoice(exchangeRate,exchangeRateUpdatedAt,paymentTermId: input.paymentTermId ?? paymentTermId,- dateIssued: input.dateIssued ?? today(getLocalTimeZone()).toString(),+ dateIssued:+ input.dateIssued ??+ datetime+ .today(await getCompanyTimeZone(client, input.companyId))+ .toString(),dateDue: input.dateDue ?? null,locationId,customFields: input.customFields,@@ -1009,7 +1014,7 @@ export async function updateSalesInvoice(.from("salesInvoice").update({...sanitize(rest),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", id).select("id")@@ -1042,7 +1047,7 @@ export async function upsertSalesInvoice(.from("salesInvoice").update({...sanitize(salesInvoice),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", salesInvoice.id).select("id, invoiceId");diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 1b6d6e5cce..4cc70d14b9 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -1,5 +1,5 @@import type { Database, Json } from "@carbon/database";-import { fetchAllFromTable } from "@carbon/database";+import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";import type {ExpressionBuilder,Kysely,@@ -7,7 +7,7 @@ import type {KyselyTx} from "@carbon/database/client";import { getLogger } from "@carbon/logger";-import { getLocalTimeZone, now, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";import type { z } from "zod";@@ -585,7 +585,8 @@ export async function getItemCostHistory(itemId: string,companyId: string) {- const dateOneYearAgo = today(getLocalTimeZone())+ const dateOneYearAgo = datetime+ .today(await getCompanyTimeZone(client, companyId)).subtract({ years: 1 }).toString();@@ -2263,7 +2264,7 @@ export async function updateItemCost(.update({...cost,costIsAdjusted: true,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("itemId", itemId).single();@@ -2309,7 +2310,7 @@ export async function updateRevision(.from("item").update({...revision,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", revision.id);}@@ -2329,7 +2330,7 @@ export async function upsertConfigurationParameter(sanitize({...data,updatedBy: userId,- updatedAt: now(getLocalTimeZone()).toAbsoluteString()+ updatedAt: datetime.timestamp()})).eq("id", configurationParameter.id);@@ -2494,7 +2495,7 @@ export async function upsertItemDefaultPickMethod(companyId: storageUnit.data.companyId,createdBy: args.userId,updatedBy: args.userId,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()},{ onConflict: "itemId,locationId" });@@ -2725,7 +2726,7 @@ export async function upsertPickMethodWithShelfLife(};}) {- const updatedAt = now(getLocalTimeZone()).toAbsoluteString();+ const updatedAt = datetime.timestamp();return db.transaction().execute(async (trx) => {await trx@@ -2861,7 +2862,7 @@ export async function cascadeItemTrackingType(const requiresSerialTracking = args.newType === ItemTrackingType.Serial;const requiresBatchTracking = args.newType === ItemTrackingType.Batch;- const updatedAt = now(getLocalTimeZone()).toAbsoluteString();+ const updatedAt = datetime.timestamp();return db.transaction().execute(async (trx) => {await trx@@ -3009,7 +3010,7 @@ export async function updateItemMethodAndSourcing() {if (args.itemIds.length === 0) return;- const updatedAt = now(getLocalTimeZone()).toAbsoluteString();+ const updatedAt = datetime.timestamp();return db.transaction().execute(async (trx) => {await trx@@ -3048,7 +3049,7 @@ async function cascadeSourcingAndMethodTypeToMethodMaterials(if (args.itemIds.length === 0) return;if (!args.newSourcingType && !args.newMethodType) return;- const updatedAt = now(getLocalTimeZone()).toAbsoluteString();+ const updatedAt = datetime.timestamp();// Restrict to method materials whose make method is still Draft.const onDraftMakeMethod = (@@ -3212,14 +3213,14 @@ export async function upsertConsumable(.from("item").update({...sanitize(itemUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", consumable.id),client.from("consumable").update({...sanitize(consumableUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", consumable.id)]);@@ -3512,14 +3513,14 @@ export async function upsertPart(.from("item").update({...sanitize(itemUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", part.id),client.from("part").update({...sanitize(partUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", part.id)]);@@ -4530,14 +4531,14 @@ export async function upsertMaterial(.from("item").update({...sanitize(itemUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", material.id),client.from("material").update({...sanitize(materialUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", material.id)]);@@ -4894,7 +4895,7 @@ export async function upsertService(.from("item").update({...sanitize(itemUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", service.id),// service.id is the item uuid; the service row is keyed by readableId@@ -4902,7 +4903,7 @@ export async function upsertService(.from("service").update({...sanitize(serviceUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", item.data.readableId ?? "").eq("companyId", item.data.companyId ?? "")@@ -5050,14 +5051,14 @@ export async function upsertTool(.from("item").update({...sanitize(itemUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", tool.id),client.from("tool").update({...sanitize(toolUpdate),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", tool.id)]);diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.tsindex f09e748b1f..97fd9a9147 100644--- a/apps/erp/app/modules/people/people.service.ts+++ b/apps/erp/app/modules/people/people.service.ts@@ -1,4 +1,7 @@import type { Database, Json } from "@carbon/database";+import { getCompanyTimeZone } from "@carbon/database";+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";@@ -769,11 +772,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,18 +844,17 @@ 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.+ const tz = await getCompanyTimeZone(client, companyId);+ 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/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 603d1d230d..c2c7ab6c41 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -1,9 +1,8 @@import type { Database, Json } from "@carbon/database";-import { fetchAllFromTable } from "@carbon/database";+import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { getLogger } from "@carbon/logger";-import { getPurchaseOrderStatus } from "@carbon/utils";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime, getPurchaseOrderStatus } from "@carbon/utils";import type {PostgrestResponse,PostgrestSingleResponse,@@ -51,11 +50,20 @@ export async function closePurchaseOrder(purchaseOrderId: string,userId: string) {+ const purchaseOrder = await client+ .from("purchaseOrder")+ .select("companyId")+ .eq("id", purchaseOrderId)+ .single();+ const companyTz = await getCompanyTimeZone(+ client,+ purchaseOrder.data?.companyId ?? ""+ );return client.from("purchaseOrder").update({closed: true,- closedAt: today(getLocalTimeZone()).toString(),+ closedAt: datetime.today(companyTz).toString(),closedBy: userId}).eq("id", purchaseOrderId)@@ -292,7 +300,7 @@ export async function finalizeSupplierQuote(.from("supplierQuote").update({status: "Active",- updatedAt: today(getLocalTimeZone()).toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId}).eq("id", supplierQuoteId);@@ -1094,13 +1102,17 @@ export async function finalizePurchaseOrder(const updateData: Database["public"]["Tables"]["purchaseOrder"]["Update"] = {status,- updatedAt: today(getLocalTimeZone()).toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId};// Only set orderDate if it's not already setif (!purchaseOrder.data?.orderDate) {- updateData.orderDate = today(getLocalTimeZone()).toString();+ const companyTz = await getCompanyTimeZone(+ client,+ purchaseOrder.data?.companyId ?? ""+ );+ updateData.orderDate = datetime.today(companyTz).toString();}return client@@ -1118,7 +1130,7 @@ export async function sendSupplierQuote(const quoteUpdate = await client.from("supplierQuote").update({- updatedAt: today(getLocalTimeZone()).toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId}).eq("id", supplierQuoteId);@@ -1473,7 +1485,11 @@ export async function insertPurchaseOrder(supplierLocationId: input.supplierLocationId,supplierInteractionId: supplierInteraction.data?.id,status: input.status ?? "Draft",- orderDate: input.orderDate ?? new Date().toISOString().split("T")[0],+ orderDate:+ input.orderDate ??+ datetime+ .today(await getCompanyTimeZone(client, input.companyId))+ .toString(),currencyCode: input.currencyCode,exchangeRate,exchangeRateUpdatedAt,@@ -1931,7 +1947,7 @@ export async function upsertSupplier(.from("supplier").update({...sanitize(supplier),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", supplier.id).select("id")@@ -2243,13 +2259,17 @@ export async function upsertSupplierQuote(// Only update the exchange rate if the currency code has changedconst existingQuote = await client.from("supplierQuote")- .select("currencyCode, status")+ .select("currencyCode, status, companyId").eq("id", supplierQuote.id).single();if (existingQuote.error) return existingQuote;- const { currencyCode, status: existingStatus } = existingQuote.data;+ const {+ currencyCode,+ status: existingStatus,+ companyId+ } = existingQuote.data;if (supplierQuote.currencyCode &&@@ -2267,16 +2287,17 @@ export async function upsertSupplierQuote(}const { companyGroupId: _companyGroupId2, ...supplierQuoteUpdateData } =supplierQuote;+ const companyTz = await getCompanyTimeZone(client, companyId);return client.from("supplierQuote").update({...sanitize(supplierQuoteUpdateData),status:supplierQuote.expirationDate &&- today(getLocalTimeZone()).toString() > supplierQuote.expirationDate+ datetime.today(companyTz).toString() > supplierQuote.expirationDate? "Expired": (supplierQuote.status ?? existingStatus ?? "Draft"),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", supplierQuote.id);}@@ -2511,7 +2532,11 @@ export async function insertPurchasingRFQ(.from("purchasingRfq").insert({rfqId,- rfqDate: input.rfqDate ?? today(getLocalTimeZone()).toString(),+ rfqDate:+ input.rfqDate ??+ datetime+ .today(await getCompanyTimeZone(client, input.companyId))+ .toString(),expirationDate: input.expirationDate,locationId: input.locationId,employeeId: input.employeeId,diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.tsindex 9cdfcdbdff..55fc345fd2 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -1,7 +1,8 @@import type { Database, Json } from "@carbon/database";-import { fetchAllFromTable } from "@carbon/database";+import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";+import { datetime } from "@carbon/utils";import { parseDate } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";@@ -1255,8 +1256,16 @@ export async function updateIssueTaskStatus(};if (status === "Completed") {+ const task = await client+ .from(table)+ .select("companyId")+ .eq("id", id)+ .maybeSingle();+ const timezone = task.data?.companyId+ ? await getCompanyTimeZone(client, task.data.companyId)+ : "UTC";// @ts-expect-error- updateData.completedDate = new Date().toISOString().split("T")[0];+ updateData.completedDate = datetime.today(timezone).toString();}return clientdiff --git a/apps/erp/app/modules/resources/resources.models.ts b/apps/erp/app/modules/resources/resources.models.tsindex fd886e2c18..b71af1bcbe 100644--- a/apps/erp/app/modules/resources/resources.models.ts+++ b/apps/erp/app/modules/resources/resources.models.ts@@ -1,3 +1,4 @@+import { isValidTimeZone } from "@carbon/utils";import { z } from "zod";import { zfd } from "zod-form-data";import { operationTypes, standardFactorType } from "../shared";@@ -78,7 +79,10 @@ export const locationValidator = zstateProvince: zfd.text(z.string().optional()),postalCode: z.string().min(1, { message: "Postal Code is required" }),countryCode: z.string().min(1, { message: "Country is required" }),- timezone: z.string().min(1, { message: "Timezone is required" }),+ timezone: z+ .string()+ .min(1, { message: "Timezone is required" })+ .refine(isValidTimeZone, { message: "Invalid timezone" }),latitude: zfd.numeric(z.number().optional()),longitude: zfd.numeric(z.number().optional())})diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 210ed3dc89..9e71f6a75d 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -1,9 +1,9 @@import type { Database, Json } from "@carbon/database";-import { fetchAllFromTable } from "@carbon/database";+import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { getLogger } from "@carbon/logger";import type { PickPartial } from "@carbon/utils";-import { getLocalTimeZone, now, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type {PostgrestError,PostgrestSingleResponse,@@ -153,11 +153,20 @@ export async function closeSalesOrder(salesOrderId: string,userId: string) {+ const salesOrder = await client+ .from("salesOrder")+ .select("companyId")+ .eq("id", salesOrderId)+ .single();+ const companyTz = await getCompanyTimeZone(+ client,+ salesOrder.data?.companyId ?? ""+ );return client.from("salesOrder").update({closed: true,- closedAt: today(getLocalTimeZone()).toString(),+ closedAt: datetime.today(companyTz).toString(),closedBy: userId}).eq("id", salesOrderId)@@ -1981,7 +1990,7 @@ export async function finalizeQuote(.from("quote").update({status: "Sent",- updatedAt: today(getLocalTimeZone()).toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId}).eq("id", quoteId);@@ -1994,7 +2003,7 @@ export async function finalizeQuote(.from("quoteLine").update({status: "Complete",- updatedAt: today(getLocalTimeZone()).toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId}).neq("status", "No Quote")@@ -2010,7 +2019,7 @@ export async function releaseSalesOrder(.from("salesOrder").update({status: "To Ship and Invoice",- updatedAt: today(getLocalTimeZone()).toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId}).eq("id", salesOrderId);@@ -2021,7 +2030,9 @@ export async function resolvePrice(companyId: string,input: PriceResolutionInput): Promise<PriceResolutionResult> {- const date = input.date ?? new Date().toISOString().split("T")[0]!;+ const date =+ input.date ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const trace: PriceTraceStep[] = [];let resolvedCustomerTypeId = input.customerTypeId ?? null;@@ -2252,7 +2263,9 @@ export async function resolvePriceList(quantity?: number;}): Promise<PriceListResult> {- const date = new Date().toISOString().split("T")[0]!;+ const date = datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString();const previewQuantity = Math.max(args.quantity ?? 1, 0);let scopeQuery = client@@ -2647,7 +2660,7 @@ export async function upsertCustomer(.from("customer").update({...sanitize(customer),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", customer.id).select("id")@@ -3237,7 +3250,7 @@ export async function updateSalesRFQStatus(...rest,...(noQuoteReasonId ? { noQuoteReasonId } : {}),...(status === "Ready for Quote"- ? { completedDate: now(getLocalTimeZone()).toAbsoluteString() }+ ? { completedDate: datetime.timestamp() }: {})};@@ -3287,9 +3300,7 @@ export async function updateQuoteStatus(const updateData = {status,...rest,- ...(status === "Sent"- ? { completedDate: now(getLocalTimeZone()).toAbsoluteString() }- : {})+ ...(status === "Sent" ? { completedDate: datetime.timestamp() } : {})};return client.from("quote").update(updateData).eq("id", update.id);}@@ -3604,7 +3615,7 @@ export async function updateQuote(...(exchangeRateUpdatedAt && { exchangeRateUpdatedAt }),...(notes !== undefined && { internalNotes: notes }),updatedBy,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", id).select("id")@@ -3779,7 +3790,7 @@ export async function upsertQuote(.from("quote").update({...sanitize(quoteUpdateData),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", quote.id);}@@ -4979,7 +4990,7 @@ export async function updateSalesOrderStatus(status,...rest,...(["To Ship", "To Ship and Invoice"].includes(status)- ? { completedDate: now(getLocalTimeZone()).toAbsoluteString() }+ ? { completedDate: datetime.timestamp() }: {})};@@ -5108,7 +5119,11 @@ export async function insertSalesOrder(salesPersonId: input.salesPersonId ?? null,opportunityId,status: input.status ?? "Draft",- orderDate: input.orderDate ?? new Date().toISOString().split("T")[0],+ orderDate:+ input.orderDate ??+ datetime+ .today(await getCompanyTimeZone(client, input.companyId))+ .toString(),currencyCode,exchangeRate,exchangeRateUpdatedAt,@@ -5689,7 +5704,11 @@ export async function insertSalesRFQ(customerId: input.customerId,customerContactId: input.customerContactId,customerReference: input.customerReference,- rfqDate: input.rfqDate ?? today(getLocalTimeZone()).toString(),+ rfqDate:+ input.rfqDate ??+ datetime+ .today(await getCompanyTimeZone(client, input.companyId))+ .toString(),expirationDate: input.expirationDate,locationId: input.locationId,salesPersonId: input.salesPersonId,@@ -5824,7 +5843,7 @@ export async function upsertSalesRFQ(.from("salesRfq").update({...sanitize(rfq),- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", rfq.id);}diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex 4f80681e55..0f96fc4157 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -6,7 +6,7 @@ import {sectionConfigSchema,themeSchema} from "@carbon/documents/template";-import { labelSizes } from "@carbon/utils";+import { isValidTimeZone, labelSizes } from "@carbon/utils";import { z } from "zod";import { zfd } from "zod-form-data";import { plmReleaseControl } from "~/modules/items/items.models";@@ -75,6 +75,10 @@ const companyAddress = {postalCode: z.string().min(1, { message: "Postal Code is required" }),countryCode: z.string().min(1, { message: "Country is required" }),baseCurrencyCode: zfd.text(z.string()),+ timezone: z+ .string()+ .min(1, { message: "Timezone is required" })+ .refine(isValidTimeZone, { message: "Invalid timezone" }),website: zfd.text(z.string().optional())};diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 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/Companies/SubsidiaryCompanyForm.tsx b/apps/erp/app/modules/settings/ui/Companies/SubsidiaryCompanyForm.tsxindex 7cd4330a1a..5c19d662e0 100644--- a/apps/erp/app/modules/settings/ui/Companies/SubsidiaryCompanyForm.tsx+++ b/apps/erp/app/modules/settings/ui/Companies/SubsidiaryCompanyForm.tsx@@ -1,7 +1,7 @@import { ValidatedForm } from "@carbon/form";import { VStack } from "@carbon/react";import type { z } from "zod";-import { Currency, Input, Select, Submit } from "~/components/Form";+import { Currency, Input, Select, Submit, Timezone } from "~/components/Form";import AddressAutocomplete from "~/components/Form/AddressAutocomplete";import { useRouteData } from "~/hooks";import { type Company, subsidiaryValidator } from "~/modules/settings";@@ -41,6 +41,7 @@ const SubsidiaryCompanyForm = ({/><Input name="name" label="Company Name" /><AddressAutocomplete variant="grid" />+ <Timezone name="timezone" label="Timezone" /><Currency name="baseCurrencyCode" label="Base Currency" /></div><Submit withBlocker={false}>Save</Submit>diff --git a/apps/erp/app/modules/settings/ui/Company/CompanyForm.tsx b/apps/erp/app/modules/settings/ui/Company/CompanyForm.tsxindex 312549328e..b896e78b0c 100644--- a/apps/erp/app/modules/settings/ui/Company/CompanyForm.tsx+++ b/apps/erp/app/modules/settings/ui/Company/CompanyForm.tsx@@ -3,7 +3,14 @@ import { VStack } from "@carbon/react";import { isEoriCountry, isRegistrationNumberCountry } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { z } from "zod";-import { Currency, Hidden, Input, PhoneInput, Submit } from "~/components/Form";+import {+ Currency,+ Hidden,+ Input,+ PhoneInput,+ Submit,+ Timezone+} from "~/components/Form";import AddressAutocomplete from "~/components/Form/AddressAutocomplete";import { companyValidator } from "~/modules/settings";import { path } from "~/utils/path";@@ -74,6 +81,7 @@ const CompanyForm = ({ company }: CompanyFormProps) => {label={t`Base Currency`}disabled={true}/>+ <Timezone name="timezone" label={t`Timezone`} /><PhoneInputname="phone"label={t`Phone Number`}diff --git a/apps/erp/app/modules/settings/ui/Sequences/SequenceForm.tsx b/apps/erp/app/modules/settings/ui/Sequences/SequenceForm.tsxindex 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.tsxindex 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/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.tsindex 5c828d8005..2c001bf6f4 100644--- a/apps/erp/app/modules/shared/shared.server.ts+++ b/apps/erp/app/modules/shared/shared.server.ts@@ -15,6 +15,7 @@ import {getSalesOrderLines} from "~/modules/sales";import { getCompany } from "~/modules/settings";+import { getTimezoneNames } from "~/modules/shared/shared.service";import { getUser } from "~/modules/users/users.server";import { getDatabaseClient } from "~/services/database.server";import { stripSpecialCharacters } from "~/utils/string";@@ -97,6 +98,44 @@ export async function getCustomFieldsSchemas(return result;}+const TIMEZONES_CACHE_KEY = "timezones:v1";+// tzdata only changes when the Postgres image is upgraded — a day-long TTL+// keeps the pg_timezone_names scan (~1ms but per-request) off the hot path+// while still picking up a DB upgrade within 24h.+const TIMEZONES_CACHE_TTL_SECONDS = 60 * 60 * 24;++/**+ * Redis-cached wrapper around the get_timezone_names RPC (pg_timezone_names).+ * The list is global (not company-scoped). Follows the getCustomFieldsSchemas+ * pattern: a miss, unreachable Redis (the @carbon/kv resilience wrapper fails+ * soft), or a corrupt entry all fall through to the database.+ */+export async function getCachedTimezoneNames(client: SupabaseClient<Database>) {+ const cached = await redis.get(TIMEZONES_CACHE_KEY);+ if (cached) {+ try {+ return {+ data: JSON.parse(cached) as { name: string; utcOffset: string }[],+ error: null+ };+ } catch {+ // Corrupt cache entry — fall through to the source of truth.+ }+ }++ const result = await getTimezoneNames(client);+ if (result.data?.length) {+ await redis.set(+ TIMEZONES_CACHE_KEY,+ JSON.stringify(result.data),+ "EX",+ TIMEZONES_CACHE_TTL_SECONDS+ );+ }++ return result;+}+/*** Generates a sales order PDF via the pdfLoader, uploads it to Supabase* storage under the opportunity path, and creates a document DB record.diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 3eaf96ed65..9f54409a74 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -712,6 +712,15 @@ export async function getCountries(client: SupabaseClient<Database>) {return client.from("country").select("*").order("name");}+/**+ * Timezone names from the database's own tzdata (pg_timezone_names via the+ * get_timezone_names RPC) — the authoritative list for what AT TIME ZONE+ * resolves.+ */+export async function getTimezoneNames(client: SupabaseClient<Database>) {+ return client.rpc("get_timezone_names");+}+export async function getLatestApprovalRequestForDocument(client: SupabaseClient<Database>,documentType: (typeof approvalDocumentType)[number],diff --git a/apps/erp/app/modules/shared/timezone.server.ts b/apps/erp/app/modules/shared/timezone.server.tsnew file mode 100644index 0000000000..57cc07cb56--- /dev/null+++ b/apps/erp/app/modules/shared/timezone.server.ts@@ -0,0 +1,73 @@+import type { AnyPostgresClient } from "@carbon/database";+import {+ getLocationOwnTimeZone,+ getCompanyTimeZone as resolveCompanyTimeZone+} from "@carbon/database";+import { redis } from "@carbon/kv";++// Timezones change only when someone edits Settings → Company or a location, so+// a long TTL is fine — writes invalidate the key explicitly (below). The+// @carbon/kv resilience wrapper fails soft: a Redis miss/outage/corrupt value+// just falls through to the database read.+const TTL_SECONDS = 60 * 60 * 24 * 7; // 7 days+const companyKey = (companyId: string) => `timezone:company:${companyId}`;+const locationKey = (companyId: string, locationId: string) =>+ `timezone:location:${companyId}:${locationId}`;++// Cached marker for "this location defines no timezone of its own". The+// location cache must never store an INHERITED company timezone: that copy+// would survive invalidateCompanyTimeZone for up to 7 days. Instead the+// inherit case is cached as this sentinel and the fallback flows through the+// (invalidatable) company cache on every read.+const INHERIT = "__inherit__";++/** Redis-cached {@link resolveCompanyTimeZone}. */+export async function getCompanyTimeZone(+ db: AnyPostgresClient,+ companyId: string+): Promise<string> {+ const key = companyKey(companyId);+ const cached = await redis.get(key);+ if (cached) return cached;++ const tz = await resolveCompanyTimeZone(db, companyId);+ await redis.set(key, tz, "EX", TTL_SECONDS);+ return tz;+}++/**+ * Redis-cached location timezone with company fallback. Only the location's+ * OWN timezone is cached under the location key (company-scoped); a location+ * that inherits resolves through {@link getCompanyTimeZone} on every call, so+ * a company-timezone change takes effect immediately after its invalidation.+ */+export async function getLocationTimeZone(+ db: AnyPostgresClient,+ locationId: string,+ companyId: string+): Promise<string> {+ const key = locationKey(companyId, locationId);+ const cached = await redis.get(key);+ if (cached !== null) {+ return cached === INHERIT ? getCompanyTimeZone(db, companyId) : cached;+ }++ const own = await getLocationOwnTimeZone(db, locationId, companyId);+ await redis.set(key, own ?? INHERIT, "EX", TTL_SECONDS);+ return own ?? getCompanyTimeZone(db, companyId);+}++/** Drop the cached company timezone — call after writing `company.timezone`. */+export async function invalidateCompanyTimeZone(+ companyId: string+): Promise<void> {+ await redis.del(companyKey(companyId));+}++/** Drop the cached location timezone — call after writing `location.timezone`. */+export async function invalidateLocationTimeZone(+ locationId: string,+ companyId: string+): Promise<void> {+ await redis.del(locationKey(companyId, locationId));+}diff --git a/apps/erp/app/modules/storage-rules/storage-rules.service.ts b/apps/erp/app/modules/storage-rules/storage-rules.service.tsindex f0909a0505..d94e7309c4 100644--- a/apps/erp/app/modules/storage-rules/storage-rules.service.ts+++ b/apps/erp/app/modules/storage-rules/storage-rules.service.ts@@ -9,7 +9,7 @@ import type {TargetType,TransactionSurface} from "@carbon/utils";-import { getLocalTimeZone, now } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";@@ -98,7 +98,7 @@ export async function upsertStorageRule(.update({...sanitize(rule),conditionAst: rule.conditionAst as unknown as Json,- updatedAt: now(getLocalTimeZone()).toAbsoluteString()+ updatedAt: datetime.timestamp()}).eq("id", rule.id).select("id")diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.tsindex 517a1fea4c..67d88dc0ca 100644--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts@@ -1,7 +1,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import {@@ -15,6 +15,7 @@ import {getOpenSalesOrderLines} from "~/modules/items/items.service";import { getOrCreatePeriods } from "~/modules/shared/shared.server";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";const defaultResponse = {demand: [],@@ -41,7 +42,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (!locationId) throw new Error("Could not find locationId");const periods = await getOrCreatePeriods(- today(getLocalTimeZone()),+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),WEEKS_TO_FORECAST);diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsxindex a6a8ed0e1d..cecccb1603 100644--- a/apps/erp/app/routes/api+/kanban.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.$id.tsx@@ -5,7 +5,7 @@ import type { Database } from "@carbon/database";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { Loading } from "@carbon/react";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { Suspense } from "react";import type { LoaderFunctionArgs } from "react-router";@@ -25,6 +25,10 @@ import {insertPurchaseOrder,upsertPurchaseOrderLine} from "~/modules/purchasing";+import {+ getCompanyTimeZone,+ getLocationTimeZone+} from "~/modules/shared/timezone.server";import { path } from "~/utils/path";const logger = getLogger("erp", "kanban");@@ -86,7 +90,12 @@ async function handleKanban({]);const leadTime = manufacturing.data?.leadTime ?? 7;- const startDate = today(getLocalTimeZone());+ // No location on the kanban → the company calendar.+ const startDate = datetime.today(+ kanban.data.locationId+ ? await getLocationTimeZone(client, kanban.data.locationId, companyId)+ : await getCompanyTimeZone(client, companyId)+ );const dueDate = startDate.add({ days: leadTime }).toString();// Use storage unit from kanban if it exists, otherwise use default storage unitdiff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.tsindex db47022fff..559141e502 100644--- a/apps/erp/app/routes/api+/mcp+/_index.ts+++ b/apps/erp/app/routes/api+/mcp+/_index.ts@@ -4,9 +4,11 @@ import {getUserScopedClient} from "@carbon/auth/client.server";import { getAppUrl } from "@carbon/env";+import { datetime } from "@carbon/utils";import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs } from "react-router";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { createMcpServer } from "./lib/server";const corsHeaders = {@@ -123,7 +125,14 @@ async function resolveAuth(request: Request): Promise<{export async function action({ request }: ActionFunctionArgs) {const { ctx, request: authedRequest } = await resolveAuth(request);- const server = createMcpServer(ctx);+ // The agent is told what "today" is; it has to be the company's day, not the+ // server's, or every relative-date tool call it makes lands a day off.+ const server = createMcpServer(+ ctx,+ datetime+ .today(await getCompanyTimeZone(ctx.client, ctx.companyId))+ .toString()+ );const transport = new WebStandardStreamableHTTPServerTransport({sessionIdGenerator: undefined,enableJsonResponse: truediff --git a/apps/erp/app/routes/api+/mcp+/lib/server.ts b/apps/erp/app/routes/api+/mcp+/lib/server.tsindex dc3dee3964..c1ecb71404 100644--- a/apps/erp/app/routes/api+/mcp+/lib/server.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/server.ts@@ -10,9 +10,8 @@ import { executeFunction } from "./direct-executor";const logger = getLogger("erp", "mcp");-function getServerInstructions(): string {- const today = new Date().toISOString().split("T")[0];-+function getServerInstructions(today: string): string {+return `Carbon ERP Manufacturing System==========================================Date: ${today}@@ -54,14 +53,14 @@ KEY PATTERNS:- Pagination: limit/offset`;}-export function createMcpServer(ctx: McpContext): McpServer {+export function createMcpServer(ctx: McpContext, today: string): McpServer {const server = new McpServer({name: "carbon-erp",version: process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 7) ?? "1.0.0",},{- instructions: getServerInstructions(),+ instructions: getServerInstructions(today),},);diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 42b542afb0..e2ba16f8e0 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-08-05T17:32:29.010Z",- "totalTools": 1413,+ "generated": "2026-08-05T21:50:58.234Z",+ "totalTools": 1414,"modules": 15,"tools": [{@@ -41983,6 +41983,23 @@"properties": {}}},+ {+ "name": "shared_getTimezoneNames",+ "module": "shared",+ "classification": "READ",+ "description": "get timezone names",+ "paramCount": 0,+ "serviceParams": [+ "client"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {}+ }+ },{"name": "shared_getLatestApprovalRequestForDocument","module": "shared",diff --git a/apps/erp/app/routes/api+/timezones.ts b/apps/erp/app/routes/api+/timezones.tsnew file mode 100644index 0000000000..5f0eed0281--- /dev/null+++ b/apps/erp/app/routes/api+/timezones.ts@@ -0,0 +1,28 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type {+ ClientLoaderFunctionArgs,+ LoaderFunctionArgs+} from "react-router";+import { getCachedTimezoneNames } from "~/modules/shared/shared.server";+import { timezonesQuery } from "~/utils/react-query";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {});+ return await getCachedTimezoneNames(client);+}++export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {+ const query = timezonesQuery();+ const data = window?.clientCache?.getQueryData<+ Awaited<ReturnType<typeof loader>>+ >(query.queryKey);++ if (!data) {+ const serverData = await serverLoader<typeof loader>();+ window?.clientCache?.setQueryData(query.queryKey, serverData);+ return serverData;+ }++ return data;+}+clientLoader.hydrate = true;diff --git a/apps/erp/app/routes/onboarding+/company.tsx b/apps/erp/app/routes/onboarding+/company.tsxindex a3a920309b..cf9ff54c19 100644--- a/apps/erp/app/routes/onboarding+/company.tsx+++ b/apps/erp/app/routes/onboarding+/company.tsx@@ -15,6 +15,7 @@ import {VStack} from "@carbon/react";import { isInternalEmail } from "@carbon/utils";+import { getLocalTimeZone } from "@internationalized/date";import {type ActionFunctionArgs,Link,@@ -26,7 +27,8 @@ import {Currency,Hidden,Input,- Submit+ Submit,+ Timezone} from "~/components/Form";import { useOnboarding } from "~/hooks";import { addressValidator, getCompany } from "~/modules/settings";@@ -121,6 +123,9 @@ export default function OnboardingCompany() {countryCode: company?.countryCode ?? draft?.company?.countryCode ?? "US",baseCurrencyCode:company?.baseCurrencyCode ?? draft?.company?.baseCurrencyCode ?? "USD",+ // Browser timezone is the best guess for the HQ at onboarding time+ timezone:+ company?.timezone ?? draft?.company?.timezone ?? getLocalTimeZone(),website: company?.website ?? draft?.company?.website ?? ""};@@ -139,6 +144,7 @@ export default function OnboardingCompany() {<VStack spacing={4}><Input autoFocus name="name" label="Company Name" /><AddressAutocomplete />+ <Timezone name="timezone" label="Timezone" /><Input name="website" label="Website" /><Currency name="baseCurrencyCode" label="Base Currency" /></VStack>diff --git a/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx b/apps/erp/app/routes/x+/accounting+/balance-sheet.tsxindex 95cb29d315..7c7ea63104 100644--- a/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx+++ b/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx@@ -2,6 +2,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";+import { datetime } from "@carbon/utils";import { msg } from "@lingui/core/macro";import { useState } from "react";import type { LoaderFunctionArgs } from "react-router";@@ -19,6 +20,7 @@ import {ReportFilters} from "~/modules/accounting/ui/Reports";import { months } from "~/modules/shared";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { revalidateIgnoringOffset } from "~/utils/revalidate";@@ -64,7 +66,9 @@ export async function loader({ request }: LoaderFunctionArgs) {const isMultiCompany = selectedCompanyIds.length > 1;if (isMultiCompany && parentCurrency) {- const periodEnd = endDate ?? new Date().toISOString().split("T")[0];+ const periodEnd =+ endDate ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const consolidated = await getConsolidatedBalances(client,companyGroupId,@@ -131,7 +135,9 @@ export async function loader({ request }: LoaderFunctionArgs) {let cta = 0;if (showTranslated && isForeignCurrency && parentCurrency) {- const periodEnd = endDate ?? new Date().toISOString().split("T")[0];+ const periodEnd =+ endDate ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const translation = await translateCompanyBalances(client,companyGroupId,diff --git a/apps/erp/app/routes/x+/accounting+/income-statement.tsx b/apps/erp/app/routes/x+/accounting+/income-statement.tsxindex f2724621e6..6714c5946f 100644--- a/apps/erp/app/routes/x+/accounting+/income-statement.tsx+++ b/apps/erp/app/routes/x+/accounting+/income-statement.tsx@@ -2,6 +2,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";+import { datetime } from "@carbon/utils";import { msg } from "@lingui/core/macro";import { useState } from "react";import type { LoaderFunctionArgs } from "react-router";@@ -19,6 +20,7 @@ import {ReportFilters} from "~/modules/accounting/ui/Reports";import { months } from "~/modules/shared";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { revalidateIgnoringOffset } from "~/utils/revalidate";@@ -65,7 +67,9 @@ export async function loader({ request }: LoaderFunctionArgs) {const isMultiCompany = selectedCompanyIds.length > 1;if (isMultiCompany && parentCurrency) {- const periodEnd = endDate ?? new Date().toISOString().split("T")[0];+ const periodEnd =+ endDate ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const consolidated = await getConsolidatedBalances(client,companyGroupId,@@ -124,7 +128,9 @@ export async function loader({ request }: LoaderFunctionArgs) {) as (Chart & { translatedBalance?: number; exchangeRate?: number })[];if (showTranslated && isForeignCurrency && parentCurrency) {- const periodEnd = endDate ?? new Date().toISOString().split("T")[0];+ const periodEnd =+ endDate ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const translation = await translateCompanyBalances(client,companyGroupId,diff --git a/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx b/apps/erp/app/routes/x+/accounting+/intercompany.new.tsxindex 07b0ab0b40..7184c45c3d 100644--- a/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx+++ b/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx@@ -4,6 +4,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, redirect, useLoaderData, useNavigate } from "react-router";+import { useCompanyToday } from "~/hooks";import {createIntercompanyTransaction,getCompaniesInGroup,@@ -65,6 +66,7 @@ export default function NewIntercompanyTransactionRoute() {const { companies } = useLoaderData<typeof loader>();const navigate = useNavigate();+ const companyToday = useCompanyToday();const initialValues = {sourceCompanyId: "",targetCompanyId: "",@@ -73,7 +75,7 @@ export default function NewIntercompanyTransactionRoute() {description: "",debitAccountId: "",creditAccountId: "",- postingDate: new Date().toISOString().split("T")[0]+ postingDate: companyToday};return (diff --git a/apps/erp/app/routes/x+/accounting+/periods.generate.tsx b/apps/erp/app/routes/x+/accounting+/periods.generate.tsxindex 2439338b25..edd2d15ace 100644--- a/apps/erp/app/routes/x+/accounting+/periods.generate.tsx+++ b/apps/erp/app/routes/x+/accounting+/periods.generate.tsx@@ -15,6 +15,7 @@ import {VStack} from "@carbon/react";import {+ datetime,fiscalYearAndPeriodFor,formatDate,MONTH_NUMBER@@ -35,6 +36,7 @@ import {generateFiscalYearPeriodsValidator,getFiscalYearSettings} from "~/modules/accounting";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -53,8 +55,12 @@ export async function loader({ request }: LoaderFunctionArgs) {const startMonth = settings.data?.startMonth? (MONTH_NUMBER[settings.data.startMonth] ?? 1): 1;+ const companyToday = datetime.today(+ await getCompanyTimeZone(client, companyId)+ );const defaultFiscalYear = fiscalYearAndPeriodFor(- new Date(),+ companyToday.year,+ companyToday.month,startMonth).fiscalYear;diff --git a/apps/erp/app/routes/x+/accounting+/trial-balance.tsx b/apps/erp/app/routes/x+/accounting+/trial-balance.tsxindex 0bbd715b9d..1c18d7c787 100644--- a/apps/erp/app/routes/x+/accounting+/trial-balance.tsx+++ b/apps/erp/app/routes/x+/accounting+/trial-balance.tsx@@ -2,6 +2,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";+import { datetime } from "@carbon/utils";import { msg } from "@lingui/core/macro";import { useState } from "react";import type { LoaderFunctionArgs } from "react-router";@@ -19,6 +20,7 @@ import {TrialBalanceTree} from "~/modules/accounting/ui/Reports";import { months } from "~/modules/shared";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { revalidateIgnoringOffset } from "~/utils/revalidate";@@ -65,7 +67,9 @@ export async function loader({ request }: LoaderFunctionArgs) {const isMultiCompany = selectedCompanyIds.length > 1;if (isMultiCompany && parentCurrency) {- const periodEnd = endDate ?? new Date().toISOString().split("T")[0];+ const periodEnd =+ endDate ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const consolidated = await getConsolidatedBalances(client,companyGroupId,@@ -121,7 +125,9 @@ export async function loader({ request }: LoaderFunctionArgs) {})[];if (showTranslated && isForeignCurrency && parentCurrency) {- const periodEnd = endDate ?? new Date().toISOString().split("T")[0];+ const periodEnd =+ endDate ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const translation = await translateCompanyBalances(client,companyGroupId,diff --git a/apps/erp/app/routes/x+/change-notice+/new.tsx b/apps/erp/app/routes/x+/change-notice+/new.tsxindex 0e50c49fe6..60e0c859fb 100644--- a/apps/erp/app/routes/x+/change-notice+/new.tsx+++ b/apps/erp/app/routes/x+/change-notice+/new.tsx@@ -3,11 +3,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { Json } from "@carbon/database";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";-import { useUser } from "~/hooks";+import { useCompanyToday, useUser } from "~/hooks";import {addChangeNoticeAffectedItem,changeNoticeValidator,@@ -15,6 +15,7 @@ import {insertChangeNotice} from "~/modules/items";import { ChangeNoticeForm } from "~/modules/items/ui/ChangeNotice";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { setCustomFields } from "~/utils/form";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -84,7 +85,9 @@ export async function action({ request }: ActionFunctionArgs) {priority: d.priority,changeNoticeTypeId: d.changeOrderTypeId || undefined,nonConformanceId: d.nonConformanceId || undefined,- openDate: d.openDate || today(getLocalTimeZone()).toString(),+ openDate:+ d.openDate ||+ datetime.today(await getCompanyTimeZone(client, companyId)).toString(),dueDate: d.dueDate || undefined,assignee: d.assignee || undefined,companyId,@@ -158,6 +161,7 @@ export default function ChangeNoticeNewRoute() {const { types, nonConformanceId, name } = useLoaderData<typeof loader>();const user = useUser();+ const companyToday = useCompanyToday();const initialValues = {id: undefined,changeOrderId: undefined,@@ -167,7 +171,7 @@ export default function ChangeNoticeNewRoute() {changeOrderTypeId: "",assignee: user.id,priority: "Medium" as const,- openDate: today(getLocalTimeZone()).toString(),+ openDate: companyToday,dueDate: "",nonConformanceId,affectedItemIds: []diff --git a/apps/erp/app/routes/x+/credits+/new.tsx b/apps/erp/app/routes/x+/credits+/new.tsxindex f70e71afd8..9c718644ff 100644--- a/apps/erp/app/routes/x+/credits+/new.tsx+++ b/apps/erp/app/routes/x+/credits+/new.tsx@@ -2,10 +2,12 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";import { MemoForm, memoValidator, upsertMemo } from "~/modules/invoicing";import { getCompany, getNextSequence } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";@@ -23,7 +25,9 @@ export async function loader({ request }: LoaderFunctionArgs) {direction: "Credit" as const,customerId: "",supplierId: "",- memoDate: new Date().toISOString().slice(0, 10),+ memoDate: datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString(),currencyCode,exchangeRate: 1,amount: 0,diff --git a/apps/erp/app/routes/x+/inspection+/$id.reject.tsx b/apps/erp/app/routes/x+/inspection+/$id.reject.tsxindex f3e06e76fb..8c842b7a25 100644--- a/apps/erp/app/routes/x+/inspection+/$id.reject.tsx+++ b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx@@ -4,7 +4,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { notifyIssueCreated } from "@carbon/ee/notifications";import { getLogger } from "@carbon/logger";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import { FunctionRegion } from "@supabase/supabase-js";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -19,6 +19,7 @@ import {} from "~/modules/quality";import { dispositionInspection } from "~/modules/quality/quality.server";import { getCompanyIntegrations } from "~/modules/settings/settings.server";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";import { getUserDefaults } from "~/modules/users/users.server";import { path } from "~/utils/path";@@ -217,7 +218,9 @@ export async function action({ request, params }: ActionFunctionArgs) {source: "Internal",locationId,nonConformanceTypeId: issueType.id,- openDate: today(getLocalTimeZone()).toString(),+ openDate: datetime+ .today(await getLocationTimeZone(client, locationId, companyId))+ .toString(),quantity: Number(insp.lotSize ?? 0),items: insp.itemId ? [insp.itemId] : [],companyId,diff --git a/apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx b/apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsxindex ac3ee1073c..c90b1699ff 100644--- a/apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx+++ b/apps/erp/app/routes/x+/inventory+/valuation.reconcile.tsx@@ -1,9 +1,11 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data, redirect } from "react-router";import { createInventoryReconciliationJournal } from "~/modules/inventory";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";@@ -19,7 +21,7 @@ export async function action({ request }: ActionFunctionArgs) {const formData = await request.formData();const asOfDate =(formData.get("asOfDate") as string | null) ||- new Date().toISOString().slice(0, 10);+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const result = await createInventoryReconciliationJournal(client,diff --git a/apps/erp/app/routes/x+/inventory+/valuation.tsx b/apps/erp/app/routes/x+/inventory+/valuation.tsxindex 325524bbb4..f3cc331672 100644--- a/apps/erp/app/routes/x+/inventory+/valuation.tsx+++ b/apps/erp/app/routes/x+/inventory+/valuation.tsx@@ -1,4 +1,5 @@import { requirePermissions } from "@carbon/auth/auth.server";+import { datetime } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";@@ -8,6 +9,7 @@ import {InventoryValuationWorkbench} from "~/modules/inventory";import { getCompanySettings } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -24,7 +26,8 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const asOfDate =- url.searchParams.get("asOfDate") ?? new Date().toISOString().slice(0, 10);+ url.searchParams.get("asOfDate") ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const groupBy: "location" | "item" =url.searchParams.get("groupBy") === "item" ? "item" : "location";const locationId = url.searchParams.get("locationId") || null;diff --git a/apps/erp/app/routes/x+/invoicing+/_index.tsx b/apps/erp/app/routes/x+/invoicing+/_index.tsxindex f9bc9fdb8b..f62202a4a9 100644--- a/apps/erp/app/routes/x+/invoicing+/_index.tsx+++ b/apps/erp/app/routes/x+/invoicing+/_index.tsx@@ -1,4 +1,5 @@import { requirePermissions } from "@carbon/auth/auth.server";+import { datetime } from "@carbon/utils";import type { LoaderFunctionArgs, MetaFunction } from "react-router";import { useLoaderData } from "react-router";import type { AgingTotals, RecentPayment } from "~/modules/invoicing";@@ -11,6 +12,7 @@ import {InvoicingDashboard} from "~/modules/invoicing";import { getCompanySettings } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { getGenericQueryFilters } from "~/utils/query";export const meta: MetaFunction = () => {@@ -61,7 +63,9 @@ export async function loader({ request }: LoaderFunctionArgs) {view: "invoicing"});- const asOfDate = new Date().toISOString().slice(0, 10);+ const asOfDate = datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString();const { sorts, filters } = getGenericQueryFilters(new URLSearchParams());// GL tie-outs only mean something when journals are being posted — skipdiff --git a/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsx b/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsxindex e39367adc2..31cb1a9418 100644--- a/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsx+++ b/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsx@@ -2,6 +2,7 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import { datetime } from "@carbon/utils";import { FunctionRegion } from "@supabase/supabase-js";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -11,6 +12,7 @@ import {} from "~/modules/accounting";import { getApTieOut } from "~/modules/invoicing";import { getCompanySettings } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { path } from "~/utils/path";// Turns a non-zero AP tie-out variance into a balanced Draft journal entry — the@@ -40,7 +42,7 @@ export async function action({ request }: ActionFunctionArgs) {const formData = await request.formData();const asOfDate =(formData.get("asOfDate") as string | null) ??- new Date().toISOString().slice(0, 10);+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const [tieOut, defaults] = await Promise.all([getApTieOut(client, companyId, asOfDate),diff --git a/apps/erp/app/routes/x+/invoicing+/payables.tsx b/apps/erp/app/routes/x+/invoicing+/payables.tsxindex 12f461fa7e..a978dc6061 100644--- a/apps/erp/app/routes/x+/invoicing+/payables.tsx+++ b/apps/erp/app/routes/x+/invoicing+/payables.tsx@@ -1,4 +1,5 @@import { requirePermissions } from "@carbon/auth/auth.server";+import { datetime } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {@@ -8,6 +9,7 @@ import {getApTieOut} from "~/modules/invoicing";import { getCompanySettings } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -32,7 +34,8 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const asOfDate =- url.searchParams.get("asOfDate") ?? new Date().toISOString().slice(0, 10);+ url.searchParams.get("asOfDate") ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const agingMethod: "dueDate" | "documentDate" =url.searchParams.get("agingMethod") === "documentDate"? "documentDate"diff --git a/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsx b/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsxindex 950c3856e2..91874305cd 100644--- a/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsx+++ b/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsx@@ -2,6 +2,7 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import { datetime } from "@carbon/utils";import { FunctionRegion } from "@supabase/supabase-js";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -11,6 +12,7 @@ import {} from "~/modules/accounting";import { getArTieOut } from "~/modules/invoicing";import { getCompanySettings } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { path } from "~/utils/path";// Turns a non-zero AR tie-out variance into a balanced Draft journal entry — the@@ -40,7 +42,7 @@ export async function action({ request }: ActionFunctionArgs) {const formData = await request.formData();const asOfDate =(formData.get("asOfDate") as string | null) ??- new Date().toISOString().slice(0, 10);+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const [tieOut, defaults] = await Promise.all([getArTieOut(client, companyId, asOfDate),diff --git a/apps/erp/app/routes/x+/invoicing+/receivables.tsx b/apps/erp/app/routes/x+/invoicing+/receivables.tsxindex ee3de012c7..a8642ab0e8 100644--- a/apps/erp/app/routes/x+/invoicing+/receivables.tsx+++ b/apps/erp/app/routes/x+/invoicing+/receivables.tsx@@ -1,4 +1,5 @@import { requirePermissions } from "@carbon/auth/auth.server";+import { datetime } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {@@ -8,6 +9,7 @@ import {getArTieOut} from "~/modules/invoicing";import { getCompanySettings } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -32,7 +34,8 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const asOfDate =- url.searchParams.get("asOfDate") ?? new Date().toISOString().slice(0, 10);+ url.searchParams.get("asOfDate") ??+ datetime.today(await getCompanyTimeZone(client, companyId)).toString();const agingMethod: "dueDate" | "documentDate" =url.searchParams.get("agingMethod") === "documentDate"? "documentDate"diff --git a/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx b/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsxindex d0e6fc7674..bc8ade0326 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx@@ -1,7 +1,7 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {@@ -11,6 +11,7 @@ import {getItem,insertChangeNotice} from "~/modules/items";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { path, requestReferrer } from "~/utils/path";// One-click "Create Change Notice" for a part/tool: mint a CO and attach the item@@ -54,7 +55,9 @@ export async function action({ request, params }: ActionFunctionArgs) {companyId,createdBy: userId,name: `Change for ${label}`,- openDate: today(getLocalTimeZone()).toString()+ openDate: datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString()});if (co.error || !co.data) {throw redirect(diff --git a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx b/apps/erp/app/routes/x+/job+/$jobId.materials.tsxindex 845704f3a5..7d30963da1 100644--- a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.materials.tsx@@ -2,7 +2,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { useMount, VStack } from "@carbon/react";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";import { usePanels } from "~/components/Layout";@@ -14,6 +14,7 @@ import {} from "~/modules/production";import { JobMaterialsTable } from "~/modules/production/ui/Jobs";import { getCompanySettings } from "~/modules/settings";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -76,7 +77,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// Both depend on the materials but not on each other.const [expiredItemIds, orderStatusByMaterialId] = await Promise.all([- getExpiredItemIds(client, companyId, rows, nearExpiryWarningDays),+ getExpiredItemIds(+ client,+ companyId,+ rows,+ nearExpiryWarningDays,+ locationId+ ),getJobOrderStatusMap(client,jobId,@@ -112,7 +119,8 @@ async function getExpiredItemIds(client: Parameters<typeof getJob>[0],companyId: string,materials: { jobMaterialItemId: string | null }[],- nearExpiryWarningDays: number | null+ nearExpiryWarningDays: number | null,+ locationId: string): Promise<Set<string>> {if (nearExpiryWarningDays === null) return new Set();const itemIds = materials@@ -126,7 +134,12 @@ async function getExpiredItemIds(.in("sourceDocumentId", itemIds).eq("companyId", companyId).not("expirationDate", "is", null)- .lt("expirationDate", today(getLocalTimeZone()).toString());+ .lt(+ "expirationDate",+ datetime+ .today(await getLocationTimeZone(client, locationId, companyId))+ .toString()+ );return new Set((data ?? [])diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsxindex 11088d28b8..a5a9b8e8f7 100644--- a/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx+++ b/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx@@ -1,10 +1,12 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { z } from "zod";import { applyCreditsToInvoices, getPayment } from "~/modules/invoicing";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";@@ -80,7 +82,9 @@ export async function action({ request, params }: ActionFunctionArgs) {paymentId,companyId,createdBy: userId,- appliedDate: new Date().toISOString().slice(0, 10),+ appliedDate: datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString(),side,applications: rows.data});diff --git a/apps/erp/app/routes/x+/payments+/new.tsx b/apps/erp/app/routes/x+/payments+/new.tsxindex e62432c4c6..715299a1c8 100644--- a/apps/erp/app/routes/x+/payments+/new.tsx+++ b/apps/erp/app/routes/x+/payments+/new.tsx@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";import { validationError, validator } from "@carbon/form";+import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";@@ -16,6 +17,7 @@ import {upsertPayment} from "~/modules/invoicing";import { getCompany, getNextSequence } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";@@ -93,7 +95,9 @@ export async function loader({ request }: LoaderFunctionArgs) {paymentType,customerId: customerId ?? "",supplierId: supplierId ?? "",- paymentDate: new Date().toISOString().slice(0, 10),+ paymentDate: datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString(),currencyCode,exchangeRate,totalAmount,diff --git a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx b/apps/erp/app/routes/x+/person+/$personId.timecard.tsxindex e5a39de58b..9dec73abff 100644--- a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx+++ b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx@@ -29,6 +29,8 @@ import {Thead,Tr} from "@carbon/react";+import { datetime } from "@carbon/utils";+import { parseDate } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import { useEffect, useState } from "react";@@ -65,27 +67,9 @@ 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);-- return {- from: monday.toISOString(),- to: sunday.toISOString(),- monday,- sunday- };-}-function formatDuration(clockIn: string, clockOut: string | null) {const end = clockOut ? new Date(clockOut).getTime() : Date.now();const ms = end - new Date(clockIn).getTime();@@ -145,7 +129,15 @@ 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);+ // Week runs Monday → Sunday on the company calendar (one payroll boundary+ // per books, not the server's zone).+ const tz = await getCompanyTimeZone(client, companyId);+ const { from, to } = datetime.weekBounds(tz, weekOffset);+ // Calendar days of the window on the COMPANY calendar — the client renders+ // these directly so the header and day picker never shift a day in a+ // different browser tz.+ const weekStart = datetime.businessDay(from, tz).toString();+ const weekEnd = datetime.businessDay(to, tz).toString();const [entries, openEntry, companySettings, employeeShift] =await Promise.all([@@ -187,8 +179,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {entries: entries.data ?? [],openEntry: openEntry.data,weekOffset,- from,- to,+ weekStart,+ weekEnd,shift};}@@ -360,7 +352,7 @@ export default function PersonTimecardRoute() {const { t } = useLingui();const { locale } = useLocale();const { formatDate } = useDateFormatter();- const { entries, openEntry, weekOffset, from, to, shift } =+ const { entries, openEntry, weekOffset, weekStart, weekEnd, shift } =useLoaderData<typeof loader>();const { personId } = useParams();const fetcher = useFetcher<typeof action>();@@ -384,8 +376,6 @@ export default function PersonTimecardRoute() {return () => clearInterval(interval);}, []);- const monday = new Date(from);- const sunday = new Date(to);const isCurrentWeek = weekOffset === 0;useEffect(() => {@@ -488,8 +478,8 @@ export default function PersonTimecardRoute() {</Link></Button><span className="text-sm text-muted-foreground">- {formatDate(monday.toISOString(), { dateStyle: "medium" })} —{" "}- {formatDate(sunday.toISOString(), { dateStyle: "medium" })}+ {formatDate(weekStart, { dateStyle: "medium" })} —{" "}+ {formatDate(weekEnd, { dateStyle: "medium" })}</span><Buttonvariant="outline"@@ -549,12 +539,12 @@ export default function PersonTimecardRoute() {</SelectTrigger><SelectContent>{Array.from({ length: 7 }, (_, i) => {- const d = new Date(monday);- d.setDate(monday.getDate() + i);- const val = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;+ const val = parseDate(weekStart)+ .add({ days: i })+ .toString();return (<SelectItem key={val} value={val}>- {d.toLocaleDateString(locale, {+ {formatDate(val, {weekday: "short",month: "short",day: "numeric"diff --git a/apps/erp/app/routes/x+/production+/planning.tsx b/apps/erp/app/routes/x+/production+/planning.tsxindex fb878a8a41..b20a4abff8 100644--- a/apps/erp/app/routes/x+/production+/planning.tsx+++ b/apps/erp/app/routes/x+/production+/planning.tsx@@ -2,7 +2,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { ResizablePanel, ResizablePanelGroup, VStack } from "@carbon/react";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { Outlet, redirect, useLoaderData } from "react-router";@@ -11,6 +11,7 @@ import { getProductionPlanning } from "~/modules/production";import ProductionPlanningTable from "~/modules/production/ui/Planning/ProductionPlanningTable";import { getLocationsList } from "~/modules/resources";import { getOrCreatePeriods } from "~/modules/shared/shared.server";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";import { getUserDefaults } from "~/modules/users/users.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -68,7 +69,7 @@ export async function loader({ request }: LoaderFunctionArgs) {}const periods = await getOrCreatePeriods(- today(getLocalTimeZone()),+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),WEEKS_TO_PLAN);diff --git a/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsxindex 81cb130c5f..a0e6018ef6 100644--- a/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx+++ b/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx@@ -2,7 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, redirect, useLoaderData, useNavigate } from "react-router";import { demandProjectionValidator } from "~/modules/production/production.models";@@ -12,6 +12,7 @@ import {} from "~/modules/production/production.service";import DemandProjectionsForm from "~/modules/production/ui/Projection/DemandProjectionForm";import { getOrCreatePeriods } from "~/modules/shared/shared.server";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";import { path } from "~/utils/path";const WEEKS_TO_PROJECT = 52;@@ -28,7 +29,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}const periods = await getOrCreatePeriods(- today(getLocalTimeZone()),+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),WEEKS_TO_PROJECT);diff --git a/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsxindex 2b23d3b582..55864407bc 100644--- a/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx+++ b/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx@@ -1,11 +1,12 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data, redirect } from "react-router";import { deleteDemandProjections } from "~/modules/production/production.service";import { getOrCreatePeriods } from "~/modules/shared/shared.server";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";import { path } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {@@ -27,7 +28,10 @@ export async function action({ request, params }: ActionFunctionArgs) {}// Get current date to determine future periods- const periods = await getOrCreatePeriods(today(getLocalTimeZone()), 52);+ const periods = await getOrCreatePeriods(+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),+ 52+ );// Only delete projections for future periods (current week and beyond)const futurePeriodIds = periods.map((p) => p.id);diff --git a/apps/erp/app/routes/x+/production+/projections.new.tsx b/apps/erp/app/routes/x+/production+/projections.new.tsxindex c5fe6276ea..c23060fbbf 100644--- a/apps/erp/app/routes/x+/production+/projections.new.tsx+++ b/apps/erp/app/routes/x+/production+/projections.new.tsx@@ -3,24 +3,27 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, redirect, useNavigate } from "react-router";import { demandProjectionValidator } from "~/modules/production/production.models";import { upsertDemandProjections } from "~/modules/production/production.service";import DemandProjectionForm from "~/modules/production/ui/Projection/DemandProjectionForm";import { getOrCreatePeriods } from "~/modules/shared/shared.server";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { path } from "~/utils/path";const WEEKS_TO_PROJECT = 52;export async function loader({ request }: LoaderFunctionArgs) {- await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {create: "production"});+ // No location yet — it is picked in the form — so the week grid anchors on+ // the company calendar.const periods = await getOrCreatePeriods(- today(getLocalTimeZone()),+ datetime.today(await getCompanyTimeZone(client, companyId)),WEEKS_TO_PROJECT);diff --git a/apps/erp/app/routes/x+/production+/projections.tsx b/apps/erp/app/routes/x+/production+/projections.tsxindex bdd903ab5b..4df9855f7a 100644--- a/apps/erp/app/routes/x+/production+/projections.tsx+++ b/apps/erp/app/routes/x+/production+/projections.tsx@@ -2,7 +2,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { Outlet, redirect, useLoaderData } from "react-router";@@ -10,6 +10,7 @@ import { getProductionProjections } from "~/modules/production";import DemandProjectionsTable from "~/modules/production/ui/Projection/DemandProjectionTable";import { getLocationsList } from "~/modules/resources";import { getOrCreatePeriods } from "~/modules/shared/shared.server";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";import { getUserDefaults } from "~/modules/users/users.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -67,7 +68,7 @@ export async function loader({ request }: LoaderFunctionArgs) {}const periods = await getOrCreatePeriods(- today(getLocalTimeZone()),+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),WEEKS_TO_PROJECT);diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsxindex 9cb6183a8d..c0c14e37da 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsx@@ -1,11 +1,13 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { updatePurchaseInvoiceStatus } from "~/modules/invoicing";import { purchaseInvoiceStatusType } from "~/modules/invoicing/invoicing.models";import { getCompanySettings } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {@@ -97,7 +99,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- datePaid = isMarkingPaid ? new Date().toISOString().slice(0, 10) : null;+ datePaid = isMarkingPaid+ ? datetime.today(await getCompanyTimeZone(client, companyId)).toString()+ : null;}const update = await updatePurchaseInvoiceStatus(client, {diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsxindex 8200ab7228..7a6f309da6 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx@@ -3,12 +3,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";import type { FunctionsResponse } from "@supabase/functions-js";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";-import { useUrlParams, useUser } from "~/hooks";+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";import { upsertDocument } from "~/modules/documents";import {createPurchaseInvoiceFromPurchaseOrder,@@ -222,12 +221,13 @@ export default function PurchaseInvoiceNewRoute() {const supplierId = params.get("supplierId");const { defaults } = useUser();+ const companyToday = useCompanyToday();const initialValues = {id: undefined,invoiceId: undefined,supplierId: supplierId ?? "",locationId: defaults?.locationId ?? "",- dateIssued: today(getLocalTimeZone()).toString()+ dateIssued: companyToday};return (diff --git a/apps/erp/app/routes/x+/purchase-order+/new.tsx b/apps/erp/app/routes/x+/purchase-order+/new.tsxindex 256c8fd54a..accfa8389e 100644--- a/apps/erp/app/routes/x+/purchase-order+/new.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/new.tsx@@ -2,12 +2,11 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { z } from "zod";-import { useUrlParams, useUser } from "~/hooks";+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";import type { PurchaseOrderStatus } from "~/modules/purchasing";import {insertPurchaseOrder,@@ -70,12 +69,13 @@ export default function PurchaseOrderNewRoute() {const [params] = useUrlParams();const supplierId = params.get("supplierId");const { defaults } = useUser();+ const companyToday = useCompanyToday();const initialValues = {id: undefined,purchaseOrderId: undefined,supplierId: supplierId ?? "",locationId: defaults?.locationId ?? "",- orderDate: today(getLocalTimeZone()).toString(),+ orderDate: companyToday,status: "Draft" as PurchaseOrderStatus,purchaseOrderType: "Purchase" as const};diff --git a/apps/erp/app/routes/x+/purchasing+/planning.tsx b/apps/erp/app/routes/x+/purchasing+/planning.tsxindex 5228078858..42a4430a8d 100644--- a/apps/erp/app/routes/x+/purchasing+/planning.tsx+++ b/apps/erp/app/routes/x+/purchasing+/planning.tsx@@ -2,7 +2,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { ResizablePanel, ResizablePanelGroup, VStack } from "@carbon/react";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { Outlet, redirect, useLoaderData } from "react-router";@@ -11,6 +11,7 @@ import { getPurchasingPlanning } from "~/modules/purchasing";import PurchasingPlanningTable from "~/modules/purchasing/ui/Planning/PurchasingPlanningTable";import { getLocationsList } from "~/modules/resources";import { getOrCreatePeriods } from "~/modules/shared/shared.server";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";import { getUserDefaults } from "~/modules/users/users.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -68,7 +69,7 @@ export async function loader({ request }: LoaderFunctionArgs) {}const periods = await getOrCreatePeriods(- today(getLocalTimeZone()),+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),WEEKS_TO_PLAN);diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/new.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/new.tsxindex aa92be6ddf..50db19a4e0 100644--- a/apps/erp/app/routes/x+/purchasing-rfq+/new.tsx+++ b/apps/erp/app/routes/x+/purchasing-rfq+/new.tsx@@ -2,11 +2,10 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { useUser } from "~/hooks";+import { useCompanyToday, useUser } from "~/hooks";import type { PurchasingRFQStatusType } from "~/modules/purchasing";import {insertPurchasingRFQ,@@ -80,11 +79,12 @@ export async function action({ request }: ActionFunctionArgs) {export default function PurchasingRFQNewRoute() {const { id: userId, defaults } = useUser();+ const companyToday = useCompanyToday();const initialValues = {expirationDate: "",id: undefined,locationId: defaults?.locationId ?? "",- rfqDate: today(getLocalTimeZone()).toString(),+ rfqDate: companyToday,rfqId: undefined,status: "Draft" as PurchasingRFQStatusType,employeeId: userId,diff --git a/apps/erp/app/routes/x+/quality+/gauges.$id.tsx b/apps/erp/app/routes/x+/quality+/gauges.$id.tsxindex ea2a74f0bd..4c7fe33cce 100644--- a/apps/erp/app/routes/x+/quality+/gauges.$id.tsx+++ b/apps/erp/app/routes/x+/quality+/gauges.$id.tsx@@ -3,7 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";+import { parseDate } from "@internationalized/date";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData, useNavigate, useParams } from "react-router";@@ -16,6 +17,7 @@ import {updateGauge} from "~/modules/quality";import GaugeForm from "~/modules/quality/ui/Gauge/GaugeForm";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { getCustomFields, setCustomFields } from "~/utils/form";import type { Handle } from "~/utils/handle";import { getParams, path } from "~/utils/path";@@ -55,7 +57,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "quality"});@@ -72,8 +74,11 @@ export async function action({ request, params }: ActionFunctionArgs) {const { gaugeId, ...d } = validation.data;if (!gaugeId) throw new Error("Could not find gaugeId");+ const companyToday = datetime.today(+ await getCompanyTimeZone(client, companyId)+ );const gaugeCalibrationStatus = d.nextCalibrationDate- ? parseDate(d.nextCalibrationDate) < today(getLocalTimeZone())+ ? parseDate(d.nextCalibrationDate).compare(companyToday) < 0? "Out-of-Calibration": d.lastCalibrationDate? "In-Calibration"diff --git a/apps/erp/app/routes/x+/quality+/gauges.new.tsx b/apps/erp/app/routes/x+/quality+/gauges.new.tsxindex b1d8507af8..0c84cd4720 100644--- a/apps/erp/app/routes/x+/quality+/gauges.new.tsx+++ b/apps/erp/app/routes/x+/quality+/gauges.new.tsx@@ -2,13 +2,15 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";+import { parseDate } from "@internationalized/date";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useNavigate } from "react-router";-import { useRouteData, useUser } from "~/hooks";+import { useCompanyToday, useRouteData, useUser } from "~/hooks";import type { GaugeType } from "~/modules/quality";import { gaugeValidator, insertGauge } from "~/modules/quality";import GaugeForm from "~/modules/quality/ui/Gauge/GaugeForm";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";@@ -35,8 +37,11 @@ export async function action({ request }: ActionFunctionArgs) {const { id: _id, ...d } = validation.data;+ const companyToday = datetime.today(+ await getCompanyTimeZone(client, companyId)+ );const gaugeCalibrationStatus = d.nextCalibrationDate- ? parseDate(d.nextCalibrationDate) < today(getLocalTimeZone())+ ? parseDate(d.nextCalibrationDate).compare(companyToday) < 0? "Out-of-Calibration": d.lastCalibrationDate? "In-Calibration"@@ -73,6 +78,7 @@ export default function GaugeNewRoute() {gaugeTypes: GaugeType[];}>(path.to.gauges);+ const companyToday = useCompanyToday();const initialValues = {id: undefined,gaugeId: undefined,@@ -80,7 +86,7 @@ export default function GaugeNewRoute() {modelNumber: "",serialNumber: "",description: "",- dateAcquired: today(getLocalTimeZone()).toString(),+ dateAcquired: companyToday,gaugeTypeId: "",gaugeCalibrationStatus: "Pending" as const,gaugeStatus: "Active" as const,diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsxindex 8e12e606fb..cd1a1280e7 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx@@ -4,7 +4,7 @@ import { flash } from "@carbon/auth/session.server";import { QuoteEmail } from "@carbon/documents/email";import { validationError, validator } from "@carbon/form";import { trigger } from "@carbon/jobs";-import { getLocalTimeZone, now } from "@internationalized/date";+import { datetime } from "@carbon/utils";import { renderAsync } from "@react-email/components";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -62,7 +62,7 @@ export async function action(args: ActionFunctionArgs) {.from("quote").update({externalLinkId: externalLink.data.id,- completedDate: now(getLocalTimeZone()).toAbsoluteString()+ completedDate: datetime.timestamp()}).eq("id", quoteId);}diff --git a/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsxindex ee9784924b..8bd8264f82 100644--- a/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx+++ b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx@@ -15,6 +15,7 @@ import {locationValidator,upsertLocation} from "~/modules/resources";+import { invalidateLocationTimeZone } from "~/modules/shared/timezone.server";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";import { getCompanyId, locationsQuery } from "~/utils/react-query";@@ -43,7 +44,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {create: "resources"});@@ -74,6 +75,9 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // location.timezone may have changed — drop the cached resolution.+ await invalidateLocationTimeZone(id, companyId);+throw redirect(path.to.locations,await flash(request, success("Location updated"))diff --git a/apps/erp/app/routes/x+/sales+/price-list.new.tsx b/apps/erp/app/routes/x+/sales+/price-list.new.tsxindex f0baec9bec..998af59f73 100644--- a/apps/erp/app/routes/x+/sales+/price-list.new.tsx+++ b/apps/erp/app/routes/x+/sales+/price-list.new.tsx@@ -2,7 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData, useNavigate } from "react-router";import {@@ -11,11 +11,14 @@ import {upsertCustomerItemPriceOverride} from "~/modules/sales";import PriceOverrideForm from "~/modules/sales/ui/Pricing/PriceOverrideForm";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { getDatabaseClient } from "~/services/database.server";import { getParams, path } from "~/utils/path";export async function loader({ request }: LoaderFunctionArgs) {- await requirePermissions(request, { create: "sales" });+ const { client, companyId } = await requirePermissions(request, {+ create: "sales"+ });const url = new URL(request.url);const customerId = url.searchParams.get("customerId") ?? undefined;@@ -32,7 +35,7 @@ export async function loader({ request }: LoaderFunctionArgs) {itemId: url.searchParams.get("itemId") ?? "",validFrom:url.searchParams.get("validFrom") ??- today(getLocalTimeZone()).toString()+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()},initialScope};diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsxindex a998f45e62..6e3c713c0b 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsx@@ -1,11 +1,13 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { updateSalesInvoiceStatus } from "~/modules/invoicing";import { salesInvoiceStatusType } from "~/modules/invoicing/invoicing.models";import { getCompanySettings } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {@@ -94,7 +96,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- datePaid = isMarkingPaid ? new Date().toISOString().slice(0, 10) : null;+ datePaid = isMarkingPaid+ ? datetime.today(await getCompanyTimeZone(client, companyId)).toString()+ : null;}const update = await updateSalesInvoiceStatus(client, {diff --git a/apps/erp/app/routes/x+/sales-invoice+/new.tsx b/apps/erp/app/routes/x+/sales-invoice+/new.tsxindex ec6bb0050d..aa7a13e936 100644--- a/apps/erp/app/routes/x+/sales-invoice+/new.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/new.tsx@@ -3,12 +3,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";import type { FunctionsResponse } from "@supabase/functions-js";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";-import { useUrlParams, useUser } from "~/hooks";+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";import {createSalesInvoiceFromSalesOrder,createSalesInvoiceFromShipment,@@ -143,12 +142,13 @@ export default function SalesInvoiceNewRoute() {const customerId = params.get("customerId");const { defaults } = useUser();+ const companyToday = useCompanyToday();const initialValues = {id: undefined,invoiceId: undefined,customerId: customerId ?? "",locationId: defaults?.locationId ?? "",- dateIssued: today(getLocalTimeZone()).toString()+ dateIssued: companyToday};return (diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsxindex 3b7c9845b1..817ce9d86b 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx@@ -2,8 +2,7 @@ import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { validator } from "@carbon/form";-import { getSalesOrderStatus } from "@carbon/utils";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime, getSalesOrderStatus } from "@carbon/utils";import { parseAcceptLanguage } from "intl-parse-accept-language";import type { ActionFunctionArgs } from "react-router";import { runMRP } from "~/modules/production/production.service";@@ -16,6 +15,7 @@ import {generateAndAttachSalesOrderPdf,sendSalesOrderEmail} from "~/modules/shared/shared.server";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { loader as pdfLoader } from "~/routes/file+/sales-order+/$id[.]pdf";export async function action(args: ActionFunctionArgs) {@@ -150,8 +150,11 @@ export async function action(args: ActionFunctionArgs) {.update({status,orderDate:- salesOrder.data.orderDate ?? today(getLocalTimeZone()).toString(),- updatedAt: today(getLocalTimeZone()).toString(),+ salesOrder.data.orderDate ??+ datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId}).eq("id", orderId);diff --git a/apps/erp/app/routes/x+/sales-rfq+/new.tsx b/apps/erp/app/routes/x+/sales-rfq+/new.tsxindex a8d08b00ce..1916ae59e6 100644--- a/apps/erp/app/routes/x+/sales-rfq+/new.tsx+++ b/apps/erp/app/routes/x+/sales-rfq+/new.tsx@@ -2,11 +2,10 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { useUrlParams, useUser } from "~/hooks";+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";import { upsertDocument } from "~/modules/documents";import { resolveItemIdFromExtractedText } from "~/modules/items";import type { SalesRFQStatusType } from "~/modules/sales";@@ -155,6 +154,7 @@ export default function SalesRFQNewRoute() {const { id: userId, defaults } = useUser();const [params] = useUrlParams();const customerId = params.get("customerId");+ const companyToday = useCompanyToday();const initialValues = {customerContactId: "",customerLocationId: "",@@ -163,7 +163,7 @@ export default function SalesRFQNewRoute() {expirationDate: "",id: undefined,locationId: defaults?.locationId ?? "",- rfqDate: today(getLocalTimeZone()).toString(),+ rfqDate: companyToday,rfqId: undefined,status: "Draft" as SalesRFQStatusType,salesPersonId: userIddiff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsxindex c1500e011f..b9373fadf6 100644--- a/apps/erp/app/routes/x+/schedule+/dates.tsx+++ b/apps/erp/app/routes/x+/schedule+/dates.tsx@@ -25,7 +25,6 @@ import {import {endOfMonth,endOfWeek,- getLocalTimeZone,now,parseDate,startOfMonth,@@ -56,6 +55,7 @@ import { DateKanban } from "~/modules/production/ui/Schedule/Kanban/DateKanban";import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";import { getLocationsList } from "~/modules/resources";import { getTagsList } from "~/modules/shared";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";import { getUserDefaults } from "~/modules/users/users.server";import { usePeople } from "~/stores";import type { Handle } from "~/utils/handle";@@ -84,11 +84,6 @@ export async function loader({ request }: LoaderFunctionArgs) {const view = (searchParams.get("view") as ViewType) ?? "week";const dateParam = searchParams.get("date");- const timezone = getLocalTimeZone();- const currentDate = dateParam- ? parseDate(dateParam)- : toCalendarDate(now(timezone));-let selectedSalesOrderIds: string[] = [];let selectedTags: string[] = [];let selectedAssignee: string[] = [];@@ -149,6 +144,13 @@ export async function loader({ request }: LoaderFunctionArgs) {locationId = locations.data?.[0].id as string;}+ // The board's "today" and its week/month windows belong to the plant being+ // scheduled, not the server — resolved after locationId settles.+ const timezone = await getLocationTimeZone(client, locationId, companyId);+ const currentDate = dateParam+ ? parseDate(dateParam)+ : toCalendarDate(now(timezone));+// Calculate date range based on viewlet startDate: string;let endDate: string;@@ -496,7 +498,8 @@ export async function loader({ request }: LoaderFunctionArgs) {tags: tags.data ?? [],locationId,view,- currentDate: currentDate.toString()+ currentDate: currentDate.toString(),+ timezone};}@@ -526,11 +529,10 @@ function DateKanbanSchedule() {tags,locationId,view,- currentDate+ currentDate,+ timezone} = useLoaderData<typeof loader>();- const timezone = getLocalTimeZone();-// Reformat column titles using user localeconst columns = useMemo(() => {return loaderColumns.map((col) => {@@ -652,25 +654,24 @@ function DateKanbanSchedule() {const getDateSpanLabel = useCallback((date: typeof parsedDate, viewType: ViewType) => {- const tz = getLocalTimeZone();if (viewType === "week") {const weekStart = startOfWeek(date, "en-GB");const weekEnd = endOfWeek(date, "en-GB");- return `${weekStart.toDate(tz).toLocaleDateString(locale, {+ return `${weekStart.toDate(timezone).toLocaleDateString(locale, {month: "short",day: "numeric"- })} - ${weekEnd.toDate(tz).toLocaleDateString(locale, {+ })} - ${weekEnd.toDate(timezone).toLocaleDateString(locale, {month: "short",day: "numeric"})}`;} else {- return date.toDate(tz).toLocaleDateString(locale, {+ return date.toDate(timezone).toLocaleDateString(locale, {month: "short",year: "numeric"});}},- [locale]+ [locale, timezone]);const getSpanStartDate = useCallback(diff --git a/apps/erp/app/routes/x+/settings+/companies.$id.tsx b/apps/erp/app/routes/x+/settings+/companies.$id.tsxindex 5e081b921c..4949b099bc 100644--- a/apps/erp/app/routes/x+/settings+/companies.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/companies.$id.tsx@@ -10,6 +10,7 @@ import {subsidiaryValidator,updateSubsidiary} from "~/modules/settings";+import { invalidateCompanyTimeZone } from "~/modules/shared/timezone.server";import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -59,6 +60,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // company.timezone may have changed — drop the cached resolution.+ await invalidateCompanyTimeZone(id);+throw redirect(path.to.companies,await flash(request, success("Updated subsidiary"))@@ -81,7 +85,8 @@ export default function EditSubsidiaryRoute() {phone: subsidiary.phone ?? "",fax: subsidiary.fax ?? "",email: subsidiary.email ?? "",- website: subsidiary.website ?? ""+ website: subsidiary.website ?? "",+ timezone: subsidiary.timezone ?? "UTC"};return <CompanyForm company={initialValues} />;diff --git a/apps/erp/app/routes/x+/settings+/companies.new.tsx b/apps/erp/app/routes/x+/settings+/companies.new.tsxindex ffdd38f58a..5aaa89e602 100644--- a/apps/erp/app/routes/x+/settings+/companies.new.tsx+++ b/apps/erp/app/routes/x+/settings+/companies.new.tsx@@ -82,7 +82,7 @@ export async function action({ request }: ActionFunctionArgs) {...locationData,name: "Headquarters",companyId,- timezone: getLocalTimeZone(),+ // timezone comes from locationData — HQ shares the company's timezone.createdBy: userId});@@ -140,7 +140,8 @@ export default function NewSubsidiaryRoute() {stateProvince: "",postalCode: "",countryCode: "",- baseCurrencyCode: company?.baseCurrencyCode ?? "USD"+ baseCurrencyCode: company?.baseCurrencyCode ?? "USD",+ timezone: getLocalTimeZone()};return (diff --git a/apps/erp/app/routes/x+/settings+/company.new.tsx b/apps/erp/app/routes/x+/settings+/company.new.tsxindex 456952b2f6..b7e1c4fed3 100644--- a/apps/erp/app/routes/x+/settings+/company.new.tsx+++ b/apps/erp/app/routes/x+/settings+/company.new.tsx@@ -6,7 +6,6 @@ import { updateCompanySession } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redis } from "@carbon/kv";import { getLogger } from "@carbon/logger";-import { getLocalTimeZone } from "@internationalized/date";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { insertEmployeeJob } from "~/modules/people";@@ -58,7 +57,7 @@ export async function action({ request }: ActionFunctionArgs) {...locationData,name: "Headquarters",companyId,- timezone: getLocalTimeZone(),+ // timezone comes from locationData — HQ shares the company's timezone.createdBy: userId});diff --git a/apps/erp/app/routes/x+/settings+/company.tsx b/apps/erp/app/routes/x+/settings+/company.tsxindex 85f7e73d58..5ea8d04abc 100644--- a/apps/erp/app/routes/x+/settings+/company.tsx+++ b/apps/erp/app/routes/x+/settings+/company.tsx@@ -30,6 +30,7 @@ import {companyValidator,updateCompany} from "~/modules/settings";+import { invalidateCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { copyToClipboard } from "~/utils/string";@@ -62,6 +63,9 @@ export async function action({ request }: ActionFunctionArgs) {await flash(request, error(update.error, "Failed to update company")));+ // company.timezone may have changed — drop the cached resolution.+ await invalidateCompanyTimeZone(companyId);+return data({}, await flash(request, success("Updated company")));}@@ -90,6 +94,7 @@ export default function Company() {stateProvince: company.stateProvince ?? "",postalCode: company.postalCode ?? "",countryCode: company.countryCode ?? "",+ timezone: company.timezone ?? "UTC",baseCurrencyCode: company.baseCurrencyCode ?? undefined,phone: company.phone ?? undefined,email: company.email ?? undefined,diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsxindex 6ad374163b..d3a2edc94c 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx@@ -10,10 +10,15 @@ import {import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { getCachedPrinterConfig } from "@carbon/printing/printing.server";-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";+import { parseDate } from "@internationalized/date";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { upsertDocument } from "~/modules/documents";+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";@@ -49,7 +54,7 @@ export async function action({ request, params }: ActionFunctionArgs) {// fire here too.const { data: shipmentForSurface } = await serviceRole.from("shipment")- .select("sourceDocument")+ .select("sourceDocument, locationId").eq("id", shipmentId).single();const surfaces: ("shipment" | "warehouseTransfer")[] = ["shipment"];@@ -131,7 +136,15 @@ export async function action({ request, params }: ActionFunctionArgs) {.eq("attributes ->> Shipment", shipmentId).eq("companyId", companyId);- const todayLocal = today(getLocalTimeZone());+ // 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(+ shipmentLocationId+ ? await getLocationTimeZone(serviceRole, shipmentLocationId, companyId)+ : await getCompanyTimeZone(serviceRole, companyId)+ );const expiredEntities = (shipmentTrackedEntities ?? []).filter((e) => {if (!e.expirationDate) return false;try {diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsxindex 50480bee28..9de4eea760 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx@@ -6,7 +6,7 @@ import { validationError, validator } from "@carbon/form";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { NotificationEvent } from "@carbon/notifications";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { supplierApprovalDecisionValidator } from "~/modules/purchasing";@@ -71,7 +71,7 @@ export async function action({ request, params }: ActionFunctionArgs) {.update({supplierStatus: "Pending",updatedBy: userId,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", supplierId);@@ -134,7 +134,7 @@ export async function action({ request, params }: ActionFunctionArgs) {.update({supplierStatus: "Inactive",updatedBy: userId,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", supplierId);diff --git a/apps/erp/app/routes/x+/supplier-quote+/new.tsx b/apps/erp/app/routes/x+/supplier-quote+/new.tsxindex d63959d6ac..f0eda89121 100644--- a/apps/erp/app/routes/x+/supplier-quote+/new.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/new.tsx@@ -2,11 +2,10 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { useUrlParams, useUser } from "~/hooks";+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";import {insertSupplierQuote,supplierQuoteValidator@@ -65,12 +64,13 @@ export default function SupplierQuoteNewRoute() {const [params] = useUrlParams();const { company } = useUser();const supplierId = params.get("supplierId");+ const companyToday = useCompanyToday();const initialValues = {supplierContactId: "",supplierId: supplierId ?? "",supplierReference: "",expirationDate: "",- quotedDate: today(getLocalTimeZone()).toString(),+ quotedDate: companyToday,supplierQuoteId: undefined,status: "Draft" as const,currencyCode: company.baseCurrencyCode,diff --git a/apps/erp/app/routes/x+/supplier-quote+/update.tsx b/apps/erp/app/routes/x+/supplier-quote+/update.tsxindex 5aed60a92d..aca6c55893 100644--- a/apps/erp/app/routes/x+/supplier-quote+/update.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/update.tsx@@ -1,14 +1,16 @@import { requirePermissions } from "@carbon/auth/auth.server";-import { getLocalTimeZone, today } from "@internationalized/date";+import { datetime } from "@carbon/utils";+import type { CalendarDate } from "@internationalized/date";+import { parseDate } from "@internationalized/date";import type { ActionFunctionArgs } from "react-router";import { getCurrencyByCode } from "~/modules/accounting";import { isSupplierQuoteLocked } from "~/modules/purchasing";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";export async function action({ request }: ActionFunctionArgs) {- const { client, companyGroupId, userId } = await requirePermissions(request, {- update: "purchasing"- });+ const { client, companyGroupId, companyId, userId } =+ await requirePermissions(request, { update: "purchasing" });const formData = await request.formData();const ids = formData.getAll("ids");@@ -99,20 +101,38 @@ export async function action({ request }: ActionFunctionArgs) {}).in("id", ids as string[]);- case "expirationDate":+ case "expirationDate": {+ // Reject non-canonical dates before comparing — a malformed string would+ // otherwise produce a status that disagrees with the stored date.+ let expirationDate: CalendarDate | null = null;+ if (value) {+ try {+ expirationDate = parseDate(value);+ } catch {+ return {+ error: { message: "Invalid expiration date" },+ data: null+ };+ }+ }+ // Expiry is judged on the company's calendar — one set of books, one+ // "today" — not the server's or the editing user's.+ const companyToday = datetime.today(+ await getCompanyTimeZone(client, companyId)+ );return await client.from("supplierQuote").update({- status: value- ? today(getLocalTimeZone()).toString() > value+ status:+ expirationDate && companyToday.compare(expirationDate) > 0? "Expired"- : "Active"- : "Active",- expirationDate: value ? value : null,+ : "Active",+ expirationDate: expirationDate ? expirationDate.toString() : null,updatedBy: userId,updatedAt: new Date().toISOString()}).in("id", ids as string[]);+ }default:return { error: { message: "Invalid field" }, data: null };}diff --git a/apps/erp/app/services/onboarding-draft.server.ts b/apps/erp/app/services/onboarding-draft.server.tsindex e44fefed83..5aff3fb17b 100644--- a/apps/erp/app/services/onboarding-draft.server.ts+++ b/apps/erp/app/services/onboarding-draft.server.ts@@ -27,6 +27,7 @@ export type OnboardingDraft = {postalCode?: string;countryCode?: string;baseCurrencyCode?: string;+ timezone?: string;website?: string;};};diff --git a/apps/erp/app/services/onboarding.server.ts b/apps/erp/app/services/onboarding.server.tsindex c9dc719320..3a42f11ab3 100644--- a/apps/erp/app/services/onboarding.server.ts+++ b/apps/erp/app/services/onboarding.server.ts@@ -139,7 +139,7 @@ export async function provisionOnboardingCompany(upsertLocation(serviceRole, {...location,...addressData,- timezone: getLocalTimeZone(),+ timezone: companyData.timezone || getLocalTimeZone(),updatedBy: userId})]);@@ -184,7 +184,7 @@ export async function provisionOnboardingCompany(...addressData,name: "Headquarters",companyId,- timezone: getLocalTimeZone(),+ timezone: companyData.timezone || getLocalTimeZone(),createdBy: userId});if (locationInsert.error) {diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 830f575820..b486ee4611 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -259,6 +259,7 @@ export const path = {tags: (table?: string) =>generatePath(`${api}/shared/tags?table=${table}`),timecard: `${api}/people/timecard`,+ timezones: `${api}/timezones`,unitOfMeasures: `${api}/items/uoms`,userSelectGroupEmails: (groupId: string) =>generatePath(`${api}/users/select/groups/${groupId}/emails`),diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.tsindex 4fed5100d0..3ce8ea676d 100644--- a/apps/erp/app/utils/react-query.ts+++ b/apps/erp/app/utils/react-query.ts@@ -55,6 +55,11 @@ export const currenciesQuery = () => ({staleTime: RefreshRate.Never});+export const timezonesQuery = () => ({+ queryKey: ["timezones"],+ staleTime: RefreshRate.Never+});+export const customerContactsQuery = (customerId: string) => ({queryKey: ["customerContacts", customerId],staleTime: RefreshRate.Lowdiff --git a/apps/erp/app/utils/string.ts b/apps/erp/app/utils/string.tsindex bad2ae80dd..cd15b995c4 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, now } from "@internationalized/date";export { stripSpecialCharacters } from "@carbon/utils";@@ -52,31 +54,20 @@ 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);-};--// used to generate sequences-export const interpolateSequenceDate = (value: string | null) => {+// 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 = "UTC"+) => {// replace all instances of %{year} with the current yearif (!value) return "";let result = value;if (result.includes("%{")) {- const date = new Date();- const year = date.getFullYear();- const month = date.getMonth() + 1;- const day = date.getDate();- const hours = date.getHours();- const seconds = date.getSeconds();- const week = getISOWeek(date);+ const { year, month, day, hour: hours, second: seconds } = now(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+/dispatch.new.tsx b/apps/mes/app/routes/x+/dispatch.new.tsxindex 65ac7f4d7c..f57595a49b 100644--- a/apps/mes/app/routes/x+/dispatch.new.tsx+++ b/apps/mes/app/routes/x+/dispatch.new.tsx@@ -6,7 +6,7 @@ import { validationError, validator } from "@carbon/form";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { NotificationEvent } from "@carbon/notifications";-import { getLocalTimeZone, now } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data, redirect } from "react-router";import { maintenanceDispatchValidator } from "~/services/models";@@ -58,7 +58,7 @@ export async function action({ request }: ActionFunctionArgs) {: "In Progress": "Open";- const currentTime = now(getLocalTimeZone()).toAbsoluteString();+ const currentTime = datetime.timestamp();// Get locationId from work centerlet locationId: string | undefined;@@ -115,7 +115,7 @@ export async function action({ request }: ActionFunctionArgs) {await endProductionEventsByWorkCenter(serviceRole, {workCenterId: validation.data.workCenterId,companyId,- endTime: now(getLocalTimeZone()).toAbsoluteString()+ endTime: datetime.timestamp()});}diff --git a/apps/mes/app/routes/x+/end-shift.tsx b/apps/mes/app/routes/x+/end-shift.tsxindex d8e1791060..0ec8b2e5ec 100644--- a/apps/mes/app/routes/x+/end-shift.tsx+++ b/apps/mes/app/routes/x+/end-shift.tsx@@ -1,7 +1,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getLogger } from "@carbon/logger";-import { getLocalTimeZone, now } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { clearConsolePinIn } from "~/services/console.server";@@ -14,13 +14,12 @@ export async function action({ request }: ActionFunctionArgs) {request,{});- const formData = await request.formData();- const timezone = formData.get("timezone") as string | null;+ await request.formData();const updates = await endProductionEvents(client, {companyId,employeeId: userId,- endTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString()+ endTime: datetime.timestamp()});if (updates.error) {@@ -42,7 +41,7 @@ export async function action({ request }: ActionFunctionArgs) {const clockOutResult = await serviceRole.from("timeCardEntry").update({- clockOut: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),+ clockOut: datetime.timestamp(),updatedBy: userId} as any).eq("employeeId", userId)diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsxindex 3cf243ce4b..147e17cfe6 100644--- a/apps/mes/app/routes/x+/event.tsx+++ b/apps/mes/app/routes/x+/event.tsx@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { getLocalTimeZone, now } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { productionEventValidator } from "~/services/models";@@ -28,7 +28,6 @@ export async function action({ request }: ActionFunctionArgs) {const {id,action: productionAction,- timezone,trackedEntityId,unitIndex,exclusive,@@ -49,7 +48,7 @@ export async function action({ request }: ActionFunctionArgs) {.neq("type", d.type);if (openOthers.data && openOthers.data.length > 0) {const serviceRole = await getCarbonServiceRole();- const endTime = now(timezone ?? getLocalTimeZone()).toAbsoluteString();+ const endTime = datetime.timestamp();for (const ev of openOthers.data) {const ended = await endProductionEvent(client, {id: ev.id,@@ -68,7 +67,7 @@ export async function action({ request }: ActionFunctionArgs) {client,{...d,- startTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),+ startTime: datetime.timestamp(),employeeId: userId,companyId,createdBy: userId@@ -94,7 +93,7 @@ export async function action({ request }: ActionFunctionArgs) {}const endEvent = await endProductionEvent(client, {id,- endTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),+ endTime: datetime.timestamp(),employeeId: userId});if (endEvent.error) {diff --git a/apps/mes/app/routes/x+/maintenance-event.tsx b/apps/mes/app/routes/x+/maintenance-event.tsxindex 2413242ec0..e7de42a68b 100644--- a/apps/mes/app/routes/x+/maintenance-event.tsx+++ b/apps/mes/app/routes/x+/maintenance-event.tsx@@ -2,7 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";-import { getLocalTimeZone, now } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data, redirect } from "react-router";import {@@ -27,7 +27,7 @@ export async function action({ request }: ActionFunctionArgs) {}const serviceRole = await getCarbonServiceRole();- const currentTime = now(getLocalTimeZone()).toAbsoluteString();+ const currentTime = datetime.timestamp();if (action === "Start") {// Start a new maintenance eventdiff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsxindex 7fee94623a..c8e137e02f 100644--- a/apps/mes/app/routes/x+/start.$operationId.tsx+++ b/apps/mes/app/routes/x+/start.$operationId.tsx@@ -6,7 +6,7 @@ import {evaluateLinesForSurface,isBlocked} from "@carbon/ee/storage-rules.server";-import { getLocalTimeZone, now } from "@internationalized/date";+import { datetime } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";import { getWorkCenterWithBlockingStatus } from "~/services/maintenance.service";@@ -156,7 +156,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// If type is Machine, cancel all setup and labor production events for this operationif (type === "Machine") {- const currentTime = now(getLocalTimeZone()).toAbsoluteString();+ const currentTime = datetime.timestamp();await serviceRole.from("productionEvent")@@ -176,7 +176,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {type,jobOperationId: operationId,workCenterId: jobOperation.data.workCenterId!,- startTime: now(getLocalTimeZone()).toAbsoluteString(),+ startTime: datetime.timestamp(),employeeId: userId,companyId,createdBy: userIddiff --git a/apps/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsxindex 3e3e9f8191..7edda6680b 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 { datetime } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import { useEffect, useState } from "react";@@ -50,25 +52,6 @@ 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);-- return {- from: monday.toISOString(),- to: sunday.toISOString(),- monday,- sunday- };-}-function formatDuration(clockInStr: string, clockOutStr: string | null) {const end = clockOutStr ? new Date(clockOutStr).getTime() : Date.now();const ms = end - new Date(clockInStr).getTime();@@ -122,7 +105,14 @@ 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);+ // Week runs Monday → Sunday on the company calendar (one payroll boundary+ // per books, not the server's zone).+ const tz = await getCompanyTimeZone(client, companyId);+ const { from, to } = datetime.weekBounds(tz, weekOffset);+ // Calendar days of the window on the COMPANY calendar — the client renders+ // these directly so the header never shifts a day in a different browser tz.+ const weekStart = datetime.businessDay(from, tz).toString();+ const weekEnd = datetime.businessDay(to, tz).toString();const [entries, openEntry] = await Promise.all([client@@ -140,8 +130,8 @@ export async function loader({ request }: LoaderFunctionArgs) {entries: entries.data ?? [],openEntry: openEntry.data,weekOffset,- from,- to+ weekStart,+ weekEnd};}@@ -195,7 +185,7 @@ export async function action({ request }: ActionFunctionArgs) {}export default function MESTimecardPage() {- const { entries, openEntry, weekOffset, from, to } =+ const { entries, openEntry, weekOffset, weekStart, weekEnd } =useLoaderData<typeof loader>();const fetcher = useFetcher<typeof action>();const [editingId, setEditingId] = useState<string | null>(null);@@ -210,8 +200,6 @@ export default function MESTimecardPage() {clockIn: string;} | null>(null);- const monday = new Date(from);- const sunday = new Date(to);const isCurrentWeek = weekOffset === 0;useEffect(() => {@@ -286,8 +274,8 @@ export default function MESTimecardPage() {</Link></Button><span className="text-sm text-muted-foreground">- {formatDate(monday.toISOString(), { dateStyle: "medium" })} —{" "}- {formatDate(sunday.toISOString(), { dateStyle: "medium" })}+ {formatDate(weekStart, { dateStyle: "medium" })} —{" "}+ {formatDate(weekEnd, { dateStyle: "medium" })}</span><Buttonvariant="outline"diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.tsindex 38e662c56a..d54d6a03a7 100644--- a/apps/mes/app/services/inventory.service.ts+++ b/apps/mes/app/services/inventory.service.ts@@ -1,10 +1,12 @@import { SUPABASE_URL } from "@carbon/auth";import type { Database } from "@carbon/database";+import { getLocationTimeZone } from "@carbon/database";import type {DocumentTemplate,DocumentTemplateType} from "@carbon/documents/template";import { toDocumentTemplate } from "@carbon/documents/template";+import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { z } from "zod";import { zfd } from "zod-form-data";@@ -323,7 +325,9 @@ export async function getSuggestedAllocationForMaterial(// issue modal refuses to offer (expiredEntityPolicy 'Block' drops them from// the options), netting the seed to nothing. An expired lot is never the// "correct batch to use" — skip them regardless of policy.- const today = new Date().toISOString().slice(0, 10);+ const today = datetime+ .today(await getLocationTimeZone(client, args.locationId, args.companyId))+ .toString();const unexpired = data.filter((row) => !row.expirationDate || row.expirationDate >= today);diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 03370eb0db..01edee9236 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -1,13 +1,14 @@import type { Database } from "@carbon/database";+import { getCompanyTimeZone } from "@carbon/database";import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";import {+ datetime,type FlatTree,flattenTree,generateBomIds,type TrackedActivityAttributes} from "@carbon/utils";-import { getLocalTimeZone, today } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";import type { z } from "zod";@@ -649,16 +650,34 @@ export async function getJobMaterialsByOperationId(const consumedEntityIds = Array.from(new Set((trackedInputs.data ?? []).map((i) => i.id).filter(Boolean)));- const todayStr = today(getLocalTimeZone()).toString();- const expiredConsumed =- consumedEntityIds.length > 0- ? await client- .from("trackedEntity")- .select("id")- .in("id", consumedEntityIds)- .not("expirationDate", "is", null)- .lt("expirationDate", todayStr)- : { data: [] as { id: string }[] };+ let expiredConsumed: { data: { id: string }[] | null } = {+ data: [] as { id: string }[]+ };+ if (consumedEntityIds.length > 0) {+ const job = await client+ .from("job")+ .select("companyId")+ .eq("id", operation.jobId)+ .single();+ // A missing job row must not silently degrade the expiry cutoff to UTC+ // (getCompanyTimeZone("") resolves no company and falls back).+ if (job.error || !job.data) {+ throw new Error(+ `Failed to resolve job ${operation.jobId} for the expiry check: ${+ job.error?.message ?? "not found"+ }`+ );+ }+ const todayStr = datetime+ .today(await getCompanyTimeZone(client, job.data.companyId))+ .toString();+ expiredConsumed = await client+ .from("trackedEntity")+ .select("id")+ .in("id", consumedEntityIds)+ .not("expirationDate", "is", null)+ .lt("expirationDate", todayStr);+ }const expiredConsumedIds = new Set((expiredConsumed.data ?? []).map((r) => r.id));diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.tsindex d3cd319cd9..a3e958deeb 100644--- a/apps/mes/app/services/quality.server.ts+++ b/apps/mes/app/services/quality.server.ts@@ -1,5 +1,7 @@import type { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";+import { getLocationTimeZone } from "@carbon/database";+import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import {getJobMakeMethod,@@ -110,7 +112,11 @@ export async function createQualityIssue(locationId: context.locationId,nonConformanceTypeId: args.nonConformanceTypeId ?? context.issueTypeId,nonConformanceWorkflowId: null,- openDate: new Date().toISOString().slice(0, 10),+ openDate: datetime+ .today(+ await getLocationTimeZone(serviceRole, context.locationId, companyId)+ )+ .toString(),quantity,assignee: context.assignee,requiredActionIds: [],diff --git a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml b/contrib/deploying/simple-docker-caddy/docker-compose.prod.ymlindex 41506a0cd0..f9cf6cf6a5 100644--- a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml+++ b/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml@@ -64,6 +64,7 @@ services:environment:NODE_ENV: productionPORT: "3000"+ TZ: UTCCARBON_EDITION: ${CARBON_EDITION:-community}AUTH_PROVIDERS: ${AUTH_PROVIDERS:-email,google,azure}DOMAIN: ${DOMAIN}@@ -106,6 +107,7 @@ services:environment:NODE_ENV: productionPORT: "3000"+ TZ: UTCCARBON_EDITION: ${CARBON_EDITION:-community}AUTH_PROVIDERS: ${AUTH_PROVIDERS:-email,google,azure}DOMAIN: ${DOMAIN}@@ -205,6 +207,7 @@ services:- postgres_password- jwt_secretenvironment:+ TZ: UTCPOSTGRES_HOST: /var/run/postgresqlPOSTGRES_PORT: "5432"PGPORT: "5432"@@ -476,6 +479,7 @@ services:- anon_key- service_role_keyenvironment:+ TZ: UTCJWT_SECRET: __JWT_SECRET__SUPABASE_URL: http://kong:8000SUPABASE_ANON_KEY: __ANON_KEY__diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.mdindex 94666c124d..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+- **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/baseline.json b/packages/checks/src/conformance/baseline.jsonindex 3dfbb4b0b4..39d82abca0 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -1,6 +1,4 @@[- "module-shape::items::extra-models:changeOrder.models.ts",- "module-shape::items::extra-service:changeOrder.service.ts","module-shape::settings::extra-service:backups.service.ts","module-shape::shared::extra-models:imports.models.ts","module-shape::shared::missing:ui",@@ -90,6 +88,12 @@"no-legacy-rls::20250128094053_traceability.sql::has_company_permission(","no-legacy-rls::20260115143000_purchasing-rfq.sql::has_company_permission(","no-legacy-rls::20260430000001_tax-status.sql::has_company_permission(",+ "no-local-timezone::apps/erp/app/modules/accounting/accounting.service.ts::new Date().toISOString().split(\"T\")[0]",+ "no-local-timezone::apps/erp/app/modules/items/items.service.ts::new Date().toISOString().split(\"T\")[0]",+ "no-local-timezone::apps/erp/app/modules/sales/sales.service.ts::new Date().toISOString().split(\"T\")[0]",+ "no-local-timezone::packages/database/supabase/functions/get-method/index.ts::new Date().toISOString().slice(0, 10)",+ "no-local-timezone::packages/database/supabase/functions/lib/scheduling/work-center-selector.ts::new Date().toISOString().split(\"T\")[0]",+ "no-local-timezone::packages/database/supabase/functions/reschedule/index.ts::new Date().toISOString().split(\"T\")[0]","no-numeric-precision::20230330024715_accounts.sql::NUMERIC(20,8)","no-numeric-precision::20230330024716_parts.sql::NUMERIC(15,5)","no-numeric-precision::20230510035345_purchasing.sql::NUMERIC(10,5)",diff --git a/packages/checks/src/conformance/no-local-timezone.test.ts b/packages/checks/src/conformance/no-local-timezone.test.tsnew file mode 100644index 0000000000..daa6409069--- /dev/null+++ b/packages/checks/src/conformance/no-local-timezone.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it } from "vitest";+import { noLocalTimezone } from "./no-local-timezone";++describe("noLocalTimezone", () => {+ it("flags getLocalTimeZone() in server code", () => {+ const ts = "const d = today(getLocalTimeZone()).toString();";+ const v = noLocalTimezone.scan("apps/erp/app/modules/x/x.service.ts", ts);+ expect(v).toHaveLength(1);+ expect(v[0]?.snippet).toBe("getLocalTimeZone(");+ });++ it("flags UTC day-slicing via split", () => {+ const ts = 'const today = new Date().toISOString().split("T")[0];';+ const v = noLocalTimezone.scan("f.ts", ts);+ expect(v).toHaveLength(1);+ });++ it("flags UTC day-slicing via slice", () => {+ const ts = "const today = new Date().toISOString().slice(0, 10);";+ const v = noLocalTimezone.scan("f.ts", ts);+ expect(v).toHaveLength(1);+ });++ it("flags UTC day-slicing of a supplied instant", () => {+ const cases = [+ 'const day = new Date(eventAt).toISOString().split("T")[0];',+ "const day = new Date(entry.clockIn).toISOString().slice(0, 10);"+ ];+ for (const ts of cases) {+ expect(noLocalTimezone.scan("f.ts", ts)).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();";+ expect(noLocalTimezone.scan("f.ts", ts)).toHaveLength(0);+ });++ it("records provenance pointing at the company-timezone migration", () => {+ expect(noLocalTimezone.provenance.since).toBe(+ "20260805020925_company-timezone.sql"+ );+ });+});diff --git a/packages/checks/src/conformance/no-local-timezone.ts b/packages/checks/src/conformance/no-local-timezone.tsnew file mode 100644index 0000000000..a958b59d52--- /dev/null+++ b/packages/checks/src/conformance/no-local-timezone.ts@@ -0,0 +1,63 @@+import type { ConformanceCheck, Violation } from "../check";++/**+ * Server code must not derive calendar days from the process timezone. The+ * 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. 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 = [+ {+ pattern: /getLocalTimeZone\s*\(/g,+ message:+ "Server code: resolve company/location timezone and use datetime.today(tz) — getLocalTimeZone() is the process zone, not the user's."+ },+ {+ // [^)]* also catches supplied instants: new Date(eventAt).toISOString()+ // .slice(0, 10) is that event's UTC day, not its business day.+ pattern:+ /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) / datetime.businessDay(instant, 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."+ }+];++export const noLocalTimezone: ConformanceCheck = {+ id: "no-local-timezone",+ description:+ "Server code derives calendar days via datetime.today(tz), never the process clock or UTC-slicing.",+ provenance: {+ deprecates: "getLocalTimeZone() / toISOString() day-slicing in server code",+ replacedBy: "@carbon/utils datetime + company/location timezone",+ since: "20260805020925_company-timezone.sql"+ },+ scan(file, contents) {+ const violations: Violation[] = [];+ contents.split("\n").forEach((text, i) => {+ for (const { pattern, message } of BANNED) {+ for (const m of text.matchAll(pattern)) {+ violations.push({ file, line: i + 1, snippet: m[0], message });+ }+ }+ });+ return violations;+ }+};diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.tsindex c5a2e37f0b..c731d18a92 100644--- a/packages/checks/src/index.ts+++ b/packages/checks/src/index.ts@@ -7,6 +7,7 @@ export type {export { findClobbers, objectRefs, type SourceFile } from "./clobber";export { moduleShape } from "./conformance/module-shape";export { noLegacyRls } from "./conformance/no-legacy-rls";+export { noLocalTimezone } from "./conformance/no-local-timezone";export { noNumericPrecision } from "./conformance/no-numeric-precision";export {type Invariant,@@ -20,8 +21,10 @@ export {collectFindings,type Finding,newViolations,+ SERVER_CHECKS,STRUCTURE_CHECKS,scanAll,scanModules} from "./run";export { loadModules, modulesDir } from "./sources/modules";+export { loadServerFiles } from "./sources/server-files";diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsindex c5303fd61e..c2e22a9146 100644--- a/packages/checks/src/run.ts+++ b/packages/checks/src/run.ts@@ -7,6 +7,7 @@ import type {} from "./check";import { moduleShape } from "./conformance/module-shape";import { noLegacyRls } from "./conformance/no-legacy-rls";+import { noLocalTimezone } from "./conformance/no-local-timezone";import { noNumericPrecision } from "./conformance/no-numeric-precision";import {loadSqlFiles,@@ -15,12 +16,16 @@ import {type SqlFile} from "./sources/migrations";import { loadModules, modulesDir } from "./sources/modules";+import { loadServerFiles } from "./sources/server-files";export const CONFORMANCE_CHECKS: ConformanceCheck[] = [noNumericPrecision,noLegacyRls];+/** Checks that run over server-side TS, not SQL migrations. */+export const SERVER_CHECKS: ConformanceCheck[] = [noLocalTimezone];+export const STRUCTURE_CHECKS: StructureCheck[] = [moduleShape];export type Finding = { checkId: string; violation: Violation };@@ -55,11 +60,12 @@ export function scanModules(return out;}-/** Every finding across the real migrations (text) + modules (structure) under `root`. */+/** Every finding across the real migrations (text) + modules (structure) + server TS under `root`. */export function collectFindings(root: string = repoRoot()): Finding[] {return [...scanAll(loadSqlFiles(migrationsDir(root))),- ...scanModules(loadModules(modulesDir(root)))+ ...scanModules(loadModules(modulesDir(root))),+ ...scanAll(loadServerFiles(root), SERVER_CHECKS)];}diff --git a/packages/checks/src/sources/server-files.test.ts b/packages/checks/src/sources/server-files.test.tsnew file mode 100644index 0000000000..f8ff51fb23--- /dev/null+++ b/packages/checks/src/sources/server-files.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from "vitest";+import { noLocalTimezone } from "../conformance/no-local-timezone";+import { maskClientCode } from "./server-files";++/**+ * A route module is server AND client in one file. These cases pin the split:+ * loader/action (and the module-level helpers they call) are scanned; the+ * component, its hooks, and clientLoader/clientAction are not.+ */+describe("maskClientCode", () => {+ const scan = (src: string) =>+ noLocalTimezone.scan("apps/erp/app/routes/x+/r.tsx", maskClientCode(src));++ it("keeps loader bodies", () => {+ const src = [+ "export async function loader({ request }: LoaderFunctionArgs) {",+ " const d = today(getLocalTimeZone());",+ "}"+ ].join("\n");+ expect(scan(src)).toHaveLength(1);+ });++ it("keeps action bodies, including the arrow-const form", () => {+ const src = [+ "export const action: ActionFunction = async ({ request }) => {",+ " const d = today(getLocalTimeZone());",+ "};"+ ].join("\n");+ expect(scan(src)).toHaveLength(1);+ });++ it("keeps module-level server helpers a loader calls", () => {+ const src = [+ "export async function loader() {",+ " return getExpired(client);",+ "}",+ "",+ "async function getExpired(client: Client) {",+ " return client.lt('expirationDate', today(getLocalTimeZone()));",+ "}"+ ].join("\n");+ expect(scan(src)).toHaveLength(1);+ });++ it("skips the default-export component", () => {+ const src = [+ "export default function Route() {",+ " const initialValues = { orderDate: today(getLocalTimeZone()) };",+ " return null;",+ "}"+ ].join("\n");+ expect(scan(src)).toHaveLength(0);+ });++ it("skips clientLoader and clientAction, which run in the browser", () => {+ const src = [+ "export async function clientAction({ serverAction }) {",+ " const d = today(getLocalTimeZone());",+ " return serverAction();",+ "}"+ ].join("\n");+ expect(scan(src)).toHaveLength(0);+ });++ it("skips PascalCase components and use-prefixed hooks", () => {+ const src = [+ "function DatePickerCell() {",+ " return today(getLocalTimeZone());",+ "}",+ "",+ "export function useToday() {",+ " return today(getLocalTimeZone());",+ "}"+ ].join("\n");+ expect(scan(src)).toHaveLength(0);+ });++ it("does not swallow server code after an expression-bodied component", () => {+ const src = [+ "const Toolbar = () => null;",+ "",+ "export async function loader() {",+ " const d = today(getLocalTimeZone());",+ "}"+ ].join("\n");+ const violations = scan(src);+ expect(violations).toHaveLength(1);+ expect(violations[0]?.line).toBe(4);+ });++ it("closes a paren-wrapped expression-bodied component at its `)` closer", () => {+ const src = [+ "const Header = () => (",+ " <div>{today(getLocalTimeZone()).toString()}</div>",+ ");",+ "",+ "export async function loader() {",+ " const d = today(getLocalTimeZone());",+ "}"+ ].join("\n");+ const violations = scan(src);+ expect(violations).toHaveLength(1);+ expect(violations[0]?.line).toBe(6);+ });++ it("keeps masking a hook whose signature spans multiple lines", () => {+ // The `) {` that closes a multi-line parameter list must NOT end the+ // region — the body is still ahead.+ const src = [+ "function useProgressByOperation(",+ " items: Item[]",+ ") {",+ " return now(getLocalTimeZone());",+ "}",+ "",+ "export async function loader() {",+ " const d = today(getLocalTimeZone());",+ "}"+ ].join("\n");+ const violations = scan(src);+ expect(violations).toHaveLength(1);+ expect(violations[0]?.line).toBe(8);+ });++ it("resumes scanning after a client region closes", () => {+ const src = [+ "export default function Route() {",+ " return today(getLocalTimeZone());",+ "}",+ "",+ "export async function action() {",+ " const d = today(getLocalTimeZone());",+ "}"+ ].join("\n");+ const violations = scan(src);+ expect(violations).toHaveLength(1);+ expect(violations[0]?.line).toBe(6);+ });++ it("preserves line numbers so violations point at the real line", () => {+ const src = [+ "export default function Route() {",+ " return null;",+ "}",+ "",+ "export async function loader() {",+ " const d = today(getLocalTimeZone());",+ "}"+ ].join("\n");+ expect(scan(src)[0]?.line).toBe(6);+ });+});diff --git a/packages/checks/src/sources/server-files.ts b/packages/checks/src/sources/server-files.tsnew file mode 100644index 0000000000..afbcb8d77d--- /dev/null+++ b/packages/checks/src/sources/server-files.ts@@ -0,0 +1,146 @@+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { join, relative } from "node:path";+import type { SqlFile } from "./migrations";++/**+ * Server-side TypeScript that must derive calendar days through the `datetime`+ * API (explicit company/location timezone), never the process clock. Client+ * components are exempt — the browser's timezone IS the right one there.+ */+const SERVER_ROOTS = [+ "apps/mes/app/services",+ "packages/jobs/src",+ "packages/database/supabase/functions"+];++/** ERP module server files are matched by suffix inside apps/erp/app/modules. */+const ERP_MODULES_ROOT = "apps/erp/app/modules";+const ERP_SERVER_SUFFIXES = [".service.ts", ".server.ts"];++/**+ * Route modules are server AND client in one file: `loader`/`action` run on the+ * server, while the default export and `clientLoader`/`clientAction` run in the+ * browser. Scanning them whole would flag every legitimate browser-side+ * `getLocalTimeZone()`, so route files are masked down to their server+ * functions before the checks see them.+ */+const ROUTE_ROOTS = ["apps/erp/app/routes", "apps/mes/app/routes"];++/**+ * Opens a browser-only region. Masking *out* these rather than masking *in*+ * `loader`/`action` is deliberate: module-level helpers that the loader calls+ * (e.g. `getExpiredItemIds` in job+/$jobId.materials.tsx) are server code too,+ * and a mask-in rule would silently skip them.+ */+const CLIENT_REGION_START = [+ /^export\s+default\s+(?:async\s+)?function\b/,+ /^export\s+default\s+(?:memo|forwardRef)\b/,+ // clientLoader/clientAction run in the browser, unlike loader/action.+ /^export\s+(?:async\s+function\s+|function\s+|const\s+)client(?:Loader|Action)\b/,+ // Components and hooks: PascalCase or use-prefixed declarations.+ /^(?:export\s+)?(?:async\s+)?function\s+(?:[A-Z]|use[A-Z])/,+ /^(?:export\s+)?const\s+(?:[A-Z]|use[A-Z])[A-Za-z0-9_]*\s*(?::[^=]*)?=\s*(?:\(|function|memo|forwardRef)/+];++function walk(dir: string, out: string[], extensions: string[]): void {+ // A missing root (e.g. a partial checkout) yields no findings for it rather+ // than aborting the whole scan.+ if (!existsSync(dir)) return;+ for (const entry of readdirSync(dir)) {+ if (entry === "node_modules" || entry.startsWith(".")) continue;+ const path = join(dir, entry);+ if (statSync(path).isDirectory()) {+ walk(path, out, extensions);+ } else if (+ extensions.some((ext) => entry.endsWith(ext)) &&+ !entry.endsWith(".test.ts") &&+ !entry.endsWith(".test.tsx")+ ) {+ out.push(path);+ }+ }+}++const netCount = (line: string, open: string, close: string): number =>+ line.split(open).length - line.split(close).length;++/**+ * A declaration that begins AND ends on one line (`const Toolbar = () => null;`)+ * opens no block, so it must not open a region — otherwise everything after it+ * (including a later `loader`) would be masked until a column-0 closer that+ * never comes.+ */+const isSingleLineDeclaration = (line: string): boolean =>+ line.trimEnd().endsWith(";") &&+ netCount(line, "{", "}") <= 0 &&+ netCount(line, "(", ")") <= 0;++/**+ * Blanks every component/hook/clientLoader/clientAction body, leaving the+ * server half of a route module. Line numbering is preserved so violations+ * still point at the real line. A region runs from its declaration to the next+ * column-0 `}` or `)` (`}` for block bodies, `)` for paren-wrapped+ * expression-bodied arrows) — reliable because the repo is Biome-formatted, so+ * a top-level closer is never indented.+ */+export function maskClientCode(contents: string): string {+ const lines = contents.split("\n");+ const kept = [...lines];+ let inClientRegion = false;++ lines.forEach((line, i) => {+ if (!inClientRegion && CLIENT_REGION_START.some((re) => re.test(line))) {+ if (isSingleLineDeclaration(line)) {+ kept[i] = "";+ return;+ }+ inClientRegion = true;+ }+ if (inClientRegion) {+ kept[i] = "";+ // `}`/`};` closes a block body; a bare `)`/`);` closes a paren-wrapped+ // expression body. A `) {`-style line is a multi-line SIGNATURE closer —+ // the body is still ahead, so it must not end the region.+ if (line.startsWith("}") || /^\)\s*;?\s*$/.test(line)) {+ inClientRegion = false;+ }+ }+ });++ return kept.join("\n");+}++/** Every server-side TS file, as repo-relative { file, contents }. */+export function loadServerFiles(root: string): SqlFile[] {+ const paths: string[] = [];++ for (const rel of SERVER_ROOTS) {+ walk(join(root, rel), paths, [".ts"]);+ }++ const erpPaths: string[] = [];+ walk(join(root, ERP_MODULES_ROOT), erpPaths, [".ts"]);+ for (const path of erpPaths) {+ if (ERP_SERVER_SUFFIXES.some((suffix) => path.endsWith(suffix))) {+ paths.push(path);+ }+ }++ const routePaths: string[] = [];+ for (const rel of ROUTE_ROOTS) {+ walk(join(root, rel), routePaths, [".ts", ".tsx"]);+ }+ paths.push(...routePaths);+ const isRoute = new Set(routePaths);++ return paths+ .map((path) => ({ path, file: relative(root, path) }))+ .sort((a, b) => a.file.localeCompare(b.file))+ .map(({ path, file }) => {+ const contents = readFileSync(path, "utf8");+ return {+ file,+ contents: isRoute.has(path) ? maskClientCode(contents) : contents+ };+ });+}diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex e89b418eb7..f1fb65a9ee 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) |+| `.` (root, from `src/timezone.ts` + `src/utils.ts`) | `getCompanyTimeZone(db, companyId)` / `getLocationTimeZone(db, locationId, companyId)` — business-timezone resolvers, overloaded for Supabase client or Kysely handle (they throw on query failure rather than silently falling back); `AnyPostgresClient` + `isKysely` guard 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-Referencesdiff --git a/packages/database/package.json b/packages/database/package.jsonindex 939c7b232a..2a127b5685 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -44,6 +44,7 @@"sideEffects": false,"version": "0.0.0","dependencies": {+ "@internationalized/date": "catalog:","@supabase/postgrest-js": "catalog:","cookie": "catalog:","dompurify": "catalog:",diff --git a/packages/database/src/index.ts b/packages/database/src/index.tsindex b47e50edfc..c3e4180a67 100644--- a/packages/database/src/index.ts+++ b/packages/database/src/index.ts@@ -1,2 +1,3 @@+export * from "./timezone.ts";export * from "./types.ts";export * from "./utils.ts";diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.tsindex 2b1d037fe7..fce1c44e29 100644--- a/packages/database/src/seed-dev.ts+++ b/packages/database/src/seed-dev.ts@@ -205,9 +205,11 @@ async function seedDev() {// Create the companyconsole.log("6. Creating company...");+ // Company timezone matches the seeded HQ location — one calendar for+ // ledger-scoped derivation from the first day.await client.query(- `INSERT INTO company (id, name, "baseCurrencyCode", "companyGroupId") VALUES ($1, $2, 'USD', $3)`,- [companyId, DEV_COMPANY_NAME, companyGroupId]+ `INSERT INTO company (id, name, "baseCurrencyCode", "companyGroupId", timezone) VALUES ($1, $2, 'USD', $3, $4)`,+ [companyId, DEV_COMPANY_NAME, companyGroupId, defaultLocation.timezone]);console.log(` Company "${DEV_COMPANY_NAME}" created.`);diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 2fba9bbed6..21cb7864ac 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -23049,6 +23049,9 @@ export default {{$ref: "#/parameters/rowFilter.companies.registrationNumber"},+ {+ $ref: "#/parameters/rowFilter.companies.timezone"+ },{$ref: "#/parameters/rowFilter.companies.userId"},@@ -65274,6 +65277,9 @@ export default {{$ref: "#/parameters/rowFilter.company.registrationNumber"},+ {+ $ref: "#/parameters/rowFilter.company.timezone"+ },{$ref: "#/parameters/select"},@@ -65438,6 +65444,9 @@ export default {{$ref: "#/parameters/rowFilter.company.registrationNumber"},+ {+ $ref: "#/parameters/rowFilter.company.timezone"+ },{$ref: "#/parameters/preferReturn"}@@ -65556,6 +65565,9 @@ export default {{$ref: "#/parameters/rowFilter.company.registrationNumber"},+ {+ $ref: "#/parameters/rowFilter.company.timezone"+ },{$ref: "#/parameters/body.company"},@@ -87468,6 +87480,63 @@ export default {tags: ["(rpc) get_item_quantities_by_tracking_id"]}},+ "/rpc/company_today": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "p_company_id",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) company_today"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) company_today"]+ }+ },"/rpc/sync_update_customer_type_group": {post: {parameters: [@@ -105855,6 +105924,10 @@ export default {format: "text",type: "string"},+ timezone: {+ format: "text",+ type: "string"+ },userId: {description:"Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",@@ -125869,7 +125942,8 @@ export default {"suggestionNotificationGroup","auditLogEnabled","isEliminationEntity",- "active"+ "active",+ "timezone"],properties: {id: {@@ -126033,6 +126107,11 @@ export default {registrationNumber: {format: "text",type: "string"+ },+ timezone: {+ default: "UTC",+ format: "text",+ type: "string"}},type: "object"@@ -147602,6 +147681,12 @@ export default {in: "query",type: "string"},+ "rowFilter.companies.timezone": {+ name: "timezone",+ required: false,+ in: "query",+ type: "string"+ },"rowFilter.companies.userId": {name: "userId",required: false,@@ -170022,6 +170107,12 @@ export default {in: "query",type: "string"},+ "rowFilter.company.timezone": {+ name: "timezone",+ required: false,+ in: "query",+ type: "string"+ },"body.documentTemplate": {name: "documentTemplate",description: "documentTemplate",diff --git a/packages/database/src/timezone.ts b/packages/database/src/timezone.tsnew file mode 100644index 0000000000..c2bc8285e9--- /dev/null+++ b/packages/database/src/timezone.ts@@ -0,0 +1,134 @@+import type { SupabaseClient } from "@supabase/supabase-js";+import type { Kysely } from "kysely";+import type { KyselyDatabase } from "./client.ts";+import type { Database } from "./types.ts";+import { type AnyPostgresClient, isKysely } from "./utils.ts";++/**+ * Ledger-scoped timezone: one calendar per set of books. Accounting periods,+ * posting dates, and sequence date tokens derive their business day here —+ * never from the process timezone. Falls back to UTC. Accepts a Supabase client+ * or a Kysely handle (pass an active `trx` when resolving inside a transaction).+ */+export function getCompanyTimeZone(+ db: SupabaseClient<Database>,+ companyId: string+): Promise<string>;+export function getCompanyTimeZone(+ db: Kysely<KyselyDatabase>,+ companyId: string+): Promise<string>;+/** For callers holding an un-narrowed handle (e.g. a caching wrapper). */+export function getCompanyTimeZone(+ db: AnyPostgresClient,+ companyId: string+): Promise<string>;+export async function getCompanyTimeZone(+ db: AnyPostgresClient,+ companyId: string+): Promise<string> {+ if (isKysely(db)) {+ const row = await db+ .selectFrom("company")+ .select("timezone")+ .where("id", "=", companyId)+ .executeTakeFirst();+ return row?.timezone ?? "UTC";+ }+ const company = await db+ .from("company")+ .select("timezone")+ .eq("id", companyId)+ .maybeSingle();+ // A failed read must not silently become a (wrong) business calendar —+ // fall back to UTC only when the query succeeded and found nothing.+ if (company.error) {+ throw new Error(+ `Failed to resolve company timezone: ${company.error.message}`+ );+ }+ return company.data?.timezone ?? "UTC";+}++/**+ * Operational timezone of a physical site — scheduling, shifts, MES+ * day-grouping. Falls back to the company timezone when the location is+ * missing or has no timezone.+ */+export function getLocationTimeZone(+ db: SupabaseClient<Database>,+ locationId: string,+ companyId: string+): Promise<string>;+export function getLocationTimeZone(+ db: Kysely<KyselyDatabase>,+ locationId: string,+ companyId: string+): Promise<string>;+/** For callers holding an un-narrowed handle (e.g. a caching wrapper). */+export function getLocationTimeZone(+ db: AnyPostgresClient,+ locationId: string,+ companyId: string+): Promise<string>;+export async function getLocationTimeZone(+ db: AnyPostgresClient,+ locationId: string,+ companyId: string+): Promise<string> {+ if (isKysely(db)) {+ const row = await db+ .selectFrom("location")+ .select("timezone")+ .where("id", "=", locationId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ return row?.timezone || getCompanyTimeZone(db, companyId);+ }+ const location = await db+ .from("location")+ .select("timezone")+ .eq("id", locationId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (location.error) {+ throw new Error(+ `Failed to resolve location timezone: ${location.error.message}`+ );+ }+ return location.data?.timezone || getCompanyTimeZone(db, companyId);+}++/**+ * The timezone a location DEFINES ITSELF, or null when it inherits the+ * company's (missing row, null, or legacy empty-string value). For callers+ * that must distinguish own-vs-inherited — e.g. the ERP Redis cache, which+ * must never store an inherited company timezone under a location key.+ */+export async function getLocationOwnTimeZone(+ db: AnyPostgresClient,+ locationId: string,+ companyId: string+): Promise<string | null> {+ if (isKysely(db)) {+ const row = await db+ .selectFrom("location")+ .select("timezone")+ .where("id", "=", locationId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ return row?.timezone || null;+ }+ const location = await db+ .from("location")+ .select("timezone")+ .eq("id", locationId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (location.error) {+ throw new Error(+ `Failed to resolve location timezone: ${location.error.message}`+ );+ }+ return location.data?.timezone || null;+}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 593d65a3cd..f93d3e2bce 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -6113,6 +6113,7 @@ export type Database = {stateProvince: string | nullsuggestionNotificationGroup: string[]taxId: string | null+ timezone: stringupdatedBy: string | nullvatNumber: string | nullwebsite: string | null@@ -6150,6 +6151,7 @@ export type Database = {stateProvince?: string | nullsuggestionNotificationGroup?: string[]taxId?: string | null+ timezone?: stringupdatedBy?: string | nullvatNumber?: string | nullwebsite?: string | null@@ -6187,6 +6189,7 @@ export type Database = {stateProvince?: string | nullsuggestionNotificationGroup?: string[]taxId?: string | null+ timezone?: stringupdatedBy?: string | nullvatNumber?: string | nullwebsite?: string | null@@ -59135,6 +59138,7 @@ export type Database = {stateProvince: string | nullsuggestionNotificationGroup: string[] | nulltaxId: string | null+ timezone: string | nullupdatedBy: string | nulluserId: string | nullvatNumber: string | null@@ -70156,21 +70160,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -74066,6 +74070,7 @@ export type Database = {Args: { operation_id: string }Returns: boolean}+ company_today: { Args: { p_company_id: string }; Returns: string }complete_job_to_inventory: {Args: {p_company_id?: string@@ -75797,6 +75802,13 @@ export type Database = {supplierQuotes: Json}[]}+ get_timezone_names: {+ Args: never+ Returns: {+ name: string+ utcOffset: string+ }[]+ }get_tool_details: {Args: { item_id: string }Returns: {@@ -76035,6 +76047,7 @@ export type Database = {Args: { operation_id: string }Returns: boolean}+ is_valid_timezone: { Args: { tz: string }; Returns: boolean }items_search: {Args: {match_count: number@@ -76061,6 +76074,10 @@ export type Database = {}[]}jsonb_to_text_array: { Args: { "": Json }; Returns: string[] }+ location_today: {+ Args: { p_company_id: string; p_location_id: string }+ Returns: string+ }matchIntercompanyTransactions: {Args: { p_company_group_id: string }Returns: {diff --git a/packages/database/src/utils.ts b/packages/database/src/utils.tsindex 0a64684dab..27b1c1e3cd 100644--- a/packages/database/src/utils.ts+++ b/packages/database/src/utils.ts@@ -4,8 +4,27 @@ import type {PostgrestFilterBuilder} from "@supabase/postgrest-js";import type { SupabaseClient } from "@supabase/supabase-js";+import type { Kysely } from "kysely";+import type { KyselyDatabase } from "./client.ts";import type { Database } from "./types.ts";+/**+ * Either data-access handle a helper might receive: a Supabase client or a+ * Kysely handle (a `Kysely` instance or an active `Transaction`). Use it to+ * overload a helper that some callers reach with a client and others with+ * Kysely, instead of maintaining two near-identical `*Db` twins.+ */+export type AnyPostgresClient =+ | SupabaseClient<Database>+ | Kysely<KyselyDatabase>;++/**+ * Runtime guard narrowing {@link AnyPostgresClient} to the Kysely handle. Kysely+ * exposes `.selectFrom`; the Supabase client does not.+ */+export const isKysely = (db: AnyPostgresClient): db is Kysely<KyselyDatabase> =>+ typeof (db as Kysely<KyselyDatabase>).selectFrom === "function";+const BATCH_SIZE = 1000;export type PaginatedResult<T> =diff --git a/packages/database/supabase/functions/close-job/index.ts b/packages/database/supabase/functions/close-job/index.tsindex ab30f33ce2..ec1dfb7482 100644--- a/packages/database/supabase/functions/close-job/index.ts+++ b/packages/database/supabase/functions/close-job/index.ts@@ -1,8 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import z from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { requirePermissions } from "../lib/supabase.ts";import { credit, debit, journalReference } from "../lib/utils.ts";@@ -24,12 +24,12 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const { jobId, userId, companyId } = payloadValidator.parse(payload);const client = await requirePermissions(req, companyId, userId, { update: "production" });+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const [accountingSettings, companyRecord] = await Promise.all([client@@ -139,7 +139,8 @@ serve(async (req: Request) => {const accountingPeriodId = await getCurrentAccountingPeriod(client,companyId,- trx+ trx,+ today);const journalEntryId = await getNextSequence(diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.tsindex ca74324376..1d09304cd0 100644--- a/packages/database/supabase/functions/convert/index.ts+++ b/packages/database/supabase/functions/convert/index.ts@@ -1,12 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import {- getLocalTimeZone,- now,- toCalendarDate,-} from "npm:@internationalized/date";import { z } from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { format } from "https://deno.land/[email protected]/datetime/format.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";@@ -371,7 +367,7 @@ serve(async (req: Request) => {locationId: purchaseOrderDelivery.data.locationId,paymentTermId: purchaseOrderPayment.data.paymentTermId,currencyCode: purchaseOrder.data.currencyCode ?? "USD",- dateIssued: new Date().toISOString().split("T")[0],+ dateIssued: datetime.today(await getCompanyTimeZone(client, companyId)).toString(),exchangeRate: purchaseOrder.data.exchangeRate ?? 1,subtotal: uninvoicedSubtotal ?? 0,supplierInteractionId: purchaseOrder.data.supplierInteractionId,@@ -526,7 +522,7 @@ serve(async (req: Request) => {let insertedSalesOrderId = "";await db.transaction().execute(async (trx) => {- const today = format(new Date(), "yyyy-MM-dd");+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const salesOrderId = await getNextSequence(trx,"salesOrder",@@ -864,7 +860,7 @@ serve(async (req: Request) => {locationId: salesOrderShipment.data.locationId,paymentTermId: salesOrderPayment.data.paymentTermId,currencyCode: salesOrder.data.currencyCode ?? "USD",- dateIssued: new Date().toISOString().split("T")[0],+ dateIssued: datetime.today(await getCompanyTimeZone(client, companyId)).toString(),exchangeRate: salesOrder.data.exchangeRate ?? 1,subtotal: uninvoicedSubtotal ?? 0,opportunityId: salesOrder.data.opportunityId,@@ -1147,9 +1143,9 @@ serve(async (req: Request) => {customerLocationId: salesRfq.data?.customerLocationId,customerReference: salesRfq.data?.customerReference,locationId: salesRfq.data?.locationId,- expirationDate: toCalendarDate(- now(getLocalTimeZone()).add({ days: 30 })- ).toString(),+ expirationDate: datetime.today(+ await getCompanyTimeZone(client, companyId)+ ).add({ days: 30 }).toString(),salesPersonId: salesRfq.data?.salesPersonId ?? userId,status: "Draft",externalNotes: salesRfq.data?.externalNotes,@@ -1453,7 +1449,7 @@ serve(async (req: Request) => {locationId: salesOrderShipment.data.locationId,paymentTermId: salesOrderPayment.data.paymentTermId,currencyCode: salesOrder.data.currencyCode ?? "USD",- dateIssued: new Date().toISOString().split("T")[0],+ dateIssued: datetime.today(await getCompanyTimeZone(client, companyId)).toString(),exchangeRate: salesOrder.data.exchangeRate ?? 1,subtotal: uninvoicedSubtotal ?? 0,opportunityId: salesOrder.data.opportunityId,diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.tsindex f29fb09429..4cfa796f93 100644--- a/packages/database/supabase/functions/create/index.ts+++ b/packages/database/supabase/functions/create/index.ts@@ -1,6 +1,7 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import z from "npm:zod@^3.24.1";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";@@ -2567,7 +2568,7 @@ serve(async (req: Request) => {.insertInto("journal").values({journalEntryId,- postingDate: new Date().toISOString().split("T")[0],+ postingDate: datetime.today(await getCompanyTimeZone(client, companyId)).toString(),companyId,sourceType: "Manual",status: "Draft",diff --git a/packages/database/supabase/functions/deno.json b/packages/database/supabase/functions/deno.jsonindex 18c5494fca..4c25f88fa4 100644--- a/packages/database/supabase/functions/deno.json+++ b/packages/database/supabase/functions/deno.json@@ -5,6 +5,7 @@"check:response": "deno check --no-lock lib/response.ts lib/response.test.ts"},"imports": {+ "@internationalized/date": "npm:@internationalized/[email protected]","kysely": "npm:[email protected]","pg": "https://deno.land/x/[email protected]/mod.ts","@supabase/supabase-js": "npm:@supabase/[email protected]",diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 2e3eb39ebc..aa3cb9a696 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -8,15 +8,11 @@ import type {} from "@supabase/supabase-js";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { requirePermissions } from "../lib/supabase.ts";import type { Database } from "../lib/types.ts";import { Transaction } from "kysely";-import {- getLocalTimeZone,- now,- toCalendarDate,-} from "npm:@internationalized/date";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import {calculateQuoteLinePrices,@@ -5662,9 +5658,9 @@ serve(async (req: Request) => {customerLocationId: sourceQuote.data?.customerLocationId,customerReference: sourceQuote.data?.customerReference,locationId: sourceQuote.data?.locationId,- expirationDate: toCalendarDate(- now(getLocalTimeZone()).add({ days: 30 })- ).toString(),+ expirationDate: datetime.today(+ await getCompanyTimeZone(client, companyId)+ ).add({ days: 30 }).toString(),salesPersonId: sourceQuote.data?.salesPersonId ?? userId,status: "Draft",externalNotes: sourceQuote.data?.externalNotes,diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.tsindex 1c700e2220..63c63f66ef 100644--- a/packages/database/supabase/functions/issue/index.ts+++ b/packages/database/supabase/functions/issue/index.ts@@ -1,9 +1,10 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { getLocalTimeZone, parseDate, today } from "npm:@internationalized/date";+import { type CalendarDate, parseDate } from "@internationalized/date";import { Transaction } from "kysely";import { z } from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";@@ -67,13 +68,13 @@ async function getExpiredEntityPolicy(function checkExpiredEntities(entities: { id: string; expirationDate: string | null }[],policy: ExpiredEntityPolicy,- override: { allowed: boolean; reason: string | null }+ override: { allowed: boolean; reason: string | null },+ today: CalendarDate): { ok: true; warning?: string } | { ok: false; reason: string } {- const todayLocal = today(getLocalTimeZone());const expired = entities.filter((e) => {if (!e.expirationDate) return false;try {- return parseDate(e.expirationDate).compare(todayLocal) < 0;+ return parseDate(e.expirationDate).compare(today) < 0;} catch {return false;}@@ -200,6 +201,13 @@ async function issueJobOperationMaterials(items.map((item) => [item.id, item.itemTrackingType === "Inventory"]));+ // Company business day — item/cost ledgers and this function's journals must+ // all post on the same day (they previously relied on the CURRENT_DATE default,+ // which is UTC and diverged from the company-TZ journals here).+ const today = datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString();+const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =[];@@ -295,6 +303,7 @@ async function issueJobOperationMaterials(quantity: -quantityToIssue,locationId: job.locationId,storageUnitId: finalStorageUnitId,+ postingDate: today,createdBy: userId,});}@@ -425,6 +434,7 @@ async function issueJobOperationMaterials(quantity: -materialQuantity,cost: -cogsResult.totalCost,remainingQuantity: 0,+ postingDate: today,companyId,}).execute();@@ -439,7 +449,9 @@ async function issueJobOperationMaterials(}if (journalLineInserts.length > 0) {- const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, trx);+ // Resolve the period from the SAME hoisted `today` the ledger rows used —+ // a midnight rollover mid-transaction must not split journal and ledger.+ const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, trx, today);const journalEntryId = await getNextSequence(trx, "journalEntry", companyId);const journalResult = await trx@@ -448,7 +460,7 @@ async function issueJobOperationMaterials(journalEntryId,accountingPeriodId,description: `Material Issue to Job ${job?.jobId ?? jobId}`,- postingDate: new Date().toISOString().slice(0, 10),+ postingDate: today,companyId,sourceType: "Job Consumption",status: "Posted",@@ -544,6 +556,12 @@ async function createMaterialWipEntries(client, db, companyId, userId,} = args;+ // Cost layer posts on the company business day, matching the caller's+ // itemLedger movement (was defaulting to CURRENT_DATE = UTC).+ const today = datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString();+const journalLineInserts: {accountId: string;description: string;@@ -683,6 +701,7 @@ async function createMaterialWipEntries(quantity: isConsumption ? -absQty : absQty,cost: isConsumption ? -cost : cost,remainingQuantity: 0,+ postingDate: today,companyId,}).execute();@@ -698,7 +717,8 @@ async function createMaterialWipEntries(if (journalLineInserts.length === 0) return;- const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, trx);+ // Same hoisted `today` as this function's ledger rows (see above).+ const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, trx, today);const journalEntryId = await getNextSequence(trx, "journalEntry", companyId);const journalResult = await trx@@ -707,7 +727,7 @@ async function createMaterialWipEntries(journalEntryId,accountingPeriodId,description,- postingDate: new Date().toISOString().slice(0, 10),+ postingDate: today,companyId,sourceType: "Job Consumption",status: "Posted",@@ -1881,6 +1901,7 @@ serve(async (req: Request) => {}const client = await requirePermissions(req, companyId, userId, { update: "production" });+ const companyToday = datetime.today(await getCompanyTimeZone(client, companyId));const [accountingSettingsTracked, companyRecordTracked] = await Promise.all([client@@ -1954,7 +1975,8 @@ serve(async (req: Request) => {expirationDate: e.expirationDate,})),expiredPolicy,- { allowed: !!overrideExpired, reason: overrideReason ?? null }+ { allowed: !!overrideExpired, reason: overrideReason ?? null },+ companyToday);if (!expiredCheck.ok) {throw new Error(expiredCheck.reason);@@ -2243,7 +2265,7 @@ serve(async (req: Request) => {itemLedgerItemId: trackedEntity.sourceDocumentId,companyId,userId,- postingDate: new Date().toISOString().slice(0, 10),+ postingDate: companyToday.toString(),// Created Available; the shared status update below flips the// child to Consumed in the same transaction.childStatus: "Available",@@ -3037,6 +3059,7 @@ serve(async (req: Request) => {}let expiredWarning: string | undefined;+ const companyToday = datetime.today(await getCompanyTimeZone(db, companyId));const splitEntities = await db.transaction().execute(async (trx) => {// Get the maintenance dispatch to find the location@@ -3107,7 +3130,8 @@ serve(async (req: Request) => {expirationDate: e.expirationDate,})),expiredPolicy,- { allowed: !!overrideExpired, reason: overrideReason ?? null }+ { allowed: !!overrideExpired, reason: overrideReason ?? null },+ companyToday);if (!expiredCheck.ok) {throw new Error(expiredCheck.reason);@@ -3222,7 +3246,7 @@ serve(async (req: Request) => {itemLedgerItemId: trackedEntity.sourceDocumentId,companyId,userId,- postingDate: new Date().toISOString().slice(0, 10),+ postingDate: companyToday.toString(),// Created Available; the shared status update below flips the// child to Consumed in the same transaction.childStatus: "Available"diff --git a/packages/database/supabase/functions/lib/datetime.ts b/packages/database/supabase/functions/lib/datetime.tsnew file mode 100644index 0000000000..ee165d6505--- /dev/null+++ b/packages/database/supabase/functions/lib/datetime.ts@@ -0,0 +1,132 @@+// Deno mirror of packages/utils/src/datetime.ts — edge functions cannot import+// workspace packages, so the ~40-line module is duplicated with the same API.+// Keep the two files in sync. One deliberate delta: the Node copy also has+// `weekBounds` (payroll/timecard week windows) — no edge function needs it+// yet; mirror it in when one does.+import {+ type CalendarDate,+ now,+ parseAbsolute,+ toCalendarDate,+ today+} from "@internationalized/date";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { Kysely } from "kysely";+import type { DB } from "./database.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. Delegates to the single algorithm in ./utils.ts.+ */+function weekNumber(date: CalendarDate): number {+ return isoWeekFromYmd(date.year, date.month, date.day);+}++/**+ * The one sanctioned way to derive dates and times in edge functions.+ *+ * Every derivation method takes a mandatory IANA timezone — resolved from+ * `company.timezone` (ledger-scoped: accounting periods, posting dates,+ * sequence date tokens) or `location.timezone` (operational: scheduling,+ * shifts, MES) — so "which calendar day is it?" is never answered implicitly+ * by the process timezone.+ */+export const datetime = {+ /** UTC instant string for timestamp columns (createdAt/updatedAt). The only timezone-free method. */+ timestamp: () => new Date().toISOString(),++ /** Current moment as a ZonedDateTime in the given business timezone. */+ now: (tz: string) => now(tz),++ /** Today as a CalendarDate in the given business timezone. */+ today: (tz: string) => today(tz),++ /** The business day a stored UTC instant falls on in the given timezone. */+ businessDay: (instant: string, tz: string) =>+ toCalendarDate(parseAbsolute(instant, tz)),++ weekNumber+};++// Both resolvers accept EITHER a Supabase client (request handlers) or a Kysely+// handle (transaction-only functions with no client) via AnyPostgresClient/isKysely.+// Pass the active `trx` when resolving inside a Kysely transaction — the pool is+// size 1, so reading via the module `db` while a `trx` holds the connection would+// deadlock; the Supabase client is a separate connection and is always safe.++/** Ledger-scoped timezone: one calendar per set of books. Falls back to UTC. */+export function getCompanyTimeZone(+ db: SupabaseClient<Database>,+ companyId: string+): Promise<string>;+export function getCompanyTimeZone(+ db: Kysely<DB>,+ companyId: string+): Promise<string>;+export async function getCompanyTimeZone(+ db: AnyPostgresClient,+ companyId: string+): Promise<string> {+ if (isKysely(db)) {+ const row = await db+ .selectFrom("company")+ .select("timezone")+ .where("id", "=", companyId)+ .executeTakeFirst();+ return row?.timezone ?? "UTC";+ }+ const company = await db+ .from("company")+ .select("timezone")+ .eq("id", companyId)+ .maybeSingle();+ // A failed read must not silently become a (wrong) business calendar —+ // fall back to UTC only when the query succeeded and found nothing.+ if (company.error) {+ throw new Error(+ `Failed to resolve company timezone: ${company.error.message}`+ );+ }+ return company.data?.timezone ?? "UTC";+}++/** Operational timezone of a physical site. Falls back to the company timezone. */+export function getLocationTimeZone(+ db: SupabaseClient<Database>,+ locationId: string,+ companyId: string+): Promise<string>;+export function getLocationTimeZone(+ db: Kysely<DB>,+ locationId: string,+ companyId: string+): Promise<string>;+export async function getLocationTimeZone(+ db: AnyPostgresClient,+ locationId: string,+ companyId: string+): Promise<string> {+ if (isKysely(db)) {+ const row = await db+ .selectFrom("location")+ .select("timezone")+ .where("id", "=", locationId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ return row?.timezone || getCompanyTimeZone(db, companyId);+ }+ const location = await db+ .from("location")+ .select("timezone")+ .eq("id", locationId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (location.error) {+ throw new Error(+ `Failed to resolve location timezone: ${location.error.message}`+ );+ }+ return location.data?.timezone || getCompanyTimeZone(db, companyId);+}diff --git a/packages/database/supabase/functions/lib/scheduling/date-calculator.ts b/packages/database/supabase/functions/lib/scheduling/date-calculator.tsindex f4d73c460d..97cfc06236 100644--- a/packages/database/supabase/functions/lib/scheduling/date-calculator.ts+++ b/packages/database/supabase/functions/lib/scheduling/date-calculator.ts@@ -9,6 +9,12 @@ import type {SchedulingDirection,} from "./types.ts";+// All Date math in this module is UTC-based pure calendar arithmetic on+// "yyyy-MM-dd" strings — date-only strings parse as UTC midnight, so UTC+// getters keep the walk independent of the process timezone. The only+// wall-clock input is `today`, which the engine derives in the job location's+// timezone.+/*** Subtract business days from a date (skips weekends)*/@@ -17,9 +23,9 @@ function subtractBusinessDays(date: Date, days: number): Date {let remainingDays = days;while (remainingDays > 0) {- result.setDate(result.getDate() - 1);+ result.setUTCDate(result.getUTCDate() - 1);// Skip weekends (0 = Sunday, 6 = Saturday)- const dayOfWeek = result.getDay();+ const dayOfWeek = result.getUTCDay();if (dayOfWeek !== 0 && dayOfWeek !== 6) {remainingDays--;}@@ -36,9 +42,9 @@ function addBusinessDays(date: Date, days: number): Date {let remainingDays = days;while (remainingDays > 0) {- result.setDate(result.getDate() + 1);+ result.setUTCDate(result.getUTCDate() + 1);// Skip weekends (0 = Sunday, 6 = Saturday)- const dayOfWeek = result.getDay();+ const dayOfWeek = result.getUTCDay();if (dayOfWeek !== 0 && dayOfWeek !== 6) {remainingDays--;}@@ -54,13 +60,6 @@ function formatDate(date: Date): string {return date.toISOString().split("T")[0];}-/**- * Get today's date as ISO string- */-function getTodayString(): string {- return formatDate(new Date());-}-/*** Interface for scheduling strategy*/@@ -69,7 +68,8 @@ export interface SchedulingStrategy {operations: BaseOperation[],operationMap: Map<string, BaseOperation>,graph: DependencyGraph,- anchorDate: string | null+ anchorDate: string | null,+ today: string): Map<string, ScheduledOperation>;}@@ -81,10 +81,10 @@ export class BackwardSchedulingStrategy implements SchedulingStrategy {_operations: BaseOperation[],operationMap: Map<string, BaseOperation>,graph: DependencyGraph,- jobDueDate: string | null+ jobDueDate: string | null,+ today: string): Map<string, ScheduledOperation> {const scheduled = new Map<string, ScheduledOperation>();- const today = getTodayString();const finalDueDate = jobDueDate || today;// Topological sort in reverse order (leaf nodes first)@@ -244,10 +244,10 @@ export class ForwardSchedulingStrategy implements SchedulingStrategy {_operations: BaseOperation[],operationMap: Map<string, BaseOperation>,graph: DependencyGraph,- jobStartDate: string | null+ jobStartDate: string | null,+ today: string): Map<string, ScheduledOperation> {const scheduled = new Map<string, ScheduledOperation>();- const today = getTodayString();const startDate = jobStartDate || today;// Topological sort in forward order (root nodes first)@@ -380,6 +380,7 @@ export function calculateOperationDates(operations: BaseOperation[],graph: DependencyGraph,anchorDate: string | null,+ today: string,direction: SchedulingDirection = "backward"): Map<string, ScheduledOperation> {// Build operation map for quick lookup@@ -391,7 +392,13 @@ export function calculateOperationDates(}const strategy = getSchedulingStrategy(direction);- return strategy.calculateDates(operations, operationMap, graph, anchorDate);+ return strategy.calculateDates(+ operations,+ operationMap,+ graph,+ anchorDate,+ today+ );}-export { addBusinessDays, formatDate, getTodayString, subtractBusinessDays };+export { addBusinessDays, formatDate, subtractBusinessDays };diff --git a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.tsindex 404e205a23..466280653d 100644--- a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts+++ b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts@@ -6,6 +6,7 @@ import {AssemblyHandler,buildMakeMethodDependencies,} from "./assembly-handler.ts";+import { datetime, getCompanyTimeZone, getLocationTimeZone } from "../datetime.ts";import { calculateOperationDates } from "./date-calculator.ts";import {buildOperationDependencies,@@ -54,6 +55,7 @@ export class SchedulingEngine {private affectedWorkCenters: Set<string> = new Set();private assemblyDepth: number = 0;private conflictsDetected: number = 0;+ private timezone: string = "UTC";private assemblyHandler: AssemblyHandler;private workCenterSelector: WorkCenterSelector | null = null;@@ -98,6 +100,12 @@ export class SchedulingEngine {this.job = job;+ // "Today" (conflict detection, fallback anchor) follows the job site's+ // wall clock — scheduling is operational, not ledger-scoped.+ this.timezone = job.locationId+ ? await getLocationTimeZone(this.db, job.locationId, this.companyId)+ : await getCompanyTimeZone(this.db, this.companyId);+// Initialize work center selector with locationif (job.locationId) {this.workCenterSelector = new WorkCenterSelector(@@ -424,6 +432,7 @@ export class SchedulingEngine {this.operations,graph,anchorDate,+ datetime.today(this.timezone).toString(),this.direction);diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 593d65a3cd..f93d3e2bce 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -6113,6 +6113,7 @@ export type Database = {stateProvince: string | nullsuggestionNotificationGroup: string[]taxId: string | null+ timezone: stringupdatedBy: string | nullvatNumber: string | nullwebsite: string | null@@ -6150,6 +6151,7 @@ export type Database = {stateProvince?: string | nullsuggestionNotificationGroup?: string[]taxId?: string | null+ timezone?: stringupdatedBy?: string | nullvatNumber?: string | nullwebsite?: string | null@@ -6187,6 +6189,7 @@ export type Database = {stateProvince?: string | nullsuggestionNotificationGroup?: string[]taxId?: string | null+ timezone?: stringupdatedBy?: string | nullvatNumber?: string | nullwebsite?: string | null@@ -59135,6 +59138,7 @@ export type Database = {stateProvince: string | nullsuggestionNotificationGroup: string[] | nulltaxId: string | null+ timezone: string | nullupdatedBy: string | nulluserId: string | nullvatNumber: string | null@@ -70156,21 +70160,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -74066,6 +74070,7 @@ export type Database = {Args: { operation_id: string }Returns: boolean}+ company_today: { Args: { p_company_id: string }; Returns: string }complete_job_to_inventory: {Args: {p_company_id?: string@@ -75797,6 +75802,13 @@ export type Database = {supplierQuotes: Json}[]}+ get_timezone_names: {+ Args: never+ Returns: {+ name: string+ utcOffset: string+ }[]+ }get_tool_details: {Args: { item_id: string }Returns: {@@ -76035,6 +76047,7 @@ export type Database = {Args: { operation_id: string }Returns: boolean}+ is_valid_timezone: { Args: { tz: string }; Returns: boolean }items_search: {Args: {match_count: number@@ -76061,6 +76074,10 @@ export type Database = {}[]}jsonb_to_text_array: { Args: { "": Json }; Returns: string[] }+ location_today: {+ Args: { p_company_id: string; p_location_id: string }+ Returns: string+ }matchIntercompanyTransactions: {Args: { p_company_group_id: string }Returns: {diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.tsindex ecf18994a6..0be961bf07 100644--- a/packages/database/supabase/functions/lib/utils.ts+++ b/packages/database/supabase/functions/lib/utils.ts@@ -1,3 +1,30 @@+// Bare specifier on purpose: Deno resolves it through the deno.json import map+// (like kysely), and the node-side @carbon/database build — which reaches this+// file via shared/get-next-sequence.ts — resolves it from node_modules.+import { CalendarDate, getDayOfWeek, now } from "@internationalized/date";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { Kysely } from "kysely";+// Type-only import from postgres/index.ts (not lib/database.ts) keeps the+// Deno-only driver out of the graph — this file is reached from the node-side+// @carbon/database build via shared/get-next-sequence.ts.+import type { KyselyDatabase as DB } from "./postgres/index.ts";+import type { Database } from "./types.ts";++/**+ * Either data-access handle an edge function might hold: a Supabase client+ * (request handlers) or a Kysely handle — the module `db` or an active `trx`.+ * Use it to overload a helper that some callers reach with a client and others+ * with Kysely, instead of maintaining two near-identical `*Db` twins.+ */+export type AnyPostgresClient = SupabaseClient<Database> | Kysely<DB>;++/**+ * Runtime guard narrowing {@link AnyPostgresClient} to the Kysely handle. Kysely+ * exposes `.selectFrom`; the Supabase client does not.+ */+export const isKysely = (db: AnyPostgresClient): db is Kysely<DB> =>+ typeof (db as Kysely<DB>).selectFrom === "function";+export interface TrackedEntityAttributes {"Batch Number"?: string;Customer?: string;@@ -17,31 +44,45 @@ export interface TrackedEntityAttributes {Shelf?: string;}-// 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())+// 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. Pure calendar arithmetic: en-GB is Monday-first, so+// getDayOfWeek gives Mon=0…Sun=6 and `3 - dow` lands on the week's Thursday;+// CalendarDate.compare returns whole days.+export const isoWeekFromYmd = (+ year: number,+ month: number,+ day: number+): number => {+ const date = new CalendarDate(year, month, day);+ const thursday = date.add({ days: 3 - getDayOfWeek(date, "en-GB") });+ return (+ Math.floor(+ thursday.compare(new CalendarDate(thursday.year, 1, 1)) / 7+ ) + 1);- 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);};-// used to generate sequences-export const interpolateSequenceDate = (value?: string | null) => {+// 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+export const interpolateSequenceDate = (+ value?: string | null,+ timezone = "UTC"+) => {// replace all instances of %{year} with the current yearif (!value) return "";let result = value;if (result.includes("%{")) {- const date = new Date();- const year = date.getFullYear();- const month = date.getMonth() + 1;- const day = date.getDate();- const hours = date.getHours();- const seconds = date.getSeconds();- const week = getISOWeek(date);+ const {+ year,+ month,+ day,+ hour: hours,+ second: seconds+ } = now(timezone);+ const week = isoWeekFromYmd(year, month, day);result = result.replace(/%{yyyy}/g, year.toString());result = result.replace(/%{yy}/g, year.toString().slice(-2));@@ -59,9 +100,13 @@ export const interpolateSequenceDate = (value?: string | null) => {// job-context %{location} token (location.code, falling back to location.name).export const interpolateSerialNumber = (value: string | null | undefined,- context: { locationCode?: string | null; locationName?: string | null }+ context: {+ locationCode?: string | null;+ locationName?: string | null;+ timezone?: string;+ }) => {- const withDates = interpolateSequenceDate(value);+ const withDates = interpolateSequenceDate(value, context.timezone);if (!withDates.includes("%{location}")) return withDates;const location = (context.locationCode ?? context.locationName ?? "").trim();return withDates.replace(/%{location}/g, location);diff --git a/packages/database/supabase/functions/mrp/index.ts b/packages/database/supabase/functions/mrp/index.tsindex 1d8a05a167..087f9b7082 100644--- a/packages/database/supabase/functions/mrp/index.ts+++ b/packages/database/supabase/functions/mrp/index.ts@@ -1,12 +1,11 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";import {- getLocalTimeZone,- today as getToday,parseDate,startOfWeek,type CalendarDate,-} from "npm:@internationalized/date";+} from "@internationalized/date";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import {explodeBom,splitKey,@@ -81,7 +80,7 @@ serve(async (req: Request) => {console.log({ function: "mrp", type, companyId, userId });- const today = getToday(getLocalTimeZone());+ const today = datetime.today(await getCompanyTimeZone(db, companyId));const ranges = getStartAndEndDates(today, "Week");const periods = await getOrCreateDemandPeriods(db, ranges, "Week");diff --git a/packages/database/supabase/functions/post-inventory-adjustment/index.ts b/packages/database/supabase/functions/post-inventory-adjustment/index.tsindex eb250df732..90161ef0c9 100644--- a/packages/database/supabase/functions/post-inventory-adjustment/index.ts+++ b/packages/database/supabase/functions/post-inventory-adjustment/index.ts@@ -3,6 +3,7 @@ import { serve } from "https://deno.land/[email protected]/http/server.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";import { Transaction } from "kysely";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { getFunctionLogger } from "../lib/logging.ts";import { requirePermissions } from "../lib/supabase.ts";@@ -71,7 +72,7 @@ serve(async (req: Request) => {update: "inventory",});- const today = format(new Date(), "yyyy-MM-dd");+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const nowIso = new Date().toISOString();const [@@ -168,7 +169,7 @@ serve(async (req: Request) => {// getCurrentAccountingPeriod uses the REST client and calling it// mid-transaction parks the (size 1) pool in idle-in-transaction.const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;const accounting =accountingEnabled && accountDefaults?.data && accountingPeriodIddiff --git a/packages/database/supabase/functions/post-inventory-count/index.ts b/packages/database/supabase/functions/post-inventory-count/index.tsindex 336bdcfd01..aa7060358c 100644--- a/packages/database/supabase/functions/post-inventory-count/index.ts+++ b/packages/database/supabase/functions/post-inventory-count/index.ts@@ -1,7 +1,7 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { getFunctionLogger } from "../lib/logging.ts";import { requirePermissions } from "../lib/supabase.ts";@@ -73,7 +73,7 @@ serve(async (req: Request) => {update: "inventory"});- const today = format(new Date(), "yyyy-MM-dd");+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const nowIso = new Date().toISOString();const inventoryCount = await client@@ -191,7 +191,7 @@ serve(async (req: Request) => {throw new Error("Error getting account defaults");}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;// Active dimensions for the company group (post-shipment precedent) —diff --git a/packages/database/supabase/functions/post-memo/index.ts b/packages/database/supabase/functions/post-memo/index.tsindex 1db76f1165..6f1c519b36 100644--- a/packages/database/supabase/functions/post-memo/index.ts+++ b/packages/database/supabase/functions/post-memo/index.ts@@ -1,8 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import z from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { getSupabaseServiceRole } from "../lib/supabase.ts";@@ -26,7 +26,6 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const { type, memoId, userId, companyId } = payloadValidator.parse(payload);@@ -38,6 +37,7 @@ serve(async (req: Request) => {req.headers.get("carbon-key") ?? "",companyId);+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const accountingSettings = await client.from("companySettings")@@ -70,7 +70,7 @@ serve(async (req: Request) => {}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;await db.transaction().execute(async (trx) => {@@ -209,7 +209,7 @@ serve(async (req: Request) => {}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;// Build the (balanced, two-line) journal in base currency. Account-iddiff --git a/packages/database/supabase/functions/post-nonconformance/index.ts b/packages/database/supabase/functions/post-nonconformance/index.tsindex 92850df900..b4c15b5d68 100644--- a/packages/database/supabase/functions/post-nonconformance/index.ts+++ b/packages/database/supabase/functions/post-nonconformance/index.ts@@ -1,7 +1,7 @@-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { serve } from "https://deno.land/[email protected]/http/server.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { getFunctionLogger } from "../lib/logging.ts";import { requirePermissions } from "../lib/supabase.ts";@@ -71,7 +71,7 @@ serve(async (req: Request) => {update: "quality",});- const postingDate = providedPostingDate || format(new Date(), "yyyy-MM-dd");+ const postingDate = providedPostingDate || datetime.today(await getCompanyTimeZone(client, companyId)).toString();// Only movements that actually move stock post anything.const effectiveMovements = movements.filter((m) => m.quantity !== 0);@@ -174,7 +174,7 @@ serve(async (req: Request) => {// getCurrentAccountingPeriod uses the REST client and calling it// mid-transaction parks the (size 1) pool in idle-in-transaction.const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, postingDate): null;const journalDescription =diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.tsindex 8d05a5a668..1fbb3ff687 100644--- a/packages/database/supabase/functions/post-payment/index.ts+++ b/packages/database/supabase/functions/post-payment/index.ts@@ -1,8 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import z from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { getSupabaseServiceRole } from "../lib/supabase.ts";@@ -30,7 +30,6 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const { type, paymentId, userId, companyId } =@@ -43,6 +42,7 @@ serve(async (req: Request) => {req.headers.get("carbon-key") ?? "",companyId);+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const accountingSettings = await client.from("companySettings")@@ -85,7 +85,7 @@ serve(async (req: Request) => {}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;await db.transaction().execute(async (trx) => {@@ -289,7 +289,7 @@ serve(async (req: Request) => {// Build journal lines (in base currency)// --------------------------------------------------------------const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;const journalLineInserts: PaymentJournalLine[] = [];diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.tsindex 4ba56650dd..030116affe 100644--- a/packages/database/supabase/functions/post-picking/index.ts+++ b/packages/database/supabase/functions/post-picking/index.ts@@ -1,10 +1,9 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";-import { getLocalTimeZone, today as getToday } from "npm:@internationalized/date";import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";import { sql } from "kysely";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import type { Database } from "../lib/types.ts";import { resolveTrackedEntityBin } from "../issue/resolve-tracked-entity-bin.ts";@@ -119,11 +118,10 @@ serve(async (req: Request) => {const preflight = corsPreflight(req);if (preflight) return preflight;- const today = format(getToday(getLocalTimeZone()).toDate(getLocalTimeZone()), "yyyy-MM-dd");-try {const payload = await req.json();const validatedPayload = payloadValidator.parse(payload);+ const today = datetime.today(await getCompanyTimeZone(db, validatedPayload.companyId)).toString();let splitEntityId: string | undefined;switch (validatedPayload.type) {diff --git a/packages/database/supabase/functions/post-production-event/index.ts b/packages/database/supabase/functions/post-production-event/index.tsindex e8b2a0a355..eb789740c5 100644--- a/packages/database/supabase/functions/post-production-event/index.ts+++ b/packages/database/supabase/functions/post-production-event/index.ts@@ -1,8 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import z from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { requirePermissions } from "../lib/supabase.ts";@@ -28,13 +28,13 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const { productionEventId, userId, companyId, reverse } =payloadValidator.parse(payload);const client = await requirePermissions(req, companyId, userId, { update: "production" });+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const [accountingSettings, companyRecord] = await Promise.all([client@@ -296,7 +296,8 @@ serve(async (req: Request) => {const accountingPeriodId = await getCurrentAccountingPeriod(client,companyId,- db+ db,+ today);await db.transaction().execute(async (trx) => {diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsindex 4f61351235..14c4f6548c 100644--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts@@ -1,8 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import z from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { requirePermissions } from "../lib/supabase.ts";import type { Database } from "../lib/types.ts";@@ -39,7 +39,6 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const { type, invoiceId, userId, companyId, skipReceiptPost } =@@ -53,6 +52,7 @@ serve(async (req: Request) => {skipReceiptPost,});const client = await requirePermissions(req, companyId, userId, { update: "invoicing" });+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const accountingEnabled = await client.from("companySettings")@@ -328,10 +328,11 @@ serve(async (req: Request) => {cost: -entry.cost,supplierId: entry.supplierId,companyId,+ postingDate: today,}));const accountingPeriodIdVoid = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;await db.transaction().execute(async (trx) => {@@ -440,6 +441,7 @@ serve(async (req: Request) => {remainingQuantity: child.remainingQuantity,supplierId: child.supplierId,companyId,+ postingDate: today,}).execute();}@@ -474,6 +476,7 @@ serve(async (req: Request) => {remainingQuantity: 0,supplierId: layer.supplierId,companyId,+ postingDate: today,}).execute();await trx@@ -909,6 +912,7 @@ serve(async (req: Request) => {remainingQuantity: invoiceLineQuantityInInventoryUnit,supplierId: purchaseInvoice.data?.supplierId,companyId,+ postingDate: today,});}@@ -1200,6 +1204,7 @@ serve(async (req: Request) => {remainingQuantity: entry.appliedQuantity,supplierId: purchaseInvoice.data?.supplierId,companyId,+ postingDate: today,});}} else {@@ -1261,6 +1266,7 @@ serve(async (req: Request) => {remainingQuantity: coveredQuantity,supplierId: purchaseInvoice.data?.supplierId,companyId,+ postingDate: today,});}// The write-up is baked into the layer; no child rows.@@ -1736,7 +1742,7 @@ serve(async (req: Request) => {}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;const createdReceiptIds: string[] = [];diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.tsindex 7ede0244c6..be44909279 100644--- a/packages/database/supabase/functions/post-receipt/index.ts+++ b/packages/database/supabase/functions/post-receipt/index.ts@@ -1,8 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { requirePermissions } from "../lib/supabase.ts";import type { Database } from "../lib/types.ts";@@ -40,7 +40,6 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const { type, receiptId, userId, companyId } =@@ -55,6 +54,7 @@ serve(async (req: Request) => {});const client = await requirePermissions(req, companyId, userId, { update: "inventory" });+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const [companyRecord, accountingSettings] = await Promise.all([client@@ -457,7 +457,8 @@ serve(async (req: Request) => {const accountingPeriodId = await getCurrentAccountingPeriod(client,companyId,- db+ db,+ today);await db.transaction().execute(async (trx) => {@@ -1241,6 +1242,7 @@ serve(async (req: Request) => {remainingQuantity: invoiceFirstQty,supplierId: purchaseOrder.data?.supplierId ?? undefined,companyId,+ postingDate: today,isInvoiceFirst: true,poLineId: poLineId ?? undefined,});@@ -1261,6 +1263,7 @@ serve(async (req: Request) => {remainingQuantity: normalQty,supplierId: purchaseOrder.data?.supplierId ?? undefined,companyId,+ postingDate: today,});}}@@ -1501,7 +1504,7 @@ serve(async (req: Request) => {}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;await db.transaction().execute(async (trx) => {@@ -1545,6 +1548,7 @@ serve(async (req: Request) => {remainingQuantity: 0,supplierId: purchaseOrder.data?.supplierId ?? undefined,companyId,+ postingDate: today,});}@@ -2161,7 +2165,7 @@ serve(async (req: Request) => {}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;await db.transaction().execute(async (trx) => {diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.tsindex f81aa0038a..4eb8e4c318 100644--- a/packages/database/supabase/functions/post-sales-invoice/index.ts+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts@@ -1,8 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import z from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { requirePermissions } from "../lib/supabase.ts";import type { Database } from "../lib/types.ts";@@ -32,7 +32,6 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const { type, invoiceId, userId, companyId } =@@ -47,6 +46,7 @@ serve(async (req: Request) => {});const client = await requirePermissions(req, companyId, userId, { update: "invoicing" });+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const [companyRecord, accountingSettings] = await Promise.all([client@@ -898,7 +898,7 @@ serve(async (req: Request) => {}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;await db.transaction().execute(async (trx) => {@@ -1076,6 +1076,7 @@ serve(async (req: Request) => {cost: -cogsResult.totalCost,remainingQuantity: 0,companyId,+ postingDate: today,}).execute();@@ -1410,7 +1411,7 @@ serve(async (req: Request) => {}const accountingPeriodId = accountingEnabled- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;await db.transaction().execute(async (trx) => {diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.tsindex 5c1cc9a523..cb9f83a145 100644--- a/packages/database/supabase/functions/post-shipment/index.ts+++ b/packages/database/supabase/functions/post-shipment/index.ts@@ -1,8 +1,8 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { requirePermissions } from "../lib/supabase.ts";import type { Database, Json } from "../lib/types.ts";@@ -31,7 +31,6 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const { type, shipmentId, userId, companyId } =@@ -46,6 +45,7 @@ serve(async (req: Request) => {});const client = await requirePermissions(req, companyId, userId, { update: "inventory" });+ const today = datetime.today(await getCompanyTimeZone(client, companyId)).toString();const [shipment, shipmentLines, shipmentLineTracking] = await Promise.all([client.from("shipment").select("*").eq("id", shipmentId).single(),@@ -783,7 +783,8 @@ serve(async (req: Request) => {const accountingPeriodId = await getCurrentAccountingPeriod(client,companyId,- db+ db,+ today);await db.transaction().execute(async (trx) => {@@ -1107,6 +1108,7 @@ serve(async (req: Request) => {cost: -cogsResult.totalCost,remainingQuantity: 0,companyId,+ postingDate: today,}).execute();}@@ -2142,7 +2144,7 @@ serve(async (req: Request) => {const accountingPeriodId =accountingEnabled && reversingJournalLines.length > 0- ? await getCurrentAccountingPeriod(client, companyId, db)+ ? await getCurrentAccountingPeriod(client, companyId, db, today): null;await db.transaction().execute(async (trx) => {diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.tsindex d761aa9555..5ebc22fab2 100644--- a/packages/database/supabase/functions/post-stock-transfer/index.ts+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts@@ -1,10 +1,10 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";-import { getLocalTimeZone, parseDate, today } from "npm:@internationalized/date";+import { type CalendarDate, parseDate } from "@internationalized/date";import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";import { sql } from "kysely";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import type { Database } from "../lib/types.ts";import { buildBatchSplitRecords } from "../shared/batch-split.ts";@@ -35,12 +35,12 @@ async function getExpiredEntityPolicy(companyId: string): Promise<ExpiredEntityPfunction checkExpiredEntity(entity: { id: string; expirationDate: string | null },policy: ExpiredEntityPolicy,- override: { allowed: boolean; reason: string | null }+ override: { allowed: boolean; reason: string | null },+ today: CalendarDate): { warning?: string } {if (!entity.expirationDate) return {};- const todayLocal = today(getLocalTimeZone());try {- if (parseDate(entity.expirationDate).compare(todayLocal) >= 0) return {};+ if (parseDate(entity.expirationDate).compare(today) >= 0) return {};} catch {return {};}@@ -127,10 +127,11 @@ serve(async (req: Request) => {if (preflight) return preflight;const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");try {const validatedPayload = payloadValidator.parse(payload);+ const companyToday = datetime.today(await getCompanyTimeZone(db, validatedPayload.companyId));+ const today = companyToday.toString();let expiredWarning: string | undefined;let splitEntityId: string | undefined;@@ -442,7 +443,8 @@ serve(async (req: Request) => {const expiredCheck = checkExpiredEntity({ id: trackedEntity.id, expirationDate: trackedEntity.expirationDate },policy,- { allowed: !!overrideExpired, reason: overrideReason ?? null }+ { allowed: !!overrideExpired, reason: overrideReason ?? null },+ companyToday);if (expiredCheck.warning) {expiredWarning = expiredCheck.warning;diff --git a/packages/database/supabase/functions/shared/get-accounting-period.ts b/packages/database/supabase/functions/shared/get-accounting-period.tsindex 09acd4b5da..aca0ab5dd0 100644--- a/packages/database/supabase/functions/shared/get-accounting-period.ts+++ b/packages/database/supabase/functions/shared/get-accounting-period.ts@@ -1,10 +1,10 @@+import { parseDate } from "@internationalized/date";import { SupabaseClient } from "@supabase/supabase-js";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { Kysely } from "kysely";import { DB } from "../lib/database.ts";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { Database } from "../lib/types.ts";-// TODO: refactor to use @internationalized/date when npm:<package>@<version> is supportedconst isLeapYear = (year: number) => {return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;};@@ -186,17 +186,24 @@ export async function getAccountingPeriodForDate(export async function getCurrentAccountingPeriod<T>(client: SupabaseClient<Database>,companyId: string,- db: Kysely<DB>+ db: Kysely<DB>,+ // Pass the SAME hoisted business day the caller stamps on its ledger and+ // journal rows — two independent "today" resolutions inside one transaction+ // can straddle midnight and split the journal's period from its ledger+ // dates. Omitted = resolved fresh in the company timezone.+ forDate?: string // yyyy-MM-dd) {- // const d = today(getLocalTimeZone());- const d = format(new Date(), "yyyy-MM-dd");+ // "Today" in the company's business timezone — one set of books needs one+ // calendar, so ledger-scoped derivation never uses the process clock.+ const companyToday = forDate+ ? parseDate(forDate)+ : datetime.today(await getCompanyTimeZone(client, companyId));+ const d = companyToday.toString();// get the current accounting periodconst currentAccountingPeriod = await client.from("accountingPeriod").select("*")- // .gte("endDate", d.toString())- // .lte("startDate", d.toString()).eq("companyId", companyId).gte("endDate", d).lte("startDate", d)@@ -256,8 +263,8 @@ export async function getCurrentAccountingPeriod<T>(return periodId;}- const year = new Date().getFullYear();- const month = new Date().getMonth() + 1;+ const year = companyToday.year;+ const month = companyToday.month;const startDate = `${year}-${month.toString().padStart(2, "0")}-01`;let endDate = `${year}-${month.toString().padStart(2, "0")}-${daysInMonths[month]diff --git a/packages/database/supabase/functions/shared/get-next-sequence.ts b/packages/database/supabase/functions/shared/get-next-sequence.tsindex 11d2b2e820..2557632a2c 100644--- a/packages/database/supabase/functions/shared/get-next-sequence.ts+++ b/packages/database/supabase/functions/shared/get-next-sequence.ts@@ -5,6 +5,21 @@ import { sql, Transaction } from "kysely";import type { KyselyDatabase as DB } from "../lib/postgres/index.ts";import { interpolateSequenceDate } from "../lib/utils.ts";+// Sequence date tokens (%{yyyy}, %{ww}, …) roll over at the COMPANY's midnight —+// document numbering is ledger-scoped. Inline query (not lib/datetime.ts) so+// this file stays importable from Node.+export async function getSequenceTimeZone(+ trx: Transaction<DB>,+ companyId: string+): Promise<string> {+ const row = await trx+ .selectFrom("company")+ .select("timezone")+ .where("id", "=", companyId)+ .executeTakeFirst();+ return row?.timezone ?? "UTC";+}+export async function getNextSequence(trx: Transaction<DB>,tableName: string,@@ -29,8 +44,9 @@ export async function getNextSequence(if (!Number.isInteger(size)) throw new Error("Size is not an integer");const nextSequence = next!.toString().padStart(size!, "0");- const derivedPrefix = interpolateSequenceDate(prefix);- const derivedSuffix = interpolateSequenceDate(suffix);+ const timezone = await getSequenceTimeZone(trx, companyId);+ const derivedPrefix = interpolateSequenceDate(prefix, timezone);+ const derivedSuffix = interpolateSequenceDate(suffix, timezone);return `${derivedPrefix}${nextSequence}${derivedSuffix}`;}diff --git a/packages/database/supabase/functions/shared/get-next-serial-number.ts b/packages/database/supabase/functions/shared/get-next-serial-number.tsindex 9849e18157..e3e6bd300b 100644--- a/packages/database/supabase/functions/shared/get-next-serial-number.ts+++ b/packages/database/supabase/functions/shared/get-next-serial-number.ts@@ -1,6 +1,7 @@import { sql, Transaction } from "kysely";import type { KyselyDatabase as DB } from "../lib/postgres/index.ts";import { interpolateSerialNumber } from "../lib/utils.ts";+import { getSequenceTimeZone } from "./get-next-sequence.ts";/*** Atomically reserve and format the next `count` serial numbers for an item from@@ -49,6 +50,7 @@ export async function getNextSerialNumbers(const context = {locationCode: args.locationCode,locationName: args.locationName,+ timezone: await getSequenceTimeZone(trx, args.companyId),};const serials: string[] = [];diff --git a/packages/database/supabase/functions/shared/post-adjustment.ts b/packages/database/supabase/functions/shared/post-adjustment.tsindex 313dee3769..25ee28b6d1 100644--- a/packages/database/supabase/functions/shared/post-adjustment.ts+++ b/packages/database/supabase/functions/shared/post-adjustment.ts@@ -217,6 +217,7 @@ export async function bookAdjustment(quantity: -absQuantity,cost: -cogs.totalCost,remainingQuantity: 0,+ postingDate: ledger.postingDate,companyId,}).execute();@@ -283,6 +284,7 @@ export async function bookAdjustment(quantity: absQuantity,cost,remainingQuantity: absQuantity,+ postingDate: ledger.postingDate,companyId,}).execute();diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.tsindex 970528aa81..b04780a98c 100644--- a/packages/database/supabase/functions/update-purchased-prices/index.ts+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts@@ -1,9 +1,9 @@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";+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { requirePermissions } from "../lib/supabase.ts";import { Database } from "../lib/types.ts";@@ -120,6 +120,10 @@ serve(async (req: Request) => {.filter((line) => line.quantity > 0);if (shouldUpdatePrices) {+ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();+// Delete any existing cost ledger entries for this PO (handles re-finalization)await db.deleteFrom("costLedger")@@ -145,6 +149,7 @@ serve(async (req: Request) => {cost:(line.quantity / (line.conversionFactor ?? 1)) * line.unitPrice,remainingQuantity: 0,+ postingDate: today,supplierId,companyId,}));@@ -209,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/20260805020925_company-timezone.sql b/packages/database/supabase/migrations/20260805020925_company-timezone.sqlnew file mode 100644index 0000000000..ec8b5d4355--- /dev/null+++ b/packages/database/supabase/migrations/20260805020925_company-timezone.sql@@ -0,0 +1,53 @@+-- Pin the database clock: CURRENT_DATE / date_trunc business logic must not+-- depend on a server-local timezone. All prod runtimes already default to UTC;+-- this makes it explicit and covers self-hosted installs.+ALTER DATABASE postgres SET timezone TO 'UTC';++-- Company-level business timezone. Anything ledger-scoped (accounting periods,+-- posting dates, sequence date tokens) derives its calendar day here — one set+-- of books needs one calendar. location.timezone remains the anchor for+-- operational, physically-local work (shifts, scheduling, MES).+ALTER TABLE "company"+ ADD COLUMN "timezone" TEXT NOT NULL DEFAULT 'UTC';++-- Backfill from each company's first location ("first location = HQ"+-- assumption). location.timezone was free text before the picker existed, so+-- only copy values Postgres can actually resolve — an unresolvable name would+-- make every later `now() AT TIME ZONE "timezone"` (company_today) raise at+-- posting time, and the validity CHECK added later is NOT VALID so it would+-- never reject the backfilled row. Companies with no resolvable location+-- timezone keep the 'UTC' default.+UPDATE "company" c+SET "timezone" = l."timezone"+FROM (+ SELECT DISTINCT ON ("companyId") "companyId", "timezone"+ FROM "location"+ WHERE "timezone" IS NOT NULL+ AND "timezone" <> ''+ AND EXISTS (+ SELECT 1 FROM pg_timezone_names tz WHERE tz.name = "location"."timezone"+ )+ ORDER BY "companyId", "createdAt" ASC+) l+WHERE c."id" = l."companyId";++-- Postgres views freeze their column manifest at CREATE time, so adding+-- columns to "company" does not propagate to the "companies" view unless we+-- recreate it. Drop + recreate to refresh the column list.+DROP VIEW IF EXISTS "companies";+CREATE OR REPLACE VIEW "companies" WITH(SECURITY_INVOKER=true) AS+ SELECT DISTINCT+ c.*,+ uc.*,+ et.name AS "employeeType",+ cg.name AS "companyGroupName",+ cg."ownerId"+ FROM "userToCompany" uc+ INNER JOIN "company" c+ ON c.id = uc."companyId"+ LEFT JOIN "employee" e+ ON e.id = uc."userId" AND e."companyId" = uc."companyId"+ LEFT JOIN "employeeType" et+ ON et.id = e."employeeTypeId"+ LEFT JOIN "companyGroup" cg+ ON cg.id = c."companyGroupId";diff --git a/packages/database/supabase/migrations/20260805023439_company-timezone-sql-functions.sql b/packages/database/supabase/migrations/20260805023439_company-timezone-sql-functions.sqlnew file mode 100644index 0000000000..c1fcb50bec--- /dev/null+++ b/packages/database/supabase/migrations/20260805023439_company-timezone-sql-functions.sql@@ -0,0 +1,1236 @@+-- Ledger-scoped "today" must match the app's company-timezone derivation.+-- 20260805020925_company-timezone.sql pinned the DB session to UTC and added+-- company."timezone"; app code now derives posting dates and accounting-period+-- membership in the company's timezone. The ledger-posting SQL functions below+-- still derived "today" from the UTC session clock, so a posting near a month+-- boundary could land in a different accounting period than an app-posted+-- document for the same business day. One set of books needs one calendar:+-- every timezone-sensitive session-date site in these functions now uses+-- company_today(companyId).+--+-- Each function is recreated VERBATIM from its newest committed definition+-- (backflush_job_materials: 20260804111631_picked-material-return-timing.sql;+-- complete_job_to_inventory + recompute_service_line_fulfillment:+-- 20260731164213_service-only-completion-fulfillment.sql), changing ONLY the+-- session-date sites plus one added v_company_today declaration per function.++-- Company-calendar "today". STABLE (one timestamp per statement), and safe+-- under SECURITY DEFINER SET search_path = public: the lookup is+-- schema-qualified and falls back to UTC for a missing company row.+CREATE OR REPLACE FUNCTION company_today(p_company_id TEXT)+RETURNS DATE+LANGUAGE sql+STABLE+AS $$+ SELECT (now() AT TIME ZONE COALESCE(+ (SELECT "timezone" FROM public."company" WHERE "id" = p_company_id),+ 'UTC'+ ))::date+$$;++CREATE OR REPLACE FUNCTION backflush_job_materials(+ p_job_id TEXT,+ p_quantity_complete NUMERIC,+ p_company_id TEXT,+ p_user_id TEXT+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_job_quantity NUMERIC;+ v_job_location_id TEXT;+ v_job_id_readable TEXT;+ v_ratio NUMERIC;+ v_target NUMERIC;+ v_material RECORD;+ v_material_qty_to_issue NUMERIC;+ v_material_storage_unit_id TEXT;+ v_bin_work_center_id TEXT;+ v_bin_on_hand NUMERIC;+ v_material_costing_method TEXT;+ v_material_standard_cost NUMERIC;+ v_material_unit_cost NUMERIC;+ v_material_item_posting_group_id TEXT;+ v_material_cogs_total NUMERIC;+ v_cost_layer RECORD;+ v_remaining_to_consume NUMERIC;+ v_layer_unit_cost NUMERIC;+ v_quantity_from_layer NUMERIC;+ v_adjustment_child RECORD;+ v_child_budget NUMERIC;+ v_child_apply NUMERIC;+ v_child_per_unit NUMERIC;+ v_accounting_enabled BOOLEAN;+ v_company_group_id TEXT;+ v_raw_materials_account TEXT;+ v_finished_goods_account TEXT;+ v_material_inventory_account TEXT;+ v_material_inventory_description TEXT;+ v_wip_account TEXT;+ v_dimension_item_posting_group TEXT;+ v_dimension_item TEXT;+ v_dimension_location TEXT;+ v_bf_item_ids TEXT[] := '{}';+ v_bf_quantities NUMERIC[] := '{}';+ v_bf_storage_unit_ids TEXT[] := '{}';+ v_bf_journal_id TEXT;+ v_bf_journal_entry_id TEXT;+ v_bf_accounting_period_id TEXT;+ v_bf_journal_line_ref TEXT;+ v_bf_jl_id TEXT;+ v_bf_jl_ids TEXT[];+ v_bf_posting_group_ids TEXT[];+ v_bf_line_item_ids TEXT[];+ v_company_today DATE := company_today(p_company_id);+BEGIN+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));++ -- Fetch job details+ SELECT quantity, "locationId", "jobId"+ INTO STRICT v_job_quantity, v_job_location_id, v_job_id_readable+ FROM "job"+ WHERE id = p_job_id;++ IF v_job_quantity IS NULL OR v_job_quantity <= 0 THEN+ RETURN;+ END IF;++ v_ratio := p_quantity_complete / v_job_quantity;++ -- Backflush non-tracked materials+ FOR v_material IN+ SELECT jm.id, jm."itemId", jm."quantityToIssue", jm."quantityIssued",+ jm."estimatedQuantity", jm."storageUnitId", jm."defaultStorageUnit"+ FROM "jobMaterial" jm+ WHERE jm."jobId" = p_job_id+ AND jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" != 'Make to Order'+ AND jm."requiresBatchTracking" = false+ AND jm."requiresSerialTracking" = false+ AND jm."quantityToIssue" > 0+ LOOP+ -- Prorate: only issue what's needed for the completed quantity+ v_target := v_material."estimatedQuantity" * v_ratio;+ v_material_qty_to_issue := GREATEST(v_target - COALESCE(v_material."quantityIssued", 0), 0);++ IF v_material_qty_to_issue <= 0 THEN+ CONTINUE;+ END IF;++ -- Resolve storage unit+ v_material_storage_unit_id := v_material."storageUnitId";++ IF v_material_storage_unit_id IS NULL AND v_material."defaultStorageUnit" THEN+ SELECT "defaultStorageUnitId" INTO v_material_storage_unit_id+ FROM "pickMethod"+ WHERE "itemId" = v_material."itemId"+ AND "locationId" = v_job_location_id+ AND "companyId" = p_company_id;+ END IF;++ IF v_material_storage_unit_id IS NULL THEN+ SELECT "storageUnitId" INTO v_material_storage_unit_id+ FROM "itemLedger"+ WHERE "itemId" = v_material."itemId"+ AND "locationId" = v_job_location_id+ AND "storageUnitId" IS NOT NULL+ GROUP BY "storageUnitId"+ HAVING SUM(quantity) > 0+ ORDER BY SUM(quantity) DESC+ LIMIT 1;+ END IF;++ -- Clamp lineside draws to actual untracked on-hand. An early per-operation+ -- return (returnPickedMaterialTiming = 'operation') or a manual transfer can+ -- leave the lineside bin short of the prorated target; never post a+ -- consumption the bin cannot supply. Warehouse bins (no workCenterId) keep+ -- the historical unclamped behavior.+ v_bin_work_center_id := NULL;+ IF v_material_storage_unit_id IS NOT NULL THEN+ SELECT su."workCenterId" INTO v_bin_work_center_id+ FROM "storageUnit" su+ WHERE su.id = v_material_storage_unit_id;++ IF v_bin_work_center_id IS NOT NULL THEN+ SELECT COALESCE(SUM(quantity), 0) INTO v_bin_on_hand+ FROM "itemLedger"+ WHERE "itemId" = v_material."itemId"+ AND "storageUnitId" = v_material_storage_unit_id+ AND "locationId" = v_job_location_id+ AND "companyId" = p_company_id+ AND "trackedEntityId" IS NULL;++ v_material_qty_to_issue := LEAST(v_material_qty_to_issue, GREATEST(v_bin_on_hand, 0));++ IF v_material_qty_to_issue <= 0 THEN+ CONTINUE;+ END IF;+ END IF;+ END IF;++ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"+ ) VALUES (+ 'Consumption', 'Job Consumption', p_job_id, p_company_id,+ v_material."itemId", -v_material_qty_to_issue,+ v_job_location_id, v_material_storage_unit_id, p_user_id+ );++ UPDATE "jobMaterial"+ SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_material_qty_to_issue+ WHERE id = v_material.id;++ v_bf_item_ids := v_bf_item_ids || v_material."itemId";+ v_bf_quantities := v_bf_quantities || v_material_qty_to_issue;+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || COALESCE(v_material_storage_unit_id, '');+ END LOOP;++ -- Check if accounting is enabled+ SELECT "accountingEnabled"+ INTO v_accounting_enabled+ FROM "companySettings"+ WHERE id = p_company_id;++ v_accounting_enabled := COALESCE(v_accounting_enabled, false);++ IF NOT v_accounting_enabled THEN+ RETURN;+ END IF;++ IF array_length(v_bf_item_ids, 1) IS NULL OR array_length(v_bf_item_ids, 1) = 0 THEN+ RETURN;+ END IF;++ -- Fetch company group+ SELECT "companyGroupId"+ INTO STRICT v_company_group_id+ FROM company+ WHERE id = p_company_id;++ -- Fetch account defaults+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount"+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account+ FROM "accountDefault"+ WHERE "companyId" = p_company_id;++ -- Fetch dimension IDs+ SELECT+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),+ MAX(CASE WHEN "entityType" = 'Location' THEN id END)+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location+ FROM dimension+ WHERE "companyGroupId" = v_company_group_id+ AND active = true+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location');++ -- Get accounting period+ SELECT id INTO v_bf_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_company_today+ AND "endDate" >= v_company_today+ AND status = 'Active'+ LIMIT 1;++ IF v_bf_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_company_today+ AND "endDate" >= v_company_today+ RETURNING id INTO v_bf_accounting_period_id;++ IF v_bf_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', v_company_today)::DATE,+ (date_trunc('month', v_company_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_bf_accounting_period_id;+ END IF;+ END IF;++ v_bf_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_bf_journal_entry_id, v_bf_accounting_period_id,+ 'Material Issue — Job ' || v_job_id_readable,+ v_company_today, p_company_id, 'Job Consumption', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_bf_journal_id;++ v_bf_jl_ids := '{}';+ v_bf_posting_group_ids := '{}';+ v_bf_line_item_ids := '{}';++ FOR i IN 1..array_length(v_bf_item_ids, 1)+ LOOP+ -- Get itemCost for COGS calculation+ SELECT "costingMethod", "standardCost", "unitCost", "itemPostingGroupId"+ INTO v_material_costing_method, v_material_standard_cost, v_material_unit_cost, v_material_item_posting_group_id+ FROM "itemCost"+ WHERE "itemId" = v_bf_item_ids[i]+ AND "companyId" = p_company_id;++ IF v_material_costing_method IS NULL THEN+ CONTINUE;+ END IF;++ -- Calculate COGS based on costing method+ v_material_cogs_total := 0;++ IF v_material_costing_method = 'Standard' THEN+ v_material_cogs_total := COALESCE(v_material_standard_cost, 0) * v_bf_quantities[i];++ ELSIF v_material_costing_method = 'Average' THEN+ v_material_cogs_total := COALESCE(v_material_unit_cost, 0) * v_bf_quantities[i];++ ELSIF v_material_costing_method IN ('FIFO', 'LIFO') THEN+ v_remaining_to_consume := v_bf_quantities[i];++ FOR v_cost_layer IN+ SELECT id, quantity, cost, "remainingQuantity"+ FROM "costLedger"+ WHERE "itemId" = v_bf_item_ids[i]+ AND "companyId" = p_company_id+ AND "remainingQuantity" > 0+ -- adjustment child rows are consumed with their parent, not as layers+ AND adjustment = false+ AND "appliesToCostLedgerId" IS NULL+ -- 'Purchase Order' rows are planning/cost-history artifacts, not layers+ AND ("documentType" IS NULL OR "documentType" <> 'Purchase Order')+ ORDER BY+ CASE WHEN v_material_costing_method = 'FIFO' THEN "postingDate" END ASC,+ CASE WHEN v_material_costing_method = 'LIFO' THEN "postingDate" END DESC,+ CASE WHEN v_material_costing_method = 'FIFO' THEN "createdAt" END ASC,+ CASE WHEN v_material_costing_method = 'LIFO' THEN "createdAt" END DESC+ LOOP+ EXIT WHEN v_remaining_to_consume <= 0;++ v_layer_unit_cost := CASE+ WHEN v_cost_layer.quantity > 0 THEN v_cost_layer.cost / v_cost_layer.quantity+ ELSE 0+ END;++ v_quantity_from_layer := LEAST(v_remaining_to_consume, v_cost_layer."remainingQuantity");+ v_material_cogs_total := v_material_cogs_total + v_quantity_from_layer * v_layer_unit_cost;+ v_remaining_to_consume := v_remaining_to_consume - v_quantity_from_layer;++ UPDATE "costLedger"+ SET "remainingQuantity" = "remainingQuantity" - v_quantity_from_layer+ WHERE id = v_cost_layer.id;++ -- Consume the layer's cost-adjustment children (invoice-vs-receipt+ -- price corrections linked via "appliesToCostLedgerId") alongside the+ -- parent: each adjusted unit carries a bump of child.cost/child.quantity.+ -- Mirrors shared/calculate-cogs.ts.+ v_child_budget := v_quantity_from_layer;+ FOR v_adjustment_child IN+ SELECT id, quantity, cost, "remainingQuantity"+ FROM "costLedger"+ WHERE "appliesToCostLedgerId" = v_cost_layer.id+ AND "remainingQuantity" > 0+ ORDER BY "createdAt" ASC+ LOOP+ EXIT WHEN v_child_budget <= 0;++ v_child_per_unit := CASE+ WHEN v_adjustment_child.quantity > 0+ THEN v_adjustment_child.cost / v_adjustment_child.quantity+ ELSE 0+ END;++ v_child_apply := LEAST(v_adjustment_child."remainingQuantity", v_child_budget);+ v_material_cogs_total := v_material_cogs_total + v_child_apply * v_child_per_unit;+ v_child_budget := v_child_budget - v_child_apply;++ UPDATE "costLedger"+ SET "remainingQuantity" = "remainingQuantity" - v_child_apply+ WHERE id = v_adjustment_child.id;+ END LOOP;+ END LOOP;++ -- Fallback for negative inventory+ IF v_remaining_to_consume > 0 THEN+ v_material_cogs_total := v_material_cogs_total + v_remaining_to_consume * COALESCE(v_material_unit_cost, 0);+ END IF;+ END IF;++ IF v_material_cogs_total <= 0 THEN+ CONTINUE;+ END IF;++ -- Resolve Raw Materials vs Finished Goods from the consumed item:+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.+ SELECT+ CASE WHEN i2."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,+ CASE WHEN i2."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END+ INTO v_material_inventory_account, v_material_inventory_description+ FROM "item" i2+ WHERE i2."id" = v_bf_item_ids[i]+ AND i2."companyId" = p_company_id;++ v_bf_journal_line_ref := nanoid();++ -- DR WIP+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_bf_journal_id, v_wip_account, 'WIP Account',+ v_material_cogs_total, v_bf_quantities[i],+ 'Job Consumption', p_job_id, 'job:' || p_job_id,+ v_bf_journal_line_ref, p_company_id+ )+ RETURNING id INTO v_bf_jl_id;++ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');+ v_bf_line_item_ids := v_bf_line_item_ids || COALESCE(v_bf_item_ids[i], '');++ -- CR Inventory (Raw Materials or Finished Goods by item)+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_bf_journal_id, v_material_inventory_account, v_material_inventory_description,+ -v_material_cogs_total, v_bf_quantities[i],+ 'Job Consumption', p_job_id, 'job:' || p_job_id,+ v_bf_journal_line_ref, p_company_id+ )+ RETURNING id INTO v_bf_jl_id;++ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');+ v_bf_line_item_ids := v_bf_line_item_ids || COALESCE(v_bf_item_ids[i], '');++ -- Cost ledger entry for consumption+ INSERT INTO "costLedger" (+ "itemLedgerType", "costLedgerType", adjustment,+ "documentType", "documentId", "itemId",+ quantity, cost, "remainingQuantity", "companyId"+ ) VALUES (+ 'Consumption', 'Direct Cost', false,+ 'Job Consumption', p_job_id, v_bf_item_ids[i],+ -v_bf_quantities[i], -v_material_cogs_total,+ 0, p_company_id+ );+ END LOOP;++ -- Dimensions for material consumption journal lines+ IF array_length(v_bf_jl_ids, 1) IS NOT NULL THEN+ FOR i IN 1..array_length(v_bf_jl_ids, 1)+ LOOP+ IF v_bf_posting_group_ids[i] != '' AND v_dimension_item_posting_group IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_item_posting_group, v_bf_posting_group_ids[i], p_company_id+ );+ END IF;++ IF v_dimension_item IS NOT NULL AND v_bf_line_item_ids[i] != '' THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_item, v_bf_line_item_ids[i], p_company_id+ );+ END IF;++ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id+ );+ END IF;+ END LOOP;+ END IF;+END;+$$;++CREATE OR REPLACE FUNCTION complete_job_to_inventory(+ p_job_id TEXT,+ p_quantity_complete NUMERIC,+ p_storage_unit_id TEXT DEFAULT NULL,+ p_location_id TEXT DEFAULT NULL,+ p_company_id TEXT DEFAULT NULL,+ p_user_id TEXT DEFAULT NULL+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_item_id TEXT;+ v_item_tracking_type "itemTrackingType";+ v_cogs_account TEXT;+ v_sales_order_line_id TEXT;+ v_line_quantity_complete NUMERIC;+ v_job_company_id TEXT;+ v_prior_quantity_received NUMERIC;+ v_quantity_received_to_inventory NUMERIC;+ v_job_id_readable TEXT;+ v_job_make_method RECORD;+ v_tracked_entity RECORD;+ v_accounting_enabled BOOLEAN;+ v_company_group_id TEXT;+ v_raw_materials_account TEXT;+ v_finished_goods_account TEXT;+ v_item_inventory_account TEXT;+ v_item_inventory_description TEXT;+ v_wip_account TEXT;+ v_labor_absorption_account TEXT;+ v_overhead_absorption_account TEXT;+ v_dimension_item_posting_group TEXT;+ v_dimension_item TEXT;+ v_dimension_location TEXT;+ v_dimension_cost_center TEXT;+ v_dimension_employee TEXT;+ v_event RECORD;+ v_duration_hours NUMERIC;+ v_rate NUMERIC;+ v_labor_cost NUMERIC;+ v_overhead_cost NUMERIC;+ v_event_reference TEXT;+ v_labor_journal_line_reference TEXT;+ v_labor_accounting_period_id TEXT;+ v_labor_journal_entry_id TEXT;+ v_labor_journal_id TEXT;+ v_labor_jl_id TEXT;+ v_accumulated_wip_cost NUMERIC;+ v_today DATE;+ v_journal_line_reference TEXT;+ v_accounting_period_id TEXT;+ v_journal_entry_id TEXT;+ v_journal_id TEXT;+ v_jl_ids TEXT[];+ v_new_per_unit_cost NUMERIC;+ v_costing_method TEXT;+ v_existing_unit_cost NUMERIC;+ v_item_posting_group_id TEXT;+ v_job_location_id TEXT;+ v_total_qty_on_hand NUMERIC;+ v_prior_qty NUMERIC;+ v_prior_value NUMERIC;+ v_new_unit_cost NUMERIC;+ v_company_today DATE := company_today(p_company_id);+BEGIN+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));++ -- Fetch job details+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId", "salesOrderLineId", "companyId"+ INTO STRICT v_item_id, v_prior_quantity_received, v_job_id_readable, v_job_location_id, v_sales_order_line_id, v_job_company_id+ FROM "job"+ WHERE id = p_job_id;++ -- SECURITY DEFINER bypasses RLS: bind the call to the job's own company so a+ -- caller can never complete another tenant's job or post into a mismatched+ -- company's ledger/journal.+ IF p_company_id IS NULL OR v_job_company_id IS DISTINCT FROM p_company_id THEN+ RAISE EXCEPTION 'Job % does not belong to company %', p_job_id, COALESCE(p_company_id, '<null>');+ END IF;++ -- Non-Inventory items (services) never enter inventory+ SELECT "itemTrackingType"+ INTO v_item_tracking_type+ FROM "item"+ WHERE id = v_item_id+ AND "companyId" = p_company_id;++ -- Delta for this completion: drives the itemLedger/costLedger quantities and+ -- the WIP-discharge journal. The job column itself stores the CUMULATIVE+ -- quantity (get_inventory_quantities computes on-production supply as+ -- production + scrap - received - shipped, which requires cumulative).+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_prior_quantity_received, 0);++ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)+ SELECT *+ INTO STRICT v_job_make_method+ FROM "jobMakeMethod"+ WHERE "jobId" = p_job_id+ AND "parentMaterialId" IS NULL;++ -- Update job status. quantityReceivedToInventory is CUMULATIVE (not the+ -- delta): re-completions previously overwrote it with the delta, corrupting+ -- get_inventory_quantities' on-production supply math. Non-Inventory items+ -- never receive to inventory, so their value is left unchanged.+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "quantityComplete" = p_quantity_complete,+ "quantityReceivedToInventory" = CASE+ WHEN v_item_tracking_type = 'Non-Inventory' THEN v_prior_quantity_received+ ELSE p_quantity_complete+ END,+ "updatedAt" = NOW(),+ "updatedBy" = p_user_id+ WHERE id = p_job_id;++ -- Services never ship, so job completion is the fulfillment event: advance+ -- the linked sales-order line the way post-shipment does for physical lines.+ -- Lives HERE (not in app code) because completion has multiple entry points —+ -- the ERP complete route AND the sync_finish_job_operation interceptor that+ -- auto-completes when the last operation finishes. Recomputed from ALL jobs+ -- on the line, so it is idempotent and lot-split safe. Runs before the+ -- accounting-enabled / zero-WIP early returns.+ -- NARROWED: only genuine Service lines (salesOrderLineType = 'Service') fulfill+ -- by completion. They never receive a shipment line (the `create` edge fn skips+ -- salesOrderLineType='Service'), so completion is their only fulfillment event.+ -- A Non-Inventory *Part* (or Material/Tool/etc.) still ships via post-shipment and+ -- must NOT be auto-fulfilled here — that was marking SO lines "Shipped" with no shipment.+ IF v_item_tracking_type = 'Non-Inventory' AND v_sales_order_line_id IS NOT NULL+ AND EXISTS (+ SELECT 1 FROM "salesOrderLine" sol+ WHERE sol.id = v_sales_order_line_id+ AND sol."companyId" = p_company_id+ AND sol."salesOrderLineType" = 'Service'+ ) THEN+ SELECT COALESCE(SUM("quantityComplete"), 0)+ INTO v_line_quantity_complete+ FROM "job"+ WHERE "salesOrderLineId" = v_sales_order_line_id+ AND "companyId" = p_company_id+ AND status != 'Cancelled';++ UPDATE "salesOrderLine" sol+ SET "quantitySent" = v_line_quantity_complete,+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_line_quantity_complete >= sol."saleQuantity"),+ "sentDate" = CASE+ WHEN COALESCE(sol."saleQuantity", 0) > 0+ AND v_line_quantity_complete >= sol."saleQuantity"+ AND sol."sentDate" IS NULL+ THEN v_company_today+ ELSE sol."sentDate"+ END,+ "updatedBy" = p_user_id,+ "updatedAt" = NOW()+ WHERE sol.id = v_sales_order_line_id+ AND sol."companyId" = p_company_id;+ END IF;++ -- Insert itemLedger entries based on tracking type.+ -- Non-Inventory items (services) never enter inventory.+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN+ IF v_job_make_method."requiresBatchTracking" THEN+ SELECT *+ INTO v_tracked_entity+ FROM "trackedEntity"+ WHERE attributes->>'Job Make Method' = v_job_make_method.id+ AND status != 'Consumed'+ ORDER BY "createdAt" DESC+ LIMIT 1;++ IF v_tracked_entity.id IS NULL THEN+ RAISE EXCEPTION 'Tracked entity not found';+ END IF;++ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId",+ "trackedEntityId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,+ v_tracked_entity.id, p_user_id+ );++ ELSIF v_job_make_method."requiresSerialTracking" THEN+ FOR v_tracked_entity IN+ SELECT *+ FROM "trackedEntity"+ WHERE attributes->>'Job Make Method' = v_job_make_method.id+ -- Rejected units (scrapped at inspection) must not be received.+ AND status NOT IN ('Consumed', 'Rejected')+ LOOP+ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId",+ "trackedEntityId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, 1, p_location_id, p_storage_unit_id,+ v_tracked_entity.id, p_user_id+ );+ END LOOP;++ UPDATE "trackedEntity"+ SET status = 'Available'+ WHERE attributes->>'Job Make Method' = v_job_make_method.id+ -- Rejected units (scrapped at inspection) stay Rejected, out of stock.+ AND status NOT IN ('Consumed', 'Rejected');++ ELSE+ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,+ p_user_id+ );+ END IF;+ END IF;++ -- Update pickMethod defaultStorageUnitId if needed+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN+ IF NOT EXISTS (+ SELECT 1 FROM "itemLedger"+ WHERE "itemId" = v_item_id+ AND "locationId" = p_location_id+ AND "storageUnitId" IS NOT NULL+ AND "storageUnitId" != p_storage_unit_id+ LIMIT 1+ ) THEN+ IF EXISTS (+ SELECT 1 FROM "pickMethod"+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id+ ) THEN+ UPDATE "pickMethod"+ SET "defaultStorageUnitId" = p_storage_unit_id,+ "updatedBy" = p_user_id,+ "updatedAt" = NOW()+ WHERE "itemId" = v_item_id+ AND "locationId" = p_location_id;+ ELSE+ INSERT INTO "pickMethod" (+ "itemId", "locationId", "defaultStorageUnitId",+ "companyId", "createdBy", "createdAt"+ ) VALUES (+ v_item_id, p_location_id, p_storage_unit_id,+ p_company_id, p_user_id, NOW()+ );+ END IF;+ END IF;+ END IF;++ -- Backflush unissued materials (delegated to shared function)+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);++ -- Check if accounting is enabled+ SELECT "accountingEnabled"+ INTO v_accounting_enabled+ FROM "companySettings"+ WHERE id = p_company_id;++ v_accounting_enabled := COALESCE(v_accounting_enabled, false);++ IF NOT v_accounting_enabled THEN+ RETURN;+ END IF;++ -- Fetch company group+ SELECT "companyGroupId"+ INTO STRICT v_company_group_id+ FROM company+ WHERE id = p_company_id;++ -- Fetch account defaults+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account+ FROM "accountDefault"+ WHERE "companyId" = p_company_id;++ -- Resolve Raw Materials vs Finished Goods from the produced item:+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.+ SELECT+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END+ INTO v_item_inventory_account, v_item_inventory_description+ FROM "item" i+ WHERE i."id" = v_item_id+ AND i."companyId" = p_company_id;++ -- Non-Inventory (Service): the produced output is never stocked, so completion+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS+ -- branch off and post COGS as-incurred in the recognition run instead. <<<+ IF v_item_tracking_type = 'Non-Inventory' THEN+ v_item_inventory_account := v_cogs_account;+ v_item_inventory_description := 'Cost of Goods Sold';+ END IF;++ -- Fetch dimension IDs+ SELECT+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,+ v_dimension_cost_center, v_dimension_employee+ FROM dimension+ WHERE "companyGroupId" = v_company_group_id+ AND active = true+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');++ -- Post unposted production events as labor/machine + overhead absorption JEs+ -- (mirrors post-production-event; this is the catch-up path for events that+ -- were never posted individually)+ FOR v_event IN+ SELECT+ pe.id,+ pe.duration,+ pe.type,+ pe."employeeId",+ wc."laborRate",+ wc."machineRate",+ wc."overheadRate"+ FROM "productionEvent" pe+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"+ WHERE jo."jobId" = p_job_id+ AND pe."endTime" IS NOT NULL+ AND pe."postedToGL" = false+ AND pe.duration > 0+ LOOP+ v_duration_hours := v_event.duration::NUMERIC / 3600;+ v_rate := CASE+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)+ ELSE COALESCE(v_event."laborRate", 0)+ END;+ v_labor_cost := v_duration_hours * v_rate;+ v_overhead_cost := v_duration_hours * COALESCE(v_event."overheadRate", 0);+ v_event_reference := 'production-event:' || v_event.id;++ IF (v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL)+ OR (v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL) THEN+ v_labor_journal_line_reference := nanoid();++ -- Get current accounting period+ SELECT id INTO v_labor_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_company_today+ AND "endDate" >= v_company_today+ AND status = 'Active'+ LIMIT 1;++ IF v_labor_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_company_today+ AND "endDate" >= v_company_today+ RETURNING id INTO v_labor_accounting_period_id;++ IF v_labor_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', v_company_today)::DATE,+ (date_trunc('month', v_company_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_labor_accounting_period_id;+ END IF;+ END IF;++ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_labor_journal_entry_id, v_labor_accounting_period_id,+ v_event.type || ' Time — Job ' || v_job_id_readable,+ v_company_today, p_company_id, 'Production Event', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_labor_journal_id;++ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN+ -- DR WIP (labor/machine)+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_wip_account, 'WIP Account',+ v_labor_cost, 1,+ 'Production Event', p_job_id, v_event_reference,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on WIP line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on WIP line (the finished good this labor rolls into)+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;++ -- CR Labor/Machine Absorption+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',+ -v_labor_cost, 1,+ 'Production Event', p_job_id, v_event_reference,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on absorption line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on absorption line+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;+ END IF;++ IF v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL THEN+ -- DR WIP (overhead)+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_wip_account, 'WIP Account (Overhead)',+ v_overhead_cost, 1,+ 'Production Event', p_job_id, v_event_reference,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on WIP overhead line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on WIP overhead line+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;++ -- CR Overhead Absorption+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_overhead_absorption_account, 'Overhead Absorption',+ -v_overhead_cost, 1,+ 'Production Event', p_job_id, v_event_reference,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on overhead absorption line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on overhead absorption line+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;+ END IF;+ END IF;++ UPDATE "productionEvent"+ SET "postedToGL" = true+ WHERE id = v_event.id;+ END LOOP;++ -- Calculate accumulated WIP cost for this job+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)+ INTO v_accumulated_wip_cost+ FROM "journalLine" jl+ INNER JOIN journal j ON j.id = jl."journalId"+ WHERE jl."accountId" = v_wip_account+ AND jl."documentId" = p_job_id+ AND j."companyId" = p_company_id;++ IF v_accumulated_wip_cost <= 0 THEN+ RETURN;+ END IF;++ v_today := v_company_today;+ v_journal_line_reference := nanoid();++ -- Get accounting period for WIP discharge+ SELECT id INTO v_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_today+ AND "endDate" >= v_today+ AND status = 'Active'+ LIMIT 1;++ IF v_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_today+ AND "endDate" >= v_today+ RETURNING id INTO v_accounting_period_id;++ IF v_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', v_today)::DATE,+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_accounting_period_id;+ END IF;+ END IF;++ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_journal_entry_id, v_accounting_period_id,+ 'Job Completion ' || v_job_id_readable,+ v_today, p_company_id, 'Job Receipt', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_journal_id;++ -- DR Inventory (Raw Materials or Finished Goods by item)+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_journal_id, v_item_inventory_account, v_item_inventory_description,+ v_accumulated_wip_cost, v_quantity_received_to_inventory,+ 'Job Receipt', p_job_id, 'job:' || p_job_id,+ v_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ v_jl_ids := ARRAY[v_labor_jl_id];++ -- CR WIP+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_journal_id, v_wip_account, 'WIP Account',+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,+ 'Job Receipt', p_job_id, 'job:' || p_job_id,+ v_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ v_jl_ids := v_jl_ids || v_labor_jl_id;++ -- Write costLedger entry for finished good (skipped for Non-Inventory: no+ -- output layer exists for a service — its cost went straight to COGS above)+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN+ INSERT INTO "costLedger" (+ "itemLedgerType", "costLedgerType", adjustment,+ "documentType", "documentId", "itemId",+ quantity, cost, "remainingQuantity", "companyId"+ ) VALUES (+ 'Output', 'Direct Cost', false,+ 'Job Receipt', p_job_id, v_item_id,+ v_quantity_received_to_inventory, v_accumulated_wip_cost,+ v_quantity_received_to_inventory, p_company_id+ );+ END IF;++ -- Update item cost+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id+ FROM "itemCost"+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;++ -- Update itemCost.unitCost (skipped for Non-Inventory: a service has no+ -- stocked unit cost; the read above still feeds the dimension inserts below)+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;++ IF v_costing_method = 'Average' THEN+ SELECT COALESCE(SUM(quantity), 0)+ INTO v_total_qty_on_hand+ FROM "itemLedger"+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;++ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);++ IF v_total_qty_on_hand > 0 THEN+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;+ UPDATE "itemCost"+ SET "unitCost" = v_new_unit_cost+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;+ END IF;++ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN+ UPDATE "itemCost"+ SET "unitCost" = v_new_per_unit_cost+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;+ END IF;+ END IF;++ -- Insert dimensions on WIP discharge journal lines+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN+ FOR i IN 1..array_length(v_jl_ids, 1)+ LOOP+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id+ );+ END IF;++ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id+ );+ END IF;++ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id+ );+ END IF;+ END LOOP;+ END IF;+END;+$$;++CREATE OR REPLACE FUNCTION recompute_service_line_fulfillment(+ p_sales_order_line_id TEXT,+ p_company_id TEXT,+ p_user_id TEXT+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_item_tracking_type "itemTrackingType";+ v_line_type "salesOrderLineType";+ v_fulfilled NUMERIC;+ v_company_today DATE := company_today(p_company_id);+BEGIN+ IF p_sales_order_line_id IS NULL OR p_company_id IS NULL THEN+ RETURN;+ END IF;++ -- Only genuine Service lines fulfill by completion (kept in sync with+ -- complete_job_to_inventory). A Non-Inventory Part ships via post-shipment.+ SELECT i."itemTrackingType", sol."salesOrderLineType"+ INTO v_item_tracking_type, v_line_type+ FROM "salesOrderLine" sol+ JOIN "item" i ON i.id = sol."itemId" AND i."companyId" = sol."companyId"+ WHERE sol.id = p_sales_order_line_id+ AND sol."companyId" = p_company_id;++ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'+ OR v_line_type IS DISTINCT FROM 'Service' THEN+ RETURN;+ END IF;++ -- Fulfilled quantity = sum over this line's jobs that are actually completed.+ SELECT COALESCE(SUM("quantityComplete"), 0)+ INTO v_fulfilled+ FROM "job"+ WHERE "salesOrderLineId" = p_sales_order_line_id+ AND "companyId" = p_company_id+ AND status IN ('Completed', 'Closed');++ UPDATE "salesOrderLine" sol+ SET "quantitySent" = v_fulfilled,+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_fulfilled >= sol."saleQuantity"),+ "sentDate" = CASE+ WHEN COALESCE(sol."saleQuantity", 0) > 0 AND v_fulfilled >= sol."saleQuantity"+ THEN COALESCE(sol."sentDate", v_company_today)+ ELSE NULL+ END,+ "updatedBy" = p_user_id,+ "updatedAt" = NOW()+ WHERE sol.id = p_sales_order_line_id+ AND sol."companyId" = p_company_id;+END;+$$;diff --git a/packages/database/supabase/migrations/20260805152353_timezone-validity-check.sql b/packages/database/supabase/migrations/20260805152353_timezone-validity-check.sqlnew file mode 100644index 0000000000..68dac52cb0--- /dev/null+++ b/packages/database/supabase/migrations/20260805152353_timezone-validity-check.sql@@ -0,0 +1,50 @@+-- The stored timezone is consumed by BOTH runtimes: Postgres (company_today()+-- via AT TIME ZONE) and ICU/Intl (the app's datetime API). The app layer+-- validates the ICU side; this constraint makes Postgres itself the arbiter of+-- the database side — a zone name the server cannot resolve is rejected at+-- write time instead of erroring inside a posting function later.+CREATE OR REPLACE FUNCTION is_valid_timezone(tz TEXT)+RETURNS BOOLEAN+LANGUAGE plpgsql+STABLE+AS $$+BEGIN+ IF tz IS NULL OR tz = '' THEN+ RETURN FALSE;+ END IF;+ PERFORM now() AT TIME ZONE tz;+ RETURN TRUE;+EXCEPTION WHEN OTHERS THEN+ RETURN FALSE;+END;+$$;++-- NOT VALID: enforce on new writes without failing the migration if legacy+-- rows (e.g. free-text location timezones from before the picker) are invalid.+ALTER TABLE "company"+ ADD CONSTRAINT "company_timezone_valid"+ CHECK (is_valid_timezone("timezone")) NOT VALID;++ALTER TABLE "location"+ ADD CONSTRAINT "location_timezone_valid"+ CHECK (is_valid_timezone("timezone")) NOT VALID;++-- Timezone options for the app's pickers, sourced from the server's own tzdata+-- (pg_timezone_names) so the offered list is exactly what AT TIME ZONE+-- resolves — not a JS engine's Intl list, whose canonicalization and freshness+-- vary by engine. Filtered to canonical geographic zones + UTC; excludes+-- posix/*, right/*, Etc/* (inverted signs), bare abbreviations, and legacy+-- aliases (US/*, Brazil/*, ...). utc_offset is the zone's CURRENT offset.+CREATE OR REPLACE FUNCTION get_timezone_names()+RETURNS TABLE("name" TEXT, "utcOffset" TEXT)+LANGUAGE sql+STABLE+AS $$+ SELECT+ "name"::TEXT,+ "utc_offset"::TEXT+ FROM pg_timezone_names+ WHERE "name" ~ '^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/'+ OR "name" = 'UTC'+ ORDER BY "name";+$$;diff --git a/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql b/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sqlnew file mode 100644index 0000000000..882133b05c--- /dev/null+++ b/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql@@ -0,0 +1,479 @@+-- Business dates derived in SQL must use the business calendar, not the+-- database's. `company_today()` landed in 20260805023439; this migration adds+-- the location counterpart and converts the four remaining SQL functions that+-- WRITE or ANCHOR a business date off `CURRENT_DATE` (= UTC).+--+-- Read-only "is it overdue?" surfaces (gauges, purchaseInvoices, salesInvoices,+-- training periods, planning discontinuation filters) still compare against+-- CURRENT_DATE. They render a status rather than storing one, so a one-day skew+-- is cosmetic; converting them is a separate change.++-- 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+)+RETURNS date+LANGUAGE sql+STABLE+AS $function$+ SELECT (now() AT TIME ZONE COALESCE(+ (+ SELECT "timezone" FROM public."location"+ WHERE "id" = p_location_id AND "companyId" = p_company_id+ ),+ (SELECT "timezone" FROM public."company" WHERE "id" = p_company_id),+ 'UTC'+ ))::date+$function$;++-- 1. get_next_sequence — every ERP document number flows through here. The+-- date tokens were interpolated off the UTC day while the TypeScript twin+-- (interpolateSequenceDate) used the company timezone, so the two numbering+-- paths disagreed. Also adds %{ww}/%{hh}/%{ss}, which the Sequences settings+-- UI advertises but this function emitted literally.+CREATE OR REPLACE FUNCTION public.get_next_sequence(sequence_name text, company_id text)+ RETURNS text+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ v_prefix text;+ v_suffix text;+ v_next_value integer;+ v_size integer;+ v_next_sequence text;+ v_derived_prefix text;+ v_derived_suffix text;+ v_now timestamp;+BEGIN+ IF session_user = 'authenticator' THEN+ IF NOT (has_role('employee', company_id) OR has_valid_api_key_for_company(company_id)) THEN+ RAISE EXCEPTION 'Insufficient permissions';+ END IF;+ END IF;++ UPDATE sequence+ SET next = next + step,+ "updatedBy" = 'system'+ WHERE "table" = sequence_name+ AND "companyId" = company_id+ RETURNING next, prefix, suffix, size+ INTO v_next_value, v_prefix, v_suffix, v_size;++ IF NOT FOUND THEN+ RAISE EXCEPTION 'Sequence not found for table % and company %', sequence_name, company_id;+ END IF;++ -- Format sequence number+ v_next_sequence := lpad(v_next_value::text, COALESCE(v_size, 4), '0');++ -- Wall-clock in the company's timezone: document prefixes must roll over at+ -- the company's midnight, not the database's. Matches the TypeScript twin+ -- interpolateSequenceDate(value, companyTimezone).+ v_now := now() AT TIME ZONE COALESCE(+ (SELECT "timezone" FROM "company" WHERE "id" = company_id),+ 'UTC'+ );++ -- Interpolate date variables in prefix/suffix+ v_derived_prefix := COALESCE(v_prefix, '');+ v_derived_prefix := replace(v_derived_prefix, '%{yyyy}', to_char(v_now, 'YYYY'));+ v_derived_prefix := replace(v_derived_prefix, '%{yy}', to_char(v_now, 'YY'));+ v_derived_prefix := replace(v_derived_prefix, '%{mm}', to_char(v_now, 'MM'));+ v_derived_prefix := replace(v_derived_prefix, '%{ww}', to_char(v_now, 'IW'));+ v_derived_prefix := replace(v_derived_prefix, '%{dd}', to_char(v_now, 'DD'));+ v_derived_prefix := replace(v_derived_prefix, '%{hh}', to_char(v_now, 'HH24'));+ v_derived_prefix := replace(v_derived_prefix, '%{ss}', to_char(v_now, 'SS'));++ v_derived_suffix := COALESCE(v_suffix, '');+ v_derived_suffix := replace(v_derived_suffix, '%{yyyy}', to_char(v_now, 'YYYY'));+ v_derived_suffix := replace(v_derived_suffix, '%{yy}', to_char(v_now, 'YY'));+ v_derived_suffix := replace(v_derived_suffix, '%{mm}', to_char(v_now, 'MM'));+ v_derived_suffix := replace(v_derived_suffix, '%{ww}', to_char(v_now, 'IW'));+ v_derived_suffix := replace(v_derived_suffix, '%{dd}', to_char(v_now, 'DD'));+ v_derived_suffix := replace(v_derived_suffix, '%{hh}', to_char(v_now, 'HH24'));+ v_derived_suffix := replace(v_derived_suffix, '%{ss}', to_char(v_now, 'SS'));++ RETURN v_derived_prefix || v_next_sequence || v_derived_suffix;+END;+$function$;++-- 2. generateEliminationEntries — the elimination journal's postingDate is a+-- ledger date and must derive on the elimination entity's calendar.+CREATE OR REPLACE FUNCTION public."generateEliminationEntries"(p_company_group_id text, p_user_id text)+ RETURNS integer+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_rec RECORD;+ v_lca_id TEXT;+ v_elim_id TEXT;+ v_journal_id INTEGER;+ v_period_id TEXT;+ v_journals_created INTEGER := 0;+ v_posting_date DATE;+ v_journals_by_elim RECORD;+BEGIN+ -- Check that user belongs to at least one company in this group+ IF NOT EXISTS (+ SELECT 1+ FROM "userToCompany" utc+ INNER JOIN "company" c ON c."id" = utc."companyId"+ WHERE utc."userId" = auth.uid()::text+ AND utc."role" = 'employee'+ AND c."companyGroupId" = p_company_group_id+ ) THEN+ RAISE EXCEPTION 'Insufficient permissions to generate elimination entries';+ END IF;++ -- Process each matched IC transaction pair, routing to the correct elimination entity+ -- Group matched transactions by their lowest common parent's elimination entity+ FOR v_rec IN+ SELECT DISTINCT+ ict."sourceCompanyId",+ ict."targetCompanyId"+ FROM "intercompanyTransaction" ict+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ LOOP+ -- Find the lowest common parent+ v_lca_id := "findLowestCommonParent"(v_rec."sourceCompanyId", v_rec."targetCompanyId");++ -- Find the elimination entity for this LCA+ SELECT c."id" INTO v_elim_id+ FROM "company" c+ WHERE c."parentCompanyId" = v_lca_id+ AND c."isEliminationEntity" = true+ AND c."companyGroupId" = p_company_group_id+ LIMIT 1;++ -- If no elimination entity at the LCA level, fall back to any in the group+ IF v_elim_id IS NULL THEN+ SELECT c."id" INTO v_elim_id+ FROM "company" c+ WHERE c."companyGroupId" = p_company_group_id+ AND c."isEliminationEntity" = true+ LIMIT 1;+ END IF;++ IF v_elim_id IS NULL THEN+ RAISE EXCEPTION 'No elimination entity found for company group %', p_company_group_id;+ END IF;++ -- The journal posts on company_today(v_elim_id), so resolve the period+ -- CONTAINING that date — an Active flag alone can point at a different+ -- month and split the journal from its posting date. Fall back to the+ -- Active period only when no period covers the date (calendar not yet+ -- generated), preserving the pre-timezone behavior.+ v_posting_date := company_today(v_elim_id);++ SELECT "id" INTO v_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = v_elim_id+ AND "startDate" <= v_posting_date+ AND "endDate" >= v_posting_date+ LIMIT 1;++ IF v_period_id IS NULL THEN+ SELECT "id" INTO v_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = v_elim_id+ AND "status" = 'Active'+ LIMIT 1;+ END IF;++ -- Create elimination journal on this elimination entity+ INSERT INTO "journal" ("description", "accountingPeriodId", "companyId", "postingDate")+ VALUES (+ 'IC Elimination: ' || v_rec."sourceCompanyId" || ' ↔ ' || v_rec."targetCompanyId",+ v_period_id,+ v_elim_id,+ -- Ledger date: the elimination entity's calendar, not the database's.+ v_posting_date+ )+ RETURNING "id" INTO v_journal_id;++ v_journals_created := v_journals_created + 1;++ -- Generate reversing entries from source journal lines+ INSERT INTO "journalLine" (+ "journalId", "accountId", "description", "amount",+ "documentType", "journalLineReference",+ "companyId", "companyGroupId"+ )+ SELECT+ v_journal_id,+ jl."accountId",+ 'IC Elimination: ' || COALESCE(jl."description", ''),+ -jl."amount",+ jl."documentType",+ 'ic-elim-' || ict."id",+ v_elim_id,+ p_company_group_id+ FROM "intercompanyTransaction" ict+ INNER JOIN "journalLine" jl ON jl."id" = ict."sourceJournalLineId"+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ AND ict."sourceCompanyId" = v_rec."sourceCompanyId"+ AND ict."targetCompanyId" = v_rec."targetCompanyId";++ -- Also reverse the matched counterpart entries+ INSERT INTO "journalLine" (+ "journalId", "accountId", "description", "amount",+ "documentType", "journalLineReference",+ "companyId", "companyGroupId"+ )+ SELECT+ v_journal_id,+ jl."accountId",+ 'IC Elimination: ' || COALESCE(jl."description", ''),+ -jl."amount",+ jl."documentType",+ 'ic-elim-' || ict."id",+ v_elim_id,+ p_company_group_id+ FROM "intercompanyTransaction" ict+ INNER JOIN "journalLine" jl ON jl."id" = ict."targetJournalLineId"+ WHERE ict."companyGroupId" = p_company_group_id+ AND ict."status" = 'Matched'+ AND ict."sourceCompanyId" = v_rec."sourceCompanyId"+ AND ict."targetCompanyId" = v_rec."targetCompanyId"+ AND ict."targetJournalLineId" IS NOT NULL;++ -- Update these IC transactions to Eliminated+ UPDATE "intercompanyTransaction"+ SET "status" = 'Eliminated',+ "eliminationJournalId" = v_journal_id,+ "updatedAt" = NOW()+ WHERE "companyGroupId" = p_company_group_id+ AND "status" = 'Matched'+ AND "sourceCompanyId" = v_rec."sourceCompanyId"+ AND "targetCompanyId" = v_rec."targetCompanyId";++ END LOOP;++ RETURN v_journals_created;+END;+$function$;++-- 3. set_shelf_life_for_operation — writes trackedEntity."expirationDate".+-- Shelf life is operational, so it counts from the producing plant's day.+CREATE OR REPLACE FUNCTION public.set_shelf_life_for_operation(p_job_operation_id text, p_event "shelfLifeTriggerTiming")+ RETURNS void+ LANGUAGE plpgsql+ SECURITY DEFINER+AS $function$+DECLARE+ v_job_id TEXT;+ v_job_make_method_id TEXT;+ v_operation_process_id TEXT;+ v_item_id TEXT;+ v_company_id TEXT;+ v_location_id TEXT;+ v_shelf_life_mode "shelfLifeMode";+ v_shelf_life_days NUMERIC;+ v_shelf_life_trigger_process TEXT;+ v_shelf_life_trigger_timing "shelfLifeTriggerTiming";+ v_calc_from_bom BOOLEAN;+ v_input_scope TEXT;+ v_computed_expiry DATE;+ v_input_min DATE;+BEGIN+ SELECT+ jo."jobId",+ jo."jobMakeMethodId",+ jo."processId",+ jmm."itemId",+ i."companyId",+ j."locationId"+ INTO+ v_job_id,+ v_job_make_method_id,+ v_operation_process_id,+ v_item_id,+ v_company_id,+ v_location_id+ FROM "jobOperation" jo+ JOIN "jobMakeMethod" jmm ON jmm."id" = jo."jobMakeMethodId"+ JOIN "item" i ON i."id" = jmm."itemId"+ LEFT JOIN "job" j ON j."id" = jo."jobId"+ WHERE jo."id" = p_job_operation_id;++ IF v_item_id IS NULL THEN+ RETURN;+ END IF;++ SELECT+ "mode", "days", "triggerProcessId", "triggerTiming",+ "calculateFromBom"+ INTO+ v_shelf_life_mode, v_shelf_life_days, v_shelf_life_trigger_process,+ v_shelf_life_trigger_timing, v_calc_from_bom+ FROM "itemShelfLife"+ WHERE "itemId" = v_item_id;++ IF NOT FOUND THEN+ RETURN;+ END IF;++ IF v_shelf_life_mode = 'Fixed Duration' THEN+ IF v_shelf_life_days IS NULL THEN+ RETURN;+ END IF;++ IF v_shelf_life_trigger_process IS NULL THEN+ IF p_event <> 'After' THEN+ RETURN;+ END IF;+ ELSE+ IF v_operation_process_id IS DISTINCT FROM v_shelf_life_trigger_process THEN+ RETURN;+ END IF;+ IF p_event <> v_shelf_life_trigger_timing THEN+ RETURN;+ END IF;+ END IF;++ -- Shelf life counts from the producing plant's day, not the database's.+ v_computed_expiry := (+ location_today(v_location_id, v_company_id)+ + (v_shelf_life_days || ' days')::INTERVAL+ )::DATE;++ -- Cap by earliest input expiry when the flag is on.+ IF v_calc_from_bom THEN+ SELECT COALESCE(+ "inventoryShelfLife"->>'calculatedInputScope',+ 'AllInputs'+ )+ INTO v_input_scope+ FROM "companySettings"+ WHERE "id" = v_company_id;++ IF v_input_scope IS NULL THEN+ v_input_scope := 'AllInputs';+ END IF;++ IF v_input_scope = 'AllInputs' THEN+ SELECT MIN(te."expirationDate")+ INTO v_input_min+ FROM "trackedActivityInput" tai+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"+ WHERE ta.attributes->>'Job Make Method' = v_job_make_method_id+ AND te."expirationDate" IS NOT NULL;+ ELSE+ SELECT MIN(te."expirationDate")+ INTO v_input_min+ FROM "trackedActivityInput" tai+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"+ JOIN "itemShelfLife" isl ON isl."itemId" = te."sourceDocumentId"+ WHERE ta.attributes->>'Job Make Method' = v_job_make_method_id+ AND isl."mode" IN ('Fixed Duration', 'Calculated')+ AND te."expirationDate" IS NOT NULL;+ END IF;++ IF v_input_min IS NOT NULL AND v_input_min < v_computed_expiry THEN+ v_computed_expiry := v_input_min;+ END IF;+ END IF;++ ELSIF v_shelf_life_mode = 'Calculated' THEN+ IF p_event <> 'After' THEN+ RETURN;+ END IF;++ SELECT COALESCE(+ "inventoryShelfLife"->>'calculatedInputScope',+ 'AllInputs'+ )+ INTO v_input_scope+ FROM "companySettings"+ WHERE "id" = v_company_id;++ IF v_input_scope IS NULL THEN+ v_input_scope := 'AllInputs';+ END IF;++ IF v_input_scope = 'AllInputs' THEN+ SELECT MIN(te."expirationDate")+ INTO v_computed_expiry+ FROM "trackedActivityInput" tai+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"+ WHERE ta.attributes->>'Job Make Method' = v_job_make_method_id+ AND te."expirationDate" IS NOT NULL;+ ELSE+ SELECT MIN(te."expirationDate")+ INTO v_computed_expiry+ FROM "trackedActivityInput" tai+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"+ JOIN "itemShelfLife" isl ON isl."itemId" = te."sourceDocumentId"+ WHERE ta.attributes->>'Job Make Method' = v_job_make_method_id+ AND isl."mode" IN ('Fixed Duration', 'Calculated')+ AND te."expirationDate" IS NOT NULL;+ END IF;++ IF v_computed_expiry IS NULL THEN+ RETURN;+ END IF;++ ELSIF v_shelf_life_mode = 'Set on Receipt' THEN+ RETURN;++ ELSE+ RETURN;+ END IF;++ UPDATE "trackedEntity"+ SET "expirationDate" = v_computed_expiry+ WHERE "sourceDocument" = 'Item'+ AND "sourceDocumentId" = v_item_id+ AND "attributes"->>'Job Make Method' = v_job_make_method_id+ AND "expirationDate" IS NULL;+END;+$function$;++-- 4. resolve_shelf_life_start_for_receipt — the anchor falls back to "today"+-- when the receipt has no postingDate yet; that fallback is the receiving+-- site's day.+CREATE OR REPLACE FUNCTION public.resolve_shelf_life_start_for_receipt(p_item_id text, p_receipt_id text)+ RETURNS date+ LANGUAGE plpgsql+AS $function$+DECLARE+ v_mode "shelfLifeMode";+ v_days NUMERIC;+ v_anchor DATE;+BEGIN+ SELECT "mode", "days" INTO v_mode, v_days+ FROM "itemShelfLife"+ WHERE "itemId" = p_item_id;++ IF NOT FOUND OR v_mode <> 'Fixed Duration' OR v_days IS NULL THEN+ RETURN NULL;+ END IF;++ SELECT COALESCE("postingDate", location_today("locationId", "companyId"))+ INTO v_anchor+ FROM "receipt"+ WHERE id = p_receipt_id;++ RETURN (v_anchor + (v_days || ' days')::INTERVAL)::DATE;+END;+$function$;diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.ymlindex 6b85f4111b..0818d37012 100644--- a/packages/dev/docker/docker-compose.dev.yml+++ b/packages/dev/docker/docker-compose.dev.yml@@ -21,6 +21,7 @@ services:ports:- "${PORT_DB}:5432"environment:+ TZ: UTCPOSTGRES_HOST: /var/run/postgresqlPOSTGRES_PORT: 5432PGPORT: 5432@@ -283,6 +284,7 @@ services:postgres:condition: service_healthyenvironment:+ TZ: UTCJWT_SECRET: ${SUPABASE_JWT_SECRET}SUPABASE_URL: http://kong:8000SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}diff --git a/packages/form/src/components/Timezone.tsx b/packages/form/src/components/Timezone.tsxindex c744615c44..537d80f5d1 100644--- a/packages/form/src/components/Timezone.tsx+++ b/packages/form/src/components/Timezone.tsx@@ -1,102 +1,39 @@-import {- FormControl,- FormErrorMessage,- FormHelperText,- FormLabel,- HStack,- IconButton,- LabelWithHelp,- Select as SelectBase,- SelectContent,- SelectGroup,- SelectItem,- SelectLabel,- SelectTrigger,- SelectValue-} from "@carbon/react";-import { timezones } from "@carbon/utils";-import { LuX } from "react-icons/lu";-import { useControlField, useField } from "../hooks";-import { useFormStateContext } from "../internal/formStateContext";-import type { SelectProps } from "./Select";+import { getTimezones, type TimezoneGroup } from "@carbon/utils";+import { useMemo } from "react";+import type { ComboboxProps } from "./Combobox";+import Combobox from "./Combobox";-type TimezoneProps = Omit<SelectProps, "options"> & {- size?: "sm" | "md" | "lg";+type TimezoneProps = Omit<ComboboxProps, "options"> & {+ /**+ * Grouped zone options. Pass the database-sourced list (pg_timezone_names+ * via the ERP wrapper) when available; falls back to the runtime's Intl+ * list, whose canonicalization/freshness varies by engine.+ */+ options?: TimezoneGroup[];};-const Timezone = ({- name,- label,- termId,- helperText,- isReadOnly: isReadOnlyProp,- isClearable,- placeholder,- size,- ...props-}: TimezoneProps) => {- const { getInputProps, error, isOptional: fieldIsOptional } = useField(name);- const formState = useFormStateContext();- const isReadOnly =- formState.isReadOnly || formState.isDisabled || isReadOnlyProp;- const [value, setValue] = useControlField<string | undefined>(name);+/**+ * Searchable timezone picker. Options are flattened to full IANA names with+ * the current offset ("America/Chicago (UTC-06:00)") so search matches by+ * city, region, or offset.+ */+const Timezone = ({ options, ...props }: TimezoneProps) => {+ const flatOptions = useMemo(() => {+ const groups = options?.length ? options : getTimezones();+ return groups.flatMap((group) =>+ group.options.map((option) => {+ const offset = /\(UTC[^)]*\)/.exec(option.label)?.[0];+ return {+ value: option.value,+ label: `${option.value.replace(/_/g, " ")}${+ offset ? ` ${offset}` : ""+ }`+ };+ })+ );+ }, [options]);- return (- <FormControl isInvalid={!!error}>- {label && (- <FormLabel htmlFor={name} isOptional={fieldIsOptional ?? false}>- <LabelWithHelp termId={termId}>{label}</LabelWithHelp>- </FormLabel>- )}- <input- {...getInputProps({- id: name,- value: value ?? ""- })}- type="hidden"- name={name}- id={name}- />- <HStack spacing={1}>- <SelectBase- value={value}- onValueChange={(value) => setValue(value)}- disabled={isReadOnly}- >- <SelectTrigger size={size} className="min-w-[160px]">- <SelectValue placeholder={placeholder} />- </SelectTrigger>- <SelectContent>- {timezones.map(({ label, options }) => (- <SelectGroup key={label}>- <SelectLabel>{label}</SelectLabel>- {options.map((option) => (- <SelectItem key={option.value} value={option.value}>- {option.label}- </SelectItem>- ))}- </SelectGroup>- ))}- </SelectContent>- </SelectBase>- {isClearable && !isReadOnly && value && (- <IconButton- variant="ghost"- aria-label="Clear"- icon={<LuX />}- onClick={() => setValue("")}- size={size === "sm" ? "md" : size}- />- )}- </HStack>-- {error ? (- <FormErrorMessage>{error}</FormErrorMessage>- ) : (- helperText && <FormHelperText>{helperText}</FormHelperText>- )}- </FormControl>- );+ return <Combobox {...props} options={flatOptions} />;};Timezone.displayName = "Timezone";diff --git a/packages/jobs/src/inngest/functions/extraction/extract-document.ts b/packages/jobs/src/inngest/functions/extraction/extract-document.tsindex c63534d407..2199f1ec66 100644--- a/packages/jobs/src/inngest/functions/extraction/extract-document.ts+++ b/packages/jobs/src/inngest/functions/extraction/extract-document.ts@@ -20,6 +20,11 @@ function parseDateToISO8601(value: unknown): string | null {const parsed = Date.parse(cleaned);if (isNaN(parsed)) return null;+ // Only NON-ISO text reaches this fallback (ISO forms returned above), and+ // Date.parse interprets non-ISO date strings in the PROCESS timezone — so+ // reading the parts back with local getters is the symmetric round-trip+ // that preserves the document's written date under any TZ. UTC getters here+ // would shift "Jan 2, 2026" to Jan 1 west of UTC.const d = new Date(parsed);return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;}diff --git a/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts b/packages/jobs/src/inngest/functions/scheduled/audit-archive.tsindex 11fd17e53f..23ebe502bf 100644--- a/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts+++ b/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts@@ -3,6 +3,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { auditConfig } from "@carbon/database/audit.config";import type { AuditLogEntry } from "@carbon/database/audit.types";import { getLogger } from "@carbon/logger";+import { datetime } from "@carbon/utils";import { inngest } from "../../client";const log = getLogger("jobs", "audit-archive");@@ -47,11 +48,12 @@ async function archiveCompanyLogs(const jsonl = records.map((r) => JSON.stringify(r)).join("\n");const gzipped = gzipSync(Buffer.from(jsonl));- // Generate archive path- 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");+ // Generate archive path — a storage key, so the UTC calendar is the+ // explicit, deterministic choice under any process timezone.+ const utcToday = datetime.today("UTC");+ const year = utcToday.year;+ const month = String(utcToday.month).padStart(2, "0");+ const day = String(utcToday.day).padStart(2, "0");const timestamp = `${year}-${month}-${day}`;const archivePath = `audit-logs/${companyId}/${year}/${month}/${timestamp}.jsonl.gz`;diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsxindex abcfe11f6f..7d7690c724 100644--- a/packages/react/src/Combobox.tsx+++ b/packages/react/src/Combobox.tsx@@ -80,8 +80,14 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(return [labelText, selectedOption.helper].filter(Boolean).join(" - ");}, [selectedOption]);- const dropdownContentWidthCh = useMemo(() => {- const maxOptionChars = options.reduce((longest, option) => {+ // The list is virtualized (items are absolutely positioned), so the+ // popover can't size to its options naturally. Instead of estimating in+ // `ch` (which overestimates proportional text and made every popover wider+ // than its trigger), render the longest label in an invisible zero-height+ // sizer row — the browser measures the true text width and the popover+ // takes max(trigger width, real content width).+ const longestOptionText = useMemo(() => {+ return options.reduce((longest, option) => {const labelText =typeof option.label === "string"? option.label@@ -90,13 +96,8 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(.filter(Boolean).join(" ");- return Math.max(longest, combined.length);- }, 0);-- // Keep a sensible minimum even for an empty list so the `emptyMessage`- // has room. An inline "+" trigger is tiny, so falling back to the trigger- // width would collapse the popover and wrap the message one word per line.- return Math.min(72, Math.max(36, maxOptionChars + 8));+ return combined.length > longest.length ? combined : longest;+ }, "");}, [options]);return (@@ -159,11 +160,17 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(align="start"onWheel={(e) => e.stopPropagation()}onTouchMove={(e) => e.stopPropagation()}- className="min-w-[var(--radix-popover-trigger-width)] max-w-[min(560px,calc(100vw-2rem))] p-1"- style={{- width: `min(560px, max(var(--radix-popover-trigger-width), ${dropdownContentWidthCh}ch))`- }}+ className="w-auto min-w-[max(var(--radix-popover-trigger-width),14rem)] max-w-[min(560px,calc(100vw-2rem))] p-1">+ {/* Zero-height sizer: the widest option, so the auto width fits it+ even when virtualization keeps it unrendered. px-8 covers item+ padding + the selected-check icon + scrollbar. */}+ <div+ aria-hidden+ className="invisible h-0 overflow-hidden whitespace-nowrap px-8 text-sm"+ >+ {longestOptionText}+ </div>{emptyMessage && options.length === 0 ? (emptyMessage) : (@@ -230,7 +237,7 @@ function VirtualizedCommand({count: filteredOptions.length,getScrollElement: () => parentRef.current,estimateSize: () => itemHeight,- overscan: 5+ overscan: 12});const items = virtualizer.getVirtualItems();diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsxindex 32374c593d..09cc9d3bc4 100644--- a/packages/react/src/CreateableCombobox.tsx+++ b/packages/react/src/CreateableCombobox.tsx@@ -89,10 +89,9 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(return [labelText, selectedOption.helper].filter(Boolean).join(" - ");}, [selectedOption]);- const dropdownContentWidthCh = useMemo(() => {- if (options.length === 0) return undefined;-- const maxOptionChars = options.reduce((longest, option) => {+ // Real-text sizer instead of a ch estimate — see Combobox.tsx.+ const longestOptionText = useMemo(() => {+ return options.reduce((longest, option) => {const labelText =typeof option.label === "string"? option.label@@ -101,10 +100,8 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(.filter(Boolean).join(" ");- return Math.max(longest, combined.length);- }, 0);-- return Math.min(72, Math.max(36, maxOptionChars + 8));+ return combined.length > longest.length ? combined : longest;+ }, "");}, [options]);return (@@ -173,21 +170,22 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(onWheel={(e) => e.stopPropagation()}onTouchMove={(e) => e.stopPropagation()}className={cn(- "max-w-[min(560px,calc(100vw-2rem))] p-1",+ "w-auto max-w-[min(560px,calc(100vw-2rem))] p-1",// Inline mode's trigger is a small icon button, so falling back to// the trigger width collapses the popover. Floor it to a usable width.inline? "min-w-[220px]"- : "min-w-[var(--radix-popover-trigger-width)]"+ : "min-w-[max(var(--radix-popover-trigger-width),14rem)]")}- style={{- width: dropdownContentWidthCh- ? `min(560px, max(var(--radix-popover-trigger-width), ${dropdownContentWidthCh}ch))`- : inline- ? "240px"- : "var(--radix-popover-trigger-width)"- }}>+ {/* Zero-height sizer: the widest option, so the auto width fits it+ even when virtualization keeps it unrendered. */}+ <div+ aria-hidden+ className="invisible h-0 overflow-hidden whitespace-nowrap px-8 text-sm"+ >+ {longestOptionText}+ </div>{emptyMessage && options.length === 0 ? (emptyMessage) : (@@ -288,7 +286,7 @@ function VirtualizedCommand({count: filteredOptions.length,getScrollElement: () => parentRef.current,estimateSize: () => itemHeight,- overscan: 5+ overscan: 12});const items = virtualizer.getVirtualItems();diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsxindex 4aa30eda4c..95915a2473 100644--- a/packages/react/src/CreateableMultiSelect.tsx+++ b/packages/react/src/CreateableMultiSelect.tsx@@ -89,18 +89,15 @@ const CreatableMultiSelect = forwardRef<.map((item) => options.find((option) => option.value === item)?.label).filter((label): label is string => Boolean(label));const selectedLabelText = selectedLabels.join(", ");- const dropdownContentWidthCh = useMemo(() => {- if (options.length === 0) return undefined;-- const maxOptionChars = options.reduce((longest, option) => {+ // Real-text sizer instead of a ch estimate — see Combobox.tsx.+ const longestOptionText = useMemo(() => {+ return options.reduce((longest, option) => {const combined = [option.label, option.helper].filter(Boolean).join(" ");- return Math.max(longest, combined.length);- }, 0);-- return Math.min(72, Math.max(36, maxOptionChars + 8));+ return combined.length > longest.length ? combined : longest;+ }, "");}, [options]);return (@@ -169,13 +166,16 @@ const CreatableMultiSelect = forwardRef<align="end"onWheel={(e) => e.stopPropagation()}onTouchMove={(e) => e.stopPropagation()}- className="min-w-[max(var(--radix-popover-trigger-width),11rem)] max-w-[min(560px,calc(100vw-2rem))] p-1"- style={{- width: dropdownContentWidthCh- ? `min(560px, max(var(--radix-popover-trigger-width), 11rem, ${dropdownContentWidthCh}ch))`- : "max(var(--radix-popover-trigger-width), 11rem)"- }}+ className="w-auto min-w-[max(var(--radix-popover-trigger-width),11rem)] max-w-[min(560px,calc(100vw-2rem))] p-1">+ {/* Zero-height sizer: the widest option, so the auto width fits it+ even when virtualization keeps it unrendered. */}+ <div+ aria-hidden+ className="invisible h-0 overflow-hidden whitespace-nowrap px-8 text-sm"+ >+ {longestOptionText}+ </div>{emptyMessage && options.length === 0 ? (emptyMessage) : (@@ -269,7 +269,7 @@ function VirtualizedCommand({count: filteredOptions.length,getScrollElement: () => parentRef.current,estimateSize: () => itemHeight,- overscan: 5+ overscan: 12});const items = virtualizer.getVirtualItems();diff --git a/packages/react/src/MultiSelect.tsx b/packages/react/src/MultiSelect.tsxindex 42aa05db08..ab7c87f1a8 100644--- a/packages/react/src/MultiSelect.tsx+++ b/packages/react/src/MultiSelect.tsx@@ -221,7 +221,7 @@ function VirtualizedCommand({count: filteredOptions.length,getScrollElement: () => parentRef.current,estimateSize: () => itemHeight,- overscan: 5+ overscan: 12});const items = virtualizer.getVirtualItems();diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.mdindex 36581a895f..710b8aa820 100644--- a/packages/utils/AGENTS.md+++ b/packages/utils/AGENTS.md@@ -36,6 +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)`, `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/accounting.ts b/packages/utils/src/accounting.tsindex adde452b9b..cc1e14f661 100644--- a/packages/utils/src/accounting.ts+++ b/packages/utils/src/accounting.ts@@ -87,11 +87,10 @@ export const MONTH_NUMBER: Record<string, number> = {// Fiscal year is named by its ending calendar year (FY2026 = the year that// ends in 2026). periodNumber is 1..12 counted from the fiscal start month.export function fiscalYearAndPeriodFor(- date: Date,+ year: number,+ month: number, // 1-12startMonth: number): { fiscalYear: number; periodNumber: number } {- const month = date.getMonth() + 1;- const year = date.getFullYear();const periodNumber = ((month - startMonth + 12) % 12) + 1;const fiscalYear =startMonth === 1 ? year : month >= startMonth ? year + 1 : year;diff --git a/packages/utils/src/datetime.test.ts b/packages/utils/src/datetime.test.tsnew file mode 100644index 0000000000..c6d5cdb532--- /dev/null+++ b/packages/utils/src/datetime.test.ts@@ -0,0 +1,208 @@+import {+ CalendarDate,+ CalendarDateTime,+ toZoned+} from "@internationalized/date";+import { describe, expect, it } from "vitest";+import { datetime } from "./datetime";++describe("datetime.businessDay", () => {+ it("assigns a late-evening US instant to the previous UTC day", () => {+ // 2026-02-01T04:59Z is still Jan 31 in Chicago (UTC-6)+ expect(+ datetime.businessDay("2026-02-01T04:59:00Z", "America/Chicago").toString()+ ).toBe("2026-01-31");+ expect(datetime.businessDay("2026-02-01T04:59:00Z", "UTC").toString()).toBe(+ "2026-02-01"+ );+ });++ it("assigns an early-morning UTC instant to the next day east of UTC", () => {+ // 23:30Z is already the next day in Tokyo (UTC+9)+ expect(+ datetime.businessDay("2026-08-04T23:30:00Z", "Asia/Tokyo").toString()+ ).toBe("2026-08-05");+ });++ it("handles DST transitions", () => {+ // US spring forward 2026-03-08: 07:30Z = 01:30 CST (UTC-6), same calendar day+ expect(+ datetime.businessDay("2026-03-08T07:30:00Z", "America/Chicago").toString()+ ).toBe("2026-03-08");+ // After the jump the offset is -5; 04:30Z on Mar 9 is still Mar 8 23:30 CDT+ expect(+ datetime.businessDay("2026-03-09T04:30:00Z", "America/Chicago").toString()+ ).toBe("2026-03-08");+ });+});++describe("datetime.today / datetime.now", () => {+ it("differ across the date line at the right moments", () => {+ // Can't pin the wall clock in a unit test, but the invariant holds always:+ // Pacific/Kiritimati (UTC+14) and Pacific/Niue (UTC-11) are 25h apart, so+ // they are never on the same calendar day.+ const east = datetime.today("Pacific/Kiritimati");+ const west = datetime.today("Pacific/Niue");+ expect(east.compare(west)).toBeGreaterThan(0);+ });++ it("now() carries the requested timezone", () => {+ expect(datetime.now("America/Chicago").timeZone).toBe("America/Chicago");+ });+});++describe("datetime.timestamp", () => {+ it("returns a UTC instant string", () => {+ expect(datetime.timestamp()).toMatch(/^\d{4}-\d{2}-\d{2}T.*Z$/);+ });+});++// 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 the reference UTC-arithmetic implementation for every day 2019-2031", () => {+ // Oracle: the previous native-Date implementation (covers week-53 years,+ // leap years, and both year-boundary spill directions).+ const oracle = (y: number, m: number, day: number): number => {+ const d = new Date(Date.UTC(y, m - 1, day));+ const dayNum = d.getUTCDay() || 7;+ d.setUTCDate(d.getUTCDate() + 4 - dayNum);+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));+ return Math.ceil(+ ((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7+ );+ };+ for (let y = 2019; y <= 2031; y++) {+ for (let m = 1; m <= 12; m++) {+ const first = new CalendarDate(y, m, 1);+ const days = first.calendar.getDaysInMonth(first);+ for (let d = 1; d <= days; d++) {+ expect(datetime.weekNumber(new CalendarDate(y, m, d))).toBe(+ oracle(y, m, d)+ );+ }+ }+ }+ });++ it("matches known ISO 8601 week numbers", () => {+ expect(+ datetime.weekNumber(datetime.businessDay("2026-01-01T12:00:00Z", "UTC"))+ ).toBe(1);+ // 2027-01-01 is a Friday → belongs to ISO week 53 of 2026+ expect(+ datetime.weekNumber(datetime.businessDay("2027-01-01T12:00:00Z", "UTC"))+ ).toBe(53);+ // 2024-12-30 (Monday) belongs to week 1 of 2025+ expect(+ datetime.weekNumber(datetime.businessDay("2024-12-30T12:00:00Z", "UTC"))+ ).toBe(1);+ expect(+ datetime.weekNumber(datetime.businessDay("2026-08-05T12:00:00Z", "UTC"))+ ).toBe(32);+ });+});diff --git a/packages/utils/src/datetime.ts b/packages/utils/src/datetime.tsnew file mode 100644index 0000000000..18d6f616ce--- /dev/null+++ b/packages/utils/src/datetime.ts@@ -0,0 +1,78 @@+import {+ CalendarDate,+ getDayOfWeek,+ now,+ parseAbsolute,+ startOfWeek,+ toCalendarDate,+ today+} from "@internationalized/date";++/**+ * ISO 8601 week number (1-53). Week 1 is the week containing the year's first+ * Thursday. Pure calendar arithmetic: en-GB is Monday-first, so getDayOfWeek+ * gives Mon=0…Sun=6 and `3 - dow` lands on the week's Thursday;+ * CalendarDate.compare returns whole days.+ */+function weekNumber(date: CalendarDate): number {+ const thursday = date.add({ days: 3 - getDayOfWeek(date, "en-GB") });+ return (+ Math.floor(thursday.compare(new CalendarDate(thursday.year, 1, 1)) / 7) + 1+ );+}++/**+ * The one sanctioned way to derive dates and times in server code.+ *+ * Every derivation method takes a mandatory IANA timezone — resolved from+ * `company.timezone` (ledger-scoped: accounting periods, posting dates,+ * sequence date tokens) or `location.timezone` (operational: scheduling,+ * shifts, MES) — so "which calendar day is it?" is never answered implicitly+ * by the process timezone. Client components displaying dates in the user's+ * browser timezone keep using `@internationalized/date` directly.+ */+export const datetime = {+ /** UTC instant string for timestamp columns (createdAt/updatedAt). The only timezone-free method. */+ timestamp: () => new Date().toISOString(),++ /** Current moment as a ZonedDateTime in the given business timezone. */+ now: (tz: string) => now(tz),++ /** Today as a CalendarDate in the given business timezone. */+ today: (tz: string) => today(tz),++ /** The business day a stored UTC instant falls on in the given timezone. */+ 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/src/geo.ts b/packages/utils/src/geo.tsindex d03f71fb9c..3ad4373f9f 100644--- a/packages/utils/src/geo.ts+++ b/packages/utils/src/geo.ts@@ -1,169 +1,95 @@-export const timezones: {- label: string;- options: {- label: string;- value: string;- }[];-}[] = [- {- label: "North America",- options: [- {- label: "Eastern Time",- value: "America/New_York"- },- {- label: "Central Time",- value: "America/Chicago"- },- {- label: "Mountain Time",- value: "America/Denver"- },- {- label: "Pacific Time",- value: "America/Los_Angeles"- },- {- label: "Alaska Time",- value: "America/Anchorage"- },- {- label: "Hawaii Time",- value: "Pacific/Honolulu"- }- ]- },- {- label: "Europe & Africa",- options: [- {- label: "Greenwich Mean Time",- value: "Europe/London"- },- {- label: "Central European Time",- value: "Europe/Berlin"- },- {- label: "Eastern European Time",- value: "Europe/Moscow"- },- {- label: "Western European Summer Time",- value: "Europe/Lisbon"- },- {- label: "Central Africa Time",- value: "Africa/Nairobi"- },- {- label: "East Africa Time",- value: "Africa/Addis_Ababa"- },- {- label: "South Africa Standard Time",- value: "Africa/Johannesburg"- }- ]- },- {- label: "Asia",- options: [- {- label: "Moscow Standard Time",- value: "Europe/Moscow"- },- {- label: "India Standard Time",- value: "Asia/Kolkata"- },- {- label: "China Standard Time",- value: "Asia/Shanghai"- },- {- label: "Japan Standard Time",- value: "Asia/Tokyo"- },- {- label: "Korea Standard Time",- value: "Asia/Seoul"- },- {- label: "Singapore Standard Time",- value: "Asia/Singapore"- },- {- label: "Australia Eastern Time",- value: "Australia/Sydney"- },- {- label: "Australia Central Time",- value: "Australia/Darwin"- },- {- label: "Australia Western Time",- value: "Australia/Perth"- },- {- label: "Indonesia Standard Time",- value: "Asia/Jakarta"- }- ]- },- {- label: "Australia & Pacific",- options: [- {- label: "Australia Eastern Time",- value: "Australia/Sydney"- },- {- label: "Australia Central Time",- value: "Australia/Darwin"- },- {- label: "Australia Western Time",- value: "Australia/Perth"- },- {- label: "New Zealand Standard Time",- value: "Pacific/Auckland"- },- {- label: "Fiji Time",- value: "Pacific/Fiji"- }- ]- },- {- label: "South America",- options: [- {- label: "Brasilia Time",- value: "America/Sao_Paulo"- },- {- label: "Argentina Time",- value: "America/Argentina/Buenos_Aires"- },- {- label: "Chile Time",- value: "America/Santiago"- },- {- label: "Peru Time",- value: "America/Lima"- },- {- label: "Colombia Time",- value: "America/Bogota"- },- {- label: "Venezuela Time",- value: "America/Caracas"- }- ]+export type TimezoneOption = { label: string; value: string };+export type TimezoneGroup = { label: string; options: TimezoneOption[] };++/** True when `tz` is an IANA timezone the runtime (and Postgres) can resolve. */+export function isValidTimeZone(tz: string): boolean {+ try {+ new Intl.DateTimeFormat("en-US", { timeZone: tz });+ return true;+ } catch {+ return false;}-];+}++function offsetLabel(zone: string): string {+ try {+ const parts = new Intl.DateTimeFormat("en-US", {+ timeZone: zone,+ timeZoneName: "longOffset"+ }).formatToParts(new Date());+ const name = parts.find((p) => p.type === "timeZoneName")?.value ?? "";+ // "GMT" (UTC itself) and "GMT-06:00" → "UTC±HH:MM"+ return name === "GMT" ? "UTC+00:00" : name.replace("GMT", "UTC");+ } catch {+ return "";+ }+}++let cachedTimezones: TimezoneGroup[] | null = null;+let cachedAt = 0;+// Offset labels show the CURRENT UTC offset, which changes at DST transitions —+// an immortal memo on a long-lived server would keep showing the old offset.+// One hour bounds the staleness while still amortizing the ~420 Intl lookups.+const CACHE_TTL_MS = 60 * 60 * 1000;++/**+ * IANA timezones from the runtime's own tzdata (`Intl.supportedValuesOf`) —+ * no hardcoded list to drift. Grouped by region, labeled with the current UTC+ * offset. Canonical IANA names, so every value is also valid for Postgres+ * `AT TIME ZONE` (used by `company_today()`). Memoized: the ~420 offset+ * lookups run at most once per hour, not per render.+ */+export function getTimezones(): TimezoneGroup[] {+ if (cachedTimezones && Date.now() - cachedAt < CACHE_TTL_MS) {+ return cachedTimezones;+ }++ const zones: string[] =+ typeof Intl.supportedValuesOf === "function"+ ? Intl.supportedValuesOf("timeZone")+ : [];+ // Bare "UTC" is the DB default and backfill value but is absent from some+ // runtimes' supported list — the picker must always be able to render it.+ if (!zones.includes("UTC")) zones.unshift("UTC");++ const groups = new Map<string, TimezoneOption[]>();+ for (const zone of zones) {+ const [region = "Other", ...rest] = zone.split("/");+ const city = rest.join("/").replace(/_/g, " ");+ const group = rest.length === 0 ? "Other" : region;+ const offset = offsetLabel(zone);+ const label = city+ ? `${city}${offset ? ` (${offset})` : ""}`+ : `${zone}${offset ? ` (${offset})` : ""}`;+ const options = groups.get(group) ?? [];+ options.push({ label, value: zone });+ groups.set(group, options);+ }++ const regionOrder = [+ "America",+ "Europe",+ "Asia",+ "Africa",+ "Australia",+ "Pacific",+ "Atlantic",+ "Indian",+ "Antarctica",+ "Arctic",+ "Other"+ ];++ cachedTimezones = [...groups.entries()]+ .sort(+ ([a], [b]) =>+ (regionOrder.indexOf(a) + 1 || 99) - (regionOrder.indexOf(b) + 1 || 99)+ )+ .map(([label, options]) => ({+ label,+ options: options.sort((a, b) => a.label.localeCompare(b.label))+ }));+ cachedAt = Date.now();++ return cachedTimezones;+}diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex b0d075398a..3163415ce5 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -8,6 +8,7 @@ export * from "./color";export * from "./const";export * from "./country";export * from "./date";+export * from "./datetime";export * from "./duration";export * from "./field-registry";export * from "./file";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d403230c05..073a227af9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -787,7 +787,7 @@ importers:version: 11.18.2(@emotion/[email protected])([email protected]([email protected]))([email protected])inngest:specifier: ^3.52.7- version: 3.54.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 3.54.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])intl-parse-accept-language:specifier: 'catalog:'version: 1.0.0@@ -1136,7 +1136,7 @@ importers:version: 5.9.4(@lingui/[email protected]([email protected])([email protected]))([email protected])([email protected])'@lingui/vite-plugin':specifier: 'catalog:'- version: 5.9.4([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.9.4([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@nanostores/react':specifier: 'catalog:'version: 0.7.3([email protected])([email protected])@@ -1148,10 +1148,10 @@ importers:version: 3.4.5([email protected])([email protected])'@react-router/dev':specifier: 'catalog:'- version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])+ version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])'@react-router/serve':specifier: 'catalog:'version: 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])@@ -1172,7 +1172,7 @@ importers:version: 0.5.19([email protected])'@tailwindcss/vite':specifier: 'catalog:'- version: 4.3.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.3.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@tanstack/react-query':specifier: 5.97.0version: 5.97.0([email protected])@@ -1217,7 +1217,7 @@ importers:version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])'@xyflow/react':specifier: 12.10.2version: 12.10.2(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -1347,13 +1347,13 @@ importers:version: 5.8.3vite:specifier: 'catalog:'- version: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-plugin-babel-macros:specifier: 'catalog:'- version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: 'catalog:'- version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wait-on:specifier: 'catalog:'version: 7.2.0@@ -1943,6 +1943,9 @@ importers:packages/database:dependencies:+ '@internationalized/date':+ specifier: 'catalog:'+ version: 3.12.0'@supabase/postgrest-js':specifier: 'catalog:'version: 2.80.0@@ -17088,7 +17091,7 @@ snapshots:'@babel/traverse': 7.29.0'@babel/types': 7.29.0convert-source-map: 2.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])gensync: 1.0.0-beta.2json5: 2.2.3semver: 7.7.4@@ -17108,7 +17111,7 @@ snapshots:'@babel/types': 7.29.0'@jridgewell/remapping': 2.3.5convert-source-map: 2.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])gensync: 1.0.0-beta.2json5: 2.2.3semver: 7.7.4@@ -17278,7 +17281,7 @@ snapshots:'@babel/parser': 7.29.2'@babel/template': 7.28.6'@babel/types': 7.29.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])globals: 11.12.0transitivePeerDependencies:- supports-color@@ -17291,7 +17294,7 @@ snapshots:'@babel/parser': 7.29.2'@babel/template': 7.28.6'@babel/types': 7.29.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -18364,16 +18367,6 @@ snapshots:transitivePeerDependencies:- typescript- '@lingui/[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@lingui/cli': 5.9.4([email protected])([email protected])- '@lingui/conf': 5.9.4([email protected])- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- transitivePeerDependencies:- - babel-plugin-macros- - supports-color- - typescript-'@lingui/[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@lingui/cli': 5.9.4([email protected])([email protected])@@ -18735,7 +18728,7 @@ snapshots:dependencies:'@oclif/core': 4.11.7ansis: 3.17.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])npm: 11.17.0npm-package-arg: 11.0.3npm-run-path: 5.3.0@@ -22102,56 +22095,6 @@ snapshots:- tsx- yaml- '@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':- dependencies:- '@babel/core': 7.29.0- '@babel/generator': 7.29.1- '@babel/parser': 7.29.2- '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])- '@babel/preset-typescript': 7.28.5(@babel/[email protected])- '@babel/traverse': 7.29.0- '@babel/types': 7.29.0- '@react-router/node': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- '@remix-run/node-fetch-server': 0.13.1- arg: 5.0.2- babel-dead-code-elimination: 1.0.12- chokidar: 4.0.3- dedent: 1.7.2([email protected])- es-module-lexer: 1.7.0- exit-hook: 2.2.1- isbot: 5.1.37- jsesc: 3.0.2- lodash: 4.17.21- p-map: 7.0.4- pathe: 1.1.2- picocolors: 1.1.1- pkg-types: 2.3.0- prettier: 3.8.1- react-refresh: 0.14.2- semver: 7.7.4- tinyglobby: 0.2.17- valibot: 1.3.1([email protected])- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- optionalDependencies:- '@react-router/serve': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- typescript: 5.8.3- transitivePeerDependencies:- - '@types/node'- - babel-plugin-macros- - jiti- - less- - lightningcss- - sass- - sass-embedded- - stylus- - sugarss- - supports-color- - terser- - tsx- - yaml-'@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@babel/core': 7.29.0@@ -22230,12 +22173,6 @@ snapshots:optionalDependencies:typescript: 5.8.3- '@react-router/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])':- dependencies:- '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])- optionalDependencies:- typescript: 5.8.3-'@react-router/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])':dependencies:'@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])@@ -23517,13 +23454,6 @@ snapshots:postcss-selector-parser: 6.0.10tailwindcss: 4.3.0- '@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@tailwindcss/node': 4.3.0- '@tailwindcss/oxide': 4.3.0- tailwindcss: 4.3.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])-'@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@tailwindcss/node': 4.3.0@@ -24391,16 +24321,6 @@ snapshots:'@vercel/[email protected]': {}- '@vercel/[email protected](patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])- '@react-router/node': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- '@vercel/static-config': 3.2.0- isbot: 5.1.37- react: 18.3.1- react-dom: 18.3.1([email protected])- ts-morph: 12.0.0-'@vercel/[email protected](patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])':dependencies:'@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])@@ -24539,14 +24459,6 @@ snapshots:optionalDependencies:vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@vitest/spy': 4.1.6- estree-walker: 3.0.3- magic-string: 0.30.21- optionalDependencies:- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])-'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@vitest/spy': 4.1.6@@ -25016,7 +24928,7 @@ snapshots:dependencies:bytes: 3.1.2content-type: 1.0.5- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])http-errors: 2.0.1iconv-lite: 0.7.2on-finished: 2.4.1@@ -25897,7 +25809,7 @@ snapshots:dependencies:'@socket.io/component-emitter': 3.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io-parser: 5.2.3ws: 8.21.0xmlhttprequest-ssl: 2.1.2@@ -25917,7 +25829,7 @@ snapshots:base64id: 2.0.0cookie: 0.7.2cors: 2.8.6- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io-parser: 5.2.3ws: 8.21.0transitivePeerDependencies:@@ -26334,7 +26246,7 @@ snapshots:content-type: 1.0.5cookie: 0.7.2cookie-signature: 1.2.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])depd: 2.0.0encodeurl: 2.0.0escape-html: 1.0.3@@ -26463,7 +26375,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])encodeurl: 2.0.0escape-html: 1.0.3on-finished: 2.4.1@@ -27029,14 +26941,14 @@ snapshots:dependencies:agent-base: 7.1.4- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-colordependencies:agent-base: 9.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -27130,6 +27042,44 @@ snapshots:+ [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):+ dependencies:+ '@bufbuild/protobuf': 2.11.0+ '@inngest/ai': 0.1.7+ '@jpwilliams/waitgroup': 2.1.1+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/auto-instrumentations-node': 0.72.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))+ '@opentelemetry/context-async-hooks': 2.6.1(@opentelemetry/[email protected])+ '@opentelemetry/exporter-trace-otlp-http': 0.214.0(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.6.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.6.1(@opentelemetry/[email protected])+ '@standard-schema/spec': 1.1.0+ '@traceloop/instrumentation-anthropic': 0.20.0+ '@types/debug': 4.1.13+ '@types/ms': 2.1.0+ canonicalize: 1.0.8+ chalk: 4.1.2+ cross-fetch: 4.1.0([email protected])+ debug: 4.4.3([email protected])+ hash.js: 1.1.7+ json-stringify-safe: 5.0.1+ ms: 2.1.3+ serialize-error-cjs: 0.1.4+ strip-ansi: 5.2.0+ temporal-polyfill: 0.2.5+ ulid: 2.4.0+ zod: 3.25.76+ optionalDependencies:+ express: 4.22.1+ hono: 4.12.14+ next: 16.2.3(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])+ typescript: 5.8.3+ transitivePeerDependencies:+ - '@opentelemetry/core'+ - encoding+ - supports-color+[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):dependencies:'@bufbuild/protobuf': 2.11.0@@ -27149,7 +27099,7 @@ snapshots:canonicalize: 1.0.8chalk: 4.1.2cross-fetch: 4.1.0([email protected])- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])hash.js: 1.1.7json-stringify-safe: 5.0.1ms: 2.1.3@@ -27211,7 +27161,7 @@ snapshots:dependencies:'@ioredis/commands': 1.5.1cluster-key-slot: 1.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])denque: 2.1.0lodash.defaults: 4.2.0lodash.isarguments: 3.1.0@@ -28337,7 +28287,7 @@ snapshots:dependencies:'@types/debug': 4.1.13- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])decode-named-character-reference: 1.3.0devlop: 1.1.0micromark-core-commonmark: 2.0.3@@ -29921,7 +29871,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])module-details-from-path: 1.0.4resolve: 1.22.11transitivePeerDependencies:@@ -29929,7 +29879,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])module-details-from-path: 1.0.4transitivePeerDependencies:- supports-color@@ -30046,7 +29996,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])depd: 2.0.0is-promise: 4.0.0parseurl: 1.3.3@@ -30154,7 +30104,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])encodeurl: 2.0.0escape-html: 1.0.3etag: 1.8.1@@ -30361,7 +30311,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])ws: 8.21.0transitivePeerDependencies:- bufferutil@@ -30382,7 +30332,7 @@ snapshots:dependencies:'@socket.io/component-emitter': 3.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -30391,7 +30341,7 @@ snapshots:accepts: 1.3.8base64id: 2.0.0cors: 2.8.6- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io: 6.6.9socket.io-adapter: 2.5.8socket.io-parser: 4.2.6@@ -30854,7 +30804,7 @@ snapshots:dependencies:callsites: 3.1.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])is-observable: 2.1.0observable-fns: 0.6.1optionalDependencies:@@ -31000,7 +30950,7 @@ snapshots:cac: 6.7.14chokidar: 4.0.3consola: 3.4.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])esbuild: 0.27.7fix-dts-default-cjs-exports: 1.0.1joycon: 3.1.1@@ -31028,7 +30978,7 @@ snapshots:cac: 6.7.14chokidar: 4.0.3consola: 3.4.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])esbuild: 0.27.7fix-dts-default-cjs-exports: 1.0.1joycon: 3.1.1@@ -31328,7 +31278,7 @@ snapshots:[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:cac: 6.7.14- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])es-module-lexer: 1.7.0pathe: 2.0.3vite: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -31349,7 +31299,7 @@ snapshots:[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:cac: 6.7.14- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])es-module-lexer: 1.7.0pathe: 2.0.3vite: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -31378,17 +31328,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):- dependencies:- '@babel/core': 7.29.0- '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])- '@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])- '@types/babel__core': 7.20.5- babel-plugin-macros: 3.1.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- transitivePeerDependencies:- - supports-color-[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@babel/core': 7.29.0@@ -31499,22 +31438,6 @@ snapshots:tsx: 4.21.0yaml: 2.8.3- [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):- dependencies:- lightningcss: 1.32.0- picomatch: 4.0.4- postcss: 8.5.15- rolldown: 1.0.0-rc.17- tinyglobby: 0.2.17- optionalDependencies:- '@types/node': 26.1.0- esbuild: 0.27.7- fsevents: 2.3.3- jiti: 2.7.0- terser: 5.48.0- tsx: 4.21.0- yaml: 2.8.3-[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.32.0@@ -31659,34 +31582,6 @@ snapshots:transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):- dependencies:- '@vitest/expect': 4.1.6- '@vitest/mocker': 4.1.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- '@vitest/pretty-format': 4.1.6- '@vitest/runner': 4.1.6- '@vitest/snapshot': 4.1.6- '@vitest/spy': 4.1.6- '@vitest/utils': 4.1.6- es-module-lexer: 2.0.0- expect-type: 1.3.0- magic-string: 0.30.21- obug: 2.1.1- pathe: 2.0.3- picomatch: 4.0.4- std-env: 4.0.0- tinybench: 2.9.0- tinyexec: 1.2.4- tinyglobby: 0.2.17- tinyrainbow: 3.1.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- why-is-node-running: 2.3.0- optionalDependencies:- '@opentelemetry/api': 1.9.0- '@types/node': 26.1.0- transitivePeerDependencies:- - msw-[email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.6diff --git a/sst.config.ts b/sst.config.tsindex eea37721ce..98bd480b60 100644--- a/sst.config.ts+++ b/sst.config.ts@@ -66,6 +66,7 @@ export default $config({JIRA_STATE_SECRET: process.env.JIRA_STATE_SECRET,MES_URL: process.env.URL_MES ? `https://${process.env.URL_MES}` : "https://mes.itar.carbon.ms",NODE_ENV: "production",+ TZ: "UTC",OPENAI_API_KEY: process.env.OPENAI_API_KEY,ONSHAPE_CLIENT_ID: process.env.ONSHAPE_CLIENT_ID,ONSHAPE_CLIENT_SECRET: process.env.ONSHAPE_CLIENT_SECRET,@@ -160,6 +161,7 @@ export default $config({INNGEST_SIGNING_KEY: process.env.INNGEST_SIGNING_KEY,MES_URL: process.env.URL_MES ? `https://${process.env.URL_MES}` : "https://mes.itar.carbon.ms",NODE_ENV: "production",+ TZ: "UTC",ONSHAPE_CLIENT_ID: process.env.ONSHAPE_CLIENT_ID,ONSHAPE_CLIENT_SECRET: process.env.ONSHAPE_CLIENT_SECRET,ONSHAPE_OAUTH_REDIRECT_URL: process.env.ONSHAPE_OAUTH_REDIRECT_URL,