This commit is contained in:
Marcelo
2026-04-24 02:01:40 +00:00
parent 2707fd974a
commit e705f5e965
19 changed files with 2255 additions and 805 deletions

View File

@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { createHash } from "crypto";
import { prisma } from "@/lib/prisma";
import { requireSession } from "@/lib/auth/requireSession";
import { logLine } from "@/lib/logger";
@@ -46,6 +47,10 @@ function safeNum(v: unknown) {
return typeof v === "number" && Number.isFinite(v) ? v : null;
}
function toMs(value?: Date | null) {
return value ? value.getTime() : 0;
}
export async function GET(req: NextRequest) {
const perfEnabled = PERF_LOGS_ENABLED;
const totalStart = nowMs();
@@ -73,6 +78,52 @@ export async function GET(req: NextRequest) {
if (perfEnabled) timings.preQuery = elapsedMs(preQueryStart);
const versionStart = nowMs();
const [kpiMax, cycleMax, eventMax] = await Promise.all([
prisma.machineKpiSnapshot.aggregate({
where: { ...baseWhere, ts: { gte: start, lte: end } },
_max: { tsServer: true },
}),
prisma.machineCycle.aggregate({
where: { ...baseWhere, ts: { gte: start, lte: end } },
_max: { tsServer: true },
}),
prisma.machineEvent.aggregate({
where: { ...baseWhere, ts: { gte: start, lte: end } },
_max: { tsServer: true },
}),
]);
if (perfEnabled) timings.version = elapsedMs(versionStart);
const lastModifiedMs = Math.max(
toMs(kpiMax._max.tsServer),
toMs(cycleMax._max.tsServer),
toMs(eventMax._max.tsServer)
);
const versionParts = [
session.orgId,
range,
machineId ?? "",
workOrderId ?? "",
sku ?? "",
toMs(kpiMax._max.tsServer),
toMs(cycleMax._max.tsServer),
toMs(eventMax._max.tsServer),
];
const etag = `W/"${createHash("sha1").update(versionParts.join("|")).digest("hex")}"`;
const responseHeaders = new Headers({
"Cache-Control": "private, no-cache, max-age=0, must-revalidate",
ETag: etag,
"Last-Modified": new Date(lastModifiedMs || 0).toUTCString(),
Vary: "Cookie",
});
const ifNoneMatch = req.headers.get("if-none-match");
if (ifNoneMatch && ifNoneMatch === etag) {
return new NextResponse(null, { status: 304, headers: responseHeaders });
}
const kpiStart = nowMs();
const kpiRows = await prisma.machineKpiSnapshot.findMany({
where: { ...baseWhere, ts: { gte: start, lte: end } },
@@ -405,7 +456,6 @@ export async function GET(req: NextRequest) {
},
};
const responseHeaders = new Headers();
if (perfEnabled) {
timings.postQuery = elapsedMs(postQueryStart);
timings.total = elapsedMs(totalStart);