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 percentage change from previous period

Brad Barbin121fd0da7338
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 5c467348fc..a9f9cc4461 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -13,24 +13,24 @@ import {
export const KPIs = [
{
key: "quoteCount",
- label: "Quote Count",
+ label: "Quotes",
},
{
key: "rfqCount",
- label: "RFQ Count",
+ label: "RFQs",
},
{
key: "salesOrderCount",
- label: "Sales Order Count",
+ label: "Sales Orders",
},
{
key: "salesOrderRevenue",
label: "Sales Order Revenue",
},
- {
- key: "turnaroundTime",
- label: "Turnaround Time",
- },
+ // {
+ // key: "turnaroundTime",
+ // label: "Turnaround Time",
+ // },
] as const;
export const salesRFQStatusType = [
diff --git a/apps/erp/app/routes/api+/sales.kpi.$key.ts b/apps/erp/app/routes/api+/sales.kpi.$key.ts
index 8ce878381c..b5764f4cf8 100644
--- a/apps/erp/app/routes/api+/sales.kpi.$key.ts
+++ b/apps/erp/app/routes/api+/sales.kpi.$key.ts
@@ -19,6 +19,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
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;
@@ -32,191 +36,359 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
)
return json({
data: [],
+ previousPeriodData: [],
});
const kpi = KPIs.find((k) => k.key === key);
if (!kpi)
return json({
data: [],
+ previousPeriodData: [],
});
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 });
+ case "salesOrderCount": {
+ const [salesOrders, previousSalesOrders] = await Promise.all([
+ 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 }),
+ client
+ .from("salesOrders")
+ .select("orderTotal, orderDate", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .in("status", [
+ "In Progress",
+ "Needs Approval",
+ "Confirmed",
+ "Completed",
+ "Invoiced",
+ ])
+ .gt("orderDate", previousStartDate.toString())
+ .lte("orderDate", previousEndDate.toString())
+ .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));
+ const [groupedData, previousGroupedData] = [
+ groupDataByDay(salesOrders.data ?? [], {
+ start,
+ end,
+ groupBy: "orderDate",
+ }),
+ groupDataByDay(previousSalesOrders.data ?? [], {
+ start: previousStartDate.toString(),
+ end: previousEndDate.toString(),
+ groupBy: "orderDate",
+ }),
+ ];
+
+ const [data, previousPeriodData] = [
+ 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)),
+ Object.entries(previousGroupedData)
+ .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,
+ previousPeriodData,
});
} 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));
+ const [groupedData, previousGroupedData] = [
+ groupDataByMonth(salesOrders.data ?? [], {
+ start,
+ end,
+ groupBy: "orderDate",
+ }),
+ groupDataByMonth(previousSalesOrders.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 === "salesOrderRevenue"
+ ? 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 === "salesOrderRevenue"
+ ? d.reduce((sum, i) => sum + (i.orderTotal ?? 0), 0)
+ : d.length,
+ }))
+ .sort((a, b) => a.monthKey.localeCompare(b.monthKey)),
+ ];
return json({
data,
+ previousPeriodData,
});
}
+ }
- 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 });
+ case "quoteCount": {
+ const [quotes, previousQuotes] = await Promise.all([
+ 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 }),
+ client
+ .from("quote")
+ .select("createdAt", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .in("status", ["Sent", "Ordered", "Partial", "Lost", "Expired"])
+ .gt("createdAt", previousStartDate.toString())
+ .lte("createdAt", previousEndDate.toString())
+ .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 });
+ 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 = 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 });
+ 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 });
}
+ }
- 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 });
+ case "rfqCount": {
+ const [rfqs, previousRfqs] = await Promise.all([
+ 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 }),
+ client
+ .from("salesRfq")
+ .select("createdAt", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .in("status", ["Ready for Quote", "Quoted", "Closed"])
+ .gt("createdAt", previousStartDate.toString())
+ .lte("createdAt", previousEndDate.toString())
+ .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 });
+ const [groupedData, previousGroupedData] = [
+ groupDataByDay(
+ rfqs.data?.map((r) => ({
+ createdAt: r.createdAt?.split("T")[0],
+ })) ?? [],
+ {
+ start,
+ end,
+ groupBy: "createdAt",
+ }
+ ),
+ groupDataByDay(
+ previousRfqs.data?.map((r) => ({
+ createdAt: r.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 = 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 });
+ const [groupedData, previousGroupedData] = [
+ groupDataByMonth(
+ rfqs.data?.map((r) => ({
+ createdAt: r.createdAt?.split("T")[0],
+ })) ?? [],
+ {
+ start,
+ end,
+ groupBy: "createdAt",
+ }
+ ),
+ groupDataByMonth(
+ previousRfqs.data?.map((r) => ({
+ createdAt: r.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 });
}
+ }
- case "turnaroundTime":
- return json({ data: [] });
default:
throw new Error("Invalid KPI key");
}
diff --git a/apps/erp/app/routes/x+/sales+/_index.tsx b/apps/erp/app/routes/x+/sales+/_index.tsx
index 4039dfd121..0f071a6e6a 100644
--- a/apps/erp/app/routes/x+/sales+/_index.tsx
+++ b/apps/erp/app/routes/x+/sales+/_index.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import {
+ Badge,
Button,
Card,
CardAction,
@@ -16,6 +17,7 @@ import {
HStack,
IconButton,
Loading,
+ Skeleton,
} from "@carbon/react";
import {
ChartContainer,
@@ -36,6 +38,7 @@ import {
RiProgress8Line,
} from "react-icons/ri";
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
+import { useUser } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
import { KPIs } from "~/modules/sales/sales.models";
import type { loader as kpiLoader } from "~/routes/api+/sales.kpi.$key";
@@ -96,14 +99,21 @@ export default function SalesDashboard() {
useLoaderData<typeof loader>();
const kpiFetcher = useFetcher<typeof kpiLoader>();
+ const isFetching = kpiFetcher.state !== "idle" || !kpiFetcher.data;
const dateFormatter = useDateFormatter({
month: "short",
day: "numeric",
});
- const currencyFormatter = useCurrencyFormatter();
- const numberFormatter = useNumberFormatter();
+ 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("salesOrderRevenue");
@@ -145,6 +155,20 @@ export default function SalesDashboard() {
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;
+
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">
@@ -302,13 +326,33 @@ export default function SalesDashboard() {
/>
)}
</div>
+ <HStack className="text-sm text-muted-foreground pl-[3px] pt-1">
+ {isFetching ? (
+ <Skeleton className="h-5 w-1/4" />
+ ) : (
+ <>
+ <p>
+ {["salesOrderRevenue"].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-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
variant="secondary"
- size="sm"
icon={<LuMoreVertical />}
aria-label="More"
/>
@@ -318,7 +362,7 @@ export default function SalesDashboard() {
</HStack>
<CardContent className="p-4">
<Loading
- isLoading={kpiFetcher.state === "loading" || !kpiFetcher.data}
+ isLoading={isFetching}
className="h-[30dvw] md:h-[23dvw] w-full"
>
<ChartContainer
@@ -335,14 +379,14 @@ export default function SalesDashboard() {
tickMargin={8}
minTickGap={32}
axisLine={false}
- tickFormatter={
- ["week", "month"].includes(interval)
- ? (value) =>
- dateFormatter.format(
- parseDate(value).toDate(getLocalTimeZone())
- )
- : (value) => value.slice(0, 3)
- }
+ tickFormatter={(value) => {
+ if (!value) return "";
+ return ["week", "month"].includes(interval)
+ ? dateFormatter.format(
+ parseDate(value).toDate(getLocalTimeZone())
+ )
+ : value.slice(0, 3);
+ }}
/>
<ChartTooltip
content={
@@ -379,7 +423,7 @@ export default function SalesDashboard() {
</CardHeader>
<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>
+ {/* TODO: Add recent activity */}
</div>
</CardContent>
</Card>
@@ -392,7 +436,9 @@ export default function SalesDashboard() {
Sales documents currently assigned to me
</CardDescription>
</CardHeader>
- <CardContent className="p-4 min-h-[200px]"></CardContent>
+ <CardContent className="p-4 min-h-[200px]">
+ {/* TODO: Add assigned to me */}
+ </CardContent>
</Card>
</div>
);