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(approvals): rules UI and settings routes

Ayush Sonibd99653739fc
diff --git a/apps/erp/app/modules/approvals/ui/ApprovalDecisionModal.tsx b/apps/erp/app/modules/approvals/ui/ApprovalDecisionModal.tsx
index e779d24f60..a020d2813c 100644
--- a/apps/erp/app/modules/approvals/ui/ApprovalDecisionModal.tsx
+++ b/apps/erp/app/modules/approvals/ui/ApprovalDecisionModal.tsx
@@ -12,8 +12,8 @@ import {
Textarea,
VStack
} from "@carbon/react";
-import { useState } from "react";
-import { useFetcher } from "react-router";
+import { useEffect, useState } from "react";
+import { useFetcher, useRevalidator } from "react-router";
import type { ApprovalRequest } from "~/modules/approvals";
import { path } from "~/utils/path";
@@ -31,27 +31,50 @@ const ApprovalDecisionModal = ({
onClose
}: ApprovalDecisionModalProps) => {
const fetcher = useFetcher();
+ const revalidator = useRevalidator();
const [notes, setNotes] = useState("");
const isApproving = decisionType === "approve";
const isSubmitting = fetcher.state !== "idle";
- const handleSubmit = () => {
- fetcher.submit(
- {
- id: approval.id!,
- decision: isApproving ? "Approved" : "Rejected",
- decisionNotes: notes
- },
- {
- method: "post",
- action: path.to.approvalDecision
+ // Close modal and refresh on successful submission
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data) {
+ // Check if the response indicates success
+ if (fetcher.data.success) {
+ onClose();
+ // Revalidate the data to refresh the table
+ revalidator.revalidate();
}
- );
+ // If there's a validation error (fieldErrors), it will be handled by the form
+ // If there's an error message, we should show it (but the modal will stay open)
+ }
+ }, [fetcher.state, fetcher.data, onClose, revalidator]);
+
+ const handleSubmit = () => {
+ if (!approval.id) {
+ console.error("Approval ID is missing");
+ return;
+ }
+
+ const formData = new FormData();
+ formData.append("id", approval.id);
+ formData.append("decision", isApproving ? "Approved" : "Rejected");
+ if (notes) {
+ formData.append("decisionNotes", notes);
+ }
+
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.approvalDecision(approval.id)
+ });
};
return (
- <Modal open={isOpen}>
+ <Modal
+ open={isOpen}
+ onOpenChange={(open) => !open && !isSubmitting && onClose()}
+ >
<ModalContent>
<ModalHeader>
<ModalTitle>
@@ -59,22 +82,27 @@ const ApprovalDecisionModal = ({
</ModalTitle>
<ModalDescription>
{isApproving
- ? `Are you sure you want to approve ${approval.documentReadableId}?`
- : `Are you sure you want to reject ${approval.documentReadableId}?`}
+ ? `Are you sure you want to approve ${approval.documentReadableId ?? approval.documentId}?`
+ : `Are you sure you want to reject ${approval.documentReadableId ?? approval.documentId}?`}
</ModalDescription>
- <ModalClose onClick={onClose} />
+ <ModalClose onClick={onClose} disabled={isSubmitting} />
</ModalHeader>
<ModalBody>
<VStack spacing={4}>
<div className="w-full">
- <label className="text-sm font-medium text-muted-foreground mb-2 block">
+ <label
+ htmlFor="decisionNotes"
+ className="text-sm font-medium text-muted-foreground mb-2 block"
+ >
Notes (optional)
</label>
<Textarea
+ id="decisionNotes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder="Add any notes about your decision..."
rows={4}
+ disabled={isSubmitting}
/>
</div>
</VStack>
diff --git a/apps/erp/app/modules/approvals/ui/ApprovalRuleDrawer.tsx b/apps/erp/app/modules/approvals/ui/ApprovalRuleDrawer.tsx
new file mode 100644
index 0000000000..185aac2e2c
--- /dev/null
+++ b/apps/erp/app/modules/approvals/ui/ApprovalRuleDrawer.tsx
@@ -0,0 +1,151 @@
+import {
+ Number as FormNumber,
+ Hidden,
+ Input,
+ MultiSelect,
+ Submit,
+ ValidatedForm
+} from "@carbon/form";
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ HStack,
+ Switch
+} from "@carbon/react";
+import { User } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { type ApprovalRule, approvalRuleValidator } from "~/modules/approvals";
+import { path } from "~/utils/path";
+
+type ApprovalRuleDrawerProps = {
+ rule: ApprovalRule | null;
+ documentType: "purchaseOrder" | "qualityDocument";
+ groups: Array<{ id: string; name: string }>;
+ onClose: () => void;
+};
+
+const ApprovalRuleDrawer = ({
+ rule,
+ documentType,
+ groups,
+ onClose
+}: ApprovalRuleDrawerProps) => {
+ const permissions = usePermissions();
+ const isEditing = !!rule;
+ const isDisabled = !permissions.can("update", "settings");
+
+ const groupOptions = groups.map((g) => ({
+ value: g.id,
+ label: g.name
+ }));
+
+ const defaultValues = rule
+ ? {
+ id: rule.id,
+ name: rule.name ?? "",
+ documentType: rule.documentType,
+ enabled: rule.enabled ?? false,
+ approverGroupIds: Array.isArray(rule.approverGroupIds)
+ ? rule.approverGroupIds
+ : [],
+ defaultApproverId: rule.defaultApproverId ?? undefined,
+ lowerBoundAmount: rule.lowerBoundAmount ?? 0,
+ upperBoundAmount: rule.upperBoundAmount ?? undefined,
+ escalationDays: rule.escalationDays ?? undefined
+ }
+ : {
+ name: "",
+ documentType,
+ enabled: true,
+ approverGroupIds: [],
+ lowerBoundAmount: 0,
+ upperBoundAmount: undefined,
+ escalationDays: undefined
+ };
+
+ return (
+ <Drawer open onOpenChange={(open) => !open && onClose()}>
+ <DrawerContent>
+ <ValidatedForm
+ validator={approvalRuleValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.approvalRule(rule!.id!)
+ : path.to.newApprovalRule(documentType)
+ }
+ defaultValues={defaultValues}
+ className="flex flex-col h-full"
+ >
+ <DrawerHeader>
+ <DrawerTitle>
+ {isEditing ? "Edit" : "New"} Approval Rule
+ </DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ <div className="flex flex-col gap-6">
+ {isEditing && rule?.id && <Hidden name="id" value={rule.id} />}
+ <Hidden name="documentType" value={documentType} />
+ <Input
+ name="name"
+ label="Rule Name"
+ helperText="A descriptive name for this approval rule (e.g., 'Low Value PO Rule', 'High Value PO Rule')"
+ required
+ />
+ <Switch name="enabled" label="Enabled" />
+ <MultiSelect
+ name="approverGroupIds"
+ label="Approver Groups"
+ placeholder="Select groups"
+ options={groupOptions}
+ />
+ <User
+ name="defaultApproverId"
+ label="Default Approver"
+ placeholder="Select a user"
+ />
+ {documentType === "purchaseOrder" && (
+ <>
+ <FormNumber
+ name="lowerBoundAmount"
+ label="Lower Bound Amount"
+ helperText="Minimum amount (inclusive) for this rule"
+ step={0.01}
+ />
+ <FormNumber
+ name="upperBoundAmount"
+ label="Upper Bound Amount"
+ helperText="Maximum amount (exclusive) for this rule. Leave empty for no upper limit."
+ step={0.01}
+ />
+ </>
+ )}
+ <FormNumber
+ name="escalationDays"
+ label="Escalation Days"
+ helperText="Auto-escalate after this many days (leave empty to disable)"
+ />
+ </div>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>
+ {isEditing ? "Update" : "Create"} Rule
+ </Submit>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </ValidatedForm>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default ApprovalRuleDrawer;
diff --git a/apps/erp/app/modules/approvals/ui/ApprovalRulesTable.tsx b/apps/erp/app/modules/approvals/ui/ApprovalRulesTable.tsx
new file mode 100644
index 0000000000..4e261be2a8
--- /dev/null
+++ b/apps/erp/app/modules/approvals/ui/ApprovalRulesTable.tsx
@@ -0,0 +1,298 @@
+import {
+ Badge,
+ Checkbox,
+ MenuIcon,
+ MenuItem,
+ useDisclosure
+} from "@carbon/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo, useState } from "react";
+import {
+ LuCalendar,
+ LuCircleCheck,
+ LuDollarSign,
+ LuFileText,
+ LuPencil,
+ LuTrash,
+ LuUser,
+ LuUsers
+} from "react-icons/lu";
+import { useNavigate } from "react-router";
+import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import {
+ useCurrencyFormatter,
+ usePermissions,
+ useUrlParams,
+ useUser
+} from "~/hooks";
+import type { ApprovalRule } from "~/modules/approvals";
+import { usePeople } from "~/stores";
+import { path } from "~/utils/path";
+
+type ApprovalRulesTableProps = {
+ data: ApprovalRule[];
+ count: number;
+ documentType: "purchaseOrder" | "qualityDocument";
+};
+
+const ApprovalRulesTable = memo(
+ ({ data, count, documentType }: ApprovalRulesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const user = useUser();
+ const currencyFormatter = useCurrencyFormatter();
+ const deleteDisclosure = useDisclosure();
+ const [people] = usePeople();
+ const [selectedRule, setSelectedRule] = useState<ApprovalRule | null>(null);
+
+ const columns = useMemo<ColumnDef<ApprovalRule>[]>(() => {
+ const baseColumns: ColumnDef<ApprovalRule>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <Hyperlink
+ to={`${path.to.approvalRule(row.original.id!)}?${params.toString()}`}
+ >
+ <span className="font-medium text-sm">{row.original.name}</span>
+ </Hyperlink>
+ ),
+ meta: {
+ icon: <LuFileText />
+ }
+ },
+ {
+ accessorKey: "enabled",
+ header: "Status",
+ cell: ({ row }) => (
+ <div className="flex items-center gap-2">
+ <Checkbox isChecked={row.original.enabled ?? false} />
+ <Badge variant={row.original.enabled ? "green" : "gray"}>
+ {row.original.enabled ? "Enabled" : "Disabled"}
+ </Badge>
+ </div>
+ ),
+ meta: {
+ icon: <LuCircleCheck />,
+ filter: {
+ type: "static",
+ options: [
+ { value: "true", label: "Enabled" },
+ { value: "false", label: "Disabled" }
+ ]
+ }
+ }
+ }
+ ];
+
+ if (documentType === "purchaseOrder") {
+ baseColumns.push({
+ id: "amountRange",
+ header: "Amount Range",
+ cell: ({ row }) => {
+ const lower = currencyFormatter.format(
+ row.original.lowerBoundAmount ?? 0
+ );
+ const upper = row.original.upperBoundAmount
+ ? currencyFormatter.format(row.original.upperBoundAmount)
+ : null;
+ return (
+ <span className="text-sm">
+ {lower} {upper ? `- ${upper}` : "+"}
+ </span>
+ );
+ },
+ meta: {
+ icon: <LuDollarSign />
+ }
+ });
+ }
+
+ baseColumns.push(
+ {
+ id: "approverGroups",
+ header: "Approver Groups",
+ cell: ({ row }) => {
+ const groups = row.original.approverGroupIds ?? [];
+ if (groups.length === 0)
+ return <span className="text-muted-foreground text-sm">—</span>;
+ return (
+ <span className="text-sm">
+ {groups.length} {groups.length === 1 ? "group" : "groups"}
+ </span>
+ );
+ },
+ meta: {
+ icon: <LuUsers />,
+ filter: {
+ type: "fetcher",
+ endpoint: path.to.api.groupsByType("employee"),
+ transform: (
+ data: {
+ groups: {
+ data: { id: string; name: string };
+ children: any[];
+ }[];
+ } | null
+ ) => {
+ if (!data?.groups) return [];
+ // Flatten tree structure
+ const flattenGroups = (
+ groups: {
+ data: { id: string; name: string };
+ children: any[];
+ }[]
+ ): { id: string; name: string }[] => {
+ const result: { id: string; name: string }[] = [];
+ groups.forEach((group) => {
+ result.push({
+ id: group.data.id,
+ name: group.data.name
+ });
+ if (group.children && group.children.length > 0) {
+ result.push(...flattenGroups(group.children));
+ }
+ });
+ return result;
+ };
+ const flatGroups = flattenGroups(data.groups);
+ return flatGroups.map(({ id, name }) => ({
+ value: id,
+ label: name
+ }));
+ },
+ isArray: true
+ }
+ }
+ },
+ {
+ id: "defaultApprover",
+ header: "Default Approver",
+ cell: ({ row }) =>
+ row.original.defaultApproverId ? (
+ <EmployeeAvatar employeeId={row.original.defaultApproverId} />
+ ) : (
+ <span className="text-muted-foreground text-sm">—</span>
+ ),
+ meta: {
+ icon: <LuUser />,
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name
+ }))
+ }
+ }
+ },
+ {
+ 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) => {
+ const date = item.getValue<string>();
+ return date ? new Date(date).toLocaleDateString() : "—";
+ },
+ meta: {
+ icon: <LuCalendar />
+ }
+ }
+ );
+
+ return baseColumns;
+ }, [documentType, currencyFormatter, people, params]);
+
+ const renderContextMenu = useCallback(
+ (row: ApprovalRule) => {
+ const canDelete =
+ permissions.can("update", "settings") && row.createdBy === user?.id;
+
+ return (
+ <>
+ <MenuItem
+ disabled={!permissions.can("update", "settings")}
+ onClick={() => {
+ navigate(
+ `${path.to.approvalRule(row.id!)}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Rule
+ </MenuItem>
+ <MenuItem
+ destructive
+ disabled={!canDelete}
+ onClick={() => {
+ setSelectedRule(row);
+ deleteDisclosure.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Rule
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions, user, deleteDisclosure]
+ );
+
+ return (
+ <>
+ <Table<ApprovalRule>
+ data={data}
+ columns={columns}
+ count={count}
+ renderContextMenu={renderContextMenu}
+ title={
+ documentType === "purchaseOrder"
+ ? "Purchase Order Approval Rules"
+ : "Quality Document Approval Rules"
+ }
+ primaryAction={
+ permissions.can("update", "settings") && (
+ <New label="Rule" to={path.to.newApprovalRule(documentType)} />
+ )
+ }
+ />
+ {selectedRule?.id && (
+ <ConfirmDelete
+ action={path.to.deleteApprovalRule(selectedRule!.id)}
+ isOpen={deleteDisclosure.isOpen}
+ name={`${documentType === "purchaseOrder" ? "Purchase Order" : "Quality Document"} approval rule`}
+ text={`Are you sure you want to delete this approval rule? This cannot be undone.`}
+ onCancel={() => {
+ deleteDisclosure.onClose();
+ setSelectedRule(null);
+ }}
+ onSubmit={() => {
+ deleteDisclosure.onClose();
+ setSelectedRule(null);
+ }}
+ />
+ )}
+ </>
+ );
+ }
+);
+
+ApprovalRulesTable.displayName = "ApprovalRulesTable";
+export default ApprovalRulesTable;
diff --git a/apps/erp/app/modules/approvals/ui/ApprovalsTable.tsx b/apps/erp/app/modules/approvals/ui/ApprovalsTable.tsx
index 1511562d3b..0cb5c1f51c 100644
--- a/apps/erp/app/modules/approvals/ui/ApprovalsTable.tsx
+++ b/apps/erp/app/modules/approvals/ui/ApprovalsTable.tsx
@@ -254,7 +254,7 @@ const ApprovalsTable = memo(({ data, count }: ApprovalsTableProps) => {
decisionByName: false
}}
renderContextMenu={renderContextMenu}
- title="Approvals"
+ title="Approvals Requests"
table="approvalRequest"
withSavedView
/>
diff --git a/apps/erp/app/modules/approvals/ui/index.ts b/apps/erp/app/modules/approvals/ui/index.ts
index 61a1b40a39..f27b60a03b 100644
--- a/apps/erp/app/modules/approvals/ui/index.ts
+++ b/apps/erp/app/modules/approvals/ui/index.ts
@@ -1,4 +1,6 @@
export { default as ApprovalDecisionModal } from "./ApprovalDecisionModal";
export { default as ApprovalHistory } from "./ApprovalHistory";
+export { default as ApprovalRuleDrawer } from "./ApprovalRuleDrawer";
+export { default as ApprovalRulesTable } from "./ApprovalRulesTable";
export { default as ApprovalStatus } from "./ApprovalStatus";
export { default as ApprovalsTable } from "./ApprovalsTable";
diff --git a/apps/erp/app/routes/x+/settings+/approvals+/_index.tsx b/apps/erp/app/routes/x+/settings+/approvals+/_index.tsx
new file mode 100644
index 0000000000..b2f6c6ec40
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/approvals+/_index.tsx
@@ -0,0 +1,114 @@
+import { error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ Button,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger
+} from "@carbon/react";
+import { LuInbox } from "react-icons/lu";
+import type { LoaderFunctionArgs } from "react-router";
+import { Link, Outlet, redirect, useLoaderData } from "react-router";
+import { getApprovalRules } from "~/modules/approvals";
+import ApprovalRulesTable from "~/modules/approvals/ui/ApprovalRulesTable";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Rules",
+ to: path.to.approvalSettings
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { companyId } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee"
+ });
+
+ const serviceRole = getCarbonServiceRole();
+ const rules = await getApprovalRules(serviceRole, companyId);
+
+ if (rules.error) {
+ throw redirect(
+ path.to.company,
+ await flash(request, error(rules.error, "Failed to load approval rules"))
+ );
+ }
+
+ const poRules =
+ rules.data?.filter((r) => r.documentType === "purchaseOrder") || [];
+
+ const qdRules =
+ rules.data?.filter((r) => r.documentType === "qualityDocument") || [];
+
+ return {
+ poRules,
+ qdRules
+ };
+}
+
+export default function ApprovalSettingsRoute() {
+ const { poRules, qdRules } = useLoaderData<typeof loader>();
+
+ return (
+ <>
+ <div className="h-full w-full flex flex-col">
+ <Tabs
+ defaultValue="purchaseOrder"
+ className="h-full w-full flex flex-col"
+ >
+ <div className="border-b border-border bg-card">
+ <div className="px-4 py-1 md:px-6 lg:px-8 flex items-center justify-between">
+ <TabsList className="bg-transparent h-10 border-none gap-1">
+ <TabsTrigger
+ value="purchaseOrder"
+ variant="primary"
+ className="px-4 py-1.5"
+ >
+ Purchase Orders
+ </TabsTrigger>
+ <TabsTrigger
+ value="qualityDocument"
+ variant="primary"
+ className="px-4 py-1.5"
+ >
+ Quality Documents
+ </TabsTrigger>
+ </TabsList>
+ <Button variant="secondary" leftIcon={<LuInbox />} asChild>
+ <Link to={path.to.approvalRequests}>View Requests</Link>
+ </Button>
+ </div>
+ </div>
+ <TabsContent
+ value="purchaseOrder"
+ className="flex-1 overflow-hidden w-full mt-0 data-[state=inactive]:hidden"
+ >
+ <div className="h-full w-full">
+ <ApprovalRulesTable
+ data={poRules}
+ count={poRules.length}
+ documentType="purchaseOrder"
+ />
+ </div>
+ </TabsContent>
+ <TabsContent
+ value="qualityDocument"
+ className="flex-1 overflow-hidden w-full mt-0 data-[state=inactive]:hidden"
+ >
+ <div className="h-full w-full">
+ <ApprovalRulesTable
+ data={qdRules}
+ count={qdRules.length}
+ documentType="qualityDocument"
+ />
+ </div>
+ </TabsContent>
+ </Tabs>
+ </div>
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/erp/app/routes/x+/approvals+/_layout.tsx b/apps/erp/app/routes/x+/settings+/approvals+/_layout.tsx
similarity index 59%
rename from apps/erp/app/routes/x+/approvals+/_layout.tsx
rename to apps/erp/app/routes/x+/settings+/approvals+/_layout.tsx
index 8a37f72a59..e26e53d07d 100644
--- a/apps/erp/app/routes/x+/approvals+/_layout.tsx
+++ b/apps/erp/app/routes/x+/settings+/approvals+/_layout.tsx
@@ -1,17 +1,12 @@
-import { VStack } from "@carbon/react";
import { Outlet } from "react-router";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
export const handle: Handle = {
breadcrumb: "Approvals",
- to: path.to.approvals
+ to: path.to.approvalSettings
};
export default function ApprovalsLayout() {
- return (
- <VStack spacing={0} className="h-full">
- <Outlet />
- </VStack>
- );
+ return <Outlet />;
}
diff --git a/apps/erp/app/routes/x+/settings+/approvals+/requests.$id.tsx b/apps/erp/app/routes/x+/settings+/approvals+/requests.$id.tsx
new file mode 100644
index 0000000000..af084a96a1
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/approvals+/requests.$id.tsx
@@ -0,0 +1,204 @@
+import { error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { NotificationEvent } from "@carbon/notifications";
+import { tasks } from "@trigger.dev/sdk";
+import { useEffect } from "react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useNavigate } from "react-router";
+import {
+ approvalDecisionValidator,
+ approveRequest,
+ canApproveRequest,
+ getApprovalById,
+ rejectRequest
+} from "~/modules/approvals";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { userId } = await requirePermissions(request, {
+ role: "employee"
+ });
+
+ const serviceRole = getCarbonServiceRole();
+ const { id } = params;
+ if (!id) throw new Error("id is not found");
+
+ const approval = await getApprovalById(serviceRole, id);
+ if (approval.error || !approval.data) {
+ throw redirect(
+ path.to.approvalRequests,
+ await flash(
+ request,
+ error(
+ approval.error ?? new Error("Approval request not found"),
+ "Approval request not found"
+ )
+ )
+ );
+ }
+
+ // Check if user can approve/reject this request
+ const canApprove = await canApproveRequest(
+ serviceRole,
+ approval.data,
+ userId
+ );
+ if (!canApprove) {
+ throw redirect(
+ path.to.approvalRequests,
+ await flash(
+ request,
+ error(
+ new Error(
+ "You do not have permission to approve/reject this request"
+ ),
+ "You do not have permission to approve or reject this request"
+ )
+ )
+ );
+ }
+
+ if (approval.data.status !== "Pending") {
+ throw redirect(
+ path.to.approvalRequests,
+ await flash(
+ request,
+ error(
+ new Error("Approval request is not pending"),
+ "Approval request is not pending"
+ )
+ )
+ );
+ }
+
+ return { approval: approval.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ role: "employee"
+ });
+
+ const serviceRole = getCarbonServiceRole();
+ const { id } = params;
+ if (!id) throw new Error("id is not found");
+
+ const formData = await request.formData();
+ const validation = await validator(approvalDecisionValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { decision, decisionNotes } = validation.data;
+
+ // Get approval request and check permissions
+ const approval = await getApprovalById(serviceRole, id);
+ if (approval.error || !approval.data) {
+ throw redirect(
+ path.to.approvalRequests,
+ await flash(
+ request,
+ error(
+ approval.error ?? new Error("Approval request not found"),
+ "Approval request not found"
+ )
+ )
+ );
+ }
+
+ // Check if user can approve/reject this request
+ const canApprove = await canApproveRequest(
+ serviceRole,
+ approval.data,
+ userId
+ );
+ if (!canApprove) {
+ throw redirect(
+ path.to.approvalRequests,
+ await flash(
+ request,
+ error(
+ new Error(
+ "You do not have permission to approve/reject this request"
+ ),
+ "You do not have permission to approve or reject this request"
+ )
+ )
+ );
+ }
+
+ if (approval.data.status !== "Pending") {
+ throw redirect(
+ path.to.approvalRequests,
+ await flash(
+ request,
+ error(
+ new Error("Approval request is not pending"),
+ "Approval request is not pending"
+ )
+ )
+ );
+ }
+
+ let result;
+ if (decision === "Approved") {
+ result = await approveRequest(serviceRole, id, userId, decisionNotes);
+ } else {
+ result = await rejectRequest(serviceRole, id, userId, decisionNotes);
+ }
+
+ if (result.error) {
+ // Return JSON error for fetcher requests
+ // Regular form submissions will be handled by the redirect below
+ return Response.json(
+ { error: result.error.message, success: false },
+ { status: 400 }
+ );
+ }
+
+ try {
+ await tasks.trigger("notify", {
+ event:
+ decision === "Approved"
+ ? NotificationEvent.ApprovalApproved
+ : NotificationEvent.ApprovalRejected,
+ companyId,
+ documentId: id,
+ recipient: {
+ type: "user" as const,
+ userId: approval.data.requestedBy
+ },
+ from: userId
+ });
+ } catch (err) {
+ console.error("Failed to notify requester", err);
+ }
+
+ // Return JSON response for fetcher requests
+ // The modal will handle the response and refresh the data
+ return Response.json({
+ success: true,
+ message:
+ decision === "Approved"
+ ? "Approval request approved"
+ : "Approval request rejected"
+ });
+}
+
+export default function ApprovalDecisionRoute() {
+ // This route is only used for the action handler (POST requests via fetcher)
+ // If accessed directly via GET, redirect to the requests list
+ // The modal in ApprovalsTable handles the UI
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ navigate(path.to.approvalRequests, { replace: true });
+ }, [navigate]);
+
+ return null;
+}
diff --git a/apps/erp/app/routes/x+/approvals+/_index.tsx b/apps/erp/app/routes/x+/settings+/approvals+/requests.tsx
similarity index 91%
rename from apps/erp/app/routes/x+/approvals+/_index.tsx
rename to apps/erp/app/routes/x+/settings+/approvals+/requests.tsx
index d273f01af2..719e7e4324 100644
--- a/apps/erp/app/routes/x+/approvals+/_index.tsx
+++ b/apps/erp/app/routes/x+/settings+/approvals+/requests.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect, useLoaderData } from "react-router";
+import { Outlet, redirect, useLoaderData } from "react-router";
import {
type ApprovalDocumentType,
type ApprovalStatus,
@@ -15,8 +15,8 @@ import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
export const handle: Handle = {
- breadcrumb: "Inbox",
- to: path.to.approvals
+ breadcrumb: "Requests",
+ to: path.to.approvalRequests
};
export async function loader({ request }: LoaderFunctionArgs) {
@@ -60,12 +60,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
};
}
-export default function ApprovalsInboxRoute() {
+export default function ApprovalRequestsRoute() {
const { approvals, count } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<ApprovalsTable data={approvals} count={count} />
+ <Outlet />
</VStack>
);
}
diff --git a/apps/erp/app/routes/x+/settings+/approvals+/rules.$id.delete.tsx b/apps/erp/app/routes/x+/settings+/approvals+/rules.$id.delete.tsx
new file mode 100644
index 0000000000..c12a200484
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/approvals+/rules.$id.delete.tsx
@@ -0,0 +1,167 @@
+import { error, getCarbonServiceRole, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { getApprovalRules } from "~/modules/approvals";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "settings",
+ role: "employee"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Rule ID is required");
+
+ const serviceRole = getCarbonServiceRole();
+ const rules = await getApprovalRules(serviceRole, companyId);
+
+ if (rules.error) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(request, error(rules.error, "Failed to load approval rule"))
+ );
+ }
+
+ const rule = rules.data?.find((r) => r.id === id);
+
+ if (!rule) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(request, error(null, "Approval rule not found"))
+ );
+ }
+
+ if (rule.createdBy !== userId) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(
+ request,
+ error(null, "Only the creator can delete this approval rule")
+ )
+ );
+ }
+
+ return { rule };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "settings",
+ role: "employee"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Rule ID is required");
+
+ const serviceRole = getCarbonServiceRole();
+
+ // Verify user is creator before deleting
+ const rules = await getApprovalRules(serviceRole, companyId);
+ const rule = rules.data?.find((r) => r.id === id);
+
+ if (!rule) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(request, error(null, "Approval rule not found"))
+ );
+ }
+
+ if (rule.createdBy !== userId) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(
+ request,
+ error(null, "Only the creator can delete this approval rule")
+ )
+ );
+ }
+
+ // Check for pending approval requests that might be using this rule
+ const pendingRequests = await serviceRole
+ .from("approvalRequest")
+ .select("id, approverGroupIds, approverId")
+ .eq("companyId", companyId)
+ .eq("status", "Pending")
+ .eq("documentType", rule.documentType);
+
+ if (pendingRequests.error) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(
+ request,
+ error(pendingRequests.error, "Failed to check for pending approvals")
+ )
+ );
+ }
+
+ // Check if any pending requests match this rule's approvers
+ const matchingRequests = pendingRequests.data?.filter((req) => {
+ // Check if request has matching approver groups
+ if (rule.approverGroupIds && rule.approverGroupIds.length > 0) {
+ const requestGroups = req.approverGroupIds || [];
+ const hasMatchingGroup = requestGroups.some((groupId) =>
+ rule.approverGroupIds?.includes(groupId)
+ );
+ if (hasMatchingGroup) return true;
+ }
+
+ // Check if request has matching default approver
+ if (rule.defaultApproverId && req.approverId === rule.defaultApproverId) {
+ return true;
+ }
+
+ return false;
+ });
+
+ if (matchingRequests && matchingRequests.length > 0) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(
+ request,
+ error(
+ null,
+ `Cannot delete this rule because there are ${matchingRequests.length} pending approval request(s) that may be using it. Please resolve or cancel those requests first.`
+ )
+ )
+ );
+ }
+
+ let result = await serviceRole
+ .from("approvalRule")
+ .delete()
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .select();
+
+ if (result.error) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(
+ request,
+ error(result.error, "Failed to delete approval rule")
+ )
+ );
+ }
+
+ if (!result.data || result.data.length === 0) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(
+ request,
+ error(null, "Approval rule not found or already deleted")
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.approvalSettings}?${getParams(request)}`,
+ await flash(request, success("Approval rule deleted successfully"))
+ );
+}
+
+export default function DeleteApprovalRuleRoute() {
+ return null;
+}
diff --git a/apps/erp/app/routes/x+/settings+/approvals+/rules.$id.tsx b/apps/erp/app/routes/x+/settings+/approvals+/rules.$id.tsx
new file mode 100644
index 0000000000..81fa1fef49
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/approvals+/rules.$id.tsx
@@ -0,0 +1,141 @@
+import { error, getCarbonServiceRole, 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, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate } from "react-router";
+import { useUrlParams } from "~/hooks";
+import {
+ approvalRuleValidator,
+ getApprovalRules,
+ upsertApprovalRule
+} from "~/modules/approvals";
+import ApprovalRuleDrawer from "~/modules/approvals/ui/ApprovalRuleDrawer";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Rule ID is required");
+
+ const serviceRole = getCarbonServiceRole();
+
+ const [rules, groupsResult] = await Promise.all([
+ getApprovalRules(serviceRole, companyId),
+ client
+ .from("group")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .eq("isCustomerOrgGroup", false)
+ .eq("isSupplierOrgGroup", false)
+ ]);
+
+ if (rules.error) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(request, error(rules.error, "Failed to load approval rule"))
+ );
+ }
+
+ if (groupsResult.error) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(
+ request,
+ error(groupsResult.error, "Failed to load approver groups")
+ )
+ );
+ }
+
+ const rule = rules.data?.find((r) => r.id === id);
+
+ if (!rule) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(request, error(null, "Approval rule not found"))
+ );
+ }
+
+ return {
+ rule,
+ groups: groupsResult.data ?? []
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "settings",
+ role: "employee"
+ });
+
+ const serviceRole = getCarbonServiceRole();
+ const { id } = params;
+ if (!id) throw new Error("Rule ID is required");
+
+ const formData = await request.formData();
+ const validation = await validator(approvalRuleValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const existingRule = await serviceRole
+ .from("approvalRule")
+ .select("id")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+
+ if (existingRule.error || !existingRule.data) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(request, error(null, "Approval rule not found"))
+ );
+ }
+
+ const result = await upsertApprovalRule(serviceRole, {
+ id,
+ updatedBy: userId,
+ name: validation.data.name,
+ documentType: validation.data.documentType,
+ enabled: validation.data.enabled,
+ approverGroupIds: validation.data.approverGroupIds || [],
+ defaultApproverId: validation.data.defaultApproverId,
+ lowerBoundAmount: validation.data.lowerBoundAmount ?? 0,
+ upperBoundAmount: validation.data.upperBoundAmount ?? null,
+ escalationDays: validation.data.escalationDays
+ });
+
+ if (result.error) {
+ throw redirect(
+ `${path.to.approvalRule(id)}?${getParams(request)}`,
+ await flash(request, error(result.error, result.error.message))
+ );
+ }
+
+ throw redirect(
+ `${path.to.approvalSettings}?${getParams(request)}`,
+ await flash(request, success("Approval rule updated"))
+ );
+}
+
+export default function EditApprovalRuleRoute() {
+ const { rule, groups } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+ const [params] = useUrlParams();
+ const onClose = () =>
+ navigate(`${path.to.approvalSettings}?${params.toString()}`);
+
+ return (
+ <ApprovalRuleDrawer
+ rule={rule}
+ documentType={rule.documentType as "purchaseOrder" | "qualityDocument"}
+ groups={groups}
+ onClose={onClose}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/approvals+/rules.new.tsx b/apps/erp/app/routes/x+/settings+/approvals+/rules.new.tsx
new file mode 100644
index 0000000000..b801e4946b
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/approvals+/rules.new.tsx
@@ -0,0 +1,104 @@
+import { error, getCarbonServiceRole, 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, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate } from "react-router";
+import { useUrlParams } from "~/hooks";
+import { approvalRuleValidator, upsertApprovalRule } from "~/modules/approvals";
+import ApprovalRuleDrawer from "~/modules/approvals/ui/ApprovalRuleDrawer";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const documentType = url.searchParams.get("documentType") as
+ | "purchaseOrder"
+ | "qualityDocument"
+ | null;
+
+ if (
+ !documentType ||
+ !["purchaseOrder", "qualityDocument"].includes(documentType)
+ ) {
+ throw redirect(
+ path.to.approvalSettings,
+ await flash(request, error(null, "Invalid document type"))
+ );
+ }
+
+ const groupsResult = await client
+ .from("group")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .eq("isCustomerOrgGroup", false)
+ .eq("isSupplierOrgGroup", false);
+
+ return {
+ rule: null,
+ documentType,
+ groups: groupsResult.data ?? []
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "settings",
+ role: "employee"
+ });
+
+ const serviceRole = getCarbonServiceRole();
+
+ const formData = await request.formData();
+ const validation = await validator(approvalRuleValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const result = await upsertApprovalRule(serviceRole, {
+ createdBy: userId,
+ companyId,
+ name: validation.data.name,
+ documentType: validation.data.documentType,
+ enabled: validation.data.enabled,
+ approverGroupIds: validation.data.approverGroupIds || [],
+ defaultApproverId: validation.data.defaultApproverId,
+ lowerBoundAmount: validation.data.lowerBoundAmount ?? 0,
+ upperBoundAmount: validation.data.upperBoundAmount ?? null,
+ escalationDays: validation.data.escalationDays
+ });
+
+ if (result.error) {
+ throw redirect(
+ `${path.to.newApprovalRule(validation.data.documentType)}?${getParams(request)}`,
+ await flash(request, error(result.error, result.error.message))
+ );
+ }
+
+ throw redirect(
+ `${path.to.approvalSettings}?${getParams(request)}`,
+ await flash(request, success("Approval rule created"))
+ );
+}
+
+export default function NewApprovalRuleRoute() {
+ const { rule, documentType, groups } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+ const [params] = useUrlParams();
+ const onClose = () =>
+ navigate(`${path.to.approvalSettings}?${params.toString()}`);
+
+ return (
+ <ApprovalRuleDrawer
+ rule={rule}
+ documentType={documentType!}
+ groups={groups}
+ onClose={onClose}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/approvals+/rules.tsx b/apps/erp/app/routes/x+/settings+/approvals+/rules.tsx
new file mode 100644
index 0000000000..ad4035d370
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/approvals+/rules.tsx
@@ -0,0 +1,114 @@
+import { error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ Button,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger
+} from "@carbon/react";
+import { LuInbox } from "react-icons/lu";
+import type { LoaderFunctionArgs } from "react-router";
+import { Link, Outlet, redirect, useLoaderData } from "react-router";
+import { getApprovalRules } from "~/modules/approvals";
+import ApprovalRulesTable from "~/modules/approvals/ui/ApprovalRulesTable";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Rules",
+ to: path.to.approvalSettings
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { companyId } = await requirePermissions(request, {
+ view: "settings",
+ role: "employee"
+ });
+
+ const serviceRole = getCarbonServiceRole();
+ const rules = await getApprovalRules(serviceRole, companyId);
+
+ if (rules.error) {
+ throw redirect(
+ path.to.company,
+ await flash(request, error(rules.error, "Failed to load approval rules"))
+ );
+ }
+
+ const poRules =
+ rules.data?.filter((r) => r.documentType === "purchaseOrder") || [];
+
+ const qdRules =
+ rules.data?.filter((r) => r.documentType === "qualityDocument") || [];
+
+ return {
+ poRules,
+ qdRules
+ };
+}
+
+export default function ApprovalRulesRoute() {
+ const { poRules, qdRules } = useLoaderData<typeof loader>();
+
+ return (
+ <>
+ <div className="h-full w-full flex flex-col">
+ <Tabs
+ defaultValue="purchaseOrder"
+ className="h-full w-full flex flex-col"
+ >
+ <div className="border-b border-border bg-card">
+ <div className="px-4 py-1 md:px-6 lg:px-8 flex items-center justify-between">
+ <TabsList className="bg-transparent h-10 border-none gap-1">
+ <TabsTrigger
+ value="purchaseOrder"
+ variant="primary"
+ className="px-4 py-1.5"
+ >
+ Purchase Orders
+ </TabsTrigger>
+ <TabsTrigger
+ value="qualityDocument"
+ variant="primary"
+ className="px-4 py-1.5"
+ >
+ Quality Documents
+ </TabsTrigger>
+ </TabsList>
+ <Button variant="secondary" leftIcon={<LuInbox />} asChild>
+ <Link to={path.to.approvalRequests}>View Requests</Link>
+ </Button>
+ </div>
+ </div>
+ <TabsContent
+ value="purchaseOrder"
+ className="flex-1 overflow-hidden w-full mt-0 data-[state=inactive]:hidden"
+ >
+ <div className="h-full w-full">
+ <ApprovalRulesTable
+ data={poRules}
+ count={poRules.length}
+ documentType="purchaseOrder"
+ />
+ </div>
+ </TabsContent>
+ <TabsContent
+ value="qualityDocument"
+ className="flex-1 overflow-hidden w-full mt-0 data-[state=inactive]:hidden"
+ >
+ <div className="h-full w-full">
+ <ApprovalRulesTable
+ data={qdRules}
+ count={qdRules.length}
+ documentType="qualityDocument"
+ />
+ </div>
+ </TabsContent>
+ </Tabs>
+ </div>
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/approvals.tsx b/apps/erp/app/routes/x+/settings+/approvals.tsx
deleted file mode 100644
index 558f2ae22d..0000000000
--- a/apps/erp/app/routes/x+/settings+/approvals.tsx
+++ /dev/null
@@ -1,435 +0,0 @@
-import {
- assertIsPost,
- error,
- getCarbonServiceRole,
- success
-} from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import {
- Hidden,
- MultiSelect,
- Number,
- Submit,
- ValidatedForm,
- validationError,
- validator
-} from "@carbon/form";
-import {
- Button,
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
- Heading,
- HStack,
- ScrollArea,
- Switch,
- VStack
-} from "@carbon/react";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { Link, redirect, useLoaderData } from "react-router";
-import { User } from "~/components/Form";
-import {
- approvalConfigurationValidator,
- getApprovalConfigurations,
- upsertApprovalConfiguration
-} from "~/modules/approvals";
-import type { Handle } from "~/utils/handle";
-import { path } from "~/utils/path";
-
-export const handle: Handle = {
- breadcrumb: "Approvals",
- to: path.to.approvalSettings
-};
-
-export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "settings",
- role: "employee"
- });
-
- const serviceRole = getCarbonServiceRole();
-
- const [configurations, groupsResult] = await Promise.all([
- getApprovalConfigurations(serviceRole, companyId),
- client
- .from("group")
- .select("id, name")
- .eq("companyId", companyId)
- .eq("isCustomerOrgGroup", false)
- .eq("isSupplierOrgGroup", false)
- ]);
-
- if (configurations.error) {
- console.error(
- "Failed to load approval configurations:",
- configurations.error
- );
- }
-
- if (groupsResult.error) {
- console.error("Failed to load groups:", groupsResult.error);
- }
-
- // Get all configurations grouped by document type
- const poConfigs =
- configurations.data?.filter((c) => c.documentType === "purchaseOrder") ||
- [];
-
- const qdConfigs =
- configurations.data?.filter((c) => c.documentType === "qualityDocument") ||
- [];
-
- return {
- poConfigs,
- qdConfigs,
- groups: groupsResult.data ?? []
- };
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { companyId, userId } = await requirePermissions(request, {
- update: "settings",
- role: "employee"
- });
-
- const serviceRole = getCarbonServiceRole();
-
- const formData = await request.formData();
- const validation = await validator(approvalConfigurationValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const existingId = formData.get("id") as string | null;
-
- const result = await upsertApprovalConfiguration(serviceRole, {
- ...(existingId
- ? { id: existingId, updatedBy: userId }
- : { createdBy: userId, companyId }),
- documentType: validation.data.documentType,
- enabled: validation.data.enabled,
- approverGroupIds: validation.data.approverGroupIds || [],
- defaultApproverId: validation.data.defaultApproverId,
- lowerBoundAmount: validation.data.lowerBoundAmount ?? 0,
- upperBoundAmount: validation.data.upperBoundAmount ?? null,
- escalationDays: validation.data.escalationDays
- });
-
- if (result.error) {
- throw redirect(
- path.to.approvalSettings,
- await flash(request, error(result.error, result.error.message))
- );
- }
-
- throw redirect(
- path.to.approvalSettings,
- await flash(request, success("Approval configuration saved"))
- );
-}
-
-export default function ApprovalSettingsRoute() {
- const loaderData = useLoaderData<typeof loader>();
-
- const poConfigs = loaderData?.poConfigs ?? [];
- const qdConfigs = loaderData?.qdConfigs ?? [];
- const groups = loaderData?.groups ?? [];
-
- const groupOptions = groups.map((g) => ({
- value: g.id,
- label: g.name
- }));
-
- return (
- <ScrollArea className="w-full h-[calc(100dvh-49px)]">
- <VStack
- spacing={4}
- className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"
- >
- <HStack className="justify-between items-center w-full">
- <Heading size="h3">Approval Settings</Heading>
- <Button variant="secondary" size="sm" asChild>
- <Link to={path.to.approvals}>View approval requests</Link>
- </Button>
- </HStack>
-
- {/* Purchase Order Configurations */}
- <Card>
- <CardHeader>
- <CardTitle>Purchase Order Approvals</CardTitle>
- <CardDescription>
- Configure approval workflows for purchase orders by amount ranges.
- Each configuration applies to orders within its specified amount
- range.
- </CardDescription>
- </CardHeader>
- <CardContent>
- {poConfigs.length > 0 ? (
- <div className="flex flex-col gap-4">
- {poConfigs.map((config) => (
- <Card key={config.id}>
- <ValidatedForm
- method="post"
- validator={approvalConfigurationValidator}
- defaultValues={{
- documentType: "purchaseOrder",
- enabled: config.enabled ?? false,
- approverGroupIds: Array.isArray(config.approverGroupIds)
- ? config.approverGroupIds
- : [],
- defaultApproverId:
- config.defaultApproverId ?? undefined,
- lowerBoundAmount: config.lowerBoundAmount ?? 0,
- upperBoundAmount: config.upperBoundAmount ?? undefined,
- escalationDays: config.escalationDays ?? undefined
- }}
- >
- <CardHeader>
- <CardTitle>
- Range: ${config.lowerBoundAmount ?? 0}
- {config.upperBoundAmount !== null
- ? ` - $${config.upperBoundAmount}`
- : "+"}
- </CardTitle>
- </CardHeader>
- <CardContent>
- {config.id && <Hidden name="id" value={config.id} />}
- <Hidden name="documentType" value="purchaseOrder" />
- <div className="flex flex-col gap-6 max-w-[400px]">
- <Switch name="enabled" label="Enabled" />
- <MultiSelect
- name="approverGroupIds"
- label="Approver Groups"
- placeholder="Select groups"
- options={groupOptions}
- />
- <User
- name="defaultApproverId"
- label="Default Approver"
- placeholder="Select a user"
- />
- <Number
- name="lowerBoundAmount"
- label="Lower Bound Amount"
- helperText="Minimum amount (inclusive) for this configuration"
- step={0.01}
- />
- <Number
- name="upperBoundAmount"
- label="Upper Bound Amount"
- helperText="Maximum amount (exclusive) for this configuration. Leave empty for no upper limit."
- step={0.01}
- />
- <Number
- name="escalationDays"
- label="Escalation Days"
- helperText="Auto-escalate after this many days (leave empty to disable)"
- />
- </div>
- </CardContent>
- <CardFooter>
- <Submit>Update</Submit>
- </CardFooter>
- </ValidatedForm>
- </Card>
- ))}
- </div>
- ) : (
- <p className="text-sm text-muted-foreground">
- No purchase order approval configurations. Create one below.
- </p>
- )}
- </CardContent>
- </Card>
-
- {/* Add New Purchase Order Configuration */}
- <Card>
- <CardHeader>
- <CardTitle>Add Purchase Order Configuration</CardTitle>
- <CardDescription>
- Create a new approval configuration for a specific amount range
- </CardDescription>
- </CardHeader>
- <CardContent>
- <ValidatedForm
- method="post"
- validator={approvalConfigurationValidator}
- defaultValues={{
- documentType: "purchaseOrder",
- enabled: true,
- lowerBoundAmount: 0,
- upperBoundAmount: undefined
- }}
- >
- <Hidden name="documentType" value="purchaseOrder" />
- <div className="flex flex-col gap-6 max-w-[400px]">
- <Switch name="enabled" label="Enabled" />
- <MultiSelect
- name="approverGroupIds"
- label="Approver Groups"
- placeholder="Select groups"
- options={groupOptions}
- />
- <User
- name="defaultApproverId"
- label="Default Approver"
- placeholder="Select a user"
- />
- <Number
- name="lowerBoundAmount"
- label="Lower Bound Amount"
- helperText="Minimum amount (inclusive) for this configuration"
- step={0.01}
- />
- <Number
- name="upperBoundAmount"
- label="Upper Bound Amount"
- helperText="Maximum amount (exclusive) for this configuration. Leave empty for no upper limit."
- step={0.01}
- />
- <Number
- name="escalationDays"
- label="Escalation Days"
- helperText="Auto-escalate after this many days (leave empty to disable)"
- />
- </div>
- <CardFooter className="py-4 px-0">
- <Submit>Create Configuration</Submit>
- </CardFooter>
- </ValidatedForm>
- </CardContent>
- </Card>
-
- {/* Quality Document Configurations */}
- <Card>
- <CardHeader>
- <CardTitle>Quality Document Approvals</CardTitle>
- <CardDescription>
- Configure approval workflows for quality documents
- </CardDescription>
- </CardHeader>
- <CardContent>
- {qdConfigs.length > 0 ? (
- <div className="flex flex-col gap-4">
- {qdConfigs.map((config) => (
- <Card key={config.id}>
- <ValidatedForm
- method="post"
- validator={approvalConfigurationValidator}
- defaultValues={{
- documentType: "qualityDocument",
- enabled: config.enabled ?? false,
- approverGroupIds: Array.isArray(config.approverGroupIds)
- ? config.approverGroupIds
- : [],
- defaultApproverId:
- config.defaultApproverId ?? undefined,
- lowerBoundAmount: config.lowerBoundAmount ?? 0,
- upperBoundAmount: config.upperBoundAmount ?? undefined,
- escalationDays: config.escalationDays ?? undefined
- }}
- >
- <CardHeader>
- <CardTitle>Configuration</CardTitle>
- </CardHeader>
- <CardContent>
- {config.id && <Hidden name="id" value={config.id} />}
- <Hidden name="documentType" value="qualityDocument" />
- <div className="flex flex-col gap-6 max-w-[400px]">
- <Switch
- name="enabled"
- label="Enable Quality Document Approvals"
- />
- <MultiSelect
- name="approverGroupIds"
- label="Approver Groups"
- placeholder="Select groups"
- options={groupOptions}
- />
- <User
- name="defaultApproverId"
- label="Default Approver"
- placeholder="Select a user"
- />
- <Number
- name="escalationDays"
- label="Escalation Days"
- helperText="Auto-escalate after this many days (leave empty to disable)"
- />
- </div>
- </CardContent>
- <CardFooter>
- <Submit>Update</Submit>
- </CardFooter>
- </ValidatedForm>
- </Card>
- ))}
- </div>
- ) : (
- <p className="text-sm text-muted-foreground">
- No quality document approval configurations. Create one below.
- </p>
- )}
- </CardContent>
- </Card>
-
- {/* Add New Quality Document Configuration */}
- <Card>
- <CardHeader>
- <CardTitle>Add Quality Document Configuration</CardTitle>
- <CardDescription>
- Create a new approval configuration for quality documents
- </CardDescription>
- </CardHeader>
- <CardContent>
- <ValidatedForm
- method="post"
- validator={approvalConfigurationValidator}
- defaultValues={{
- documentType: "qualityDocument",
- enabled: true,
- lowerBoundAmount: 0,
- upperBoundAmount: undefined
- }}
- >
- <Hidden name="documentType" value="qualityDocument" />
- <div className="flex flex-col gap-6 max-w-[400px]">
- <Switch
- name="enabled"
- label="Enable Quality Document Approvals"
- />
- <MultiSelect
- name="approverGroupIds"
- label="Approver Groups"
- placeholder="Select groups"
- options={groupOptions}
- />
- <User
- name="defaultApproverId"
- label="Default Approver"
- placeholder="Select a user"
- />
- <Number
- name="escalationDays"
- label="Escalation Days"
- helperText="Auto-escalate after this many days (leave empty to disable)"
- />
- </div>
- <CardFooter className="py-4 px-0">
- <Submit>Create Configuration</Submit>
- </CardFooter>
- </ValidatedForm>
- </CardContent>
- </Card>
- </VStack>
- </ScrollArea>
- );
-}