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(pwa): offline page, app icon badge and installable ERP/MES

naveenkash8f626b13cb72
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 3fd6baca1a..1a253d3fee 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3356,7 +3356,7 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf
**Rule:** Never pass a reused `tag` to `showNotification` when the user must see the repeat. Close the older notifications yourself (`registration.getNotifications()`, match on `notification.data.tag`), then show the new one with no `tag`, so it gets a fresh identifier. To debug a push that "does not arrive", read the send's status code first, then the OS notification log, before changing code.
-**Applies to:** `apps/erp/public/push-worker.js`; any future service worker or Notification API caller.
+**Applies to:** `apps/erp/public/service-worker.js` (was `push-worker.js`); any future service worker or Notification API caller.
## A new key in an Inngest step's return breaks runs in flight at deploy
@@ -3377,7 +3377,7 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf
**Rule:** Call `matchAll({ type: "window" })` without `includeUncontrolled` when you will call `navigate()`. Focus first, because the click allows focus for a short time only. Wrap the focus and the navigation in `try`, and call `clients.openWindow()` when either fails or no tab exists.
-**Applies to:** `apps/erp/public/push-worker.js`; any service worker that navigates a client.
+**Applies to:** `apps/erp/public/service-worker.js` (was `push-worker.js`); any service worker that navigates a client.
## A push service's 401 or 403 does not mean the subscription is dead
diff --git a/apps/erp/app/components/Layout/Mobile/MobileDock.tsx b/apps/erp/app/components/Layout/Mobile/MobileDock.tsx
index ded61e6624..81920872cd 100644
--- a/apps/erp/app/components/Layout/Mobile/MobileDock.tsx
+++ b/apps/erp/app/components/Layout/Mobile/MobileDock.tsx
@@ -9,6 +9,7 @@ import { useEffect, useState } from "react";
import { LuMenu, LuPlus, LuSearch, LuX } from "react-icons/lu";
import { useLocation } from "react-router";
import { useUser } from "~/hooks";
+import { useAppBadge } from "~/hooks/useAppBadge";
import { useNotifications } from "~/hooks/useNotifications";
import { useRestoreBrowserNotifications } from "~/hooks/usePushSubscription";
import { useUIStore } from "~/stores/ui";
@@ -47,6 +48,7 @@ export function MobileDock() {
publicKey: usePushPublicKey(),
userId: user.id
});
+ useAppBadge({ userId: user.id });
const unread = notifications.notifications.filter((n) => !n.read).length;
const canCreate = useCreate().length > 0;
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
index 69a40d95be..eae929c562 100644
--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
@@ -61,6 +61,7 @@ import {
import { Link, useNavigate } from "react-router";
import { DateTime } from "~/components";
import { useNotifications, useUser } from "~/hooks";
+import { useAppBadge } from "~/hooks/useAppBadge";
import { useRestoreBrowserNotifications } from "~/hooks/usePushSubscription";
import { usePeople } from "~/stores";
import type { Notification as NotificationRecord } from "~/types";
@@ -926,6 +927,7 @@ const Notifications = () => {
// The bell is always mounted on desktop (the Profile sheet is on phones), so
// it is where a signed-back-in user's browser notifications come back.
useRestoreBrowserNotifications({ publicKey: usePushPublicKey(), userId });
+ useAppBadge({ userId });
const [isOpen, setOpen] = useState(false);
const [activeTab, setActiveTab] = useState("inbox");
const notificationsState = useNotifications({
diff --git a/apps/erp/app/entry.client.tsx b/apps/erp/app/entry.client.tsx
index 50109da1e6..2ab1986865 100644
--- a/apps/erp/app/entry.client.tsx
+++ b/apps/erp/app/entry.client.tsx
@@ -7,12 +7,14 @@ import {
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY
} from "@carbon/auth";
+import { getLogger } from "@carbon/logger";
import { ensureLoggingConfigured } from "@carbon/logger/config.client";
import posthog from "posthog-js";
import { startTransition } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
import { preloadCatalog } from "~/services/lingui";
+import { SERVICE_WORKER_URL } from "~/utils/service-worker";
ensureLoggingConfigured();
@@ -46,6 +48,23 @@ if (CONTROLLED_ENVIRONMENT && posthog.__loaded) {
);
}
+// Shows an offline page when a page load finds no network, and carries Web
+// Push (public/service-worker.js). Registered for everyone, not only when push
+// is on: the offline page is for every user. After the page has loaded, so
+// the worker's own download does not compete with the page's; this module can
+// run after "load" has fired (the dev server imports it late), so check first.
+if ("serviceWorker" in navigator) {
+ const register = () => {
+ navigator.serviceWorker
+ .register(SERVICE_WORKER_URL, { scope: "/" })
+ .catch((error) =>
+ getLogger("erp", "service-worker").warn("not registered", { error })
+ );
+ };
+ if (document.readyState === "complete") register();
+ else window.addEventListener("load", register, { once: true });
+}
+
// The catalog is no longer in loader data, so fetch the active language's
// chunk before hydrating — otherwise a non-en page hydrates against an empty
// catalog and mismatches the server markup.
diff --git a/apps/erp/app/hooks/useAppBadge.ts b/apps/erp/app/hooks/useAppBadge.ts
new file mode 100644
index 0000000000..74c2147ccc
--- /dev/null
+++ b/apps/erp/app/hooks/useAppBadge.ts
@@ -0,0 +1,81 @@
+// 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 { getLogger } from "@carbon/logger";
+import { useTopic } from "@carbon/query";
+import { useCarbon, useRouteData } from "@carbon/react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { path } from "~/utils/path";
+
+const logger = getLogger("erp", "useappbadge");
+
+// A bulk change (mark all read) broadcasts once per row; count once.
+const RECOUNT_DELAY_MS = 500;
+
+// Sets or clears the installed app's icon badge. Only an installed app shows
+// one; elsewhere the call is missing or does nothing.
+export function setAppBadge(count: number) {
+ if (typeof navigator === "undefined" || !("setAppBadge" in navigator)) {
+ return;
+ }
+ const result =
+ count > 0 ? navigator.setAppBadge(count) : navigator.clearAppBadge();
+ // Refused (Safari without notification permission): no badge is fine.
+ result.catch(() => undefined);
+}
+
+// The installed app's icon badge: the user's unread notifications in every
+// company they work in. The bell counts one company; the icon stands for the
+// whole app, and a push from any company sets it the same way (send-push
+// "count-unread"). Recounted whenever the user's notifications change — the
+// topic carries every company's rows.
+export function useAppBadge({ userId }: { userId: string }) {
+ const { carbon } = useCarbon();
+ const shell = useRouteData<{
+ companies: { companyId: string | null; role: string | null }[];
+ }>(path.to.authenticatedRoot);
+ // A string, so a revalidation that returns the same companies is no change.
+ const companyIds = useMemo(
+ () =>
+ (shell?.companies ?? [])
+ .flatMap((company) =>
+ company.role === "employee" && company.companyId
+ ? [company.companyId]
+ : []
+ )
+ .join(","),
+ [shell?.companies]
+ );
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const recount = useCallback(async () => {
+ if (!carbon || !companyIds) return;
+ const { count, error } = await carbon
+ .from("notification")
+ .select("id", { count: "exact", head: true })
+ .eq("userId", userId)
+ .in("companyId", companyIds.split(","))
+ .is("readAt", null)
+ .is("digestedInto", null);
+ if (error) {
+ logger.warn("Failed to count unread notifications for the badge", {
+ error
+ });
+ return;
+ }
+ setAppBadge(count ?? 0);
+ }, [carbon, companyIds, userId]);
+
+ useEffect(() => {
+ recount();
+ return () => {
+ if (timer.current) clearTimeout(timer.current);
+ };
+ }, [recount]);
+
+ useTopic(`user:${userId}:notification`, () => {
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(recount, RECOUNT_DELAY_MS);
+ });
+}
diff --git a/apps/erp/app/hooks/usePushSubscription.ts b/apps/erp/app/hooks/usePushSubscription.ts
index 4224aaba87..6f1bbb44af 100644
--- a/apps/erp/app/hooks/usePushSubscription.ts
+++ b/apps/erp/app/hooks/usePushSubscription.ts
@@ -15,11 +15,10 @@ import {
supportsPush,
urlBase64ToUint8Array
} from "~/utils/push";
+import { SERVICE_WORKER_URL } from "~/utils/service-worker";
const logger = getLogger("erp", "usepushsubscription");
-const WORKER_URL = "/push-worker.js";
-
export type PushState = "loading" | "unsupported" | "denied" | "off" | "on";
async function currentSubscription() {
@@ -56,7 +55,7 @@ function isEnabledOnServer(endpoint: string) {
// (subscribe() refuses a new key while it exists), and its endpoint comes
// back as replacedEndpoint so the server drops that row.
async function subscribe(publicKey: string) {
- await navigator.serviceWorker.register(WORKER_URL, { scope: "/" });
+ await navigator.serviceWorker.register(SERVICE_WORKER_URL, { scope: "/" });
const registration = await navigator.serviceWorker.ready;
const existing = await registration.pushManager.getSubscription();
let replacedEndpoint: string | null = null;
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index c9fb1c7c3f..5499f88f5e 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -68,6 +68,7 @@ import type {
MetaFunction
} from "react-router";
import { data, useFetcher, useLoaderData, useSearchParams } from "react-router";
+import { setAppBadge } from "~/hooks/useAppBadge";
import type { Result } from "~/types";
import { path } from "~/utils/path";
@@ -293,8 +294,10 @@ export async function action({ request }: ActionFunctionArgs) {
export default function LoginRoute() {
// A signed-out user lands here however the session ended (sign out, expiry,
- // a revoked account), so this is where the lists kept on the device go.
+ // a revoked account), so this is where the lists kept on the device go, and
+ // the app icon's unread badge with them.
useEffect(() => {
+ setAppBadge(0);
import("localforage")
.then((storage) => storage.default.clear())
.catch((error) =>
diff --git a/apps/erp/app/routes/api+/push-subscription.ts b/apps/erp/app/routes/api+/push-subscription.ts
index 387c5afc06..877338d986 100644
--- a/apps/erp/app/routes/api+/push-subscription.ts
+++ b/apps/erp/app/routes/api+/push-subscription.ts
@@ -64,7 +64,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
// This browser's Web Push subscription for the signed-in user.
-// PUT saves it (also from push-worker.js after a pushsubscriptionchange),
+// PUT saves it (also from service-worker.js after a pushsubscriptionchange),
// DELETE removes it.
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {});
diff --git a/apps/erp/app/utils/service-worker.ts b/apps/erp/app/utils/service-worker.ts
new file mode 100644
index 0000000000..ea0eea5372
--- /dev/null
+++ b/apps/erp/app/utils/service-worker.ts
@@ -0,0 +1,13 @@
+// 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.
+
+// Carbon's one service worker, at scope "/": the offline page and Web Push
+// (public/service-worker.js). Registered on every page load
+// (entry.client.tsx); subscribing to push reuses that registration.
+//
+// It was /push-worker.js until it took on the offline page. A browser keeps
+// one registration per scope and its push subscription with it, so
+// registering this URL at "/" swaps the script under an existing push
+// registration without losing the subscription.
+export const SERVICE_WORKER_URL = "/service-worker.js";
diff --git a/apps/erp/public/apple-touch-icon.png b/apps/erp/public/apple-touch-icon.png
index f63749a97c..2fdd26bca7 100644
Binary files a/apps/erp/public/apple-touch-icon.png and b/apps/erp/public/apple-touch-icon.png differ
diff --git a/apps/erp/public/icon-192.png b/apps/erp/public/icon-192.png
new file mode 100644
index 0000000000..1a89c615b1
Binary files /dev/null and b/apps/erp/public/icon-192.png differ
diff --git a/apps/erp/public/icon-512.png b/apps/erp/public/icon-512.png
new file mode 100644
index 0000000000..aa79060217
Binary files /dev/null and b/apps/erp/public/icon-512.png differ
diff --git a/apps/erp/public/icon-maskable-512.png b/apps/erp/public/icon-maskable-512.png
new file mode 100644
index 0000000000..ec10514d9f
Binary files /dev/null and b/apps/erp/public/icon-maskable-512.png differ
diff --git a/apps/erp/public/offline.html b/apps/erp/public/offline.html
new file mode 100644
index 0000000000..1f43e9ff74
--- /dev/null
+++ b/apps/erp/public/offline.html
@@ -0,0 +1,435 @@
+<!doctype html>
+<!-- Served by the service worker (public/service-worker.js)
+ when a page load fails for want of a network. Self-contained: nothing else
+ is reachable while offline. Each app has a copy in its public folder;
+ keep them the same. The workers save it when they install: bump the offline
+ cache version in both service-worker.js files after any change here. -->
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta
+ name="viewport"
+ content="width=device-width, initial-scale=1, viewport-fit=cover"
+ />
+ <title>Offline | Carbon</title>
+ <style>
+ :root {
+ color-scheme: light dark;
+ font-family:
+ ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ --fg: #09090b;
+ --muted: #71717a;
+ --line: #e4e4e7;
+ }
+ body {
+ margin: 0;
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ background: #fff;
+ color: var(--fg);
+ }
+ main {
+ width: 100%;
+ max-width: 22rem;
+ padding: 1.5rem;
+ box-sizing: border-box;
+ text-align: center;
+ }
+ main.playing {
+ max-width: 40rem;
+ }
+ h1 {
+ margin: 0 0 0.5rem;
+ font-size: 1.25rem;
+ font-weight: 600;
+ text-wrap: balance;
+ }
+ /* The text keeps its width when the game widens the page, and its
+ lines are balanced, so no word is left alone on the last line. */
+ p {
+ max-width: 19rem;
+ margin: 0 auto 1.5rem;
+ color: var(--muted);
+ line-height: 1.5;
+ text-wrap: balance;
+ }
+ .actions {
+ display: flex;
+ gap: 0.5rem;
+ justify-content: center;
+ }
+ button {
+ font: inherit;
+ font-weight: 500;
+ border: 0;
+ border-radius: 0.4375rem;
+ padding: 0.625rem 1.25rem;
+ background: var(--fg);
+ color: #fafafa;
+ cursor: pointer;
+ }
+ button.secondary {
+ background: transparent;
+ color: var(--fg);
+ box-shadow: inset 0 0 0 1px var(--line);
+ }
+ #game {
+ display: none;
+ margin-top: 1.5rem;
+ }
+ main.playing #game {
+ display: block;
+ }
+ main.playing #play {
+ display: none;
+ }
+ canvas {
+ display: block;
+ width: 100%;
+ aspect-ratio: 4 / 1;
+ border-radius: 0.4375rem;
+ box-shadow: inset 0 0 0 1px var(--line);
+ touch-action: manipulation;
+ cursor: pointer;
+ }
+ canvas:focus-visible {
+ outline: 2px solid var(--muted);
+ outline-offset: 2px;
+ }
+ .hint {
+ max-width: none;
+ margin: 0.5rem 0 0;
+ font-size: 0.8125rem;
+ }
+ /* Last, so it overrides the light rules above. */
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --fg: #fafafa;
+ --muted: #a1a1aa;
+ --line: #27272a;
+ }
+ body {
+ background: #09090b;
+ }
+ button {
+ color: #09090b;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <main id="main">
+ <h1>You're offline</h1>
+ <p>
+ This device lost its connection. Carbon reloads the page when the
+ connection is back.
+ </p>
+ <div class="actions">
+ <button type="button" id="retry">Try again</button>
+ <button type="button" id="play" class="secondary">
+ Play while you wait
+ </button>
+ </div>
+ <div id="game">
+ <canvas
+ id="canvas"
+ tabindex="0"
+ aria-label="Forklift game: press Space or tap to jump over the crates"
+ ></canvas>
+ <p class="hint">Space, ↑ or tap to jump</p>
+ </div>
+ </main>
+ <script>
+ document
+ .getElementById("retry")
+ .addEventListener("click", () => location.reload());
+ window.addEventListener("online", () => location.reload());
+
+ // "online" never fires when the device kept its network but Carbon
+ // could not be reached (the server, or the internet behind the Wi-Fi):
+ // ask Carbon itself every few seconds. offline.html is a static file, so
+ // the check costs the server nothing; the service workers pass it
+ // straight to the network.
+ // Not at its own address: there it is not standing in for a page, and
+ // the check would succeed and reload it forever.
+ setInterval(() => {
+ if (!navigator.onLine || location.pathname === "/offline.html") return;
+ fetch("/offline.html", { method: "HEAD", cache: "no-store" }).then(
+ () => location.reload(),
+ () => undefined
+ );
+ }, 10000);
+
+ // A forklift runner: jump the crates, pallets and cones on the shop
+ // floor. Opened from a button, so the page stays quiet until asked.
+ (() => {
+ const main = document.getElementById("main");
+ const canvas = document.getElementById("canvas");
+ const ctx = canvas.getContext("2d");
+ const W = 600;
+ const H = 150;
+ const GROUND = 128;
+ const GRAVITY = 1700;
+ const JUMP = 560;
+ const START_SPEED = 260;
+ const MAX_SPEED = 620;
+ const BEST_KEY = "carbon-offline-best";
+
+ // Fixed logical size, drawn at the screen's pixel density.
+ const ratio = window.devicePixelRatio || 1;
+ canvas.width = W * ratio;
+ canvas.height = H * ratio;
+ ctx.scale(ratio, ratio);
+
+ const readBest = () => {
+ try {
+ return Number(localStorage.getItem(BEST_KEY)) || 0;
+ } catch {
+ return 0;
+ }
+ };
+ const writeBest = (value) => {
+ try {
+ localStorage.setItem(BEST_KEY, String(value));
+ } catch {
+ // Private mode: the best score lasts this page only.
+ }
+ };
+
+ const player = { x: 48, y: GROUND, vy: 0, w: 34, h: 28 };
+ let state = "ready"; // ready | running | paused | over
+ let obstacles = [];
+ let speed = START_SPEED;
+ let distance = 0;
+ let nextGap = 0;
+ let floorOffset = 0;
+ let best = readBest();
+ let last = 0;
+ let frame = 0;
+
+ // Read once, and again when the light/dark mode changes.
+ const readColors = () => {
+ const style = getComputedStyle(document.documentElement);
+ return {
+ fg: style.getPropertyValue("--fg").trim(),
+ muted: style.getPropertyValue("--muted").trim(),
+ line: style.getPropertyValue("--line").trim()
+ };
+ };
+ let palette = readColors();
+
+ const reset = () => {
+ obstacles = [];
+ speed = START_SPEED;
+ distance = 0;
+ nextGap = 320;
+ player.y = GROUND;
+ player.vy = 0;
+ };
+
+ const spawn = () => {
+ const kind = Math.random();
+ if (kind < 0.45) {
+ const size = 18 + Math.random() * 10;
+ obstacles.push({ type: "crate", x: W, w: size, h: size });
+ } else if (kind < 0.75) {
+ obstacles.push({ type: "pallet", x: W, w: 38, h: 22 });
+ } else {
+ obstacles.push({ type: "cone", x: W, w: 16, h: 24 });
+ }
+ // Gaps grow with speed, so every gap stays jumpable.
+ nextGap = speed * (0.75 + Math.random() * 0.9) + 90;
+ };
+
+ const start = () => {
+ state = "running";
+ last = performance.now();
+ frame = requestAnimationFrame(loop);
+ };
+
+ const jump = () => {
+ if (state === "ready" || state === "over") {
+ reset();
+ start();
+ return;
+ }
+ if (state === "paused") {
+ start();
+ return;
+ }
+ if (player.y >= GROUND) player.vy = -JUMP;
+ };
+
+ const hits = (o) => {
+ // A little forgiveness: the boxes are drawn larger than they hit.
+ const pad = 4;
+ return (
+ player.x + pad < o.x + o.w &&
+ player.x + player.w - pad > o.x &&
+ player.y - pad > GROUND - o.h
+ );
+ };
+
+ const update = (dt) => {
+ speed = Math.min(MAX_SPEED, speed + 9 * dt);
+ distance += speed * dt;
+ floorOffset = (floorOffset + speed * dt) % 24;
+
+ player.vy += GRAVITY * dt;
+ player.y = Math.min(GROUND, player.y + player.vy * dt);
+ if (player.y === GROUND) player.vy = 0;
+
+ for (const o of obstacles) o.x -= speed * dt;
+ obstacles = obstacles.filter((o) => o.x + o.w > 0);
+ const lastObstacle = obstacles[obstacles.length - 1];
+ if (!lastObstacle || W - (lastObstacle.x + lastObstacle.w) > nextGap) {
+ spawn();
+ }
+
+ if (obstacles.some(hits)) {
+ state = "over";
+ const score = Math.floor(distance / 10);
+ if (score > best) {
+ best = score;
+ writeBest(best);
+ }
+ }
+ };
+
+ const drawForklift = (c) => {
+ const x = player.x;
+ const y = player.y;
+ ctx.fillStyle = c.fg;
+ ctx.strokeStyle = c.fg;
+ ctx.lineWidth = 2;
+ // Body and cab.
+ ctx.fillRect(x, y - 18, 22, 12);
+ ctx.strokeRect(x + 4, y - 28, 12, 10);
+ // Mast and forks, at the front.
+ ctx.fillRect(x + 24, y - 30, 3, 26);
+ ctx.fillRect(x + 27, y - 6, 9, 2);
+ // Wheels.
+ ctx.beginPath();
+ ctx.arc(x + 5, y - 3, 3.5, 0, Math.PI * 2);
+ ctx.arc(x + 19, y - 3, 3.5, 0, Math.PI * 2);
+ ctx.fill();
+ };
+
+ const drawObstacle = (o, c) => {
+ const top = GROUND - o.h;
+ ctx.strokeStyle = c.muted;
+ ctx.fillStyle = c.muted;
+ ctx.lineWidth = 2;
+ if (o.type === "crate") {
+ ctx.strokeRect(o.x + 1, top + 1, o.w - 2, o.h - 2);
+ ctx.beginPath();
+ ctx.moveTo(o.x + 1, top + 1);
+ ctx.lineTo(o.x + o.w - 1, GROUND - 1);
+ ctx.stroke();
+ } else if (o.type === "pallet") {
+ ctx.fillRect(o.x, top, o.w, 10);
+ ctx.fillRect(o.x, GROUND - 4, o.w, 4);
+ ctx.fillRect(o.x + 2, top + 10, 5, 8);
+ ctx.fillRect(o.x + o.w / 2 - 2.5, top + 10, 5, 8);
+ ctx.fillRect(o.x + o.w - 7, top + 10, 5, 8);
+ } else {
+ ctx.beginPath();
+ ctx.moveTo(o.x + o.w / 2, top);
+ ctx.lineTo(o.x + o.w, GROUND);
+ ctx.lineTo(o.x, GROUND);
+ ctx.closePath();
+ ctx.fill();
+ }
+ };
+
+ const drawText = (text, y, c, size) => {
+ ctx.fillStyle = c;
+ ctx.font = `500 ${size}px ui-sans-serif, system-ui, sans-serif`;
+ ctx.textAlign = "center";
+ ctx.fillText(text, W / 2, y);
+ };
+
+ const draw = () => {
+ const c = palette;
+ ctx.clearRect(0, 0, W, H);
+
+ // Floor, with lane markings moving past.
+ ctx.fillStyle = c.line;
+ ctx.fillRect(0, GROUND, W, 2);
+ ctx.fillStyle = c.muted;
+ for (let x = -floorOffset; x < W; x += 24) {
+ ctx.fillRect(x, GROUND + 9, 10, 2);
+ }
+
+ for (const o of obstacles) drawObstacle(o, c);
+ drawForklift(c);
+
+ // Score, top right.
+ ctx.fillStyle = c.muted;
+ ctx.font = "500 12px ui-monospace, SFMono-Regular, monospace";
+ ctx.textAlign = "right";
+ const score = String(Math.floor(distance / 10)).padStart(5, "0");
+ const bestText = best ? `BEST ${String(best).padStart(5, "0")} ` : "";
+ ctx.fillText(`${bestText}${score} m`, W - 12, 22);
+
+ if (state === "ready") {
+ drawText("Press Space or tap to start", 64, c.fg, 15);
+ } else if (state === "paused") {
+ drawText("Paused", 56, c.fg, 15);
+ drawText("Press Space or tap to carry on", 78, c.muted, 13);
+ } else if (state === "over") {
+ drawText("Crashed into the stock", 56, c.fg, 15);
+ drawText("Press Space or tap to go again", 78, c.muted, 13);
+ }
+ };
+
+ const loop = (now) => {
+ if (state !== "running") return;
+ // Capped, so a frame after a stall does not leap through a crate.
+ const dt = Math.min((now - last) / 1000, 1 / 30);
+ last = now;
+ update(dt);
+ draw();
+ if (state === "running") frame = requestAnimationFrame(loop);
+ };
+
+ canvas.addEventListener("keydown", (event) => {
+ if (event.code === "Space" || event.code === "ArrowUp") {
+ event.preventDefault();
+ jump();
+ }
+ });
+ canvas.addEventListener("pointerdown", (event) => {
+ event.preventDefault();
+ canvas.focus();
+ jump();
+ });
+
+ // Hidden tab: stop, and wait for a key or tap to carry on.
+ document.addEventListener("visibilitychange", () => {
+ if (document.hidden && state === "running") {
+ cancelAnimationFrame(frame);
+ state = "paused";
+ draw();
+ }
+ });
+
+ window
+ .matchMedia("(prefers-color-scheme: dark)")
+ .addEventListener("change", () => {
+ palette = readColors();
+ if (state !== "running") draw();
+ });
+
+ document.getElementById("play").addEventListener("click", () => {
+ main.classList.add("playing");
+ reset();
+ draw();
+ // Keys go to the game, not to the Try again button.
+ canvas.focus();
+ });
+ })();
+ </script>
+ </body>
+</html>
diff --git a/apps/erp/public/push-worker.js b/apps/erp/public/push-worker.js
deleted file mode 100644
index 8abbd1e076..0000000000
--- a/apps/erp/public/push-worker.js
+++ /dev/null
@@ -1,104 +0,0 @@
-// 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.
-
-// Web Push for Carbon: shows the notification, opens its link on click, and
-// re-registers a subscription the browser rotated. No fetch handler — this
-// worker caches nothing.
-
-// Nothing is cached, so a new version can take over at once instead of
-// waiting for every Carbon tab to close.
-self.addEventListener("install", () => self.skipWaiting());
-self.addEventListener("activate", (event) => {
- event.waitUntil(self.clients.claim());
-});
-
-self.addEventListener("push", (event) => {
- let payload = {};
- try {
- payload = event.data ? event.data.json() : {};
- } catch {
- payload = { body: event.data ? event.data.text() : "" };
- }
- const title = payload.title || "Carbon";
- event.waitUntil(
- (async () => {
- // The browser hands `tag` to the OS as the notification's identifier,
- // and macOS replaces a notification with the same identifier silently —
- // no banner, `renotify` notwithstanding. So the tag never reaches
- // showNotification: older notifications about the same thing are
- // closed here, and the new one gets a fresh identifier and alerts.
- if (payload.tag) {
- const shown = await self.registration.getNotifications();
- for (const notification of shown) {
- if (notification.data?.tag === payload.tag) notification.close();
- }
- }
- await self.registration.showNotification(title, {
- body: payload.body || "",
- icon: "/carbon-mark-dark.png",
- data: { url: payload.url || "/", tag: payload.tag }
- });
- })()
- );
-});
-
-self.addEventListener("notificationclick", (event) => {
- event.notification.close();
- const url = event.notification.data?.url || "/";
- event.waitUntil(
- (async () => {
- // Only tabs this worker controls: navigate() rejects for any other (one
- // opened before the worker was installed, or hard-reloaded), and the
- // rejection would end the click with nothing opened.
- const windows = await self.clients.matchAll({ type: "window" });
- const target = new URL(url, self.location.origin);
- const tab = windows.find(
- (client) => new URL(client.url).origin === target.origin
- );
- if (tab) {
- try {
- // Focus first: the click allows focusing a window only briefly.
- await tab.focus();
- await tab.navigate(target.href);
- return;
- } catch {
- // fall through to a new window
- }
- }
- await self.clients.openWindow(target.href);
- })()
- );
-});
-
-self.addEventListener("pushsubscriptionchange", (event) => {
- event.waitUntil(
- (async () => {
- // Both subscriptions are nullable (Push API): Chromium can hand over a
- // usable newSubscription with no oldSubscription. Save whatever
- // replacement exists; subscribe only when there is none and the old
- // key is known.
- const old = event.oldSubscription;
- const key = old?.options?.applicationServerKey;
- const next =
- event.newSubscription ||
- (await self.registration.pushManager.getSubscription()) ||
- (key
- ? await self.registration.pushManager.subscribe({
- userVisibleOnly: true,
- applicationServerKey: key
- })
- : null);
- if (!next) return;
- await fetch("/api/push-subscription", {
- method: "PUT",
- credentials: "same-origin",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- ...next.toJSON(),
- ...(old ? { oldEndpoint: old.endpoint } : {})
- })
- });
- })()
- );
-});
diff --git a/apps/erp/public/service-worker.js b/apps/erp/public/service-worker.js
new file mode 100644
index 0000000000..7c7d983c8e
--- /dev/null
+++ b/apps/erp/public/service-worker.js
@@ -0,0 +1,208 @@
+// 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.
+
+// Carbon's one service worker (scope "/"; a scope holds one worker). Every
+// page load registers it (entry.client.tsx), push or not. It shows a page
+// that cannot load for want of a network as offline.html, and for Web Push
+// it shows the notification, sets the installed app's icon badge, opens its
+// link on click, and re-registers a subscription the browser rotated.
+// Nothing but offline.html is cached: never a page or its data. It was
+// /push-worker.js until it took on the offline page (utils/service-worker.ts).
+
+// offline.html is saved only when this worker installs, and it installs only
+// when this file changes: bump the version whenever offline.html changes, or
+// browsers keep the old page.
+const OFFLINE_CACHE = "erp-offline-v4";
+const OFFLINE_URL = "/offline.html";
+
+// Only offline.html is cached, so a new version can take over at once instead
+// of waiting for every Carbon tab to close.
+self.addEventListener("install", (event) => {
+ event.waitUntil(
+ (async () => {
+ try {
+ const cache = await caches.open(OFFLINE_CACHE);
+ await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
+ } catch {
+ // No offline page is no reason to lose push: install anyway. The
+ // next page load that reaches the network saves it
+ // (ensureOfflinePage); until then fallbackOfflinePage stands in.
+ }
+ await self.skipWaiting();
+ })()
+ );
+});
+
+self.addEventListener("activate", (event) => {
+ event.waitUntil(
+ (async () => {
+ for (const name of await caches.keys()) {
+ if (name.startsWith("erp-offline-") && name !== OFFLINE_CACHE) {
+ await caches.delete(name);
+ }
+ }
+ // Starts the page request while this worker boots, so going through the
+ // worker costs a navigation nothing.
+ if (self.registration.navigationPreload) {
+ await self.registration.navigationPreload.enable();
+ }
+ await self.clients.claim();
+ })()
+ );
+});
+
+async function navigate(event) {
+ try {
+ const response =
+ (await event.preloadResponse) ?? (await fetch(event.request));
+ // Online: make sure the offline page is there for next time.
+ event.waitUntil(ensureOfflinePage());
+ return response;
+ } catch {
+ // Only a network failure lands here; a server error page is a response
+ // and is shown as the server sent it.
+ const offline = await caches.match(OFFLINE_URL, { cacheName: OFFLINE_CACHE });
+ return offline ?? fallbackOfflinePage();
+ }
+}
+
+// Saves offline.html when it is missing. Install saves it, but a save that
+// fails there (the network dropped mid-install) would otherwise leave no
+// offline page until the next worker update; every page load that reaches
+// the network fills the gap.
+async function ensureOfflinePage() {
+ try {
+ const cache = await caches.open(OFFLINE_CACHE);
+ if (await cache.match(OFFLINE_URL)) return;
+ await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
+ } catch {
+ // Still offline, or the file is missing: the next page load tries again.
+ }
+}
+
+// The last resort when offline.html was never saved: a plain page, never the
+// browser's "This site can't be reached".
+function fallbackOfflinePage() {
+ const html =
+ '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Offline | Carbon</title>' +
+ '<body style="margin:0;min-height:100vh;display:grid;place-items:center;font-family:system-ui,sans-serif;text-align:center">' +
+ "<main><h1 style=\"font-size:1.25rem\">You're offline</h1><p>Carbon reloads the page when the connection is back.</p></main>" +
+ '<script>addEventListener("online",()=>location.reload());setInterval(()=>navigator.onLine&&fetch("/offline.html",{method:"HEAD",cache:"no-store"}).then(()=>location.reload(),()=>{}),10000)</script>';
+ return new Response(html, {
+ headers: { "Content-Type": "text/html; charset=utf-8" }
+ });
+}
+
+// Page loads only. Everything else — assets, loader data, API calls — goes to
+// the network untouched: React Router shows its own error for a failed
+// client-side navigation.
+self.addEventListener("fetch", (event) => {
+ if (event.request.mode !== "navigate" || event.request.method !== "GET") {
+ return;
+ }
+ event.respondWith(navigate(event));
+});
+
+async function setBadge(count) {
+ if (typeof count !== "number" || !("setAppBadge" in self.navigator)) return;
+ try {
+ if (count > 0) await self.navigator.setAppBadge(count);
+ else await self.navigator.clearAppBadge();
+ } catch {
+ // Refused (Safari without notification permission): no badge is fine.
+ }
+}
+
+self.addEventListener("push", (event) => {
+ let payload = {};
+ try {
+ payload = event.data ? event.data.json() : {};
+ } catch {
+ payload = { body: event.data ? event.data.text() : "" };
+ }
+ const title = payload.title || "Carbon";
+ event.waitUntil(
+ (async () => {
+ // The unread count send-push read for this user. Only an installed app
+ // shows a badge; elsewhere the call is missing or does nothing.
+ await setBadge(payload.badge);
+ // The browser hands `tag` to the OS as the notification's identifier,
+ // and macOS replaces a notification with the same identifier silently —
+ // no banner, `renotify` notwithstanding. So the tag never reaches
+ // showNotification: older notifications about the same thing are
+ // closed here, and the new one gets a fresh identifier and alerts.
+ if (payload.tag) {
+ const shown = await self.registration.getNotifications();
+ for (const notification of shown) {
+ if (notification.data?.tag === payload.tag) notification.close();
+ }
+ }
+ await self.registration.showNotification(title, {
+ body: payload.body || "",
+ icon: "/icon-192.png",
+ data: { url: payload.url || "/", tag: payload.tag }
+ });
+ })()
+ );
+});
+
+self.addEventListener("notificationclick", (event) => {
+ event.notification.close();
+ const url = event.notification.data?.url || "/";
+ event.waitUntil(
+ (async () => {
+ // Only tabs this worker controls: navigate() rejects for any other (one
+ // opened before the worker was installed, or hard-reloaded), and the
+ // rejection would end the click with nothing opened.
+ const windows = await self.clients.matchAll({ type: "window" });
+ const target = new URL(url, self.location.origin);
+ const tab = windows.find(
+ (client) => new URL(client.url).origin === target.origin
+ );
+ if (tab) {
+ try {
+ // Focus first: the click allows focusing a window only briefly.
+ await tab.focus();
+ await tab.navigate(target.href);
+ return;
+ } catch {
+ // fall through to a new window
+ }
+ }
+ await self.clients.openWindow(target.href);
+ })()
+ );
+});
+
+self.addEventListener("pushsubscriptionchange", (event) => {
+ event.waitUntil(
+ (async () => {
+ // Both subscriptions are nullable (Push API): Chromium can hand over a
+ // usable newSubscription with no oldSubscription. Save whatever
+ // replacement exists; subscribe only when there is none and the old
+ // key is known.
+ const old = event.oldSubscription;
+ const key = old?.options?.applicationServerKey;
+ const next =
+ event.newSubscription ||
+ (await self.registration.pushManager.getSubscription()) ||
+ (key
+ ? await self.registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: key
+ })
+ : null);
+ if (!next) return;
+ await fetch("/api/push-subscription", {
+ method: "PUT",
+ credentials: "same-origin",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...next.toJSON(),
+ ...(old ? { oldEndpoint: old.endpoint } : {})
+ })
+ });
+ })()
+ );
+});
diff --git a/apps/erp/public/site.webmanifest b/apps/erp/public/site.webmanifest
index 2b5ee4884e..6c577e8cb2 100644
--- a/apps/erp/public/site.webmanifest
+++ b/apps/erp/public/site.webmanifest
@@ -1 +1 @@
-{"name": "Carbon ERP", "short_name": "ERP", "icons": [{"src": "/carbon-mark-dark.png", "type": "image/png", "sizes": "any"}], "theme_color": "#ffffff", "background_color": "#ffffff", "display": "standalone"}
\ No newline at end of file
+{"id": "/", "name": "Carbon ERP", "short_name": "ERP", "start_url": "/", "scope": "/", "display": "standalone", "icons": [{"src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"}, {"src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"}, {"src": "/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"}], "theme_color": "#ffffff", "background_color": "#ffffff"}
\ No newline at end of file
diff --git a/apps/mes/app/entry.client.tsx b/apps/mes/app/entry.client.tsx
index bb8846bdff..3eb1a77c47 100644
--- a/apps/mes/app/entry.client.tsx
+++ b/apps/mes/app/entry.client.tsx
@@ -7,6 +7,7 @@ import {
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY
} from "@carbon/auth";
+import { getLogger } from "@carbon/logger";
import { ensureLoggingConfigured } from "@carbon/logger/config.client";
import posthog from "posthog-js";
import { startTransition } from "react";
@@ -52,6 +53,24 @@ if (CONTROLLED_ENVIRONMENT && posthog.__loaded) {
);
}
+// Caches the build files and shows an offline page when a tablet loses the
+// network (public/service-worker.js). Also in dev: the dev server serves no
+// /assets/ URL, so its modules never reach the cache. After the page has
+// loaded, so the worker's own download does not compete with the page's; this
+// module can run after "load" has fired (the dev server imports it late), so
+// check first.
+if ("serviceWorker" in navigator) {
+ const register = () => {
+ navigator.serviceWorker
+ .register("/service-worker.js", { scope: "/" })
+ .catch((error) =>
+ getLogger("mes", "service-worker").warn("not registered", { error })
+ );
+ };
+ if (document.readyState === "complete") register();
+ else window.addEventListener("load", register, { once: true });
+}
+
// The catalog is no longer in loader data, so fetch the active language's
// chunk before hydrating — otherwise a non-en page hydrates against an empty
// catalog and mismatches the server markup.
diff --git a/apps/mes/public/apple-touch-icon.png b/apps/mes/public/apple-touch-icon.png
index f63749a97c..2fdd26bca7 100644
Binary files a/apps/mes/public/apple-touch-icon.png and b/apps/mes/public/apple-touch-icon.png differ
diff --git a/apps/mes/public/icon-192.png b/apps/mes/public/icon-192.png
new file mode 100644
index 0000000000..1a89c615b1
Binary files /dev/null and b/apps/mes/public/icon-192.png differ
diff --git a/apps/mes/public/icon-512.png b/apps/mes/public/icon-512.png
new file mode 100644
index 0000000000..aa79060217
Binary files /dev/null and b/apps/mes/public/icon-512.png differ
diff --git a/apps/mes/public/icon-maskable-512.png b/apps/mes/public/icon-maskable-512.png
new file mode 100644
index 0000000000..ec10514d9f
Binary files /dev/null and b/apps/mes/public/icon-maskable-512.png differ
diff --git a/apps/mes/public/offline.html b/apps/mes/public/offline.html
new file mode 100644
index 0000000000..1f43e9ff74
--- /dev/null
+++ b/apps/mes/public/offline.html
@@ -0,0 +1,435 @@
+<!doctype html>
+<!-- Served by the service worker (public/service-worker.js)
+ when a page load fails for want of a network. Self-contained: nothing else
+ is reachable while offline. Each app has a copy in its public folder;
+ keep them the same. The workers save it when they install: bump the offline
+ cache version in both service-worker.js files after any change here. -->
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta
+ name="viewport"
+ content="width=device-width, initial-scale=1, viewport-fit=cover"
+ />
+ <title>Offline | Carbon</title>
+ <style>
+ :root {
+ color-scheme: light dark;
+ font-family:
+ ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ --fg: #09090b;
+ --muted: #71717a;
+ --line: #e4e4e7;
+ }
+ body {
+ margin: 0;
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ background: #fff;
+ color: var(--fg);
+ }
+ main {
+ width: 100%;
+ max-width: 22rem;
+ padding: 1.5rem;
+ box-sizing: border-box;
+ text-align: center;
+ }
+ main.playing {
+ max-width: 40rem;
+ }
+ h1 {
+ margin: 0 0 0.5rem;
+ font-size: 1.25rem;
+ font-weight: 600;
+ text-wrap: balance;
+ }
+ /* The text keeps its width when the game widens the page, and its
+ lines are balanced, so no word is left alone on the last line. */
+ p {
+ max-width: 19rem;
+ margin: 0 auto 1.5rem;
+ color: var(--muted);
+ line-height: 1.5;
+ text-wrap: balance;
+ }
+ .actions {
+ display: flex;
+ gap: 0.5rem;
+ justify-content: center;
+ }
+ button {
+ font: inherit;
+ font-weight: 500;
+ border: 0;
+ border-radius: 0.4375rem;
+ padding: 0.625rem 1.25rem;
+ background: var(--fg);
+ color: #fafafa;
+ cursor: pointer;
+ }
+ button.secondary {
+ background: transparent;
+ color: var(--fg);
+ box-shadow: inset 0 0 0 1px var(--line);
+ }
+ #game {
+ display: none;
+ margin-top: 1.5rem;
+ }
+ main.playing #game {
+ display: block;
+ }
+ main.playing #play {
+ display: none;
+ }
+ canvas {
+ display: block;
+ width: 100%;
+ aspect-ratio: 4 / 1;
+ border-radius: 0.4375rem;
+ box-shadow: inset 0 0 0 1px var(--line);
+ touch-action: manipulation;
+ cursor: pointer;
+ }
+ canvas:focus-visible {
+ outline: 2px solid var(--muted);
+ outline-offset: 2px;
+ }
+ .hint {
+ max-width: none;
+ margin: 0.5rem 0 0;
+ font-size: 0.8125rem;
+ }
+ /* Last, so it overrides the light rules above. */
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --fg: #fafafa;
+ --muted: #a1a1aa;
+ --line: #27272a;
+ }
+ body {
+ background: #09090b;
+ }
+ button {
+ color: #09090b;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <main id="main">
+ <h1>You're offline</h1>
+ <p>
+ This device lost its connection. Carbon reloads the page when the
+ connection is back.
+ </p>
+ <div class="actions">
+ <button type="button" id="retry">Try again</button>
+ <button type="button" id="play" class="secondary">
+ Play while you wait
+ </button>
+ </div>
+ <div id="game">
+ <canvas
+ id="canvas"
+ tabindex="0"
+ aria-label="Forklift game: press Space or tap to jump over the crates"
+ ></canvas>
+ <p class="hint">Space, ↑ or tap to jump</p>
+ </div>
+ </main>
+ <script>
+ document
+ .getElementById("retry")
+ .addEventListener("click", () => location.reload());
+ window.addEventListener("online", () => location.reload());
+
+ // "online" never fires when the device kept its network but Carbon
+ // could not be reached (the server, or the internet behind the Wi-Fi):
+ // ask Carbon itself every few seconds. offline.html is a static file, so
+ // the check costs the server nothing; the service workers pass it
+ // straight to the network.
+ // Not at its own address: there it is not standing in for a page, and
+ // the check would succeed and reload it forever.
+ setInterval(() => {
+ if (!navigator.onLine || location.pathname === "/offline.html") return;
+ fetch("/offline.html", { method: "HEAD", cache: "no-store" }).then(
+ () => location.reload(),
+ () => undefined
+ );
+ }, 10000);
+
+ // A forklift runner: jump the crates, pallets and cones on the shop
+ // floor. Opened from a button, so the page stays quiet until asked.
+ (() => {
+ const main = document.getElementById("main");
+ const canvas = document.getElementById("canvas");
+ const ctx = canvas.getContext("2d");
+ const W = 600;
+ const H = 150;
+ const GROUND = 128;
+ const GRAVITY = 1700;
+ const JUMP = 560;
+ const START_SPEED = 260;
+ const MAX_SPEED = 620;
+ const BEST_KEY = "carbon-offline-best";
+
+ // Fixed logical size, drawn at the screen's pixel density.
+ const ratio = window.devicePixelRatio || 1;
+ canvas.width = W * ratio;
+ canvas.height = H * ratio;
+ ctx.scale(ratio, ratio);
+
+ const readBest = () => {
+ try {
+ return Number(localStorage.getItem(BEST_KEY)) || 0;
+ } catch {
+ return 0;
+ }
+ };
+ const writeBest = (value) => {
+ try {
+ localStorage.setItem(BEST_KEY, String(value));
+ } catch {
+ // Private mode: the best score lasts this page only.
+ }
+ };
+
+ const player = { x: 48, y: GROUND, vy: 0, w: 34, h: 28 };
+ let state = "ready"; // ready | running | paused | over
+ let obstacles = [];
+ let speed = START_SPEED;
+ let distance = 0;
+ let nextGap = 0;
+ let floorOffset = 0;
+ let best = readBest();
+ let last = 0;
+ let frame = 0;
+
+ // Read once, and again when the light/dark mode changes.
+ const readColors = () => {
+ const style = getComputedStyle(document.documentElement);
+ return {
+ fg: style.getPropertyValue("--fg").trim(),
+ muted: style.getPropertyValue("--muted").trim(),
+ line: style.getPropertyValue("--line").trim()
+ };
+ };
+ let palette = readColors();
+
+ const reset = () => {
+ obstacles = [];
+ speed = START_SPEED;
+ distance = 0;
+ nextGap = 320;
+ player.y = GROUND;
+ player.vy = 0;
+ };
+
+ const spawn = () => {
+ const kind = Math.random();
+ if (kind < 0.45) {
+ const size = 18 + Math.random() * 10;
+ obstacles.push({ type: "crate", x: W, w: size, h: size });
+ } else if (kind < 0.75) {
+ obstacles.push({ type: "pallet", x: W, w: 38, h: 22 });
+ } else {
+ obstacles.push({ type: "cone", x: W, w: 16, h: 24 });
+ }
+ // Gaps grow with speed, so every gap stays jumpable.
+ nextGap = speed * (0.75 + Math.random() * 0.9) + 90;
+ };
+
+ const start = () => {
+ state = "running";
+ last = performance.now();
+ frame = requestAnimationFrame(loop);
+ };
+
+ const jump = () => {
+ if (state === "ready" || state === "over") {
+ reset();
+ start();
+ return;
+ }
+ if (state === "paused") {
+ start();
+ return;
+ }
+ if (player.y >= GROUND) player.vy = -JUMP;
+ };
+
+ const hits = (o) => {
+ // A little forgiveness: the boxes are drawn larger than they hit.
+ const pad = 4;
+ return (
+ player.x + pad < o.x + o.w &&
+ player.x + player.w - pad > o.x &&
+ player.y - pad > GROUND - o.h
+ );
+ };
+
+ const update = (dt) => {
+ speed = Math.min(MAX_SPEED, speed + 9 * dt);
+ distance += speed * dt;
+ floorOffset = (floorOffset + speed * dt) % 24;
+
+ player.vy += GRAVITY * dt;
+ player.y = Math.min(GROUND, player.y + player.vy * dt);
+ if (player.y === GROUND) player.vy = 0;
+
+ for (const o of obstacles) o.x -= speed * dt;
+ obstacles = obstacles.filter((o) => o.x + o.w > 0);
+ const lastObstacle = obstacles[obstacles.length - 1];
+ if (!lastObstacle || W - (lastObstacle.x + lastObstacle.w) > nextGap) {
+ spawn();
+ }
+
+ if (obstacles.some(hits)) {
+ state = "over";
+ const score = Math.floor(distance / 10);
+ if (score > best) {
+ best = score;
+ writeBest(best);
+ }
+ }
+ };
+
+ const drawForklift = (c) => {
+ const x = player.x;
+ const y = player.y;
+ ctx.fillStyle = c.fg;
+ ctx.strokeStyle = c.fg;
+ ctx.lineWidth = 2;
+ // Body and cab.
+ ctx.fillRect(x, y - 18, 22, 12);
+ ctx.strokeRect(x + 4, y - 28, 12, 10);
+ // Mast and forks, at the front.
+ ctx.fillRect(x + 24, y - 30, 3, 26);
+ ctx.fillRect(x + 27, y - 6, 9, 2);
+ // Wheels.
+ ctx.beginPath();
+ ctx.arc(x + 5, y - 3, 3.5, 0, Math.PI * 2);
+ ctx.arc(x + 19, y - 3, 3.5, 0, Math.PI * 2);
+ ctx.fill();
+ };
+
+ const drawObstacle = (o, c) => {
+ const top = GROUND - o.h;
+ ctx.strokeStyle = c.muted;
+ ctx.fillStyle = c.muted;
+ ctx.lineWidth = 2;
+ if (o.type === "crate") {
+ ctx.strokeRect(o.x + 1, top + 1, o.w - 2, o.h - 2);
+ ctx.beginPath();
+ ctx.moveTo(o.x + 1, top + 1);
+ ctx.lineTo(o.x + o.w - 1, GROUND - 1);
+ ctx.stroke();
+ } else if (o.type === "pallet") {
+ ctx.fillRect(o.x, top, o.w, 10);
+ ctx.fillRect(o.x, GROUND - 4, o.w, 4);
+ ctx.fillRect(o.x + 2, top + 10, 5, 8);
+ ctx.fillRect(o.x + o.w / 2 - 2.5, top + 10, 5, 8);
+ ctx.fillRect(o.x + o.w - 7, top + 10, 5, 8);
+ } else {
+ ctx.beginPath();
+ ctx.moveTo(o.x + o.w / 2, top);
+ ctx.lineTo(o.x + o.w, GROUND);
+ ctx.lineTo(o.x, GROUND);
+ ctx.closePath();
+ ctx.fill();
+ }
+ };
+
+ const drawText = (text, y, c, size) => {
+ ctx.fillStyle = c;
+ ctx.font = `500 ${size}px ui-sans-serif, system-ui, sans-serif`;
+ ctx.textAlign = "center";
+ ctx.fillText(text, W / 2, y);
+ };
+
+ const draw = () => {
+ const c = palette;
+ ctx.clearRect(0, 0, W, H);
+
+ // Floor, with lane markings moving past.
+ ctx.fillStyle = c.line;
+ ctx.fillRect(0, GROUND, W, 2);
+ ctx.fillStyle = c.muted;
+ for (let x = -floorOffset; x < W; x += 24) {
+ ctx.fillRect(x, GROUND + 9, 10, 2);
+ }
+
+ for (const o of obstacles) drawObstacle(o, c);
+ drawForklift(c);
+
+ // Score, top right.
+ ctx.fillStyle = c.muted;
+ ctx.font = "500 12px ui-monospace, SFMono-Regular, monospace";
+ ctx.textAlign = "right";
+ const score = String(Math.floor(distance / 10)).padStart(5, "0");
+ const bestText = best ? `BEST ${String(best).padStart(5, "0")} ` : "";
+ ctx.fillText(`${bestText}${score} m`, W - 12, 22);
+
+ if (state === "ready") {
+ drawText("Press Space or tap to start", 64, c.fg, 15);
+ } else if (state === "paused") {
+ drawText("Paused", 56, c.fg, 15);
+ drawText("Press Space or tap to carry on", 78, c.muted, 13);
+ } else if (state === "over") {
+ drawText("Crashed into the stock", 56, c.fg, 15);
+ drawText("Press Space or tap to go again", 78, c.muted, 13);
+ }
+ };
+
+ const loop = (now) => {
+ if (state !== "running") return;
+ // Capped, so a frame after a stall does not leap through a crate.
+ const dt = Math.min((now - last) / 1000, 1 / 30);
+ last = now;
+ update(dt);
+ draw();
+ if (state === "running") frame = requestAnimationFrame(loop);
+ };
+
+ canvas.addEventListener("keydown", (event) => {
+ if (event.code === "Space" || event.code === "ArrowUp") {
+ event.preventDefault();
+ jump();
+ }
+ });
+ canvas.addEventListener("pointerdown", (event) => {
+ event.preventDefault();
+ canvas.focus();
+ jump();
+ });
+
+ // Hidden tab: stop, and wait for a key or tap to carry on.
+ document.addEventListener("visibilitychange", () => {
+ if (document.hidden && state === "running") {
+ cancelAnimationFrame(frame);
+ state = "paused";
+ draw();
+ }
+ });
+
+ window
+ .matchMedia("(prefers-color-scheme: dark)")
+ .addEventListener("change", () => {
+ palette = readColors();
+ if (state !== "running") draw();
+ });
+
+ document.getElementById("play").addEventListener("click", () => {
+ main.classList.add("playing");
+ reset();
+ draw();
+ // Keys go to the game, not to the Try again button.
+ canvas.focus();
+ });
+ })();
+ </script>
+ </body>
+</html>
diff --git a/apps/mes/public/service-worker.js b/apps/mes/public/service-worker.js
new file mode 100644
index 0000000000..4cbe45c836
--- /dev/null
+++ b/apps/mes/public/service-worker.js
@@ -0,0 +1,158 @@
+// 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.
+
+// MES on shop-floor tablets: build files come from the cache, and a page load
+// with no network shows offline.html instead of the browser's error page.
+// Only public, same-origin static files are cached — never a page, loader
+// data or a private file, so nothing here outlives a sign-out.
+
+// offline.html is saved only when this worker installs, and it installs only
+// when this file changes: bump SHELL_CACHE whenever offline.html changes, or
+// browsers keep the old page. The asset cache has its own version: build files
+// are named by their content, so an offline.html change keeps them.
+const SHELL_CACHE = "mes-shell-v4";
+const ASSET_CACHE = "mes-assets-v1";
+const OFFLINE_URL = "/offline.html";
+
+// Hashed build files pile up across deploys under new names; the oldest go.
+const MAX_ASSET_ENTRIES = 400;
+
+self.addEventListener("install", (event) => {
+ event.waitUntil(
+ (async () => {
+ try {
+ const cache = await caches.open(SHELL_CACHE);
+ await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
+ } catch {
+ // Install anyway: the next page load that reaches the network saves
+ // it (ensureOfflinePage); until then fallbackOfflinePage stands in.
+ }
+ await self.skipWaiting();
+ })()
+ );
+});
+
+self.addEventListener("activate", (event) => {
+ event.waitUntil(
+ (async () => {
+ const keep = new Set([SHELL_CACHE, ASSET_CACHE]);
+ for (const name of await caches.keys()) {
+ if (!keep.has(name)) await caches.delete(name);
+ }
+ // Starts the page request while this worker boots.
+ if (self.registration.navigationPreload) {
+ await self.registration.navigationPreload.enable();
+ }
+ await self.clients.claim();
+ })()
+ );
+});
+
+// Vite names every build file by its content hash, so a URL never changes
+// meaning: served from the cache with no network check.
+function isHashedAsset(url) {
+ return url.pathname.startsWith("/assets/");
+}
+
+// Public files with a fixed name (icons, logos): served from the cache and
+// refreshed behind it, so a changed icon shows on the next load.
+function isPublicFile(url) {
+ return (
+ url.pathname.startsWith("/icons/") ||
+ /^\/(carbon-[\w-]+|apple-touch-icon)\.(png|svg)$/.test(url.pathname) ||
+ url.pathname === "/site.webmanifest"
+ );
+}
+
+async function trimAssets(cache) {
+ const keys = await cache.keys();
+ // keys() is in insertion order: the first are the oldest.
+ for (const request of keys.slice(0, keys.length - MAX_ASSET_ENTRIES)) {
+ await cache.delete(request);
+ }
+}
+
+async function cacheFirst(request) {
+ const cache = await caches.open(ASSET_CACHE);
+ const cached = await cache.match(request);
+ if (cached) return cached;
+ const response = await fetch(request);
+ if (response.ok) {
+ await cache.put(request, response.clone());
+ await trimAssets(cache);
+ }
+ return response;
+}
+
+async function staleWhileRevalidate(event) {
+ const cache = await caches.open(ASSET_CACHE);
+ const cached = await cache.match(event.request);
+ const refresh = fetch(event.request).then(async (response) => {
+ if (response.ok) await cache.put(event.request, response.clone());
+ return response;
+ });
+ if (cached) {
+ event.waitUntil(refresh.catch(() => undefined));
+ return cached;
+ }
+ return refresh;
+}
+
+async function navigate(event) {
+ try {
+ const response =
+ (await event.preloadResponse) ?? (await fetch(event.request));
+ // Online: make sure the offline page is there for next time.
+ event.waitUntil(ensureOfflinePage());
+ return response;
+ } catch {
+ // Only a network failure lands here; a server error page is a response
+ // and is shown as the server sent it.
+ const offline = await caches.match(OFFLINE_URL, { cacheName: SHELL_CACHE });
+ return offline ?? fallbackOfflinePage();
+ }
+}
+
+// Saves offline.html when it is missing. Install saves it, but a save that
+// fails there (the network dropped mid-install) would otherwise leave no
+// offline page until the next worker update; every page load that reaches
+// the network fills the gap.
+async function ensureOfflinePage() {
+ try {
+ const cache = await caches.open(SHELL_CACHE);
+ if (await cache.match(OFFLINE_URL)) return;
+ await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
+ } catch {
+ // Still offline, or the file is missing: the next page load tries again.
+ }
+}
+
+// The last resort when offline.html was never saved: a plain page, never the
+// browser's "This site can't be reached".
+function fallbackOfflinePage() {
+ const html =
+ '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Offline | Carbon</title>' +
+ '<body style="margin:0;min-height:100vh;display:grid;place-items:center;font-family:system-ui,sans-serif;text-align:center">' +
+ "<main><h1 style=\"font-size:1.25rem\">You're offline</h1><p>Carbon reloads the page when the connection is back.</p></main>" +
+ '<script>addEventListener("online",()=>location.reload());setInterval(()=>navigator.onLine&&fetch("/offline.html",{method:"HEAD",cache:"no-store"}).then(()=>location.reload(),()=>{}),10000)</script>';
+ return new Response(html, {
+ headers: { "Content-Type": "text/html; charset=utf-8" }
+ });
+}
+
+self.addEventListener("fetch", (event) => {
+ const { request } = event;
+ if (request.method !== "GET") return;
+ const url = new URL(request.url);
+ // Supabase, analytics, and a CDN asset base (ASSETS_URL) go straight out.
+ if (url.origin !== self.location.origin) return;
+
+ if (request.mode === "navigate") {
+ event.respondWith(navigate(event));
+ } else if (isHashedAsset(url)) {
+ event.respondWith(cacheFirst(request));
+ } else if (isPublicFile(url)) {
+ event.respondWith(staleWhileRevalidate(event));
+ }
+});
diff --git a/apps/mes/public/serviceWorker.js b/apps/mes/public/serviceWorker.js
deleted file mode 100644
index 1d9a5947a8..0000000000
--- a/apps/mes/public/serviceWorker.js
+++ /dev/null
@@ -1,35 +0,0 @@
-// 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.
-
-self.addEventListener("fetch", (event) => {
- let url = new URL(event.request.url);
- let method = event.request.method;
-
- // any non GET request is ignored
- if (method.toLowerCase() !== "get") return;
-
- // If the request is for the favicons, fonts, or the built files (which are hashed in the name)
- if (
- url.pathname.includes("logo") ||
- url.pathname.includes("storage/v1/object/public/avatars")
- ) {
- event.respondWith(
- // we will open the assets cache
- caches.open("assets").then(async (cache) => {
- // if the request is cached we will use the cache
- let cacheResponse = await cache.match(event.request);
- if (cacheResponse) return cacheResponse;
-
- // if it's not cached we will run the fetch, cache it and return it
- // this way the next time this asset it's needed it will load from the cache
- let fetchResponse = await fetch(event.request);
- cache.put(event.request, fetchResponse.clone());
-
- return fetchResponse;
- })
- );
- }
-
- return;
-});
diff --git a/apps/mes/public/site.webmanifest b/apps/mes/public/site.webmanifest
index 3e2eba02dd..a258fba101 100644
--- a/apps/mes/public/site.webmanifest
+++ b/apps/mes/public/site.webmanifest
@@ -1 +1 @@
-{"name": "Carbon MES", "short_name": "MES", "icons": [{"src": "/carbon-mark-dark.png", "type": "image/png", "sizes": "any"}], "theme_color": "#ffffff", "background_color": "#ffffff", "display": "standalone"}
\ No newline at end of file
+{"id": "/", "name": "Carbon MES", "short_name": "MES", "start_url": "/", "scope": "/", "display": "standalone", "icons": [{"src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"}, {"src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"}, {"src": "/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"}], "theme_color": "#ffffff", "background_color": "#ffffff"}
\ No newline at end of file
diff --git a/docs/content/docs/reference/mes.mdx b/docs/content/docs/reference/mes.mdx
index 9e6db71d0a..aec7518e3d 100644
--- a/docs/content/docs/reference/mes.mdx
+++ b/docs/content/docs/reference/mes.mdx
@@ -5,7 +5,7 @@ description: The shop-floor surface where operators run operations, report quant
The <Term>MES</Term> app is Carbon's shop-floor interface. Planners release and schedule work in the ERP; operators execute and report that work from tablets or shared stations in MES. See the [run the floor tour](/guides/floor) for a walkthrough and [jobs](/docs/reference/jobs), [picking lists](/docs/reference/picking), and [quality](/docs/reference/quality) for the underlying records.
-MES requires a network connection for all writes. It caches item and people picker data in IndexedDB for faster reads, but it has **no offline mode**. Operators cannot start work, report output, or issue material while disconnected.
+MES requires a network connection for all writes. It caches item and people picker data in IndexedDB for faster reads, but it has **no offline mode**. Operators cannot start work, report output, or issue material while disconnected. A page opened without a connection shows an offline page instead of the browser's error, and Carbon reloads it once the connection is back.
## Getting onto the floor
diff --git a/docs/content/docs/reference/notifications.mdx b/docs/content/docs/reference/notifications.mdx
index 7b40b07b29..7c77de9433 100644
--- a/docs/content/docs/reference/notifications.mdx
+++ b/docs/content/docs/reference/notifications.mdx
@@ -45,7 +45,7 @@ Each channel is enabled by default. Turning off a switch mutes only that topic a
## Browser notifications
-Above the grid, the **Browser notifications** card turns them on for the browser you are using. Click **Enable** and allow the browser's prompt. The bell also offers **Enable browser notifications** at the top of the inbox until you enable them or choose **Not now** (it asks once more after 30 days, then stops). Browser notifications are a setting of the browser: once enabled on a computer or phone, whoever signs in there gets their own notifications, from every company they belong to. Signing out — or being signed out — stops the previous user's notifications at once, so a shared computer never shows someone else's. **Disable** turns them off for that browser, for everyone who uses it. On iPhone or iPad, add Carbon to the Home Screen first — Safari offers push only to Home Screen apps.
+Above the grid, the **Browser notifications** card turns them on for the browser you are using. Click **Enable** and allow the browser's prompt. The bell also offers **Enable browser notifications** at the top of the inbox until you enable them or choose **Not now** (it asks once more after 30 days, then stops). Browser notifications are a setting of the browser: once enabled on a computer or phone, whoever signs in there gets their own notifications, from every company they belong to. Signing out — or being signed out — stops the previous user's notifications at once, so a shared computer never shows someone else's. **Disable** turns them off for that browser, for everyone who uses it. On iPhone or iPad, add Carbon to the Home Screen first — Safari offers push only to Home Screen apps. When Carbon is installed as an app (Home Screen, Dock, or an installed browser app), its icon shows how many notifications are unread across all your companies; signing out clears it.
## Who receives an expiration or reminder
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index 7db610adae..261c415066 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -70,7 +70,7 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +
| `invoice-automate` | `carbon/invoice.automate` | Posts one drafted recurring invoice (rental or contract), then emails it under `Post and Email` or sends it through Stripe Connect under `Post and Send via Stripe`; mode from the event or the source's effective mode (`resolveInvoiceAutomation`: `customerContracts.effectiveInvoiceAutomation` when the invoice has a `customerContractId`, else the rental agreement's). Fired by the **Invoice** action of a rental agreement or contract, by Sell to Customer, and by the invoice's Send action (`resend: true` — Stripe when that is the resolved mode, else `Post and Email`). One run per invoice (`concurrency` on `invoiceId`, not shared with the cron's steps). Every step is safe to retry: posting claims only a Draft (a Pending claim is reported as held, never re-claimed), and a send is skipped once `sentAt` is set or a Stripe invoice is linked — but an email that went out before its `sentAt` write failed is recorded as a `sendError`, and a Send then emails it again. `sendPostedInvoiceViaStripe` stamps `sentTo: "Stripe"`, or `sendError` "Stripe is not connected" / "No Stripe customer is linked", and never sends an invoice twice (it checks `sentAt` and the existing Stripe invoice link) |
| `revenue-recognition-proposal` | `0 12 1 * *` | One query (`companiesToPropose`: `company` joined to `companySettings`, `accountingCutoverDate` set) finds every company with an accounting cutover. Per company, one step per run type (`rev-rec-<id>`, `lease-run-<id>`): proposes a Draft revenue recognition run and a Draft lease run for the month that just ended on the company's calendar (`proposeRevenueRecognitionRun` (`accounting.service.ts`, ported from the `propose-revenue-recognition-run` server function) with `type`, `userId "system"`). Only an existing Draft run of the same type for that period skips it; a Posted run does not, because rows can fall due after it posted. Posting stays human |
| `notify` | `carbon/notify` (`trigger("notify", …)` from app code) | Resolve the recipients, write the in-app rows, then fan out email, Slack and push. Built for large groups: every read keyed by the recipients goes through `fetchAllByIds`, the `.in()` writes run per `IN_FILTER_CHUNK` (100) ids, inserts per `INSERT_CHUNK` (500) rows, emails render and send per `EMAIL_CHUNK` (20, about 16.9 KB each against Inngest's 512 KB send limit), and Slack and push send per `EVENT_CHUNK` (500) events |
-| `send-push` | `carbon/send-push` (one per `pushSubscription` row, fanned out by `notify` for every notification, like in-app, when `isPushConfigured()`) | Send one Web Push with `web-push`; deletes the row on 404/410, logs a warning and keeps it on 401/403 (another VAPID key, or Apple refusing our token), retries 429/5xx, fails other 4xx (`pushDeliveryOutcome`) |
+| `send-push` | `carbon/send-push` (one per `pushSubscription` row, fanned out by `notify` for every notification, like in-app, when `isPushConfigured()`) | Send one Web Push with `web-push`, carrying `badge` (the user's unread top-level notifications across their employee companies, as `useAppBadge` counts them; omitted when the count fails); deletes the row on 404/410, logs a warning and keeps it on 401/403 (another VAPID key, or Apple refusing our token), retries 429/5xx, fails other 4xx (`pushDeliveryOutcome`) |
| `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` |
diff --git a/packages/jobs/src/inngest/functions/notifications/send-push.ts b/packages/jobs/src/inngest/functions/notifications/send-push.ts
index 7274585627..584205f7a5 100644
--- a/packages/jobs/src/inngest/functions/notifications/send-push.ts
+++ b/packages/jobs/src/inngest/functions/notifications/send-push.ts
@@ -55,6 +55,43 @@ export const sendPushFunction = inngest.createFunction(
return { skipped: "subscription not found" };
}
+ // The installed app's icon badge: the user's unread notifications in every
+ // company they work in, as the open tab counts them (useAppBadge).
+ // Read after the in-app row exists, so it includes this one. A failed read
+ // sends no badge rather than failing the push.
+ const badge = await step.run("count-unread", async () => {
+ const client = getCarbonServiceRole();
+ const memberships = await client
+ .from("userToCompany")
+ .select("companyId")
+ .eq("userId", userId)
+ .eq("role", "employee");
+ if (memberships.error) {
+ log.warn("Failed to read the user's companies for the badge", {
+ error: memberships.error,
+ userId
+ });
+ return null;
+ }
+ const companyIds = (memberships.data ?? []).map((row) => row.companyId);
+ if (companyIds.length === 0) return 0;
+ const { count, error } = await client
+ .from("notification")
+ .select("id", { count: "exact", head: true })
+ .eq("userId", userId)
+ .in("companyId", companyIds)
+ .is("readAt", null)
+ .is("digestedInto", null);
+ if (error) {
+ log.warn("Failed to count unread notifications for the badge", {
+ error,
+ userId
+ });
+ return null;
+ }
+ return count ?? null;
+ });
+
const sent = await step.run("send-push", async () => {
try {
const result = await webpush.sendNotification(
@@ -62,7 +99,7 @@ export const sendPushFunction = inngest.createFunction(
endpoint: subscription.endpoint,
keys: { auth: subscription.auth, p256dh: subscription.p256dh }
},
- JSON.stringify({ body, tag, title, url }),
+ JSON.stringify({ badge, body, tag, title, url }),
{
TTL: PUSH_TTL_SECONDS,
urgency: "normal",