Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix: company save creation
Sidwebworks3be8a0fe5b98
diff --git a/apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsx b/apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsxindex 6d351b0a01..a00a2f7d5c 100644--- a/apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsx+++ b/apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsx@@ -279,7 +279,7 @@ function CompanyBreadcrumb() {action={path.to.newCompany}validator={companyValidator}method="post"- onSubmit={companyForm.onClose}+ onAfterSubmit={companyForm.onClose}defaultValues={{countryCode: "US",baseCurrencyCode: "USD",diff --git a/apps/erp/app/entry.client.tsx b/apps/erp/app/entry.client.tsxindex 224d26ad3f..fd7349cd2c 100644--- a/apps/erp/app/entry.client.tsx+++ b/apps/erp/app/entry.client.tsx@@ -28,7 +28,7 @@ ensureLoggingConfigured();//// Controlled (ITAR) environments never initialize analytics — no data about a// U.S.-Persons-only environment leaves it, even if the key is set.-if (POSTHOG_PROJECT_PUBLIC_KEY && !CONTROLLED_ENVIRONMENT) {+if (POSTHOG_PROJECT_PUBLIC_KEY?.startsWith("phc_") && !CONTROLLED_ENVIRONMENT) {posthog.init(POSTHOG_PROJECT_PUBLIC_KEY, {api_host: POSTHOG_API_HOST});diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex b0db755c74..f9ed111eeb 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-09-03T20:26:47.954Z",+ "generated": "2026-09-05T12:37:38.879Z","totalTools": 1495,"modules": 15,"tools": [diff --git a/apps/erp/app/routes/x+/settings+/company.new.tsx b/apps/erp/app/routes/x+/settings+/company.new.tsxindex 049b371820..0e6e42be30 100644--- a/apps/erp/app/routes/x+/settings+/company.new.tsx+++ b/apps/erp/app/routes/x+/settings+/company.new.tsx@@ -22,95 +22,111 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "settings", "company");export async function action({ request }: ActionFunctionArgs) {- assertIsPost(request);- const { userId } = await requirePermissions(request, {- update: ["settings", "users"]- });- const formData = await request.formData();- const validation = await validator(companyValidator).validate(formData);- if (validation.error) {- return validationError(validation.error);- }+ try {+ assertIsPost(request);+ const { userId } = await requirePermissions(request, {+ update: ["settings", "users"]+ });+ const formData = await request.formData();+ const validation = await validator(companyValidator).validate(formData);+ if (validation.error) {+ return validationError(validation.error);+ }- const client = getCarbonServiceRole();+ const client = getCarbonServiceRole();- const companyInsert = await insertCompany(client, validation.data);- if (companyInsert.error) {- logger.error("Failed to insert company", { error: companyInsert.error });- throw new Error("Fatal: failed to insert company");- }+ const companyInsert = await insertCompany(client, validation.data);+ if (companyInsert.error) {+ logger.error("Failed to insert company", { error: companyInsert.error });+ throw new Error("Fatal: failed to insert company");+ }- let companyId = companyInsert.data?.id;- if (!companyId) {- throw new Error("Fatal: failed to get company ID");- }+ let companyId = companyInsert.data?.id;+ if (!companyId) {+ throw new Error("Fatal: failed to get company ID");+ }- const seed = await seedCompany(client, companyId, userId);- if (seed.error) {- logger.error("Failed to seed company", { error: seed.error });- throw new Error("Fatal: failed to seed company");- }+ const seed = await seedCompany(client, companyId, userId);+ if (seed.error) {+ logger.error("Failed to seed company", { error: seed.error });+ throw new Error("Fatal: failed to seed company");+ }- // Controlled environments (ITAR/CUI, NIST 800-171 3.3.1) capture audit from- // day one — enable it at company creation, not just when settings are opened.- if (CONTROLLED_ENVIRONMENT) {- await enableAuditLog(client, companyId).catch((err) =>- logger.error("Failed to enable audit log for new company", { error: err })- );- }+ // Controlled environments (ITAR/CUI, NIST 800-171 3.3.1) capture audit from+ // day one — enable it at company creation, not just when settings are opened.+ if (CONTROLLED_ENVIRONMENT) {+ await enableAuditLog(client, companyId).catch((err) =>+ logger.error("Failed to enable audit log for new company", {+ error: err+ })+ );+ }- // TODO: move all of this to transaction- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const { baseCurrencyCode, ...locationData } = validation.data;- const locationInsert = await upsertLocation(client, {- ...locationData,- name: "Headquarters",- companyId,- // timezone comes from locationData — HQ shares the company's timezone.- createdBy: userId- });+ // TODO: move all of this to transaction+ // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration+ const { baseCurrencyCode, ...locationData } = validation.data;+ const locationInsert = await upsertLocation(client, {+ ...locationData,+ name: "Headquarters",+ companyId,+ // timezone comes from locationData — HQ shares the company's timezone.+ createdBy: userId+ });- if (locationInsert.error) {- logger.error("Failed to insert location", { error: locationInsert.error });- throw new Error("Fatal: failed to insert location");- }+ if (locationInsert.error) {+ logger.error("Failed to insert location", {+ error: locationInsert.error+ });+ throw new Error("Fatal: failed to insert location");+ }- const locationId = locationInsert.data?.id;- if (!locationId) {- throw new Error("Fatal: failed to get location ID");- }+ const locationId = locationInsert.data?.id;+ if (!locationId) {+ throw new Error("Fatal: failed to get location ID");+ }- const [job] = await Promise.all([- insertEmployeeJob(client, {- id: userId,- companyId,- locationId- }),- redis.del(getPermissionCacheKey(userId))- ]);+ const [job] = await Promise.all([+ insertEmployeeJob(client, {+ id: userId,+ companyId,+ locationId+ }),+ redis.del(getPermissionCacheKey(userId))+ ]);- if (job.error) {- logger.error("Failed to insert job", { error: job.error });- throw new Error("Fatal: failed to insert job");- }+ if (job.error) {+ logger.error("Failed to insert job", { error: job.error });+ throw new Error("Fatal: failed to insert job");+ }- const { data: companyRecord } = await client- .from("company")- .select("companyGroupId")- .eq("id", companyId)- .single();+ const { data: companyRecord } = await client+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();- const sessionCookie = await updateCompanySession(- request,- companyId,- companyRecord?.companyGroupId ?? ""- );- const companyIdCookie = setCompanyId(companyId);+ const sessionCookie = await updateCompanySession(+ request,+ companyId,+ companyRecord?.companyGroupId ?? ""+ );+ const companyIdCookie = setCompanyId(companyId);- throw redirect(path.to.authenticatedRoot, {- headers: [- ["Set-Cookie", sessionCookie],- ["Set-Cookie", companyIdCookie]- ]- });+ throw redirect(path.to.authenticatedRoot, {+ headers: [+ ["Set-Cookie", sessionCookie],+ ["Set-Cookie", companyIdCookie]+ ]+ });+ } catch (error) {+ // Thrown Response = React Router control flow (the success redirect above,+ // or validationError) — rethrow untouched or the client gets nothing.+ if (error instanceof Response) throw error;+ logger.error("Company create failed: {message}", {+ message: error instanceof Error ? error.message : String(error),+ stack: error instanceof Error ? error.stack : undefined,+ error+ });+ throw error;+ }}diff --git a/apps/erp/app/routes/x+/settings+/company.tsx b/apps/erp/app/routes/x+/settings+/company.tsxindex 590b0b5bcd..17fb0c172b 100644--- a/apps/erp/app/routes/x+/settings+/company.tsx+++ b/apps/erp/app/routes/x+/settings+/company.tsx@@ -50,7 +50,7 @@ export async function action({ request }: ActionFunctionArgs) {const formData = await request.formData();const validation = await validator(companyValidator).validate(formData);-+ console.log(validation.error);if (validation.error) {return validationError(validation.error);}@@ -80,6 +80,7 @@ export async function action({ request }: ActionFunctionArgs) {});} catch (err) {+ console.error(err);return data({},await flash(request, error(err, "Failed to update company"))@@ -90,6 +91,7 @@ export async function action({ request }: ActionFunctionArgs) {...validation.data,updatedBy: userId});+ console.log(update.error);if (update.error)return data({},diff --git a/apps/mes/app/entry.client.tsx b/apps/mes/app/entry.client.tsxindex 5507f6d214..5009aed1ab 100644--- a/apps/mes/app/entry.client.tsx+++ b/apps/mes/app/entry.client.tsx@@ -28,7 +28,13 @@ ensureLoggingConfigured();//// Controlled (ITAR) environments never initialize analytics — no data about a// U.S.-Persons-only environment leaves it, even if the key is set.-if (POSTHOG_PROJECT_PUBLIC_KEY && !CONTROLLED_ENVIRONMENT) {+//+// The key must be a real PostHog project key (`phc_…`), not just non-empty: a+// placeholder value (e.g. a masked "****" in a local .env) passes a truthiness+// check, and initializing with it makes posthog-js inject its remote-config+// <script> into the document before hydrateRoot(document) runs — an extra DOM+// node React can't match, so the ENTIRE document fails hydration.+if (POSTHOG_PROJECT_PUBLIC_KEY?.startsWith("phc_") && !CONTROLLED_ENVIRONMENT) {posthog.init(POSTHOG_PROJECT_PUBLIC_KEY, {api_host: POSTHOG_API_HOST});diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex d24430a038..ec57ac752e 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -70090,14 +70090,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -73517,14 +73517,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex d24430a038..ec57ac752e 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -70090,14 +70090,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -73517,14 +73517,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/form/src/components/Submit.tsx b/packages/form/src/components/Submit.tsxindex 9e4fd2abcc..0adc567ea7 100644--- a/packages/form/src/components/Submit.tsx+++ b/packages/form/src/components/Submit.tsx@@ -63,6 +63,12 @@ export const Submit = forwardRef<HTMLButtonElement, SubmitProps>(({ currentLocation, nextLocation }) =>withBlocker &&isTouched &&+ // The form's own save is not "leaving with unsaved changes": a form+ // whose action posts to a DIFFERENT route (e.g. the Add Company modal+ // on /x posting to /x/settings/company/new) submits via a cross-pathname+ // navigation, which this blocker would otherwise intercept — blocking+ // the save itself behind the Unsaved-changes dialog.+ !isSubmitting &¤tLocation.pathname !== nextLocation.pathname);