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: edit production quantities

Brad Barbin1912b39914c0
diff --git a/apps/carbon/app/modules/inventory/inventory.service.ts b/apps/carbon/app/modules/inventory/inventory.service.ts
index 32850ec6cf..cc1a14cabe 100644
--- a/apps/carbon/app/modules/inventory/inventory.service.ts
+++ b/apps/carbon/app/modules/inventory/inventory.service.ts
@@ -74,7 +74,7 @@ export async function insertManualInventoryAdjustment(
return client.from("itemLedger").insert([data]).select("*").single();
}
-export async function getItemLedger(
+export async function getItemLedgerPage(
client: SupabaseClient<Database>,
itemId: string,
companyId: string,
diff --git a/apps/carbon/app/modules/inventory/types.ts b/apps/carbon/app/modules/inventory/types.ts
index b9c5cd9204..799a929de5 100644
--- a/apps/carbon/app/modules/inventory/types.ts
+++ b/apps/carbon/app/modules/inventory/types.ts
@@ -1,7 +1,7 @@
import type { Database } from "@carbon/database";
import type {
getInventoryItems,
- getItemLedger,
+ getItemLedgerPage,
getReceiptLines,
getReceipts,
getShippingMethods,
@@ -12,7 +12,7 @@ export type InventoryItem = NonNullable<
>[number];
export type ItemLedger = NonNullable<
- Awaited<ReturnType<typeof getItemLedger>>["data"]
+ Awaited<ReturnType<typeof getItemLedgerPage>>["data"]
>[number];
export type Receipt = NonNullable<
diff --git a/apps/carbon/app/modules/production/production.models.ts b/apps/carbon/app/modules/production/production.models.ts
index 313c2ebe0f..44d830a77b 100644
--- a/apps/carbon/app/modules/production/production.models.ts
+++ b/apps/carbon/app/modules/production/production.models.ts
@@ -415,3 +415,13 @@ export const productionEventValidator = z
path: ["endTime"],
}
);
+
+export const productionQuantityValidator = z.object({
+ id: z.string().min(0, { message: "ID is required" }),
+ jobOperationId: z.string().min(1, { message: "Operation is required" }),
+ type: z.enum(["Rework", "Scrap", "Production"], {
+ errorMap: () => ({ message: "Quantity type is required" }),
+ }),
+ createdBy: zfd.text(z.string().optional()),
+ quantity: zfd.numeric(z.number().min(0)),
+});
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index 13a18f0be0..c30bf9787c 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -12,6 +12,7 @@ import type {
jobStatus,
jobValidator,
productionEventValidator,
+ productionQuantityValidator,
} from "./production.models";
import type { Job } from "./types";
@@ -311,7 +312,7 @@ export async function getJobOperationsByMethodId(
.from("jobOperation")
.select("*")
.eq("jobMakeMethodId", jobMakeMethodId)
- .order("startTime", { ascending: true });
+ .order("createdAt", { ascending: true });
}
export async function getProductionEvent(
@@ -332,9 +333,85 @@ export async function getProductionEvents(
) {
let query = client
.from("productionEvent")
- .select("*, jobOperation(description)", {
- count: "exact",
- })
+ .select(
+ "*, jobOperation(description, jobMakeMethod(parentMaterialId, item(readableId)))",
+ {
+ count: "exact",
+ }
+ )
+ .in("jobOperationId", jobOperationIds)
+ .order("startTime", { ascending: true });
+
+ if (args?.search) {
+ query = query.or(`jobOperation.description.ilike.%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "createdAt", ascending: false },
+ ]);
+ }
+
+ return query;
+}
+
+export async function getProductionEventsPage(
+ client: SupabaseClient<Database>,
+ jobOperationId: string,
+ companyId: string,
+ sortDescending: boolean = false,
+ page: number = 1
+) {
+ const pageSize = 20;
+ const offset = (page - 1) * pageSize;
+
+ let query = client
+ .from("productionEvent")
+ .select("*", { count: "exact" })
+ .eq("jobOperationId", jobOperationId)
+ .eq("companyId", companyId)
+ .order("startTime", { ascending: !sortDescending })
+ .range(offset, offset + pageSize - 1);
+
+ const { data, error, count } = await query;
+
+ if (error) {
+ return { error };
+ }
+
+ return {
+ data,
+ count,
+ page,
+ pageSize,
+ hasMore: count !== null && offset + pageSize < count,
+ };
+}
+
+export async function getProductionQuantity(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("productionQuantity")
+ .select("*, jobOperation(description)")
+ .eq("id", id)
+ .single();
+}
+
+export async function getProductionQuantities(
+ client: SupabaseClient<Database>,
+ jobOperationIds: string[],
+ args?: { search: string | null } & GenericQueryFilters
+) {
+ let query = client
+ .from("productionQuantity")
+ .select(
+ "*, jobOperation(description, jobMakeMethod(parentMaterialId, item(readableId)))",
+ {
+ count: "exact",
+ }
+ )
.in("jobOperationId", jobOperationIds);
if (args?.search) {
@@ -473,6 +550,29 @@ export async function updateProductionEvent(
.single();
}
+export async function updateProductionQuantity(
+ client: SupabaseClient<Database>,
+ productionQuantity: z.infer<typeof productionQuantityValidator> & {
+ id: string;
+ updatedBy: string;
+ companyId: string;
+ }
+) {
+ const { id, updatedBy, companyId, ...updateData } = productionQuantity;
+
+ return client
+ .from("productionQuantity")
+ .update({
+ ...sanitize(updateData),
+ updatedBy,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .select()
+ .single();
+}
+
export async function upsertJob(
client: SupabaseClient<Database>,
job:
diff --git a/apps/carbon/app/modules/production/types.ts b/apps/carbon/app/modules/production/types.ts
index 64932744fa..fa7b6fea9f 100644
--- a/apps/carbon/app/modules/production/types.ts
+++ b/apps/carbon/app/modules/production/types.ts
@@ -4,6 +4,7 @@ import type {
getJobMethodTree,
getJobOperations,
getProductionEvents,
+ getProductionQuantities,
} from "./production.service";
export type Job = NonNullable<Awaited<ReturnType<typeof getJob>>["data"]>;
@@ -23,3 +24,7 @@ export type JobOperation = NonNullable<
export type ProductionEvent = NonNullable<
Awaited<ReturnType<typeof getProductionEvents>>["data"]
>[number];
+
+export type ProductionQuantity = NonNullable<
+ Awaited<ReturnType<typeof getProductionQuantities>>["data"]
+>[number];
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 52eb25d514..0d57318827 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -1,5 +1,6 @@
"use client";
import { useCarbon } from "@carbon/auth";
+import type { Database } from "@carbon/database";
import { ValidatedForm } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
@@ -19,16 +20,19 @@ import {
useDebounce,
useThrottle,
} from "@carbon/react";
+import { formatDateTime, formatDurationMilliseconds } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { useFetcher, useParams } from "@remix-run/react";
+import type { RealtimeChannel } from "@supabase/supabase-js";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import { nanoid } from "nanoid";
import type { Dispatch, SetStateAction } from "react";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { LuChevronDown, LuDollarSign, LuSettings2, LuX } from "react-icons/lu";
import type { z } from "zod";
import { DirectionAwareTabs, TimeTypeIcon } from "~/components";
+import Activity from "~/components/Activity";
import {
Hidden,
InputControlled,
@@ -44,12 +48,14 @@ import {
getUnitHint,
} from "~/components/Form";
import { OperationStatusIcon } from "~/components/Icons";
+import InfiniteScroll from "~/components/InfiniteScroll";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { methodOperationOrders, operationTypes } from "~/modules/shared";
import { path } from "~/utils/path";
import { jobOperationValidator } from "../../production.models";
+import { getProductionEventsPage } from "../../production.service";
import type { Job, JobOperation } from "../../types";
type Operation = z.infer<typeof jobOperationValidator> & {
@@ -135,7 +141,7 @@ const JobBillOfProcess = ({
jobMakeMethodId,
operations,
}: JobBillOfProcessProps) => {
- const { carbon } = useCarbon();
+ const { carbon, accessToken } = useCarbon();
const sortOrderFetcher = useFetcher<{}>();
const permissions = usePermissions();
const {
@@ -297,6 +303,90 @@ const JobBillOfProcess = ({
return `/file/preview/private/${result.data.path}`;
};
+ const [productionEvents, setProductionEvents] = useState<
+ Database["public"]["Tables"]["productionEvent"]["Row"][]
+ >([]);
+ const [page, setPage] = useState(0);
+ const [isLoading, setIsLoading] = useState(false);
+ const [hasMore, setHasMore] = useState(true);
+ const channelRef = useRef<RealtimeChannel | null>(null);
+
+ useEffect(() => {
+ if (!carbon || !accessToken || !selectedItemId) return;
+ carbon.realtime.setAuth(accessToken);
+
+ if (!channelRef.current) {
+ channelRef.current = carbon
+ .channel("realtime:core")
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "productionEvent",
+ filter: `jobOperationId=eq.${selectedItemId}`,
+ },
+ (payload) => {
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
+ setProductionEvents((prevEvents) => [
+ ...prevEvents,
+ inserted as Database["public"]["Tables"]["productionEvent"]["Row"],
+ ]);
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
+ setProductionEvents((prevEvents) =>
+ prevEvents.map((event) =>
+ event.id === updated.id
+ ? (updated as Database["public"]["Tables"]["productionEvent"]["Row"])
+ : event
+ )
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setProductionEvents((prevEvents) =>
+ prevEvents.filter((event) => event.id !== deleted.id)
+ );
+ break;
+ default:
+ break;
+ }
+ }
+ )
+ .subscribe();
+ }
+
+ return () => {
+ if (channelRef.current) carbon?.removeChannel(channelRef.current);
+ };
+ }, [accessToken, carbon, selectedItemId]);
+
+ const loadMoreProductionEvents = useCallback(async () => {
+ if (isLoading || !hasMore || !selectedItemId) return;
+
+ setIsLoading(true);
+
+ const newProductionEvents = await getProductionEventsPage(
+ carbon!,
+ selectedItemId,
+ companyId,
+ false,
+ page + 1
+ );
+
+ if (newProductionEvents.data && newProductionEvents.data.length > 0) {
+ setProductionEvents((prev) => [...prev, ...newProductionEvents.data]);
+ setPage((prevPage) => prevPage + 1);
+ } else {
+ setHasMore(false);
+ }
+
+ setIsLoading(false);
+ }, [isLoading, hasMore, carbon, selectedItemId, companyId, page]);
+
const [tabChangeRerender, setTabChangeRerender] = useState<number>(1);
const renderListItem = ({
item,
@@ -369,6 +459,31 @@ const JobBillOfProcess = ({
</div>
),
},
+ {
+ id: 2,
+ label: "Realtime Events",
+ content: (
+ <div className="flex w-full flex-col pr-2 py-6 min-h-[300px]">
+ <motion.div
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ bounce: 0.2,
+ duration: 0.75,
+ delay: 0.15,
+ }}
+ >
+ <InfiniteScroll
+ component={ProductionEventActivity}
+ items={productionEvents}
+ loadMore={loadMoreProductionEvents}
+ hasMore={hasMore}
+ />
+ </motion.div>
+ </div>
+ ),
+ },
];
return (
@@ -1207,3 +1322,52 @@ function OperationForm({
</ValidatedForm>
);
}
+
+type ProductionEventActivityProps = {
+ item: Database["public"]["Tables"]["productionEvent"]["Row"];
+};
+
+const getActivityText = (
+ item: Database["public"]["Tables"]["productionEvent"]["Row"]
+) => {
+ switch (item.type) {
+ case "Setup":
+ return item.duration
+ ? `did ${formatDurationMilliseconds(item.duration * 1000)} of setup`
+ : `started setup`;
+ case "Labor":
+ return item.duration
+ ? `did ${formatDurationMilliseconds(item.duration * 1000)} of labor`
+ : `started labor`;
+ case "Machine":
+ return item.duration
+ ? `did ${formatDurationMilliseconds(item.duration * 1000)} of machine`
+ : `started machine`;
+ default:
+ return "";
+ }
+};
+
+const ProductionEventActivity = ({ item }: ProductionEventActivityProps) => {
+ return (
+ <Activity
+ employeeId={item.employeeId ?? item.createdBy}
+ activityMessage={getActivityText(item)}
+ activityTime={formatDateTime(item.startTime)}
+ activityIcon={
+ item.type ? (
+ <TimeTypeIcon
+ type={item.type}
+ className={cn(
+ item.type === "Labor"
+ ? "text-green-500"
+ : item.type === "Machine"
+ ? "text-blue-500"
+ : "text-yellow-500"
+ )}
+ />
+ ) : null
+ }
+ />
+ );
+};
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
index 3657fda6dc..8b9a6c3360 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -77,6 +77,8 @@ const JobHeader = () => {
return "operations";
if (location.pathname.includes(path.to.jobProductionEvents(jobId)))
return "events";
+ if (location.pathname.includes(path.to.jobProductionQuantities(jobId)))
+ return "quantities";
return "details";
};
diff --git a/apps/carbon/app/modules/production/ui/Jobs/ProductionEventsTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/ProductionEventsTable.tsx
index 603a16f4d3..9e678ee9ff 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/ProductionEventsTable.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/ProductionEventsTable.tsx
@@ -46,7 +46,13 @@ const ProductionEventsTable = memo(
},
},
},
-
+ {
+ id: "item",
+ header: "Item",
+ cell: ({ row }) => {
+ return row.original.jobOperation?.jobMakeMethod?.item?.readableId;
+ },
+ },
{
accessorKey: "employeeId",
header: "Employee",
diff --git a/apps/carbon/app/modules/production/ui/Jobs/ProductionQuantitiesTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/ProductionQuantitiesTable.tsx
new file mode 100644
index 0000000000..f4d1ffef2a
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/ProductionQuantitiesTable.tsx
@@ -0,0 +1,189 @@
+import { Badge, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
+import { useNavigate, useParams } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo, useState } from "react";
+import { LuPencil, LuTrash } from "react-icons/lu";
+import { EmployeeAvatar, Hyperlink, Table } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import { usePeople } from "~/stores";
+import { path } from "~/utils/path";
+import type { ProductionQuantity } from "../../types";
+
+type ProductionQuantitiesTableProps = {
+ data: ProductionQuantity[];
+ count: number;
+ operations: { id: string; description: string | null }[];
+};
+
+const ProductionQuantitiesTable = memo(
+ ({ data, count, operations }: ProductionQuantitiesTableProps) => {
+ const { jobId } = useParams();
+ if (!jobId) throw new Error("Job ID is required");
+ const [people] = usePeople();
+
+ const columns = useMemo<ColumnDef<ProductionQuantity>[]>(() => {
+ return [
+ {
+ accessorKey: "jobOperationId",
+ header: "Operation",
+ cell: ({ row }) => (
+ <Hyperlink to={row.original.id}>
+ {row.original.jobOperation?.description ?? null}
+ </Hyperlink>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: operations.map((operation) => ({
+ value: operation.id,
+ label: <Enumerable value={operation.description} />,
+ })),
+ },
+ },
+ },
+ {
+ id: "item",
+ header: "Item",
+ cell: ({ row }) => {
+ return row.original.jobOperation?.jobMakeMethod?.item?.readableId;
+ },
+ },
+ {
+ accessorKey: "createdBy",
+ header: "Employee",
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.createdBy} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: <Enumerable value={employee.name} />,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "type",
+ header: "Type",
+ cell: ({ row }) => (
+ <Badge
+ variant={
+ row.original.type === "Production"
+ ? "green"
+ : row.original.type === "Rework"
+ ? "orange"
+ : "red"
+ }
+ >
+ {row.original.type}
+ </Badge>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: ["Production", "Rework", "Scrap"].map((type) => ({
+ value: type,
+ label: (
+ <Badge
+ variant={
+ type === "Production"
+ ? "green"
+ : type === "Rework"
+ ? "orange"
+ : "red"
+ }
+ >
+ {type}
+ </Badge>
+ ),
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "quantity",
+ header: "Quantity",
+ cell: ({ row }) => row.original.quantity,
+ },
+ ];
+ }, [operations, people]);
+
+ const permissions = usePermissions();
+
+ const deleteModal = useDisclosure();
+ const [selectedEvent, setSelectedEvent] =
+ useState<ProductionQuantity | null>(null);
+
+ const onDelete = (data: ProductionQuantity) => {
+ setSelectedEvent(data);
+ deleteModal.onOpen();
+ };
+
+ const onDeleteCancel = () => {
+ setSelectedEvent(null);
+ deleteModal.onClose();
+ };
+
+ const navigate = useNavigate();
+
+ const renderContextMenu = useCallback<
+ (row: ProductionQuantity) => JSX.Element
+ >(
+ (row) => (
+ <>
+ <MenuItem
+ disabled={!permissions.can("update", "production")}
+ onClick={() => navigate(row.id)}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Quantity
+ </MenuItem>
+ <MenuItem
+ disabled={!permissions.can("delete", "users")}
+ onClick={() => onDelete(row)}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Quantity
+ </MenuItem>
+ </>
+ ),
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [permissions]
+ );
+
+ return (
+ <>
+ <Table<ProductionQuantity>
+ count={count}
+ columns={columns}
+ data={data}
+ renderContextMenu={renderContextMenu}
+ />
+ {deleteModal.isOpen && selectedEvent && (
+ <ConfirmDelete
+ action={path.to.deleteProductionQuantity(selectedEvent.id)}
+ isOpen
+ name={`${
+ selectedEvent.jobOperation?.description ?? "Operation"
+ } by ${
+ people.find((p) => p.id === selectedEvent.createdBy)?.name ??
+ "Unknown Employee"
+ }`}
+ text="Are you sure you want to delete this production quantity? This action cannot be undone."
+ onCancel={onDeleteCancel}
+ onSubmit={onDeleteCancel}
+ />
+ )}
+ </>
+ );
+ }
+);
+
+ProductionQuantitiesTable.displayName = "ProductionQuantitiesTable";
+
+export default ProductionQuantitiesTable;
diff --git a/apps/carbon/app/modules/production/ui/Jobs/ProductionQuantityForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/ProductionQuantityForm.tsx
new file mode 100644
index 0000000000..0876f7ce19
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/ProductionQuantityForm.tsx
@@ -0,0 +1,88 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ HStack,
+ VStack,
+} from "@carbon/react";
+
+import { useNavigate } from "@remix-run/react";
+import type { z } from "zod";
+import {
+ Employee,
+ Hidden,
+ Number,
+ Select,
+ Submit,
+ TextArea,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { productionQuantityValidator } from "~/modules/production";
+
+type ProductionQuantityFormProps = {
+ initialValues: z.infer<typeof productionQuantityValidator>;
+};
+
+const ProductionQuantityForm = ({
+ initialValues,
+}: ProductionQuantityFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isDisabled = !permissions.can("update", "production");
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent>
+ <ValidatedForm
+ validator={productionQuantityValidator}
+ method="post"
+ defaultValues={initialValues}
+ className="flex flex-col h-full"
+ >
+ <DrawerHeader>
+ <DrawerTitle>Edit Production Quantity</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ <Hidden name="id" />
+ <Hidden name="jobOperationId" />
+ <VStack spacing={4}>
+ <Employee name="createdBy" label="Employee" />
+ <Number name="quantity" label="Quantity" />
+ <Select
+ name="type"
+ label="Quantity Type"
+ options={[
+ { label: "Production", value: "Production" },
+ { label: "Scrap", value: "Scrap" },
+ { label: "Rework", value: "Rework" },
+ ]}
+ />
+ <TextArea name="scrapReason" label="Scrap Reason" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </ValidatedForm>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default ProductionQuantityForm;
diff --git a/apps/carbon/app/modules/production/ui/Jobs/index.ts b/apps/carbon/app/modules/production/ui/Jobs/index.ts
index 6f43eb159b..535a53bc38 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/index.ts
+++ b/apps/carbon/app/modules/production/ui/Jobs/index.ts
@@ -12,6 +12,8 @@ import JobsTable from "./JobsTable";
import JobStatus from "./JobStatus";
import ProductionEventForm from "./ProductionEventForm";
import ProductionEventsTable from "./ProductionEventsTable";
+import ProductionQuantitiesTable from "./ProductionQuantitiesTable";
+import ProductionQuantityForm from "./ProductionQuantityForm";
export {
getDeadlineIcon,
@@ -28,4 +30,6 @@ export {
JobStatus,
ProductionEventForm,
ProductionEventsTable,
+ ProductionQuantitiesTable,
+ ProductionQuantityForm,
};
diff --git a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
index 749c0d6164..112c1aaa3d 100644
--- a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
@@ -6,7 +6,7 @@ import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useCallback, useState } from "react";
import InfiniteScroll from "~/components/InfiniteScroll";
-import { getItemLedger, InventoryActivity } from "~/modules/inventory";
+import { getItemLedgerPage, InventoryActivity } from "~/modules/inventory";
import { getLocationsList } from "~/modules/resources";
import { getUserDefaults } from "~/modules/users/users.server";
import { path } from "~/utils/path";
@@ -52,7 +52,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
locationId = locations.data?.[0].id as string;
}
- const itemLedgerRecords = await getItemLedger(
+ const itemLedgerRecords = await getItemLedgerPage(
client,
itemId,
companyId,
@@ -93,7 +93,7 @@ export default function ItemInventoryActivityRoute() {
setIsLoading(true);
- const newItemLedgers = await getItemLedger(
+ const newItemLedgers = await getItemLedgerPage(
carbon!,
itemId,
companyId,
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.quantities.$id.tsx b/apps/carbon/app/routes/x+/job+/$jobId.quantities.$id.tsx
new file mode 100644
index 0000000000..39a7eb2626
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.quantities.$id.tsx
@@ -0,0 +1,93 @@
+import { validationError, validator } from "@carbon/form";
+import { useLoaderData } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ ProductionQuantityForm,
+ getProductionQuantity,
+ productionQuantityValidator,
+ updateProductionQuantity,
+} from "~/modules/production";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const productionQuantity = await getProductionQuantity(client, id);
+
+ return json({
+ productionQuantity: productionQuantity?.data ?? null,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "accounting",
+ });
+
+ const { jobId } = params;
+ if (!jobId) throw notFound("jobId or id not found");
+
+ const formData = await request.formData();
+ const validation = await validator(productionQuantityValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const update = await updateProductionQuantity(client, {
+ id,
+ ...data,
+ companyId,
+ updatedBy: userId,
+ });
+
+ if (update.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(update.error, "Failed to update production quantity")
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.jobProductionQuantities(jobId)}?${getParams(request)}`,
+ await flash(request, success("Updated production quantity"))
+ );
+}
+
+export default function EditProductionQuantityRoute() {
+ const { productionQuantity } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: productionQuantity?.id!,
+ type: productionQuantity?.type ?? ("Scrap" as "Scrap"),
+ jobOperationId: productionQuantity?.jobOperationId ?? "",
+ quantity: productionQuantity?.quantity ?? 0,
+ createdBy: productionQuantity?.createdBy ?? "",
+ };
+
+ return (
+ <ProductionQuantityForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.quantities.tsx b/apps/carbon/app/routes/x+/job+/$jobId.quantities.tsx
index be0d7dffc4..676b9e0daa 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.quantities.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.quantities.tsx
@@ -2,16 +2,16 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
-import { useLoaderData } from "@remix-run/react";
+import { Outlet, useLoaderData } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import {
getJobOperationsList,
- getJobQuantities,
- JobQuantitiesTable,
+ getProductionQuantities,
+ ProductionQuantitiesTable,
} from "~/modules/production";
import { getWorkCentersList } from "~/modules/resources";
-import { path } from "~/utils/path";
+import { path, requestReferrer } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -28,8 +28,27 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [events, workCenters, operations] = await Promise.all([
- getJobQuantities(client, jobId, {
+ const operations = await getJobOperationsList(client, jobId);
+ if (operations.error) {
+ redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(
+ request,
+ error(operations.error, "Failed to fetch job operations")
+ )
+ );
+ }
+
+ if (operations.data?.length === 0) {
+ return json({
+ count: 0,
+ events: [],
+ operations: [],
+ });
+ }
+
+ const [events] = await Promise.all([
+ getProductionQuantities(client, operations.data?.map((o) => o.id) ?? [], {
search,
limit,
offset,
@@ -37,7 +56,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
filters,
}),
getWorkCentersList(client, companyId),
- getJobOperationsList(client, jobId),
]);
if (events.error) {
@@ -50,23 +68,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return json({
count: events.count ?? 0,
events: events.data ?? [],
- workCenters: workCenters.data ?? [],
operations: operations.data ?? [],
});
}
-export default function JobQuantitiesRoute() {
- const { count, events, operations, workCenters } =
- useLoaderData<typeof loader>();
+export default function ProductionQuantitiesRoute() {
+ const { count, events, operations } = useLoaderData<typeof loader>();
return (
- <VStack spacing={0} className="h-[calc(100vh-99px)]">
- <JobQuantitiesTable
- data={events}
- count={count}
- operations={operations}
- workCenters={workCenters}
- />
- </VStack>
+ <>
+ <VStack spacing={0} className="h-[calc(100vh-99px)]">
+ <ProductionQuantitiesTable
+ data={events}
+ count={count}
+ operations={operations}
+ />
+ </VStack>
+ <Outlet />
+ </>
);
}
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index cb93f117b1..c5e4c1c951 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -1202,9 +1202,9 @@ function PauseButton({ className, ...props }: ComponentProps<"button">) {
<ButtonWithTooltip
{...props}
tooltip="Pause"
- className="group w-16 h-16 md:w-20 md:h-20 flex flex-row items-center gap-2 justify-center bg-red-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-red-600 hover:scale-105 transition-all disabled:bg-muted text-2xl"
+ className="group w-16 h-16 md:w-20 md:h-20 flex flex-row items-center gap-2 justify-center bg-red-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-red-600 hover:scale-105 transition-all text-accent disabled:bg-muted disabled:text-muted-foreground/80 text-2xl"
>
- <FaPause className="text-accent group-hover:scale-125" />
+ <FaPause className="group-hover:scale-125" />
</ButtonWithTooltip>
);
}
@@ -1214,9 +1214,9 @@ function PlayButton({ className, ...props }: ComponentProps<"button">) {
<ButtonWithTooltip
{...props}
tooltip="Start"
- className="group w-16 h-16 md:w-20 md:h-20 flex flex-row items-center gap-2 justify-center bg-emerald-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-emerald-600 hover:scale-105 transition-all disabled:bg-muted text-xl"
+ className="group w-16 h-16 md:w-20 md:h-20 flex flex-row items-center gap-2 justify-center bg-emerald-500 rounded-full shadow-lg hover:cursor-pointer hover:drop-shadow-xl hover:bg-emerald-600 hover:scale-105 transition-all text-accent disabled:bg-muted disabled:text-muted-foreground/80 text-xl"
>
- <FaPlay className="text-accent group-hover:scale-125" />
+ <FaPlay className="group-hover:scale-125" />
</ButtonWithTooltip>
);
}