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/infinite-scroll
aashuc0b89322df32
diff --cc apps/erp/app/components/Table/Table.tsxindex 7bd4e9d2ea,68892ec5bb..1d067d0b7f--- a/apps/erp/app/components/Table/Table.tsx+++ b/apps/erp/app/components/Table/Table.tsx@@@ -1585,97 -1485,90 +1592,109 @@@ const Table = <T extends object>(</Tr>))}</Thead>- <Tbody>- {rows.map((row) => {- const rowExpandable =- !!renderExpandedRow &&- (!canExpandRow || canExpandRow(row.original));- const isRowExpanded =- rowExpandable && expandedRows[row.index];- const handleRowClick = rowExpandable- ? () => toggleRowExpanded(row.index)- : undefined;- const rowContent = renderContextMenu ? (- <Menu type="context" key={row.index}>- <ContextMenu>- <ContextMenuTrigger asChild>- <Row- editableComponents={editableComponents}- isEditing={isEditing}- isEditMode={editMode}- isRowSelected={- row.index in rowSelection &&- !!rowSelection[row.index]- }- visibleColumns={visibleColumns}- selectedCell={selectedCell}- row={row}- rowIsSelected={selectedCell?.row === row.index}- getPinnedStyles={getPinnedStyles}- pinnedStyleKey={pinnedStyleKey}- onCellClick={onCellClick}- onCellUpdate={onCellUpdate}- onClick={handleRowClick}+ {renderVirtualRows((virtualIndex) => {+ const row = rows[virtualIndex]!;+ const rowExpandable =+ !!renderExpandedRow &&+ (!canExpandRow || canExpandRow(row.original));+ const isRowExpanded = rowExpandable && !!expandedRows[row.id];+ const handleRowClick = rowExpandable+ ? () => toggleRowExpanded(row.id)+ : undefined;+ const rowContent = renderContextMenu ? (+ <Menu type="context">+ <ContextMenu>+ <ContextMenuTrigger asChild>+ <Row+ editableComponents={editableComponents}+ isEditing={isEditing}+ isEditMode={editMode}+ isRowSelected={row.getIsSelected()}+ visibleColumns={visibleColumns}+ selectedCell={selectedCell}+ row={row}+ rowIsSelected={selectedCell?.row === row.index}+ getPinnedStyles={getPinnedStyles}+ pinnedStyleKey={pinnedStyleKey}+ onCellClick={onCellClick}+ onCellUpdate={onCellUpdate}+ onClick={handleRowClick}+ className={cn(+ rowExpandable && "cursor-pointer",+ getRowClassName?.(row.original)+ )}+ />+ </ContextMenuTrigger>+ <ContextMenuContent className="w-128">+ {renderContextMenu(row.original)}+ </ContextMenuContent>+ </ContextMenu>+ </Menu>+ ) : (+ <Row+ key={row.id}+ editableComponents={editableComponents}+ isEditing={isEditing}+ isEditMode={editMode}+ isRowSelected={row.getIsSelected()}+ visibleColumns={visibleColumns}+ selectedCell={selectedCell}+ row={row}+ rowIsSelected={selectedCell?.row === row.index}+ getPinnedStyles={getPinnedStyles}+ pinnedStyleKey={pinnedStyleKey}+ onCellClick={onCellClick}+ onCellUpdate={onCellUpdate}+ onClick={handleRowClick}+ className={cn(+ rowExpandable && "cursor-pointer",+ getRowClassName?.(row.original)+ )}+ />+ );++ const groupRows = groupStarts.get(row.id);++ return (+ <Tbody+ key={row.id}+ ref={rowVirtualizer.measureElement}+ data-index={virtualIndex}+ >+ {groupRows && groupRowsBy && (+ <Tr>+ <Td+ colSpan={visibleColumns.length}+ className="p-0 bg-muted/40 border-b border-border"+ >- <div className="sticky left-0 w-fit">++ {/* As wide as the visible table, so a header++ can put its actions at the right edge. */}++ <div+ className={cn(- rowExpandable && "cursor-pointer",- getRowClassName?.(row.original)++ "sticky left-0",++ containerWidth === 0 && "w-fit"+ )}- />- </ContextMenuTrigger>- <ContextMenuContent className="w-128">- {renderContextMenu(row.original)}- </ContextMenuContent>- </ContextMenu>- </Menu>- ) : (- <Row- key={row.id}- editableComponents={editableComponents}- isEditing={isEditing}- isEditMode={editMode}- isRowSelected={- row.index in rowSelection && !!rowSelection[row.index]- }- visibleColumns={visibleColumns}- selectedCell={selectedCell}- row={row}- rowIsSelected={selectedCell?.row === row.index}- getPinnedStyles={getPinnedStyles}- pinnedStyleKey={pinnedStyleKey}- onCellClick={onCellClick}- onCellUpdate={onCellUpdate}- onClick={handleRowClick}- className={cn(- rowExpandable && "cursor-pointer",- getRowClassName?.(row.original)- )}- />- );-- const groupRows = groupStarts.get(row.id);-- return (- <Fragment key={row.id}>- {groupRows && groupRowsBy && (- <Tr>- <Td- colSpan={visibleColumns.length}- className="p-0 bg-muted/40 border-b border-border"++ style={++ containerWidth > 0++ ? { width: containerWidth }++ : undefined++ }+ >- {/* As wide as the visible table, so a header- can put its actions at the right edge. */}+ {groupRowsBy.header(groupRows)}+ </div>+ </Td>+ </Tr>+ )}+ {rowContent}+ {isRowExpanded && (+ <Tr>+ <Td+ colSpan={visibleColumns.length}+ className="p-0 bg-muted/20 border-b border-border"+ >+ {pinExpandedRows ? (<div- className={cn(- "sticky left-0",- containerWidth === 0 && "w-fit"- )}+ className="sticky left-0"style={containerWidth > 0? { width: containerWidth }diff --cc apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsxindex 4feeeeebeb,88056821ec..5242527ecc--- a/apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsx+++ b/apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsx@@@ -27,10 -30,8 +30,10 @@@ import type { AccountClass, GeneralLedgimport JournalEntryStatus from "../JournalEntries/JournalEntryStatus";type GeneralLedgerTableProps = {- data: GeneralLedgerLine[];+ data: GeneralLedgerRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;accounts: { id: string; number: string | null; name: string | null }[];currencyCode: string;};diff --cc apps/erp/app/modules/inventory/inventory.service.tsindex 64acfe8231,70c6dd3802..205061ba1e--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@@ -866,6 -859,85 +873,85 @@@ export async function getReceiptsreturn query;}+ /**+ * The purchase order lines Receiving searches: lines of orders waiting to be+ * received and not fully received, oldest order first and in line order within+ * it, so the list groups by order (its sort is fixed). Every search word must+ * occur in one of the line's values, case, spaces and punctuation ignored+ * (`receivingSearchTerms`).+ */+ export async function getPurchaseOrderLinesToReceive(+ client: SupabaseClient<Database>,+ companyId: string,+ args: Omit<GenericQueryFilters, "sorts"> & { search: string | null }+ ) {+ let query = client+ .from("purchaseOrderLinesToReceive")+ .select(+ "id, purchaseOrderId, purchaseOrderReadableId, revisionId, orderDate, supplierId, supplierName, supplierReference, trackingNumber, locationId, itemId, itemReadableId, itemName, itemType, thumbnailPath, description, supplierPartId, purchaseQuantity, quantityReceived, quantityToReceive, purchaseUnitOfMeasureCode, promisedDate",+ { count: LIST_COUNT }+ )+ .eq("companyId", companyId)+ .eq("receivedComplete", false);++ for (const term of receivingSearchTerms(args.search)) {+ query = query.ilike("searchText", `%${term}%`);+ }+ // Filters only: assigned back so the select keeps its row type.+ query = setGenericQueryFilters(query, { filters: args.filters });++ return query+ .order("orderDate", { ascending: true })+ .order("purchaseOrderReadableId", { ascending: true })+ .order("sortOrder", { ascending: true })+ .order("id", { ascending: true })- .range(args.offset, args.offset + args.limit - 1);++ .range(args.offset ?? 0, (args.offset ?? 0) + args.limit - 1);+ }++ /**+ * Every order still waiting on these items, so Receiving can say a part is+ * also open on another order.+ */+ export async function getOpenPurchaseOrdersForItems(+ client: SupabaseClient<Database>,+ companyId: string,+ itemIds: string[]+ ) {+ return fetchAllByIds(itemIds, (batch) =>+ client+ .from("purchaseOrderLinesToReceive")+ .select(+ "id, itemId, purchaseOrderId, purchaseOrderReadableId, revisionId"+ )+ .eq("companyId", companyId)+ .eq("receivedComplete", false)+ .in("itemId", batch)+ .order("id")+ );+ }++ /**+ * The Draft receipts already started for these purchase orders, oldest first,+ * so Receiving opens one instead of starting a second.+ */+ export async function getDraftReceiptsForPurchaseOrders(+ client: SupabaseClient<Database>,+ companyId: string,+ purchaseOrderIds: string[]+ ) {+ return fetchAllByIds(purchaseOrderIds, (batch) =>+ client+ .from("receipt")+ .select("id, receiptId, sourceDocumentId")+ .eq("companyId", companyId)+ .eq("sourceDocument", "Purchase Order")+ .eq("status", "Draft")+ .in("sourceDocumentId", batch)+ .order("createdAt", { ascending: true })+ .order("id", { ascending: true })+ );+ }+export async function getReceipt(client: SupabaseClient<Database>,receiptId: stringdiff --cc apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsxindex 175bc699a9,81edca1ca1..3e370fb47e--- a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx+++ b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx@@@ -16,8 -16,7 +16,8 @@@ importimport { useNavigate } from "react-router";import { EmployeeAvatarGroup, Hyperlink, New, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";+import type { InfiniteOptions } from "~/components/Table";- import { usePermissions, useUrlParams } from "~/hooks";+ import { useCompanyToday, usePermissions, useUrlParams } from "~/hooks";import type { Abilities } from "~/modules/resources/types";import { usePeople } from "~/stores";import { path } from "~/utils/path";diff --cc apps/erp/app/routes/x+/reports+/general-ledger.tsxindex d158ea9ea8,e11d4de7a6..f1fb857635--- a/apps/erp/app/routes/x+/reports+/general-ledger.tsx+++ b/apps/erp/app/routes/x+/reports+/general-ledger.tsx@@@ -11,9 -10,9 +11,10 @@@ import { msg } from "@lingui/core/macroimport type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useLocation } from "react-router";import {+ GENERAL_LEDGER_PAGING,getAccountsList,- getGeneralLedgerLines+ getGeneralLedgerLines,+ withGeneralLedgerCounterparties} from "~/modules/accounting/accounting.service";import {GeneralLedgerTable,@@@ -68,16 -55,21 +69,32 @@@ export async function loader({ request);}+ const page = toPage(+ lines.data ?? [],+ { limit, sorts: query.sorts },+ GENERAL_LEDGER_PAGING+ );+ const rows = await withGeneralLedgerCounterparties(+ client,+ selectedCompany.id,- lines.data ?? []++ page.rows+ );+ if (rows.error) {++ logger.error("Failed to load the counterparties of the general ledger", {++ companyId: selectedCompany.id,++ error: rows.error++ });++ if (cursor) return listErrorPage("lines");+ throw redirect(+ path.to.reports,+ await flash(request, error(rows.error, "Failed to load general ledger"))+ );+ }return {- lines: page.rows,+ lines: rows.data,count: lines.count ?? 0,+ nextCursor: page.nextCursor,accounts: accounts.data ?? [],companies,selectedCompanyId: selectedCompany.id,diff --cc packages/jobs/AGENTS.mdindex 08460d3964,2f395c0b6a..d18f2cdccb--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@@ -74,10 -74,8 +74,10 @@@ pnpm --filter @carbon/jobs plan:compan| `notification-digest` | `carbon/notification-digest.process` (sent by the `notification-digest-sweeper` pg_cron job every 15 min, only when `util.notification_digest_has_work()`) | Roll unread notifications into one digest per user, company and topic || `workflow-run-retention` | `carbon/workflow-run-retention.process` (sent by the `workflow-run-retention-sweeper` pg_cron job at 04:00 UTC, only when `util.workflow_run_retention_has_work()`) | Reap stale runs, compact and drop step detail, purge old run headers || `kanban-level-check` | `carbon/kanban.level-check` `{ companyId, kanbanIds }` (sent by the database only: the `queue_kanban_level_checks` statement handler on `itemLedger`, the `sync_kanban_level_check` interceptor on `kanban`, and the hourly `kanban-level-sweeper` pg_cron job through `util.sweep_kanban_levels()`, each only for Transfer kanbans already below their `replenishmentLevel`) | Calls `postingOrThrow("kanban-replenish", …)` in level mode (`userId "system"`, concurrency 1 per company, no `debounce`). It re-checks the projected quantity under a row lock, so a stale or duplicate event writes nothing. See `.claude/rules/kanban-system.md` |- | `model-optimize` | `carbon/model-optimize` `{ modelUploadId, companyId }` (sent by the database: the `queue_model_pipeline` statement handler on `modelUpload` for every new row, except under `app.sync_in_progress` and for bundled `_templates/` paths; also by the viewer's Retry) | One assembler job per new model (`runAssemblerJob`, `tasks/assembler-client.ts`): the optimised preview GLB, the raw's compact form while the raw is in `temp-staging`, and the thumbnail. Then it moves the raw out of staging (`settleCompactedRaw`, else `relocateRaw`, `tasks/model-compact.ts`). The model's file is read only from its own company (`resolveModelSourceBucket`). pg_cron `model-pipeline-reaper` (`util.reap_model_pipeline()`, at :13 and :43) marks an optimise, conversion or plan job Queued or Processing for 8 hours as Failed, and resends this event for a model still Idle 30 to 60 minutes after it was created |+ | `model-optimize` | `carbon/model-optimize` `{ modelUploadId, companyId }` (sent by the database: the `queue_model_pipeline` statement handler on `modelUpload` for every new row, except under `app.sync_in_progress` and for bundled `_templates/` paths; also by the viewer's Retry) | One assembler job per new model (`runAssemblerJob`, `tasks/assembler-client.ts`): the optimised preview GLB, the raw's compact form while the raw is in `temp-staging`, the thumbnail, and for a STEP with PMI the `pmi-{run}.json` the viewer draws (`modelUpload.pmiPath`, null when the model has none; the previous run's file is removed). Then it moves the raw out of staging (`settleCompactedRaw`, else `relocateRaw`, `tasks/model-compact.ts`). The model's file is read only from its own company (`resolveModelSourceBucket`). pg_cron `model-pipeline-reaper` (`util.reap_model_pipeline()`, at :13 and :43) marks an optimise, conversion or plan job Queued or Processing for 8 hours as Failed, and resends this event for a model still Idle 30 to 60 minutes after it was created || `embedding-queue` | `carbon/embedding-queue.process` (sent by the 10 s `process-embeddings` pg_cron doorbell while visible messages wait) | Drain the pgmq `embedding_jobs` queue and write embeddings |+| `table-export` | `carbon/table-export` (`api+/table.export.ts`) | Background CSV export of a registered ERP list past 1,000 rows. One run per company. Steps of at most 10,000 rows write part files to `temp-staging`; `compose` streams them into `{companyId}/exports/{userId}/{exportId}.csv`. Stops at 100,000 rows or 200 MB. Step bodies in `src/table-jobs/export-run.ts` |+| `table-bulk-action` | `carbon/table-bulk-action` (`startBackgroundBulkAction`, ERP `utils/table-jobs.server.ts`) | A bulk action on every matching row of a registered list, or on selected rows too many for one request (`ids` in the event). One run per company, `retries: 0`. Collect steps store the ids (10,000 rows per step) in `temp-staging`; a selected-rows run stores its ids in one step instead. Apply steps run the action on one slice each, 100 ids per call, passing each call's `carry` to the next. Step bodies in `src/table-jobs/bulk-run.ts` || `mrp` | `*/15 * * * *` | Scheduled MRP. Each tick plans only the companies that are DUE — every 3 hours (UTC) by default, or once a day at `companySettings.mrpRunTime` on the company's clock (`isMrpDue` / `mrpTick`) — and have planning work (`companiesWithPlanningWork`), both in `scheduled/mrp-companies.ts`; one `step.run` per company |## Safety Notes