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
fix(tables): background bulk notifications name the rows that failed or need a fix; export and bulk refusals are translated
aashu81b947c78c54
diff --git a/apps/erp/app/components/Table/components/Download.tsx b/apps/erp/app/components/Table/components/Download.tsxindex dba647c123..b436bda2b0 100644--- a/apps/erp/app/components/Table/components/Download.tsx+++ b/apps/erp/app/components/Table/components/Download.tsx@@ -19,6 +19,7 @@ import { useCustomers, useItems, usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import { BROWSER_ROW_LIMIT } from "../infiniteRowsStore";import { selectExportColumns } from "../utils";+import { useTableJobRefusalMessage } from "./SelectAllMatching";/** An infinite list's export: the rows the browser has not loaded yet. */export type InfiniteExport = {@@ -66,6 +67,7 @@ export function useCsvDownload({infinite}: DownloadProps) {const { t } = useLingui();+ const refusalMessage = useTableJobRefusalMessage();const numberFormatter = useNumberFormatter();const { search } = useLocation();const [items] = useItems();@@ -148,13 +150,15 @@ export function useCsvDownload({t`Your export is being prepared. We'll notify you when it's ready.`);} else {- toast.error(errorMessage(result) ?? failed);+ toast.error(+ refusalMessage(refusalOf(result)) ?? errorMessage(result) ?? failed+ );}} catch {toast.error(failed);}},- [t, search, exportColumns, columnAccessors]+ [t, refusalMessage, search, exportColumns, columnAccessors]);const onClick = useCallback(async () => {@@ -209,6 +213,11 @@ function isSuccess(result: unknown): boolean {);}+function refusalOf(result: unknown): unknown {+ if (typeof result !== "object" || result === null) return null;+ return (result as { refusal?: unknown }).refusal ?? null;+}+function errorMessage(result: unknown): string | null {if (typeof result !== "object" || result === null) return null;const { error } = result as { error?: unknown };diff --git a/apps/erp/app/components/Table/components/SelectAllMatching.tsx b/apps/erp/app/components/Table/components/SelectAllMatching.tsxindex 2b2a2274f0..26dab54eab 100644--- a/apps/erp/app/components/Table/components/SelectAllMatching.tsx+++ b/apps/erp/app/components/Table/components/SelectAllMatching.tsx@@ -6,8 +6,9 @@ import { Button, cn } from "@carbon/react";import { Plural, Trans, useLingui } from "@lingui/react/macro";import { useNumberFormatter } from "@react-aria/i18n";import type { OnChangeFn, RowSelectionState } from "@tanstack/react-table";-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { useLocation } from "react-router";+import type { TableJobRefusal } from "~/utils/table-jobs";import { BROWSER_ROW_LIMIT, EXACT_COUNT_LIMIT } from "../infiniteRowsStore";import type { AllMatchingSelection, InfiniteRows } from "../types";@@ -123,6 +124,52 @@ export function useBackgroundBulkActionMessage() {return t`Running in the background. We'll notify you when it's done.`;}+/**+ * Words why an export or a bulk action did not start, from the route's+ * `refusal` (`TableJobRefusal`, `~/utils/table-jobs`), or null when the+ * answer has none.+ */+export function useTableJobRefusalMessage() {+ const { t, i18n } = useLingui();+ return useCallback(+ (refusal: unknown): string | null => {+ if (!isTableJobRefusal(refusal)) return null;+ switch (refusal.code) {+ case "busy": {+ const minutes = i18n.number(refusal.minutes);+ if (refusal.kind === "export") {+ return refusal.minutes > 0+ ? t`An export is already running for your company. Try again when it ends, at the latest in ${minutes} min.`+ : t`An export is already running for your company. Try again when it ends.`;+ }+ return refusal.minutes > 0+ ? t`A bulk action is already running for your company. Try again when it ends, at the latest in ${minutes} min.`+ : t`A bulk action is already running for your company. Try again when it ends.`;+ }+ case "row-limit": {+ const rows = i18n.number(refusal.maxRows);+ return t`This action runs on at most ${rows} rows. Filter the list to ${rows} rows or fewer.`;+ }+ case "not-supported":+ return t`This action cannot run on this list.`;+ case "no-permission":+ return t`You do not have permission to do this on every matching row.`;+ case "not-started":+ return t`It could not start. Try again.`;+ }+ },+ [t, i18n]+ );+}++function isTableJobRefusal(value: unknown): value is TableJobRefusal {+ return (+ typeof value === "object" &&+ value !== null &&+ typeof (value as { code?: unknown }).code === "string"+ );+}+/** What a bulk action posts in place of ids for an "all matching" selection:* the list and its URL search (the route reads it with `parseAllMatching`). */export function allMatchingRequest(allMatching: AllMatchingSelection) {diff --git a/apps/erp/app/components/Table/index.ts b/apps/erp/app/components/Table/index.tsindex 961a287775..92f80181b3 100644--- a/apps/erp/app/components/Table/index.ts+++ b/apps/erp/app/components/Table/index.ts@@ -7,7 +7,8 @@ import Table from "./Table";export {allMatchingRequest,useAllMatchingUnsupportedLabel,- useBackgroundBulkActionMessage+ useBackgroundBulkActionMessage,+ useTableJobRefusalMessage} from "./components/SelectAllMatching";export type {AllMatchingSelection,diff --git a/apps/erp/app/hooks/useBulkAction.ts b/apps/erp/app/hooks/useBulkAction.tsindex 756d448941..03e02bb3ae 100644--- a/apps/erp/app/hooks/useBulkAction.ts+++ b/apps/erp/app/hooks/useBulkAction.ts@@ -6,7 +6,10 @@ import { useAction } from "@carbon/query";import { toast } from "@carbon/react";import { useLingui } from "@lingui/react/macro";import { useCallback, useRef } from "react";-import { useBackgroundBulkActionMessage } from "~/components/Table";+import {+ useBackgroundBulkActionMessage,+ useTableJobRefusalMessage+} from "~/components/Table";import {appendBulkSelection,type BulkSelection@@ -27,6 +30,7 @@ import {*/export function useBulkStartToast() {const backgroundMessage = useBackgroundBulkActionMessage();+ const refusalMessage = useTableJobRefusalMessage();return useCallback((data: unknown): boolean => {if (data === null || typeof data !== "object") return false;@@ -34,18 +38,19 @@ export function useBulkStartToast() {success?: unknown;background?: unknown;message?: unknown;+ refusal?: unknown;};if (result.background === true) {toast.success(backgroundMessage);return true;}if (result.success === false && typeof result.message === "string") {- toast.error(result.message);+ toast.error(refusalMessage(result.refusal) ?? result.message);return true;}return false;},- [backgroundMessage]+ [backgroundMessage, refusalMessage]);}diff --git a/apps/erp/app/routes/api+/table.export.ts b/apps/erp/app/routes/api+/table.export.tsindex 28d3668284..1004d38f95 100644--- a/apps/erp/app/routes/api+/table.export.ts+++ b/apps/erp/app/routes/api+/table.export.ts@@ -11,7 +11,12 @@ import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { z } from "zod";import { getListDefinition } from "~/utils/list-registry/index.server";-import { newTableExportId, tableJobBusyMessage } from "~/utils/table-jobs";+import {+ newTableExportId,+ type TableJobRefusal,+ tableJobBusyMessage,+ tableJobBusyRefusal+} from "~/utils/table-jobs";const logger = getLogger("erp", "table-export");@@ -43,14 +48,26 @@ export async function action({ request }: ActionFunctionArgs) {await request.json().catch(() => null));if (!body.success) {- return data({ error: "The export request is not valid" }, { status: 400 });+ return data(+ {+ error: "The export request is not valid",+ refusal: { code: "not-started" } satisfies TableJobRefusal+ },+ { status: 400 }+ );}const { listKey, search, columns } = body.data;const definition = getListDefinition(listKey);if (!definition) {logger.error("Export requested for an unknown list", { listKey });- return data({ error: "This list cannot be exported" }, { status: 400 });+ return data(+ {+ error: "This list cannot be exported",+ refusal: { code: "not-supported" } satisfies TableJobRefusal+ },+ { status: 400 }+ );}const { companyId, userId } = await requirePermissions(request, {@@ -62,7 +79,10 @@ export async function action({ request }: ActionFunctionArgs) {const lock = await takeTableJobLock("export", companyId, exportId);if (lock.status === "busy") {return data(- { error: tableJobBusyMessage("export", lock.retryAfterSeconds) },+ {+ error: tableJobBusyMessage("export", lock.retryAfterSeconds),+ refusal: tableJobBusyRefusal("export", lock.retryAfterSeconds)+ },{ status: 409 });}@@ -90,7 +110,13 @@ export async function action({ request }: ActionFunctionArgs) {error});await releaseTableJobLock("export", companyId, exportId);- return data({ error: "The export could not start" }, { status: 500 });+ return data(+ {+ error: "The export could not start",+ refusal: { code: "not-started" } satisfies TableJobRefusal+ },+ { status: 500 }+ );}return data({ success: true });diff --git a/apps/erp/app/utils/table-jobs.server.ts b/apps/erp/app/utils/table-jobs.server.tsindex 650344e870..ba0dbf6c9f 100644--- a/apps/erp/app/utils/table-jobs.server.ts+++ b/apps/erp/app/utils/table-jobs.server.ts@@ -11,6 +11,7 @@ import type { Json } from "@carbon/database";import { companyHasFeature } from "@carbon/ee/plan.server";import { trigger } from "@carbon/jobs";import {+ MAX_BULK_PROBLEMS,releaseTableJobLock,type TableBulkAction,type TableBulkActionCarry,@@ -51,7 +52,8 @@ import {rowLimitRefusal,type TableBulkActionKey,type TableJobClaims,- tableJobBusyMessage+ tableJobBusyMessage,+ tableJobBusyRefusal} from "./table-jobs";const logger = getLogger("erp", "table-jobs");@@ -78,21 +80,24 @@ async function canReadList(}/** The user's claims for the company, read fresh as the user (not through- * the permission cache, which can hold a revoked permission for an hour). */+ * the permission cache, which can hold a revoked permission for an hour).+ * Null when the user has none. Throws when the read fails, so a job step+ * retries or fails instead of telling the user they lost access. */async function readClaims({companyId,userId}: TableJobContext): Promise<TableJobClaims | null> {const client = await getUserScopedClient(userId);const claims = await getClaims(client, userId, companyId);- if (claims.error || claims.data === null) {+ if (claims.error) {logger.error("Failed to read the claims of a table job's user", {companyId,userId,error: claims.error});- return null;+ throw new Error("Failed to read the claims of a table job's user");}+ if (claims.data === null) return null;return makePermissionsFromClaims(claims.data as Json[]) ?? null;}@@ -170,6 +175,24 @@ function carriedPurchaseOrders();}+type RowProblem = { readableId: string; message: string };++/** The notification's line per failed row, then per row done with a warning. */+function problemLines(+ failed: RowProblem[],+ warnings: RowProblem[] = []+): Pick<TableBulkActionResult, "problems" | "problemCount"> {+ const lines = [+ ...failed.map((p) => `${p.readableId}: ${p.message}`),+ ...warnings.map((p) => `${p.readableId} (done): ${p.message}`)+ ];+ if (lines.length === 0) return {};+ return {+ problems: lines.slice(0, MAX_BULK_PROBLEMS),+ problemCount: lines.length+ };+}+function userClientFactory(userId: string) {return refreshingClientFactory(() => getUserScopedClient(userId));}@@ -216,6 +239,9 @@ const BULK_ACTION_RUNS: Record<TableBulkActionKey, BulkActionRun> = {done: result.released,skipped: result.skipped,failed: result.failed.length,+ // Released jobs with something left to fix (a PO that failed) are named+ // too: the in-request release shows them, and so must the notification.+ ...problemLines(result.failed, result.warnings),carry: { purchaseOrdersBySupplierId: result.purchaseOrdersBySupplierId }};},@@ -254,7 +280,8 @@ const BULK_ACTION_RUNS: Record<TableBulkActionKey, BulkActionRun> = {return {done: result.done,skipped: result.skipped,- failed: result.failed.length+ failed: result.failed.length,+ ...problemLines(result.failed)};},"batches.dissolve": async (ids, _params, context) => {@@ -269,7 +296,8 @@ const BULK_ACTION_RUNS: Record<TableBulkActionKey, BulkActionRun> = {return {done: result.done,skipped: result.skipped,- failed: result.failed.length+ failed: result.failed.length,+ ...problemLines(result.failed)};},"users.deactivate": async (ids, { ip }, { companyId, userId }) => {@@ -504,14 +532,34 @@ async function startBulkRun({actionKey,listKey});- return { success: false, message: "This action cannot run on this list" };+ return {+ success: false,+ message: "This action cannot run on this list",+ refusal: { code: "not-supported" }+ };}const context = { companyId, userId };- if (!(await canRunBulkAction(listKey, { key: actionKey, params }, context))) {+ let allowed: boolean;+ try {+ allowed = await canRunBulkAction(+ listKey,+ { key: actionKey, params },+ context+ );+ } catch {+ // `readClaims` logged it.+ return {+ success: false,+ message: "The bulk action could not start",+ refusal: { code: "not-started" }+ };+ }+ if (!allowed) {return {success: false,- message: "You do not have permission to do this on every matching row"+ message: "You do not have permission to do this on every matching row",+ refusal: { code: "no-permission" }};}@@ -520,10 +568,20 @@ async function startBulkRun({? ids.length: await countMatchingRows(listKey, context, search);if (matching === null) {- return { success: false, message: "The bulk action could not start" };+ return {+ success: false,+ message: "The bulk action could not start",+ refusal: { code: "not-started" }+ };}const refusal = rowLimitRefusal(bulkAction, matching);- if (refusal) return { success: false, message: refusal };+ if (refusal) {+ return {+ success: false,+ message: refusal,+ refusal: { code: "row-limit", maxRows: bulkAction.maxRows }+ };+ }}const bulkActionId = nanoid();@@ -531,7 +589,8 @@ async function startBulkRun({if (lock.status === "busy") {return {success: false,- message: tableJobBusyMessage("bulk", lock.retryAfterSeconds)+ message: tableJobBusyMessage("bulk", lock.retryAfterSeconds),+ refusal: tableJobBusyRefusal("bulk", lock.retryAfterSeconds)};}if (lock.status === "unavailable") {@@ -567,7 +626,11 @@ async function startBulkRun({error});await releaseTableJobLock("bulk", companyId, bulkActionId);- return { success: false, message: "The bulk action could not start" };+ return {+ success: false,+ message: "The bulk action could not start",+ refusal: { code: "not-started" }+ };}return { success: true, background: true };}diff --git a/apps/erp/app/utils/table-jobs.test.ts b/apps/erp/app/utils/table-jobs.test.tsindex a0e8168b4f..640987a13e 100644--- a/apps/erp/app/utils/table-jobs.test.ts+++ b/apps/erp/app/utils/table-jobs.test.ts@@ -19,6 +19,7 @@ import {splitIdsByStatus,type TableJobClaims,tableJobBusyMessage,+ tableJobBusyRefusal,USER_CLIENT_MAX_AGE_MS} from "./table-jobs";@@ -209,15 +210,34 @@ describe("the bulk actions' background path", () => {data: null,error: null});- expect(bulkStartFormResponse({ success: false, message: "Busy" })).toEqual({+ const refusal = { code: "busy", kind: "bulk", minutes: 3 } as const;+ expect(+ bulkStartFormResponse({ success: false, message: "Busy", refusal })+ ).toEqual({success: false,message: "Busy",+ refusal,data: null,error: { message: "Busy" }});});});+describe("tableJobBusyRefusal", () => {+ it("rounds the lock's time left up to whole minutes", () => {+ expect(tableJobBusyRefusal("export", 1741)).toEqual({+ code: "busy",+ kind: "export",+ minutes: 30+ });+ expect(tableJobBusyRefusal("bulk", 0)).toEqual({+ code: "busy",+ kind: "bulk",+ minutes: 0+ });+ });+});+describe("fitsOneRequest", () => {it("keeps a selection inside one background step in the request", () => {expect(fitsOneRequest("jobs.release", 25)).toBe(true);diff --git a/apps/erp/app/utils/table-jobs.ts b/apps/erp/app/utils/table-jobs.tsindex a15c213863..db36861e73 100644--- a/apps/erp/app/utils/table-jobs.ts+++ b/apps/erp/app/utils/table-jobs.ts@@ -154,9 +154,37 @@ export type AllMatchingRequest = { listKey: string; search: string };* background job started, or why it did not. Every route answers the same* shape, so one client helper (`useBulkActionResult`) reads them all.*/+/**+ * Why a table job (an export or a bulk action) did not start. The browser+ * words it in the user's language (`useTableJobRefusalMessage`); `message`+ * next to it is the English text for logs and older callers.+ */+export type TableJobRefusal =+ | { code: "busy"; kind: "export" | "bulk"; minutes: number }+ | { code: "row-limit"; maxRows: number }+ | { code: "not-supported" }+ | { code: "no-permission" }+ | { code: "not-started" };++/** The busy refusal: minutes until the lock expires at the latest, 0 when+ * Redis does not know. */+export function tableJobBusyRefusal(+ kind: "export" | "bulk",+ retryAfterSeconds: number+): TableJobRefusal {+ return {+ code: "busy",+ kind,+ minutes:+ retryAfterSeconds > 0+ ? round(retryAfterSeconds / 60, 0, RoundingMode.Up)+ : 0+ };+}+export type BulkActionStart =| { success: true; background: true }- | { success: false; message: string };+ | { success: false; message: string; refusal: TableJobRefusal };/*** A form-posted route's answer for a bulk start: the `BulkActionStart` fieldsdiff --git a/packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts b/packages/jobs/src/inngest/functions/tasks/table-bulk-action.tsindex 547c18067a..f0766f81a1 100644--- a/packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts+++ b/packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts@@ -7,6 +7,7 @@ import { NotificationEvent } from "@carbon/notifications";import {addBulkActionCounts,BULK_CHUNK_SIZE,+ bulkActionProblemsBody,bulkActionTitle,bulkActionTruncatedBody,DEFAULT_BULK_IDS_PER_STEP,@@ -234,7 +235,13 @@ export const tableBulkActionFunction = inngest.createFunction(userId,documentId: bulkActionId,title: bulkActionTitle(actionLabel, counts),- body: truncated ? bulkActionTruncatedBody(maxRows) : undefined,+ body:+ [+ truncated ? bulkActionTruncatedBody(maxRows) : undefined,+ bulkActionProblemsBody(counts)+ ]+ .filter(Boolean)+ .join("\n\n") || undefined,dedupeId: `table-bulk-action:${bulkActionId}:done`}));diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.tsindex a9824807aa..66d4893d01 100644--- a/packages/jobs/src/inngest/index.ts+++ b/packages/jobs/src/inngest/index.ts@@ -9,6 +9,7 @@ import { Edition } from "@carbon/utils";// Re-export the inngest client and helpers+export { MAX_BULK_PROBLEMS } from "../table-jobs/bulk.ts";export type {TableBulkAction,TableBulkActionCarry,diff --git a/packages/jobs/src/table-jobs/bulk.test.ts b/packages/jobs/src/table-jobs/bulk.test.tsindex 323b8690de..da85494dfe 100644--- a/packages/jobs/src/table-jobs/bulk.test.ts+++ b/packages/jobs/src/table-jobs/bulk.test.ts@@ -5,9 +5,11 @@import { describe, expect, it } from "vitest";import {addBulkActionCounts,+ bulkActionProblemsBody,bulkActionTitle,bulkActionTruncatedBody,collectRowIds,+ MAX_BULK_PROBLEMS,NO_BULK_COUNTS,planIdSlices} from "./bulk";@@ -29,6 +31,49 @@ describe("addBulkActionCounts", () => {});});+describe("addBulkActionCounts problems", () => {+ it("keeps every slice's problem lines in order", () => {+ expect(+ addBulkActionCounts(+ { done: 1, skipped: 0, failed: 1, problems: ["J1: no operations"] },+ {+ done: 2,+ skipped: 0,+ failed: 0,+ problems: ["J2 (done): PO failed"],+ problemCount: 1+ }+ )+ ).toEqual({+ done: 3,+ skipped: 0,+ failed: 1,+ problems: ["J1: no operations", "J2 (done): PO failed"],+ problemCount: 2+ });+ });++ it("keeps the first lines and counts the rest", () => {+ const many = Array.from(+ { length: MAX_BULK_PROBLEMS },+ (_, i) => `J${i}: failed`+ );+ const sum = addBulkActionCounts(+ { done: 0, skipped: 0, failed: MAX_BULK_PROBLEMS, problems: many },+ { done: 0, skipped: 0, failed: 5, problems: ["late"], problemCount: 5 }+ );+ expect(sum.problems).toEqual(many);+ expect(sum.problemCount).toBe(MAX_BULK_PROBLEMS + 5);+ expect(bulkActionProblemsBody(sum)).toMatch(/\nand 5 more$/);+ });++ it("has no body without problems", () => {+ expect(+ bulkActionProblemsBody({ done: 3, skipped: 0, failed: 0 })+ ).toBeUndefined();+ });+});+describe("collectRowIds", () => {it("reads the id column and keeps the page order", () => {const ids = new Set<string>();diff --git a/packages/jobs/src/table-jobs/bulk.ts b/packages/jobs/src/table-jobs/bulk.tsindex 3c100428e6..c12ae030dc 100644--- a/packages/jobs/src/table-jobs/bulk.ts+++ b/packages/jobs/src/table-jobs/bulk.ts@@ -27,15 +27,33 @@ export const NO_BULK_COUNTS: TableBulkActionCounts = {failed: 0};+/** Problem lines a run keeps for its notification. They ride in the step+ * results, so the list stays short; the rest are only counted. */+export const MAX_BULK_PROBLEMS = 20;+export function addBulkActionCounts(a: TableBulkActionCounts,b: TableBulkActionCounts): TableBulkActionCounts {- return {+ const counts = {done: a.done + b.done,skipped: a.skipped + b.skipped,failed: a.failed + b.failed};+ const problemCount = countProblems(a) + countProblems(b);+ if (problemCount === 0) return counts;+ return {+ ...counts,+ problems: [...(a.problems ?? []), ...(b.problems ?? [])].slice(+ 0,+ MAX_BULK_PROBLEMS+ ),+ problemCount+ };+}++function countProblems(counts: TableBulkActionCounts): number {+ return counts.problemCount ?? counts.problems?.length ?? 0;}/**@@ -67,6 +85,18 @@ export function bulkActionTitle()} skipped, ${count.format(counts.failed)} failed`;}+/** The notification body's lines for the rows that failed or need a fix. */+export function bulkActionProblemsBody(+ counts: TableBulkActionCounts+): string | undefined {+ const problems = counts.problems ?? [];+ if (problems.length === 0) return undefined;+ const more = countProblems(counts) - problems.length;+ return more > 0+ ? [...problems, `and ${count.format(more)} more`].join("\n")+ : problems.join("\n");+}+/** The notification body when the run stopped at its row limit. */export function bulkActionTruncatedBody(maxRows: number): string {return `The list has more than ${count.format(maxRows)} rows. Only the first ${count.format(diff --git a/packages/jobs/src/table-jobs/handlers.ts b/packages/jobs/src/table-jobs/handlers.tsindex bc2ce15b5a..5ecb7b9be5 100644--- a/packages/jobs/src/table-jobs/handlers.ts+++ b/packages/jobs/src/table-jobs/handlers.ts@@ -83,6 +83,10 @@ export type TableBulkActionCounts = {done: number;skipped: number;failed: number;+ /** A line per row that failed, or that is done with something left to fix+ * ("J000123: …"). At most `MAX_BULK_PROBLEMS`; `problemCount` counts all. */+ problems?: string[];+ problemCount?: number;};/** JSON an action hands from one chunk of a run to the next. It goes through