Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(erp): derive business dates in company/location tz in routes and SQL

Sidwebworks2e649a3e1d1d
diff --git a/.claude/rules/date-handling.md b/.claude/rules/date-handling.md
index 1606ecdffb..dbca1be615 100644
--- a/.claude/rules/date-handling.md
+++ b/.claude/rules/date-handling.md
@@ -42,17 +42,25 @@ must not do.
`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:
+`supabase/functions`, and **route `loader`/`action` bodies** under
+`apps/{erp,mes}/app/routes`) and enforced by the `no-local-timezone` conformance
+check in `@carbon/checks`. Route modules are server AND client in one file, so
+`sources/server-files.ts` masks out the default export, `clientLoader`/
+`clientAction`, and PascalCase/`use*` declarations before scanning — module-level
+helpers a loader calls ARE scanned. Instead:
- `datetime.timestamp()` — UTC instant string for `createdAt`/`updatedAt`/instant columns (the only tz-free method).
- `datetime.today(tz)` / `datetime.now(tz)` — calendar day / zoned now in an explicit IANA timezone.
- `datetime.businessDay(instantStr, tz)` — which day a stored instant falls on in tz.
- Resolve `tz` with `getCompanyTimeZone(client, companyId)` (ledger-scoped: posting dates, accounting periods, sequences, aging) or `getLocationTimeZone(client, locationId, companyId)` (operational: scheduling, shifts, MES, expiry) from `@carbon/database`. Deno edge functions use the mirror in `functions/lib/datetime.ts` (`getCompanyTimeZoneDb`/`getLocationTimeZoneDb` for Kysely).
-- SQL functions use `company_today(p_company_id)` (migration `20260805023439`) instead of `CURRENT_DATE` for business dates.
+- SQL functions use `company_today(p_company_id)` (migration `20260805023439`) or `location_today(p_location_id, p_company_id)` (migration `20260805201623`) instead of `CURRENT_DATE` for business dates. Read-only "is it overdue?" views still compare against `CURRENT_DATE` — they render a status rather than storing one.
-Client components keep `today(getLocalTimeZone())` etc. — in the browser the
-local timezone IS the user's and is correct for pickers and display.
+Client components keep `today(getLocalTimeZone())` etc. for **display** — in the
+browser the local timezone IS the user's and is correct for pickers and
+formatting. But a form default that will be **persisted as a business date**
+(`postingDate`, `orderDate`, `dateIssued`, `openDate`, …) must use
+`useCompanyToday()` from `~/hooks`: the stored value belongs to the company's
+calendar, not to whichever zone the person filling the form happens to be in.
## Repo patterns to copy
diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.ts
index a2b5461766..f8badf6c88 100644
--- a/apps/erp/app/hooks/index.ts
+++ b/apps/erp/app/hooks/index.ts
@@ -6,6 +6,7 @@ import {
useUrlParams
} from "@carbon/react";
import { useCompanySettings } from "./useCompanySettings";
+import { useCompanyTimeZone, useCompanyToday } from "./useCompanyTimeZone";
import { useCurrencyFormatter } from "./useCurrencyFormatter";
import { useDateFormatter } from "./useDateFormatter";
import { useFlags } from "./useFlags";
@@ -31,6 +32,8 @@ import { useUser } from "./useUser";
export {
useCompanySettings,
+ useCompanyTimeZone,
+ useCompanyToday,
useCurrencyFormatter,
useDateFormatter,
useFlags,
diff --git a/apps/erp/app/hooks/useCompanyTimeZone.tsx b/apps/erp/app/hooks/useCompanyTimeZone.tsx
new file mode 100644
index 0000000000..04e2c00d66
--- /dev/null
+++ b/apps/erp/app/hooks/useCompanyTimeZone.tsx
@@ -0,0 +1,20 @@
+import { useRouteData } from "@carbon/react";
+import { today } from "@internationalized/date";
+import type { Company } from "~/modules/settings";
+import { path } from "~/utils/path";
+
+/**
+ * The company's IANA timezone — the ledger calendar. Use it to seed any date a
+ * form will persist as a business date (postingDate, orderDate, dateIssued, …)
+ * so the stored value matches the books, not whichever zone the browser is in.
+ * Falls back to UTC before the layout route data is available.
+ */
+export function useCompanyTimeZone(): string {
+ const data = useRouteData<{ company: Company }>(path.to.authenticatedRoot);
+ return data?.company?.timezone ?? "UTC";
+}
+
+/** Today's `YYYY-MM-DD` on the company's calendar — a form-ready default. */
+export function useCompanyToday(): string {
+ return today(useCompanyTimeZone()).toString();
+}
diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
index 517a1fea4c..67d88dc0ca 100644
--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
@@ -1,7 +1,7 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
import {
@@ -15,6 +15,7 @@ import {
getOpenSalesOrderLines
} from "~/modules/items/items.service";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
const defaultResponse = {
demand: [],
@@ -41,7 +42,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (!locationId) throw new Error("Could not find locationId");
const periods = await getOrCreatePeriods(
- today(getLocalTimeZone()),
+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),
WEEKS_TO_FORECAST
);
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index a6a8ed0e1d..890f2a5e47 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -5,7 +5,7 @@ import type { Database } from "@carbon/database";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { Loading } from "@carbon/react";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { Suspense } from "react";
import type { LoaderFunctionArgs } from "react-router";
@@ -25,6 +25,7 @@ import {
insertPurchaseOrder,
upsertPurchaseOrderLine
} from "~/modules/purchasing";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { path } from "~/utils/path";
const logger = getLogger("erp", "kanban");
@@ -86,7 +87,9 @@ async function handleKanban({
]);
const leadTime = manufacturing.data?.leadTime ?? 7;
- const startDate = today(getLocalTimeZone());
+ const startDate = datetime.today(
+ await getLocationTimeZone(client, kanban.data.locationId!, companyId)
+ );
const dueDate = startDate.add({ days: leadTime }).toString();
// Use storage unit from kanban if it exists, otherwise use default storage unit
diff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.ts
index db47022fff..559141e502 100644
--- a/apps/erp/app/routes/api+/mcp+/_index.ts
+++ b/apps/erp/app/routes/api+/mcp+/_index.ts
@@ -4,9 +4,11 @@ import {
getUserScopedClient
} from "@carbon/auth/client.server";
import { getAppUrl } from "@carbon/env";
+import { datetime } from "@carbon/utils";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { ActionFunctionArgs } from "react-router";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { createMcpServer } from "./lib/server";
const corsHeaders = {
@@ -123,7 +125,14 @@ async function resolveAuth(request: Request): Promise<{
export async function action({ request }: ActionFunctionArgs) {
const { ctx, request: authedRequest } = await resolveAuth(request);
- const server = createMcpServer(ctx);
+ // The agent is told what "today" is; it has to be the company's day, not the
+ // server's, or every relative-date tool call it makes lands a day off.
+ const server = createMcpServer(
+ ctx,
+ datetime
+ .today(await getCompanyTimeZone(ctx.client, ctx.companyId))
+ .toString()
+ );
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true
diff --git a/apps/erp/app/routes/api+/mcp+/lib/server.ts b/apps/erp/app/routes/api+/mcp+/lib/server.ts
index dc3dee3964..c1ecb71404 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/server.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/server.ts
@@ -10,9 +10,8 @@ import { executeFunction } from "./direct-executor";
const logger = getLogger("erp", "mcp");
-function getServerInstructions(): string {
- const today = new Date().toISOString().split("T")[0];
-
+function getServerInstructions(today: string): string {
+
return `Carbon ERP Manufacturing System
==========================================
Date: ${today}
@@ -54,14 +53,14 @@ KEY PATTERNS:
- Pagination: limit/offset`;
}
-export function createMcpServer(ctx: McpContext): McpServer {
+export function createMcpServer(ctx: McpContext, today: string): McpServer {
const server = new McpServer(
{
name: "carbon-erp",
version: process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 7) ?? "1.0.0",
},
{
- instructions: getServerInstructions(),
+ instructions: getServerInstructions(today),
},
);
diff --git a/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx b/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx
index ac2a1f5282..7184c45c3d 100644
--- a/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx
+++ b/apps/erp/app/routes/x+/accounting+/intercompany.new.tsx
@@ -2,9 +2,9 @@ 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 { useCompanyToday } from "~/hooks";
import {
createIntercompanyTransaction,
getCompaniesInGroup,
@@ -66,6 +66,7 @@ export default function NewIntercompanyTransactionRoute() {
const { companies } = useLoaderData<typeof loader>();
const navigate = useNavigate();
+ const companyToday = useCompanyToday();
const initialValues = {
sourceCompanyId: "",
targetCompanyId: "",
@@ -74,9 +75,7 @@ export default function NewIntercompanyTransactionRoute() {
description: "",
debitAccountId: "",
creditAccountId: "",
- // 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()
+ postingDate: companyToday
};
return (
diff --git a/apps/erp/app/routes/x+/change-notice+/new.tsx b/apps/erp/app/routes/x+/change-notice+/new.tsx
index 0e50c49fe6..60e0c859fb 100644
--- a/apps/erp/app/routes/x+/change-notice+/new.tsx
+++ b/apps/erp/app/routes/x+/change-notice+/new.tsx
@@ -3,11 +3,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { Json } from "@carbon/database";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
-import { useUser } from "~/hooks";
+import { useCompanyToday, useUser } from "~/hooks";
import {
addChangeNoticeAffectedItem,
changeNoticeValidator,
@@ -15,6 +15,7 @@ import {
insertChangeNotice
} from "~/modules/items";
import { ChangeNoticeForm } from "~/modules/items/ui/ChangeNotice";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -84,7 +85,9 @@ export async function action({ request }: ActionFunctionArgs) {
priority: d.priority,
changeNoticeTypeId: d.changeOrderTypeId || undefined,
nonConformanceId: d.nonConformanceId || undefined,
- openDate: d.openDate || today(getLocalTimeZone()).toString(),
+ openDate:
+ d.openDate ||
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString(),
dueDate: d.dueDate || undefined,
assignee: d.assignee || undefined,
companyId,
@@ -158,6 +161,7 @@ export default function ChangeNoticeNewRoute() {
const { types, nonConformanceId, name } = useLoaderData<typeof loader>();
const user = useUser();
+ const companyToday = useCompanyToday();
const initialValues = {
id: undefined,
changeOrderId: undefined,
@@ -167,7 +171,7 @@ export default function ChangeNoticeNewRoute() {
changeOrderTypeId: "",
assignee: user.id,
priority: "Medium" as const,
- openDate: today(getLocalTimeZone()).toString(),
+ openDate: companyToday,
dueDate: "",
nonConformanceId,
affectedItemIds: []
diff --git a/apps/erp/app/routes/x+/inspection+/$id.reject.tsx b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
index f3e06e76fb..8c842b7a25 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
@@ -4,7 +4,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { notifyIssueCreated } from "@carbon/ee/notifications";
import { getLogger } from "@carbon/logger";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import { FunctionRegion } from "@supabase/supabase-js";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -19,6 +19,7 @@ import {
} from "~/modules/quality";
import { dispositionInspection } from "~/modules/quality/quality.server";
import { getCompanyIntegrations } from "~/modules/settings/settings.server";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { getUserDefaults } from "~/modules/users/users.server";
import { path } from "~/utils/path";
@@ -217,7 +218,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
source: "Internal",
locationId,
nonConformanceTypeId: issueType.id,
- openDate: today(getLocalTimeZone()).toString(),
+ openDate: datetime
+ .today(await getLocationTimeZone(client, locationId, companyId))
+ .toString(),
quantity: Number(insp.lotSize ?? 0),
items: insp.itemId ? [insp.itemId] : [],
companyId,
diff --git a/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx b/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx
index d0e6fc7674..bc8ade0326 100644
--- a/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx
+++ b/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx
@@ -1,7 +1,7 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import {
@@ -11,6 +11,7 @@ import {
getItem,
insertChangeNotice
} from "~/modules/items";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { path, requestReferrer } from "~/utils/path";
// One-click "Create Change Notice" for a part/tool: mint a CO and attach the item
@@ -54,7 +55,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
companyId,
createdBy: userId,
name: `Change for ${label}`,
- openDate: today(getLocalTimeZone()).toString()
+ openDate: datetime
+ .today(await getCompanyTimeZone(client, companyId))
+ .toString()
});
if (co.error || !co.data) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx b/apps/erp/app/routes/x+/job+/$jobId.materials.tsx
index 845704f3a5..7d30963da1 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.materials.tsx
@@ -2,7 +2,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { useMount, VStack } from "@carbon/react";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData } from "react-router";
import { usePanels } from "~/components/Layout";
@@ -14,6 +14,7 @@ import {
} from "~/modules/production";
import { JobMaterialsTable } from "~/modules/production/ui/Jobs";
import { getCompanySettings } from "~/modules/settings";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
@@ -76,7 +77,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// Both depend on the materials but not on each other.
const [expiredItemIds, orderStatusByMaterialId] = await Promise.all([
- getExpiredItemIds(client, companyId, rows, nearExpiryWarningDays),
+ getExpiredItemIds(
+ client,
+ companyId,
+ rows,
+ nearExpiryWarningDays,
+ locationId
+ ),
getJobOrderStatusMap(
client,
jobId,
@@ -112,7 +119,8 @@ async function getExpiredItemIds(
client: Parameters<typeof getJob>[0],
companyId: string,
materials: { jobMaterialItemId: string | null }[],
- nearExpiryWarningDays: number | null
+ nearExpiryWarningDays: number | null,
+ locationId: string
): Promise<Set<string>> {
if (nearExpiryWarningDays === null) return new Set();
const itemIds = materials
@@ -126,7 +134,12 @@ async function getExpiredItemIds(
.in("sourceDocumentId", itemIds)
.eq("companyId", companyId)
.not("expirationDate", "is", null)
- .lt("expirationDate", today(getLocalTimeZone()).toString());
+ .lt(
+ "expirationDate",
+ datetime
+ .today(await getLocationTimeZone(client, locationId, companyId))
+ .toString()
+ );
return new Set(
(data ?? [])
diff --git a/apps/erp/app/routes/x+/production+/planning.tsx b/apps/erp/app/routes/x+/production+/planning.tsx
index fb878a8a41..b20a4abff8 100644
--- a/apps/erp/app/routes/x+/production+/planning.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.tsx
@@ -2,7 +2,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { ResizablePanel, ResizablePanelGroup, VStack } from "@carbon/react";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
@@ -11,6 +11,7 @@ import { getProductionPlanning } from "~/modules/production";
import ProductionPlanningTable from "~/modules/production/ui/Planning/ProductionPlanningTable";
import { getLocationsList } from "~/modules/resources";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -68,7 +69,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const periods = await getOrCreatePeriods(
- today(getLocalTimeZone()),
+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),
WEEKS_TO_PLAN
);
diff --git a/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx
index 81cb130c5f..a0e6018ef6 100644
--- a/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx
@@ -2,7 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useNavigate } from "react-router";
import { demandProjectionValidator } from "~/modules/production/production.models";
@@ -12,6 +12,7 @@ import {
} from "~/modules/production/production.service";
import DemandProjectionsForm from "~/modules/production/ui/Projection/DemandProjectionForm";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { path } from "~/utils/path";
const WEEKS_TO_PROJECT = 52;
@@ -28,7 +29,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
const periods = await getOrCreatePeriods(
- today(getLocalTimeZone()),
+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),
WEEKS_TO_PROJECT
);
diff --git a/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx
index 2b23d3b582..55864407bc 100644
--- a/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx
@@ -1,11 +1,12 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
import { deleteDemandProjections } from "~/modules/production/production.service";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -27,7 +28,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
// Get current date to determine future periods
- const periods = await getOrCreatePeriods(today(getLocalTimeZone()), 52);
+ const periods = await getOrCreatePeriods(
+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),
+ 52
+ );
// Only delete projections for future periods (current week and beyond)
const futurePeriodIds = periods.map((p) => p.id);
diff --git a/apps/erp/app/routes/x+/production+/projections.new.tsx b/apps/erp/app/routes/x+/production+/projections.new.tsx
index c5fe6276ea..c23060fbbf 100644
--- a/apps/erp/app/routes/x+/production+/projections.new.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.new.tsx
@@ -3,24 +3,27 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { useRouteData } from "@carbon/react";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useNavigate } from "react-router";
import { demandProjectionValidator } from "~/modules/production/production.models";
import { upsertDemandProjections } from "~/modules/production/production.service";
import DemandProjectionForm from "~/modules/production/ui/Projection/DemandProjectionForm";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { path } from "~/utils/path";
const WEEKS_TO_PROJECT = 52;
export async function loader({ request }: LoaderFunctionArgs) {
- await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
create: "production"
});
+ // No location yet — it is picked in the form — so the week grid anchors on
+ // the company calendar.
const periods = await getOrCreatePeriods(
- today(getLocalTimeZone()),
+ datetime.today(await getCompanyTimeZone(client, companyId)),
WEEKS_TO_PROJECT
);
diff --git a/apps/erp/app/routes/x+/production+/projections.tsx b/apps/erp/app/routes/x+/production+/projections.tsx
index bdd903ab5b..4df9855f7a 100644
--- a/apps/erp/app/routes/x+/production+/projections.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.tsx
@@ -2,7 +2,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
@@ -10,6 +10,7 @@ import { getProductionProjections } from "~/modules/production";
import DemandProjectionsTable from "~/modules/production/ui/Projection/DemandProjectionTable";
import { getLocationsList } from "~/modules/resources";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -67,7 +68,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const periods = await getOrCreatePeriods(
- today(getLocalTimeZone()),
+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),
WEEKS_TO_PROJECT
);
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
index 8200ab7228..7a6f309da6 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
@@ -3,12 +3,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
import { msg } from "@lingui/core/macro";
import type { FunctionsResponse } from "@supabase/functions-js";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { useUrlParams, useUser } from "~/hooks";
+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";
import { upsertDocument } from "~/modules/documents";
import {
createPurchaseInvoiceFromPurchaseOrder,
@@ -222,12 +221,13 @@ export default function PurchaseInvoiceNewRoute() {
const supplierId = params.get("supplierId");
const { defaults } = useUser();
+ const companyToday = useCompanyToday();
const initialValues = {
id: undefined,
invoiceId: undefined,
supplierId: supplierId ?? "",
locationId: defaults?.locationId ?? "",
- dateIssued: today(getLocalTimeZone()).toString()
+ dateIssued: companyToday
};
return (
diff --git a/apps/erp/app/routes/x+/purchase-order+/new.tsx b/apps/erp/app/routes/x+/purchase-order+/new.tsx
index 256c8fd54a..accfa8389e 100644
--- a/apps/erp/app/routes/x+/purchase-order+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/new.tsx
@@ -2,12 +2,11 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { z } from "zod";
-import { useUrlParams, useUser } from "~/hooks";
+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";
import type { PurchaseOrderStatus } from "~/modules/purchasing";
import {
insertPurchaseOrder,
@@ -70,12 +69,13 @@ export default function PurchaseOrderNewRoute() {
const [params] = useUrlParams();
const supplierId = params.get("supplierId");
const { defaults } = useUser();
+ const companyToday = useCompanyToday();
const initialValues = {
id: undefined,
purchaseOrderId: undefined,
supplierId: supplierId ?? "",
locationId: defaults?.locationId ?? "",
- orderDate: today(getLocalTimeZone()).toString(),
+ orderDate: companyToday,
status: "Draft" as PurchaseOrderStatus,
purchaseOrderType: "Purchase" as const
};
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.tsx b/apps/erp/app/routes/x+/purchasing+/planning.tsx
index 5228078858..42a4430a8d 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.tsx
@@ -2,7 +2,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { ResizablePanel, ResizablePanelGroup, VStack } from "@carbon/react";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
@@ -11,6 +11,7 @@ import { getPurchasingPlanning } from "~/modules/purchasing";
import PurchasingPlanningTable from "~/modules/purchasing/ui/Planning/PurchasingPlanningTable";
import { getLocationsList } from "~/modules/resources";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -68,7 +69,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const periods = await getOrCreatePeriods(
- today(getLocalTimeZone()),
+ datetime.today(await getLocationTimeZone(client, locationId, companyId)),
WEEKS_TO_PLAN
);
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/new.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/new.tsx
index aa92be6ddf..50db19a4e0 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/new.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/new.tsx
@@ -2,11 +2,10 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { useUser } from "~/hooks";
+import { useCompanyToday, useUser } from "~/hooks";
import type { PurchasingRFQStatusType } from "~/modules/purchasing";
import {
insertPurchasingRFQ,
@@ -80,11 +79,12 @@ export async function action({ request }: ActionFunctionArgs) {
export default function PurchasingRFQNewRoute() {
const { id: userId, defaults } = useUser();
+ const companyToday = useCompanyToday();
const initialValues = {
expirationDate: "",
id: undefined,
locationId: defaults?.locationId ?? "",
- rfqDate: today(getLocalTimeZone()).toString(),
+ rfqDate: companyToday,
rfqId: undefined,
status: "Draft" as PurchasingRFQStatusType,
employeeId: userId,
diff --git a/apps/erp/app/routes/x+/quality+/gauges.$id.tsx b/apps/erp/app/routes/x+/quality+/gauges.$id.tsx
index ea2a74f0bd..4c7fe33cce 100644
--- a/apps/erp/app/routes/x+/quality+/gauges.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/gauges.$id.tsx
@@ -3,7 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
@@ -16,6 +17,7 @@ import {
updateGauge
} from "~/modules/quality";
import GaugeForm from "~/modules/quality/ui/Gauge/GaugeForm";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { getCustomFields, setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { getParams, path } from "~/utils/path";
@@ -55,7 +57,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "quality"
});
@@ -72,8 +74,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { gaugeId, ...d } = validation.data;
if (!gaugeId) throw new Error("Could not find gaugeId");
+ const companyToday = datetime.today(
+ await getCompanyTimeZone(client, companyId)
+ );
const gaugeCalibrationStatus = d.nextCalibrationDate
- ? parseDate(d.nextCalibrationDate) < today(getLocalTimeZone())
+ ? parseDate(d.nextCalibrationDate).compare(companyToday) < 0
? "Out-of-Calibration"
: d.lastCalibrationDate
? "In-Calibration"
diff --git a/apps/erp/app/routes/x+/quality+/gauges.new.tsx b/apps/erp/app/routes/x+/quality+/gauges.new.tsx
index b1d8507af8..0c84cd4720 100644
--- a/apps/erp/app/routes/x+/quality+/gauges.new.tsx
+++ b/apps/erp/app/routes/x+/quality+/gauges.new.tsx
@@ -2,13 +2,15 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useNavigate } from "react-router";
-import { useRouteData, useUser } from "~/hooks";
+import { useCompanyToday, useRouteData, useUser } from "~/hooks";
import type { GaugeType } from "~/modules/quality";
import { gaugeValidator, insertGauge } from "~/modules/quality";
import GaugeForm from "~/modules/quality/ui/Gauge/GaugeForm";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { setCustomFields } from "~/utils/form";
import { getParams, path } from "~/utils/path";
@@ -35,8 +37,11 @@ export async function action({ request }: ActionFunctionArgs) {
const { id: _id, ...d } = validation.data;
+ const companyToday = datetime.today(
+ await getCompanyTimeZone(client, companyId)
+ );
const gaugeCalibrationStatus = d.nextCalibrationDate
- ? parseDate(d.nextCalibrationDate) < today(getLocalTimeZone())
+ ? parseDate(d.nextCalibrationDate).compare(companyToday) < 0
? "Out-of-Calibration"
: d.lastCalibrationDate
? "In-Calibration"
@@ -73,6 +78,7 @@ export default function GaugeNewRoute() {
gaugeTypes: GaugeType[];
}>(path.to.gauges);
+ const companyToday = useCompanyToday();
const initialValues = {
id: undefined,
gaugeId: undefined,
@@ -80,7 +86,7 @@ export default function GaugeNewRoute() {
modelNumber: "",
serialNumber: "",
description: "",
- dateAcquired: today(getLocalTimeZone()).toString(),
+ dateAcquired: companyToday,
gaugeTypeId: "",
gaugeCalibrationStatus: "Pending" as const,
gaugeStatus: "Active" as const,
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
index 8e12e606fb..cd1a1280e7 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -4,7 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import { QuoteEmail } from "@carbon/documents/email";
import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
-import { getLocalTimeZone, now } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import { renderAsync } from "@react-email/components";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -62,7 +62,7 @@ export async function action(args: ActionFunctionArgs) {
.from("quote")
.update({
externalLinkId: externalLink.data.id,
- completedDate: now(getLocalTimeZone()).toAbsoluteString()
+ completedDate: datetime.timestamp()
})
.eq("id", quoteId);
}
diff --git a/apps/erp/app/routes/x+/sales+/price-list.new.tsx b/apps/erp/app/routes/x+/sales+/price-list.new.tsx
index f8999f17a5..1c34d4298d 100644
--- a/apps/erp/app/routes/x+/sales+/price-list.new.tsx
+++ b/apps/erp/app/routes/x+/sales+/price-list.new.tsx
@@ -2,7 +2,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useLoaderData, useNavigate } from "react-router";
import {
@@ -11,10 +11,13 @@ import {
upsertCustomerItemPriceOverride
} from "~/modules/sales";
import PriceOverrideForm from "~/modules/sales/ui/Pricing/PriceOverrideForm";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { getParams, path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
- await requirePermissions(request, { create: "sales" });
+ const { client, companyId } = await requirePermissions(request, {
+ create: "sales"
+ });
const url = new URL(request.url);
const customerId = url.searchParams.get("customerId") ?? undefined;
@@ -31,7 +34,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
itemId: url.searchParams.get("itemId") ?? "",
validFrom:
url.searchParams.get("validFrom") ??
- today(getLocalTimeZone()).toString()
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()
},
initialScope
};
diff --git a/apps/erp/app/routes/x+/sales-invoice+/new.tsx b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
index ec6bb0050d..aa7a13e936 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
@@ -3,12 +3,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
import { msg } from "@lingui/core/macro";
import type { FunctionsResponse } from "@supabase/functions-js";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { useUrlParams, useUser } from "~/hooks";
+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";
import {
createSalesInvoiceFromSalesOrder,
createSalesInvoiceFromShipment,
@@ -143,12 +142,13 @@ export default function SalesInvoiceNewRoute() {
const customerId = params.get("customerId");
const { defaults } = useUser();
+ const companyToday = useCompanyToday();
const initialValues = {
id: undefined,
invoiceId: undefined,
customerId: customerId ?? "",
locationId: defaults?.locationId ?? "",
- dateIssued: today(getLocalTimeZone()).toString()
+ dateIssued: companyToday
};
return (
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
index 3b7c9845b1..817ce9d86b 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
@@ -2,8 +2,7 @@ import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { validator } from "@carbon/form";
-import { getSalesOrderStatus } from "@carbon/utils";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime, getSalesOrderStatus } from "@carbon/utils";
import { parseAcceptLanguage } from "intl-parse-accept-language";
import type { ActionFunctionArgs } from "react-router";
import { runMRP } from "~/modules/production/production.service";
@@ -16,6 +15,7 @@ import {
generateAndAttachSalesOrderPdf,
sendSalesOrderEmail
} from "~/modules/shared/shared.server";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { loader as pdfLoader } from "~/routes/file+/sales-order+/$id[.]pdf";
export async function action(args: ActionFunctionArgs) {
@@ -150,8 +150,11 @@ export async function action(args: ActionFunctionArgs) {
.update({
status,
orderDate:
- salesOrder.data.orderDate ?? today(getLocalTimeZone()).toString(),
- updatedAt: today(getLocalTimeZone()).toString(),
+ salesOrder.data.orderDate ??
+ datetime
+ .today(await getCompanyTimeZone(client, companyId))
+ .toString(),
+ updatedAt: datetime.timestamp(),
updatedBy: userId
})
.eq("id", orderId);
diff --git a/apps/erp/app/routes/x+/sales-rfq+/new.tsx b/apps/erp/app/routes/x+/sales-rfq+/new.tsx
index a8d08b00ce..1916ae59e6 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/new.tsx
@@ -2,11 +2,10 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { useUrlParams, useUser } from "~/hooks";
+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";
import { upsertDocument } from "~/modules/documents";
import { resolveItemIdFromExtractedText } from "~/modules/items";
import type { SalesRFQStatusType } from "~/modules/sales";
@@ -155,6 +154,7 @@ export default function SalesRFQNewRoute() {
const { id: userId, defaults } = useUser();
const [params] = useUrlParams();
const customerId = params.get("customerId");
+ const companyToday = useCompanyToday();
const initialValues = {
customerContactId: "",
customerLocationId: "",
@@ -163,7 +163,7 @@ export default function SalesRFQNewRoute() {
expirationDate: "",
id: undefined,
locationId: defaults?.locationId ?? "",
- rfqDate: today(getLocalTimeZone()).toString(),
+ rfqDate: companyToday,
rfqId: undefined,
status: "Draft" as SalesRFQStatusType,
salesPersonId: userId
diff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsx
index c1500e011f..d7eef60912 100644
--- a/apps/erp/app/routes/x+/schedule+/dates.tsx
+++ b/apps/erp/app/routes/x+/schedule+/dates.tsx
@@ -56,6 +56,7 @@ import { DateKanban } from "~/modules/production/ui/Schedule/Kanban/DateKanban";
import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";
import { getLocationsList } from "~/modules/resources";
import { getTagsList } from "~/modules/shared";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { getUserDefaults } from "~/modules/users/users.server";
import { usePeople } from "~/stores";
import type { Handle } from "~/utils/handle";
@@ -84,11 +85,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
const view = (searchParams.get("view") as ViewType) ?? "week";
const dateParam = searchParams.get("date");
- const timezone = getLocalTimeZone();
- const currentDate = dateParam
- ? parseDate(dateParam)
- : toCalendarDate(now(timezone));
-
let selectedSalesOrderIds: string[] = [];
let selectedTags: string[] = [];
let selectedAssignee: string[] = [];
@@ -149,6 +145,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
locationId = locations.data?.[0].id as string;
}
+ // The board's "today" and its week/month windows belong to the plant being
+ // scheduled, not the server — resolved after locationId settles.
+ const timezone = await getLocationTimeZone(client, locationId, companyId);
+ const currentDate = dateParam
+ ? parseDate(dateParam)
+ : toCalendarDate(now(timezone));
+
// Calculate date range based on view
let startDate: string;
let endDate: string;
diff --git a/apps/erp/app/routes/x+/settings+/companies.new.tsx b/apps/erp/app/routes/x+/settings+/companies.new.tsx
index 6a3da757ea..5aaa89e602 100644
--- a/apps/erp/app/routes/x+/settings+/companies.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/companies.new.tsx
@@ -82,7 +82,7 @@ export async function action({ request }: ActionFunctionArgs) {
...locationData,
name: "Headquarters",
companyId,
- timezone: getLocalTimeZone(),
+ // timezone comes from locationData — HQ shares the company's timezone.
createdBy: userId
});
diff --git a/apps/erp/app/routes/x+/settings+/company.new.tsx b/apps/erp/app/routes/x+/settings+/company.new.tsx
index dc023a4046..b7e1c4fed3 100644
--- a/apps/erp/app/routes/x+/settings+/company.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/company.new.tsx
@@ -6,7 +6,6 @@ import { updateCompanySession } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
-import { getLocalTimeZone } from "@internationalized/date";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { insertEmployeeJob } from "~/modules/people";
@@ -58,7 +57,7 @@ export async function action({ request }: ActionFunctionArgs) {
...locationData,
name: "Headquarters",
companyId,
- timezone: validation.data.timezone || getLocalTimeZone(),
+ // timezone comes from locationData — HQ shares the company's timezone.
createdBy: userId
});
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
index 6ad374163b..c592008911 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
@@ -10,10 +10,12 @@ import {
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { getCachedPrinterConfig } from "@carbon/printing/printing.server";
-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { upsertDocument } from "~/modules/documents";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { loader as pdfLoader } from "~/routes/file+/shipment+/$id[.]pdf";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
@@ -49,7 +51,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// fire here too.
const { data: shipmentForSurface } = await serviceRole
.from("shipment")
- .select("sourceDocument")
+ .select("sourceDocument, locationId")
.eq("id", shipmentId)
.single();
const surfaces: ("shipment" | "warehouseTransfer")[] = ["shipment"];
@@ -131,7 +133,15 @@ export async function action({ request, params }: ActionFunctionArgs) {
.eq("attributes ->> Shipment", shipmentId)
.eq("companyId", companyId);
- const todayLocal = today(getLocalTimeZone());
+ // Expiry is judged on the shipping site's calendar, not the server's — a lot
+ // that expires today must not read as expired at a plant still on yesterday.
+ const todayLocal = datetime.today(
+ await getLocationTimeZone(
+ serviceRole,
+ shipmentForSurface?.locationId as string,
+ companyId
+ )
+ );
const expiredEntities = (shipmentTrackedEntities ?? []).filter((e) => {
if (!e.expirationDate) return false;
try {
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
index 50480bee28..9de4eea760 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.approval.tsx
@@ -6,7 +6,7 @@ import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { supplierApprovalDecisionValidator } from "~/modules/purchasing";
@@ -71,7 +71,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.update({
supplierStatus: "Pending",
updatedBy: userId,
- updatedAt: today(getLocalTimeZone()).toString()
+ updatedAt: datetime.timestamp()
})
.eq("id", supplierId);
@@ -134,7 +134,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.update({
supplierStatus: "Inactive",
updatedBy: userId,
- updatedAt: today(getLocalTimeZone()).toString()
+ updatedAt: datetime.timestamp()
})
.eq("id", supplierId);
diff --git a/apps/erp/app/routes/x+/supplier-quote+/new.tsx b/apps/erp/app/routes/x+/supplier-quote+/new.tsx
index d63959d6ac..f0eda89121 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/new.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/new.tsx
@@ -2,11 +2,10 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { getLocalTimeZone, today } from "@internationalized/date";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { useUrlParams, useUser } from "~/hooks";
+import { useCompanyToday, useUrlParams, useUser } from "~/hooks";
import {
insertSupplierQuote,
supplierQuoteValidator
@@ -65,12 +64,13 @@ export default function SupplierQuoteNewRoute() {
const [params] = useUrlParams();
const { company } = useUser();
const supplierId = params.get("supplierId");
+ const companyToday = useCompanyToday();
const initialValues = {
supplierContactId: "",
supplierId: supplierId ?? "",
supplierReference: "",
expirationDate: "",
- quotedDate: today(getLocalTimeZone()).toString(),
+ quotedDate: companyToday,
supplierQuoteId: undefined,
status: "Draft" as const,
currencyCode: company.baseCurrencyCode,
diff --git a/apps/erp/app/routes/x+/supplier-quote+/update.tsx b/apps/erp/app/routes/x+/supplier-quote+/update.tsx
index 5aed60a92d..241c33c8ab 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/update.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/update.tsx
@@ -1,14 +1,14 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
import { isSupplierQuoteLocked } from "~/modules/purchasing";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyGroupId, userId } = await requirePermissions(request, {
- update: "purchasing"
- });
+ const { client, companyGroupId, companyId, userId } =
+ await requirePermissions(request, { update: "purchasing" });
const formData = await request.formData();
const ids = formData.getAll("ids");
@@ -100,11 +100,16 @@ export async function action({ request }: ActionFunctionArgs) {
.in("id", ids as string[]);
case "expirationDate":
+ // Expiry is judged on the company's calendar — one set of books, one
+ // "today" — not the server's or the editing user's.
+ const companyToday = datetime
+ .today(await getCompanyTimeZone(client, companyId))
+ .toString();
return await client
.from("supplierQuote")
.update({
status: value
- ? today(getLocalTimeZone()).toString() > value
+ ? companyToday > value
? "Expired"
: "Active"
: "Active",
diff --git a/packages/checks/src/sources/server-files.test.ts b/packages/checks/src/sources/server-files.test.ts
new file mode 100644
index 0000000000..fea2512c67
--- /dev/null
+++ b/packages/checks/src/sources/server-files.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import { noLocalTimezone } from "../conformance/no-local-timezone";
+import { maskClientCode } from "./server-files";
+
+/**
+ * A route module is server AND client in one file. These cases pin the split:
+ * loader/action (and the module-level helpers they call) are scanned; the
+ * component, its hooks, and clientLoader/clientAction are not.
+ */
+describe("maskClientCode", () => {
+ const scan = (src: string) =>
+ noLocalTimezone.scan("apps/erp/app/routes/x+/r.tsx", maskClientCode(src));
+
+ it("keeps loader bodies", () => {
+ const src = [
+ "export async function loader({ request }: LoaderFunctionArgs) {",
+ " const d = today(getLocalTimeZone());",
+ "}"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(1);
+ });
+
+ it("keeps action bodies, including the arrow-const form", () => {
+ const src = [
+ "export const action: ActionFunction = async ({ request }) => {",
+ " const d = today(getLocalTimeZone());",
+ "};"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(1);
+ });
+
+ it("keeps module-level server helpers a loader calls", () => {
+ const src = [
+ "export async function loader() {",
+ " return getExpired(client);",
+ "}",
+ "",
+ "async function getExpired(client: Client) {",
+ " return client.lt('expirationDate', today(getLocalTimeZone()));",
+ "}"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(1);
+ });
+
+ it("skips the default-export component", () => {
+ const src = [
+ "export default function Route() {",
+ " const initialValues = { orderDate: today(getLocalTimeZone()) };",
+ " return null;",
+ "}"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("skips clientLoader and clientAction, which run in the browser", () => {
+ const src = [
+ "export async function clientAction({ serverAction }) {",
+ " const d = today(getLocalTimeZone());",
+ " return serverAction();",
+ "}"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("skips PascalCase components and use-prefixed hooks", () => {
+ const src = [
+ "function DatePickerCell() {",
+ " return today(getLocalTimeZone());",
+ "}",
+ "",
+ "export function useToday() {",
+ " return today(getLocalTimeZone());",
+ "}"
+ ].join("\n");
+ expect(scan(src)).toHaveLength(0);
+ });
+
+ it("resumes scanning after a client region closes", () => {
+ const src = [
+ "export default function Route() {",
+ " return today(getLocalTimeZone());",
+ "}",
+ "",
+ "export async function action() {",
+ " const d = today(getLocalTimeZone());",
+ "}"
+ ].join("\n");
+ const violations = scan(src);
+ expect(violations).toHaveLength(1);
+ expect(violations[0]?.line).toBe(6);
+ });
+
+ it("preserves line numbers so violations point at the real line", () => {
+ const src = [
+ "export default function Route() {",
+ " return null;",
+ "}",
+ "",
+ "export async function loader() {",
+ " const d = today(getLocalTimeZone());",
+ "}"
+ ].join("\n");
+ expect(scan(src)[0]?.line).toBe(6);
+ });
+});
diff --git a/packages/checks/src/sources/server-files.ts b/packages/checks/src/sources/server-files.ts
index 09992cf84b..184e4491cc 100644
--- a/packages/checks/src/sources/server-files.ts
+++ b/packages/checks/src/sources/server-files.ts
@@ -17,39 +17,103 @@ const SERVER_ROOTS = [
const ERP_MODULES_ROOT = "apps/erp/app/modules";
const ERP_SERVER_SUFFIXES = [".service.ts", ".server.ts"];
-function walk(dir: string, out: string[]): void {
+/**
+ * Route modules are server AND client in one file: `loader`/`action` run on the
+ * server, while the default export and `clientLoader`/`clientAction` run in the
+ * browser. Scanning them whole would flag every legitimate browser-side
+ * `getLocalTimeZone()`, so route files are masked down to their server
+ * functions before the checks see them.
+ */
+const ROUTE_ROOTS = ["apps/erp/app/routes", "apps/mes/app/routes"];
+
+/**
+ * Opens a browser-only region. Masking *out* these rather than masking *in*
+ * `loader`/`action` is deliberate: module-level helpers that the loader calls
+ * (e.g. `getExpiredItemIds` in job+/$jobId.materials.tsx) are server code too,
+ * and a mask-in rule would silently skip them.
+ */
+const CLIENT_REGION_START = [
+ /^export\s+default\s+(?:async\s+)?function\b/,
+ /^export\s+default\s+(?:memo|forwardRef)\b/,
+ // clientLoader/clientAction run in the browser, unlike loader/action.
+ /^export\s+(?:async\s+function\s+|function\s+|const\s+)client(?:Loader|Action)\b/,
+ // Components and hooks: PascalCase or use-prefixed declarations.
+ /^(?:export\s+)?(?:async\s+)?function\s+(?:[A-Z]|use[A-Z])/,
+ /^(?:export\s+)?const\s+(?:[A-Z]|use[A-Z])[A-Za-z0-9_]*\s*(?::[^=]*)?=\s*(?:\(|function|memo|forwardRef)/
+];
+
+function walk(dir: string, out: string[], extensions: string[]): void {
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")) {
+ walk(path, out, extensions);
+ } else if (
+ extensions.some((ext) => entry.endsWith(ext)) &&
+ !entry.endsWith(".test.ts") &&
+ !entry.endsWith(".test.tsx")
+ ) {
out.push(path);
}
}
}
+/**
+ * Blanks every component/hook/clientLoader/clientAction body, leaving the
+ * server half of a route module. Line numbering is preserved so violations
+ * still point at the real line. A region runs from its declaration to the next
+ * column-0 `}` — reliable because the repo is Biome-formatted, so a top-level
+ * closing brace is never indented.
+ */
+export function maskClientCode(contents: string): string {
+ const lines = contents.split("\n");
+ const kept = [...lines];
+ let inClientRegion = false;
+
+ lines.forEach((line, i) => {
+ if (!inClientRegion && CLIENT_REGION_START.some((re) => re.test(line))) {
+ inClientRegion = true;
+ }
+ if (inClientRegion) {
+ kept[i] = "";
+ if (line.startsWith("}")) inClientRegion = false;
+ }
+ });
+
+ return kept.join("\n");
+}
+
/** Every server-side TS file, as repo-relative { file, contents }. */
export function loadServerFiles(root: string): SqlFile[] {
const paths: string[] = [];
for (const rel of SERVER_ROOTS) {
- walk(join(root, rel), paths);
+ walk(join(root, rel), paths, [".ts"]);
}
const erpPaths: string[] = [];
- walk(join(root, ERP_MODULES_ROOT), erpPaths);
+ walk(join(root, ERP_MODULES_ROOT), erpPaths, [".ts"]);
for (const path of erpPaths) {
if (ERP_SERVER_SUFFIXES.some((suffix) => path.endsWith(suffix))) {
paths.push(path);
}
}
+ const routePaths: string[] = [];
+ for (const rel of ROUTE_ROOTS) {
+ walk(join(root, rel), routePaths, [".ts", ".tsx"]);
+ }
+ paths.push(...routePaths);
+ const isRoute = new Set(routePaths);
+
return paths
- .map((path) => relative(root, path))
- .sort()
- .map((file) => ({
- file,
- contents: readFileSync(join(root, file), "utf8")
- }));
+ .map((path) => ({ path, file: relative(root, path) }))
+ .sort((a, b) => a.file.localeCompare(b.file))
+ .map(({ path, file }) => {
+ const contents = readFileSync(path, "utf8");
+ return {
+ file,
+ contents: isRoute.has(path) ? maskClientCode(contents) : contents
+ };
+ });
}
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5ebadd83d8..f93d3e2bce 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -76074,6 +76074,10 @@ export type Database = {
}[]
}
jsonb_to_text_array: { Args: { "": Json }; Returns: string[] }
+ location_today: {
+ Args: { p_company_id: string; p_location_id: string }
+ Returns: string
+ }
matchIntercompanyTransactions: {
Args: { p_company_group_id: string }
Returns: {
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 5ebadd83d8..f93d3e2bce 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -76074,6 +76074,10 @@ export type Database = {
}[]
}
jsonb_to_text_array: { Args: { "": Json }; Returns: string[] }
+ location_today: {
+ Args: { p_company_id: string; p_location_id: string }
+ Returns: string
+ }
matchIntercompanyTransactions: {
Args: { p_company_group_id: string }
Returns: {
diff --git a/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql b/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql
new file mode 100644
index 0000000000..536d6cbfeb
--- /dev/null
+++ b/packages/database/supabase/migrations/20260805201623_company-today-sql-writers.sql
@@ -0,0 +1,455 @@
+-- Business dates derived in SQL must use the business calendar, not the
+-- database's. `company_today()` landed in 20260805023439; this migration adds
+-- the location counterpart and converts the four remaining SQL functions that
+-- WRITE or ANCHOR a business date off `CURRENT_DATE` (= UTC).
+--
+-- Read-only "is it overdue?" surfaces (gauges, purchaseInvoices, salesInvoices,
+-- training periods, planning discontinuation filters) still compare against
+-- CURRENT_DATE. They render a status rather than storing one, so a one-day skew
+-- is cosmetic; converting them is a separate change.
+
+-- Operational sibling of company_today(): a physical site's calendar day, for
+-- expiry and scheduling. Falls back to the company timezone, then UTC — the
+-- same precedence as getLocationTimeZone() in the app.
+CREATE OR REPLACE FUNCTION public.location_today(
+ p_location_id TEXT,
+ p_company_id TEXT
+)
+RETURNS date
+LANGUAGE sql
+STABLE
+AS $function$
+ SELECT (now() AT TIME ZONE COALESCE(
+ (
+ SELECT "timezone" FROM public."location"
+ WHERE "id" = p_location_id AND "companyId" = p_company_id
+ ),
+ (SELECT "timezone" FROM public."company" WHERE "id" = p_company_id),
+ 'UTC'
+ ))::date
+$function$;
+
+-- 1. get_next_sequence — every ERP document number flows through here. The
+-- date tokens were interpolated off the UTC day while the TypeScript twin
+-- (interpolateSequenceDate) used the company timezone, so the two numbering
+-- paths disagreed. Also adds %{ww}/%{hh}/%{ss}, which the Sequences settings
+-- UI advertises but this function emitted literally.
+CREATE OR REPLACE FUNCTION public.get_next_sequence(sequence_name text, company_id text)
+ RETURNS text
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_prefix text;
+ v_suffix text;
+ v_next_value integer;
+ v_size integer;
+ v_next_sequence text;
+ v_derived_prefix text;
+ v_derived_suffix text;
+ v_now timestamp;
+BEGIN
+ IF session_user = 'authenticator' THEN
+ IF NOT (has_role('employee', company_id) OR has_valid_api_key_for_company(company_id)) THEN
+ RAISE EXCEPTION 'Insufficient permissions';
+ END IF;
+ END IF;
+
+ UPDATE sequence
+ SET next = next + step,
+ "updatedBy" = 'system'
+ WHERE "table" = sequence_name
+ AND "companyId" = company_id
+ RETURNING next, prefix, suffix, size
+ INTO v_next_value, v_prefix, v_suffix, v_size;
+
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Sequence not found for table % and company %', sequence_name, company_id;
+ END IF;
+
+ -- Format sequence number
+ v_next_sequence := lpad(v_next_value::text, COALESCE(v_size, 4), '0');
+
+ -- Wall-clock in the company's timezone: document prefixes must roll over at
+ -- the company's midnight, not the database's. Matches the TypeScript twin
+ -- interpolateSequenceDate(value, companyTimezone).
+ v_now := now() AT TIME ZONE COALESCE(
+ (SELECT "timezone" FROM "company" WHERE "id" = company_id),
+ 'UTC'
+ );
+
+ -- Interpolate date variables in prefix/suffix
+ v_derived_prefix := COALESCE(v_prefix, '');
+ v_derived_prefix := replace(v_derived_prefix, '%{yyyy}', to_char(v_now, 'YYYY'));
+ v_derived_prefix := replace(v_derived_prefix, '%{yy}', to_char(v_now, 'YY'));
+ v_derived_prefix := replace(v_derived_prefix, '%{mm}', to_char(v_now, 'MM'));
+ v_derived_prefix := replace(v_derived_prefix, '%{ww}', to_char(v_now, 'IW'));
+ v_derived_prefix := replace(v_derived_prefix, '%{dd}', to_char(v_now, 'DD'));
+ v_derived_prefix := replace(v_derived_prefix, '%{hh}', to_char(v_now, 'HH24'));
+ v_derived_prefix := replace(v_derived_prefix, '%{ss}', to_char(v_now, 'SS'));
+
+ v_derived_suffix := COALESCE(v_suffix, '');
+ v_derived_suffix := replace(v_derived_suffix, '%{yyyy}', to_char(v_now, 'YYYY'));
+ v_derived_suffix := replace(v_derived_suffix, '%{yy}', to_char(v_now, 'YY'));
+ v_derived_suffix := replace(v_derived_suffix, '%{mm}', to_char(v_now, 'MM'));
+ v_derived_suffix := replace(v_derived_suffix, '%{ww}', to_char(v_now, 'IW'));
+ v_derived_suffix := replace(v_derived_suffix, '%{dd}', to_char(v_now, 'DD'));
+ v_derived_suffix := replace(v_derived_suffix, '%{hh}', to_char(v_now, 'HH24'));
+ v_derived_suffix := replace(v_derived_suffix, '%{ss}', to_char(v_now, 'SS'));
+
+ RETURN v_derived_prefix || v_next_sequence || v_derived_suffix;
+END;
+$function$;
+
+-- 2. generateEliminationEntries — the elimination journal's postingDate is a
+-- ledger date and must derive on the elimination entity's calendar.
+CREATE OR REPLACE FUNCTION public."generateEliminationEntries"(p_company_group_id text, p_user_id text)
+ RETURNS integer
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_rec RECORD;
+ v_lca_id TEXT;
+ v_elim_id TEXT;
+ v_journal_id INTEGER;
+ v_period_id TEXT;
+ v_journals_created INTEGER := 0;
+ v_journals_by_elim RECORD;
+BEGIN
+ -- Check that user belongs to at least one company in this group
+ IF NOT EXISTS (
+ SELECT 1
+ FROM "userToCompany" utc
+ INNER JOIN "company" c ON c."id" = utc."companyId"
+ WHERE utc."userId" = auth.uid()::text
+ AND utc."role" = 'employee'
+ AND c."companyGroupId" = p_company_group_id
+ ) THEN
+ RAISE EXCEPTION 'Insufficient permissions to generate elimination entries';
+ END IF;
+
+ -- Process each matched IC transaction pair, routing to the correct elimination entity
+ -- Group matched transactions by their lowest common parent's elimination entity
+ FOR v_rec IN
+ SELECT DISTINCT
+ ict."sourceCompanyId",
+ ict."targetCompanyId"
+ FROM "intercompanyTransaction" ict
+ WHERE ict."companyGroupId" = p_company_group_id
+ AND ict."status" = 'Matched'
+ LOOP
+ -- Find the lowest common parent
+ v_lca_id := "findLowestCommonParent"(v_rec."sourceCompanyId", v_rec."targetCompanyId");
+
+ -- Find the elimination entity for this LCA
+ SELECT c."id" INTO v_elim_id
+ FROM "company" c
+ WHERE c."parentCompanyId" = v_lca_id
+ AND c."isEliminationEntity" = true
+ AND c."companyGroupId" = p_company_group_id
+ LIMIT 1;
+
+ -- If no elimination entity at the LCA level, fall back to any in the group
+ IF v_elim_id IS NULL THEN
+ SELECT c."id" INTO v_elim_id
+ FROM "company" c
+ WHERE c."companyGroupId" = p_company_group_id
+ AND c."isEliminationEntity" = true
+ LIMIT 1;
+ END IF;
+
+ IF v_elim_id IS NULL THEN
+ RAISE EXCEPTION 'No elimination entity found for company group %', p_company_group_id;
+ END IF;
+
+ -- Get active accounting period for elimination entity
+ SELECT "id" INTO v_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = v_elim_id
+ AND "status" = 'Active'
+ LIMIT 1;
+
+ -- Create elimination journal on this elimination entity
+ INSERT INTO "journal" ("description", "accountingPeriodId", "companyId", "postingDate")
+ VALUES (
+ 'IC Elimination: ' || v_rec."sourceCompanyId" || ' ↔ ' || v_rec."targetCompanyId",
+ v_period_id,
+ v_elim_id,
+ -- Ledger date: the elimination entity's calendar, not the database's.
+ company_today(v_elim_id)
+ )
+ RETURNING "id" INTO v_journal_id;
+
+ v_journals_created := v_journals_created + 1;
+
+ -- Generate reversing entries from source journal lines
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", "description", "amount",
+ "documentType", "journalLineReference",
+ "companyId", "companyGroupId"
+ )
+ SELECT
+ v_journal_id,
+ jl."accountId",
+ 'IC Elimination: ' || COALESCE(jl."description", ''),
+ -jl."amount",
+ jl."documentType",
+ 'ic-elim-' || ict."id",
+ v_elim_id,
+ p_company_group_id
+ FROM "intercompanyTransaction" ict
+ INNER JOIN "journalLine" jl ON jl."id" = ict."sourceJournalLineId"
+ WHERE ict."companyGroupId" = p_company_group_id
+ AND ict."status" = 'Matched'
+ AND ict."sourceCompanyId" = v_rec."sourceCompanyId"
+ AND ict."targetCompanyId" = v_rec."targetCompanyId";
+
+ -- Also reverse the matched counterpart entries
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", "description", "amount",
+ "documentType", "journalLineReference",
+ "companyId", "companyGroupId"
+ )
+ SELECT
+ v_journal_id,
+ jl."accountId",
+ 'IC Elimination: ' || COALESCE(jl."description", ''),
+ -jl."amount",
+ jl."documentType",
+ 'ic-elim-' || ict."id",
+ v_elim_id,
+ p_company_group_id
+ FROM "intercompanyTransaction" ict
+ INNER JOIN "journalLine" jl ON jl."id" = ict."targetJournalLineId"
+ WHERE ict."companyGroupId" = p_company_group_id
+ AND ict."status" = 'Matched'
+ AND ict."sourceCompanyId" = v_rec."sourceCompanyId"
+ AND ict."targetCompanyId" = v_rec."targetCompanyId"
+ AND ict."targetJournalLineId" IS NOT NULL;
+
+ -- Update these IC transactions to Eliminated
+ UPDATE "intercompanyTransaction"
+ SET "status" = 'Eliminated',
+ "eliminationJournalId" = v_journal_id,
+ "updatedAt" = NOW()
+ WHERE "companyGroupId" = p_company_group_id
+ AND "status" = 'Matched'
+ AND "sourceCompanyId" = v_rec."sourceCompanyId"
+ AND "targetCompanyId" = v_rec."targetCompanyId";
+
+ END LOOP;
+
+ RETURN v_journals_created;
+END;
+$function$;
+
+-- 3. set_shelf_life_for_operation — writes trackedEntity."expirationDate".
+-- Shelf life is operational, so it counts from the producing plant's day.
+CREATE OR REPLACE FUNCTION public.set_shelf_life_for_operation(p_job_operation_id text, p_event "shelfLifeTriggerTiming")
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ v_job_id TEXT;
+ v_job_make_method_id TEXT;
+ v_operation_process_id TEXT;
+ v_item_id TEXT;
+ v_company_id TEXT;
+ v_location_id TEXT;
+ v_shelf_life_mode "shelfLifeMode";
+ v_shelf_life_days NUMERIC;
+ v_shelf_life_trigger_process TEXT;
+ v_shelf_life_trigger_timing "shelfLifeTriggerTiming";
+ v_calc_from_bom BOOLEAN;
+ v_input_scope TEXT;
+ v_computed_expiry DATE;
+ v_input_min DATE;
+BEGIN
+ SELECT
+ jo."jobId",
+ jo."jobMakeMethodId",
+ jo."processId",
+ jmm."itemId",
+ i."companyId",
+ j."locationId"
+ INTO
+ v_job_id,
+ v_job_make_method_id,
+ v_operation_process_id,
+ v_item_id,
+ v_company_id,
+ v_location_id
+ FROM "jobOperation" jo
+ JOIN "jobMakeMethod" jmm ON jmm."id" = jo."jobMakeMethodId"
+ JOIN "item" i ON i."id" = jmm."itemId"
+ LEFT JOIN "job" j ON j."id" = jo."jobId"
+ WHERE jo."id" = p_job_operation_id;
+
+ IF v_item_id IS NULL THEN
+ RETURN;
+ END IF;
+
+ SELECT
+ "mode", "days", "triggerProcessId", "triggerTiming",
+ "calculateFromBom"
+ INTO
+ v_shelf_life_mode, v_shelf_life_days, v_shelf_life_trigger_process,
+ v_shelf_life_trigger_timing, v_calc_from_bom
+ FROM "itemShelfLife"
+ WHERE "itemId" = v_item_id;
+
+ IF NOT FOUND THEN
+ RETURN;
+ END IF;
+
+ IF v_shelf_life_mode = 'Fixed Duration' THEN
+ IF v_shelf_life_days IS NULL THEN
+ RETURN;
+ END IF;
+
+ IF v_shelf_life_trigger_process IS NULL THEN
+ IF p_event <> 'After' THEN
+ RETURN;
+ END IF;
+ ELSE
+ IF v_operation_process_id IS DISTINCT FROM v_shelf_life_trigger_process THEN
+ RETURN;
+ END IF;
+ IF p_event <> v_shelf_life_trigger_timing THEN
+ RETURN;
+ END IF;
+ END IF;
+
+ -- Shelf life counts from the producing plant's day, not the database's.
+ v_computed_expiry := (
+ location_today(v_location_id, v_company_id)
+ + (v_shelf_life_days || ' days')::INTERVAL
+ )::DATE;
+
+ -- Cap by earliest input expiry when the flag is on.
+ IF v_calc_from_bom THEN
+ SELECT COALESCE(
+ "inventoryShelfLife"->>'calculatedInputScope',
+ 'AllInputs'
+ )
+ INTO v_input_scope
+ FROM "companySettings"
+ WHERE "id" = v_company_id;
+
+ IF v_input_scope IS NULL THEN
+ v_input_scope := 'AllInputs';
+ END IF;
+
+ IF v_input_scope = 'AllInputs' THEN
+ SELECT MIN(te."expirationDate")
+ INTO v_input_min
+ FROM "trackedActivityInput" tai
+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"
+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"
+ WHERE ta.attributes->>'Job Make Method' = v_job_make_method_id
+ AND te."expirationDate" IS NOT NULL;
+ ELSE
+ SELECT MIN(te."expirationDate")
+ INTO v_input_min
+ FROM "trackedActivityInput" tai
+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"
+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"
+ JOIN "itemShelfLife" isl ON isl."itemId" = te."sourceDocumentId"
+ WHERE ta.attributes->>'Job Make Method' = v_job_make_method_id
+ AND isl."mode" IN ('Fixed Duration', 'Calculated')
+ AND te."expirationDate" IS NOT NULL;
+ END IF;
+
+ IF v_input_min IS NOT NULL AND v_input_min < v_computed_expiry THEN
+ v_computed_expiry := v_input_min;
+ END IF;
+ END IF;
+
+ ELSIF v_shelf_life_mode = 'Calculated' THEN
+ IF p_event <> 'After' THEN
+ RETURN;
+ END IF;
+
+ SELECT COALESCE(
+ "inventoryShelfLife"->>'calculatedInputScope',
+ 'AllInputs'
+ )
+ INTO v_input_scope
+ FROM "companySettings"
+ WHERE "id" = v_company_id;
+
+ IF v_input_scope IS NULL THEN
+ v_input_scope := 'AllInputs';
+ END IF;
+
+ IF v_input_scope = 'AllInputs' THEN
+ SELECT MIN(te."expirationDate")
+ INTO v_computed_expiry
+ FROM "trackedActivityInput" tai
+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"
+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"
+ WHERE ta.attributes->>'Job Make Method' = v_job_make_method_id
+ AND te."expirationDate" IS NOT NULL;
+ ELSE
+ SELECT MIN(te."expirationDate")
+ INTO v_computed_expiry
+ FROM "trackedActivityInput" tai
+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"
+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"
+ JOIN "itemShelfLife" isl ON isl."itemId" = te."sourceDocumentId"
+ WHERE ta.attributes->>'Job Make Method' = v_job_make_method_id
+ AND isl."mode" IN ('Fixed Duration', 'Calculated')
+ AND te."expirationDate" IS NOT NULL;
+ END IF;
+
+ IF v_computed_expiry IS NULL THEN
+ RETURN;
+ END IF;
+
+ ELSIF v_shelf_life_mode = 'Set on Receipt' THEN
+ RETURN;
+
+ ELSE
+ RETURN;
+ END IF;
+
+ UPDATE "trackedEntity"
+ SET "expirationDate" = v_computed_expiry
+ WHERE "sourceDocument" = 'Item'
+ AND "sourceDocumentId" = v_item_id
+ AND "attributes"->>'Job Make Method' = v_job_make_method_id
+ AND "expirationDate" IS NULL;
+END;
+$function$;
+
+-- 4. resolve_shelf_life_start_for_receipt — the anchor falls back to "today"
+-- when the receipt has no postingDate yet; that fallback is the receiving
+-- site's day.
+CREATE OR REPLACE FUNCTION public.resolve_shelf_life_start_for_receipt(p_item_id text, p_receipt_id text)
+ RETURNS date
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_mode "shelfLifeMode";
+ v_days NUMERIC;
+ v_anchor DATE;
+BEGIN
+ SELECT "mode", "days" INTO v_mode, v_days
+ FROM "itemShelfLife"
+ WHERE "itemId" = p_item_id;
+
+ IF NOT FOUND OR v_mode <> 'Fixed Duration' OR v_days IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ SELECT COALESCE("postingDate", location_today("locationId", "companyId"))
+ INTO v_anchor
+ FROM "receipt"
+ WHERE id = p_receipt_id;
+
+ RETURN (v_anchor + (v_days || ' days')::INTERVAL)::DATE;
+END;
+$function$;