Skip to content

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

refactor: combine item + part/service forms

Brad Barbincea39239d7b8
diff --git a/apps/carbon/app/modules/parts/parts.models.ts b/apps/carbon/app/modules/parts/parts.models.ts
index fa9491827f..cbeadc1f82 100644
--- a/apps/carbon/app/modules/parts/parts.models.ts
+++ b/apps/carbon/app/modules/parts/parts.models.ts
@@ -36,24 +36,24 @@ export const itemValidator = z.object({
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",
+export const partValidator = itemValidator.merge(
+ 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",
+ }),
}),
- }),
- partType: z.enum(partTypes, {
- errorMap: (issue, ctx) => ({
- message: "Part type is required",
+ partType: z.enum(partTypes, {
+ errorMap: (issue, ctx) => ({
+ message: "Part type is required",
+ }),
}),
- }),
- unitOfMeasureCode: z
- .string()
- .min(1, { message: "Unit of Measure is required" }),
-});
-
-export const newPartValidator = itemValidator.merge(partValidator);
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of Measure is required" }),
+ })
+);
export const partCostValidator = z.object({
partId: z.string().min(1, { message: "Part ID is required" }),
@@ -147,16 +147,16 @@ export const partUnitSalePriceValidator = z.object({
allowInvoiceDiscount: zfd.checkbox(),
});
-export const serviceValidator = z.object({
- id: z.string().min(1, { message: "Service ID is required" }).max(255),
- serviceType: z.enum(serviceType, {
- errorMap: (issue, ctx) => ({
- message: "Service type is required",
+export const serviceValidator = itemValidator.merge(
+ z.object({
+ id: z.string().min(1, { message: "Service ID is required" }).max(255),
+ serviceType: z.enum(serviceType, {
+ errorMap: (issue, ctx) => ({
+ message: "Service type is required",
+ }),
}),
- }),
-});
-
-export const newServiceValidator = itemValidator.merge(serviceValidator);
+ })
+);
export const serviceSupplierValidator = z.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/parts/parts.service.ts b/apps/carbon/app/modules/parts/parts.service.ts
index 6eb9ea70c6..bfc2aa9b2d 100644
--- a/apps/carbon/app/modules/parts/parts.service.ts
+++ b/apps/carbon/app/modules/parts/parts.service.ts
@@ -7,8 +7,6 @@ import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
itemValidator,
- newPartValidator,
- newServiceValidator,
partCostValidator,
partGroupValidator,
partInventoryValidator,
@@ -219,13 +217,13 @@ export async function getPartQuantities(
export async function getPart(
client: SupabaseClient<Database>,
- id: string,
+ itemId: string,
companyId: string
) {
return client
.from("parts")
.select("*")
- .eq("id", id)
+ .eq("itemId", itemId)
.eq("companyId", companyId)
.single();
}
@@ -307,13 +305,13 @@ export async function getServices(
export async function getService(
client: SupabaseClient<Database>,
- id: string,
+ itemId: string,
companyId: string
) {
return client
.from("services")
.select("*")
- .eq("id", id)
+ .eq("itemId", itemId)
.eq("companyId", companyId)
.single();
}
@@ -447,7 +445,7 @@ export async function insertShelf(
export async function upsertPart(
client: SupabaseClient<Database>,
part:
- | (z.infer<typeof newPartValidator> & {
+ | (z.infer<typeof partValidator> & {
companyId: string;
createdBy: string;
customFields?: Json;
@@ -487,13 +485,41 @@ export async function upsertPart(
.select("*")
.single();
}
- return client
- .from("part")
- .update({
- ...sanitize(part),
- updatedAt: today(getLocalTimeZone()).toString(),
- })
- .eq("id", part.id);
+
+ const itemUpdate = {
+ id: part.id,
+ name: part.name,
+ description: part.description,
+ partGroupId: part.partGroupId,
+ active: part.active,
+ blocked: part.blocked,
+ };
+
+ const partUpdate = {
+ replenishmentSystem: part.replenishmentSystem,
+ partType: part.partType,
+ unitOfMeasureCode: part.unitOfMeasureCode,
+ };
+
+ const [updateItem, updatePart] = await Promise.all([
+ client
+ .from("item")
+ .update({
+ ...sanitize(itemUpdate),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", part.id),
+ client
+ .from("part")
+ .update({
+ ...sanitize(partUpdate),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("itemId", part.id),
+ ]);
+
+ if (updateItem.error) return updateItem;
+ return updatePart;
}
export async function updateItem(
@@ -669,7 +695,7 @@ export async function upsertPartUnitSalePrice(
export async function upsertService(
client: SupabaseClient<Database>,
service:
- | (z.infer<typeof newServiceValidator> & {
+ | (z.infer<typeof serviceValidator> & {
companyId: string;
createdBy: string;
customFields?: Json;
@@ -707,13 +733,38 @@ export async function upsertService(
.select("*")
.single();
}
- return client
- .from("service")
- .update({
- ...sanitize(service),
- updatedAt: today(getLocalTimeZone()).toString(),
- })
- .eq("id", service.id);
+ const itemUpdate = {
+ id: service.id,
+ name: service.name,
+ description: service.description,
+ partGroupId: service.partGroupId,
+ active: service.active,
+ blocked: service.blocked,
+ };
+
+ const serviceUpdate = {
+ serviceType: service.serviceType,
+ };
+
+ const [updateItem, updateService] = await Promise.all([
+ client
+ .from("item")
+ .update({
+ ...sanitize(itemUpdate),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", service.id),
+ client
+ .from("service")
+ .update({
+ ...sanitize(serviceUpdate),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("itemId", service.id),
+ ]);
+
+ if (updateItem.error) return updateItem;
+ return updateService;
}
export async function upsertServiceSupplier(
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
index 709823e212..ce0654420c 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={isEditing ? partValidator : newPartValidator}
+ validator={partValidator}
defaultValues={initialValues}
fetcher={fetcher}
>
@@ -147,14 +147,15 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
</ModalCardHeader>
<ModalCardBody>
<Hidden name="type" value={type} />
- {isEditing && <Hidden name="id" />}
<div
className={cn(
"grid w-full gap-x-8 gap-y-2",
isEditing ? "grid-cols-1 md:grid-cols-3" : "grid-cols-1"
)}
>
- {!isEditing && (
+ {isEditing ? (
+ <Input name="id" label="Part ID" isReadOnly />
+ ) : (
<InputControlled
name="id"
label="Part ID"
@@ -169,11 +170,10 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
/>
)}
- {!isEditing && (
- <>
- <Input name="name" label="Name" />
- <PartGroup name="partGroupId" label="Part Group" />
- </>
+ <Input name="name" label="Name" />
+ <PartGroup name="partGroupId" label="Part Group" />
+ {isEditing && (
+ <TextArea name="description" label="Description" />
)}
<Select
name="replenishmentSystem"
@@ -190,7 +190,8 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
label="Unit of Measure"
/>
- {!isEditing && <Boolean name="blocked" label="Blocked" />}
+ <Boolean name="blocked" label="Blocked" />
+ {isEditing && <Boolean name="active" label="Active" />}
<CustomFormFields table="part" />
</div>
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartHeader.tsx b/apps/carbon/app/modules/parts/ui/Part/PartHeader.tsx
index 7e46b44757..1e914fbd6d 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartHeader.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartHeader.tsx
@@ -23,15 +23,15 @@ import { path } from "~/utils/path";
const PartHeader = () => {
const permissions = usePermissions();
- const { partId } = useParams();
- if (!partId) throw new Error("partId not found");
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
const routeData = useRouteData<{ partSummary: PartSummary }>(
- path.to.part(partId)
+ path.to.part(itemId)
);
const optimisticAssignment = useOptimisticAssignment({
- id: partId,
+ id: itemId,
table: "part",
});
const assignee =
@@ -41,10 +41,10 @@ const PartHeader = () => {
return (
<VStack>
- {permissions.is("employee") && (
+ {permissions.is("employee") && !!routeData?.partSummary?.id && (
<Menubar>
<Assign
- id={partId}
+ id={routeData?.partSummary?.id}
table="part"
value={routeData?.partSummary?.assignee ?? ""}
/>
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartSidebar/PartSidebar.tsx b/apps/carbon/app/modules/parts/ui/Part/PartSidebar/PartSidebar.tsx
index 62909322ea..6b4942e4f5 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartSidebar/PartSidebar.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartSidebar/PartSidebar.tsx
@@ -6,11 +6,11 @@ import { path } from "~/utils/path";
import { usePartSidebar } from "./usePartSidebar";
const PartSidebar = () => {
- const { partId } = useParams();
- if (!partId) throw new Error("partId not found");
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
const routeData = useRouteData<{ partSummary: PartSummary }>(
- path.to.part(partId)
+ path.to.part(itemId)
);
if (!routeData?.partSummary?.replenishmentSystem)
throw new Error("Could not find replenishmentSystem in routeData");
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartSidebar/usePartSidebar.tsx b/apps/carbon/app/modules/parts/ui/Part/PartSidebar/usePartSidebar.tsx
index b6976954b3..a902eccc0f 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartSidebar/usePartSidebar.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartSidebar/usePartSidebar.tsx
@@ -16,19 +16,19 @@ import { path } from "~/utils/path";
export function usePartSidebar(replenishment: PartReplenishmentSystem) {
const permissions = usePermissions();
- const { partId } = useParams();
- if (!partId) throw new Error("partId not found");
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
return [
{
name: "Details",
- to: path.to.partDetails(partId),
+ to: path.to.partDetails(itemId),
icon: LuFileText,
shortcut: "Command+Shift+d",
},
{
name: "Purchasing",
- to: path.to.partPurchasing(partId),
+ to: path.to.partPurchasing(itemId),
isDisabled: replenishment === "Make",
role: ["employee", "supplier"],
icon: LuShoppingCart,
@@ -36,7 +36,7 @@ export function usePartSidebar(replenishment: PartReplenishmentSystem) {
},
{
name: "Suppliers",
- to: path.to.partSuppliers(partId),
+ to: path.to.partSuppliers(itemId),
isDisabled: replenishment === "Make",
role: ["employee", "supplier"],
icon: LuShare2,
@@ -44,7 +44,7 @@ export function usePartSidebar(replenishment: PartReplenishmentSystem) {
},
{
name: "Manufacturing",
- to: path.to.partManufacturing(partId),
+ to: path.to.partManufacturing(itemId),
isDisabled: replenishment === "Buy",
role: ["employee"],
icon: BiListCheck,
@@ -52,28 +52,28 @@ export function usePartSidebar(replenishment: PartReplenishmentSystem) {
},
{
name: "Costing",
- to: path.to.partCosting(partId),
+ to: path.to.partCosting(itemId),
role: ["employee", "supplier"],
icon: LuTags,
shortcut: "Command+Shift+c",
},
{
name: "Planning",
- to: path.to.partPlanning(partId),
+ to: path.to.partPlanning(itemId),
role: ["employee"],
icon: LuFileBarChart,
shortcut: "Command+Shift+p",
},
{
name: "Inventory",
- to: path.to.partInventory(partId),
+ to: path.to.partInventory(itemId),
role: ["employee", "supplier"],
icon: LuBox,
shortcut: "Command+Shift+i",
},
{
name: "Sale Price",
- to: path.to.partSalePrice(partId),
+ to: path.to.partSalePrice(itemId),
role: ["employee", "customer"],
icon: LuReceipt,
shortcut: "Command+Shift+x",
diff --git a/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupForm.tsx b/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupForm.tsx
index b706c8ba4c..79557f78da 100644
--- a/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupForm.tsx
@@ -53,11 +53,9 @@ const PartGroupForm = ({
if (fetcher.state === "loading" && fetcher.data?.data) {
onClose?.();
- toast.success(`Created supplier status`);
+ toast.success(`Created part group`);
} else if (fetcher.state === "idle" && fetcher.data?.error) {
- toast.error(
- `Failed to create supplier status: ${fetcher.data.error.message}`
- );
+ toast.error(`Failed to create part group: ${fetcher.data.error.message}`);
}
}, [fetcher.data, fetcher.state, onClose, type]);
diff --git a/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx b/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
index e929c571a2..dd5321ebd1 100644
--- a/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/Parts/PartsTable.tsx
@@ -32,7 +32,7 @@ const PartsTable = memo(({ data, count, partGroups }: PartsTableProps) => {
accessorKey: "id",
header: "Part ID",
cell: ({ row }) => (
- <Hyperlink to={path.to.partDetails(row.original.id!)}>
+ <Hyperlink to={path.to.partDetails(row.original.itemId!)}>
{row.original.id}
</Hyperlink>
),
diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceForm.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceForm.tsx
index 52846be8d7..d987a6c985 100644
--- a/apps/carbon/app/modules/parts/ui/Service/ServiceForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceForm.tsx
@@ -13,7 +13,6 @@ import type { z } from "zod";
import {
Boolean,
CustomFormFields,
- Hidden,
Input,
InputControlled,
PartGroup,
@@ -23,11 +22,7 @@ import {
} from "~/components/Form";
import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
-import {
- newServiceValidator,
- serviceType,
- serviceValidator,
-} from "~/modules/parts";
+import { serviceType, serviceValidator } from "~/modules/parts";
type ServiceFormProps = {
initialValues: z.infer<typeof serviceValidator>;
@@ -95,8 +90,9 @@ const ServiceForm = ({ initialValues }: ServiceFormProps) => {
return (
<ValidatedForm
method="post"
- validator={isEditing ? serviceValidator : newServiceValidator}
+ validator={serviceValidator}
defaultValues={initialValues}
+ className="w-full"
>
<Card>
<CardHeader>
@@ -109,29 +105,27 @@ const ServiceForm = ({ initialValues }: ServiceFormProps) => {
)}
</CardHeader>
<CardContent>
- {isEditing && <Hidden name="id" />}
<div
className={cn(
"grid w-full gap-x-8 gap-y-2",
isEditing ? "grid-cols-1 lg:grid-cols-3" : "grid-cols-1"
)}
>
- {!isEditing && (
- <>
- {" "}
- <InputControlled
- name="id"
- label="Service ID"
- helperText="Use ... to get the next service ID"
- value={serviceId}
- onChange={onServiceIdChange}
- isDisabled={loading}
- />
- <Input name="name" label="Name" />
- <PartGroup name="partGroupId" label="Part Group" />
- <TextArea name="description" label="Description" />
- </>
+ {isEditing ? (
+ <Input name="id" label="Service ID" isReadOnly />
+ ) : (
+ <InputControlled
+ name="id"
+ label="Service ID"
+ helperText="Use ... to get the next service ID"
+ value={serviceId}
+ onChange={onServiceIdChange}
+ isDisabled={loading}
+ />
)}
+ <Input name="name" label="Name" />
+ <PartGroup name="partGroupId" label="Part Group" />
+ <TextArea name="description" label="Description" />
<Select
name="serviceType"
@@ -139,8 +133,8 @@ const ServiceForm = ({ initialValues }: ServiceFormProps) => {
options={serviceTypeOptions}
/>
- {!isEditing && <Boolean name="blocked" label="Blocked" />}
-
+ <Boolean name="blocked" label="Blocked" />
+ {isEditing && <Boolean name="active" label="Active" />}
<CustomFormFields table="service" />
</div>
</CardContent>
diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceHeader.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceHeader.tsx
index 0952f57b6b..eaa1345f4f 100644
--- a/apps/carbon/app/modules/parts/ui/Service/ServiceHeader.tsx
+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceHeader.tsx
@@ -23,15 +23,13 @@ import { path } from "~/utils/path";
const ServiceHeader = () => {
const permissions = usePermissions();
- const { serviceId } = useParams();
- if (!serviceId) throw new Error("serviceId not found");
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
- const routeData = useRouteData<{ service: Service }>(
- path.to.service(serviceId)
- );
+ const routeData = useRouteData<{ service: Service }>(path.to.service(itemId));
const optimisticAssignment = useOptimisticAssignment({
- id: serviceId,
+ id: itemId,
table: "service",
});
const assignee =
@@ -44,7 +42,7 @@ const ServiceHeader = () => {
{permissions.is("employee") && (
<Menubar>
<Assign
- id={serviceId}
+ id={itemId}
table="service"
value={routeData?.service?.assignee ?? ""}
/>
diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/ServiceSidebar.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/ServiceSidebar.tsx
index bdac8ef253..ff2fd5204f 100644
--- a/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/ServiceSidebar.tsx
+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/ServiceSidebar.tsx
@@ -6,13 +6,11 @@ import { path } from "~/utils/path";
import { useServiceSidebar } from "./useServiceSidebar";
const ServiceSidebar = () => {
- const { serviceId } = useParams();
+ const { itemId } = useParams();
- if (!serviceId) throw new Error("serviceId not found");
+ if (!itemId) throw new Error("itemId not found");
- const routeData = useRouteData<{ service: Service }>(
- path.to.service(serviceId)
- );
+ const routeData = useRouteData<{ service: Service }>(path.to.service(itemId));
if (!routeData?.service?.serviceType)
throw new Error("Could not find service type in routeData");
diff --git a/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx b/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
index fdf8dd451c..f48435580e 100644
--- a/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/Services/ServicesTable.tsx
@@ -32,7 +32,7 @@ const ServicesTable = memo(
accessorKey: "id",
header: "Service ID",
cell: ({ row }) => (
- <Hyperlink to={path.to.serviceDetails(row.original.id!)}>
+ <Hyperlink to={path.to.serviceDetails(row.original.itemId!)}>
{row.original.id}
</Hyperlink>
),
diff --git a/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx b/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx
index 3dfc8baa86..b45725a434 100644
--- a/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx
+++ b/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx
@@ -43,7 +43,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
const [parts, suppliers, customers, people] = await Promise.all([
supabase
- .from("part")
+ .from("parts")
.select("id, name, replenishmentSystem")
.eq("companyId", companyId)
.eq("active", true)
@@ -66,12 +66,22 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
.order("name"),
]);
- if (parts.error || suppliers.error || customers.error || people.error) {
- throw new Error("Failed to fetch core data");
+ if (parts.error) {
+ throw new Error("Failed to fetch parts");
+ }
+ if (suppliers.error) {
+ throw new Error("Failed to fetch suppliers");
+ }
+ if (customers.error) {
+ throw new Error("Failed to fetch customers");
+ }
+ if (people.error) {
+ throw new Error("Failed to fetch people");
}
hydratedFromServer = true;
+ // @ts-ignore
setParts(parts.data ?? []);
setSuppliers(suppliers.data ?? []);
setCustomers(customers.data ?? []);
@@ -100,16 +110,18 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
switch (payload.eventType) {
case "INSERT":
const { new: inserted } = payload;
- setParts((parts) =>
- [
- ...parts,
- {
- id: inserted.id,
- name: inserted.name,
- replenishmentSystem: inserted.replenishmentSystem,
- },
- ].sort((a, b) => a.name.localeCompare(b.name))
- );
+ if (inserted.active && !inserted.blocked) {
+ setParts((parts) =>
+ [
+ ...parts,
+ {
+ id: inserted.id,
+ name: inserted.name,
+ replenishmentSystem: inserted.replenishmentSystem,
+ },
+ ].sort((a, b) => a.name.localeCompare(b.name))
+ );
+ }
break;
case "UPDATE":
const { new: updated } = payload;
diff --git a/apps/carbon/app/routes/x+/part+/$partId._index.tsx b/apps/carbon/app/routes/x+/part+/$itemId._index.tsx
similarity index 60%
rename from apps/carbon/app/routes/x+/part+/$partId._index.tsx
rename to apps/carbon/app/routes/x+/part+/$itemId._index.tsx
index 6fcd70cea4..998b65cee9 100644
--- a/apps/carbon/app/routes/x+/part+/$partId._index.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId._index.tsx
@@ -3,7 +3,7 @@ import { redirect } from "@remix-run/node";
import { path } from "~/utils/path";
export async function loader({ params }: LoaderFunctionArgs) {
- const { partId } = params;
- if (!partId) throw new Error("Could not find partId");
- throw redirect(path.to.partDetails(partId));
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+ throw redirect(path.to.partDetails(itemId));
}
diff --git a/apps/carbon/app/routes/x+/part+/$partId.details.tsx b/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
similarity index 79%
rename from apps/carbon/app/routes/x+/part+/$partId.details.tsx
rename to apps/carbon/app/routes/x+/part+/$itemId.details.tsx
index 2a073b8e74..9da12be1ab 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.details.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
@@ -5,7 +5,7 @@ import { redirect } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import { useRouteData } from "~/hooks";
import type { PartSummary } from "~/modules/parts";
-import { ItemForm, PartForm, partValidator, upsertPart } from "~/modules/parts";
+import { 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";
@@ -19,8 +19,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "parts",
});
- const { partId } = params;
- if (!partId) throw new Error("Could not find partId");
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
const formData = await request.formData();
const validation = await validator(partValidator).validate(formData);
@@ -31,43 +31,39 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatePart = await upsertPart(client, {
...validation.data,
- id: partId,
+ id: itemId,
customFields: setCustomFields(formData),
updatedBy: userId,
});
if (updatePart.error) {
throw redirect(
- path.to.part(partId),
+ path.to.part(itemId),
await flash(request, error(updatePart.error, "Failed to update part"))
);
}
throw redirect(
- path.to.part(partId),
+ path.to.part(itemId),
await flash(request, success("Updated part"))
);
}
export default function PartDetailsRoute() {
- const { partId } = useParams();
- if (!partId) throw new Error("Could not find partId");
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
const partData = useRouteData<{ partSummary: PartSummary }>(
- path.to.part(partId)
+ path.to.part(itemId)
);
if (!partData) throw new Error("Could not find part data");
- const itemInitialValues = {
- id: partData.partSummary?.itemId ?? "",
- readableId: partData.partSummary?.id ?? "",
+ const partInitialValues = {
+ id: partData.partSummary?.id ?? "",
+ itemId: partData.partSummary?.itemId ?? "",
name: partData.partSummary?.name ?? "",
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",
replenishmentSystem: partData.partSummary?.replenishmentSystem ?? "Buy",
unitOfMeasureCode: partData.partSummary?.unitOfMeasureCode ?? "EA",
@@ -76,11 +72,6 @@ export default function PartDetailsRoute() {
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+/$partId.tsx b/apps/carbon/app/routes/x+/part+/$itemId.tsx
similarity index 87%
rename from apps/carbon/app/routes/x+/part+/$partId.tsx
rename to apps/carbon/app/routes/x+/part+/$itemId.tsx
index 7bb48c7d7b..23fce3e36d 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.tsx
@@ -12,10 +12,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
view: "parts",
});
- const { partId } = params;
- if (!partId) throw new Error("Could not find partId");
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
- const [partSummary] = await Promise.all([getPart(client, partId, companyId)]);
+ const [partSummary] = await Promise.all([getPart(client, itemId, companyId)]);
if (partSummary.error) {
throw redirect(
diff --git a/apps/carbon/app/routes/x+/part+/new.tsx b/apps/carbon/app/routes/x+/part+/new.tsx
index df01d995dc..1c4b4a62a3 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, newPartValidator, upsertPart } from "~/modules/parts";
+import { PartForm, partValidator, 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(newPartValidator).validate(formData);
+ const validation = await validator(partValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
@@ -43,12 +43,12 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- const partId = createPart.data?.id;
- if (!partId) throw new Error("Part ID not found");
+ const itemId = createPart.data?.itemId;
+ if (!itemId) throw new Error("Part ID not found");
return modal
? json(createPart, { status: 201 })
- : redirect(path.to.part(partId));
+ : redirect(path.to.part(itemId));
}
export default function PartsNewRoute() {
diff --git a/apps/carbon/app/routes/x+/service+/$serviceId._index.tsx b/apps/carbon/app/routes/x+/service+/$itemId._index.tsx
similarity index 58%
rename from apps/carbon/app/routes/x+/service+/$serviceId._index.tsx
rename to apps/carbon/app/routes/x+/service+/$itemId._index.tsx
index c91d8020ec..39182b0082 100644
--- a/apps/carbon/app/routes/x+/service+/$serviceId._index.tsx
+++ b/apps/carbon/app/routes/x+/service+/$itemId._index.tsx
@@ -3,7 +3,7 @@ import { redirect } from "@remix-run/node";
import { path } from "~/utils/path";
export async function loader({ params }: LoaderFunctionArgs) {
- const { serviceId } = params;
- if (!serviceId) throw new Error("Could not find serviceId");
- throw redirect(path.to.serviceDetails(serviceId));
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+ throw redirect(path.to.serviceDetails(itemId));
}
diff --git a/apps/carbon/app/routes/x+/service+/$serviceId.details.tsx b/apps/carbon/app/routes/x+/service+/$itemId.details.tsx
similarity index 68%
rename from apps/carbon/app/routes/x+/service+/$serviceId.details.tsx
rename to apps/carbon/app/routes/x+/service+/$itemId.details.tsx
index 12f28fbeff..b2bd6ce35a 100644
--- a/apps/carbon/app/routes/x+/service+/$serviceId.details.tsx
+++ b/apps/carbon/app/routes/x+/service+/$itemId.details.tsx
@@ -5,12 +5,7 @@ import { redirect } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import { useRouteData } from "~/hooks";
import type { Service } from "~/modules/parts";
-import {
- ItemForm,
- ServiceForm,
- serviceValidator,
- upsertService,
-} from "~/modules/parts";
+import { ServiceForm, serviceValidator, upsertService } from "~/modules/parts";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { getCustomFields, setCustomFields } from "~/utils/form";
@@ -24,8 +19,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
update: "parts",
});
- const { serviceId } = params;
- if (!serviceId) throw new Error("Could not find serviceId");
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
const formData = await request.formData();
const validation = await validator(serviceValidator).validate(formData);
@@ -36,42 +31,30 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatePart = await upsertService(client, {
...validation.data,
- id: serviceId,
+ id: itemId,
updatedBy: userId,
customFields: setCustomFields(formData),
});
if (updatePart.error) {
throw redirect(
- path.to.service(serviceId),
+ path.to.service(itemId),
await flash(request, error(updatePart.error, "Failed to update part"))
);
}
throw redirect(
- path.to.service(serviceId),
+ path.to.service(itemId),
await flash(request, success("Updated part"))
);
}
export default function ServiceDetailsRoute() {
- const { serviceId } = useParams();
- if (!serviceId) throw new Error("Could not find serviceId");
- const routeData = useRouteData<{ service: Service }>(
- path.to.service(serviceId)
- );
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+ const routeData = useRouteData<{ service: Service }>(path.to.service(itemId));
if (!routeData) throw new Error("Could not find part data");
- const itemInitialValues = {
- id: routeData.service?.itemId ?? "",
- readableId: routeData.service?.id ?? "",
- name: routeData.service?.name ?? "",
- description: routeData.service?.description ?? "",
- partGroupId: routeData.service?.partGroupId ?? "",
- active: routeData.service?.active ?? true,
- blocked: routeData.service?.blocked ?? false,
- };
-
const serviceInitialValues = {
id: routeData.service?.id!,
name: routeData.service?.name ?? "",
@@ -85,11 +68,6 @@ export default function ServiceDetailsRoute() {
return (
<VStack spacing={4}>
- <ItemForm
- key={itemInitialValues.id}
- initialValues={itemInitialValues}
- type="service"
- />
<ServiceForm
key={serviceInitialValues.id}
initialValues={serviceInitialValues}
diff --git a/apps/carbon/app/routes/x+/service+/$serviceId.tsx b/apps/carbon/app/routes/x+/service+/$itemId.tsx
similarity index 86%
rename from apps/carbon/app/routes/x+/service+/$serviceId.tsx
rename to apps/carbon/app/routes/x+/service+/$itemId.tsx
index 93c6719495..e4a414c21e 100644
--- a/apps/carbon/app/routes/x+/service+/$serviceId.tsx
+++ b/apps/carbon/app/routes/x+/service+/$itemId.tsx
@@ -18,12 +18,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
view: "parts",
});
- const { serviceId } = params;
- if (!serviceId) throw new Error("Could not find serviceId");
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
- const [service] = await Promise.all([
- getService(client, serviceId, companyId),
- ]);
+ const [service] = await Promise.all([getService(client, itemId, companyId)]);
if (service.error) {
throw redirect(
diff --git a/apps/carbon/app/routes/x+/service+/new.tsx b/apps/carbon/app/routes/x+/service+/new.tsx
index 8718530ba8..d533d785dc 100644
--- a/apps/carbon/app/routes/x+/service+/new.tsx
+++ b/apps/carbon/app/routes/x+/service+/new.tsx
@@ -1,11 +1,7 @@
import { validationError, validator } from "@carbon/remix-validated-form";
import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
-import {
- ServiceForm,
- newServiceValidator,
- upsertService,
-} from "~/modules/parts";
+import { ServiceForm, serviceValidator, upsertService } from "~/modules/parts";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { setCustomFields } from "~/utils/form";
@@ -26,7 +22,7 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- const validation = await validator(newServiceValidator).validate(formData);
+ const validation = await validator(serviceValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 7048590ec9..57f902ced2 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -5425,6 +5425,8 @@ export type Database = {
partGroupId: string | null
readableId: string
type: Database["public"]["Enums"]["itemType"]
+ updatedAt: string | null
+ updatedBy: string | null
}
Insert: {
active?: boolean
@@ -5438,6 +5440,8 @@ export type Database = {
partGroupId?: string | null
readableId: string
type: Database["public"]["Enums"]["itemType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
}
Update: {
active?: boolean
@@ -5451,6 +5455,8 @@ export type Database = {
partGroupId?: string | null
readableId?: string
type?: Database["public"]["Enums"]["itemType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
}
Relationships: [
{
@@ -5523,6 +5529,41 @@ export type Database = {
referencedRelation: "partGroup"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
]
}
journal: {
@@ -20522,14 +20563,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 7048590ec9..57f902ced2 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -5425,6 +5425,8 @@ export type Database = {
partGroupId: string | null
readableId: string
type: Database["public"]["Enums"]["itemType"]
+ updatedAt: string | null
+ updatedBy: string | null
}
Insert: {
active?: boolean
@@ -5438,6 +5440,8 @@ export type Database = {
partGroupId?: string | null
readableId: string
type: Database["public"]["Enums"]["itemType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
}
Update: {
active?: boolean
@@ -5451,6 +5455,8 @@ export type Database = {
partGroupId?: string | null
readableId?: string
type?: Database["public"]["Enums"]["itemType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
}
Relationships: [
{
@@ -5523,6 +5529,41 @@ export type Database = {
referencedRelation: "partGroup"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
]
}
journal: {
@@ -20522,14 +20563,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
diff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sql
index 0acb09b171..5f911a05e7 100644
--- a/packages/database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/database/supabase/migrations/20230330024716_parts.sql
@@ -73,12 +73,15 @@ CREATE TABLE "item" (
"companyId" TEXT NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
CONSTRAINT "item_pkey" PRIMARY KEY (id),
CONSTRAINT "item_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "item_unique" UNIQUE ("readableId", "companyId", "type"),
CONSTRAINT "item_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "item_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
+ CONSTRAINT "item_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "item_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
CREATE INDEX "item_companyId_idx" ON "item" ("companyId");