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: add keyboard wedge shortcut for completing operations without a page reload

Brad Barbin6b3125b437bb
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 7aaee1990b..863feae28b 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -37,7 +37,7 @@ import {
getUserDefaults,
getUserGroups,
} from "~/modules/users/users.server";
-import { path } from "~/utils/path";
+import { ERP_URL, MES_URL, path } from "~/utils/path";
import { getSavedViews } from "~/modules/shared/shared.service";
@@ -141,7 +141,7 @@ export default function AuthenticatedRoute() {
useNProgress();
useKeyboardWedge({
- test: (input) => input.startsWith("http"),
+ test: (input) => input.startsWith(MES_URL) || input.startsWith(ERP_URL),
callback: (input) => {
try {
const url = new URL(input);
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 58f819a93d..0bc5c49419 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1,11 +1,12 @@
-import { getMESUrl, SUPABASE_URL } from "@carbon/auth";
+import { getAppUrl, getMESUrl, SUPABASE_URL } from "@carbon/auth";
import { generatePath } from "@remix-run/react";
const x = "/x"; // from ~/routes/x+ folder
const api = "/api"; // from ~/routes/api+ folder
const file = "/file"; // from ~/routes/file+ folder
const onboarding = "/onboarding"; // from ~/routes/onboarding+ folder
-const mes = getMESUrl();
+export const MES_URL = getMESUrl();
+export const ERP_URL = getAppUrl();
export const path = {
to: {
@@ -158,11 +159,11 @@ export const path = {
shippingMethods: `${api}/inventory/shipping-methods`,
},
external: {
- mes: mes,
- mesJobOperation: (id: string) => `${mes}/x/operation/${id}`,
+ mes: MES_URL,
+ mesJobOperation: (id: string) => `${MES_URL}/x/operation/${id}`,
mesJobOperationStart: (id: string, type: "Setup" | "Labor" | "Machine") =>
- `${mes}/x/start/${id}?type=${type}`,
- mesJobOperationComplete: (id: string) => `${mes}/x/end/${id}`,
+ `${MES_URL}/x/start/${id}?type=${type}`,
+ mesJobOperationComplete: (id: string) => `${MES_URL}/x/end/${id}`,
},
file: {
cadModel: (id: string) => generatePath(`${file}/model/${id}`),
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 42bb69b470..94e52699ab 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -127,7 +127,7 @@ import {
TextArea,
ValidatedForm,
} from "@carbon/form";
-import { useMode } from "@carbon/remix";
+import { useKeyboardWedge, useMode } from "@carbon/remix";
import type { TrackedEntityAttributes } from "@carbon/utils";
import {
convertDateStringToIsoString,
@@ -370,6 +370,14 @@ export const JobOperation = ({
}
};
+ const completeFetcher = useFetcher<{}>();
+ useKeyboardWedge({
+ test: (input) => input === "x",
+ callback: () => {
+ completeFetcher.load(path.to.endOperation(operation.id));
+ },
+ });
+
return (
<>
<Tabs
@@ -524,13 +532,17 @@ export const JobOperation = ({
</div>
</HStack>
<div className="flex flex-col flex-shrink items-end">
- {parentIsSerial ? (
- <Heading size="h2">
- {serialIndex + 1} of {operation.operationQuantity}
- </Heading>
- ) : (
- <Heading size="h2">{operation.operationQuantity}</Heading>
- )}
+ <Heading size="h2">
+ {formatDurationMilliseconds(
+ ((progress.setup ?? 0) +
+ (progress.labor ?? 0) +
+ (progress.machine ?? 0)) /
+ Math.max(operation.quantityComplete, 1),
+ {
+ style: "short",
+ }
+ )}
+ </Heading>
<p className="text-muted-foreground line-clamp-1">
{operation.itemUnitOfMeasure}
</p>
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index 00d6a77922..eaba80a218 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -191,7 +191,7 @@ export default function App() {
if (result?.flash) {
flashOverlay.flash(result.flash);
}
- }, [result?.flash]);
+ }, [result]);
/* Dark/Light Mode */
const mode = useMode();
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index 24f01b4b07..f5b0c1baf8 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -31,7 +31,7 @@ import {
getActiveJobCount,
getLocationsByCompany,
} from "~/services/operations.service";
-import { path } from "~/utils/path";
+import { ERP_URL, MES_URL, path } from "~/utils/path";
export const config = {
runtime: "nodejs",
@@ -135,7 +135,9 @@ export default function AuthenticatedRoute() {
useNProgress();
useKeyboardWedge({
- test: (input) => input.startsWith("http"),
+ test: (input) =>
+ (input.startsWith(MES_URL) || input.startsWith(ERP_URL)) &&
+ !input.includes("/kanban/complete/"), // we handle this more gracefully in JobOperation
callback: (input) => {
try {
const url = new URL(input);
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
index 8c11b389d3..5860c05e8f 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -49,10 +49,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (jobOperation.error || !jobOperation.data) {
return json(
{},
- await flash(
- request,
- error(jobOperation.error, "Failed to fetch job operation")
- )
+ await flash(request, {
+ ...error(jobOperation.error, "Failed to fetch job operation"),
+ flash: "error",
+ })
);
}
@@ -86,16 +86,19 @@ export async function action({ request }: ActionFunctionArgs) {
if (finishOperation.error) {
return json(
{},
- await flash(
- request,
- error(finishOperation.error, "Failed to finish operation")
- )
+ await flash(request, {
+ ...error(finishOperation.error, "Failed to finish operation"),
+ flash: "error",
+ })
);
}
throw redirect(
path.to.operations,
- await flash(request, success("Operation finished successfully"))
+ await flash(request, {
+ ...success("Operation finished successfully"),
+ flash: "success",
+ })
);
}
@@ -123,10 +126,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (response.error) {
return json(
{},
- await flash(
- request,
- error(response.error, "Failed to complete job operation")
- )
+ await flash(request, {
+ ...error(response.error, "Failed to complete job operation"),
+ flash: "error",
+ })
);
}
@@ -139,16 +142,19 @@ export async function action({ request }: ActionFunctionArgs) {
if (finishOperation.error) {
return json(
{},
- await flash(
- request,
- error(finishOperation.error, "Failed to finish operation")
- )
+ await flash(request, {
+ ...error(finishOperation.error, "Failed to finish operation"),
+ flash: "error",
+ })
);
}
throw redirect(
path.to.operations,
- await flash(request, success("Operation finished successfully"))
+ await flash(request, {
+ ...success("Operation finished successfully"),
+ flash: "success",
+ })
);
}
@@ -164,10 +170,13 @@ export async function action({ request }: ActionFunctionArgs) {
if (insertProduction.error) {
return json(
{},
- await flash(
- request,
- error(insertProduction.error, "Failed to record production quantity")
- )
+ await flash(request, {
+ ...error(
+ insertProduction.error,
+ "Failed to record production quantity"
+ ),
+ flash: "error",
+ })
);
}
@@ -185,7 +194,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (issue.error) {
throw json(
insertProduction.data,
- await flash(request, error(issue.error, "Failed to issue materials"))
+ await flash(request, {
+ ...error(issue.error, "Failed to issue materials"),
+ flash: "error",
+ })
);
}
@@ -198,16 +210,19 @@ export async function action({ request }: ActionFunctionArgs) {
if (finishOperation.error) {
return json(
{},
- await flash(
- request,
- error(finishOperation.error, "Failed to finish operation")
- )
+ await flash(request, {
+ ...error(finishOperation.error, "Failed to finish operation"),
+ flash: "error",
+ })
);
}
throw redirect(
path.to.operations,
- await flash(request, success("Operation finished successfully"))
+ await flash(request, {
+ ...success("Operation finished successfully"),
+ flash: "success",
+ })
);
}
diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsx
index aea93edba4..f46bd23808 100644
--- a/apps/mes/app/routes/x+/end.$operationId.tsx
+++ b/apps/mes/app/routes/x+/end.$operationId.tsx
@@ -41,20 +41,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
) {
throw redirect(
path.to.operations,
- await flash(
- request,
- error(jobOperation.error, "Failed to fetch job operation")
- )
+ await flash(request, {
+ ...error(jobOperation.error, "Failed to fetch job operation"),
+ flash: "error",
+ })
);
}
if (jobOperation.data?.companyId !== companyId) {
throw redirect(
path.to.operations,
- await flash(
- request,
- error("You are not authorized to start this operation", "Unauthorized")
- )
+ await flash(request, {
+ ...error(
+ "You are not authorized to start this operation",
+ "Unauthorized"
+ ),
+ flash: "error",
+ })
);
}
const completeAll = jobOperation.data?.completeAllOnScan ?? false;
@@ -150,7 +153,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw redirect(
path.to.operations,
- await flash(request, success("Operation finished successfully"))
+ await flash(request, {
+ ...success("Operation finished successfully"),
+ flash: "success",
+ })
);
}
} else if (jobMakeMethod.data.requiresBatchTracking) {
@@ -171,10 +177,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (response.error) {
throw redirect(
path.to.operation(operationId),
- await flash(
- request,
- error(response.error, "Failed to complete job operation")
- )
+ await flash(request, {
+ ...error(response.error, "Failed to complete job operation"),
+ flash: "error",
+ })
);
}
}
@@ -190,13 +196,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (insertProduction.error) {
throw redirect(
path.to.operation(operationId),
- await flash(
- request,
- error(
+ await flash(request, {
+ ...error(
insertProduction.error,
"Failed to record production quantity"
- )
- )
+ ),
+ flash: "error",
+ })
);
}
@@ -214,7 +220,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (issue.error) {
throw redirect(
path.to.operation(operationId),
- await flash(request, error(issue.error, "Failed to issue materials"))
+ await flash(request, {
+ ...error(issue.error, "Failed to issue materials"),
+ flash: "error",
+ })
);
}
}
@@ -229,16 +238,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (finishOperation.error) {
throw redirect(
path.to.operation(operationId),
- await flash(
- request,
- error(finishOperation.error, "Failed to finish operation")
- )
+ await flash(request, {
+ ...error(finishOperation.error, "Failed to finish operation"),
+ flash: "error",
+ })
);
}
throw redirect(
path.to.operations,
- await flash(request, success("Operation finished successfully"))
+ await flash(request, {
+ ...success("Operation finished successfully"),
+ flash: "success",
+ })
);
}
diff --git a/apps/mes/app/routes/x+/scrap.tsx b/apps/mes/app/routes/x+/scrap.tsx
index 07f37da0cf..540505fe2f 100644
--- a/apps/mes/app/routes/x+/scrap.tsx
+++ b/apps/mes/app/routes/x+/scrap.tsx
@@ -62,9 +62,6 @@ export async function action({ request }: ActionFunctionArgs) {
return json(
insertScrap.data,
- await flash(request, {
- ...success("Scrap quantity recorded successfully"),
- flash: "error",
- })
+ await flash(request, success("Scrap quantity recorded successfully"))
);
}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 31f529a62a..d2348c3236 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -1,7 +1,8 @@
-import { getAppUrl, SUPABASE_URL } from "@carbon/auth";
+import { getAppUrl, getMESUrl, SUPABASE_URL } from "@carbon/auth";
import { generatePath } from "@remix-run/react";
export const ERP_URL = getAppUrl();
+export const MES_URL = getMESUrl();
const x = "/x";
const api = "/api";
@@ -67,6 +68,7 @@ export const path = {
generatePath(`${x}/company/switch/${companyId}`),
complete: `${x}/complete`,
endShift: `${x}/end-shift`,
+ endOperation: (id: string) => generatePath(`${x}/end/${id}`),
feedback: `${x}/feedback`,
finish: `${x}/finish`,
@@ -91,6 +93,7 @@ export const path = {
root: "/",
scrap: `${x}/scrap`,
scrapReasons: `${api}/scrap-reasons`,
+ startOperation: (id: string) => generatePath(`${x}/start/${id}`),
switchCompany: (companyId: string) =>
generatePath(`${x}/company/switch/${companyId}`),
unconsume: `${x}/unconsume`,
diff --git a/llm/cache/clientAction-patterns.md b/llm/cache/clientAction-patterns.md
index b66a804977..58c545ef5f 100644
--- a/llm/cache/clientAction-patterns.md
+++ b/llm/cache/clientAction-patterns.md
@@ -1,12 +1,14 @@
# ClientAction Implementation Patterns
## Overview
+
ClientAction is a Remix feature used to handle client-side operations before calling the server action. In this codebase, it's primarily used for cache invalidation with React Query.
## Common Patterns
### 1. Cache Invalidation with Predicate (Delete Operations)
-**File**: `/Users/barbinbrad/Code/carbon/apps/erp/app/routes/x+/inventory+/shelves.delete.$shelfId.tsx`
+
+**File**: `carbon/apps/erp/app/routes/x+/inventory+/shelves.delete.$shelfId.tsx`
```typescript
export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
@@ -24,7 +26,8 @@ export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
```
### 2. Setting Query Data to Null (Update Operations)
-**File**: `/Users/barbinbrad/Code/carbon/apps/erp/app/routes/x+/resources+/work-centers.$id.tsx`
+
+**File**: `carbon/apps/erp/app/routes/x+/resources+/work-centers.$id.tsx`
```typescript
export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
@@ -37,7 +40,8 @@ export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
```
### 3. Setting Query Data to Null (Create Operations)
-**File**: `/Users/barbinbrad/Code/carbon/apps/erp/app/routes/x+/items+/uom.new.tsx`
+
+**File**: `carbon/apps/erp/app/routes/x+/items+/uom.new.tsx`
```typescript
export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
@@ -48,7 +52,8 @@ export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
```
### 4. Conditional Cache Updates Based on Form Data
-**File**: `/Users/barbinbrad/Code/carbon/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsx`
+
+**File**: `carbon/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsx`
```typescript
export async function clientAction({
@@ -87,7 +92,8 @@ export async function clientAction({
6. **Company scoping**: Most queries are scoped by company ID using `getCompanyId()`
## Import Requirements
+
```typescript
import type { ClientActionFunctionArgs } from "@remix-run/react";
import { getCompanyId } from "~/utils/react-query";
-```
\ No newline at end of file
+```
diff --git a/llm/cache/flash-system.md b/llm/cache/flash-system.md
new file mode 100644
index 0000000000..9cb9f9b708
--- /dev/null
+++ b/llm/cache/flash-system.md
@@ -0,0 +1,444 @@
+# Session Flash Message System
+
+## Overview
+
+Carbon uses a session-based flash message system to display success/error notifications to users. The system consists of three main components:
+
+1. Server-side flash session management
+2. Toast notifications for general feedback
+3. Flash overlay for MES-specific visual feedback
+
+## Core Implementation
+
+### 1. Flash Type Definition
+
+**Location:** `carbon/packages/auth/src/types.ts`
+
+```typescript
+export type Result = {
+ success: boolean;
+ message?: string;
+ flash?: "success" | "error";
+};
+```
+
+The `Result` type has three properties:
+
+- `success`: Boolean indicating operation success/failure
+- `message`: Optional message to display to user
+- `flash`: Optional visual flash effect (only used in MES app)
+
+### 2. Server-Side Flash Functions
+
+**Location:** `carbon/packages/auth/src/services/session.server.ts`
+
+#### Setting Flash Messages
+
+```typescript
+export async function flash(request: Request, result: Result) {
+ const session = await getSession(request);
+ if (typeof result.success === "boolean") {
+ session.flash("success", result.success);
+ session.flash("message", result.message);
+ if (result.flash) {
+ session.flash("flash", result.flash);
+ }
+ }
+
+ return {
+ headers: { "Set-Cookie": await sessionStorage.commitSession(session) },
+ };
+}
+```
+
+**How it works:**
+
+1. Retrieves the current session from the request
+2. Uses Remix's `session.flash()` to store temporary data that will be cleared after being read once
+3. Stores three pieces of data: `success` (boolean), `message` (string), and optionally `flash` (visual effect type)
+4. Returns headers to commit the session cookie
+
+#### Reading Flash Messages
+
+```typescript
+export async function getSessionFlash(request: Request) {
+ const session = await getSession(request);
+
+ const result: Result = {
+ success: session.get("success") === true,
+ message: session.get("message"),
+ flash: session.get("flash") as "success" | "error" | undefined,
+ };
+
+ if (!result.message) return null;
+
+ const headers = { "Set-Cookie": await sessionStorage.commitSession(session) };
+
+ return { result, headers };
+}
+```
+
+**How it works:**
+
+1. Reads flash data from the session
+2. Returns null if there's no message (prevents empty flashes)
+3. Commits the session, which clears the flash data (single-use nature)
+4. Returns both the result and headers
+
+### 3. Helper Functions
+
+**Location:** `carbon/packages/auth/src/utils/result.ts`
+
+```typescript
+export function error(error: any, message = "Request failed"): Result {
+ if (error) console.error({ error, message });
+ return {
+ success: false,
+ message: message,
+ };
+}
+
+export function success(message = "Request succeeded", data?: any): Result {
+ return {
+ success: true,
+ message,
+ };
+}
+```
+
+These utility functions create properly formatted `Result` objects:
+
+- `error()`: Creates a failure result, logs the error to console
+- `success()`: Creates a success result
+
+## Usage Patterns
+
+### Pattern 1: Flash with Redirect (Most Common)
+
+```typescript
+export async function action({ request }: ActionFunctionArgs) {
+ // ... perform operation
+
+ if (operationFailed) {
+ return json(
+ {},
+ await flash(request, error(operationError, "Operation failed"))
+ );
+ }
+
+ // Redirect with success flash
+ throw redirect(
+ "/destination",
+ await flash(request, success("Operation succeeded"))
+ );
+}
+```
+
+**Key points:**
+
+- Use `throw redirect()` with flash headers to redirect and show message
+- The flash headers must be included in the redirect response
+
+### Pattern 2: Flash with JSON Response
+
+```typescript
+export async function action({ request }: ActionFunctionArgs) {
+ // ... perform operation
+
+ return json(
+ operationData,
+ await flash(request, {
+ ...success("Operation succeeded"),
+ flash: "success", // Optional: adds visual flash effect
+ })
+ );
+}
+```
+
+**Key points:**
+
+- Use `json()` to return data along with flash
+- Can optionally add `flash: "success"` or `flash: "error"` for visual effects (MES only)
+
+### Pattern 3: Flash with Visual Overlay (MES App Only)
+
+```typescript
+return json(
+ data,
+ await flash(request, {
+ ...success("Production quantity recorded"),
+ flash: "success", // Triggers green flash overlay
+ })
+);
+
+// Or for errors:
+return json(
+ data,
+ await flash(request, {
+ ...error(err, "Operation failed"),
+ flash: "error", // Triggers red flash overlay
+ })
+);
+```
+
+## Client-Side Display
+
+### 1. Root Loader Pattern
+
+All apps must retrieve flash messages in their root loader:
+
+```typescript
+export async function loader({ request }: LoaderFunctionArgs) {
+ const sessionFlash = await getSessionFlash(request);
+
+ return json(
+ {
+ // ... other data
+ result: sessionFlash?.result,
+ },
+ {
+ headers: sessionFlash?.headers, // CRITICAL: Must return headers
+ }
+ );
+}
+```
+
+**IMPORTANT:** Always return the `sessionFlash.headers` in the loader response. This commits the session and ensures the flash data is cleared after being read.
+
+### 2. Toast Notifications (Standard Display)
+
+**Location:** Root component of any app (e.g., `carbon/apps/mes/app/root.tsx`)
+
+```typescript
+export default function App() {
+ const loaderData = useLoaderData<typeof loader>();
+ const result = loaderData?.result;
+
+ /* Toast Messages */
+ useEffect(() => {
+ if (result?.success === true) {
+ toast.success(result.message);
+ } else if (result?.message) {
+ toast.error(result.message);
+ }
+ }, [result]);
+
+ return (
+ <Document>
+ <Outlet />
+ <Toaster position="bottom-right" visibleToasts={5} />
+ </Document>
+ );
+}
+```
+
+**How it works:**
+
+1. Effect runs when `result` changes
+2. Shows success toast if `result.success === true`
+3. Shows error toast if there's a message (and not success)
+4. `<Toaster>` component renders the toast notifications
+
+### 3. Flash Overlay (MES App Only)
+
+**Location:** `carbon/apps/mes/app/components/FlashOverlay.tsx`
+
+The MES app includes a visual flash overlay for tactile feedback:
+
+```typescript
+export default function App() {
+ const loaderData = useLoaderData<typeof loader>();
+ const result = loaderData?.result;
+
+ /* Flash Overlay */
+ useEffect(() => {
+ if (result?.flash) {
+ flashOverlay.flash(result.flash);
+ }
+ }, [result?.flash]);
+
+ return (
+ <Document>
+ <Outlet />
+ <FlashOverlay />
+ </Document>
+ );
+}
+```
+
+**Flash Overlay Features:**
+
+- Green radial gradient for success
+- Red radial gradient for error
+- Plays victory sound on success (`/victory.mp3`)
+- Auto-dismisses after 300ms
+- Uses pub/sub pattern via `FlashOverlayManager`
+
+## Common Issues and Solutions
+
+### Issue 1: Flash Message Not Displaying
+
+**Symptoms:** Action completes but no toast appears
+
+**Common Causes:**
+
+1. Missing headers in root loader response
+
+ ```typescript
+ // ❌ WRONG
+ return json({ result: sessionFlash?.result });
+
+ // ✅ CORRECT
+ return json(
+ { result: sessionFlash?.result },
+ { headers: sessionFlash?.headers }
+ );
+ ```
+
+2. Not using `throw redirect()` with flash
+
+ ```typescript
+ // ❌ WRONG
+ redirect("/path", await flash(request, success("Done")));
+
+ // ✅ CORRECT
+ throw redirect("/path", await flash(request, success("Done")));
+ ```
+
+3. Missing root loader flash retrieval
+
+ ```typescript
+ // ❌ WRONG - No getSessionFlash call
+ export async function loader({ request }: LoaderFunctionArgs) {
+ return json({});
+ }
+
+ // ✅ CORRECT
+ export async function loader({ request }: LoaderFunctionArgs) {
+ const sessionFlash = await getSessionFlash(request);
+ return json(
+ { result: sessionFlash?.result },
+ { headers: sessionFlash?.headers }
+ );
+ }
+ ```
+
+### Issue 2: Flash Shows on Wrong Page
+
+**Symptom:** Message appears on different page than expected
+
+**Cause:** Flash messages persist across redirects until displayed. If the root loader doesn't properly consume them, they can leak to subsequent pages.
+
+**Solution:** Always ensure root loader gets and returns flash headers to clear them.
+
+### Issue 3: Multiple Flash Messages
+
+**Symptom:** Multiple toasts appear for single action
+
+**Cause:** Using both `json()` and `redirect()` with flash, or multiple flash calls
+
+**Solution:** Use flash only once per action:
+
+```typescript
+// ❌ WRONG
+await flash(request, success("Part 1"));
+await flash(request, success("Part 2"));
+
+// ✅ CORRECT
+await flash(request, success("Operation completed"));
+```
+
+### Issue 4: Flash Overlay Not Working (MES)
+
+**Symptom:** Toast shows but no visual flash
+
+**Cause:** Missing `flash` property in result
+
+**Solution:**
+
+```typescript
+// ❌ WRONG
+await flash(request, success("Done"));
+
+// ✅ CORRECT (for visual flash)
+await flash(request, {
+ ...success("Done"),
+ flash: "success",
+});
+```
+
+## Best Practices
+
+1. **Always include message**: Even for redirects, include a meaningful message
+
+ ```typescript
+ throw redirect(path.to.list, await flash(request, success("Item created")));
+ ```
+
+2. **Use helper functions**: Always use `success()` and `error()` helpers
+
+ ```typescript
+ // ✅ GOOD
+ await flash(request, success("Saved"));
+
+ // ❌ BAD
+ await flash(request, { success: true, message: "Saved" });
+ ```
+
+3. **Return headers properly**: For JSON responses, return as second argument
+
+ ```typescript
+ return json(data, await flash(request, result));
+ ```
+
+4. **Use visual flash sparingly**: Only use `flash: "success"/"error"` for important MES operations
+
+ ```typescript
+ // Use for: completing production, scrapping items
+ flash: "success";
+
+ // Don't use for: form saves, minor updates
+ ```
+
+5. **Handle errors consistently**: Always show error messages
+ ```typescript
+ if (result.error) {
+ return json(
+ {},
+ await flash(request, error(result.error, "Failed to save"))
+ );
+ }
+ ```
+
+## Implementation Checklist
+
+When adding flash messages to a new app:
+
+- [ ] Import `getSessionFlash` in root loader
+- [ ] Call `getSessionFlash(request)` in root loader
+- [ ] Return `sessionFlash?.result` in loader data
+- [ ] Return `sessionFlash?.headers` in loader headers
+- [ ] Add `useEffect` to display toasts based on `result`
+- [ ] Include `<Toaster>` component in Document
+- [ ] (Optional - MES) Add flash overlay for visual feedback
+- [ ] Test both success and error scenarios
+- [ ] Verify flash clears after display (doesn't persist)
+
+## Related Files
+
+**Core Flash System:**
+
+- `carbon/packages/auth/src/types.ts` - Type definitions
+- `carbon/packages/auth/src/services/session.server.ts` - Flash functions
+- `carbon/packages/auth/src/utils/result.ts` - Helper functions
+
+**Example Implementations:**
+
+- `carbon/apps/mes/app/root.tsx` - MES app with overlay
+- `carbon/apps/mes/app/routes/x+/complete.tsx` - Action with flash
+- `carbon/apps/mes/app/components/FlashOverlay.tsx` - Visual overlay component
+
+**Other Patterns:**
+
+- `carbon/llm/cache/shipments-receipts-ui-patterns.md` - Mentions flash for errors
+- `carbon/llm/cache/clientAction-patterns.md` - Client-side validation with flash
diff --git a/llm/cache/pdf-generation-patterns.md b/llm/cache/pdf-generation-patterns.md
index 99bcb44124..edaed4681d 100644
--- a/llm/cache/pdf-generation-patterns.md
+++ b/llm/cache/pdf-generation-patterns.md
@@ -8,9 +8,9 @@ The Carbon codebase uses React PDF for generating PDFs with asynchronous pattern
### Core Components
-- **PackingSlipPDF** (`/Users/barbinbrad/Code/carbon/packages/documents/src/pdf/PackingSlipPDF.tsx`)
-- **ProductLabelPDF** (`/Users/barbinbrad/Code/carbon/packages/documents/src/pdf/ProductLabelPDF.tsx`)
-- **JobTravelerPDF** (`/Users/barbinbrad/Code/carbon/packages/documents/src/pdf/JobTravelerPDF.tsx`)
+- **PackingSlipPDF** (`carbon/packages/documents/src/pdf/PackingSlipPDF.tsx`)
+- **ProductLabelPDF** (`carbon/packages/documents/src/pdf/ProductLabelPDF.tsx`)
+- **JobTravelerPDF** (`carbon/packages/documents/src/pdf/JobTravelerPDF.tsx`)
## Async Patterns
@@ -18,7 +18,7 @@ The Carbon codebase uses React PDF for generating PDFs with asynchronous pattern
All QR code generation is asynchronous using the `bwip-js/node` library:
-#### QR Code Utility (`/Users/barbinbrad/Code/carbon/packages/documents/src/qr/qr-code.ts`)
+#### QR Code Utility (`carbon/packages/documents/src/qr/qr-code.ts`)
```typescript
export async function generateQRCode(
diff --git a/llm/cache/realtime-service.md b/llm/cache/realtime-service.md
index f8eab74df2..80f33a99f0 100644
--- a/llm/cache/realtime-service.md
+++ b/llm/cache/realtime-service.md
@@ -28,6 +28,7 @@ carbon.realtime.setAuth(accessToken);
```
**Important**:
+
- `carbon.realtime.setAuth(accessToken)` must be called before subscribing to channels
- The access token is obtained from the `useCarbon()` hook
- The token should be updated whenever it changes (on refresh)
@@ -49,6 +50,7 @@ useRealtime("salesOrder", `status=eq.released`);
```
**How it works:**
+
1. Sets authentication using `carbon.realtime.setAuth(accessToken)`
2. Creates a channel with unique name: `postgres_changes:${table}`
3. Listens for all database events (`*`) on the specified table
@@ -63,6 +65,7 @@ Located at: `/apps/erp/app/components/RealtimeDataProvider.tsx` and `/apps/mes/a
This provider manages realtime subscriptions for core lookup data (items, customers, suppliers, employees) and maintains them in Zustand stores with IndexedDB persistence.
**Features:**
+
- Hydrates data from IndexedDB first for instant UI
- Fetches fresh data from server on mount
- Subscribes to realtime changes for all core tables
@@ -90,31 +93,39 @@ const RealtimeDataProvider = ({ children }) => {
// Create channel with multiple table subscriptions
channelRef.current = carbon
.channel("realtime:core")
- .on("postgres_changes", {
- event: "*",
- schema: "public",
- table: "item",
- }, (payload) => {
- // Handle item changes
- switch (payload.eventType) {
- case "INSERT":
- // Add new item to store
- break;
- case "UPDATE":
- // Update item in store
- break;
- case "DELETE":
- // Remove item from store
- break;
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "item",
+ },
+ (payload) => {
+ // Handle item changes
+ switch (payload.eventType) {
+ case "INSERT":
+ // Add new item to store
+ break;
+ case "UPDATE":
+ // Update item in store
+ break;
+ case "DELETE":
+ // Remove item from store
+ break;
+ }
+ }
+ )
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "customer",
+ },
+ (payload) => {
+ // Handle customer changes
}
- })
- .on("postgres_changes", {
- event: "*",
- schema: "public",
- table: "customer",
- }, (payload) => {
- // Handle customer changes
- })
+ )
.subscribe();
return () => {
@@ -220,17 +231,20 @@ All realtime subscriptions should filter by companyId to ensure tenant isolation
### Common Issues
**Subscriptions not receiving events:**
+
- Ensure `carbon.realtime.setAuth(accessToken)` is called before subscribing
- Check that accessToken is defined and valid
- Verify RLS policies allow the user to SELECT the table
- Confirm the table has REPLICA IDENTITY FULL (for DELETE events)
**Multiple event firings:**
+
- Make sure channels are properly cleaned up in useEffect return
- Use `channelRef` to prevent creating duplicate channels
- Check dependency arrays in useEffect hooks
**Events from wrong company:**
+
- Always filter events by companyId in the event handler
- Don't rely solely on database filters for multi-tenant isolation
@@ -246,4 +260,5 @@ All realtime subscriptions should filter by companyId to ensure tenant isolation
## Database Patterns Documentation
For more details on database patterns including realtime subscriptions, see:
-- `/Users/barbinbrad/Code/carbon/llm/cache/database-patterns.md` (lines 127-144)
+
+- `carbon/llm/cache/database-patterns.md` (lines 127-144)
diff --git a/packages/remix/src/hooks/useKeyboardWedge.ts b/packages/remix/src/hooks/useKeyboardWedge.ts
index 52b2a23c0a..145c02617a 100644
--- a/packages/remix/src/hooks/useKeyboardWedge.ts
+++ b/packages/remix/src/hooks/useKeyboardWedge.ts
@@ -25,6 +25,7 @@ export function useKeyboardWedge(options?: UseKeyboardWedgeOptions) {
const test = options?.test ?? defaultTest;
const callback = options?.callback ?? defaultCallback;
const active = options?.active ?? true;
+ console.log(inputBuffer);
useEffect(() => {
if (!active) return;