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.

Use Kysely DB client for approval flows

Sidwebworkseee842f81824
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 6c9c06b1f7..bf5bced4d4 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -1,8 +1,8 @@
import type { Database } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { getPurchaseOrderStatus, supportedModelTypes } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { FunctionRegion } from "@supabase/supabase-js";
-import { getPurchaseOrderLines } from "~/modules/purchasing";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
@@ -18,86 +18,113 @@ import type {
} from "./types";
export async function approveRequest(
- client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
id: string,
userId: string,
notes?: string
) {
- const approvalRequest = await client
- .from("approvalRequest")
- .select("id, status, documentType, documentId, companyId")
- .eq("id", id)
- .single();
-
- if (approvalRequest.error || !approvalRequest.data) {
+ // Pre-flight check: verify approval request exists and is pending
+ const approvalRequest = await db
+ .selectFrom("approvalRequest")
+ .select(["id", "status", "documentType", "documentId", "companyId"])
+ .where("id", "=", id)
+ .executeTakeFirst();
+
+ if (!approvalRequest) {
return { error: { message: "Approval request not found" }, data: null };
}
- if (approvalRequest.data.status !== "Pending") {
+ if (approvalRequest.status !== "Pending") {
return {
error: { message: "Approval request is not pending" },
data: null
};
}
- const approvalUpdate = await client
- .from("approvalRequest")
- .update({
- status: "Approved",
- decisionBy: userId,
- decisionAt: new Date().toISOString(),
- decisionNotes: notes || null,
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("id", id)
- .select("id, documentType, documentId")
- .single();
-
- if (approvalUpdate.error) {
- return { error: approvalUpdate.error, data: null };
- }
-
- if (approvalUpdate.data) {
- const { documentType, documentId } = approvalUpdate.data;
-
- if (documentType === "purchaseOrder") {
- const lines = await getPurchaseOrderLines(client, documentId);
- const { status: calculatedStatus } = getPurchaseOrderStatus(
- lines.data || []
- );
-
- const statusUpdate = await client
- .from("purchaseOrder")
- .update({
- status: calculatedStatus,
+ const { documentType, documentId } = approvalRequest;
+ const now = new Date().toISOString();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ // 1. Update approval request to "Approved"
+ const updatedApproval = await trx
+ .updateTable("approvalRequest")
+ .set({
+ status: "Approved",
+ decisionBy: userId,
+ decisionAt: now,
+ decisionNotes: notes || null,
updatedBy: userId,
- updatedAt: new Date().toISOString()
+ updatedAt: now
})
- .eq("id", documentId)
- .eq("status", "Needs Approval")
- .select("id")
- .single();
-
- if (statusUpdate.error) {
- console.warn(
- `Failed to update PO ${documentId} status after approval:`,
- statusUpdate.error
- );
+ .where("id", "=", id)
+ .returning(["id", "documentType", "documentId"])
+ .executeTakeFirstOrThrow();
+
+ // 2. Update document status based on type
+ if (documentType === "purchaseOrder") {
+ // Fetch PO lines to calculate new status
+ const lines = await trx
+ .selectFrom("purchaseOrderLine")
+ .select([
+ "purchaseOrderLineType",
+ "invoicedComplete",
+ "receivedComplete"
+ ])
+ .where("purchaseOrderId", "=", documentId)
+ .execute();
+
+ const { status: calculatedStatus } = getPurchaseOrderStatus(lines);
+
+ // Update PO status (only if currently "Needs Approval")
+ const poUpdate = await trx
+ .updateTable("purchaseOrder")
+ .set({
+ status: calculatedStatus,
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", documentId)
+ .where("status", "=", "Needs Approval")
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!poUpdate) {
+ throw new Error(
+ "Failed to update purchase order status - it may no longer be in 'Needs Approval' state"
+ );
+ }
+ } else if (documentType === "qualityDocument") {
+ const qdUpdate = await trx
+ .updateTable("qualityDocument")
+ .set({
+ status: "Active",
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", documentId)
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!qdUpdate) {
+ throw new Error("Failed to update quality document status");
+ }
}
- } else if (documentType === "qualityDocument") {
- await client
- .from("qualityDocument")
- .update({
- status: "Active",
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("id", documentId);
- }
- }
- return approvalUpdate;
+ return updatedApproval;
+ });
+
+ return { data: result, error: null };
+ } catch (error) {
+ // Transaction automatically rolled back on error
+ return {
+ error: {
+ message:
+ error instanceof Error ? error.message : "Failed to process approval"
+ },
+ data: null
+ };
+ }
}
export async function canApproveRequest(
@@ -1021,66 +1048,85 @@ export async function updateNote(
}
export async function rejectRequest(
- client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
id: string,
userId: string,
notes?: string
) {
- const existing = await client
- .from("approvalRequest")
- .select("id, status, documentType, documentId")
- .eq("id", id)
- .single();
-
- if (existing.error || !existing.data) {
+ // Pre-flight check: verify approval request exists and is pending
+ const approvalRequest = await db
+ .selectFrom("approvalRequest")
+ .select(["id", "status", "documentType", "documentId"])
+ .where("id", "=", id)
+ .executeTakeFirst();
+
+ if (!approvalRequest) {
return { error: { message: "Approval request not found" }, data: null };
}
- if (existing.data.status !== "Pending") {
+ if (approvalRequest.status !== "Pending") {
return {
error: { message: "Approval request is not pending" },
data: null
};
}
- const approvalUpdate = await client
- .from("approvalRequest")
- .update({
- status: "Rejected",
- decisionBy: userId,
- decisionAt: new Date().toISOString(),
- decisionNotes: notes || null,
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("id", id)
- .select("id, documentType, documentId")
- .single();
-
- if (approvalUpdate.error) {
- return { error: approvalUpdate.error, data: null };
- }
-
- if (approvalUpdate.data) {
- const { documentType, documentId } = approvalUpdate.data;
+ const { documentType, documentId } = approvalRequest;
+ const now = new Date().toISOString();
- if (documentType === "purchaseOrder") {
- await client
- .from("purchaseOrder")
- .update({
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ // 1. Update approval request to "Rejected"
+ const updatedApproval = await trx
+ .updateTable("approvalRequest")
+ .set({
status: "Rejected",
+ decisionBy: userId,
+ decisionAt: now,
+ decisionNotes: notes || null,
updatedBy: userId,
- updatedAt: new Date().toISOString()
+ updatedAt: now
})
- .eq("id", documentId)
- .eq("status", "Needs Approval");
- } else if (documentType === "qualityDocument") {
- // Keep quality document as "Draft" when rejected
- // (No status change needed, it should remain in Draft)
- }
- }
+ .where("id", "=", id)
+ .returning(["id", "documentType", "documentId"])
+ .executeTakeFirstOrThrow();
+
+ // 2. Update document status based on type
+ if (documentType === "purchaseOrder") {
+ const poUpdate = await trx
+ .updateTable("purchaseOrder")
+ .set({
+ status: "Rejected",
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", documentId)
+ .where("status", "=", "Needs Approval")
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!poUpdate) {
+ throw new Error(
+ "Failed to update purchase order status - it may no longer be in 'Needs Approval' state"
+ );
+ }
+ }
+ // Note: qualityDocument rejection doesn't change status (stays Draft)
+
+ return updatedApproval;
+ });
- return approvalUpdate;
+ return { data: result, error: null };
+ } catch (error) {
+ // Transaction automatically rolled back on error
+ return {
+ error: {
+ message:
+ error instanceof Error ? error.message : "Failed to process rejection"
+ },
+ data: null
+ };
+ }
}
export async function upsertApprovalRule(
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index 9c24a46a2c..3665097e94 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -46,6 +46,7 @@ import {
} from "~/modules/shared";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/purchase-order+/$orderId[.]pdf";
+import { getDatabaseClient } from "~/services/database.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
@@ -119,10 +120,11 @@ export async function action(args: ActionFunctionArgs) {
}
// Process approval decision
+ const db = getDatabaseClient();
const result =
decision === "Approved"
- ? await approveRequest(serviceRole, approvalRequestId, userId)
- : await rejectRequest(serviceRole, approvalRequestId, userId);
+ ? await approveRequest(db, approvalRequestId, userId)
+ : await rejectRequest(db, approvalRequestId, userId);
if (result.error) {
throw redirect(
diff --git a/apps/erp/app/routes/x+/quality-document+/$id.tsx b/apps/erp/app/routes/x+/quality-document+/$id.tsx
index 210523837c..a177e80727 100644
--- a/apps/erp/app/routes/x+/quality-document+/$id.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/$id.tsx
@@ -32,6 +32,7 @@ import {
isApprovalRequired,
rejectRequest
} from "~/modules/shared";
+import { getDatabaseClient } from "~/services/database.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -161,20 +162,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
// Process approval decision
+ const db = getDatabaseClient();
const result =
decision === "Approved"
- ? await approveRequest(
- serviceRole,
- approvalRequestId,
- userId,
- notes || undefined
- )
- : await rejectRequest(
- serviceRole,
- approvalRequestId,
- userId,
- notes || undefined
- );
+ ? await approveRequest(db, approvalRequestId, userId, notes || undefined)
+ : await rejectRequest(db, approvalRequestId, userId, notes || undefined);
if (result.error) {
throw redirect(