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: non-overlapping total for utilization

Brad Barbin9dffbeac3669
diff --git a/apps/erp/app/routes/api+/production.kpi.$key.ts b/apps/erp/app/routes/api+/production.kpi.$key.ts
index 4b8b3c5537..b01d0d37a4 100644
--- a/apps/erp/app/routes/api+/production.kpi.$key.ts
+++ b/apps/erp/app/routes/api+/production.kpi.$key.ts
@@ -1,13 +1,18 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import {
now,
- parseAbsolute,
parseDateTime,
toCalendarDateTime,
} from "@internationalized/date";
import { json, type LoaderFunctionArgs } from "@vercel/remix";
import { KPIs } from "~/modules/production/production.models";
+type ProductionEvent = {
+ startTime: string;
+ endTime: string;
+ workCenterId: string;
+};
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "production",
@@ -18,21 +23,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const start = String(searchParams.get("start"));
const end = String(searchParams.get("end"));
- console.log({ start, end });
-
const startDate = toCalendarDateTime(parseDateTime(start));
const endDate = toCalendarDateTime(parseDateTime(end));
const currentDate = toCalendarDateTime(now("UTC"));
const daysBetween = endDate.compare(startDate);
- console.log({
- startDate: startDate.toString(),
- endDate: endDate.toString(),
- currentDate: currentDate.toString(),
- daysBetween,
- });
-
// Calculate previous period dates
const previousEndDate = startDate;
const previousStartDate = startDate.add({ days: -daysBetween });
@@ -76,40 +72,95 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.eq("companyId", companyId)
.gt("startTime", start)
.or(`endTime.lte.${end},endTime.is.null`)
- .order("startTime", { ascending: false }),
+ .order("startTime", { ascending: false })
+ .order("endTime", { ascending: false }),
client
.from("productionEvent")
.select("startTime, endTime, workCenterId")
.eq("companyId", companyId)
.gt("startTime", previousStartDate.toString())
.or(`endTime.lte.${previousEndDate.toString()},endTime.is.null`)
- .order("startTime", { ascending: false }),
+ .order("startTime", { ascending: false })
+ .order("endTime", { ascending: false }),
]);
- const [data, previousPeriodData] = [
+
+ const [groupedEvents, previousGroupedEvents] = [
productionEvents.data ?? [],
previousProductionEvents.data ?? [],
- ].map((events) => {
- return (
- workCenters.data?.map((workCenter) => {
- const workCenterEvents = events.filter(
- (event) => event.workCenterId === workCenter.id
- );
+ ].map((events) =>
+ events.reduce<Record<string, ProductionEvent[]>>((acc, event) => {
+ if (!event.workCenterId) return acc;
+
+ if (!acc[event.workCenterId]) {
+ acc[event.workCenterId] = [];
+ }
+
+ acc[event.workCenterId].push({
+ ...event,
+ workCenterId: event.workCenterId!,
+ endTime:
+ event.endTime === null ? currentDate.toString() : event.endTime,
+ });
+ return acc;
+ }, {})
+ );
- const totalDuration = workCenterEvents.reduce((total, event) => {
- const startTime = parseAbsolute(event.startTime, "UTC");
- const endTime = event.endTime
- ? parseAbsolute(event.endTime, "UTC")
- : currentDate;
- return total + endTime.compare(startTime);
- }, 0);
+ const [data, previousPeriodData] = [
+ groupedEvents,
+ previousGroupedEvents,
+ ].map((events) =>
+ Object.entries(events)
+ .map(([workCenterId, events]) => {
+ const workCenter = workCenters.data?.find(
+ (wc) => wc.id === workCenterId
+ );
+ if (!workCenter) return { key: workCenterId, value: 0 };
+
+ // Sort events by start time, then end time if start times are equal
+ const sortedEvents = [...events].sort((a, b) => {
+ const aStart = new Date(a.startTime).getTime();
+ const bStart = new Date(b.startTime).getTime();
+ if (aStart !== bStart) return aStart - bStart;
+ return (
+ new Date(a.endTime).getTime() - new Date(b.endTime).getTime()
+ );
+ });
+
+ let totalTime = 0;
+ let lastEndTime: number | null = null;
+
+ // Calculate non-overlapping time
+ for (const event of sortedEvents) {
+ const startTime = new Date(event.startTime).getTime();
+ const endTime = new Date(event.endTime).getTime();
+
+ if (lastEndTime === null) {
+ totalTime += endTime - startTime;
+ } else {
+ // If this event starts after the last end time, add the full duration
+ if (startTime > lastEndTime) {
+ totalTime += endTime - startTime;
+ }
+ // If this event overlaps but ends later, add the non-overlapping portion
+ else if (endTime > lastEndTime) {
+ totalTime += endTime - lastEndTime;
+ }
+ // If this event is completely contained within the last event, skip it
+ }
+
+ // Update lastEndTime if this event ends later
+ if (lastEndTime === null || endTime > lastEndTime) {
+ lastEndTime = endTime;
+ }
+ }
return {
key: workCenter.name,
- value: totalDuration,
+ value: totalTime,
};
- }) ?? []
- ).sort((a, b) => b.value - a.value);
- });
+ })
+ .sort((a, b) => b.value - a.value)
+ );
return json({
data,
diff --git a/apps/erp/app/routes/x+/production+/_index.tsx b/apps/erp/app/routes/x+/production+/_index.tsx
index 94bc152c3c..5e4215722d 100644
--- a/apps/erp/app/routes/x+/production+/_index.tsx
+++ b/apps/erp/app/routes/x+/production+/_index.tsx
@@ -24,6 +24,7 @@ import {
ChartTooltipContent,
type ChartConfig,
} from "@carbon/react/Chart";
+import { formatDurationMilliseconds } from "@carbon/utils";
import { now, toCalendarDateTime } from "@internationalized/date";
import { useNumberFormatter } from "@react-aria/i18n";
import type { DateRange } from "@react-types/datepicker";
@@ -39,7 +40,7 @@ import { path } from "~/utils/path";
const chartConfig = {
actual: {
- color: "hsl(var(--chart-1))", // Primary color
+ color: "hsl(var(--primary))", // Primary color
},
estimate: {
color: "hsl(var(--chart-2))", // Secondary color
@@ -70,7 +71,7 @@ export default function ProductionDashboard() {
const totalTimeInInterval = useMemo(() => {
if (!dateRange) return 0;
- return dateRange.end.compare(dateRange.start);
+ return dateRange.end.compare(dateRange.start) * 24 * 60 * 60 * 1000;
}, [dateRange]);
useEffect(() => {
@@ -101,8 +102,20 @@ export default function ProductionDashboard() {
setInterval(value);
};
- const average = 0;
- const percentageChange = 0;
+ const total =
+ kpiFetcher.data?.data?.reduce((acc, item) => {
+ return acc + item.value;
+ }, 0) ?? 0;
+ const previousTotal =
+ kpiFetcher.data?.previousPeriodData?.reduce((acc, item) => {
+ return acc + item.value;
+ }, 0) ?? 0;
+ const percentageChange =
+ previousTotal === 0
+ ? total > 0
+ ? 100
+ : 0
+ : ((total - previousTotal) / previousTotal) * 100;
const csvData = useMemo(() => {
if (!kpiFetcher.data?.data) return [];
@@ -206,7 +219,7 @@ export default function ProductionDashboard() {
<Skeleton className="h-5 w-1/4" />
) : (
<>
- <p>Average: {numberFormatter.format(average * 100)}%</p>
+ <p>{formatDurationMilliseconds(total)}</p>
<Badge
variant="secondary"
className="normal-case font-medium px-2 rounded-full"
@@ -268,8 +281,27 @@ export default function ProductionDashboard() {
/>
<XAxis type="number" dataKey="value" hide />
<ChartTooltip
- cursor={false}
- content={<ChartTooltipContent hideLabel />}
+ content={
+ <ChartTooltipContent
+ formatter={(value) => {
+ const percentage =
+ totalTimeInInterval === 0
+ ? "0.00"
+ : (
+ ((value as number) / totalTimeInInterval) *
+ 100
+ ).toFixed(2);
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="font-medium">{percentage}%</div>
+ <div>
+ {formatDurationMilliseconds(value as number)}
+ </div>
+ </div>
+ );
+ }}
+ />
+ }
/>
<Bar dataKey="value" fill="var(--color-actual)" radius={2} />
</BarChart>