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 ability to issue material to a job

Brad Barbina3d0738398a7
diff --git a/apps/carbon/app/components/Form/Item.tsx b/apps/carbon/app/components/Form/Item.tsx
index 84d3963420..ecfc7fb15b 100644
--- a/apps/carbon/app/components/Form/Item.tsx
+++ b/apps/carbon/app/components/Form/Item.tsx
@@ -265,7 +265,6 @@ const Item = ({
}}
/>
)}
-
{type === "Material" && newItemsModal.isOpen && (
<MaterialForm
type="modal"
@@ -286,6 +285,7 @@ const Item = ({
defaultMethodType: "Buy",
active: props?.includeInactive === undefined,
unitCost: 0,
+ tags: [],
}}
/>
)}
diff --git a/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx b/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
index da43fac363..95ed0ec554 100644
--- a/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
@@ -11,7 +11,7 @@ import { Link } from "@remix-run/react";
import {
LuContainer,
LuHardHat,
- LuPlus,
+ LuPenSquare,
LuShoppingCart,
LuSquareStack,
LuUserSquare,
@@ -113,7 +113,7 @@ const CreateMenu = () => {
<DropdownMenuTrigger asChild>
<IconButton
aria-label="Create"
- icon={<LuPlus />}
+ icon={<LuPenSquare />}
variant="secondary"
className={"!border-dashed border-border"}
/>
diff --git a/apps/carbon/app/hooks/index.ts b/apps/carbon/app/hooks/index.ts
index 71564aa82d..e6c6cbe05b 100644
--- a/apps/carbon/app/hooks/index.ts
+++ b/apps/carbon/app/hooks/index.ts
@@ -1,17 +1,21 @@
+import {
+ useNanoStore,
+ useOptimisticLocation,
+ useRouteData,
+ useUrlParams,
+} from "@carbon/remix";
+
import { useCurrencyFormatter } from "./useCurrencyFormatter";
import { useModules } from "./useModules";
import { useMovingCellRef } from "./useMovingCellRef";
-import { useNanoStore } from "./useNanoStore";
+
import { useNextItemId } from "./useNextItemId";
import { useNotifications } from "./useNotifications";
import { useOnboarding } from "./useOnboarding";
-import { useOptimisticLocation } from "./useOptimisticLocation";
import { usePercentFormatter } from "./usePercentFormatter";
import { usePermissions } from "./usePermissions";
import { useRealtime } from "./useRealtime";
-import { useRouteData } from "./useRouteData";
import { useScrollPosition } from "./useScrollPosition";
-import { useUrlParams } from "./useUrlParams";
import { useUser } from "./useUser";
export {
diff --git a/apps/carbon/app/hooks/useCustomFieldsSchema.tsx b/apps/carbon/app/hooks/useCustomFieldsSchema.tsx
index 4fa4995457..be1c22ea1e 100644
--- a/apps/carbon/app/hooks/useCustomFieldsSchema.tsx
+++ b/apps/carbon/app/hooks/useCustomFieldsSchema.tsx
@@ -1,8 +1,8 @@
import type { Json } from "@carbon/database";
+import { useRouteData } from "@carbon/remix";
import { useMemo } from "react";
import { z } from "zod";
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
export function useCustomFieldsSchema() {
const data = useRouteData<{
diff --git a/apps/carbon/app/hooks/useIntegrations.tsx b/apps/carbon/app/hooks/useIntegrations.tsx
index 19469584a8..41ed896c44 100644
--- a/apps/carbon/app/hooks/useIntegrations.tsx
+++ b/apps/carbon/app/hooks/useIntegrations.tsx
@@ -1,7 +1,7 @@
+import { useRouteData } from "@carbon/remix";
import { useCallback } from "react";
import type { Integration } from "~/modules/settings";
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
export function useIntegrations(): {
list: Integration[];
diff --git a/apps/carbon/app/hooks/useMode.tsx b/apps/carbon/app/hooks/useMode.tsx
index 619332f725..580d9fbd9e 100644
--- a/apps/carbon/app/hooks/useMode.tsx
+++ b/apps/carbon/app/hooks/useMode.tsx
@@ -1,8 +1,8 @@
+import { useRouteData } from "@carbon/remix";
import { useFetchers } from "@remix-run/react";
import type { Mode } from "~/types/validators";
import { modeValidator } from "~/types/validators";
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
export function useOptimisticMode() {
const fetchers = useFetchers();
diff --git a/apps/carbon/app/hooks/useOnboarding.tsx b/apps/carbon/app/hooks/useOnboarding.tsx
index 3bf2b1bbf0..bab589876c 100644
--- a/apps/carbon/app/hooks/useOnboarding.tsx
+++ b/apps/carbon/app/hooks/useOnboarding.tsx
@@ -1,5 +1,5 @@
+import { useRouteData } from "@carbon/remix";
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
export function useOnboarding() {
const routeData = useRouteData<{
diff --git a/apps/carbon/app/hooks/usePermissions.tsx b/apps/carbon/app/hooks/usePermissions.tsx
index 48697deebc..ad48b78399 100644
--- a/apps/carbon/app/hooks/usePermissions.tsx
+++ b/apps/carbon/app/hooks/usePermissions.tsx
@@ -1,8 +1,8 @@
+import { useRouteData } from "@carbon/remix";
import { useCallback } from "react";
import type { Permission } from "~/modules/users";
import type { Role } from "~/types";
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
import { useUser } from "./useUser";
export function usePermissions() {
diff --git a/apps/carbon/app/hooks/useReplaceLocation.tsx b/apps/carbon/app/hooks/useReplaceLocation.tsx
index 911c68b64c..3cca3762e7 100644
--- a/apps/carbon/app/hooks/useReplaceLocation.tsx
+++ b/apps/carbon/app/hooks/useReplaceLocation.tsx
@@ -1,6 +1,6 @@
+import { useOptimisticLocation } from "@carbon/remix";
import type { Location } from "@remix-run/react";
import { useCallback, useState } from "react";
-import { useOptimisticLocation } from "./useOptimisticLocation";
export function useReplaceLocation() {
const optimisticLocation = useOptimisticLocation();
diff --git a/apps/carbon/app/hooks/useTheme.tsx b/apps/carbon/app/hooks/useTheme.tsx
index 4d8cb5c4ff..68f3281fee 100644
--- a/apps/carbon/app/hooks/useTheme.tsx
+++ b/apps/carbon/app/hooks/useTheme.tsx
@@ -1,8 +1,8 @@
import { useFetchers } from "@remix-run/react";
+import { useRouteData } from "@carbon/remix";
import { themeValidator } from "~/modules/settings";
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
export function useOptimisticTheme() {
const fetchers = useFetchers();
diff --git a/apps/carbon/app/hooks/useUser.tsx b/apps/carbon/app/hooks/useUser.tsx
index 7a185118c1..073d3bb878 100644
--- a/apps/carbon/app/hooks/useUser.tsx
+++ b/apps/carbon/app/hooks/useUser.tsx
@@ -1,5 +1,5 @@
+import { useRouteData } from "@carbon/remix";
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
type PersonalData = {
id: string;
diff --git a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityState.tsx b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityState.tsx
index 690a8bb0ad..17ba3ab9de 100644
--- a/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityState.tsx
+++ b/apps/carbon/app/modules/sales/ui/Opportunity/OpportunityState.tsx
@@ -1,4 +1,5 @@
import { Button, cn, Menubar } from "@carbon/react";
+import { useOptimisticLocation } from "@carbon/remix";
import { Link } from "@remix-run/react";
import { LuCircle } from "react-icons/lu";
import {
@@ -6,7 +7,6 @@ import {
RiProgress4Line,
RiProgress8Line,
} from "react-icons/ri";
-import { useOptimisticLocation } from "~/hooks/useOptimisticLocation";
import { path } from "~/utils/path";
import type { Opportunity } from "../../types";
diff --git a/apps/carbon/app/routes/x+/job+/update.tsx b/apps/carbon/app/routes/x+/job+/update.tsx
index 51f163b713..588b899320 100644
--- a/apps/carbon/app/routes/x+/job+/update.tsx
+++ b/apps/carbon/app/routes/x+/job+/update.tsx
@@ -1,6 +1,11 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
+import {
+ recalculateJobRequirements,
+ upsertJobMethod,
+} from "~/modules/production";
import type { recalculateTask } from "~/trigger/recalculate";
export const config = {
@@ -24,6 +29,7 @@ export async function action({ request }: ActionFunctionArgs) {
return json({ error: { message: "Invalid form data" }, data: null });
}
+ const serviceRole = await getCarbonServiceRole();
switch (field) {
case "itemId":
if (!value) {
@@ -46,47 +52,71 @@ export async function action({ request }: ActionFunctionArgs) {
.single(),
]);
- const result = await client
- .from("job")
- .update({
- itemId: value,
- unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
- quantity:
- (manufacturing?.data?.lotSize ?? 0) === 0
- ? undefined
- : manufacturing?.data?.lotSize ?? 0,
- modelUploadId: item.data?.modelUploadId ?? null,
- scrapQuantity: Math.ceil(
- (manufacturing?.data?.lotSize ?? 0) *
- ((manufacturing?.data?.scrapPercentage ?? 0) / 100)
- ),
- updatedBy: userId,
- updatedAt: new Date().toISOString(),
- })
- .in("id", ids as string[]);
+ const [itemUpdate, makeMethodUpdate] = await Promise.all([
+ client
+ .from("job")
+ .update({
+ itemId: value,
+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
+ quantity:
+ (manufacturing?.data?.lotSize ?? 0) === 0
+ ? undefined
+ : manufacturing?.data?.lotSize ?? 0,
+ modelUploadId: item.data?.modelUploadId ?? null,
+ scrapQuantity: Math.ceil(
+ (manufacturing?.data?.lotSize ?? 0) *
+ ((manufacturing?.data?.scrapPercentage ?? 0) / 100)
+ ),
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", ids as string[]),
+
+ client
+ .from("jobMakeMethod")
+ .update({
+ itemId: value,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("jobId", ids as string[])
+ .is("parentMaterialId", null),
+ ]);
+
+ if (itemUpdate.error) {
+ return json(itemUpdate);
+ }
+
+ if (makeMethodUpdate.error) {
+ return json(makeMethodUpdate);
+ }
+
+ for await (const id of ids) {
+ const upsertMethod = await upsertJobMethod(serviceRole, "itemToJob", {
+ sourceId: value,
+ targetId: id as string,
+ companyId,
+ userId,
+ });
+
+ if (upsertMethod.error) {
+ json(upsertMethod.error);
+ }
- if (!result.error) {
- await tasks.batchTrigger<typeof recalculateTask>(
- "recalculate",
- ids.map((id) => ({
- payload: {
- type: "jobRequirements",
- id: id as string,
- companyId,
- userId,
- },
- }))
- );
+ await tasks.trigger<typeof recalculateTask>("recalculate", {
+ type: "jobRequirements",
+ id: id as string,
+ companyId,
+ userId,
+ });
}
- return json(result);
+ return json(itemUpdate);
case "customerId":
case "deadlineType":
case "dueDate":
case "jobId":
case "locationId":
- case "quantity":
- case "scrapQuantity":
case "unitOfMeasureCode":
return json(
await client
@@ -98,6 +128,34 @@ export async function action({ request }: ActionFunctionArgs) {
})
.in("id", ids as string[])
);
+ case "quantity":
+ case "scrapQuantity":
+ const quantityUpdate = await client
+ .from("job")
+ .update({
+ [field]: value ? value : null,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", ids as string[]);
+
+ if (quantityUpdate.error) {
+ return json(quantityUpdate);
+ }
+
+ for await (const id of ids) {
+ const recalculate = await recalculateJobRequirements(serviceRole, {
+ id: id as string,
+ companyId,
+ userId,
+ });
+ if (recalculate.error) {
+ console.error(recalculate.error);
+ return json(recalculate);
+ }
+ }
+
+ return json(quantityUpdate);
default:
return json({ error: { message: "Invalid field" }, data: null });
}
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index 80a9003ed8..a548d3ba95 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -10,6 +10,7 @@
"@carbon/kv": "*",
"@carbon/notifications": "*",
"@carbon/react": "*",
+ "@carbon/remix": "*",
"@carbon/utils": "*",
"@dnd-kit/core": "^6.1.0",
"@dnd-kit/sortable": "^8.0.0",
diff --git a/apps/developers/app/hooks/index.ts b/apps/developers/app/hooks/index.ts
index a3062fc453..408d24c5e3 100644
--- a/apps/developers/app/hooks/index.ts
+++ b/apps/developers/app/hooks/index.ts
@@ -1,6 +1,9 @@
+import {
+ useOptimisticLocation,
+ useRouteData,
+ useUrlParams,
+} from "@carbon/remix";
import { useMode } from "./useMode";
-import { useOptimisticLocation } from "./useOptimisticLocation";
-import { useRouteData } from "./useRouteData";
import { useUser } from "./useUser";
-export { useMode, useOptimisticLocation, useRouteData, useUser };
+export { useMode, useOptimisticLocation, useRouteData, useUrlParams, useUser };
diff --git a/apps/developers/app/hooks/useOptimisticLocation.ts b/apps/developers/app/hooks/useOptimisticLocation.ts
deleted file mode 100644
index 84eb784fa9..0000000000
--- a/apps/developers/app/hooks/useOptimisticLocation.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-// credit: Matt Aitken at trigger.dev
-import { useLocation, useNavigation } from "@remix-run/react";
-
-export function useOptimisticLocation() {
- const navigation = useNavigation();
- const location = useLocation();
-
- if (navigation.state === "idle" || !navigation.location) {
- return location;
- }
-
- return navigation.location;
-}
diff --git a/apps/developers/app/hooks/useRouteData.tsx b/apps/developers/app/hooks/useRouteData.tsx
deleted file mode 100644
index 9c6f2bf54a..0000000000
--- a/apps/developers/app/hooks/useRouteData.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { useMatches } from "@remix-run/react";
-import { useMemo } from "react";
-
-export function useRouteData<T>(path: string): T | undefined {
- const matchingRoutes = useMatches();
- const route = useMemo(
- () => matchingRoutes.find((route) => route.pathname === path),
- [matchingRoutes, path]
- );
- return (route?.data as T) || undefined;
-}
diff --git a/apps/developers/app/hooks/useUrlParams.tsx b/apps/developers/app/hooks/useUrlParams.tsx
deleted file mode 100644
index df815dfcaf..0000000000
--- a/apps/developers/app/hooks/useUrlParams.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useSearchParams, useSubmit } from "@remix-run/react";
-import { useCallback } from "react";
-
-export function useUrlParams(): [
- URLSearchParams,
- (
- params: Record<string, string | string[] | number | undefined | null>
- ) => void
-] {
- const submit = useSubmit();
- const [searchParams] = useSearchParams();
-
- const setSearchParams = useCallback(
- (params: Record<string, string | string[] | number | undefined | null>) => {
- Object.entries(params).forEach(([name, value]) => {
- if (value) {
- if (Array.isArray(value)) {
- if (value.length === 0) {
- searchParams.delete(name);
- } else {
- value.forEach((v, i) => {
- if (i === 0) {
- searchParams.set(name, v.toString());
- } else {
- searchParams.append(name, v.toString());
- }
- });
- }
- } else {
- searchParams.set(name, value.toString());
- }
- } else {
- searchParams.delete(name);
- }
- });
-
- submit(searchParams);
- },
- [submit, searchParams]
- );
-
- return [searchParams, setSearchParams];
-}
diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsx
index 6f5d735016..da5c18180e 100644
--- a/apps/mes/app/components/AppSidebar.tsx
+++ b/apps/mes/app/components/AppSidebar.tsx
@@ -48,7 +48,7 @@ import { Form, Link, useFetcher, useLocation } from "@remix-run/react";
import { useRef, type ComponentProps } from "react";
import { useMode, useUser } from "~/hooks";
import type { action } from "~/root";
-import type { Location } from "~/services/operations.service";
+import type { Location } from "~/services/types";
import { path } from "~/utils/path";
import { EndShift } from "./EndShift";
import Feedback from "./Feedback";
diff --git a/apps/mes/app/components/EndShift.tsx b/apps/mes/app/components/EndShift.tsx
index 4eb3250b46..98ad37e0ea 100644
--- a/apps/mes/app/components/EndShift.tsx
+++ b/apps/mes/app/components/EndShift.tsx
@@ -23,8 +23,8 @@ import { useEffect, useState } from "react";
import { flushSync } from "react-dom";
import { useUser } from "~/hooks";
import type { action as endShiftAction } from "~/routes/x+/end-shift";
-import type { Operation } from "~/services/operations.service";
import { getActiveJobOperationsByEmployee } from "~/services/operations.service";
+import type { Operation } from "~/services/types";
import { path } from "~/utils/path";
export function EndShift() {
diff --git a/apps/mes/app/components/Feedback.tsx b/apps/mes/app/components/Feedback.tsx
index d34e7ffef5..9209ae33cd 100644
--- a/apps/mes/app/components/Feedback.tsx
+++ b/apps/mes/app/components/Feedback.tsx
@@ -24,8 +24,8 @@ import { nanoid } from "nanoid";
import type { ChangeEvent } from "react";
import { useEffect, useRef, useState } from "react";
import { LuImage, LuMessageCircle } from "react-icons/lu";
-import { feedbackValidator } from "~/models/feedback";
import type { action } from "~/routes/x+/feedback";
+import { feedbackValidator } from "~/services/models";
import { path } from "~/utils/path";
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes
diff --git a/apps/mes/app/components/Filter/useFilters.tsx b/apps/mes/app/components/Filter/useFilters.tsx
index 23ed92b2fd..dbb81eaeff 100644
--- a/apps/mes/app/components/Filter/useFilters.tsx
+++ b/apps/mes/app/components/Filter/useFilters.tsx
@@ -1,4 +1,4 @@
-import { useUrlParams } from "~/hooks/useUrlParams";
+import { useUrlParams } from "~/hooks";
export function useFilters() {
const [params, setParams] = useUrlParams();
diff --git a/apps/mes/app/components/Icons.tsx b/apps/mes/app/components/Icons.tsx
index 7b8a2c70ca..5d8b5cacbe 100644
--- a/apps/mes/app/components/Icons.tsx
+++ b/apps/mes/app/components/Icons.tsx
@@ -31,7 +31,8 @@ import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
-import type { documentTypes, Operation } from "~/services/operations.service";
+import type { documentTypes } from "~/services/models";
+import type { Operation } from "~/services/types";
type FileIconProps = {
type: (typeof documentTypes)[number];
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index c9a6a5a124..9dbaec0a65 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -8,6 +8,7 @@ import {
generateHTML,
Heading,
HStack,
+ IconButton,
Modal,
ModalBody,
ModalContent,
@@ -61,27 +62,29 @@ import {
OperationStatusIcon,
} from "~/components";
import { useMode, useRealtime, useUser } from "~/hooks";
+import type { productionEventType } from "~/services/models";
+import {
+ finishValidator,
+ issueValidator,
+ nonScrapQuantityValidator,
+ productionEventValidator,
+ scrapQuantityValidator,
+} from "~/services/models";
import type {
Job,
JobMaterial,
OperationWithDetails,
ProductionEvent,
- productionEventType,
ProductionQuantity,
StorageItem,
-} from "~/services/operations.service";
-import {
- finishValidator,
- getFileType,
- nonScrapQuantityValidator,
- productionEventValidator,
- scrapQuantityValidator,
-} from "~/services/operations.service";
+} from "~/services/types";
import { path } from "~/utils/path";
import { useCarbon } from "@carbon/auth";
import {
+ Combobox,
Hidden,
+ Number,
NumberControlled,
TextArea,
ValidatedForm,
@@ -104,17 +107,21 @@ import type {
PostgrestSingleResponse,
RealtimeChannel,
} from "@supabase/supabase-js";
+import { flushSync } from "react-dom";
import { FaTasks } from "react-icons/fa";
import { FaCheck, FaPause, FaPlay, FaPlus, FaTrash } from "react-icons/fa6";
import {
LuAlertTriangle,
LuChevronLeft,
LuClipboardCheck,
+ LuGitBranchPlus,
LuHammer,
LuHardHat,
LuTimer,
} from "react-icons/lu";
import { MethodIcon, MethodItemTypeIcon } from "~/components/Icons";
+import { getFileType } from "~/services/operations.service";
+import { useItems } from "~/stores";
import ItemThumbnail from "./ItemThumbnail";
import ScrapReason from "./ScrapReason";
@@ -144,10 +151,13 @@ export const JobOperation = ({
eventType,
isOverdue,
operation,
+ issueModal,
finishModal,
scrapModal,
reworkModal,
completeModal,
+ selectedMaterial,
+ setSelectedMaterial,
setActiveTab,
setEventType,
} = useOperationState(originalOperation, job);
@@ -350,30 +360,33 @@ export const JobOperation = ({
<span className="text-muted-foreground text-sm">
{operation.jobDueDate
? formatDate(operation.jobDueDate)
- : "–"}
+ : null}
</span>
</VStack>
</div>
</div>
-
- {/* <div className="rounded-xl border bg-card text-card-foreground shadow">
- <div className="p-6 flex flex-row items-center justify-between space-y-0 pb-2">
- <h3 className="tracking-tight text-sm font-medium">
- Reworked
- </h3>
- <FaRedoAlt className="h-3 w-3 text-muted-foreground" />
- </div>
- <div className="p-6 pt-0">
- <Heading size="h2">{operation.quantityReworked}</Heading>
- </div>
- </div> */}
</div>
</div>
<Separator />
<div className="flex flex-col items-start justify-between w-full">
<div className="flex flex-col gap-4 p-4 w-full">
- <Heading size="h3">Materials</Heading>
+ <HStack className="justify-between w-full">
+ <Heading size="h3">Materials</Heading>
+ <Button
+ aria-label="Issue Material"
+ leftIcon={<LuGitBranchPlus />}
+ variant="secondary"
+ onClick={() => {
+ flushSync(() => {
+ setSelectedMaterial(null);
+ });
+ issueModal.onOpen();
+ }}
+ >
+ Issue Material
+ </Button>
+ </HStack>
<Suspense key={operationId} fallback={<TableSkeleton />}>
<Await resolve={materials}>
{(resolvedMaterials) => (
@@ -382,7 +395,9 @@ export const JobOperation = ({
<Tr>
<Th>Part</Th>
<Th className="lg:table-cell hidden">Method</Th>
- <Th>Quantity</Th>
+ <Th>Issued</Th>
+ <Th>Required</Th>
+ <Th className="text-right" />
</Tr>
</Thead>
<Tbody>
@@ -397,17 +412,28 @@ export const JobOperation = ({
</Tr>
) : (
resolvedMaterials?.data?.map((material) => (
- <Tr key={material.id}>
- <Td className="flex items-center gap-2">
- <MethodItemTypeIcon
- type={material.itemType}
- />
- <span className="font-semibold">
- {material.itemReadableId}
- </span>
- <span className="md:flex hidden">
- {material.description}
- </span>
+ <Tr
+ key={material.id}
+ className={cn(
+ material.jobOperationId !== operationId &&
+ "opacity-50 hover:opacity-100"
+ )}
+ >
+ <Td>
+ <HStack spacing={2}>
+ <MethodItemTypeIcon
+ type={material.itemType}
+ className="size-4"
+ />
+ <VStack spacing={0}>
+ <span className="font-semibold">
+ {material.itemReadableId}
+ </span>
+ <span className="text-muted-foreground text-xs">
+ {material.description}
+ </span>
+ </VStack>
+ </HStack>
</Td>
<Td className="lg:table-cell hidden">
<Badge variant="secondary">
@@ -418,7 +444,30 @@ export const JobOperation = ({
{material.methodType}
</Badge>
</Td>
+ <Td>
+ {material.methodType === "Make" ? (
+ <MethodIcon type="Make" />
+ ) : (
+ material.quantityIssued
+ )}
+ </Td>
<Td>{material.estimatedQuantity}</Td>
+ <Td className="text-right">
+ {material.methodType !== "Make" && (
+ <IconButton
+ aria-label="Issue Material"
+ variant="ghost"
+ icon={<LuGitBranchPlus />}
+ className="h-8 w-8"
+ onClick={() => {
+ flushSync(() => {
+ setSelectedMaterial(material);
+ });
+ issueModal.onOpen();
+ }}
+ />
+ )}
+ </Td>
</Tr>
))
)}
@@ -799,6 +848,16 @@ export const JobOperation = ({
onClose={finishModal.onClose}
/>
)}
+ {issueModal.isOpen && (
+ <IssueModal
+ operationId={operation.id}
+ material={selectedMaterial ?? undefined}
+ onClose={() => {
+ setSelectedMaterial(null);
+ issueModal.onClose();
+ }}
+ />
+ )}
</>
);
};
@@ -1009,6 +1068,11 @@ function useOperationState(operation: OperationWithDetails, job: Job) {
const reworkModal = useDisclosure();
const completeModal = useDisclosure();
const finishModal = useDisclosure();
+ const issueModal = useDisclosure();
+
+ const [selectedMaterial, setSelectedMaterial] = useState<JobMaterial | null>(
+ null
+ );
const [activeTab, setActiveTab] = useState("details");
const [eventType, setEventType] = useState(() => {
@@ -1084,10 +1148,12 @@ function useOperationState(operation: OperationWithDetails, job: Job) {
reworkModal,
completeModal,
finishModal,
+ issueModal,
isOverdue: operation.jobDueDate
? new Date(operation.jobDueDate) < new Date()
: false,
-
+ selectedMaterial,
+ setSelectedMaterial,
setActiveTab,
setEventType,
};
@@ -1574,6 +1640,68 @@ function QuantityModal({
);
}
+function IssueModal({
+ operationId,
+ material,
+ onClose,
+}: {
+ operationId: string;
+ material?: JobMaterial;
+ onClose: () => void;
+}) {
+ const [items] = useItems();
+ const itemOptions = useMemo(() => {
+ return items.map((item) => ({
+ label: item.readableId,
+ helper: item.name,
+ value: item.id,
+ }));
+ }, [items]);
+
+ return (
+ <Modal open onOpenChange={onClose}>
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Issue Material</ModalTitle>
+ <ModalDescription>
+ Manually add or subtract material from the required quantities.
+ </ModalDescription>
+ </ModalHeader>
+
+ <ValidatedForm
+ method="post"
+ action={path.to.issue}
+ onSubmit={onClose}
+ validator={issueValidator}
+ defaultValues={{
+ materialId: material?.id,
+ jobOperationId: operationId,
+ itemId: material?.itemId,
+ quantity: 1,
+ }}
+ >
+ <ModalBody>
+ <Hidden name="jobOperationId" />
+ <Hidden name="materialId" />
+ <VStack spacing={4}>
+ <Combobox name="itemId" label="Item" options={itemOptions} />
+ <Number name="quantity" label="Quantity" />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="primary">
+ Issue
+ </Button>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
+
function Navigation({
job,
operation,
diff --git a/apps/mes/app/components/Kanban/components/ColumnCard.tsx b/apps/mes/app/components/Kanban/components/ColumnCard.tsx
index 86d92713f3..38c23f92db 100644
--- a/apps/mes/app/components/Kanban/components/ColumnCard.tsx
+++ b/apps/mes/app/components/Kanban/components/ColumnCard.tsx
@@ -14,7 +14,7 @@ import { CSS } from "@dnd-kit/utilities";
import { cva } from "class-variance-authority";
import { useMemo } from "react";
import { LuGripVertical } from "react-icons/lu";
-import { useUrlParams } from "~/hooks/useUrlParams";
+import { useUrlParams } from "~/hooks";
import type { Column, ColumnDragData, DisplaySettings, Item } from "../types";
import { ItemCard } from "./ItemCard";
@@ -118,7 +118,7 @@ export function ColumnCard({
<CardContent className="flex flex-col gap-2 p-2">
<SortableContext items={itemsIds}>
{items.map((item) => (
- <ItemCard key={item.id} item={item} {...displaySettings} />
+ <ItemCard key={item.id!} item={item} {...displaySettings} />
))}
</SortableContext>
</CardContent>
diff --git a/apps/mes/app/components/Kanban/types.ts b/apps/mes/app/components/Kanban/types.ts
index 2765f4d534..0db55cf9fd 100644
--- a/apps/mes/app/components/Kanban/types.ts
+++ b/apps/mes/app/components/Kanban/types.ts
@@ -1,8 +1,5 @@
import { z } from "zod";
-import {
- deadlineTypes,
- jobOperationStatus,
-} from "~/services/operations.service";
+import { deadlineTypes, jobOperationStatus } from "~/services/models";
export const columnValidator = z.object({
id: z.string(),
diff --git a/apps/mes/app/components/OperationsList.tsx b/apps/mes/app/components/OperationsList.tsx
index bd9045011f..d3123e59fd 100644
--- a/apps/mes/app/components/OperationsList.tsx
+++ b/apps/mes/app/components/OperationsList.tsx
@@ -15,10 +15,7 @@ import {
} from "@carbon/utils";
import { Link } from "@remix-run/react";
import { LuClipboardCheck, LuTimer } from "react-icons/lu";
-import type {
- Operation,
- OperationSettings,
-} from "~/services/operations.service";
+import type { Operation, OperationSettings } from "~/services/types";
import { path } from "~/utils/path";
import { DeadlineIcon, OperationStatusIcon } from "./Icons";
diff --git a/apps/mes/app/components/RealtimeDataProvider.tsx b/apps/mes/app/components/RealtimeDataProvider.tsx
new file mode 100644
index 0000000000..8312b5a29c
--- /dev/null
+++ b/apps/mes/app/components/RealtimeDataProvider.tsx
@@ -0,0 +1,176 @@
+"use client";
+
+import { useCarbon } from "@carbon/auth";
+import idb from "localforage";
+import { useEffect } from "react";
+import { useUser } from "~/hooks";
+import { useItems, usePeople } from "~/stores";
+import type { Item } from "~/stores/items";
+
+let hydratedFromIdb = false;
+let hydratedFromServer = false;
+
+const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
+ const { carbon, accessToken } = useCarbon();
+ const {
+ company: { id: companyId },
+ } = useUser();
+
+ useEffect(() => {
+ hydratedFromServer = false;
+ }, [companyId]);
+
+ const [, setItems] = useItems();
+ const [, setPeople] = usePeople();
+
+ const hydrate = async () => {
+ if (!hydratedFromIdb) {
+ hydratedFromIdb = true;
+
+ idb.getItem("items").then((data) => {
+ if (data && !hydratedFromServer) setItems(data as Item[], true);
+ });
+ idb.getItem("people").then((data) => {
+ // @ts-ignore
+ if (data && !hydratedFromServer) setPeople(data, true);
+ });
+ }
+
+ if (!carbon || !accessToken || hydratedFromServer) return;
+
+ const [items, people] = await Promise.all([
+ carbon
+ .from("item")
+ .select("id, readableId, name, type, replenishmentSystem, active")
+ .eq("companyId", companyId)
+ .order("readableId"),
+
+ carbon
+ .from("employees")
+ .select("id, name, email, avatarUrl")
+ .eq("companyId", companyId)
+ .order("name"),
+ ]);
+
+ if (items.error) {
+ throw new Error("Failed to fetch items");
+ }
+ if (people.error) {
+ throw new Error("Failed to fetch people");
+ }
+
+ hydratedFromServer = true;
+
+ // @ts-ignore
+ setItems(items.data ?? []);
+ setPeople(
+ // @ts-ignore
+ people.data?.filter((p) => !p.email?.includes("@carbonos.dev")) ?? []
+ );
+ };
+
+ useEffect(() => {
+ if (!companyId) return;
+ hydrate();
+
+ if (!carbon || !accessToken) return;
+ carbon.realtime.setAuth(accessToken);
+ const channel = carbon
+ .channel("realtime:core")
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "item",
+ },
+ (payload) => {
+ if ("companyId" in payload.new && payload.new.companyId !== companyId)
+ return;
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
+
+ setItems((items) =>
+ [
+ ...items,
+ {
+ id: inserted.id,
+ name: inserted.name,
+ readableId: inserted.readableId,
+ description: inserted.description,
+ replenishmentSystem: inserted.replenishmentSystem,
+ type: inserted.type,
+ active: inserted.active,
+ },
+ ].sort((a, b) => a.readableId.localeCompare(b.readableId))
+ );
+
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
+
+ setItems((items) =>
+ items
+ .map((i) => {
+ if (i.id === updated.id) {
+ return {
+ ...i,
+ readableId: updated.readableId,
+ name: updated.name,
+ replenishmentSystem: updated.replenishmentSystem,
+ type: updated.type,
+ active: updated.active,
+ };
+ }
+ return i;
+ })
+ .sort((a, b) => a.readableId.localeCompare(b.readableId))
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setItems((items) => items.filter((p) => p.id !== deleted.id));
+ break;
+ default:
+ break;
+ }
+ }
+ )
+
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "employee",
+ },
+ async (payload) => {
+ if ("companyId" in payload.new && payload.new.companyId !== companyId)
+ return;
+ // TODO: there's a cleaner way of doing this, but since customers and suppliers
+ // are also in the users table, we can't automatically add/update/delete them
+ // from our list of employees. So for now we just refetch.
+ const { data } = await carbon
+ .from("employees")
+ .select("id, name, avatarUrl")
+ .eq("companyId", companyId)
+ .order("name");
+ if (data) {
+ // @ts-ignore
+ setPeople(data);
+ }
+ }
+ )
+ .subscribe();
+
+ return () => {
+ if (channel) carbon?.removeChannel(channel);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [carbon, accessToken, companyId]);
+
+ return <>{children}</>;
+};
+
+export default RealtimeDataProvider;
diff --git a/apps/mes/app/components/SearchFilter.tsx b/apps/mes/app/components/SearchFilter.tsx
index 4e59cc3d34..01ca00112b 100644
--- a/apps/mes/app/components/SearchFilter.tsx
+++ b/apps/mes/app/components/SearchFilter.tsx
@@ -7,7 +7,7 @@ import {
} from "@carbon/react";
import { useState } from "react";
import { LuSearch } from "react-icons/lu";
-import { useUrlParams } from "~/hooks/useUrlParams";
+import { useUrlParams } from "~/hooks";
type SearchFilterProps = InputProps & {
param: string;
diff --git a/apps/mes/app/hooks/index.ts b/apps/mes/app/hooks/index.ts
index 9af763d599..174b82ef26 100644
--- a/apps/mes/app/hooks/index.ts
+++ b/apps/mes/app/hooks/index.ts
@@ -1,15 +1,19 @@
-import useMediaQuery from "./useMediaQuery";
+import {
+ useNanoStore,
+ useOptimisticLocation,
+ useRouteData,
+ useUrlParams,
+} from "@carbon/remix";
import { useMode } from "./useMode";
-import { useOptimisticLocation } from "./useOptimisticLocation";
import { useRealtime } from "./useRealtime";
-import { useRouteData } from "./useRouteData";
import { useUser } from "./useUser";
export {
- useMediaQuery,
useMode,
+ useNanoStore,
useOptimisticLocation,
useRealtime,
useRouteData,
+ useUrlParams,
useUser,
};
diff --git a/apps/mes/app/hooks/useMediaQuery.ts b/apps/mes/app/hooks/useMediaQuery.ts
deleted file mode 100644
index a134c9c141..0000000000
--- a/apps/mes/app/hooks/useMediaQuery.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { useEffect, useState } from "react";
-
-type ScreenSize = "sm" | "md" | "lg" | "xl" | "2xl";
-
-function useMediaQuery() {
- const [screenSize, setScreenSize] = useState<ScreenSize>("sm");
-
- useEffect(() => {
- const checkScreenSize = () => {
- if (window.matchMedia("(min-width: 1536px)").matches) {
- setScreenSize("2xl");
- } else if (window.matchMedia("(min-width: 1280px)").matches) {
- setScreenSize("xl");
- } else if (window.matchMedia("(min-width: 1024px)").matches) {
- setScreenSize("lg");
- } else if (window.matchMedia("(min-width: 768px)").matches) {
- setScreenSize("md");
- } else {
- setScreenSize("sm");
- }
- };
-
- checkScreenSize();
- window.addEventListener("resize", checkScreenSize);
-
- return () => window.removeEventListener("resize", checkScreenSize);
- }, []);
-
- return {
- isMobile: ["sm", "md", "lg"].includes(screenSize),
- screenSize,
- };
-}
-
-export default useMediaQuery;
diff --git a/apps/mes/app/hooks/useMode.tsx b/apps/mes/app/hooks/useMode.tsx
index 619332f725..bf4faa81a3 100644
--- a/apps/mes/app/hooks/useMode.tsx
+++ b/apps/mes/app/hooks/useMode.tsx
@@ -2,7 +2,7 @@ import { useFetchers } from "@remix-run/react";
import type { Mode } from "~/types/validators";
import { modeValidator } from "~/types/validators";
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
+import { useRouteData } from "../../../../packages/remix/src/hooks/useRouteData";
export function useOptimisticMode() {
const fetchers = useFetchers();
diff --git a/apps/mes/app/hooks/useOptimisticLocation.ts b/apps/mes/app/hooks/useOptimisticLocation.ts
deleted file mode 100644
index 84eb784fa9..0000000000
--- a/apps/mes/app/hooks/useOptimisticLocation.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-// credit: Matt Aitken at trigger.dev
-import { useLocation, useNavigation } from "@remix-run/react";
-
-export function useOptimisticLocation() {
- const navigation = useNavigation();
- const location = useLocation();
-
- if (navigation.state === "idle" || !navigation.location) {
- return location;
- }
-
- return navigation.location;
-}
diff --git a/apps/mes/app/hooks/useRouteData.tsx b/apps/mes/app/hooks/useRouteData.tsx
deleted file mode 100644
index 9c6f2bf54a..0000000000
--- a/apps/mes/app/hooks/useRouteData.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { useMatches } from "@remix-run/react";
-import { useMemo } from "react";
-
-export function useRouteData<T>(path: string): T | undefined {
- const matchingRoutes = useMatches();
- const route = useMemo(
- () => matchingRoutes.find((route) => route.pathname === path),
- [matchingRoutes, path]
- );
- return (route?.data as T) || undefined;
-}
diff --git a/apps/mes/app/hooks/useUrlParams.tsx b/apps/mes/app/hooks/useUrlParams.tsx
deleted file mode 100644
index df815dfcaf..0000000000
--- a/apps/mes/app/hooks/useUrlParams.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useSearchParams, useSubmit } from "@remix-run/react";
-import { useCallback } from "react";
-
-export function useUrlParams(): [
- URLSearchParams,
- (
- params: Record<string, string | string[] | number | undefined | null>
- ) => void
-] {
- const submit = useSubmit();
- const [searchParams] = useSearchParams();
-
- const setSearchParams = useCallback(
- (params: Record<string, string | string[] | number | undefined | null>) => {
- Object.entries(params).forEach(([name, value]) => {
- if (value) {
- if (Array.isArray(value)) {
- if (value.length === 0) {
- searchParams.delete(name);
- } else {
- value.forEach((v, i) => {
- if (i === 0) {
- searchParams.set(name, v.toString());
- } else {
- searchParams.append(name, v.toString());
- }
- });
- }
- } else {
- searchParams.set(name, value.toString());
- }
- } else {
- searchParams.delete(name);
- }
- });
-
- submit(searchParams);
- },
- [submit, searchParams]
- );
-
- return [searchParams, setSearchParams];
-}
diff --git a/apps/mes/app/hooks/useUser.tsx b/apps/mes/app/hooks/useUser.tsx
index 34500d1c23..edb4e42e7c 100644
--- a/apps/mes/app/hooks/useUser.tsx
+++ b/apps/mes/app/hooks/useUser.tsx
@@ -1,5 +1,5 @@
import { path } from "~/utils/path";
-import { useRouteData } from "./useRouteData";
+import { useRouteData } from "../../../../packages/remix/src/hooks/useRouteData";
type PersonalData = {
id: string;
diff --git a/apps/mes/app/models/feedback.ts b/apps/mes/app/models/feedback.ts
deleted file mode 100644
index 028a25bda8..0000000000
--- a/apps/mes/app/models/feedback.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { z } from "zod";
-
-export const feedbackValidator = z.object({
- feedback: z.string().min(1, { message: "" }),
- attachmentPath: z.string().optional(),
- location: z.string(),
-});
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index 97d48cc107..fdf4b2831a 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -11,6 +11,7 @@ import { json, redirect } from "@vercel/remix";
import NProgress from "nprogress";
import { useEffect } from "react";
import { AppSidebar } from "~/components";
+import RealtimeDataProvider from "~/components/RealtimeDataProvider";
import { getLocation, setLocation } from "~/services/location.server";
import {
getActiveJobCount,
@@ -115,20 +116,22 @@ export default function AuthenticatedRoute() {
return (
<div className="h-screen w-screen overflow-y-auto md:overflow-hidden">
<CarbonProvider session={session}>
- <SidebarProvider defaultOpen={false}>
- <TooltipProvider delayDuration={0}>
- <AppSidebar
- activeEvents={activeEvents}
- company={company}
- companies={companies}
- location={location}
- locations={locations}
- />
- <SidebarInset className="bg-card">
- <Outlet />
- </SidebarInset>
- </TooltipProvider>
- </SidebarProvider>
+ <RealtimeDataProvider>
+ <SidebarProvider defaultOpen={false}>
+ <TooltipProvider delayDuration={0}>
+ <AppSidebar
+ activeEvents={activeEvents}
+ company={company}
+ companies={companies}
+ location={location}
+ locations={locations}
+ />
+ <SidebarInset className="bg-card">
+ <Outlet />
+ </SidebarInset>
+ </TooltipProvider>
+ </SidebarProvider>
+ </RealtimeDataProvider>
</CarbonProvider>
</div>
);
diff --git a/apps/mes/app/routes/x+/active.tsx b/apps/mes/app/routes/x+/active.tsx
index 25cebdbfdc..c3b5a98986 100644
--- a/apps/mes/app/routes/x+/active.tsx
+++ b/apps/mes/app/routes/x+/active.tsx
@@ -1,5 +1,11 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { Button, Heading, Input, SidebarTrigger } from "@carbon/react";
+import {
+ Button,
+ Heading,
+ Input,
+ SidebarTrigger,
+ useIsMobile,
+} from "@carbon/react";
import { json, useLoaderData, useParams } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { useEffect, useMemo, useRef, useState } from "react";
@@ -7,7 +13,6 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { LuAlertTriangle, LuSearch } from "react-icons/lu";
import type { ImperativePanelHandle } from "react-resizable-panels";
import { OperationsList } from "~/components";
-import { useMediaQuery } from "~/hooks";
import { getActiveJobOperationsByEmployee } from "~/services/operations.service";
import { makeDurations } from "~/utils/durations";
@@ -31,7 +36,7 @@ export default function ActiveRoute() {
const [searchTerm, setSearchTerm] = useState("");
const panelRef = useRef<ImperativePanelHandle>(null);
- const { isMobile } = useMediaQuery();
+ const isMobile = useIsMobile();
const { operationId } = useParams();
useEffect(() => {
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
index 7ae86c59fa..9074ab4062 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -4,10 +4,8 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import {
- insertProductionQuantity,
- nonScrapQuantityValidator,
-} from "~/services/operations.service";
+import { nonScrapQuantityValidator } from "~/services/models";
+import { insertProductionQuantity } from "~/services/operations.service";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsx
index ae6d7e6dc0..1b5c52dc5a 100644
--- a/apps/mes/app/routes/x+/event.tsx
+++ b/apps/mes/app/routes/x+/event.tsx
@@ -10,9 +10,9 @@ import { validationError, validator } from "@carbon/form";
import { getLocalTimeZone, now } from "@internationalized/date";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
+import { productionEventValidator } from "~/services/models";
import {
endProductionEvent,
- productionEventValidator,
startProductionEvent,
} from "~/services/operations.service";
diff --git a/apps/mes/app/routes/x+/feedback.tsx b/apps/mes/app/routes/x+/feedback.tsx
index 5b26022d98..d12976ad69 100644
--- a/apps/mes/app/routes/x+/feedback.tsx
+++ b/apps/mes/app/routes/x+/feedback.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { getSlackClient } from "~/lib/slack.server";
-import { feedbackValidator } from "~/models/feedback";
+import { feedbackValidator } from "~/services/models";
export const config = {
runtime: "nodejs",
diff --git a/apps/mes/app/routes/x+/finish.tsx b/apps/mes/app/routes/x+/finish.tsx
index eedc8a636d..b38fcdb8ca 100644
--- a/apps/mes/app/routes/x+/finish.tsx
+++ b/apps/mes/app/routes/x+/finish.tsx
@@ -9,10 +9,8 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import {
- finishJobOperation,
- finishValidator,
-} from "~/services/operations.service";
+import { finishValidator } from "~/services/models";
+import { finishJobOperation } from "~/services/operations.service";
import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/mes/app/routes/x+/issue.tsx b/apps/mes/app/routes/x+/issue.tsx
new file mode 100644
index 0000000000..fa1162940f
--- /dev/null
+++ b/apps/mes/app/routes/x+/issue.tsx
@@ -0,0 +1,44 @@
+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { issueValidator } from "~/services/models";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId, companyId } = await requirePermissions(request, {});
+
+ const formData = await request.formData();
+ const validation = await validator(issueValidator).validate(formData);
+
+ if (validation.error) {
+ return json({ error: validation.error }, { status: 400 });
+ }
+
+ const { jobOperationId, materialId, itemId, quantity } = validation.data;
+
+ const serviceRole = await getCarbonServiceRole();
+ const issue = await serviceRole.functions.invoke("issue", {
+ body: {
+ id: jobOperationId,
+ type: "partToOperation",
+ itemId,
+ materialId,
+ quantity,
+ companyId,
+ userId,
+ },
+ });
+
+ if (issue.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.operations,
+ await flash(request, error(issue.error, "Failed to issue material"))
+ );
+ }
+
+ throw redirect(requestReferrer(request) ?? path.to.operations);
+}
diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsx
index 79cf7e14a3..9604437fce 100644
--- a/apps/mes/app/routes/x+/operation.$operationId.tsx
+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx
@@ -7,7 +7,6 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { defer, redirect } from "@vercel/remix";
-import type { OperationWithDetails } from "~/services/operations.service";
import {
getJobByOperationId,
getJobFiles,
@@ -18,6 +17,7 @@ import {
getThumbnailPathByItemId,
getWorkCenter,
} from "~/services/operations.service";
+import type { OperationWithDetails } from "~/services/types";
import { makeDurations } from "~/utils/durations";
import { path } from "~/utils/path";
diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsx
index d24be50234..00939e2ed0 100644
--- a/apps/mes/app/routes/x+/operations.tsx
+++ b/apps/mes/app/routes/x+/operations.tsx
@@ -18,7 +18,7 @@ import { ActiveFilters, Filter, useFilters } from "~/components/Filter";
import type { Column, Item } from "~/components/Kanban";
import { Kanban } from "~/components/Kanban";
import SearchFilter from "~/components/SearchFilter";
-import { useUrlParams } from "~/hooks/useUrlParams";
+import { useUrlParams } from "~/hooks";
import { getLocation } from "~/services/location.server";
import { getFilters, setFilters } from "~/services/operation.server";
import {
diff --git a/apps/mes/app/routes/x+/recent.tsx b/apps/mes/app/routes/x+/recent.tsx
index 698d74a2ee..f113f5a100 100644
--- a/apps/mes/app/routes/x+/recent.tsx
+++ b/apps/mes/app/routes/x+/recent.tsx
@@ -1,12 +1,17 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { Button, Heading, Input, SidebarTrigger } from "@carbon/react";
+import {
+ Button,
+ Heading,
+ Input,
+ SidebarTrigger,
+ useIsMobile,
+} from "@carbon/react";
import { json, useLoaderData, useParams } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { useEffect, useMemo, useRef, useState } from "react";
import { LuAlertTriangle, LuSearch } from "react-icons/lu";
import type { ImperativePanelHandle } from "react-resizable-panels";
import { OperationsList } from "~/components";
-import { useMediaQuery } from "~/hooks";
import { getRecentJobOperationsByEmployee } from "~/services/operations.service";
import { makeDurations } from "~/utils/durations";
@@ -30,7 +35,7 @@ export default function ActiveRoute() {
const [searchTerm, setSearchTerm] = useState("");
const panelRef = useRef<ImperativePanelHandle>(null);
- const { isMobile } = useMediaQuery();
+ const isMobile = useIsMobile();
const { operationId } = useParams();
useEffect(() => {
diff --git a/apps/mes/app/routes/x+/rework.tsx b/apps/mes/app/routes/x+/rework.tsx
index d92ddd0e89..50813c182d 100644
--- a/apps/mes/app/routes/x+/rework.tsx
+++ b/apps/mes/app/routes/x+/rework.tsx
@@ -4,10 +4,8 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import {
- insertReworkQuantity,
- nonScrapQuantityValidator,
-} from "~/services/operations.service";
+import { nonScrapQuantityValidator } from "~/services/models";
+import { insertReworkQuantity } from "~/services/operations.service";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
diff --git a/apps/mes/app/routes/x+/scrap.tsx b/apps/mes/app/routes/x+/scrap.tsx
index 5d5c00ef46..f714fc3bc0 100644
--- a/apps/mes/app/routes/x+/scrap.tsx
+++ b/apps/mes/app/routes/x+/scrap.tsx
@@ -4,10 +4,8 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import {
- insertScrapQuantity,
- scrapQuantityValidator,
-} from "~/services/operations.service";
+import { scrapQuantityValidator } from "~/services/models";
+import { insertScrapQuantity } from "~/services/operations.service";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.ts
new file mode 100644
index 0000000000..b88719c382
--- /dev/null
+++ b/apps/mes/app/services/models.ts
@@ -0,0 +1,94 @@
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const documentTypes = [
+ "Archive",
+ "Document",
+ "Presentation",
+ "PDF",
+ "Spreadsheet",
+ "Text",
+ "Image",
+ "Video",
+ "Audio",
+ "Other",
+] as const;
+
+export const deadlineTypes = [
+ "ASAP",
+ "Hard Deadline",
+ "Soft Deadline",
+ "No Deadline",
+] as const;
+
+export const jobStatus = [
+ "Draft",
+ "Ready",
+ "In Progress",
+ "Paused",
+ "Completed",
+ "Cancelled",
+] as const;
+
+export const jobOperationStatus = [
+ "Todo",
+ "Ready",
+ "Waiting",
+ "In Progress",
+ "Paused",
+ "Done",
+ "Canceled",
+] as const;
+
+export const issueValidator = z.object({
+ itemId: z.string().min(1, { message: "Item is required" }),
+ jobOperationId: z.string().min(1, { message: "Job Operation is required" }),
+ materialId: zfd.text(z.string().optional()),
+ quantity: zfd.numeric(z.number()),
+});
+
+export const feedbackValidator = z.object({
+ feedback: z.string().min(1, { message: "" }),
+ attachmentPath: z.string().optional(),
+ location: z.string(),
+});
+
+export const productionEventType = ["Setup", "Labor", "Machine"] as const;
+
+export const productionEventAction = ["Start", "End"] as const;
+
+export const productionEventValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ jobOperationId: z
+ .string()
+ .min(1, { message: "Job Operation ID is required" }),
+ timezone: zfd.text(z.string()),
+ action: z.enum(productionEventAction, {
+ errorMap: (issue, ctx) => ({
+ message: "Action is required",
+ }),
+ }),
+ type: z.enum(productionEventType, {
+ errorMap: (issue, ctx) => ({
+ message: "Type is required",
+ }),
+ }),
+ workCenterId: zfd.text(z.string().optional()),
+ hasActiveEvents: z.enum(["true", "false"]),
+});
+
+export const finishValidator = z.object({
+ jobOperationId: z.string(),
+ setupProductionEventId: zfd.text(z.string().optional()),
+ laborProductionEventId: zfd.text(z.string().optional()),
+ machineProductionEventId: zfd.text(z.string().optional()),
+});
+
+export const nonScrapQuantityValidator = finishValidator.extend({
+ quantity: zfd.numeric(z.number().positive()),
+});
+
+export const scrapQuantityValidator = nonScrapQuantityValidator.extend({
+ scrapReasonId: zfd.text(z.string()),
+ notes: zfd.text(z.string().optional()),
+});
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 805c64a543..5998cf74f5 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -1,144 +1,14 @@
import type { Database } from "@carbon/database";
-import type { FileObject } from "@supabase/storage-js";
import type { PostgrestResponse, SupabaseClient } from "@supabase/supabase-js";
-import { z } from "zod";
-import { zfd } from "zod-form-data";
+import type { z } from "zod";
import { sanitize } from "~/utils/supabase";
-
-export type BaseOperation = NonNullable<
- Awaited<ReturnType<typeof getJobOperationsByWorkCenter>>["data"]
->[number];
-
-export type BaseOperationWithDetails = NonNullable<
- Awaited<ReturnType<typeof getJobOperationById>>["data"]
->[number];
-
-type Durations = {
- duration: number;
- setupDuration: number;
- laborDuration: number;
- machineDuration: number;
-};
-
-export type Location = NonNullable<
- Awaited<ReturnType<typeof getLocationsByCompany>>["data"]
->[number];
-
-export type Job = NonNullable<
- Awaited<ReturnType<typeof getJobByOperationId>>["data"]
->;
-
-export type JobMaterial = NonNullable<
- Awaited<ReturnType<typeof getJobMaterialsByOperationId>>["data"]
->[number];
-
-export type Operation = BaseOperation & Durations;
-export type OperationWithDetails = BaseOperationWithDetails & Durations;
-
-export type OperationSettings = {
- showCustomer: boolean;
- showDescription: boolean;
- showDueDate: boolean;
- showDuration: boolean;
- showEmployee: boolean;
- showProgress: boolean;
- showStatus: boolean;
-};
-
-export type ProductionEvent = NonNullable<
- Awaited<ReturnType<typeof getProductionEventsForJobOperation>>["data"]
->[number];
-
-export type ProductionQuantity = NonNullable<
- Awaited<ReturnType<typeof getProductionQuantitiesForJobOperation>>["data"]
->[number];
-
-export type StorageItem = FileObject & {
- bucket: string;
-};
-
-export type WorkCenter = NonNullable<
- Awaited<ReturnType<typeof getJobOperationsByWorkCenter>>["data"]
->[number];
-
-export const documentTypes = [
- "Archive",
- "Document",
- "Presentation",
- "PDF",
- "Spreadsheet",
- "Text",
- "Image",
- "Video",
- "Audio",
- "Other",
-] as const;
-
-export const deadlineTypes = [
- "ASAP",
- "Hard Deadline",
- "Soft Deadline",
- "No Deadline",
-] as const;
-
-export const jobStatus = [
- "Draft",
- "Ready",
- "In Progress",
- "Paused",
- "Completed",
- "Cancelled",
-] as const;
-
-export const jobOperationStatus = [
- "Todo",
- "Ready",
- "Waiting",
- "In Progress",
- "Paused",
- "Done",
- "Canceled",
-] as const;
-
-export const productionEventType = ["Setup", "Labor", "Machine"] as const;
-
-export const productionEventAction = ["Start", "End"] as const;
-
-export const productionEventValidator = z.object({
- id: zfd.text(z.string().optional()),
- jobOperationId: z
- .string()
- .min(1, { message: "Job Operation ID is required" }),
- timezone: zfd.text(z.string()),
- action: z.enum(productionEventAction, {
- errorMap: (issue, ctx) => ({
- message: "Action is required",
- }),
- }),
- type: z.enum(productionEventType, {
- errorMap: (issue, ctx) => ({
- message: "Type is required",
- }),
- }),
- workCenterId: zfd.text(z.string().optional()),
- hasActiveEvents: z.enum(["true", "false"]),
-});
-
-export const finishValidator = z.object({
- jobOperationId: z.string(),
- setupProductionEventId: zfd.text(z.string().optional()),
- laborProductionEventId: zfd.text(z.string().optional()),
- machineProductionEventId: zfd.text(z.string().optional()),
-});
-
-export const nonScrapQuantityValidator = finishValidator.extend({
- quantity: zfd.numeric(z.number().positive()),
-});
-
-export const scrapQuantityValidator = nonScrapQuantityValidator.extend({
- scrapReasonId: zfd.text(z.string()),
- notes: zfd.text(z.string().optional()),
-});
+import type {
+ documentTypes,
+ nonScrapQuantityValidator,
+ productionEventValidator,
+ scrapQuantityValidator,
+} from "./models";
+import type { BaseOperationWithDetails, Job, StorageItem } from "./types";
export async function finishJobOperation(
client: SupabaseClient<Database>,
@@ -274,7 +144,9 @@ export async function getJobMaterialsByOperationId(
return client
.from("jobMaterial")
.select("*")
- .eq("jobMakeMethodId", operation.jobMakeMethodId);
+ .eq("jobMakeMethodId", operation.jobMakeMethodId)
+ .order("itemReadableId", { ascending: true })
+ .order("id", { ascending: true });
}
export async function getJobOperationById(
diff --git a/apps/mes/app/services/types.ts b/apps/mes/app/services/types.ts
new file mode 100644
index 0000000000..088d5362fb
--- /dev/null
+++ b/apps/mes/app/services/types.ts
@@ -0,0 +1,66 @@
+import type { FileObject } from "@supabase/storage-js";
+import type {
+ getJobByOperationId,
+ getJobMaterialsByOperationId,
+ getJobOperationById,
+ getJobOperationsByWorkCenter,
+ getLocationsByCompany,
+ getProductionEventsForJobOperation,
+ getProductionQuantitiesForJobOperation,
+} from "./operations.service";
+
+export type BaseOperation = NonNullable<
+ Awaited<ReturnType<typeof getJobOperationsByWorkCenter>>["data"]
+>[number];
+
+export type BaseOperationWithDetails = NonNullable<
+ Awaited<ReturnType<typeof getJobOperationById>>["data"]
+>[number];
+
+type Durations = {
+ duration: number;
+ setupDuration: number;
+ laborDuration: number;
+ machineDuration: number;
+};
+
+export type Location = NonNullable<
+ Awaited<ReturnType<typeof getLocationsByCompany>>["data"]
+>[number];
+
+export type Job = NonNullable<
+ Awaited<ReturnType<typeof getJobByOperationId>>["data"]
+>;
+
+export type JobMaterial = NonNullable<
+ Awaited<ReturnType<typeof getJobMaterialsByOperationId>>["data"]
+>[number];
+
+export type Operation = BaseOperation & Durations;
+export type OperationWithDetails = BaseOperationWithDetails & Durations;
+
+export type OperationSettings = {
+ showCustomer: boolean;
+ showDescription: boolean;
+ showDueDate: boolean;
+ showDuration: boolean;
+ showEmployee: boolean;
+ showProgress: boolean;
+ showStatus: boolean;
+};
+
+export type ProductionEvent = NonNullable<
+ Awaited<ReturnType<typeof getProductionEventsForJobOperation>>["data"]
+>[number];
+
+export type ProductionQuantity = NonNullable<
+ Awaited<ReturnType<typeof getProductionQuantitiesForJobOperation>>["data"]
+>[number];
+
+export type StorageItem = FileObject & {
+ bucket: string;
+};
+
+export type WorkCenter = NonNullable<
+ Awaited<ReturnType<typeof getJobOperationsByWorkCenter>>["data"]
+>[number];
diff --git a/apps/mes/app/stores/index.ts b/apps/mes/app/stores/index.ts
new file mode 100644
index 0000000000..da18b01b55
--- /dev/null
+++ b/apps/mes/app/stores/index.ts
@@ -0,0 +1,2 @@
+export * from "./items";
+export * from "./people";
diff --git a/apps/mes/app/stores/items.ts b/apps/mes/app/stores/items.ts
new file mode 100644
index 0000000000..9ee714a54b
--- /dev/null
+++ b/apps/mes/app/stores/items.ts
@@ -0,0 +1,36 @@
+import type { Database } from "@carbon/database";
+import { useStore as useValue } from "@nanostores/react";
+import { atom, computed } from "nanostores";
+import { useNanoStore } from "~/hooks";
+import type { ListItem } from "~/types";
+
+export type Item = ListItem & {
+ readableId: string;
+ type: Database["public"]["Enums"]["itemType"];
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];
+ active: boolean;
+};
+
+const $itemsStore = atom<Item[]>([]);
+
+const $partsStore = computed($itemsStore, (item) =>
+ item.filter((i) => i.type === "Part")
+);
+
+const $toolsStore = computed($itemsStore, (item) =>
+ item.filter((i) => i.type === "Tool")
+);
+
+const $serivceStore = computed($itemsStore, (item) =>
+ item.filter((i) => i.type === "Service")
+);
+
+const $materialsStore = computed($itemsStore, (item) =>
+ item.filter((i) => i.type === "Material")
+);
+
+export const useItems = () => useNanoStore<Item[]>($itemsStore, "items");
+export const useParts = () => useValue($partsStore);
+export const useTools = () => useValue($toolsStore);
+export const useServices = () => useValue($serivceStore);
+export const useMaterials = () => useValue($materialsStore);
diff --git a/apps/mes/app/stores/people.ts b/apps/mes/app/stores/people.ts
new file mode 100644
index 0000000000..e91c3e1c64
--- /dev/null
+++ b/apps/mes/app/stores/people.ts
@@ -0,0 +1,6 @@
+import { atom } from "nanostores";
+import { useNanoStore } from "~/hooks";
+import type { ListItem } from "~/types";
+
+const $peopleStore = atom<(ListItem & { avatarUrl: string | null })[]>([]);
+export const usePeople = () => useNanoStore($peopleStore, "people");
diff --git a/apps/mes/app/types/index.ts b/apps/mes/app/types/index.ts
new file mode 100644
index 0000000000..7984d24ac6
--- /dev/null
+++ b/apps/mes/app/types/index.ts
@@ -0,0 +1,4 @@
+export type ListItem = {
+ id: string;
+ name: string;
+};
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 75ac458942..ad75bde4cd 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -30,6 +30,7 @@ export const path = {
finish: `${x}/finish`,
forgotPassword: "/forgot-password",
healthcheck: "/healthcheck",
+ issue: `${x}/issue`,
operation: (id: string) => generatePath(`${x}/operation/${id}`),
operations: `${x}/operations?saved=1`,
location: `${x}/location`,
diff --git a/apps/mes/package.json b/apps/mes/package.json
index 74647ae166..898f5a621e 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -5,10 +5,11 @@
"@carbon/auth": "*",
"@carbon/database": "*",
"@carbon/documents": "*",
+ "@carbon/form": "*",
+ "@carbon/kv": "*",
"@carbon/logger": "*",
"@carbon/react": "*",
- "@carbon/kv": "*",
- "@carbon/form": "*",
+ "@carbon/remix": "*",
"@carbon/utils": "*",
"@dnd-kit/core": "^6.1.0",
"@dnd-kit/sortable": "^8.0.0",
diff --git a/apps/mes/tsconfig.json b/apps/mes/tsconfig.json
index ac163dacdb..4413d8817f 100644
--- a/apps/mes/tsconfig.json
+++ b/apps/mes/tsconfig.json
@@ -1,11 +1,5 @@
{
- "include": [
- "env.d.ts",
- "**/*.ts",
- "**/*.tsx",
- "app/modules/documents/documents.service.ts",
- "../carbon/app/components/Breadcrumb.tsx"
- ],
+ "include": ["env.d.ts", "**/*.ts", "**/*.tsx"],
"compilerOptions": {
"lib": ["dom", "dom.iterable", "ESNext"],
"esModuleInterop": true,
diff --git a/package-lock.json b/package-lock.json
index 48d1ff6b57..3a2b8d23fa 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -41,6 +41,7 @@
"@carbon/kv": "*",
"@carbon/notifications": "*",
"@carbon/react": "*",
+ "@carbon/remix": "*",
"@carbon/utils": "*",
"@dnd-kit/core": "^6.1.0",
"@dnd-kit/sortable": "^8.0.0",
@@ -200,6 +201,7 @@
"@carbon/kv": "*",
"@carbon/logger": "*",
"@carbon/react": "*",
+ "@carbon/remix": "*",
"@carbon/utils": "*",
"@dnd-kit/core": "^6.1.0",
"@dnd-kit/sortable": "^8.0.0",
@@ -1531,6 +1533,10 @@
"resolved": "packages/react",
"link": true
},
+ "node_modules/@carbon/remix": {
+ "resolved": "packages/remix",
+ "link": true
+ },
"node_modules/@carbon/tailwind": {
"resolved": "packages/tailwind",
"link": true
@@ -33961,6 +33967,31 @@
"react-icons": "^5.3.0"
}
},
+ "packages/remix": {
+ "version": "*",
+ "devDependencies": {
+ "@carbon/tsconfig": "*",
+ "@carbon/utils": "*",
+ "@types/jest": "^26.0.22",
+ "@types/react": "^18.2.74",
+ "eslint": "^8.23.1",
+ "eslint-config-carbon": "*",
+ "jest": "^26.6.3",
+ "tsup": "^6.5.0",
+ "typescript": "^5.2.2"
+ },
+ "peerDependencies": {
+ "@carbon/database": "*",
+ "@carbon/kv": "*",
+ "@carbon/react": "*",
+ "@carbon/utils": "*",
+ "@remix-run/react": "2.10.2",
+ "@vercel/remix": "2.10.2",
+ "react": "^18.3.1",
+ "zod": "^3.23.8",
+ "zod-form-data": "*"
+ }
+ },
"packages/tailwind": {
"name": "@carbon/tailwind",
"version": "*",
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index b31bc6ffbc..aece03143a 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -9,12 +9,25 @@ import { Database } from "../lib/types.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
-const payloadValidator = z.object({
- type: z.enum(["jobOperation"]),
- id: z.string(),
- companyId: z.string(),
- userId: z.string(),
-});
+const payloadValidator = z
+ .object({
+ type: z.enum(["jobOperation", "partToOperation"]),
+ id: z.string(),
+ itemId: z.string().optional(),
+ quantity: z.number().optional(),
+ materialId: z.string().optional(),
+ companyId: z.string(),
+ userId: z.string(),
+ })
+ .refine(
+ (data) => {
+ if (data.type === "partToOperation") {
+ return data.itemId && data.quantity;
+ }
+ return true;
+ },
+ { message: "Item and quantity are required for part to operation" }
+ );
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
@@ -23,7 +36,8 @@ serve(async (req: Request) => {
const payload = await req.json();
try {
- const { type, id, companyId, userId } = payloadValidator.parse(payload);
+ const { type, id, companyId, itemId, materialId, quantity, userId } =
+ payloadValidator.parse(payload);
console.log({
function: "issue",
@@ -140,7 +154,113 @@ serve(async (req: Request) => {
break;
}
+ case "partToOperation": {
+ await db.transaction().execute(async (trx) => {
+ const jobOperation = await trx
+ .selectFrom("jobOperation")
+ .where("id", "=", id)
+ .select(["jobId", "jobMakeMethodId"])
+ .executeTakeFirst();
+
+ const [job, item] = await Promise.all([
+ trx
+ .selectFrom("job")
+ .where("id", "=", jobOperation?.jobId!)
+ .select("locationId")
+ .executeTakeFirst(),
+ trx
+ .selectFrom("item")
+ .where("id", "=", itemId)
+ .select(["id", "itemTrackingType", "name", "readableId", "type"])
+ .executeTakeFirst(),
+ ]);
+
+ if (materialId) {
+ const material = await trx
+ .selectFrom("jobMaterial")
+ .where("id", "=", materialId)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (material?.methodType !== "Make") {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: material?.jobId,
+ documentLineId: id,
+ companyId,
+ itemId: material?.itemId!,
+ quantity: -Number(material?.quantityToIssue),
+ });
+ }
+ await trx
+ .updateTable("jobMaterial")
+ .set({
+ quantityIssued:
+ (Number(material?.quantityIssued) ?? 0) + Number(quantity),
+ })
+ .where("id", "=", materialId)
+ .execute();
+ } else {
+ if (item?.itemTrackingType === "Inventory") {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: jobOperation?.jobId,
+ documentLineId: id,
+ companyId,
+ itemId: itemId!,
+ quantity: -Number(quantity ?? 0),
+ locationId: job?.locationId,
+ createdBy: userId,
+ });
+ }
+
+ const [itemCost, pickMethod] = await Promise.all([
+ trx
+ .selectFrom("itemCost")
+ .where("itemId", "=", itemId!)
+ .select("unitCost")
+ .executeTakeFirst(),
+ trx
+ .selectFrom("pickMethod")
+ .where("itemId", "=", itemId!)
+ .where("locationId", "=", job?.locationId!)
+ .select("defaultShelfId")
+ .executeTakeFirst(),
+ ]);
+
+ await trx
+ .insertInto("jobMaterial")
+ .values({
+ // @ts-ignore // not sure why ts is complaining here
+ companyId,
+ createdBy: userId,
+ description: item?.name,
+ estimatedQuantity: Number(quantity ?? 0),
+ itemId: itemId!,
+ itemReadableId: item?.readableId,
+ itemType: item?.type,
+ jobId: jobOperation?.jobId!,
+ jobMakeMethodId: jobOperation?.jobMakeMethodId,
+ jobOperationId: id,
+ shelfId: pickMethod?.defaultShelfId,
+ methodType: "Pick",
+ quantity: Number(quantity ?? 0),
+ quantityIssued: Number(quantity ?? 0),
+ unitCost: itemCost?.unitCost,
+ })
+ .executeTakeFirst();
+
+ await trx
+ .insertInto("itemLedger")
+ .values(itemLedgerInserts)
+ .execute();
+ }
+ });
+ break;
+ }
default:
throw new Error(`Invalid type ${type}`);
}
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index 7fae42ae2b..a513204e37 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -219,14 +219,14 @@ function VirtualizedCommand({
}}
>
{item.helper ? (
- <div className="flex flex-col">
- <p className="line-clamp-1">{item.label}</p>
+ <div className="flex flex-col pr-2">
+ <p className="line-clamp-1 w-full">{item.label}</p>
<p className="text-xs text-muted-foreground line-clamp-1">
{item.helper}
</p>
</div>
) : (
- <span className="line-clamp-1">{item.label}</span>
+ <span className="line-clamp-1 w-full pr-2">{item.label}</span>
)}
<LuCheck
className={cn(
diff --git a/packages/remix/.eslintrc.js b/packages/remix/.eslintrc.js
new file mode 100644
index 0000000000..1308cba140
--- /dev/null
+++ b/packages/remix/.eslintrc.js
@@ -0,0 +1,4 @@
+module.exports = {
+ root: true,
+ extends: ["carbon"],
+};
diff --git a/packages/remix/package.json b/packages/remix/package.json
new file mode 100644
index 0000000000..f801697050
--- /dev/null
+++ b/packages/remix/package.json
@@ -0,0 +1,42 @@
+{
+ "name": "@carbon/remix",
+ "dependencies": {},
+ "devDependencies": {
+ "@carbon/tsconfig": "*",
+ "@carbon/utils": "*",
+ "@types/jest": "^26.0.22",
+ "@types/react": "^18.2.74",
+ "eslint": "^8.23.1",
+ "eslint-config-carbon": "*",
+ "jest": "^26.6.3",
+ "tsup": "^6.5.0",
+ "typescript": "^5.2.2"
+ },
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "jest": {
+ "preset": "@carbon/jest/node"
+ },
+ "peerDependencies": {
+ "@carbon/database": "*",
+ "@carbon/react": "*",
+ "@carbon/kv": "*",
+ "@carbon/utils": "*",
+ "@remix-run/react": "2.10.2",
+ "@vercel/remix": "2.10.2",
+ "react": "^18.3.1",
+ "zod": "^3.23.8",
+ "zod-form-data": "*"
+ },
+ "private": true,
+ "scripts": {
+ "clean": "rimraf .turbo node_modules",
+ "lint": "TIMING=1 eslint \"src/**/*.ts*\"",
+ "test": "jest"
+ },
+ "sideEffects": false,
+ "version": "*"
+}
diff --git a/packages/remix/src/hooks/index.ts b/packages/remix/src/hooks/index.ts
new file mode 100644
index 0000000000..49190492eb
--- /dev/null
+++ b/packages/remix/src/hooks/index.ts
@@ -0,0 +1,6 @@
+import { useNanoStore } from "./useNanoStore";
+import { useOptimisticLocation } from "./useOptimisticLocation";
+import { useRouteData } from "./useRouteData";
+import { useUrlParams } from "./useUrlParams";
+
+export { useNanoStore, useOptimisticLocation, useRouteData, useUrlParams };
diff --git a/apps/carbon/app/hooks/useNanoStore.ts b/packages/remix/src/hooks/useNanoStore.ts
similarity index 100%
rename from apps/carbon/app/hooks/useNanoStore.ts
rename to packages/remix/src/hooks/useNanoStore.ts
diff --git a/apps/carbon/app/hooks/useOptimisticLocation.ts b/packages/remix/src/hooks/useOptimisticLocation.ts
similarity index 100%
rename from apps/carbon/app/hooks/useOptimisticLocation.ts
rename to packages/remix/src/hooks/useOptimisticLocation.ts
diff --git a/apps/carbon/app/hooks/useRouteData.tsx b/packages/remix/src/hooks/useRouteData.tsx
similarity index 100%
rename from apps/carbon/app/hooks/useRouteData.tsx
rename to packages/remix/src/hooks/useRouteData.tsx
diff --git a/apps/carbon/app/hooks/useUrlParams.tsx b/packages/remix/src/hooks/useUrlParams.tsx
similarity index 100%
rename from apps/carbon/app/hooks/useUrlParams.tsx
rename to packages/remix/src/hooks/useUrlParams.tsx
diff --git a/packages/remix/src/index.ts b/packages/remix/src/index.ts
new file mode 100644
index 0000000000..007f69d09c
--- /dev/null
+++ b/packages/remix/src/index.ts
@@ -0,0 +1 @@
+export * from "./hooks";
diff --git a/packages/remix/tsconfig.json b/packages/remix/tsconfig.json
new file mode 100644
index 0000000000..c44cb63bb2
--- /dev/null
+++ b/packages/remix/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "compilerOptions": {
+ "lib": ["dom", "ES2015"]
+ },
+ "include": [
+ "src",
+ "../../apps/mes/app/hooks/useMode.tsx",
+ "../../apps/mes/app/hooks/useRealtime.tsx"
+ ],
+ "exclude": ["node_modules"],
+ "extends": "@carbon/tsconfig/react-library.json"
+}