Files
ERP/frontend/src/App.tsx
T
whqreza 0adadd2cf8 feat(monitoring): bot observability dashboards — Grafana + Persian RTL ERP page
Grafana (full use of the existing monitoring/ stack, per OSS policy):
- datasources.yml: BotPostgres (uid bot-postgres) over the shared network;
  grafana service joins 'shared' + carries the datasource env
- db_init.py: idempotent read-only role obs_reader (USAGE on schema public +
  SELECT on bot_traces/bot_trace_events; skipped when
  OBS_READER_PASSWORD empty; ALTER ROLE for rotation) + composite index
  ix_bot_trace_events_stage_time (stage, created_at DESC) — senior-engineer
  review applied with the column-name fix (event_type -> stage); (trace_id)
  already covered by the existing (trace_id, created_at) index
- dashboards/bot-observability.json: KPI row (real traffic, events, Jev/
  fallback errors, Jev p95, tokens, commits, archive guard), events/day,
  per-stage p50/p95, mention statuses (arbiter+fallback aggregates + legacy
  rows), DeepSeek arbiter actions, tokens/day, model-drift vs jev-1.13.0,
  user-choice A/B, STT + audio.enhance health, archive size guard
- dashboards/bot-trace-explorer.json: trace table + full event drill-down
  via the trace_id variable

ERP page (admin-only, Persian RTL, recharts@^3 for React 19):
- backend bot_metrics.py: read-only require_role('admin') endpoints
  (summary/routing/quality/jev/stt/traces + trace detail); aggregates count
  real traffic only (calibration/demo/chat_id=0 excluded)
- frontend BotMonitorPage at /bot-monitor (KPI cards, daily events,
  status donut, arbiter actions, user-choice A/B, STT/enhance tables,
  stage latency, tokens chart, traces table + detail drawer with payload
  viewer); entry link from the admin panel; MobileTabBar hidden there
- api.ts: typed botMetrics client section

Tooling/docs:
- tools/seed_observability_demo.py: deterministic demo traces (source='demo',
  every current pipeline stage incl. audio.enhance/jev.failure/arbitration/
  fallback/user choices) — excluded from real-traffic aggregates
- monitoring/README.md + bot/docs/DEPLOY-AND-MONITORING.md: setup, seed and
  rollback notes; alerts deliberately deferred (owner decision 2026-10-24)

Verified locally: obs_reader SELECT ok / INSERT denied; panels' SQL run as
obs_reader with data; datasource health OK; both dashboards survive a grafana
restart; endpoints 200 as admin and 403 without role; tsc + vite build clean;
page renders in-browser (admin session); bot startup provisions role+index.
2026-10-24 15:09:01 +03:30

241 lines
7.7 KiB
TypeScript

