Skip to content

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

feat: add routes for consumables

Brad Barbina310c9edefe6
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index af288d5d73..472c5af3f4 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -6,6 +6,7 @@ import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
+ consumableValidator,
itemCostValidator,
itemGroupValidator,
itemInventoryValidator,
@@ -638,6 +639,86 @@ export async function insertShelf(
.single();
}
+export async function upsertConsumable(
+ client: SupabaseClient<Database>,
+ consumable:
+ | (z.infer<typeof consumableValidator> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (z.infer<typeof consumableValidator> & {
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in consumable) {
+ const itemInsert = await client
+ .from("item")
+ .insert({
+ readableId: consumable.id,
+ name: consumable.name,
+ type: "Consumable",
+ itemGroupId: consumable.itemGroupId,
+ itemInventoryType: consumable.itemInventoryType,
+ unitOfMeasureCode: consumable.unitOfMeasureCode,
+ companyId: consumable.companyId,
+ createdBy: consumable.createdBy,
+ })
+ .select("id")
+ .single();
+ if (itemInsert.error) return itemInsert;
+ const itemId = itemInsert.data?.id;
+
+ return client
+ .from("consumable")
+ .insert({
+ id: consumable.id,
+ itemId: itemId,
+ companyId: consumable.companyId,
+ createdBy: consumable.createdBy,
+ customFields: consumable.customFields,
+ })
+ .select("*")
+ .single();
+ }
+
+ const itemUpdate = {
+ id: consumable.id,
+ name: consumable.name,
+ description: consumable.description,
+ itemGroupId: consumable.itemGroupId,
+ itemInventoryType: consumable.itemInventoryType,
+ unitOfMeasureCode: consumable.unitOfMeasureCode,
+ active: consumable.active,
+ blocked: consumable.blocked,
+ };
+
+ const consumableUpdate = {
+ customFields: consumable.customFields,
+ };
+
+ const [updateItem, updatePart] = await Promise.all([
+ client
+ .from("item")
+ .update({
+ ...sanitize(itemUpdate),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", consumable.id),
+ client
+ .from("consumable")
+ .update({
+ ...sanitize(consumableUpdate),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("itemId", consumable.id),
+ ]);
+
+ if (updateItem.error) return updateItem;
+ return updatePart;
+}
+
export async function upsertPart(
client: SupabaseClient<Database>,
part:
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemSupplierForm.tsx b/apps/carbon/app/modules/items/ui/Item/ItemSupplierForm.tsx
index d748f9ecc0..59cbe338e1 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" | "Tool";
+ type: "Part" | "Service" | "Tool" | "Consumable" | "Material";
};
const ItemSupplierForm = ({ initialValues, type }: ItemSupplierFormProps) => {
@@ -124,7 +124,7 @@ export default ItemSupplierForm;
function getAction(
isEditing: boolean,
- type: "Part" | "Service" | "Tool",
+ type: "Part" | "Service" | "Tool" | "Consumable" | "Material",
itemId: string,
id?: string
) {
@@ -150,5 +150,21 @@ function getAction(
return path.to.newToolSupplier(itemId);
}
}
+
+ if (type === "Consumable") {
+ if (isEditing) {
+ return path.to.consumableSupplier(itemId, id!);
+ } else {
+ return path.to.newConsumableSupplier(itemId);
+ }
+ }
+
+ if (type === "Material") {
+ if (isEditing) {
+ return path.to.materialSupplier(itemId, id!);
+ } else {
+ return path.to.newMaterialSupplier(itemId);
+ }
+ }
throw new Error("Invalid type");
}
diff --git a/apps/carbon/app/modules/items/ui/index.ts b/apps/carbon/app/modules/items/ui/index.ts
index 1dc10cb37b..107a67f5f7 100644
--- a/apps/carbon/app/modules/items/ui/index.ts
+++ b/apps/carbon/app/modules/items/ui/index.ts
@@ -1,5 +1,6 @@
import useItemsSubmodules from "./useItemsSubmodules";
+export * from "./Consumables";
export * from "./Item";
export * from "./ItemGroups";
export * from "./MaterialForms";
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId._index.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId._index.tsx
new file mode 100644
index 0000000000..71c64f381c
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$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.consumableDetails(itemId));
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.costing.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.costing.tsx
new file mode 100644
index 0000000000..2910093c49
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$itemId.costing.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 { 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 consumable 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.consumable(itemId),
+ await flash(
+ request,
+ error(updateItemCost.error, "Failed to update consumable costing")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.consumableCosting(itemId),
+ await flash(request, success("Updated consumable costing"))
+ );
+}
+
+export default function ConsumableCostingRoute() {
+ const { itemCost } = useLoaderData<typeof loader>();
+ return (
+ <ItemCostingForm
+ key={itemCost.itemId}
+ initialValues={{ ...itemCost, ...getCustomFields(itemCost.customFields) }}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.details.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.details.tsx
new file mode 100644
index 0000000000..dfa7eb17ec
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$itemId.details.tsx
@@ -0,0 +1,89 @@
+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 { Consumable } from "~/modules/items";
+import {
+ ConsumableForm,
+ consumableValidator,
+ upsertConsumable,
+} 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(consumableValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateConsumable = await upsertConsumable(client, {
+ ...validation.data,
+ id: itemId,
+ customFields: setCustomFields(formData),
+ updatedBy: userId,
+ });
+ if (updateConsumable.error) {
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(
+ request,
+ error(updateConsumable.error, "Failed to update consumable")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(request, success("Updated consumable"))
+ );
+}
+
+export default function ConsumableDetailsRoute() {
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+ const consumableData = useRouteData<{ consumableSummary: Consumable }>(
+ path.to.consumable(itemId)
+ );
+ if (!consumableData) throw new Error("Could not find consumable data");
+
+ const consumableInitialValues = {
+ id: consumableData.consumableSummary?.id ?? "",
+ itemId: consumableData.consumableSummary?.itemId ?? "",
+ name: consumableData.consumableSummary?.name ?? "",
+ description: consumableData.consumableSummary?.description ?? "",
+ itemGroupId: consumableData.consumableSummary?.itemGroupId ?? "",
+ itemInventoryType:
+ consumableData.consumableSummary?.itemInventoryType ?? "Inventory",
+ active: consumableData.consumableSummary?.active ?? true,
+ blocked: consumableData.consumableSummary?.blocked ?? false,
+ unitOfMeasureCode:
+ consumableData.consumableSummary?.unitOfMeasureCode ?? "EA",
+ ...getCustomFields(consumableData.consumableSummary?.customFields ?? {}),
+ };
+
+ return (
+ <VStack spacing={4}>
+ <ConsumableForm
+ key={consumableInitialValues.id}
+ initialValues={consumableInitialValues}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.inventory.tsx
new file mode 100644
index 0000000000..4796224530
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$itemId.inventory.tsx
@@ -0,0 +1,208 @@
+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.consumable(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.consumable(itemId),
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ let [consumableInventory, shelves] = await Promise.all([
+ getItemInventory(client, itemId, companyId, locationId),
+ getShelvesList(client, locationId),
+ ]);
+
+ if (consumableInventory.error || !consumableInventory.data) {
+ const insertItemInventory = await upsertItemInventory(client, {
+ itemId,
+ companyId,
+ locationId,
+ customFields: {},
+ createdBy: userId,
+ });
+
+ if (insertItemInventory.error) {
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(
+ request,
+ error(
+ insertItemInventory.error,
+ "Failed to insert consumable inventory"
+ )
+ )
+ );
+ }
+
+ consumableInventory = await getItemInventory(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (consumableInventory.error || !consumableInventory.data) {
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(
+ request,
+ error(
+ consumableInventory.error,
+ "Failed to load consumable 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 consumable quantities")
+ )
+ );
+ }
+
+ return json({
+ consumableInventory: consumableInventory.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 consumablesValidator
+ 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.consumable(itemId),
+ await flash(
+ request,
+ error(
+ updateItemInventory.error,
+ "Failed to update consumable inventory"
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.consumableInventoryLocation(itemId, update.locationId),
+ await flash(request, success("Updated consumable inventory"))
+ );
+}
+
+export default function ConsumableInventoryRoute() {
+ const sharedConsumablesData = useRouteData<{ locations: ListItem[] }>(
+ path.to.consumableRoot
+ );
+ const { consumableInventory, quantities, shelves } =
+ useLoaderData<typeof loader>();
+
+ const initialValues = {
+ ...consumableInventory,
+ defaultShelfId: consumableInventory.defaultShelfId ?? undefined,
+ ...getCustomFields(consumableInventory.customFields ?? {}),
+ };
+ return (
+ <ItemInventoryForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ quantities={quantities}
+ locations={sharedConsumablesData?.locations ?? []}
+ shelves={shelves}
+ type="Consumable"
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.planning.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.planning.tsx
new file mode 100644
index 0000000000..f20f5c75e9
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$itemId.planning.tsx
@@ -0,0 +1,175 @@
+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.consumable(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.consumable(itemId),
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ let consumablePlanning = await getItemPlanning(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+
+ if (consumablePlanning.error || !consumablePlanning.data) {
+ const insertConsumablePlanning = await upsertItemPlanning(client, {
+ itemId,
+ companyId,
+ locationId,
+ createdBy: userId,
+ });
+
+ if (insertConsumablePlanning.error) {
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(
+ request,
+ error(
+ insertConsumablePlanning.error,
+ "Failed to insert consumable planning"
+ )
+ )
+ );
+ }
+
+ consumablePlanning = await getItemPlanning(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+ if (consumablePlanning.error || !consumablePlanning.data) {
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(
+ request,
+ error(consumablePlanning.error, "Failed to load consumable planning")
+ )
+ );
+ }
+ }
+
+ return json({
+ consumablePlanning: consumablePlanning.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 updateConsumablePlanning = await upsertItemPlanning(client, {
+ ...validation.data,
+ itemId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (updateConsumablePlanning.error) {
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(
+ request,
+ error(
+ updateConsumablePlanning.error,
+ "Failed to update consumable planning"
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.consumablePlanningLocation(itemId, validation.data.locationId),
+ await flash(request, success("Updated consumable planning"))
+ );
+}
+
+export default function ConsumablePlanningRoute() {
+ const sharedConsumablesData = useRouteData<{
+ locations: ListItem[];
+ }>(path.to.consumableRoot);
+
+ const { consumablePlanning } = useLoaderData<typeof loader>();
+
+ if (!sharedConsumablesData)
+ throw new Error("Could not load shared consumables data");
+
+ return (
+ <ItemPlanningForm
+ key={consumablePlanning.itemId}
+ initialValues={{
+ ...consumablePlanning,
+ ...getCustomFields(consumablePlanning.customFields),
+ }}
+ locations={sharedConsumablesData.locations ?? []}
+ type="Consumable"
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.purchasing.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.purchasing.tsx
new file mode 100644
index 0000000000..e5e989e832
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$itemId.purchasing.tsx
@@ -0,0 +1,110 @@
+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 consumablePurchasing = await getItemReplenishment(
+ client,
+ itemId,
+ companyId
+ );
+
+ if (consumablePurchasing.error) {
+ throw redirect(
+ path.to.items,
+ await flash(
+ request,
+ error(
+ consumablePurchasing.error,
+ "Failed to load consumable purchasing"
+ )
+ )
+ );
+ }
+
+ return json({
+ consumablePurchasing: consumablePurchasing.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 consumablesValidator
+ const validation = await validator(itemPurchasingValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateConsumablePurchasing = await upsertItemPurchasing(client, {
+ ...validation.data,
+ itemId,
+ updatedBy: userId,
+ });
+ if (updateConsumablePurchasing.error) {
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(
+ request,
+ error(
+ updateConsumablePurchasing.error,
+ "Failed to update consumable purchasing"
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.consumablePurchasing(itemId),
+ await flash(request, success("Updated consumable purchasing"))
+ );
+}
+
+export default function ConsumablePurchasingRoute() {
+ const { consumablePurchasing } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ ...consumablePurchasing,
+ preferredSupplierId: consumablePurchasing?.preferredSupplierId ?? undefined,
+ purchasingLeadTime: consumablePurchasing?.purchasingLeadTime ?? "",
+ purchasingBlocked: consumablePurchasing?.purchasingBlocked ?? false,
+ purchasingUnitOfMeasureCode:
+ consumablePurchasing?.purchasingUnitOfMeasureCode ?? "",
+ conversionFactor: consumablePurchasing?.conversionFactor ?? 1,
+ };
+
+ return (
+ <ItemPurchasingForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.suppliers.new.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.suppliers.new.tsx
new file mode 100644
index 0000000000..9b670e7b55
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$itemId.suppliers.new.tsx
@@ -0,0 +1,74 @@
+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 createConsumableSupplier = await upsertItemSupplier(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createConsumableSupplier.error) {
+ throw redirect(
+ path.to.consumableSuppliers(itemId),
+ await flash(
+ request,
+ error(
+ createConsumableSupplier.error,
+ "Failed to create consumable supplier"
+ )
+ )
+ );
+ }
+
+ throw redirect(path.to.consumableSuppliers(itemId));
+}
+
+export default function NewConsumableSupplierRoute() {
+ const { itemId } = useParams();
+
+ if (!itemId) throw new Error("itemId not found");
+
+ const initialValues = {
+ itemId: itemId,
+ supplierId: "",
+ supplierConsumableId: "",
+ unitPrice: 0,
+ supplierUnitOfMeasureCode: "EA",
+ minimumOrderQuantity: 1,
+ conversionFactor: 1,
+ };
+
+ return <ItemSupplierForm type="Consumable" initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.suppliers.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.suppliers.tsx
new file mode 100644
index 0000000000..120898e410
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$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.consumable(itemId),
+ await flash(
+ request,
+ error(suppliers.error, "Failed to load consumable suppliers")
+ )
+ );
+ }
+
+ return json({
+ suppliers: suppliers.data ?? [],
+ });
+}
+
+export default function ConsumableSuppliersRoute() {
+ const { suppliers } = useLoaderData<typeof loader>();
+
+ return <ItemSuppliers suppliers={suppliers} />;
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/$itemId.tsx b/apps/carbon/app/routes/x+/consumable+/$itemId.tsx
new file mode 100644
index 0000000000..73060543a0
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/$itemId.tsx
@@ -0,0 +1,51 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import {
+ ConsumableHeader,
+ ConsumableNavigation,
+ getConsumable,
+} 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 [consumableSummary] = await Promise.all([
+ getConsumable(client, itemId, companyId),
+ ]);
+
+ if (consumableSummary.error) {
+ throw redirect(
+ path.to.items,
+ await flash(
+ request,
+ error(consumableSummary.error, "Failed to load consumable summary")
+ )
+ );
+ }
+
+ return json({
+ consumableSummary: consumableSummary.data,
+ });
+}
+
+export default function ConsumableRoute() {
+ return (
+ <>
+ <ConsumableHeader />
+ <div className="grid grid-cols-1 md:grid-cols-[1fr_4fr] h-full w-full gap-4">
+ <ConsumableNavigation />
+ <Outlet />
+ </div>
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/_layout.tsx b/apps/carbon/app/routes/x+/consumable+/_layout.tsx
new file mode 100644
index 0000000000..5947870220
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/_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 | Consumables" }];
+};
+
+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 ConsumableRoute() {
+ return (
+ <VStack spacing={4} className="h-full p-4">
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/consumable+/new.tsx b/apps/carbon/app/routes/x+/consumable+/new.tsx
new file mode 100644
index 0000000000..9432d5090f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/consumable+/new.tsx
@@ -0,0 +1,80 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import {
+ ConsumableForm,
+ consumableValidator,
+ upsertConsumable,
+} 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(consumableValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const createConsumable = await upsertConsumable(client, {
+ ...validation.data,
+ active: true,
+ companyId,
+ customFields: setCustomFields(formData),
+ createdBy: userId,
+ });
+ if (createConsumable.error) {
+ return modal
+ ? json(
+ createConsumable,
+ await flash(
+ request,
+ error(createConsumable.error, "Failed to insert consumable")
+ )
+ )
+ : redirect(
+ path.to.consumables,
+ await flash(
+ request,
+ error(createConsumable.error, "Failed to insert consumable")
+ )
+ );
+ }
+
+ const itemId = createConsumable.data?.itemId;
+ if (!itemId) throw new Error("Consumable ID not found");
+
+ return modal
+ ? json(createConsumable, { status: 201 })
+ : redirect(path.to.consumable(itemId));
+}
+
+export default function ConsumablesNewRoute() {
+ const initialValues = {
+ id: "",
+ name: "",
+ description: "",
+ itemInventoryType: "Non-Inventory" as "Non-Inventory",
+ unitOfMeasureCode: "EA",
+ blocked: false,
+ active: false,
+ };
+
+ return (
+ <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto">
+ <ConsumableForm initialValues={initialValues} />
+ </div>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/consumables.tsx b/apps/carbon/app/routes/x+/items+/consumables.tsx
new file mode 100644
index 0000000000..7af5570fa2
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/consumables.tsx
@@ -0,0 +1,77 @@
+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 {
+ ConsumablesTable,
+ getConsumables,
+ getItemGroupsList,
+} 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: "Consumables",
+ to: path.to.consumables,
+};
+
+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 [consumables, itemGroups] = await Promise.all([
+ getConsumables(client, companyId, {
+ search,
+ supplierId,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
+ getItemGroupsList(client, companyId),
+ ]);
+
+ if (consumables.error) {
+ redirect(
+ path.to.authenticatedRoot,
+ await flash(
+ request,
+ error(consumables.error, "Failed to fetch consumables")
+ )
+ );
+ }
+
+ return json({
+ count: consumables.count ?? 0,
+ consumables: consumables.data ?? [],
+ itemGroups: itemGroups.data ?? [],
+ });
+}
+
+export default function ConsumablesSearchRoute() {
+ const { count, consumables, itemGroups } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <ConsumablesTable
+ data={consumables}
+ count={count}
+ itemGroups={itemGroups}
+ />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/tool+/_layout.tsx b/apps/carbon/app/routes/x+/tool+/_layout.tsx
index 1a4d0aba1f..bcc18b668f 100644
--- a/apps/carbon/app/routes/x+/tool+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/tool+/_layout.tsx
@@ -8,7 +8,7 @@ import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
export const meta: MetaFunction = () => {
- return [{ title: "Carbon | Part" }];
+ return [{ title: "Carbon | Tools" }];
};
export const handle: Handle = {
@@ -33,7 +33,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
};
}
-export default function PartRoute() {
+export default function ToolRoute() {
return (
<VStack spacing={4} className="h-full p-4">
<Outlet />
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index d819aa1da7..867b669244 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -114,10 +114,17 @@ export const path = {
generatePath(`${x}/consumable/${id}/details`),
consumableInventory: (id: string) =>
generatePath(`${x}/consumable/${id}/inventory`),
+ consumableInventoryLocation: (id: string, locationId: string) =>
+ generatePath(`${x}/consumable/${id}/inventory?location=${locationId}`),
consumablePlanning: (id: string) =>
generatePath(`${x}/consumable/${id}/planning`),
+ consumablePlanningLocation: (id: string, locationId: string) =>
+ generatePath(`${x}/consumable/${id}/planning?location=${locationId}`),
consumablePurchasing: (id: string) =>
generatePath(`${x}/consumable/${id}/purchasing`),
+ consumableRoot: `${x}/consumable`,
+ consumableSupplier: (itemId: string, id: string) =>
+ generatePath(`${x}/consumable/${itemId}/suppliers/${id}`),
consumableSuppliers: (id: string) =>
generatePath(`${x}/consumable/${id}/suppliers`),
convertQuoteToOrder: (id: string) =>
@@ -311,6 +318,8 @@ export const path = {
materialSubstance: (id: string) =>
generatePath(`${x}/items/substances/${id}`),
materialSubstances: `${x}/items/substances`,
+ materialSupplier: (itemId: string, id: string) =>
+ generatePath(`${x}/material/${itemId}/suppliers/${id}`),
messaging: `${x}/messaging`,
newAbility: `${x}/resources/abilities/new`,
newAccountingCategory: `${x}/accounting/categories/new`,
@@ -323,6 +332,8 @@ export const path = {
newChartOfAccount: `${x}/accounting/charts/new`,
newCompany: `${x}/settings/company/new`,
newConsumable: `${x}/consumable/new`,
+ newConsumableSupplier: (id: string) =>
+ generatePath(`${x}/consumable/${id}/suppliers/new`),
newContractor: `${x}/resources/contractors/new`,
newCurrency: `${x}/accounting/currencies/new`,
newCustomer: `${x}/customer/new`,
@@ -353,6 +364,8 @@ export const path = {
newItemGroup: `${x}/items/groups/new`,
newMaterialForm: `${x}/items/forms/new`,
newMaterialSubstance: `${x}/items/substances/new`,
+ newMaterialSupplier: (id: string) =>
+ generatePath(`${x}/material/${id}/suppliers/new`),
newPartSupplier: (id: string) =>
generatePath(`${x}/part/${id}/suppliers/new`),
newPartner: `${x}/resources/partners/new`,