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 records to gauge drawer

Brad Barbin38c267b3ee4f
diff --git a/apps/erp/app/components/Form/Gauge.tsx b/apps/erp/app/components/Form/Gauge.tsx
new file mode 100644
index 0000000000..ecf5002327
--- /dev/null
+++ b/apps/erp/app/components/Form/Gauge.tsx
@@ -0,0 +1,94 @@
+import type { ComboboxProps } from "@carbon/form";
+import { CreatableCombobox } from "@carbon/form";
+import { useDisclosure, useMount } from "@carbon/react";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import { useFetcher } from "@remix-run/react";
+import { useMemo, useRef, useState } from "react";
+import { useUser } from "~/hooks";
+import type { getGaugesList, getGaugeTypesList } from "~/modules/quality";
+import GaugeForm from "~/modules/quality/ui/Gauge/GaugeForm";
+
+import { path } from "~/utils/path";
+
+type GaugeSelectProps = Omit<ComboboxProps, "options">;
+
+const Gauge = (props: GaugeSelectProps) => {
+ const newGaugeModal = useDisclosure();
+ const [created, setCreated] = useState<string>("");
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ const { options, gaugeTypes } = useGauges();
+ const { defaults } = useUser();
+
+ return (
+ <>
+ <CreatableCombobox
+ ref={triggerRef}
+ options={options}
+ {...props}
+ label={props?.label ?? "Gauge"}
+ onCreateOption={(option) => {
+ newGaugeModal.onOpen();
+ setCreated(option);
+ }}
+ />
+ {newGaugeModal.isOpen && (
+ <GaugeForm
+ type="modal"
+ onClose={() => {
+ setCreated("");
+ newGaugeModal.onClose();
+ triggerRef.current?.click();
+ }}
+ gaugeTypes={gaugeTypes}
+ initialValues={{
+ id: undefined,
+ gaugeId: undefined,
+ supplierId: "",
+ modelNumber: "",
+ serialNumber: "",
+ description: created,
+ dateAcquired: today(getLocalTimeZone()).toString(),
+ gaugeTypeId: "",
+
+ lastCalibrationDate: "",
+ nextCalibrationDate: "",
+ locationId: defaults.locationId ?? "",
+ shelfId: "",
+ calibrationIntervalInMonths: 6,
+ gaugeRole: "Standard" as const,
+ }}
+ />
+ )}
+ </>
+ );
+};
+
+Gauge.displayName = "Gauge";
+
+export default Gauge;
+
+export const useGauges = () => {
+ const gaugeFetcher = useFetcher<{
+ gauges: Awaited<ReturnType<typeof getGaugesList>>["data"];
+ gaugeTypes: Awaited<ReturnType<typeof getGaugeTypesList>>["data"];
+ }>();
+
+ useMount(() => {
+ gaugeFetcher.load(path.to.api.gauges);
+ });
+
+ const options = useMemo(
+ () =>
+ gaugeFetcher.data?.gauges
+ ? gaugeFetcher.data?.gauges.map((c) => ({
+ value: c.id,
+ label: c.name,
+ helper: c.description ?? undefined,
+ }))
+ : [],
+ [gaugeFetcher.data]
+ );
+
+ return { options, gaugeTypes: gaugeFetcher.data?.gaugeTypes ?? [] };
+};
diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.ts
index 7f6bd24421..241a124b25 100644
--- a/apps/erp/app/modules/quality/quality.models.ts
+++ b/apps/erp/app/modules/quality/quality.models.ts
@@ -92,7 +92,16 @@ export const gaugeCalibrationRecordValidator = z.object({
requiresAction: zfd.checkbox(),
requiresAdjustment: zfd.checkbox(),
requiresRepair: zfd.checkbox(),
- notes: zfd.text(z.string().optional()),
+ notes: z
+ .string()
+ .optional()
+ .transform((val) => {
+ try {
+ return val ? JSON.parse(val) : {};
+ } catch (e) {
+ return {};
+ }
+ }),
});
export const gaugeTypeValidator = z.object({
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 0eb1e1b581..5afb728867 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -199,6 +199,16 @@ export async function getGaugeCalibrationRecords(
return query;
}
+export async function getGaugeCalibrationRecordsByGaugeId(
+ client: SupabaseClient<Database>,
+ gaugeId: string
+) {
+ return client
+ .from("gaugeCalibrationRecords")
+ .select("*")
+ .eq("gaugeId", gaugeId);
+}
+
export async function getGaugeTypesList(
client: SupabaseClient<Database>,
companyId: string
diff --git a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx
new file mode 100644
index 0000000000..553c3d1ed5
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx
@@ -0,0 +1,338 @@
+import { useCarbon } from "@carbon/auth";
+import { Boolean, DatePicker, ValidatedForm } from "@carbon/form";
+import type { JSONContent } from "@carbon/react";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Combobox,
+ HStack,
+ Label,
+ Loading,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ toast,
+ useDisclosure,
+ VStack,
+} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useState } from "react";
+import { flushSync } from "react-dom";
+import { LuDraftingCompass, LuHash, LuShapes, LuShield } from "react-icons/lu";
+import type { z } from "zod";
+import { Enumerable } from "~/components/Enumerable";
+import { Hidden, Submit } from "~/components/Form";
+import { useGauges } from "~/components/Form/Gauge";
+import { usePermissions, useUser } from "~/hooks";
+
+import { Editor } from "@carbon/react/Editor";
+import { nanoid } from "nanoid";
+import { getPrivateUrl, path } from "~/utils/path";
+import { gaugeCalibrationRecordValidator } from "../../quality.models";
+import type { Gauge } from "../../types";
+import { GaugeRole } from "../Gauge/GaugeStatus";
+
+type GaugeCalibrationRecordFormValues = z.infer<
+ typeof gaugeCalibrationRecordValidator
+>;
+
+type GaugeCalibrationRecordFormProps = {
+ initialValues: GaugeCalibrationRecordFormValues;
+ type?: "modal" | "drawer";
+ open?: boolean;
+ onClose?: () => void;
+};
+
+const GaugeCalibrationRecordForm = ({
+ initialValues,
+ open = true,
+ type = "drawer",
+ onClose,
+}: GaugeCalibrationRecordFormProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<{}>();
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "quality")
+ : !permissions.can("create", "quality");
+
+ const [selectedGauge, setSelectedGauge] = useState<Gauge | null>(null);
+ const gaugeSelectionModal = useDisclosure({
+ defaultIsOpen: !initialValues.gaugeId,
+ });
+ const [loading, setLoading] = useState(false);
+
+ const { carbon } = useCarbon();
+ const { options: gaugeOptions, gaugeTypes } = useGauges();
+
+ useEffect(() => {
+ if (initialValues.gaugeId) {
+ onGaugeSelected(initialValues.gaugeId);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [initialValues.gaugeId]);
+
+ const onGaugeSelected = async (gaugeId: string) => {
+ flushSync(() => {
+ setLoading(true);
+ });
+ const result = await carbon
+ ?.from("gauges")
+ .select("*")
+ .eq("id", gaugeId)
+ .single();
+ if (!result?.data) {
+ toast.error("Gauge not found");
+ setSelectedGauge(null);
+ setLoading(false);
+ return;
+ }
+ setSelectedGauge(result.data);
+ setLoading(false);
+ };
+
+ const [notes, setNotes] = useState<JSONContent>(
+ (JSON.parse(initialValues?.notes ?? {}) as JSONContent) ?? {}
+ );
+
+ const {
+ company: { id: companyId },
+ } = useUser();
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/quality/${nanoid()}.${fileType}`;
+
+ const result = await carbon?.storage.from("private").upload(fileName, file);
+
+ if (result?.error) {
+ toast.error("Failed to upload image");
+ throw new Error(result.error.message);
+ }
+
+ if (!result?.data) {
+ throw new Error("Failed to upload image");
+ }
+
+ return getPrivateUrl(result.data.path);
+ };
+
+ return (
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open && onClose) onClose();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ method="post"
+ validator={gaugeCalibrationRecordValidator}
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ action={
+ isEditing
+ ? path.to.gaugeCalibrationRecord(initialValues.id!)
+ : path.to.newGaugeCalibrationRecord
+ }
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing
+ ? "Edit Gauge Calibration Record"
+ : "New Gauge Calibration Record"}
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <Hidden name="notes" value={JSON.stringify(notes)} />
+
+ <VStack spacing={4}>
+ <Card className="p-2">
+ <Loading isLoading={loading}>
+ <HStack className="w-full justify-between">
+ <CardHeader>
+ <CardTitle>
+ {selectedGauge?.gaugeId ?? "No Gauge Selected"}
+ </CardTitle>
+ {selectedGauge?.description && (
+ <CardDescription>
+ {selectedGauge.description}
+ </CardDescription>
+ )}
+ <Hidden
+ name="gaugeId"
+ value={
+ selectedGauge?.id ?? initialValues.gaugeId ?? ""
+ }
+ />
+ </CardHeader>
+ <CardAction>
+ <Button
+ leftIcon={<LuDraftingCompass />}
+ variant="secondary"
+ onClick={gaugeSelectionModal.onOpen}
+ >
+ Select Gauge
+ </Button>
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <VStack>
+ {selectedGauge && (
+ <div className="w-full space-y-2 text-xs">
+ <div className="flex flex-col gap-4 py-2">
+ {selectedGauge.modelNumber && (
+ <div className="flex items-center gap-2">
+ <LuHash className="text-muted-foreground" />
+ <span className="font-medium">
+ Model Number:
+ </span>
+ <span>
+ {selectedGauge.modelNumber || "N/A"}
+ </span>
+ </div>
+ )}
+ {selectedGauge.serialNumber && (
+ <div className="flex items-center gap-2">
+ <LuHash className="text-muted-foreground" />
+ <span className="font-medium">
+ Serial Number:
+ </span>
+ <span>
+ {selectedGauge.serialNumber || "N/A"}
+ </span>
+ </div>
+ )}
+ </div>
+ <div className="flex flex-col gap-4">
+ <div className="flex items-center gap-2">
+ <LuShield className="text-muted-foreground" />
+ <span className="font-medium">Role:</span>
+ <GaugeRole role={selectedGauge.gaugeRole} />
+ </div>
+ <div className="flex items-center gap-2">
+ <LuShapes className="text-muted-foreground" />
+ <span className="font-medium">Type:</span>
+ <Enumerable
+ value={
+ gaugeTypes.find(
+ (type) =>
+ type.id === selectedGauge.gaugeTypeId
+ )?.name ?? null
+ }
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ </VStack>
+ </CardContent>
+ </Loading>
+ </Card>
+ <DatePicker name="dateCalibrated" label="Date Calibrated" />
+ <Boolean name="requiresAction" label="Requires Action" />
+ <Boolean
+ name="requiresAdjustment"
+ label="Requires Adjustment"
+ />
+ <Boolean name="requiresRepair" label="Requires Repair" />
+ <div className="flex flex-col gap-2 w-full">
+ <Label>Notes</Label>
+ <Editor
+ initialValue={notes}
+ onUpload={onUploadImage}
+ onChange={(value) => {
+ setNotes(value);
+ }}
+ className="[&_.is-empty]:text-muted-foreground min-h-[120px] py-3 px-4 border rounded-md w-full"
+ />
+ </div>
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ {onClose && (
+ <Button size="md" variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ )}
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ {gaugeSelectionModal.isOpen && (
+ <Modal
+ open={gaugeSelectionModal.isOpen}
+ onOpenChange={(open) => {
+ if (!open) gaugeSelectionModal.onClose();
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Select Gauge</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack className="w-full">
+ <div className="w-full">
+ <Combobox
+ options={gaugeOptions}
+ onChange={(value) => {
+ onGaugeSelected(value);
+ gaugeSelectionModal.onClose();
+ }}
+ value={
+ selectedGauge?.id ?? initialValues.gaugeId ?? undefined
+ }
+ size="lg"
+ />
+ </div>
+ </VStack>
+ <ModalFooter>
+ <Button
+ variant="secondary"
+ onClick={() => {
+ if (
+ selectedGauge &&
+ selectedGauge.id !== initialValues.gaugeId
+ ) {
+ onGaugeSelected(initialValues.gaugeId!);
+ } else {
+ setSelectedGauge(null);
+ }
+ gaugeSelectionModal.onClose();
+ }}
+ >
+ Cancel
+ </Button>
+ <Button onClick={gaugeSelectionModal.onClose}>Confirm</Button>
+ </ModalFooter>
+ </ModalBody>
+ </ModalContent>
+ </Modal>
+ )}
+ </ModalDrawerProvider>
+ );
+};
+
+export default GaugeCalibrationRecordForm;
diff --git a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordStatus.tsx b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordStatus.tsx
new file mode 100644
index 0000000000..97a7295c82
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordStatus.tsx
@@ -0,0 +1,21 @@
+import type { Database } from "@carbon/database";
+import { Status } from "@carbon/react";
+
+type GaugeCalibrationRecordStatusProps = {
+ status?: Database["public"]["Enums"]["inspectionStatus"] | null;
+};
+
+const GaugeCalibrationRecordStatus = ({
+ status,
+}: GaugeCalibrationRecordStatusProps) => {
+ switch (status) {
+ case "Pass":
+ return <Status color="green">{status}</Status>;
+ case "Fail":
+ return <Status color="red">{status}</Status>;
+ default:
+ return null;
+ }
+};
+
+export { GaugeCalibrationRecordStatus };
diff --git a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx
new file mode 100644
index 0000000000..c288ab6e08
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx
@@ -0,0 +1,314 @@
+import { Checkbox, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo, useState } from "react";
+import {
+ LuBookMarked,
+ LuCalendar,
+ LuCheck,
+ LuFileText,
+ LuPencil,
+ LuShapes,
+ LuTrash,
+ LuUser,
+ LuUsers,
+} from "react-icons/lu";
+import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+
+import { flushSync } from "react-dom";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { ListItem } from "~/types";
+import { path } from "~/utils/path";
+import type { GaugeCalibrationRecord } from "../../types";
+
+import { formatDate } from "@carbon/utils";
+import { Enumerable } from "~/components/Enumerable";
+import { useCustomColumns } from "~/hooks/useCustomColumns";
+import { usePeople } from "~/stores";
+import { GaugeCalibrationRecordStatus } from "./GaugeCalibrationRecordStatus";
+
+type GaugeCalibrationRecordsTableProps = {
+ data: GaugeCalibrationRecord[];
+ types: ListItem[];
+ count: number;
+};
+
+const defaultColumnVisibility = {
+ gaugeTypeId: false,
+ createdAt: false,
+ updatedAt: false,
+ updatedBy: false,
+};
+
+const GaugeCalibrationRecordsTable = memo(
+ ({ data, types, count }: GaugeCalibrationRecordsTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const deleteDisclosure = useDisclosure();
+ const [selectedGaugeCalibrationRecord, setSelectedGaugeCalibrationRecord] =
+ useState<GaugeCalibrationRecord | null>(null);
+
+ const customColumns = useCustomColumns<GaugeCalibrationRecord>(
+ "gaugeCalibrationRecord"
+ );
+
+ const [people] = usePeople();
+
+ const columns = useMemo<ColumnDef<GaugeCalibrationRecord>[]>(() => {
+ const defaultColumns: ColumnDef<GaugeCalibrationRecord>[] = [
+ {
+ accessorKey: "gaugeId",
+ header: "ID",
+ cell: ({ row }) => (
+ <Hyperlink to={path.to.gaugeCalibrationRecord(row.original.id!)}>
+ <div className="flex flex-col gap-0">
+ <span className="text-sm font-medium">
+ {row.original.gaugeReadableId}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {row.original.description}
+ </span>
+ </div>
+ </Hyperlink>
+ ),
+ meta: {
+ icon: <LuBookMarked />,
+ },
+ },
+ {
+ accessorKey: "dateCalibrated",
+ header: "Date Calibrated",
+ cell: (item) => formatDate(item.getValue<string>()),
+ meta: {
+ icon: <LuCalendar />,
+ },
+ },
+ {
+ accessorKey: "inspectionStatus",
+ header: "Inspection Status",
+ cell: (item) => (
+ <GaugeCalibrationRecordStatus
+ status={item.getValue<string>() as "Pass" | "Fail"}
+ />
+ ),
+ meta: {
+ icon: <LuCheck />,
+ filter: {
+ type: "static",
+ options: [
+ {
+ value: "Pass",
+ label: <GaugeCalibrationRecordStatus status="Pass" />,
+ },
+ {
+ value: "Fail",
+ label: <GaugeCalibrationRecordStatus status="Fail" />,
+ },
+ ],
+ },
+ },
+ },
+ {
+ accessorKey: "gaugeTypeId",
+ header: "Type",
+ cell: ({ row }) => (
+ <Enumerable
+ value={
+ types.find((type) => type.id === row.original.gaugeTypeId)
+ ?.name ?? null
+ }
+ />
+ ),
+ meta: {
+ icon: <LuShapes />,
+ filter: {
+ type: "static",
+ options: types.map((type) => ({
+ label: <Enumerable value={type.name} />,
+ value: type.id,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "requiresAction",
+ header: "Requires Action",
+ cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { value: "true", label: "Yes" },
+ { value: "false", label: "No" },
+ ],
+ },
+ icon: <LuCheck />,
+ },
+ },
+ {
+ accessorKey: "requiresAdjustment",
+ header: "Requires Adjustment",
+ cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { value: "true", label: "Yes" },
+ { value: "false", label: "No" },
+ ],
+ },
+ icon: <LuCheck />,
+ },
+ },
+ {
+ accessorKey: "requiresRepair",
+ header: "Requires Repair",
+ cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { value: "true", label: "Yes" },
+ { value: "false", label: "No" },
+ ],
+ },
+ icon: <LuCheck />,
+ },
+ },
+ {
+ id: "createdBy",
+ header: "Created By",
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.createdBy} />
+ ),
+ meta: {
+ icon: <LuUser />,
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created At",
+ cell: (item) => formatDate(item.getValue<string>()),
+ meta: {
+ icon: <LuFileText />,
+ },
+ },
+ {
+ id: "updatedBy",
+ header: "Updated By",
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.updatedBy} />
+ ),
+ meta: {
+ icon: <LuUsers />,
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "updatedAt",
+ header: "Updated At",
+ cell: (item) => formatDate(item.getValue<string>()),
+ meta: {
+ icon: <LuFileText />,
+ },
+ },
+ ];
+ return [...defaultColumns, ...customColumns];
+ }, [customColumns, people, types]);
+
+ const renderContextMenu = useCallback(
+ (row: GaugeCalibrationRecord) => {
+ return (
+ <>
+ <MenuItem
+ disabled={!permissions.can("update", "quality")}
+ onClick={() => {
+ navigate(`${path.to.gauge(row.id!)}?${params?.toString()}`);
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Record
+ </MenuItem>
+ <MenuItem
+ destructive
+ disabled={!permissions.can("delete", "quality")}
+ onClick={() => {
+ flushSync(() => {
+ setSelectedGaugeCalibrationRecord(row);
+ });
+ deleteDisclosure.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Record
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, permissions, deleteDisclosure, params]
+ );
+
+ return (
+ <>
+ <Table<GaugeCalibrationRecord>
+ data={data}
+ columns={columns}
+ count={count}
+ defaultColumnVisibility={defaultColumnVisibility}
+ primaryAction={
+ permissions.can("create", "quality") && (
+ <New
+ label="Record"
+ to={`${
+ path.to.newGaugeCalibrationRecord
+ }?${params?.toString()}`}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title="Calibration Records"
+ table="gaugeCalibrationRecord"
+ withSavedView
+ />
+ {deleteDisclosure.isOpen && selectedGaugeCalibrationRecord && (
+ <ConfirmDelete
+ action={path.to.deleteGaugeCalibrationRecord(
+ selectedGaugeCalibrationRecord.id!
+ )}
+ isOpen
+ onCancel={() => {
+ setSelectedGaugeCalibrationRecord(null);
+ deleteDisclosure.onClose();
+ }}
+ onSubmit={() => {
+ setSelectedGaugeCalibrationRecord(null);
+ deleteDisclosure.onClose();
+ }}
+ name={`record for ${
+ selectedGaugeCalibrationRecord.gaugeId ?? "gauge"
+ }`}
+ text="Are you sure you want to delete this record?"
+ />
+ )}
+ </>
+ );
+ }
+);
+
+GaugeCalibrationRecordsTable.displayName = "GaugeCalibrationRecordsTable";
+export default GaugeCalibrationRecordsTable;
diff --git a/apps/erp/app/modules/quality/ui/Gauge/GaugeForm.tsx b/apps/erp/app/modules/quality/ui/Gauge/GaugeForm.tsx
index 02e8d41c39..9fdb682a23 100644
--- a/apps/erp/app/modules/quality/ui/Gauge/GaugeForm.tsx
+++ b/apps/erp/app/modules/quality/ui/Gauge/GaugeForm.tsx
@@ -1,7 +1,13 @@
import { DatePicker, Select, ValidatedForm } from "@carbon/form";
import {
Button,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
HStack,
+ IconButton,
ModalDrawer,
ModalDrawerBody,
ModalDrawerContent,
@@ -9,13 +15,26 @@ import {
ModalDrawerHeader,
ModalDrawerProvider,
ModalDrawerTitle,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ useDisclosure,
VStack,
} from "@carbon/react";
-import { parseDate } from "@internationalized/date";
-import { useFetcher } from "@remix-run/react";
-import { useState } from "react";
-import { LuCalendar } from "react-icons/lu";
+import { formatRelativeTime } from "@carbon/utils";
+import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
+import { Await, Link, useFetcher } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { Suspense, useState } from "react";
+import {
+ LuCalendar,
+ LuCircleGauge,
+ LuCirclePlus,
+ LuEllipsisVertical,
+} from "react-icons/lu";
import type { z } from "zod";
+import { EmployeeAvatar, Empty } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import {
CustomFormFields,
@@ -32,6 +51,8 @@ import { usePermissions } from "~/hooks";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
import { gaugeRole, gaugeValidator } from "../../quality.models";
+import type { GaugeCalibrationRecord } from "../../types";
+import GaugeCalibrationRecordForm from "../Calibrations/GaugeCalibrationRecordForm";
import { GaugeRole } from "./GaugeStatus";
type GaugeFormValues = z.infer<typeof gaugeValidator>;
@@ -39,6 +60,7 @@ type GaugeFormValues = z.infer<typeof gaugeValidator>;
type GaugeFormProps = {
initialValues: GaugeFormValues;
gaugeTypes: ListItem[];
+ records?: Promise<PostgrestResponse<GaugeCalibrationRecord>>;
type?: "modal" | "drawer";
open?: boolean;
onClose?: () => void;
@@ -47,6 +69,7 @@ type GaugeFormProps = {
const GaugeForm = ({
initialValues,
gaugeTypes,
+ records,
open = true,
type = "drawer",
onClose,
@@ -64,159 +87,377 @@ const GaugeForm = ({
calibrationIntervalInMonths: initialValues.calibrationIntervalInMonths ?? 6,
});
+ const [activeTab, setActiveTab] = useState<string>("gauge");
+ const newRecordDisclosure = useDisclosure();
+
return (
- <ModalDrawerProvider type={type}>
- <ModalDrawer
- open={open}
- onOpenChange={(open) => {
- if (!open && onClose) onClose();
- }}
- >
- <ModalDrawerContent size="lg">
- <ValidatedForm
- method="post"
- validator={gaugeValidator}
- defaultValues={initialValues}
- fetcher={fetcher}
- action={
- isEditing ? path.to.gauge(initialValues.id!) : path.to.newGauge
- }
- className="flex flex-col h-full"
- >
- <ModalDrawerHeader>
- <ModalDrawerTitle>
- {isEditing ? "Edit Gauge" : "New Gauge"}
- </ModalDrawerTitle>
- </ModalDrawerHeader>
- <ModalDrawerBody>
- <Hidden name="id" />
- <Hidden name="type" value={type} />
+ <>
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open && onClose) onClose();
+ }}
+ >
+ <ModalDrawerContent size="lg">
+ <Tabs
+ value={activeTab}
+ onValueChange={setActiveTab}
+ className="flex flex-col h-full"
+ >
+ <ValidatedForm
+ method="post"
+ validator={gaugeValidator}
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ action={
+ isEditing
+ ? path.to.gauge(initialValues.id!)
+ : path.to.newGauge
+ }
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader className="flex flex-col gap-4">
+ <HStack className="w-full justify-between pr-8">
+ <ModalDrawerTitle>
+ {isEditing ? `${initialValues.gaugeId}` : "New Gauge"}
+ </ModalDrawerTitle>
+
+ {isEditing && (
+ <div>
+ <TabsList>
+ <TabsTrigger value="gauge">Details</TabsTrigger>
+ <TabsTrigger value="records">
+ Calibration Records
+ </TabsTrigger>
+ </TabsList>
+ </div>
+ )}
+ </HStack>
+ </ModalDrawerHeader>
+ <ModalDrawerBody className="w-full">
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
- <VStack spacing={4}>
- <div className="grid w-full gap-4 grid-cols-1 md:grid-cols-2">
{isEditing ? (
- <Input name="gaugeId" label="Gauge ID" isReadOnly />
+ <>
+ <TabsContent value="gauge" className="w-full">
+ <GaugeFormContent
+ isEditing={isEditing}
+ gaugeTypes={gaugeTypes}
+ initialValues={initialValues}
+ calibrationInterval={calibrationInterval}
+ setCalibrationInterval={setCalibrationInterval}
+ />
+ </TabsContent>
+ <TabsContent
+ value="records"
+ className="w-full flex flex-col gap-4"
+ >
+ <div className="flex justify-end">
+ <Button
+ leftIcon={<LuCirclePlus />}
+ onClick={newRecordDisclosure.onOpen}
+ >
+ Add Calibration Record
+ </Button>
+ </div>
+ {records && (
+ <Suspense fallback={null}>
+ <Await resolve={records}>
+ {(resolvedRecords) => (
+ <VStack spacing={4} className="w-full">
+ {Array.isArray(resolvedRecords.data) &&
+ resolvedRecords.data.length > 0 ? (
+ <div className="border rounded-lg w-full">
+ {resolvedRecords.data.map(
+ (record, index) => {
+ const isUpdated =
+ record.updatedBy !== null;
+ const person = isUpdated
+ ? record.updatedBy
+ : record.createdBy;
+ const date = isUpdated
+ ? record.updatedAt
+ : record.createdAt;
+ return (
+ <div
+ key={record.id}
+ className={cn(
+ "border-b p-6",
+ index ===
+ (resolvedRecords.data
+ ?.length ?? 0) -
+ 1 && "border-none"
+ )}
+ >
+ <div className="flex flex-1 justify-between items-center w-full">
+ <HStack
+ spacing={4}
+ className="w-1/2"
+ >
+ <HStack
+ spacing={4}
+ className="flex-1"
+ >
+ <div
+ className={cn(
+ "rounded-full flex items-center justify-center p-2",
+ record.inspectionStatus ===
+ "Pass"
+ ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-400"
+ : "bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-400"
+ )}
+ >
+ <LuCircleGauge className="size-4" />
+ </div>
+ <VStack spacing={0}>
+ <p className="text-foreground text-sm font-medium">
+ {
+ record.inspectionStatus
+ }
+ </p>
+ <span className="text-xs text-muted-foreground">
+ Calibration Record
+ </span>
+ </VStack>
+ </HStack>
+ </HStack>
+ <div className="flex items-center justify-end gap-2">
+ <HStack spacing={2}>
+ <span className="text-xs text-muted-foreground">
+ {date
+ ? isUpdated
+ ? "Updated"
+ : "Created"
+ : null}{" "}
+ {date
+ ? formatRelativeTime(
+ date
+ )
+ : null}
+ </span>
+ <EmployeeAvatar
+ employeeId={person}
+ withName={false}
+ />
+ </HStack>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ asChild
+ >
+ <IconButton
+ aria-label="Open menu"
+ icon={
+ <LuEllipsisVertical />
+ }
+ variant="ghost"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem asChild>
+ <Link
+ to={path.to.gaugeCalibrationRecord(
+ record.id!
+ )}
+ >
+ View
+ </Link>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ </div>
+ );
+ }
+ )}
+ </div>
+ ) : (
+ <div className="py-16 w-full">
+ <Empty title="No calibration records found" />
+ </div>
+ )}
+ </VStack>
+ )}
+ </Await>
+ </Suspense>
+ )}
+ </TabsContent>
+ </>
) : (
- <SequenceOrCustomId
- name="gaugeId"
- label="Gauge ID"
- table="gauge"
+ <GaugeFormContent
+ isEditing={isEditing}
+ gaugeTypes={gaugeTypes}
+ initialValues={initialValues}
+ calibrationInterval={calibrationInterval}
+ setCalibrationInterval={setCalibrationInterval}
/>
)}
- <Input name="description" label="Description" />
- <Select
- name="gaugeTypeId"
- label="Gauge Type"
- options={gaugeTypes.map((type) => ({
- label: <Enumerable value={type.name} />,
- value: type.id,
- }))}
- />
- <Supplier name="supplierId" label="Supplier" />
- <Input name="modelNumber" label="Model Number" />
- <Input name="serialNumber" label="Serial Number" />
- {/* <Select
- name="gaugeCalibrationStatus"
- label="Calibration Status"
- options={gaugeCalibrationStatus.map((status) => ({
- label: <GaugeCalibrationStatus status={status} />,
- value: status,
- }))}
- /> */}
- <Select
- name="gaugeRole"
- label="Role"
- options={gaugeRole.map((role) => ({
- label: <GaugeRole role={role} />,
- value: role,
- }))}
- />
- <DatePicker name="dateAcquired" label="Date Acquired" />
- {/* <Select
- name="gaugeStatus"
- label="Status"
- options={gaugeStatus.map((status) => ({
- label: <GaugeStatus status={status} />,
- value: status,
- }))}
- /> */}
- <DatePicker
- name="lastCalibrationDate"
- label="Last Calibration Date"
- value={calibrationInterval.lastCalibrationDate}
- onChange={(value) => {
- setCalibrationInterval({
- ...calibrationInterval,
- lastCalibrationDate: value?.toString(),
- nextCalibrationDate: value
- ? parseDate(value?.toString())
- .add({
- months:
- calibrationInterval.calibrationIntervalInMonths,
- })
- .toString()
- : undefined,
- });
- }}
- />
- <DatePicker
- name="nextCalibrationDate"
- label="Next Calibration Date"
- value={calibrationInterval.nextCalibrationDate}
- onChange={(value) => {
- setCalibrationInterval({
- ...calibrationInterval,
- nextCalibrationDate: value?.toString(),
- });
- }}
- />
- <Location name="locationId" label="Location" />
- <Shelf
- name="shelfId"
- label="Shelf"
- locationId={initialValues.locationId}
- />
- <CustomFormFields table="gauge" />
- </div>
- <div className="border bg-muted/30 rounded-lg p-4 relative w-full">
- <LuCalendar className="absolute top-2 right-4 text-muted-foreground" />
- <NumberControlled
- name="calibrationIntervalInMonths"
- label="Calibration Interval (Months)"
- value={calibrationInterval.calibrationIntervalInMonths}
- onChange={(value) => {
- setCalibrationInterval({
- ...calibrationInterval,
- calibrationIntervalInMonths: value,
- nextCalibrationDate:
- calibrationInterval.lastCalibrationDate
- ? parseDate(calibrationInterval.lastCalibrationDate)
- .add({
- months: value,
- })
- .toString()
- : undefined,
- });
- }}
- />
- </div>
- </VStack>
- </ModalDrawerBody>
- <ModalDrawerFooter>
- <HStack>
- <Submit isDisabled={isDisabled}>Save</Submit>
- {onClose && (
- <Button size="md" variant="solid" onClick={onClose}>
- Cancel
- </Button>
- )}
- </HStack>
- </ModalDrawerFooter>
- </ValidatedForm>
- </ModalDrawerContent>
- </ModalDrawer>
- </ModalDrawerProvider>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ {onClose && (
+ <Button size="md" variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ )}
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </Tabs>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ {newRecordDisclosure.isOpen && (
+ <GaugeCalibrationRecordForm
+ initialValues={{
+ id: undefined,
+ gaugeId: initialValues.id!,
+ dateCalibrated: today(getLocalTimeZone()).toString(),
+ requiresAction: false,
+ requiresAdjustment: false,
+ requiresRepair: false,
+ notes: "{}",
+ }}
+ type="drawer"
+ open={newRecordDisclosure.isOpen}
+ onClose={newRecordDisclosure.onClose}
+ />
+ )}
+ </>
);
};
+function GaugeFormContent({
+ isEditing,
+ gaugeTypes,
+ initialValues,
+ calibrationInterval,
+ setCalibrationInterval,
+}: {
+ isEditing: boolean;
+ gaugeTypes: ListItem[];
+ initialValues: GaugeFormValues;
+ calibrationInterval: {
+ lastCalibrationDate: string | undefined;
+ nextCalibrationDate: string | undefined;
+ calibrationIntervalInMonths: number;
+ };
+ setCalibrationInterval: React.Dispatch<
+ React.SetStateAction<{
+ lastCalibrationDate: string | undefined;
+ nextCalibrationDate: string | undefined;
+ calibrationIntervalInMonths: number;
+ }>
+ >;
+}) {
+ return (
+ <VStack spacing={4}>
+ <div className="grid w-full gap-4 grid-cols-1 md:grid-cols-2">
+ {isEditing ? (
+ <Input name="gaugeId" label="Gauge ID" isReadOnly />
+ ) : (
+ <SequenceOrCustomId name="gaugeId" label="Gauge ID" table="gauge" />
+ )}
+ <Input name="description" label="Description" />
+ <Select
+ name="gaugeTypeId"
+ label="Gauge Type"
+ options={gaugeTypes.map((type) => ({
+ label: <Enumerable value={type.name} />,
+ value: type.id,
+ }))}
+ />
+ <Supplier name="supplierId" label="Supplier" />
+ <Input name="modelNumber" label="Model Number" />
+ <Input name="serialNumber" label="Serial Number" />
+ {/* <Select
+ name="gaugeCalibrationStatus"
+ label="Calibration Status"
+ options={gaugeCalibrationStatus.map((status) => ({
+ label: <GaugeCalibrationStatus status={status} />,
+ value: status,
+ }))}
+ /> */}
+ <Select
+ name="gaugeRole"
+ label="Role"
+ options={gaugeRole.map((role) => ({
+ label: <GaugeRole role={role} />,
+ value: role,
+ }))}
+ />
+ <DatePicker name="dateAcquired" label="Date Acquired" />
+ {/* <Select
+ name="gaugeStatus"
+ label="Status"
+ options={gaugeStatus.map((status) => ({
+ label: <GaugeStatus status={status} />,
+ value: status,
+ }))}
+ /> */}
+ <DatePicker
+ name="lastCalibrationDate"
+ label="Last Calibration Date"
+ value={calibrationInterval.lastCalibrationDate}
+ onChange={(value) => {
+ setCalibrationInterval({
+ ...calibrationInterval,
+ lastCalibrationDate: value?.toString(),
+ nextCalibrationDate: value
+ ? parseDate(value?.toString())
+ .add({
+ months: calibrationInterval.calibrationIntervalInMonths,
+ })
+ .toString()
+ : undefined,
+ });
+ }}
+ />
+ <DatePicker
+ name="nextCalibrationDate"
+ label="Next Calibration Date"
+ value={calibrationInterval.nextCalibrationDate}
+ onChange={(value) => {
+ setCalibrationInterval({
+ ...calibrationInterval,
+ nextCalibrationDate: value?.toString(),
+ });
+ }}
+ />
+ <Location name="locationId" label="Location" />
+ <Shelf
+ name="shelfId"
+ label="Shelf"
+ locationId={initialValues.locationId}
+ />
+ <CustomFormFields table="gauge" />
+ </div>
+ <div className="border bg-muted/30 rounded-lg p-4 relative w-full">
+ <LuCalendar className="absolute top-2 right-4 text-muted-foreground" />
+ <NumberControlled
+ name="calibrationIntervalInMonths"
+ label="Calibration Interval (Months)"
+ value={calibrationInterval.calibrationIntervalInMonths}
+ onChange={(value) => {
+ setCalibrationInterval({
+ ...calibrationInterval,
+ calibrationIntervalInMonths: value,
+ nextCalibrationDate: calibrationInterval.lastCalibrationDate
+ ? parseDate(calibrationInterval.lastCalibrationDate)
+ .add({
+ months: value,
+ })
+ .toString()
+ : undefined,
+ });
+ }}
+ />
+ </div>
+ </VStack>
+ );
+}
+
export default GaugeForm;
diff --git a/apps/erp/app/modules/quality/ui/NonConformanceWorkflows/NonConformanceWorkflowForm.tsx b/apps/erp/app/modules/quality/ui/NonConformanceWorkflows/NonConformanceWorkflowForm.tsx
index ab9a1fe3a6..c7c124a831 100644
--- a/apps/erp/app/modules/quality/ui/NonConformanceWorkflows/NonConformanceWorkflowForm.tsx
+++ b/apps/erp/app/modules/quality/ui/NonConformanceWorkflows/NonConformanceWorkflowForm.tsx
@@ -1,4 +1,6 @@
+import { useCarbon } from "@carbon/auth";
import { MultiSelect, Select, ValidatedForm } from "@carbon/form";
+import type { JSONContent } from "@carbon/react";
import {
Button,
Card,
@@ -8,11 +10,13 @@ import {
toast,
VStack,
} from "@carbon/react";
-import type { JSONContent } from "@carbon/react";
import { Editor, generateHTML } from "@carbon/react/Editor";
+import { nanoid } from "nanoid";
+import { useState } from "react";
import type { z } from "zod";
import { Hidden, Input, Submit } from "~/components/Form";
import { usePermissions, useUser } from "~/hooks";
+import { getPrivateUrl, path } from "~/utils/path";
import {
nonConformanceApprovalRequirement,
nonConformanceInvestigationType,
@@ -21,18 +25,10 @@ import {
nonConformanceSource,
nonConformanceWorkflowValidator,
} from "../../quality.models";
-import { useState } from "react";
-import { useCarbon } from "@carbon/auth";
-import { nanoid } from "nanoid";
-import { getPrivateUrl, path } from "~/utils/path";
import { getPriorityIcon } from "../NonConformance/NonConformanceIcons";
-import type { ListItem } from "~/types";
-import type { NonConformanceWorkflow } from "../../types";
type NonConformanceWorkflowFormProps = {
initialValues: z.infer<typeof nonConformanceWorkflowValidator>;
- nonConformanceWorkflows: NonConformanceWorkflow[];
- nonConformanceTypes: ListItem[];
onClose: () => void;
};
diff --git a/apps/erp/app/routes/api+/quality.gauges.tsx b/apps/erp/app/routes/api+/quality.gauges.tsx
new file mode 100644
index 0000000000..4beea6018b
--- /dev/null
+++ b/apps/erp/app/routes/api+/quality.gauges.tsx
@@ -0,0 +1,17 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { getGaugesList, getGaugeTypesList } from "~/modules/quality";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "quality",
+ });
+
+ const [gauges, gaugeTypes] = await Promise.all([
+ getGaugesList(client, companyId),
+ getGaugeTypesList(client, companyId),
+ ]);
+
+ return json({ gauges: gauges.data ?? [], gaugeTypes: gaugeTypes.data ?? [] });
+}
diff --git a/apps/erp/app/routes/x+/quality+/calibrations.$id.tsx b/apps/erp/app/routes/x+/quality+/calibrations.$id.tsx
new file mode 100644
index 0000000000..ce0e4e5838
--- /dev/null
+++ b/apps/erp/app/routes/x+/quality+/calibrations.$id.tsx
@@ -0,0 +1,121 @@
+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 { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import {
+ gaugeCalibrationRecordValidator,
+ getGaugeCalibrationRecord,
+ upsertGaugeCalibrationRecord,
+} from "~/modules/quality";
+import GaugeCalibrationRecordForm from "~/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import type { Handle } from "~/utils/handle";
+import { getParams, path } from "~/utils/path";
+export const handle: Handle = {
+ breadcrumb: "Gauges",
+ to: path.to.gauges,
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "quality",
+ bypassRls: true,
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const [record] = await Promise.all([getGaugeCalibrationRecord(client, id)]);
+
+ if (record.error) {
+ throw redirect(
+ path.to.gauges,
+ await flash(
+ request,
+ error(record.error, "Failed to load gauge calibration record")
+ )
+ );
+ }
+
+ return json({
+ record: record.data,
+ });
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "quality",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(gaugeCalibrationRecordValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("Could not find id");
+
+ const inspectionStatus =
+ data.requiresAction || data.requiresAdjustment || data.requiresRepair
+ ? "Fail"
+ : "Pass";
+
+ const updateGuage = await upsertGaugeCalibrationRecord(client, {
+ id,
+ ...data,
+ inspectionStatus,
+ companyId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (updateGuage.error || !updateGuage.data) {
+ throw redirect(
+ `${path.to.calibrations}?${getParams(request)}`,
+ await flash(request, error(updateGuage.error, "Failed to insert gauge"))
+ );
+ }
+
+ throw redirect(
+ `${path.to.calibrations}?${getParams(request)}`,
+ await flash(request, success("Calibration record created"))
+ );
+}
+
+export default function GaugeCalibrationRecordRoute() {
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const { record } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: record.id || undefined,
+ gaugeId: record.gaugeId || "",
+ dateCalibrated: record.dateCalibrated || "",
+ requiresAction: record.requiresAction || false,
+ requiresAdjustment: record.requiresAdjustment || false,
+ requiresRepair: record.requiresRepair || false,
+ notes: JSON.stringify(record.notes),
+
+ ...getCustomFields(record.customFields),
+ };
+
+ const navigate = useNavigate();
+
+ return (
+ <GaugeCalibrationRecordForm
+ key={id}
+ // @ts-ignore
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/quality+/calibrations.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/calibrations.delete.$id.tsx
new file mode 100644
index 0000000000..af590862a5
--- /dev/null
+++ b/apps/erp/app/routes/x+/quality+/calibrations.delete.$id.tsx
@@ -0,0 +1,38 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { deleteGaugeCalibrationRecord } from "~/modules/quality";
+import { getParams, path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "quality",
+ });
+
+ const { id } = params;
+
+ if (!id) throw new Error("id is not found");
+
+ const mutation = await deleteGaugeCalibrationRecord(client, id);
+ if (mutation.error) {
+ return json(
+ {
+ success: false,
+ },
+ await flash(
+ request,
+ error(mutation.error, "Failed to delete gauge calibration record")
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.calibrations}?${getParams(request)}`,
+ await flash(
+ request,
+ success("Successfully deleted gauge calibration record")
+ )
+ );
+}
diff --git a/apps/erp/app/routes/x+/quality+/calibrations.new.tsx b/apps/erp/app/routes/x+/quality+/calibrations.new.tsx
new file mode 100644
index 0000000000..75db3141de
--- /dev/null
+++ b/apps/erp/app/routes/x+/quality+/calibrations.new.tsx
@@ -0,0 +1,89 @@
+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 { getLocalTimeZone, today } from "@internationalized/date";
+import { useNavigate } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import {
+ gaugeCalibrationRecordValidator,
+ upsertGaugeCalibrationRecord,
+} from "~/modules/quality";
+import GaugeCalibrationRecordForm from "~/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm";
+
+import { setCustomFields } from "~/utils/form";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ create: "quality",
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "quality",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(gaugeCalibrationRecordValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id: _id, ...data } = validation.data;
+
+ const inspectionStatus =
+ data.requiresAction || data.requiresAdjustment || data.requiresRepair
+ ? "Fail"
+ : "Pass";
+
+ const createGauge = await upsertGaugeCalibrationRecord(client, {
+ ...data,
+ inspectionStatus,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createGauge.error || !createGauge.data) {
+ throw redirect(
+ path.to.gauges,
+ await flash(request, error(createGauge.error, "Failed to insert gauge"))
+ );
+ }
+
+ throw redirect(
+ `${path.to.calibrations}?${getParams(request)}`,
+ await flash(request, success("Calibration record created"))
+ );
+}
+
+export default function GaugeCalibrationRecordNewRoute() {
+ const navigate = useNavigate();
+
+ const initialValues = {
+ id: undefined,
+ gaugeId: "",
+ dateCalibrated: today(getLocalTimeZone()).toString(),
+ requiresAction: false,
+ requiresAdjustment: false,
+ requiresRepair: false,
+ notes: "{}",
+ dateAcquired: today(getLocalTimeZone()).toString(),
+ };
+
+ return (
+ <GaugeCalibrationRecordForm
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/quality+/calibrations.tsx b/apps/erp/app/routes/x+/quality+/calibrations.tsx
new file mode 100644
index 0000000000..13fa6b29c1
--- /dev/null
+++ b/apps/erp/app/routes/x+/quality+/calibrations.tsx
@@ -0,0 +1,64 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { VStack } from "@carbon/react";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import {
+ getGaugeCalibrationRecords,
+ getGaugeTypesList,
+} from "~/modules/quality";
+import GaugeCalibrationRecordsTable from "~/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Calibrations",
+ to: path.to.gauges,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "quality",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [gaugeCalibrationRecords, gaugeTypes] = await Promise.all([
+ getGaugeCalibrationRecords(client, companyId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
+ getGaugeTypesList(client, companyId),
+ ]);
+
+ return json({
+ gaugeCalibrationRecords: gaugeCalibrationRecords.data ?? [],
+ count: gaugeCalibrationRecords.count ?? 0,
+ gaugeTypes: gaugeTypes.data ?? [],
+ });
+}
+
+export default function GaugesRoute() {
+ const { gaugeCalibrationRecords, count, gaugeTypes } =
+ useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <GaugeCalibrationRecordsTable
+ data={gaugeCalibrationRecords}
+ count={count}
+ types={gaugeTypes}
+ />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/quality+/gauges.$id.tsx b/apps/erp/app/routes/x+/quality+/gauges.$id.tsx
index c5080d7ce0..c28fff2d4f 100644
--- a/apps/erp/app/routes/x+/quality+/gauges.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/gauges.$id.tsx
@@ -16,7 +16,7 @@ import type { GaugeType } from "~/modules/quality";
import {
gaugeValidator,
getGauge,
- getGaugeTypes,
+ getGaugeCalibrationRecordsByGaugeId,
upsertGauge,
} from "~/modules/quality";
import GaugeForm from "~/modules/quality/ui/Gauge/GaugeForm";
@@ -38,10 +38,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { id } = params;
if (!id) throw new Error("Could not find id");
- const [gauge, gaugeTypes] = await Promise.all([
- getGauge(serviceRole, id),
- getGaugeTypes(serviceRole, companyId),
- ]);
+ const [gauge] = await Promise.all([getGauge(serviceRole, id)]);
if (gauge.error) {
throw redirect(
@@ -56,7 +53,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
gauge: gauge.data,
- gaugeTypes: gaugeTypes.data ?? [],
+ records: getGaugeCalibrationRecordsByGaugeId(serviceRole, id),
});
}
@@ -112,7 +109,7 @@ export default function GaugeRoute() {
const { id } = useParams();
if (!id) throw new Error("Could not find id");
- const { gauge } = useLoaderData<typeof loader>();
+ const { gauge, records } = useLoaderData<typeof loader>();
const routeData = useRouteData<{
gaugeTypes: GaugeType[];
@@ -145,6 +142,7 @@ export default function GaugeRoute() {
key={id}
// @ts-ignore
initialValues={initialValues}
+ records={records}
gaugeTypes={routeData?.gaugeTypes ?? []}
onClose={() => navigate(-1)}
/>
diff --git a/packages/react/src/hooks/useKeyboardShortcuts.ts b/packages/react/src/hooks/useKeyboardShortcuts.ts
index d5f1e3dee6..87422dd827 100644
--- a/packages/react/src/hooks/useKeyboardShortcuts.ts
+++ b/packages/react/src/hooks/useKeyboardShortcuts.ts
@@ -12,7 +12,8 @@ export default function useKeyboardShortcuts(keyMap: {
const handleKeydown = (event: any) => {
if (
!keyMap ||
- includes(["INPUT", "TEXTAREA", "SELECT"], event.target.nodeName)
+ includes(["INPUT", "TEXTAREA", "SELECT"], event.target.nodeName) ||
+ event.target.classList.contains("ProseMirror")
) {
return;
}