Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add and update part with item abstraction

Brad Barbinba40c6e98973
diff --git a/apps/carbon/app/modules/parts/parts.models.ts b/apps/carbon/app/modules/parts/parts.models.ts
index 4b338ece2f..50e6c056f7 100644
--- a/apps/carbon/app/modules/parts/parts.models.ts
+++ b/apps/carbon/app/modules/parts/parts.models.ts
@@ -27,18 +27,22 @@ export const partManufacturingPolicies = [
export const serviceType = ["Internal", "External"] as const;
-export const partValidator = z.object({
- id: z.string().min(1, { message: "Part ID is required" }).max(255),
+export const itemValidator = z.object({
+ id: z.string().min(1, { message: "Item ID is required" }).max(255),
name: z.string().min(1, { message: "Name is required" }).max(255),
description: zfd.text(z.string().optional()),
+ partGroupId: zfd.text(z.string().optional()),
blocked: zfd.checkbox(),
active: zfd.checkbox(),
+});
+
+export const partValidator = z.object({
+ id: z.string().min(1, { message: "Part ID is required" }).max(255),
replenishmentSystem: z.enum(partReplenishmentSystems, {
errorMap: (issue, ctx) => ({
message: "Replenishment system is required",
}),
}),
- partGroupId: zfd.text(z.string().optional()),
partType: z.enum(partTypes, {
errorMap: (issue, ctx) => ({
message: "Part type is required",
@@ -49,6 +53,8 @@ export const partValidator = z.object({
.min(1, { message: "Unit of Measure is required" }),
});
+export const newPartValidator = itemValidator.merge(partValidator);
+
export const partCostValidator = z.object({
partId: z.string().min(1, { message: "Part ID is required" }),
costingMethod: z.enum(partCostingMethods, {
diff --git a/apps/carbon/app/modules/parts/parts.service.ts b/apps/carbon/app/modules/parts/parts.service.ts
index d247b17c3a..bd1e5db83b 100644
--- a/apps/carbon/app/modules/parts/parts.service.ts
+++ b/apps/carbon/app/modules/parts/parts.service.ts
@@ -6,6 +6,7 @@ import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
+ newPartValidator,
partCostValidator,
partGroupValidator,
partInventoryValidator,
@@ -220,7 +221,7 @@ export async function getPart(
companyId: string
) {
return client
- .from("part")
+ .from("parts")
.select("*")
.eq("id", id)
.eq("companyId", companyId)
@@ -444,7 +445,7 @@ export async function insertShelf(
export async function upsertPart(
client: SupabaseClient<Database>,
part:
- | (z.infer<typeof partValidator> & {
+ | (z.infer<typeof newPartValidator> & {
companyId: string;
createdBy: string;
customFields?: Json;
@@ -472,8 +473,14 @@ export async function upsertPart(
return client
.from("part")
.insert({
- ...part,
- itemId,
+ id: part.id,
+ itemId: itemId,
+ replenishmentSystem: part.replenishmentSystem,
+ partType: part.partType,
+ unitOfMeasureCode: part.unitOfMeasureCode,
+ companyId: part.companyId,
+ createdBy: part.createdBy,
+ customFields: part.customFields,
})
.select("*")
.single();
diff --git a/apps/carbon/app/modules/parts/ui/Item/ItemForm.tsx b/apps/carbon/app/modules/parts/ui/Item/ItemForm.tsx
new file mode 100644
index 0000000000..53a9a16c74
--- /dev/null
+++ b/apps/carbon/app/modules/parts/ui/Item/ItemForm.tsx
@@ -0,0 +1,73 @@
+import type { Database } from "@carbon/database";
+import {
+ Card,
+ CardContent,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@carbon/react";
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import type { z } from "zod";
+import {
+ Boolean,
+ CustomFormFields,
+ Hidden,
+ Input,
+ PartGroup,
+ Submit,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { itemValidator } from "~/modules/parts";
+import { path } from "~/utils/path";
+import { capitalize } from "~/utils/string";
+
+type ItemFormProps = {
+ initialValues: z.infer<typeof itemValidator>;
+ type: Database["public"]["Enums"]["itemType"];
+};
+
+function getLabel(type: Database["public"]["Enums"]["itemType"]) {
+ return capitalize(type);
+}
+
+const ItemForm = ({ initialValues, type }: ItemFormProps) => {
+ const permissions = usePermissions();
+
+ return (
+ <Card>
+ <ValidatedForm
+ action={path.to.item}
+ method="post"
+ validator={itemValidator}
+ defaultValues={initialValues}
+ >
+ <CardHeader>
+ <CardTitle>{getLabel(type)}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <Hidden name="id" />
+ <div className="grid w-full gap-x-8 gap-y-2 grid-cols-1 md:grid-cols-3">
+ <Input
+ isReadOnly
+ name="readableId"
+ label={`${getLabel(type)} ID`}
+ />
+
+ <Input name="name" label="Name" />
+ <PartGroup name="partGroupId" label="Part Group" />
+
+ <Boolean name="active" label="Active" />
+ <Boolean name="blocked" label="Blocked" />
+
+ <CustomFormFields table="part" />
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Submit isDisabled={!permissions.can("update", "parts")}>Save</Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+ );
+};
+
+export default ItemForm;
diff --git a/apps/carbon/app/modules/parts/ui/Item/index.ts b/apps/carbon/app/modules/parts/ui/Item/index.ts
new file mode 100644
index 0000000000..1f9a75bf86
--- /dev/null
+++ b/apps/carbon/app/modules/parts/ui/Item/index.ts
@@ -0,0 +1,3 @@
+import ItemForm from "./ItemForm";
+
+export { ItemForm };
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
index ce0654420c..99968e50d1 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
@@ -24,12 +24,12 @@ import {
PartGroup,
Select,
Submit,
- TextArea,
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import {
+ newPartValidator,
partReplenishmentSystems,
partTypes,
partValidator,
@@ -130,7 +130,7 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
<ValidatedForm
action={isEditing ? undefined : path.to.newPart}
method="post"
- validator={partValidator}
+ validator={isEditing ? partValidator : newPartValidator}
defaultValues={initialValues}
fetcher={fetcher}
>
@@ -153,9 +153,7 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
isEditing ? "grid-cols-1 md:grid-cols-3" : "grid-cols-1"
)}
>
- {isEditing ? (
- <Input name="id" label="Part ID" isReadOnly />
- ) : (
+ {!isEditing && (
<InputControlled
name="id"
label="Part ID"
@@ -170,10 +168,11 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
/>
)}
- <Input name="name" label="Name" />
- <PartGroup name="partGroupId" label="Part Group" />
- {isEditing && (
- <TextArea name="description" label="Description" />
+ {!isEditing && (
+ <>
+ <Input name="name" label="Name" />
+ <PartGroup name="partGroupId" label="Part Group" />
+ </>
)}
<Select
name="replenishmentSystem"
@@ -190,8 +189,7 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
label="Unit of Measure"
/>
- <Boolean name="blocked" label="Blocked" />
- {isEditing && <Boolean name="active" label="Active" />}
+ {!isEditing && <Boolean name="blocked" label="Blocked" />}
<CustomFormFields table="part" />
</div>
diff --git a/apps/carbon/app/modules/parts/ui/index.ts b/apps/carbon/app/modules/parts/ui/index.ts
index 081bd9a1b2..9f9ba1951f 100644
--- a/apps/carbon/app/modules/parts/ui/index.ts
+++ b/apps/carbon/app/modules/parts/ui/index.ts
@@ -1,5 +1,6 @@
import usePartsSubmodules from "./usePartsSubmodules";
+export * from "./Item";
export * from "./Part";
export * from "./PartGroups";
export * from "./Parts";
diff --git a/apps/carbon/app/routes/x+/part+/$partId.details.tsx b/apps/carbon/app/routes/x+/part+/$partId.details.tsx
index 626f24216f..2a073b8e74 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.details.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.details.tsx
@@ -1,10 +1,11 @@
+import { VStack } from "@carbon/react";
import { validationError, validator } from "@carbon/remix-validated-form";
import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import { useRouteData } from "~/hooks";
import type { PartSummary } from "~/modules/parts";
-import { PartForm, partValidator, upsertPart } from "~/modules/parts";
+import { ItemForm, PartForm, partValidator, upsertPart } from "~/modules/parts";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { getCustomFields, setCustomFields } from "~/utils/form";
@@ -47,7 +48,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
-export default function PartBasicRoute() {
+export default function PartDetailsRoute() {
const { partId } = useParams();
if (!partId) throw new Error("Could not find partId");
const partData = useRouteData<{ partSummary: PartSummary }>(
@@ -55,18 +56,32 @@ export default function PartBasicRoute() {
);
if (!partData) throw new Error("Could not find part data");
- const initialValues = {
- id: partData.partSummary?.id ?? "",
+ const itemInitialValues = {
+ id: partData.partSummary?.itemId ?? "",
+ readableId: partData.partSummary?.id ?? "",
name: partData.partSummary?.name ?? "",
- description: partData.partSummary?.description ?? undefined,
+ description: partData.partSummary?.description ?? "",
+ partGroupId: partData.partSummary?.partGroupId ?? "",
+ active: partData.partSummary?.active ?? true,
+ blocked: partData.partSummary?.blocked ?? false,
+ };
+
+ const partInitialValues = {
+ id: partData.partSummary?.id ?? "",
partType: partData.partSummary?.partType ?? "Inventory",
- partGroupId: partData.partSummary?.partGroupId ?? undefined,
replenishmentSystem: partData.partSummary?.replenishmentSystem ?? "Buy",
unitOfMeasureCode: partData.partSummary?.unitOfMeasureCode ?? "EA",
- blocked: partData.partSummary?.blocked ?? false,
- active: partData.partSummary?.active ?? false,
...getCustomFields(partData.partSummary?.customFields ?? {}),
};
- return <PartForm key={initialValues.id} initialValues={initialValues} />;
+ return (
+ <VStack spacing={4}>
+ <ItemForm
+ key={itemInitialValues.id}
+ type="part"
+ initialValues={itemInitialValues}
+ />
+ <PartForm key={partInitialValues.id} initialValues={partInitialValues} />
+ </VStack>
+ );
}
diff --git a/apps/carbon/app/routes/x+/part+/new.tsx b/apps/carbon/app/routes/x+/part+/new.tsx
index 3a933eff2c..df01d995dc 100644
--- a/apps/carbon/app/routes/x+/part+/new.tsx
+++ b/apps/carbon/app/routes/x+/part+/new.tsx
@@ -1,7 +1,7 @@
import { validationError, validator } from "@carbon/remix-validated-form";
import type { ActionFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
-import { PartForm, partValidator, upsertPart } from "~/modules/parts";
+import { PartForm, newPartValidator, upsertPart } from "~/modules/parts";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { setCustomFields } from "~/utils/form";
@@ -18,7 +18,7 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const modal = formData.get("type") === "modal";
- const validation = await validator(partValidator).validate(formData);
+ const validation = await validator(newPartValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index c473608e36..873d9add47 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -267,6 +267,7 @@ export const path = {
integration: (name: string) =>
generatePath(`${x}/settings/integrations/${name}`),
integrations: `${x}/settings/integrations`,
+ item: `${x}/item`,
inventory: `${x}/inventory`,
invoicing: `${x}/invoicing`,
jobs: `${x}/jobs`,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 614e7ad3cf..66491ff232 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -5414,9 +5414,12 @@ export type Database = {
}
item: {
Row: {
+ active: boolean
+ blocked: boolean
companyId: string
createdAt: string
createdBy: string
+ description: string | null
id: string
name: string
partGroupId: string | null
@@ -5424,9 +5427,12 @@ export type Database = {
type: Database["public"]["Enums"]["itemType"]
}
Insert: {
+ active?: boolean
+ blocked?: boolean
companyId: string
createdAt?: string
createdBy: string
+ description?: string | null
id?: string
name: string
partGroupId?: string | null
@@ -5434,9 +5440,12 @@ export type Database = {
type: Database["public"]["Enums"]["itemType"]
}
Update: {
+ active?: boolean
+ blocked?: boolean
companyId?: string
createdAt?: string
createdBy?: string
+ description?: string | null
id?: string
name?: string
partGroupId?: string | null
@@ -5947,22 +5956,16 @@ export type Database = {
}
part: {
Row: {
- active: boolean
approved: boolean
approvedBy: string | null
assignee: string | null
- blocked: boolean
companyId: string
createdAt: string
createdBy: string
customFields: Json | null
- description: string | null
fromDate: string | null
id: string
itemId: string
- manufacturerPartNumber: string | null
- name: string
- partGroupId: string | null
partType: Database["public"]["Enums"]["partType"]
replenishmentSystem: Database["public"]["Enums"]["partReplenishmentSystem"]
toDate: string | null
@@ -5971,22 +5974,16 @@ export type Database = {
updatedBy: string | null
}
Insert: {
- active?: boolean
approved?: boolean
approvedBy?: string | null
assignee?: string | null
- blocked?: boolean
companyId: string
createdAt?: string
createdBy: string
customFields?: Json | null
- description?: string | null
fromDate?: string | null
id: string
itemId: string
- manufacturerPartNumber?: string | null
- name: string
- partGroupId?: string | null
partType: Database["public"]["Enums"]["partType"]
replenishmentSystem: Database["public"]["Enums"]["partReplenishmentSystem"]
toDate?: string | null
@@ -5995,22 +5992,16 @@ export type Database = {
updatedBy?: string | null
}
Update: {
- active?: boolean
approved?: boolean
approvedBy?: string | null
assignee?: string | null
- blocked?: boolean
companyId?: string
createdAt?: string
createdBy?: string
customFields?: Json | null
- description?: string | null
fromDate?: string | null
id?: string
itemId?: string
- manufacturerPartNumber?: string | null
- name?: string
- partGroupId?: string | null
partType?: Database["public"]["Enums"]["partType"]
replenishmentSystem?: Database["public"]["Enums"]["partReplenishmentSystem"]
toDate?: string | null
@@ -6159,13 +6150,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "part_partGroupId_fkey"
- columns: ["partGroupId"]
- isOneToOne: false
- referencedRelation: "partGroup"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "part_unitOfMeasureCode_fkey"
columns: ["unitOfMeasureCode", "companyId"]
@@ -19831,7 +19815,6 @@ export type Database = {
fromDate: string | null
id: string | null
itemId: string | null
- manufacturerPartNumber: string | null
name: string | null
partGroup: string | null
partGroupId: string | null
@@ -19846,6 +19829,13 @@ export type Database = {
updatedBy: string | null
}
Relationships: [
+ {
+ foreignKeyName: "item_partGroupId_fkey"
+ columns: ["partGroupId"]
+ isOneToOne: false
+ referencedRelation: "partGroup"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "part_approvedBy_fkey"
columns: ["approvedBy"]
@@ -19986,13 +19976,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "part_partGroupId_fkey"
- columns: ["partGroupId"]
- isOneToOne: false
- referencedRelation: "partGroup"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "part_unitOfMeasureCode_fkey"
columns: ["unitOfMeasureCode", "companyId"]
@@ -20300,9 +20283,7 @@ export type Database = {
inventoryUnitOfMeasureCode: string | null
invoicedComplete: boolean | null
locationId: string | null
- partDescription: string | null
partId: string | null
- partName: string | null
purchaseOrderId: string | null
purchaseOrderLineType:
| Database["public"]["Enums"]["purchaseOrderLineType"]
@@ -21738,9 +21719,7 @@ export type Database = {
id: string | null
invoicedComplete: boolean | null
locationId: string | null
- partDescription: string | null
partId: string | null
- partName: string | null
quantityInvoiced: number | null
quantitySent: number | null
quantityToInvoice: number | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 614e7ad3cf..66491ff232 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -5414,9 +5414,12 @@ export type Database = {
}
item: {
Row: {
+ active: boolean
+ blocked: boolean
companyId: string
createdAt: string
createdBy: string
+ description: string | null
id: string
name: string
partGroupId: string | null
@@ -5424,9 +5427,12 @@ export type Database = {
type: Database["public"]["Enums"]["itemType"]
}
Insert: {
+ active?: boolean
+ blocked?: boolean
companyId: string
createdAt?: string
createdBy: string
+ description?: string | null
id?: string
name: string
partGroupId?: string | null
@@ -5434,9 +5440,12 @@ export type Database = {
type: Database["public"]["Enums"]["itemType"]
}
Update: {
+ active?: boolean
+ blocked?: boolean
companyId?: string
createdAt?: string
createdBy?: string
+ description?: string | null
id?: string
name?: string
partGroupId?: string | null
@@ -5947,22 +5956,16 @@ export type Database = {
}
part: {
Row: {
- active: boolean
approved: boolean
approvedBy: string | null
assignee: string | null
- blocked: boolean
companyId: string
createdAt: string
createdBy: string
customFields: Json | null
- description: string | null
fromDate: string | null
id: string
itemId: string
- manufacturerPartNumber: string | null
- name: string
- partGroupId: string | null
partType: Database["public"]["Enums"]["partType"]
replenishmentSystem: Database["public"]["Enums"]["partReplenishmentSystem"]
toDate: string | null
@@ -5971,22 +5974,16 @@ export type Database = {
updatedBy: string | null
}
Insert: {
- active?: boolean
approved?: boolean
approvedBy?: string | null
assignee?: string | null
- blocked?: boolean
companyId: string
createdAt?: string
createdBy: string
customFields?: Json | null
- description?: string | null
fromDate?: string | null
id: string
itemId: string
- manufacturerPartNumber?: string | null
- name: string
- partGroupId?: string | null
partType: Database["public"]["Enums"]["partType"]
replenishmentSystem: Database["public"]["Enums"]["partReplenishmentSystem"]
toDate?: string | null
@@ -5995,22 +5992,16 @@ export type Database = {
updatedBy?: string | null
}
Update: {
- active?: boolean
approved?: boolean
approvedBy?: string | null
assignee?: string | null
- blocked?: boolean
companyId?: string
createdAt?: string
createdBy?: string
customFields?: Json | null
- description?: string | null
fromDate?: string | null
id?: string
itemId?: string
- manufacturerPartNumber?: string | null
- name?: string
- partGroupId?: string | null
partType?: Database["public"]["Enums"]["partType"]
replenishmentSystem?: Database["public"]["Enums"]["partReplenishmentSystem"]
toDate?: string | null
@@ -6159,13 +6150,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "part_partGroupId_fkey"
- columns: ["partGroupId"]
- isOneToOne: false
- referencedRelation: "partGroup"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "part_unitOfMeasureCode_fkey"
columns: ["unitOfMeasureCode", "companyId"]
@@ -19831,7 +19815,6 @@ export type Database = {
fromDate: string | null
id: string | null
itemId: string | null
- manufacturerPartNumber: string | null
name: string | null
partGroup: string | null
partGroupId: string | null
@@ -19846,6 +19829,13 @@ export type Database = {
updatedBy: string | null
}
Relationships: [
+ {
+ foreignKeyName: "item_partGroupId_fkey"
+ columns: ["partGroupId"]
+ isOneToOne: false
+ referencedRelation: "partGroup"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "part_approvedBy_fkey"
columns: ["approvedBy"]
@@ -19986,13 +19976,6 @@ export type Database = {
referencedRelation: "item"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "part_partGroupId_fkey"
- columns: ["partGroupId"]
- isOneToOne: false
- referencedRelation: "partGroup"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "part_unitOfMeasureCode_fkey"
columns: ["unitOfMeasureCode", "companyId"]
@@ -20300,9 +20283,7 @@ export type Database = {
inventoryUnitOfMeasureCode: string | null
invoicedComplete: boolean | null
locationId: string | null
- partDescription: string | null
partId: string | null
- partName: string | null
purchaseOrderId: string | null
purchaseOrderLineType:
| Database["public"]["Enums"]["purchaseOrderLineType"]
@@ -21738,9 +21719,7 @@ export type Database = {
id: string | null
invoicedComplete: boolean | null
locationId: string | null
- partDescription: string | null
partId: string | null
- partName: string | null
quantityInvoiced: number | null
quantitySent: number | null
quantityToInvoice: number | null
diff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sql
index b0e1e79b3b..53f552f613 100644
--- a/packages/database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/database/supabase/migrations/20230330024716_parts.sql
@@ -64,9 +64,12 @@ CREATE TYPE "itemType" AS ENUM (
CREATE TABLE "item" (
"id" TEXT NOT NULL DEFAULT xid(),
"readableId" TEXT NOT NULL,
- "name" TEXT NOT NULL,
"type" "itemType" NOT NULL,
+ "name" TEXT NOT NULL,
+ "description" TEXT,
"partGroupId" TEXT,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "blocked" BOOLEAN NOT NULL DEFAULT false,
"companyId" TEXT NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
@@ -78,6 +81,8 @@ CREATE TABLE "item" (
CONSTRAINT "item_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
);
+CREATE INDEX "item_companyId_idx" ON "item" ("companyId");
+CREATE INDEX "item_name_companyId_idx" ON "item" ("name", "companyId");
CREATE TYPE "partType" AS ENUM (
'Inventory',
@@ -169,15 +174,9 @@ CREATE POLICY "Employees with parts_delete can delete units of measure" ON "unit
CREATE TABLE "part" (
"id" TEXT NOT NULL,
"itemId" TEXT NOT NULL,
- "name" TEXT NOT NULL,
- "description" TEXT,
- "blocked" BOOLEAN NOT NULL DEFAULT false,
"replenishmentSystem" "partReplenishmentSystem" NOT NULL,
- "partGroupId" TEXT,
"partType" "partType" NOT NULL,
- "manufacturerPartNumber" TEXT,
"unitOfMeasureCode" TEXT NOT NULL,
- "active" BOOLEAN NOT NULL DEFAULT true,
"approved" BOOLEAN NOT NULL DEFAULT false,
"approvedBy" TEXT,
"fromDate" DATE,
@@ -193,7 +192,6 @@ CREATE TABLE "part" (
CONSTRAINT "part_pkey" PRIMARY KEY ("id", "companyId"),
CONSTRAINT "part_id_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "part_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "part_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id"),
CONSTRAINT "part_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,
CONSTRAINT "part_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
@@ -201,12 +199,10 @@ CREATE TABLE "part" (
CONSTRAINT "part_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
-CREATE INDEX "part_name_idx" ON "part"("name");
+CREATE INDEX "part_itemId_idx" ON "part" ("itemId");
CREATE INDEX "part_companyId_idx" ON "part" ("companyId");
-CREATE INDEX "part_partType_idx" ON "part"("partType");
-CREATE INDEX "part_partGroupId_idx" ON "part"("partGroupId");
-CREATE INDEX "part_replenishmentSystem_idx" ON "part"("replenishmentSystem");
-CREATE INDEX "part_active_blocked_idx" ON "part"("active", "blocked");
+CREATE INDEX "part_partType_idx" ON "part"("partType", "companyId");
+CREATE INDEX "part_replenishmentSystem_idx" ON "part"("replenishmentSystem", "companyId");
ALTER publication supabase_realtime ADD TABLE "part";
ALTER TABLE "part" ENABLE ROW LEVEL SECURITY;
@@ -241,18 +237,18 @@ CREATE POLICY "Employees with parts_delete can delete parts" ON "part"
has_company_permission('parts_delete', "companyId")
);
-CREATE OR REPLACE FUNCTION public.create_part_search_result()
+CREATE OR REPLACE FUNCTION public.create_item_search_result()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.search(name, description, entity, uuid, link, "companyId")
- VALUES (new.id, new.name || ' ' || COALESCE(new.description, ''), 'Part', new.id, '/x/part/' || new.id, new."companyId");
+ VALUES (new."readableId", new.name || ' ' || COALESCE(new.description, ''), 'Part', new."readableId", '/x/part/' || new."id", new."companyId");
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-CREATE TRIGGER create_part_search_result
- AFTER INSERT on public.part
- FOR EACH ROW EXECUTE PROCEDURE public.create_part_search_result();
+CREATE TRIGGER create_item_search_result
+ AFTER INSERT on public.item
+ FOR EACH ROW EXECUTE PROCEDURE public.create_item_search_result();
CREATE FUNCTION public.create_part_related_records()
RETURNS TRIGGER AS $$
@@ -276,23 +272,23 @@ CREATE TRIGGER create_part_related_records
AFTER INSERT on public.part
FOR EACH ROW EXECUTE PROCEDURE public.create_part_related_records();
-CREATE OR REPLACE FUNCTION public.update_part_search_result()
+CREATE OR REPLACE FUNCTION public.update_item_search_result()
RETURNS TRIGGER AS $$
BEGIN
IF (old.name <> new.name OR old.description <> new.description) THEN
- UPDATE public.search SET name = new.id, description = new.name || ' ' || COALESCE(new.description, '')
- WHERE entity = 'Part' AND uuid = new.id AND "companyId" = new."companyId";
+ UPDATE public.search SET name = new."readableId", description = new.name || ' ' || COALESCE(new.description, '')
+ WHERE entity = 'Part' AND uuid = new."readableId" AND "companyId" = new."companyId";
END IF;
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-CREATE TRIGGER update_part_search_result
- AFTER UPDATE on public.part
- FOR EACH ROW EXECUTE PROCEDURE public.update_part_search_result();
+CREATE TRIGGER update_item_search_result
+ AFTER UPDATE on public.item
+ FOR EACH ROW EXECUTE PROCEDURE public.update_item_search_result();
-CREATE FUNCTION public.delete_part_search_result()
+CREATE FUNCTION public.delete_item_search_result()
RETURNS TRIGGER AS $$
BEGIN
DELETE FROM public.search WHERE entity = 'Part' AND uuid = old.id AND "companyId" = old."companyId";
@@ -300,9 +296,9 @@ BEGIN
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-CREATE TRIGGER delete_part_search_result
- AFTER DELETE on public.part
- FOR EACH ROW EXECUTE PROCEDURE public.delete_part_search_result();
+CREATE TRIGGER delete_item_search_result
+ AFTER DELETE on public.item
+ FOR EACH ROW EXECUTE PROCEDURE public.delete_item_search_result();
CREATE TABLE "partCost" (
"partId" TEXT NOT NULL,
diff --git a/packages/database/supabase/migrations/20230704161623_parts-view.sql b/packages/database/supabase/migrations/20230704161623_parts-view.sql
index b216707a30..cd4e73416a 100644
--- a/packages/database/supabase/migrations/20230704161623_parts-view.sql
+++ b/packages/database/supabase/migrations/20230704161623_parts-view.sql
@@ -1,27 +1,31 @@
CREATE OR REPLACE VIEW "parts" AS
SELECT
p.id,
- p.name,
- p.description,
+ p."itemId",
+ i.name,
+ i.description,
p."partType",
- p."partGroupId",
+ i."partGroupId",
pg.name AS "partGroup",
p."replenishmentSystem",
- p.active,
+ i.active,
+ i.blocked,
p."customFields",
p."companyId",
array_agg(ps."supplierId") AS "supplierIds"
FROM "part" p
- LEFT JOIN "partGroup" pg ON pg.id = p."partGroupId"
+ INNER JOIN "item" i ON i.id = p."itemId"
+ LEFT JOIN "partGroup" pg ON pg.id = i."partGroupId"
LEFT JOIN "partSupplier" ps ON ps."partId" = p.id
GROUP BY p.id,
- p.name,
- p.description,
+ i.name,
+ i.description,
p."partType",
- p."partGroupId",
+ i."partGroupId",
pg.name,
p."replenishmentSystem",
- p.active,
+ i.active,
+ i.blocked,
p."customFields",
p."companyId";
diff --git a/packages/database/supabase/migrations/20231222200612_purchase-order-document.sql b/packages/database/supabase/migrations/20231222200612_purchase-order-document.sql
index 410396c6a9..20b5da79c1 100644
--- a/packages/database/supabase/migrations/20231222200612_purchase-order-document.sql
+++ b/packages/database/supabase/migrations/20231222200612_purchase-order-document.sql
@@ -2,8 +2,8 @@ CREATE OR REPLACE VIEW "purchaseOrderLines" WITH(SECURITY_INVOKER=true) AS
SELECT
pol.*,
po."supplierId" ,
- p.name AS "partName",
- p.description AS "partDescription",
+ -- p.name AS "partName",
+ -- p.description AS "partDescription",
ps."supplierPartId",
s.name AS "serviceName",
s.description AS "serviceDescription",
diff --git a/packages/database/supabase/migrations/20240324175747_assignee.sql b/packages/database/supabase/migrations/20240324175747_assignee.sql
index a032cc630e..15e18fe1c1 100644
--- a/packages/database/supabase/migrations/20240324175747_assignee.sql
+++ b/packages/database/supabase/migrations/20240324175747_assignee.sql
@@ -11,11 +11,17 @@ CREATE OR REPLACE VIEW "customers" WITH(SECURITY_INVOKER=true) AS
DROP VIEW "parts";
CREATE OR REPLACE VIEW "parts" WITH(SECURITY_INVOKER=true) AS
SELECT
+ i.name,
+ i.description,
+ i."partGroupId",
+ i.active,
+ i.blocked,
p.*,
pg.name AS "partGroup",
ps."supplierIds"
FROM "part" p
- LEFT JOIN "partGroup" pg ON pg.id = p."partGroupId"
+ INNER JOIN "item" i ON i.id = p."itemId"
+ LEFT JOIN "partGroup" pg ON pg.id = i."partGroupId"
LEFT JOIN (
SELECT
"partId",
diff --git a/packages/database/supabase/migrations/20240402052512_purchasing-conversion-factors.sql b/packages/database/supabase/migrations/20240402052512_purchasing-conversion-factors.sql
index f2475d40d0..4513e3793f 100644
--- a/packages/database/supabase/migrations/20240402052512_purchasing-conversion-factors.sql
+++ b/packages/database/supabase/migrations/20240402052512_purchasing-conversion-factors.sql
@@ -10,8 +10,8 @@ CREATE OR REPLACE VIEW "purchaseOrderLines" WITH(SECURITY_INVOKER=true) AS
SELECT
pol.*,
po."supplierId" ,
- p.name AS "partName",
- p.description AS "partDescription",
+ -- p.name AS "partName",
+ -- p.description AS "partDescription",
ps."supplierPartId",
s.name AS "serviceName",
s.description AS "serviceDescription",
diff --git a/packages/database/supabase/migrations/20240412224648_sales-orders.sql b/packages/database/supabase/migrations/20240412224648_sales-orders.sql
index aeb36d35d2..8265048e34 100644
--- a/packages/database/supabase/migrations/20240412224648_sales-orders.sql
+++ b/packages/database/supabase/migrations/20240412224648_sales-orders.sql
@@ -623,9 +623,10 @@ CREATE OR REPLACE VIEW "customers" WITH(SECURITY_INVOKER=true) AS
CREATE OR REPLACE VIEW "salesOrderLines" WITH(SECURITY_INVOKER=true) AS
SELECT
sol.*,
- so."customerId" ,
- p.name AS "partName",
- p.description AS "partDescription"
+ so."customerId"
+ -- ,
+ -- p.name AS "partName",
+ -- p.description AS "partDescription"
FROM "salesOrderLine" sol
INNER JOIN "salesOrder" so
ON so.id = sol."salesOrderId"