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: remove upper bound and name from approval rules

Brad Barbin95c3fa6b7a26
diff --git a/apps/erp/app/modules/approvals/approvals.models.ts b/apps/erp/app/modules/approvals/approvals.models.ts
index c3fd5a87c5..ed441d3754 100644
--- a/apps/erp/app/modules/approvals/approvals.models.ts
+++ b/apps/erp/app/modules/approvals/approvals.models.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
+import { ApprovalDocumentType } from "./types";
export const approvalStatusType = [
"Pending",
@@ -13,6 +14,15 @@ export const approvalDocumentType = [
"qualityDocument"
] as const;
+export const approvalDocumentTypesWithAmounts: ApprovalDocumentType[] = [
+ "purchaseOrder"
+] as const;
+
+export const approvalDocumentTypeLabel: Record<ApprovalDocumentType, string> = {
+ purchaseOrder: "Purchase Order",
+ qualityDocument: "Quality Document"
+};
+
export const approvalRequestValidator = z.object({
id: zfd.text(z.string().optional()),
documentType: z.enum(approvalDocumentType, {
@@ -35,19 +45,15 @@ export const approvalDecisionValidator = z.object({
export const approvalRuleValidator = z.object({
id: zfd.text(z.string().optional()),
- name: z
- .string()
- .min(1, { message: "Rule name is required" })
- .max(100, { message: "Rule name must be 100 characters or less" }),
documentType: z.enum(approvalDocumentType, {
errorMap: () => ({ message: "Document type is required" })
}),
- enabled: zfd.checkbox(),
- approverGroupIds: zfd.repeatableOfType(z.string()).optional(),
+ approverGroupIds: z.array(
+ z.string().min(1, { message: "Invalid selection" })
+ ),
defaultApproverId: zfd.text(z.string().optional()),
- lowerBoundAmount: zfd.numeric(z.number().min(0).default(0)),
- upperBoundAmount: zfd.numeric(z.number().min(0).nullable()).optional(),
- escalationDays: zfd.numeric(z.number().min(0).optional())
+ lowerBoundAmount: zfd.numeric(z.number().gt(0).default(0)).optional(),
+ enabled: zfd.checkbox()
});
export const approvalFiltersValidator = z.object({
diff --git a/apps/erp/app/modules/approvals/approvals.service.ts b/apps/erp/app/modules/approvals/approvals.service.ts
index 127d0c163e..00a540d41a 100644
--- a/apps/erp/app/modules/approvals/approvals.service.ts
+++ b/apps/erp/app/modules/approvals/approvals.service.ts
@@ -1,5 +1,5 @@
import type { Database } from "@carbon/database";
-import { getPurchaseOrderStatus, roundAmount } from "@carbon/utils";
+import { getPurchaseOrderStatus } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getPurchaseOrderLines } from "~/modules/purchasing";
import type { GenericQueryFilters } from "~/utils/query";
@@ -66,6 +66,18 @@ export function canCancelRequest(
);
}
+export async function deleteApprovalRule(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ return client
+ .from("approvalRule")
+ .delete()
+ .eq("id", id)
+ .eq("companyId", companyId);
+}
+
export async function getApprovalsForUser(
client: SupabaseClient<Database>,
userId: string,
@@ -141,6 +153,19 @@ export async function getPendingApprovalsForApprover(
return query.order("requestedAt", { ascending: false });
}
+export async function getApprovalRuleById(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ return client
+ .from("approvalRule")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+}
+
export async function getApprovalById(
client: SupabaseClient<Database>,
id: string
@@ -427,36 +452,6 @@ export async function getApprovalRuleByAmount(
.maybeSingle();
}
-async function checkApprovalRuleRangeDuplicate(
- client: SupabaseClient<Database>,
- companyId: string,
- documentType: (typeof approvalDocumentType)[number],
- lowerBoundAmount: number,
- upperBoundAmount: number | null,
- excludeId?: string
-): Promise<boolean> {
- const lower = roundAmount(lowerBoundAmount);
- let query = client
- .from("approvalRule")
- .select("id")
- .eq("companyId", companyId)
- .eq("documentType", documentType)
- .eq("lowerBoundAmount", lower);
-
- if (upperBoundAmount == null) {
- query = query.is("upperBoundAmount", null);
- } else {
- query = query.eq("upperBoundAmount", roundAmount(upperBoundAmount));
- }
-
- if (excludeId) {
- query = query.neq("id", excludeId);
- }
-
- const { data } = await query.limit(1);
- return Array.isArray(data) && data.length > 0;
-}
-
export async function getApprovalRules(
client: SupabaseClient<Database>,
companyId: string
@@ -468,13 +463,6 @@ export async function upsertApprovalRule(
client: SupabaseClient<Database>,
rule: UpsertApprovalRuleInput
) {
- const lower = roundAmount(Number(rule.lowerBoundAmount ?? 0));
- const rawUpper = rule.upperBoundAmount;
- const upper =
- rawUpper != null && !Number.isNaN(Number(rawUpper))
- ? roundAmount(Number(rawUpper))
- : null;
-
if ("id" in rule) {
const existing = await client
.from("approvalRule")
@@ -489,24 +477,6 @@ export async function upsertApprovalRule(
};
}
- const duplicate = await checkApprovalRuleRangeDuplicate(
- client,
- existing.data.companyId,
- rule.documentType,
- lower,
- upper,
- rule.id
- );
- if (duplicate) {
- return {
- data: null,
- error: {
- message:
- "Another approval rule already exists for this amount range. Use a different range or edit the existing rule."
- }
- };
- }
-
return client
.from("approvalRule")
.update(sanitize(rule))
@@ -516,23 +486,6 @@ export async function upsertApprovalRule(
.single();
}
- const duplicate = await checkApprovalRuleRangeDuplicate(
- client,
- rule.companyId,
- rule.documentType,
- lower,
- upper
- );
- if (duplicate) {
- return {
- data: null,
- error: {
- message:
- "Another approval rule already exists for this amount range. Use a different range or edit the existing rule."
- }
- };
- }
-
return client.from("approvalRule").insert([rule]).select("id").single();
}
diff --git a/apps/erp/app/modules/approvals/ui/ApprovalRuleCard.tsx b/apps/erp/app/modules/approvals/ui/ApprovalRuleCard.tsx
index f46f267b9c..33f65b270a 100644
--- a/apps/erp/app/modules/approvals/ui/ApprovalRuleCard.tsx
+++ b/apps/erp/app/modules/approvals/ui/ApprovalRuleCard.tsx
@@ -10,6 +10,7 @@ import {
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
+ Heading,
HStack,
IconButton,
useDisclosure
@@ -18,19 +19,19 @@ import { memo, useCallback } from "react";
import { LuEllipsisVertical, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import { useCurrencyFormatter, usePermissions, useUrlParams } from "~/hooks";
import {
- useCurrencyFormatter,
- usePermissions,
- useUrlParams,
- useUser
-} from "~/hooks";
-import type { ApprovalRule } from "~/modules/approvals";
+ ApprovalDocumentType,
+ type ApprovalRule,
+ approvalDocumentTypeLabel,
+ approvalDocumentTypesWithAmounts
+} from "~/modules/approvals";
import { path } from "~/utils/path";
import ApprovalRuleDetails from "./ApprovalRuleDetails";
type ApprovalRuleCardProps = {
rule: ApprovalRule & { approverGroupNames?: string[] };
- documentType: "purchaseOrder" | "qualityDocument";
+ documentType: ApprovalDocumentType;
};
const ApprovalRuleCard = memo(
@@ -38,14 +39,14 @@ const ApprovalRuleCard = memo(
const [params] = useUrlParams();
const navigate = useNavigate();
const permissions = usePermissions();
- const user = useUser();
- const currencyFormatter = useCurrencyFormatter();
+ const currencyFormatter = useCurrencyFormatter({
+ notation: "compact", // short/compact form
+ compactDisplay: "short" // "short" → 1.2M, "long" → 1.2 million
+ });
const deleteDisclosure = useDisclosure();
- const canEdit =
- permissions.can("update", "settings") && rule.createdBy === user?.id;
- const canDelete =
- permissions.can("update", "settings") && rule.createdBy === user?.id;
+ const canEdit = permissions.can("update", "settings");
+ const canDelete = permissions.can("update", "settings");
const handleEdit = useCallback(() => {
if (!rule.id) return;
@@ -68,23 +69,21 @@ const ApprovalRuleCard = memo(
<Accordion type="multiple" className="w-full">
<AccordionItem value={rule.id} className="border-none">
<div className="relative">
- <AccordionTrigger className="px-6 py-4 hover:no-underline w-full">
- <HStack spacing={4} className="flex-1">
+ <AccordionTrigger className="px-6 py-8 hover:no-underline w-full">
+ <HStack spacing={4} className="flex-1 justify-between pr-12">
+ <Heading size="h4" as="h3">
+ {approvalDocumentTypeLabel[documentType]}
+ {approvalDocumentTypesWithAmounts.includes(
+ documentType
+ ) &&
+ ` over ${currencyFormatter.format(rule.lowerBoundAmount ?? 0)}`}
+ </Heading>
<Badge
variant={rule.enabled ? "green" : "gray"}
className="text-xs font-medium"
>
{rule.enabled ? "Enabled" : "Disabled"}
</Badge>
- <span className="font-medium text-sm">{rule.name}</span>
- {documentType === "purchaseOrder" && (
- <span className="text-xs text-muted-foreground">
- {currencyFormatter.format(rule.lowerBoundAmount ?? 0)}
- {rule.upperBoundAmount
- ? ` - ${currencyFormatter.format(rule.upperBoundAmount)}`
- : "+"}
- </span>
- )}
</HStack>
</AccordionTrigger>
<div className="absolute right-12 top-1/2 -translate-y-1/2 z-10">
diff --git a/apps/erp/app/modules/approvals/ui/ApprovalRuleDetails.tsx b/apps/erp/app/modules/approvals/ui/ApprovalRuleDetails.tsx
index 56a5005576..2d6e50489d 100644
--- a/apps/erp/app/modules/approvals/ui/ApprovalRuleDetails.tsx
+++ b/apps/erp/app/modules/approvals/ui/ApprovalRuleDetails.tsx
@@ -1,11 +1,4 @@
-import {
- Badge,
- HStack,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
- VStack
-} from "@carbon/react";
+import { cn, HStack, VStack } from "@carbon/react";
import { formatDate } from "@carbon/utils";
import { memo } from "react";
import {
@@ -16,6 +9,7 @@ import {
LuUsers
} from "react-icons/lu";
import { EmployeeAvatar } from "~/components";
+import { UserSelect } from "~/components/Selectors";
import type { ApprovalDocumentType, ApprovalRule } from "~/modules/approvals";
type ApprovalRuleDetailsProps = {
@@ -33,7 +27,7 @@ type FieldItemProps = {
const FieldItem = memo(
({ icon: Icon, label, children, className }: FieldItemProps) => (
- <VStack spacing={2} className={className}>
+ <VStack spacing={2} className={cn("w-full justify-start", className)}>
<HStack spacing={2} className="items-center">
<div className="flex items-center justify-center w-6 h-6 rounded-md bg-muted/50 shrink-0">
<Icon className="h-3.5 w-3.5 text-muted-foreground" />
@@ -42,7 +36,7 @@ const FieldItem = memo(
{label}
</p>
</HStack>
- <div className="pl-8">{children}</div>
+ <div className="pl-8 w-full">{children}</div>
</VStack>
)
);
@@ -51,60 +45,30 @@ FieldItem.displayName = "FieldItem";
const ApprovalRuleDetails = memo(
({ rule, documentType, currencyFormatter }: ApprovalRuleDetailsProps) => {
- const groupNames = rule.approverGroupNames || [];
-
return (
<VStack spacing={4} className="w-full">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
{documentType === "purchaseOrder" && (
- <FieldItem icon={LuDollarSign} label="Amount Range">
+ <FieldItem icon={LuDollarSign} label="Minimum Amount">
<p className="text-sm font-semibold text-foreground leading-relaxed">
{currencyFormatter.format(rule.lowerBoundAmount ?? 0)}
- {rule.upperBoundAmount
- ? ` - ${currencyFormatter.format(rule.upperBoundAmount)}`
- : " and above"}
</p>
</FieldItem>
)}
{/* Approver Groups */}
- <FieldItem
- icon={LuUsers}
- label="Approver Groups"
- className={documentType === "purchaseOrder" ? "" : "md:col-span-2"}
- >
- {groupNames.length > 0 ? (
- <HStack spacing={2} className="flex-wrap">
- {groupNames.map((name, idx) => (
- <Tooltip key={idx}>
- <TooltipTrigger asChild>
- <Badge
- variant="outline"
- className="cursor-help text-xs font-medium px-2.5 py-1"
- >
- {name}
- </Badge>
- </TooltipTrigger>
- <TooltipContent>
- <p className="text-xs">
- Members of this group can approve documents matching
- this rule
- </p>
- </TooltipContent>
- </Tooltip>
- ))}
- </HStack>
+ <FieldItem icon={LuUsers} label="Approvers">
+ {rule.approverGroupIds && rule.approverGroupIds.length > 0 ? (
+ <UserSelect
+ value={rule.approverGroupIds ?? []}
+ readOnly
+ isMulti
+ className="w-full"
+ />
) : (
- <VStack spacing={1}>
- <p className="text-sm text-muted-foreground leading-relaxed">
- No groups assigned
- </p>
- {rule.defaultApproverId && (
- <p className="text-xs text-muted-foreground leading-relaxed">
- Using default approver instead
- </p>
- )}
- </VStack>
+ <p className="text-sm text-muted-foreground leading-relaxed">
+ No groups assigned
+ </p>
)}
</FieldItem>
diff --git a/apps/erp/app/modules/approvals/ui/ApprovalRuleDrawer.tsx b/apps/erp/app/modules/approvals/ui/ApprovalRuleForm.tsx
similarity index 56%
rename from apps/erp/app/modules/approvals/ui/ApprovalRuleDrawer.tsx
rename to apps/erp/app/modules/approvals/ui/ApprovalRuleForm.tsx
index 18002a8e53..91e4e73234 100644
--- a/apps/erp/app/modules/approvals/ui/ApprovalRuleDrawer.tsx
+++ b/apps/erp/app/modules/approvals/ui/ApprovalRuleForm.tsx
@@ -2,8 +2,6 @@ import {
Boolean as FormBoolean,
Number as FormNumber,
Hidden,
- Input,
- SelectControlled,
Submit,
ValidatedForm
} from "@carbon/form";
@@ -18,53 +16,37 @@ import {
HStack,
VStack
} from "@carbon/react";
-import { useState } from "react";
import { Employee, Users } from "~/components/Form";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useUser } from "~/hooks";
import {
ApprovalDocumentType,
type ApprovalRule,
+ approvalDocumentTypesWithAmounts,
approvalRuleValidator
} from "~/modules/approvals";
import { path } from "~/utils/path";
-type ApprovalRuleDrawerProps = {
+type ApprovalRuleFormProps = {
rule: ApprovalRule | null;
documentType: ApprovalDocumentType | null;
- groups?: Array<{ id: string; name: string }>;
- canEdit?: boolean;
onClose: () => void;
};
-const ApprovalRuleDrawer = ({
+const ApprovalRuleForm = ({
rule,
documentType,
- groups,
- canEdit = true,
onClose
-}: ApprovalRuleDrawerProps) => {
+}: ApprovalRuleFormProps) => {
const permissions = usePermissions();
- const isEditing = !!rule;
- const isDisabled =
- !permissions.can("update", "settings") || (isEditing && !canEdit);
-
- const [selectedDocumentType, setSelectedDocumentType] =
- useState<ApprovalDocumentType | null>(documentType || null);
-
- const documentTypeOptions: Array<{
- value: ApprovalDocumentType;
- label: string;
- }> = [
- { value: "purchaseOrder", label: "Purchase Order" },
- { value: "qualityDocument", label: "Quality Document" }
- ];
-
- const effectiveDocumentType = rule?.documentType || selectedDocumentType;
-
+ const {
+ company: { baseCurrencyCode }
+ } = useUser();
+ const isEditing = !!rule?.id;
+ const isDisabled = !permissions.can("update", "settings");
+ const effectiveDocumentType = rule?.documentType || documentType;
const defaultValues = rule
? {
id: rule.id,
- name: rule.name ?? "",
documentType: rule.documentType,
enabled: rule.enabled ?? false,
approverGroupIds: Array.isArray(rule.approverGroupIds)
@@ -72,16 +54,14 @@ const ApprovalRuleDrawer = ({
: [],
defaultApproverId: rule.defaultApproverId ?? undefined,
lowerBoundAmount: rule.lowerBoundAmount ?? 0,
- upperBoundAmount: rule.upperBoundAmount ?? undefined,
escalationDays: rule.escalationDays ?? undefined
}
: {
name: "",
- documentType: selectedDocumentType || undefined,
+ documentType: documentType || undefined,
enabled: true,
approverGroupIds: [],
lowerBoundAmount: 0,
- upperBoundAmount: undefined,
escalationDays: undefined
};
@@ -108,76 +88,51 @@ const ApprovalRuleDrawer = ({
<VStack spacing={4} className="items-stretch">
{isEditing && rule?.id && <Hidden name="id" value={rule.id} />}
- {!isEditing && (
- <SelectControlled
- name="documentType"
- label="Document Type"
- options={documentTypeOptions}
- value={selectedDocumentType || ""}
- onChange={(option) => {
- if (option) {
- setSelectedDocumentType(
- option.value as ApprovalDocumentType
- );
- }
- }}
- />
- )}
-
- {isEditing && effectiveDocumentType && (
+ {effectiveDocumentType && (
<Hidden name="documentType" value={effectiveDocumentType} />
)}
- <FormBoolean
- name="enabled"
- label="Enabled"
- helperText="Enable this rule to automatically require approval for matching documents"
- variant="large"
- />
-
- <Input name="name" label="Rule Name" required />
+ {/* Purchase Order Specific Fields */}
+ {effectiveDocumentType &&
+ approvalDocumentTypesWithAmounts.includes(
+ effectiveDocumentType
+ ) && (
+ <>
+ <FormNumber
+ name="lowerBoundAmount"
+ label="Minimum Amount"
+ step={100}
+ formatOptions={{
+ style: "currency",
+ currency: baseCurrencyCode
+ }}
+ />
+ </>
+ )}
<Users
- type="employee"
name="approverGroupIds"
- label="Approver Groups"
+ label="Approvers"
placeholder="Select approver groups"
/>
<Employee
name="defaultApproverId"
- label="Default Approver (Optional)"
+ label="Default Approver"
placeholder="Select a default approver"
/>
- {/* Purchase Order Specific Fields */}
- {effectiveDocumentType === "purchaseOrder" && (
- <>
- <FormNumber
- name="lowerBoundAmount"
- label="Minimum Amount"
- formatOptions={{
- style: "currency",
- currency: "USD"
- }}
- />
-
- <FormNumber
- name="upperBoundAmount"
- label="Maximum Amount (Optional)"
- formatOptions={{
- style: "currency",
- currency: "USD"
- }}
- />
- </>
- )}
-
- <FormNumber
+ <FormBoolean
+ name="enabled"
+ label="Enabled"
+ helperText="Enable this rule to automatically require approval for matching documents"
+ variant="large"
+ />
+ {/* <FormNumber
name="escalationDays"
label="Escalation Days"
helperText="Automatically escalate approval requests after this many days. Leave empty to disable escalation."
- />
+ /> */}
</VStack>
</DrawerBody>
<DrawerFooter>
@@ -196,4 +151,4 @@ const ApprovalRuleDrawer = ({
);
};
-export default ApprovalRuleDrawer;
+export default ApprovalRuleForm;
diff --git a/apps/erp/app/modules/approvals/ui/ApprovalRules.tsx b/apps/erp/app/modules/approvals/ui/ApprovalRules.tsx
index d6fade4f22..9de796fa17 100644
--- a/apps/erp/app/modules/approvals/ui/ApprovalRules.tsx
+++ b/apps/erp/app/modules/approvals/ui/ApprovalRules.tsx
@@ -14,7 +14,10 @@ import { LuInbox, LuPlus } from "react-icons/lu";
import { Link } from "react-router";
import { Empty } from "~/components";
import { usePermissions } from "~/hooks";
-import type { ApprovalRule } from "~/modules/approvals";
+import {
+ type ApprovalRule,
+ approvalDocumentTypesWithAmounts
+} from "~/modules/approvals";
import { path } from "~/utils/path";
import ApprovalRuleCard from "./ApprovalRuleCard";
@@ -29,7 +32,7 @@ const ApprovalRules = memo(({ poRules, qdRules }: ApprovalRulesProps) => {
return (
<ScrollArea className="h-full w-full">
- <div className="px-4 py-6 md:px-6 lg:px-8 max-w-[90rem] mx-auto">
+ <div className="py-12 px-4 max-w-[60rem] mx-auto">
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
<Heading size="h2">Approval Rules</Heading>
@@ -52,7 +55,9 @@ const ApprovalRules = memo(({ poRules, qdRules }: ApprovalRulesProps) => {
</div>
{canCreate && (
<Button variant="primary" leftIcon={<LuPlus />} asChild>
- <Link to={path.to.newApprovalRule()}>New Rule</Link>
+ <Link to={path.to.newApprovalRule("purchaseOrder")}>
+ New Rule
+ </Link>
</Button>
)}
</div>
@@ -85,11 +90,15 @@ const ApprovalRules = memo(({ poRules, qdRules }: ApprovalRulesProps) => {
Require approval for quality documents in your workflow
</CardDescription>
</div>
- {canCreate && (
- <Button variant="primary" leftIcon={<LuPlus />} asChild>
- <Link to={path.to.newApprovalRule()}>New Rule</Link>
- </Button>
- )}
+ {canCreate &&
+ (approvalDocumentTypesWithAmounts.includes("qualityDocument") ||
+ qdRules.length === 0) && (
+ <Button variant="primary" leftIcon={<LuPlus />} asChild>
+ <Link to={path.to.newApprovalRule("qualityDocument")}>
+ New Rule
+ </Link>
+ </Button>
+ )}
</div>
</CardHeader>
<CardContent>
diff --git a/apps/erp/app/modules/approvals/ui/index.ts b/apps/erp/app/modules/approvals/ui/index.ts
index b7954be945..36b6c5b799 100644
--- a/apps/erp/app/modules/approvals/ui/index.ts
+++ b/apps/erp/app/modules/approvals/ui/index.ts
@@ -1,5 +1,6 @@
export { default as ApprovalDecisionModal } from "./ApprovalDecisionModal";
export { default as ApprovalHistory } from "./ApprovalHistory";
-export { default as ApprovalRuleDrawer } from "./ApprovalRuleDrawer";
+export { default as ApprovalRuleForm } from "./ApprovalRuleForm";
+
export { default as ApprovalStatus } from "./ApprovalStatus";
export { default as ApprovalsTable } from "./ApprovalsTable";
diff --git a/apps/erp/app/routes/x+/settings+/approval-rules.$id.delete.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.$id.delete.tsx
index 2445b25626..1dcc69ad7c 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.$id.delete.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.$id.delete.tsx
@@ -1,140 +1,21 @@
-import { error, getCarbonServiceRole, success } from "@carbon/auth";
+import { error, 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 type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { getApprovalRules } from "~/modules/approvals";
+import { deleteApprovalRule } 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.approvalRules,
- 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.approvalRules,
- await flash(request, error(null, "Approval rule not found"))
- );
- }
-
- if (rule.createdBy !== userId) {
- throw redirect(
- path.to.approvalRules,
- 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",
+ const { client, companyId } = await requirePermissions(request, {
+ delete: "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.approvalRules,
- await flash(request, error(null, "Approval rule not found"))
- );
- }
-
- if (rule.createdBy !== userId) {
- throw redirect(
- path.to.approvalRules,
- 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.approvalRules,
- 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.approvalRules,
- 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();
+ const result = await deleteApprovalRule(client, id, companyId);
if (result.error) {
throw redirect(
@@ -146,22 +27,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- if (!result.data || result.data.length === 0) {
- throw redirect(
- path.to.approvalRules,
- await flash(
- request,
- error(null, "Approval rule not found or already deleted")
- )
- );
- }
-
throw redirect(
`${path.to.approvalRules}?${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+/approval-rules.$id.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx
index 07f37b4db8..3bb76e70b3 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx
@@ -12,14 +12,16 @@ import { redirect, useLoaderData, useNavigate } from "react-router";
import { useUrlParams } from "~/hooks";
import {
approvalRuleValidator,
+ getApprovalRuleById,
getApprovalRules,
upsertApprovalRule
} from "~/modules/approvals";
-import ApprovalRuleDrawer from "~/modules/approvals/ui/ApprovalRuleDrawer";
+import ApprovalRuleForm from "~/modules/approvals/ui/ApprovalRuleForm";
+
import { getParams, path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "settings",
role: "employee"
});
@@ -27,51 +29,24 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
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.approvalRules,
- await flash(request, error(rules.error, "Failed to load approval rule"))
- );
- }
+ const rule = await getApprovalRuleById(client, id, companyId);
- if (groupsResult.error) {
+ if (rule.error) {
throw redirect(
path.to.approvalRules,
- await flash(
- request,
- error(groupsResult.error, "Failed to load approver groups")
- )
+ await flash(request, error(rule.error, "Failed to load approval rule"))
);
}
- const rule = rules.data?.find((r) => r.id === id);
-
- if (!rule) {
+ if (!rule.data) {
throw redirect(
path.to.approvalRules,
await flash(request, error(null, "Approval rule not found"))
);
}
- // Check if user can edit (only creator can edit)
- const canEdit = rule.createdBy === userId;
-
return {
- rule,
- groups: groupsResult.data ?? [],
- canEdit
+ rule: rule.data
};
}
@@ -119,14 +94,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
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
+ lowerBoundAmount: validation.data.lowerBoundAmount ?? 0
});
if (result.error) {
@@ -149,18 +121,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function EditApprovalRuleRoute() {
- const { rule, groups, canEdit } = useLoaderData<typeof loader>();
+ const { rule } = useLoaderData<typeof loader>();
const navigate = useNavigate();
const [params] = useUrlParams();
const onClose = () =>
navigate(`${path.to.approvalRules}?${params.toString()}`);
return (
- <ApprovalRuleDrawer
+ <ApprovalRuleForm
rule={rule}
documentType={rule.documentType}
- groups={groups}
- canEdit={canEdit}
onClose={onClose}
/>
);
diff --git a/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx
index e85d277dc1..7081fa65cd 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx
@@ -9,37 +9,31 @@ 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 { approvalRuleValidator, upsertApprovalRule } from "~/modules/approvals";
-import ApprovalRuleDrawer from "~/modules/approvals/ui/ApprovalRuleDrawer";
+import {
+ type ApprovalDocumentType,
+ approvalRuleValidator,
+ upsertApprovalRule
+} from "~/modules/approvals";
+import ApprovalRuleForm from "~/modules/approvals/ui/ApprovalRuleForm";
+
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
+ await requirePermissions(request, {
view: "settings",
role: "employee"
});
- const groupsResult = await client
- .from("group")
- .select("id, name")
- .eq("companyId", companyId)
- .eq("isCustomerOrgGroup", false)
- .eq("isSupplierOrgGroup", false);
-
- if (groupsResult.error) {
- throw redirect(
- path.to.approvalRules,
- await flash(
- request,
- error(groupsResult.error, "Failed to load approver groups")
- )
- );
- }
+ const url = new URL(request.url);
+ const typeParam = url.searchParams.get("type");
+ const documentType: ApprovalDocumentType | null =
+ typeParam === "purchaseOrder" || typeParam === "qualityDocument"
+ ? typeParam
+ : null;
return {
rule: null,
- documentType: null,
- groups: groupsResult.data ?? []
+ documentType: documentType as ApprovalDocumentType | null
};
}
@@ -63,14 +57,11 @@ export async function action({ request }: ActionFunctionArgs) {
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
+ lowerBoundAmount: validation.data.lowerBoundAmount ?? 0
});
if (result.error) {
@@ -93,15 +84,14 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function NewApprovalRuleRoute() {
- const { rule, documentType, groups } = useLoaderData<typeof loader>();
+ const { rule, documentType } = useLoaderData<typeof loader>();
const navigate = useNavigate();
const onClose = () => navigate(path.to.approvalRules);
return (
- <ApprovalRuleDrawer
+ <ApprovalRuleForm
rule={rule}
documentType={documentType}
- groups={groups}
onClose={onClose}
/>
);
diff --git a/apps/erp/app/routes/x+/settings+/approval-rules.tsx b/apps/erp/app/routes/x+/settings+/approval-rules.tsx
index 253d1b331a..2a158aedb3 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.tsx
@@ -51,11 +51,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
: []
}));
- const poRules =
- enrichedRules.filter((r) => r.documentType === "purchaseOrder") || [];
+ const poRules = enrichedRules
+ .filter((r) => r.documentType === "purchaseOrder")
+ .sort((a, b) => (a.lowerBoundAmount ?? 0) - (b.lowerBoundAmount ?? 0));
- const qdRules =
- enrichedRules.filter((r) => r.documentType === "qualityDocument") || [];
+ const qdRules = enrichedRules.filter(
+ (r) => r.documentType === "qualityDocument"
+ );
return {
poRules,
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 4955fc92a0..66e302d560 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -372,7 +372,10 @@ export const path = {
approvalRules: `${x}/settings/approval-rules`,
approvalRule: (id: string) =>
generatePath(`${x}/settings/approval-rules/${id}`),
- newApprovalRule: () => `${x}/settings/approval-rules/new`,
+ newApprovalRule: (documentType?: string) =>
+ documentType
+ ? `${x}/settings/approval-rules/new?type=${documentType}`
+ : `${x}/settings/approval-rules/new`,
deleteApprovalRule: (id: string) =>
generatePath(`${x}/settings/approval-rules/${id}/delete`),
abilities: `${x}/resources/abilities`,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index dcc4dd2a7a..32c5fcf94a 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -3939,9 +3939,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRequests.requestedAt",
},
- {
- $ref: "#/parameters/rowFilter.approvalRequests.approverGroupIds",
- },
{
$ref: "#/parameters/rowFilter.approvalRequests.approverId",
},
@@ -3966,27 +3963,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRequests.documentDescription",
},
- {
- $ref: "#/parameters/rowFilter.approvalRequests.requestedByName",
- },
- {
- $ref: "#/parameters/rowFilter.approvalRequests.requestedByAvatarUrl",
- },
- {
- $ref: "#/parameters/rowFilter.approvalRequests.approverName",
- },
- {
- $ref: "#/parameters/rowFilter.approvalRequests.approverAvatarUrl",
- },
- {
- $ref: "#/parameters/rowFilter.approvalRequests.decisionByName",
- },
- {
- $ref: "#/parameters/rowFilter.approvalRequests.decisionByAvatarUrl",
- },
- {
- $ref: "#/parameters/rowFilter.approvalRequests.approverGroupNames",
- },
{
$ref: "#/parameters/select",
},
@@ -38838,9 +38814,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRequest.requestedAt",
},
- {
- $ref: "#/parameters/rowFilter.approvalRequest.approverGroupIds",
- },
{
$ref: "#/parameters/rowFilter.approvalRequest.approverId",
},
@@ -38945,9 +38918,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRequest.requestedAt",
},
- {
- $ref: "#/parameters/rowFilter.approvalRequest.approverGroupIds",
- },
{
$ref: "#/parameters/rowFilter.approvalRequest.approverId",
},
@@ -39006,9 +38976,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRequest.requestedAt",
},
- {
- $ref: "#/parameters/rowFilter.approvalRequest.approverGroupIds",
- },
{
$ref: "#/parameters/rowFilter.approvalRequest.approverId",
},
@@ -60360,9 +60327,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRule.id",
},
- {
- $ref: "#/parameters/rowFilter.approvalRule.name",
- },
{
$ref: "#/parameters/rowFilter.approvalRule.documentType",
},
@@ -60378,9 +60342,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRule.lowerBoundAmount",
},
- {
- $ref: "#/parameters/rowFilter.approvalRule.upperBoundAmount",
- },
{
$ref: "#/parameters/rowFilter.approvalRule.escalationDays",
},
@@ -60461,9 +60422,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRule.id",
},
- {
- $ref: "#/parameters/rowFilter.approvalRule.name",
- },
{
$ref: "#/parameters/rowFilter.approvalRule.documentType",
},
@@ -60479,9 +60437,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRule.lowerBoundAmount",
},
- {
- $ref: "#/parameters/rowFilter.approvalRule.upperBoundAmount",
- },
{
$ref: "#/parameters/rowFilter.approvalRule.escalationDays",
},
@@ -60516,9 +60471,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRule.id",
},
- {
- $ref: "#/parameters/rowFilter.approvalRule.name",
- },
{
$ref: "#/parameters/rowFilter.approvalRule.documentType",
},
@@ -60534,9 +60486,6 @@ export default {
{
$ref: "#/parameters/rowFilter.approvalRule.lowerBoundAmount",
},
- {
- $ref: "#/parameters/rowFilter.approvalRule.upperBoundAmount",
- },
{
$ref: "#/parameters/rowFilter.approvalRule.escalationDays",
},
@@ -67181,13 +67130,6 @@ export default {
format: "timestamp with time zone",
type: "string",
},
- approverGroupIds: {
- format: "text[]",
- items: {
- type: "string",
- },
- type: "array",
- },
approverId: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -67226,37 +67168,6 @@ export default {
format: "text",
type: "string",
},
- requestedByName: {
- format: "text",
- type: "string",
- },
- requestedByAvatarUrl: {
- format: "text",
- type: "string",
- },
- approverName: {
- format: "text",
- type: "string",
- },
- approverAvatarUrl: {
- format: "text",
- type: "string",
- },
- decisionByName: {
- format: "text",
- type: "string",
- },
- decisionByAvatarUrl: {
- format: "text",
- type: "string",
- },
- approverGroupNames: {
- format: "text[]",
- items: {
- type: "string",
- },
- type: "array",
- },
},
type: "object",
},
@@ -83578,13 +83489,6 @@ export default {
format: "timestamp with time zone",
type: "string",
},
- approverGroupIds: {
- format: "text[]",
- items: {
- type: "string",
- },
- type: "array",
- },
approverId: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -94251,7 +94155,6 @@ export default {
approvalRule: {
required: [
"id",
- "name",
"documentType",
"enabled",
"lowerBoundAmount",
@@ -94261,15 +94164,11 @@ export default {
],
properties: {
id: {
- default: "public.id('aprl'::text)",
+ default: "public.id('approval'::text)",
description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
type: "string",
},
- name: {
- format: "text",
- type: "string",
- },
documentType: {
enum: ["purchaseOrder", "qualityDocument"],
format: 'public."approvalDocumentType"',
@@ -94298,10 +94197,6 @@ export default {
format: "numeric",
type: "number",
},
- upperBoundAmount: {
- format: "numeric",
- type: "number",
- },
escalationDays: {
format: "integer",
type: "integer",
@@ -96638,12 +96533,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.approvalRequests.approverGroupIds": {
- name: "approverGroupIds",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.approvalRequests.approverId": {
name: "approverId",
required: false,
@@ -96692,48 +96581,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.approvalRequests.requestedByName": {
- name: "requestedByName",
- required: false,
- in: "query",
- type: "string",
- },
- "rowFilter.approvalRequests.requestedByAvatarUrl": {
- name: "requestedByAvatarUrl",
- required: false,
- in: "query",
- type: "string",
- },
- "rowFilter.approvalRequests.approverName": {
- name: "approverName",
- required: false,
- in: "query",
- type: "string",
- },
- "rowFilter.approvalRequests.approverAvatarUrl": {
- name: "approverAvatarUrl",
- required: false,
- in: "query",
- type: "string",
- },
- "rowFilter.approvalRequests.decisionByName": {
- name: "decisionByName",
- required: false,
- in: "query",
- type: "string",
- },
- "rowFilter.approvalRequests.decisionByAvatarUrl": {
- name: "decisionByAvatarUrl",
- required: false,
- in: "query",
- type: "string",
- },
- "rowFilter.approvalRequests.approverGroupNames": {
- name: "approverGroupNames",
- required: false,
- in: "query",
- type: "string",
- },
"body.jobOperationsWithDependencies": {
name: "jobOperationsWithDependencies",
description: "jobOperationsWithDependencies",
@@ -115057,12 +114904,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.approvalRequest.approverGroupIds": {
- name: "approverGroupIds",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.approvalRequest.approverId": {
name: "approverId",
required: false,
@@ -127060,12 +126901,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.approvalRule.name": {
- name: "name",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.approvalRule.documentType": {
name: "documentType",
required: false,
@@ -127096,12 +126931,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.approvalRule.upperBoundAmount": {
- name: "upperBoundAmount",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.approvalRule.escalationDays": {
name: "escalationDays",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index d83e982cdc..89adef245e 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1694,7 +1694,6 @@ export type Database = {
}
approvalRequest: {
Row: {
- approverGroupIds: string[] | null
approverId: string | null
companyId: string
createdAt: string
@@ -1712,7 +1711,6 @@ export type Database = {
updatedBy: string | null
}
Insert: {
- approverGroupIds?: string[] | null
approverId?: string | null
companyId: string
createdAt?: string
@@ -1730,7 +1728,6 @@ export type Database = {
updatedBy?: string | null
}
Update: {
- approverGroupIds?: string[] | null
approverId?: string | null
companyId?: string
createdAt?: string
@@ -1965,10 +1962,8 @@ export type Database = {
escalationDays: number | null
id: string
lowerBoundAmount: number
- name: string
updatedAt: string | null
updatedBy: string | null
- upperBoundAmount: number | null
}
Insert: {
approverGroupIds?: string[] | null
@@ -1981,10 +1976,8 @@ export type Database = {
escalationDays?: number | null
id?: string
lowerBoundAmount?: number
- name: string
updatedAt?: string | null
updatedBy?: string | null
- upperBoundAmount?: number | null
}
Update: {
approverGroupIds?: string[] | null
@@ -1997,10 +1990,8 @@ export type Database = {
escalationDays?: number | null
id?: string
lowerBoundAmount?: number
- name?: string
updatedAt?: string | null
updatedBy?: string | null
- upperBoundAmount?: number | null
}
Relationships: [
{
@@ -41374,17 +41365,11 @@ export type Database = {
}
approvalRequests: {
Row: {
- approverAvatarUrl: string | null
- approverGroupIds: string[] | null
- approverGroupNames: string[] | null
approverId: string | null
- approverName: string | null
companyId: string | null
createdAt: string | null
decisionAt: string | null
decisionBy: string | null
- decisionByAvatarUrl: string | null
- decisionByName: string | null
decisionNotes: string | null
documentDescription: string | null
documentId: string | null
@@ -41395,8 +41380,6 @@ export type Database = {
id: string | null
requestedAt: string | null
requestedBy: string | null
- requestedByAvatarUrl: string | null
- requestedByName: string | null
status: Database["public"]["Enums"]["approvalStatus"] | null
}
Relationships: [
@@ -45980,14 +45963,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -47360,14 +47343,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -50051,14 +50034,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -50594,14 +50577,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index d83e982cdc..89adef245e 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -1694,7 +1694,6 @@ export type Database = {
}
approvalRequest: {
Row: {
- approverGroupIds: string[] | null
approverId: string | null
companyId: string
createdAt: string
@@ -1712,7 +1711,6 @@ export type Database = {
updatedBy: string | null
}
Insert: {
- approverGroupIds?: string[] | null
approverId?: string | null
companyId: string
createdAt?: string
@@ -1730,7 +1728,6 @@ export type Database = {
updatedBy?: string | null
}
Update: {
- approverGroupIds?: string[] | null
approverId?: string | null
companyId?: string
createdAt?: string
@@ -1965,10 +1962,8 @@ export type Database = {
escalationDays: number | null
id: string
lowerBoundAmount: number
- name: string
updatedAt: string | null
updatedBy: string | null
- upperBoundAmount: number | null
}
Insert: {
approverGroupIds?: string[] | null
@@ -1981,10 +1976,8 @@ export type Database = {
escalationDays?: number | null
id?: string
lowerBoundAmount?: number
- name: string
updatedAt?: string | null
updatedBy?: string | null
- upperBoundAmount?: number | null
}
Update: {
approverGroupIds?: string[] | null
@@ -1997,10 +1990,8 @@ export type Database = {
escalationDays?: number | null
id?: string
lowerBoundAmount?: number
- name?: string
updatedAt?: string | null
updatedBy?: string | null
- upperBoundAmount?: number | null
}
Relationships: [
{
@@ -41374,17 +41365,11 @@ export type Database = {
}
approvalRequests: {
Row: {
- approverAvatarUrl: string | null
- approverGroupIds: string[] | null
- approverGroupNames: string[] | null
approverId: string | null
- approverName: string | null
companyId: string | null
createdAt: string | null
decisionAt: string | null
decisionBy: string | null
- decisionByAvatarUrl: string | null
- decisionByName: string | null
decisionNotes: string | null
documentDescription: string | null
documentId: string | null
@@ -41395,8 +41380,6 @@ export type Database = {
id: string | null
requestedAt: string | null
requestedBy: string | null
- requestedByAvatarUrl: string | null
- requestedByName: string | null
status: Database["public"]["Enums"]["approvalStatus"] | null
}
Relationships: [
@@ -45980,14 +45963,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -47360,14 +47343,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -50051,14 +50034,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -50594,14 +50577,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/migrations/20260119191608_approvals-workflow.sql b/packages/database/supabase/migrations/20260119191608_approvals-workflow.sql
index 81faa95ed0..4276e44b98 100644
--- a/packages/database/supabase/migrations/20260119191608_approvals-workflow.sql
+++ b/packages/database/supabase/migrations/20260119191608_approvals-workflow.sql
@@ -16,9 +16,9 @@ CREATE TABLE "approvalRequest" (
"documentType" "approvalDocumentType" NOT NULL,
"documentId" TEXT NOT NULL,
"status" "approvalStatus" NOT NULL DEFAULT 'Pending',
+ "amount" NUMERIC,
"requestedBy" TEXT NOT NULL,
"requestedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- "approverGroupIds" TEXT[] DEFAULT ARRAY[]::TEXT[],
"approverId" TEXT,
"decisionBy" TEXT,
"decisionAt" TIMESTAMP WITH TIME ZONE,
@@ -45,19 +45,16 @@ CREATE INDEX "approvalRequest_documentId_idx" ON "approvalRequest"("documentId")
CREATE INDEX "approvalRequest_status_idx" ON "approvalRequest"("status");
CREATE INDEX "approvalRequest_requestedBy_idx" ON "approvalRequest"("requestedBy");
CREATE INDEX "approvalRequest_approverId_idx" ON "approvalRequest"("approverId");
-CREATE INDEX "approvalRequest_approverGroupIds_idx" ON "approvalRequest" USING GIN("approverGroupIds");
-- Multiple approval rules per document type
-- Each rule defines conditions (amount range for POs) and associated approver groups/users
CREATE TABLE "approvalRule" (
- "id" TEXT NOT NULL DEFAULT id('aprl'),
- "name" TEXT NOT NULL,
+ "id" TEXT NOT NULL DEFAULT id('approval'),
"documentType" "approvalDocumentType" NOT NULL,
"enabled" BOOLEAN NOT NULL DEFAULT true,
"approverGroupIds" TEXT[] DEFAULT ARRAY[]::TEXT[],
"defaultApproverId" TEXT,
"lowerBoundAmount" NUMERIC NOT NULL DEFAULT 0,
- "upperBoundAmount" NUMERIC,
"escalationDays" INTEGER,
"companyId" TEXT NOT NULL,
"createdBy" TEXT NOT NULL,
@@ -70,18 +67,13 @@ CREATE TABLE "approvalRule" (
CONSTRAINT "approvalRule_defaultApproverId_fkey" FOREIGN KEY ("defaultApproverId") REFERENCES "user"("id") ON DELETE SET NULL,
CONSTRAINT "approvalRule_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "approvalRule_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"),
- CONSTRAINT "approvalRule_name_check" CHECK (LENGTH("name") > 0 AND LENGTH("name") <= 100),
- CONSTRAINT "approvalRule_lowerBoundAmount_check" CHECK ("lowerBoundAmount" >= 0),
- CONSTRAINT "approvalRule_amountRange_check" CHECK (
- "upperBoundAmount" IS NULL OR "upperBoundAmount" > "lowerBoundAmount"
- )
+ CONSTRAINT "approvalRule_lowerBoundAmount_check" CHECK ("lowerBoundAmount" >= 0)
);
-- Indexes for approval rules
CREATE INDEX "approvalRule_companyId_idx" ON "approvalRule"("companyId");
CREATE INDEX "approvalRule_documentType_idx" ON "approvalRule"("documentType");
-CREATE INDEX "approvalRule_name_idx" ON "approvalRule"("companyId", "documentType", "name");
-CREATE INDEX "approvalRule_amountRange_idx" ON "approvalRule"("companyId", "documentType", "lowerBoundAmount", "upperBoundAmount") WHERE "enabled" = true;
+CREATE INDEX "approvalRule_name_idx" ON "approvalRule"("companyId", "documentType");
-- View for approval requests with related data
CREATE OR REPLACE VIEW "approvalRequests" WITH (SECURITY_INVOKER=true) AS
@@ -92,7 +84,6 @@ SELECT
ar."status",
ar."requestedBy",
ar."requestedAt",
- ar."approverGroupIds",
ar."approverId",
ar."decisionBy",
ar."decisionAt",
@@ -110,32 +101,50 @@ SELECT
WHEN ar."documentType" = 'purchaseOrder' THEN s."name"
WHEN ar."documentType" = 'qualityDocument' THEN qd."description"
ELSE NULL
- END AS "documentDescription",
- -- Requester info
- ru."fullName" AS "requestedByName",
- ru."avatarUrl" AS "requestedByAvatarUrl",
- -- Approver info
- au."fullName" AS "approverName",
- au."avatarUrl" AS "approverAvatarUrl",
- -- Decision maker info
- du."fullName" AS "decisionByName",
- du."avatarUrl" AS "decisionByAvatarUrl",
- -- Group names as array (get names for all groups in the array)
- (
- SELECT ARRAY_AGG(g."name" ORDER BY g."name")
- FROM "group" g
- WHERE g."id" = ANY(ar."approverGroupIds")
- ) AS "approverGroupNames"
+ END AS "documentDescription"
+
FROM "approvalRequest" ar
LEFT JOIN "purchaseOrder" po ON ar."documentType" = 'purchaseOrder' AND ar."documentId" = po."id"
LEFT JOIN "supplier" s ON po."supplierId" = s."id"
-LEFT JOIN "qualityDocument" qd ON ar."documentType" = 'qualityDocument' AND ar."documentId" = qd."id"
-LEFT JOIN "user" ru ON ar."requestedBy" = ru."id"
-LEFT JOIN "user" au ON ar."approverId" = au."id"
-LEFT JOIN "user" du ON ar."decisionBy" = du."id";
+LEFT JOIN "qualityDocument" qd ON ar."documentType" = 'qualityDocument' AND ar."documentId" = qd."id";
-- Enable RLS on approvalRequest
ALTER TABLE "approvalRequest" ENABLE ROW LEVEL SECURITY;
-- Enable RLS on approval rules table
ALTER TABLE "approvalRule" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "approvalRule"
+FOR SELECT
+USING (
+ "companyId" = ANY (
+ (
+ SELECT get_companies_with_employee_permission('settings_view')
+ )::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "approvalRule"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT get_companies_with_employee_permission('settings_create')
+ )::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "approvalRule" USING (
+ "companyId" = ANY (
+ (
+ SELECT get_companies_with_employee_permission('settings_update')
+ )::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "approvalRule" USING (
+ "companyId" = ANY (
+ (
+ SELECT get_companies_with_employee_permission('settings_delete')
+ )::text[]
+ )
+);
\ No newline at end of file