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
feat: add setting for generating material id
Brad Barbinb46c4b80d5a8
diff --git a/apps/erp/app/components/Form/MaterialDimension.tsx b/apps/erp/app/components/Form/MaterialDimension.tsxindex d870f4e78e..39660bf52f 100644--- a/apps/erp/app/components/Form/MaterialDimension.tsx+++ b/apps/erp/app/components/Form/MaterialDimension.tsx@@ -51,6 +51,7 @@ const MaterialDimension = (props: MaterialDimensionSelectProps) => {path.to.api.materialDimensions(props.formId));}+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [props.formId]);const options = useMemo(() => {@@ -78,6 +79,7 @@ const MaterialDimension = (props: MaterialDimensionSelectProps) => {{...props}disabled={props.disabled || !props.formId}inline={props?.inline ? MaterialDimensionPreview : undefined}+ isOptional={props?.isOptional ?? true}label={props?.label ?? "Dimensions"}onChange={onChange}onCreateOption={(option) => {diff --git a/apps/erp/app/components/Form/MaterialFinish.tsx b/apps/erp/app/components/Form/MaterialFinish.tsxindex ccede629cc..d0a97d9e31 100644--- a/apps/erp/app/components/Form/MaterialFinish.tsx+++ b/apps/erp/app/components/Form/MaterialFinish.tsx@@ -51,6 +51,7 @@ const MaterialFinish = (props: MaterialFinishSelectProps) => {path.to.api.materialFinishes(props.substanceId));}+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [props.substanceId]);const options = useMemo(() => {@@ -78,6 +79,7 @@ const MaterialFinish = (props: MaterialFinishSelectProps) => {{...props}disabled={props.disabled || !props.substanceId}inline={props?.inline ? MaterialFinishPreview : undefined}+ isOptional={props?.isOptional ?? true}label={props?.label ?? "Finish"}onChange={onChange}onCreateOption={(option) => {diff --git a/apps/erp/app/components/Form/MaterialGrade.tsx b/apps/erp/app/components/Form/MaterialGrade.tsxindex 8aa6fdd46f..8906a80f8f 100644--- a/apps/erp/app/components/Form/MaterialGrade.tsx+++ b/apps/erp/app/components/Form/MaterialGrade.tsx@@ -47,6 +47,7 @@ const MaterialGrade = (props: MaterialGradeSelectProps) => {if (props.substanceId) {materialGradesLoader.load(path.to.api.materialGrades(props.substanceId));}+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [props.substanceId]);const options = useMemo(() => {@@ -74,6 +75,7 @@ const MaterialGrade = (props: MaterialGradeSelectProps) => {{...props}disabled={props.disabled || !props.substanceId}inline={props?.inline ? MaterialGradePreview : undefined}+ isOptional={props?.isOptional ?? true}label={props?.label ?? "Grade"}onChange={onChange}onCreateOption={(option) => {diff --git a/apps/erp/app/hooks/useSettings.tsx b/apps/erp/app/hooks/useSettings.tsxnew file mode 100644index 0000000000..f7559b1bd4--- /dev/null+++ b/apps/erp/app/hooks/useSettings.tsx@@ -0,0 +1,15 @@+import type { Database } from "@carbon/database";+import { useRouteData } from "@carbon/remix";+import { path } from "~/utils/path";++export function useSettings(): Database["public"]["Tables"]["companySettings"]["Row"] {+ const routeData = useRouteData<{+ companySettings: Database["public"]["Tables"]["companySettings"]["Row"];+ }>(path.to.authenticatedRoot);++ if (!routeData?.companySettings) {+ throw new Error("Company settings not found");+ }++ return routeData.companySettings;+}diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex 48dc3dc2eb..1a081c75f5 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -178,12 +178,21 @@ export const materialValidator = itemValidator.merge(id: z.string().min(1, { message: "Material ID is required" }).max(255),materialSubstanceId: zfd.text(z.string().optional()),materialFormId: zfd.text(z.string().optional()),- finish: z.string().optional(),- grade: z.string().optional(),- dimensions: z.string().optional(),+ finish: zfd.text(z.string().optional()),+ grade: zfd.text(z.string().optional()),+ dimensions: zfd.text(z.string().optional()),}));+export const materialValidatorWithGeneratedIds = z.object({+ id: z.string().min(1, { message: "" }),+ materialSubstanceId: z.string().min(1, { message: "Substance is required" }),+ materialFormId: z.string().min(1, { message: "Shape is required" }),+ finish: zfd.text(z.string().optional()),+ grade: zfd.text(z.string().optional()),+ dimensions: zfd.text(z.string().optional()),+});+export const methodMaterialValidator = z.object({id: zfd.text(z.string().optional()),diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsxindex 211acc986f..2852fda722 100644--- a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx@@ -33,8 +33,13 @@ import MaterialGrade from "~/components/Form/MaterialGrade";import Shape from "~/components/Form/Shape";import Substance from "~/components/Form/Substance";import { useNextItemId, usePermissions, useUser } from "~/hooks";+import { useSettings } from "~/hooks/useSettings";import { path } from "~/utils/path";-import { itemTrackingTypes, materialValidator } from "../../items.models";+import {+ itemTrackingTypes,+ materialValidator,+ materialValidatorWithGeneratedIds,+} from "../../items.models";type MaterialFormProps = {initialValues: z.infer<typeof materialValidator> & { tags?: string[] };@@ -128,7 +133,8 @@ const MaterialForm = ({}, [id]);const permissions = usePermissions();- const [withCustomId, setWithCustomId] = useState(false);+ const companySettings = useSettings();+ const useCustomId = companySettings.materialGeneratedIds === false;const [defaultMethodType, setDefaultMethodType] = useState<string>(initialValues.defaultMethodType ?? "Buy"@@ -151,7 +157,11 @@ const MaterialForm = ({<ValidatedFormaction={path.to.newMaterial}method="post"- validator={materialValidator}+ validator={+ useCustomId+ ? materialValidator+ : materialValidatorWithGeneratedIds+ }defaultValues={initialValues}fetcher={fetcher}>@@ -165,7 +175,7 @@ const MaterialForm = ({<ModalCardBody><Hidden name="type" value={type} /><Hidden name="replenishmentSystem" value="Buy" />- {!withCustomId && (+ {!useCustomId && (<><Hidden name="id" value={materialId} /><Hidden name="name" value={description} />@@ -177,7 +187,7 @@ const MaterialForm = ({"grid-cols-1 md:grid-cols-2")}>- {withCustomId && (+ {useCustomId && (<><InputControlledname="id"diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex 2ee2410bb3..94ed2f6729 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -76,6 +76,10 @@ export const digitalQuoteValidator = z.object({digitalQuoteIncludesPurchaseOrders: zfd.checkbox(),});+export const materialIdsValidator = z.object({+ materialGeneratedIds: zfd.checkbox(),+});+export const productLabelSizeValidator = z.object({productLabelSize: z.enum(labelSizes.map((size) => size.id) as [string, ...string[]],diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex d3230e22cd..b618551e97 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -533,6 +533,22 @@ export async function updateLogoLightIcon(.eq("id", companyId);}+export async function updateMaterialGeneratedIdsSetting(+ client: SupabaseClient<Database>,+ companyId: string,+ materialGeneratedIds: boolean+) {+ console.log("materialGeneratedIds", materialGeneratedIds);+ return client+ .from("companySettings")+ .update(+ sanitize({+ materialGeneratedIds,+ })+ )+ .eq("id", companyId);+}+export async function updateProductLabelSize(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsxindex d60e749396..313a487df8 100644--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx@@ -7,6 +7,7 @@ import {LuLayoutDashboard,LuSheet,LuShoppingCart,+ LuSquareStack,LuWebhook,LuWorkflow,} from "react-icons/lu";@@ -48,6 +49,12 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [{name: "Modules",routes: [+ {+ name: "Items",+ to: path.to.itemsSettings,+ role: "employee",+ icon: <LuSquareStack />,+ },{name: "Purchasing",to: path.to.purchasingSettings,diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex 5cdd5c4996..ce68a3a350 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -22,7 +22,11 @@ import posthog from "posthog-js";import { LuArrowUpRight, LuX } from "react-icons/lu";import { RealtimeDataProvider } from "~/components";import { PrimaryNavigation, Topbar } from "~/components/Layout";-import { getCompanies, getCompanyIntegrations } from "~/modules/settings";+import {+ getCompanies,+ getCompanyIntegrations,+ getCompanySettings,+} from "~/modules/settings";import { getCustomFieldsSchemas } from "~/modules/shared/shared.server";import {getUser,@@ -76,6 +80,7 @@ export async function loader({ request }: LoaderFunctionArgs) {stripeCustomer,customFields,integrations,+ companySettings,savedViews,user,claims,@@ -86,6 +91,7 @@ export async function loader({ request }: LoaderFunctionArgs) {getStripeCustomerByCompanyId(companyId),getCustomFieldsSchemas(client, { companyId }),getCompanyIntegrations(client, companyId),+ getCompanySettings(client, companyId),getSavedViews(client, userId, companyId),getUser(client, userId),getUserClaims(userId, companyId),@@ -113,6 +119,7 @@ export async function loader({ request }: LoaderFunctionArgs) {},company,companies: companies.data ?? [],+ companySettings: companySettings.data,customFields: customFields.data ?? [],defaults: defaults.data,integrations: integrations.data ?? [],diff --git a/apps/erp/app/routes/x+/settings+/items.tsx b/apps/erp/app/routes/x+/settings+/items.tsxnew file mode 100644index 0000000000..7ba2961e6b--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/items.tsx@@ -0,0 +1,147 @@+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ Heading,+ ScrollArea,+ toast,+ VStack,+} from "@carbon/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";++import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { Boolean, Submit, ValidatedForm, validator } from "@carbon/form";+import { useFetcher, useLoaderData } from "@remix-run/react";+import { useEffect } from "react";+import {+ getCompanySettings,+ materialIdsValidator,+ updateMaterialGeneratedIdsSetting,+} from "~/modules/settings";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: "Items",+ to: path.to.itemsSettings,+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings",+ });++ const [companySettings] = await Promise.all([+ getCompanySettings(client, companyId),+ ]);+ if (!companySettings.data)+ throw redirect(+ path.to.settings,+ await flash(+ request,+ error(companySettings.error, "Failed to get company settings")+ )+ );+ return json({ companySettings: companySettings.data });+}++export async function action({ request }: ActionFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "settings",+ });++ const formData = await request.formData();+ const intent = formData.get("intent");++ switch (intent) {+ case "materialGeneratedIds":+ const validation = await validator(materialIdsValidator).validate(+ formData+ );++ if (validation.error) {+ return json({ success: false, message: "Invalid form data" });+ }++ const materialGeneratedIds = await updateMaterialGeneratedIdsSetting(+ client,+ companyId,+ validation.data.materialGeneratedIds+ );+ if (materialGeneratedIds.error)+ return json({+ success: false,+ message: materialGeneratedIds.error.message,+ });++ return json({ success: true, message: "Material IDs setting updated" });+ }++ return json({ success: false, message: "Invalid form data" });+}++export default function ItemsSettingsRoute() {+ const { companySettings } = useLoaderData<typeof loader>();+ const fetcher = useFetcher<typeof action>();++ useEffect(() => {+ if (fetcher.data?.success === true && fetcher?.data?.message) {+ toast.success(fetcher.data.message);+ }++ if (fetcher.data?.success === false && fetcher?.data?.message) {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.data?.message, fetcher.data?.success]);++ return (+ <ScrollArea className="w-full h-[calc(100dvh-49px)]">+ <VStack+ spacing={4}+ className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"+ >+ <Heading size="h3">Sales</Heading>+ <Card>+ <ValidatedForm+ method="post"+ validator={materialIdsValidator}+ defaultValues={{+ materialGeneratedIds: companySettings.materialGeneratedIds ?? [],+ }}+ fetcher={fetcher}+ >+ <input type="hidden" name="intent" value="materialGeneratedIds" />+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ Material IDs+ </CardTitle>+ <CardDescription>+ Generate material IDs and descriptions based on the properties+ of the material.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col gap-8 max-w-[400px]">+ <div className="flex flex-col gap-2">+ <Boolean+ name="materialGeneratedIds"+ description="Generate material IDs"+ />+ </div>+ </div>+ </CardContent>+ <CardFooter>+ <Submit>Save</Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ </VStack>+ </ScrollArea>+ );+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 0b992a8cb2..27beddb8ee 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -691,6 +691,7 @@ export const path = {itemCostUpdate: (id: string) => generatePath(`${x}/items/cost/${id}`),itemPostingGroup: (id: string) => generatePath(`${x}/items/groups/${id}`),itemPostingGroups: `${x}/items/groups`,+ itemsSettings: `${x}/settings/items`,job: (id: string) => generatePath(`${x}/job/${id}`),jobBatchNumber: (id: string) => generatePath(`${x}/job/${id}/batch`),jobComplete: (id: string) => generatePath(`${x}/job/${id}/complete`),diff --git a/llm/cache/material-tables.md b/llm/cache/material-tables.mdnew file mode 100644index 0000000000..b0216b401c--- /dev/null+++ b/llm/cache/material-tables.md@@ -0,0 +1,86 @@+# Material Tables Schema++## Overview++Carbon implements a comprehensive material management system with separate tables for material properties including dimensions, finishes, and grades. These tables were created in migration `20250719100358_material-seed.sql`.++## Material Table++The main `material` table stores material records with the following columns:++- `id`: string (primary key)+- `companyId`: string (required)+- `materialFormId`: string | null (references materialForm table)+- `materialSubstanceId`: string | null (references materialSubstance table)+- `dimensions`: string | null (now references materialDimension.id)+- `finish`: string | null (now references materialFinish.id)+- `grade`: string | null (now references materialGrade.id)+- `approved`: boolean+- `approvedBy`: string | null+- `customFields`: Json | null+- `tags`: string[] | null+- `externalId`: Json | null+- `createdAt`: string+- `createdBy`: string+- `updatedAt`: string | null+- `updatedBy`: string | null++## Material Property Tables++### materialDimension Table++Stores material dimensions specific to material forms:++- `id`: string (primary key)+- `materialFormId`: string (required, references materialForm)+- `name`: string (required)+- `companyId`: string | null (for company-specific dimensions)++Has a unique constraint on `(materialFormId, name, companyId)`.++### materialFinish Table++Stores material finishes specific to material substances:++- `id`: string (primary key)+- `materialSubstanceId`: string (required, references materialSubstance)+- `name`: string (required)+- `companyId`: string | null (for company-specific finishes)++Has a unique constraint on `(materialSubstanceId, name, companyId)`.++### materialGrade Table++Stores material grades specific to material substances:++- `id`: string (primary key)+- `materialSubstanceId`: string (required, references materialSubstance)+- `name`: string (required)+- `companyId`: string | null (for company-specific grades)++Has a unique constraint on `(materialSubstanceId, name, companyId)`.++## Views++Each property table has an associated view that joins with the parent table:++- `materialDimensions`: Joins with materialForm to include `formName`+- `materialFinishes`: Joins with materialSubstance to include `substanceName`+- `materialGrades`: Joins with materialSubstance to include `substanceName`++## Key Relationships++1. **Material → MaterialDimension**: The `dimensions` column in the material table references `materialDimension.id`+2. **Material → MaterialFinish**: The `finish` column in the material table references `materialFinish.id`+3. **Material → MaterialGrade**: The `grade` column in the material table references `materialGrade.id`+4. **MaterialDimension → MaterialForm**: Each dimension is specific to a form (e.g., sheet, plate, round bar)+5. **MaterialFinish → MaterialSubstance**: Each finish is specific to a substance (e.g., steel, aluminum)+6. **MaterialGrade → MaterialSubstance**: Each grade is specific to a substance++## System vs Company Data++All three property tables support both system-wide and company-specific entries:+- System entries have `companyId = null` and are available to all companies+- Company-specific entries have a `companyId` value and are only available to that company++The migration seeds the database with comprehensive system-wide entries for common dimensions, finishes, and grades across various material forms and substances.\ No newline at end of filediff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex b07e0e779a..706ada6e5d 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -2245,7 +2245,6 @@ export type Database = {rfqReadyNotificationGroup: string[];salesJobCompletedNotificationGroup: string[];shelfLabelSize: string | null;- useMetric: boolean;};Insert: {digitalQuoteEnabled?: boolean;@@ -2258,7 +2257,6 @@ export type Database = {rfqReadyNotificationGroup?: string[];salesJobCompletedNotificationGroup?: string[];shelfLabelSize?: string | null;- useMetric?: boolean;};Update: {digitalQuoteEnabled?: boolean;@@ -2271,7 +2269,6 @@ export type Database = {rfqReadyNotificationGroup?: string[];salesJobCompletedNotificationGroup?: string[];shelfLabelSize?: string | null;- useMetric?: boolean;};Relationships: [{@@ -38733,14 +38730,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey";- columns: ["supplierLocationId"];+ columns: ["id"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];},{foreignKeyName: "partner_id_fkey";- columns: ["id"];+ columns: ["supplierLocationId"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];@@ -40080,14 +40077,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["supplierCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["supplierCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex b07e0e779a..706ada6e5d 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -2245,7 +2245,6 @@ export type Database = {rfqReadyNotificationGroup: string[];salesJobCompletedNotificationGroup: string[];shelfLabelSize: string | null;- useMetric: boolean;};Insert: {digitalQuoteEnabled?: boolean;@@ -2258,7 +2257,6 @@ export type Database = {rfqReadyNotificationGroup?: string[];salesJobCompletedNotificationGroup?: string[];shelfLabelSize?: string | null;- useMetric?: boolean;};Update: {digitalQuoteEnabled?: boolean;@@ -2271,7 +2269,6 @@ export type Database = {rfqReadyNotificationGroup?: string[];salesJobCompletedNotificationGroup?: string[];shelfLabelSize?: string | null;- useMetric?: boolean;};Relationships: [{@@ -38733,14 +38730,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey";- columns: ["supplierLocationId"];+ columns: ["id"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];},{foreignKeyName: "partner_id_fkey";- columns: ["id"];+ columns: ["supplierLocationId"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];@@ -40080,14 +40077,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["supplierCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["supplierCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];diff --git a/packages/database/supabase/migrations/20250719100358_material-seed.sql b/packages/database/supabase/migrations/20250719100358_material-seed.sqlindex 7f5e19d167..e17a717c0b 100644--- a/packages/database/supabase/migrations/20250719100358_material-seed.sql+++ b/packages/database/supabase/migrations/20250719100358_material-seed.sql@@ -1,3 +1,5 @@+ALTER TABLE "companySettings" ADD COLUMN "materialGeneratedIds" BOOLEAN NOT NULL DEFAULT FALSE;+INSERT INTO "materialForm" ("id", "name", "createdBy") VALUES('angle', 'Angle', 'system'),('channel', 'Channel', 'system'),@@ -495,3 +497,5 @@ INSERT INTO "materialDimension" ("id", "materialFormId", "name", "companyId") VA('pellet-20', 'pellet', '20 mesh', null);++diff --git a/packages/database/supabase/migrations/20250721100955_material-dimension-finish-grade-ids.sql b/packages/database/supabase/migrations/20250721100955_material-dimension-finish-grade-ids.sqlnew file mode 100644index 0000000000..de80f9e452--- /dev/null+++ b/packages/database/supabase/migrations/20250721100955_material-dimension-finish-grade-ids.sql@@ -0,0 +1,16 @@+-- Add new ID columns for dimension, finish, and grade+ALTER TABLE "material"+ ADD COLUMN "dimensionId" TEXT,+ ADD COLUMN "finishId" TEXT,+ ADD COLUMN "gradeId" TEXT;++-- Add foreign key constraints+ALTER TABLE "material"+ ADD CONSTRAINT "material_dimensionId_fkey" FOREIGN KEY ("dimensionId") REFERENCES "materialDimension"("id"),+ ADD CONSTRAINT "material_finishId_fkey" FOREIGN KEY ("finishId") REFERENCES "materialFinish"("id"),+ ADD CONSTRAINT "material_gradeId_fkey" FOREIGN KEY ("gradeId") REFERENCES "materialGrade"("id");++-- Create indexes for better performance+CREATE INDEX "material_dimensionId_idx" ON "material"("dimensionId");+CREATE INDEX "material_finishId_idx" ON "material"("finishId");+CREATE INDEX "material_gradeId_idx" ON "material"("gradeId");\ No newline at end of filediff --git a/packages/database/supabase/migrations/20250721101024_material-data-migration.sql b/packages/database/supabase/migrations/20250721101024_material-data-migration.sqlnew file mode 100644index 0000000000..c2f5b8e3b0--- /dev/null+++ b/packages/database/supabase/migrations/20250721101024_material-data-migration.sql@@ -0,0 +1,134 @@+-- Migrate dimension data+-- First, insert any company-specific dimensions that don't exist in the global table+INSERT INTO "materialDimension" ("materialFormId", "name", "companyId")+SELECT DISTINCT+ m."materialFormId",+ m."dimensions",+ m."companyId"+FROM "material" m+WHERE m."dimensions" IS NOT NULL+ AND m."companyId" IS NOT NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "materialDimension" md+ WHERE md."name" = m."dimensions"+ AND md."companyId" IS NULL+ AND md."materialFormId" = m."materialFormId"+ )+ AND NOT EXISTS (+ SELECT 1+ FROM "materialDimension" md+ WHERE md."name" = m."dimensions"+ AND md."companyId" = m."companyId"+ AND md."materialFormId" = m."materialFormId"+ );++-- Update material dimensionId to use global entries where they exist, otherwise company-specific+UPDATE "material" m+SET "dimensionId" = COALESCE(+ -- First try to find a global entry (companyId = null)+ (SELECT md."id"+ FROM "materialDimension" md+ WHERE md."name" = m."dimensions"+ AND md."companyId" IS NULL+ AND md."materialFormId" = m."materialFormId"+ LIMIT 1),+ -- If no global entry, use company-specific+ (SELECT md."id"+ FROM "materialDimension" md+ WHERE md."name" = m."dimensions"+ AND md."companyId" = m."companyId"+ AND md."materialFormId" = m."materialFormId"+ LIMIT 1)+)+WHERE m."dimensions" IS NOT NULL;++-- Migrate finish data+-- First, insert any company-specific finishes that don't exist in the global table+INSERT INTO "materialFinish" ("materialSubstanceId", "name", "companyId")+SELECT DISTINCT+ m."materialSubstanceId",+ m."finish",+ m."companyId"+FROM "material" m+WHERE m."finish" IS NOT NULL+ AND m."companyId" IS NOT NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "materialFinish" mf+ WHERE mf."name" = m."finish"+ AND mf."companyId" IS NULL+ AND mf."materialSubstanceId" = m."materialSubstanceId"+ )+ AND NOT EXISTS (+ SELECT 1+ FROM "materialFinish" mf+ WHERE mf."name" = m."finish"+ AND mf."companyId" = m."companyId"+ AND mf."materialSubstanceId" = m."materialSubstanceId"+ );++-- Update material finishId to use global entries where they exist, otherwise company-specific+UPDATE "material" m+SET "finishId" = COALESCE(+ -- First try to find a global entry (companyId = null)+ (SELECT mf."id"+ FROM "materialFinish" mf+ WHERE mf."name" = m."finish"+ AND mf."companyId" IS NULL+ AND mf."materialSubstanceId" = m."materialSubstanceId"+ LIMIT 1),+ -- If no global entry, use company-specific+ (SELECT mf."id"+ FROM "materialFinish" mf+ WHERE mf."name" = m."finish"+ AND mf."companyId" = m."companyId"+ AND mf."materialSubstanceId" = m."materialSubstanceId"+ LIMIT 1)+)+WHERE m."finish" IS NOT NULL;++-- Migrate grade data+-- First, insert any company-specific grades that don't exist in the global table+INSERT INTO "materialGrade" ("materialSubstanceId", "name", "companyId")+SELECT DISTINCT+ m."materialSubstanceId",+ m."grade",+ m."companyId"+FROM "material" m+WHERE m."grade" IS NOT NULL+ AND m."companyId" IS NOT NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "materialGrade" mg+ WHERE mg."name" = m."grade"+ AND mg."companyId" IS NULL+ AND mg."materialSubstanceId" = m."materialSubstanceId"+ )+ AND NOT EXISTS (+ SELECT 1+ FROM "materialGrade" mg+ WHERE mg."name" = m."grade"+ AND mg."companyId" = m."companyId"+ AND mg."materialSubstanceId" = m."materialSubstanceId"+ );++-- Update material gradeId to use global entries where they exist, otherwise company-specific+UPDATE "material" m+SET "gradeId" = COALESCE(+ -- First try to find a global entry (companyId = null)+ (SELECT mg."id"+ FROM "materialGrade" mg+ WHERE mg."name" = m."grade"+ AND mg."companyId" IS NULL+ AND mg."materialSubstanceId" = m."materialSubstanceId"+ LIMIT 1),+ -- If no global entry, use company-specific+ (SELECT mg."id"+ FROM "materialGrade" mg+ WHERE mg."name" = m."grade"+ AND mg."companyId" = m."companyId"+ AND mg."materialSubstanceId" = m."materialSubstanceId"+ LIMIT 1)+)+WHERE m."grade" IS NOT NULL;\ No newline at end of filediff --git a/packages/database/supabase/migrations/20250721101110_material-drop-text-columns.sql b/packages/database/supabase/migrations/20250721101110_material-drop-text-columns.sqlnew file mode 100644index 0000000000..81625cf08f--- /dev/null+++ b/packages/database/supabase/migrations/20250721101110_material-drop-text-columns.sql@@ -0,0 +1,44 @@+-- Drop the old unique constraint that includes the text columns+ALTER TABLE "material" DROP CONSTRAINT "material_unique";++-- Create new unique constraint with the ID columns+ALTER TABLE "material" ADD CONSTRAINT "material_unique"+ UNIQUE ("materialFormId", "materialSubstanceId", "gradeId", "dimensionId", "finishId", "companyId");++-- Drop the old text columns+ALTER TABLE "material"+ DROP COLUMN "dimensions",+ DROP COLUMN "finish",+ DROP COLUMN "grade";++-- Update the materials view if it exists+DROP VIEW IF EXISTS "materials";++CREATE OR REPLACE VIEW "materials" WITH(SECURITY_INVOKER=true) AS+ SELECT+ m."id",+ m."materialFormId",+ m."materialSubstanceId",+ m."dimensionId",+ m."finishId",+ m."gradeId",+ m."approved",+ m."approvedBy",+ m."customFields",+ m."companyId",+ m."createdBy",+ m."createdAt",+ m."updatedBy",+ m."updatedAt",+ m."tags",+ mf."name" AS "formName",+ ms."name" AS "substanceName",+ md."name" AS "dimensions",+ mfin."name" AS "finish",+ mg."name" AS "grade"+ FROM "material" m+ LEFT JOIN "materialForm" mf ON m."materialFormId" = mf."id"+ LEFT JOIN "materialSubstance" ms ON m."materialSubstanceId" = ms."id"+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"+ LEFT JOIN "materialFinish" mfin ON m."finishId" = mfin."id"+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id";\ No newline at end of file