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.

feat(settings): configurable per-item serial number sequences (#1307)

Brad Barbin00179b942429
diff --git a/.ai/plans/2026-08-02-serial-number-sequences.md b/.ai/plans/2026-08-02-serial-number-sequences.md
new file mode 100644
index 0000000000..8391487001
--- /dev/null
+++ b/.ai/plans/2026-08-02-serial-number-sequences.md
@@ -0,0 +1,166 @@
+# Serial Number Sequences — Implementation Plan
+
+**Date:** 2026-08-02
+**Branch:** malabo
+**Status:** APPROVED — Option A (full v1: config + location code + batch + serial pre-split + MES rework). Smaller decisions accepted as recommended: table `itemSerialSequence`, Serial/Batch-only, `settings` permission, `assign-serial-numbers` edge fn, root-item scope, ISO `%{ww}`.
+
+## Goal
+
+Let users configure an optional serial-number **format + counter per item** (zero or one per
+item), almost identical to the existing document **Sequences** feature, but keyed to an item
+instead of a document type. When a job is created for that item, auto-generate serial numbers
+from the format and assign them as the `readableId` of the job's tracked entities:
+
+- **Batch** item → generate **1** number → the single `quantity=N` seed entity.
+- **Serial** item, qty N → generate **N** numbers → **N** `quantity=1` entities (pre-split at creation).
+
+Configured format segments (generalized from the customer's `[Site][Year][Month][serial]` /
+`[Product family][Year][Week][serial]` examples):
+
+- **Prefix** (static text; generalizes "site"/"product family") — supports tokens.
+- **Date tokens**: `%{yyyy}` `%{yy}` `%{mm}` `%{dd}` and **NEW `%{ww}`** (week).
+- **Location token NEW `%{location}`** → `location.code ?? location.name`.
+- **Counter** with configurable zero-pad width (`size`) and `step`.
+- **Suffix** (optional; same tokens).
+
+Worked examples this must reproduce:
+- `%{location}-%{yy}%{mm}` + size 5, location code `US`, 2026-07 → `US-260700001`
+- `MOTH%{yy}%{ww}` + size 5, 2026 week 31 → `MOTH263100001`
+
+## Key design decisions (NEED CONFIRMATION where flagged 🔶)
+
+1. **Table `itemSerialSequence`**, PK `("id","companyId")` (modern convention) with a
+ **UNIQUE `("itemId","companyId")`** to enforce one-per-item. Columns mirror `sequence`
+ (`prefix`, `suffix`, `next` default 0 = none issued, `size` default 5, `step` default 1) +
+ full audit columns. FK `itemId → item(id)`. 🔶 Name: `itemSerialSequence` (avoids collision
+ with existing inventory `path.to.serialNumbers`).
+2. **Only Serial/Batch items** may have a serial sequence (non-tracked items get no tracked
+ entities, so nothing to number). Enforced in the item picker + item-page card visibility.
+3. **Permission gating = `settings`** (view/create/update/delete), mirroring Sequences, since
+ this is "a new sub-module in settings." The item-page card is also `settings`-gated. 🔶
+ Alternative: gate on `parts`. Recommend `settings`.
+4. **Generation lives in a new edge function `assign-serial-numbers`** invoked from `insertJob`
+ after the job insert (Seam A). Atomic reservation via Kysely `UPDATE ... SET next = next +
+ count*step ... RETURNING` inside the function's transaction. Interpolation (date + week +
+ location) done in TS. No new Postgres RPC needed (settings/item previews compute in TS
+ without incrementing).
+5. **Serial pre-split at job creation** into N `quantity=1` Reserved entities. 🔶 **This is the
+ scope-expanding decision** — it requires reworking 4 MES route heuristics (see Phase 5).
+ Verified: no data/ledger double-creation downstream; `complete_job_to_inventory` iterates
+ existing entities; `issue.jobOperationSerialComplete` spawn is self-guarding. The only breakage
+ is MES "select newest Reserved entity" logic.
+6. **Scope = root make method seed per job.** MTO sub-assemblies are separate jobs → each gets
+ its own serials via the same hook. Non-root `jobMaterial` seeds are out of scope for v1.
+7. **`%{ww}` = ISO week** (`getISOWeek`-style). Minor year-boundary caveat vs calendar `%{yy}`;
+ acceptable, documented.
+
+## Phases
+
+### Phase 0 — Location `code` column
+- Migration: `ALTER TABLE "location" ADD COLUMN IF NOT EXISTS "code" TEXT;` (nullable).
+- Backfill (idempotent): `UPDATE "location" SET "code" = 'HQ' WHERE "name" = 'Headquarters' AND "code" IS NULL;`
+- Redefine SELECT-* views over `location` so `code` flows through — **view list PENDING from
+ location research agent** (finalize before writing the migration).
+- Add `code` to `locationValidator` (models) + the location form UI (optional Input, label "Code",
+ helper "Short abbreviation used in serial numbers, e.g. HQ, US").
+- `generate:types`.
+
+### Phase 1 — `itemSerialSequence` table
+- Migration: table + composite PK + unique(itemId,companyId) + FKs + `companyId` index + 4 RLS
+ policies gated on `settings_view/create/update/delete` (::text[] casts, simple names).
+- No seed rows (user-created, unlike `sequence`).
+- `generate:types`.
+
+### Phase 2 — Interpolation (`%{ww}`, `%{location}`)
+- Extend `interpolateSequenceDate` in BOTH `apps/erp/app/utils/string.ts` and
+ `packages/database/supabase/functions/lib/utils.ts` to add `%{ww}` (additive, safe).
+- New `interpolateSerialNumber(format, { location })` (edge lib) that runs date/week interpolation
+ then replaces `%{location}` with `code ?? name`. Used by the edge function.
+- Settings/item preview: show `%{location}` as a literal placeholder (no job context).
+
+### Phase 3 — Settings sub-module (CRUD, mirror Webhooks not Sequences)
+- Models: `itemSerialSequenceValidator` in `settings.models.ts`.
+- Service in `settings.service.ts`: `getItemSerialSequences` (list, join item readableId/name),
+ `getItemSerialSequence`, `getItemSerialSequenceByItem(itemId)`, `upsertItemSerialSequence`,
+ `deleteItemSerialSequence`.
+- Types: `ItemSerialSequence` derived type.
+- Routes: `x+/settings+/serial-numbers.tsx` (list+Outlet), `.new.tsx`, `.$id.tsx`, `.delete.$id.tsx`.
+- UI: `ItemSerialSequencesTable` + `ItemSerialSequenceForm` (mirror SequenceForm preview + token
+ legend incl. `%{ww}` and `%{location}`; add item picker on New, disabled on edit).
+- Nav entry in `useSettingsSubmodules.tsx` (System group, icon e.g. `LuBarcode`).
+- Path helpers: `serialNumberSettings`, `newSerialNumberSetting`, `serialNumberSetting(id)`,
+ `deleteSerialNumberSetting(id)`, `api.serialNumberSettingByItem(itemId)`.
+- Item combobox source: only `itemTrackingType IN ('Serial','Batch')` items without an existing
+ sequence.
+
+### Phase 4 — Item-detail surface
+- A card on the item detail page (part/material/tool/consumable) to add/edit/delete THIS item's
+ serial sequence, reusing `ItemSerialSequenceForm` + service. Visible only when
+ `itemTrackingType ∈ {Serial,Batch}`.
+- Simplest home: extend `x+/part+/$itemId.details.tsx` (+ material/tool/consumable equivalents)
+ action with an `intent` branch, render the card in the details stack. (Confirm exact host tab
+ during execution.)
+
+### Phase 5 — Job-creation integration + MES rework
+- **Edge function `assign-serial-numbers`** (`config.toml` + `functions/assign-serial-numbers/index.ts`):
+ - Validate `{ jobId, companyId, userId }`; `requirePermissions(update: production)`.
+ - Kysely txn: load job (itemId, quantity, locationId), item (itemTrackingType),
+ `itemSerialSequence` (none → return `{assigned:0}`), location (code,name).
+ - Reserve `count` = (Batch ? 1 : round(job.quantity)) via `UPDATE ... RETURNING`.
+ - Format the `count` numbers with date/week/location interpolation.
+ - Batch: update the single seed entity's `readableId`.
+ - Serial: transform the seed into entity #1 (quantity=1, readableId=serial1) + insert N-1 more
+ (quantity=1, same attributes, Reserved) with the remaining serials.
+- `insertJob` invokes `assign-serial-numbers` after the job insert (near the `recalculate` invoke).
+- **MES rework (required by pre-split)** — migrate "newest Reserved entity" heuristics to "next
+ entity without an `Operation ${operationId}` attribute" (the pattern already in
+ `useOperation.tsx` / `postSerialCompletions`):
+ 1. `apps/mes/app/routes/x+/operation.$operationId.tsx` (loader `[length-1]` fallback + default id)
+ 2. `apps/mes/app/routes/x+/start.$operationId.tsx` (`[length-1]` fallback)
+ 3. `apps/mes/app/routes/x+/end.$operationId.tsx` (`[length-1]` fallback + `newTrackedEntityId` advance)
+ 4. `apps/mes/app/routes/x+/complete.tsx` (stop relying on `newTrackedEntityId`)
+ - Optional cleanup: remove now-dead spawn block in `issue.jobOperationSerialComplete`; tighten
+ its re-completion guard to skip entities already carrying `Operation ${id}`.
+
+### Phase 6 — Verification
+- `generate:types` (after Phases 0/1), scoped typechecks (erp, mes, database, functions), biome.
+- Browser e2e (mandatory per project rule): configure a serial sequence for a serial item, create a
+ job qty=3 → confirm 3 numbered "Serial 1..3" entities on Job Properties; batch item → 1 number;
+ MES: complete units in order, confirm each advances and no re-completion.
+
+## Progress (2026-08-02)
+
+Implemented (lint-clean via Biome; NOT yet type-checked or browser-verified — pending stack boot):
+- [x] Phase 0 — `location.code` migration + HQ backfill; validator/form/seed (`code`) added.
+- [x] Phase 1 — `itemSerialSequence` table + RLS + `itemSerialSequences` list view.
+- [x] Phase 2 — `%{ww}` added to both `interpolateSequenceDate`; `interpolateSerialNumber` (+`%{location}`) in edge lib.
+- [x] Phase 3 — settings CRUD: validator, service (get/list/getByItem/upsert/delete), type, form+table UI,
+ 4 routes (list/new/$id/delete), nav entry, 4 path helpers (`serialNumberSequence*`), barrels.
+- [x] Phase 5a — `assign-serial-numbers` edge fn + `config.toml`.
+- [x] Phase 5b — `insertJob` + `convertSalesOrderLinesToJobs` both call shared `assignJobSerialNumbers`
+ helper (guarded: only invokes when the item has a sequence). Deprecated `upsertJob` has no create callers.
+- [x] Phase 5c — MES pre-split rework: shared `getNextIncompleteSerialEntity` helper +
+ `isSerialEntityIncompleteForOperation` predicate; 4 routes advance #1→#N; old lazy-split flow preserved.
+- [x] Phase 6a — stack booted (freed 4 slots), **migrations applied cleanly**, types regenerated,
+ `erp` + `mes` + `@carbon/database` typecheck GREEN, Biome GREEN. (Fixed nullable-view-column
+ handling in the table + new/$id routes.)
+- [~] Phase 6b — browser e2e (configure sequence → create serial job qty 3 → verify SN-00001/2/3) running.
+- [ ] Commit + PR (with screenshots) — only on the user's ok (no auto-commit).
+
+Design note: settings sub-module is full CRUD with an Item picker in New (blacklisting already-configured
+items to enforce one-per-item); no per-item-page card in v1 (any item type is configurable from settings).
+
+## Risks / open questions
+- 🔶 Serial pre-split + MES rework in v1 vs. ship config + Batch first, defer Serial. (Serial can't
+ ship without the MES fixes — they're a unit.)
+- Job quantity is `NUMERIC(10,4)`; serial jobs assumed integer — round + guard.
+- Concurrency: two jobs for the same item created simultaneously — the atomic `UPDATE...RETURNING`
+ reservation prevents duplicate serials.
+- Existing jobs created before a sequence exists are unaffected (readableId stays null; manual entry
+ still works via Job Properties).
+
+## Files touched (estimate)
+~3 migrations, 1 edge function (+config.toml), settings module (models/service/types/4 routes/2 UI
++ nav + path helpers), items module (card + service + validator, ×4 item types), production
+`insertJob`, 4 MES routes, location validator + form, 2 interpolation utils. Cross-module → approval
+required per AGENTS.md.
diff --git a/apps/academy/app/styles/tailwind.css b/apps/academy/app/styles/tailwind.css
index 08e97c934c..c239c81dd8 100644
--- a/apps/academy/app/styles/tailwind.css
+++ b/apps/academy/app/styles/tailwind.css
@@ -98,3 +98,16 @@
.font-display {
font-family: "DM Sans", sans-serif;
}
+
+@keyframes spinner-fade {
+ 0% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0.15;
+ }
+}
+
+.animate-spinner {
+ animation: spinner-fade 1.2s linear infinite;
+}
\ No newline at end of file
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 53a2d57f96..ebe9c70c0a 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -328,6 +328,13 @@ export async function convertSalesOrderLinesToJobs(
}
});
+ await assignJobSerialNumbers(client, {
+ jobId: createJob.data.id,
+ itemId: data.itemId,
+ companyId,
+ userId
+ });
+
jobsCreated++;
}
}
@@ -2831,6 +2838,14 @@ export async function insertJob(
}
}
+ // Assign configured serial numbers to the job's tracked entities (best-effort).
+ await assignJobSerialNumbers(client, {
+ jobId: createdJobId,
+ itemId: input.itemId,
+ companyId: input.companyId,
+ userId: input.createdBy
+ });
+
if (!options?.skipRecalculate) {
await client.functions.invoke("recalculate", {
body: {
@@ -2845,6 +2860,46 @@ export async function insertJob(
return { data: { id: createdJobId, jobId }, error: null };
}
+/**
+ * Assign configured serial numbers to a freshly-created job's tracked entities.
+ * Best-effort and cheap: it skips the edge function entirely unless the item has
+ * an `itemSerialSequence` configured. Shared by every job-creation path so serial
+ * numbering is applied consistently (insertJob, sales-order conversion, ...).
+ */
+async function assignJobSerialNumbers(
+ client: SupabaseClient<Database>,
+ args: { jobId: string; itemId: string; companyId: string; userId: string }
+) {
+ const serialSequence = await client
+ .from("itemSerialSequence")
+ .select("id")
+ .eq("itemId", args.itemId)
+ .eq("companyId", args.companyId)
+ .maybeSingle();
+ // A query error (DB/RLS) also returns null data — distinguish it from "no
+ // sequence configured" so a failure can't silently create an unnumbered job.
+ if (serialSequence.error) {
+ logger.error("Failed to check item serial sequence", {
+ error: serialSequence.error,
+ itemId: args.itemId,
+ companyId: args.companyId
+ });
+ return;
+ }
+ if (!serialSequence.data) return;
+
+ const { error } = await client.functions.invoke("assign-serial-numbers", {
+ body: {
+ jobId: args.jobId,
+ companyId: args.companyId,
+ userId: args.userId
+ }
+ });
+ if (error) {
+ logger.error("Failed to assign serial numbers", { error });
+ }
+}
+
export async function updateJob(
client: SupabaseClient<Database>,
input: {
diff --git a/apps/erp/app/modules/resources/resources.models.ts b/apps/erp/app/modules/resources/resources.models.ts
index e48c86b933..6861032e00 100644
--- a/apps/erp/app/modules/resources/resources.models.ts
+++ b/apps/erp/app/modules/resources/resources.models.ts
@@ -71,6 +71,7 @@ export const locationValidator = z
.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
+ code: zfd.text(z.string().optional()),
addressLine1: z.string().min(1, { message: "Address is required" }),
addressLine2: z.string().optional(),
city: z.string().min(1, { message: "City is required" }),
diff --git a/apps/erp/app/modules/resources/ui/Locations/LocationForm.tsx b/apps/erp/app/modules/resources/ui/Locations/LocationForm.tsx
index 63cb36d687..73c44403be 100644
--- a/apps/erp/app/modules/resources/ui/Locations/LocationForm.tsx
+++ b/apps/erp/app/modules/resources/ui/Locations/LocationForm.tsx
@@ -97,6 +97,7 @@ const LocationForm = ({
<Hidden name="type" value={type} />
<VStack spacing={4}>
<Input name="name" label={t`Location Name`} />
+ <Input name="code" label={t`Code`} />
<AddressAutocomplete />
<Timezone
name="timezone"
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index 604c262e0e..ac6d7c1c20 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -314,6 +314,16 @@ export const sequenceValidator = z.object({
size: zfd.numeric(z.number().min(1).max(20))
});
+export const itemSerialSequenceValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ prefix: zfd.text(z.string().optional()),
+ suffix: zfd.text(z.string().optional()),
+ next: zfd.numeric(z.number().min(0)),
+ step: zfd.numeric(z.number().min(1)),
+ size: zfd.numeric(z.number().min(1).max(20))
+});
+
export const themes = [
"zinc",
"neutral",
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 8a2acedd42..42b19c007e 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -28,6 +28,7 @@ import type {
accountsReceivableBillingAddressValidator,
apiKeyValidator,
companyValidator,
+ itemSerialSequenceValidator,
kanbanOutputTypes,
purchasePriceUpdateTimingTypes,
sequenceValidator,
@@ -461,6 +462,103 @@ export async function getSequencesList(
.order("table");
}
+export async function getItemSerialSequences(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & {
+ search: string | null;
+ }
+) {
+ let query = client
+ .from("itemSerialSequences")
+ .select("*", {
+ count: "exact"
+ })
+ .eq("companyId", companyId);
+
+ if (args.search) {
+ // Strip PostgREST filter-grammar characters so a search term can't alter the
+ // `or` expression or filter unintended columns (mirrors inventory.service.ts).
+ const search = args.search.replace(/[,()\\]/g, " ");
+ query = query.or(
+ `itemReadableId.ilike.%${search}%,itemName.ilike.%${search}%`
+ );
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "itemReadableId", ascending: true }
+ ]);
+ return query;
+}
+
+export async function getItemSerialSequence(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ return client
+ .from("itemSerialSequences")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+}
+
+export async function getItemSerialSequenceByItemId(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ return client
+ .from("itemSerialSequence")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+}
+
+export async function upsertItemSerialSequence(
+ client: SupabaseClient<Database>,
+ itemSerialSequence:
+ | (Omit<z.infer<typeof itemSerialSequenceValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof itemSerialSequenceValidator>, "id"> & {
+ id: string;
+ companyId: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in itemSerialSequence) {
+ return client
+ .from("itemSerialSequence")
+ .insert([itemSerialSequence])
+ .select("id")
+ .single();
+ }
+ const { id, companyId, ...update } = itemSerialSequence;
+ return client
+ .from("itemSerialSequence")
+ .update(sanitize(update))
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .select("id")
+ .single();
+}
+
+export async function deleteItemSerialSequence(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ return client
+ .from("itemSerialSequence")
+ .delete()
+ .eq("id", id)
+ .eq("companyId", companyId);
+}
+
export async function getSubsidiaries(
client: SupabaseClient<Database>,
companyGroupId: string
diff --git a/apps/erp/app/modules/settings/types.ts b/apps/erp/app/modules/settings/types.ts
index 43ab4ff10a..06a241a516 100644
--- a/apps/erp/app/modules/settings/types.ts
+++ b/apps/erp/app/modules/settings/types.ts
@@ -4,6 +4,7 @@ import type {
getCustomField,
getCustomFieldsTables,
getIntegrations,
+ getItemSerialSequences,
getSequences,
getSubsidiaries,
getWebhooks
@@ -37,6 +38,10 @@ export type Sequence = NonNullable<
Awaited<ReturnType<typeof getSequences>>["data"]
>[number];
+export type ItemSerialSequence = NonNullable<
+ Awaited<ReturnType<typeof getItemSerialSequences>>["data"]
+>[number];
+
export type Webhook = NonNullable<
Awaited<ReturnType<typeof getWebhooks>>["data"]
>[number];
diff --git a/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequenceForm.tsx b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequenceForm.tsx
new file mode 100644
index 0000000000..acb635a466
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequenceForm.tsx
@@ -0,0 +1,160 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ Heading,
+ HStack,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useState } from "react";
+import { useNavigate } from "react-router";
+import type { z } from "zod";
+import { Hidden, Input, Item, Number, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { itemSerialSequenceValidator } from "~/modules/settings";
+import { path } from "~/utils/path";
+import { interpolateSequenceDate } from "~/utils/string";
+
+type ItemSerialSequenceFormProps = {
+ initialValues: z.infer<typeof itemSerialSequenceValidator>;
+ // Items that already have a sequence — excluded from the picker so a second
+ // sequence can't be created for the same item.
+ configuredItemIds?: string[];
+};
+
+const ItemSerialSequenceForm = ({
+ initialValues,
+ configuredItemIds = []
+}: ItemSerialSequenceFormProps) => {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = initialValues.id !== undefined;
+
+ const [prefix, setPrefix] = useState(initialValues.prefix ?? "");
+ const [suffix, setSuffix] = useState(initialValues.suffix ?? "");
+ const [next, setNext] = useState(initialValues.next ?? 0);
+ const [size, setSize] = useState(initialValues.size ?? 5);
+ const [step, setStep] = useState(initialValues.step ?? 1);
+
+ const makePreview = () => {
+ // %{location} is resolved at issue time from the item's location; for the
+ // preview we stand in a sample location code ("HQ") so the token doesn't
+ // show through literally.
+ const p = interpolateSequenceDate(prefix).replace(/%{location}/g, "HQ");
+ const s = interpolateSequenceDate(suffix).replace(/%{location}/g, "HQ");
+ // Preview the NEXT number that will be issued (current counter + step),
+ // not the current counter itself — so a fresh sequence shows "00001".
+ return `${p}${(next + step).toString().padStart(size, "0")}${s}`;
+ };
+
+ const isDisabled = isEditing
+ ? !permissions.can("update", "settings")
+ : !permissions.can("create", "settings");
+
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent>
+ <ValidatedForm
+ validator={itemSerialSequenceValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.serialNumberSequence(initialValues.id!)
+ : path.to.newSerialNumberSequence
+ }
+ defaultValues={initialValues}
+ className="flex flex-col h-full"
+ >
+ <DrawerHeader>
+ <DrawerTitle>
+ {isEditing ? t`Edit Serial Number` : t`New Serial Number`}
+ </DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ <Hidden name="id" />
+ <VStack spacing={4}>
+ <Heading size="h2">{makePreview()}</Heading>
+
+ {isEditing ? (
+ <Item name="itemId" label={t`Item`} type="Item" isReadOnly />
+ ) : (
+ <Item
+ name="itemId"
+ label={t`Item`}
+ type="Item"
+ blacklist={configuredItemIds}
+ helperText={t`Serial numbers are only generated for serial- or batch-tracked items.`}
+ />
+ )}
+
+ <Input
+ name="prefix"
+ label={t`Prefix`}
+ onChange={(e) => setPrefix(e.target.value)}
+ />
+ <Number
+ name="next"
+ minValue={0}
+ label={t`Current`}
+ onChange={setNext}
+ />
+ <Number
+ name="size"
+ minValue={1}
+ maxValue={20}
+ label={t`Size`}
+ onChange={setSize}
+ />
+ <Number
+ name="step"
+ minValue={1}
+ maxValue={10000}
+ label={t`Step`}
+ onChange={setStep}
+ />
+ <Input
+ name="suffix"
+ label={t`Suffix`}
+ onChange={(e) => setSuffix(e.target.value)}
+ />
+ <VStack spacing={0}>
+ <p className="text-muted-foreground text-sm">{`%{yyyy} = Full Year`}</p>
+ <p className="text-muted-foreground text-sm">{`%{yy} = Year`}</p>
+ <p className="text-muted-foreground text-sm">{`%{mm} = Month`}</p>
+ <p className="text-muted-foreground text-sm">{`%{ww} = Week`}</p>
+ <p className="text-muted-foreground text-sm">{`%{dd} = Day`}</p>
+ <p className="text-muted-foreground text-sm">{`%{location} = Location code`}</p>
+ </VStack>
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>
+ <Trans>Save</Trans>
+ </Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </ValidatedForm>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default ItemSerialSequenceForm;
diff --git a/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsx b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsx
new file mode 100644
index 0000000000..50a9ecf27f
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsx
@@ -0,0 +1,161 @@
+import { MenuIcon, MenuItem } from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import {
+ LuArrowRight,
+ LuHash,
+ LuMaximize,
+ LuPackage,
+ LuPencil,
+ LuStepForward,
+ LuText,
+ LuTextCursor,
+ LuTrash
+} from "react-icons/lu";
+import { useNavigate } from "react-router";
+import { Hyperlink, New, Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { ItemSerialSequence } from "~/modules/settings";
+import { useItems } from "~/stores/items";
+import { path } from "~/utils/path";
+
+type ItemSerialSequencesTableProps = {
+ data: ItemSerialSequence[];
+ count: number;
+};
+
+const ItemSerialSequencesTable = memo(
+ ({ data, count }: ItemSerialSequencesTableProps) => {
+ const { t } = useLingui();
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [items] = useItems();
+
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
+ return [
+ {
+ accessorKey: "itemReadableId",
+ header: t`Item`,
+ cell: ({ row }) => (
+ <Hyperlink to={row.original.id ?? ""}>
+ {row.original.itemReadableId}
+ </Hyperlink>
+ ),
+ meta: {
+ icon: <LuPackage />,
+ filter: {
+ type: "static",
+ options: items?.map((item) => ({
+ value: item.readableIdWithRevision,
+ label: item.readableIdWithRevision
+ }))
+ }
+ }
+ },
+ {
+ accessorKey: "itemName",
+ header: t`Name`,
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuText />
+ }
+ },
+ {
+ accessorKey: "prefix",
+ header: t`Prefix`,
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuTextCursor />
+ }
+ },
+ {
+ accessorKey: "next",
+ header: t`Current`,
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuArrowRight />
+ }
+ },
+ {
+ accessorKey: "size",
+ header: t`Size`,
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuMaximize />
+ }
+ },
+ {
+ accessorKey: "step",
+ header: t`Step`,
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuStepForward />
+ }
+ },
+ {
+ accessorKey: "suffix",
+ header: t`Suffix`,
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuHash />
+ }
+ }
+ ];
+ }, [items, t]);
+
+ const renderContextMenu = useCallback(
+ (row: (typeof data)[number]) => {
+ return (
+ <>
+ <MenuItem
+ disabled={!permissions.can("update", "settings")}
+ onClick={() => {
+ navigate(
+ `${path.to.serialNumberSequence(row.id ?? "")}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ <Trans>Edit</Trans>
+ </MenuItem>
+ <MenuItem
+ disabled={!permissions.can("delete", "settings")}
+ onClick={() => {
+ navigate(
+ `${path.to.deleteSerialNumberSequence(row.id ?? "")}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ <Trans>Delete</Trans>
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<(typeof data)[number]>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={
+ permissions.can("create", "settings") && (
+ <New
+ label={t`Serial Number`}
+ to={path.to.newSerialNumberSequence}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title={t`Serial Numbers`}
+ />
+ );
+ }
+);
+
+ItemSerialSequencesTable.displayName = "ItemSerialSequencesTable";
+export default ItemSerialSequencesTable;
diff --git a/apps/erp/app/modules/settings/ui/SerialNumbers/index.ts b/apps/erp/app/modules/settings/ui/SerialNumbers/index.ts
new file mode 100644
index 0000000000..e8828ff3e7
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/SerialNumbers/index.ts
@@ -0,0 +1,4 @@
+import ItemSerialSequenceForm from "./ItemSerialSequenceForm";
+import ItemSerialSequencesTable from "./ItemSerialSequencesTable";
+
+export { ItemSerialSequenceForm, ItemSerialSequencesTable };
diff --git a/apps/erp/app/modules/settings/ui/index.ts b/apps/erp/app/modules/settings/ui/index.ts
index 09265660ca..85c179d1e5 100644
--- a/apps/erp/app/modules/settings/ui/index.ts
+++ b/apps/erp/app/modules/settings/ui/index.ts
@@ -10,5 +10,6 @@ export * from "./CustomFields";
export * from "./Integrations";
export * from "./Printing";
export * from "./Sequences";
+export * from "./SerialNumbers";
export * from "./Theme";
export { useSettingsSubmodules };
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index 9729a1a95b..e871e503d2 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -17,6 +17,7 @@ import {
LuLayoutDashboard,
LuNetwork,
LuPrinter,
+ LuScanBarcode,
LuSheet,
LuShoppingCart,
LuUsers,
@@ -191,6 +192,12 @@ export default function useSettingsSubmodules() {
role: "employee",
icon: <LuSheet />
},
+ {
+ name: t`Serial Numbers`,
+ to: path.to.serialNumberSequences,
+ role: "employee",
+ icon: <LuScanBarcode />
+ },
{
name: t`Webhooks`,
to: path.to.webhooks,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 5a13a05403..9914d472d7 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-07-31T05:48:08.334Z",
- "totalTools": 1405,
+ "generated": "2026-08-03T05:37:07.055Z",
+ "totalTools": 1410,
"modules": 15,
"tools": [
{
@@ -39502,6 +39502,168 @@
]
}
},
+ {
+ "name": "settings_getItemSerialSequences",
+ "module": "settings",
+ "classification": "READ",
+ "description": "get item serial sequences",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "args": {
+ "type": "object",
+ "properties": {
+ "limit": {
+ "type": "integer",
+ "default": 100
+ },
+ "offset": {
+ "type": "integer",
+ "default": 0
+ },
+ "search": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ }
+ }
+ }
+ }
+ },
+ {
+ "name": "settings_getItemSerialSequence",
+ "module": "settings",
+ "classification": "READ",
+ "description": "get item serial sequence",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "settings_getItemSerialSequenceByItemId",
+ "module": "settings",
+ "classification": "READ",
+ "description": "get item serial sequence by item id",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "itemId",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "itemId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "itemId"
+ ]
+ }
+ },
+ {
+ "name": "settings_upsertItemSerialSequence",
+ "module": "settings",
+ "classification": "WRITE",
+ "description": "upsert item serial sequence",
+ "paramCount": 7,
+ "serviceParams": [
+ "client",
+ "itemSerialSequence"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "itemId": {
+ "type": "string"
+ },
+ "prefix": {
+ "type": "string"
+ },
+ "suffix": {
+ "type": "string"
+ },
+ "next": {
+ "type": "number"
+ },
+ "step": {
+ "type": "number"
+ },
+ "size": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "itemId"
+ ]
+ }
+ },
+ {
+ "name": "settings_deleteItemSerialSequence",
+ "module": "settings",
+ "classification": "DESTRUCTIVE",
+ "description": "delete item serial sequence",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
{
"name": "settings_getSubsidiaries",
"module": "settings",
diff --git a/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx
index 8903004a54..ee9784924b 100644
--- a/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx
+++ b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx
@@ -96,6 +96,7 @@ export default function LocationRoute() {
const initialValues = {
id: location.id,
name: location.name,
+ code: location.code ?? undefined,
addressLine1: location.addressLine1 ?? undefined,
addressLine2: location.addressLine2 ?? undefined,
city: location.city ?? undefined,
diff --git a/apps/erp/app/routes/x+/settings+/serial-numbers.$id.tsx b/apps/erp/app/routes/x+/settings+/serial-numbers.$id.tsx
new file mode 100644
index 0000000000..3be498f970
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.$id.tsx
@@ -0,0 +1,99 @@
+import { assertIsPost, error, notFound, 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 type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data, redirect, useLoaderData } from "react-router";
+import {
+ getItemSerialSequence,
+ ItemSerialSequenceForm,
+ itemSerialSequenceValidator,
+ upsertItemSerialSequence
+} from "~/modules/settings";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee"
+ });
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const itemSerialSequence = await getItemSerialSequence(client, id, companyId);
+ if (itemSerialSequence.error) {
+ throw redirect(
+ path.to.serialNumberSequences,
+ await flash(
+ request,
+ error(itemSerialSequence.error, "Failed to get serial number")
+ )
+ );
+ }
+
+ return { itemSerialSequence: itemSerialSequence.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const validation = await validator(itemSerialSequenceValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id: _id, ...d } = validation.data;
+
+ const update = await upsertItemSerialSequence(client, {
+ id,
+ ...d,
+ companyId,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(update.error, "Failed to update serial number")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.serialNumberSequences,
+ await flash(request, success("Updated serial number"))
+ );
+}
+
+export default function EditSerialNumberRoute() {
+ const { itemSerialSequence } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: itemSerialSequence.id ?? undefined,
+ itemId: itemSerialSequence.itemId ?? "",
+ prefix: itemSerialSequence.prefix ?? "",
+ suffix: itemSerialSequence.suffix ?? "",
+ next: itemSerialSequence.next ?? 0,
+ size: itemSerialSequence.size ?? 5,
+ step: itemSerialSequence.step ?? 1
+ };
+
+ return (
+ <ItemSerialSequenceForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/serial-numbers.delete.$id.tsx b/apps/erp/app/routes/x+/settings+/serial-numbers.delete.$id.tsx
new file mode 100644
index 0000000000..d7517236ca
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.delete.$id.tsx
@@ -0,0 +1,83 @@
+import { error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { useLingui } from "@lingui/react/macro";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
+import { ConfirmDelete } from "~/components/Modals";
+import {
+ deleteItemSerialSequence,
+ getItemSerialSequence
+} from "~/modules/settings";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee"
+ });
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const itemSerialSequence = await getItemSerialSequence(client, id, companyId);
+ if (itemSerialSequence.error) {
+ throw redirect(
+ path.to.serialNumberSequences,
+ await flash(
+ request,
+ error(itemSerialSequence.error, "Failed to load serial number")
+ )
+ );
+ }
+
+ return { itemSerialSequence: itemSerialSequence.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ delete: "settings"
+ });
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const { error: deleteError } = await deleteItemSerialSequence(
+ client,
+ id,
+ companyId
+ );
+ if (deleteError) {
+ throw redirect(
+ `${path.to.serialNumberSequences}?${getParams(request)}`,
+ await flash(request, error(deleteError, "Failed to delete serial number"))
+ );
+ }
+
+ throw redirect(
+ `${path.to.serialNumberSequences}?${getParams(request)}`,
+ await flash(request, success("Deleted serial number"))
+ );
+}
+
+export default function DeleteSerialNumberRoute() {
+ const { itemSerialSequence } = useLoaderData<typeof loader>();
+
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const navigate = useNavigate();
+ const { t } = useLingui();
+ const onCancel = () => navigate(-1);
+
+ const itemLabel = itemSerialSequence.itemReadableId ?? t`this item`;
+
+ return (
+ <ConfirmDelete
+ action={path.to.deleteSerialNumberSequence(id)}
+ name={itemLabel}
+ text={t`Are you sure you want to delete the serial number sequence for ${itemLabel}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsx b/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsx
new file mode 100644
index 0000000000..f237ca29d1
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsx
@@ -0,0 +1,93 @@
+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 type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data, redirect, useLoaderData } from "react-router";
+import {
+ getItemSerialSequences,
+ ItemSerialSequenceForm,
+ itemSerialSequenceValidator,
+ upsertItemSerialSequence
+} from "~/modules/settings";
+import { path } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ create: "settings",
+ role: "employee"
+ });
+
+ // Items that already have a sequence can't get a second one.
+ const existing = await getItemSerialSequences(client, companyId, {
+ search: null,
+ limit: 1000,
+ offset: 0,
+ sorts: [],
+ filters: []
+ });
+
+ return {
+ configuredItemIds: (existing.data ?? [])
+ .map((s) => s.itemId)
+ .filter((id): id is string => id !== null)
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "settings"
+ });
+
+ const validation = await validator(itemSerialSequenceValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id: _id, ...d } = validation.data;
+
+ const create = await upsertItemSerialSequence(client, {
+ ...d,
+ companyId,
+ createdBy: userId
+ });
+
+ if (create.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(create.error, "Failed to create serial number")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.serialNumberSequences,
+ await flash(request, success("Created serial number"))
+ );
+}
+
+export default function NewSerialNumberRoute() {
+ const { configuredItemIds } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ itemId: "",
+ prefix: "",
+ suffix: "",
+ next: 0,
+ size: 5,
+ step: 1
+ };
+
+ return (
+ <ItemSerialSequenceForm
+ initialValues={initialValues}
+ configuredItemIds={configuredItemIds}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/serial-numbers.tsx b/apps/erp/app/routes/x+/settings+/serial-numbers.tsx
new file mode 100644
index 0000000000..10f30cc892
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.tsx
@@ -0,0 +1,49 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { VStack } from "@carbon/react";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, useLoaderData } from "react-router";
+import {
+ getItemSerialSequences,
+ ItemSerialSequencesTable
+} from "~/modules/settings";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: msg`Serial Numbers`,
+ to: path.to.serialNumberSequences
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ return await getItemSerialSequences(client, companyId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters
+ });
+}
+
+export default function SerialNumbersRoute() {
+ const { data, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <ItemSerialSequencesTable data={data ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/styles/tailwind.css b/apps/erp/app/styles/tailwind.css
index 775e375de9..c6e5e98a10 100644
--- a/apps/erp/app/styles/tailwind.css
+++ b/apps/erp/app/styles/tailwind.css
@@ -200,3 +200,16 @@ p.is-editor-empty:first-child:before {
.loading-dot:nth-child(3) {
animation-delay: 0.4s;
}
+
+@keyframes spinner-fade {
+ 0% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0.15;
+ }
+}
+
+.animate-spinner {
+ animation: spinner-fade 1.2s linear infinite;
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 5fd7b55164..830f575820 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -782,6 +782,8 @@ export const path = {
generatePath(`${x}/shared/views/delete/${id}`),
deleteScrapReason: (id: string) =>
generatePath(`${x}/production/scrap-reasons/delete/${id}`),
+ deleteSerialNumberSequence: (id: string) =>
+ generatePath(`${x}/settings/serial-numbers/delete/${id}`),
deleteShift: (id: string) =>
generatePath(`${x}/people/shifts/delete/${id}`),
deleteShipment: (id: string) => generatePath(`${x}/shipment/${id}/delete`),
@@ -1543,6 +1545,7 @@ export const path = {
newSalesRFQ: `${x}/sales-rfq/new`,
newSalesRFQLine: (id: string) => generatePath(`${x}/sales-rfq/${id}/new`),
newScrapReason: `${x}/production/scrap-reasons/new`,
+ newSerialNumberSequence: `${x}/settings/serial-numbers/new`,
newService: `${x}/service/new`,
newServiceSupplier: (id: string) =>
generatePath(`${x}/service/${id}/purchasing/new`),
@@ -1941,6 +1944,9 @@ export const path = {
sequences: `${x}/settings/sequences`,
serialNumber: (id: string) =>
generatePath(`${x}/inventory/serial-numbers/${id}`),
+ serialNumberSequence: (id: string) =>
+ generatePath(`${x}/settings/serial-numbers/${id}`),
+ serialNumberSequences: `${x}/settings/serial-numbers`,
serialNumbers: `${x}/inventory/serial-numbers`,
service: (id: string) => generatePath(`${x}/service/${id}`),
serviceCosting: (id: string) => generatePath(`${x}/service/${id}/costing`),
diff --git a/apps/erp/app/utils/string.ts b/apps/erp/app/utils/string.ts
index 31bb477ba5..bad2ae80dd 100644
--- a/apps/erp/app/utils/string.ts
+++ b/apps/erp/app/utils/string.ts
@@ -52,6 +52,17 @@ export const copyToClipboard = async (
}
};
+// ISO 8601 week number (1-53). Week 1 is the week containing the year's first Thursday.
+export const getISOWeek = (date: Date): number => {
+ const d = new Date(
+ Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())
+ );
+ const dayNum = d.getUTCDay() || 7; // Sunday → 7
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum); // shift to the week's Thursday
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
+ return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
+};
+
// used to generate sequences
export const interpolateSequenceDate = (value: string | null) => {
// replace all instances of %{year} with the current year
@@ -65,10 +76,12 @@ export const interpolateSequenceDate = (value: string | null) => {
const day = date.getDate();
const hours = date.getHours();
const seconds = date.getSeconds();
+ const week = getISOWeek(date);
result = result.replace(/%{yyyy}/g, year.toString());
result = result.replace(/%{yy}/g, year.toString().slice(-2));
result = result.replace(/%{mm}/g, month.toString().padStart(2, "0"));
+ result = result.replace(/%{ww}/g, week.toString().padStart(2, "0"));
result = result.replace(/%{dd}/g, day.toString().padStart(2, "0"));
result = result.replace(/%{hh}/g, hours.toString().padStart(2, "0"));
result = result.replace(/%{ss}/g, seconds.toString().padStart(2, "0"));
diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsx
index 65794cb37a..7e01c3d828 100644
--- a/apps/mes/app/components/AssemblyView.tsx
+++ b/apps/mes/app/components/AssemblyView.tsx
@@ -98,6 +98,7 @@ import { ReworkModal } from "~/components/JobOperation/components/ReworkModal";
import { SerialSelectorModal } from "~/components/JobOperation/components/SerialSelectorModal";
import { RecordModal } from "~/components/JobOperation/components/Step";
import { useUser } from "~/hooks";
+import { isSerialEntityIncompleteForOperation } from "~/services/operations.service";
import type {
JobMaterial,
JobOperationStep,
@@ -270,6 +271,7 @@ type Props = {
id: string;
readableId?: string | null;
status?: string | null;
+ attributes?: unknown;
}[];
trackedEntityId: string | null;
materials: { materials?: any[]; trackedInputs?: any[] } | null;
@@ -287,6 +289,7 @@ type Props = {
ncrs: any[];
requiresSerialTracking: boolean;
requiresBatchTracking: boolean;
+ isFirstOperation: boolean;
openEvent: { id: string; startTime: string } | null;
events: ProductionEvent[];
nonConformanceActions: ContainmentAction[];
@@ -470,6 +473,21 @@ function SlidePins({
);
}
+// The view's `trackedEntities` prop is a hand-written subset of the DB row that widens
+// `status`/`attributes`, so bridge to the shared helper's Row-derived shape here rather
+// than duplicating the "done for this operation" rule.
+function isUnitIncompleteForOperation(
+ entity: { attributes?: unknown; status?: string | null },
+ operationId: string
+): boolean {
+ return isSerialEntityIncompleteForOperation(
+ entity as unknown as Parameters<
+ typeof isSerialEntityIncompleteForOperation
+ >[0],
+ operationId
+ );
+}
+
export function AssemblyView({
operationId,
job,
@@ -483,6 +501,7 @@ export function AssemblyView({
ncrs,
requiresSerialTracking,
requiresBatchTracking,
+ isFirstOperation,
openEvent,
events,
nonConformanceActions,
@@ -519,7 +538,10 @@ export function AssemblyView({
const completeAllFetcher = useFetcher<{ success?: boolean }>();
// Silent auto-completion of a single unit once its final step is recorded
// (multi-quantity assembly builds one at a time — see the effect below).
- const completeUnitFetcher = useFetcher<{ id?: string }>();
+ const completeUnitFetcher = useFetcher<{
+ id?: string;
+ completed?: boolean;
+ }>();
// Lazily creates NCR containment inspection steps for this operation (see effect below).
const inspectionStepsFetcher = useFetcher();
const imageViewer = useDisclosure();
@@ -1167,8 +1189,14 @@ export function AssemblyView({
if (!isMultiQuantity || unitsRemaining <= 0) return;
// Only auto-complete the unit currently being built. Guards against
// re-completing an already-finished unit whose step records still read
- // "done" if the operator navigates back to it.
- if (currentUnitIndex < quantityComplete) return;
+ // "done" if the operator navigates back to it. Serial parents may be worked
+ // in any order (scan/select on later ops), so "already built" is per-entity
+ // (its completion marker); batch/untracked build strictly in order by index.
+ const currentAlreadyBuilt =
+ navigatesByEntity && currentEntity
+ ? !isUnitIncompleteForOperation(currentEntity, operationId)
+ : currentUnitIndex < quantityComplete;
+ if (currentAlreadyBuilt) return;
if (!allStepsRecorded) {
// On a not-yet-finished unit — arm for its eventual completion.
autoCompleteSubmittedRef.current = false;
@@ -1223,6 +1251,7 @@ export function AssemblyView({
// auto-complete effect only re-fires when its deps actually change, and a
// failed completion leaves quantityComplete (hence unitsRemaining) unchanged.
const prevCompleteUnitStateRef = useRef(completeUnitFetcher.state);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: settle-detect on the fetcher
useEffect(() => {
const settled =
prevCompleteUnitStateRef.current !== "idle" &&
@@ -1235,9 +1264,51 @@ export function AssemblyView({
!Array.isArray(result) &&
typeof result === "object" &&
Object.keys(result).length === 0;
- if (failed) autoCompleteSubmittedRef.current = false;
+ if (failed) {
+ autoCompleteSubmittedRef.current = false;
+ return;
+ }
+ // A serial unit just completed (complete.tsx returns { completed: true } and no
+ // longer redirects to a next unit — the client is the single advancement
+ // authority). Advance to the next unit still to build: on the first operation
+ // auto-select it (no printed labels to scan yet); on later operations prompt the
+ // operator to scan/select (every unit already carries a label). The final unit
+ // finishes the operation server-side and redirects, so `result` is undefined
+ // there and nothing happens.
+ if (navigatesByEntity && result?.completed) {
+ // Search the capped unit axis (unitEntities), not the raw prop: a job can
+ // pre-generate more serials than the operation quantity, and navigating to
+ // one of those would fall outside currentUnitIndex / the maxNavigableUnitIndex
+ // clamp and desync the URL from the rendered unit.
+ const next = unitEntities.find((entity) =>
+ isUnitIncompleteForOperation(entity, operationId)
+ );
+ if (!next) return;
+ if (isFirstOperation) navigateEntity(next);
+ else serialModal.onOpen();
+ }
}, [completeUnitFetcher.state, completeUnitFetcher.data]);
+ // Later operations: prompt the operator to scan/select the unit on arrival. Every
+ // unit already carries a printed label (labels print at the first operation's
+ // completion), so there is nothing to auto-select. Prompt once per mount — even if
+ // the loader seeded a ?trackedEntityId — and only while units remain to build. The
+ // first operation auto-selects instead (loader default + the settle effect above).
+ const arrivalPromptedRef = useRef(false);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: one-shot arrival prompt
+ useEffect(() => {
+ if (!navigatesByEntity || isFirstOperation) return;
+ if (arrivalPromptedRef.current) return;
+ // Cap to the unit axis (see the settle effect): don't prompt for serials the
+ // job pre-generated beyond the operation quantity.
+ const hasIncomplete = unitEntities.some((entity) =>
+ isUnitIncompleteForOperation(entity, operationId)
+ );
+ if (!hasIncomplete) return;
+ arrivalPromptedRef.current = true;
+ serialModal.onOpen();
+ }, [navigatesByEntity, isFirstOperation, trackedEntities, operationId]);
+
// Return to step 1 on a new unit. Whenever the active unit changes — the
// auto-complete rolls quantityComplete forward (untracked), a serial/batch
// completion redirects to a fresh entity, or the operator pages units by hand —
@@ -1524,13 +1595,27 @@ export function AssemblyView({
</p>
)}
{!isMultiQuantity && currentEntity ? (
- <div className="mt-1.5 flex items-center gap-1.5">
- <Badge variant="secondary" className="font-mono text-[10px]">
+ <div className="mt-1.5 flex items-center gap-1.5 min-w-0">
+ <Badge
+ variant="secondary"
+ className="font-mono text-[10px] shrink-0"
+ >
{requiresBatchTracking ? "Batch" : "S/N"}
</Badge>
- <span className="truncate font-mono text-[10px] text-muted-foreground">
- {currentEntity.readableId ?? currentEntity.id.slice(0, 8)}
- </span>
+ {currentEntity.readableId ? (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate text-[10px] font-medium">
+ {currentEntity.readableId}
+ </span>
+ <span className="truncate font-mono text-[10px] text-muted-foreground">
+ {currentEntity.id.slice(0, 8)}
+ </span>
+ </span>
+ ) : (
+ <span className="truncate font-mono text-[10px] text-muted-foreground">
+ {currentEntity.id.slice(0, 8)}
+ </span>
+ )}
</div>
) : null}
</div>
@@ -2269,7 +2354,11 @@ export function AssemblyView({
{serialModal.isOpen && (
<SerialSelectorModal
- availableEntities={unitEntities as never}
+ availableEntities={
+ unitEntities.filter((entity) =>
+ isUnitIncompleteForOperation(entity, operationId)
+ ) as never
+ }
onClose={serialModal.onClose}
onCancel={serialModal.onClose}
onSelect={(entity) => {
@@ -2936,11 +3025,12 @@ function StepCompleteAction({
// Units section for the left sidebar — its own labeled section (like Time), sitting
// directly below the timers. A compact prev/next pager sits top-right by the label,
// and the full, scrollable list of EVERY unit gives full visibility. A serial parent
-// binds a distinct entity per unit, so it lists those by readableId; a batch parent
-// binds a single lot to unit 0 (the rest are null), so listing that one id is more
-// noise than signal — batch and untracked parents both list "Unit 1 / Unit 2 / …".
-// The list auto-scrolls to keep the current unit in view; units with an out-of-spec
-// measurement (or a failed inspection) are flagged red, fully-recorded units green.
+// binds a distinct entity per unit, so it lists those by readableId (with muted
+// entity id when both exist); a batch parent binds a single lot to unit 0 (the rest
+// are null), so listing that one id is more noise than signal — batch and untracked
+// parents both list "Unit 1 / Unit 2 / …". The list auto-scrolls to keep the current
+// unit in view; units with an out-of-spec measurement (or a failed inspection) are
+// flagged red, fully-recorded units green.
function UnitNavigator({
units,
currentUnitIndex,
@@ -2975,10 +3065,6 @@ function UnitNavigator({
labelByEntity && !!u.entity;
const isNavigable = (u: (typeof units)[number]) =>
u.index <= maxNavigableIndex;
- const labelFor = (u: (typeof units)[number]) =>
- labelByEntity && u.entity
- ? (u.entity.readableId ?? u.entity.id.slice(0, 8))
- : `Unit ${u.index + 1}`;
// Keep the selected unit visible as the operator pages/jumps between units.
// currentUnitIndex is a real dep: the ref points at a different row after it
@@ -3057,9 +3143,24 @@ function UnitNavigator({
: "bg-transparent"
)}
/>
- <span className={cn("truncate", isEntityLabel(u) && "font-mono")}>
- {labelFor(u)}
- </span>
+ {isEntityLabel(u) && u.entity ? (
+ u.entity.readableId ? (
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate font-medium">
+ {u.entity.readableId}
+ </span>
+ <span className="truncate font-mono text-[10px] text-muted-foreground">
+ {u.entity.id.slice(0, 8)}
+ </span>
+ </span>
+ ) : (
+ <span className="truncate font-mono">
+ {u.entity.id.slice(0, 8)}
+ </span>
+ )
+ ) : (
+ <span className="truncate">{`Unit ${u.index + 1}`}</span>
+ )}
</button>
);
})}
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 9f7a37f8cf..b19e3595b3 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -174,6 +174,7 @@ type JobOperationProps = {
job: Job;
thumbnailPath: string | null;
trackedEntities: TrackedEntity[];
+ isFirstOperation: boolean;
workCenter: Promise<
PostgrestSingleResponse<{
name: string;
@@ -227,6 +228,7 @@ export const JobOperation = ({
procedure,
thumbnailPath,
trackedEntities,
+ isFirstOperation,
workCenter
}: JobOperationProps) => {
const { t } = useLingui();
@@ -296,8 +298,15 @@ export const JobOperation = ({
operation: originalOperation,
events,
trackedEntities,
+ isFirstOperation,
pauseInterval: isModalOpen,
- procedure
+ procedure,
+ // First operation only (no labels to scan yet): auto-select the next unit.
+ // `activeStep` follows `trackedEntityId` via the sync effect above, so setting
+ // the URL param is all that's needed.
+ onAdvanceToUnit: (entity) => {
+ setParams({ trackedEntityId: entity.id });
+ }
});
const controlsHeight = useMemo(() => {
@@ -1728,11 +1737,26 @@ export const JobOperation = ({
>
<Td>
<div className="flex gap-2 items-center">
- <span>{entity.id}</span>
+ <div className="flex flex-col min-w-0">
+ {entity.readableId ? (
+ <>
+ <span className="font-medium truncate">
+ {entity.readableId}
+ </span>
+ <span className="text-xs text-muted-foreground font-mono truncate">
+ {entity.id}
+ </span>
+ </>
+ ) : (
+ <span className="font-mono truncate">
+ {entity.id}
+ </span>
+ )}
+ </div>
{entity.id === trackedEntityId && (
- <LuCheck className="text-emerald-500 size-4" />
+ <LuCheck className="text-emerald-500 size-4 shrink-0" />
)}
- <Copy text={entity.id} />
+ <Copy text={entity.readableId || entity.id} />
</div>
</Td>
diff --git a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
index 9e538a48d6..c367a69093 100644
--- a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
+++ b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
@@ -5,7 +5,6 @@ import {
useInterval,
useRealtimeChannel
} from "@carbon/react";
-import type { TrackedEntityAttributes } from "@carbon/utils";
import {
getLocalTimeZone,
now,
@@ -16,6 +15,7 @@ import type { RealtimeChannel } from "@supabase/supabase-js";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useParams, useRevalidator } from "react-router";
import { useUrlParams, useUser } from "~/hooks";
+import { isSerialEntityIncompleteForOperation } from "~/services/operations.service";
import type {
JobMaterial,
JobOperationParameter,
@@ -30,17 +30,25 @@ export function useOperation({
operation,
events,
trackedEntities,
+ isFirstOperation,
pauseInterval,
- procedure
+ procedure,
+ onAdvanceToUnit
}: {
operation: OperationWithDetails;
events: ProductionEvent[];
trackedEntities: TrackedEntity[];
+ // The first operation in the routing has no printed labels yet, so units are
+ // auto-selected; later operations require the operator to scan/select.
+ isFirstOperation: boolean;
pauseInterval: boolean;
procedure: Promise<{
attributes: JobOperationStep[];
parameters: JobOperationParameter[];
}>;
+ // Auto-select the next serial unit (used on the first operation, where there
+ // are no printed labels to scan yet). Provided by JobOperation.
+ onAdvanceToUnit?: (entity: TrackedEntity) => void;
}) {
const [params] = useUrlParams();
const trackedEntityParam = params.get("trackedEntityId");
@@ -256,21 +264,47 @@ export function useOperation({
const [availableEntities, setAvailableEntities] = useState<TrackedEntity[]>(
[]
);
- // show the serial selector with the remaining serial numbers for the operation
+ // Later operations prompt scan/select once on arrival — even if a stale or
+ // auto-seeded ?trackedEntityId is already in the URL. This ref makes that a
+ // once-per-mount prompt so we don't re-open the picker while the operator is
+ // working a scanned unit.
+ const arrivalPromptedRef = useRef(false);
+ // Select / advance the serial unit the operator works on. This is the single
+ // advancement authority — complete.tsx no longer redirects to a next unit.
+ // - First operation: no labels have been printed yet, so there is nothing to
+ // scan — auto-select the next unit and flow through #1..#N.
+ // - Later operations: every unit already carries a printed label, so the
+ // operator scans/selects. Prompt once on arrival (even if a stale param sits
+ // in the URL) and again after each completion.
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
- if (trackedEntityParam) return;
- const uncompletedEntities = trackedEntities.filter(
- (entity) =>
- !(
- `Operation ${operationId}` in
- ((entity.attributes as TrackedEntityAttributes) ?? {})
- )
+ const uncompletedEntities = trackedEntities.filter((entity) =>
+ isSerialEntityIncompleteForOperation(entity, operationId ?? "")
);
- if (uncompletedEntities.length > 0) serialModal.onOpen();
setAvailableEntities(uncompletedEntities);
+ if (uncompletedEntities.length === 0) return;
+ const selectedIsIncomplete =
+ !!trackedEntityParam &&
+ uncompletedEntities.some((entity) => entity.id === trackedEntityParam);
+
+ if (isFirstOperation) {
+ // Auto-select the next unit once the selected one is done (or none yet).
+ if (!selectedIsIncomplete) onAdvanceToUnit?.(uncompletedEntities[0]);
+ return;
+ }
+
+ // Prompt scan/select once on arrival — even when a stale/auto-seeded
+ // ?trackedEntityId is present, which would otherwise read as "already working
+ // a unit". After that, only re-open once the selected unit is complete; stay
+ // quiet while the operator works a scanned, still-incomplete unit.
+ if (!arrivalPromptedRef.current) {
+ arrivalPromptedRef.current = true;
+ serialModal.onOpen();
+ return;
+ }
+ if (!selectedIsIncomplete) serialModal.onOpen();
// causes an infinite loop on navigation
- }, [trackedEntities, trackedEntityParam]);
+ }, [trackedEntities, trackedEntityParam, operationId, isFirstOperation]);
return {
active,
diff --git a/apps/mes/app/routes/x+/assembly.$operationId.tsx b/apps/mes/app/routes/x+/assembly.$operationId.tsx
index 1c4dafc771..ca6baf1575 100644
--- a/apps/mes/app/routes/x+/assembly.$operationId.tsx
+++ b/apps/mes/app/routes/x+/assembly.$operationId.tsx
@@ -192,7 +192,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
? navEntities[0]?.id
: navEntities[unitIndex]?.id;
- const [materials, openEvent] = await Promise.all([
+ const [materials, openEvent, priorDependency] = await Promise.all([
getJobMaterialsByOperationId(serviceRole, {
operation: op,
trackedEntityId: effectiveEntityId,
@@ -211,8 +211,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.is("endTime", null)
.order("startTime", { ascending: false })
.limit(1)
+ .maybeSingle(),
+ // Is this the first operation in the routing? A serial unit only earns a printed
+ // label when completed at its first operation, so the first op flows unit-by-unit
+ // (auto-select), and later ops scan/select (labels exist). "First" means nothing
+ // precedes it — no jobOperationDependency row keyed to this operation. `order` is
+ // only a display/sort field and isn't a reliable precedence signal.
+ serviceRole
+ .from("jobOperationDependency")
+ .select("operationId")
+ .eq("operationId", operationId)
+ .limit(1)
.maybeSingle()
]);
+ // Fail closed: a query error also returns null data, so treat an errored lookup
+ // as "not first" — later ops require scan/select, which is the safe default when
+ // we can't confirm the operation has no predecessor.
+ const isFirstOperation = !priorDependency.error && !priorDependency.data;
return {
job: job.data,
@@ -228,6 +243,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
ncrs: ncrs.data ?? [],
requiresSerialTracking: jobMakeMethod.data?.requiresSerialTracking ?? false,
requiresBatchTracking: jobMakeMethod.data?.requiresBatchTracking ?? false,
+ isFirstOperation,
openEvent: openEvent.data ?? null,
events: events.data ?? [],
nonConformanceActions,
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
index 797e79b635..d0d3e4a895 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -149,7 +149,6 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
- const trackedEntityId = newTrackedEntityId;
if (response.error) {
return data(
{},
@@ -186,15 +185,21 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- if (trackedEntityId) {
- return redirect(
- `${path.to.operation(
- validation.data.jobOperationId
- )}?trackedEntityId=${trackedEntityId}`
- );
- }
-
- return redirect(`${path.to.operation(validation.data.jobOperationId)}`);
+ // Not finished: complete this unit and let the client (useOperation for the
+ // operation view, AssemblyView for assembly ops) decide how to advance —
+ // auto-select the next unit on the first operation, or open the scan/select
+ // picker on later operations. Returning data (instead of redirecting to a
+ // specific next unit) keeps the just-completed unit in the URL and revalidates
+ // the loader, so the client is the single advancement authority and nothing
+ // races it. The `{ completed: true }` marker lets AssemblyView tell a
+ // successful completion apart from a failure (which returns an empty `{}`).
+ return data(
+ { completed: true },
+ await flash(request, {
+ ...success("Completed"),
+ flash: "success"
+ })
+ );
} else if (validation.data.trackingType === "Batch") {
const response = await serviceRole.functions.invoke("issue", {
body: {
diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsx
index 7740efd088..13ed89492f 100644
--- a/apps/mes/app/routes/x+/end.$operationId.tsx
+++ b/apps/mes/app/routes/x+/end.$operationId.tsx
@@ -10,8 +10,10 @@ import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
import {
finishJobOperation,
+ getNextIncompleteSerialEntity,
getTrackedEntitiesByMakeMethodId,
- insertProductionQuantity
+ insertProductionQuantity,
+ isSerialEntityIncompleteForOperation
} from "~/services/operations.service";
import { path } from "~/utils/path";
@@ -160,9 +162,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
jobOperation.data.jobMakeMethodId
);
- if (trackedEntities.data && trackedEntities.data.length > 0) {
- trackedEntityId =
- trackedEntities.data[trackedEntities.data.length - 1].id;
+ // Complete the next incomplete serial unit for this operation (createdAt
+ // asc), falling back to the last entity when every unit is complete.
+ const nextTrackedEntity = getNextIncompleteSerialEntity(
+ trackedEntities.data ?? [],
+ operationId
+ );
+ if (nextTrackedEntity) {
+ trackedEntityId = nextTrackedEntity.id;
}
}
@@ -215,6 +222,25 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
})
);
}
+
+ // Pre-split flow: the issue function did not spawn a new entity (all
+ // units already exist), so advance to the next incomplete serial unit
+ // for this operation. When none remain, fall through to the shared
+ // "operation complete" redirect below.
+ const remainingTrackedEntities = await getTrackedEntitiesByMakeMethodId(
+ serviceRole,
+ jobOperation.data.jobMakeMethodId
+ );
+ const nextTrackedEntity = (remainingTrackedEntities.data ?? []).find(
+ (entity) => isSerialEntityIncompleteForOperation(entity, operationId)
+ );
+ if (nextTrackedEntity) {
+ return redirect(
+ `${path.to.operation(
+ operationId
+ )}?trackedEntityId=${nextTrackedEntity.id}`
+ );
+ }
} else if (jobMakeMethod.data.requiresBatchTracking) {
const response = await serviceRole.functions.invoke("issue", {
body: {
diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsx
index 651733fdc7..c4cb8e5f61 100644
--- a/apps/mes/app/routes/x+/operation.$operationId.tsx
+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx
@@ -15,12 +15,14 @@ import {
getJobOperationById,
getJobOperationProcedure,
getKanbanByJobId,
+ getNextIncompleteSerialEntity,
getNonConformanceActions,
getProductionEventsForJobOperation,
getProductionQuantitiesForJobOperation,
getThumbnailPathByItemId,
getTrackedEntitiesByMakeMethodId,
- getWorkCenter
+ getWorkCenter,
+ isSerialEntityIncompleteForOperation
} from "~/services/operations.service";
import type { OperationWithDetails } from "~/services/types";
@@ -109,23 +111,46 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const autoSelectMaterialWithoutPickingList =
companySettings.data?.autoSelectMaterialWithoutPickingList ?? false;
- // If no trackedEntityId is provided in the URL but trackedEntities exist,
- // redirect to the same URL with the last trackedEntityId as a search param
+ // Is this the first operation in the routing? A serial unit only earns a
+ // printed label when it is completed at its first operation, so:
+ // - first operation: no labels exist yet → the operator flows unit-by-unit
+ // (auto-select here on arrival, and in the client after each completion);
+ // - later operations: every unit already has a label → the operator
+ // scans/selects each unit (no auto-select, here or in the client).
+ // An operation is "first" when nothing precedes it in the routing — i.e. it has
+ // no jobOperationDependency (a row means this op depends on / comes after
+ // another). `order` is only a display/sort field and isn't a reliable
+ // precedence signal, so it's not used here. A first op has no printed labels
+ // yet (they print on its completion), so its units are auto-selected; later
+ // ops already have labels, so the operator scans/selects.
+ const priorDependency = await serviceRole
+ .from("jobOperationDependency")
+ .select("operationId")
+ .eq("operationId", operationId)
+ .limit(1)
+ .maybeSingle();
+ // Fail closed: a query error also returns null data, so treat an errored lookup
+ // as "not first" — later ops require scan/select, which is the safe default when
+ // we can't confirm the operation has no predecessor.
+ const isFirstOperation = !priorDependency.error && !priorDependency.data;
+
+ // On the first operation only, auto-select the first incomplete unit when none
+ // is in the URL. Later operations leave it unset so the client presents the
+ // scan/select picker for every unit (including the first one picked up).
if (
!trackedEntityId &&
+ isFirstOperation &&
trackedEntities.data &&
- trackedEntities.data.length > 0 &&
- // Check if any tracked entity has an attribute for this operation
- !trackedEntities.data.every((entity) => {
- const attributes = entity.attributes as Record<string, unknown>;
- return Object.keys(attributes).some((key) => key.startsWith(`Operation`));
- })
+ trackedEntities.data.length > 0
) {
- const lastTrackedEntity =
- trackedEntities.data[trackedEntities.data.length - 1];
- const redirectUrl = new URL(request.url);
- redirectUrl.searchParams.set("trackedEntityId", lastTrackedEntity.id);
- throw redirect(`${redirectUrl.pathname}${redirectUrl.search}`);
+ const nextTrackedEntity = trackedEntities.data.find((entity) =>
+ isSerialEntityIncompleteForOperation(entity, operationId)
+ );
+ if (nextTrackedEntity) {
+ const redirectUrl = new URL(request.url);
+ redirectUrl.searchParams.set("trackedEntityId", nextTrackedEntity.id);
+ throw redirect(`${redirectUrl.pathname}${redirectUrl.search}`);
+ }
}
return {
@@ -150,11 +175,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
files: getJobFiles(serviceRole, companyId, job.data, operation.data),
materials: getJobMaterialsByOperationId(serviceRole, {
operation: operation.data?.[0],
- trackedEntityId: trackedEntityId ?? trackedEntities?.data?.[0]?.id,
+ trackedEntityId:
+ trackedEntityId ??
+ getNextIncompleteSerialEntity(trackedEntities.data ?? [], operationId)
+ ?.id,
requiresSerialTracking:
jobMakeMethod.data?.requiresSerialTracking ?? false
}),
trackedEntities: trackedEntities.data ?? [],
+ isFirstOperation,
nonConformanceActions: getNonConformanceActions(serviceRole, {
itemId: operation.data?.[0].itemId,
processId: operation.data?.[0].processId,
@@ -197,6 +226,7 @@ export default function OperationRoute() {
procedure,
thumbnailPath,
trackedEntities,
+ isFirstOperation,
workCenter,
nonConformanceActions
} = useLoaderData<typeof loader>();
@@ -214,6 +244,7 @@ export default function OperationRoute() {
materials={materials}
method={jobMakeMethod}
trackedEntities={trackedEntities}
+ isFirstOperation={isFirstOperation}
nonConformanceActions={nonConformanceActions}
operation={operation}
procedure={procedure}
diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsx
index 346d162830..7fee94623a 100644
--- a/apps/mes/app/routes/x+/start.$operationId.tsx
+++ b/apps/mes/app/routes/x+/start.$operationId.tsx
@@ -11,6 +11,7 @@ import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { getWorkCenterWithBlockingStatus } from "~/services/maintenance.service";
import {
+ getNextIncompleteSerialEntity,
getTrackedEntitiesByMakeMethodId,
startProductionEvent
} from "~/services/operations.service";
@@ -97,10 +98,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
jobOperation.data.jobMakeMethodId
);
- if (trackedEntities.data && trackedEntities.data.length > 0) {
- // Use the last tracked entity if available
- trackedEntityId =
- trackedEntities.data[trackedEntities.data.length - 1].id;
+ // Start the next incomplete serial unit for this operation (createdAt asc),
+ // falling back to the last entity when every unit is already complete.
+ const nextTrackedEntity = getNextIncompleteSerialEntity(
+ trackedEntities.data ?? [],
+ operationId
+ );
+ if (nextTrackedEntity) {
+ trackedEntityId = nextTrackedEntity.id;
}
}
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index c5a6e3d1a1..2022844f8e 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -1165,6 +1165,48 @@ export async function getTrackedEntitiesByMakeMethodId(
.order("createdAt", { ascending: true });
}
+type SerialEntityForSelection = Pick<
+ Database["public"]["Tables"]["trackedEntity"]["Row"],
+ "attributes" | "status"
+>;
+
+/**
+ * A serial tracked entity is still "incomplete" for a job operation when its
+ * attributes carry no `Operation ${jobOperationId}` completion marker and it has
+ * not been consumed. Shared by the serial auto-selection (routes) and the manual
+ * serial picker (`useOperation`) so both agree on "done for this operation".
+ */
+export function isSerialEntityIncompleteForOperation(
+ entity: SerialEntityForSelection,
+ jobOperationId: string
+): boolean {
+ const attributes = (entity.attributes ?? {}) as Record<string, unknown>;
+ return (
+ !(`Operation ${jobOperationId}` in attributes) &&
+ entity.status !== "Consumed"
+ );
+}
+
+/**
+ * The next serial unit an operator should work on for a job operation. Entities
+ * must be ordered by `createdAt` ascending (as `getTrackedEntitiesByMakeMethodId`
+ * returns them). Returns the first entity still incomplete for this operation;
+ * when every entity is already complete it falls back to the last entity, which
+ * preserves the prior end-state behavior. This unifies both the pre-split flow
+ * (all N `quantity=1` entities exist up front) and the old lazy-split flow (the
+ * `issue` edge function spawns the next entity on each completion).
+ */
+export function getNextIncompleteSerialEntity<
+ T extends SerialEntityForSelection
+>(entities: T[], jobOperationId: string): T | undefined {
+ if (entities.length === 0) return undefined;
+ return (
+ entities.find((entity) =>
+ isSerialEntityIncompleteForOperation(entity, jobOperationId)
+ ) ?? entities[entities.length - 1]
+ );
+}
+
export async function getTrackedEntity(
client: SupabaseClient<Database>,
id: string
diff --git a/apps/mes/app/styles/tailwind.css b/apps/mes/app/styles/tailwind.css
index c31ecad3bc..12a82e6509 100644
--- a/apps/mes/app/styles/tailwind.css
+++ b/apps/mes/app/styles/tailwind.css
@@ -137,3 +137,16 @@ p.is-editor-empty:first-child:before {
.mention {
@apply inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-400;
}
+
+@keyframes spinner-fade {
+ 0% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0.15;
+ }
+}
+
+.animate-spinner {
+ animation: spinner-fade 1.2s linear infinite;
+}
diff --git a/apps/starter/app/styles/tailwind.css b/apps/starter/app/styles/tailwind.css
index 3b70c89f30..b76f8664de 100644
--- a/apps/starter/app/styles/tailwind.css
+++ b/apps/starter/app/styles/tailwind.css
@@ -146,3 +146,16 @@ p.is-editor-empty:first-child:before {
.tiptap.ProseMirror-selectedNode div[data-video-embed] {
@apply ring-2 ring-primary cursor-move p-2 rounded-lg;
}
+
+@keyframes spinner-fade {
+ 0% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0.15;
+ }
+}
+
+.animate-spinner {
+ animation: spinner-fade 1.2s linear infinite;
+}
diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.ts
index f3fe488b0f..2b1d037fe7 100644
--- a/packages/database/src/seed-dev.ts
+++ b/packages/database/src/seed-dev.ts
@@ -508,8 +508,8 @@ async function seedDev() {
// Seed default location (required for inventory, jobs, etc.)
// Must be after accountDefaults since location trigger copies from accountDefaults
const locationResult = await client.query(
- `INSERT INTO location (name, "addressLine1", city, "stateProvince", "postalCode", "countryCode", timezone, "companyId", "createdBy")
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'system') RETURNING id`,
+ `INSERT INTO location (name, "code", "addressLine1", city, "stateProvince", "postalCode", "countryCode", timezone, "companyId", "createdBy")
+ VALUES ($1, 'HQ', $2, $3, $4, $5, $6, $7, $8, 'system') RETURNING id`,
[
defaultLocation.name,
defaultLocation.addressLine1,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 05a653b871..13c0f1b2ea 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -18477,6 +18477,93 @@ export default {
tags: ["jobs"]
}
},
+ "/itemSerialSequences": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.prefix"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.suffix"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.next"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.step"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.itemReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.itemName"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequences.itemTrackingType"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/itemSerialSequences"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["itemSerialSequences"]
+ }
+ },
"/department": {
get: {
parameters: [
@@ -22416,6 +22503,9 @@ export default {
{
$ref: "#/parameters/rowFilter.location.tags"
},
+ {
+ $ref: "#/parameters/rowFilter.location.code"
+ },
{
$ref: "#/parameters/select"
},
@@ -22529,6 +22619,9 @@ export default {
{
$ref: "#/parameters/rowFilter.location.tags"
},
+ {
+ $ref: "#/parameters/rowFilter.location.code"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -22596,6 +22689,9 @@ export default {
{
$ref: "#/parameters/rowFilter.location.tags"
},
+ {
+ $ref: "#/parameters/rowFilter.location.code"
+ },
{
$ref: "#/parameters/body.location"
},
@@ -62484,6 +62580,204 @@ export default {
tags: ["nonConformanceActionProcess"]
}
},
+ "/itemSerialSequence": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.prefix"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.suffix"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.next"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.step"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/itemSerialSequence"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["itemSerialSequence"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.itemSerialSequence"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["itemSerialSequence"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.prefix"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.suffix"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.next"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.step"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["itemSerialSequence"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.prefix"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.suffix"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.next"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.size"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.step"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.itemSerialSequence.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.itemSerialSequence"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["itemSerialSequence"]
+ }
+ },
"/batchProperty": {
get: {
parameters: [
@@ -100190,7 +100484,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -100239,7 +100533,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -103381,6 +103675,81 @@ export default {
},
type: "object"
},
+ itemSerialSequences: {
+ properties: {
+ id: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ prefix: {
+ format: "text",
+ type: "string"
+ },
+ suffix: {
+ format: "text",
+ type: "string"
+ },
+ next: {
+ format: "integer",
+ type: "integer"
+ },
+ size: {
+ format: "integer",
+ type: "integer"
+ },
+ step: {
+ format: "integer",
+ type: "integer"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ itemReadableId: {
+ format: "text",
+ type: "string"
+ },
+ itemName: {
+ format: "text",
+ type: "string"
+ },
+ itemTrackingType: {
+ enum: ["Inventory", "Non-Inventory", "Serial", "Batch"],
+ format: 'public."itemTrackingType"',
+ type: "string"
+ }
+ },
+ type: "object"
+ },
department: {
required: ["id", "name", "companyId", "createdBy", "createdAt"],
properties: {
@@ -105176,6 +105545,10 @@ export default {
type: "string"
},
type: "array"
+ },
+ code: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -124197,6 +124570,83 @@ export default {
},
type: "object"
},
+ itemSerialSequence: {
+ required: [
+ "id",
+ "companyId",
+ "itemId",
+ "next",
+ "size",
+ "step",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('iss'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ prefix: {
+ format: "text",
+ type: "string"
+ },
+ suffix: {
+ format: "text",
+ type: "string"
+ },
+ next: {
+ default: 0,
+ format: "integer",
+ type: "integer"
+ },
+ size: {
+ default: 5,
+ format: "integer",
+ type: "integer"
+ },
+ step: {
+ default: 1,
+ format: "integer",
+ type: "integer"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
batchProperty: {
required: [
"id",
@@ -144665,6 +145115,105 @@ export default {
in: "query",
type: "string"
},
+ "body.itemSerialSequences": {
+ name: "itemSerialSequences",
+ description: "itemSerialSequences",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/itemSerialSequences"
+ }
+ },
+ "rowFilter.itemSerialSequences.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.prefix": {
+ name: "prefix",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.suffix": {
+ name: "suffix",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.next": {
+ name: "next",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.size": {
+ name: "size",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.step": {
+ name: "step",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.itemReadableId": {
+ name: "itemReadableId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.itemName": {
+ name: "itemName",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequences.itemTrackingType": {
+ name: "itemTrackingType",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.department": {
name: "department",
description: "department",
@@ -146642,6 +147191,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.location.code": {
+ name: "code",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.kanbans": {
name: "kanbans",
description: "kanbans",
@@ -167811,6 +168366,87 @@ export default {
in: "query",
type: "string"
},
+ "body.itemSerialSequence": {
+ name: "itemSerialSequence",
+ description: "itemSerialSequence",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/itemSerialSequence"
+ }
+ },
+ "rowFilter.itemSerialSequence.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.prefix": {
+ name: "prefix",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.suffix": {
+ name: "suffix",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.next": {
+ name: "next",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.size": {
+ name: "size",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.step": {
+ name: "step",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.itemSerialSequence.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.batchProperty": {
name: "batchProperty",
description: "batchProperty",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index b9e42c5872..3b61af76da 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -20362,6 +20362,192 @@ export type Database = {
},
]
}
+ itemSerialSequence: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ itemId: string
+ next: number
+ prefix: string | null
+ size: number
+ step: number
+ suffix: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ itemId: string
+ next?: number
+ prefix?: string | null
+ size?: number
+ step?: number
+ suffix?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ itemId?: string
+ next?: number
+ prefix?: string | null
+ size?: number
+ step?: number
+ suffix?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
itemShelfLife: {
Row: {
calculateFromBom: boolean
@@ -24532,6 +24718,7 @@ export type Database = {
addressLine1: string
addressLine2: string | null
city: string
+ code: string | null
companyId: string
countryCode: string | null
createdAt: string
@@ -24552,6 +24739,7 @@ export type Database = {
addressLine1: string
addressLine2?: string | null
city: string
+ code?: string | null
companyId: string
countryCode?: string | null
createdAt?: string
@@ -24572,6 +24760,7 @@ export type Database = {
addressLine1?: string
addressLine2?: string | null
city?: string
+ code?: string | null
companyId?: string
countryCode?: string | null
createdAt?: string
@@ -61597,6 +61786,169 @@ export type Database = {
},
]
}
+ itemSerialSequences: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ id: string | null
+ itemId: string | null
+ itemName: string | null
+ itemReadableId: string | null
+ itemTrackingType:
+ | Database["public"]["Enums"]["itemTrackingType"]
+ | null
+ next: number | null
+ prefix: string | null
+ size: number | null
+ step: number | null
+ suffix: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
itemStockQuantities: {
Row: {
companyId: string | null
@@ -66418,14 +66770,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -69804,21 +70156,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index dc7edc3c39..03640fad1b 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -236,3 +236,8 @@ entrypoint = "./functions/embedding/index.ts"
# Specifies static files to be bundled with the function. Supports glob patterns.
# For example, if you want to serve static HTML pages in your function:
# static_files = [ "./functions/embedding/*.html" ]
+
+[functions.assign-serial-numbers]
+enabled = true
+verify_jwt = true
+entrypoint = "./functions/assign-serial-numbers/index.ts"
diff --git a/packages/database/supabase/functions/assign-serial-numbers/index.ts b/packages/database/supabase/functions/assign-serial-numbers/index.ts
new file mode 100644
index 0000000000..484b1e7894
--- /dev/null
+++ b/packages/database/supabase/functions/assign-serial-numbers/index.ts
@@ -0,0 +1,165 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { sql } from "kysely";
+import { z } from "npm:zod@^3.24.1";
+
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
+import { requirePermissions } from "../lib/supabase.ts";
+import { getNextSerialNumbers } from "../shared/get-next-serial-number.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+const payloadValidator = z.object({
+ jobId: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+});
+
+/**
+ * Assigns configured serial numbers to a job's tracked entities at creation time.
+ *
+ * Invoked (best-effort) from `insertJob` only when the job's item has an
+ * `itemSerialSequence`. For a Batch item it stamps one number on the single
+ * whole-quantity seed entity; for a Serial item it splits the seed into N
+ * quantity-1 entities and stamps one number on each. Numbers come from the
+ * item's sequence (atomic counter) with %{...} date/week/location tokens.
+ *
+ * Idempotent: it no-ops when the seed is already numbered or already split.
+ */
+serve(async (req: Request) => {
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
+
+ try {
+ const payload = await req.json();
+ const { jobId, companyId, userId } = payloadValidator.parse(payload);
+
+ // Auth gate (throws on denial). Service-role invocations from insertJob pass.
+ await requirePermissions(req, companyId, userId, { update: "production" });
+
+ const result = await db.transaction().execute(async (trx) => {
+ // 1. The job
+ const job = await trx
+ .selectFrom("job")
+ .select(["id", "itemId", "quantity", "locationId"])
+ .where("id", "=", jobId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!job) throw new Error(`Job ${jobId} not found`);
+
+ // 2. Only serial/batch tracked items carry serial numbers
+ const item = await trx
+ .selectFrom("item")
+ .select(["itemTrackingType"])
+ .where("id", "=", job.itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ const trackingType = item?.itemTrackingType;
+ if (trackingType !== "Serial" && trackingType !== "Batch") {
+ return { assigned: 0 };
+ }
+
+ // 3. The item's serial sequence (optional, at most one)
+ const sequence = await trx
+ .selectFrom("itemSerialSequence")
+ .select(["prefix", "suffix", "next", "size", "step"])
+ .where("itemId", "=", job.itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!sequence) return { assigned: 0 };
+
+ // 4. Location context for the %{location} token (code, falling back to name)
+ let locationCode: string | null = null;
+ let locationName: string | null = null;
+ if (job.locationId) {
+ const location = await trx
+ .selectFrom("location")
+ .select(["code", "name"])
+ .where("id", "=", job.locationId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ locationCode = location?.code ?? null;
+ locationName = location?.name ?? null;
+ }
+
+ // 5. The root make-method seed entity for this job. The job-insert
+ // interceptor tags it with the Job id; sub-assembly seeds also carry a
+ // Job Material id, and consumption remainders carry a Split Entity ID —
+ // exclude both so we only touch the root make method's seed.
+ const seeds = await trx
+ .selectFrom("trackedEntity")
+ .selectAll()
+ .where("companyId", "=", companyId)
+ .where(sql<boolean>`attributes->>'Job' = ${jobId}`)
+ .where(sql<boolean>`attributes->>'Job Material' IS NULL`)
+ .where(sql<boolean>`attributes->>'Split Entity ID' IS NULL`)
+ .orderBy("createdAt", "asc")
+ // Lock the seed row for the duration of the transaction so concurrent
+ // invocations for the same job serialize here: the second waits, then
+ // sees the readableId the first assigned and no-ops the idempotency guard
+ // below instead of reserving a duplicate range and inserting duplicates.
+ .forUpdate()
+ .execute();
+
+ // Idempotency: already split into many, or already numbered → do nothing.
+ if (seeds.length !== 1) return { assigned: 0 };
+ const seed = seeds[0];
+ if (seed.readableId) return { assigned: 0 };
+
+ // 6. How many numbers to reserve. Serial → one per unit; Batch → one.
+ const count =
+ trackingType === "Batch" ? 1 : Math.round(Number(job.quantity));
+ if (count < 1) return { assigned: 0 };
+
+ // 7. Atomically reserve + format the next `count` serial numbers.
+ const serials = await getNextSerialNumbers(trx, {
+ itemId: job.itemId,
+ companyId,
+ count,
+ locationCode,
+ locationName,
+ });
+ if (serials.length === 0) return { assigned: 0 };
+
+ // 8. Assign. Batch keeps the single whole-quantity seed; Serial splits it
+ // into `count` quantity-1 entities, one number each (seed becomes #1).
+ if (trackingType === "Batch") {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ readableId: serials[0] })
+ .where("id", "=", seed.id)
+ .execute();
+ } else {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ readableId: serials[0], quantity: 1 })
+ .where("id", "=", seed.id)
+ .execute();
+
+ if (count > 1) {
+ const rows = serials.slice(1).map((readableId) => ({
+ sourceDocument: seed.sourceDocument,
+ sourceDocumentId: seed.sourceDocumentId,
+ sourceDocumentReadableId: seed.sourceDocumentReadableId,
+ quantity: 1,
+ status: seed.status,
+ attributes: seed.attributes,
+ itemId: seed.itemId ?? null,
+ expirationDate: seed.expirationDate ?? null,
+ readableId,
+ companyId,
+ createdBy: seed.createdBy,
+ }));
+ await trx.insertInto("trackedEntity").values(rows).execute();
+ }
+ }
+
+ return { assigned: count };
+ });
+
+ return jsonResponse({ success: true, ...result });
+ } catch (err) {
+ return errorResponse(err);
+ }
+});
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 725b1979bd..639c721b1e 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -17,6 +17,7 @@ import { TrackedEntityAttributes, credit, debit, journalReference } from "../lib
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 {
getDefaultPostingGroup,
resolveInventoryAccount,
@@ -1280,6 +1281,47 @@ serve(async (req: Request) => {
trackedEntities.data.length <
(jobOperation.data.operationQuantity ?? 0)
) {
+ // Number this lazily-spawned unit from the item's serial sequence, if
+ // one is configured. This unit wasn't part of the initial pre-split at
+ // job creation (e.g. the job quantity was increased afterwards, or the
+ // sequence was configured later), so it would otherwise be created with
+ // a null readableId. Resolve the job's location for the %{location}
+ // token; the reservation runs in this transaction, atomic with the spawn.
+ let spawnReadableId: string | null = null;
+ if (trackedEntity.itemId) {
+ let locationCode: string | null = null;
+ let locationName: string | null = null;
+ const jobIdForLocation = (
+ trackedEntity.attributes as Record<string, unknown>
+ ).Job;
+ if (typeof jobIdForLocation === "string") {
+ const jobRow = await client
+ .from("job")
+ .select("locationId")
+ .eq("id", jobIdForLocation)
+ .eq("companyId", companyId)
+ .single();
+ if (jobRow.data?.locationId) {
+ const loc = await client
+ .from("location")
+ .select("code, name")
+ .eq("id", jobRow.data.locationId)
+ .eq("companyId", companyId)
+ .single();
+ locationCode = loc.data?.code ?? null;
+ locationName = loc.data?.name ?? null;
+ }
+ }
+ const spawnSerials = await getNextSerialNumbers(trx, {
+ itemId: trackedEntity.itemId,
+ companyId,
+ count: 1,
+ locationCode,
+ locationName,
+ });
+ spawnReadableId = spawnSerials[0] ?? null;
+ }
+
// Create a new trackedEntity with the same attributes but status = Reserved
const newTrackedEntityResult = await trx
.insertInto("trackedEntity")
@@ -1293,6 +1335,7 @@ serve(async (req: Request) => {
attributes: trackedEntity.attributes,
itemId: trackedEntity.itemId ?? null,
expirationDate: trackedEntity.expirationDate ?? null,
+ readableId: spawnReadableId,
companyId,
createdBy: userId,
})
diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.ts
index f88453a699..5c780397b5 100644
--- a/packages/database/supabase/functions/lib/seed.data.ts
+++ b/packages/database/supabase/functions/lib/seed.data.ts
@@ -955,6 +955,7 @@ export const periodCloseTaskDefinitions = [
*/
export const defaultLocation = {
name: "Headquarters",
+ code: "HQ",
addressLine1: "123 Main Street",
city: "Austin",
stateProvince: "TX",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index b9e42c5872..3b61af76da 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -20362,6 +20362,192 @@ export type Database = {
},
]
}
+ itemSerialSequence: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ itemId: string
+ next: number
+ prefix: string | null
+ size: number
+ step: number
+ suffix: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ itemId: string
+ next?: number
+ prefix?: string | null
+ size?: number
+ step?: number
+ suffix?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ itemId?: string
+ next?: number
+ prefix?: string | null
+ size?: number
+ step?: number
+ suffix?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
itemShelfLife: {
Row: {
calculateFromBom: boolean
@@ -24532,6 +24718,7 @@ export type Database = {
addressLine1: string
addressLine2: string | null
city: string
+ code: string | null
companyId: string
countryCode: string | null
createdAt: string
@@ -24552,6 +24739,7 @@ export type Database = {
addressLine1: string
addressLine2?: string | null
city: string
+ code?: string | null
companyId: string
countryCode?: string | null
createdAt?: string
@@ -24572,6 +24760,7 @@ export type Database = {
addressLine1?: string
addressLine2?: string | null
city?: string
+ code?: string | null
companyId?: string
countryCode?: string | null
createdAt?: string
@@ -61597,6 +61786,169 @@ export type Database = {
},
]
}
+ itemSerialSequences: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ id: string | null
+ itemId: string | null
+ itemName: string | null
+ itemReadableId: string | null
+ itemTrackingType:
+ | Database["public"]["Enums"]["itemTrackingType"]
+ | null
+ next: number | null
+ prefix: string | null
+ size: number | null
+ step: number | null
+ suffix: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemSerialSequence_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
itemStockQuantities: {
Row: {
companyId: string | null
@@ -66418,14 +66770,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -69804,21 +70156,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.ts
index 88d225c678..bb6ce9463f 100644
--- a/packages/database/supabase/functions/lib/utils.ts
+++ b/packages/database/supabase/functions/lib/utils.ts
@@ -16,6 +16,17 @@ export interface TrackedEntityAttributes {
Shelf?: string;
}
+// ISO 8601 week number (1-53). Week 1 is the week containing the year's first Thursday.
+export const getISOWeek = (date: Date): number => {
+ const d = new Date(
+ Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())
+ );
+ const dayNum = d.getUTCDay() || 7; // Sunday → 7
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum); // shift to the week's Thursday
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
+ return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
+};
+
// used to generate sequences
export const interpolateSequenceDate = (value?: string | null) => {
// replace all instances of %{year} with the current year
@@ -29,10 +40,12 @@ export const interpolateSequenceDate = (value?: string | null) => {
const day = date.getDate();
const hours = date.getHours();
const seconds = date.getSeconds();
+ const week = getISOWeek(date);
result = result.replace(/%{yyyy}/g, year.toString());
result = result.replace(/%{yy}/g, year.toString().slice(-2));
result = result.replace(/%{mm}/g, month.toString().padStart(2, "0"));
+ result = result.replace(/%{ww}/g, week.toString().padStart(2, "0"));
result = result.replace(/%{dd}/g, day.toString().padStart(2, "0"));
result = result.replace(/%{hh}/g, hours.toString().padStart(2, "0"));
result = result.replace(/%{ss}/g, seconds.toString().padStart(2, "0"));
@@ -41,6 +54,18 @@ export const interpolateSequenceDate = (value?: string | null) => {
return result;
};
+// Serial-number segment interpolation: the date/week tokens above, plus the
+// job-context %{location} token (location.code, falling back to location.name).
+export const interpolateSerialNumber = (
+ value: string | null | undefined,
+ context: { locationCode?: string | null; locationName?: string | null }
+) => {
+ const withDates = interpolateSequenceDate(value);
+ if (!withDates.includes("%{location}")) return withDates;
+ const location = (context.locationCode ?? context.locationName ?? "").trim();
+ return withDates.replace(/%{location}/g, location);
+};
+
export const getReadableIdWithRevision = (
readableId: string,
revision?: string | null
diff --git a/packages/database/supabase/functions/shared/get-next-serial-number.ts b/packages/database/supabase/functions/shared/get-next-serial-number.ts
new file mode 100644
index 0000000000..9849e18157
--- /dev/null
+++ b/packages/database/supabase/functions/shared/get-next-serial-number.ts
@@ -0,0 +1,63 @@
+import { sql, Transaction } from "kysely";
+import type { KyselyDatabase as DB } from "../lib/postgres/index.ts";
+import { interpolateSerialNumber } from "../lib/utils.ts";
+
+/**
+ * Atomically reserve and format the next `count` serial numbers for an item from
+ * its configured `itemSerialSequence`. Returns `[]` when the item has no sequence
+ * (so callers leave `readableId` null, exactly as before). Runs inside the
+ * caller's Kysely transaction, so the counter reservation commits — or rolls back
+ * — together with the write that consumes the numbers.
+ *
+ * Each number interpolates the date/week tokens (%{yyyy} %{yy} %{mm} %{ww} %{dd})
+ * plus %{location} (location.code, falling back to the location name).
+ *
+ * Used by both `assign-serial-numbers` (the N units that exist at job creation)
+ * and `issue` (a unit spawned lazily on completion, e.g. after the job quantity
+ * was increased), so serials follow the pattern regardless of when the entity is
+ * created.
+ */
+export async function getNextSerialNumbers(
+ trx: Transaction<DB>,
+ args: {
+ itemId: string;
+ companyId: string;
+ count: number;
+ locationCode?: string | null;
+ locationName?: string | null;
+ }
+): Promise<string[]> {
+ if (args.count < 1) return [];
+
+ const reserved = await trx
+ .updateTable("itemSerialSequence")
+ .set({
+ next: sql<number>`"next" + ${args.count} * "step"`,
+ updatedBy: "system",
+ updatedAt: new Date().toISOString(),
+ })
+ .where("itemId", "=", args.itemId)
+ .where("companyId", "=", args.companyId)
+ .returning(["next", "prefix", "suffix", "size", "step"])
+ .executeTakeFirst();
+
+ if (!reserved) return []; // item has no serial sequence configured
+
+ const size = reserved.size ?? 5;
+ const step = reserved.step ?? 1;
+ const startNext = reserved.next - args.count * step;
+ const context = {
+ locationCode: args.locationCode,
+ locationName: args.locationName,
+ };
+
+ const serials: string[] = [];
+ for (let i = 1; i <= args.count; i++) {
+ const value = startNext + i * step;
+ const counter = value.toString().padStart(size, "0");
+ const prefix = interpolateSerialNumber(reserved.prefix, context);
+ const suffix = interpolateSerialNumber(reserved.suffix, context);
+ serials.push(`${prefix}${counter}${suffix}`);
+ }
+ return serials;
+}
diff --git a/packages/database/supabase/migrations/20260802141530_location-code.sql b/packages/database/supabase/migrations/20260802141530_location-code.sql
new file mode 100644
index 0000000000..5ab9565268
--- /dev/null
+++ b/packages/database/supabase/migrations/20260802141530_location-code.sql
@@ -0,0 +1,9 @@
+-- Add a short abbreviation ("code") to locations, used as the [Site] segment of
+-- configurable serial numbers (falls back to the location name when null).
+-- Nullable; no view depends on SELECT * over "location" so no view recreate is needed.
+ALTER TABLE "location" ADD COLUMN IF NOT EXISTS "code" TEXT;
+
+-- Backfill the seeded default location. Idempotent: only fills a still-null code.
+UPDATE "location"
+SET "code" = 'HQ'
+WHERE "name" = 'Headquarters' AND "code" IS NULL;
diff --git a/packages/database/supabase/migrations/20260802141712_item-serial-sequence.sql b/packages/database/supabase/migrations/20260802141712_item-serial-sequence.sql
new file mode 100644
index 0000000000..075a80e895
--- /dev/null
+++ b/packages/database/supabase/migrations/20260802141712_item-serial-sequence.sql
@@ -0,0 +1,72 @@
+-- Per-item serial-number sequence: an optional, at-most-one configurable format +
+-- counter per item (mirrors the document "sequence" table, but keyed to an item).
+-- When a job is created for the item, the assign-serial-numbers edge function reserves
+-- the next N values and stamps them onto the job's tracked entities' readableId.
+--
+-- Format tokens (interpolated at generation time): %{yyyy} %{yy} %{mm} %{dd} %{ww}
+-- (ISO week) and %{location} (location.code, falling back to location.name).
+CREATE TABLE IF NOT EXISTS "itemSerialSequence" (
+ "id" TEXT NOT NULL DEFAULT id('iss'),
+ "companyId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+
+ "prefix" TEXT,
+ "suffix" TEXT,
+ "next" INTEGER NOT NULL DEFAULT 0,
+ "size" INTEGER NOT NULL DEFAULT 5,
+ "step" INTEGER NOT NULL DEFAULT 1,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "itemSerialSequence_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "itemSerialSequence_next_check" CHECK ("next" >= 0),
+ CONSTRAINT "itemSerialSequence_size_check" CHECK ("size" >= 1),
+ CONSTRAINT "itemSerialSequence_step_check" CHECK ("step" >= 1),
+ CONSTRAINT "itemSerialSequence_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "itemSerialSequence_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ -- One serial sequence per item (the "can't add two for the same item" rule).
+ CONSTRAINT "itemSerialSequence_itemId_companyId_key" UNIQUE ("itemId", "companyId")
+);
+
+CREATE INDEX IF NOT EXISTS "itemSerialSequence_companyId_idx" ON "itemSerialSequence" ("companyId");
+CREATE INDEX IF NOT EXISTS "itemSerialSequence_itemId_idx" ON "itemSerialSequence" ("itemId");
+CREATE INDEX IF NOT EXISTS "itemSerialSequence_createdBy_idx" ON "itemSerialSequence" ("createdBy");
+
+ALTER TABLE "public"."itemSerialSequence" ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."itemSerialSequence";
+CREATE POLICY "SELECT" ON "public"."itemSerialSequence"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+
+DROP POLICY IF EXISTS "INSERT" ON "public"."itemSerialSequence";
+CREATE POLICY "INSERT" ON "public"."itemSerialSequence"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('settings_create'))::text[])
+);
+
+DROP POLICY IF EXISTS "UPDATE" ON "public"."itemSerialSequence";
+CREATE POLICY "UPDATE" ON "public"."itemSerialSequence"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('settings_update'))::text[])
+);
+
+DROP POLICY IF EXISTS "DELETE" ON "public"."itemSerialSequence";
+CREATE POLICY "DELETE" ON "public"."itemSerialSequence"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('settings_delete'))::text[])
+);
+
+-- List view: joins the item so the settings table can show/search the part.
+CREATE OR REPLACE VIEW "itemSerialSequences" WITH(SECURITY_INVOKER=true) AS
+SELECT
+ iss.*,
+ i."readableIdWithRevision" AS "itemReadableId",
+ i."name" AS "itemName",
+ i."itemTrackingType"
+FROM "itemSerialSequence" iss
+INNER JOIN "item" i ON i."id" = iss."itemId";
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 83bccf578b..b53c36051f 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -1394,6 +1394,9 @@ msgstr "Sind Sie sicher, dass Sie die Verkaufsauftragsposition für {0} {1} lös
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "Sind Sie sicher, dass Sie den Verschrottungsgrund: {0}? löschen möchten? Dies kann nicht rückgängig gemacht werden."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "Sind Sie sicher, dass Sie die Seriennummernfolge für {itemLabel} löschen möchten? Dies kann nicht rückgängig gemacht werden."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "Sind Sie sicher, dass Sie die Schicht: {name} von {locationName} löschen möchten? Dies kann nicht rückgängig gemacht werden."
@@ -4804,6 +4807,9 @@ msgstr "Geplante Wartung bearbeiten"
msgid "Edit Sequence"
msgstr "Sequenz bearbeiten"
+msgid "Edit Serial Number"
+msgstr "Seriennummer bearbeiten"
+
msgid "Edit Service"
msgstr "Dienstleistung bearbeiten"
@@ -8284,6 +8290,9 @@ msgstr "Neue Verkaufsauftragsposition"
msgid "New Scheduled Maintenance"
msgstr "Neue geplante Wartung"
+msgid "New Serial Number"
+msgstr "Neue Seriennummer"
+
msgid "New Service"
msgstr "Neue Dienstleistung"
@@ -11504,6 +11513,12 @@ msgstr "Seriennummer"
msgid "Serial Number:"
msgstr "Seriennummer:"
+msgid "Serial Numbers"
+msgstr "Seriennummern"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "Seriennummern werden nur für Artikel mit Serien- oder Chargenverfolgung generiert."
+
msgid "Serial or Batch Tracking Required"
msgstr "Serien- oder Chargenverfolgung erforderlich"
@@ -13359,6 +13374,9 @@ msgstr "Dies ist der Monat, in dem Ihr Geschäftsjahr beginnt."
msgid "This is the month your tax year starts."
msgstr "Dies ist der Monat, in dem Ihr Steuerjahr beginnt."
+msgid "this item"
+msgstr "diesen Artikel"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "Dieser Artikel wird über einen Konfigurator gebaut und löst seine Komponenten pro Bestellung auf; für ihn erstellte Aufträge erben die aufgelöste Stückliste des Konfigurators."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 122e4cf12d..e7aac4d8ac 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -1394,6 +1394,9 @@ msgstr "Are you sure you want to delete the sales order line for {0} {1}? This c
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
@@ -4804,6 +4807,9 @@ msgstr "Edit Scheduled Maintenance"
msgid "Edit Sequence"
msgstr "Edit Sequence"
+msgid "Edit Serial Number"
+msgstr "Edit Serial Number"
+
msgid "Edit Service"
msgstr "Edit Service"
@@ -8284,6 +8290,9 @@ msgstr "New Sales Order Line"
msgid "New Scheduled Maintenance"
msgstr "New Scheduled Maintenance"
+msgid "New Serial Number"
+msgstr "New Serial Number"
+
msgid "New Service"
msgstr "New Service"
@@ -11504,6 +11513,12 @@ msgstr "Serial Number"
msgid "Serial Number:"
msgstr "Serial Number:"
+msgid "Serial Numbers"
+msgstr "Serial Numbers"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "Serial numbers are only generated for serial- or batch-tracked items."
+
msgid "Serial or Batch Tracking Required"
msgstr "Serial or Batch Tracking Required"
@@ -13359,6 +13374,9 @@ msgstr "This is the month your fiscal year starts."
msgid "This is the month your tax year starts."
msgstr "This is the month your tax year starts."
+msgid "this item"
+msgstr "this item"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 51cfcc6fe5..97ccd06278 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -1394,6 +1394,9 @@ msgstr "¿Estás seguro de que deseas eliminar la línea de pedido de venta para
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "¿Estás seguro de que deseas eliminar la razón de rechazo: {0}? Esto no se puede deshacer."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "¿Está seguro de que desea eliminar la secuencia de número de serie de {itemLabel}? Esto no se puede deshacer."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "¿Estás seguro de que deseas eliminar el turno: {name} de {locationName}? Esto no se puede deshacer."
@@ -4804,6 +4807,9 @@ msgstr "Editar Mantenimiento Programado"
msgid "Edit Sequence"
msgstr "Editar Secuencia"
+msgid "Edit Serial Number"
+msgstr "Editar Número de Serie"
+
msgid "Edit Service"
msgstr "Editar servicio"
@@ -8284,6 +8290,9 @@ msgstr "Nueva Línea de Orden de Venta"
msgid "New Scheduled Maintenance"
msgstr "Nuevo Mantenimiento Programado"
+msgid "New Serial Number"
+msgstr "Nuevo Número de Serie"
+
msgid "New Service"
msgstr "Nuevo servicio"
@@ -11504,6 +11513,12 @@ msgstr "Número de Serie"
msgid "Serial Number:"
msgstr "Número de Serie:"
+msgid "Serial Numbers"
+msgstr "Números de Serie"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "Los números de serie se generan solo para artículos con seguimiento de serie o lote."
+
msgid "Serial or Batch Tracking Required"
msgstr "Seguimiento Serial o por Lote Requerido"
@@ -13359,6 +13374,9 @@ msgstr "Este es el mes en que comienza tu año fiscal."
msgid "This is the month your tax year starts."
msgstr "Este es el mes en que comienza tu año fiscal."
+msgid "this item"
+msgstr "este artículo"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "Este artículo se construye a través de un configurador y resuelve sus componentes por pedido; los trabajos creados para él heredan la BOM resuelta del configurador."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index c67fa0f36e..10ede00a0b 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -1394,6 +1394,9 @@ msgstr "Êtes-vous sûr de vouloir supprimer la ligne de commande client pour {0
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "Êtes-vous sûr de vouloir supprimer la raison de rebut : {0}? Cette action ne peut pas être annulée."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "Êtes-vous sûr de vouloir supprimer la séquence de numéro de série pour {itemLabel} ? Cette action ne peut pas être annulée."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "Êtes-vous sûr de vouloir supprimer le quart : {name} de {locationName} ? Cette action ne peut pas être annulée."
@@ -4804,6 +4807,9 @@ msgstr "Modifier la maintenance planifiée"
msgid "Edit Sequence"
msgstr "Modifier la séquence"
+msgid "Edit Serial Number"
+msgstr "Modifier le numéro de série"
+
msgid "Edit Service"
msgstr "Modifier le service"
@@ -8284,6 +8290,9 @@ msgstr "Nouvelle ligne de commande client"
msgid "New Scheduled Maintenance"
msgstr "Nouvelle Maintenance Planifiée"
+msgid "New Serial Number"
+msgstr "Nouveau numéro de série"
+
msgid "New Service"
msgstr "Nouveau service"
@@ -11504,6 +11513,12 @@ msgstr "Numéro de série"
msgid "Serial Number:"
msgstr "Numéro de série :"
+msgid "Serial Numbers"
+msgstr "Numéros de série"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "Les numéros de série ne sont générés que pour les articles suivis en série ou en lot."
+
msgid "Serial or Batch Tracking Required"
msgstr "Suivi en série ou par lot requis"
@@ -13359,6 +13374,9 @@ msgstr "C'est le mois où votre exercice fiscal commence."
msgid "This is the month your tax year starts."
msgstr "C'est le mois où votre année fiscale commence."
+msgid "this item"
+msgstr "cet article"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "Cet article est construit via un configurateur et résout ses composants par commande; les travaux créés pour lui héritent du BOM résolu du configurateur."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 95bfad512b..c31fcc43ab 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -1394,6 +1394,9 @@ msgstr "क्या आप सुनिश्चित हैं कि आप
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "क्या आप सुनिश्चित हैं कि आप स्क्रैप कारण को हटाना चाहते हैं: {0}? यह पूर्ववत नहीं किया जा सकता।"
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "क्या आप {itemLabel} के लिए सीरियल नंबर अनुक्रम को हटाना निश्चित हैं? इसे पूर्ववत नहीं किया जा सकता।"
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "क्या आप सुनिश्चित हैं कि आप शिफ्ट को हटाना चाहते हैं: {name} से {locationName}? यह पूर्ववत नहीं किया जा सकता।"
@@ -4804,6 +4807,9 @@ msgstr "निर्धारित रखरखाव संपादित क
msgid "Edit Sequence"
msgstr "अनुक्रम संपादित करें"
+msgid "Edit Serial Number"
+msgstr "सीरियल नंबर संपादित करें"
+
msgid "Edit Service"
msgstr "सेवा संपादित करें"
@@ -8284,6 +8290,9 @@ msgstr "नई बिक्रय आदेश पंक्ति"
msgid "New Scheduled Maintenance"
msgstr "नया निर्धारित रखरखाव"
+msgid "New Serial Number"
+msgstr "नया सीरियल नंबर"
+
msgid "New Service"
msgstr "नई सेवा"
@@ -11504,6 +11513,12 @@ msgstr "सीरियल नंबर"
msgid "Serial Number:"
msgstr "सीरियल नंबर:"
+msgid "Serial Numbers"
+msgstr "सीरियल नंबर"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "सीरियल नंबर केवल सीरियल या बैच-ट्रैक किए गए आइटम के लिए उत्पन्न होते हैं।"
+
msgid "Serial or Batch Tracking Required"
msgstr "सीरियल या बैच ट्रैकिंग आवश्यक है"
@@ -13359,6 +13374,9 @@ msgstr "यह वह महीना है जब आपका वित्त
msgid "This is the month your tax year starts."
msgstr "यह वह महीना है जब आपका कर वर्ष शुरू होता है।"
+msgid "this item"
+msgstr "यह आइटम"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "इस आइटम को एक कॉन्फ़िगरेटर के माध्यम से बनाया जाता है और प्रति-आदेश अपने घटकों को हल करता है; इसके लिए बनाई गई नौकरियां कॉन्फ़िगरेटर के हल बिल को विरासत में पाती हैं।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 3944d95aa7..0ecea10587 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -1394,6 +1394,9 @@ msgstr "Sei sicuro di voler eliminare la riga dell'ordine di vendita per {0} {1}
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "Sei sicuro di voler eliminare il motivo di scarto: {0}? Questa azione non può essere annullata."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "Sei sicuro di voler eliminare la sequenza del numero di serie per {itemLabel}? Questa azione non può essere annullata."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "Sei sicuro di voler eliminare il turno: {name} da {locationName}? Questa azione non può essere annullata."
@@ -4804,6 +4807,9 @@ msgstr "Modifica Manutenzione Programmata"
msgid "Edit Sequence"
msgstr "Modifica Sequenza"
+msgid "Edit Serial Number"
+msgstr "Modifica Numero di Serie"
+
msgid "Edit Service"
msgstr "Modifica Servizio"
@@ -8284,6 +8290,9 @@ msgstr "Nuova Riga Ordine Vendita"
msgid "New Scheduled Maintenance"
msgstr "Nuova Manutenzione Programmata"
+msgid "New Serial Number"
+msgstr "Nuovo Numero di Serie"
+
msgid "New Service"
msgstr "Nuovo Servizio"
@@ -11504,6 +11513,12 @@ msgstr "Numero di Serie"
msgid "Serial Number:"
msgstr "Numero di Serie:"
+msgid "Serial Numbers"
+msgstr "Numeri di Serie"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "I numeri di serie vengono generati solo per articoli tracciati in serie o per lotto."
+
msgid "Serial or Batch Tracking Required"
msgstr "Tracciamento Seriale o Batch Richiesto"
@@ -13359,6 +13374,9 @@ msgstr "Questo è il mese in cui inizia il tuo anno fiscale."
msgid "This is the month your tax year starts."
msgstr "Questo è il mese in cui inizia il tuo anno fiscale."
+msgid "this item"
+msgstr "questo articolo"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "Questo articolo viene costruito tramite un configuratore e risolve i suoi componenti per ordine; i lavori creati per esso ereditano il BOM risolto del configuratore."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 294e8ff701..976604a08c 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -1394,6 +1394,9 @@ msgstr "本当に販売注文行 {0} {1} を削除してもよろしいですか
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "スクラップ理由「{0}」を削除してもよろしいですか?この操作は取り消せません。"
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "{itemLabel} 用のシリアル番号シーケンスを削除してもよろしいですか?この操作は取り消すことができません。"
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "シフト「{name}」を{locationName}から削除してもよろしいですか?この操作は取り消せません。"
@@ -4804,6 +4807,9 @@ msgstr "スケジュール済みメンテナンスを編集"
msgid "Edit Sequence"
msgstr "シーケンスを編集"
+msgid "Edit Serial Number"
+msgstr "シリアル番号を編集"
+
msgid "Edit Service"
msgstr "サービスを編集"
@@ -8284,6 +8290,9 @@ msgstr "新しい販売注文行"
msgid "New Scheduled Maintenance"
msgstr "新しいスケジュール済みメンテナンス"
+msgid "New Serial Number"
+msgstr "新しいシリアル番号"
+
msgid "New Service"
msgstr "新規サービス"
@@ -11504,6 +11513,12 @@ msgstr "シリアル番号"
msgid "Serial Number:"
msgstr "シリアル番号:"
+msgid "Serial Numbers"
+msgstr "シリアル番号"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "シリアル番号は、シリアルまたはバッチ追跡アイテムに対してのみ生成されます。"
+
msgid "Serial or Batch Tracking Required"
msgstr "シリアルまたはバッチ追跡が必要です"
@@ -13359,6 +13374,9 @@ msgstr "これはあなたの会計年度が始まる月です。"
msgid "This is the month your tax year starts."
msgstr "これはあなたの税務年度が始まる月です。"
+msgid "this item"
+msgstr "このアイテム"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "このアイテムはコンフィグレータを使用して構築され、注文ごとにコンポーネントを解決します。このために作成されたジョブは、コンフィグレータの解決されたBOMを継承します。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 71ffc7c09c..ce558c2993 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -1394,6 +1394,9 @@ msgstr "{0} {1}의 판매주문 라인을 삭제하시겠습니까? 이 작업
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "스크랩 사유 {0}을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "{itemLabel}의 시리얼 번호 시퀀스를 삭제하시겠습니까? 이 작업은 실행 취소할 수 없습니다."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "{locationName}의 교대 {name}을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
@@ -4804,6 +4807,9 @@ msgstr "예정된 유지보수 수정"
msgid "Edit Sequence"
msgstr "순서 수정"
+msgid "Edit Serial Number"
+msgstr "시리얼 번호 편집"
+
msgid "Edit Service"
msgstr "서비스 편집"
@@ -8284,6 +8290,9 @@ msgstr "새 판매주문 라인"
msgid "New Scheduled Maintenance"
msgstr "새 예정된 유지보수"
+msgid "New Serial Number"
+msgstr "새 시리얼 번호"
+
msgid "New Service"
msgstr "새 서비스"
@@ -11504,6 +11513,12 @@ msgstr "일련번호"
msgid "Serial Number:"
msgstr "일련번호:"
+msgid "Serial Numbers"
+msgstr "시리얼 번호"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "시리얼 번호는 시리얼 또는 배치 추적 항목에만 생성됩니다."
+
msgid "Serial or Batch Tracking Required"
msgstr "일련번호 또는 배치 추적 필요"
@@ -13359,6 +13374,9 @@ msgstr "회계연도가 시작되는 월입니다."
msgid "This is the month your tax year starts."
msgstr "세무연도가 시작되는 월입니다."
+msgid "this item"
+msgstr "이 항목"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "이 품목은 컨피규레이터를 통해 제작되며 구성품을 주문별로 결정합니다. 이를 위해 생성된 작업은 컨피규레이터가 결정한 BOM을 상속받습니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 2d8c5b6299..0b907f2158 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -1394,6 +1394,9 @@ msgstr "Czy na pewno chcesz usunąć linię zamówienia sprzedaży dla {0} {1}?
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "Czy na pewno chcesz usunąć przyczynę braku: {0}? Tej czynności nie można cofnąć."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "Czy na pewno chcesz usunąć sekwencję numeru seryjnego dla {itemLabel}? Tej akcji nie można cofnąć."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "Czy na pewno chcesz usunąć zmianę: {name} z {locationName}? Tej czynności nie można cofnąć."
@@ -4804,6 +4807,9 @@ msgstr "Edytuj zaplanowaną konserwację"
msgid "Edit Sequence"
msgstr "Edytuj sekwencję"
+msgid "Edit Serial Number"
+msgstr "Edytuj numer seryjny"
+
msgid "Edit Service"
msgstr "Edytuj usługę"
@@ -8284,6 +8290,9 @@ msgstr "Nowa linia zamówienia sprzedaży"
msgid "New Scheduled Maintenance"
msgstr "Nowa zaplanowana konserwacja"
+msgid "New Serial Number"
+msgstr "Nowy numer seryjny"
+
msgid "New Service"
msgstr "Nowa usługa"
@@ -11504,6 +11513,12 @@ msgstr "Numer seryjny"
msgid "Serial Number:"
msgstr "Numer seryjny:"
+msgid "Serial Numbers"
+msgstr "Numery seryjne"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "Numery seryjne są generowane tylko dla elementów śledzonych numerem seryjnym lub partią."
+
msgid "Serial or Batch Tracking Required"
msgstr "Wymagane śledzenie seryjne lub partyjne"
@@ -13359,6 +13374,9 @@ msgstr "To jest miesiąc, w którym rozpoczyna się Twój rok obrachunkowy."
msgid "This is the month your tax year starts."
msgstr "To jest miesiąc, w którym rozpoczyna się Twój rok podatkowy."
+msgid "this item"
+msgstr "ten element"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "Ten artykuł jest zbudowany za pośrednictwem konfiguratora i rozwiązuje jego komponenty na zamówienie; zadania dla niego dziedziczą rozwiązaną BOM konfiguratora."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 5fa674569a..2dc921e55d 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -1394,6 +1394,9 @@ msgstr "Tem a certeza de que deseja eliminar a linha de encomenda de vendas para
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "Tem a certeza de que deseja eliminar o motivo de sucata: {0}? Isto não pode ser desfeito."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "Tem certeza de que deseja deletar a sequência de número de série para {itemLabel}? Isso não pode ser desfeito."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "Tem a certeza de que deseja eliminar o turno: {name} de {locationName}? Esta ação não pode ser desfeita."
@@ -4804,6 +4807,9 @@ msgstr "Editar Manutenção Agendada"
msgid "Edit Sequence"
msgstr "Editar Sequência"
+msgid "Edit Serial Number"
+msgstr "Editar Número de Série"
+
msgid "Edit Service"
msgstr "Editar Serviço"
@@ -8284,6 +8290,9 @@ msgstr "Nova Linha de Pedido de Venda"
msgid "New Scheduled Maintenance"
msgstr "Nova Manutenção Agendada"
+msgid "New Serial Number"
+msgstr "Novo Número de Série"
+
msgid "New Service"
msgstr "Novo Serviço"
@@ -11504,6 +11513,12 @@ msgstr "Número de Série"
msgid "Serial Number:"
msgstr "Número de Série:"
+msgid "Serial Numbers"
+msgstr "Números de Série"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "Números de série são gerados apenas para itens rastreados por série ou lote."
+
msgid "Serial or Batch Tracking Required"
msgstr "Rastreamento Serial ou em Lote Obrigatório"
@@ -13359,6 +13374,9 @@ msgstr "Este é o mês em que seu ano fiscal começa."
msgid "This is the month your tax year starts."
msgstr "Este é o mês em que seu ano fiscal começa."
+msgid "this item"
+msgstr "este item"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "Este item é construído por meio de um configurador e resolve seus componentes por pedido; os trabalhos criados para ele herdam a BOM resolvida do configurador."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index b597c99a1d..7ed746c2b3 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -1394,6 +1394,9 @@ msgstr "Вы уверены, что хотите удалить строку з
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "Вы уверены, что хотите удалить причину брака: {0}? Это действие невозможно отменить."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "Вы уверены, что хотите удалить последовательность серийных номеров для {itemLabel}? Это невозможно отменить."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "Вы уверены, что хотите удалить смену: {name} из {locationName}? Это действие невозможно отменить."
@@ -4804,6 +4807,9 @@ msgstr "Редактировать плановое обслуживание"
msgid "Edit Sequence"
msgstr "Редактировать последовательность"
+msgid "Edit Serial Number"
+msgstr "Редактировать серийный номер"
+
msgid "Edit Service"
msgstr "Редактировать услугу"
@@ -8284,6 +8290,9 @@ msgstr "Новая строка заказа продажи"
msgid "New Scheduled Maintenance"
msgstr "Новое плановое обслуживание"
+msgid "New Serial Number"
+msgstr "Новый серийный номер"
+
msgid "New Service"
msgstr "Новая услуга"
@@ -11504,6 +11513,12 @@ msgstr "Серийный номер"
msgid "Serial Number:"
msgstr "Серийный номер:"
+msgid "Serial Numbers"
+msgstr "Серийные номера"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "Серийные номера генерируются только для серийных или партионно отслеживаемых товаров."
+
msgid "Serial or Batch Tracking Required"
msgstr "Требуется отслеживание по серийному номеру или партии"
@@ -13359,6 +13374,9 @@ msgstr "Это месяц, когда начинается ваш финансо
msgid "This is the month your tax year starts."
msgstr "Это месяц, когда начинается ваш налоговый год."
+msgid "this item"
+msgstr "этот товар"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "Этот элемент строится через конфигуратор и разрешает его компоненты в зависимости от заказа; задания, созданные для него, наследуют разрешенный BOM конфигуратора."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 5ca57c1ee4..14ca347d8e 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -1394,6 +1394,9 @@ msgstr "Satır siparişi için {0} {1} satırını silmek istediğinizden emin m
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "Atık nedeni: {0}'ı silmek istediğinizden emin misiniz? Bu geri alınamaz."
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "Seri numarası dizisini {itemLabel} için silmek istediğinizden emin misiniz? Bu geri alınamaz."
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "Vardığınız vardiyayı silmek istediğinizden emin misiniz: {name} adlı vardiya, {locationName}'dan mı? Bu işlem geri alınamaz."
@@ -4804,6 +4807,9 @@ msgstr "Planlanmış Bakımı Düzenle"
msgid "Edit Sequence"
msgstr "Sıralamayı Düzenle"
+msgid "Edit Serial Number"
+msgstr "Seri Numarasını Düzenle"
+
msgid "Edit Service"
msgstr "Hizmeti Düzenle"
@@ -8284,6 +8290,9 @@ msgstr "Yeni Satış Siparişi Kalemi"
msgid "New Scheduled Maintenance"
msgstr "Yeni Planlanmış Bakım"
+msgid "New Serial Number"
+msgstr "Yeni Seri Numarası"
+
msgid "New Service"
msgstr "Yeni Hizmet"
@@ -11504,6 +11513,12 @@ msgstr "Seri Numarası"
msgid "Serial Number:"
msgstr "Seri Numarası:"
+msgid "Serial Numbers"
+msgstr "Seri Numaraları"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "Seri numaraları yalnızca seri- veya batch-izlenen öğeler için oluşturulur."
+
msgid "Serial or Batch Tracking Required"
msgstr "Seri veya Parti Takibi Gerekli"
@@ -13359,6 +13374,9 @@ msgstr "Bu, mali yılınızın başladığı aydır."
msgid "This is the month your tax year starts."
msgstr "Bu, vergi yılınızın başladığı aydır."
+msgid "this item"
+msgstr "bu öğe"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "Bu öğe bir configuratör aracılığıyla oluşturulmuş ve bileşenlerini siparişe göre çözer; bunun için oluşturulan işler configuratörün çözülmüş BOM'unu devralır."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 373acdc037..30fb71b1fd 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -1394,6 +1394,9 @@ msgstr "您确定要删除销售订单行 {0} {1} 吗?此操作无法撤销。
msgid "Are you sure you want to delete the scrap reason: {0}? This cannot be undone."
msgstr "您确定要删除废料原因:{0}?此操作无法撤销。"
+msgid "Are you sure you want to delete the serial number sequence for {itemLabel}? This cannot be undone."
+msgstr "你确定要删除 {itemLabel} 的序列号序列吗?这无法撤销。"
+
msgid "Are you sure you want to delete the shift: {name} from {locationName}? This cannot be undone."
msgstr "您确定要删除班次:{name} 从 {locationName}?此操作无法撤销。"
@@ -4804,6 +4807,9 @@ msgstr "编辑计划维护"
msgid "Edit Sequence"
msgstr "编辑序列"
+msgid "Edit Serial Number"
+msgstr "编辑序列号"
+
msgid "Edit Service"
msgstr "编辑服务"
@@ -8284,6 +8290,9 @@ msgstr "新销售订单行"
msgid "New Scheduled Maintenance"
msgstr "新的定期维护"
+msgid "New Serial Number"
+msgstr "新序列号"
+
msgid "New Service"
msgstr "新服务"
@@ -11504,6 +11513,12 @@ msgstr "序列号"
msgid "Serial Number:"
msgstr "序列号:"
+msgid "Serial Numbers"
+msgstr "序列号"
+
+msgid "Serial numbers are only generated for serial- or batch-tracked items."
+msgstr "序列号仅为序列号或批次跟踪的物料生成。"
+
msgid "Serial or Batch Tracking Required"
msgstr "序列号或批次跟踪必需"
@@ -13359,6 +13374,9 @@ msgstr "这是您的财政年度开始的月份。"
msgid "This is the month your tax year starts."
msgstr "这是您的税务年度开始的月份。"
+msgid "this item"
+msgstr "此物料"
+
msgid "This item is built via a configurator and resolves its components per-order; jobs created for it inherit the configurator's resolved BOM."
msgstr "该项目通过配置器构建,并按订单解析其组件;为其创建的工作继承配置器的解析BOM。"
diff --git a/packages/react/src/Spinner.tsx b/packages/react/src/Spinner.tsx
index 2e6c097c91..796022bab5 100644
--- a/packages/react/src/Spinner.tsx
+++ b/packages/react/src/Spinner.tsx
@@ -1,28 +1,33 @@
-import type { ComponentProps } from "react";
import { cn } from "./utils/cn";
-const Spinner = ({
- className,
- size = 24,
- ...props
-}: ComponentProps<"svg"> & { size?: number }) => {
+interface SpinnerProps {
+ /** Diameter of the spinner in pixels */
+ size?: number;
+ className?: string;
+}
+
+const BARS = Array.from({ length: 12 });
+
+export function Spinner({ size = 18, className }: SpinnerProps) {
return (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- width={size}
- height={size}
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- className={cn("animate-spin", className)}
- {...props}
+ <div
+ role="status"
+ aria-label="Loading"
+ className={cn("relative inline-block", className)}
+ style={{ width: size, height: size }}
>
- <path d="M21 12a9 9 0 1 1-6.219-8.56"></path>
- </svg>
+ {BARS.map((_, i) => (
+ <div
+ key={i}
+ className="absolute left-1/2 top-0 h-[24%] w-[8%] -translate-x-1/2 animate-spinner rounded-full bg-current"
+ style={{
+ transformOrigin: `center ${size / 2}px`,
+ transform: `rotate(${i * 30}deg)`,
+ animationDelay: `${-(11 - i) * (1 / 12)}s`
+ }}
+ />
+ ))}
+ <span className="sr-only">Loading</span>
+ </div>
);
-};
-
-export { Spinner };
+}