build(frontend): migrate CRA to Next.js (CSR lift-and-shift)
CI and Deploy / test (pull_request) Failing after 50s
CI and Deploy / deploy (pull_request) Has been skipped

Wave 6. Swaps react-scripts' build/dev tooling for Next.js while
keeping the app's actual routing/rendering model unchanged -- the app
is almost entirely behind auth with no proven SSR/SEO need, so a real
App Router rewrite would touch ~90 files for zero user-visible benefit.

- next.config.js: output:'export' (static HTML+JS, same "single
  index.html served by nginx with try_files fallback" deploy as CRA).
- app/layout.tsx + app/page.tsx: root shell ports public/index.html's
  <head>, mounts the whole existing App tree client-only (ssr:false)
  since it reads window/localStorage during initial render and Next's
  static prerender would otherwise execute that on the server.
- Renamed src/pages/ -> src/views/ (Next's Pages Router auto-detects
  any `pages/` dir under the app root and tried to build our React
  Router page components as its own routes).
- REACT_APP_* -> NEXT_PUBLIC_* across code, .env.development,
  Dockerfile, docker-compose.yml build args.
- Replaced the CRA SVGR import (`ReactComponent` from .svg, unsupported
  under Turbopack) with a small inline JobbjaktMark component.
- TypeScript 4.9 -> 5.9 (MUI v8's type-checked build needs syntax
  4.9's parser rejects; CRA never hit this because babel doesn't
  type-check).
- Dropped CRA-only files (index.tsx, reportWebVitals, react-app-env.d.ts,
  public/index.html); kept react-scripts as the Jest test runner only
  (next/jest migration not needed -- the existing config already works).

Verified: `next build` static export succeeds, `next dev` serves the
landing page and client-side routes (login etc.) correctly, all 57
frontend tests + 172 backend tests still green.

Known caveat: deep-linking straight to a sub-route (e.g. /login) 404s
in `next dev` since there's no server route for it -- the app only
ever mounts at "/". Production is unaffected: nginx's existing
try_files fallback still serves index.html for any path.
This commit is contained in:
cesnimda
2026-07-12 00:50:45 +02:00
parent fc62a659ef
commit acf60c2a07
39 changed files with 948 additions and 127 deletions
+183
View File
@@ -0,0 +1,183 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
Box,
Button,
Chip,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Typography,
} from "@mui/material";
import { api } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
type AuditItem = {
id: number;
type: string;
oldValue?: string | null;
newValue?: string | null;
note?: string | null;
at: string;
jobApplicationId: number;
jobTitle?: string | null;
companyName?: string | null;
ownerUserId?: string | null;
ownerEmail?: string | null;
ownerUserName?: string | null;
};
function canUndo(type: string) {
return ["StatusChanged", "FollowUpSet", "ResponseUpdated", "Deleted", "Restored"].includes(type);
}
export default function AdminAuditPage() {
const { toast } = useToast();
const { t } = useI18n();
const [items, setItems] = useState<AuditItem[]>([]);
const [loading, setLoading] = useState(false);
const [busyId, setBusyId] = useState<number | null>(null);
const load = useCallback(async () => {
setLoading(true);
try {
const r = await api.get<AuditItem[]>("/admin/audit?take=200");
setItems(r.data ?? []);
} catch {
setItems([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
const undo = async (e: AuditItem) => {
if (!canUndo(e.type)) return;
setBusyId(e.id);
try {
const res = await api.post<{ ok: boolean; message: string }>(`/admin/audit/${e.id}/undo`, {});
toast(res.data?.message || "Undone.", "success");
await load();
} catch (err: any) {
const msg = err?.response?.data?.message || err?.response?.data || err?.message || "Undo failed.";
toast(String(msg), "error");
} finally {
setBusyId(null);
}
};
const restore = async (e: AuditItem) => {
setBusyId(e.id);
try {
await api.post(`/jobapplications/${e.jobApplicationId}/restore`, {});
toast(t("adminAuditRestored"), "success");
await load();
} catch (err: any) {
const msg = err?.response?.data || err?.message || "Restore failed.";
toast(String(msg), "error");
} finally {
setBusyId(null);
}
};
const rows = useMemo(() => items, [items]);
return (
<Paper sx={{ mt: 0, p: 2 }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 1 }}>
{t("adminAuditTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{t("adminAuditSubtitle")}
</Typography>
<TableContainer sx={{ borderRadius: 2, border: "1px solid", borderColor: "divider" }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell sx={{ width: 165 }}>{t("adminAuditAt")}</TableCell>
<TableCell sx={{ width: 160 }}>{t("adminAuditType")}</TableCell>
<TableCell>{t("adminAuditJob")}</TableCell>
<TableCell sx={{ width: 220 }}>{t("adminAuditUser")}</TableCell>
<TableCell>{t("adminAuditDetails")}</TableCell>
<TableCell sx={{ width: 170 }}>{t("adminAuditActions")}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={6}>
<Typography sx={{ color: "text.secondary" }}>{t("loading")}</Typography>
</TableCell>
</TableRow>
) : rows.length === 0 ? (
<TableRow>
<TableCell colSpan={6}>
<Typography sx={{ color: "text.secondary" }}>{t("adminAuditNoEvents")}</Typography>
</TableCell>
</TableRow>
) : (
rows.map((e) => {
const jobLabel = e.jobTitle || `Job #${e.jobApplicationId}`;
const ownerLabel = e.ownerEmail || e.ownerUserName || e.ownerUserId || "-";
const details = e.oldValue || e.newValue ? `${e.oldValue ?? ""} -> ${e.newValue ?? ""}` : "";
const disabled = busyId === e.id;
const showRestore = e.type === "Deleted";
return (
<TableRow key={e.id} hover>
<TableCell>{e.at ? new Date(e.at).toLocaleString() : ""}</TableCell>
<TableCell>
<Chip label={e.type} size="small" variant="outlined" />
</TableCell>
<TableCell>
<Typography sx={{ fontWeight: 800, lineHeight: 1.25 }}>
{e.companyName ? `${e.companyName} - ` : ""}
{jobLabel}
</Typography>
<Typography variant="caption" sx={{ color: "text.secondary" }}>
jobId={e.jobApplicationId}
</Typography>
</TableCell>
<TableCell>
<Typography sx={{ fontWeight: 700 }}>{ownerLabel}</Typography>
</TableCell>
<TableCell>
<Typography sx={{ whiteSpace: "pre-wrap", color: "text.secondary" }}>
{details}
{e.note ? `${details ? "\n" : ""}${e.note}` : ""}
</Typography>
</TableCell>
<TableCell>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
{canUndo(e.type) ? (
<Button size="small" variant="outlined" disabled={disabled} onClick={() => void undo(e)}>
Undo
</Button>
) : null}
{showRestore ? (
<Button size="small" variant="contained" disabled={disabled} onClick={() => void restore(e)}>
Restore
</Button>
) : null}
</Box>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</TableContainer>
</Paper>
);
}
@@ -0,0 +1,623 @@
import React, { useEffect, useMemo, useState } from "react";
import {
Alert,
Box,
Button,
Chip,
Paper,
Stack,
Tab,
Tabs,
TextField,
Typography,
Checkbox,
FormControlLabel,
} from "@mui/material";
import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";
type AiServiceMetrics = {
healthy: boolean;
model?: string | null;
device?: string | null;
gpuAvailable?: boolean;
gpuName?: string | null;
ocrAvailable?: boolean | null;
ocrLanguages?: string | null;
ollamaConfigured?: boolean | null;
ollamaReachable?: boolean | null;
ollamaModel?: string | null;
ollamaModelAvailable?: boolean | null;
ollamaVersion?: string | null;
ollamaInstalledModels?: string[] | null;
ollamaLoadedModels?: string[] | null;
ollamaLoadedCount?: number | null;
healthLatencyMs?: number | null;
probeLatencyMs?: number | null;
lastProbeAt?: string | null;
lastProbeSuccessAt?: string | null;
lastProbeFailureAt?: string | null;
probeFailures: number;
requests: number;
cacheHits: number;
cacheMisses: number;
failures: number;
averageLatencyMs?: number | null;
ocrRequests: number;
ocrFailures: number;
averageOcrLatencyMs?: number | null;
lastOcrSuccessAt?: string | null;
lastOcrFailureAt?: string | null;
lastSuccessAt?: string | null;
lastFailureAt?: string | null;
lastError?: string | null;
};
type EditableEmailSettings = {
enabled: boolean;
host: string;
port: number;
user: string;
from: string;
fromName: string;
enableSsl: boolean;
timeoutMs: number;
usesOverrides: boolean;
hasPassword: boolean;
};
type CvBenchmarkEntry = {
FileName: string;
Slug: string;
Extension: string;
Characters: number;
OutputPath: string;
ApprovedFixturePath?: string | null;
CandidateFixturePath?: string | null;
ContactLocation?: string | null;
FirstJob?: string | null;
FirstJobLocation?: string | null;
FirstEducation?: string | null;
FirstEducationLocation?: string | null;
QualificationLevels: string[];
SuspiciousLocations: string[];
CoverageScore: number;
ConfidenceScore: number;
ConsistencyScore: number;
DiffSummary?: string | null;
};
type CvBenchmarkIndex = {
CorpusRoot: string;
OutputRoot: string;
GeneratedAtUtc: string;
TotalFiles: number;
AverageCoverage: number;
AverageConfidence: number;
AverageConsistency: number;
FilesWithSuspiciousLocations: number;
MissingApprovedFixtures: number;
Entries: CvBenchmarkEntry[];
};
type CvBenchmarkStatus = {
indexJson?: string | null;
reportMarkdown?: string | null;
rootPath: string;
lastUpdatedAtUtc?: string | null;
};
type SystemStatus = {
environment: string;
contentRoot: string;
version: string;
commitSha?: string | null;
buildStamp?: string | null;
storage: {
dataRoot: string;
dbPath: string;
dbExists: boolean;
dbSizeBytes?: number | null;
companyCount: number;
jobCount: number;
deletedCount: number;
};
email: {
enabled: boolean;
host?: string | null;
port: number;
enableSsl: boolean;
from?: string | null;
fromName?: string | null;
};
database: {
provider: string;
looksConfigured: boolean;
canConnect: boolean;
target?: string | null;
usesFileStorage: boolean;
warning?: string | null;
};
runtime: {
framework: string;
osDescription: string;
processArchitecture: string;
machineName?: string | null;
};
auth: {
required: boolean;
hasJwtKey: boolean;
googleConfigured: boolean;
gmailConfigured: boolean;
};
ai: AiServiceMetrics;
};
function formatBytes(bytes?: number | null) {
if (bytes == null) return "-";
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function displayMetadata(value?: string | null) {
return value && value.trim().length > 0 ? value : "-";
}
function formatDate(value?: string | null) {
return value ? new Date(value).toLocaleString() : "-";
}
function formatPercent(value?: number | null) {
return typeof value === "number" ? `${Math.round(value * 100)}%` : "-";
}
function parseBenchmarkIndex(indexJson?: string | null): CvBenchmarkIndex | null {
if (!indexJson?.trim()) return null;
try {
return JSON.parse(indexJson) as CvBenchmarkIndex;
} catch {
return null;
}
}
function benchmarkTone(value?: number | null) {
if (typeof value !== "number") return "default" as const;
if (value >= 0.8) return "success" as const;
if (value >= 0.6) return "warning" as const;
return "error" as const;
}
function SummaryCard({ title, value, subtitle, tone = "default" }: { title: string; value: string; subtitle?: string; tone?: "default" | "success" | "warning" | "error" }) {
const color = tone === "success" ? "success.main" : tone === "warning" ? "warning.main" : tone === "error" ? "error.main" : "text.primary";
return (
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="overline" sx={{ color: "text.secondary" }}>{title}</Typography>
<Typography variant="h5" sx={{ fontWeight: 950, color }}>{value}</Typography>
<Typography variant="body2" sx={{ color: "text.secondary", mt: 1 }}>{subtitle || "-"}</Typography>
</Paper>
);
}
function DetailRow({ label, value }: { label: string; value: React.ReactNode }) {
return <Typography variant="body2"><strong>{label}:</strong> {value}</Typography>;
}
export default function AdminSystemPage() {
const { t } = useI18n();
const [tab, setTab] = useState(0);
const [status, setStatus] = useState<SystemStatus | null>(null);
const [emailSettings, setEmailSettings] = useState<EditableEmailSettings | null>(null);
const [benchmarkStatus, setBenchmarkStatus] = useState<CvBenchmarkStatus | null>(null);
const [smtpPassword, setSmtpPassword] = useState("");
const [clearPassword, setClearPassword] = useState(false);
const [loading, setLoading] = useState(false);
const [runningProbe, setRunningProbe] = useState(false);
const [savingSettings, setSavingSettings] = useState(false);
const [error, setError] = useState<string | null>(null);
const [testEmailTo, setTestEmailTo] = useState("");
const [testEmailSubject, setTestEmailSubject] = useState("Jobbjakt SMTP test");
const [testEmailMessage, setTestEmailMessage] = useState("This is a test email from the Jobbjakt system panel.");
const [sendingTestEmail, setSendingTestEmail] = useState(false);
const load = async () => {
setLoading(true);
setError(null);
try {
const [statusRes, emailRes, benchmarkRes] = await Promise.all([
api.get<SystemStatus>("/admin/system"),
api.get<EditableEmailSettings>("/admin/system/email-settings"),
api.get<CvBenchmarkStatus>("/admin/system/cv-benchmark").catch(() => ({ data: null } as any)),
]);
setStatus(statusRes.data);
setEmailSettings(emailRes.data);
setBenchmarkStatus(benchmarkRes.data ?? null);
setSmtpPassword("");
setClearPassword(false);
} catch (e: any) {
setError(getApiErrorMessage(e, "Failed to load system status."));
setStatus(null);
setEmailSettings(null);
setBenchmarkStatus(null);
} finally {
setLoading(false);
}
};
useEffect(() => {
void load();
}, []);
const dbTone = useMemo(() => {
if (!status) return "default" as const;
if (!status.database.looksConfigured || !status.database.canConnect) return "error" as const;
if (status.database.warning) return "warning" as const;
return "success" as const;
}, [status]);
const aiTone = useMemo(() => {
if (!status) return "default" as const;
if (!status.ai.healthy) return "error" as const;
if (status.ai.probeFailures > 0 || status.ai.failures > 0 || (status.ai.ocrFailures ?? 0) > 0) return "warning" as const;
return "success" as const;
}, [status]);
const benchmarkIndex = useMemo(() => parseBenchmarkIndex(benchmarkStatus?.indexJson), [benchmarkStatus?.indexJson]);
const weakestEntries = useMemo(() => {
if (!benchmarkIndex) return [] as CvBenchmarkEntry[];
return [...benchmarkIndex.Entries]
.sort((a, b) => (a.CoverageScore + a.ConfidenceScore + a.ConsistencyScore) - (b.CoverageScore + b.ConfidenceScore + b.ConsistencyScore))
.slice(0, 6);
}, [benchmarkIndex]);
const benchmarkFindings = useMemo(() => {
if (!benchmarkIndex) return [] as Array<{ file: string; issue: string }>;
return benchmarkIndex.Entries.flatMap((entry) => {
const findings: Array<{ file: string; issue: string }> = [];
if (entry.ContactLocation && /(culture|education|arial|hobbies|cooperate|ag, ni|bold)/i.test(entry.ContactLocation)) {
findings.push({ file: entry.FileName, issue: `Suspicious contact location: ${entry.ContactLocation}` });
}
if (entry.FirstEducation && entry.FirstEducation.length > 120) {
findings.push({ file: entry.FileName, issue: "Education qualification looks over-captured." });
}
if ((entry.FirstJob ?? "").length > 120) {
findings.push({ file: entry.FileName, issue: "Work title looks over-captured." });
}
if ((entry.QualificationLevels ?? []).includes("Other")) {
findings.push({ file: entry.FileName, issue: "Qualification level fell back to Other." });
}
return findings;
}).slice(0, 10);
}, [benchmarkIndex]);
const sendTestEmail = async () => {
setSendingTestEmail(true);
try {
await api.post("/users/send-test-email", {
toEmail: testEmailTo.trim() || null,
subject: testEmailSubject.trim() || null,
message: testEmailMessage.trim() || null,
});
setError(null);
} catch (e: any) {
setError(getApiErrorMessage(e, "Failed to send test email."));
} finally {
setSendingTestEmail(false);
}
};
const saveEmailSettings = async () => {
if (!emailSettings) return;
setSavingSettings(true);
try {
const res = await api.put<EditableEmailSettings>("/admin/system/email-settings", {
enabled: emailSettings.enabled,
host: emailSettings.host,
port: Number(emailSettings.port) || 587,
user: emailSettings.user,
password: smtpPassword.trim() || null,
clearPassword,
from: emailSettings.from,
fromName: emailSettings.fromName,
enableSsl: emailSettings.enableSsl,
timeoutMs: Number(emailSettings.timeoutMs) || 15000,
});
setEmailSettings(res.data);
setSmtpPassword("");
setClearPassword(false);
await load();
} catch (e: any) {
setError(getApiErrorMessage(e, "Failed to save email settings."));
} finally {
setSavingSettings(false);
}
};
return (
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
<Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, alignItems: "center", flexWrap: "wrap" }}>
<Box>
<Typography variant="h5" sx={{ fontWeight: 950 }}>{t("adminSystemTitle")}</Typography>
<Typography sx={{ color: "text.secondary" }}>{t("adminSystemSubtitle")}</Typography>
</Box>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
<Button
variant="outlined"
onClick={async () => {
setRunningProbe(true);
setError(null);
try {
await api.post("/admin/system/ai/probe");
await load();
} catch (e: any) {
setError(getApiErrorMessage(e, "Failed to run AI service probe."));
} finally {
setRunningProbe(false);
}
}}
disabled={loading || runningProbe}
>
{runningProbe ? t("adminSystemRunningProbe") : t("adminSystemRunProbe")}
</Button>
<Button variant="contained" onClick={() => void load()} disabled={loading}>
{loading ? t("adminSystemRefreshing") : t("adminSystemRefresh")}
</Button>
</Box>
</Box>
<Tabs value={tab} onChange={(_, value) => setTab(value)}>
<Tab label={t("adminSystemStatusTab")} />
<Tab label={t("adminSystemSettingsTab")} />
</Tabs>
{error ? <Alert severity="error">{error}</Alert> : null}
{status?.database.warning && tab === 0 ? <Alert severity={status.database.canConnect ? "warning" : "error"}>{status.database.warning}</Alert> : null}
{status?.ai.lastError && tab === 0 ? <Alert severity={status.ai.healthy ? "warning" : "error"}>{status.ai.lastError}</Alert> : null}
{tab === 0 ? (
<>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "repeat(4, 1fr)" }, gap: 2 }}>
<SummaryCard
title={t("adminSystemEnvironment")}
value={status?.environment ?? "-"}
subtitle={`Version ${displayMetadata(status?.version)} · Commit ${displayMetadata(status?.commitSha)}`}
/>
<SummaryCard
title={t("adminSystemDatabase")}
value={status ? (status.database.canConnect ? t("adminSystemConnected") : t("adminSystemOffline")) : "-"}
subtitle={status ? `${status.database.provider} · ${status.database.target || "No target"}` : "-"}
tone={dbTone}
/>
<SummaryCard
title={t("adminSystemSmtp")}
value={status?.email.enabled ? t("adminSystemEnabled") : t("adminSystemDisabled")}
subtitle={status?.email.host || t("adminSystemNoSmtpHost")}
tone={status?.email.enabled ? "success" : "default"}
/>
<SummaryCard
title={t("adminSystemSummarizer")}
value={status?.ai.healthy ? t("adminSystemHealthy") : t("adminSystemOffline")}
subtitle={status?.ai.probeLatencyMs != null
? `${status.ai.probeLatencyMs} ms probe · ${status.ai.device || "unknown device"}`
: status?.ai.healthLatencyMs != null
? `${status.ai.healthLatencyMs} ms health · ${status.ai.device || "unknown device"}`
: t("adminSystemNoLatencyData")}
tone={aiTone}
/>
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "1.2fr 1fr" }, gap: 2 }}>
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemDatabaseStorage")}</Typography>
<Stack spacing={0.75}>
<DetailRow label={t("adminSystemProvider")} value={status?.database.provider || "-"} />
<DetailRow label={t("adminSystemTarget")} value={status?.database.target || "-"} />
<DetailRow label={t("adminSystemConfigured")} value={status?.database.looksConfigured ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemCanConnect")} value={status?.database.canConnect ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemUsesFileStorage")} value={status?.database.usesFileStorage ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemDataRoot")} value={status?.storage.dataRoot || "-"} />
<DetailRow label={t("adminSystemDbPath")} value={status?.storage.dbPath || "-"} />
<DetailRow label={t("adminSystemDbFileExists")} value={status?.storage.dbExists ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemDbSize")} value={formatBytes(status?.storage.dbSizeBytes)} />
<DetailRow label={t("companies")} value={status?.storage.companyCount ?? 0} />
<DetailRow label={t("adminSystemJobs")} value={status?.storage.jobCount ?? 0} />
<DetailRow label={t("adminSystemDeletedJobs")} value={status?.storage.deletedCount ?? 0} />
</Stack>
</Paper>
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemRuntimeAuth")}</Typography>
<Stack spacing={0.75}>
<DetailRow label={t("adminSystemFramework")} value={status?.runtime.framework || "-"} />
<DetailRow label={t("adminSystemOs")} value={status?.runtime.osDescription || "-"} />
<DetailRow label={t("adminSystemArchitecture")} value={status?.runtime.processArchitecture || "-"} />
<DetailRow label={t("adminSystemMachine")} value={status?.runtime.machineName || "-"} />
<DetailRow label={t("adminSystemContentRoot")} value={status?.contentRoot || "-"} />
<DetailRow label={t("adminSystemBuildStamp")} value={displayMetadata(status?.buildStamp)} />
<DetailRow label={t("adminSystemAuthRequired")} value={status?.auth.required ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemJwtConfigured")} value={status?.auth.hasJwtKey ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemGoogleConfigured")} value={status?.auth.googleConfigured ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemGmailConfigured")} value={status?.auth.gmailConfigured ? t("yes") : t("noWord")} />
</Stack>
</Paper>
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "1fr 1fr" }, gap: 2 }}>
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemEmailConfig")}</Typography>
<Stack spacing={0.75}>
<DetailRow label={t("adminSystemEnabled")} value={status?.email.enabled ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemFrom")} value={status?.email.from || "-"} />
<DetailRow label={t("adminSystemFromName")} value={status?.email.fromName || "-"} />
<DetailRow label={t("adminSystemHost")} value={status?.email.host || "-"} />
<DetailRow label={t("adminSystemPort")} value={status?.email.port ?? "-"} />
<DetailRow label={t("adminSystemSsl")} value={status?.email.enableSsl ? t("yes") : t("noWord")} />
</Stack>
</Paper>
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSummarizerRuntime")}</Typography>
<Stack spacing={0.75}>
<DetailRow label={t("adminSystemModel")} value={status?.ai.model || "-"} />
<DetailRow label={t("adminSystemDevice")} value={status?.ai.device || "-"} />
<DetailRow label={t("adminSystemGpuAvailable")} value={status?.ai.gpuAvailable ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemGpuName")} value={status?.ai.gpuName || "-"} />
<DetailRow label={t("adminSystemOllamaConfigured")} value={status?.ai.ollamaConfigured ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemOllamaReachable")} value={status?.ai.ollamaReachable ? t("yes") : t("noWord")} />
<DetailRow label={t("adminSystemOllamaModel")} value={status?.ai.ollamaModel || "-"} />
<DetailRow label={t("adminSystemOllamaModelAvailable")} value={status?.ai.ollamaModelAvailable ? t("yes") : t("noWord")} />
<DetailRow label="Ollama version" value={status?.ai.ollamaVersion || "-"} />
<DetailRow label="Loaded models" value={status?.ai.ollamaLoadedCount ?? 0} />
<DetailRow label={t("adminSystemHealthLatency")} value={status?.ai.healthLatencyMs != null ? `${status.ai.healthLatencyMs} ms` : "-"} />
<DetailRow label={t("adminSystemProbeLatency")} value={status?.ai.probeLatencyMs != null ? `${status.ai.probeLatencyMs} ms` : "-"} />
<DetailRow label={t("adminSystemLastProbe")} value={formatDate(status?.ai.lastProbeAt)} />
<DetailRow label={t("adminSystemLastSuccessfulProbe")} value={formatDate(status?.ai.lastProbeSuccessAt)} />
<DetailRow label={t("adminSystemLastSummarizationSuccess")} value={formatDate(status?.ai.lastSuccessAt)} />
</Stack>
</Paper>
</Box>
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSummarizerTelemetry")}</Typography>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr 1fr", md: "repeat(8, 1fr)" }, gap: 2 }}>
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemRequests")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.requests ?? 0}</Typography></Box>
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemCacheHits")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.cacheHits ?? 0}</Typography></Box>
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemCacheMisses")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.cacheMisses ?? 0}</Typography></Box>
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemFailures")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.failures ?? 0}</Typography></Box>
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemProbeFailures")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.probeFailures ?? 0}</Typography></Box>
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemAvgLatency")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.averageLatencyMs != null ? `${status.ai.averageLatencyMs} ms` : "-"}</Typography></Box>
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemOcrRequests")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.ocrRequests ?? 0}</Typography></Box>
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemOcrAvgLatency")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.averageOcrLatencyMs != null ? `${status.ai.averageOcrLatencyMs} ms` : "-"}</Typography></Box>
</Box>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", mt: 2 }}>
<Chip label={status?.database.canConnect ? t("adminSystemDatabaseConnected") : t("adminSystemDatabaseIssue")} color={status?.database.canConnect ? "success" : "error"} size="small" />
<Chip label={status?.auth.required ? t("adminSystemAuthEnforced") : t("adminSystemAuthOptional")} color={status?.auth.required ? "success" : "warning"} size="small" />
<Chip label={status?.auth.googleConfigured ? t("adminSystemGoogleReady") : t("adminSystemGoogleOff")} variant="outlined" size="small" />
<Chip label={status?.auth.gmailConfigured ? t("adminSystemGmailReady") : t("adminSystemGmailIncomplete")} variant="outlined" size="small" />
<Chip label={status?.ai.gpuAvailable ? t("adminSystemGpuVisible") : t("adminSystemCpuMode")} color={status?.ai.gpuAvailable ? "success" : "default"} size="small" />
<Chip label={status?.ai.ocrAvailable ? `OCR ${status.ai.ocrLanguages || "enabled"}` : t("adminSystemOcrUnavailable")} variant="outlined" size="small" />
{(status?.ai.ollamaInstalledModels ?? []).slice(0, 4).map((model) => (
<Chip key={model} label={`Model · ${model}`} variant="outlined" size="small" />
))}
{(status?.ai.ollamaLoadedModels ?? []).slice(0, 3).map((model) => (
<Chip key={`loaded-${model}`} label={`Loaded · ${model}`} color="primary" variant="outlined" size="small" />
))}
</Box>
</Paper>
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>CV benchmark review</Typography>
<Stack spacing={0.75}>
<DetailRow label="Benchmark root" value={benchmarkStatus?.rootPath || "-"} />
<DetailRow label="Last benchmark update" value={formatDate(benchmarkStatus?.lastUpdatedAtUtc)} />
<DetailRow label="Corpus root" value={benchmarkIndex?.CorpusRoot || "-"} />
</Stack>
{benchmarkIndex ? (
<>
<Box sx={{ mt: 2, display: "grid", gridTemplateColumns: { xs: "1fr 1fr", md: "repeat(5, 1fr)" }, gap: 1.25 }}>
<SummaryCard title="Files" value={String(benchmarkIndex.TotalFiles)} subtitle="Corpus inputs" />
<SummaryCard title="Coverage" value={formatPercent(benchmarkIndex.AverageCoverage)} subtitle="Structured field coverage" tone={benchmarkTone(benchmarkIndex.AverageCoverage)} />
<SummaryCard title="Confidence" value={formatPercent(benchmarkIndex.AverageConfidence)} subtitle="Field metadata confidence" tone={benchmarkTone(benchmarkIndex.AverageConfidence)} />
<SummaryCard title="Consistency" value={formatPercent(benchmarkIndex.AverageConsistency)} subtitle="Normalization consistency" tone={benchmarkTone(benchmarkIndex.AverageConsistency)} />
<SummaryCard title="Missing approved" value={String(benchmarkIndex.MissingApprovedFixtures)} subtitle="Needs fixture review" tone={benchmarkIndex.MissingApprovedFixtures > 0 ? "warning" : "success"} />
</Box>
<Box sx={{ mt: 2.5, display: "grid", gridTemplateColumns: { xs: "1fr", xl: "1.1fr 0.9fr" }, gap: 2 }}>
<Paper variant="outlined" sx={{ p: 1.5, borderRadius: 3 }}>
<Typography variant="subtitle1" sx={{ fontWeight: 900, mb: 1 }}>Top parser findings</Typography>
<Stack spacing={1}>
{benchmarkFindings.length > 0 ? benchmarkFindings.map((finding) => (
<Box key={`${finding.file}:${finding.issue}`} sx={{ p: 1.25, borderRadius: 2, backgroundColor: "background.default", border: "1px solid", borderColor: "divider" }}>
<Typography variant="caption" sx={{ color: "text.secondary" }}>{finding.file}</Typography>
<Typography variant="body2">{finding.issue}</Typography>
</Box>
)) : <Typography variant="body2" sx={{ color: "text.secondary" }}>No standout benchmark anomalies in the current run.</Typography>}
</Stack>
</Paper>
<Paper variant="outlined" sx={{ p: 1.5, borderRadius: 3 }}>
<Typography variant="subtitle1" sx={{ fontWeight: 900, mb: 1 }}>Weakest files in current run</Typography>
<Stack spacing={1}>
{weakestEntries.map((entry) => (
<Box key={entry.Slug} sx={{ p: 1.25, borderRadius: 2, backgroundColor: "background.default", border: "1px solid", borderColor: "divider" }}>
<Typography variant="body2" sx={{ fontWeight: 800 }}>{entry.FileName}</Typography>
<Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap", mt: 0.75 }}>
<Chip size="small" label={`Coverage ${formatPercent(entry.CoverageScore)}`} color={benchmarkTone(entry.CoverageScore)} />
<Chip size="small" label={`Confidence ${formatPercent(entry.ConfidenceScore)}`} color={benchmarkTone(entry.ConfidenceScore)} />
<Chip size="small" label={`Consistency ${formatPercent(entry.ConsistencyScore)}`} color={benchmarkTone(entry.ConsistencyScore)} />
</Box>
<Typography variant="caption" sx={{ display: "block", color: "text.secondary", mt: 0.75 }}>{entry.DiffSummary || "-"}</Typography>
</Box>
))}
</Stack>
</Paper>
</Box>
<Box sx={{ mt: 2, p: 1.5, borderRadius: 2, backgroundColor: "background.default", border: "1px solid", borderColor: "divider", maxHeight: 280, overflow: "auto" }}>
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>Latest markdown summary</Typography>
<Typography variant="body2" sx={{ whiteSpace: "pre-wrap", fontFamily: "ui-monospace, SFMono-Regular, monospace" }}>
{benchmarkStatus?.reportMarkdown || "-"}
</Typography>
</Box>
</>
) : (
<Box sx={{ mt: 1.5, p: 1.5, borderRadius: 2, backgroundColor: "background.default", border: "1px solid", borderColor: "divider" }}>
<Typography variant="body2" sx={{ whiteSpace: "pre-wrap", fontFamily: "ui-monospace, SFMono-Regular, monospace" }}>
{benchmarkStatus?.reportMarkdown || "Run scripts/run-cv-benchmark.sh to generate the latest corpus report and fixture candidates."}
</Typography>
</Box>
)}
</Paper>
</>
) : (
<Box sx={{ display: "grid", gap: 2 }}>
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemEmailSettingsTitle")}</Typography>
<Typography variant="body2" sx={{ color: "text.secondary", mb: 1.5 }}>{t("adminSystemEmailSettingsBody")}</Typography>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 1.5 }}>
<FormControlLabel
control={<Checkbox checked={Boolean(emailSettings?.enabled)} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, enabled: e.target.checked } : prev)} />}
label={t("adminSystemEnabled")}
sx={{ gridColumn: { xs: "1 / -1", md: "1 / -1" } }}
/>
<TextField label={t("adminSystemHost")} value={emailSettings?.host ?? ""} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, host: e.target.value } : prev)} fullWidth />
<TextField label={t("adminSystemPort")} type="number" value={emailSettings?.port ?? 587} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, port: Number(e.target.value) } : prev)} fullWidth />
<TextField label={t("adminSystemUsername")} value={emailSettings?.user ?? ""} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, user: e.target.value } : prev)} fullWidth />
<TextField label={t("adminSystemPassword")} type="password" value={smtpPassword} onChange={(e) => { setSmtpPassword(e.target.value); if (e.target.value.trim()) setClearPassword(false); }} helperText={emailSettings?.hasPassword ? t("adminSystemPasswordStored") : t("adminSystemPasswordMissing")} fullWidth />
<TextField label={t("adminSystemFrom")} value={emailSettings?.from ?? ""} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, from: e.target.value } : prev)} fullWidth />
<TextField label={t("adminSystemFromName")} value={emailSettings?.fromName ?? ""} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, fromName: e.target.value } : prev)} fullWidth />
<TextField label={t("adminSystemTimeoutMs")} type="number" value={emailSettings?.timeoutMs ?? 15000} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, timeoutMs: Number(e.target.value) } : prev)} fullWidth />
<FormControlLabel control={<Checkbox checked={Boolean(emailSettings?.enableSsl)} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, enableSsl: e.target.checked } : prev)} />} label={t("adminSystemSsl")} />
<FormControlLabel control={<Checkbox checked={clearPassword} onChange={(e) => { setClearPassword(e.target.checked); if (e.target.checked) setSmtpPassword(""); }} />} label={t("adminSystemClearStoredPassword")} sx={{ gridColumn: { xs: "1 / -1", md: "1 / -1" } }} />
</Box>
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 1.5 }}>
<Button variant="contained" disabled={savingSettings || !emailSettings} onClick={() => void saveEmailSettings()}>
{savingSettings ? t("adminSystemSaving") : t("adminSystemSaveSettings")}
</Button>
</Box>
</Paper>
<Paper sx={{ p: 2, borderRadius: 3 }}>
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSmtpTest")}</Typography>
<Typography variant="body2" sx={{ color: "text.secondary", mb: 1.5 }}>
{t("adminSystemSmtpTestBody")}
</Typography>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 1.5 }}>
<TextField label={t("adminSystemRecipientEmail")} value={testEmailTo} onChange={(e) => setTestEmailTo(e.target.value)} placeholder={t("adminSystemRecipientPlaceholder")} />
<TextField label={t("adminSystemSubject")} value={testEmailSubject} onChange={(e) => setTestEmailSubject(e.target.value)} />
<TextField label={t("adminSystemMessage")} multiline minRows={3} value={testEmailMessage} onChange={(e) => setTestEmailMessage(e.target.value)} sx={{ gridColumn: { xs: "1 / -1", md: "1 / -1" } }} />
</Box>
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 1.5 }}>
<Button variant="contained" disabled={sendingTestEmail} onClick={() => void sendTestEmail()}>
{sendingTestEmail ? t("adminSystemSending") : t("adminSystemSendTestEmail")}
</Button>
</Box>
</Paper>
</Box>
)}
</Box>
);
}
+266
View File
@@ -0,0 +1,266 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
Box,
Button,
Checkbox,
Chip,
FormControlLabel,
Paper,
Stack,
TextField,
Typography,
} from "@mui/material";
import useMediaQuery from "@mui/material/useMediaQuery";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useDialogActions } from "../dialogs";
import { useI18n } from "../i18n/I18nProvider";
type UserDto = {
id: string;
email?: string | null;
userName?: string | null;
emailConfirmed: boolean;
roles: string[];
};
export default function AdminUsersPage() {
const isMobile = useMediaQuery("(max-width:767.95px)");
const { toast } = useToast();
const { confirmAction } = useDialogActions();
const { t } = useI18n();
const [users, setUsers] = useState<UserDto[]>([]);
const [loading, setLoading] = useState(false);
const [newEmail, setNewEmail] = useState("");
const [newPassword, setNewPassword] = useState("");
const [newIsAdmin, setNewIsAdmin] = useState(false);
async function load() {
setLoading(true);
try {
const res = await api.get<UserDto[]>("/users");
setUsers(res.data ?? []);
} catch {
setUsers([]);
} finally {
setLoading(false);
}
}
useEffect(() => {
void load();
}, []);
const canCreate = useMemo(() => newEmail.trim().length > 3 && newPassword.length >= 6, [newEmail, newPassword]);
const rows = useMemo(() => users.map((u) => ({
id: u.id,
email: u.email || "",
userName: u.userName || "",
roles: u.roles || [],
emailConfirmed: u.emailConfirmed,
raw: u,
})), [users]);
const setAdminRole = useCallback(async (u: UserDto, isAdmin: boolean) => {
try {
await api.put(`/users/${u.id}/roles`, { roles: isAdmin ? ["Admin"] : [] });
toast(t("adminUsersRolesUpdated"), "success");
await load();
} catch (e: any) {
const msg = e?.response?.data || e?.message || t("adminUsersRolesUpdateFailed");
toast(String(msg), "error");
}
}, [t, toast]);
const sendReset = useCallback(async (u: UserDto) => {
try {
await api.post(`/users/${u.id}/send-password-reset`);
toast(t("adminUsersResetSent"), "success");
} catch (e: any) {
toast(getApiErrorMessage(e, t("adminUsersResetFailed")), "error");
}
}, [t, toast]);
const remove = useCallback(async (u: UserDto) => {
const name = u.userName || u.email || u.id;
if (!(await confirmAction(t("adminUsersDeleteConfirmNamed", { name }), { title: t("adminUsersDeleteConfirmTitle"), confirmLabel: t("adminUsersDelete"), destructive: true }))) return;
try {
await api.delete(`/users/${u.id}`);
toast(t("adminUsersDeleted"), "info");
await load();
} catch {
toast(t("adminUsersDeleteFailed"), "error");
}
}, [confirmAction, t, toast]);
const columns = useMemo<GridColDef[]>(() => [
{ field: "email", headerName: t("profileEmail"), flex: 1.2, minWidth: 220 },
{ field: "userName", headerName: t("profileUsername"), flex: 1, minWidth: 180 },
{
field: "roles",
headerName: t("adminUsersRolesLabel"),
flex: 1,
minWidth: 180,
sortable: false,
renderCell: (params) => {
const roles = params.row.roles as string[];
return (
<Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap", py: 0.5 }}>
{roles.length ? roles.map((role) => <Chip key={role} size="small" label={role} variant="outlined" />) : <Typography variant="body2" sx={{ color: "text.secondary" }}>—</Typography>}
</Box>
);
},
},
{
field: "emailConfirmed",
headerName: t("adminUsersConfirmed"),
width: 130,
renderCell: (params) => (
<Chip size="small" label={params.value ? t("yes") : t("noWord")} color={params.value ? "success" : "default"} variant={params.value ? "filled" : "outlined"} />
),
},
{
field: "actions",
headerName: t("adminUsersActions"),
minWidth: 300,
flex: 1.4,
sortable: false,
filterable: false,
renderCell: (params) => {
const user = params.row.raw as UserDto;
const isAdmin = (user.roles || []).includes("Admin");
return (
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", py: 0.5 }}>
<Button size="small" variant={isAdmin ? "contained" : "outlined"} onClick={() => void setAdminRole(user, !isAdmin)}>
{t("adminUsersAdmin")}
</Button>
<Button size="small" variant="outlined" onClick={() => void sendReset(user)}>
{t("adminUsersSendReset")}
</Button>
<Button size="small" color="error" variant="outlined" onClick={() => void remove(user)}>
{t("adminUsersDelete")}
</Button>
</Box>
);
},
},
], [remove, sendReset, setAdminRole, t]);
return (
<Paper sx={{ p: { xs: 1.5, sm: 2 } }}>
<Typography variant="h6" sx={{ fontWeight: 950, mb: 0.5 }}>
{t("adminUsersTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>{t("adminUsersSubtitle")}</Typography>
<Paper sx={{ p: { xs: 1.5, sm: 2 }, mb: 2 }}>
<Typography sx={{ fontWeight: 900, mb: 1 }}>{t("adminUsersCreateUser")}</Typography>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 1.5 }}>
<TextField label={t("profileEmail")} value={newEmail} onChange={(e) => setNewEmail(e.target.value)} fullWidth />
<TextField label={t("profileNewPassword")} type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} fullWidth />
</Box>
<Box sx={{ display: "flex", alignItems: { xs: "stretch", sm: "center" }, justifyContent: "space-between", gap: 2, mt: 1.5, flexWrap: "wrap" }}>
<FormControlLabel control={<Checkbox checked={newIsAdmin} onChange={(e) => setNewIsAdmin(e.target.checked)} />} label={t("adminUsersAdmin")} />
<Button
variant="contained"
disabled={!canCreate || loading}
sx={{ width: { xs: "100%", sm: "auto" } }}
onClick={async () => {
try {
await api.post("/users", { email: newEmail, password: newPassword, roles: newIsAdmin ? ["Admin"] : [] });
setNewEmail("");
setNewPassword("");
setNewIsAdmin(false);
toast(t("adminUsersCreated"), "success");
await load();
} catch (e: any) {
const msg = e?.response?.data || e?.message || t("adminUsersCreateFailed");
toast(String(msg), "error");
}
}}
>
{t("create")}
</Button>
</Box>
</Paper>
{isMobile ? (
<Stack spacing={1.5}>
{!loading && rows.length === 0 ? (
<Typography sx={{ color: "text.secondary", py: 2, textAlign: "center" }}>{t("adminUsersNoUsers")}</Typography>
) : null}
{rows.map((row) => {
const user = row.raw as UserDto;
const isAdmin = user.roles.includes("Admin");
return (
<Paper key={row.id} sx={{ p: 1.5, borderRadius: 3 }}>
<Stack spacing={1.25}>
<Box>
<Typography sx={{ fontWeight: 900, overflowWrap: "anywhere" }}>
{row.userName || row.email || row.id}
</Typography>
<Typography variant="body2" sx={{ color: "text.secondary", overflowWrap: "anywhere" }}>
{row.email || "—"}
</Typography>
</Box>
<Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap" }}>
{(row.roles as string[]).length ? (row.roles as string[]).map((role) => (
<Chip key={role} size="small" label={role} variant="outlined" />
)) : <Chip size="small" label="—" variant="outlined" />}
<Chip size="small" label={row.emailConfirmed ? t("yes") : t("noWord")} color={row.emailConfirmed ? "success" : "default"} variant={row.emailConfirmed ? "filled" : "outlined"} />
</Box>
<Stack spacing={1}>
<Button variant={isAdmin ? "contained" : "outlined"} onClick={() => void setAdminRole(user, !isAdmin)} fullWidth>
{t("adminUsersAdmin")}
</Button>
<Button variant="outlined" onClick={() => void sendReset(user)} fullWidth>
{t("adminUsersSendReset")}
</Button>
<Button color="error" variant="outlined" onClick={() => void remove(user)} fullWidth>
{t("adminUsersDelete")}
</Button>
</Stack>
</Stack>
</Paper>
);
})}
</Stack>
) : (
<Paper sx={{ borderRadius: 3, border: "1px solid", borderColor: "divider", overflow: "hidden" }}>
<DataGrid
autoHeight
rows={rows}
columns={columns}
disableRowSelectionOnClick
loading={loading}
pageSizeOptions={[5, 10, 25]}
initialState={{
pagination: { paginationModel: { pageSize: 10, page: 0 } },
sorting: { sortModel: [{ field: "email", sort: "asc" }] },
}}
sx={{
border: 0,
'& .MuiDataGrid-columnHeaders': {
backgroundColor: 'action.hover',
fontWeight: 800,
},
'& .MuiDataGrid-cell': {
alignItems: 'center',
},
}}
/>
{!loading && rows.length === 0 ? (
<Typography sx={{ color: "text.secondary", py: 2, textAlign: "center" }}>{t("adminUsersNoUsers")}</Typography>
) : null}
</Paper>
)}
</Paper>
);
}
@@ -0,0 +1,144 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
Box,
Chip,
CircularProgress,
FormControl,
InputLabel,
MenuItem,
Paper,
Select,
Stack,
TextField,
Typography,
Button,
} from "@mui/material";
import MailOutlineIcon from "@mui/icons-material/MailOutline";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
export type CorrespondenceInboxItem = {
id: number;
jobApplicationId: number;
companyName?: string | null;
jobTitle?: string | null;
from: string;
direction?: string | null;
subject?: string | null;
channel?: string | null;
date: string;
contentPreview: string;
externalThreadId?: string | null;
externalFrom?: string | null;
externalTo?: string | null;
labelCount: number;
attachmentCount: number;
};
export default function CorrespondenceInboxPage() {
const navigate = useNavigate();
const { toast } = useToast();
const [items, setItems] = useState<CorrespondenceInboxItem[]>([]);
const [loading, setLoading] = useState(false);
const [query, setQuery] = useState("");
const [direction, setDirection] = useState<string>("all");
const [linkState, setLinkState] = useState<string>("all");
const load = useCallback(async () => {
setLoading(true);
try {
const res = await api.get<CorrespondenceInboxItem[]>("/correspondence", {
params: {
q: query.trim() || undefined,
direction: direction === "all" ? undefined : direction,
linkState: linkState === "all" ? undefined : linkState,
},
});
setItems(res.data ?? []);
} catch (error) {
toast(getApiErrorMessage(error, "Failed to load correspondence inbox."), "error");
} finally {
setLoading(false);
}
}, [direction, linkState, query, toast]);
useEffect(() => {
void load();
}, [load]);
const filteredSummary = useMemo(() => {
const linked = items.filter((item) => item.externalThreadId).length;
const inbound = items.filter((item) => item.direction === "inbound").length;
return { linked, inbound };
}, [items]);
return (
<Paper sx={{ mt: 0, p: 2 }}>
<Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, alignItems: "center", flexWrap: "wrap", mb: 2 }}>
<Box>
<Typography variant="h5" sx={{ fontWeight: 900 }}>Correspondence inbox</Typography>
<Typography variant="body2" sx={{ color: "text.secondary" }}>
Cross-job view of imported correspondence and Gmail-linked history.
</Typography>
</Box>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
<Chip icon={<MailOutlineIcon />} label={`${items.length} items`} variant="outlined" />
<Chip label={`${filteredSummary.linked} linked`} variant="outlined" color={filteredSummary.linked > 0 ? "success" : "default"} />
<Chip label={`${filteredSummary.inbound} inbound`} variant="outlined" />
</Box>
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "2fr 1fr 1fr auto" }, gap: 1.25, mb: 2 }}>
<TextField label="Search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Company, role, recruiter, subject" />
<FormControl fullWidth>
<InputLabel>Direction</InputLabel>
<Select value={direction} label="Direction" onChange={(e) => setDirection(String(e.target.value))}>
<MenuItem value="all">All</MenuItem>
<MenuItem value="inbound">Inbound</MenuItem>
<MenuItem value="outbound">Outbound</MenuItem>
<MenuItem value="internal">Internal</MenuItem>
</Select>
</FormControl>
<FormControl fullWidth>
<InputLabel>Link state</InputLabel>
<Select value={linkState} label="Link state" onChange={(e) => setLinkState(String(e.target.value))}>
<MenuItem value="all">All</MenuItem>
<MenuItem value="linked">Linked threads</MenuItem>
<MenuItem value="manual">Manual/internal only</MenuItem>
</Select>
</FormControl>
<Button variant="contained" onClick={() => void load()} disabled={loading}>{loading ? "Loading..." : "Refresh"}</Button>
</Box>
{loading ? <Box sx={{ py: 6, display: "flex", justifyContent: "center" }}><CircularProgress size={28} /></Box> : null}
{!loading && items.length === 0 ? (
<Typography sx={{ color: "text.secondary", py: 4, textAlign: "center" }}>No correspondence matches the current filters.</Typography>
) : null}
<Stack spacing={1.25}>
{items.map((item) => (
<Paper key={item.id} variant="outlined" sx={{ p: 1.5, borderRadius: 3 }}>
<Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, flexWrap: "wrap", alignItems: "flex-start" }}>
<Box sx={{ minWidth: 0 }}>
<Typography sx={{ fontWeight: 800, overflowWrap: "anywhere" }}>{item.companyName || "Unknown company"} • {item.jobTitle || "Unknown role"}</Typography>
<Typography variant="body2" sx={{ color: "text.secondary", overflowWrap: "anywhere" }}>{item.subject || item.contentPreview}</Typography>
<Typography variant="caption" sx={{ color: "text.secondary", display: "block", mt: 0.5 }}>
{item.externalFrom || item.from} {item.externalTo ? `→ ${item.externalTo}` : ""} · {new Date(item.date).toLocaleString()}
</Typography>
</Box>
<Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap", justifyContent: "flex-end" }}>
{item.direction ? <Chip size="small" label={item.direction} variant="outlined" /> : null}
{item.externalThreadId ? <Chip size="small" label={`Thread ${item.externalThreadId}`} color="success" variant="outlined" /> : <Chip size="small" label="Manual/internal" variant="outlined" />}
{item.labelCount > 0 ? <Chip size="small" label={`${item.labelCount} labels`} variant="outlined" /> : null}
{item.attachmentCount > 0 ? <Chip size="small" label={`${item.attachmentCount} attachments`} variant="outlined" /> : null}
<Button size="small" variant="text" onClick={() => navigate(`/jobs?open=${item.jobApplicationId}`)}>Open job</Button>
</Box>
</Box>
</Paper>
))}
</Stack>
</Paper>
);
}
@@ -0,0 +1,82 @@
import React, { useEffect, useState } from "react";
import { Alert, Box, Button, Paper, TextField, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
export default function ForgotPasswordPage() {
const { toast } = useToast();
const { t } = useI18n();
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [loading, setLoading] = useState(false);
const [submitted, setSubmitted] = useState(false);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
setEmail(params.get("email") || "");
}, []);
return (
<Box
sx={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
background:
"radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
}}
>
<Paper sx={{ width: "min(520px, 100%)", p: 3 }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{t("forgotPasswordTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{t("forgotPasswordBody")}
</Typography>
<Box
component="form"
onSubmit={(e) => {
e.preventDefault();
if (!email.trim()) {
toast(t("passwordResetEnterEmail"), "info");
return;
}
setLoading(true);
api
.post("/auth/request-password-reset", { email: email.trim() })
.then(() => {
setSubmitted(true);
toast(t("passwordResetRequestSent"), "success");
})
.catch((error: any) => {
toast(getApiErrorMessage(error, t("passwordResetRequestFailed")), "error");
})
.finally(() => setLoading(false));
}}
sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
>
{submitted ? <Alert severity="success">{t("passwordResetRequestSent")}</Alert> : null}
<TextField label={t("profileEmail")} value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" fullWidth />
<Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1, mt: 1 }}>
<Button type="button" variant="outlined" onClick={() => navigate("/login")} disabled={loading}>
{t("backToLogin")}
</Button>
<Button type="submit" variant="contained" disabled={loading}>
{loading ? t("passwordResetRequestSending") : t("forgotPasswordSubmit")}
</Button>
</Box>
</Box>
</Paper>
</Box>
);
}
@@ -0,0 +1,269 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Box, Button, Chip, CircularProgress, Paper, Stack, TextField, Typography } from "@mui/material";
import { api, getApiErrorMessage } from "../api";
import { CreatedSuggestedGmailJobResult, GmailManualSyncResult, GmailReviewQueueResponse, GmailSuggestedJobsResponse } from "../types";
import { useToast } from "../toast";
import { useNavigate } from "react-router-dom";
export default function GmailReviewPage() {
const { toast } = useToast();
const navigate = useNavigate();
const [data, setData] = useState<GmailReviewQueueResponse | null>(null);
const [suggestions, setSuggestions] = useState<GmailSuggestedJobsResponse | null>(null);
const [loading, setLoading] = useState(false);
const [syncing, setSyncing] = useState(false);
const [savingThreadId, setSavingThreadId] = useState<string | null>(null);
const [creatingThreadId, setCreatingThreadId] = useState<string | null>(null);
const [routingFilter, setRoutingFilter] = useState<"all" | "auto-link" | "review" | "unmatched" | "suggested" | "linked" | "rejected">("all");
const [notes, setNotes] = useState<Record<string, string>>({});
const load = useCallback(async () => {
setLoading(true);
try {
const [reviewRes, suggestedRes] = await Promise.all([
api.get<GmailReviewQueueResponse>("/gmail/review-candidates"),
api.get<GmailSuggestedJobsResponse>("/gmail/suggested-jobs"),
]);
setData(reviewRes.data);
setSuggestions(suggestedRes.data);
setNotes((prev) => {
const next = { ...prev };
for (const thread of reviewRes.data.threads) {
if (next[thread.threadId] === undefined) next[thread.threadId] = thread.decisionNote || "";
}
return next;
});
} catch (error) {
toast(getApiErrorMessage(error, "Failed to load Gmail review candidates."), "error");
} finally {
setLoading(false);
}
}, [toast]);
useEffect(() => {
void load();
}, [load]);
const saveDecision = useCallback(async (threadId: string, decision: "linked" | "rejected" | "review" | "suggested", jobApplicationId?: number) => {
setSavingThreadId(threadId);
try {
await api.post("/gmail/review-decision", {
threadId,
decision,
jobApplicationId: decision === "linked" ? jobApplicationId ?? null : null,
note: notes[threadId]?.trim() || null,
});
await load();
toast(
decision === "linked"
? "Thread linked and imported."
: decision === "rejected"
? "Thread rejected from review."
: decision === "suggested"
? "Thread kept as suggested job material."
: "Thread returned to review.",
"success",
);
} catch (error) {
toast(getApiErrorMessage(error, "Failed to save Gmail review decision."), "error");
} finally {
setSavingThreadId(null);
}
}, [load, notes, toast]);
const runManualSync = useCallback(async () => {
setSyncing(true);
try {
const res = await api.post<GmailManualSyncResult>("/gmail/manual-sync", {
lookbackDays: 365,
maxResultsPerQuery: 8,
autoImportHighConfidence: true,
includeSpamTrash: false,
});
await load();
toast(
`Manual Gmail sync finished: ${res.data.importedThreads} threads linked, ${res.data.reviewThreadCount} review, ${res.data.unmatchedThreadCount} unmatched.`,
"success",
);
} catch (error) {
toast(getApiErrorMessage(error, "Failed to run Gmail manual sync."), "error");
} finally {
setSyncing(false);
}
}, [load, toast]);
const createSuggestedJob = useCallback(async (threadId: string) => {
const suggestion = suggestions?.items.find((item) => item.threadId === threadId);
if (!suggestion) return;
setCreatingThreadId(threadId);
try {
const res = await api.post<CreatedSuggestedGmailJobResult>("/gmail/create-suggested-job", {
threadId,
companyName: suggestion.companyName || "Unknown company",
jobTitle: suggestion.suggestedJobTitle || suggestion.subject || "Suggested role",
recruiterName: suggestion.recruiterName || null,
recruiterEmail: suggestion.recruiterEmail || null,
notes: notes[threadId]?.trim() || suggestion.preview || null,
status: "Applied",
});
await load();
toast(`Created suggested job and imported ${res.data.imported} message${res.data.imported === 1 ? "" : "s"}.`, "success");
navigate(`/jobs?open=${res.data.jobApplicationId}`);
} catch (error) {
toast(getApiErrorMessage(error, "Failed to create the suggested job."), "error");
} finally {
setCreatingThreadId(null);
}
}, [load, navigate, notes, suggestions?.items, toast]);
const filteredThreads = useMemo(() => {
const threads = data?.threads ?? [];
return routingFilter === "all" ? threads : threads.filter((thread) => thread.routing === routingFilter);
}, [data?.threads, routingFilter]);
return (
<Paper sx={{ mt: 0, p: 2 }}>
<Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, alignItems: "center", flexWrap: "wrap", mb: 2 }}>
<Box>
<Typography variant="h5" sx={{ fontWeight: 900 }}>Gmail review queue</Typography>
<Typography variant="body2" sx={{ color: "text.secondary" }}>
Manual sync, high-confidence auto-linking, medium-confidence review, and suggested jobs from unmatched Gmail threads.
</Typography>
</Box>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
<Button variant="contained" onClick={() => void runManualSync()} disabled={syncing}>
{syncing ? "Syncing..." : "Run manual sync"}
</Button>
<Button variant="outlined" onClick={() => void load()} disabled={loading || syncing}>
{loading ? "Loading..." : "Refresh"}
</Button>
</Box>
</Box>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", mb: 2 }}>
<Chip label={`Filter: ${routingFilter}`} variant="outlined" />
{(["all", "auto-link", "review", "unmatched", "suggested", "linked", "rejected"] as const).map((value) => (
<Button key={value} size="small" variant={routingFilter === value ? "contained" : "text"} onClick={() => setRoutingFilter(value)}>
{value}
</Button>
))}
</Box>
{data ? (
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", mb: 2 }}>
<Chip label={`${data.candidateThreadCount} candidate threads`} variant="outlined" />
<Chip label={`${data.autoLinkThreadCount} auto-link`} color="success" variant="outlined" />
<Chip label={`${data.reviewThreadCount} review`} color="warning" variant="outlined" />
<Chip label={`${data.unmatchedThreadCount} unmatched`} variant="outlined" />
{suggestions?.count ? <Chip label={`${suggestions.count} suggested jobs`} color="secondary" variant="outlined" /> : null}
</Box>
) : null}
{loading ? <Box sx={{ py: 6, display: "flex", justifyContent: "center" }}><CircularProgress size={28} /></Box> : null}
{!loading && data && filteredThreads.length === 0 ? <Typography sx={{ color: "text.secondary" }}>No Gmail review candidates match the current filter.</Typography> : null}
<Stack spacing={1.25}>
{filteredThreads.map((thread) => {
const suggestion = (suggestions?.items ?? []).find((item) => item.threadId === thread.threadId);
return (
<Paper key={thread.threadId} variant="outlined" sx={{ p: 1.5, borderRadius: 3 }}>
<Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, flexWrap: "wrap", alignItems: "flex-start" }}>
<Box sx={{ minWidth: 0, flex: "1 1 420px" }}>
<Typography sx={{ fontWeight: 800, overflowWrap: "anywhere" }}>{thread.subject}</Typography>
<Typography variant="body2" sx={{ color: "text.secondary" }}>
{thread.messageCount} messages · {thread.routing}
</Typography>
<Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap", mt: 0.75 }}>
{thread.matchedQueries.slice(0, 3).map((query) => (
<Chip key={query} size="small" label={query} variant="outlined" />
))}
{thread.hasImportedMessages ? <Chip size="small" label="Has imported messages" color="success" variant="outlined" /> : null}
</Box>
<TextField
label="Review notes"
value={notes[thread.threadId] ?? ""}
onChange={(event) => setNotes((prev) => ({ ...prev, [thread.threadId]: event.target.value }))}
size="small"
fullWidth
multiline
minRows={2}
sx={{ mt: 1.25 }}
placeholder="Why this should link, stay in review, or become a suggested job."
/>
{suggestion ? (
<Typography variant="body2" sx={{ color: "text.secondary", mt: 1 }}>
Suggested job: {suggestion.companyName || "Unknown company"} · {suggestion.suggestedJobTitle || "Unknown role"}
</Typography>
) : null}
</Box>
<Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap", justifyContent: "flex-end" }}>
{thread.jobCandidates.slice(0, 2).map((candidate) => (
<Chip
key={candidate.jobApplicationId}
label={`${candidate.companyName} • ${candidate.jobTitle} (${candidate.score})`}
variant="outlined"
color={candidate.confidence === "high" ? "success" : candidate.confidence === "medium" ? "warning" : "default"}
/>
))}
{thread.jobCandidates[0] ? (
<Button size="small" variant="text" onClick={() => navigate(`/jobs?open=${thread.jobCandidates[0].jobApplicationId}`)}>
Open top job
</Button>
) : null}
{thread.jobCandidates[0] ? (
<Button
size="small"
variant="contained"
disabled={savingThreadId === thread.threadId}
onClick={() => void saveDecision(thread.threadId, "linked", thread.jobCandidates[0].jobApplicationId)}
>
Link top job
</Button>
) : null}
<Button
size="small"
variant="outlined"
color="warning"
disabled={savingThreadId === thread.threadId}
onClick={() => void saveDecision(thread.threadId, "review")}
>
Keep in review
</Button>
<Button
size="small"
variant="outlined"
color="secondary"
disabled={savingThreadId === thread.threadId}
onClick={() => void saveDecision(thread.threadId, "suggested")}
>
Suggested job
</Button>
{suggestion ? (
<Button
size="small"
variant="outlined"
disabled={creatingThreadId === thread.threadId}
onClick={() => void createSuggestedJob(thread.threadId)}
>
{creatingThreadId === thread.threadId ? "Creating..." : "Create job"}
</Button>
) : null}
<Button
size="small"
variant="outlined"
color="error"
disabled={savingThreadId === thread.threadId}
onClick={() => void saveDecision(thread.threadId, "rejected")}
>
Reject
</Button>
</Box>
</Box>
</Paper>
);
})}
</Stack>
</Paper>
);
}
+263
View File
@@ -0,0 +1,263 @@
import React, { useEffect, useState } from "react";
import { Box, Button, Container, Stack, Typography } from "@mui/material";
import { alpha } from "@mui/material/styles";
import { useLocation, useNavigate } from "react-router-dom";
import DashboardIcon from "@mui/icons-material/SpaceDashboardOutlined";
import AlarmIcon from "@mui/icons-material/NotificationsActiveOutlined";
import MatchIcon from "@mui/icons-material/FactCheckOutlined";
import MailIcon from "@mui/icons-material/MarkEmailReadOutlined";
import AttachIcon from "@mui/icons-material/DescriptionOutlined";
import InsightsIcon from "@mui/icons-material/InsightsOutlined";
import { api } from "../api";
const BRAND_DARK = "#0b1020";
const BRAND_PANEL = "#111a33";
const FEATURES: { icon: React.ReactNode; title: string; body: string }[] = [
{ icon: <DashboardIcon />, title: "Centralized pipeline", body: "Track every application across Applied, Waiting, Interview, Offer, Rejected and Ghosted — drag to update." },
{ icon: <AlarmIcon />, title: "Smart follow-ups", body: "Reminders surface what needs attention next, with a grounded draft ready to review and send." },
{ icon: <MatchIcon />, title: "Honest CV match", body: "A deterministic keyword-coverage score with matched vs missing skills — not an opaque black box." },
{ icon: <MailIcon />, title: "Email correspondence", body: "Link Gmail threads to a job; new replies appear automatically without re-importing." },
{ icon: <AttachIcon />, title: "Attachments & docs", body: "Keep resumes, cover letters and portfolios versioned per application, right where you need them." },
{ icon: <InsightsIcon />, title: "Dashboard & insights", body: "Response rates, funnel, time-in-stage and skill demand across your whole search." },
];
const STEPS: { n: number; title: string; body: string }[] = [
{ n: 1, title: "Import", body: "Paste a job URL or use the bookmarklet — we parse the role into structured fields." },
{ n: 2, title: "Match", body: "See how your CV covers the role: matched keywords and the gaps to close." },
{ n: 3, title: "Tailor", body: "AI drafts a tailored CV and cover letter — you review every word before it goes out." },
{ n: 4, title: "Track", body: "Move it through the pipeline; documents, notes and history stay attached." },
{ n: 5, title: "Follow up", body: "Linked email threads and reminders keep momentum with grounded replies." },
{ n: 6, title: "Analyze", body: "See what's working — response rate, funnel and time-in-stage — and focus your effort." },
];
const PRICING: { name: string; price: string; cadence: string; highlight: boolean; features: string[]; cta: string }[] = [
{ name: "Free", price: "£0", cadence: "forever", highlight: false, cta: "Get started", features: ["Unlimited job tracking & pipeline", "One-click capture (bookmarklet + PWA)", "Deterministic CV↔job match score", "3 AI CV tailors / month"] },
{ name: "Pro", price: "£9", cadence: "/ month · billed monthly or yearly", highlight: true, cta: "Start Pro", features: ["Everything in Free", "Unlimited AI CV & cover-letter tailoring", "CV versions + factuality guardrail", "Gmail correspondence CRM", "Analytics drill-downs"] },
{ name: "Bring your own key", price: "£3", cadence: "/ month + your AI key", highlight: false, cta: "Get started", features: ["Everything in Pro", "Use your own Gemini / Groq key", "Unlimited AI at provider cost", "Privacy-first & self-host friendly"] },
];
export default function LandingPage() {
const navigate = useNavigate();
const location = useLocation() as { state?: { from?: string } };
const [checking, setChecking] = useState(true);
// If the visitor already has a session, send them straight into the app.
useEffect(() => {
let active = true;
api
.get("/auth/me")
.then(() => { if (active) navigate("/jobs", { replace: true }); })
.catch(() => { if (active) setChecking(false); });
return () => { active = false; };
}, [navigate]);
// A protected route redirects unauthenticated visitors here with the page they
// wanted in location state; forward it to /login so sign-in returns them there
// instead of dropping them on /jobs.
const goToLogin = () => navigate("/login", { state: location.state });
if (checking) {
return (
<Box sx={{ minHeight: "100vh", display: "grid", placeItems: "center", bgcolor: BRAND_DARK }}>
<Typography sx={{ color: "#94a3b8" }}>Loading…</Typography>
</Box>
);
}
const gradientText = {
background: "linear-gradient(90deg,#6366f1,#22d3ee)",
WebkitBackgroundClip: "text",
WebkitTextFillColor: "transparent",
} as const;
return (
<Box sx={{ bgcolor: "background.default" }}>
{/* Top bar */}
<Box sx={{ position: "sticky", top: 0, zIndex: 10, bgcolor: alpha(BRAND_DARK, 0.85), backdropFilter: "blur(8px)", borderBottom: `1px solid ${alpha("#ffffff", 0.08)}` }}>
<Container maxWidth="lg">
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ height: 64 }}>
<Stack direction="row" alignItems="center" spacing={1.25}>
<Box sx={{ width: 30, height: 30, borderRadius: "8px", background: "linear-gradient(135deg,#6366f1,#22d3ee)", display: "grid", placeItems: "center", color: BRAND_DARK, fontWeight: 900 }}>✓</Box>
<Typography sx={{ color: "#fff", fontWeight: 800, fontSize: 20 }}>JobTrack</Typography>
</Stack>
<Button variant="contained" onClick={goToLogin} sx={{ background: "linear-gradient(90deg,#6366f1,#22d3ee)", color: "#0b1020", fontWeight: 700 }}>
Sign in
</Button>
</Stack>
</Container>
</Box>
{/* Hero */}
<Box sx={{ background: `radial-gradient(1200px 500px at 80% -10%, ${alpha("#6366f1", 0.35)}, transparent), linear-gradient(180deg, ${BRAND_DARK}, ${BRAND_PANEL})`, color: "#fff", py: { xs: 8, md: 12 } }}>
<Container maxWidth="lg">
<Box sx={{ maxWidth: 760 }}>
<Box sx={{ display: "inline-block", px: 1.5, py: 0.5, borderRadius: 999, bgcolor: alpha("#ffffff", 0.08), color: "#a5b4fc", fontSize: 13, fontWeight: 600, letterSpacing: 0.5, mb: 3 }}>
AI-ASSISTED JOB SEARCH WORKSPACE
</Box>
<Typography component="h1" sx={{ fontWeight: 800, fontSize: { xs: 40, md: 60 }, lineHeight: 1.05, mb: 2 }}>
Run your job search without losing <Box component="span" sx={gradientText}>the thread</Box>.
</Typography>
<Typography sx={{ color: "#94a3b8", fontSize: { xs: 17, md: 20 }, mb: 4 }}>
Import a role, tailor your CV, track every application, and keep recruiter correspondence tied to the
right job — all in one focused workspace. Assistive, never autonomous: you approve every draft.
</Typography>
<Stack direction={{ xs: "column", sm: "row" }} spacing={2}>
<Button size="large" variant="contained" onClick={goToLogin} sx={{ background: "linear-gradient(90deg,#6366f1,#22d3ee)", color: "#0b1020", fontWeight: 800, px: 4, py: 1.25 }}>
Get started
</Button>
<Button size="large" variant="outlined" href="#features" sx={{ color: "#e2e8f0", borderColor: alpha("#ffffff", 0.25), px: 3, py: 1.25 }}>
See features
</Button>
</Stack>
<Typography sx={{ color: "#64748b", fontSize: 14, mt: 3 }}>
React · TypeScript · ASP.NET Core · EF Core · FastAPI AI · Gmail
</Typography>
</Box>
</Container>
</Box>
{/* Product preview */}
<Container maxWidth="lg" sx={{ py: { xs: 6, md: 9 } }}>
<Box sx={{ textAlign: "center", mb: 5 }}>
<Typography sx={{ color: "primary.main", fontWeight: 700, letterSpacing: 1, fontSize: 13 }}>SEE IT IN ACTION</Typography>
<Typography component="h2" sx={{ fontWeight: 800, fontSize: { xs: 26, md: 34 }, mt: 1 }}>Your whole search, at a glance</Typography>
</Box>
<Box sx={{ borderRadius: 3, overflow: "hidden", border: "1px solid", borderColor: "divider", boxShadow: 10, mb: 3, bgcolor: "background.paper" }}>
<Box component="img" src="/mockups/dashboard.svg" alt="JobTrack dashboard — KPIs, funnel, response trend and follow-ups" sx={{ width: "100%", display: "block" }} />
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 3 }}>
<Box sx={{ borderRadius: 3, overflow: "hidden", border: "1px solid", borderColor: "divider", boxShadow: 6, bgcolor: "background.paper" }}>
<Box component="img" src="/mockups/pipeline.svg" alt="Drag-and-drop pipeline board" sx={{ width: "100%", display: "block" }} />
</Box>
<Box sx={{ borderRadius: 3, overflow: "hidden", border: "1px solid", borderColor: "divider", boxShadow: 6, bgcolor: "background.paper" }}>
<Box component="img" src="/mockups/workspace.svg" alt="Per-job workspace with match score, correspondence and attachments" sx={{ width: "100%", display: "block" }} />
</Box>
</Box>
<Typography sx={{ textAlign: "center", color: "text.secondary", fontSize: 13, mt: 2 }}>Interface preview.</Typography>
</Container>
{/* Features */}
<Container id="features" maxWidth="lg" sx={{ py: { xs: 7, md: 10 } }}>
<Box sx={{ textAlign: "center", mb: 6 }}>
<Typography sx={{ color: "primary.main", fontWeight: 700, letterSpacing: 1, fontSize: 13 }}>WHAT IT DOES</Typography>
<Typography component="h2" sx={{ fontWeight: 800, fontSize: { xs: 28, md: 38 }, mt: 1 }}>One workspace for the whole search</Typography>
<Typography sx={{ color: "text.secondary", fontSize: 18, mt: 1.5 }}>
Everything from a single import to the final offer — no more spreadsheets and scattered inboxes.
</Typography>
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr", md: "1fr 1fr 1fr" }, gap: 3 }}>
{FEATURES.map((f) => (
<Box key={f.title} sx={{ p: 3, borderRadius: 3, border: "1px solid", borderColor: "divider", bgcolor: "background.paper", transition: "box-shadow .2s, transform .2s", "&:hover": { boxShadow: 6, transform: "translateY(-2px)" } }}>
<Box sx={{ width: 48, height: 48, borderRadius: 2.5, display: "grid", placeItems: "center", bgcolor: alpha("#6366f1", 0.12), color: "primary.main", mb: 2 }}>{f.icon}</Box>
<Typography sx={{ fontWeight: 700, fontSize: 19, mb: 0.75 }}>{f.title}</Typography>
<Typography sx={{ color: "text.secondary", fontSize: 15 }}>{f.body}</Typography>
</Box>
))}
</Box>
</Container>
{/* How it works */}
<Box sx={{ background: `linear-gradient(180deg, ${BRAND_DARK}, ${BRAND_PANEL})`, color: "#fff", py: { xs: 7, md: 10 } }}>
<Container maxWidth="lg">
<Box sx={{ textAlign: "center", mb: 6 }}>
<Typography sx={{ color: "#a5b4fc", fontWeight: 700, letterSpacing: 1, fontSize: 13 }}>HOW IT WORKS</Typography>
<Typography component="h2" sx={{ fontWeight: 800, fontSize: { xs: 28, md: 38 }, mt: 1 }}>From a link to an offer</Typography>
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr", md: "1fr 1fr 1fr" }, gap: 3 }}>
{STEPS.map((s) => (
<Box key={s.n} sx={{ p: 3, borderRadius: 3, border: `1px solid ${alpha("#ffffff", 0.1)}`, bgcolor: alpha("#ffffff", 0.03) }}>
<Box sx={{ width: 40, height: 40, borderRadius: 999, display: "grid", placeItems: "center", background: "linear-gradient(135deg,#6366f1,#22d3ee)", color: "#0b1020", fontWeight: 900, mb: 1.5 }}>{s.n}</Box>
<Typography sx={{ fontWeight: 700, fontSize: 18, mb: 0.5 }}>{s.title}</Typography>
<Typography sx={{ color: "#94a3b8", fontSize: 15 }}>{s.body}</Typography>
</Box>
))}
</Box>
</Container>
</Box>
{/* Pricing */}
<Container id="pricing" maxWidth="lg" sx={{ py: { xs: 7, md: 10 } }}>
<Box sx={{ textAlign: "center", mb: 6 }}>
<Typography sx={{ color: "primary.main", fontWeight: 700, letterSpacing: 1, fontSize: 13 }}>PRICING</Typography>
<Typography component="h2" sx={{ fontWeight: 800, fontSize: { xs: 28, md: 38 }, mt: 1 }}>Honest, simple pricing</Typography>
<Typography sx={{ color: "text.secondary", fontSize: 18, mt: 1.5 }}>
Billed monthly or yearly — never by the week. Cancel anytime.
</Typography>
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "repeat(3, 1fr)" }, gap: 3, alignItems: "start" }}>
{PRICING.map((tier) => (
<Box
key={tier.name}
sx={{
p: 3.5,
borderRadius: 3,
position: "relative",
bgcolor: "background.paper",
border: "2px solid",
borderColor: tier.highlight ? "primary.main" : "divider",
boxShadow: tier.highlight ? 8 : 0,
}}
>
{tier.highlight && (
<Box sx={{ position: "absolute", top: -13, left: 24, px: 1.5, py: 0.5, borderRadius: 999, background: "linear-gradient(90deg,#6366f1,#22d3ee)", color: "#0b1020", fontSize: 12, fontWeight: 800 }}>
Most popular
</Box>
)}
<Typography sx={{ fontWeight: 700, fontSize: 18 }}>{tier.name}</Typography>
<Stack direction="row" alignItems="baseline" spacing={0.75} sx={{ my: 1.5 }}>
<Typography sx={{ fontWeight: 900, fontSize: 40, lineHeight: 1 }}>{tier.price}</Typography>
<Typography sx={{ color: "text.secondary", fontSize: 14 }}>{tier.cadence}</Typography>
</Stack>
<Stack spacing={1.25} sx={{ my: 2.5 }}>
{tier.features.map((f) => (
<Stack key={f} direction="row" spacing={1.25} alignItems="flex-start">
<Box sx={{ color: "success.main", fontWeight: 900, lineHeight: 1.4 }}>✓</Box>
<Typography sx={{ fontSize: 15, color: "text.secondary" }}>{f}</Typography>
</Stack>
))}
</Stack>
<Button
fullWidth
variant={tier.highlight ? "contained" : "outlined"}
onClick={goToLogin}
sx={tier.highlight ? { background: "linear-gradient(90deg,#6366f1,#22d3ee)", color: "#0b1020", fontWeight: 800 } : { fontWeight: 700 }}
>
{tier.cta}
</Button>
</Box>
))}
</Box>
<Typography sx={{ textAlign: "center", color: "text.secondary", fontSize: 13, mt: 3 }}>
Prices indicative — assistive, never autonomous: you always review and send. No auto-apply spam.
</Typography>
</Container>
{/* CTA */}
<Container maxWidth="lg" sx={{ py: { xs: 7, md: 10 } }}>
<Box sx={{ borderRadius: 4, p: { xs: 4, md: 6 }, background: "linear-gradient(120deg,#0f172a,#1e293b)", color: "#fff", display: "flex", flexDirection: { xs: "column", md: "row" }, alignItems: { md: "center" }, justifyContent: "space-between", gap: 3 }}>
<Box>
<Typography sx={{ fontWeight: 800, fontSize: { xs: 24, md: 30 }, mb: 1 }}>Ready to organize your search?</Typography>
<Typography sx={{ color: "#94a3b8", fontSize: 17 }}>Sign in to start tracking applications, tailoring CVs, and following up with intent.</Typography>
</Box>
<Button size="large" variant="contained" onClick={goToLogin} sx={{ background: "linear-gradient(90deg,#6366f1,#22d3ee)", color: "#0b1020", fontWeight: 800, px: 4, py: 1.25, whiteSpace: "nowrap" }}>
Sign in →
</Button>
</Box>
</Container>
{/* Footer */}
<Box sx={{ borderTop: "1px solid", borderColor: "divider", py: 4 }}>
<Container maxWidth="lg">
<Stack direction={{ xs: "column", sm: "row" }} justifyContent="space-between" alignItems="center" spacing={1}>
<Typography sx={{ color: "text.secondary", fontSize: 14 }}>© {new Date().getFullYear()} JobTrack — a focused workspace for the modern job search.</Typography>
<Button variant="text" onClick={goToLogin} sx={{ fontWeight: 700 }}>Sign in</Button>
</Stack>
</Container>
</Box>
</Box>
);
}
+129
View File
@@ -0,0 +1,129 @@
import React, { useEffect, useState } from "react";
import { Box, Button, Checkbox, FormControlLabel, Paper, Tab, Tabs, TextField, Typography } from "@mui/material";
import { useLocation, useNavigate } from "react-router-dom";
import { api, getApiErrorMessage } from "../api";
import { getRememberMePref, setAuthPersistencePreference } from "../auth";
import GoogleAuthCard from "../components/GoogleAuthCard";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
type AuthConfig = {
requireAuth: boolean;
googleEnabled: boolean;
localEnabled: boolean;
allowRegistration: boolean;
};
export default function LoginPage() {
const { toast } = useToast();
const { t } = useI18n();
const navigate = useNavigate();
const location = useLocation() as any;
const [tab, setTab] = useState(0);
const [cfg, setCfg] = useState<AuthConfig | null>(null);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [rememberMe, setRememberMe] = useState(() => getRememberMePref());
const [loading, setLoading] = useState(false);
const nextPath = (location?.state?.from as string | undefined) ?? "/jobs";
useEffect(() => {
api
.get<AuthConfig>("/auth/config")
.then((r) => setCfg(r.data))
.catch(() => setCfg(null));
}, []);
async function submit(mode: "login" | "register") {
setLoading(true);
try {
const url = mode === "register" ? "/auth/register" : "/auth/login";
await api.post(url, { email, password, rememberMe });
setAuthPersistencePreference(rememberMe ? "local" : "session");
await api.get("/auth/me");
toast(t("signedIn"), "success");
navigate(nextPath, { replace: true });
} catch (e: any) {
toast(getApiErrorMessage(e, t("loginFailed")), "error");
} finally {
setLoading(false);
}
}
const allowReg = cfg?.allowRegistration ?? false;
return (
<Box
sx={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
background:
"radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
}}
>
<Paper sx={{ width: "min(520px, 100%)", p: 3 }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{t("signInTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{cfg?.requireAuth ? t("authRequired") : t("authOptional")}
</Typography>
<Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 2 }}>
<Tab label={t("emailAndPassword")} />
<Tab label={t("google")} />
</Tabs>
{tab === 0 && (
<Box component="form" onSubmit={(e) => { e.preventDefault(); void submit("login"); }} sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
<TextField label={t("profileEmail")} value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" fullWidth />
<TextField label={t("profileCurrentPassword")} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete={allowReg ? "new-password" : "current-password"} type="password" fullWidth />
<Box sx={{ display: "flex", alignItems: { xs: "flex-start", sm: "center" }, justifyContent: "space-between", gap: 1, flexWrap: "wrap" }}>
<FormControlLabel
control={<Checkbox disableRipple checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} />}
label={t("rememberMe")}
/>
<Button
type="button"
variant="text"
size="small"
disableRipple
onClick={() => navigate(`/forgot-password${email.trim() ? `?email=${encodeURIComponent(email.trim())}` : ""}`)}
sx={{ px: 0, minWidth: 0, fontWeight: 700, alignSelf: { xs: "stretch", sm: "auto" } }}
>
{t("forgotPassword")}
</Button>
</Box>
<Typography variant="body2" sx={{ color: "text.secondary", mt: -0.5 }}>
{rememberMe ? t("rememberMeHelpPersistent") : t("rememberMeHelpSession")}
</Typography>
<Box sx={{ display: "flex", gap: 1, justifyContent: "flex-end", mt: 1 }}>
{allowReg && (
<Button type="button" variant="outlined" disableRipple disabled={loading} onClick={() => void submit("register")}>
{t("createAccount")}
</Button>
)}
<Button type="submit" variant="contained" disableRipple disabled={loading}>
{t("signInTitle")}
</Button>
</Box>
</Box>
)}
{tab === 1 && <GoogleAuthCard onSignedIn={() => { navigate(nextPath, { replace: true }); }} />}
</Paper>
</Box>
);
}
+33
View File
@@ -0,0 +1,33 @@
import React from "react";
import { Box, Button, Paper, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { useI18n } from "../i18n/I18nProvider";
export default function NotFoundPage() {
const navigate = useNavigate();
const { t } = useI18n();
return (
<Paper sx={{ p: { xs: 3, md: 5 }, borderRadius: 4 }}>
<Box sx={{ display: "grid", gap: 1.5, maxWidth: 560 }}>
<Typography variant="overline" sx={{ color: "text.secondary", letterSpacing: 1.6 }}>
404
</Typography>
<Typography variant="h4" sx={{ fontWeight: 800 }}>
{t("notFoundTitle")}
</Typography>
<Typography sx={{ color: "text.secondary" }}>
{t("notFoundBody")}
</Typography>
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mt: 1 }}>
<Button variant="contained" onClick={() => navigate("/jobs")}>
{t("goHome")}
</Button>
<Button variant="outlined" onClick={() => navigate(-1)}>
{t("goBack")}
</Button>
</Box>
</Box>
</Paper>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,88 @@
import React, { useEffect, useState } from "react";
import { Alert, Box, Button, Paper, TextField, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { api } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
export default function ResetPasswordPage() {
const { toast } = useToast();
const { t } = useI18n();
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [token, setToken] = useState("");
const [newPassword, setNewPassword] = useState("");
const [loading, setLoading] = useState(false);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
setEmail(params.get("email") || "");
setToken(params.get("token") || "");
}, []);
const missingResetInfo = !email || !token;
return (
<Box
sx={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
background:
"radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
}}
>
<Paper sx={{ width: "min(520px, 100%)", p: 3 }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{t("resetPasswordTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{t("resetPasswordBody")}
</Typography>
<Box
component="form"
onSubmit={(e) => {
e.preventDefault();
if (missingResetInfo) {
toast(t("missingResetLinkInfo"), "error");
return;
}
setLoading(true);
api
.post("/auth/reset-password", { email, token, newPassword })
.then(() => {
toast(t("passwordResetSuccess"), "success");
navigate("/login", { replace: true });
})
.catch((e2: any) => {
const msg = e2?.response?.data || e2?.message || t("resetFailed");
toast(String(msg), "error");
})
.finally(() => setLoading(false));
}}
sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
>
{missingResetInfo ? <Alert severity="warning">{t("missingResetLinkInfo")}</Alert> : null}
<TextField label={t("profileEmail")} value={email} onChange={(e) => setEmail(e.target.value)} disabled={!missingResetInfo} fullWidth />
<TextField label={t("profileNewPassword")} type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} fullWidth />
<Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1, mt: 1 }}>
<Button type="button" variant="outlined" onClick={() => navigate("/login")} disabled={loading}>
{t("backToLogin")}
</Button>
<Button type="submit" variant="contained" disabled={loading || missingResetInfo}>
{t("updatePassword")}
</Button>
</Box>
</Box>
</Paper>
</Box>
);
}
@@ -0,0 +1,43 @@
import React from "react";
import { Box, Button, Paper, Typography } from "@mui/material";
import { useNavigate, useRouteError } from "react-router-dom";
import { useI18n } from "../i18n/I18nProvider";
export default function RouteErrorPage() {
const navigate = useNavigate();
const error = useRouteError() as any;
const { t } = useI18n();
const details = typeof error?.statusText === "string" && error.statusText.trim()
? error.statusText
: typeof error?.message === "string" && error.message.trim()
? error.message
: null;
return (
<Box sx={{ minHeight: "100vh", display: "grid", placeItems: "center", p: 3 }}>
<Paper sx={{ p: { xs: 3, md: 5 }, borderRadius: 4, width: "100%", maxWidth: 640 }}>
<Box sx={{ display: "grid", gap: 1.5 }}>
<Typography variant="overline" sx={{ color: "text.secondary", letterSpacing: 1.6 }}>
{error?.status || 500}
</Typography>
<Typography variant="h4" sx={{ fontWeight: 800 }}>
{t("appErrorTitle")}
</Typography>
<Typography sx={{ color: "text.secondary" }}>
{t("appErrorBody")}
</Typography>
{details ? <Typography sx={{ color: "text.secondary" }}>{details}</Typography> : null}
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mt: 1 }}>
<Button variant="contained" onClick={() => navigate("/jobs")}>
{t("goHome")}
</Button>
<Button variant="outlined" onClick={() => navigate(-1)}>
{t("goBack")}
</Button>
</Box>
</Box>
</Paper>
</Box>
);
}