Add initial work from Codex

This commit is contained in:
2026-03-20 15:13:33 +01:00
parent 19771ddd37
commit adb5c1a439
48 changed files with 7054 additions and 16 deletions

13
frontend/.env.example Normal file
View File

@@ -0,0 +1,13 @@
VITE_API_BASE_URL=http://localhost:8000
VITE_OTEL_COLLECTOR_ENDPOINT=http://localhost:4318
# K8s + Alloy example:
# VITE_OTEL_COLLECTOR_ENDPOINT=http://alloy.monitoring.svc.cluster.local:4318
VITE_OTEL_SERVICE_NAME=otel-bi-frontend
VITE_OTEL_SERVICE_NAMESPACE=final-thesis
VITE_OIDC_ENABLED=true
VITE_OIDC_AUTHORITY=https://<your-idp-domain>/realms/<your-realm>
VITE_OIDC_CLIENT_ID=otel-bi-frontend
VITE_OIDC_REDIRECT_URI=http://localhost:5173
VITE_OIDC_POST_LOGOUT_REDIRECT_URI=http://localhost:5173
VITE_OIDC_SCOPE=openid profile email

12
frontend/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OTel BI Command Center</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

2749
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
frontend/package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "otel-bi-frontend",
"version": "0.1.0",
"private": true,
"license": "AGPL-3.0-or-later",
"author": "Domagoj Andrić",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-zone-peer-dep": "^2.2.0",
"@opentelemetry/core": "^2.2.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.213.0",
"@opentelemetry/instrumentation-document-load": "^0.58.0",
"@opentelemetry/instrumentation": "^0.213.0",
"@opentelemetry/instrumentation-fetch": "^0.213.0",
"@opentelemetry/instrumentation-user-interaction": "^0.57.0",
"@opentelemetry/instrumentation-xml-http-request": "^0.213.0",
"@opentelemetry/resources": "^2.2.0",
"@opentelemetry/sdk-trace-base": "^2.2.0",
"@opentelemetry/sdk-trace-web": "^2.2.0",
"@tanstack/react-query": "^5.90.2",
"oidc-client-ts": "^3.1.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"recharts": "^3.2.1",
"zone.js": "^0.15.1"
},
"devDependencies": {
"@types/react": "^19.1.10",
"@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^5.0.0",
"typescript": "~5.9.2",
"vite": "^7.1.4"
}
}