import { lazy, Suspense } from "react";
import { Navigate, Route, Routes, useLocation } from "react-router-dom";
import { useAuthStore } from "./store/auth";
import { ErrorBoundary } from "./components/ErrorBoundary";
import { RequirePmProjects } from "./components/RequirePmProjects";
import { MobileTabBar } from "./components/layout/MobileTabBar";
// هر صفحه با React.lazy لود می‌شود (code splitting)
const DashboardPage = lazy(() =>
import("./pages/Dashboard/DashboardPage").then((m) => ({ default: m.DashboardPage })),
);
const WizardPage = lazy(() => import("./pages/Wizard/WizardPage").then((m) => ({ default: m.WizardPage })));
const SuppliersPage = lazy(() =>
import("./pages/Suppliers/SuppliersPage").then((m) => ({ default: m.SuppliersPage })),
);
const CategoryPage = lazy(() =>
import("./pages/Suppliers/CategoryPage").then((m) => ({ default: m.CategoryPage })),
);
const SupplierDetailPage = lazy(() =>
import("./pages/Suppliers/SupplierDetailPage").then((m) => ({ default: m.SupplierDetailPage })),
);
const ProjectsPage = lazy(() =>
import("./pages/Projects/ProjectsPage").then((m) => ({ default: m.ProjectsPage })),
);
const UnitsPage = lazy(() => import("./pages/Units/UnitsPage").then((m) => ({ default: m.UnitsPage })));
const LoginPage = lazy(() => import("./pages/Auth/LoginPage").then((m) => ({ default: m.LoginPage })));
const InventoryPage = lazy(() =>
import("./pages/Inventory/InventoryPage").then((m) => ({ default: m.InventoryPage })),
);
const ArrivalsPage = lazy(() => import("./pages/Inventory/ArrivalsPage").then((m) => ({ default: m.ArrivalsPage })));
const ChangeInventoryPage = lazy(() =>
import("./pages/Inventory/ChangeInventoryPage").then((m) => ({ default: m.ChangeInventoryPage })),
);
const DailyControlPage = lazy(() =>
import("./pages/Inventory/DailyControlPage").then((m) => ({ default: m.DailyControlPage })),
);
const WarehousesPage = lazy(() =>
import("./pages/Inventory/WarehousesPage").then((m) => ({ default: m.WarehousesPage })),
);
const OrganizationPage = lazy(() =>
import("./pages/Inventory/OrganizationPage").then((m) => ({ default: m.OrganizationPage })),
);
const AdminPanelPage = lazy(() =>
import("./pages/Admin/AdminPanel").then((m) => ({ default: m.AdminPanel })),
);
const BotMonitorPage = lazy(() =>
import("./pages/BotMonitor/BotMonitorPage").then((m) => ({ default: m.BotMonitorPage })),
);
function Loading() {
return (
<div className="flex min-h-screen items-center justify-center text-sm text-muted">
در حال بارگذاری...
</div>
);
}
// همه‌ی صفحات پشت ورود هستند — به جز پیش‌نویس‌های ویزارد از ربات یا بدون نشست که به صفحه‌ی ورود می‌روند.
function RequireAuth({ children }: { children: React.ReactNode }) {
const user = useAuthStore((s) => s.user);
const location = useLocation();
// در صورت داشتن شناسه پیش‌نویس (از ربات بله)، دسترسی مستقیم به ویزارد بدون لاگین مجاز است
const searchParams = new URLSearchParams(location.search);
const hasDraft = searchParams.has("draft") || searchParams.has("draft_id");
if (location.pathname === "/wizard" && hasDraft) {
return <>{children}</>;
}
if (!user) {
const returnUrl = encodeURIComponent(location.pathname + location.search);
return <Navigate to={`/login?returnUrl=${returnUrl}`} replace />;
}
return <>{children}</>;
}
// صفحه‌ی اصلی بر اساس نقش: مدیر پروژه → پنل انبار؛ مدیر تدارکات/ادمین → دفتر
function HomeRoute() {
const user = useAuthStore((s) => s.user);
if (user?.role === "pm") return <Navigate to="/inventory" replace />;
return <DashboardPage />;
}
export default function App() {
return (
<ErrorBoundary>
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/review" element={<WizardPage isStandalone />} />
<Route path="/login" element={<LoginPage />} />
<Route
path="/"
element={
<RequireAuth>
<HomeRoute />
</RequireAuth>
}
/>
<Route
path="/wizard"
element={
<RequireAuth>
<WizardPage />
</RequireAuth>
}
/>
<Route
path="/suppliers"
element={
<RequireAuth>
<SuppliersPage />
</RequireAuth>
}
/>
{/* سلسله‌مراتب دامنه: دسته → تأمین‌کننده. کارت دسته مستقیم به
فهرست تأمین‌کننده‌های همان دسته می‌رود (بدون صفحه‌ی واسط متریال). */}
<Route
path="/suppliers/category/:category"
element={
<RequireAuth>
<CategoryPage />
</RequireAuth>
}
/>
{/* مسیرهای قدیمی (درخت معکوس topic → material → supplier) — ریدایرکت */}
<Route
path="/topics/:topic/:category"
element={<Navigate to="/suppliers/category/:category" replace />}
/>
<Route
path="/topics/:topic"
element={<Navigate to="/suppliers" replace />}
/>
<Route
path="/suppliers/:id"
element={
<RequireAuth>
<SupplierDetailPage />
</RequireAuth>
}
/>
<Route
path="/projects"
element={
<RequireAuth>
<ProjectsPage />
</RequireAuth>
}
/>
<Route
path="/units"
element={
<RequireAuth>
<UnitsPage />
</RequireAuth>
}
/>
<Route
path="/inventory"
element={
<RequireAuth>
<RequirePmProjects>
<InventoryPage />
</RequirePmProjects>
</RequireAuth>
}
/>
<Route
path="/inventory/arrivals"
element={
<RequireAuth>
<RequirePmProjects>
<ArrivalsPage />
</RequirePmProjects>
</RequireAuth>
}
/>
<Route
path="/inventory/change"
element={
<RequireAuth>
<RequirePmProjects>
<ChangeInventoryPage />
</RequirePmProjects>
</RequireAuth>
}
/>
<Route
path="/inventory/daily"
element={
<RequireAuth>
<RequirePmProjects>
<DailyControlPage />
</RequirePmProjects>
</RequireAuth>
}
/>
<Route
path="/inventory/warehouses"
element={
<RequireAuth>
<RequirePmProjects>
<WarehousesPage />
</RequirePmProjects>
</RequireAuth>
}
/>
<Route
path="/inventory/org"
element={
<RequireAuth>
<RequirePmProjects>
<OrganizationPage />
</RequirePmProjects>
</RequireAuth>
}
/>
<Route
path="/admin"
element={
<RequireAuth>
<AdminPanelPage />
</RequireAuth>
}
/>
<Route
path="/bot-monitor"
element={
<RequireAuth>
<BotMonitorPage />
</RequireAuth>
}
/>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Suspense>
<MobileTabBar />
</ErrorBoundary>
);
}