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.

refactor(erp): consolidate shell, hub, draft and action-task server helpers into shared.server (#1838)

Brad Barbind4fd55db1934
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 88a983742c..a5985dc573 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -12,7 +12,6 @@ paths:
- "apps/erp/app/routes/api+/settings.backup-summary.ts"
- "apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts"
- "apps/erp/app/services/onboarding.server.ts"
- - "apps/erp/app/services/onboarding-draft.server.ts"
- "packages/jobs/src/scripts/check-backups.ts"
- "packages/jobs/manifests/**"
---
diff --git a/apps/erp/app/services/app-shell.server.test.ts b/apps/erp/app/modules/shared/app-shell.server.test.ts
similarity index 69%
rename from apps/erp/app/services/app-shell.server.test.ts
rename to apps/erp/app/modules/shared/app-shell.server.test.ts
index 4d4ca7b38c..f2c5c8642d 100644
--- a/apps/erp/app/services/app-shell.server.test.ts
+++ b/apps/erp/app/modules/shared/app-shell.server.test.ts
@@ -4,6 +4,18 @@
import { describe, expect, it, vi } from "vitest";
+// shared.server.ts also holds the sales-order/return PDF and email helpers;
+// stub their imports so this test loads only what it exercises.
+vi.mock("@carbon/documents/email", () => ({}));
+vi.mock("@carbon/jobs", () => ({}));
+vi.mock("~/modules/accounting", () => ({}));
+vi.mock("~/modules/sales", () => ({}));
+vi.mock("~/modules/users/users.server", () => ({}));
+vi.mock("~/routes/file+/purchase-return-order+/$id[.]pdf", () => ({}));
+vi.mock("~/routes/file+/sales-return-order+/$id[.]pdf", () => ({}));
+vi.mock("../documents/documents.service", () => ({}));
+vi.mock("~/modules/shared/shared.service", () => ({}));
+vi.mock("@carbon/onboarding/server", () => ({}));
vi.mock("~/modules/settings", () => ({
withLogoUrls: (company: { logoLight: string | null }) => ({
...company,
@@ -11,7 +23,7 @@ vi.mock("~/modules/settings", () => ({
})
}));
-const { getAppShell } = await import("./app-shell.server");
+const { getAppShell } = await import("./shared.server");
type Client = Parameters<typeof getAppShell>[0];
const clientReturning = (result: unknown) => {
diff --git a/apps/erp/app/services/implementation-signals.server.test.ts b/apps/erp/app/modules/shared/implementation-signals.server.test.ts
similarity index 76%
rename from apps/erp/app/services/implementation-signals.server.test.ts
rename to apps/erp/app/modules/shared/implementation-signals.server.test.ts
index 4f64bd5bbc..0ca5cfb8fc 100644
--- a/apps/erp/app/services/implementation-signals.server.test.ts
+++ b/apps/erp/app/modules/shared/implementation-signals.server.test.ts
@@ -18,9 +18,20 @@ vi.mock("@carbon/onboarding/server", () => ({
detectImplementationSignals: detect
}));
-const { getImplementationSignals } = await import(
- "./implementation-signals.server"
-);
+// shared.server.ts also holds the sales-order/return PDF and email helpers;
+// stub their imports so this test loads only what it exercises.
+vi.mock("@carbon/documents/email", () => ({}));
+vi.mock("@carbon/jobs", () => ({}));
+vi.mock("~/modules/accounting", () => ({}));
+vi.mock("~/modules/sales", () => ({}));
+vi.mock("~/modules/users/users.server", () => ({}));
+vi.mock("~/routes/file+/purchase-return-order+/$id[.]pdf", () => ({}));
+vi.mock("~/routes/file+/sales-return-order+/$id[.]pdf", () => ({}));
+vi.mock("../documents/documents.service", () => ({}));
+vi.mock("~/modules/shared/shared.service", () => ({}));
+vi.mock("~/modules/settings", () => ({}));
+
+const { getImplementationSignals } = await import("./shared.server");
const client = {} as Parameters<typeof getImplementationSignals>[0];
const signals = (overrides: Record<string, boolean>) => ({
diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.ts
index 3d35529797..d58e6940b5 100644
--- a/apps/erp/app/modules/shared/shared.server.ts
+++ b/apps/erp/app/modules/shared/shared.server.ts
@@ -4,16 +4,22 @@
import type { Database } from "@carbon/database";
import { SalesOrderEmail } from "@carbon/documents/email";
+import type { ActionTaskEntityType } from "@carbon/ee/action-task-entity";
+import { actionTaskEntities } from "@carbon/ee/action-task-entity";
import { storage } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
+import type { Signals } from "@carbon/onboarding";
+import { detectImplementationSignals } from "@carbon/onboarding/server";
+import type { PrinterRoute } from "@carbon/printing";
import { unchecked } from "@carbon/utils";
import type { CalendarDate } from "@internationalized/date";
import { startOfWeek } from "@internationalized/date";
import { renderAsync } from "@react-email/components";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { LoaderFunctionArgs } from "react-router";
+import { createCookieSessionStorage } from "react-router";
import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import {
getCustomerContact,
@@ -21,7 +27,7 @@ import {
getSalesOrderCustomerDetails,
getSalesOrderLines
} from "~/modules/sales";
-import { getCompany } from "~/modules/settings";
+import { getCompany, withLogoUrls } from "~/modules/settings";
import { getTimezoneNames } from "~/modules/shared/shared.service";
import { getUser } from "~/modules/users/users.server";
// Created concurrently with the returns module; see routes/file+/purchase-return-order+/
@@ -35,6 +41,9 @@ import type { CustomFieldsTableType } from "../settings";
const logger = getLogger("erp", "shared");
+type Tables = Database["public"]["Tables"];
+type Views = Database["public"]["Views"];
+
export async function assign(
client: SupabaseClient<Database>,
args: {
@@ -597,8 +606,6 @@ function toPlainPeriod(p: {
};
}
-type Tables = Database["public"]["Tables"];
-
/**
* Every table with a string `id` and a `companyId` column. A nullable
* `companyId` (e.g. `item`) is fine: global rows never match `.eq("companyId")`.
@@ -652,3 +659,220 @@ export async function requireCompanyRecord(
throw new Response("Not found", { status: 404 });
}
}
+
+// What `get_app_shell` returns: the rows the shell used to read with nine
+// requests. Each key holds what `select("*")` on that table returned.
+type AppShellRows = {
+ companies: Views["companies"]["Row"][];
+ companyIntegrations: Tables["companyIntegration"]["Row"][];
+ companySettings: Tables["companySettings"]["Row"] | null;
+ savedViews: Tables["tableView"]["Row"][];
+ user: Tables["user"]["Row"] | null;
+ groups: string[];
+ defaults: Views["userDefaults"]["Row"] | null;
+ modulePreferences: Pick<
+ Tables["userModulePreference"]["Row"],
+ "module" | "position" | "hidden"
+ >[];
+ printerRoutes: PrinterRoute[];
+ implementationHub: Tables["implementationHub"]["Row"] | null;
+};
+
+/**
+ * Everything the app shell reads about the user and the company, in one round
+ * trip. `client` is the user's own client: the function runs as them, so each
+ * table's RLS applies as it did when these were separate requests.
+ */
+export async function getAppShell(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ userId: string
+) {
+ const result = await client.rpc("get_app_shell", {
+ company_id: companyId,
+ user_id: userId
+ });
+ if (result.error || !result.data) {
+ return { data: null, error: result.error ?? new Error("Empty app shell") };
+ }
+ const rows = result.data as unknown as AppShellRows;
+ return {
+ data: { ...rows, companies: rows.companies.map(withLogoUrls) },
+ error: null
+ };
+}
+
+const signalsLogger = getLogger("erp", "implementation-signals");
+
+// A day, not forever: wiping a company's data (a demo template revert, a
+// restore) can make a signal false again, and this bounds how long the hub
+// would keep showing that step as done.
+const IMPLEMENTATION_SIGNALS_TTL_SECONDS = 60 * 60 * 24;
+
+const implementationSignalsKey = (companyId: string) =>
+ `implementation:signals:${companyId}`;
+
+/**
+ * The hub's product signals, probing only the ones not already seen true.
+ *
+ * The app shell loads these on every page for an enrolled company — five
+ * existence queries each time. A signal that is true stays true, so it is
+ * remembered per company and its probe is skipped; a company that has done
+ * all five steps costs one Redis read instead.
+ */
+export async function getImplementationSignals(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<Signals> {
+ let known: Partial<Signals> = {};
+ try {
+ const cached = await redis.get(implementationSignalsKey(companyId));
+ if (cached) known = JSON.parse(cached) as Partial<Signals>;
+ } catch (error) {
+ // Redis is an optimisation here; without it, probe everything.
+ signalsLogger.warn("Could not read cached implementation signals", {
+ companyId,
+ error
+ });
+ }
+
+ const signals = await detectImplementationSignals(client, companyId, known);
+
+ const seen = Object.fromEntries(
+ Object.entries(signals).filter(([, value]) => value)
+ ) as Partial<Signals>;
+ if (Object.keys(seen).length > Object.keys(known).length) {
+ try {
+ await redis.set(
+ implementationSignalsKey(companyId),
+ JSON.stringify(seen),
+ "EX",
+ IMPLEMENTATION_SIGNALS_TTL_SECONDS
+ );
+ } catch (error) {
+ signalsLogger.warn("Could not cache implementation signals", {
+ companyId,
+ error
+ });
+ }
+ }
+ return signals;
+}
+
+// The readable identifier on each action task's parent, used for the Linear
+// attachment / Jira remote-link title.
+const actionTaskParents: Record<
+ ActionTaskEntityType,
+ { parentTable: string; readableColumn: string }
+> = {
+ nonConformanceActionTask: {
+ parentTable: "nonConformance",
+ readableColumn: "nonConformanceId"
+ },
+ changeOrderActionTask: {
+ parentTable: "changeOrder",
+ readableColumn: "changeOrderId"
+ }
+};
+
+export type ActionTaskWithParent = {
+ id: string | null;
+ notes: unknown;
+ parentId: string | null;
+ parentReadableId: string | null;
+};
+
+// Entity-aware action-task read: resolves the task plus its parent (NCR or change notice) — reads an action
+// task and its parent's readable id from whichever table the entity type names.
+export async function getActionTaskWithParent(
+ client: SupabaseClient<Database>,
+ entityType: ActionTaskEntityType,
+ taskId: string,
+ companyId: string
+): Promise<ActionTaskWithParent> {
+ const { table, parentColumn } = actionTaskEntities[entityType];
+ const { parentTable, readableColumn } = actionTaskParents[entityType];
+
+ const result = await client
+ .from(table)
+ .select(`id, notes, ${parentColumn}, ${parentTable}(${readableColumn})`)
+ .eq("id", taskId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ // The select string is built from the entity map, which erases Supabase's row typing
+ const row = result.data as Record<string, any> | null;
+
+ return {
+ id: row?.id ?? null,
+ notes: row?.notes ?? null,
+ parentId: row?.[parentColumn] ?? null,
+ parentReadableId: row?.[parentTable]?.[readableColumn] ?? null
+ };
+}
+
+const ONBOARDING_DRAFT_KEY = "onboarding-draft";
+
+const onboardingDraftStorage = createCookieSessionStorage({
+ cookie: {
+ name: ONBOARDING_DRAFT_KEY,
+ path: "/",
+ secure: false,
+ httpOnly: true,
+ sameSite: "lax",
+ maxAge: 60 * 60 * 24 // 24 hours
+ }
+});
+
+export type OnboardingDraft = {
+ industry?: {
+ industryId: string;
+ customIndustryDescription?: string;
+ };
+ company?: {
+ name?: string;
+ addressLine1?: string;
+ addressLine2?: string;
+ city?: string;
+ stateProvince?: string;
+ postalCode?: string;
+ countryCode?: string;
+ baseCurrencyCode?: string;
+ timezone?: string;
+ website?: string;
+ };
+};
+
+export async function getOnboardingDraft(
+ request: Request
+): Promise<OnboardingDraft | null> {
+ const session = await onboardingDraftStorage.getSession(
+ request.headers.get("Cookie")
+ );
+ const draft = session.get(ONBOARDING_DRAFT_KEY) as
+ | OnboardingDraft
+ | undefined;
+ return draft ?? null;
+}
+
+export async function setOnboardingDraft(
+ request: Request,
+ draft: Partial<OnboardingDraft>
+): Promise<string> {
+ const session = await onboardingDraftStorage.getSession(
+ request.headers.get("Cookie")
+ );
+ const existingDraft =
+ (session.get(ONBOARDING_DRAFT_KEY) as OnboardingDraft | undefined) ?? {};
+ const updatedDraft = { ...existingDraft, ...draft };
+ session.set(ONBOARDING_DRAFT_KEY, updatedDraft);
+ return onboardingDraftStorage.commitSession(session);
+}
+
+export async function clearOnboardingDraft(request: Request): Promise<string> {
+ const session = await onboardingDraftStorage.getSession(
+ request.headers.get("Cookie")
+ );
+ session.set(ONBOARDING_DRAFT_KEY, undefined);
+ return onboardingDraftStorage.commitSession(session);
+}
diff --git a/apps/erp/app/routes/api+/integrations.jira.issue.create.ts b/apps/erp/app/routes/api+/integrations.jira.issue.create.ts
index b0e2f362e1..3d06fc7d3c 100644
--- a/apps/erp/app/routes/api+/integrations.jira.issue.create.ts
+++ b/apps/erp/app/routes/api+/integrations.jira.issue.create.ts
@@ -20,7 +20,7 @@ import { getLogger } from "@carbon/logger";
import type { ActionFunction, LoaderFunction } from "react-router";
import { data } from "react-router";
import { requireChangeNoticeEditable } from "~/modules/items/items.server";
-import { getActionTaskWithParent } from "~/services/action-task.server";
+import { getActionTaskWithParent } from "~/modules/shared/shared.server";
const logger = getLogger("erp", "integrations-jira-issue-create");
diff --git a/apps/erp/app/routes/api+/integrations.jira.issue.link.ts b/apps/erp/app/routes/api+/integrations.jira.issue.link.ts
index d6900d0f8b..47d6494d5b 100644
--- a/apps/erp/app/routes/api+/integrations.jira.issue.link.ts
+++ b/apps/erp/app/routes/api+/integrations.jira.issue.link.ts
@@ -21,7 +21,7 @@ import { getLogger } from "@carbon/logger";
import type { ActionFunction, LoaderFunction } from "react-router";
import { data } from "react-router";
import { requireChangeNoticeEditable } from "~/modules/items/items.server";
-import { getActionTaskWithParent } from "~/services/action-task.server";
+import { getActionTaskWithParent } from "~/modules/shared/shared.server";
const jira = getJiraClient();
const logger = getLogger("erp", "jira", "issue-link");
diff --git a/apps/erp/app/routes/api+/integrations.jira.issue.sync-notes.ts b/apps/erp/app/routes/api+/integrations.jira.issue.sync-notes.ts
index 9d2a27011b..1d7a2c8c1b 100644
--- a/apps/erp/app/routes/api+/integrations.jira.issue.sync-notes.ts
+++ b/apps/erp/app/routes/api+/integrations.jira.issue.sync-notes.ts
@@ -17,7 +17,7 @@ import { getLogger } from "@carbon/logger";
import type { ActionFunction } from "react-router";
import { data } from "react-router";
import { requireChangeNoticeEditable } from "~/modules/items/items.server";
-import { getActionTaskWithParent } from "~/services/action-task.server";
+import { getActionTaskWithParent } from "~/modules/shared/shared.server";
const logger = getLogger("erp", "integrations-jira-issue-sync-notes");
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.create.ts b/apps/erp/app/routes/api+/integrations.linear.issue.create.ts
index 49c2034b27..8f63b57ea4 100644
--- a/apps/erp/app/routes/api+/integrations.linear.issue.create.ts
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.create.ts
@@ -19,7 +19,7 @@ import { getLogger } from "@carbon/logger";
import type { ActionFunction, LoaderFunction } from "react-router";
import { data } from "react-router";
import { requireChangeNoticeEditable } from "~/modules/items/items.server";
-import { getActionTaskWithParent } from "~/services/action-task.server";
+import { getActionTaskWithParent } from "~/modules/shared/shared.server";
const logger = getLogger("erp", "integrations-linear-issue-create");
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.link.ts b/apps/erp/app/routes/api+/integrations.linear.issue.link.ts
index 5fdf365b77..d7365138da 100644
--- a/apps/erp/app/routes/api+/integrations.linear.issue.link.ts
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.link.ts
@@ -19,7 +19,7 @@ import { getLogger } from "@carbon/logger";
import type { ActionFunction, LoaderFunction } from "react-router";
import { data } from "react-router";
import { requireChangeNoticeEditable } from "~/modules/items/items.server";
-import { getActionTaskWithParent } from "~/services/action-task.server";
+import { getActionTaskWithParent } from "~/modules/shared/shared.server";
const logger = getLogger("erp", "integrations-linear-issue-link");
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts b/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts
index 11f56b97eb..e1673c6894 100644
--- a/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts
@@ -17,7 +17,7 @@ import { getLogger } from "@carbon/logger";
import type { ActionFunction } from "react-router";
import { data } from "react-router";
import { requireChangeNoticeEditable } from "~/modules/items/items.server";
-import { getActionTaskWithParent } from "~/services/action-task.server";
+import { getActionTaskWithParent } from "~/modules/shared/shared.server";
const logger = getLogger("erp", "integrations-linear-issue-sync-notes");
diff --git a/apps/erp/app/routes/onboarding+/company.tsx b/apps/erp/app/routes/onboarding+/company.tsx
index 6285ba21c7..3662d424b9 100644
--- a/apps/erp/app/routes/onboarding+/company.tsx
+++ b/apps/erp/app/routes/onboarding+/company.tsx
@@ -35,7 +35,7 @@ import { addressValidator, getCompany } from "~/modules/settings";
import {
getOnboardingDraft,
setOnboardingDraft
-} from "~/services/onboarding-draft.server";
+} from "~/modules/shared/shared.server";
import { ONBOARDING_SHORTCUTS } from "~/shortcuts";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/onboarding+/industry.tsx b/apps/erp/app/routes/onboarding+/industry.tsx
index 9297a50883..ccaefba2e0 100644
--- a/apps/erp/app/routes/onboarding+/industry.tsx
+++ b/apps/erp/app/routes/onboarding+/industry.tsx
@@ -52,12 +52,12 @@ import {
getIndustries,
onboardingCompanyValidator
} from "~/modules/settings";
-import { provisionOnboardingCompany } from "~/services/onboarding.server";
import {
clearOnboardingDraft,
getOnboardingDraft,
type OnboardingDraft
-} from "~/services/onboarding-draft.server";
+} from "~/modules/shared/shared.server";
+import { provisionOnboardingCompany } from "~/services/onboarding.server";
import { ONBOARDING_SHORTCUTS } from "~/shortcuts";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index ef1f9f7f16..67e8c19602 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -71,11 +71,13 @@ import { getCachedChangelogPanelEntry } from "~/modules/account/account.server";
import { AgentRoot } from "~/modules/agent/ui/AgentRoot";
import { getOpenClockEntry } from "~/modules/people";
import { employeeCompaniesOf, getEmployeeCompanies } from "~/modules/settings";
-import { getCustomFieldsSchemas } from "~/modules/shared/shared.server";
+import {
+ getAppShell,
+ getCustomFieldsSchemas,
+ getImplementationSignals
+} from "~/modules/shared/shared.server";
import { getItarCertificationStatus } from "~/modules/users";
import { getUserClaims } from "~/modules/users/users.server";
-import { getAppShell } from "~/services/app-shell.server";
-import { getImplementationSignals } from "~/services/implementation-signals.server";
import { ERP_URL, MES_URL, path } from "~/utils/path";
const log = getLogger("erp", "auth");
diff --git a/apps/erp/app/routes/x+/get-started+/_layout.tsx b/apps/erp/app/routes/x+/get-started+/_layout.tsx
index 1f66a72732..2a6bfd0cfa 100644
--- a/apps/erp/app/routes/x+/get-started+/_layout.tsx
+++ b/apps/erp/app/routes/x+/get-started+/_layout.tsx
@@ -51,7 +51,7 @@ import {
import { useFlags } from "~/hooks/useFlags";
import { useImplementationRealtime } from "~/hooks/useImplementationRealtime";
import { useImplementationSubmodules } from "~/hooks/useImplementationSubmodules";
-import { getImplementationSignals } from "~/services/implementation-signals.server";
+import { getImplementationSignals } from "~/modules/shared/shared.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { trainingConfig } from "~/utils/training";
diff --git a/apps/erp/app/services/action-task.server.ts b/apps/erp/app/services/action-task.server.ts
deleted file mode 100644
index 2e6e1db8f9..0000000000
--- a/apps/erp/app/services/action-task.server.ts
+++ /dev/null
@@ -1,60 +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.
-
-import type { Database } from "@carbon/database";
-import type { ActionTaskEntityType } from "@carbon/ee/action-task-entity";
-import { actionTaskEntities } from "@carbon/ee/action-task-entity";
-import type { SupabaseClient } from "@supabase/supabase-js";
-
-// The readable identifier on each action task's parent, used for the Linear
-// attachment / Jira remote-link title.
-const actionTaskParents: Record<
- ActionTaskEntityType,
- { parentTable: string; readableColumn: string }
-> = {
- nonConformanceActionTask: {
- parentTable: "nonConformance",
- readableColumn: "nonConformanceId"
- },
- changeOrderActionTask: {
- parentTable: "changeOrder",
- readableColumn: "changeOrderId"
- }
-};
-
-export type ActionTaskWithParent = {
- id: string | null;
- notes: unknown;
- parentId: string | null;
- parentReadableId: string | null;
-};
-
-// Entity-aware action-task read: resolves the task plus its parent (NCR or change notice) — reads an action
-// task and its parent's readable id from whichever table the entity type names.
-export async function getActionTaskWithParent(
- client: SupabaseClient<Database>,
- entityType: ActionTaskEntityType,
- taskId: string,
- companyId: string
-): Promise<ActionTaskWithParent> {
- const { table, parentColumn } = actionTaskEntities[entityType];
- const { parentTable, readableColumn } = actionTaskParents[entityType];
-
- const result = await client
- .from(table)
- .select(`id, notes, ${parentColumn}, ${parentTable}(${readableColumn})`)
- .eq("id", taskId)
- .eq("companyId", companyId)
- .maybeSingle();
-
- // The select string is built from the entity map, which erases Supabase's row typing
- const row = result.data as Record<string, any> | null;
-
- return {
- id: row?.id ?? null,
- notes: row?.notes ?? null,
- parentId: row?.[parentColumn] ?? null,
- parentReadableId: row?.[parentTable]?.[readableColumn] ?? null
- };
-}
diff --git a/apps/erp/app/services/app-shell.server.ts b/apps/erp/app/services/app-shell.server.ts
deleted file mode 100644
index 1ef5a768d2..0000000000
--- a/apps/erp/app/services/app-shell.server.ts
+++ /dev/null
@@ -1,53 +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.
-
-import type { Database } from "@carbon/database";
-import type { PrinterRoute } from "@carbon/printing";
-import type { SupabaseClient } from "@supabase/supabase-js";
-import { withLogoUrls } from "~/modules/settings";
-
-type Tables = Database["public"]["Tables"];
-type Views = Database["public"]["Views"];
-
-// What `get_app_shell` returns: the rows the shell used to read with nine
-// requests. Each key holds what `select("*")` on that table returned.
-type AppShellRows = {
- companies: Views["companies"]["Row"][];
- companyIntegrations: Tables["companyIntegration"]["Row"][];
- companySettings: Tables["companySettings"]["Row"] | null;
- savedViews: Tables["tableView"]["Row"][];
- user: Tables["user"]["Row"] | null;
- groups: string[];
- defaults: Views["userDefaults"]["Row"] | null;
- modulePreferences: Pick<
- Tables["userModulePreference"]["Row"],
- "module" | "position" | "hidden"
- >[];
- printerRoutes: PrinterRoute[];
- implementationHub: Tables["implementationHub"]["Row"] | null;
-};
-
-/**
- * Everything the app shell reads about the user and the company, in one round
- * trip. `client` is the user's own client: the function runs as them, so each
- * table's RLS applies as it did when these were separate requests.
- */
-export async function getAppShell(
- client: SupabaseClient<Database>,
- companyId: string,
- userId: string
-) {
- const result = await client.rpc("get_app_shell", {
- company_id: companyId,
- user_id: userId
- });
- if (result.error || !result.data) {
- return { data: null, error: result.error ?? new Error("Empty app shell") };
- }
- const rows = result.data as unknown as AppShellRows;
- return {
- data: { ...rows, companies: rows.companies.map(withLogoUrls) },
- error: null
- };
-}
diff --git a/apps/erp/app/services/implementation-signals.server.ts b/apps/erp/app/services/implementation-signals.server.ts
deleted file mode 100644
index fa482506ac..0000000000
--- a/apps/erp/app/services/implementation-signals.server.ts
+++ /dev/null
@@ -1,58 +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.
-
-import type { Database } from "@carbon/database";
-import { redis } from "@carbon/kv";
-import { getLogger } from "@carbon/logger";
-import type { Signals } from "@carbon/onboarding";
-import { detectImplementationSignals } from "@carbon/onboarding/server";
-import type { SupabaseClient } from "@supabase/supabase-js";
-
-const log = getLogger("erp", "implementation-signals");
-
-// A day, not forever: wiping a company's data (a demo template revert, a
-// restore) can make a signal false again, and this bounds how long the hub
-// would keep showing that step as done.
-const TTL_SECONDS = 60 * 60 * 24;
-
-const key = (companyId: string) => `implementation:signals:${companyId}`;
-
-/**
- * The hub's product signals, probing only the ones not already seen true.
- *
- * The app shell loads these on every page for an enrolled company — five
- * existence queries each time. A signal that is true stays true, so it is
- * remembered per company and its probe is skipped; a company that has done
- * all five steps costs one Redis read instead.
- */
-export async function getImplementationSignals(
- client: SupabaseClient<Database>,
- companyId: string
-): Promise<Signals> {
- let known: Partial<Signals> = {};
- try {
- const cached = await redis.get(key(companyId));
- if (cached) known = JSON.parse(cached) as Partial<Signals>;
- } catch (error) {
- // Redis is an optimisation here; without it, probe everything.
- log.warn("Could not read cached implementation signals", {
- companyId,
- error
- });
- }
-
- const signals = await detectImplementationSignals(client, companyId, known);
-
- const seen = Object.fromEntries(
- Object.entries(signals).filter(([, value]) => value)
- ) as Partial<Signals>;
- if (Object.keys(seen).length > Object.keys(known).length) {
- try {
- await redis.set(key(companyId), JSON.stringify(seen), "EX", TTL_SECONDS);
- } catch (error) {
- log.warn("Could not cache implementation signals", { companyId, error });
- }
- }
- return signals;
-}
diff --git a/apps/erp/app/services/onboarding-draft.server.ts b/apps/erp/app/services/onboarding-draft.server.ts
deleted file mode 100644
index 6c940b507c..0000000000
--- a/apps/erp/app/services/onboarding-draft.server.ts
+++ /dev/null
@@ -1,71 +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.
-
-import { createCookieSessionStorage } from "react-router";
-
-const ONBOARDING_DRAFT_KEY = "onboarding-draft";
-
-const sessionStorage = createCookieSessionStorage({
- cookie: {
- name: ONBOARDING_DRAFT_KEY,
- path: "/",
- secure: false,
- httpOnly: true,
- sameSite: "lax",
- maxAge: 60 * 60 * 24 // 24 hours
- }
-});
-
-export type OnboardingDraft = {
- industry?: {
- industryId: string;
- customIndustryDescription?: string;
- };
- company?: {
- name?: string;
- addressLine1?: string;
- addressLine2?: string;
- city?: string;
- stateProvince?: string;
- postalCode?: string;
- countryCode?: string;
- baseCurrencyCode?: string;
- timezone?: string;
- website?: string;
- };
-};
-
-export async function getOnboardingDraft(
- request: Request
-): Promise<OnboardingDraft | null> {
- const session = await sessionStorage.getSession(
- request.headers.get("Cookie")
- );
- const draft = session.get(ONBOARDING_DRAFT_KEY) as
- | OnboardingDraft
- | undefined;
- return draft ?? null;
-}
-
-export async function setOnboardingDraft(
- request: Request,
- draft: Partial<OnboardingDraft>
-): Promise<string> {
- const session = await sessionStorage.getSession(
- request.headers.get("Cookie")
- );
- const existingDraft =
- (session.get(ONBOARDING_DRAFT_KEY) as OnboardingDraft | undefined) ?? {};
- const updatedDraft = { ...existingDraft, ...draft };
- session.set(ONBOARDING_DRAFT_KEY, updatedDraft);
- return sessionStorage.commitSession(session);
-}
-
-export async function clearOnboardingDraft(request: Request): Promise<string> {
- const session = await sessionStorage.getSession(
- request.headers.get("Cookie")
- );
- session.set(ONBOARDING_DRAFT_KEY, undefined);
- return sessionStorage.commitSession(session);
-}