Skip to content

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

feat: add and remove invnetory from MES

Brad Barbin02fa1150656a
diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsx
index dc17526d65..b49a3029ff 100644
--- a/apps/erp/app/routes/file+/model+/public.$.tsx
+++ b/apps/erp/app/routes/file+/model+/public.$.tsx
@@ -22,7 +22,7 @@ const supportedFileTypes: Record<string, string> = {
flac: "audio/flac",
};
-export let loader = async ({ params }: LoaderFunctionArgs) => {
+export async function loader({ params }: LoaderFunctionArgs) {
const client = getCarbonServiceRole();
const path = params["*"];
@@ -70,4 +70,4 @@ export let loader = async ({ params }: LoaderFunctionArgs) => {
"Access-Control-Allow-Headers": "Content-Type", // Allow Content-Type header
});
return new Response(fileData, { status: 200, headers });
-};
+}
diff --git a/apps/mes/app/components/AdjustInventory.tsx b/apps/mes/app/components/AdjustInventory.tsx
new file mode 100644
index 0000000000..3ca8eee2f6
--- /dev/null
+++ b/apps/mes/app/components/AdjustInventory.tsx
@@ -0,0 +1,178 @@
+"use client";
+
+import { LuGitBranchPlus, LuGitPullRequestCreateArrow } from "react-icons/lu";
+
+import { useCarbon } from "@carbon/auth";
+import { Combobox, Hidden, Number, Submit, ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Loading,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ SidebarMenuButton,
+ toast,
+ useDisclosure,
+ useMount,
+ VStack,
+} from "@carbon/react";
+import { useRouteData } from "@carbon/remix";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useState } from "react";
+import type { action as endShiftAction } from "~/routes/x+/end-shift";
+import { inventoryAdjustmentValidator } from "~/services/inventory.service";
+import { useItems } from "~/stores";
+import { path } from "~/utils/path";
+
+export function AdjustInventory({ add }: { add: boolean }) {
+ const modal = useDisclosure();
+ const fetcher = useFetcher<typeof endShiftAction>();
+ const [items] = useItems();
+ const [loading, setLoading] = useState(false);
+
+ const [shelves, setShelves] = useState<{ value: string; label: string }[]>(
+ []
+ );
+ const [selectedShelf, setSelectedShelf] = useState<string | null>(null);
+ const { carbon } = useCarbon();
+
+ const routeData = useRouteData<{
+ location: string;
+ }>(path.to.authenticatedRoot);
+
+ const onItemChange = async (
+ value: { value: string; label: string } | null
+ ) => {
+ if (!value || !carbon) return;
+ const pickMethod = await carbon
+ .from("pickMethod")
+ .select("defaultShelfId")
+ .eq("itemId", value.value)
+ .eq("locationId", routeData?.location ?? "")
+ .maybeSingle();
+
+ setSelectedShelf(pickMethod?.data?.defaultShelfId ?? null);
+ };
+
+ async function fetchShelvesByLocationId() {
+ if (!carbon) {
+ toast.error("Failed to fetch shelves");
+ return;
+ }
+ const shelves = await carbon
+ .from("shelf")
+ .select("id, name")
+ .eq("locationId", routeData?.location ?? "");
+
+ setShelves(
+ shelves.data?.map((shelf) => ({
+ value: shelf.id,
+ label: shelf.name,
+ })) ?? []
+ );
+ setLoading(false);
+ }
+
+ useMount(() => {
+ setLoading(true);
+ fetchShelvesByLocationId();
+ });
+
+ useEffect(() => {
+ if (fetcher.data?.success === true) {
+ modal.onClose();
+ toast.success(fetcher.data?.message ?? "Inventory adjustment completed");
+ }
+
+ if (fetcher.data?.success === false) {
+ toast.error(
+ fetcher.data?.message ?? "Failed to complete inventory adjustment"
+ );
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.data?.success]);
+
+ return (
+ <>
+ <SidebarMenuButton onClick={modal.onOpen}>
+ {add ? <LuGitPullRequestCreateArrow /> : <LuGitBranchPlus />}
+ <span>{add ? "Add" : "Remove"} Inventory</span>
+ </SidebarMenuButton>
+ {modal.isOpen && (
+ <Modal
+ open={modal.isOpen}
+ onOpenChange={(open) => !open && modal.onClose()}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ action={path.to.inventoryAdjustment}
+ validator={inventoryAdjustmentValidator}
+ defaultValues={{
+ itemId: "",
+ quantity: 1,
+ entryType: add ? "Positive Adjmt." : "Negative Adjmt.",
+ }}
+ fetcher={fetcher}
+ >
+ <ModalHeader>
+ <ModalTitle>{add ? "Add" : "Remove"} Inventory</ModalTitle>
+ <ModalDescription>
+ Manually {add ? "add" : "remove"} items to inventory
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden
+ name="entryType"
+ value={add ? "Positive Adjmt." : "Negative Adjmt."}
+ />
+ <Hidden name="locationId" value={routeData?.location ?? ""} />
+ <VStack spacing={4}>
+ <Loading isLoading={loading}>
+ <Combobox
+ label="Item"
+ name="itemId"
+ onChange={onItemChange}
+ options={items.map((item) => ({
+ label: item.readableId,
+ value: item.id,
+ helper: item.name,
+ }))}
+ itemHeight={44}
+ />
+ <Number label="Quantity" name="quantity" />
+ <Combobox
+ label="Shelf"
+ name="shelfId"
+ options={shelves}
+ value={selectedShelf ?? ""}
+ onChange={(value) =>
+ setSelectedShelf(value?.value ?? null)
+ }
+ />
+ </Loading>
+ </VStack>
+ </ModalBody>
+
+ <ModalFooter>
+ <Button
+ type="button"
+ onClick={modal.onClose}
+ variant="secondary"
+ >
+ Cancel
+ </Button>
+
+ <Submit>{add ? "Add" : "Remove"} Inventory</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
+ </>
+ );
+}
diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsx
index f342dedf64..9987829544 100644
--- a/apps/mes/app/components/AppSidebar.tsx
+++ b/apps/mes/app/components/AppSidebar.tsx
@@ -51,6 +51,7 @@ import { useMode, useUser } from "~/hooks";
import type { action } from "~/root";
import type { Location } from "~/services/types";
import { path } from "~/utils/path";
+import { AdjustInventory } from "./AdjustInventory";
import { EndShift } from "./EndShift";
import Feedback from "./Feedback";
@@ -225,18 +226,31 @@ export function OperationsNav({ activeEvents }: { activeEvents: number }) {
export function ToolsNav() {
return (
- <SidebarGroup className="group-data-[collapsible=icon]:hidden">
- <SidebarGroupLabel>Tools</SidebarGroupLabel>
- <SidebarMenu>
- <SidebarMenuItem>
- <EndShift />
- </SidebarMenuItem>
+ <>
+ <SidebarGroup>
+ <SidebarGroupLabel>Inventory Adjustments</SidebarGroupLabel>
+ <SidebarMenu>
+ <SidebarMenuItem>
+ <AdjustInventory add={true} />
+ </SidebarMenuItem>
+ <SidebarMenuItem>
+ <AdjustInventory add={false} />
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarGroup>
+ <SidebarGroup>
+ <SidebarGroupLabel>Tools</SidebarGroupLabel>
+ <SidebarMenu>
+ <SidebarMenuItem>
+ <EndShift />
+ </SidebarMenuItem>
- <SidebarMenuItem>
- <Feedback />
- </SidebarMenuItem>
- </SidebarMenu>
- </SidebarGroup>
+ <SidebarMenuItem>
+ <Feedback />
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarGroup>
+ </>
);
}
diff --git a/apps/mes/app/routes/x+/adjustment.tsx b/apps/mes/app/routes/x+/adjustment.tsx
new file mode 100644
index 0000000000..d646fcef99
--- /dev/null
+++ b/apps/mes/app/routes/x+/adjustment.tsx
@@ -0,0 +1,46 @@
+import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { validationError, validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import {
+ insertManualInventoryAdjustment,
+ inventoryAdjustmentValidator,
+} from "~/services/inventory.service";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {});
+ const serviceRole = await getCarbonServiceRole();
+
+ const formData = await request.formData();
+ const validation = await validator(inventoryAdjustmentValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+ const { ...data } = validation.data;
+
+ const itemLedger = await insertManualInventoryAdjustment(serviceRole, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (itemLedger.error) {
+ const flashMessage =
+ itemLedger.error === "Insufficient quantity for negative adjustment"
+ ? "Insufficient quantity for negative adjustment"
+ : "Failed to create manual inventory adjustment";
+
+ return json({
+ success: false,
+ message: flashMessage,
+ });
+ }
+
+ return json({
+ success: true,
+ });
+}
diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.ts
new file mode 100644
index 0000000000..c45005f02d
--- /dev/null
+++ b/apps/mes/app/services/inventory.service.ts
@@ -0,0 +1,57 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const inventoryAdjustmentValidator = z.object({
+ itemId: z.string().min(1, { message: "Item ID is required" }),
+ locationId: z.string().min(20, { message: "Location is required" }),
+ shelfId: zfd.text(z.string().optional()),
+ entryType: z.enum(["Positive Adjmt.", "Negative Adjmt."]),
+ quantity: zfd.numeric(z.number().min(1, { message: "Quantity is required" })),
+});
+
+export async function insertManualInventoryAdjustment(
+ client: SupabaseClient<Database>,
+ inventoryAdjustment: z.infer<typeof inventoryAdjustmentValidator> & {
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ // Look up the current quantity for this itemId, locationId, and shelfId
+ const query = client
+ .from("itemInventory")
+ .select("quantityOnHand")
+ .eq("itemId", inventoryAdjustment.itemId)
+ .eq("locationId", inventoryAdjustment.locationId);
+
+ if (inventoryAdjustment.shelfId) {
+ query.eq("shelfId", inventoryAdjustment.shelfId);
+ } else {
+ query.is("shelfId", null);
+ }
+
+ const { data: currentQuantity, error: quantityError } =
+ await query.maybeSingle();
+ const currentQuantityOnHand = currentQuantity?.quantityOnHand ?? 0;
+
+ if (quantityError) {
+ return { error: "Failed to fetch current quantity" };
+ }
+
+ // Check if it's a negative adjustment and if the quantity is sufficient
+ if (inventoryAdjustment.entryType === "Negative Adjmt.") {
+ if (inventoryAdjustment.quantity > currentQuantityOnHand) {
+ return {
+ error: "Insufficient quantity for negative adjustment",
+ };
+ }
+ inventoryAdjustment.quantity = -Math.abs(inventoryAdjustment.quantity);
+ }
+
+ return client
+ .from("itemLedger")
+ .insert([inventoryAdjustment])
+ .select("*")
+ .single();
+}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index facf2a7dec..12458a5f5d 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -28,13 +28,14 @@ export const path = {
finish: `${x}/finish`,
forgotPassword: `${ERP_URL}/forgot-password`,
healthcheck: "/healthcheck",
+ inventoryAdjustment: `${x}/adjustment`,
issue: `${x}/issue`,
- messagingNotify: `${x}/proxy/api/messaging/notify`,
- operation: (id: string) => generatePath(`${x}/operation/${id}`),
- operations: `${x}/operations?saved=1`,
location: `${x}/location`,
login: "/login",
logout: "/logout",
+ messagingNotify: `${x}/proxy/api/messaging/notify`,
+ operation: (id: string) => generatePath(`${x}/operation/${id}`),
+ operations: `${x}/operations?saved=1`,
productionEvent: `${x}/event`,
recent: `${x}/recent`,
refreshSession: "/refresh-session",