363
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,363 @@
import { trace, SpanStatusCode } from "@opentelemetry/api";
import { useQuery } from "@tanstack/react-query";
import { startTransition, useDeferredValue } from "react";
import {
Area,
AreaChart,
CartesianGrid,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { getDashboard } from "./api/client";
import { useAuth } from "./auth/AuthContext";
const money = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
});
const tracer = trace.getTracer("bi-frontend-ui");
function formatCompactDate(value: string): string {
return new Date(value).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
});
}
function formatTooltipMoney(
value: string | number | readonly (string | number)[] | undefined,
): string {
const raw = Array.isArray(value) ? Number(value[0]) : Number(value);
return money.format(Number.isFinite(raw) ? raw : 0);
}
function formatTooltipNumber(
value: string | number | readonly (string | number)[] | undefined,
): string {
const raw = Array.isArray(value) ? Number(value[0]) : Number(value);
return Number.isFinite(raw) ? raw.toFixed(2) : "0.00";
}
export default function App() {
const auth = useAuth();
const dashboardQuery = useQuery({
queryKey: ["dashboard"],
queryFn: getDashboard,
staleTime: 30_000,
refetchInterval: 120_000,
enabled: auth.authenticated || !auth.enabled,
});
const deferredRankings = useDeferredValue(
dashboardQuery.data?.rankings ?? [],
);
const chartHistory =
dashboardQuery.data?.history.slice(-120).map((point) => ({
date: point.date,
actual: point.revenue,
forecast: null as number | null,
lower: null as number | null,
upper: null as number | null,
})) ?? [];
const chartForecast =
dashboardQuery.data?.forecasts.slice(0, 45).map((point) => ({
date: point.date,
actual: null as number | null,
forecast: point.predicted_revenue,
lower: point.lower_bound,
upper: point.upper_bound,
})) ?? [];
const trendData = [...chartHistory, ...chartForecast];
const refreshData = () => {
tracer.startActiveSpan("frontend.refresh_click", async (span) => {
try {
startTransition(() => {
void dashboardQuery.refetch();
});
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
span.recordException(error as Error);
span.setStatus({
code: SpanStatusCode.ERROR,
message: "Failed to refresh dashboard data.",
});
} finally {
span.end();
}
});
};
if (auth.loading) {
return <div className="loading-shell">Initializing OIDC session...</div>;
}
if (auth.error) {
return (
<div className="loading-shell">
Authentication setup error.
<br />
{auth.error}
</div>
);
}
if (auth.enabled && !auth.authenticated) {
return (
<div className="loading-shell">
Authentication required.
<br />
<button
className="refresh-button"
onClick={() => void auth.login()}
type="button"
>
Sign In with OIDC
</button>
</div>
);
}
if (dashboardQuery.isLoading) {
return (
<div className="loading-shell">
Loading telemetry-enabled BI dashboard...
</div>
);
}
if (dashboardQuery.error || !dashboardQuery.data) {
return (
<div className="loading-shell">
Dashboard could not load.
<br />
{(dashboardQuery.error as Error | undefined)?.message ??
"No response from backend."}
</div>
);
}
const { kpis, recommendations, telemetry } = dashboardQuery.data;
const topScore = deferredRankings[0]?.score ?? 0;
return (
<main className="app-shell">
<div className="radial-glow" />
<header className="dashboard-header">
<div>
<p className="eyebrow">Business Intelligence Command Center</p>
<h1>Warehouse Forecasting and Ranking Dashboard</h1>
<p className="subtitle">
Data sources: <strong>WorldWideImporters</strong> +{" "}
<strong>AdventureWorks2022DWH</strong> (read-only) with
OpenTelemetry traces from browser to SQL.
</p>
<p className="trace-id">
Last backend trace:{" "}
<code>{telemetry.backendTraceId ?? "missing-trace-id-header"}</code>
</p>
</div>
<div className="auth-actions">
<p className="subtitle">
User: <strong>{auth.subject ?? "unknown"}</strong>
</p>
<div className="header-actions">
<button
className="refresh-button"
onClick={refreshData}
type="button"
>
Refresh
</button>
{auth.enabled ? (
<button
className="logout-button"
onClick={() => void auth.logout()}
type="button"
>
Sign Out
</button>
) : null}
</div>
</div>
</header>
<section className="kpi-grid">
<article className="kpi-card">
<p>Total Revenue</p>
<h2>{money.format(kpis.total_revenue)}</h2>
</article>
<article className="kpi-card">
<p>Gross Margin</p>
<h2>{kpis.gross_margin_pct.toFixed(2)}%</h2>
</article>
<article className="kpi-card">
<p>Avg Order Value</p>
<h2>{money.format(kpis.avg_order_value)}</h2>
</article>
<article className="kpi-card">
<p>Total Quantity</p>
<h2>
{kpis.total_quantity.toLocaleString("en-US", {
maximumFractionDigits: 0,
})}
</h2>
</article>
</section>
<section className="panel-grid">
<article className="panel wide">
<div className="panel-title-row">
<h3>Revenue Trend + Forecast</h3>
<span>{trendData.length} points</span>
</div>
<div className="chart-wrap">
<ResponsiveContainer width="100%" height={320}>
<LineChart data={trendData}>
<CartesianGrid
strokeDasharray="4 4"
stroke="rgba(255,255,255,0.08)"
/>
<XAxis
dataKey="date"
tickFormatter={formatCompactDate}
stroke="rgba(255,255,255,0.65)"
/>
<YAxis
tickFormatter={(value) => money.format(value)}
stroke="rgba(255,255,255,0.65)"
/>
<Tooltip
labelFormatter={(label) =>
new Date(label).toLocaleDateString("en-US")
}
formatter={formatTooltipMoney}
/>
<Area
type="monotone"
dataKey="upper"
stroke="none"
fill="rgba(90, 201, 255, 0.1)"
/>
<Area
type="monotone"
dataKey="lower"
stroke="none"
fill="rgba(15, 20, 31, 0.9)"
/>
<Line
type="monotone"
dataKey="actual"
stroke="#f9de70"
strokeWidth={2.5}
dot={false}
/>
<Line
type="monotone"
dataKey="forecast"
stroke="#57d4ff"
strokeWidth={2.5}
strokeDasharray="8 5"
dot={false}
/>
</LineChart>
</ResponsiveContainer>
</div>
</article>
<article className="panel">
<div className="panel-title-row">
<h3>Top Product Score</h3>
<span>Weighted ranking index</span>
</div>
<div className="score-wrap">
<ResponsiveContainer width="100%" height={240}>
<AreaChart
data={[
{ label: "baseline", value: 0 },
{ label: "current", value: topScore },
]}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="rgba(255,255,255,0.08)"
/>
<XAxis dataKey="label" stroke="rgba(255,255,255,0.65)" />
<YAxis stroke="rgba(255,255,255,0.65)" />
<Tooltip formatter={formatTooltipNumber} />
<Area
type="monotone"
dataKey="value"
stroke="#8ef2c7"
fill="rgba(142, 242, 199, 0.28)"
/>
</AreaChart>
</ResponsiveContainer>
<p className="score-caption">
Current leader score <strong>{topScore.toFixed(2)}</strong> / 100
</p>
</div>
</article>
<article className="panel wide">
<div className="panel-title-row">
<h3>Product Rankings</h3>
<span>Top {deferredRankings.length}</span>
</div>
<div className="table-wrap">
<table>
<thead>
<tr>
<th>Rank</th>
<th>Product</th>
<th>Category</th>
<th>Revenue</th>
<th>Margin</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{deferredRankings.map((item) => (
<tr key={`${item.rank}-${item.product_id}`}>
<td>{item.rank}</td>
<td>{item.product_name}</td>
<td>{item.category}</td>
<td>{money.format(item.revenue)}</td>
<td>{item.margin_pct.toFixed(2)}%</td>
<td>{item.score.toFixed(2)}</td>
</tr>
))}
</tbody>
</table>
</div>
</article>
<article className="panel">
<div className="panel-title-row">
<h3>Recommendations</h3>
<span>Action queue</span>
</div>
<ul className="recommendations-list">
{recommendations.map((item, index) => (
<li key={`${item.title}-${index}`}>
<span className={`priority ${item.priority}`}>
{item.priority}
</span>
<h4>{item.title}</h4>
<p>{item.summary}</p>
</li>
))}
</ul>
</article>
</section>
</main>
);
}

