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: routes for tools

Brad Barbin5f4ac4feef2c
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
index 839f8584f4..2efacdf8f4 100644
--- a/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
@@ -82,22 +82,20 @@ const EditablePurchaseInvoiceLineNumber =
const onItemChange = async (itemId: string) => {
if (!client) throw new Error("Supabase client not found");
switch (row.invoiceLineType) {
+ case "Material":
case "Part":
- const [item, part, itemSupplier, inventory] = await Promise.all([
+ case "Tool":
+ case "Fixture":
+ case "Consumable":
+ const [item, itemSupplier, inventory] = await Promise.all([
client
.from("item")
.select(
- "name, readableId, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
+ "name, readableId, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
)
.eq("id", itemId)
.eq("companyId", row.companyId!)
.single(),
- client
- .from("part")
- .select("unitOfMeasureCode")
- .eq("itemId", itemId)
- .eq("companyId", row.companyId!)
- .single(),
client
.from("itemSupplier")
.select("*")
@@ -117,12 +115,7 @@ const EditablePurchaseInvoiceLineNumber =
const itemCost = item?.data?.itemCost?.[0];
const itemReplenishment = item?.data?.itemReplenishment?.[0];
- if (
- item.error ||
- part.error ||
- itemSupplier.error ||
- inventory.error
- ) {
+ if (item.error || itemSupplier.error || inventory.error) {
onError();
return;
}
@@ -136,7 +129,7 @@ const EditablePurchaseInvoiceLineNumber =
unitPrice: itemSupplier?.data?.unitPrice ?? itemCost?.unitCost ?? 0,
purchaseUnitOfMeasureCode:
itemReplenishment?.purchasingUnitOfMeasureCode ??
- part.data?.unitOfMeasureCode ??
+ item.data?.unitOfMeasureCode ??
"EA",
conversionFactor: itemReplenishment?.conversionFactor ?? 1,
@@ -156,7 +149,7 @@ const EditablePurchaseInvoiceLineNumber =
itemSupplier?.data?.unitPrice ?? itemCost?.unitCost ?? 0,
purchaseUnitOfMeasureCode:
itemReplenishment?.purchasingUnitOfMeasureCode ??
- part.data?.unitOfMeasureCode ??
+ item.data?.unitOfMeasureCode ??
"EA",
conversionFactor: itemReplenishment?.conversionFactor ?? 1,
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
index ac9405bfaf..820cfd4ff0 100644
--- a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
@@ -87,22 +87,21 @@ const EditablePurchaseOrderLineNumber =
if (!row.id) throw new Error("Purchase order line ID not found");
switch (row.purchaseOrderLineType) {
+ case "Material":
case "Part":
- const [item, part, itemSupplier, inventory] = await Promise.all([
+ case "Tool":
+ case "Fixture":
+ case "Consumable":
+ const [item, itemSupplier, inventory] = await Promise.all([
client
.from("item")
.select(
- "name, readableId, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
+ "name, readableId, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
)
.eq("id", itemId)
.eq("companyId", row.companyId!)
.single(),
- client
- .from("part")
- .select("unitOfMeasureCode")
- .eq("itemId", itemId)
- .eq("companyId", row.companyId!)
- .single(),
+
client
.from("itemSupplier")
.select("*")
@@ -122,12 +121,7 @@ const EditablePurchaseOrderLineNumber =
const itemCost = item?.data?.itemCost?.[0];
const itemReplenishment = item?.data?.itemReplenishment?.[0];
- if (
- item.error ||
- part.error ||
- itemSupplier.error ||
- inventory.error
- ) {
+ if (item.error || itemSupplier.error || inventory.error) {
onError();
return;
}
@@ -141,7 +135,7 @@ const EditablePurchaseOrderLineNumber =
unitPrice: itemSupplier?.data?.unitPrice ?? itemCost?.unitCost ?? 0,
purchaseUnitOfMeasureCode:
itemReplenishment?.purchasingUnitOfMeasureCode ??
- part.data?.unitOfMeasureCode ??
+ item.data?.unitOfMeasureCode ??
"EA",
conversionFactor: itemReplenishment?.conversionFactor ?? 1,
@@ -161,7 +155,7 @@ const EditablePurchaseOrderLineNumber =
itemSupplier?.data?.unitPrice ?? itemCost?.unitCost ?? 0,
purchaseUnitOfMeasureCode:
itemReplenishment?.purchasingUnitOfMeasureCode ??
- part.data?.unitOfMeasureCode ??
+ item.data?.unitOfMeasureCode ??
"EA",
conversionFactor: itemReplenishment?.conversionFactor ?? 1,
diff --git a/apps/carbon/app/components/Editable/EditableSalesOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditableSalesOrderLineNumber.tsx
index f205fb4ac1..ef45081f9d 100644
--- a/apps/carbon/app/components/Editable/EditableSalesOrderLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditableSalesOrderLineNumber.tsx
@@ -45,23 +45,20 @@ const EditableSalesOrderLineNumber =
if (!row.id) throw new Error("Purchase order line ID not found");
switch (row.salesOrderLineType) {
+ case "Consumable":
+ case "Tool":
+ case "Fixture":
+ case "Material":
case "Part":
- const [item, part, inventory] = await Promise.all([
+ const [item, inventory] = await Promise.all([
client
.from("item")
.select(
- "name, readableId, itemUnitSalePrice(unitSalePrice), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
+ "name, readableId, unitOfMeasureCode, itemUnitSalePrice(unitSalePrice)"
)
.eq("id", itemId)
.eq("companyId", row.companyId!)
.single(),
- client
- .from("part")
- .select("unitOfMeasureCode")
- .eq("itemId", itemId)
- .eq("companyId", row.companyId!)
- .single(),
-
client
.from("itemInventory")
.select("defaultShelfId")
@@ -72,9 +69,8 @@ const EditableSalesOrderLineNumber =
]);
const itemUnitSalePrice = item?.data?.itemUnitSalePrice?.[0];
- const itemReplenishment = item?.data?.itemReplenishment?.[0];
- if (item.error || part.error || inventory.error) {
+ if (item.error || inventory.error) {
onError();
return;
}
@@ -85,7 +81,7 @@ const EditableSalesOrderLineNumber =
locationId: options.defaultLocationId,
description: item.data?.name ?? "",
unitPrice: itemUnitSalePrice?.unitSalePrice ?? 0,
- unitOfMeasureCode: part.data?.unitOfMeasureCode ?? "EA",
+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
shelfId: inventory.data?.defaultShelfId ?? null,
});
@@ -98,7 +94,7 @@ const EditableSalesOrderLineNumber =
locationId: options.defaultLocationId,
description: item.data?.name ?? "",
unitPrice: itemUnitSalePrice?.unitSalePrice ?? 0,
- unitOfMeasureCode: part.data?.unitOfMeasureCode ?? "EA",
+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
shelfId: inventory.data?.defaultShelfId ?? null,
updatedBy: userId,
})
diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
index 8b1acf4a95..2df5fd93b0 100644
--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
@@ -152,22 +152,20 @@ const PurchaseInvoiceLineForm = ({
const onItemChange = async (itemId: string) => {
if (!supabase) throw new Error("Supabase client not found");
switch (type) {
+ case "Consumable":
+ case "Material":
case "Part":
- const [item, part, itemSupplier, inventory] = await Promise.all([
+ case "Tool":
+ case "Fixture":
+ const [item, itemSupplier, inventory] = await Promise.all([
supabase
.from("item")
.select(
- "name, readableId, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
+ "name, readableId, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
)
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
- .from("part")
- .select("unitOfMeasureCode")
- .eq("itemId", itemId)
- .eq("companyId", company.id)
- .single(),
supabase
.from("itemSupplier")
.select("*")
@@ -195,9 +193,9 @@ const PurchaseInvoiceLineForm = ({
unitPrice: itemSupplier?.data?.unitPrice ?? itemCost?.unitCost ?? 0,
purchaseUom:
itemReplenishment?.purchasingUnitOfMeasureCode ??
- part.data?.unitOfMeasureCode ??
+ item.data?.unitOfMeasureCode ??
"EA",
- inventoryUom: part.data?.unitOfMeasureCode ?? "EA",
+ inventoryUom: item.data?.unitOfMeasureCode ?? "EA",
conversionFactor: itemReplenishment?.conversionFactor ?? 1,
shelfId: inventory.data?.defaultShelfId ?? null,
diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
index 266ab98338..0c118529a4 100644
--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
@@ -153,10 +153,13 @@ const PurchaseInvoiceLines = () => {
header: "Pur. UoM",
cell: ({ row }) => {
switch (row.original.invoiceLineType) {
- case "Part":
- return <span>{row.original.purchaseUnitOfMeasureCode}</span>;
- default:
+ case "Comment":
+ case "Service":
+ case "G/L Account":
+ case "Fixed Asset":
return null;
+ default:
+ return <span>{row.original.purchaseUnitOfMeasureCode}</span>;
}
},
},
@@ -165,10 +168,13 @@ const PurchaseInvoiceLines = () => {
header: "Conversion Factor",
cell: ({ row }) => {
switch (row.original.invoiceLineType) {
- case "Part":
- return <span>{row.original.conversionFactor}</span>;
- default:
+ case "Comment":
+ case "Service":
+ case "G/L Account":
+ case "Fixed Asset":
return null;
+ default:
+ return <span>{row.original.conversionFactor}</span>;
}
},
},
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index d1ab17b167..ffec2d1d02 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -37,6 +37,9 @@ export const itemValidator = z.object({
message: "Part type is required",
}),
}),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of Measure is required" }),
blocked: zfd.checkbox(),
active: zfd.checkbox(),
});
@@ -65,9 +68,6 @@ export const partValidator = itemValidator.merge(
message: "Replenishment system is required",
}),
}),
- unitOfMeasureCode: z
- .string()
- .min(1, { message: "Unit of Measure is required" }),
})
);
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index 90914f84e5..5c70e4ee1c 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -19,9 +19,9 @@ import type {
partManufacturingValidator,
partValidator,
serviceValidator,
+ toolValidator,
unitOfMeasureValidator,
} from "./items.models";
-import type { ItemReplenishmentSystem, ServiceType } from "./types";
export async function deleteItemGroup(
client: SupabaseClient<Database>,
@@ -249,6 +249,19 @@ export async function getMaterialSubstancesList(
.order("name");
}
+export async function getPart(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ return client
+ .from("parts")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single();
+}
+
export async function getParts(
client: SupabaseClient<Database>,
companyId: string,
@@ -282,22 +295,16 @@ export async function getParts(
export async function getPartsList(
client: SupabaseClient<Database>,
- companyId: string,
- replenishmentSystem: ItemReplenishmentSystem | null
+ companyId: string
) {
let query = client
.from("item")
.select("id, name, readableId")
+ .eq("type", "Part")
.eq("companyId", companyId)
.eq("blocked", false)
.eq("active", true);
- if (replenishmentSystem) {
- query = query.or(
- `replenishmentSystem.eq.${replenishmentSystem},replenishmentSystem.eq.Buy and Make`
- );
- }
-
return query.order("name");
}
@@ -316,19 +323,6 @@ export async function getItemQuantities(
.maybeSingle();
}
-export async function getPart(
- client: SupabaseClient<Database>,
- itemId: string,
- companyId: string
-) {
- return client
- .from("parts")
- .select("*")
- .eq("itemId", itemId)
- .eq("companyId", companyId)
- .single();
-}
-
export async function getItemSuppliers(
client: SupabaseClient<Database>,
id: string,
@@ -419,21 +413,17 @@ export async function getService(
export async function getServicesList(
client: SupabaseClient<Database>,
- companyId: string,
- type: ServiceType | null
+ companyId: string
) {
let query = client
- .from("service")
+ .from("item")
.select("id, name")
+ .eq("type", "Service")
.eq("companyId", companyId)
.eq("blocked", false)
.eq("active", true)
.order("name");
- if (type) {
- query = query.eq("serviceType", type);
- }
-
return query;
}
@@ -449,6 +439,65 @@ export async function getShelvesList(
.order("id");
}
+export async function getTool(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ return client
+ .from("tools")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single();
+}
+
+export async function getTools(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & {
+ search: string | null;
+ supplierId: string | null;
+ }
+) {
+ let query = client
+ .from("tools")
+ .select("*", {
+ count: "exact",
+ })
+ .eq("companyId", companyId);
+
+ if (args.search) {
+ query = query.or(
+ `id.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%`
+ );
+ }
+
+ if (args.supplierId) {
+ query = query.contains("supplierIds", [args.supplierId]);
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "id", ascending: true },
+ ]);
+ return query;
+}
+
+export async function getToolsList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ let query = client
+ .from("item")
+ .select("id, name, readableId")
+ .eq("type", "Tool")
+ .eq("companyId", companyId)
+ .eq("blocked", false)
+ .eq("active", true);
+
+ return query.order("name");
+}
+
export async function getUnitOfMeasure(
client: SupabaseClient<Database>,
id: string,
@@ -552,6 +601,7 @@ export async function upsertPart(
type: "Part",
itemGroupId: part.itemGroupId,
itemInventoryType: part.itemInventoryType,
+ unitOfMeasureCode: part.unitOfMeasureCode,
companyId: part.companyId,
createdBy: part.createdBy,
})
@@ -566,7 +616,6 @@ export async function upsertPart(
id: part.id,
itemId: itemId,
replenishmentSystem: part.replenishmentSystem,
- unitOfMeasureCode: part.unitOfMeasureCode,
companyId: part.companyId,
createdBy: part.createdBy,
customFields: part.customFields,
@@ -581,13 +630,13 @@ export async function upsertPart(
description: part.description,
itemGroupId: part.itemGroupId,
itemInventoryType: part.itemInventoryType,
+ unitOfMeasureCode: part.unitOfMeasureCode,
active: part.active,
blocked: part.blocked,
};
const partUpdate = {
replenishmentSystem: part.replenishmentSystem,
- unitOfMeasureCode: part.unitOfMeasureCode,
customFields: part.customFields,
};
@@ -869,6 +918,7 @@ export async function upsertService(
type: "Service",
itemGroupId: service.itemGroupId,
itemInventoryType: service.itemInventoryType,
+ unitOfMeasureCode: null,
companyId: service.companyId,
createdBy: service.createdBy,
})
@@ -895,6 +945,7 @@ export async function upsertService(
description: service.description,
itemGroupId: service.itemGroupId,
itemInventoryType: service.itemInventoryType,
+ unitOfMeasureCode: null,
active: service.active,
blocked: service.blocked,
};
@@ -953,3 +1004,83 @@ export async function upsertUnitOfMeasure(
.select("id")
.single();
}
+
+export async function upsertTool(
+ client: SupabaseClient<Database>,
+ tool:
+ | (z.infer<typeof toolValidator> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (z.infer<typeof toolValidator> & {
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in tool) {
+ const itemInsert = await client
+ .from("item")
+ .insert({
+ readableId: tool.id,
+ name: tool.name,
+ type: "Tool",
+ itemGroupId: tool.itemGroupId,
+ itemInventoryType: tool.itemInventoryType,
+ unitOfMeasureCode: tool.unitOfMeasureCode,
+ companyId: tool.companyId,
+ createdBy: tool.createdBy,
+ })
+ .select("id")
+ .single();
+ if (itemInsert.error) return itemInsert;
+ const itemId = itemInsert.data?.id;
+
+ return client
+ .from("tool")
+ .insert({
+ id: tool.id,
+ itemId: itemId,
+ companyId: tool.companyId,
+ createdBy: tool.createdBy,
+ customFields: tool.customFields,
+ })
+ .select("*")
+ .single();
+ }
+
+ const itemUpdate = {
+ id: tool.id,
+ name: tool.name,
+ description: tool.description,
+ itemGroupId: tool.itemGroupId,
+ itemInventoryType: tool.itemInventoryType,
+ unitOfMeasureCode: tool.unitOfMeasureCode,
+ active: tool.active,
+ blocked: tool.blocked,
+ };
+
+ const toolUpdate = {
+ customFields: tool.customFields,
+ };
+
+ const [updateItem, updatePart] = await Promise.all([
+ client
+ .from("item")
+ .update({
+ ...sanitize(itemUpdate),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", tool.id),
+ client
+ .from("tool")
+ .update({
+ ...sanitize(toolUpdate),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("itemId", tool.id),
+ ]);
+
+ if (updateItem.error) return updateItem;
+ return updatePart;
+}
diff --git a/apps/carbon/app/modules/items/types.ts b/apps/carbon/app/modules/items/types.ts
index 49b58ade98..3497e53e55 100644
--- a/apps/carbon/app/modules/items/types.ts
+++ b/apps/carbon/app/modules/items/types.ts
@@ -10,6 +10,8 @@ import type {
getPart,
getParts,
getServices,
+ getTool,
+ getTools,
getUnitOfMeasure,
getUnitOfMeasuresList,
} from "./items.service";
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemInventoryForm.tsx b/apps/carbon/app/modules/items/ui/Item/ItemInventoryForm.tsx
index 05af1eed9a..f08f2502ff 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemInventoryForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemInventoryForm.tsx
@@ -30,6 +30,7 @@ type ItemInventoryFormProps = {
quantities: ItemQuantities;
locations: ListItem[];
shelves: string[];
+ type: "Part" | "Material" | "Tool" | "Fixture" | "Consumable";
};
const ItemInventoryForm = ({
@@ -37,6 +38,7 @@ const ItemInventoryForm = ({
locations,
quantities,
shelves,
+ type,
}: ItemInventoryFormProps) => {
const permissions = usePermissions();
const { supabase } = useSupabase();
@@ -68,9 +70,11 @@ const ItemInventoryForm = ({
options={locationOptions}
onChange={(selected) => {
// hard refresh because initialValues update has no effect otherwise
- window.location.href = `${path.to.partInventory(
- initialValues.itemId
- )}?location=${selected}`;
+ window.location.href = getLocationPath(
+ initialValues.itemId,
+ selected,
+ type
+ );
}}
/>
</CardAction>
@@ -132,3 +136,25 @@ const ItemInventoryForm = ({
};
export default ItemInventoryForm;
+
+function getLocationPath(
+ itemId: string,
+ locationId: string,
+ type: "Part" | "Material" | "Tool" | "Fixture" | "Consumable"
+) {
+ switch (type) {
+ case "Part":
+ return `${path.to.partInventory(itemId)}?location=${locationId}`;
+ case "Material":
+ return `${path.to.materialInventory(itemId)}?location=${locationId}`;
+
+ case "Tool":
+ return `${path.to.toolInventory(itemId)}?location=${locationId}`;
+ case "Fixture":
+ return `${path.to.fixtureInventory(itemId)}?location=${locationId}`;
+ case "Consumable":
+ return `${path.to.consumableInventory(itemId)}?location=${locationId}`;
+ default:
+ throw new Error(`Invalid item type: ${type}`);
+ }
+}
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemPlanningForm.tsx b/apps/carbon/app/modules/items/ui/Item/ItemPlanningForm.tsx
index 7342722deb..7ec33dd45b 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemPlanningForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemPlanningForm.tsx
@@ -26,11 +26,13 @@ import { path } from "~/utils/path";
type ItemPlanningFormProps = {
initialValues: z.infer<typeof itemPlanningValidator>;
locations: ListItem[];
+ type: "Part" | "Material" | "Tool" | "Fixture" | "Consumable";
};
const ItemPlanningForm = ({
initialValues,
locations,
+ type,
}: ItemPlanningFormProps) => {
const permissions = usePermissions();
@@ -57,9 +59,11 @@ const ItemPlanningForm = ({
options={locationOptions}
onChange={(selected) => {
// hard refresh because initialValues update has no effect otherwise
- window.location.href = `${path.to.partPlanning(
- initialValues.itemId
- )}?location=${selected}`;
+ window.location.href = window.location.href = getLocationPath(
+ initialValues.itemId,
+ selected,
+ type
+ );
}}
/>
</CardAction>
@@ -131,3 +135,25 @@ const ItemPlanningForm = ({
};
export default ItemPlanningForm;
+
+function getLocationPath(
+ itemId: string,
+ locationId: string,
+ type: "Part" | "Material" | "Tool" | "Fixture" | "Consumable"
+) {
+ switch (type) {
+ case "Part":
+ return `${path.to.partPlanning(itemId)}?location=${locationId}`;
+ case "Material":
+ return `${path.to.materialPlanning(itemId)}?location=${locationId}`;
+
+ case "Tool":
+ return `${path.to.toolPlanning(itemId)}?location=${locationId}`;
+ case "Fixture":
+ return `${path.to.fixturePlanning(itemId)}?location=${locationId}`;
+ case "Consumable":
+ return `${path.to.consumablePlanning(itemId)}?location=${locationId}`;
+ default:
+ throw new Error(`Invalid item type: ${type}`);
+ }
+}
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemSupplierForm.tsx b/apps/carbon/app/modules/items/ui/Item/ItemSupplierForm.tsx
index e864d8c030..d748f9ecc0 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemSupplierForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemSupplierForm.tsx
@@ -30,7 +30,7 @@ import { path } from "~/utils/path";
type ItemSupplierFormProps = {
initialValues: z.infer<typeof itemSupplierValidator>;
- type: "Part" | "Service";
+ type: "Part" | "Service" | "Tool";
};
const ItemSupplierForm = ({ initialValues, type }: ItemSupplierFormProps) => {
@@ -124,7 +124,7 @@ export default ItemSupplierForm;
function getAction(
isEditing: boolean,
- type: "Part" | "Service",
+ type: "Part" | "Service" | "Tool",
itemId: string,
id?: string
) {
@@ -142,5 +142,13 @@ function getAction(
return path.to.newServiceSupplier(itemId);
}
}
+
+ if (type === "Tool") {
+ if (isEditing) {
+ return path.to.toolSupplier(itemId, id!);
+ } else {
+ return path.to.newToolSupplier(itemId);
+ }
+ }
throw new Error("Invalid type");
}
diff --git a/apps/carbon/app/modules/items/ui/Services/ServiceForm.tsx b/apps/carbon/app/modules/items/ui/Services/ServiceForm.tsx
index 5a944360d8..fba2141eec 100644
--- a/apps/carbon/app/modules/items/ui/Services/ServiceForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Services/ServiceForm.tsx
@@ -58,6 +58,7 @@ const ServiceForm = ({ initialValues }: ServiceFormProps) => {
</CardHeader>
<CardContent>
<Hidden name="itemInventoryType" value="Non-Inventory" />
+ <Hidden name="unitOfMeasureCode" value="" />
<div
className={cn(
"grid w-full gap-x-8 gap-y-2",
diff --git a/apps/carbon/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/carbon/app/modules/items/ui/Tools/ToolsTable.tsx
index 4c59312b91..a8f1bc14e6 100644
--- a/apps/carbon/app/modules/items/ui/Tools/ToolsTable.tsx
+++ b/apps/carbon/app/modules/items/ui/Tools/ToolsTable.tsx
@@ -32,7 +32,7 @@ const ToolsTable = memo(({ data, count, itemGroups }: ToolsTableProps) => {
accessorKey: "id",
header: "Tool ID",
cell: ({ row }) => (
- <Hyperlink to={path.to.partDetails(row.original.itemId!)}>
+ <Hyperlink to={path.to.toolDetails(row.original.itemId!)}>
{row.original.id}
</Hyperlink>
),
@@ -171,7 +171,7 @@ const ToolsTable = memo(({ data, count, itemGroups }: ToolsTableProps) => {
const renderContextMenu = useMemo(() => {
// eslint-disable-next-line react/display-name
return (row: Tool) => (
- <MenuItem onClick={() => navigate(path.to.part(row.id!))}>
+ <MenuItem onClick={() => navigate(path.to.tool(row.id!))}>
<MenuIcon icon={<LuPencil />} />
Edit Tool
</MenuItem>
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
index deeb4cd8b5..c34b137f2f 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
@@ -148,22 +148,20 @@ const PurchaseOrderLineForm = ({
const onItemChange = async (itemId: string) => {
if (!supabase) throw new Error("Supabase client not found");
switch (type) {
+ case "Consumable":
+ case "Material":
case "Part":
- const [item, part, itemSupplier, inventory] = await Promise.all([
+ case "Tool":
+ case "Fixture":
+ const [item, itemSupplier, inventory] = await Promise.all([
supabase
.from("item")
.select(
- "name, readableId, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
+ "name, readableId, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
)
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
- .from("part")
- .select("unitOfMeasureCode")
- .eq("itemId", itemId)
- .eq("companyId", company.id)
- .single(),
supabase
.from("itemSupplier")
.select("*")
@@ -191,9 +189,9 @@ const PurchaseOrderLineForm = ({
unitPrice: itemSupplier?.data?.unitPrice ?? itemCost?.unitCost ?? 0,
purchaseUom:
itemReplenishment?.purchasingUnitOfMeasureCode ??
- part.data?.unitOfMeasureCode ??
+ item.data?.unitOfMeasureCode ??
"EA",
- inventoryUom: part.data?.unitOfMeasureCode ?? "EA",
+ inventoryUom: item.data?.unitOfMeasureCode ?? "EA",
conversionFactor: itemReplenishment?.conversionFactor ?? 1,
shelfId: inventory.data?.defaultShelfId ?? null,
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
index f0429a876e..039418d0d1 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
@@ -171,10 +171,13 @@ const PurchaseOrderLines = () => {
header: "Pur. UoM",
cell: ({ row }) => {
switch (row.original.purchaseOrderLineType) {
- case "Part":
- return <span>{row.original.purchaseUnitOfMeasureCode}</span>;
- default:
+ case "Service":
+ case "Comment":
+ case "G/L Account":
+ case "Fixed Asset":
return null;
+ default:
+ return <span>{row.original.purchaseUnitOfMeasureCode}</span>;
}
},
},
@@ -183,10 +186,13 @@ const PurchaseOrderLines = () => {
header: "Conversion Factor",
cell: ({ row }) => {
switch (row.original.purchaseOrderLineType) {
- case "Part":
- return <span>{row.original.conversionFactor}</span>;
- default:
+ case "Service":
+ case "Comment":
+ case "G/L Account":
+ case "Fixed Asset":
return null;
+ default:
+ return <span>{row.original.conversionFactor}</span>;
}
},
},
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index 0465e45c5f..63a7fc125c 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -126,19 +126,13 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
const onChange = async (itemId: string) => {
if (!itemId) return;
if (!supabase || !company.id) return;
- const [item, part, shelf, price] = await Promise.all([
+ const [item, shelf, price] = await Promise.all([
supabase
.from("item")
- .select("name, readableId")
+ .select("name, readableId, unitOfMeasureCode")
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
- .from("part")
- .select("unitOfMeasureCode")
- .eq("itemId", itemId)
- .eq("companyId", company.id)
- .maybeSingle(),
supabase
.from("itemInventory")
.select("defaultShelfId")
@@ -159,7 +153,7 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
itemReadableId: item.data?.readableId,
description: item.data?.name ?? "",
unitPrice: price.data?.unitSalePrice ?? 0,
- uom: part.data?.unitOfMeasureCode ?? "EA",
+ uom: item.data?.unitOfMeasureCode ?? "EA",
shelfId: shelf.data?.defaultShelfId ?? "",
});
};
@@ -260,7 +254,14 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
}))
}
/>
- {["Part", "Service"].includes(type) && (
+ {[
+ "Part",
+ "Material",
+ "Service",
+ "Tool",
+ "Fixture",
+ "Consumable",
+ ].includes(type) && (
<ComboboxControlled
name="locationId"
label="Location"
@@ -269,7 +270,13 @@ const SalesOrderLineForm = ({ initialValues }: SalesOrderLineFormProps) => {
onChange={onLocationChange}
/>
)}
- {type === "Part" && (
+ {[
+ "Part",
+ "Material",
+ "Tool",
+ "Fixture",
+ "Consumable",
+ ].includes(type) && (
<ComboboxControlled
name="shelfId"
label="Shelf"
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLines/SalesOrderLines.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLines/SalesOrderLines.tsx
index 02ad6e9fb6..22fec69f03 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLines/SalesOrderLines.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLines/SalesOrderLines.tsx
@@ -156,7 +156,10 @@ const SalesOrderLines = () => {
header: "Location",
cell: ({ row }) => {
switch (row.original.salesOrderLineType) {
- case "Part":
+ case "Comment":
+ case "Service":
+ return null;
+ default:
return (
<span>
{locations.find((l) => l.id == row.original.locationId)?.name}
diff --git a/apps/carbon/app/routes/_public+/_layout.tsx b/apps/carbon/app/routes/_public+/_layout.tsx
index 75e5224509..e2f9dbaf8a 100644
--- a/apps/carbon/app/routes/_public+/_layout.tsx
+++ b/apps/carbon/app/routes/_public+/_layout.tsx
@@ -7,7 +7,7 @@ export default function PublicRoute() {
<div className="flex min-h-screen min-w-screen">
<VStack
spacing={8}
- className="items-center justify-center mx-auto max-w-lg z-[3]"
+ className="items-center justify-start pt-[20vh] mx-auto max-w-lg z-[3]"
>
<Outlet />
</VStack>
diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsx
index c0a0eb6822..c3e0c24099 100644
--- a/apps/carbon/app/routes/onboarding+/company.tsx
+++ b/apps/carbon/app/routes/onboarding+/company.tsx
@@ -9,7 +9,6 @@ import {
HStack,
VStack,
} from "@carbon/react";
-import { redis } from "@carbon/redis";
import {
ValidatedForm,
validationError,
@@ -35,12 +34,8 @@ import {
seedCompany,
updateCompany,
} from "~/modules/settings";
-import { getPermissionCacheKey } from "~/modules/users/users.server";
import { requirePermissions } from "~/services/auth/auth.server";
-import {
- destroyAuthSession,
- updateCompanySession,
-} from "~/services/session.server";
+import { updateCompanySession } from "~/services/session.server";
import { assertIsPost } from "~/utils/http";
export async function loader({ request }: ActionFunctionArgs) {
@@ -153,7 +148,6 @@ export async function action({ request }: ActionFunctionArgs) {
companyId,
locationId,
}),
- redis.del(getPermissionCacheKey(userId)),
]);
if (job.error) {
@@ -162,10 +156,6 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
- if (!companyId) {
- await destroyAuthSession(request);
- }
-
throw redirect(next, {
headers: {
"Set-Cookie": await updateCompanySession(request, companyId!),
diff --git a/apps/carbon/app/routes/x+/items+/tools.tsx b/apps/carbon/app/routes/x+/items+/tools.tsx
new file mode 100644
index 0000000000..2d35a1b06e
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/tools.tsx
@@ -0,0 +1,66 @@
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import { ToolsTable, getItemGroupsList, getTools } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export const handle: Handle = {
+ breadcrumb: "Tools",
+ to: path.to.tools,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const supplierId = searchParams.get("supplierId");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [tools, itemGroups] = await Promise.all([
+ getTools(client, companyId, {
+ search,
+ supplierId,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
+ getItemGroupsList(client, companyId),
+ ]);
+
+ if (tools.error) {
+ redirect(
+ path.to.authenticatedRoot,
+ await flash(request, error(tools.error, "Failed to fetch tools"))
+ );
+ }
+
+ return json({
+ count: tools.count ?? 0,
+ tools: tools.data ?? [],
+ itemGroups: itemGroups.data ?? [],
+ });
+}
+
+export default function ToolsSearchRoute() {
+ const { count, tools, itemGroups } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <ToolsTable data={tools} count={count} itemGroups={itemGroups} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.inventory.tsx b/apps/carbon/app/routes/x+/part+/$itemId.inventory.tsx
index 94f349357b..a35b6a43a2 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.inventory.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.inventory.tsx
@@ -189,6 +189,7 @@ export default function PartInventoryRoute() {
quantities={quantities}
locations={sharedPartssData?.locations ?? []}
shelves={shelves}
+ type="Part"
/>
);
}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.planning.tsx b/apps/carbon/app/routes/x+/part+/$itemId.planning.tsx
index 96bf8af220..0d0924ce76 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.planning.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.planning.tsx
@@ -157,6 +157,7 @@ export default function PartPlanningRoute() {
...getCustomFields(partPlanning.customFields),
}}
locations={sharedPartsData.locations ?? []}
+ type="Part"
/>
);
}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId._index.tsx b/apps/carbon/app/routes/x+/tool+/$itemId._index.tsx
new file mode 100644
index 0000000000..d4d763bbea
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId._index.tsx
@@ -0,0 +1,9 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { path } from "~/utils/path";
+
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+ throw redirect(path.to.toolDetails(itemId));
+}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.costing.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.costing.tsx
new file mode 100644
index 0000000000..450a5da205
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.costing.tsx
@@ -0,0 +1,97 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { getAccountsList } from "~/modules/accounting";
+import {
+ ItemCostingForm,
+ getItemCost,
+ itemCostValidator,
+ upsertItemCost,
+} from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const [itemCost, accounts] = await Promise.all([
+ getItemCost(client, itemId, companyId),
+ getAccountsList(client, companyId),
+ ]);
+
+ if (itemCost.error) {
+ throw redirect(
+ path.to.items,
+ await flash(request, error(itemCost.error, "Failed to load tool costing"))
+ );
+ }
+ if (accounts.error) {
+ throw redirect(
+ path.to.items,
+ await flash(request, error(accounts.error, "Failed to load accounts"))
+ );
+ }
+
+ return json({
+ itemCost: itemCost.data,
+ accounts: accounts.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(itemCostValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateItemCost = await upsertItemCost(client, {
+ ...validation.data,
+ itemId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (updateItemCost.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(updateItemCost.error, "Failed to update tool costing")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.toolCosting(itemId),
+ await flash(request, success("Updated tool costing"))
+ );
+}
+
+export default function ToolCostingRoute() {
+ const { itemCost } = useLoaderData<typeof loader>();
+ return (
+ <ItemCostingForm
+ key={itemCost.itemId}
+ initialValues={{ ...itemCost, ...getCustomFields(itemCost.customFields) }}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.details.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.details.tsx
new file mode 100644
index 0000000000..09132b0f36
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.details.tsx
@@ -0,0 +1,77 @@
+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 { ToolSummary } from "~/modules/items";
+import { ToolForm, toolValidator, upsertTool } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(toolValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateTool = await upsertTool(client, {
+ ...validation.data,
+ id: itemId,
+ customFields: setCustomFields(formData),
+ updatedBy: userId,
+ });
+ if (updateTool.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(request, error(updateTool.error, "Failed to update tool"))
+ );
+ }
+
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(request, success("Updated tool"))
+ );
+}
+
+export default function ToolDetailsRoute() {
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+ const toolData = useRouteData<{ toolSummary: ToolSummary }>(
+ path.to.tool(itemId)
+ );
+ if (!toolData) throw new Error("Could not find tool data");
+
+ const toolInitialValues = {
+ id: toolData.toolSummary?.id ?? "",
+ itemId: toolData.toolSummary?.itemId ?? "",
+ name: toolData.toolSummary?.name ?? "",
+ description: toolData.toolSummary?.description ?? "",
+ itemGroupId: toolData.toolSummary?.itemGroupId ?? "",
+ itemInventoryType: toolData.toolSummary?.itemInventoryType ?? "Inventory",
+ active: toolData.toolSummary?.active ?? true,
+ blocked: toolData.toolSummary?.blocked ?? false,
+ unitOfMeasureCode: toolData.toolSummary?.unitOfMeasureCode ?? "EA",
+ ...getCustomFields(toolData.toolSummary?.customFields ?? {}),
+ };
+
+ return (
+ <VStack spacing={4}>
+ <ToolForm key={toolInitialValues.id} initialValues={toolInitialValues} />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.inventory.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.inventory.tsx
new file mode 100644
index 0000000000..bb76ae2133
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.inventory.tsx
@@ -0,0 +1,195 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import {
+ ItemInventoryForm,
+ getItemInventory,
+ getItemQuantities,
+ getShelvesList,
+ itemInventoryValidator,
+ upsertItemInventory,
+} from "~/modules/items";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { ListItem } from "~/types";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ let [toolInventory, shelves] = await Promise.all([
+ getItemInventory(client, itemId, companyId, locationId),
+ getShelvesList(client, locationId),
+ ]);
+
+ if (toolInventory.error || !toolInventory.data) {
+ const insertItemInventory = await upsertItemInventory(client, {
+ itemId,
+ companyId,
+ locationId,
+ customFields: {},
+ createdBy: userId,
+ });
+
+ if (insertItemInventory.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(insertItemInventory.error, "Failed to insert tool inventory")
+ )
+ );
+ }
+
+ toolInventory = await getItemInventory(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (toolInventory.error || !toolInventory.data) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(toolInventory.error, "Failed to load tool inventory")
+ )
+ );
+ }
+ }
+
+ if (shelves.error) {
+ throw redirect(
+ path.to.items,
+ await flash(request, error(shelves.error, "Failed to load shelves"))
+ );
+ }
+
+ const quantities = await getItemQuantities(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (quantities.error || !quantities.data) {
+ throw redirect(
+ path.to.items,
+ await flash(request, error(quantities, "Failed to load tool quantities"))
+ );
+ }
+
+ return json({
+ toolInventory: toolInventory.data,
+ quantities: quantities.data,
+ shelves: shelves.data.map((s) => s.id),
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ // validate with toolsValidator
+ const validation = await validator(itemInventoryValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { ...update } = validation.data;
+
+ const updateItemInventory = await upsertItemInventory(client, {
+ ...update,
+ itemId,
+ customFields: setCustomFields(formData),
+ updatedBy: userId,
+ });
+ if (updateItemInventory.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(updateItemInventory.error, "Failed to update tool inventory")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.toolInventoryLocation(itemId, update.locationId),
+ await flash(request, success("Updated tool inventory"))
+ );
+}
+
+export default function ToolInventoryRoute() {
+ const sharedToolsData = useRouteData<{ locations: ListItem[] }>(
+ path.to.toolRoot
+ );
+ const { toolInventory, quantities, shelves } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ ...toolInventory,
+ defaultShelfId: toolInventory.defaultShelfId ?? undefined,
+ ...getCustomFields(toolInventory.customFields ?? {}),
+ };
+ return (
+ <ItemInventoryForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ quantities={quantities}
+ locations={sharedToolsData?.locations ?? []}
+ shelves={shelves}
+ type="Tool"
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.planning.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.planning.tsx
new file mode 100644
index 0000000000..3ea263133e
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.planning.tsx
@@ -0,0 +1,163 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import {
+ ItemPlanningForm,
+ getItemPlanning,
+ itemPlanningValidator,
+ upsertItemPlanning,
+} from "~/modules/items";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { ListItem } from "~/types";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ let toolPlanning = await getItemPlanning(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+
+ if (toolPlanning.error || !toolPlanning.data) {
+ const insertToolPlanning = await upsertItemPlanning(client, {
+ itemId,
+ companyId,
+ locationId,
+ createdBy: userId,
+ });
+
+ if (insertToolPlanning.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(insertToolPlanning.error, "Failed to insert tool planning")
+ )
+ );
+ }
+
+ toolPlanning = await getItemPlanning(client, itemId, companyId, locationId);
+ if (toolPlanning.error || !toolPlanning.data) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(toolPlanning.error, "Failed to load tool planning")
+ )
+ );
+ }
+ }
+
+ return json({
+ toolPlanning: toolPlanning.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(itemPlanningValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateToolPlanning = await upsertItemPlanning(client, {
+ ...validation.data,
+ itemId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (updateToolPlanning.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(updateToolPlanning.error, "Failed to update tool planning")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.toolPlanningLocation(itemId, validation.data.locationId),
+ await flash(request, success("Updated tool planning"))
+ );
+}
+
+export default function ToolPlanningRoute() {
+ const sharedToolsData = useRouteData<{
+ locations: ListItem[];
+ }>(path.to.toolRoot);
+
+ const { toolPlanning } = useLoaderData<typeof loader>();
+
+ if (!sharedToolsData) throw new Error("Could not load shared tools data");
+
+ return (
+ <ItemPlanningForm
+ key={toolPlanning.itemId}
+ initialValues={{
+ ...toolPlanning,
+ ...getCustomFields(toolPlanning.customFields),
+ }}
+ locations={sharedToolsData.locations ?? []}
+ type="Tool"
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.purchasing.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.purchasing.tsx
new file mode 100644
index 0000000000..9148c752d1
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.purchasing.tsx
@@ -0,0 +1,100 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import {
+ ItemPurchasingForm,
+ getItemReplenishment,
+ itemPurchasingValidator,
+ upsertItemPurchasing,
+} from "~/modules/items";
+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, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const toolPurchasing = await getItemReplenishment(client, itemId, companyId);
+
+ if (toolPurchasing.error) {
+ throw redirect(
+ path.to.items,
+ await flash(
+ request,
+ error(toolPurchasing.error, "Failed to load tool purchasing")
+ )
+ );
+ }
+
+ return json({
+ toolPurchasing: toolPurchasing.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ // validate with toolsValidator
+ const validation = await validator(itemPurchasingValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateToolPurchasing = await upsertItemPurchasing(client, {
+ ...validation.data,
+ itemId,
+ updatedBy: userId,
+ });
+ if (updateToolPurchasing.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(updateToolPurchasing.error, "Failed to update tool purchasing")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.toolPurchasing(itemId),
+ await flash(request, success("Updated tool purchasing"))
+ );
+}
+
+export default function ToolPurchasingRoute() {
+ const { toolPurchasing } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ ...toolPurchasing,
+ preferredSupplierId: toolPurchasing?.preferredSupplierId ?? undefined,
+ purchasingLeadTime: toolPurchasing?.purchasingLeadTime ?? "",
+ purchasingBlocked: toolPurchasing?.purchasingBlocked ?? false,
+ purchasingUnitOfMeasureCode:
+ toolPurchasing?.purchasingUnitOfMeasureCode ?? "",
+ conversionFactor: toolPurchasing?.conversionFactor ?? 1,
+ };
+
+ return (
+ <ItemPurchasingForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.suppliers.new.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.suppliers.new.tsx
new file mode 100644
index 0000000000..2a3f9f7584
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.suppliers.new.tsx
@@ -0,0 +1,71 @@
+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 {
+ ItemSupplierForm,
+ itemSupplierValidator,
+ upsertItemSupplier,
+} from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+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, userId } = 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(itemSupplierValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createToolSupplier = await upsertItemSupplier(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createToolSupplier.error) {
+ throw redirect(
+ path.to.toolSuppliers(itemId),
+ await flash(
+ request,
+ error(createToolSupplier.error, "Failed to create tool supplier")
+ )
+ );
+ }
+
+ throw redirect(path.to.toolSuppliers(itemId));
+}
+
+export default function NewToolSupplierRoute() {
+ const { itemId } = useParams();
+
+ if (!itemId) throw new Error("itemId not found");
+
+ const initialValues = {
+ itemId: itemId,
+ supplierId: "",
+ supplierToolId: "",
+ unitPrice: 0,
+ supplierUnitOfMeasureCode: "EA",
+ minimumOrderQuantity: 1,
+ conversionFactor: 1,
+ };
+
+ return <ItemSupplierForm type="Tool" initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.suppliers.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.suppliers.tsx
new file mode 100644
index 0000000000..145dbc0b18
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.suppliers.tsx
@@ -0,0 +1,41 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { ItemSuppliers, getItemSuppliers } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const [suppliers] = await Promise.all([
+ getItemSuppliers(client, itemId, companyId),
+ ]);
+
+ if (suppliers.error) {
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(suppliers.error, "Failed to load tool suppliers")
+ )
+ );
+ }
+
+ return json({
+ suppliers: suppliers.data ?? [],
+ });
+}
+
+export default function ToolSuppliersRoute() {
+ const { suppliers } = useLoaderData<typeof loader>();
+
+ return <ItemSuppliers suppliers={suppliers} />;
+}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.tsx
new file mode 100644
index 0000000000..29865d75a0
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.tsx
@@ -0,0 +1,45 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { ToolHeader, ToolNavigation, getTool } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const [toolSummary] = await Promise.all([getTool(client, itemId, companyId)]);
+
+ if (toolSummary.error) {
+ throw redirect(
+ path.to.items,
+ await flash(
+ request,
+ error(toolSummary.error, "Failed to load tool summary")
+ )
+ );
+ }
+
+ return json({
+ toolSummary: toolSummary.data,
+ });
+}
+
+export default function ToolRoute() {
+ return (
+ <>
+ <ToolHeader />
+ <div className="grid grid-cols-1 md:grid-cols-[1fr_4fr] h-full w-full gap-4">
+ <ToolNavigation />
+ <Outlet />
+ </div>
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/tool+/_layout.tsx b/apps/carbon/app/routes/x+/tool+/_layout.tsx
new file mode 100644
index 0000000000..1a4d0aba1f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/_layout.tsx
@@ -0,0 +1,42 @@
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { getUnitOfMeasuresList } from "~/modules/items";
+import { getLocationsList } from "~/modules/resources";
+import { requirePermissions } from "~/services/auth/auth.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Part" }];
+};
+
+export const handle: Handle = {
+ breadcrumb: "Items",
+ to: path.to.items,
+ module: "parts",
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const [unitOfMeasures, locations] = await Promise.all([
+ getUnitOfMeasuresList(client, companyId),
+ getLocationsList(client, companyId),
+ ]);
+
+ return {
+ locations: locations?.data ?? [],
+ unitOfMeasures: unitOfMeasures?.data ?? [],
+ };
+}
+
+export default function PartRoute() {
+ return (
+ <VStack spacing={4} className="h-full p-4">
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/tool+/new.tsx b/apps/carbon/app/routes/x+/tool+/new.tsx
new file mode 100644
index 0000000000..496f8da2f2
--- /dev/null
+++ b/apps/carbon/app/routes/x+/tool+/new.tsx
@@ -0,0 +1,70 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { ToolForm, toolValidator, upsertTool } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "parts",
+ });
+
+ const formData = await request.formData();
+ const modal = formData.get("type") === "modal";
+
+ const validation = await validator(toolValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const createTool = await upsertTool(client, {
+ ...validation.data,
+ active: true,
+ companyId,
+ customFields: setCustomFields(formData),
+ createdBy: userId,
+ });
+ if (createTool.error) {
+ return modal
+ ? json(
+ createTool,
+ await flash(request, error(createTool.error, "Failed to insert tool"))
+ )
+ : redirect(
+ path.to.tools,
+ await flash(request, error(createTool.error, "Failed to insert tool"))
+ );
+ }
+
+ const itemId = createTool.data?.itemId;
+ if (!itemId) throw new Error("Tool ID not found");
+
+ return modal
+ ? json(createTool, { status: 201 })
+ : redirect(path.to.tool(itemId));
+}
+
+export default function ToolsNewRoute() {
+ const initialValues = {
+ id: "",
+ name: "",
+ description: "",
+ itemInventoryType: "Inventory" as "Inventory",
+ unitOfMeasureCode: "EA",
+ blocked: false,
+ active: false,
+ };
+
+ return (
+ <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto">
+ <ToolForm initialValues={initialValues} />
+ </div>
+ );
+}
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index 99a16e9cee..25be21e799 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -139,10 +139,7 @@ export async function requirePermissions(
path.to.authenticatedRoot,
await flash(
request,
- error(
- { myClaims: JSON.stringify(myClaims, null, 2), requiredPermissions },
- "Access Denied"
- )
+ error({ myClaims: myClaims, requiredPermissions }, "Access Denied")
)
);
}
diff --git a/apps/carbon/app/services/session.server.ts b/apps/carbon/app/services/session.server.ts
index 361dbab925..6241b71eab 100644
--- a/apps/carbon/app/services/session.server.ts
+++ b/apps/carbon/app/services/session.server.ts
@@ -10,6 +10,8 @@ import {
SESSION_SECRET,
} from "~/config/env";
+import { redis } from "@carbon/redis";
+import { getPermissionCacheKey } from "~/modules/users/users.server";
import type { Result } from "~/types";
import { path } from "~/utils/path";
import { refreshAccessToken, verifyAuthSession } from "./auth/auth.server";
@@ -188,6 +190,7 @@ export async function updateCompanySession(
// allow user session to be null.
// useful you want to clear session and display a message explaining why
if (authSession !== undefined) {
+ await redis.del(getPermissionCacheKey(authSession?.userId!));
session.set(SESSION_KEY, {
...authSession,
companyId,
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index e6b6227e35..2e45b41d7e 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -107,6 +107,10 @@ export const path = {
generatePath(`${x}/resources/contractors/${id}`),
contractors: `${x}/resources/contractors`,
consumables: `${x}/items/consumables`,
+ consumableInventory: (id: string) =>
+ generatePath(`${x}/consumable/${id}/inventory`),
+ consumablePlanning: (id: string) =>
+ generatePath(`${x}/consumable/${id}/planning`),
convertQuoteToOrder: (id: string) =>
generatePath(`${x}/quote/${id}/convert-to-order`),
currency: (id: string) => generatePath(`${x}/accounting/currencies/${id}`),
@@ -266,6 +270,10 @@ export const path = {
generatePath(`${x}/resources/equipment/unit/${id}`),
fiscalYears: `${x}/accounting/years`,
fixtures: `${x}/items/fixtures`,
+ fixtureInventory: (id: string) =>
+ generatePath(`${x}/fixture/${id}/inventory`),
+ fixturePlanning: (id: string) =>
+ generatePath(`${x}/fixture/${id}/planning`),
forgotPassword: "/forgot-password",
group: (id: string) => generatePath(`${x}/users/groups/${id}`),
groups: `${x}/users/groups`,
@@ -287,6 +295,10 @@ export const path = {
materials: `${x}/items/materials`,
materialForm: (id: string) => generatePath(`${x}/items/forms/${id}`),
materialForms: `${x}/items/forms`,
+ materialInventory: (id: string) =>
+ generatePath(`${x}/material/${id}/inventory`),
+ materialPlanning: (id: string) =>
+ generatePath(`${x}/material/${id}/planning`),
materialSubstance: (id: string) =>
generatePath(`${x}/items/substances/${id}`),
materialSubstances: `${x}/items/substances`,
@@ -380,6 +392,8 @@ export const path = {
newSupplierStatus: `${x}/purchasing/supplier-statuses/new`,
newSupplierType: `${x}/purchasing/supplier-types/new`,
newTool: `${x}/tool/new`,
+ newToolSupplier: (id: string) =>
+ generatePath(`${x}/tool/${id}/suppliers/new`),
newUom: `${x}/items/uom/new`,
newWorkCell: `${x}/resources/work-cells/cell/new`,
newWorkCellUnit: (id: string) =>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index b5c1b2e690..ef3a203849 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -5838,6 +5838,7 @@ export type Database = {
name: string
readableId: string
type: Database["public"]["Enums"]["itemType"]
+ unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
}
@@ -5855,6 +5856,7 @@ export type Database = {
name: string
readableId: string
type: Database["public"]["Enums"]["itemType"]
+ unitOfMeasureCode?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
@@ -5872,6 +5874,7 @@ export type Database = {
name?: string
readableId?: string
type?: Database["public"]["Enums"]["itemType"]
+ unitOfMeasureCode?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
@@ -5981,6 +5984,13 @@ export type Database = {
referencedRelation: "itemGroup"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "item_unitOfMeasureCode_fkey"
+ columns: ["unitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
{
foreignKeyName: "item_updatedBy_fkey"
columns: ["updatedBy"]
@@ -8370,7 +8380,6 @@ export type Database = {
itemId: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
toDate: string | null
- unitOfMeasureCode: string
updatedAt: string | null
updatedBy: string | null
}
@@ -8386,7 +8395,6 @@ export type Database = {
itemId: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
toDate?: string | null
- unitOfMeasureCode: string
updatedAt?: string | null
updatedBy?: string | null
}
@@ -8402,7 +8410,6 @@ export type Database = {
itemId?: string
replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]
toDate?: string | null
- unitOfMeasureCode?: string
updatedAt?: string | null
updatedBy?: string | null
}
@@ -8519,13 +8526,6 @@ export type Database = {
referencedRelation: "itemQuantities"
referencedColumns: ["itemId"]
},
- {
- foreignKeyName: "part_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
{
foreignKeyName: "part_updatedBy_fkey"
columns: ["updatedBy"]
@@ -17754,7 +17754,6 @@ export type Database = {
customFields: Json | null
id: string
itemId: string | null
- unitOfMeasureCode: string
updatedAt: string | null
updatedBy: string | null
}
@@ -17767,7 +17766,6 @@ export type Database = {
customFields?: Json | null
id: string
itemId?: string | null
- unitOfMeasureCode: string
updatedAt?: string | null
updatedBy?: string | null
}
@@ -17780,7 +17778,6 @@ export type Database = {
customFields?: Json | null
id?: string
itemId?: string | null
- unitOfMeasureCode?: string
updatedAt?: string | null
updatedBy?: string | null
}
@@ -17897,13 +17894,6 @@ export type Database = {
referencedRelation: "itemQuantities"
referencedColumns: ["itemId"]
},
- {
- foreignKeyName: "tool_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
{
foreignKeyName: "tool_updatedBy_fkey"
columns: ["updatedBy"]
@@ -21474,13 +21464,6 @@ export type Database = {
referencedRelation: "itemQuantities"
referencedColumns: ["itemId"]
},
- {
- foreignKeyName: "part_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
{
foreignKeyName: "part_updatedBy_fkey"
columns: ["updatedBy"]
@@ -24390,13 +24373,6 @@ export type Database = {
referencedRelation: "itemQuantities"
referencedColumns: ["itemId"]
},
- {
- foreignKeyName: "tool_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
{
foreignKeyName: "tool_updatedBy_fkey"
columns: ["updatedBy"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index b5c1b2e690..ef3a203849 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -5838,6 +5838,7 @@ export type Database = {
name: string
readableId: string
type: Database["public"]["Enums"]["itemType"]
+ unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
}
@@ -5855,6 +5856,7 @@ export type Database = {
name: string
readableId: string
type: Database["public"]["Enums"]["itemType"]
+ unitOfMeasureCode?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
@@ -5872,6 +5874,7 @@ export type Database = {
name?: string
readableId?: string
type?: Database["public"]["Enums"]["itemType"]
+ unitOfMeasureCode?: string | null
updatedAt?: string | null
updatedBy?: string | null
}
@@ -5981,6 +5984,13 @@ export type Database = {
referencedRelation: "itemGroup"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "item_unitOfMeasureCode_fkey"
+ columns: ["unitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
{
foreignKeyName: "item_updatedBy_fkey"
columns: ["updatedBy"]
@@ -8370,7 +8380,6 @@ export type Database = {
itemId: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
toDate: string | null
- unitOfMeasureCode: string
updatedAt: string | null
updatedBy: string | null
}
@@ -8386,7 +8395,6 @@ export type Database = {
itemId: string
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
toDate?: string | null
- unitOfMeasureCode: string
updatedAt?: string | null
updatedBy?: string | null
}
@@ -8402,7 +8410,6 @@ export type Database = {
itemId?: string
replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]
toDate?: string | null
- unitOfMeasureCode?: string
updatedAt?: string | null
updatedBy?: string | null
}
@@ -8519,13 +8526,6 @@ export type Database = {
referencedRelation: "itemQuantities"
referencedColumns: ["itemId"]
},
- {
- foreignKeyName: "part_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
{
foreignKeyName: "part_updatedBy_fkey"
columns: ["updatedBy"]
@@ -17754,7 +17754,6 @@ export type Database = {
customFields: Json | null
id: string
itemId: string | null
- unitOfMeasureCode: string
updatedAt: string | null
updatedBy: string | null
}
@@ -17767,7 +17766,6 @@ export type Database = {
customFields?: Json | null
id: string
itemId?: string | null
- unitOfMeasureCode: string
updatedAt?: string | null
updatedBy?: string | null
}
@@ -17780,7 +17778,6 @@ export type Database = {
customFields?: Json | null
id?: string
itemId?: string | null
- unitOfMeasureCode?: string
updatedAt?: string | null
updatedBy?: string | null
}
@@ -17897,13 +17894,6 @@ export type Database = {
referencedRelation: "itemQuantities"
referencedColumns: ["itemId"]
},
- {
- foreignKeyName: "tool_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
{
foreignKeyName: "tool_updatedBy_fkey"
columns: ["updatedBy"]
@@ -21474,13 +21464,6 @@ export type Database = {
referencedRelation: "itemQuantities"
referencedColumns: ["itemId"]
},
- {
- foreignKeyName: "part_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
{
foreignKeyName: "part_updatedBy_fkey"
columns: ["updatedBy"]
@@ -24390,13 +24373,6 @@ export type Database = {
referencedRelation: "itemQuantities"
referencedColumns: ["itemId"]
},
- {
- foreignKeyName: "tool_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
{
foreignKeyName: "tool_updatedBy_fkey"
columns: ["updatedBy"]
diff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sql
index ca4d297948..c328d61c18 100644
--- a/packages/database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/database/supabase/migrations/20230330024716_parts.sql
@@ -1,3 +1,59 @@
+CREATE TABLE "unitOfMeasure" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "code" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+
+ CONSTRAINT "unitOfMeasure_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "unitOfMeasure_code_unique" UNIQUE ("code", "companyId"),
+ CONSTRAINT "unitOfMeasure_name_unique" UNIQUE ("name", "companyId"),
+ CONSTRAINT "unitOfMeasure_code_check" CHECK (char_length("code") <= 6),
+ CONSTRAINT "unitOfMeasure_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "unitOfMeasure_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "unitOfMeasure_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
+);
+
+CREATE INDEX "unitOfMeasure_code_idx" ON "unitOfMeasure"("code");
+CREATE INDEX "unitOfMeasure_name_idx" ON "unitOfMeasure"("name");
+CREATE INDEX "unitOfMeasure_companyId_idx" ON "unitOfMeasure"("companyId");
+
+ALTER TABLE "unitOfMeasure" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Authenticated users can view units of measure" ON "unitOfMeasure"
+ FOR SELECT
+ USING (
+ auth.role() = 'authenticated'
+ );
+
+
+CREATE POLICY "Employees with parts_create can insert units of measure" ON "unitOfMeasure"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee') AND
+ has_company_permission('parts_create', "companyId")
+);
+
+CREATE POLICY "Employees with parts_update can update units of measure" ON "unitOfMeasure"
+ FOR UPDATE
+ USING (
+ has_role('employee') AND
+ has_company_permission('parts_update', "companyId")
+ );
+
+CREATE POLICY "Employees with parts_delete can delete units of measure" ON "unitOfMeasure"
+ FOR DELETE
+ USING (
+ has_role('employee') AND
+ has_company_permission('parts_delete', "companyId")
+ );
+
+
CREATE TABLE "itemGroup" (
"id" TEXT NOT NULL DEFAULT xid(),
"name" TEXT NOT NULL,
@@ -73,6 +129,7 @@ CREATE TABLE "item" (
"description" TEXT,
"itemGroupId" TEXT,
"itemInventoryType" "itemInventoryType" NOT NULL,
+ "unitOfMeasureCode" TEXT,
"active" BOOLEAN NOT NULL DEFAULT true,
"blocked" BOOLEAN NOT NULL DEFAULT false,
"companyId" TEXT NOT NULL,
@@ -84,6 +141,7 @@ CREATE TABLE "item" (
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_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "item_itemGroupId_fkey" FOREIGN KEY ("itemGroupId") REFERENCES "itemGroup"("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "item_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "item_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
@@ -154,67 +212,11 @@ CREATE TYPE "itemReorderingPolicy" AS ENUM (
'Maximum Quantity'
);
-CREATE TABLE "unitOfMeasure" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "code" TEXT NOT NULL,
- "name" TEXT NOT NULL,
- "active" BOOLEAN NOT NULL DEFAULT true,
- "companyId" TEXT NOT NULL,
- "createdBy" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- "updatedBy" TEXT,
- "updatedAt" TIMESTAMP WITH TIME ZONE,
- "customFields" JSONB,
-
- CONSTRAINT "unitOfMeasure_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "unitOfMeasure_code_unique" UNIQUE ("code", "companyId"),
- CONSTRAINT "unitOfMeasure_name_unique" UNIQUE ("name", "companyId"),
- CONSTRAINT "unitOfMeasure_code_check" CHECK (char_length("code") <= 6),
- CONSTRAINT "unitOfMeasure_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "unitOfMeasure_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
- CONSTRAINT "unitOfMeasure_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
-);
-
-CREATE INDEX "unitOfMeasure_code_idx" ON "unitOfMeasure"("code");
-CREATE INDEX "unitOfMeasure_name_idx" ON "unitOfMeasure"("name");
-CREATE INDEX "unitOfMeasure_companyId_idx" ON "unitOfMeasure"("companyId");
-
-ALTER TABLE "unitOfMeasure" ENABLE ROW LEVEL SECURITY;
-
-CREATE POLICY "Authenticated users can view units of measure" ON "unitOfMeasure"
- FOR SELECT
- USING (
- auth.role() = 'authenticated'
- );
-
-
-CREATE POLICY "Employees with parts_create can insert units of measure" ON "unitOfMeasure"
- FOR INSERT
- WITH CHECK (
- has_role('employee') AND
- has_company_permission('parts_create', "companyId")
-);
-
-CREATE POLICY "Employees with parts_update can update units of measure" ON "unitOfMeasure"
- FOR UPDATE
- USING (
- has_role('employee') AND
- has_company_permission('parts_update', "companyId")
- );
-
-CREATE POLICY "Employees with parts_delete can delete units of measure" ON "unitOfMeasure"
- FOR DELETE
- USING (
- has_role('employee') AND
- has_company_permission('parts_delete', "companyId")
- );
-
CREATE TABLE "part" (
"id" TEXT NOT NULL,
"itemId" TEXT NOT NULL,
"replenishmentSystem" "itemReplenishmentSystem" NOT NULL,
- "unitOfMeasureCode" TEXT NOT NULL,
"approved" BOOLEAN NOT NULL DEFAULT false,
"approvedBy" TEXT,
"fromDate" DATE,
@@ -229,7 +231,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_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,
@@ -287,27 +288,27 @@ 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()
+CREATE FUNCTION public.create_item_related_records()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public."itemCost"("itemId", "costingMethod", "createdBy", "companyId")
- VALUES (new."itemId", 'FIFO', new."createdBy", new."companyId");
+ VALUES (new.id, 'FIFO', new."createdBy", new."companyId");
INSERT INTO public."itemReplenishment"("itemId", "createdBy", "companyId")
- VALUES (new."itemId", new."createdBy", new."companyId");
+ VALUES (new.id, new."createdBy", new."companyId");
INSERT INTO public."itemUnitSalePrice"("itemId", "currencyCode", "createdBy", "companyId")
-- TODO: get default currency
- VALUES (new."itemId", 'USD', new."createdBy", new."companyId");
+ VALUES (new.id, 'USD', new."createdBy", new."companyId");
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-CREATE TRIGGER create_part_related_records
- AFTER INSERT on public.part
- FOR EACH ROW EXECUTE PROCEDURE public.create_part_related_records();
+CREATE TRIGGER create_item_related_records
+ AFTER INSERT on public.item
+ FOR EACH ROW EXECUTE PROCEDURE public.create_item_related_records();
CREATE OR REPLACE FUNCTION public.update_item_search_result()
RETURNS TRIGGER AS $$
diff --git a/packages/database/supabase/migrations/20230704161623_parts-view.sql b/packages/database/supabase/migrations/20230704161623_parts-view.sql
index 6a0f1274b4..0a09fe976e 100644
--- a/packages/database/supabase/migrations/20230704161623_parts-view.sql
+++ b/packages/database/supabase/migrations/20230704161623_parts-view.sql
@@ -6,6 +6,7 @@ CREATE OR REPLACE VIEW "parts" AS
i.description,
i."itemGroupId",
i."itemInventoryType",
+ i."unitOfMeasureCode",
pg.name AS "itemGroup",
uom.name as "unitOfMeasure",
p."replenishmentSystem",
@@ -18,12 +19,13 @@ CREATE OR REPLACE VIEW "parts" AS
INNER JOIN "item" i ON i.id = p."itemId"
LEFT JOIN "itemGroup" pg ON pg.id = i."itemGroupId"
LEFT JOIN "itemSupplier" s ON s."itemId" = p."itemId"
- LEFT JOIN "unitOfMeasure" uom ON uom.code = p."unitOfMeasureCode" AND uom."companyId" = p."companyId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
GROUP BY p.id,
i.name,
i.description,
i."itemGroupId",
i."itemInventoryType",
+ i."unitOfMeasureCode",
pg.name,
p."replenishmentSystem",
i.active,
diff --git a/packages/database/supabase/migrations/20240324175747_assignee.sql b/packages/database/supabase/migrations/20240324175747_assignee.sql
index 4b77b9284e..62b165256f 100644
--- a/packages/database/supabase/migrations/20240324175747_assignee.sql
+++ b/packages/database/supabase/migrations/20240324175747_assignee.sql
@@ -31,7 +31,7 @@ CREATE OR REPLACE VIEW "parts" WITH(SECURITY_INVOKER=true) AS
FROM "itemSupplier" ps
GROUP BY "itemId"
) ps ON ps."itemId" = p."itemId"
- LEFT JOIN "unitOfMeasure" uom ON uom.code = p."unitOfMeasureCode" AND uom."companyId" = p."companyId";
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId";
DROP VIEW "purchaseOrders";
CREATE OR REPLACE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS
diff --git a/packages/database/supabase/migrations/20240601210618_assignee-to-item.sql b/packages/database/supabase/migrations/20240601210618_assignee-to-item.sql
index 4ff5764842..96ed4f454f 100644
--- a/packages/database/supabase/migrations/20240601210618_assignee-to-item.sql
+++ b/packages/database/supabase/migrations/20240601210618_assignee-to-item.sql
@@ -15,6 +15,7 @@ CREATE OR REPLACE VIEW "parts" WITH(SECURITY_INVOKER=true) AS
i.description,
i."itemGroupId",
i."itemInventoryType",
+ i."unitOfMeasureCode",
i.active,
i.blocked,
i.assignee,
@@ -32,7 +33,7 @@ CREATE OR REPLACE VIEW "parts" WITH(SECURITY_INVOKER=true) AS
FROM "itemSupplier" ps
GROUP BY "itemId"
) ps ON ps."itemId" = p."itemId"
- LEFT JOIN "unitOfMeasure" uom ON uom.code = p."unitOfMeasureCode" AND uom."companyId" = p."companyId";
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId";
CREATE OR REPLACE VIEW "services" WITH(SECURITY_INVOKER=true) AS
diff --git a/packages/database/supabase/migrations/20240608103855_tools.sql b/packages/database/supabase/migrations/20240608103855_tools.sql
index c0636966f9..ae308deee7 100644
--- a/packages/database/supabase/migrations/20240608103855_tools.sql
+++ b/packages/database/supabase/migrations/20240608103855_tools.sql
@@ -5,7 +5,6 @@ UPDATE "customFieldTable" SET "module" = 'Items' WHERE "module" = 'Parts';
CREATE TABLE "tool" (
"id" TEXT NOT NULL,
"itemId" TEXT,
- "unitOfMeasureCode" TEXT NOT NULL,
"approved" BOOLEAN NOT NULL DEFAULT false,
"approvedBy" TEXT,
"customFields" JSONB,
@@ -17,7 +16,6 @@ CREATE TABLE "tool" (
CONSTRAINT "tool_pkey" PRIMARY KEY ("id", "companyId"),
CONSTRAINT "tool_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "tool_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "tool_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id"),
CONSTRAINT "tool_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id"),
CONSTRAINT "tool_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
@@ -69,6 +67,7 @@ CREATE OR REPLACE VIEW "tools" WITH(SECURITY_INVOKER=true) AS
i.active,
i.blocked,
i.assignee,
+ i."unitOfMeasureCode",
t.*,
ig.name AS "itemGroup",
s."supplierIds",
@@ -83,4 +82,4 @@ CREATE OR REPLACE VIEW "tools" WITH(SECURITY_INVOKER=true) AS
FROM "itemSupplier" s
GROUP BY "itemId"
) s ON s."itemId" = t."itemId"
- LEFT JOIN "unitOfMeasure" uom ON uom.code = t."unitOfMeasureCode" AND uom."companyId" = t."companyId";
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId";