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
Sidwebworksecee8c59b31a
diff --git a/.ai/playbooks/company-timezone-differential.md b/.ai/playbooks/company-timezone-differential.mdnew file mode 100644index 0000000000..70487f9460--- /dev/null+++ b/.ai/playbooks/company-timezone-differential.md@@ -0,0 +1,73 @@+# 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 BEFORE ~10:00, `Pacific/Kiritimati` (UTC+14) is already tomorrow.+- If UTC time is AFTER ~12:00, `Pacific/Niue` (UTC-11) is still yesterday.+- 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" 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;`+ → 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" WHERE j."companyId"='<id>' 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" 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'` 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..1606ecdffb 100644--- a/.claude/rules/date-handling.md+++ b/.claude/rules/date-handling.md@@ -34,8 +34,25 @@ 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 enforced by the `no-local-timezone` conformance check+in `@carbon/checks`. 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`) instead of `CURRENT_DATE` for business dates.++Client components keep `today(getLocalTimeZone())` etc. — in the browser the+local timezone IS the user's and is correct for pickers and display.## Repo patterns to copydiff --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/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex b91770536d..164c256f41 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";@@ -656,18 +659,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 +1263,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 +2980,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(@@ -3410,7 +3421,10 @@ export async function postJournalEntry(const period = await getOrCreateAccountingPeriod(client,entry.data.companyId,- entry.data.postingDate ?? new Date().toISOString().split("T")[0],+ entry.data.postingDate ??+ datetime+ .today(await getCompanyTimeZone(client, entry.data.companyId))+ .toString(),"accounting");if (period.error) {@@ -3474,7 +3488,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/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 921c3a1de2..ec69da0f20 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();@@ -2252,7 +2253,7 @@ export async function updateItemCost(.update({...cost,costIsAdjusted: true,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("itemId", itemId).single();@@ -2298,7 +2299,7 @@ export async function updateRevision(.from("item").update({...revision,- updatedAt: today(getLocalTimeZone()).toString()+ updatedAt: datetime.timestamp()}).eq("id", revision.id);}@@ -2318,7 +2319,7 @@ export async function upsertConfigurationParameter(sanitize({...data,updatedBy: userId,- updatedAt: now(getLocalTimeZone()).toAbsoluteString()+ updatedAt: datetime.timestamp()})).eq("id", configurationParameter.id);@@ -2483,7 +2484,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" });@@ -2714,7 +2715,7 @@ export async function upsertPickMethodWithShelfLife(};}) {- const updatedAt = now(getLocalTimeZone()).toAbsoluteString();+ const updatedAt = datetime.timestamp();return db.transaction().execute(async (trx) => {await trx@@ -2850,7 +2851,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@@ -2998,7 +2999,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@@ -3037,7 +3038,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 = (@@ -3201,14 +3202,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)]);@@ -3501,14 +3502,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)]);@@ -4519,14 +4520,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)]);@@ -4876,7 +4877,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@@ -4884,7 +4885,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 ?? "")@@ -5032,14 +5033,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/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 b07d6e316e..1e79f6300b 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,@@ -152,11 +152,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)@@ -1980,7 +1989,7 @@ export async function finalizeQuote(.from("quote").update({status: "Sent",- updatedAt: today(getLocalTimeZone()).toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId}).eq("id", quoteId);@@ -1993,7 +2002,7 @@ export async function finalizeQuote(.from("quoteLine").update({status: "Complete",- updatedAt: today(getLocalTimeZone()).toString(),+ updatedAt: datetime.timestamp(),updatedBy: userId}).neq("status", "No Quote")@@ -2009,7 +2018,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);@@ -2020,7 +2029,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;@@ -2251,7 +2262,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@@ -2646,7 +2659,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/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/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..7ba3dc0871--- /dev/null+++ b/apps/erp/app/modules/shared/timezone.server.ts@@ -0,0 +1,58 @@+import type { AnyPostgresClient } from "@carbon/database";+import {+ getCompanyTimeZone as resolveCompanyTimeZone,+ getLocationTimeZone as resolveLocationTimeZone+} 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}`;+// location.id is a globally-unique xid, so it alone keys the entry.+const locationKey = (locationId: string) => `timezone:location:${locationId}`;++/** 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 {@link resolveLocationTimeZone}. */+export async function getLocationTimeZone(+ db: AnyPostgresClient,+ locationId: string,+ companyId: string+): Promise<string> {+ const key = locationKey(locationId);+ const cached = await redis.get(key);+ if (cached) return cached;++ const tz = await resolveLocationTimeZone(db, locationId, companyId);+ await redis.set(key, tz, "EX", TTL_SECONDS);+ return tz;+}++/** 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+): Promise<void> {+ await redis.del(locationKey(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+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 7a4fd33799..e773de38b5 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-04T18:59:18.405Z",- "totalTools": 1413,+ "generated": "2026-08-05T19:39:38.408Z",+ "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..ac2a1f5282 100644--- a/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx+++ b/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx@@ -2,6 +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 type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, redirect, useLoaderData, useNavigate } from "react-router";import {@@ -73,7 +74,9 @@ export default function NewIntercompanyTransactionRoute() {description: "",debitAccountId: "",creditAccountId: "",- postingDate: new Date().toISOString().split("T")[0]+ // Client component: default to the user's calendar day; the action+ // re-defaults an empty postingDate in the source company's timezone.+ postingDate: today(getLocalTimeZone()).toString()};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+/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+/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+/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+/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+/resources+/locations.$locationId.tsx b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsxindex ee9784924b..4568b738db 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";@@ -74,6 +75,9 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // location.timezone may have changed — drop the cached resolution.+ await invalidateLocationTimeZone(id);+throw redirect(path.to.locations,await flash(request, success("Location updated"))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+/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..6a3da757ea 100644--- a/apps/erp/app/routes/x+/settings+/companies.new.tsx+++ b/apps/erp/app/routes/x+/settings+/companies.new.tsx@@ -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..dc023a4046 100644--- a/apps/erp/app/routes/x+/settings+/company.new.tsx+++ b/apps/erp/app/routes/x+/settings+/company.new.tsx@@ -58,7 +58,7 @@ export async function action({ request }: ActionFunctionArgs) {...locationData,name: "Headquarters",companyId,- timezone: getLocalTimeZone(),+ timezone: validation.data.timezone || getLocalTimeZone(),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/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..6fdef74c2b 100644--- a/apps/erp/app/utils/string.ts+++ b/apps/erp/app/utils/string.ts@@ -63,20 +63,53 @@ export const getISOWeek = (date: Date): number => {return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);};-// used to generate sequences-export const interpolateSequenceDate = (value: string | null) => {+// Current wall-clock parts in an explicit timezone (for server callers that+// derive sequence tokens in the company's business timezone).+const datePartsInTimeZone = (timezone: string) => {+ const parts = new Intl.DateTimeFormat("en-US", {+ timeZone: timezone,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ second: "2-digit",+ hourCycle: "h23"+ }).formatToParts(new Date());+ const get = (type: Intl.DateTimeFormatPartTypes) =>+ Number(parts.find((p) => p.type === type)?.value ?? 0);+ return {+ year: get("year"),+ month: get("month"),+ day: get("day"),+ hours: get("hour"),+ seconds: get("second")+ };+};++// used to generate sequences. Server callers pass the company timezone so+// tokens roll over at the company's midnight; the client-side sequence-preview+// forms omit it and preview in the browser's timezone.+export const interpolateSequenceDate = (+ value: string | null,+ timezone?: string+) => {// 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 parts = timezone+ ? datePartsInTimeZone(timezone)+ : {+ year: date.getFullYear(),+ month: date.getMonth() + 1,+ day: date.getDate(),+ hours: date.getHours(),+ seconds: date.getSeconds()+ };+ const { year, month, day, hours, seconds } = parts;+ const week = getISOWeek(new Date(year, month - 1, day));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/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..e860c2497a 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,25 @@ 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();+ 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..5dd0ff2740 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- **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..ee0b9be4fc--- /dev/null+++ b/packages/checks/src/conformance/no-local-timezone.test.ts@@ -0,0 +1,40 @@+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("allows full-instant timestamps", () => {+ const ts = "const at = new Date().toISOString();";+ 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..3e4eae6c45--- /dev/null+++ b/packages/checks/src/conformance/no-local-timezone.ts@@ -0,0 +1,47 @@+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+ * 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.+ */+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."+ },+ {+ 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) with the company/location timezone."+ }+];++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.ts b/packages/checks/src/sources/server-files.tsnew file mode 100644index 0000000000..09992cf84b--- /dev/null+++ b/packages/checks/src/sources/server-files.ts@@ -0,0 +1,55 @@+import { 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"];++function walk(dir: string, out: string[]): void {+ 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);+ } else if (entry.endsWith(".ts") && !entry.endsWith(".test.ts")) {+ out.push(path);+ }+ }+}++/** 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);+ }++ const erpPaths: string[] = [];+ walk(join(root, ERP_MODULES_ROOT), erpPaths);+ for (const path of erpPaths) {+ if (ERP_SERVER_SUFFIXES.some((suffix) => path.endsWith(suffix))) {+ paths.push(path);+ }+ }++ return paths+ .map((path) => relative(root, path))+ .sort()+ .map((file) => ({+ file,+ contents: readFileSync(join(root, file), "utf8")+ }));+}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..e5b751c908--- /dev/null+++ b/packages/database/src/timezone.ts@@ -0,0 +1,88 @@+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();+ 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();+ return location.data?.timezone || getCompanyTimeZone(db, companyId);+}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 82ae43cb1d..5ebadd83d8 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@@ -70163,14 +70167,14 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ 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: numberdiff --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..bc9bb03e2c 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([clientdiff --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/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..f6e2d50be2 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 "npm:@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();@@ -448,7 +458,7 @@ async function issueJobOperationMaterials(journalEntryId,accountingPeriodId,description: `Material Issue to Job ${job?.jobId ?? jobId}`,- postingDate: new Date().toISOString().slice(0, 10),+ postingDate: datetime.today(await getCompanyTimeZone(client, companyId)).toString(),companyId,sourceType: "Job Consumption",status: "Posted",@@ -544,6 +554,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 +699,7 @@ async function createMaterialWipEntries(quantity: isConsumption ? -absQty : absQty,cost: isConsumption ? -cost : cost,remainingQuantity: 0,+ postingDate: today,companyId,}).execute();@@ -707,7 +724,7 @@ async function createMaterialWipEntries(journalEntryId,accountingPeriodId,description,- postingDate: new Date().toISOString().slice(0, 10),+ postingDate: datetime.today(await getCompanyTimeZone(client, companyId)).toString(),companyId,sourceType: "Job Consumption",status: "Posted",@@ -1881,6 +1898,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 +1972,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 +2262,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 +3056,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 +3127,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 +3243,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..a10b34bf19--- /dev/null+++ b/packages/database/supabase/functions/lib/datetime.ts@@ -0,0 +1,122 @@+// 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.+import {+ type CalendarDate,+ now,+ parseAbsolute,+ toCalendarDate,+ today+} from "npm:@internationalized/date";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { Kysely } from "kysely";+import type { DB } from "./database.ts";+import { type AnyPostgresClient, isKysely } from "./utils.ts";+import type { Database } from "./types.ts";++/**+ * ISO 8601 week number (1-53). Week 1 is the week containing the year's first+ * Thursday. Pure UTC arithmetic on the date parts — no timezone dependency.+ */+function weekNumber(date: CalendarDate): number {+ const d = new Date(Date.UTC(date.year, date.month - 1, date.day));+ const dayNum = d.getUTCDay() || 7; // Sunday → 7+ d.setUTCDate(d.getUTCDate() + 4 - dayNum); // shift to the week's Thursday+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));+ return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);+}++/**+ * 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();+ 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();+ 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 82ae43cb1d..5ebadd83d8 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@@ -70163,14 +70167,14 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ 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: numberdiff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.tsindex ecf18994a6..96227f1bb1 100644--- a/packages/database/supabase/functions/lib/utils.ts+++ b/packages/database/supabase/functions/lib/utils.ts@@ -1,3 +1,26 @@+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;@@ -18,30 +41,54 @@ export interface TrackedEntityAttributes {}// 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 isoWeekFromYmd = (year: number, month: number, day: number): number => {+ const d = new Date(Date.UTC(year, month - 1, day));const dayNum = d.getUTCDay() || 7; // Sunday → 7d.setUTCDate(d.getUTCDate() + 4 - dayNum); // shift to the week's Thursdayconst 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) => {+export const getISOWeek = (date: Date): number =>+ isoWeekFromYmd(date.getFullYear(), date.getMonth() + 1, date.getDate());++// Current wall-clock parts in an explicit timezone. Intl-based so this module+// stays importable from both Deno and Node (no npm:/workspace deps).+const datePartsInTimeZone = (timezone: string) => {+ const parts = new Intl.DateTimeFormat("en-US", {+ timeZone: timezone,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ second: "2-digit",+ hourCycle: "h23",+ }).formatToParts(new Date());+ const get = (type: Intl.DateTimeFormatPartTypes) =>+ Number(parts.find((p) => p.type === type)?.value ?? 0);+ return {+ year: get("year"),+ month: get("month"),+ day: get("day"),+ hours: get("hour"),+ seconds: get("second"),+ };+};++// 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, hours, seconds } = datePartsInTimeZone(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 +106,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..993d5d4f8a 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";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..35e7193f27 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 [diff --git a/packages/database/supabase/functions/post-inventory-count/index.ts b/packages/database/supabase/functions/post-inventory-count/index.tsindex 336bdcfd01..c161b438b3 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 clientdiff --git a/packages/database/supabase/functions/post-memo/index.ts b/packages/database/supabase/functions/post-memo/index.tsindex 1db76f1165..ca5dbceb74 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")diff --git a/packages/database/supabase/functions/post-nonconformance/index.ts b/packages/database/supabase/functions/post-nonconformance/index.tsindex 92850df900..5d6035dacd 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);diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.tsindex 8d05a5a668..e986a52a0c 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")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..cda66eddb4 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([clientdiff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsindex 4f61351235..f9acb64f19 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,6 +328,7 @@ serve(async (req: Request) => {cost: -entry.cost,supplierId: entry.supplierId,companyId,+ postingDate: today,}));const accountingPeriodIdVoid = accountingEnabled@@ -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.diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.tsindex 7ede0244c6..8384ce67b8 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@@ -1241,6 +1241,7 @@ serve(async (req: Request) => {remainingQuantity: invoiceFirstQty,supplierId: purchaseOrder.data?.supplierId ?? undefined,companyId,+ postingDate: today,isInvoiceFirst: true,poLineId: poLineId ?? undefined,});@@ -1261,6 +1262,7 @@ serve(async (req: Request) => {remainingQuantity: normalQty,supplierId: purchaseOrder.data?.supplierId ?? undefined,companyId,+ postingDate: today,});}}@@ -1545,6 +1547,7 @@ serve(async (req: Request) => {remainingQuantity: 0,supplierId: purchaseOrder.data?.supplierId ?? undefined,companyId,+ postingDate: today,});}diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.tsindex f81aa0038a..b0a8102b83 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@@ -1076,6 +1076,7 @@ serve(async (req: Request) => {cost: -cogsResult.totalCost,remainingQuantity: 0,companyId,+ postingDate: today,}).execute();diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.tsindex 5c1cc9a523..436504934b 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(),@@ -1107,6 +1107,7 @@ serve(async (req: Request) => {cost: -cogsResult.totalCost,remainingQuantity: 0,companyId,+ postingDate: today,}).execute();}diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.tsindex d761aa9555..b0b1f48018 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 "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 { 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..85d4b48c7b 100644--- a/packages/database/supabase/functions/shared/get-accounting-period.ts+++ b/packages/database/supabase/functions/shared/get-accounting-period.ts@@ -1,10 +1,9 @@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;};@@ -188,15 +187,15 @@ export async function getCurrentAccountingPeriod<T>(companyId: string,db: Kysely<DB>) {- // 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 = 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 +255,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..4c001aadf8 100644--- a/packages/database/supabase/functions/update-purchased-prices/index.ts+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts@@ -4,6 +4,7 @@ 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 +121,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 +150,7 @@ serve(async (req: Request) => {cost:(line.quantity / (line.conversionFactor ?? 1)) * line.unitPrice,remainingQuantity: 0,+ postingDate: today,supplierId,companyId,}));diff --git a/packages/database/supabase/migrations/20260805020925_company-timezone.sql b/packages/database/supabase/migrations/20260805020925_company-timezone.sqlnew file mode 100644index 0000000000..e40ecf1e1c--- /dev/null+++ b/packages/database/supabase/migrations/20260805020925_company-timezone.sql@@ -0,0 +1,43 @@+-- 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).+UPDATE "company" c+SET "timezone" = l."timezone"+FROM (+ SELECT DISTINCT ON ("companyId") "companyId", "timezone"+ FROM "location"+ WHERE "timezone" IS NOT NULL AND "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/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/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..5ce4e1eb54 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)`, `weekNumber(date)`. 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..dd7d520eaf--- /dev/null+++ b/packages/utils/src/datetime.test.ts@@ -0,0 +1,72 @@+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$/);+ });+});++describe("datetime.weekNumber", () => {+ 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..88a090027c--- /dev/null+++ b/packages/utils/src/datetime.ts@@ -0,0 +1,46 @@+import {+ type CalendarDate,+ now,+ parseAbsolute,+ toCalendarDate,+ today+} from "@internationalized/date";++/**+ * ISO 8601 week number (1-53). Week 1 is the week containing the year's first+ * Thursday. Pure UTC arithmetic on the date parts — no timezone dependency.+ */+function weekNumber(date: CalendarDate): number {+ const d = new Date(Date.UTC(date.year, date.month - 1, date.day));+ const dayNum = d.getUTCDay() || 7; // Sunday → 7+ d.setUTCDate(d.getUTCDate() + 4 - dayNum); // shift to the week's Thursday+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));+ return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);+}++/**+ * 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)),++ weekNumber+};diff --git a/packages/utils/src/geo.ts b/packages/utils/src/geo.tsindex d03f71fb9c..dc7eb2801f 100644--- a/packages/utils/src/geo.ts+++ b/packages/utils/src/geo.ts@@ -1,169 +1,87 @@-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;++/**+ * 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.+ */+export function getTimezones(): TimezoneGroup[] {+ if (cachedTimezones) 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))+ }));++ 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/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,