This commit is contained in:
Marcelo Dares
2025-12-20 00:35:43 +00:00
parent 398fb01c21
commit 34ce0cd505
2 changed files with 192 additions and 15 deletions

View File

@@ -246,10 +246,36 @@ const events = normalized
.slice(0, 30);
// ---- cycles window ----
const url = new URL(_req.url);
const windowSec = Number(url.searchParams.get("windowSec") ?? "10800"); // default 3h
const latestKpi = machine.kpiSnapshots[0] ?? null;
// If KPI cycleTime missing, fallback to DB cycles (we fetch 1 first)
const latestCycleForIdeal = await prisma.machineCycle.findFirst({
where: { orgId: session.orgId, machineId },
orderBy: { ts: "desc" },
select: { theoreticalCycleTime: true },
});
const effectiveCycleTime =
latestKpi?.cycleTime ??
latestCycleForIdeal?.theoreticalCycleTime ??
null;
// Estimate how many cycles we need to cover the window.
// Add buffer so the chart doesnt look “tight”.
const estCycleSec = Math.max(1, Number(effectiveCycleTime ?? 14));
const needed = Math.ceil(windowSec / estCycleSec) + 50;
// Safety cap to avoid crazy payloads
const takeCycles = Math.min(5000, Math.max(200, needed));
const rawCycles = await prisma.machineCycle.findMany({
where: { orgId: session.orgId, machineId },
orderBy: { ts: "desc" },
take: 200,
take: takeCycles,
select: {
ts: true,
cycleCount: true,
@@ -265,23 +291,14 @@ const cycles = rawCycles
.slice()
.reverse()
.map((c) => ({
ts: c.ts, // keep Date for “time ago” UI
t: c.ts.getTime(), // numeric x-axis for charts
ts: c.ts,
t: c.ts.getTime(),
cycleCount: c.cycleCount ?? null,
actual: c.actualCycleTime, // rename to what chart expects
actual: c.actualCycleTime,
ideal: c.theoreticalCycleTime ?? null,
workOrderId: c.workOrderId ?? null,
sku: c.sku ?? null,
}
));
const latestKpi = machine.kpiSnapshots[0] ?? null;
// rawCycles is ordered DESC, so [0] is the most recent cycle row
const latestCycleIdeal = rawCycles[0]?.theoreticalCycleTime ?? null;
// REAL effective value (not mock): prefer KPI if present, else fallback to cycles table
const effectiveCycleTime = latestKpi?.cycleTime ?? latestCycleIdeal ?? null;
}));