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): thermo self-review round — NUL sentinel, period pinning everywhere

Sidwebworks418fdfd19d19
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 2f361ff43f..5cf756a6e1 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -630,6 +630,6 @@ Format: `Context → Problem → Rule → Applies to`
**Problem:** Two independent under-coverages compounded. (1) The check's source globs (`sources/server-files.ts`) listed services, jobs, and edge functions but not `apps/*/app/routes` — and collected only `.ts`, never `.tsx` — so route loaders/actions (server code!) were never scanned. (2) The banned-pattern list encoded only the idioms already found (`getLocalTimeZone(`, UTC-slicing), not the bug class — `new Date().getDay()` shift rosters and `setHours(0,0,0,0)` week boundaries sailed through in files that WERE scanned. Naively adding the route glob would over-flag: a route module's default export, `clientLoader`/`clientAction`, and hooks run in the browser where the local timezone is correct. Masking IN loader/action bodies also failed — module-level helpers a loader calls (e.g. `getExpiredItemIds`) are server code outside those bodies.
-**Rule:** When authoring a conformance check, verify the checker actually loads every file class the rule applies to (run it, count the files, grep one known-bad file into the scan). Ban the bug class, not just the instances you found — then run the widened pattern over the full source set and fix or baseline everything it surfaces before landing. For React Router route modules, path-level globs are the wrong granularity: mask OUT the client regions by declaration shape (`maskClientCode` blanks default export / `clientLoader` / `clientAction` / PascalCase and `use*` declarations) so server helpers stay covered; masking IN named exports under-covers.
+**Rule:** When authoring a conformance check, verify the checker actually loads every file class the rule applies to (run it, count the files, grep one known-bad file into the scan). Ban the bug class, not just the instances you found — then run the widened pattern over the full source set and fix or baseline everything it surfaces before landing. For React Router route modules, path-level globs are the wrong granularity: mask OUT the client regions by declaration shape (`maskClientCode` blanks default export / `clientLoader` / `clientAction` / PascalCase and `use*` declarations) so server helpers stay covered; masking IN named exports under-covers. And when masking by line shape, the region CLOSER is as bug-prone as the opener: a `)` closer that also matches a multi-line signature's `) {` line ends the region before the body and un-masks client code (only statement-terminating `)`/`);` lines close a region), while an expression-bodied one-liner (`const X = () => null;`) must never OPEN a region at all — pin both shapes as regression tests.
**Applies to:** `packages/checks/src/sources/server-files.ts` + `conformance/no-local-timezone.ts`; any new `SERVER_CHECKS` rule; any lint/conformance gate keyed on file paths over `apps/*/app/routes`.
diff --git a/apps/erp/app/modules/shared/timezone.server.ts b/apps/erp/app/modules/shared/timezone.server.ts
index 0fc3d51763..57cc07cb56 100644
Binary files a/apps/erp/app/modules/shared/timezone.server.ts and b/apps/erp/app/modules/shared/timezone.server.ts differ
diff --git a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx
index 1fa5cc9280..9dec73abff 100644
--- a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx
+++ b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx
@@ -179,8 +179,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
entries: entries.data ?? [],
openEntry: openEntry.data,
weekOffset,
- from,
- to,
weekStart,
weekEnd,
shift
diff --git a/apps/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsx
index 93e307dccd..7edda6680b 100644
--- a/apps/mes/app/routes/x+/timecard.tsx
+++ b/apps/mes/app/routes/x+/timecard.tsx
@@ -130,8 +130,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
entries: entries.data ?? [],
openEntry: openEntry.data,
weekOffset,
- from,
- to,
weekStart,
weekEnd
};
diff --git a/packages/database/src/timezone.ts b/packages/database/src/timezone.ts
index 90eb1a5e6f..c2bc8285e9 100644
--- a/packages/database/src/timezone.ts
+++ b/packages/database/src/timezone.ts
@@ -98,3 +98,37 @@ export async function getLocationTimeZone(
}
return location.data?.timezone || getCompanyTimeZone(db, companyId);
}
+
+/**
+ * The timezone a location DEFINES ITSELF, or null when it inherits the
+ * company's (missing row, null, or legacy empty-string value). For callers
+ * that must distinguish own-vs-inherited — e.g. the ERP Redis cache, which
+ * must never store an inherited company timezone under a location key.
+ */
+export async function getLocationOwnTimeZone(
+ db: AnyPostgresClient,
+ locationId: string,
+ companyId: string
+): Promise<string | null> {
+ if (isKysely(db)) {
+ const row = await db
+ .selectFrom("location")
+ .select("timezone")
+ .where("id", "=", locationId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ return row?.timezone || null;
+ }
+ const location = await db
+ .from("location")
+ .select("timezone")
+ .eq("id", locationId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (location.error) {
+ throw new Error(
+ `Failed to resolve location timezone: ${location.error.message}`
+ );
+ }
+ return location.data?.timezone || null;
+}
diff --git a/packages/database/supabase/functions/close-job/index.ts b/packages/database/supabase/functions/close-job/index.ts
index bc9bb03e2c..ec1dfb7482 100644
--- a/packages/database/supabase/functions/close-job/index.ts
+++ b/packages/database/supabase/functions/close-job/index.ts
@@ -139,7 +139,8 @@ serve(async (req: Request) => {
const accountingPeriodId = await getCurrentAccountingPeriod(
client,
companyId,
- trx
+ trx,
+ today
);
const journalEntryId = await getNextSequence(
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 378ac9ef5a..63c63f66ef 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -17,7 +17,7 @@ import { Database } from "../lib/types.ts";
import { TrackedEntityAttributes, credit, debit, journalReference } from "../lib/utils.ts";
import { buildBatchSplitRecords } from "../shared/batch-split.ts";
-import { getAccountingPeriodForDate } from "../shared/get-accounting-period.ts";
+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
import { getNextSerialNumbers } from "../shared/get-next-serial-number.ts";
import {
@@ -451,7 +451,7 @@ async function issueJobOperationMaterials(
if (journalLineInserts.length > 0) {
// Resolve the period from the SAME hoisted `today` the ledger rows used —
// a midnight rollover mid-transaction must not split journal and ledger.
- const accountingPeriodId = await getAccountingPeriodForDate(client, companyId, trx, today);
+ const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, trx, today);
const journalEntryId = await getNextSequence(trx, "journalEntry", companyId);
const journalResult = await trx
@@ -718,7 +718,7 @@ async function createMaterialWipEntries(
if (journalLineInserts.length === 0) return;
// Same hoisted `today` as this function's ledger rows (see above).
- const accountingPeriodId = await getAccountingPeriodForDate(client, companyId, trx, today);
+ const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, trx, today);
const journalEntryId = await getNextSequence(trx, "journalEntry", companyId);
const journalResult = await trx
diff --git a/packages/database/supabase/functions/lib/datetime.ts b/packages/database/supabase/functions/lib/datetime.ts
index 3d84653f19..ee165d6505 100644
--- a/packages/database/supabase/functions/lib/datetime.ts
+++ b/packages/database/supabase/functions/lib/datetime.ts
@@ -1,11 +1,12 @@
// 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.
+// Keep the two files in sync. One deliberate delta: the Node copy also has
+// `weekBounds` (payroll/timecard week windows) — no edge function needs it
+// yet; mirror it in when one does.
import {
type CalendarDate,
now,
parseAbsolute,
- startOfWeek,
toCalendarDate,
today
} from "@internationalized/date";
@@ -46,32 +47,6 @@ export const datetime = {
businessDay: (instant: string, tz: string) =>
toCalendarDate(parseAbsolute(instant, tz)),
- /**
- * The ISO week (Monday 00:00 → Sunday 23:59:59.999) containing `anchor`
- * (default: today on the given business calendar) as UTC instant strings.
- * `offset` shifts whole weeks (-1 = last week).
- *
- * DST-safe by construction: boundaries are derived per-day via
- * `CalendarDate.toDate(tz)`, so a transition week is genuinely 167h/169h
- * (Lord Howe: ±30min) rather than a fixed 168, consecutive weeks tile with
- * no gap or double-count, and in zones that spring forward AT midnight
- * (America/Santiago) a boundary that lands on the skipped midnight resolves
- * to that day's true first instant (01:00) instead of crashing or drifting
- * a day.
- */
- weekBounds: (
- tz: string,
- offset = 0,
- anchor?: CalendarDate
- ): { from: string; to: string } => {
- const monday = startOfWeek((anchor ?? today(tz)).add({ weeks: offset }), "en-GB");
- const nextMonday = monday.add({ weeks: 1 }).toDate(tz);
- return {
- from: monday.toDate(tz).toISOString(),
- to: new Date(nextMonday.getTime() - 1).toISOString()
- };
- },
-
weekNumber
};
diff --git a/packages/database/supabase/functions/post-inventory-adjustment/index.ts b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
index 35e7193f27..90161ef0c9 100644
--- a/packages/database/supabase/functions/post-inventory-adjustment/index.ts
+++ b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
@@ -169,7 +169,7 @@ serve(async (req: Request) => {
// getCurrentAccountingPeriod uses the REST client and calling it
// mid-transaction parks the (size 1) pool in idle-in-transaction.
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
const accounting =
accountingEnabled && accountDefaults?.data && accountingPeriodId
diff --git a/packages/database/supabase/functions/post-inventory-count/index.ts b/packages/database/supabase/functions/post-inventory-count/index.ts
index c161b438b3..aa7060358c 100644
--- a/packages/database/supabase/functions/post-inventory-count/index.ts
+++ b/packages/database/supabase/functions/post-inventory-count/index.ts
@@ -191,7 +191,7 @@ serve(async (req: Request) => {
throw new Error("Error getting account defaults");
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
// Active dimensions for the company group (post-shipment precedent) —
diff --git a/packages/database/supabase/functions/post-memo/index.ts b/packages/database/supabase/functions/post-memo/index.ts
index ca5dbceb74..6f1c519b36 100644
--- a/packages/database/supabase/functions/post-memo/index.ts
+++ b/packages/database/supabase/functions/post-memo/index.ts
@@ -70,7 +70,7 @@ serve(async (req: Request) => {
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
await db.transaction().execute(async (trx) => {
@@ -209,7 +209,7 @@ serve(async (req: Request) => {
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
// Build the (balanced, two-line) journal in base currency. Account-id
diff --git a/packages/database/supabase/functions/post-nonconformance/index.ts b/packages/database/supabase/functions/post-nonconformance/index.ts
index 5d6035dacd..b4c15b5d68 100644
--- a/packages/database/supabase/functions/post-nonconformance/index.ts
+++ b/packages/database/supabase/functions/post-nonconformance/index.ts
@@ -174,7 +174,7 @@ serve(async (req: Request) => {
// getCurrentAccountingPeriod uses the REST client and calling it
// mid-transaction parks the (size 1) pool in idle-in-transaction.
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, postingDate)
: null;
const journalDescription =
diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.ts
index e986a52a0c..1fbb3ff687 100644
--- a/packages/database/supabase/functions/post-payment/index.ts
+++ b/packages/database/supabase/functions/post-payment/index.ts
@@ -85,7 +85,7 @@ serve(async (req: Request) => {
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
await db.transaction().execute(async (trx) => {
@@ -289,7 +289,7 @@ serve(async (req: Request) => {
// Build journal lines (in base currency)
// --------------------------------------------------------------
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
const journalLineInserts: PaymentJournalLine[] = [];
diff --git a/packages/database/supabase/functions/post-production-event/index.ts b/packages/database/supabase/functions/post-production-event/index.ts
index cda66eddb4..eb789740c5 100644
--- a/packages/database/supabase/functions/post-production-event/index.ts
+++ b/packages/database/supabase/functions/post-production-event/index.ts
@@ -296,7 +296,8 @@ serve(async (req: Request) => {
const accountingPeriodId = await getCurrentAccountingPeriod(
client,
companyId,
- db
+ db,
+ today
);
await db.transaction().execute(async (trx) => {
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index f9acb64f19..14c4f6548c 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -332,7 +332,7 @@ serve(async (req: Request) => {
}));
const accountingPeriodIdVoid = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
await db.transaction().execute(async (trx) => {
@@ -1742,7 +1742,7 @@ serve(async (req: Request) => {
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
const createdReceiptIds: string[] = [];
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 8384ce67b8..be44909279 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -457,7 +457,8 @@ serve(async (req: Request) => {
const accountingPeriodId = await getCurrentAccountingPeriod(
client,
companyId,
- db
+ db,
+ today
);
await db.transaction().execute(async (trx) => {
@@ -1503,7 +1504,7 @@ serve(async (req: Request) => {
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
await db.transaction().execute(async (trx) => {
@@ -2164,7 +2165,7 @@ serve(async (req: Request) => {
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
await db.transaction().execute(async (trx) => {
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index b0a8102b83..4eb8e4c318 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -898,7 +898,7 @@ serve(async (req: Request) => {
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
await db.transaction().execute(async (trx) => {
@@ -1411,7 +1411,7 @@ serve(async (req: Request) => {
}
const accountingPeriodId = accountingEnabled
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
await db.transaction().execute(async (trx) => {
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index 436504934b..cb9f83a145 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -783,7 +783,8 @@ serve(async (req: Request) => {
const accountingPeriodId = await getCurrentAccountingPeriod(
client,
companyId,
- db
+ db,
+ today
);
await db.transaction().execute(async (trx) => {
@@ -2143,7 +2144,7 @@ serve(async (req: Request) => {
const accountingPeriodId =
accountingEnabled && reversingJournalLines.length > 0
- ? await getCurrentAccountingPeriod(client, companyId, db)
+ ? await getCurrentAccountingPeriod(client, companyId, db, today)
: null;
await db.transaction().execute(async (trx) => {
diff --git a/packages/database/supabase/functions/shared/get-accounting-period.ts b/packages/database/supabase/functions/shared/get-accounting-period.ts
index 85d4b48c7b..aca0ab5dd0 100644
--- a/packages/database/supabase/functions/shared/get-accounting-period.ts
+++ b/packages/database/supabase/functions/shared/get-accounting-period.ts
@@ -1,3 +1,4 @@
+import { parseDate } from "@internationalized/date";
import { SupabaseClient } from "@supabase/supabase-js";
import { Kysely } from "kysely";
import { DB } from "../lib/database.ts";
@@ -185,11 +186,18 @@ export async function getAccountingPeriodForDate(
export async function getCurrentAccountingPeriod<T>(
client: SupabaseClient<Database>,
companyId: string,
- db: Kysely<DB>
+ db: Kysely<DB>,
+ // Pass the SAME hoisted business day the caller stamps on its ledger and
+ // journal rows — two independent "today" resolutions inside one transaction
+ // can straddle midnight and split the journal's period from its ledger
+ // dates. Omitted = resolved fresh in the company timezone.
+ forDate?: string // yyyy-MM-dd
) {
// "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 companyToday = forDate
+ ? parseDate(forDate)
+ : datetime.today(await getCompanyTimeZone(client, companyId));
const d = companyToday.toString();
// get the current accounting period