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 kpi dashboard

Brad Barbin83c465b6da6d
diff --git a/apps/erp/app/hooks/useModules.tsx b/apps/erp/app/hooks/useModules.tsx
index 0af54728fa..6635e50107 100644
--- a/apps/erp/app/hooks/useModules.tsx
+++ b/apps/erp/app/hooks/useModules.tsx
@@ -46,7 +46,7 @@ export function useModules() {
{
permission: "purchasing",
name: "Purchasing",
- to: path.to.purchaseOrders,
+ to: path.to.purchasing,
icon: LuShoppingCart,
},
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx
index 441d4cb1c0..f1901e5f0e 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx
@@ -165,7 +165,7 @@ const PurchaseInvoiceProperties = () => {
<Assignee
id={invoiceId}
- table="purchaseOrder"
+ table="purchaseInvoice"
value={assignee ?? ""}
variant="inline"
isReadOnly={!permissions.can("update", "purchasing")}
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
index 777757829c..1378c1a773 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
@@ -333,18 +333,19 @@ const PurchaseInvoiceSummary = () => {
<CardHeader>
<HStack className="justify-between items-center">
<div className="flex flex-col gap-1">
- <CardTitle>
- Purchase Invoice {routeData?.purchaseInvoice.invoiceId}
- </CardTitle>
+ <CardTitle>{routeData?.purchaseInvoice.invoiceId}</CardTitle>
+ <CardDescription>Purchase Invoice</CardDescription>
+ </div>
+ <div className="flex flex-col gap-1 items-end">
+ <SupplierAvatar
+ supplierId={routeData?.purchaseInvoice.supplierId ?? null}
+ />
{routeData?.purchaseInvoice?.dateDue && (
- <CardDescription>
- Due {formatDate(routeData.purchaseInvoice.dateDue)}
- </CardDescription>
+ <span className="text-muted-foreground text-sm">
+ Due {formatDate(routeData?.purchaseInvoice.dateDue)}
+ </span>
)}
</div>
- <SupplierAvatar
- supplierId={routeData?.purchaseInvoice?.supplierId ?? null}
- />
</HStack>
</CardHeader>
<CardContent>
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index c4d2cac65b..f00677094c 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -4,6 +4,33 @@ import { zfd } from "zod-form-data";
import { address, contact } from "~/types/validators";
import { methodItemType } from "../shared";
+export const KPIs = [
+ {
+ key: "supplierQuoteCount",
+ label: "Supplier Quotes",
+ },
+ {
+ key: "purchaseOrderCount",
+ label: "Purchase Orders",
+ },
+ {
+ key: "purchaseInvoiceCount",
+ label: "Purchase Invoices",
+ },
+ {
+ key: "purchaseOrderAmount",
+ label: "Purchase Order Amount",
+ },
+ {
+ key: "purchaseInvoiceAmount",
+ label: "Purchase Invoice Amount",
+ },
+ // {
+ // key: "turnaroundTime",
+ // label: "Turnaround Time",
+ // },
+] as const;
+
export const purchaseOrderLineType = [
"Part",
// "Service",
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index af9e14122f..3941610b29 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -273,6 +273,47 @@ export async function getPurchaseOrderSuppliers(
.order("name");
}
+export async function getPurchasingDocumentsAssignedToMe(
+ client: SupabaseClient<Database>,
+ userId: string,
+ companyId: string
+) {
+ const [purchaseOrders, supplierQuotes, purchaseInvoices] = await Promise.all([
+ client
+ .from("purchaseOrder")
+ .select("*")
+ .eq("assignee", userId)
+ .eq("companyId", companyId),
+ client
+ .from("supplierQuote")
+ .select("*")
+ .eq("assignee", userId)
+ .eq("companyId", companyId),
+ client
+ .from("purchaseInvoice")
+ .select("*")
+ .eq("assignee", userId)
+ .eq("companyId", companyId),
+ ]);
+
+ const merged = [
+ ...(purchaseOrders.data?.map((doc) => ({
+ ...doc,
+ type: "purchaseOrder",
+ })) ?? []),
+ ...(supplierQuotes.data?.map((doc) => ({
+ ...doc,
+ type: "supplierQuote",
+ })) ?? []),
+ ...(purchaseInvoices.data?.map((doc) => ({
+ ...doc,
+ type: "purchaseInvoice",
+ })) ?? []),
+ ].sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""));
+
+ return merged;
+}
+
export async function getPurchasingTerms(
client: SupabaseClient<Database>,
companyId: string
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
index 057abeec30..32e9793b84 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
@@ -335,18 +335,19 @@ const PurchaseOrderSummary = () => {
<CardHeader>
<HStack className="justify-between items-center">
<div className="flex flex-col gap-1">
- <CardTitle>
- Purchase Order {routeData?.purchaseOrder.purchaseOrderId}
- </CardTitle>
+ <CardTitle>{routeData?.purchaseOrder.purchaseOrderId}</CardTitle>
+ <CardDescription>Purchase Order</CardDescription>
+ </div>
+ <div className="flex flex-col gap-1 items-end">
+ <SupplierAvatar
+ supplierId={routeData?.purchaseOrder.supplierId ?? null}
+ />
{routeData?.purchaseOrder?.orderDate && (
- <CardDescription>
- Ordered {formatDate(routeData.purchaseOrder.orderDate)}
- </CardDescription>
+ <span className="text-muted-foreground text-sm">
+ Ordered {formatDate(routeData?.purchaseOrder.orderDate)}
+ </span>
)}
</div>
- <SupplierAvatar
- supplierId={routeData?.purchaseOrder?.supplierId ?? null}
- />
</HStack>
</CardHeader>
<CardContent>
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
index 2eee21ef92..592d72fd70 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
@@ -311,14 +311,17 @@ const SupplierQuoteSummary = () => {
<CardHeader>
<HStack className="justify-between items-center">
<div className="flex flex-col gap-1">
- <CardTitle>Quote {routeData?.quote.supplierQuoteId}</CardTitle>
+ <CardTitle>{routeData?.quote.supplierQuoteId}</CardTitle>
+ <CardDescription>Supplier Quote</CardDescription>
+ </div>
+ <div className="flex flex-col gap-1 items-end">
+ <SupplierAvatar supplierId={routeData?.quote.supplierId ?? null} />
{routeData?.quote?.expirationDate && (
- <CardDescription>
+ <span className="text-muted-foreground text-sm">
Expires {formatDate(routeData?.quote.expirationDate)}
- </CardDescription>
+ </span>
)}
</div>
- <SupplierAvatar supplierId={routeData?.quote.supplierId ?? null} />
</HStack>
</CardHeader>
<CardContent>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
index 8baad60bb3..54e944d24b 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
@@ -651,16 +651,20 @@ const QuoteSummary = () => {
return (
<Card>
<CardHeader>
- <HStack className="justify-between items-center">
+ <HStack className="justify-between items-center w-full">
<div className="flex flex-col gap-1">
- <CardTitle>Quote {routeData?.quote.quoteId}</CardTitle>
+ <CardTitle>{routeData?.quote.quoteId}</CardTitle>
+
+ <CardDescription>Quote </CardDescription>
+ </div>
+ <div className="flex flex-col gap-1 items-end">
+ <CustomerAvatar customerId={routeData?.quote.customerId ?? null} />
{routeData?.quote?.expirationDate && (
- <CardDescription>
+ <span className="text-muted-foreground text-sm">
Expires {formatDate(routeData?.quote.expirationDate)}
- </CardDescription>
+ </span>
)}
</div>
- <CustomerAvatar customerId={routeData?.quote.customerId ?? null} />
</HStack>
</CardHeader>
<CardContent>
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
index 3e0c77f26c..054e0d786e 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
@@ -305,18 +305,19 @@ const SalesOrderSummary = () => {
<CardHeader>
<HStack className="justify-between items-center">
<div className="flex flex-col gap-1">
- <CardTitle>
- Sales Order {routeData?.salesOrder.salesOrderId}
- </CardTitle>
+ <CardTitle>{routeData?.salesOrder.salesOrderId}</CardTitle>
+ <CardDescription>Sales Order</CardDescription>
+ </div>
+ <div className="flex flex-col gap-1 items-end">
+ <CustomerAvatar
+ customerId={routeData?.salesOrder.customerId ?? null}
+ />
{routeData?.salesOrder?.orderDate && (
- <CardDescription>
- Ordered {formatDate(routeData.salesOrder.orderDate)}
- </CardDescription>
+ <span className="text-muted-foreground text-sm">
+ Ordered {formatDate(routeData?.salesOrder.orderDate)}
+ </span>
)}
</div>
- <CustomerAvatar
- customerId={routeData?.salesOrder?.customerId ?? null}
- />
</HStack>
</CardHeader>
<CardContent>
diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.ts
index 07aed45fe4..0523a5499d 100644
--- a/apps/erp/app/modules/shared/shared.models.ts
+++ b/apps/erp/app/modules/shared/shared.models.ts
@@ -1,6 +1,14 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
+export const chartIntervals = [
+ { key: "week", label: "Week" },
+ { key: "month", label: "Month" },
+ { key: "quarter", label: "Quarter" },
+ { key: "year", label: "Year" },
+ { key: "custom", label: "Custom" },
+];
+
export const documentTypes = [
"Archive",
"Document",
diff --git a/apps/erp/app/routes/api+/purchasing.kpi.$key.ts b/apps/erp/app/routes/api+/purchasing.kpi.$key.ts
new file mode 100644
index 0000000000..04858f446a
--- /dev/null
+++ b/apps/erp/app/routes/api+/purchasing.kpi.$key.ts
@@ -0,0 +1,381 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { parseDate } from "@internationalized/date";
+import { json, type LoaderFunctionArgs } from "@vercel/remix";
+import { KPIs } from "~/modules/purchasing/purchasing.models";
+import { months } from "~/modules/shared/shared.models";
+import { groupDataByDay, groupDataByMonth } from "~/utils/chart";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+
+ const start = String(searchParams.get("start"));
+ const end = String(searchParams.get("end"));
+
+ const startDate = parseDate(start);
+ const endDate = parseDate(end);
+
+ const daysBetween = endDate.compare(startDate);
+
+ // Calculate previous period dates
+ const previousEndDate = startDate;
+ const previousStartDate = previousEndDate.subtract({ days: daysBetween });
+
+ const interval = searchParams.get("interval");
+
+ const { key } = params;
+ if (
+ !key ||
+ !start ||
+ !end ||
+ !interval ||
+ daysBetween < 1 ||
+ daysBetween > 500
+ )
+ return json({
+ data: [],
+ previousPeriodData: [],
+ });
+
+ const kpi = KPIs.find((k) => k.key === key);
+ if (!kpi)
+ return json({
+ data: [],
+ previousPeriodData: [],
+ });
+
+ switch (kpi.key) {
+ case "purchaseOrderCount":
+ case "purchaseOrderAmount": {
+ const [orders, previousOrders] = await Promise.all([
+ client
+ .from("purchaseOrders")
+ .select("orderTotal, orderDate")
+ .eq("companyId", companyId)
+ .in("status", [
+ "To Review",
+ "To Receive",
+ "To Invoice",
+ "To Receive and Invoice",
+ "Completed",
+ ])
+ .gt("orderDate", start)
+ .lte("orderDate", end)
+ .order("orderDate", { ascending: false }),
+ client
+ .from("purchaseOrders")
+ .select("orderTotal, orderDate")
+ .eq("companyId", companyId)
+ .in("status", [
+ "To Review",
+ "To Receive",
+ "To Invoice",
+ "To Receive and Invoice",
+ "Completed",
+ ])
+ .gt("orderDate", previousStartDate.toString())
+ .lte("orderDate", previousEndDate.toString())
+ .order("orderDate", { ascending: false }),
+ ]);
+
+ if (daysBetween < 60) {
+ const [groupedData, previousGroupedData] = [
+ groupDataByDay(orders.data ?? [], {
+ start,
+ end,
+ groupBy: "orderDate",
+ }),
+ groupDataByDay(previousOrders.data ?? [], {
+ start: previousStartDate.toString(),
+ end: previousEndDate.toString(),
+ groupBy: "orderDate",
+ }),
+ ];
+
+ const [data, previousPeriodData] = [
+ Object.entries(groupedData)
+ .map(([date, d]) => ({
+ date,
+ value:
+ kpi.key === "purchaseOrderAmount"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date)),
+ Object.entries(previousGroupedData)
+ .map(([date, d]) => ({
+ date,
+ value:
+ kpi.key === "purchaseOrderAmount"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date)),
+ ];
+
+ return json({ data, previousPeriodData });
+ } else {
+ const [groupedData, previousGroupedData] = [
+ groupDataByMonth(orders.data ?? [], {
+ start,
+ end,
+ groupBy: "orderDate",
+ }),
+ groupDataByMonth(previousOrders.data ?? [], {
+ start: previousStartDate.toString(),
+ end: previousEndDate.toString(),
+ groupBy: "orderDate",
+ }),
+ ];
+
+ const [data, previousPeriodData] = [
+ Object.entries(groupedData)
+ .map(([date, d]) => ({
+ month: months[Number(date.split("-")[1]) - 1],
+ monthKey: date,
+ value:
+ kpi.key === "purchaseOrderAmount"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.monthKey.localeCompare(b.monthKey)),
+ Object.entries(previousGroupedData)
+ .map(([date, d]) => ({
+ month: months[Number(date.split("-")[1]) - 1],
+ monthKey: date,
+ value:
+ kpi.key === "purchaseOrderAmount"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.monthKey.localeCompare(b.monthKey)),
+ ];
+
+ return json({ data, previousPeriodData });
+ }
+ }
+
+ case "purchaseInvoiceCount":
+ case "purchaseInvoiceAmount": {
+ const dateField = "dateIssued";
+ const [invoices, previousInvoices] = await Promise.all([
+ client
+ .from("purchaseInvoices")
+ .select("orderTotal, dateIssued")
+ .eq("companyId", companyId)
+ .in("status", [
+ "Pending",
+ "Partially Paid",
+ "Paid",
+ "Submitted",
+ "Overdue",
+ ])
+ .gt(dateField, start)
+ .lte(dateField, end)
+ .order(dateField, { ascending: false }),
+ client
+ .from("purchaseInvoices")
+ .select("orderTotal, dateIssued")
+ .eq("companyId", companyId)
+ .in("status", [
+ "Pending",
+ "Partially Paid",
+ "Paid",
+ "Submitted",
+ "Overdue",
+ ])
+ .gt(dateField, previousStartDate.toString())
+ .lte(dateField, previousEndDate.toString())
+ .order(dateField, { ascending: false }),
+ ]);
+
+ if (daysBetween < 60) {
+ const [groupedData, previousGroupedData] = [
+ groupDataByDay(invoices.data ?? [], {
+ start,
+ end,
+ groupBy: dateField,
+ }),
+ groupDataByDay(previousInvoices.data ?? [], {
+ start: previousStartDate.toString(),
+ end: previousEndDate.toString(),
+ groupBy: dateField,
+ }),
+ ];
+
+ const [data, previousPeriodData] = [
+ Object.entries(groupedData)
+ .map(([date, d]) => ({
+ date,
+ value:
+ kpi.key === "purchaseInvoiceAmount"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date)),
+ Object.entries(previousGroupedData)
+ .map(([date, d]) => ({
+ date,
+ value:
+ kpi.key === "purchaseInvoiceAmount"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date)),
+ ];
+
+ return json({ data, previousPeriodData });
+ } else {
+ const [groupedData, previousGroupedData] = [
+ groupDataByMonth(invoices.data ?? [], {
+ start,
+ end,
+ groupBy: dateField,
+ }),
+ groupDataByMonth(previousInvoices.data ?? [], {
+ start: previousStartDate.toString(),
+ end: previousEndDate.toString(),
+ groupBy: dateField,
+ }),
+ ];
+
+ const [data, previousPeriodData] = [
+ Object.entries(groupedData)
+ .map(([date, d]) => ({
+ month: months[Number(date.split("-")[1]) - 1],
+ monthKey: date,
+ value:
+ kpi.key === "purchaseInvoiceAmount"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.monthKey.localeCompare(b.monthKey)),
+ Object.entries(previousGroupedData)
+ .map(([date, d]) => ({
+ month: months[Number(date.split("-")[1]) - 1],
+ monthKey: date,
+ value:
+ kpi.key === "purchaseInvoiceAmount"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.monthKey.localeCompare(b.monthKey)),
+ ];
+
+ return json({ data, previousPeriodData });
+ }
+ }
+
+ case "supplierQuoteCount": {
+ const [quotes, previousQuotes] = await Promise.all([
+ client
+ .from("supplierQuote")
+ .select("createdAt", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .gt("createdAt", start)
+ .lte("createdAt", end)
+ .order("createdAt", { ascending: false }),
+ client
+ .from("quote")
+ .select("createdAt", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .gt("createdAt", previousStartDate.toString())
+ .lte("createdAt", previousEndDate.toString())
+ .order("createdAt", { ascending: false }),
+ ]);
+
+ if (daysBetween < 60) {
+ const [groupedData, previousGroupedData] = [
+ groupDataByDay(
+ quotes.data?.map((q) => ({
+ createdAt: q.createdAt.split("T")[0],
+ })) ?? [],
+ {
+ start,
+ end,
+ groupBy: "createdAt",
+ }
+ ),
+ groupDataByDay(
+ previousQuotes.data?.map((q) => ({
+ createdAt: q.createdAt.split("T")[0],
+ })) ?? [],
+ {
+ start: previousStartDate.toString(),
+ end: previousEndDate.toString(),
+ groupBy: "createdAt",
+ }
+ ),
+ ];
+
+ const [data, previousPeriodData] = [
+ Object.entries(groupedData)
+ .map(([date, d]) => ({
+ date,
+ value: d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date)),
+ Object.entries(previousGroupedData)
+ .map(([date, d]) => ({
+ date,
+ value: d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date)),
+ ];
+
+ return json({ data, previousPeriodData });
+ } else {
+ const [groupedData, previousGroupedData] = [
+ groupDataByMonth(
+ quotes.data?.map((q) => ({
+ createdAt: q.createdAt.split("T")[0],
+ })) ?? [],
+ {
+ start,
+ end,
+ groupBy: "createdAt",
+ }
+ ),
+ groupDataByMonth(
+ previousQuotes.data?.map((q) => ({
+ createdAt: q.createdAt.split("T")[0],
+ })) ?? [],
+ {
+ start: previousStartDate.toString(),
+ end: previousEndDate.toString(),
+ groupBy: "createdAt",
+ }
+ ),
+ ];
+
+ const [data, previousPeriodData] = [
+ Object.entries(groupedData)
+ .map(([date, d]) => ({
+ month: months[Number(date.split("-")[1]) - 1],
+ monthKey: date,
+ value: d.length,
+ }))
+ .sort((a, b) => a.monthKey.localeCompare(b.monthKey)),
+ Object.entries(previousGroupedData)
+ .map(([date, d]) => ({
+ month: months[Number(date.split("-")[1]) - 1],
+ monthKey: date,
+ value: d.length,
+ }))
+ .sort((a, b) => a.monthKey.localeCompare(b.monthKey)),
+ ];
+
+ return json({ data, previousPeriodData });
+ }
+ }
+ default:
+ throw new Error(`Invalid KPI key: ${key}`);
+ }
+}
diff --git a/apps/erp/app/routes/api+/sales.kpi.$key.ts b/apps/erp/app/routes/api+/sales.kpi.$key.ts
index bdb1662b91..77bf871a1d 100644
--- a/apps/erp/app/routes/api+/sales.kpi.$key.ts
+++ b/apps/erp/app/routes/api+/sales.kpi.$key.ts
@@ -391,6 +391,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
default:
- throw new Error("Invalid KPI key");
+ throw new Error(`Invalid KPI key: ${key}`);
}
}
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
index 23fe01b429..4ab2cfbcf8 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
@@ -20,7 +20,8 @@ import { path } from "~/utils/path";
export const handle: Handle = {
breadcrumb: "Purchasing",
- to: path.to.purchaseInvoices,
+ to: path.to.purchasing,
+ module: "purchasing",
};
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/purchase-order+/_layout.tsx b/apps/erp/app/routes/x+/purchase-order+/_layout.tsx
index 27535a6bec..be327c24a0 100644
--- a/apps/erp/app/routes/x+/purchase-order+/_layout.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/_layout.tsx
@@ -9,7 +9,7 @@ export const meta: MetaFunction = () => {
export const handle: Handle = {
breadcrumb: "Purchasing",
- to: path.to.purchaseOrders,
+ to: path.to.purchasing,
module: "purchasing",
};
diff --git a/apps/erp/app/routes/x+/purchasing+/_index.tsx b/apps/erp/app/routes/x+/purchasing+/_index.tsx
index cae8dd1d8a..1914ae5ef7 100644
--- a/apps/erp/app/routes/x+/purchasing+/_index.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/_index.tsx
@@ -1,6 +1,693 @@
-import { redirect } from "@vercel/remix";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DateRangePicker,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Loading,
+ Skeleton,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
+} from "@carbon/react";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@carbon/react/Chart";
+import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
+import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";
+import type { DateRange } from "@react-types/datepicker";
+import { Await, Link, useFetcher, useLoaderData } from "@remix-run/react";
+import { defer, type LoaderFunctionArgs } from "@vercel/remix";
+import { Suspense, useEffect, useMemo, useState } from "react";
+import { CSVLink } from "react-csv";
+import {
+ LuArrowUpRight,
+ LuChevronDown,
+ LuCreditCard,
+ LuEllipsisVertical,
+ LuFile,
+ LuLayoutList,
+ LuPackageSearch,
+} from "react-icons/lu";
+import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
+import { Hyperlink, SupplierAvatar } from "~/components";
+import { useUser } from "~/hooks";
+import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
+import type { PurchaseInvoice } from "~/modules/invoicing";
+import { PurchaseInvoicingStatus } from "~/modules/invoicing";
+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 { SupplierQuoteStatus } from "~/modules/purchasing/ui/SupplierQuote";
+import { chartIntervals } from "~/modules/shared/shared.models";
+import type { loader as kpiLoader } from "~/routes/api+/purchasing.kpi.$key";
import { path } from "~/utils/path";
-export async function loader() {
- throw redirect(path.to.purchaseOrders);
+const OPEN_SUPPLIER_QUOTE_STATUSES = ["Active"];
+const OPEN_INVOICE_STATUSES = ["Draft", "Return", "Pending", "Partially Paid"];
+const OPEN_PURCHASE_ORDER_STATUSES = [
+ "Draft",
+ "To Review",
+ "To Receive",
+ "To Receive and Invoice",
+ "To Invoice",
+];
+
+const chartConfig = {
+ now: {
+ color: "hsl(var(--primary))", // Primary color
+ },
+} satisfies ChartConfig;
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, userId, companyId } = await requirePermissions(request, {
+ 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),
+ client
+ .from("purchaseInvoice")
+ .select("id, invoiceId, status, supplierId, assignee, createdAt", {
+ count: "exact",
+ })
+ .in("status", OPEN_INVOICE_STATUSES)
+ .eq("companyId", companyId),
+ client
+ .from("supplierQuote")
+ .select(
+ "id, supplierQuoteId, status, supplierId, assignee, createdAt",
+ {
+ count: "exact",
+ }
+ )
+ .in("status", OPEN_SUPPLIER_QUOTE_STATUSES)
+ .eq("companyId", companyId),
+ ]);
+
+ return defer({
+ openPurchaseOrders: openPurchaseOrders,
+ openSupplierQuotes: openSupplierQuotes,
+ openPurchaseInvoices: openPurchaseInvoices,
+ assignedToMe: getPurchasingDocumentsAssignedToMe(client, userId, companyId),
+ });
+}
+
+export default function PurchaseDashboard() {
+ const {
+ openPurchaseOrders,
+ openSupplierQuotes,
+ openPurchaseInvoices,
+ assignedToMe,
+ } = useLoaderData<typeof loader>();
+
+ const mergedOpenDocs = useMemo(() => {
+ const merged = [
+ ...(openPurchaseOrders.data?.map((doc) => ({
+ ...doc,
+ type: "purchaseOrder",
+ })) ?? []),
+ ...(openSupplierQuotes.data?.map((doc) => ({
+ ...doc,
+ type: "supplierQuote",
+ })) ?? []),
+ ...(openPurchaseInvoices.data?.map((doc) => ({
+ ...doc,
+ type: "purchaseInvoice",
+ })) ?? []),
+ ].sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
+
+ return merged;
+ }, [openPurchaseOrders, openSupplierQuotes, openPurchaseInvoices]);
+
+ const kpiFetcher = useFetcher<typeof kpiLoader>();
+ const isFetching = kpiFetcher.state !== "idle" || !kpiFetcher.data;
+
+ const dateFormatter = useDateFormatter({
+ month: "short",
+ day: "numeric",
+ });
+
+ const { company } = useUser();
+
+ const currencyFormatter = useCurrencyFormatter(company.baseCurrencyCode, 0);
+ const numberFormatter = useNumberFormatter({
+ maximumFractionDigits: 0,
+ notation: "compact",
+ compactDisplay: "short",
+ });
+
+ const [interval, setInterval] = useState("month");
+ const [selectedKpi, setSelectedKpi] = useState("purchaseOrderAmount");
+ const [dateRange, setDateRange] = useState<DateRange | null>(() => {
+ const end = today(getLocalTimeZone());
+ const start = end.add({ months: -1 });
+ return { start, end };
+ });
+
+ const selectedInterval =
+ chartIntervals.find((i) => i.key === interval) || chartIntervals[1];
+ const selectedKpiData = KPIs.find((k) => k.key === selectedKpi) || KPIs[0];
+
+ useEffect(() => {
+ kpiFetcher.load(
+ `${path.to.api.purchasingKpi(
+ selectedKpiData.key
+ )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}`
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedKpi, dateRange, interval, selectedKpiData.key]);
+
+ const onIntervalChange = (value: string) => {
+ const end = today(getLocalTimeZone());
+ if (value === "week") {
+ const start = end.add({ days: -7 });
+ setDateRange({ start, end });
+ } else if (value === "month") {
+ const start = end.add({ months: -1 });
+ setDateRange({ start, end });
+ } else if (value === "quarter") {
+ const start = end.add({ months: -3 });
+ setDateRange({ start, end });
+ } else if (value === "year") {
+ const start = end.add({ years: -1 });
+ setDateRange({ start, end });
+ }
+
+ setInterval(value);
+ };
+
+ const total =
+ kpiFetcher.data?.data.reduce((acc, curr) => acc + curr.value, 0) ?? 0;
+ const previousTotal =
+ kpiFetcher.data?.previousPeriodData.reduce(
+ (acc, curr) => acc + curr.value,
+ 0
+ ) ?? 0;
+ const percentageChange =
+ previousTotal === 0
+ ? total > 0
+ ? 100
+ : 0
+ : ((total - previousTotal) / previousTotal) * 100;
+
+ const csvData = useMemo(() => {
+ if (!kpiFetcher.data?.data) return [];
+ return [
+ ["Date", "Value"],
+ ...kpiFetcher.data.data.map((item) => [
+ "date" in item ? item.date : item.monthKey,
+ item.value,
+ ]),
+ ];
+ }, [kpiFetcher.data?.data]);
+
+ const csvFilename = useMemo(() => {
+ const startDate = dateRange?.start.toString();
+ const endDate = dateRange?.end.toString();
+ return `${selectedKpiData.label}_${startDate}_to_${endDate}.csv`;
+ }, [dateRange, selectedKpiData.label]);
+
+ return (
+ <div className="flex flex-col gap-4 w-full p-4 h-[calc(100dvh-var(--header-height))] overflow-y-auto scrollbar-thin scrollbar-thumb-rounded-full scrollbar-thumb-muted-foreground">
+ <div className="grid w-full gap-4 grid-cols-1 lg:grid-cols-3">
+ <Card className="p-6 rounded-xl items-start justify-start gap-y-4">
+ <HStack className="justify-between w-full items-start mb-4">
+ <div className="bg-muted/80 border border-border rounded-xl p-2 text-foreground shadow-md">
+ <LuPackageSearch className="size-5" />
+ </div>
+ <Button
+ size="sm"
+ rightIcon={<LuArrowUpRight />}
+ variant="secondary"
+ asChild
+ >
+ <Link
+ to={`${
+ path.to.supplierQuotes
+ }?filter=status:in:${OPEN_SUPPLIER_QUOTE_STATUSES.join(",")}`}
+ >
+ View Quotes
+ </Link>
+ </Button>
+ </HStack>
+ <div className="flex flex-col gap-2">
+ <h3 className="text-3xl font-medium tracking-tight">
+ {openSupplierQuotes.count ?? 0}
+ </h3>
+ <p className="text-sm text-muted-foreground tracking-tight">
+ Active Supplier Quotes
+ </p>
+ </div>
+ </Card>
+
+ <Card className="p-6 items-start justify-start gap-y-4">
+ <HStack className="justify-between w-full items-start mb-4">
+ <div className="bg-muted/80 border border-border rounded-xl p-2 text-foreground shadow-md">
+ <LuLayoutList className="size-5" />
+ </div>
+ <Button
+ size="sm"
+ rightIcon={<LuArrowUpRight />}
+ variant="secondary"
+ >
+ <Link
+ to={`${
+ path.to.purchaseOrders
+ }?filter=status:in:${OPEN_PURCHASE_ORDER_STATUSES.join(",")}`}
+ >
+ View Purchase Orders
+ </Link>
+ </Button>
+ </HStack>
+ <div className="flex flex-col gap-2">
+ <h3 className="text-3xl font-medium tracking-tight">
+ {openPurchaseOrders.count ?? 0}
+ </h3>
+ <p className="text-sm text-muted-foreground tracking-tight">
+ Open Purchase Orders
+ </p>
+ </div>
+ </Card>
+
+ <Card className="p-6 items-start justify-start gap-y-4">
+ <HStack className="justify-between w-full items-start mb-4">
+ <div className="bg-muted/80 border border-border rounded-xl p-2 text-foreground shadow-md">
+ <LuCreditCard className="size-5" />
+ </div>
+ <Button
+ size="sm"
+ rightIcon={<LuArrowUpRight />}
+ variant="secondary"
+ asChild
+ >
+ <Link
+ to={`${
+ path.to.purchaseInvoices
+ }?filter=status:in:${OPEN_INVOICE_STATUSES.join(",")}`}
+ >
+ View Invoices
+ </Link>
+ </Button>
+ </HStack>
+ <div className="flex flex-col gap-2">
+ <h3 className="text-3xl font-medium tracking-tight">
+ {openPurchaseInvoices.count ?? 0}
+ </h3>
+ <p className="text-sm text-muted-foreground tracking-tight">
+ Open Purchase Invoices
+ </p>
+ </div>
+ </Card>
+ </div>
+
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader className="pb-0">
+ <div className="flex w-full justify-start items-center gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ rightIcon={<LuChevronDown />}
+ className="hover:bg-background/80"
+ >
+ <span>{selectedKpiData.label}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="bottom" align="start">
+ <DropdownMenuRadioGroup
+ value={selectedKpi}
+ onValueChange={setSelectedKpi}
+ >
+ {KPIs.map((kpi) => (
+ <DropdownMenuRadioItem key={kpi.key} value={kpi.key}>
+ {kpi.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ rightIcon={<LuChevronDown />}
+ className="hover:bg-background/80"
+ >
+ <span>
+ {selectedInterval.key === "custom"
+ ? selectedInterval.label
+ : `Last ${selectedInterval.label}`}
+ </span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="bottom" align="start">
+ <DropdownMenuRadioGroup
+ value={interval}
+ onValueChange={onIntervalChange}
+ >
+ {chartIntervals.map((i) => (
+ <DropdownMenuRadioItem key={i.key} value={i.key}>
+ {i.key === "custom" ? i.label : `Last ${i.label}`}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {interval === "custom" && (
+ <DateRangePicker
+ size="sm"
+ value={dateRange}
+ onChange={setDateRange}
+ />
+ )}
+ </div>
+ <HStack className="text-sm text-muted-foreground pl-[3px] pt-1">
+ {isFetching ? (
+ <Skeleton className="h-5 w-1/4" />
+ ) : (
+ <>
+ <p>
+ {["purchaseOrderAmount", "purchaseInvoiceAmount"].includes(
+ selectedKpiData.key
+ )
+ ? currencyFormatter.format(total)
+ : numberFormatter.format(total)}
+ </p>
+ <Badge
+ variant="secondary"
+ className="normal-case font-medium px-2 rounded-full"
+ >
+ {percentageChange > 0
+ ? `+${percentageChange.toFixed(0)}%`
+ : `${percentageChange.toFixed(0)}%`}
+ </Badge>
+ </>
+ )}
+ </HStack>
+ </CardHeader>
+ <CardAction className="py-6 px-6">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="secondary"
+ icon={<LuEllipsisVertical />}
+ aria-label="More"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem>
+ <CSVLink
+ data={csvData}
+ filename={csvFilename}
+ className="flex flex-row items-center gap-2"
+ >
+ <DropdownMenuIcon icon={<LuFile />} />
+ Export CSV
+ </CSVLink>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </CardAction>
+ </HStack>
+ <CardContent className="p-6">
+ <Loading
+ isLoading={isFetching}
+ className="h-[30dvw] md:h-[23dvw] w-full"
+ >
+ <ChartContainer
+ config={chartConfig}
+ className="aspect-auto h-[30dvw] md:h-[23dvw] w-full"
+ >
+ <BarChart accessibilityLayer data={kpiFetcher.data?.data ?? []}>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ dataKey={
+ ["week", "month"].includes(interval) ? "date" : "month"
+ }
+ tickLine={false}
+ tickMargin={8}
+ minTickGap={32}
+ axisLine={false}
+ tickFormatter={(value) => {
+ if (!value) return "";
+ return ["week", "month"].includes(interval)
+ ? dateFormatter.format(
+ parseDate(value).toDate(getLocalTimeZone())
+ )
+ : value.slice(0, 3);
+ }}
+ />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ labelFormatter={
+ ["week", "month"].includes(interval)
+ ? (value) =>
+ dateFormatter.format(
+ parseDate(value).toDate(getLocalTimeZone())
+ )
+ : (value) => value
+ }
+ formatter={(value) =>
+ [
+ "purchaseOrderAmount",
+ "purchaseInvoiceAmount",
+ ].includes(selectedKpiData.key)
+ ? currencyFormatter.format(value as number)
+ : numberFormatter.format(value as number)
+ }
+ />
+ }
+ />
+ <Bar dataKey="value" fill="var(--color-now)" radius={2} />
+ </BarChart>
+ </ChartContainer>
+ </Loading>
+ </CardContent>
+ </Card>
+ <div className="grid w-full gap-4 grid-cols-1 lg:grid-cols-2">
+ <Card>
+ <CardHeader className="px-6 pb-0">
+ <CardTitle>Recently Created</CardTitle>
+ <CardDescription className="text-sm">
+ Recently created purchasing documents
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="p-6">
+ <div className="min-h-[200px] max-h-[360px] w-full overflow-y-auto">
+ {mergedOpenDocs.length > 0 ? (
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Document</Th>
+ <Th>Status</Th>
+ <Th>Customer</Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {mergedOpenDocs.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">
+ <p className="text-sm text-muted-foreground">
+ No recently created documents
+ </p>
+ </div>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="px-6 pb-0">
+ <CardTitle>Assigned to Me</CardTitle>
+ <CardDescription className="text-sm">
+ Sales documents currently assigned to me
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="p-6 min-h-[200px]">
+ <Suspense fallback={<Loading isLoading />}>
+ <Await
+ 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">
+ <p className="text-sm text-muted-foreground">
+ No documents assigned to me
+ </p>
+ </div>
+ )
+ }
+ </Await>
+ </Suspense>
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ );
+}
+
+function SupplierQuoteRow({ doc }: { doc: SupplierQuote }) {
+ return (
+ <Tr>
+ <Td>
+ <Hyperlink to={path.to.supplierQuote(doc.id!)}>
+ <HStack spacing={1}>
+ <LuPackageSearch className="size-4" />
+ <span>{doc.supplierQuoteId}</span>
+ </HStack>
+ </Hyperlink>
+ </Td>
+ <Td>
+ <SupplierQuoteStatus status={doc.status} />
+ </Td>
+ <Td>
+ <SupplierAvatar supplierId={doc.supplierId} />
+ </Td>
+ </Tr>
+ );
+}
+
+function PurchaseOrderDocumentRow({ doc }: { doc: PurchaseOrder }) {
+ return (
+ <Tr>
+ <Td>
+ <Hyperlink to={path.to.purchaseOrder(doc.id!)}>
+ <HStack spacing={1}>
+ <LuLayoutList className="size-4" />
+ <span>{doc.purchaseOrderId}</span>
+ </HStack>
+ </Hyperlink>
+ </Td>
+ <Td>
+ <PurchasingStatus status={doc.status} />
+ </Td>
+ <Td>
+ <SupplierAvatar supplierId={doc.supplierId} />
+ </Td>
+ </Tr>
+ );
+}
+
+function PurchaseInvoiceRow({ doc }: { doc: PurchaseInvoice }) {
+ return (
+ <Tr>
+ <Td>
+ <Hyperlink to={path.to.salesRfq(doc.id!)}>
+ <HStack spacing={1}>
+ <LuCreditCard className="size-4" />
+ <span>{doc.invoiceId}</span>
+ </HStack>
+ </Hyperlink>
+ </Td>
+ <Td>
+ <PurchaseInvoicingStatus status={doc.status} />
+ </Td>
+ <Td>
+ <SupplierAvatar supplierId={doc.supplierId} />
+ </Td>
+ </Tr>
+ );
}
diff --git a/apps/erp/app/routes/x+/purchasing+/_layout.tsx b/apps/erp/app/routes/x+/purchasing+/_layout.tsx
index 1623f6a8be..a33c7c8d9f 100644
--- a/apps/erp/app/routes/x+/purchasing+/_layout.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/_layout.tsx
@@ -13,7 +13,7 @@ export const meta: MetaFunction = () => {
export const handle: Handle = {
breadcrumb: "Purchasing",
- to: path.to.purchaseOrders,
+ to: path.to.purchasing,
module: "purchasing",
};
diff --git a/apps/erp/app/routes/x+/purchasing+/invoices.tsx b/apps/erp/app/routes/x+/purchasing+/invoices.tsx
index c6f0d782c2..3ae4f3c3f6 100644
--- a/apps/erp/app/routes/x+/purchasing+/invoices.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/invoices.tsx
@@ -14,7 +14,7 @@ import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
export const handle: Handle = {
- breadcrumb: "Purchase Invoices",
+ breadcrumb: "Invoices",
to: path.to.purchaseInvoices,
};
diff --git a/apps/erp/app/routes/x+/sales+/_index.tsx b/apps/erp/app/routes/x+/sales+/_index.tsx
index 6f56cbaae2..35cf8651c8 100644
--- a/apps/erp/app/routes/x+/sales+/_index.tsx
+++ b/apps/erp/app/routes/x+/sales+/_index.tsx
@@ -43,8 +43,8 @@ import { CSVLink } from "react-csv";
import {
LuArrowUpRight,
LuChevronDown,
- LuFile,
LuEllipsisVertical,
+ LuFile,
} from "react-icons/lu";
import {
RiProgress2Line,
@@ -61,6 +61,7 @@ import type { Quotation, SalesOrder, SalesRFQ } from "~/modules/sales/types";
import QuoteStatus from "~/modules/sales/ui/Quotes/QuoteStatus";
import { SalesStatus } from "~/modules/sales/ui/SalesOrder";
import { SalesRFQStatus } from "~/modules/sales/ui/SalesRFQ";
+import { chartIntervals } from "~/modules/shared/shared.models";
import type { loader as kpiLoader } from "~/routes/api+/sales.kpi.$key";
import { path } from "~/utils/path";
@@ -73,14 +74,6 @@ const OPEN_SALES_ORDER_STATUSES = [
"Draft",
];
-const CHART_INTERVALS = [
- { key: "week", label: "Week" },
- { key: "month", label: "Month" },
- { key: "quarter", label: "Quarter" },
- { key: "year", label: "Year" },
- { key: "custom", label: "Custom" },
-];
-
const chartConfig = {
now: {
color: "hsl(var(--primary))", // Primary color
@@ -167,7 +160,7 @@ export default function SalesDashboard() {
});
const selectedInterval =
- CHART_INTERVALS.find((i) => i.key === interval) || CHART_INTERVALS[1];
+ chartIntervals.find((i) => i.key === interval) || chartIntervals[1];
const selectedKpiData = KPIs.find((k) => k.key === selectedKpi) || KPIs[0];
useEffect(() => {
@@ -369,7 +362,7 @@ export default function SalesDashboard() {
value={interval}
onValueChange={onIntervalChange}
>
- {CHART_INTERVALS.map((i) => (
+ {chartIntervals.map((i) => (
<DropdownMenuRadioItem key={i.key} value={i.key}>
{i.key === "custom" ? i.label : `Last ${i.label}`}
</DropdownMenuRadioItem>
diff --git a/apps/erp/app/routes/x+/supplier+/_layout.tsx b/apps/erp/app/routes/x+/supplier+/_layout.tsx
index bc08625df5..a9124b27e1 100644
--- a/apps/erp/app/routes/x+/supplier+/_layout.tsx
+++ b/apps/erp/app/routes/x+/supplier+/_layout.tsx
@@ -14,7 +14,7 @@ export const meta: MetaFunction = () => {
export const handle: Handle = {
breadcrumb: "Purchasing",
- to: path.to.purchaseOrders,
+ to: path.to.purchasing,
module: "purchasing",
};
diff --git a/apps/erp/app/routes/x+/supplier-quote+/_layout.tsx b/apps/erp/app/routes/x+/supplier-quote+/_layout.tsx
index 8b2ad1142d..4cf9180ae4 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/_layout.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/_layout.tsx
@@ -10,7 +10,7 @@ export const meta: MetaFunction = () => {
export const handle: Handle = {
breadcrumb: "Purchasing",
- to: path.to.purchaseOrders,
+ to: path.to.purchasing,
module: "purchasing",
};
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 4cca3c8506..6e94033e67 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -41,6 +41,8 @@ export const path = {
materialForms: `${api}/items/forms`,
materialSubstances: `${api}/items/substances`,
modelUpload: `${api}/model/upload`,
+ purchasingKpi: (key: string) =>
+ generatePath(`${api}/purchasing/kpi/${key}`),
processes: `${api}/resources/processes`,
quotes: `${api}/sales/quotes`,
quoteLines: (quoteId: string) =>