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: wire up kpis

Brad Barbin2c0b3cd727e7
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index de6a21f8f4..5c467348fc 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -10,6 +10,29 @@ import {
standardFactorType,
} from "../shared";
+export const KPIs = [
+ {
+ key: "quoteCount",
+ label: "Quote Count",
+ },
+ {
+ key: "rfqCount",
+ label: "RFQ Count",
+ },
+ {
+ key: "salesOrderCount",
+ label: "Sales Order Count",
+ },
+ {
+ key: "salesOrderRevenue",
+ label: "Sales Order Revenue",
+ },
+ {
+ key: "turnaroundTime",
+ label: "Turnaround Time",
+ },
+] as const;
+
export const salesRFQStatusType = [
"Draft",
"Ready for Quote",
diff --git a/apps/erp/app/routes/api+/sales.kpi.$key.ts b/apps/erp/app/routes/api+/sales.kpi.$key.ts
new file mode 100644
index 0000000000..8ce878381c
--- /dev/null
+++ b/apps/erp/app/routes/api+/sales.kpi.$key.ts
@@ -0,0 +1,289 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { parseDate } from "@internationalized/date";
+import { json, type LoaderFunctionArgs } from "@vercel/remix";
+import { KPIs } from "~/modules/sales/sales.models";
+import { months } from "~/modules/shared/shared.models";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "sales",
+ });
+ 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);
+
+ const interval = searchParams.get("interval");
+
+ const { key } = params;
+ if (
+ !key ||
+ !start ||
+ !end ||
+ !interval ||
+ daysBetween < 1 ||
+ daysBetween > 500
+ )
+ return json({
+ data: [],
+ });
+
+ const kpi = KPIs.find((k) => k.key === key);
+ if (!kpi)
+ return json({
+ data: [],
+ });
+
+ switch (kpi.key) {
+ case "salesOrderRevenue":
+ case "salesOrderCount":
+ const salesOrders = await client
+ .from("salesOrders")
+ .select("orderTotal, orderDate", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .in("status", [
+ "In Progress",
+ "Needs Approval",
+ "Confirmed",
+ "Completed",
+ "Invoiced",
+ ])
+ .gt("orderDate", start)
+ .lte("orderDate", end)
+ .order("orderDate", { ascending: false });
+
+ if (daysBetween < 60) {
+ const groupedData = groupDataByDay(salesOrders.data ?? [], {
+ start,
+ end,
+ groupBy: "orderDate",
+ });
+
+ const data = Object.entries(groupedData)
+ .map(([date, d]) => ({
+ date,
+ value:
+ kpi.key === "salesOrderRevenue"
+ ? d.reduce((sum, i) => {
+ return sum + (i.orderTotal ?? 0);
+ }, 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date));
+
+ return json({
+ data,
+ });
+ } else {
+ const groupedData = groupDataByMonth(salesOrders.data ?? [], {
+ start,
+ end,
+ groupBy: "orderDate",
+ });
+
+ const data = Object.entries(groupedData)
+ .map(([date, d]) => ({
+ month: months[Number(date.split("-")[1]) - 1],
+ monthKey: date,
+ value:
+ kpi.key === "salesOrderRevenue"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.monthKey.localeCompare(b.monthKey));
+
+ return json({
+ data,
+ });
+ }
+
+ case "quoteCount":
+ const quotes = await client
+ .from("quote")
+ .select("createdAt", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .in("status", ["Sent", "Ordered", "Partial", "Lost", "Expired"])
+ .gt("createdAt", start)
+ .lte("createdAt", end)
+ .order("createdAt", { ascending: false });
+
+ if (daysBetween < 60) {
+ const groupedData = groupDataByDay(
+ quotes.data?.map((q) => ({
+ createdAt: q.createdAt.split("T")[0],
+ })) ?? [],
+ {
+ start,
+ end,
+ groupBy: "createdAt",
+ }
+ );
+
+ const data = Object.entries(groupedData)
+ .map(([date, d]) => ({
+ date,
+ value: d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date));
+
+ return json({ data });
+ } else {
+ const groupedData = groupDataByMonth(
+ quotes.data?.map((q) => ({
+ createdAt: q.createdAt.split("T")[0],
+ })) ?? [],
+ {
+ start,
+ end,
+ groupBy: "createdAt",
+ }
+ );
+
+ const data = 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));
+
+ return json({ data });
+ }
+
+ case "rfqCount":
+ const rfqs = await client
+ .from("salesRfq")
+ .select("createdAt", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .in("status", ["Ready for Quote", "Quoted", "Closed"])
+ .gt("createdAt", start)
+ .lte("createdAt", end)
+ .order("createdAt", { ascending: false });
+
+ if (daysBetween < 60) {
+ const groupedData = groupDataByDay(
+ rfqs.data?.map((r) => ({
+ createdAt: r.createdAt?.split("T")[0],
+ })) ?? [],
+ {
+ start,
+ end,
+ groupBy: "createdAt",
+ }
+ );
+
+ const data = Object.entries(groupedData)
+ .map(([date, d]) => ({
+ date,
+ value: d.length,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date));
+
+ return json({ data });
+ } else {
+ const groupedData = groupDataByMonth(
+ rfqs.data?.map((r) => ({
+ createdAt: r.createdAt?.split("T")[0],
+ })) ?? [],
+ {
+ start,
+ end,
+ groupBy: "createdAt",
+ }
+ );
+
+ const data = 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));
+
+ return json({ data });
+ }
+
+ case "turnaroundTime":
+ return json({ data: [] });
+ default:
+ throw new Error("Invalid KPI key");
+ }
+}
+
+function groupDataByDay<T extends object>(
+ data: T[],
+ args: {
+ start: string;
+ end: string;
+ groupBy: keyof T;
+ }
+): Record<string, T[]> {
+ const { start, end, groupBy } = args;
+
+ const result: Record<string, T[]> = {};
+
+ let d = parseDate(start);
+ let e = parseDate(end);
+
+ if (d > e) return {};
+
+ while (d <= e) {
+ const date = d.toString();
+ result[date] = [];
+ d = d.add({ days: 1 });
+ }
+
+ data.forEach((d) => {
+ const date = d[groupBy]!.toString();
+ result[date].push(d);
+ });
+
+ return result;
+}
+
+function groupDataByMonth<T extends object>(
+ data: T[],
+ args: {
+ start: string;
+ end: string;
+ groupBy: keyof T;
+ }
+): Record<string, T[]> {
+ const { start, end, groupBy } = args;
+
+ const result: Record<string, T[]> = {};
+
+ let d = parseDate(start);
+ let e = parseDate(end);
+
+ if (d > e) return {};
+
+ while (d <= e) {
+ // Format as YYYY-MM
+ const monthKey = `${d.year}-${String(d.month).padStart(2, "0")}`;
+ result[monthKey] = [];
+ d = d.add({ months: 1 });
+ }
+
+ data.forEach((item) => {
+ const date = parseDate(item[groupBy]!.toString());
+ const monthKey = `${date.year}-${String(date.month).padStart(2, "0")}`;
+ if (result[monthKey]) {
+ result[monthKey].push(item);
+ }
+ });
+
+ return result;
+}
diff --git a/apps/erp/app/routes/x+/customer+/_layout.tsx b/apps/erp/app/routes/x+/customer+/_layout.tsx
index d2e5fbc034..616f6572cc 100644
--- a/apps/erp/app/routes/x+/customer+/_layout.tsx
+++ b/apps/erp/app/routes/x+/customer+/_layout.tsx
@@ -13,7 +13,7 @@ export const meta: MetaFunction = () => {
export const handle: Handle = {
breadcrumb: "Sales",
- to: path.to.quotes,
+ to: path.to.sales,
module: "sales",
};
diff --git a/apps/erp/app/routes/x+/sales+/_index.tsx b/apps/erp/app/routes/x+/sales+/_index.tsx
index 56546b42cc..4039dfd121 100644
--- a/apps/erp/app/routes/x+/sales+/_index.tsx
+++ b/apps/erp/app/routes/x+/sales+/_index.tsx
@@ -23,11 +23,12 @@ import {
ChartTooltipContent,
type ChartConfig,
} from "@carbon/react/Chart";
-import { getLocalTimeZone, today } from "@internationalized/date";
+import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
+import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";
import type { DateRange } from "@react-types/datepicker";
import { Link, useFetcher, useLoaderData } from "@remix-run/react";
import { json, type LoaderFunctionArgs } from "@vercel/remix";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { LuArrowUpRight, LuChevronDown, LuMoreVertical } from "react-icons/lu";
import {
RiProgress2Line,
@@ -35,6 +36,9 @@ import {
RiProgress8Line,
} from "react-icons/ri";
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
+import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
+import { KPIs } from "~/modules/sales/sales.models";
+import type { loader as kpiLoader } from "~/routes/api+/sales.kpi.$key";
import { path } from "~/utils/path";
const OPEN_RFQ_STATUSES = ["Ready for Quote", "Draft"];
@@ -73,42 +77,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
}
-const chartData = [
- { month: "January", desktop: 186, mobile: 80 },
- { month: "February", desktop: 305, mobile: 200 },
- { month: "March", desktop: 237, mobile: 120 },
- { month: "April", desktop: 73, mobile: 190 },
- { month: "May", desktop: 209, mobile: 130 },
- { month: "June", desktop: 214, mobile: 140 },
-];
-
-const KPIS = [
- {
- key: "salesOrderRevenue",
- label: "Sales Order Revenue",
- },
- {
- key: "quoteRevenue",
- label: "Quote Revenue",
- },
- {
- key: "salesOrderCount",
- label: "Sales Order Count",
- },
- {
- key: "quoteCount",
- label: "Quote Count",
- },
- {
- key: "rfqCount",
- label: "RFQ Count",
- },
- {
- key: "turnaroundTime",
- label: "Turnaround Time",
- },
-];
-
const CHART_INTERVALS = [
{ key: "week", label: "Week" },
{ key: "month", label: "Month" },
@@ -118,21 +86,24 @@ const CHART_INTERVALS = [
];
const chartConfig = {
- desktop: {
- label: "Desktop",
+ now: {
color: "hsl(var(--chart-1))", // Primary color
},
- mobile: {
- label: "Mobile",
- color: "hsl(var(--chart-2))", // Lighter primary
- },
} satisfies ChartConfig;
export default function SalesDashboard() {
const { openSalesOrders, openQuotes, openRFQs } =
useLoaderData<typeof loader>();
- const kpiFetcher = useFetcher<{ data: typeof chartData }>();
+ const kpiFetcher = useFetcher<typeof kpiLoader>();
+
+ const dateFormatter = useDateFormatter({
+ month: "short",
+ day: "numeric",
+ });
+
+ const currencyFormatter = useCurrencyFormatter();
+ const numberFormatter = useNumberFormatter();
const [interval, setInterval] = useState("month");
const [selectedKpi, setSelectedKpi] = useState("salesOrderRevenue");
@@ -144,7 +115,16 @@ export default function SalesDashboard() {
const selectedInterval =
CHART_INTERVALS.find((i) => i.key === interval) || CHART_INTERVALS[1];
- const selectedKpiData = KPIS.find((k) => k.key === selectedKpi) || KPIS[0];
+ const selectedKpiData = KPIs.find((k) => k.key === selectedKpi) || KPIs[0];
+
+ useEffect(() => {
+ kpiFetcher.load(
+ `${path.to.api.salesKpi(
+ 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());
@@ -278,7 +258,7 @@ export default function SalesDashboard() {
value={selectedKpi}
onValueChange={setSelectedKpi}
>
- {KPIS.map((kpi) => (
+ {KPIs.map((kpi) => (
<DropdownMenuRadioItem key={kpi.key} value={kpi.key}>
{kpi.label}
</DropdownMenuRadioItem>
@@ -338,29 +318,52 @@ export default function SalesDashboard() {
</HStack>
<CardContent className="p-4">
<Loading
- isLoading={kpiFetcher.state === "loading"}
- className="h-[30dvw] md:h-[20dvw] w-full"
+ isLoading={kpiFetcher.state === "loading" || !kpiFetcher.data}
+ className="h-[30dvw] md:h-[23dvw] w-full"
>
<ChartContainer
config={chartConfig}
- className="h-[30dvw] md:h-[20dvw] w-full"
+ className="aspect-auto h-[30dvw] md:h-[23dvw] w-full"
>
- <BarChart accessibilityLayer data={chartData}>
+ <BarChart accessibilityLayer data={kpiFetcher.data?.data ?? []}>
<CartesianGrid vertical={false} />
<XAxis
- dataKey="month"
+ dataKey={
+ ["week", "month"].includes(interval) ? "date" : "month"
+ }
tickLine={false}
- tickMargin={10}
+ tickMargin={8}
+ minTickGap={32}
axisLine={false}
- tickFormatter={(value) => value.slice(0, 3)}
+ tickFormatter={
+ ["week", "month"].includes(interval)
+ ? (value) =>
+ dateFormatter.format(
+ parseDate(value).toDate(getLocalTimeZone())
+ )
+ : (value) => value.slice(0, 3)
+ }
/>
- <ChartTooltip content={<ChartTooltipContent />} />
- <Bar
- dataKey="desktop"
- fill="var(--color-desktop)"
- radius={4}
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ labelFormatter={
+ ["week", "month"].includes(interval)
+ ? (value) =>
+ dateFormatter.format(
+ parseDate(value).toDate(getLocalTimeZone())
+ )
+ : (value) => value
+ }
+ formatter={(value) =>
+ ["salesOrderRevenue"].includes(selectedKpiData.key)
+ ? currencyFormatter.format(value as number)
+ : numberFormatter.format(value as number)
+ }
+ />
+ }
/>
- <Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
+ <Bar dataKey="value" fill="var(--color-now)" radius={2} />
</BarChart>
</ChartContainer>
</Loading>
@@ -374,10 +377,10 @@ export default function SalesDashboard() {
Newly created sales documents
</CardDescription>
</CardHeader>
- <CardContent className="p-4 min-h-[200px]">
- <Loading isLoading>
- <p>Hello</p>
- </Loading>
+ <CardContent className="p-4">
+ <div className="h-[30dvw] md:h-[23dvw] w-full overflow-y-auto">
+ <pre>{JSON.stringify(kpiFetcher.data?.data, null, 2)}</pre>
+ </div>
</CardContent>
</Card>
</div>
diff --git a/apps/erp/app/routes/x+/sales-order+/_layout.tsx b/apps/erp/app/routes/x+/sales-order+/_layout.tsx
index d5feb2c51f..9885119643 100644
--- a/apps/erp/app/routes/x+/sales-order+/_layout.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/_layout.tsx
@@ -9,7 +9,7 @@ export const meta: MetaFunction = () => {
export const handle: Handle = {
breadcrumb: "Sales",
- to: path.to.salesOrders,
+ to: path.to.sales,
module: "sales",
};
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index ac207c2d21..4cca3c8506 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -49,6 +49,7 @@ export const path = {
generatePath(
`${api}/settings/sequence/rollback?table=${table}&currentSequence=${id}`
),
+ salesKpi: (key: string) => generatePath(`${api}/sales/kpi/${key}`),
scrapReasons: `${api}/production/scrap-reasons`,
sequences: (table: string) => `${api}/settings/sequences?table=${table}`,
services: `${api}/items/services`,