Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add ability to make supplier inactive after approval

Brad Barbinefcbe1a5f916
diff --git a/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx b/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx
index ca8fc2ce68..145145b35d 100644
--- a/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx
+++ b/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx
@@ -79,7 +79,7 @@ const Group = ({ group }: { group: OptionGroup }) => {
group.expanded ? onGroupCollapse(group.uid) : onGroupExpand(group.uid)
}
className={cn(
- "flex cursor-pointer select-none items-center gap-2 rounded-md px-2 py-2 text-xs font-semibold tracking-wide text-muted-foreground transition-colors hover:bg-muted/50",
+ "flex cursor-pointer select-none items-center gap-2 rounded-md px-2 py-2 hover:bg-muted/50 text-sm",
isFocused && "bg-muted/50"
)}
>
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 54ffaec52e..c6af21accf 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -404,6 +404,11 @@ export async function getSupplier(
type ApprovalContext = {
approvalRequest: { id: string } | null;
canApprove: boolean;
+ decision: {
+ status: "Approved" | "Rejected";
+ decisionBy: string;
+ decisionAt: string;
+ } | null;
};
export async function getSupplierApprovalContext(
@@ -431,16 +436,43 @@ export async function getSupplierApprovalContext(
userId
);
+ // Look for the latest terminal decision (Approved or Rejected)
+ let decision: ApprovalContext["decision"] = null;
+ const terminalRequest = await serviceRole
+ .from("approvalRequest")
+ .select("status, decisionBy, decisionAt")
+ .eq("documentType", "supplier")
+ .eq("documentId", supplierId)
+ .in("status", ["Approved", "Rejected"])
+ .order("decisionAt", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ if (
+ terminalRequest.data?.decisionBy &&
+ terminalRequest.data?.decisionAt &&
+ (terminalRequest.data.status === "Approved" ||
+ terminalRequest.data.status === "Rejected")
+ ) {
+ decision = {
+ status: terminalRequest.data.status,
+ decisionBy: terminalRequest.data.decisionBy,
+ decisionAt: terminalRequest.data.decisionAt
+ };
+ }
+
if (!req || req.status !== "Pending" || !req.requestedBy || !req.id) {
return {
approvalRequest: null,
- canApprove
+ canApprove,
+ decision
};
}
return {
approvalRequest: { id: req.id },
- canApprove
+ canApprove,
+ decision
};
}
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
index 88456b50b5..b30186e3c8 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
@@ -72,6 +72,11 @@ const SupplierHeader = () => {
tags: { name: string }[];
approvalRequest: { id: string } | null;
canApprove: boolean;
+ decision: {
+ status: "Approved" | "Rejected";
+ decisionBy: string;
+ decisionAt: string;
+ } | null;
}>(path.to.supplier(supplierId));
const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({
@@ -245,24 +250,44 @@ const SupplierHeader = () => {
)}
</CardAttributeValue>
</CardAttribute>
- {routeData?.supplier?.approvedBy && (
- <CardAttribute>
- <CardAttributeLabel>Approved By</CardAttributeLabel>
- <CardAttributeValue>
- <EmployeeAvatar
- employeeId={routeData.supplier.approvedBy}
- />
- </CardAttributeValue>
- </CardAttribute>
- )}
- {routeData?.supplier?.approvalDate && (
- <CardAttribute>
- <CardAttributeLabel>Approval Date</CardAttributeLabel>
- <CardAttributeValue>
- {formatDate(routeData.supplier.approvalDate)}
- </CardAttributeValue>
- </CardAttribute>
- )}
+ {routeData?.decision?.status === "Approved" &&
+ status === "Active" && (
+ <>
+ <CardAttribute>
+ <CardAttributeLabel>Approved By</CardAttributeLabel>
+ <CardAttributeValue>
+ <EmployeeAvatar
+ employeeId={routeData.decision.decisionBy}
+ />
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Approval Date</CardAttributeLabel>
+ <CardAttributeValue>
+ {formatDate(routeData.decision.decisionAt)}
+ </CardAttributeValue>
+ </CardAttribute>
+ </>
+ )}
+ {routeData?.decision?.status === "Rejected" &&
+ status === "Rejected" && (
+ <>
+ <CardAttribute>
+ <CardAttributeLabel>Rejected By</CardAttributeLabel>
+ <CardAttributeValue>
+ <EmployeeAvatar
+ employeeId={routeData.decision.decisionBy}
+ />
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Rejected Date</CardAttributeLabel>
+ <CardAttributeValue>
+ {formatDate(routeData.decision.decisionAt)}
+ </CardAttributeValue>
+ </CardAttribute>
+ </>
+ )}
<CardAttribute>
<CardAttributeValue>
<ValidatedForm
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index a9bbe29464..6c5d4d8db7 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -119,8 +119,6 @@ export async function approveRequest(
.updateTable("supplier")
.set({
supplierStatus: "Active",
- approvedBy: userId,
- approvalDate: now.split("T")[0],
updatedBy: userId,
updatedAt: now
})
diff --git a/apps/erp/app/routes/x+/purchasing+/_index.tsx b/apps/erp/app/routes/x+/purchasing+/_index.tsx
index baad7b66d5..41df1d8817 100644
--- a/apps/erp/app/routes/x+/purchasing+/_index.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/_index.tsx
@@ -68,6 +68,7 @@ import type { PurchaseOrder, SupplierQuote } from "~/modules/purchasing";
import { getPurchasingDocumentsAssignedToMe } from "~/modules/purchasing";
import { KPIs } from "~/modules/purchasing/purchasing.models";
import { PurchasingStatus } from "~/modules/purchasing/ui/PurchaseOrder";
+import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";
import { SupplierQuoteStatus } from "~/modules/purchasing/ui/SupplierQuote";
import {
type ApprovalRequest,
@@ -125,11 +126,22 @@ export async function loader({ request }: LoaderFunctionArgs) {
.map((approval: ApprovalRequest) => approval.documentId!)
.filter((id): id is string => !!id) ?? [];
+ // Extract supplier IDs that need approval and user can approve
+ const approvalSupplierIds =
+ pendingApprovals.data
+ ?.filter(
+ (approval: ApprovalRequest) =>
+ approval.documentType === "supplier" && approval.documentId
+ )
+ .map((approval: ApprovalRequest) => approval.documentId!)
+ .filter((id): id is string => !!id) ?? [];
+
const [
openPurchaseOrders,
openPurchaseInvoices,
openSupplierQuotes,
- purchaseOrdersNeedingApproval
+ purchaseOrdersNeedingApproval,
+ suppliersNeedingApproval
] = await Promise.all([
client
.from("purchaseOrder")
@@ -164,6 +176,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
.eq("status", "Needs Approval")
.eq("companyId", companyId)
.in("id", approvalPoIds)
+ : { data: [], error: null },
+ approvalSupplierIds.length > 0
+ ? client
+ .from("supplier")
+ .select("id, name, supplierStatus")
+ .eq("supplierStatus", "Pending")
+ .eq("companyId", companyId)
+ .in("id", approvalSupplierIds)
: { data: [], error: null }
]);
@@ -178,6 +198,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
openSupplierQuotes: openSupplierQuotes,
openPurchaseInvoices: openPurchaseInvoices,
purchaseOrdersNeedingApproval: purchaseOrdersNeedingApproval,
+ suppliersNeedingApproval: suppliersNeedingApproval,
assignedToMe: assignedToMePromise
};
}
@@ -188,6 +209,7 @@ export default function PurchaseDashboard() {
openSupplierQuotes,
openPurchaseInvoices,
purchaseOrdersNeedingApproval,
+ suppliersNeedingApproval,
assignedToMe
} = useLoaderData<typeof loader>();
@@ -701,6 +723,9 @@ export default function PurchaseDashboard() {
purchaseOrdersNeedingApproval={
purchaseOrdersNeedingApproval.data ?? []
}
+ suppliersNeedingApproval={
+ suppliersNeedingApproval.data ?? []
+ }
/>
)}
</Await>
@@ -714,13 +739,14 @@ export default function PurchaseDashboard() {
type AssignedDocument = {
id: string;
- type: "purchaseOrder" | "supplierQuote" | "purchaseInvoice";
+ type: "purchaseOrder" | "supplierQuote" | "purchaseInvoice" | "supplier";
[key: string]: unknown;
};
function AssignedDocumentsTable({
assignedDocs,
- purchaseOrdersNeedingApproval
+ purchaseOrdersNeedingApproval,
+ suppliersNeedingApproval
}: {
assignedDocs: Array<{ id: string; type: string; [key: string]: unknown }>;
purchaseOrdersNeedingApproval: Array<{
@@ -731,6 +757,11 @@ function AssignedDocumentsTable({
assignee: string | null;
createdAt: string | null;
}>;
+ suppliersNeedingApproval: Array<{
+ id: string;
+ name: string;
+ supplierStatus: string | null;
+ }>;
}) {
// Merge assigned docs with purchase orders needing approval
// Deduplicate: if a PO is both assigned and needs approval, prefer the assigned version
@@ -747,7 +778,16 @@ function AssignedDocumentsTable({
type: "purchaseOrder" as const
}));
- const allDocs = [...assignedDocs, ...approvalDocs] as AssignedDocument[];
+ const supplierDocs = suppliersNeedingApproval.map((doc) => ({
+ ...doc,
+ type: "supplier" as const
+ }));
+
+ const allDocs = [
+ ...assignedDocs,
+ ...approvalDocs,
+ ...supplierDocs
+ ] as AssignedDocument[];
if (allDocs.length === 0) {
return (
@@ -783,6 +823,18 @@ function DocumentRow({ doc }: { doc: AssignedDocument }) {
return <SupplierQuoteRow doc={doc as unknown as SupplierQuote} />;
case "purchaseInvoice":
return <PurchaseInvoiceRow doc={doc as unknown as PurchaseInvoice} />;
+ case "supplier":
+ return (
+ <SupplierApprovalRow
+ doc={
+ doc as unknown as {
+ id: string;
+ name: string;
+ supplierStatus: string | null;
+ }
+ }
+ />
+ );
default:
return null;
}
@@ -851,3 +903,23 @@ function PurchaseInvoiceRow({ doc }: { doc: PurchaseInvoice }) {
</Tr>
);
}
+
+function SupplierApprovalRow({
+ doc
+}: {
+ doc: { id: string; name: string; supplierStatus: string | null };
+}) {
+ return (
+ <Tr>
+ <Td>
+ <Hyperlink to={path.to.supplier(doc.id)}>
+ <SupplierAvatar supplierId={doc.id} />
+ </Hyperlink>
+ </Td>
+ <Td>
+ <SupplierStatusIndicator status={doc.supplierStatus as "Pending"} />
+ </Td>
+ <Td>-</Td>
+ </Tr>
+ );
+}
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
index 6a1a4b1a22..74508d1eed 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
@@ -1,43 +1,24 @@
-import {
- assertIsPost,
- error,
- getCarbonServiceRole,
- success
-} from "@carbon/auth";
+import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { NotificationEvent } from "@carbon/notifications";
-import { tasks } from "@trigger.dev/sdk";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect, useParams } from "react-router";
import { useRouteData } from "~/hooks";
import type { SupplierDetail } from "~/modules/purchasing";
import { supplierValidator, upsertSupplier } from "~/modules/purchasing";
import SupplierForm from "~/modules/purchasing/ui/Supplier/SupplierForm";
-import { getCompanySettings } from "~/modules/settings";
-import {
- createApprovalRequest,
- getApprovalRuleByAmount,
- getApproverUserIdsForRule,
- hasPendingApproval,
- isApprovalRequired
-} from "~/modules/shared";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { client, userId } = await requirePermissions(request, {
create: "purchasing"
});
const formData = await request.formData();
- // Normal supplier update flow
- const settings = await getCompanySettings(client, companyId);
- const supplierApprovalRequired = settings.data?.supplierApproval ?? false;
-
const validation = await validator(supplierValidator).validate(formData);
if (validation.error) {
@@ -53,83 +34,6 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- // If approval is required and status is being set to Active, intercept
- if (supplierApprovalRequired && d.supplierStatus === "Active") {
- const serviceRole = getCarbonServiceRole();
- const approvalRequired = await isApprovalRequired(
- serviceRole,
- "supplier",
- companyId,
- undefined
- );
-
- if (approvalRequired) {
- const pending = await hasPendingApproval(serviceRole, "supplier", id);
-
- if (!pending) {
- // Set status to Pending instead of Active
- d.supplierStatus = "Pending";
-
- const update = await upsertSupplier(client, {
- id,
- ...d,
- updatedBy: userId,
- customFields: setCustomFields(formData)
- });
-
- if (update.error) {
- throw redirect(
- path.to.suppliers,
- await flash(
- request,
- error(update.error, "Failed to update supplier")
- )
- );
- }
-
- // Create approval request
- await createApprovalRequest(serviceRole, {
- documentType: "supplier",
- documentId: id,
- companyId,
- requestedBy: userId,
- createdBy: userId,
- amount: undefined
- });
-
- const rule = await getApprovalRuleByAmount(
- serviceRole,
- "supplier",
- companyId,
- undefined
- );
- const approverIds = rule.data
- ? await getApproverUserIdsForRule(serviceRole, rule.data)
- : [];
-
- if (approverIds.length > 0) {
- try {
- await tasks.trigger("notify", {
- event: NotificationEvent.ApprovalRequested,
- companyId,
- documentId: id,
- documentType: "supplier",
- recipient: { type: "users", userIds: approverIds },
- from: userId
- });
- } catch (e) {
- console.error("Failed to trigger approval notification", e);
- }
- }
-
- return data(
- null,
- await flash(request, success("Supplier submitted for approval"))
- );
- }
- }
- }
-
const update = await upsertSupplier(client, {
id,
...d,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 935cf1a066..e6034b2a83 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -35625,8 +35625,6 @@ export type Database = {
supplier: {
Row: {
accountManagerId: string | null
- approvalDate: string | null
- approvedBy: string | null
assignee: string | null
companyId: string
createdAt: string
@@ -35655,8 +35653,6 @@ export type Database = {
}
Insert: {
accountManagerId?: string | null
- approvalDate?: string | null
- approvedBy?: string | null
assignee?: string | null
companyId: string
createdAt?: string
@@ -35685,8 +35681,6 @@ export type Database = {
}
Update: {
accountManagerId?: string | null
- approvalDate?: string | null
- approvedBy?: string | null
assignee?: string | null
companyId?: string
createdAt?: string
@@ -35749,41 +35743,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
{
foreignKeyName: "supplier_assignee_fkey"
columns: ["assignee"]
@@ -55078,8 +55037,6 @@ export type Database = {
suppliers: {
Row: {
accountManagerId: string | null
- approvalDate: string | null
- approvedBy: string | null
assignee: string | null
companyId: string | null
createdAt: string | null
@@ -55144,41 +55101,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplier_approvedBy_fkey"
- columns: ["approvedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
{
foreignKeyName: "supplier_assignee_fkey"
columns: ["assignee"]
diff --git a/packages/database/supabase/migrations/20260310005407_supplier-approvals.sql b/packages/database/supabase/migrations/20260310005407_supplier-approvals.sql
index f2b25d17ee..958945f418 100644
--- a/packages/database/supabase/migrations/20260310005407_supplier-approvals.sql
+++ b/packages/database/supabase/migrations/20260310005407_supplier-approvals.sql
@@ -1,10 +1,7 @@
ALTER TABLE "companySettings" ADD COLUMN "supplierApproval" BOOLEAN NOT NULL DEFAULT false;
ALTER TYPE "approvalDocumentType" ADD VALUE 'supplier';
-ALTER TABLE "supplier" ADD COLUMN "approvalDate" DATE;
-ALTER TABLE "supplier" ADD COLUMN "approvedBy" TEXT REFERENCES "user"("id") ON DELETE SET NULL;
-
--- Recreate suppliers view to include approvalDate and approvedBy
+-- Recreate suppliers view
DROP VIEW IF EXISTS "suppliers";
CREATE OR REPLACE VIEW "suppliers" WITH(SECURITY_INVOKER=true) AS
SELECT
@@ -25,8 +22,6 @@ CREATE OR REPLACE VIEW "suppliers" WITH(SECURITY_INVOKER=true) AS
s."currencyCode",
s."vatNumber",
s.website,
- s."approvalDate",
- s."approvedBy",
(
SELECT COALESCE(
jsonb_object_agg(
@@ -78,3 +73,36 @@ CREATE OR REPLACE VIEW "suppliers" WITH(SECURITY_INVOKER=true) AS
ORDER BY sc."supplierId", sc.id
) pc
ON pc.id = s.id;
+
+-- Recreate approvalRequests view to include supplier document type
+DROP VIEW IF EXISTS "approvalRequests";
+CREATE OR REPLACE VIEW "approvalRequests" WITH (SECURITY_INVOKER=true) AS
+SELECT
+ ar."id",
+ ar."documentType",
+ ar."documentId",
+ ar."status",
+ ar."requestedBy",
+ ar."requestedAt",
+ ar."decisionBy",
+ ar."decisionAt",
+ ar."decisionNotes",
+ ar."companyId",
+ ar."createdAt",
+ CASE
+ WHEN ar."documentType" = 'purchaseOrder' THEN po."purchaseOrderId"
+ WHEN ar."documentType" = 'qualityDocument' THEN qd."name"
+ WHEN ar."documentType" = 'supplier' THEN sup."name"
+ ELSE NULL
+ END AS "documentReadableId",
+ CASE
+ WHEN ar."documentType" = 'purchaseOrder' THEN s."name"
+ WHEN ar."documentType" = 'qualityDocument' THEN qd."description"
+ WHEN ar."documentType" = 'supplier' THEN NULL
+ ELSE NULL
+ 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 "supplier" sup ON ar."documentType" = 'supplier' AND ar."documentId" = sup."id";