View File

@@ -0,0 +1,53 @@
import { SpanStatusCode, trace } from "@opentelemetry/api";
import { currentAccessToken } from "../auth/oidc";
import type { DashboardPayload, DashboardResponse } from "./types";
const API_BASE_URL =
import.meta.env.VITE_API_BASE_URL ?? "http://localhost:8000";
const tracer = trace.getTracer("bi-frontend-api");
async function parseJson<T>(response: Response): Promise<T> {
if (!response.ok) {
const body = await response.text();
throw new Error(`HTTP ${response.status}: ${body}`);
}
return (await response.json()) as T;
}
export async function getDashboard(): Promise<DashboardPayload> {
return tracer.startActiveSpan("frontend.api.dashboard", async (span) => {
try {
const token = currentAccessToken();
const response = await fetch(`${API_BASE_URL}/api/dashboard`, {
method: "GET",
headers: {
Accept: "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
});
const data = await parseJson<DashboardResponse>(response);
const backendTraceId = response.headers.get("x-trace-id");
const backendSpanId = response.headers.get("x-span-id");
span.setAttribute("dashboard.kpis", Object.keys(data.kpis).length);
span.setAttribute("backend.trace_id_present", backendTraceId !== null);
span.setStatus({ code: SpanStatusCode.OK });
return {
...data,
telemetry: {
backendTraceId,
backendSpanId,
},
};
} catch (error) {
span.recordException(error as Error);
span.setStatus({
code: SpanStatusCode.ERROR,
message: "dashboard request failed",
});
throw error;
} finally {
span.end();
}
});
}

52
frontend/src/api/types.ts Normal file
View File

@@ -0,0 +1,52 @@
export type KPI = {
total_revenue: number;
gross_margin_pct: number;
total_quantity: number;
avg_order_value: number;
records_in_window: number;
};
export type HistoryPoint = {
date: string;
revenue: number;
cost: number;
quantity: number;
};
export type ForecastPoint = {
date: string;
predicted_revenue: number;
lower_bound: number;
upper_bound: number;
};
export type RankingItem = {
rank: number;
product_id: string;
product_name: string;
category: string;
revenue: number;
margin_pct: number;
score: number;
};
export type Recommendation = {
title: string;
priority: string;
summary: string;
};
export type DashboardResponse = {
kpis: KPI;
history: HistoryPoint[];
forecasts: ForecastPoint[];
rankings: RankingItem[];
recommendations: Recommendation[];
};
export type DashboardPayload = DashboardResponse & {
telemetry: {
backendTraceId: string | null;
backendSpanId: string | null;
};
};

View File

@@ -0,0 +1,90 @@
import {
createContext,
useContext,
useEffect,
useState,
type ReactNode,
} from "react";
import {
currentUser,
initializeOIDC,
isOIDCEnabled,
login,
logout,
oidcConfigError,
} from "./oidc";
type AuthState = {
loading: boolean;
authenticated: boolean;
enabled: boolean;
subject: string | null;
error: string | null;
login: () => Promise<void>;
logout: () => Promise<void>;
};
const AuthContext = createContext<AuthState>({
loading: true,
authenticated: false,
enabled: true,
subject: null,
error: null,
login,
logout,
});
export function AuthProvider({ children }: { children: ReactNode }) {
const [loading, setLoading] = useState(true);
const [authenticated, setAuthenticated] = useState(false);
const [subject, setSubject] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const enabled = isOIDCEnabled();
useEffect(() => {
const bootstrap = async () => {
try {
const configIssue = oidcConfigError();
if (configIssue) {
setError(configIssue);
setAuthenticated(false);
return;
}
await initializeOIDC();
const user = currentUser();
const isAuthed = !!user && !user.expired;
setAuthenticated(isAuthed);
setSubject((user?.profile?.sub as string | undefined) ?? null);
} catch (err) {
setError((err as Error).message);
setAuthenticated(false);
} finally {
setLoading(false);
}
};
void bootstrap();
}, []);
return (
<AuthContext.Provider
value={{
loading,
authenticated,
enabled,
subject,
error,
login,
logout,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthState {
return useContext(AuthContext);
}

105
frontend/src/auth/oidc.ts Normal file
View File

@@ -0,0 +1,105 @@
import { UserManager, type User, WebStorageStateStore } from "oidc-client-ts";
type OIDCConfig = {
enabled: boolean;
authority: string;
clientId: string;
redirectUri: string;
postLogoutRedirectUri: string;
scope: string;
};
let cachedUser: User | null = null;
function config(): OIDCConfig {
const enabled = (import.meta.env.VITE_OIDC_ENABLED ?? "true") !== "false";
return {
enabled,
authority: import.meta.env.VITE_OIDC_AUTHORITY ?? "",
clientId: import.meta.env.VITE_OIDC_CLIENT_ID ?? "",
redirectUri:
import.meta.env.VITE_OIDC_REDIRECT_URI ?? window.location.origin,
postLogoutRedirectUri:
import.meta.env.VITE_OIDC_POST_LOGOUT_REDIRECT_URI ??
window.location.origin,
scope: import.meta.env.VITE_OIDC_SCOPE ?? "openid profile email",
};
}
export function isOIDCEnabled(): boolean {
return config().enabled;
}
export function oidcConfigError(): string | null {
const cfg = config();
if (!cfg.enabled) return null;
if (!cfg.authority) return "VITE_OIDC_AUTHORITY is not set.";
if (!cfg.clientId) return "VITE_OIDC_CLIENT_ID is not set.";
return null;
}
function manager(): UserManager {
const cfg = config();
return new UserManager({
authority: cfg.authority,
client_id: cfg.clientId,
redirect_uri: cfg.redirectUri,
post_logout_redirect_uri: cfg.postLogoutRedirectUri,
response_type: "code",
scope: cfg.scope,
userStore: new WebStorageStateStore({ store: window.sessionStorage }),
monitorSession: true,
automaticSilentRenew: false,
});
}
function hasSigninParams(): boolean {
const params = new URLSearchParams(window.location.search);
return params.has("code") && params.has("state");
}
export async function initializeOIDC(): Promise<User | null> {
if (!isOIDCEnabled()) {
cachedUser = null;
return null;
}
if (oidcConfigError()) {
cachedUser = null;
return null;
}
const userManager = manager();
if (hasSigninParams()) {
cachedUser = await userManager.signinRedirectCallback();
window.history.replaceState({}, document.title, window.location.pathname);
return cachedUser;
}
cachedUser = await userManager.getUser();
return cachedUser;
}
export function currentUser(): User | null {
return cachedUser;
}
export function currentAccessToken(): string | null {
if (cachedUser?.access_token && !cachedUser.expired)
return cachedUser.access_token;
return null;
}
export async function login(): Promise<void> {
if (!isOIDCEnabled()) return;
const userManager = manager();
await userManager.signinRedirect({
state: { returnTo: window.location.pathname + window.location.search },
});
}
export async function logout(): Promise<void> {
if (!isOIDCEnabled()) return;
const userManager = manager();
await userManager.signoutRedirect();
}

31
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,31 @@
import "zone.js";
import "./styles.css";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { AuthProvider } from "./auth/AuthContext";
import { setupTelemetry } from "./telemetry";
setupTelemetry();
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
},
},
});
createRoot(document.getElementById("root")!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<AuthProvider>
<App />
</AuthProvider>
</QueryClientProvider>
</StrictMode>,
);

325
frontend/src/styles.css Normal file
View File

@@ -0,0 +1,325 @@
:root {
font-family: "Space Grotesk", "Segoe UI", sans-serif;
line-height: 1.5;
font-weight: 400;
color: #f3f7ff;
background: #0a1019;
--bg-primary: #0a1019;
--bg-secondary: #101d2e;
--bg-panel: rgba(16, 28, 44, 0.72);
--border: rgba(186, 212, 255, 0.22);
--accent-a: #f9de70;
--accent-b: #57d4ff;
--accent-c: #8ef2c7;
--text-muted: rgba(233, 244, 255, 0.7);
--shadow: 0 20px 55px rgba(3, 8, 16, 0.45);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background:
radial-gradient(
circle at 0% 0%,
rgba(122, 82, 242, 0.2),
transparent 30%
),
radial-gradient(
circle at 100% 10%,
rgba(87, 212, 255, 0.18),
transparent 30%
),
linear-gradient(150deg, var(--bg-primary), var(--bg-secondary));
}
.app-shell {
width: min(1200px, 100% - 2rem);
margin: 1.5rem auto 3rem;
position: relative;
}
.radial-glow {
position: fixed;
width: 48vw;
height: 48vw;
max-width: 540px;
max-height: 540px;
border-radius: 50%;
background: radial-gradient(
circle,
rgba(87, 212, 255, 0.16),
transparent 65%
);
top: -12rem;
right: -10rem;
pointer-events: none;
z-index: 0;
}
.dashboard-header,
.kpi-grid,
.panel-grid {
position: relative;
z-index: 1;
}
.dashboard-header {
display: flex;
justify-content: space-between;
gap: 1rem;
align-items: flex-start;
margin-bottom: 1rem;
}
.auth-actions {
display: grid;
gap: 0.5rem;
justify-items: end;
}
.header-actions {
display: flex;
gap: 0.5rem;
}
.dashboard-header h1 {
margin: 0.2rem 0 0.5rem;
font-size: clamp(1.6rem, 2.2vw, 2.4rem);
letter-spacing: -0.04em;
}
.eyebrow {
margin: 0;
color: var(--accent-b);
text-transform: uppercase;
letter-spacing: 0.14em;
font-size: 0.74rem;
font-weight: 600;
}
.subtitle {
margin: 0;
color: var(--text-muted);
max-width: 74ch;
}
.trace-id {
margin: 0.5rem 0 0;
color: var(--text-muted);
font-size: 0.8rem;
}
.trace-id code {
color: var(--accent-c);
}
.refresh-button {
background: linear-gradient(125deg, var(--accent-b), #7be8ff);
color: #04111b;
border: 0;
font-weight: 700;
padding: 0.72rem 1rem;
border-radius: 0.8rem;
box-shadow: var(--shadow);
cursor: pointer;
}
.logout-button {
background: rgba(248, 159, 159, 0.2);
color: #ffd6d6;
border: 1px solid rgba(255, 184, 184, 0.45);
font-weight: 700;
padding: 0.72rem 1rem;
border-radius: 0.8rem;
box-shadow: var(--shadow);
cursor: pointer;
}
.kpi-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 0.9rem;
margin-bottom: 0.9rem;
}
.kpi-card {
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 1rem;
padding: 0.95rem 1rem;
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
}
.kpi-card p {
margin: 0;
color: var(--text-muted);
font-size: 0.82rem;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.kpi-card h2 {
margin: 0.5rem 0 0;
font-size: clamp(1.1rem, 1.7vw, 1.6rem);
}
.panel-grid {
display: grid;
grid-template-columns: 2fr 1fr;
gap: 0.9rem;
}
.panel {
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 1rem;
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
padding: 0.9rem;
}
.panel.wide {
grid-column: span 2;
}
.panel-title-row {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 1rem;
}
.panel-title-row h3 {
margin: 0;
}
.panel-title-row span {
color: var(--text-muted);
font-size: 0.85rem;
}
.chart-wrap,
.score-wrap {
margin-top: 0.8rem;
}
.score-caption {
margin-top: 0.4rem;
color: var(--text-muted);
}
.table-wrap {
margin-top: 0.7rem;
max-height: 350px;
overflow: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
text-align: left;
padding: 0.6rem 0.45rem;
border-bottom: 1px solid rgba(216, 232, 255, 0.09);
white-space: nowrap;
}
th {
color: var(--text-muted);
font-size: 0.77rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.recommendations-list {
margin: 0.8rem 0 0;
padding: 0;
list-style: none;
display: grid;
gap: 0.75rem;
}
.recommendations-list li {
border: 1px solid rgba(190, 210, 245, 0.14);
background: rgba(12, 20, 31, 0.7);
border-radius: 0.8rem;
padding: 0.75rem;
}
.recommendations-list h4 {
margin: 0.5rem 0 0.3rem;
}
.recommendations-list p {
margin: 0;
color: var(--text-muted);
}
.priority {
display: inline-flex;
align-items: center;
border-radius: 999px;
padding: 0.2rem 0.55rem;
font-size: 0.72rem;
text-transform: uppercase;
font-weight: 700;
letter-spacing: 0.08em;
}
.priority.high {
background: rgba(255, 112, 112, 0.17);
color: #ffb6b6;
}
.priority.medium {
background: rgba(255, 205, 112, 0.18);
color: #ffe3ae;
}
.priority.low {
background: rgba(142, 242, 199, 0.18);
color: #b9ffd8;
}
.loading-shell {
color: #d6e7ff;
min-height: 100vh;
display: grid;
place-items: center;
text-align: center;
padding: 1rem;
font-size: 1.04rem;
}
@media (max-width: 980px) {
.kpi-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.panel-grid {
grid-template-columns: 1fr;
}
.panel.wide {
grid-column: auto;
}
}
@media (max-width: 640px) {
.dashboard-header {
flex-direction: column;
}
.kpi-grid {
grid-template-columns: 1fr;
}
}

77
frontend/src/telemetry.ts Normal file
View File

@@ -0,0 +1,77 @@
import { propagation } from "@opentelemetry/api";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import {
CompositePropagator,
W3CBaggagePropagator,
W3CTraceContextPropagator,
} from "@opentelemetry/core";
import { DocumentLoadInstrumentation } from "@opentelemetry/instrumentation-document-load";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
import { UserInteractionInstrumentation } from "@opentelemetry/instrumentation-user-interaction";
import { XMLHttpRequestInstrumentation } from "@opentelemetry/instrumentation-xml-http-request";
import { ZoneContextManager } from "@opentelemetry/context-zone-peer-dep";
let initialized = false;
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export function setupTelemetry(): void {
if (initialized) return;
initialized = true;
const endpoint =
import.meta.env.VITE_OTEL_COLLECTOR_ENDPOINT ?? "http://localhost:4318";
const serviceName =
import.meta.env.VITE_OTEL_SERVICE_NAME ?? "otel-bi-frontend";
const serviceNamespace =
import.meta.env.VITE_OTEL_SERVICE_NAMESPACE ?? "final-thesis";
const apiBaseUrl =
import.meta.env.VITE_API_BASE_URL ?? "http://localhost:8000";
propagation.setGlobalPropagator(
new CompositePropagator({
propagators: [
new W3CTraceContextPropagator(),
new W3CBaggagePropagator(),
],
}),
);
const provider = new WebTracerProvider({
resource: resourceFromAttributes({
"service.name": serviceName,
"service.namespace": serviceNamespace,
"deployment.environment": import.meta.env.MODE,
}),
spanProcessors: [
new BatchSpanProcessor(
new OTLPTraceExporter({
url: `${endpoint}/v1/traces`,
}),
),
],
});
provider.register({
contextManager: new ZoneContextManager(),
});
registerInstrumentations({
instrumentations: [
new DocumentLoadInstrumentation(),
new FetchInstrumentation({
propagateTraceHeaderCorsUrls: [
new RegExp(`^${escapeRegExp(apiBaseUrl)}`),
],
}),
new XMLHttpRequestInstrumentation(),
new UserInteractionInstrumentation(),
],
});
}

View File

@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"noEmit": true,
"types": ["vite/client"]
},
"include": ["src"]
}

7
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"],
"skipLibCheck": true
},
"include": ["vite.config.ts"]
}

10
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,10 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react()],
server: {
host: "0.0.0.0",
port: 5173,
},
});