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: display customer part numbers on the part sales tab

Rob Carrington8df3eb831849
diff --git a/apps/carbon/app/components/CustomerPartNumber.tsx b/apps/carbon/app/components/CustomerPartNumber.tsx
new file mode 100644
index 0000000000..a67e45c4a4
--- /dev/null
+++ b/apps/carbon/app/components/CustomerPartNumber.tsx
@@ -0,0 +1,54 @@
+import {
+ ActionMenu,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ VStack,
+} from "@carbon/react";
+import { LuMapPin } from "react-icons/lu";
+import type { Action } from "~/types";
+
+type CustomerPartNumberProps = {
+ customerPartNumber: {
+ customer: {
+ id: string;
+ name: string;
+ };
+ customerPartId: string;
+ customerPartRevision: string | null;
+ };
+ actions: Action[];
+};
+
+const CustomerPartNumber = ({
+ customerPartNumber,
+ actions,
+}: CustomerPartNumberProps) => {
+ return (
+ <div className="grid w-full gap-4 grid-cols-[auto_1fr_auto]">
+ <LuMapPin className="w-8 h-8" />
+ <VStack spacing={0}>
+ <p className="font-bold line-clamp-1">
+ {customerPartNumber.customer.name}
+ </p>
+ <p className="text-sm text-muted-foreground line-clamp-1">
+ {customerPartNumber.customerPartId}
+ </p>
+ <p className="text-sm text-muted-foreground line-clamp-1">
+ {customerPartNumber.customerPartRevision}
+ </p>
+ </VStack>
+ {actions.length > 0 && (
+ <ActionMenu>
+ {actions.map((action) => (
+ <DropdownMenuItem key={action.label} onClick={action.onClick}>
+ {action.icon && <DropdownMenuIcon icon={action.icon} />}
+ {action.label}
+ </DropdownMenuItem>
+ ))}
+ </ActionMenu>
+ )}
+ </div>
+ );
+};
+
+export default CustomerPartNumber;
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index 3d0797f8c5..7804d0a6b2 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -81,6 +81,14 @@ export const consumableValidator = itemValidator.merge(
})
);
+export const customerPartValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ itemId: z.string().min(1, { message: "Item ID is required" }),
+ customerId: z.string().min(36, { message: "Supplier ID is required" }),
+ customerPartId: z.string(),
+ customerPartRevision: zfd.text(z.string().optional()),
+});
+
export const fixtureValidator = itemValidator.merge(
z.object({
id: z.string().min(1, { message: "Fixture ID is required" }).max(255),
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index 604c988368..99b9a972c0 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -9,6 +9,7 @@ import { sanitize } from "~/utils/supabase";
import type {
buyMethodValidator,
consumableValidator,
+ customerPartValidator,
fixtureValidator,
itemCostValidator,
itemPlanningValidator,
@@ -238,6 +239,18 @@ export async function getItemCost(
.single();
}
+export async function getItemCustomerParts(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ return client
+ .from("customerPartToItem")
+ .select("*, customer(id, name)")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId);
+}
+
export async function getItemFiles(
client: SupabaseClient<Database>,
itemId: string,
@@ -1419,6 +1432,31 @@ export async function upsertBuyMethod(
.single();
}
+export async function upsertItemCustomerPart(
+ client: SupabaseClient<Database>,
+ customerPart:
+ | (Omit<z.infer<typeof customerPartValidator>, "id"> & {
+ companyId: string;
+ })
+ | (Omit<z.infer<typeof customerPartValidator>, "id"> & {
+ id: string;
+ })
+) {
+ if ("id" in customerPart) {
+ return client
+ .from("buyMethod")
+ .update(sanitize(customerPart))
+ .eq("id", customerPart.id)
+ .select("id")
+ .single();
+ }
+ return client
+ .from("customerPartToItem")
+ .insert([customerPart])
+ .select("id")
+ .single();
+}
+
export async function upsertItemUnitSalePrice(
client: SupabaseClient<Database>,
itemUnitSalePrice: z.infer<typeof itemUnitSalePriceValidator> & {
diff --git a/apps/carbon/app/modules/items/types.ts b/apps/carbon/app/modules/items/types.ts
index 595106d8c3..f2779dad6a 100644
--- a/apps/carbon/app/modules/items/types.ts
+++ b/apps/carbon/app/modules/items/types.ts
@@ -4,6 +4,7 @@ import type {
getConsumables,
getFixtures,
getItemCost,
+ getItemCustomerParts,
getItemFiles,
getItemPostingGroups,
getItemPostingGroupsList,
@@ -33,6 +34,10 @@ export type Consumable = NonNullable<
Awaited<ReturnType<typeof getConsumables>>["data"]
>[number];
+export type CustomerPart = NonNullable<
+ Awaited<ReturnType<typeof getItemCustomerParts>>["data"]
+>[number];
+
export type Form = NonNullable<
Awaited<ReturnType<typeof getMaterialForms>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/items/ui/Item/CustomerPartForm.tsx b/apps/carbon/app/modules/items/ui/Item/CustomerPartForm.tsx
new file mode 100644
index 0000000000..58a7511e80
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/Item/CustomerPartForm.tsx
@@ -0,0 +1,84 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ HStack,
+ VStack,
+} from "@carbon/react";
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useNavigate, useParams } from "@remix-run/react";
+import type { z } from "zod";
+import { Customer, Hidden, Input, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { customerPartValidator } from "~/modules/items";
+import { path } from "~/utils/path";
+
+type CustomerPartFormProps = {
+ initialValues: z.infer<typeof customerPartValidator>;
+};
+
+const CustomerPartForm = ({ initialValues }: CustomerPartFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "parts")
+ : !permissions.can("create", "parts");
+
+ const onClose = () => navigate(-1);
+
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent>
+ <ValidatedForm
+ defaultValues={initialValues}
+ validator={customerPartValidator}
+ method="post"
+ action={path.to.newCustomerPart(itemId)}
+ className="flex flex-col h-full"
+ >
+ <DrawerHeader>
+ <DrawerTitle>
+ {isEditing ? "Edit" : "New"} Customer Part
+ </DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ <Hidden name="id" />
+ <Hidden name="itemId" />
+
+ <VStack spacing={4}>
+ <Customer name="customerId" label="Customer" />
+ <Input name="customerPartId" label="Customer Part ID" />
+ <Input
+ name="customerPartRevision"
+ label="Customer Part Revision"
+ />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </ValidatedForm>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default CustomerPartForm;
diff --git a/apps/carbon/app/modules/items/ui/Item/CustomerParts/CustomerParts.tsx b/apps/carbon/app/modules/items/ui/Item/CustomerParts/CustomerParts.tsx
new file mode 100644
index 0000000000..174b687724
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/Item/CustomerParts/CustomerParts.tsx
@@ -0,0 +1,84 @@
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ HStack,
+} from "@carbon/react";
+import { Outlet, useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useMemo } from "react";
+import { New } from "~/components";
+import { EditableText } from "~/components/Editable";
+import Grid from "~/components/Grid";
+import type { CustomerPart } from "~/modules/items";
+import useCustomerParts from "./useCustomerParts";
+
+type CustomerPartsProps = {
+ customerParts: CustomerPart[];
+};
+
+const CustomerParts = ({ customerParts }: CustomerPartsProps) => {
+ const navigate = useNavigate();
+ const { canEdit, onCellEdit } = useCustomerParts();
+
+ const columns = useMemo<ColumnDef<CustomerPart>[]>(() => {
+ const defaultColumns: ColumnDef<CustomerPart>[] = [
+ {
+ accessorKey: "customer.id",
+ header: "Customer",
+ cell: ({ row }) => (
+ <HStack className="justify-between">
+ {/* @ts-ignore */}
+ <span>{row.original.customer.name}</span>
+ </HStack>
+ ),
+ },
+ {
+ accessorKey: "customerPartId",
+ header: "Customer ID",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "customerPartRevision",
+ header: "Customer Revision",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ return [...defaultColumns];
+ }, []);
+
+ const editableComponents = useMemo(
+ () => ({
+ customerPartId: EditableText(onCellEdit),
+ customerPartRevision: EditableText(onCellEdit),
+ }),
+ [onCellEdit]
+ );
+
+ return (
+ <>
+ <Card className="w-full h-full min-h-[50vh]">
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Customer Parts</CardTitle>
+ </CardHeader>
+ <CardAction>{canEdit && <New to="new" />}</CardAction>
+ </HStack>
+ <CardContent>
+ <Grid<CustomerPart>
+ data={customerParts}
+ columns={columns}
+ canEdit={canEdit}
+ editableComponents={editableComponents}
+ onNewRow={canEdit ? () => navigate("new") : undefined}
+ />
+ </CardContent>
+ </Card>
+ <Outlet />
+ </>
+ );
+};
+
+export default CustomerParts;
diff --git a/apps/carbon/app/modules/items/ui/Item/CustomerParts/index.ts b/apps/carbon/app/modules/items/ui/Item/CustomerParts/index.ts
new file mode 100644
index 0000000000..c625536a14
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/Item/CustomerParts/index.ts
@@ -0,0 +1,3 @@
+import CustomerParts from "./CustomerParts";
+
+export default CustomerParts;
diff --git a/apps/carbon/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx b/apps/carbon/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx
new file mode 100644
index 0000000000..b3397ff97b
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx
@@ -0,0 +1,32 @@
+import { useCallback } from "react";
+import { usePermissions } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { CustomerPart } from "~/modules/items";
+
+export default function useCustomerParts() {
+ const { supabase } = useSupabase();
+ const permissions = usePermissions();
+
+ const canEdit = permissions.can("update", "parts");
+ const canDelete = permissions.can("delete", "parts");
+
+ const onCellEdit = useCallback(
+ async (id: string, value: unknown, row: CustomerPart) => {
+ if (!supabase) throw new Error("Supabase client not found");
+ return await supabase
+ .from("customerPartToItem")
+ .update({
+ [id]: value,
+ })
+ .eq("id", row.id);
+ },
+ [supabase]
+ );
+
+ return {
+ canDelete,
+ canEdit,
+ supabase,
+ onCellEdit,
+ };
+}
diff --git a/apps/carbon/app/modules/items/ui/Parts/usePartNavigation.tsx b/apps/carbon/app/modules/items/ui/Parts/usePartNavigation.tsx
index c63045dbc1..153de745a0 100644
--- a/apps/carbon/app/modules/items/ui/Parts/usePartNavigation.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/usePartNavigation.tsx
@@ -73,7 +73,7 @@ export function usePartNavigation() {
},
{
name: "Sales",
- to: path.to.partSalePrice(itemId),
+ to: path.to.partSales(itemId),
role: ["employee", "customer"],
icon: LuReceipt,
shortcut: "Command+Shift+x",
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.sales.new.tsx b/apps/carbon/app/routes/x+/part+/$itemId.sales.new.tsx
new file mode 100644
index 0000000000..0f350761ec
--- /dev/null
+++ b/apps/carbon/app/routes/x+/part+/$itemId.sales.new.tsx
@@ -0,0 +1,62 @@
+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 { customerPartValidator, upsertItemCustomerPart } from "~/modules/items";
+import CustomerPartForm from "~/modules/items/ui/Item/CustomerPartForm";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId } = await requirePermissions(request, {
+ create: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(customerPartValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createCustomerPart = await upsertItemCustomerPart(client, {
+ ...data,
+ companyId,
+ });
+
+ if (createCustomerPart.error) {
+ throw redirect(
+ path.to.partSales(itemId),
+ await flash(
+ request,
+ error(createCustomerPart.error, "Failed to create part supplier")
+ )
+ );
+ }
+
+ throw redirect(path.to.partSales(itemId));
+}
+
+export default function NewCustomerPartRoute() {
+ const { itemId } = useParams();
+
+ if (!itemId) throw new Error("itemId not found");
+
+ const initialValues = {
+ itemId: itemId,
+ customerId: "",
+ customerPartId: "",
+ customerPartRevision: "",
+ };
+
+ return <CustomerPartForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.sale-price.tsx b/apps/carbon/app/routes/x+/part+/$itemId.sales.tsx
similarity index 84%
rename from apps/carbon/app/routes/x+/part+/$itemId.sale-price.tsx
rename to apps/carbon/app/routes/x+/part+/$itemId.sales.tsx
index 82770c8545..1c63d5364c 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.sale-price.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.sales.tsx
@@ -5,10 +5,12 @@ import { json, redirect } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import {
ItemSalePriceForm,
+ getItemCustomerParts,
getItemUnitSalePrice,
itemUnitSalePriceValidator,
upsertItemUnitSalePrice,
} from "~/modules/items";
+import CustomerParts from "~/modules/items/ui/Item/CustomerParts";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { getCustomFields, setCustomFields } from "~/utils/form";
@@ -24,8 +26,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { itemId } = params;
if (!itemId) throw new Error("Could not find itemId");
- const [partUnitSalePrice] = await Promise.all([
+ const [partUnitSalePrice, customerParts] = await Promise.all([
getItemUnitSalePrice(client, itemId, companyId),
+ getItemCustomerParts(client, itemId, companyId),
]);
if (partUnitSalePrice.error) {
@@ -40,6 +43,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return json({
partUnitSalePrice: partUnitSalePrice.data,
+ customerParts: customerParts.data,
});
}
@@ -78,13 +82,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
throw redirect(
- path.to.partSalePrice(itemId),
+ path.to.partSales(itemId),
await flash(request, success("Updated part sale price"))
);
}
-export default function PartSalePriceRoute() {
- const { partUnitSalePrice } = useLoaderData<typeof loader>();
+export default function PartSalesRoute() {
+ const { partUnitSalePrice, customerParts } = useLoaderData<typeof loader>();
const initialValues = {
...partUnitSalePrice,
@@ -98,6 +102,7 @@ export default function PartSalePriceRoute() {
key={initialValues.itemId}
initialValues={initialValues}
/>
+ {customerParts ? <CustomerParts customerParts={customerParts} /> : null}
</VStack>
);
}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 00dba04c9a..cddba5ff8c 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -404,6 +404,7 @@ export const path = {
newCustomerType: `${x}/sales/customer-types/new`,
newCustomField: (tableId: string) =>
generatePath(`${x}/settings/custom-fields/${tableId}/new`),
+ newCustomerPart: (id: string) => generatePath(`${x}/part/${id}/sales/new`),
newDepartment: `${x}/people/departments/new`,
newDocument: `${x}/documents/new`,
newEmployee: `${x}/users/employees/new`,
@@ -499,7 +500,7 @@ export const path = {
partPricing: (id: string) => generatePath(`${x}/part/${id}/pricing`),
partPurchasing: (id: string) => generatePath(`${x}/part/${id}/purchasing`),
partRoot: `${x}/part`,
- partSalePrice: (id: string) => generatePath(`${x}/part/${id}/sale-price`),
+ partSales: (id: string) => generatePath(`${x}/part/${id}/sales`),
partSupplier: (itemId: string, id: string) =>
generatePath(`${x}/part/${itemId}/suppliers/${id}`),
parts: `${x}/items/parts`,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index d89a465b6d..c191075e17 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -3382,6 +3382,7 @@ export type Database = {
customerId: string
customerPartId: string
customerPartRevision: string | null
+ id: string
itemId: string
}
Insert: {
@@ -3389,6 +3390,7 @@ export type Database = {
customerId: string
customerPartId: string
customerPartRevision?: string | null
+ id?: string
itemId: string
}
Update: {
@@ -3396,6 +3398,7 @@ export type Database = {
customerId?: string
customerPartId?: string
customerPartRevision?: string | null
+ id?: string
itemId?: string
}
Relationships: [
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index d89a465b6d..c191075e17 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -3382,6 +3382,7 @@ export type Database = {
customerId: string
customerPartId: string
customerPartRevision: string | null
+ id: string
itemId: string
}
Insert: {
@@ -3389,6 +3390,7 @@ export type Database = {
customerId: string
customerPartId: string
customerPartRevision?: string | null
+ id?: string
itemId: string
}
Update: {
@@ -3396,6 +3398,7 @@ export type Database = {
customerId?: string
customerPartId?: string
customerPartRevision?: string | null
+ id?: string
itemId?: string
}
Relationships: [
diff --git a/packages/database/supabase/migrations/20240815185942_add-id-col-customerPartToItem.sql b/packages/database/supabase/migrations/20240815185942_add-id-col-customerPartToItem.sql
new file mode 100644
index 0000000000..7eb4c3288e
--- /dev/null
+++ b/packages/database/supabase/migrations/20240815185942_add-id-col-customerPartToItem.sql
@@ -0,0 +1,22 @@
+-- 1. Add the new `id` column with a default value
+ALTER TABLE public."customerPartToItem"
+ADD COLUMN "id" text DEFAULT xid();
+
+-- 2. Drop the existing primary key constraint
+ALTER TABLE public."customerPartToItem"
+DROP CONSTRAINT "customerPartToItem_pkey";
+
+-- 3. Set the new `id` column as the primary key
+ALTER TABLE public."customerPartToItem"
+ADD CONSTRAINT "customerPartToItem_pkey" PRIMARY KEY ("id");
+
+-- 4. Add back in the unique constraint on (customerId, itemId)
+ALTER TABLE public."customerPartToItem"
+ADD CONSTRAINT "customerPartToItem_customerId_itemId_key" UNIQUE ("customerId", "itemId");
+
+-- 5. Fix the policy that was created incorrectly the first time
+DROP POLICY IF EXISTS "Employees with sales_create can insert customer part to item" ON public."customerPartToItem";
+CREATE POLICY "Employees with sales_create can insert customer part to item" ON "customerPartToItem" FOR INSERT WITH CHECK (
+ has_company_permission('sales_create', "companyId") AND
+ has_role('employee', "companyId")
+);
\ No newline at end of file