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(purchasing): PO approve/reject in header, delete/finalize/status flow

Ayush Soni7b983dc76058
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
index 2485fa5837..de3275bc6b 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
@@ -28,7 +28,8 @@ import {
LuPanelLeft,
LuPanelRight,
LuTrash,
- LuTruck
+ LuTruck,
+ LuX
} from "react-icons/lu";
import { Link, useFetcher, useParams } from "react-router";
@@ -56,6 +57,10 @@ const PurchaseOrderHeader = () => {
const routeData = useRouteData<{
purchaseOrder: PurchaseOrder;
lines: PurchaseOrderLine[];
+ approvalRequest: { id: string } | null;
+ canApprove: boolean;
+ canReopen: boolean;
+ canDelete: boolean;
}>(path.to.purchaseOrder(orderId));
if (!routeData?.purchaseOrder)
@@ -64,7 +69,12 @@ const PurchaseOrderHeader = () => {
const permissions = usePermissions();
const statusFetcher = useFetcher<{}>();
+ const approvalFetcher = useFetcher<{}>();
const { receive, invoice, ship } = usePurchaseOrder();
+
+ const isNeedsApproval = routeData?.purchaseOrder?.status === "Needs Approval";
+ const hasApprovalRequest = !!routeData?.approvalRequest;
+ const canApprove = routeData?.canApprove ?? false;
const { receipts, invoices, shipments } = usePurchaseOrderRelatedDocuments(
routeData?.purchaseOrder?.supplierInteractionId ?? "",
routeData?.purchaseOrder?.purchaseOrderType === "Outside Processing"
@@ -115,7 +125,8 @@ const PurchaseOrderHeader = () => {
<DropdownMenuItem
disabled={
!permissions.can("delete", "purchasing") ||
- !permissions.is("employee")
+ !permissions.is("employee") ||
+ (isNeedsApproval && !routeData?.canDelete)
}
destructive
onClick={deleteModal.onOpen}
@@ -174,14 +185,19 @@ const PurchaseOrderHeader = () => {
}
onClick={finalizeDisclosure.onOpen}
isDisabled={
- !["Draft"].includes(routeData?.purchaseOrder?.status ?? "") ||
- routeData?.lines.length === 0
+ !["Draft", "Planned"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ ) || routeData?.lines.length === 0
}
dropdownItems={[
{
label: "Mark as Planned",
icon: <LuCheckCheck />,
- onClick: markAsPlanned
+ onClick: markAsPlanned,
+ disabled:
+ !["Draft"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ ) || routeData?.lines.length === 0
}
]}
>
@@ -299,6 +315,49 @@ const PurchaseOrderHeader = () => {
))}
</DropdownMenuContent>
</DropdownMenu>
+ ) : isNeedsApproval && hasApprovalRequest ? (
+ <>
+ <approvalFetcher.Form
+ method="post"
+ action={path.to.approvalDecision(
+ routeData.approvalRequest?.id ?? ""
+ )}
+ >
+ <input type="hidden" name="decision" value="Approved" />
+ <Button
+ type="submit"
+ leftIcon={<LuCheckCheck />}
+ variant="primary"
+ isLoading={
+ approvalFetcher.state !== "idle" &&
+ approvalFetcher.formData?.get("decision") === "Approved"
+ }
+ isDisabled={!canApprove || approvalFetcher.state !== "idle"}
+ >
+ Approve
+ </Button>
+ </approvalFetcher.Form>
+ <approvalFetcher.Form
+ method="post"
+ action={path.to.approvalDecision(
+ routeData.approvalRequest?.id ?? ""
+ )}
+ >
+ <input type="hidden" name="decision" value="Rejected" />
+ <Button
+ type="submit"
+ leftIcon={<LuX />}
+ variant="destructive"
+ isLoading={
+ approvalFetcher.state !== "idle" &&
+ approvalFetcher.formData?.get("decision") === "Rejected"
+ }
+ isDisabled={!canApprove || approvalFetcher.state !== "idle"}
+ >
+ Reject
+ </Button>
+ </approvalFetcher.Form>
+ </>
) : (
<Button
leftIcon={<LuHandCoins />}
@@ -322,12 +381,63 @@ const PurchaseOrderHeader = () => {
</Button>
)}
- {invoices?.length > 0 ? (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
+ {!isNeedsApproval && (
+ <>
+ {invoices?.length > 0 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ leftIcon={<LuCreditCard />}
+ rightIcon={<LuChevronDown />}
+ variant={
+ ["To Invoice", "To Receive and Invoice"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ ) && !requiresShipment
+ ? "primary"
+ : "secondary"
+ }
+ >
+ Invoice
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ disabled={
+ !["To Invoice", "To Receive and Invoice"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ )
+ }
+ onClick={() => {
+ invoice(routeData?.purchaseOrder);
+ }}
+ >
+ <DropdownMenuIcon icon={<LuCirclePlus />} />
+ New Invoice
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {invoices.map((invoice) => (
+ <DropdownMenuItem key={invoice.id} asChild>
+ <Link to={path.to.purchaseInvoice(invoice.id!)}>
+ <DropdownMenuIcon icon={<LuCreditCard />} />
+ <HStack spacing={8}>
+ <span>{invoice.invoiceId}</span>
+ <PurchaseInvoicingStatus
+ status={invoice.status}
+ />
+ </HStack>
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
<Button
leftIcon={<LuCreditCard />}
- rightIcon={<LuChevronDown />}
+ isDisabled={
+ !["To Invoice", "To Receive and Invoice"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ )
+ }
variant={
["To Invoice", "To Receive and Invoice"].includes(
routeData?.purchaseOrder?.status ?? ""
@@ -335,59 +445,14 @@ const PurchaseOrderHeader = () => {
? "primary"
: "secondary"
}
- >
- Invoice
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- disabled={
- !["To Invoice", "To Receive and Invoice"].includes(
- routeData?.purchaseOrder?.status ?? ""
- )
- }
onClick={() => {
invoice(routeData?.purchaseOrder);
}}
>
- <DropdownMenuIcon icon={<LuCirclePlus />} />
- New Invoice
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- {invoices.map((invoice) => (
- <DropdownMenuItem key={invoice.id} asChild>
- <Link to={path.to.purchaseInvoice(invoice.id!)}>
- <DropdownMenuIcon icon={<LuCreditCard />} />
- <HStack spacing={8}>
- <span>{invoice.invoiceId}</span>
- <PurchaseInvoicingStatus status={invoice.status} />
- </HStack>
- </Link>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- ) : (
- <Button
- leftIcon={<LuCreditCard />}
- isDisabled={
- !["To Invoice", "To Receive and Invoice"].includes(
- routeData?.purchaseOrder?.status ?? ""
- )
- }
- variant={
- ["To Invoice", "To Receive and Invoice"].includes(
- routeData?.purchaseOrder?.status ?? ""
- ) && !requiresShipment
- ? "primary"
- : "secondary"
- }
- onClick={() => {
- invoice(routeData?.purchaseOrder);
- }}
- >
- Invoice
- </Button>
+ Invoice
+ </Button>
+ )}
+ </>
)}
<statusFetcher.Form
method="post"
@@ -425,7 +490,8 @@ const PurchaseOrderHeader = () => {
isDisabled={
["Draft"].includes(routeData?.purchaseOrder?.status ?? "") ||
statusFetcher.state !== "idle" ||
- !permissions.can("update", "purchasing")
+ !permissions.can("update", "purchasing") ||
+ (isNeedsApproval && !routeData?.canReopen)
}
isLoading={
statusFetcher.state !== "idle" &&
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 8776a6dff4..6c2971a000 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
@@ -1,21 +1,125 @@
-import { assertIsPost, error, notFound } from "@carbon/auth";
+import {
+ assertIsPost,
+ error,
+ getCarbonServiceRole,
+ notFound
+} from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { deletePurchaseOrder } from "~/modules/purchasing";
+import {
+ canApproveRequest,
+ canCancelRequest,
+ getLatestApprovalForDocument
+} from "~/modules/approvals";
+import { deletePurchaseOrder, getPurchaseOrder } from "~/modules/purchasing";
import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, userId } = await requirePermissions(request, {
delete: "purchasing"
});
const { orderId } = params;
if (!orderId) throw notFound("orderId not found");
+ const serviceRole = getCarbonServiceRole();
+
+ // Get PO status and check if it's in "Needs Approval"
+ const purchaseOrder = await getPurchaseOrder(serviceRole, orderId);
+ if (purchaseOrder.error || !purchaseOrder.data) {
+ throw redirect(
+ path.to.purchaseOrders,
+ await flash(
+ request,
+ error(
+ purchaseOrder.error ?? new Error("Purchase order not found"),
+ "Purchase order not found"
+ )
+ )
+ );
+ }
+
+ const poStatus = purchaseOrder.data.status;
+
+ // If PO is in "Needs Approval", check permissions
+ if (poStatus && poStatus === "Needs Approval") {
+ const approvalRequest = await getLatestApprovalForDocument(
+ serviceRole,
+ "purchaseOrder",
+ orderId
+ );
+
+ if (
+ approvalRequest.data &&
+ approvalRequest.data.status === "Pending" &&
+ approvalRequest.data.requestedBy
+ ) {
+ const isRequester = canCancelRequest(
+ {
+ requestedBy: approvalRequest.data.requestedBy,
+ status: approvalRequest.data.status as "Pending"
+ },
+ userId
+ );
+ const isApprover = await canApproveRequest(
+ serviceRole,
+ approvalRequest.data,
+ userId
+ );
+
+ // Only requester can delete POs in "Needs Approval" status
+ // Approvers should reject instead, normal users have no permission
+ if (!isRequester) {
+ throw redirect(
+ path.to.purchaseOrder(orderId),
+ await flash(
+ request,
+ error(
+ new Error(
+ isApprover
+ ? "Approvers cannot delete purchase orders. Please reject the approval request instead."
+ : "Only the requester can delete a purchase order that needs approval"
+ ),
+ isApprover
+ ? "Please reject the approval request instead of deleting"
+ : "You do not have permission to delete this purchase order"
+ )
+ )
+ );
+ }
+
+ // Cancel pending approval requests before deletion
+ await serviceRole
+ .from("approvalRequest")
+ .update({
+ status: "Cancelled",
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("documentType", "purchaseOrder")
+ .eq("documentId", orderId)
+ .eq("status", "Pending");
+ }
+ }
+
+ // Only allow deletion of Draft, Planned, or Needs Approval (if requester) statuses
+ if (!poStatus || !["Draft", "Planned", "Needs Approval"].includes(poStatus)) {
+ throw redirect(
+ path.to.purchaseOrder(orderId),
+ await flash(
+ request,
+ error(
+ new Error("Cannot delete purchase order in this status"),
+ `Cannot delete purchase order with status "${poStatus ?? "unknown"}". Only Draft, Planned, or Needs Approval (if you're the requester) purchase orders can be deleted.`
+ )
+ )
+ );
+ }
+
const remove = await deletePurchaseOrder(client, orderId);
if (remove.error) {
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 840722a37b..ade597cf52 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -89,8 +89,6 @@ export async function action(args: ActionFunctionArgs) {
// If approval is required, we'll set status to "Needs Approval" after finalizing
// Otherwise, finalizePurchaseOrder will set the calculated status
- const shouldSetNeedsApproval =
- approvalRequired && purchaseOrder.data.status !== "Planned";
// Finalize the purchase order (sets orderDate, updatedAt, etc.)
// If approval is not required, it will also set the calculated status
@@ -114,7 +112,7 @@ export async function action(args: ActionFunctionArgs) {
userId
});
- if (shouldSetNeedsApproval) {
+ if (approvalRequired) {
const hasPending = await hasPendingApproval(
serviceRole,
"purchaseOrder",
@@ -141,15 +139,6 @@ export async function action(args: ActionFunctionArgs) {
});
if (!approvalResult.error && approvalResult.data) {
- // Set status to "Needs Approval" immediately after finalizing
- // This ensures the flow is: Draft → Finalize → Needs Approval (not Draft → Finalize → To Receive and Invoice → Needs Approval)
- await updatePurchaseOrderStatus(client, {
- id: orderId,
- status: "Needs Approval",
- assignee: undefined,
- updatedBy: userId
- });
-
// Notify approvers
let notifyRecipient:
| { type: "group"; groupIds: string[] }
@@ -185,6 +174,13 @@ export async function action(args: ActionFunctionArgs) {
}
}
}
+
+ await updatePurchaseOrderStatus(client, {
+ id: orderId,
+ status: "Needs Approval",
+ assignee: undefined,
+ updatedBy: userId
+ });
}
// Check if we should update prices on purchase order finalize
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 2e72f7cc90..9c5c8991fd 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx
@@ -8,6 +8,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
+import { canApproveRequest } from "~/modules/approvals";
import { runMRP } from "~/modules/production";
import {
purchaseOrderStatusType,
@@ -36,14 +37,113 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const [update] = await Promise.all([
- updatePurchaseOrderStatus(client, {
- id,
- status,
- assignee: ["Closed"].includes(status) ? null : undefined,
- updatedBy: userId
- })
- ]);
+ const serviceRole = getCarbonServiceRole();
+
+ // Get current PO status before updating
+ const currentPo = await client
+ .from("purchaseOrder")
+ .select("status")
+ .eq("id", id)
+ .single();
+
+ const currentStatus = currentPo.data?.status;
+
+ // Cancel pending approval requests when closing the PO
+ // Closed POs are terminal - no approvals should remain pending
+ // Note: Approved/Rejected requests are NOT cancelled - they serve as audit trail
+ // Only "Pending" requests are cancelled since they're no longer actionable
+ if (status === "Closed") {
+ // Find all pending approval requests for this PO and cancel them
+ const cancelResult = await serviceRole
+ .from("approvalRequest")
+ .update({
+ status: "Cancelled",
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("documentType", "purchaseOrder")
+ .eq("documentId", id)
+ .eq("status", "Pending")
+ .select("id");
+
+ if (cancelResult.data && cancelResult.data.length > 0) {
+ console.log(
+ `Cancelled ${cancelResult.data.length} pending approval request(s) for PO ${id} when closing`
+ );
+ }
+ }
+
+ // Cancel pending approval requests when reopening to Draft
+ // This handles reopening from both "Needs Approval" and "Closed" statuses
+ if (status === "Draft") {
+ // Find all pending approval requests for this PO
+ const pendingApprovals = await serviceRole
+ .from("approvalRequest")
+ .select("*")
+ .eq("documentType", "purchaseOrder")
+ .eq("documentId", id)
+ .eq("status", "Pending");
+
+ if (pendingApprovals.data && pendingApprovals.data.length > 0) {
+ if (currentStatus === "Closed") {
+ // System action when reopening from Closed - cancel all regardless of requester
+ await serviceRole
+ .from("approvalRequest")
+ .update({
+ status: "Cancelled",
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("documentType", "purchaseOrder")
+ .eq("documentId", id)
+ .eq("status", "Pending");
+ } else if (currentStatus === "Needs Approval") {
+ // Security check: Only allow reopening if user is the requester OR an approver
+ // This prevents non-approvers from bypassing the approval workflow
+ const latestApproval = pendingApprovals.data[0]; // Get the latest pending request
+ const isRequester = latestApproval.requestedBy === userId;
+ const isApprover = await canApproveRequest(
+ serviceRole,
+ latestApproval,
+ userId
+ );
+
+ if (!isRequester && !isApprover) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.quote(id),
+ await flash(
+ request,
+ error(
+ new Error(
+ "Only the requester or an approver can reopen a purchase order that needs approval"
+ ),
+ "You do not have permission to reopen this purchase order"
+ )
+ )
+ );
+ }
+
+ // Cancel all pending approval requests when reopening (user has permission)
+ await serviceRole
+ .from("approvalRequest")
+ .update({
+ status: "Cancelled",
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("documentType", "purchaseOrder")
+ .eq("documentId", id)
+ .eq("status", "Pending");
+ }
+ }
+ }
+
+ const update = await updatePurchaseOrderStatus(client, {
+ id,
+ status,
+ assignee: ["Closed"].includes(status) ? null : undefined,
+ updatedBy: userId
+ });
if (update.error) {
throw redirect(
requestReferrer(request) ?? path.to.quote(id),
@@ -55,7 +155,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
if (status === "Planned") {
- await runMRP(getCarbonServiceRole(), {
+ await runMRP(serviceRole, {
type: "purchaseOrder",
id,
companyId,
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index a8d743e721..9137fb82f4 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -1,10 +1,15 @@
-import { error } from "@carbon/auth";
+import { error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
+import {
+ canApproveRequest,
+ canCancelRequest,
+ getLatestApprovalForDocument
+} from "~/modules/approvals";
import {
getPurchaseOrder,
getPurchaseOrderDelivery,
@@ -29,7 +34,7 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
view: "purchasing",
bypassRls: true
});
@@ -67,13 +72,54 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw redirect(path.to.purchaseOrders);
}
- const [supplier, interaction] = await Promise.all([
+ const serviceRole = getCarbonServiceRole();
+ const [supplier, interaction, approvalRequest] = await Promise.all([
purchaseOrder.data?.supplierId
? getSupplier(client, purchaseOrder.data.supplierId)
: null,
- getSupplierInteraction(client, purchaseOrder.data.supplierInteractionId)
+ getSupplierInteraction(client, purchaseOrder.data.supplierInteractionId),
+ // Only fetch approval request if status is "Needs Approval"
+ purchaseOrder.data?.status === "Needs Approval"
+ ? getLatestApprovalForDocument(serviceRole, "purchaseOrder", orderId)
+ : Promise.resolve({ data: null, error: null })
]);
+ // Check if user can approve the request
+ let canApprove = false;
+ let canReopen = true; // Default to true (no approval request = can reopen)
+ let canDelete = true; // Default to true (no approval request = can delete)
+
+ if (
+ approvalRequest.data &&
+ purchaseOrder.data?.status === "Needs Approval" &&
+ approvalRequest.data.status === "Pending" &&
+ approvalRequest.data.requestedBy
+ ) {
+ const requestedBy = approvalRequest.data.requestedBy;
+ const status = approvalRequest.data.status;
+
+ canApprove = await canApproveRequest(
+ serviceRole,
+ approvalRequest.data,
+ userId
+ );
+
+ // Check if user can reopen: must be requester OR approver
+ const isRequester = canCancelRequest(
+ {
+ requestedBy,
+ status
+ },
+ userId
+ );
+ const isApprover = canApprove;
+ canReopen = isRequester || isApprover;
+
+ // Check if user can delete: only requester can delete POs in "Needs Approval"
+ // Approvers should reject instead, normal users have no permission
+ canDelete = isRequester;
+ }
+
return {
purchaseOrder: purchaseOrder.data,
purchaseOrderDelivery: purchaseOrderDelivery.data,
@@ -84,7 +130,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
purchaseOrder.data.supplierInteractionId!
),
interaction: interaction?.data,
- supplier: supplier?.data ?? null
+ supplier: supplier?.data ?? null,
+ approvalRequest: approvalRequest.data,
+ canApprove,
+ canReopen,
+ canDelete
};
}
diff --git a/apps/erp/app/routes/x+/purchasing+/_index.tsx b/apps/erp/app/routes/x+/purchasing+/_index.tsx
index 2af44fe889..bf99fc8627 100644
--- a/apps/erp/app/routes/x+/purchasing+/_index.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/_index.tsx
@@ -1,3 +1,4 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import {
Badge,
@@ -64,6 +65,10 @@ import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
import { Empty, Hyperlink, SupplierAvatar } from "~/components";
import { useUser } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
+import {
+ type ApprovalRequest,
+ getPendingApprovalsForApprover
+} from "~/modules/approvals";
import type { PurchaseInvoice } from "~/modules/invoicing";
import { PurchaseInvoicingStatus } from "~/modules/invoicing";
import type { PurchaseOrder, SupplierQuote } from "~/modules/purchasing";
@@ -98,45 +103,79 @@ export async function loader({ request }: LoaderFunctionArgs) {
view: "purchasing"
});
- const [openPurchaseOrders, openPurchaseInvoices, openSupplierQuotes] =
- await Promise.all([
- client
- .from("purchaseOrder")
- .select(
- "id, purchaseOrderId, status, supplierId, assignee, createdAt",
- {
- count: "exact"
- }
- )
- .in("status", OPEN_PURCHASE_ORDER_STATUSES)
- .eq("companyId", companyId)
- .limit(10),
- client
- .from("purchaseInvoice")
- .select("id, invoiceId, status, supplierId, assignee, createdAt", {
- count: "exact"
- })
- .in("status", OPEN_INVOICE_STATUSES)
- .eq("companyId", companyId)
- .limit(10),
- client
- .from("supplierQuote")
- .select(
- "id, supplierQuoteId, status, supplierId, assignee, createdAt",
- {
- count: "exact"
- }
- )
- .in("status", OPEN_SUPPLIER_QUOTE_STATUSES)
- .eq("companyId", companyId)
- .limit(10)
- ]);
+ const serviceRole = getCarbonServiceRole();
+
+ // Get pending approval requests to find which POs the user can approve
+ const pendingApprovals = await getPendingApprovalsForApprover(
+ serviceRole,
+ userId,
+ companyId
+ );
+
+ // Extract purchase order IDs that need approval and user can approve
+ const approvalPoIds =
+ pendingApprovals.data
+ ?.filter(
+ (approval: ApprovalRequest) =>
+ approval.documentType === "purchaseOrder" && approval.documentId
+ )
+ .map((approval: ApprovalRequest) => approval.documentId!)
+ .filter((id): id is string => !!id) ?? [];
+
+ const [
+ openPurchaseOrders,
+ openPurchaseInvoices,
+ openSupplierQuotes,
+ purchaseOrdersNeedingApproval
+ ] = await Promise.all([
+ client
+ .from("purchaseOrder")
+ .select("id, purchaseOrderId, status, supplierId, assignee, createdAt", {
+ count: "exact"
+ })
+ .in("status", OPEN_PURCHASE_ORDER_STATUSES)
+ .eq("companyId", companyId)
+ .limit(10),
+ client
+ .from("purchaseInvoice")
+ .select("id, invoiceId, status, supplierId, assignee, createdAt", {
+ count: "exact"
+ })
+ .in("status", OPEN_INVOICE_STATUSES)
+ .eq("companyId", companyId)
+ .limit(10),
+ client
+ .from("supplierQuote")
+ .select("id, supplierQuoteId, status, supplierId, assignee, createdAt", {
+ count: "exact"
+ })
+ .in("status", OPEN_SUPPLIER_QUOTE_STATUSES)
+ .eq("companyId", companyId)
+ .limit(10),
+ approvalPoIds.length > 0
+ ? client
+ .from("purchaseOrder")
+ .select(
+ "id, purchaseOrderId, status, supplierId, assignee, createdAt"
+ )
+ .eq("status", "Needs Approval")
+ .eq("companyId", companyId)
+ .in("id", approvalPoIds)
+ : { data: [], error: null }
+ ]);
+
+ const assignedToMePromise = getPurchasingDocumentsAssignedToMe(
+ client,
+ userId,
+ companyId
+ );
return {
openPurchaseOrders: openPurchaseOrders,
openSupplierQuotes: openSupplierQuotes,
openPurchaseInvoices: openPurchaseInvoices,
- assignedToMe: getPurchasingDocumentsAssignedToMe(client, userId, companyId)
+ purchaseOrdersNeedingApproval: purchaseOrdersNeedingApproval,
+ assignedToMe: assignedToMePromise
};
}
@@ -145,6 +184,7 @@ export default function PurchaseDashboard() {
openPurchaseOrders,
openSupplierQuotes,
openPurchaseInvoices,
+ purchaseOrdersNeedingApproval,
assignedToMe
} = useLoaderData<typeof loader>();
@@ -161,11 +201,26 @@ export default function PurchaseDashboard() {
...(openPurchaseInvoices.data?.map((doc) => ({
...doc,
type: "purchaseInvoice"
+ })) ?? []),
+ ...(purchaseOrdersNeedingApproval.data?.map((doc) => ({
+ ...doc,
+ type: "purchaseOrder"
})) ?? [])
- ].sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
+ ]
+ .filter(
+ (doc, index, self) =>
+ index ===
+ self.findIndex((d) => d.id === doc.id && d.type === doc.type)
+ )
+ .sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
return merged;
- }, [openPurchaseOrders, openSupplierQuotes, openPurchaseInvoices]);
+ }, [
+ openPurchaseOrders,
+ openSupplierQuotes,
+ openPurchaseInvoices,
+ purchaseOrdersNeedingApproval
+ ]);
const kpiFetcher = useFetcher<typeof kpiLoader>();
const isFetching = kpiFetcher.state !== "idle" || !kpiFetcher.data;
@@ -619,7 +674,7 @@ export default function PurchaseDashboard() {
<CardHeader className="px-6 pb-0">
<CardTitle>Assigned to Me</CardTitle>
<CardDescription className="text-sm">
- Sales documents currently assigned to me
+ Purchasing documents assigned to me and pending approvals
</CardDescription>
</CardHeader>
<CardContent className="p-6 min-h-[200px]">
@@ -628,52 +683,14 @@ export default function PurchaseDashboard() {
resolve={assignedToMe}
errorElement={<div>Error loading assigned documents</div>}
>
- {(assignedDocs) =>
- assignedDocs.length > 0 ? (
- <Table>
- <Thead>
- <Tr>
- <Th>Document</Th>
- <Th>Status</Th>
- <Th>Customer</Th>
- </Tr>
- </Thead>
- <Tbody>
- {assignedDocs.map((doc) => {
- switch (doc.type) {
- case "purchaseOrder":
- return (
- <PurchaseOrderDocumentRow
- key={doc.id}
- doc={doc as unknown as PurchaseOrder}
- />
- );
- case "supplierQuote":
- return (
- <SupplierQuoteRow
- key={doc.id}
- doc={doc as unknown as SupplierQuote}
- />
- );
- case "purchaseInvoice":
- return (
- <PurchaseInvoiceRow
- key={doc.id}
- doc={doc as unknown as PurchaseInvoice}
- />
- );
- default:
- return null;
- }
- })}
- </Tbody>
- </Table>
- ) : (
- <div className="flex justify-center items-center h-full">
- <Empty />
- </div>
- )
- }
+ {(assignedDocs) => (
+ <AssignedDocumentsTable
+ assignedDocs={assignedDocs}
+ purchaseOrdersNeedingApproval={
+ purchaseOrdersNeedingApproval.data ?? []
+ }
+ />
+ )}
</Await>
</Suspense>
</CardContent>
@@ -683,6 +700,82 @@ export default function PurchaseDashboard() {
);
}
+type AssignedDocument = {
+ id: string;
+ type: "purchaseOrder" | "supplierQuote" | "purchaseInvoice";
+ [key: string]: unknown;
+};
+
+function AssignedDocumentsTable({
+ assignedDocs,
+ purchaseOrdersNeedingApproval
+}: {
+ assignedDocs: Array<{ id: string; type: string; [key: string]: unknown }>;
+ purchaseOrdersNeedingApproval: Array<{
+ id: string;
+ purchaseOrderId: string;
+ status: string;
+ supplierId: string | null;
+ assignee: string | null;
+ createdAt: string | null;
+ }>;
+}) {
+ // Merge assigned docs with purchase orders needing approval
+ // Deduplicate: if a PO is both assigned and needs approval, prefer the assigned version
+ const assignedPurchaseOrderIds = new Set(
+ assignedDocs
+ .filter((doc) => doc.type === "purchaseOrder")
+ .map((doc) => doc.id)
+ );
+
+ const approvalDocs = purchaseOrdersNeedingApproval
+ .filter((po) => !assignedPurchaseOrderIds.has(po.id))
+ .map((doc) => ({
+ ...doc,
+ type: "purchaseOrder" as const
+ }));
+
+ const allDocs = [...assignedDocs, ...approvalDocs] as AssignedDocument[];
+
+ if (allDocs.length === 0) {
+ return (
+ <div className="flex justify-center items-center h-full">
+ <Empty />
+ </div>
+ );
+ }
+
+ return (
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Document</Th>
+ <Th>Status</Th>
+ <Th>Supplier</Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {allDocs.map((doc) => (
+ <DocumentRow key={doc.id} doc={doc} />
+ ))}
+ </Tbody>
+ </Table>
+ );
+}
+
+function DocumentRow({ doc }: { doc: AssignedDocument }) {
+ switch (doc.type) {
+ case "purchaseOrder":
+ return <PurchaseOrderDocumentRow doc={doc as unknown as PurchaseOrder} />;
+ case "supplierQuote":
+ return <SupplierQuoteRow doc={doc as unknown as SupplierQuote} />;
+ case "purchaseInvoice":
+ return <PurchaseInvoiceRow doc={doc as unknown as PurchaseInvoice} />;
+ default:
+ return null;
+ }
+}
+
function SupplierQuoteRow({ doc }: { doc: SupplierQuote }) {
return (
<Tr>
diff --git a/apps/erp/app/routes/x+/purchasing+/orders.tsx b/apps/erp/app/routes/x+/purchasing+/orders.tsx
index 779563b34e..2dba7027a1 100644
--- a/apps/erp/app/routes/x+/purchasing+/orders.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/orders.tsx
@@ -5,7 +5,7 @@ import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
import { getPurchaseOrders } from "~/modules/purchasing";
-import { PurchaseOrdersTable } from "~/modules/purchasing/ui/PurchaseOrder";
+import PurchaseOrdersTable from "~/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";