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
fix(erp): address CodeRabbit review — cache scoping, fail-loud resolvers, mask fix
Sidwebworks021f33a6a237
diff --git a/.ai/plans/2026-08-06-timezone-audit-review-fixes.md b/.ai/plans/2026-08-06-timezone-audit-review-fixes.mdindex c698cd8525..b6a69ce69c 100644--- a/.ai/plans/2026-08-06-timezone-audit-review-fixes.md+++ b/.ai/plans/2026-08-06-timezone-audit-review-fixes.md@@ -33,7 +33,7 @@ Same pattern in two loader-called helpers — give `getWeekBounds` a `tz: string- `apps/erp/app/routes/x+/person+/$personId.timecard.tsx:70-79` (loader at :148)- `apps/mes/app/routes/x+/timecard.tsx:53-61` (loader at :125)-`from` = `startOfWeek(today(tz).add({weeks: offset}), "en-GB").toDate(tz).toISOString()`; `to` = next Monday's midnight minus 1ms (preserves the current lte semantics). Do NOT touch `getShiftTimesForDate` / `toLocalDatetimeInput` — verified client-called only (datetime-local input prefill; browser tz is correct there).+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)@@ -58,8 +58,8 @@ Edit `packages/database/supabase/migrations/20260805201623_company-today-sql-wri### 8. Jobs-package local-day fixes (#8, #13, + flagged)-- `packages/jobs/src/inngest/functions/extraction/extract-document.ts:24` — use `getUTCFullYear/getUTCMonth/getUTCDate` (document-intrinsic date; UTC makes parse→format roundtrip stable under any process tz).-- `packages/jobs/src/inngest/functions/scheduled/audit-archive.ts:52-54` — same UTC getters for the archive path (storage key, comment it).+- `packages/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)diff --git a/.ai/playbooks/company-timezone-differential.md b/.ai/playbooks/company-timezone-differential.mdindex 70487f9460..ac29c1d760 100644--- a/.ai/playbooks/company-timezone-differential.md+++ b/.ai/playbooks/company-timezone-differential.md@@ -15,8 +15,9 @@ timezone, not UTC — by setting a timezone whose calendar day differs from UTC.## Steps### 1. Pick a differential zone-- If UTC time is BEFORE ~10:00, `Pacific/Kiritimati` (UTC+14) is already tomorrow.-- If UTC time is AFTER ~12:00, `Pacific/Niue` (UTC-11) is still yesterday.+- 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@@ -28,13 +29,13 @@ timezone, not UTC — by setting a timezone whose calendar day differs from UTC.### 3. Create a PO- /x/purchase-order/new → select supplier (first combobox) → requestSubmit "Save".-- Verify: `SELECT "orderDate", "createdAt" FROM "purchaseOrder" ORDER BY "createdAt" DESC LIMIT 1;`+- 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" ORDER BY "createdAt" DESC LIMIT 1;`+- 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)@@ -43,10 +44,10 @@ timezone, not UTC — by setting a timezone whose calendar day differs from UTC.for the adjustment to post a non-zero journal (FIFO/LIFO increases cost fromempty 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" WHERE j."companyId"='<id>' ORDER BY j."createdAt" DESC LIMIT 1;`+- 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 thecompany's month (proves getCurrentAccountingPeriod uses companyToday.year/month).-- **costLedger must match itemLedger**: `SELECT "postingDate" FROM "costLedger" ORDER BY "createdAt" DESC LIMIT 1;`+- **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 showsthe UTC day, a costLedger insert is missing `postingDate:` and fell back to`DEFAULT CURRENT_DATE` — regression guard.@@ -69,5 +70,5 @@ timezone, not UTC — by setting a timezone whose calendar day differs from UTC.city/postalCode/countryCode → validation errors below the fields. Fill address first.- `agent-browser type "text"` without a ref treats the text as a selector andtimes out — always pass the element ref, or use the native-setter eval.-- Constraint check: `UPDATE company SET timezone='Fake/Zone'` must FAIL- (company_timezone_valid) — use this as a negative test.+- 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/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex de1dcc6cce..ec72b3898c 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -3420,13 +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 ??- datetime- .today(await getCompanyTimeZone(client, entry.data.companyId))- .toString(),+ postingDate,"accounting");if (period.error) {@@ -3441,6 +3445,7 @@ export async function postJournalEntry(postedAt: new Date().toISOString(),postedBy: userId,accountingPeriodId: period.data,+ postingDate,updatedBy: userId}).eq("id", id)diff --git a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsxindex 3887a4a216..d12dea3b83 100644--- a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx+++ b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx@@ -137,9 +137,12 @@ function SourcePostingDateSync({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());- }, [timezone, setPostingDate]);+ // biome-ignore lint/correctness/useExhaustiveDependencies: sourceCompanyId intentionally re-triggers the default+ }, [sourceCompanyId, timezone, setPostingDate]);return null;}diff --git a/apps/erp/app/modules/shared/timezone.server.ts b/apps/erp/app/modules/shared/timezone.server.tsindex 7ba3dc0871..0fc3d51763 100644Binary files a/apps/erp/app/modules/shared/timezone.server.ts and b/apps/erp/app/modules/shared/timezone.server.ts differdiff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 0d87d766e9..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,5 +1,5 @@{- "generated": "2026-08-05T21:13:43.723Z",+ "generated": "2026-08-05T21:50:58.234Z","totalTools": 1414,"modules": 15,"tools": [diff --git a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx b/apps/erp/app/routes/x+/person+/$personId.timecard.tsxindex fd369a1783..1fa5cc9280 100644--- a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx+++ b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx@@ -30,6 +30,7 @@ import {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";@@ -130,10 +131,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const weekOffset = parseInt(url.searchParams.get("week") ?? "0", 10);// Week runs Monday → Sunday on the company calendar (one payroll boundary// per books, not the server's zone).- const { from, to } = datetime.weekBounds(- await getCompanyTimeZone(client, companyId),- weekOffset- );+ 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([@@ -177,6 +181,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {weekOffset,from,to,+ weekStart,+ weekEnd,shift};}@@ -348,7 +354,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>();@@ -372,8 +378,6 @@ export default function PersonTimecardRoute() {return () => clearInterval(interval);}, []);- const monday = new Date(from);- const sunday = new Date(to);const isCurrentWeek = weekOffset === 0;useEffect(() => {@@ -476,8 +480,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"@@ -537,12 +541,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+/resources+/locations.$locationId.tsx b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsxindex 4568b738db..8bd8264f82 100644--- a/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx+++ b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx@@ -44,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"});@@ -76,7 +76,7 @@ export async function action({ request }: ActionFunctionArgs) {}// location.timezone may have changed — drop the cached resolution.- await invalidateLocationTimeZone(id);+ await invalidateLocationTimeZone(id, companyId);throw redirect(path.to.locations,diff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsxindex d7eef60912..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,@@ -499,7 +498,8 @@ export async function loader({ request }: LoaderFunctionArgs) {tags: tags.data ?? [],locationId,view,- currentDate: currentDate.toString()+ currentDate: currentDate.toString(),+ timezone};}@@ -529,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) => {@@ -655,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+/supplier-quote+/update.tsx b/apps/erp/app/routes/x+/supplier-quote+/update.tsxindex 241c33c8ab..aca6c55893 100644--- a/apps/erp/app/routes/x+/supplier-quote+/update.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/update.tsx@@ -1,5 +1,7 @@import { requirePermissions } from "@carbon/auth/auth.server";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";@@ -99,25 +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))- .toString();+ const companyToday = datetime.today(+ await getCompanyTimeZone(client, companyId)+ );return await client.from("supplierQuote").update({- status: value- ? companyToday > 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/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsxindex ffe49db668..93e307dccd 100644--- a/apps/mes/app/routes/x+/timecard.tsx+++ b/apps/mes/app/routes/x+/timecard.tsx@@ -107,10 +107,12 @@ export async function loader({ request }: LoaderFunctionArgs) {const weekOffset = parseInt(url.searchParams.get("week") ?? "0", 10);// Week runs Monday → Sunday on the company calendar (one payroll boundary// per books, not the server's zone).- const { from, to } = datetime.weekBounds(- await getCompanyTimeZone(client, companyId),- weekOffset- );+ 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@@ -129,7 +131,9 @@ export async function loader({ request }: LoaderFunctionArgs) {openEntry: openEntry.data,weekOffset,from,- to+ to,+ weekStart,+ weekEnd};}@@ -183,7 +187,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);@@ -198,8 +202,6 @@ export default function MESTimecardPage() {clockIn: string;} | null>(null);- const monday = new Date(from);- const sunday = new Date(to);const isCurrentWeek = weekOffset === 0;useEffect(() => {@@ -274,8 +276,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/operations.service.ts b/apps/mes/app/services/operations.service.tsindex e860c2497a..01edee9236 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -659,8 +659,17 @@ export async function getJobMaterialsByOperationId(.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 ?? ""))+ .today(await getCompanyTimeZone(client, job.data.companyId)).toString();expiredConsumed = await client.from("trackedEntity")diff --git a/packages/checks/src/conformance/no-local-timezone.test.ts b/packages/checks/src/conformance/no-local-timezone.test.tsindex bdf024cf2b..daa6409069 100644--- a/packages/checks/src/conformance/no-local-timezone.test.ts+++ b/packages/checks/src/conformance/no-local-timezone.test.ts@@ -21,6 +21,16 @@ describe("noLocalTimezone", () => {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()];",diff --git a/packages/checks/src/conformance/no-local-timezone.ts b/packages/checks/src/conformance/no-local-timezone.tsindex 6423809db0..a958b59d52 100644--- a/packages/checks/src/conformance/no-local-timezone.ts+++ b/packages/checks/src/conformance/no-local-timezone.ts@@ -21,10 +21,12 @@ const BANNED = ["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,+ /new Date\([^)]*\)\s*\.toISOString\(\)\s*\.(?:split\(\s*["']T["']\s*\)\s*\[0\]|slice\(\s*0,\s*10\s*\))/g,message:- "Server code: this is the UTC calendar day — use datetime.today(tz) with the company/location timezone."+ "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,diff --git a/packages/checks/src/sources/server-files.test.ts b/packages/checks/src/sources/server-files.test.tsindex fea2512c67..f8ff51fb23 100644--- a/packages/checks/src/sources/server-files.test.ts+++ b/packages/checks/src/sources/server-files.test.ts@@ -75,6 +75,53 @@ describe("maskClientCode", () => {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() {",diff --git a/packages/checks/src/sources/server-files.ts b/packages/checks/src/sources/server-files.tsindex 184e4491cc..afbcb8d77d 100644--- a/packages/checks/src/sources/server-files.ts+++ b/packages/checks/src/sources/server-files.ts@@ -1,4 +1,4 @@-import { readdirSync, readFileSync, statSync } from "node:fs";+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";import { join, relative } from "node:path";import type { SqlFile } from "./migrations";@@ -43,6 +43,9 @@ const CLIENT_REGION_START = [];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);@@ -58,12 +61,27 @@ function walk(dir: string, out: string[], extensions: string[]): void {}}+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 `}` — reliable because the repo is Biome-formatted, so a top-level- * closing brace is never indented.+ * 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");@@ -72,11 +90,20 @@ export function maskClientCode(contents: string): string {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] = "";- if (line.startsWith("}")) inClientRegion = false;+ // `}`/`};` 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;+ }}});diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex 930e641d81..f1fb65a9ee 100644--- a/packages/database/AGENTS.md+++ b/packages/database/AGENTS.md@@ -41,7 +41,7 @@ pnpm --filter @carbon/database typecheck| `./sampling` | Node-side re-export of `supabase/functions/shared/sampling-engine.ts` (Z1.4 / ISO 2859-1 resolvers) || `./audit` | Audit-log functions (`getEntityAuditLog`, `enableAuditLog`, `syncAuditSubscriptions`, …); `auditConfig` + `AuditEntityType` come from the separate `./audit.config` subpath || `./ratelimit` | `checkApiKeyRateLimit` (Postgres RPC wrapper) |-| `.` (timezone) | `getCompanyTimeZone(db, companyId)` / `getLocationTimeZone(db, locationId, companyId)` (`src/timezone.ts`) — business-timezone resolvers, overloaded for Supabase client or Kysely handle; `AnyPostgresClient` + `isKysely` guard (`src/utils.ts`) for writing such overloads. SQL siblings: `company_today(companyId)` / `location_today(locationId, companyId)` replace `CURRENT_DATE` for business dates in DB functions (SECURITY INVOKER — callers must be SECURITY DEFINER or service-role). ERP routes should prefer the Redis-cached wrappers in `~/modules/shared/timezone.server` |+| `.` (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/src/timezone.ts b/packages/database/src/timezone.tsindex e5b751c908..90eb1a5e6f 100644--- a/packages/database/src/timezone.ts+++ b/packages/database/src/timezone.ts@@ -40,6 +40,13 @@ export async function getCompanyTimeZone(.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";}@@ -84,5 +91,10 @@ export async function getLocationTimeZone(.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/issue/index.ts b/packages/database/supabase/functions/issue/index.tsindex f6e2d50be2..aa9b4bb33c 100644--- a/packages/database/supabase/functions/issue/index.ts+++ b/packages/database/supabase/functions/issue/index.ts@@ -17,7 +17,7 @@ import { Database } from "../lib/types.ts";import { TrackedEntityAttributes, credit, debit, journalReference } from "../lib/utils.ts";import { buildBatchSplitRecords } from "../shared/batch-split.ts";-import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";+import { getAccountingPeriodForDate } from "../shared/get-accounting-period.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";import { getNextSerialNumbers } from "../shared/get-next-serial-number.ts";import {@@ -449,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 getAccountingPeriodForDate(client, companyId, trx, today);const journalEntryId = await getNextSequence(trx, "journalEntry", companyId);const journalResult = await trx@@ -458,7 +460,7 @@ async function issueJobOperationMaterials(journalEntryId,accountingPeriodId,description: `Material Issue to Job ${job?.jobId ?? jobId}`,- postingDate: datetime.today(await getCompanyTimeZone(client, companyId)).toString(),+ postingDate: today,companyId,sourceType: "Job Consumption",status: "Posted",@@ -715,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 getAccountingPeriodForDate(client, companyId, trx, today);const journalEntryId = await getNextSequence(trx, "journalEntry", companyId);const journalResult = await trx@@ -724,7 +727,7 @@ async function createMaterialWipEntries(journalEntryId,accountingPeriodId,description,- postingDate: datetime.today(await getCompanyTimeZone(client, companyId)).toString(),+ postingDate: today,companyId,sourceType: "Job Consumption",status: "Posted",diff --git a/packages/database/supabase/functions/lib/datetime.ts b/packages/database/supabase/functions/lib/datetime.tsindex 6eaabd0d61..22477e926e 100644--- a/packages/database/supabase/functions/lib/datetime.ts+++ b/packages/database/supabase/functions/lib/datetime.ts@@ -107,6 +107,13 @@ export async function getCompanyTimeZone(.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";}@@ -141,5 +148,10 @@ export async function getLocationTimeZone(.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/migrations/20260805020925_company-timezone.sql b/packages/database/supabase/migrations/20260805020925_company-timezone.sqlindex e40ecf1e1c..ec8b5d4355 100644--- a/packages/database/supabase/migrations/20260805020925_company-timezone.sql+++ b/packages/database/supabase/migrations/20260805020925_company-timezone.sql@@ -10,13 +10,23 @@ ALTER DATABASE postgres SET timezone TO 'UTC';ALTER TABLE "company"ADD COLUMN "timezone" TEXT NOT NULL DEFAULT 'UTC';--- Backfill from each company's first location ("first location = HQ" assumption).+-- 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" cSET "timezone" = l."timezone"FROM (SELECT DISTINCT ON ("companyId") "companyId", "timezone"FROM "location"- WHERE "timezone" IS NOT NULL AND "timezone" <> ''+ 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) lWHERE c."id" = l."companyId";diff --git a/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql b/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sqlindex 21690cf557..882133b05c 100644--- a/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql+++ b/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql@@ -124,6 +124,7 @@ DECLAREv_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@@ -172,13 +173,28 @@ BEGINRAISE EXCEPTION 'No elimination entity found for company group %', p_company_group_id;END IF;- -- Get active accounting period for elimination entity+ -- 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_idFROM "accountingPeriod"WHERE "companyId" = v_elim_id- AND "status" = 'Active'+ AND "startDate" <= v_posting_date+ AND "endDate" >= v_posting_dateLIMIT 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 entityINSERT INTO "journal" ("description", "accountingPeriodId", "companyId", "postingDate")VALUES (@@ -186,7 +202,7 @@ BEGINv_period_id,v_elim_id,-- Ledger date: the elimination entity's calendar, not the database's.- company_today(v_elim_id)+ v_posting_date)RETURNING "id" INTO v_journal_id;diff --git a/packages/jobs/src/inngest/functions/extraction/extract-document.ts b/packages/jobs/src/inngest/functions/extraction/extract-document.tsindex 0989b5a1bb..2199f1ec66 100644--- a/packages/jobs/src/inngest/functions/extraction/extract-document.ts+++ b/packages/jobs/src/inngest/functions/extraction/extract-document.ts@@ -20,10 +20,13 @@ function parseDateToISO8601(value: unknown): string | null {const parsed = Date.parse(cleaned);if (isNaN(parsed)) return null;- // UTC parts: the date is document-intrinsic, and Date.parse of a bare date- // lands on UTC midnight — local getters would shift it a day under TZ ≠ UTC.+ // 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.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}`;+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;}export const extractDocumentFunction = inngest.createFunction(diff --git a/packages/jobs/src/inngest/functions/scheduled/audit-archive.ts b/packages/jobs/src/inngest/functions/scheduled/audit-archive.tsindex ee1df16185..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,12 +48,12 @@ async function archiveCompanyLogs(const jsonl = records.map((r) => JSON.stringify(r)).join("\n");const gzipped = gzipSync(Buffer.from(jsonl));- // Generate archive path — a storage key, so the UTC calendar is fine; UTC- // parts keep the path deterministic under any process timezone.- const nowDate = new Date();- const year = nowDate.getUTCFullYear();- const month = String(nowDate.getUTCMonth() + 1).padStart(2, "0");- const day = String(nowDate.getUTCDate()).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/utils/src/geo.ts b/packages/utils/src/geo.tsindex dc7eb2801f..3ad4373f9f 100644--- a/packages/utils/src/geo.ts+++ b/packages/utils/src/geo.ts@@ -26,16 +26,23 @@ function offsetLabel(zone: string): string {}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 once, on first use, not at module load.+ * lookups run at most once per hour, not per render.*/export function getTimezones(): TimezoneGroup[] {- if (cachedTimezones) return cachedTimezones;+ if (cachedTimezones && Date.now() - cachedAt < CACHE_TTL_MS) {+ return cachedTimezones;+ }const zones: string[] =typeof Intl.supportedValuesOf === "function"@@ -82,6 +89,7 @@ export function getTimezones(): TimezoneGroup[] {label,options: options.sort((a, b) => a.label.localeCompare(b.label))}));+ cachedAt = Date.now();return cachedTimezones;}