Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Merge remote-tracking branch 'origin/main' into feat/download-changenotice-and-approval-rule
aashu771f784af9cb
diff --cc .ai/lessons.mdindex c08f2426e9,c35c90cab6..cb2926539e--- a/.ai/lessons.md+++ b/.ai/lessons.md@@@ -3364,12 -3406,103 +3406,113 @@@ of `salesInvoice`; backfilled by `20261**Applies to:** `packages/react/src/utils/generatedAvatar.ts`; any isomorphic code that imports JSON from a dependency.+ ## A value two layers must agree on lives once, in the client-safe pure module++ **Context:** The accounting enable wizard (ERP) and the `activate-accounting` server function both decide whether Migration Clearing totals zero. The wizard uses the answer to offer "Enable accounting". The server function uses it to refuse the enable. The wizard steps also pass the cutover date to each other in a search param.++ **Problem:** Until 2026-10-09 each layer kept its own copy. `MigrationClearingTable.tsx` defined `MIGRATION_CLEARING_TOLERANCE = 0.01` and `isMigrationClearingZero`. `activate-accounting/index.ts` defined a second `MIGRATION_CLEARING_TOLERANCE`. `accounting.server.ts` defined `ACTIVATION_CUTOVER_PARAM`. The copies matched, but nothing kept them matched. If one copy changes, the wizard offers an enable that the server refuses, or hides one that the server accepts. Typecheck cannot see a drift between two literals.++ **Rule:** Put a value that two layers must agree on in one place: the client-safe pure module that both layers already import. Export the predicate, not only the number, so every caller compares the same way. The accounting cutover keeps `MIGRATION_CLEARING_TOLERANCE`, `isMigrationClearingZero`, `MIGRATION_CLEARING_ACCOUNT_CLASS` and `ACTIVATION_CUTOVER_PARAM` in `@carbon/database/accounting-cutover` (commits 38602af774, b9f897608c, f1fe2b6c81). That module reads no database, so the browser can import it.++ **Applies to:** `packages/database/src/accounting-cutover.ts`; `apps/erp/app/modules/accounting/ui/Activation/MigrationClearingTable.tsx`; `apps/erp/app/routes/x+/accounting+/activation.enable.tsx`; `packages/server-functions/src/activate-accounting/index.ts`; any check that a wizard previews and a server function enforces.++ ## A detector and the builder it feeds share one zero-value rule++ **Context:** The accounting enable, and the "Write missing journals" repair, find legacy documents: posted on or after the cutover with no journal (`packages/database/src/legacy-documents.ts`). A builder then writes each document's journal (`packages/server-functions/src/activate-accounting/legacy/`). After that, the enable's re-cost (`activate-accounting/recost.ts`) adjusts the inventory journal pair of each outbound movement whose cost changed.++ **Problem:** The detection and the builders used different zero rules, in both directions:++ 1. The detection found documents that the builders write no line for: a comment-only invoice, a receipt with no received line, a return received at no cost. Such a document got no journal, so every later run found it again.+ 2. The posting core wrote no journal for a zero-cost movement (`valueMovement` skipped the journal when `cost === 0`). When the re-cost gave that movement a cost, it found no pair to adjust and refused with a 409.++ Commit b9f897608c removed zero-value documents from the detection. Commits b9f897608c and 188a710e24 made every outbound cost row write its pair, at zero too.++ **Rule:** Write the zero rule once and apply it on both sides. If the builder writes no line for a document, the detection leaves the document out. If a later step adjusts a line, the builder writes that line even at zero. Pin the pair with a test that runs the detection, the builder, and the detection again: the second detection must find nothing (`activate-accounting/legacy/detection.test.ts`).++ **Applies to:** `packages/database/src/legacy-documents.ts`; `packages/server-functions/src/activate-accounting/legacy/*`; `packages/server-functions/src/activate-accounting/recost.ts`; `valueMovement` in `packages/server-functions/src/lib/post-adjustment.ts`; any detect-then-repair pair.++ ## A migration that re-scopes companies uses the company test of the migration it follows++ **Context:** `20261008211304_reset-accounting.sql` deletes the journals of every company except the demo-template companies. It finds those as the companies that hold a `JE-SEED-%` journal, which only tier 09 of the dataset seed writes. `20261009004448_accounting-cutover.sql` (section 7) then gives the spared companies a cutover, because their history is already in Carbon.++ **Problem:** The second migration first chose its companies by `accountingEnabled = true`. Only the dev CLI ever set that flag. A template applied through onboarding or Settings → Demo Data has it false. So those companies kept their Posted seed journals, but got no cutover. Their seeded Posted Opening Balance then blocked the enable wizard for good. Commit 38602af774 changed the test to the reset's `JE-SEED-%` test.++ **Rule:** If migration B acts on the companies that migration A chose, B copies A's predicate. Do not use a flag that "should" mean the same thing. Before you write the `WHERE`, read A's predicate. Then grep every writer of any flag you plan to use instead.++ **Applies to:** `packages/database/supabase/migrations/20261008211304_reset-accounting.sql`; `packages/database/supabase/migrations/20261009004448_accounting-cutover.sql`; any data migration that follows another data migration.++ ## Removing a feature flag can expose a fail-open `?.data` guard++ **Context:** Before always-posting, the return shipments in `post-shipment` and the sales return receipt in `post-receipt` read the account defaults only when `accountingEnabled` was true. Otherwise `accountDefaults` was null. The journal was written under `if (accountingEnabled && accountDefaults?.data && cost > 0)`. So `accountDefaults?.data` was part of the "accounting is off" test.++ **Problem:** The always-post change removed the flag and kept `if (accountDefaults.data && cost > 0)`. After that, the `.data` check only caught a failed read, and it failed open. If the defaults read failed, the post still wrote its stock and cost rows, but it skipped the journal with no error and no log. Typecheck and the tests passed. Commit b9f897608c makes both paths throw "Error getting account defaults" when the read fails.++ **Rule:** When you remove a flag, read every condition that used the flag. A null check that meant "feature off" becomes a silent error check when the flag goes. Turn a failed read into a throw before any write. Keep only business conditions, such as `cost > 0`, in the `if`.++ **Applies to:** `packages/server-functions/src/post-shipment/index.ts` (return shipments); `packages/server-functions/src/post-receipt/index.ts` (sales return receipt); any flag removal, such as `accountingEnabled` or a plan gate.++ ## The pre-commit Lingui extract reads the working tree, not the commit++ **Context:** `scripts/git-hooks/pre-commit` runs `pnpm lingui:check` when a staged file is TS, JS or `.po`. That script runs `lingui extract --clean` and then compiles. The hook then stages every `packages/locale/locales/**/*.po` file.++ **Problem:** The extract reads the working tree, not the index. On 2026-10-09, commit eac7595333 ran the hook while another session had uncommitted UI edits in the same tree (`PaymentApplyTable.tsx` and others). The extract removed strings that the committed code still uses ("Applied amount for {0}", "Discount for {0}"). It added strings that only the uncommitted code uses ("Apply to {0}", "FX Gain/Loss"). The hook staged all 13 catalogs, with those changes, into that commit. Commit 814631c22f restored catalogs extracted from HEAD in a clean worktree.++ **Rule:** Before you commit TS or JS, run `git status`. If it shows uncommitted `.ts` or `.tsx` edits that are not part of your commit, the hook's catalogs are wrong. A catalog-only commit in the same tree does not fix them, because the hook extracts again from the same dirty tree. Make the catalog commit in a clean tree:++ 1. Run `git worktree add -b i18n-catalogs <path> HEAD`.+ 2. In that worktree, run `pnpm install`.+ 3. In that worktree, run `pnpm lingui:check`, then `pnpm lingui:clean`.+ 4. Stage `packages/locale/locales/*/*.po` there and commit. The hook now extracts from a clean tree.+ 5. In your own tree, run `git merge --ff-only i18n-catalogs`. A fast-forward creates no commit, so no hook runs.+ 6. Remove the worktree and the branch.++ After any commit, check its `.po` diff. A removed `msgid` that HEAD code still uses means that the extract read a dirty tree.++ **Applies to:** `scripts/git-hooks/pre-commit`; `packages/locale/locales/*/*.po`; every workspace that more than one session edits at a time.++ ## One Inngest send carries at most 512 KB, and a rendered email is about 17 KB++ **Context:** `notify` rendered every recipient's notification email in one step, then sent all the `carbon/send-email` events with one `step.sendEvent` (2026-10-09).++ **Problem:** One rendered `NotificationEmail` is about 16.9 KB, because the event carries the full HTML. Inngest accepts at most 512 KB in one send and 4 MB in one step's output. So email to about 30 recipients or more could fail the send, and about 240 filled the step. A group notification reaches those sizes; a test with one recipient never does.++ **Rule:** Size a fan-out by its bytes, not its count. When each event carries a rendered body, render and send it in chunks (`EMAIL_CHUNK` in `notify.ts`), each chunk in its own step with an indexed id (`render-emails-${index}`). A new step id replays a run in flight at deploy, so a send step that changes id sends again for those runs.++ **Applies to:** `packages/jobs/src/inngest/functions/notifications/notify.ts`; any job that fans out events with large payloads.++ ## A failed COPY in a plain-text dump can swallow the rest of the restore++ **Context:** On 2026-10-09 a `crbn restore` of a prod cluster backup ended with ✅. The restored database had no index, constraint, trigger or policy in `public`, and an empty migration ledger. The trailing `migration up --include-all` would then have replayed all 1,159 migrations.++ **Problem:** The local stack's auth, storage and realtime tables come from its own service images, and they are older than prod's. Prod's `storage.objects` has a column (`archived_at`) that the local table does not have. A `COPY` that names an unknown column or table fails when psql parses it, so psql never enters copy mode. It then reads the block's data rows as SQL. In that data an unbalanced quote opened a string that never closed, so psql read the rest of the file as part of it. With `ON_ERROR_STOP=0`, nothing failed. The same drift also reaches DDL. The backup's newer `storage.protect_bucket_control_columns` trigger reads columns that the local `storage.buckets` does not have, so every bucket insert failed. Those service-schema objects survive later restores, because a restore drops only `public`. Separately, a Supabase backup is not one consistent snapshot: it contained payments whose journal it did not hold. So 15 foreign keys could not be validated.++ **Rule:** Do not trust a restore that ran with `ON_ERROR_STOP=0` until you verify it by name. `scripts/restore-database.sh` now does these things:++ 1. It fits each non-public `COPY` to the local columns, and drops the block when the local table does not exist.+ 2. It skips function definitions owned by the auth, storage and realtime admin roles. Those functions belong to the local service images.+ 3. It checks each `public` index, constraint, trigger and policy from the dump, and the ledger row count. It re-adds a foreign key that cannot be validated as `NOT VALID`.+ 4. It exits 1 on any shortfall, and `crbn restore` then does not migrate.++ A ✓ that a script prints after a step that is allowed to fail is not evidence. Read the state back.++ **Applies to:** `scripts/restore-database.sh`, `packages/dev/src/commands/restore.ts`, and any tool that loads a plain-text dump through psql.++ ## A caller-supplied document number used to leave the counter behind++ **Context:** Documents take their number from `get_next_sequence` unless the caller supplies one: a custom ID typed into `SequenceOrCustomId`, or an MCP / API upsert (`upsertSalesOrder`, `upsertQuote`, `upsertPurchaseOrder`, `upsertJob`, …) whose create path requires the number.++ **Problem:** A supplied number never moved the `sequence` row. Once the counter reached a number an agent or a user had already used, every new document failed on the unique constraint ("Failed to insert sales order") until someone moved the counter by hand.++ **Rule:** The counter is kept ahead in the database, not in app code: the `sync_advance_document_sequence` after-interceptor moves `sequence.next` past any number saved in the sequence's format, on insert and on a number change. A new numbered table must be added to that interceptor's `CASE` and given the interceptor in `attachments.ts`; the `document-sequence-synced` conformance check fails CI for a new counter that is neither covered nor in its `EXEMPT_COUNTERS`. Never "fix" a collision by retrying `get_next_sequence`.++ **Applies to:** `packages/database/src/event-system/handlers/sync_advance_document_sequence.sql`, `util.document_sequence_pattern`, any table with a readable document number.+++## An entity in `audit.config.ts` records nothing until its tables have `events: true`++**Context:** Change notice history (the `changeOrder` audit entity) was empty in the History drawer even with audit logging on (2026-10-08).++**Problem:** `auditConfig.entities.changeOrder` listed its 4 tables, and `syncAuditSubscriptions` created AUDIT subscriptions for them. But `packages/database/src/event-system/attachments.ts` gave `changeOrder` only a statement broadcast and the 3 child tables no entry at all, so no async event trigger existed and nothing reached the event queue. Every check looked green: subscriptions present, sweeper succeeding, queue empty.++**Rule:** When you add an entity to `audit.config.ts`, give each of its tables `events: true` in `attachments.ts` and ship it with `pnpm --filter @carbon/database authz migration <name>`. To debug an empty audit log, first check `pg_trigger` for `trg_event_async_*` on the table.++**Applies to:** `packages/database/src/audit.config.ts`, `packages/database/src/event-system/attachments.ts`.diff --cc apps/erp/app/modules/items/items.server.tsindex ded0e8cf74,3e3457808c..be01229baf--- a/apps/erp/app/modules/items/items.server.ts+++ b/apps/erp/app/modules/items/items.server.ts@@@ -3,11 -3,9 +3,11 @@@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { error } from "@carbon/auth";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";- import type { Database } from "@carbon/database";+ import { type Database, fetchAllByIds } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { hasPendingApproval } from "@carbon/ee/approvals.server";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { oncePerRead } from "@carbon/logger/middleware.server";diff --cc apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeHeader.tsxindex 3b54f63d7b,6167d90245..b5f1015a6c--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeHeader.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeHeader.tsx@@@ -2,45 -2,25 +2,38 @@@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type {+ ApprovalDecision,+ DocumentApprovalState+} from "@carbon/ee/approvals";import {Button,- Copy,cn,- DropdownMenu,- DropdownMenuContent,DropdownMenuIcon,DropdownMenuItem,- DropdownMenuTrigger,- Heading,- HStack,- IconButton,MENU_ITEM_SHORTCUTS,- useDisclosure+ Status,+ useDisclosure,+ VStack} from "@carbon/react";-import { useLingui } from "@lingui/react/macro";+import { formatDateTime } from "@carbon/utils";+import { Trans, useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import { useState } from "react";import {+ LuCheckCheck,LuCircleCheck,LuCircleStop,+ LuClipboardCheck,- LuEllipsisVertical,LuLoaderCircle,LuStepForward,- LuTrash+ LuTrash,+ LuX} from "react-icons/lu";- import { Link, useFetcher, useParams } from "react-router";+ import { useFetcher, useParams } from "react-router";import { useAuditLog } from "~/components/AuditLog";+ import { RecordAction, RecordHeader } from "~/components/Layout/RecordHeader";+import ApprovalDecisionModal from "~/components/Modals/ApprovalDecision";import Confirm from "~/components/Modals/Confirm/Confirm";import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { usePermissions, useRouteData, useUser } from "~/hooks";@@@ -101,209 -63,147 +94,209 @@@ const ChangeNoticeHeader = () =>status as (typeof changeNoticeStatus)[number]]?.[0] ?? null;+ const statusBadge = (- <span className={cn(isLocked && "line-through")}>- <ChangeNoticeStatus status={routeData?.changeNotice?.status} />- </span>++ <>++ <span className={cn(isLocked && "line-through")}>++ <ChangeNoticeStatus status={routeData?.changeNotice?.status} />++ </span>++ {pendingRequestId && (++ <Status color="yellow">++ <Trans>Pending Approval</Trans>++ </Status>++ )}++ {lastRejection && (++ <Status++ color="red"++ tooltip={++ <VStack spacing={1} className="max-w-xs">++ {lastRejection.decisionAt && (++ <span className="text-xs text-muted-foreground">++ {formatDateTime(lastRejection.decisionAt, locale)}++ </span>++ )}++ <span>{lastRejection.notes || t`No notes were given.`}</span>++ </VStack>++ }++ >++ <Trans>Approval Rejected</Trans>++ </Status>++ )}++ </>+ );+ const menuItems = (+ <>+ {auditLogTrigger}+ {status === "Cancelled" && (+ <DropdownMenuItem+ disabled={+ statusFetcher.state !== "idle" ||+ !permissions.can("update", "parts")+ }+ onClick={() => {+ statusFetcher.submit(+ { id, fromStatus: status, status: "Draft" },+ {+ method: "post",+ action: path.to.changeNoticeStatus(id)+ }+ );+ }}+ >+ <DropdownMenuIcon icon={<LuLoaderCircle />} />+ {t`Reopen`}+ </DropdownMenuItem>+ )}+ {/* Reopen from Implementation goes back one stage so the+ engineering content unlocks without losing progress. */}+ {status === "Implementation" && (+ <DropdownMenuItem+ disabled={+ statusFetcher.state !== "idle" ||+ !permissions.can("update", "parts")+ }+ onClick={() => {+ statusFetcher.submit(+ {+ id,+ fromStatus: status,+ status: "Engineering Complete"+ },+ {+ method: "post",+ action: path.to.changeNoticeStatus(id)+ }+ );+ }}+ >+ <DropdownMenuIcon icon={<LuLoaderCircle />} />+ {t`Reopen`}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ shortcut={MENU_ITEM_SHORTCUTS.delete}+ destructive+ disabled={+ !permissions.can("delete", "parts") || !permissions.is("employee")+ }+ onClick={deleteModal.onOpen}+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ {t`Delete Change Notice`}+ </DropdownMenuItem>+ </>+ );+return (<>- <div className="flex flex-shrink-0 items-center justify-between gap-x-4 px-4 py-2 bg-card border-b border-border h-[var(--header-height)] overflow-x-auto scrollbar-hide">- <VStack spacing={0}>- <HStack>- <Link to={path.to.changeNoticeDetails(id)}>- <Heading size="h4" className="flex items-center gap-2">- <span>{routeData?.changeNotice?.changeOrderId}</span>- </Heading>- </Link>- <span className={cn(isLocked && "line-through")}>- <ChangeNoticeStatus status={routeData?.changeNotice?.status} />- </span>- {pendingRequestId && (- <Status color="yellow">- <Trans>Pending Approval</Trans>- </Status>- )}- {lastRejection && (- <Status- color="red"- tooltip={- <VStack spacing={1} className="max-w-xs">- {lastRejection.decisionAt && (- <span className="text-xs text-muted-foreground">- {formatDateTime(lastRejection.decisionAt, locale)}- </span>- )}- <span>- {lastRejection.notes || t`No notes were given.`}- </span>- </VStack>- }- >- <Trans>Approval Rejected</Trans>- </Status>- )}- <Copy text={routeData?.changeNotice?.changeOrderId ?? ""} />- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label={t`More options`}- icon={<LuEllipsisVertical />}+ <RecordHeader+ title={routeData?.changeNotice?.changeOrderId}+ titleTo={path.to.changeNoticeDetails(id)}+ copyValue={routeData?.changeNotice?.changeOrderId ?? ""}+ menu={menuItems}+ status={statusBadge}+ actions={+ <>+ {/* The full stage flow (green-dot progress) lives in the middle pane+ (ChangeNoticeStatusFlow); the header keeps only the canonical status+ badge (above) + the advance/release action. */}++ {/* Cancel — a header action (opens the confirm modal) sitting beside the+ advance/release primary action. Reopen (from Cancelled) stays in the+ ⋮ menu. */}+ {status !== "Cancelled" && !isLocked && (+ <RecordAction slot="secondary">+ <Button+ leftIcon={<LuCircleStop />}variant="secondary"- size="sm"- />- </DropdownMenuTrigger>- <DropdownMenuContent>- {auditLogTrigger}- {status === "Cancelled" && (- <DropdownMenuItem- disabled={- statusFetcher.state !== "idle" ||- !permissions.can("update", "parts")- }- onClick={() => {- statusFetcher.submit(- { id, fromStatus: status, status: "Draft" },- {- method: "post",- action: path.to.changeNoticeStatus(id)- }- );- }}- >- <DropdownMenuIcon icon={<LuLoaderCircle />} />- {t`Reopen`}- </DropdownMenuItem>- )}- {/* Reopen from Implementation goes back one stage so the- engineering content unlocks without losing progress. */}- {status === "Implementation" && (- <DropdownMenuItem- disabled={- statusFetcher.state !== "idle" ||- !permissions.can("update", "parts")- }- onClick={() => {- statusFetcher.submit(- {- id,- fromStatus: status,- status: "Engineering Complete"- },- {- method: "post",- action: path.to.changeNoticeStatus(id)- }- );- }}- >- <DropdownMenuIcon icon={<LuLoaderCircle />} />- {t`Reopen`}- </DropdownMenuItem>- )}- <DropdownMenuItem- shortcut={MENU_ITEM_SHORTCUTS.delete}- destructive- disabled={- !permissions.can("delete", "parts") ||- !permissions.is("employee")- }- onClick={deleteModal.onOpen}+ isDisabled={!permissions.can("update", "parts")}+ onClick={cancelModal.onOpen}>- <DropdownMenuIcon icon={<LuTrash />} />- {t`Delete Change Notice`}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </HStack>- </VStack>-- <HStack spacing={2}>- {/* The full stage flow (green-dot progress) lives in the middle pane- (ChangeNoticeStatusFlow); the header keeps only the canonical status- badge (above) + the advance/release action. */}+ {t`Cancel`}+ </Button>+ </RecordAction>+ )}- {/* Cancel — a header action (opens the confirm modal) sitting beside the- advance/release primary action. Reopen (from Cancelled) stays in the- ⋮ menu. */}- {status !== "Cancelled" && !isLocked && (- <Button- leftIcon={<LuCircleStop />}- variant="secondary"- isDisabled={!permissions.can("update", "parts")}- onClick={cancelModal.onOpen}- >- {t`Cancel`}- </Button>- )}+ {/* Implementation → Done is a release: it opens the review + confirm+ dialog (which carries the merge resolution), not a one-click stage+ advance. The header only auto-advances the earlier stages. */}- {nextStatus && nextStatus !== "Done" && !isLocked && (- <RecordAction slot="primary">- <statusFetcher.Form- method="post"- action={path.to.changeNoticeStatus(id)}- >- <input type="hidden" name="id" value={id} />- <input type="hidden" name="fromStatus" value={status} />- <input type="hidden" name="status" value={nextStatus} />++ {pendingRequestId && approval?.canApprove && (++ <>++ <RecordAction slot="primary">+ <Button- type="submit"- rightIcon={<LuStepForward />}++ leftIcon={<LuCheckCheck />}+ variant="primary"- isDisabled={- statusFetcher.state !== "idle" ||- !permissions.can("update", "parts")- }- isLoading={statusFetcher.state !== "idle"}++ isDisabled={approvalFetcher.state !== "idle"}++ onClick={() => setApprovalDecision("Approved")}+ >- {t`Advance to ${nextStatus}`}++ {t`Approve`}+ </Button>- </statusFetcher.Form>- </RecordAction>++ </RecordAction>++ <RecordAction slot="secondary">++ <Button++ leftIcon={<LuX />}++ variant="destructive"++ isDisabled={approvalFetcher.state !== "idle"}++ onClick={() => setApprovalDecision("Rejected")}++ >++ {t`Reject`}++ </Button>++ </RecordAction>++ </>+ )}- {/* Implementation → Done is a release: it opens the review + confirm- dialog (which carries the merge resolution), not a one-click stage- advance. The header only auto-advances the earlier stages. */}- {pendingRequestId && approval?.canApprove && (- <>- <Button- leftIcon={<LuCheckCheck />}- variant="primary"- isDisabled={approvalFetcher.state !== "idle"}- onClick={() => setApprovalDecision("Approved")}- >- {t`Approve`}- </Button>- <Button- leftIcon={<LuX />}- variant="destructive"- isDisabled={approvalFetcher.state !== "idle"}- onClick={() => setApprovalDecision("Rejected")}- >- {t`Reject`}- </Button>- </>- )}++ {/* With no rule left, no one can decide a pending request; advancing++ withdraws it. */}++ {nextStatus &&++ nextStatus !== "Done" &&++ !isLocked &&++ (!pendingRequestId || !submitsForApproval) && (++ <RecordAction slot="primary">++ <statusFetcher.Form++ method="post"++ action={path.to.changeNoticeStatus(id)}++ >++ <input type="hidden" name="id" value={id} />++ <input type="hidden" name="fromStatus" value={status} />++ <input type="hidden" name="status" value={nextStatus} />++ <Button++ type="submit"++ rightIcon={++ submitsForApproval ? (++ <LuClipboardCheck />++ ) : (++ <LuStepForward />++ )++ }++ variant="primary"++ isDisabled={++ statusFetcher.state !== "idle" ||++ !permissions.can("update", "parts")++ }++ isLoading={statusFetcher.state !== "idle"}++ >++ {submitsForApproval++ ? t`Submit for Approval`++ : t`Advance to ${nextStatus}`}++ </Button>++ </statusFetcher.Form>++ </RecordAction>++ )}+- {/* With no rule left, no one can decide a pending request; advancing- withdraws it. */}- {nextStatus &&- nextStatus !== "Done" &&- !isLocked &&- (!pendingRequestId || !submitsForApproval) && (- <statusFetcher.Form- method="post"- action={path.to.changeNoticeStatus(id)}- >- <input type="hidden" name="id" value={id} />- <input type="hidden" name="fromStatus" value={status} />- <input type="hidden" name="status" value={nextStatus} />+ {status === "Implementation" && !isLocked && (+ <RecordAction slot="primary"><Button- type="submit"- rightIcon={- submitsForApproval ? (- <LuClipboardCheck />- ) : (- <LuStepForward />- )- }+ leftIcon={<LuCircleCheck />}variant="primary"- isDisabled={- statusFetcher.state !== "idle" ||- !permissions.can("update", "parts")- }- isLoading={statusFetcher.state !== "idle"}+ isDisabled={!permissions.can("update", "parts")}+ onClick={() => setReleaseDialogOpen(true)}>- {submitsForApproval- ? t`Submit for Approval`- : t`Advance to ${nextStatus}`}+ {t`Release`}</Button>- </statusFetcher.Form>+ </RecordAction>)}-- {status === "Implementation" && !isLocked && (- <Button- leftIcon={<LuCircleCheck />}- variant="primary"- isDisabled={!permissions.can("update", "parts")}- onClick={() => setReleaseDialogOpen(true)}- >- {t`Release`}- </Button>- )}- </HStack>- </div>+ </>+ }+ />{deleteModal.isOpen && (<ConfirmDeleteaction={path.to.deleteChangeNotice(id)}diff --cc apps/erp/app/modules/items/ui/Item/ItemRecordHeader.tsxindex 0000000000,0a01d57d78..ddf8699229mode 000000,100644..100644--- a/apps/erp/app/modules/items/ui/Item/ItemRecordHeader.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemRecordHeader.tsx@@@ -1,0 -1,140 +1,142 @@@+ // SPDX-License-Identifier: AGPL-3.0-only+ // Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+ // including ports, remain AGPLv3; serving them over a network requires releasing their source.++ import {+ DropdownMenuIcon,+ DropdownMenuItem,+ DropdownMenuSeparator,+ MENU_ITEM_SHORTCUTS,+ Status,+ useDisclosure+ } from "@carbon/react";+ import { Trans, useLingui } from "@lingui/react/macro";+ import type { ComponentProps, ReactNode } from "react";+ import { LuGitPullRequestArrow, LuTrash } from "react-icons/lu";+ import { useAuditLog } from "~/components/AuditLog";+ import { DetailsTopbar } from "~/components/Layout";+ import { RecordHeader } from "~/components/Layout/RecordHeader";+ import ConfirmDelete from "~/components/Modals/ConfirmDelete";+ import { usePermissions, useUser } from "~/hooks";+ import { useResolved } from "~/hooks/useResolved";+ import { path } from "~/utils/path";+ import type { SupersessionMode } from "../../items.models";+ import { CreateChangeNoticeModal } from "../ChangeNotice";+ import { getItemLifecycleStatus } from "./ItemSupersessionForm";++ export type ItemSupersession = Promise<{+ supersessionMode: SupersessionMode;+ } | null>;++ type ItemRecordHeaderProps = {+ itemId: string;+ readableId?: string | null;+ subtitle?: ReactNode;+ detailsTo: string;+ links: ComponentProps<typeof DetailsTopbar>["links"];+ supersession?: ItemSupersession;+ deleteLabel: ReactNode;+ deleteFallbackName: string;+ withChangeNotice?: boolean;+ };++ const ItemRecordHeader = ({+ itemId,+ readableId,+ subtitle,+ detailsTo,+ links,+ supersession: supersessionPromise,+ deleteLabel,+ deleteFallbackName,+ withChangeNotice = false+ }: ItemRecordHeaderProps) => {+ const { t } = useLingui();+ const { company } = useUser();+ const permissions = usePermissions();+ const deleteModal = useDisclosure();+ const changeNoticeModal = useDisclosure();+ const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({+ entityType: "item",+ entityId: itemId,+ companyId: company.id,- variant: "dropdown"++ variant: "dropdown",++ downloadable: true,++ downloadName: readableId ?? undefined+ });++ const supersession = useResolved(supersessionPromise, null, itemId);+ const lifecycleStatus = getItemLifecycleStatus(+ supersession?.supersessionMode+ );++ const statusPill = lifecycleStatus && (+ <Status color={lifecycleStatus.color}>{lifecycleStatus.label}</Status>+ );+ const menuItems = (+ <>+ {auditLogTrigger}+ <DropdownMenuSeparator />+ {withChangeNotice && (+ <>+ <DropdownMenuItem+ disabled={!permissions.can("create", "parts")}+ onClick={changeNoticeModal.onOpen}+ >+ <DropdownMenuIcon icon={<LuGitPullRequestArrow />} />+ <Trans>Create Change Notice</Trans>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuItem+ shortcut={MENU_ITEM_SHORTCUTS.delete}+ disabled={+ !permissions.can("delete", "parts") || !permissions.is("employee")+ }+ destructive+ onClick={deleteModal.onOpen}+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ {deleteLabel}+ </DropdownMenuItem>+ </>+ );++ return (+ <>+ <RecordHeader+ title={readableId}+ titleTo={detailsTo}+ copyValue={readableId ?? ""}+ menu={menuItems}+ status={statusPill}+ subtitle={subtitle}+ aside={<DetailsTopbar links={links} />}+ />+ {deleteModal.isOpen && (+ <ConfirmDelete+ action={path.to.deleteItem(itemId)}+ isOpen={deleteModal.isOpen}+ name={readableId ?? deleteFallbackName}+ text={t`Are you sure you want to delete ${readableId}? This cannot be undone.`}+ onCancel={() => {+ deleteModal.onClose();+ }}+ onSubmit={() => {+ deleteModal.onClose();+ }}+ />+ )}+ {changeNoticeModal.isOpen && (+ <CreateChangeNoticeModal+ itemId={itemId}+ onClose={changeNoticeModal.onClose}+ />+ )}+ {auditLogDrawer}+ </>+ );+ };++ export default ItemRecordHeader;diff --cc apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsxindex 8244938351,088e916a15..fa860c5cb1--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx@@@ -56,10 -53,12 +56,15 @@@ import { useAuditLog } from "~/componenimport { Enumerable } from "~/components/Enumerable";import { Tags } from "~/components/Form";import { useSupplierTypes } from "~/components/Form/SupplierType";+ import {+ RecordAction,+ RecordHero,+ RecordPhoneChrome+ } from "~/components/Layout/RecordHeader";-import { ConfirmDelete } from "~/components/Modals";+import {+ ApprovalDecision as ApprovalDecisionModal,+ ConfirmDelete+} from "~/components/Modals";import {usePermissions,useRouteData,diff --cc apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsxindex 4bc2fed453,40c6121d6b..d6f1b784e8--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx+++ b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentHeader.tsx@@@ -39,9 -21,9 +24,10 @@@ import { LuCheckCheck, LuClipboardCheckimport { Await, useFetcher, useParams } from "react-router";import { VersionMenu } from "~/components";import { usePanels } from "~/components/Layout";+ import { RecordAction, RecordHeader } from "~/components/Layout/RecordHeader";+import ApprovalDecisionModal from "~/components/Modals/ApprovalDecision";import ConfirmDelete from "~/components/Modals/ConfirmDelete";-import { usePermissions, useRouteData } from "~/hooks";+import { usePermissions, useRouteData, useUser } from "~/hooks";import { useDocumentStore } from "~/stores";import { path } from "~/utils/path";import type { QualityDocument } from "../../types";diff --cc apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsxindex 24b8bb42aa,93abdfc080..d887315c92--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.ee.tsx@@@ -81,10 -74,14 +81,14 @@@ const ApprovalRuleCard = memo<Accordion type="multiple" className="w-full"><AccordionItem value={rule.id} className="border-none"><div className="relative">- <AccordionTrigger className="px-6 py-8 hover:no-underline w-full">+ <AccordionTrigger className="px-6 py-8 hover:no-underline w-full max-md:px-4 max-md:py-4"><HStack spacing={4} className="flex-1 justify-between pr-12">- <Heading size="h4" as="h3">+ <Heading+ size="h4"+ as="h3"+ className="max-md:text-left max-md:min-w-0"+ >- {approvalDocumentTypeLabel[documentType]}+ {documentTypeLabel}{approvalDocumentTypesWithAmounts.includes(documentType) &&diff --cc packages/database/src/event-system/attachments.tsindex 17ea7e7d36,05682e41c2..f892a58b3c--- a/packages/database/src/event-system/attachments.ts+++ b/packages/database/src/event-system/attachments.ts@@@ -36,10 -36,10 +36,14 @@@ export const attachments =ability: { statement: ["broadcast_reference_changes"] },address: { before: ["sync_address_to_parent"], events: true },assemblyPlanJob: { statement: ["broadcast_table_changes"] },- changeOrder: { events: true, statement: ["broadcast_table_changes"] },+ changeOrder: {++ events: true,+ after: ["sync_advance_document_sequence"],+ statement: ["broadcast_table_changes"]+ },+ changeOrderActionTask: { events: true },+ changeOrderAffectedItem: { events: true },+ changeOrderSupersession: { events: true },charge: { events: true },company: { after: ["sync_insert_company_related_records"] },companyIntegration: { before: ["sync_verify_integration"], events: true },diff --cc packages/database/supabase/migrations/20261012052901_change-order-audit-events-after-sequence.sqlindex 0000000000,0000000000..86c2753f9bnew file mode 100644--- /dev/null+++ b/packages/database/supabase/migrations/20261012052901_change-order-audit-events-after-sequence.sql@@@ -1,0 -1,0 +1,8 @@@++-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++++-- event triggers (packages/database/src/event-system/attachments.ts)++SET lock_timeout = '5s';++SELECT set_event_triggers('changeOrder', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);++RESET lock_timeout;diff --cc packages/locale/locales/de/erp.poindex f523d27d59,4968930797..9c5e7f5afb--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Browser-Benachrichtigungen konnmsgid "Failed to download file for moving"msgstr "Fehler beim Herunterladen der Datei zum Verschieben"+msgid "Failed to download history"+msgstr "Verlauf konnte nicht heruntergeladen werden"++ msgid "Failed to enable browser notifications"+ msgstr "Browser-Benachrichtigungen konnten nicht aktiviert werden"+msgid "Failed to fetch item costs"msgstr "Fehler beim Abrufen der Artikelkosten"diff --cc packages/locale/locales/en/erp.poindex fc19b15fa7,19a40caa31..68038dbb44--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Failed to disable browser notifmsgid "Failed to download file for moving"msgstr "Failed to download file for moving"+msgid "Failed to download history"+msgstr "Failed to download history"++ msgid "Failed to enable browser notifications"+ msgstr "Failed to enable browser notifications"+msgid "Failed to fetch item costs"msgstr "Failed to fetch item costs"diff --cc packages/locale/locales/es/erp.poindex 93d8cd6155,8c57cd5c22..eb3b8d3e6b--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Error al desactivar las notificmsgid "Failed to download file for moving"msgstr "Error al descargar el archivo para mover"+msgid "Failed to download history"+msgstr "Error al descargar el historial"++ msgid "Failed to enable browser notifications"+ msgstr "Error al activar las notificaciones del navegador"+msgid "Failed to fetch item costs"msgstr "Error al obtener costos de artículos"diff --cc packages/locale/locales/fr/erp.poindex 695f0bfeb4,99960cbcea..5894f3361d--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Impossible de désactiver les nmsgid "Failed to download file for moving"msgstr "Échec du téléchargement du fichier pour le déplacement"+msgid "Failed to download history"+msgstr "Impossible de télécharger l'historique"++ msgid "Failed to enable browser notifications"+ msgstr "Impossible d'activer les notifications du navigateur"+msgid "Failed to fetch item costs"msgstr "Échec de la récupération des coûts des articles"diff --cc packages/locale/locales/hi/erp.poindex cf673d2885,7a4252ea2d..a3f79cb516--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "ब्राउज़र सूmsgid "Failed to download file for moving"msgstr "स्थानांतरण के लिए फ़ाइल डाउनलोड करने में विफल"+msgid "Failed to download history"+msgstr "इतिहास डाउनलोड करने में विफल"++ msgid "Failed to enable browser notifications"+ msgstr "ब्राउज़र सूचनाओं को सक्षम करने में विफल रहा"+msgid "Failed to fetch item costs"msgstr "आइटम लागत प्राप्त करने में विफल"diff --cc packages/locale/locales/it/erp.poindex ce2259441b,934cec5ef8..a24353e5ff--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Impossibile disattivare le notimsgid "Failed to download file for moving"msgstr "Impossibile scaricare il file per lo spostamento"+msgid "Failed to download history"+msgstr "Impossibile scaricare la cronologia"++ msgid "Failed to enable browser notifications"+ msgstr "Impossibile attivare le notifiche del browser"+msgid "Failed to fetch item costs"msgstr "Impossibile recuperare i costi degli articoli"diff --cc packages/locale/locales/ja/erp.poindex e8f9ce5d56,d71d9b6952..ef1c7dd51c--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "ブラウザー通知を無効�msgid "Failed to download file for moving"msgstr "ファイルの移動用ダウンロードに失敗しました"+msgid "Failed to download history"+msgstr "履歴のダウンロードに失敗しました"++ msgid "Failed to enable browser notifications"+ msgstr "ブラウザー通知を有効にできませんでした"+msgid "Failed to fetch item costs"msgstr "品目の原価を取得できませんでした"diff --cc packages/locale/locales/ko/erp.poindex 30390f0ef7,0a224ddd97..8fd3d07bdf--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "브라우저 알림 비활성�msgid "Failed to download file for moving"msgstr "이동을 위한 파일 다운로드 실패"+msgid "Failed to download history"+msgstr "이력 다운로드 실패"++ msgid "Failed to enable browser notifications"+ msgstr "브라우저 알림 활성화 실패"+msgid "Failed to fetch item costs"msgstr "품목 원가 조회 실패"diff --cc packages/locale/locales/pl/erp.poindex d82285dc5c,55bf016a88..af15cb1eb1--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Nie udało się wyłączyć powmsgid "Failed to download file for moving"msgstr "Nie udało się pobrać pliku do przeniesienia."+msgid "Failed to download history"+msgstr "Nie udało się pobrać historii"++ msgid "Failed to enable browser notifications"+ msgstr "Nie udało się włączyć powiadomień przeglądarki"+msgid "Failed to fetch item costs"msgstr "Nie udało się pobrać kosztów pozycji"diff --cc packages/locale/locales/pt/erp.poindex 60a1d8a102,485bd1a476..ec6b21d7ff--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Falha ao desativar notificaçõmsgid "Failed to download file for moving"msgstr "Falha ao baixar arquivo para mover"+msgid "Failed to download history"+msgstr "Falha ao baixar histórico"++ msgid "Failed to enable browser notifications"+ msgstr "Falha ao ativar notificações do navegador"+msgid "Failed to fetch item costs"msgstr "Falha ao buscar custos de itens"diff --cc packages/locale/locales/ru/erp.poindex 0913162517,1957a64c74..be910ca562--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Не удалось отклю�msgid "Failed to download file for moving"msgstr "Не удалось скачать файл для перемещения"+msgid "Failed to download history"+msgstr "Не удалось скачать историю"++ msgid "Failed to enable browser notifications"+ msgstr "Не удалось включить уведомления браузера"+msgid "Failed to fetch item costs"msgstr "Ошибка при получении себестоимости номенклатуры"diff --cc packages/locale/locales/tr/erp.poindex 253c93f58b,12ef0744f8..71e6a3a52f--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "Tarayıcı bildirimleri devre dmsgid "Failed to download file for moving"msgstr "Taşınacak dosya indirilemedi"+msgid "Failed to download history"+msgstr "Geçmiş indirilemedi"++ msgid "Failed to enable browser notifications"+ msgstr "Tarayıcı bildirimleri etkinleştirilemedi"+msgid "Failed to fetch item costs"msgstr "Ürün maliyetleri alınamadı"diff --cc packages/locale/locales/zh/erp.poindex 014fa73280,e977591dab..ba9fa9f3a9--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@@ -9037,9 -9239,9 +9276,12 @@@ msgstr "禁用浏览器通知失败msgid "Failed to download file for moving"msgstr "无法下载文件以进行移动"+msgid "Failed to download history"+msgstr "下载历史记录失败"++ msgid "Failed to enable browser notifications"+ msgstr "启用浏览器通知失败"+msgid "Failed to fetch item costs"msgstr "获取物料成本失败"