Files
errors.bitreport.pt/admin-ui/lib/incidents-data.ts
T
1sonhador c899cef6e1 fix(admin-ui): SSR sees ERROR_REPORTING_ADMIN_API_BASE at runtime
Next build inlines bare process.env.* as undefined without .env at build time.
Use Reflect.get for admin API base and demo flag; add .env.production default for LXC.
2026-03-29 21:20:19 +01:00

211 lines
6.0 KiB
TypeScript

import { cookies } from "next/headers";
import { getDemoIncidentDetail, getDemoIncidentSummaries } from "./demo-incidents";
import type { DetailResult, IncidentState, IncidentSummary, ListResult, Severity } from "./types";
/** Read env at runtime — avoid `process.env.FOO` here or `next build` may inline undefined. */
function _envStr(key: string): string | undefined {
const v = Reflect.get(process.env, key);
return typeof v === "string" ? v : undefined;
}
function _isDemoEnabled(): boolean {
if (process.env.NODE_ENV === "production") {
return false;
}
return _envStr("ERROR_REPORTING_UI_DEMO") === "1";
}
/** Forward session cookie to internal admin API (SSR fetch). */
async function _sessionCookieHeader(): Promise<string | undefined> {
try {
const _jar = await cookies();
const _access = _jar.get("__Host-access")?.value;
if (!_access) {
return undefined;
}
return `__Host-access=${_access}`;
} catch {
return undefined;
}
}
function _apiBase(): string | null {
const _raw = _envStr("ERROR_REPORTING_ADMIN_API_BASE")?.trim();
if (!_raw) {
return null;
}
return _raw.replace(/\/$/, "");
}
async function _fetchJson<T>(_path: string): Promise<T> {
const _base = _apiBase();
if (!_base) {
throw new Error("API base not configured");
}
const _url = `${_base}${_path.startsWith("/") ? _path : `/${_path}`}`;
const _cookie = await _sessionCookieHeader();
const _res = await fetch(_url, {
next: { revalidate: 0 },
headers: {
Accept: "application/json",
...(_cookie ? { Cookie: _cookie } : {}),
},
});
if (!_res.ok) {
throw new Error(`HTTP ${_res.status}`);
}
return (await _res.json()) as T;
}
function _applyFilters(
rows: IncidentSummary[],
_params: { state?: IncidentState | ""; severity?: Severity | ""; q?: string; project?: string },
): IncidentSummary[] {
let _out = rows;
if (_params.state) {
_out = _out.filter((r) => r.currentState === _params.state);
}
if (_params.severity) {
_out = _out.filter((r) => r.severity === _params.severity);
}
if (_params.project?.trim()) {
const _slug = _params.project.trim().toLowerCase();
_out = _out.filter((r) => r.projectSlug.toLowerCase() === _slug);
}
if (_params.q?.trim()) {
const _q = _params.q.trim().toLowerCase();
_out = _out.filter(
(r) =>
r.title.toLowerCase().includes(_q) ||
r.fingerprint.toLowerCase().includes(_q) ||
r.projectSlug.toLowerCase().includes(_q),
);
}
return _out;
}
export async function fetchIncidentList(_params: {
state?: IncidentState | "";
severity?: Severity | "";
q?: string;
project?: string;
}): Promise<ListResult> {
const _base = _apiBase();
if (!_base) {
if (_isDemoEnabled()) {
const _rows = _applyFilters(getDemoIncidentSummaries(), {
state: _params.state,
severity: _params.severity,
q: _params.q,
project: _params.project,
});
return { ok: true, incidents: _rows, source: "demo" };
}
return {
ok: false,
error: "not_configured",
message:
"ERROR_REPORTING_ADMIN_API_BASE não está definido. Para pré-visualizar o layout, defina ERROR_REPORTING_UI_DEMO=1 (apenas desenvolvimento).",
};
}
try {
const _sp = new URLSearchParams();
if (_params.state) {
_sp.set("state", _params.state);
}
if (_params.severity) {
_sp.set("severity", _params.severity);
}
if (_params.project?.trim()) {
_sp.set("project", _params.project.trim());
}
if (_params.q?.trim()) {
_sp.set("q", _params.q.trim());
}
const _qs = _sp.toString();
const _path = `/v1/incidents${_qs ? `?${_qs}` : ""}`;
const _payload = await _fetchJson<{ incidents: IncidentSummary[] }>(_path);
return { ok: true, incidents: _payload.incidents ?? [], source: "api" };
} catch (_err) {
const _msg = _err instanceof Error ? _err.message : "fetch failed";
return {
ok: false,
error: "unreachable",
message: `Não foi possível contactar a API admin (${_msg}).`,
};
}
}
export async function fetchIncidentDetail(id: string): Promise<DetailResult> {
const _base = _apiBase();
if (!_base) {
if (_isDemoEnabled()) {
const _row = getDemoIncidentDetail(id);
if (!_row) {
return {
ok: false,
error: "not_found",
message: "Incidente não encontrado.",
};
}
return { ok: true, incident: _row, source: "demo" };
}
return {
ok: false,
error: "not_configured",
message:
"ERROR_REPORTING_ADMIN_API_BASE não está definido. Para pré-visualizar o layout, defina ERROR_REPORTING_UI_DEMO=1 (apenas desenvolvimento).",
};
}
try {
const _base = _apiBase();
if (!_base) {
throw new Error("unreachable");
}
const _url = `${_base}/v1/incidents/${encodeURIComponent(id)}`;
const _cookie = await _sessionCookieHeader();
const _res = await fetch(_url, {
next: { revalidate: 0 },
headers: {
Accept: "application/json",
...(_cookie ? { Cookie: _cookie } : {}),
},
});
if (_res.status === 404) {
return {
ok: false,
error: "not_found",
message: "Incidente não encontrado.",
};
}
if (!_res.ok) {
throw new Error(`HTTP ${_res.status}`);
}
const _payload = (await _res.json()) as { incident: import("./types").IncidentDetail };
return { ok: true, incident: _payload.incident, source: "api" };
} catch (_err) {
const _msg = _err instanceof Error ? _err.message : "fetch failed";
return {
ok: false,
error: "unreachable",
message: `Não foi possível contactar a API admin (${_msg}).`,
};
}
}
export function computeKpis(incidents: IncidentSummary[]): Record<IncidentState | "total", number> {
const _acc: Record<IncidentState | "total", number> = {
total: incidents.length,
open: 0,
investigating: 0,
resolved: 0,
ignored: 0,
};
for (const _i of incidents) {
_acc[_i.currentState] += 1;
}
return _acc;
}