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.

refactor(approvals): update routes to use runtime approval resolution

Ayush Soni1db6b94b75c0
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
index 6c2971a000..b64165940a 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
@@ -11,7 +11,7 @@ import { redirect } from "react-router";
import {
canApproveRequest,
canCancelRequest,
- getLatestApprovalForDocument
+ getLatestApprovalRequestForDocument
} from "~/modules/approvals";
import { deletePurchaseOrder, getPurchaseOrder } from "~/modules/purchasing";
@@ -47,7 +47,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// If PO is in "Needs Approval", check permissions
if (poStatus && poStatus === "Needs Approval") {
- const approvalRequest = await getLatestApprovalForDocument(
+ const approvalRequest = await getLatestApprovalRequestForDocument(
serviceRole,
"purchaseOrder",
orderId
@@ -67,7 +67,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
const isApprover = await canApproveRequest(
serviceRole,
- approvalRequest.data,
+ {
+ amount: approvalRequest.data.amount,
+ documentType: approvalRequest.data.documentType,
+ companyId: approvalRequest.data.companyId
+ },
userId
);
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index 0fca776996..30ebf8578c 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -17,7 +17,6 @@ import { type ActionFunctionArgs, redirect } from "react-router";
import { getPaymentTermsList } from "~/modules/accounting";
import {
createApprovalRequest,
- getApprovalRuleByAmount,
hasPendingApproval,
isApprovalRequired
} from "~/modules/approvals";
@@ -55,8 +54,6 @@ export async function action(args: ActionFunctionArgs) {
const serviceRole = getCarbonServiceRole();
- // Get purchase order first to check if approval is required
- // This allows us to set status to "Needs Approval" directly if needed
const purchaseOrder = await getPurchaseOrder(serviceRole, orderId);
if (purchaseOrder.error) {
throw redirect(
@@ -86,12 +83,6 @@ export async function action(args: ActionFunctionArgs) {
orderAmount
);
- // If approval is required, we'll set status to "Needs Approval" after finalizing
- // Otherwise, finalizePurchaseOrder will set the calculated status
-
- // Finalize the purchase order (sets orderDate, updatedAt, etc.)
- // If approval is not required, it will also set the calculated status
- // If approval is required, we'll override the status to "Needs Approval" below
const finalize = await finalizePurchaseOrder(client, orderId, userId);
if (finalize.error) {
throw redirect(
@@ -119,22 +110,13 @@ export async function action(args: ActionFunctionArgs) {
);
if (!hasPending) {
- const config = await getApprovalRuleByAmount(
- serviceRole,
- "purchaseOrder",
- companyId,
- orderAmount
- );
-
await createApprovalRequest(serviceRole, {
documentType: "purchaseOrder",
documentId: orderId,
companyId,
requestedBy: userId,
createdBy: userId,
- amount: orderAmount,
- approverGroupIds: config.data?.approverGroupIds || undefined,
- approverId: config.data?.defaultApproverId || undefined
+ amount: orderAmount
});
}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
index 9c5c8991fd..ebd2e2f3ce 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
@@ -104,7 +104,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
const isRequester = latestApproval.requestedBy === userId;
const isApprover = await canApproveRequest(
serviceRole,
- latestApproval,
+ {
+ amount: latestApproval.amount,
+ documentType: latestApproval.documentType,
+ companyId: latestApproval.companyId
+ },
userId
);
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index 9137fb82f4..3c4b3ccb31 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -8,7 +8,7 @@ import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
import {
canApproveRequest,
canCancelRequest,
- getLatestApprovalForDocument
+ getLatestApprovalRequestForDocument
} from "~/modules/approvals";
import {
getPurchaseOrder,
@@ -80,7 +80,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getSupplierInteraction(client, purchaseOrder.data.supplierInteractionId),
// Only fetch approval request if status is "Needs Approval"
purchaseOrder.data?.status === "Needs Approval"
- ? getLatestApprovalForDocument(serviceRole, "purchaseOrder", orderId)
+ ? getLatestApprovalRequestForDocument(
+ serviceRole,
+ "purchaseOrder",
+ orderId
+ )
: Promise.resolve({ data: null, error: null })
]);
@@ -100,7 +104,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
canApprove = await canApproveRequest(
serviceRole,
- approvalRequest.data,
+ {
+ amount: approvalRequest.data.amount,
+ documentType: approvalRequest.data.documentType,
+ companyId: approvalRequest.data.companyId
+ },
userId
);
diff --git a/apps/erp/app/routes/x+/quality-document+/$id.tsx b/apps/erp/app/routes/x+/quality-document+/$id.tsx
index be7d751cb0..2ba1d92dfb 100644
--- a/apps/erp/app/routes/x+/quality-document+/$id.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/$id.tsx
@@ -9,7 +9,7 @@ import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
import {
canApproveRequest,
canCancelRequest,
- getLatestApprovalForDocument,
+ getLatestApprovalRequestForDocument,
isApprovalRequired
} from "~/modules/approvals";
import {
@@ -52,7 +52,11 @@ async function getQualityDocumentApprovalContext(
}
const [latest, approvalRequired] = await Promise.all([
- getLatestApprovalForDocument(serviceRole, "qualityDocument", documentId),
+ getLatestApprovalRequestForDocument(
+ serviceRole,
+ "qualityDocument",
+ documentId
+ ),
isApprovalRequired(serviceRole, "qualityDocument", companyId, undefined)
]);
@@ -61,7 +65,15 @@ async function getQualityDocumentApprovalContext(
return { ...defaultContext, isApprovalRequired: approvalRequired };
}
- const canApprove = await canApproveRequest(serviceRole, req, userId);
+ const canApprove = await canApproveRequest(
+ serviceRole,
+ {
+ amount: req.amount,
+ documentType: req.documentType,
+ companyId: req.companyId
+ },
+ userId
+ );
const isRequester = canCancelRequest(
{ requestedBy: req.requestedBy, status: req.status },
userId
diff --git a/apps/erp/app/routes/x+/quality-document+/update.tsx b/apps/erp/app/routes/x+/quality-document+/update.tsx
index 1c542a2d2f..aae8fac8e5 100644
--- a/apps/erp/app/routes/x+/quality-document+/update.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/update.tsx
@@ -6,8 +6,7 @@ import { type ActionFunctionArgs } from "react-router";
import {
canApproveRequest,
createApprovalRequest,
- getApprovalRuleByAmount,
- getLatestApprovalForDocument,
+ getLatestApprovalRequestForDocument,
hasPendingApproval,
isApprovalRequired
} from "~/modules/approvals";
@@ -52,20 +51,13 @@ async function processToActive(
idsToSkipActive.push(doc.id);
continue;
}
- const config = await getApprovalRuleByAmount(
- serviceRole,
- "qualityDocument",
- companyId,
- undefined
- );
await createApprovalRequest(serviceRole, {
documentType: "qualityDocument",
documentId: doc.id,
companyId,
requestedBy: userId,
createdBy: userId,
- approverGroupIds: config.data?.approverGroupIds || undefined,
- approverId: config.data?.defaultApproverId || undefined
+ amount: undefined
});
idsToSkipActive.push(doc.id);
if (doc.status === "Archived") {
@@ -109,7 +101,7 @@ async function cancelPendingApprovalsForArchiveOrDraft(
): Promise<{ message: string } | null> {
const toCancel: { id: string }[] = [];
for (const doc of docList) {
- const latest = await getLatestApprovalForDocument(
+ const latest = await getLatestApprovalRequestForDocument(
serviceRole,
"qualityDocument",
doc.id
@@ -120,7 +112,11 @@ async function cancelPendingApprovalsForArchiveOrDraft(
const isRequester = req.requestedBy === userId;
const isApprover = await canApproveRequest(
serviceRole,
- { approverId: req.approverId, approverGroupIds: req.approverGroupIds },
+ {
+ amount: req.amount,
+ documentType: req.documentType,
+ companyId: req.companyId
+ },
userId
);
if (!isRequester && !isApprover) {
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 3bb76e70b3..ec44315aa3 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.$id.tsx
@@ -91,6 +91,22 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ const rulesForType =
+ rules.data?.filter(
+ (r) => r.documentType === validation.data.documentType && r.id !== id
+ ) || [];
+ const duplicateRule = rulesForType.find(
+ (r) => r.lowerBoundAmount === (validation.data.lowerBoundAmount ?? 0)
+ );
+
+ if (duplicateRule) {
+ return validationError({
+ fieldErrors: {
+ lowerBoundAmount: `A rule with this minimum amount already exists. The maximum for this rule would be set by the next higher rule.`
+ }
+ });
+ }
+
const result = await upsertApprovalRule(serviceRole, {
id,
updatedBy: userId,
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 7081fa65cd..30b8e5e789 100644
--- a/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/approval-rules.new.tsx
@@ -12,10 +12,10 @@ import { redirect, useLoaderData, useNavigate } from "react-router";
import {
type ApprovalDocumentType,
approvalRuleValidator,
+ getApprovalRules,
upsertApprovalRule
} from "~/modules/approvals";
import ApprovalRuleForm from "~/modules/approvals/ui/ApprovalRuleForm";
-
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
@@ -54,6 +54,23 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ const existingRules = await getApprovalRules(serviceRole, companyId);
+ const rulesForType =
+ existingRules.data?.filter(
+ (r) => r.documentType === validation.data.documentType
+ ) || [];
+ const duplicateRule = rulesForType.find(
+ (r) => r.lowerBoundAmount === (validation.data.lowerBoundAmount ?? 0)
+ );
+
+ if (duplicateRule) {
+ return validationError({
+ fieldErrors: {
+ lowerBoundAmount: `A rule with this minimum amount already exists. The maximum for this rule would be set by the next higher rule.`
+ }
+ });
+ }
+
const result = await upsertApprovalRule(serviceRole, {
createdBy: userId,
companyId,
diff --git a/apps/erp/app/routes/x+/settings+/approvals+/requests.$id.tsx b/apps/erp/app/routes/x+/settings+/approvals+/requests.$id.tsx
index 35b0806125..3f3c8487bd 100644
--- a/apps/erp/app/routes/x+/settings+/approvals+/requests.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/approvals+/requests.$id.tsx
@@ -40,9 +40,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// Check if user can approve/reject this request
const canApprove = await canApproveRequest(
serviceRole,
- approval.data,
+ {
+ amount: approval.data.amount,
+ documentType: approval.data.documentType,
+ companyId: approval.data.companyId
+ },
userId
);
+
if (!canApprove) {
throw redirect(
path.to.approvalRequests,
@@ -112,7 +117,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Check if user can approve/reject this request
const canApprove = await canApproveRequest(
serviceRole,
- approval.data,
+ {
+ amount: approval.data.amount,
+ documentType: approval.data.documentType,
+ companyId: approval.data.companyId
+ },
userId
);
if (!canApprove) {