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: start and stop operations with progress updates

Brad Barbin2c6d1d11c23d
diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
index ca942bf95d..7c6134eb55 100644
--- a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
@@ -105,7 +105,7 @@ export default function MethodMaterialMakePage() {
if (!materialId) throw new Error("Could not find materialId");
return (
- <VStack spacing={2} className="p-2" key={JSON.stringify(loaderData)}>
+ <VStack spacing={2} className="p-2">
<MakeMethodBreadcrumbs itemId={item.id} type="Fixture" />
<ItemForm
key={`item:${itemId}:${makeMethodId}:${materialId}`}
@@ -113,12 +113,12 @@ export default function MethodMaterialMakePage() {
initialValues={item}
/>
<BillOfProcess
- key={`bop:${itemId}:${makeMethodId}:${materialId}`}
+ key={`bop:${itemId}:${methodOperations.length}`}
makeMethodId={makeMethodId}
operations={methodOperations}
/>
<BillOfMaterial
- key={`bom:${itemId}:${makeMethodId}:${materialId}`}
+ key={`bom:${itemId}:${methodMaterials.length}`}
makeMethodId={makeMethodId}
materials={methodMaterials}
operations={methodOperations}
diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.method.tsx
index a7f02c6028..2e47090093 100644
--- a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.method.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.method.tsx
@@ -24,20 +24,16 @@ export default function MakeMethodRoute() {
if (!makeMethodId) throw new Error("Could not find makeMethodId");
return (
- <VStack
- spacing={2}
- className="p-2"
- key={JSON.stringify(manufacturingRouteData)}
- >
+ <VStack spacing={2} className="p-2">
<MakeMethodBreadcrumbs itemId={itemId} type="Fixture" />
<BillOfProcess
- key={itemId}
+ key={`bop:${itemId}:${manufacturingRouteData?.methodOperations?.length}`}
makeMethodId={makeMethodId}
// @ts-ignore
operations={manufacturingRouteData?.methodOperations ?? []}
/>
<BillOfMaterial
- key={itemId}
+ key={`bom:${itemId}:${manufacturingRouteData?.methodMaterials?.length}`}
makeMethodId={makeMethodId}
// @ts-ignore
materials={manufacturingRouteData?.methodMaterials ?? []}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
index ca568bc9ea..df3f9370a5 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
@@ -106,11 +106,16 @@ export default function JobMakeMethodRoute() {
const { material, materials, operations } = loaderData;
return (
- <VStack spacing={2} key={JSON.stringify(loaderData)} className="p-2">
+ <VStack spacing={2} className="p-2">
<JobBreadcrumbs />
<JobMaterialForm initialValues={material} operations={operations} />
- <JobBillOfProcess jobMakeMethodId={methodId} operations={operations} />
+ <JobBillOfProcess
+ key={`bop:${methodId}:${operations.length}`}
+ jobMakeMethodId={methodId}
+ operations={operations}
+ />
<JobBillOfMaterial
+ key={`bom:${methodId}:${materials.length}`}
jobMakeMethodId={methodId}
materials={materials}
operations={operations}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx
index 7cd3f4d390..7959e8c6d1 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx
@@ -79,10 +79,15 @@ export default function JobMakeMethodRoute() {
const { materials, operations } = loaderData;
return (
- <VStack spacing={2} key={JSON.stringify(loaderData)} className="p-2">
+ <VStack spacing={2} className="p-2">
<JobBreadcrumbs />
- <JobBillOfProcess jobMakeMethodId={methodId} operations={operations} />
+ <JobBillOfProcess
+ key={`bop:${methodId}:${operations.length}`}
+ jobMakeMethodId={methodId}
+ operations={operations}
+ />
<JobBillOfMaterial
+ key={`bom:${methodId}:${materials.length}`}
jobMakeMethodId={methodId}
materials={materials}
operations={operations}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
index c15db97a22..0d0ee36b0a 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
@@ -105,7 +105,7 @@ export default function MethodMaterialMakePage() {
if (!materialId) throw new Error("Could not find materialId");
return (
- <VStack spacing={2} className="p-2" key={JSON.stringify(loaderData)}>
+ <VStack spacing={2} className="p-2">
<MakeMethodBreadcrumbs itemId={item.id} type="Part" />
<ItemForm
key={`item:${itemId}:${makeMethodId}:${materialId}`}
@@ -113,12 +113,12 @@ export default function MethodMaterialMakePage() {
initialValues={item}
/>
<BillOfProcess
- key={`bop:${itemId}:${makeMethodId}:${materialId}`}
+ key={`bop:${itemId}:${methodOperations.length}`}
makeMethodId={makeMethodId}
operations={methodOperations}
/>
<BillOfMaterial
- key={`bom:${itemId}:${makeMethodId}:${materialId}`}
+ key={`bom:${itemId}:${methodMaterials.length}`}
makeMethodId={makeMethodId}
materials={methodMaterials}
operations={methodOperations}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
index 7a4e12eb8e..7bd55274fe 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
@@ -111,24 +111,20 @@ export default function MakeMethodRoute() {
};
return (
- <VStack
- spacing={2}
- className="p-2"
- key={JSON.stringify(manufacturingRouteData)}
- >
+ <VStack spacing={2} className="p-2">
<MakeMethodBreadcrumbs itemId={itemId} type="Part" />
<PartManufacturingForm
key={itemId}
initialValues={manufacturingInitialValues}
/>
<BillOfProcess
- key={itemId}
+ key={`bop:${itemId}:${manufacturingRouteData?.methodOperations?.length}`}
makeMethodId={makeMethodId}
// @ts-ignore
operations={manufacturingRouteData?.methodOperations ?? []}
/>
<BillOfMaterial
- key={itemId}
+ key={`bom:${itemId}:${manufacturingRouteData?.methodMaterials?.length}`}
makeMethodId={makeMethodId}
// @ts-ignore
materials={manufacturingRouteData?.methodMaterials ?? []}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx
index 0c1158778d..f41f474ce8 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx
@@ -109,13 +109,15 @@ export default function QuoteMakeMethodRoute() {
const { material, materials, operations } = loaderData;
return (
- <VStack spacing={2} key={JSON.stringify(loaderData)}>
+ <VStack spacing={2}>
<QuoteMaterialForm initialValues={material} operations={operations} />
<QuoteBillOfProcess
+ key={`bop:${methodId}:${operations.length}`}
quoteMakeMethodId={methodId}
operations={operations}
/>
<QuoteBillOfMaterial
+ key={`bom:${methodId}:${materials.length}`}
quoteMakeMethodId={methodId}
materials={materials}
operations={operations}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx
index 9238e69c6d..fedeea928f 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx
@@ -82,12 +82,14 @@ export default function QuoteMakeMethodRoute() {
const { materials, operations } = loaderData;
return (
- <VStack spacing={2} key={JSON.stringify(loaderData)}>
+ <VStack spacing={2}>
<QuoteBillOfProcess
+ key={`bop:${methodId}:${operations.length}`}
quoteMakeMethodId={methodId}
operations={operations}
/>
<QuoteBillOfMaterial
+ key={`bom:${methodId}:${materials.length}`}
quoteMakeMethodId={methodId}
materials={materials}
operations={operations}
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 177ae72c08..4eaaa209d3 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -14,12 +14,6 @@ import {
ModalFooter,
ModalHeader,
ModalTitle,
- NumberDecrementStepper,
- NumberField,
- NumberIncrementStepper,
- NumberInput,
- NumberInputGroup,
- NumberInputStepper,
Progress,
ScrollArea,
Separator,
@@ -41,9 +35,12 @@ import {
TooltipProvider,
TooltipTrigger,
Tr,
+ useDisclosure,
+ useInterval,
+ VStack,
type JSONContent,
} from "@carbon/react";
-import { Await, Link } from "@remix-run/react";
+import { Await, Link, useFetcher } from "@remix-run/react";
import type { ComponentProps, ReactNode } from "react";
import { Suspense, useCallback, useMemo, useState } from "react";
import {
@@ -62,30 +59,47 @@ import type {
OperationWithDetails,
ProductionEvent,
productionEventType,
+ ProductionQuantity,
StorageItem,
} from "~/services/jobs.service";
import {
getDocumentType,
productionEventValidator,
+ scrapQuantityValidator,
} from "~/services/jobs.service";
import { path } from "~/utils/path";
import { useCarbon } from "@carbon/auth";
-import { Hidden, useIsSubmitting, ValidatedForm } from "@carbon/form";
+import {
+ Hidden,
+ Number,
+ TextArea,
+ useIsSubmitting,
+ ValidatedForm,
+} from "@carbon/form";
import {
convertDateStringToIsoString,
convertKbToString,
formatDurationMilliseconds,
formatRelativeTime,
} from "@carbon/utils";
-import { getLocalTimeZone } from "@internationalized/date";
+import {
+ getLocalTimeZone,
+ now,
+ parseAbsolute,
+ toZoned,
+} from "@internationalized/date";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { FaRedoAlt, FaTasks } from "react-icons/fa";
-import { FaCheck, FaOilCan, FaPause, FaPlay, FaTrash } from "react-icons/fa6";
import {
- LuChevronDown,
+ FaCheck,
+ FaFlagCheckered,
+ FaPause,
+ FaPlay,
+ FaTrash,
+} from "react-icons/fa6";
+import {
LuChevronLeft,
- LuChevronUp,
LuClipboardCheck,
LuExpand,
LuHammer,
@@ -114,20 +128,23 @@ export const JobOperation = ({
const {
activeTab,
eventType,
- fullScreen,
+ fullscreen,
+ laborProductionEvent,
+ machineProductionEvent,
isOverdue,
progress,
+ scrapModal,
+ setupProductionEvent,
downloadDocument,
getDocumentPath,
setActiveTab,
setEventType,
- setFullScreen,
} = useOperation(operation, events, job);
return (
<OptionallyFullscreen
- isFullScreen={fullScreen}
- onClose={() => setFullScreen(false)}
+ isFullScreen={fullscreen.isOpen}
+ onClose={fullscreen.onClose}
>
<Tabs
key={operation.id}
@@ -137,7 +154,7 @@ export const JobOperation = ({
>
<div className="flex items-center justify-between px-4 py-2 h-[52px] bg-background">
<div className="flex items-start flex-grow gap-1">
- {!fullScreen && (
+ {!fullscreen.isOpen && (
<Link to={backPath}>
<IconButton
aria-label="Back"
@@ -152,13 +169,12 @@ export const JobOperation = ({
<Navigation
job={job}
operation={operation}
- fullScreen={fullScreen}
- setFullScreen={setFullScreen}
+ fullscreen={fullscreen}
/>
</div>
</div>
- {!fullScreen && (
+ {!fullscreen.isOpen && (
<>
<Separator />
<div className="flex items-center justify-start px-4 py-2 h-[52px] bg-background gap-4 w-full overflow-y-auto">
@@ -191,12 +207,7 @@ export const JobOperation = ({
</>
)}
<div className="flex md:hidden items-center justify-start px-4 py-2 h-[52px] bg-background gap-4">
- <Navigation
- job={job}
- operation={operation}
- fullScreen={fullScreen}
- setFullScreen={setFullScreen}
- />
+ <Navigation job={job} operation={operation} fullscreen={fullscreen} />
</div>
<Separator className="flex md:hidden" />
@@ -260,7 +271,12 @@ export const JobOperation = ({
<div className="flex flex-col w-full gap-2">
{operation.setupDuration > 0 && (
<HStack>
- <LuTimer className="h-4 w-4 mr-1" />
+ <Tooltip>
+ <TooltipTrigger>
+ <LuTimer className="h-4 w-4 mr-1" />
+ </TooltipTrigger>
+ <TooltipContent side="right">Setup</TooltipContent>
+ </Tooltip>
<Progress
numerator={formatDurationMilliseconds(progress.setup)}
denominator={formatDurationMilliseconds(
@@ -272,7 +288,12 @@ export const JobOperation = ({
)}
{operation.laborDuration > 0 && (
<HStack>
- <LuHardHat className="h-4 w-4 mr-1" />
+ <Tooltip>
+ <TooltipTrigger>
+ <LuHardHat className="h-4 w-4 mr-1" />
+ </TooltipTrigger>
+ <TooltipContent side="right">Labor</TooltipContent>
+ </Tooltip>
<Progress
numerator={formatDurationMilliseconds(progress.labor)}
denominator={formatDurationMilliseconds(
@@ -284,7 +305,12 @@ export const JobOperation = ({
)}
{operation.machineDuration > 0 && (
<HStack>
- <LuHammer className="h-4 w-4 mr-1" />
+ <Tooltip>
+ <TooltipTrigger>
+ <LuHammer className="h-4 w-4 mr-1" />
+ </TooltipTrigger>
+ <TooltipContent side="right">Machine</TooltipContent>
+ </Tooltip>
<Progress
numerator={formatDurationMilliseconds(progress.machine)}
denominator={formatDurationMilliseconds(
@@ -297,7 +323,12 @@ export const JobOperation = ({
</HStack>
)}
<HStack>
- <FaTasks className="h-4 w-4 mr-1" />
+ <Tooltip>
+ <TooltipTrigger>
+ <FaTasks className="h-4 w-4 mr-1" />
+ </TooltipTrigger>
+ <TooltipContent side="right">Quantity</TooltipContent>
+ </Tooltip>
<Progress
indicatorClassName={
operation.operationStatus === "Paused"
@@ -346,7 +377,7 @@ export const JobOperation = ({
: "–"}
</span>
</TooltipTrigger>
- <TooltipContent side="bottom">
+ <TooltipContent side="right">
{operation.jobDeadlineType}
</TooltipContent>
</Tooltip>
@@ -516,55 +547,166 @@ export const JobOperation = ({
<div className="flex flex-col items-center gap-4">
<div className="flex items-center gap-4 justify-center">
<IconButtonWithTooltip
- disabled
icon={
- <FaOilCan className="text-accent-foreground group-hover:text-accent-foreground/80" />
+ <FaRedoAlt className="text-accent-foreground group-hover:text-accent-foreground/80" />
}
- tooltip="Non-Conformance Report"
+ tooltip="Rework"
/>
-
<IconButtonWithTooltip
icon={
<FaTrash className="text-accent-foreground group-hover:text-accent-foreground/80" />
}
tooltip="Scrap"
+ onClick={scrapModal.onOpen}
/>
<StartStopButton
eventType={eventType as (typeof productionEventType)[number]}
operation={operation}
+ setupProductionEvent={setupProductionEvent}
+ laborProductionEvent={laborProductionEvent}
+ machineProductionEvent={machineProductionEvent}
/>
+
<IconButtonWithTooltip
icon={
- <FaRedoAlt className="text-accent-foreground group-hover:text-accent-foreground/80" />
+ <FaCheck className="text-accent-foreground group-hover:text-accent-foreground/80" />
}
- tooltip="Rework"
+ tooltip="Complete"
/>
<IconButtonWithTooltip
icon={
- <FaCheck className="text-accent-foreground group-hover:text-accent-foreground/80" />
+ <FaFlagCheckered className="text-accent-foreground group-hover:text-accent-foreground/80" />
}
- tooltip="Complete"
+ tooltip="Finish"
/>
</div>
- <WorkTypeToggle value={eventType} onChange={setEventType} />
+ <WorkTypeToggle
+ operation={operation}
+ value={eventType}
+ onChange={setEventType}
+ />
</div>
</Controls>
)}
</Tabs>
+ {scrapModal.isOpen && (
+ <ScrapModal
+ operation={operation}
+ setupProductionEvent={setupProductionEvent}
+ laborProductionEvent={laborProductionEvent}
+ machineProductionEvent={machineProductionEvent}
+ onClose={scrapModal.onClose}
+ />
+ )}
</OptionallyFullscreen>
);
};
+function useActiveEvents(events: ProductionEvent[]): {
+ active: { setup: boolean; labor: boolean; machine: boolean };
+ setupProductionEvent: ProductionEvent | undefined;
+ laborProductionEvent: ProductionEvent | undefined;
+ machineProductionEvent: ProductionEvent | undefined;
+ progress: { setup: number; labor: number; machine: number };
+} {
+ const user = useUser();
+
+ const getProgress = useCallback(() => {
+ const timeNow = now(getLocalTimeZone());
+ return events.reduce(
+ (acc, event) => {
+ if (event.endTime && event.type) {
+ acc[event.type.toLowerCase() as keyof typeof acc] +=
+ (event.duration ?? 0) * 1000;
+ } else if (event.startTime && event.type) {
+ const startTime = toZoned(
+ parseAbsolute(event.startTime, getLocalTimeZone()),
+ getLocalTimeZone()
+ );
+
+ const difference = timeNow.compare(startTime);
+
+ if (difference > 0) {
+ acc[event.type.toLowerCase() as keyof typeof acc] += difference;
+ }
+ }
+ return acc;
+ },
+ {
+ setup: 0,
+ labor: 0,
+ machine: 0,
+ }
+ );
+ }, [events]);
+ const [progress, setProgress] = useState<{
+ setup: number;
+ labor: number;
+ machine: number;
+ }>(getProgress);
+
+ const activeEvents = useMemo(() => {
+ return {
+ setupProductionEvent: events.find(
+ (e) =>
+ e.type === "Setup" && e.endTime === null && e.employeeId === user.id
+ ),
+ laborProductionEvent: events.find(
+ (e) =>
+ e.type === "Labor" && e.endTime === null && e.employeeId === user.id
+ ),
+ machineProductionEvent: events.find(
+ (e) => e.type === "Machine" && e.endTime === null
+ ),
+ };
+ }, [events, user.id]);
+
+ const active = useMemo(() => {
+ return {
+ setup: !!activeEvents.setupProductionEvent,
+ labor: !!activeEvents.laborProductionEvent,
+ machine: !!activeEvents.machineProductionEvent,
+ };
+ }, [activeEvents]);
+
+ useInterval(() => {
+ setProgress(getProgress());
+ }, 1000);
+
+ return {
+ active,
+ ...activeEvents,
+ progress,
+ };
+}
+
function useOperation(
operation: OperationWithDetails,
events: ProductionEvent[],
job: Job
) {
+ const user = useUser();
const { carbon } = useCarbon();
- const [fullScreen, setFullScreen] = useState(false);
+ const fullscreen = useDisclosure();
+ const scrapModal = useDisclosure();
const [activeTab, setActiveTab] = useState("details");
- const [eventType, setEventType] = useState("Labor");
- const user = useUser();
+ const [eventType, setEventType] = useState(() => {
+ if (operation.laborDuration > 0) {
+ return "Labor";
+ }
+ if (operation.machineDuration > 0) {
+ return "Machine";
+ }
+ return "Setup";
+ });
+
+ const {
+ active,
+ setupProductionEvent,
+ laborProductionEvent,
+ machineProductionEvent,
+ progress,
+ } = useActiveEvents(events);
const getDocumentPath = useCallback(
(file: StorageItem) => {
@@ -612,49 +754,31 @@ function useOperation(
[carbon?.storage, getDocumentPath]
);
- const myActiveEvents = useMemo(
- () =>
- events.filter((e) => e.endTime === null && e.employeeId === user.id) ??
- [],
- [events, user.id]
- );
-
- const active = useMemo(
- () => ({
- setup: myActiveEvents.some((e) => e.type === "Setup"),
- labor: myActiveEvents.some((e) => e.type === "Labor"),
- machine: myActiveEvents.some((e) => e.type === "Machine"),
- }),
- [myActiveEvents]
- );
-
- const progress = {
- setup: 0,
- labor: 0,
- machine: 0,
- };
-
return {
active,
activeTab,
eventType,
- fullScreen,
+ fullscreen,
+ laborProductionEvent,
+ machineProductionEvent,
+ progress,
+ scrapModal,
+ setupProductionEvent,
isOverdue: operation.jobDueDate
? new Date(operation.jobDueDate) < new Date()
: false,
- progress,
+
downloadDocument,
getDocumentPath,
setActiveTab,
setEventType,
- setFullScreen,
};
}
function TableSkeleton() {
return (
<Table>
- <thead>
+ <Thead>
<Tr>
<Th>
<Skeleton className="h-4 w-full" />
@@ -663,8 +787,8 @@ function TableSkeleton() {
<Skeleton className="h-4 w-full" />
</Th>
</Tr>
- </thead>
- <tbody>
+ </Thead>
+ <Tbody>
{[...Array(5)].map((_, index) => (
<Tr key={index}>
<Td>
@@ -675,7 +799,7 @@ function TableSkeleton() {
</Td>
</Tr>
))}
- </tbody>
+ </Tbody>
</Table>
);
}
@@ -708,10 +832,10 @@ function ButtonWithTooltip({
}: ComponentProps<"button"> & { tooltip: string }) {
return (
<Tooltip>
- <TooltipTrigger asChild>
+ <TooltipTrigger>
<button {...props}>{children}</button>
</TooltipTrigger>
- <TooltipContent>{tooltip}</TooltipContent>
+ <TooltipContent side="top">{tooltip}</TooltipContent>
</Tooltip>
);
}
@@ -725,7 +849,7 @@ function IconButtonWithTooltip({
<ButtonWithTooltip
{...props}
tooltip={tooltip}
- className="w-12 h-12 flex flex-row items-center gap-2 justify-center bg-accent rounded-full shadow-lg hover:cursor-pointer hover:shadow-xl hover:accent hover:scale-105 transition-all disabled:cursor-not-allowed disabled:opacity-50"
+ className="w-16 h-16 flex flex-row items-center gap-2 justify-center bg-accent rounded-full shadow-lg hover:cursor-pointer hover:shadow-xl hover:accent hover:scale-105 transition-all disabled:cursor-not-allowed disabled:opacity-50"
>
{icon}
</ButtonWithTooltip>
@@ -733,38 +857,59 @@ function IconButtonWithTooltip({
}
function WorkTypeToggle({
+ operation,
value,
onChange,
}: {
+ operation: OperationWithDetails;
value: string;
onChange: (type: string) => void;
}) {
+ const nonZeroDurations = [
+ operation.setupDuration,
+ operation.laborDuration,
+ operation.machineDuration,
+ ].filter((duration) => duration > 0);
+
+ if (nonZeroDurations.length <= 1) {
+ return null;
+ }
+
return (
<ToggleGroup value={value} type="single" onValueChange={onChange}>
- <ToggleGroupItem
- className="w-[110px]"
- value="Setup"
- aria-label="Toggle setup"
- >
- <LuTimer className="h-4 w-4 mr-2" />
- Setup
- </ToggleGroupItem>
- <ToggleGroupItem
- className="w-[110px]"
- value="Labor"
- aria-label="Toggle labor"
- >
- <LuHardHat className="h-4 w-4 mr-2" />
- Labor
- </ToggleGroupItem>
- <ToggleGroupItem
- className="w-[110px]"
- value="Machine"
- aria-label="Toggle machine"
- >
- <LuHammer className="h-4 w-4 mr-2" />
- Machine
- </ToggleGroupItem>
+ {operation.setupDuration > 0 && (
+ <ToggleGroupItem
+ className="w-[110px]"
+ value="Setup"
+ size="lg"
+ aria-label="Toggle setup"
+ >
+ <LuTimer className="h-4 w-4 mr-2" />
+ Setup
+ </ToggleGroupItem>
+ )}
+ {operation.laborDuration > 0 && (
+ <ToggleGroupItem
+ className="w-[110px]"
+ value="Labor"
+ size="lg"
+ aria-label="Toggle labor"
+ >
+ <LuHardHat className="h-4 w-4 mr-2" />
+ Labor
+ </ToggleGroupItem>
+ )}
+ {operation.machineDuration > 0 && (
+ <ToggleGroupItem
+ className="w-[110px]"
+ value="Machine"
+ size="lg"
+ aria-label="Toggle machine"
+ >
+ <LuHammer className="h-4 w-4 mr-2" />
+ Machine
+ </ToggleGroupItem>
+ )}
</ToggleGroup>
);
}
@@ -774,12 +919,47 @@ function StartStopButton({
className,
operation,
eventType,
+ setupProductionEvent,
+ laborProductionEvent,
+ machineProductionEvent,
...props
}: ComponentProps<"button"> & {
eventType: (typeof productionEventType)[number];
operation: OperationWithDetails;
+ setupProductionEvent: ProductionEvent | undefined;
+ laborProductionEvent: ProductionEvent | undefined;
+ machineProductionEvent: ProductionEvent | undefined;
}) {
- const isActive = false; // TODO
+ const fetcher = useFetcher<ProductionEvent>();
+ const isActive = useMemo(() => {
+ if (eventType === "Setup") {
+ return !!setupProductionEvent;
+ }
+ if (eventType === "Labor") {
+ return !!laborProductionEvent;
+ }
+ return !!machineProductionEvent;
+ }, [
+ eventType,
+ setupProductionEvent,
+ laborProductionEvent,
+ machineProductionEvent,
+ ]);
+
+ const id = useMemo(() => {
+ if (eventType === "Setup") {
+ return setupProductionEvent?.id;
+ }
+ if (eventType === "Labor") {
+ return laborProductionEvent?.id;
+ }
+ return machineProductionEvent?.id;
+ }, [
+ eventType,
+ setupProductionEvent,
+ laborProductionEvent,
+ machineProductionEvent,
+ ]);
return (
<ValidatedForm
@@ -788,18 +968,21 @@ function StartStopButton({
method="post"
validator={productionEventValidator}
defaultValues={{
+ id,
jobOperationId: operation.id,
timezone: getLocalTimeZone(),
action: isActive ? "End" : "Start",
type: eventType,
workCenterId: operation.workCenterId ?? undefined,
}}
+ fetcher={fetcher}
>
- <Hidden name="jobOperationId" />
+ <Hidden name="id" value={id} />
+ <Hidden name="jobOperationId" value={operation.id} />
<Hidden name="timezone" />
- <Hidden name="action" />
- <Hidden name="type" />
- <Hidden name="workCenterId" />
+ <Hidden name="action" value={isActive ? "End" : "Start"} />
+ <Hidden name="type" value={eventType} />
+ <Hidden name="workCenterId" value={operation.workCenterId ?? undefined} />
{isActive ? <PauseButton type="submit" /> : <PlayButton type="submit" />}
</ValidatedForm>
);
@@ -812,7 +995,7 @@ function PauseButton({ className, ...props }: ComponentProps<"button">) {
{...props}
tooltip="Pause"
disabled={isSubmitting}
- className="group w-16 h-16 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:opacity-75 text-2xl"
+ className="group w-20 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:opacity-75 text-2xl"
>
<FaPause className="text-accent group-hover:scale-125" />
</ButtonWithTooltip>
@@ -825,65 +1008,120 @@ function PlayButton({ className, ...props }: ComponentProps<"button">) {
<button
{...props}
disabled={isSubmitting}
- className="group w-16 h-16 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:opacity-75"
+ className="group w-20 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:opacity-75 text-xl"
>
<FaPlay className="text-accent group-hover:scale-125" />
</button>
);
}
-function ScrapModal({ operation }: { operation: Operation }) {
- <Modal open={false}>
- <ModalContent>
- <ModalHeader>
- <ModalTitle>{`Scrap ${operation.itemReadableId}`}</ModalTitle>
- <ModalDescription>Select a scrap quantity and reason</ModalDescription>
- </ModalHeader>
- <ModalBody>
- <div className="grid grid-cols-2 gap-4">
- <NumberField
- defaultValue={1}
- // value={1}
- // onChange={onPurchaseUnitChange}
- minValue={1}
- maxValue={operation.operationQuantity}
- >
- <NumberInputGroup className="relative">
- <NumberInput />
- <NumberInputStepper>
- <NumberIncrementStepper>
- <LuChevronUp size="1em" strokeWidth="3" />
- </NumberIncrementStepper>
- <NumberDecrementStepper>
- <LuChevronDown size="1em" strokeWidth="3" />
- </NumberDecrementStepper>
- </NumberInputStepper>
- </NumberInputGroup>
- </NumberField>
- </div>
- </ModalBody>
- <ModalFooter>
- <Button variant="secondary" onClick={() => {}}>
- Cancel
- </Button>
- <Button variant="destructive" onClick={() => {}}>
- Scrap
- </Button>
- </ModalFooter>
- </ModalContent>
- </Modal>;
+function ScrapModal({
+ operation,
+ setupProductionEvent,
+ laborProductionEvent,
+ machineProductionEvent,
+ onClose,
+}: {
+ operation: Operation;
+ setupProductionEvent: ProductionEvent | undefined;
+ laborProductionEvent: ProductionEvent | undefined;
+ machineProductionEvent: ProductionEvent | undefined;
+ onClose: () => void;
+}) {
+ const fetcher = useFetcher<ProductionQuantity>();
+ const [scrapReason, setScrapReason] = useState("");
+ return (
+ <Modal open>
+ <ModalContent>
+ <ValidatedForm
+ action={path.to.scrap}
+ method="post"
+ validator={scrapQuantityValidator}
+ defaultValues={{
+ jobOperationId: operation.id,
+ quantity: 1,
+ scrapReason: "",
+ setupProductionEventId: setupProductionEvent?.id,
+ laborProductionEventId: laborProductionEvent?.id,
+ machineProductionEventId: machineProductionEvent?.id,
+ }}
+ fetcher={fetcher}
+ onSubmit={() => {
+ onClose();
+ }}
+ >
+ <ModalHeader>
+ <ModalTitle>{`Scrap ${operation.itemReadableId}`}</ModalTitle>
+ <ModalDescription>
+ Select a scrap quantity and reason
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="jobOperationId" />
+ <Hidden name="setupProductionEventId" />
+ <Hidden name="laborProductionEventId" />
+ <Hidden name="machineProductionEventId" />
+ <VStack spacing={2}>
+ <Number
+ name="quantity"
+ label="Quantity"
+ minValue={1}
+ maxValue={operation.operationQuantity}
+ />
+ <TextArea
+ label="Scrap Reason"
+ name="scrapReason"
+ value={scrapReason}
+ onChange={(e) => setScrapReason(e.target.value)}
+ />
+ <div className="col-span-2 flex gap-2 mt-2">
+ <Badge
+ variant="secondary"
+ className="cursor-pointer"
+ onClick={() => setScrapReason("Defective")}
+ >
+ Defective
+ </Badge>
+ <Badge
+ variant="secondary"
+ className="cursor-pointer"
+ onClick={() => setScrapReason("Damaged")}
+ >
+ Damaged
+ </Badge>
+ <Badge
+ variant="secondary"
+ className="cursor-pointer"
+ onClick={() => setScrapReason("Quality Control")}
+ >
+ Quality Control
+ </Badge>
+ </div>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+
+ <Button variant="destructive" type="submit">
+ Scrap
+ </Button>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
}
function Navigation({
job,
operation,
- fullScreen,
- setFullScreen,
+ fullscreen,
}: {
job: Job;
operation: OperationWithDetails;
- fullScreen: boolean;
- setFullScreen: (value: boolean) => void;
+ fullscreen: ReturnType<typeof useDisclosure>;
}) {
return (
<>
@@ -905,13 +1143,13 @@ function Navigation({
Instructions
</TabsTrigger>
</TabsList>
- {!fullScreen && (
+ {!fullscreen.isOpen && (
<IconButton
aria-label="Expand"
className="hidden md:flex"
icon={<LuExpand />}
variant="secondary"
- onClick={() => setFullScreen(true)}
+ onClick={fullscreen.onOpen}
/>
)}
</>
diff --git a/apps/mes/app/components/OperationsList.tsx b/apps/mes/app/components/OperationsList.tsx
index 0d4f0c32ed..5456b0aac2 100644
--- a/apps/mes/app/components/OperationsList.tsx
+++ b/apps/mes/app/components/OperationsList.tsx
@@ -81,7 +81,6 @@ function OperationCard({
showProgress,
showStatus,
}: OperationCardProps) {
- console.log({ operation });
const isOverdue =
operation.jobDeadlineType !== "No Deadline" && operation.jobDueDate
? new Date(operation.jobDueDate) < new Date()
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index b3c3c2cd21..c82b3a4d08 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -210,7 +210,7 @@ export default function AuthenticatedRoute() {
)}
</ClientOnly>
</TooltipProvider>
- <Toaster position="bottom-right" />
+ <Toaster position="top-right" />
</AutodeskProvider>
</CarbonProvider>
);
diff --git a/apps/mes/app/routes/x+/active.tsx b/apps/mes/app/routes/x+/active.tsx
index bae0d92264..31c6e29a83 100644
--- a/apps/mes/app/routes/x+/active.tsx
+++ b/apps/mes/app/routes/x+/active.tsx
@@ -7,7 +7,7 @@ import { useMemo, useState } from "react";
import { LuSearch } from "react-icons/lu";
import { OperationsList } from "~/components";
import { getActiveJobOperationsByEmployee } from "~/services/jobs.service";
-import { makeDurations } from "~/utils/jobs";
+import { makeDurations } from "~/utils/durations";
import { defaultLayout } from "~/utils/layout";
diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsx
index bb945502fa..7456a67550 100644
--- a/apps/mes/app/routes/x+/event.tsx
+++ b/apps/mes/app/routes/x+/event.tsx
@@ -26,7 +26,7 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const { action: productionAction, timezone, ...data } = validation.data;
+ const { id, action: productionAction, timezone, ...data } = validation.data;
if (productionAction === "Start") {
const startEvent = await startProductionEvent(client, {
@@ -45,11 +45,17 @@ export async function action({ request }: ActionFunctionArgs) {
return json(
startEvent.data,
- await flash(request, success("Started operation"))
+ await flash(
+ request,
+ success(`Started ${data.type.toLowerCase()} operation`)
+ )
);
} else {
+ if (!id) {
+ return json({}, await flash(request, error("No event id provided")));
+ }
const endEvent = await endProductionEvent(client, {
- ...data,
+ id,
endTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),
employeeId: userId,
});
@@ -59,5 +65,12 @@ export async function action({ request }: ActionFunctionArgs) {
await flash(request, error(endEvent.error, "Failed to end event"))
);
}
+ return json(
+ endEvent.data,
+ await flash(
+ request,
+ success(`Ended ${data.type.toLowerCase()} operation`)
+ )
+ );
}
}
diff --git a/apps/mes/app/routes/x+/jobs.$workCenterId.tsx b/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
index c6c7b42aef..239ff90cc8 100644
--- a/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
+++ b/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
@@ -38,7 +38,7 @@ import {
getLocationAndWorkCenter,
setLocationAndWorkCenter,
} from "~/services/location.server";
-import { makeDurations } from "~/utils/jobs";
+import { makeDurations } from "~/utils/durations";
import { path } from "~/utils/path";
// TODO: it's possible that the location cookie and the work cell become out of sync.
diff --git a/apps/mes/app/routes/x+/recent.tsx b/apps/mes/app/routes/x+/recent.tsx
index cbee86df0c..3ae56c4818 100644
--- a/apps/mes/app/routes/x+/recent.tsx
+++ b/apps/mes/app/routes/x+/recent.tsx
@@ -7,7 +7,7 @@ import { useMemo, useState } from "react";
import { LuSearch } from "react-icons/lu";
import { OperationsList } from "~/components";
import { getRecentJobOperationsByEmployee } from "~/services/jobs.service";
-import { makeDurations } from "~/utils/jobs";
+import { makeDurations } from "~/utils/durations";
import { defaultLayout } from "~/utils/layout";
diff --git a/apps/mes/app/routes/x+/scrap.tsx b/apps/mes/app/routes/x+/scrap.tsx
new file mode 100644
index 0000000000..05ebbb85be
--- /dev/null
+++ b/apps/mes/app/routes/x+/scrap.tsx
@@ -0,0 +1,42 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+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/jobs.service";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "accounting",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(scrapQuantityValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const insertScrap = await insertScrapQuantity(client, {
+ ...validation.data,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (insertScrap.error) {
+ return json(
+ {},
+ await flash(request, error("Failed to record scrap quantity"))
+ );
+ }
+
+ return json(
+ insertScrap.data,
+ await flash(request, success("Scrap quantity recorded successfully"))
+ );
+}
diff --git a/apps/mes/app/services/jobs.service.ts b/apps/mes/app/services/jobs.service.ts
index 9a7b58c101..1fa5f3f4f3 100644
--- a/apps/mes/app/services/jobs.service.ts
+++ b/apps/mes/app/services/jobs.service.ts
@@ -48,6 +48,10 @@ export type ProductionEvent = NonNullable<
Awaited<ReturnType<typeof getProductionEventsForJobOperation>>["data"]
>[number];
+export type ProductionQuantity = NonNullable<
+ Awaited<ReturnType<typeof insertScrapQuantity>>["data"]
+>[number];
+
export type StorageItem = FileObject & {
bucket: string;
};
@@ -92,6 +96,16 @@ export const productionEventValidator = z.object({
workCenterId: zfd.text(z.string().optional()),
});
+export const scrapQuantityValidator = z.object({
+ jobOperationId: z.string(),
+ quantity: zfd.numeric(z.number().positive()),
+ unitOfMeasureCode: z.string().min(1),
+ setupProductionEventId: z.string().optional(),
+ laborProductionEventId: z.string().optional(),
+ machineProductionEventId: z.string().optional(),
+ scrapReason: z.string().min(1),
+});
+
export async function getActiveJobOperationsByEmployee(
client: SupabaseClient<Database>,
args: {
@@ -306,22 +320,35 @@ export async function getWorkCentersByCompany(
.order("name", { ascending: true });
}
+export async function insertScrapQuantity(
+ client: SupabaseClient<Database>,
+ data: z.infer<typeof scrapQuantityValidator> & {
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ return client
+ .from("productionQuantity")
+ .insert({
+ ...data,
+ type: "Scrap",
+ })
+ .select("*");
+}
+
export async function endProductionEvent(
client: SupabaseClient<Database>,
data: {
- jobOperationId: string;
- employeeId: string;
+ id: string;
endTime: string;
- type: (typeof productionEventType)[number];
+ employeeId: string;
}
) {
return client
.from("productionEvent")
.update({ endTime: data.endTime, updatedBy: data.employeeId })
- .eq("jobOperationId", data.jobOperationId)
- .eq("employeeId", data.employeeId)
- .eq("type", data.type)
- .is("endTime", null);
+ .eq("id", data.id)
+ .select("*");
}
export async function startProductionEvent(
diff --git a/apps/mes/app/services/operation.server.ts b/apps/mes/app/services/operation.server.ts
index f21a58bc2c..1d92543b48 100644
--- a/apps/mes/app/services/operation.server.ts
+++ b/apps/mes/app/services/operation.server.ts
@@ -3,7 +3,7 @@ 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 { makeDurations } from "~/utils/jobs";
+import { makeDurations } from "~/utils/durations";
import { path } from "~/utils/path";
import type { OperationWithDetails } from "./jobs.service";
import {
diff --git a/apps/mes/app/utils/jobs.ts b/apps/mes/app/utils/durations.ts
similarity index 100%
rename from apps/mes/app/utils/jobs.ts
rename to apps/mes/app/utils/durations.ts
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 21cdac86f6..b76c1d6692 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -35,6 +35,7 @@ export const path = {
refreshSession: "/refresh-session",
requestAccess: "/request-access",
root: "/",
+ scrap: `${x}/scrap`,
workCenter: (workCenter: string) => generatePath(`${x}/jobs/${workCenter}`),
},
} as const;
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index d8dd7b00a6..0188440038 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -28206,6 +28206,213 @@ export default {
tags: ["supplierShipping"],
},
},
+ "/productionQuantity": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.jobOperationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.unitOfMeasureCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.setupProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.laborProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.machineProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.scrapReason",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.updatedBy",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/productionQuantity",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["productionQuantity"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.productionQuantity",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["productionQuantity"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.jobOperationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.unitOfMeasureCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.setupProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.laborProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.machineProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.scrapReason",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.updatedBy",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["productionQuantity"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.jobOperationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.unitOfMeasureCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.setupProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.laborProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.machineProductionEventId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.scrapReason",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.productionQuantity.updatedBy",
+ },
+ {
+ $ref: "#/parameters/body.productionQuantity",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["productionQuantity"],
+ },
+ },
"/customerShipping": {
get: {
parameters: [
@@ -48344,6 +48551,86 @@ export default {
},
type: "object",
},
+ productionQuantity: {
+ required: [
+ "id",
+ "jobOperationId",
+ "quantity",
+ "unitOfMeasureCode",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ "updatedBy",
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ jobOperationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ quantity: {
+ format: "integer",
+ type: "integer",
+ },
+ unitOfMeasureCode: {
+ format: "text",
+ type: "string",
+ },
+ setupProductionEventId: {
+ description:
+ "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ laborProductionEventId: {
+ description:
+ "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ machineProductionEventId: {
+ description:
+ "Note:\nThis is a Foreign Key to `productionEvent.id`.<fk table='productionEvent' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ scrapReason: {
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ createdBy: {
+ format: "text",
+ type: "string",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
customerShipping: {
required: ["customerId", "companyId"],
properties: {
@@ -67586,6 +67873,106 @@ export default {
in: "query",
type: "string",
},
+ "body.productionQuantity": {
+ name: "productionQuantity",
+ description: "productionQuantity",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/productionQuantity",
+ },
+ },
+ "rowFilter.productionQuantity.id": {
+ name: "id",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.jobOperationId": {
+ name: "jobOperationId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.quantity": {
+ name: "quantity",
+ required: false,
+ format: "integer",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.unitOfMeasureCode": {
+ name: "unitOfMeasureCode",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.setupProductionEventId": {
+ name: "setupProductionEventId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.laborProductionEventId": {
+ name: "laborProductionEventId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.machineProductionEventId": {
+ name: "machineProductionEventId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.scrapReason": {
+ name: "scrapReason",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.companyId": {
+ name: "companyId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.createdAt": {
+ name: "createdAt",
+ required: false,
+ format: "timestamp with time zone",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.createdBy": {
+ name: "createdBy",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ format: "timestamp with time zone",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.productionQuantity.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"body.customerShipping": {
name: "customerShipping",
description: "customerShipping",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 0e0ab9dc69..6402ab4052 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -11700,6 +11700,118 @@ export type Database = {
},
]
}
+ productionQuantity: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ jobOperationId: string
+ laborProductionEventId: string | null
+ machineProductionEventId: string | null
+ quantity: number
+ scrapReason: string | null
+ setupProductionEventId: string | null
+ type: Database["public"]["Enums"]["productionQuantityType"]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ jobOperationId: string
+ laborProductionEventId?: string | null
+ machineProductionEventId?: string | null
+ quantity: number
+ scrapReason?: string | null
+ setupProductionEventId?: string | null
+ type?: Database["public"]["Enums"]["productionQuantityType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ jobOperationId?: string
+ laborProductionEventId?: string | null
+ machineProductionEventId?: string | null
+ quantity?: number
+ scrapReason?: string | null
+ setupProductionEventId?: string | null
+ type?: Database["public"]["Enums"]["productionQuantityType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "productionQuantity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "productionQuantity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "productionQuantity_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_laborProductionEventId_fkey"
+ columns: ["laborProductionEventId"]
+ isOneToOne: false
+ referencedRelation: "productionEvent"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_machineProductionEventId_fkey"
+ columns: ["machineProductionEventId"]
+ isOneToOne: false
+ referencedRelation: "productionEvent"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_setupProductionEventId_fkey"
+ columns: ["setupProductionEventId"]
+ isOneToOne: false
+ referencedRelation: "productionEvent"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
purchaseInvoice: {
Row: {
assignee: string | null
@@ -29518,6 +29630,7 @@ export type Database = {
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"
processType: "Inside" | "Outside" | "Inside and Outside"
productionEventType: "Setup" | "Labor" | "Machine"
+ productionQuantityType: "Rework" | "Scrap" | "Production"
purchaseInvoiceStatus:
| "Draft"
| "Pending"
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 87dc1b2641..7c474695cc 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -112,6 +112,7 @@ serve(async (req: Request) => {
.values(
sourceMaterials.data.map((material) => ({
...material,
+ productionQuantity: undefined,
id: undefined, // Let the database generate a new ID
makeMethodId: targetMakeMethod.data.id,
createdBy: userId,
@@ -1066,6 +1067,7 @@ serve(async (req: Request) => {
.values(
materialInserts.map((insert) => ({
...insert,
+ productionQuantity: undefined,
makeMethodId:
insert.makeMethodId ===
makeMethodByItemId[jobMakeMethod.data.itemId]
@@ -1240,6 +1242,7 @@ serve(async (req: Request) => {
.values(
materialInserts.map((insert) => ({
...insert,
+ productionQuantity: undefined,
makeMethodId:
insert.makeMethodId ===
makeMethodByItemId[jobMakeMethod.data.itemId]
@@ -1423,6 +1426,7 @@ serve(async (req: Request) => {
.values(
materialInserts.map((insert) => ({
...insert,
+ productionQuantity: undefined,
makeMethodId:
insert.makeMethodId ===
makeMethodByItemId[quoteMakeMethod.data.itemId]
@@ -1801,6 +1805,7 @@ serve(async (req: Request) => {
.values(
materialInserts.map((insert) => ({
...insert,
+ productionQuantity: undefined,
makeMethodId:
insert.makeMethodId ===
makeMethodByItemId[quoteMakeMethod.data.itemId]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 0e0ab9dc69..6402ab4052 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -11700,6 +11700,118 @@ export type Database = {
},
]
}
+ productionQuantity: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ jobOperationId: string
+ laborProductionEventId: string | null
+ machineProductionEventId: string | null
+ quantity: number
+ scrapReason: string | null
+ setupProductionEventId: string | null
+ type: Database["public"]["Enums"]["productionQuantityType"]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ jobOperationId: string
+ laborProductionEventId?: string | null
+ machineProductionEventId?: string | null
+ quantity: number
+ scrapReason?: string | null
+ setupProductionEventId?: string | null
+ type?: Database["public"]["Enums"]["productionQuantityType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ jobOperationId?: string
+ laborProductionEventId?: string | null
+ machineProductionEventId?: string | null
+ quantity?: number
+ scrapReason?: string | null
+ setupProductionEventId?: string | null
+ type?: Database["public"]["Enums"]["productionQuantityType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "productionQuantity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "productionQuantity_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "productionQuantity_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_laborProductionEventId_fkey"
+ columns: ["laborProductionEventId"]
+ isOneToOne: false
+ referencedRelation: "productionEvent"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_machineProductionEventId_fkey"
+ columns: ["machineProductionEventId"]
+ isOneToOne: false
+ referencedRelation: "productionEvent"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "productionQuantity_setupProductionEventId_fkey"
+ columns: ["setupProductionEventId"]
+ isOneToOne: false
+ referencedRelation: "productionEvent"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
purchaseInvoice: {
Row: {
assignee: string | null
@@ -29518,6 +29630,7 @@ export type Database = {
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"
processType: "Inside" | "Outside" | "Inside and Outside"
productionEventType: "Setup" | "Labor" | "Machine"
+ productionQuantityType: "Rework" | "Scrap" | "Production"
purchaseInvoiceStatus:
| "Draft"
| "Pending"
diff --git a/packages/database/supabase/migrations/20241002012019_production-quantities.sql b/packages/database/supabase/migrations/20241002012019_production-quantities.sql
new file mode 100644
index 0000000000..88630aad14
--- /dev/null
+++ b/packages/database/supabase/migrations/20241002012019_production-quantities.sql
@@ -0,0 +1,71 @@
+CREATE TYPE "productionQuantityType" AS ENUM (
+ 'Rework',
+ 'Scrap',
+ 'Production'
+);
+
+CREATE TABLE "productionQuantity" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "jobOperationId" TEXT NOT NULL,
+ "type" "productionQuantityType" NOT NULL DEFAULT 'Production',
+ "quantity" INTEGER NOT NULL,
+ "setupProductionEventId" TEXT,
+ "laborProductionEventId" TEXT,
+ "machineProductionEventId" TEXT,
+ "scrapReason" TEXT,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "productionQuantity_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "productionQuantity_jobOperationId_fkey" FOREIGN KEY ("jobOperationId") REFERENCES "jobOperation" ("id"),
+ CONSTRAINT "productionQuantity_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id"),
+ CONSTRAINT "productionQuantity_setupProductionEventId_fkey" FOREIGN KEY ("setupProductionEventId") REFERENCES "productionEvent" ("id"),
+ CONSTRAINT "productionQuantity_laborProductionEventId_fkey" FOREIGN KEY ("laborProductionEventId") REFERENCES "productionEvent" ("id"),
+ CONSTRAINT "productionQuantity_machineProductionEventId_fkey" FOREIGN KEY ("machineProductionEventId") REFERENCES "productionEvent" ("id")
+);
+
+CREATE INDEX "productionQuantity_jobOperationId_idx" ON "productionQuantity" ("jobOperationId");
+CREATE INDEX "productionQuantity_companyId_idx" ON "productionQuantity" ("companyId");
+CREATE INDEX "productionQuantity_setupProductionEventId_idx" ON "productionQuantity" ("setupProductionEventId");
+CREATE INDEX "productionQuantity_laborProductionEventId_idx" ON "productionQuantity" ("laborProductionEventId");
+CREATE INDEX "productionQuantity_machineProductionEventId_idx" ON "productionQuantity" ("machineProductionEventId");
+
+-- Enable Row Level Security for productionQuantity
+ALTER TABLE "productionQuantity" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees can view production quantities" ON "productionQuantity"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
+ )
+ );
+
+CREATE POLICY "Employees can insert production quantities" ON "productionQuantity"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
+ )
+);
+
+CREATE POLICY "Employees can update production quantities" ON "productionQuantity"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_update', "companyId")
+ );
+
+CREATE POLICY "Employees can delete production quantities" ON "productionQuantity"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
+ )
+ );
\ No newline at end of file
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsx
index 8276b6b1d5..0b4ef10a07 100644
--- a/packages/react/src/Button.tsx
+++ b/packages/react/src/Button.tsx
@@ -19,7 +19,7 @@ export const buttonVariants = cva(
"border border-input bg-card hover:bg-accent hover:text-accent-foreground",
solid: "bg-accent text-accent-foreground hover:bg-accent/90",
destructive:
- "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm shadow-[inset_0_2px_3px_0_theme(colors.white/15%)]",
+ "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm shadow-[inset_0_1px_2px_0_theme(colors.white/10%)]",
ghost:
"bg-transparent hover:bg-primary/10 text-accent-foreground hover:text-accent-foreground/90",
link: "text-foreground hover:text-foreground underline-offset-4 hover:underline",
diff --git a/packages/react/src/Toggle.tsx b/packages/react/src/Toggle.tsx
index c5c36f829d..4fa53fc0a5 100644
--- a/packages/react/src/Toggle.tsx
+++ b/packages/react/src/Toggle.tsx
@@ -8,7 +8,7 @@ import { forwardRef } from "react";
import { cn } from "./utils/cn";
const toggleVariants = cva(
- "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
+ "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-primary data-[state=on]:text-primary-foreground",
{
variants: {
variant: {
diff --git a/packages/react/src/hooks/index.ts b/packages/react/src/hooks/index.ts
index 0cacc1dbf4..42d75141c9 100644
--- a/packages/react/src/hooks/index.ts
+++ b/packages/react/src/hooks/index.ts
@@ -3,7 +3,7 @@ import useDisclosure from "./useDisclosure";
import useEscape from "./useEscape";
import useHydrated from "./useHydrated";
import useInitialDimensions from "./useInitialDimenions";
-import useInterval from "./useInterval";
+import { useInterval } from "./useInterval";
import useKeyboardShortcuts from "./useKeyboardShortcuts";
import useLocalStorage from "./useLocalStorage";
import useMount from "./useMount";
diff --git a/packages/react/src/hooks/useInterval.ts b/packages/react/src/hooks/useInterval.ts
index 3cdc34f3d3..d0fa679f30 100644
--- a/packages/react/src/hooks/useInterval.ts
+++ b/packages/react/src/hooks/useInterval.ts
@@ -1,26 +1,43 @@
import { useEffect, useRef } from "react";
+import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect";
+
/**
- * useInterval
- * @param callback
- * @param delay - in seconds
+ * Custom hook that creates an interval that invokes a callback function at a specified delay using the [`setInterval API`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval).
+ * @param {() => void} callback - The function to be invoked at each interval.
+ * @param {number | null} delay - The time, in milliseconds, between each invocation of the callback. Use `null` to clear the interval.
+ * @public
+ * @see [Documentation](https://usehooks-ts.com/react-hook/use-interval)
+ * @example
+ * ```tsx
+ * const handleInterval = () => {
+ * // Code to be executed at each interval
+ * };
+ * useInterval(handleInterval, 1000);
+ * ```
*/
-export default function useInterval(callback: () => void, delay?: number) {
- const savedCallback = useRef<() => void>();
+export function useInterval(callback: () => void, delay: number | null) {
+ const savedCallback = useRef(callback);
- // Remember the latest callback.
- useEffect(() => {
+ // Remember the latest callback if it changes.
+ useIsomorphicLayoutEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
- function tick() {
- savedCallback.current?.();
- }
- if (delay) {
- const id = setInterval(tick, delay * 1_000);
- return () => clearInterval(id);
+ // Don't schedule if no delay is specified.
+ // Note: 0 is a valid value for delay.
+ if (delay === null) {
+ return;
}
+
+ const id = setInterval(() => {
+ savedCallback.current();
+ }, delay);
+
+ return () => {
+ clearInterval(id);
+ };
}, [delay]);
}
diff --git a/packages/react/src/hooks/useIsomorphicLayoutEffect.tsx b/packages/react/src/hooks/useIsomorphicLayoutEffect.tsx
new file mode 100644
index 0000000000..0c6122cbd6
--- /dev/null
+++ b/packages/react/src/hooks/useIsomorphicLayoutEffect.tsx
@@ -0,0 +1,17 @@
+import { useEffect, useLayoutEffect } from "react";
+
+/**
+ * Custom hook that uses either `useLayoutEffect` or `useEffect` based on the environment (client-side or server-side).
+ * @param {Function} effect - The effect function to be executed.
+ * @param {Array<any>} [dependencies] - An array of dependencies for the effect (optional).
+ * @public
+ * @see [Documentation](https://usehooks-ts.com/react-hook/use-isomorphic-layout-effect)
+ * @example
+ * ```tsx
+ * useIsomorphicLayoutEffect(() => {
+ * // Code to be executed during the layout phase on the client side
+ * }, [dependency1, dependency2]);
+ * ```
+ */
+export const useIsomorphicLayoutEffect =
+ typeof window !== "undefined" ? useLayoutEffect : useEffect;
diff --git a/packages/utils/src/duration.ts b/packages/utils/src/duration.ts
index a1750bea71..d35030a01d 100644
--- a/packages/utils/src/duration.ts
+++ b/packages/utils/src/duration.ts
@@ -44,7 +44,7 @@ export function formatDurationMilliseconds(
: milliseconds < 1000
? belowOneSecondUnits
: aboveOneSecondUnits,
- maxDecimalPoints: options?.maxDecimalPoints ?? 1,
+ maxDecimalPoints: options?.maxDecimalPoints ?? 0,
largest: 2,
});