feat(admin): migrate system diagnostics and retain SMTP drafts
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
import AxeBuilder from '@axe-core/playwright';
|
||||
import { expect, test as base, type APIRequestContext, type APIResponse, type Locator, type Page, type TestInfo } from '@playwright/test';
|
||||
import { translations } from '../src/i18n/translations';
|
||||
|
||||
const apiUrl = 'http://localhost:5302/api';
|
||||
const password = 'E2ePassword123!';
|
||||
type Language = 'en' | 'nb';
|
||||
type Headers = Record<string, string>;
|
||||
type Owner = { id: string; email: string; headers: Headers };
|
||||
type RequestRecord = { channel: 'browser' | 'api'; method: string; path: string; query: string; status?: number };
|
||||
type Session = { owner: Owner; admin: APIRequestContext; adminHeaders: Headers; requests: RequestRecord[] };
|
||||
const boundary = 'Actual isolated Identity/CSRF login and non-admin GET denials; administrator System GET diagnostics and SMTP PUT acknowledgements are controlled browser fixtures. No actual SMTP delivery/configuration, AI probe/model calls, maintenance dispatch or production writes. Six paired language/theme widths and automated axe do not establish human/device acceptance.';
|
||||
function copy(key: string, language: Language = 'en') { return (translations[language] as Record<string, string>)[key] ?? key; }
|
||||
function browserRequests(session: Session, path: string, method?: string) { return session.requests.filter(value => value.channel === 'browser' && value.path === `/api${path}` && (!method || value.method === method)); }
|
||||
async function call(records: RequestRecord[], api: APIRequestContext, method: 'GET' | 'POST' | 'PUT', path: string, headers?: Headers, data?: unknown) {
|
||||
const result = await api.fetch(`${apiUrl}${path}`, { method, headers, data });
|
||||
const url = new URL(result.url()); records.push({ channel: 'api', method, path: url.pathname, query: url.search, status: result.status() }); return result;
|
||||
}
|
||||
async function json<T>(response: Pick<APIResponse, 'status' | 'url' | 'json'>, status = 200): Promise<T> { expect(response.status(), response.url()).toBe(status); return response.json(); }
|
||||
async function login(records: RequestRecord[], api: APIRequestContext, email: string): Promise<Owner> {
|
||||
expect((await call(records, api, 'POST', '/auth/login', undefined, { email, password })).status()).toBe(200);
|
||||
const me = await json<{ id: string; sessionContext: string }>(await call(records, api, 'GET', '/auth/me'));
|
||||
const token = (await api.storageState()).cookies.find(value => value.name === 'XSRF-TOKEN'); expect(token).toBeDefined();
|
||||
return { id: me.id, email, headers: { 'X-CSRF-TOKEN': token!.value, 'X-Session-Context': me.sessionContext } };
|
||||
}
|
||||
async function createOwner(records: RequestRecord[], admin: APIRequestContext, headers: Headers) {
|
||||
const email = `p710-system-${Date.now()}-${Math.random().toString(36).slice(2)}@example.test`;
|
||||
expect((await call(records, admin, 'POST', '/users', headers, { email, password, roles: [] })).status()).toBe(200); return email;
|
||||
}
|
||||
const test = base.extend<{ session: Session }>({
|
||||
session: async ({ page, context, playwright }, provide, info) => {
|
||||
expect(process.env.PLAYWRIGHT_REUSE_SERVERS).not.toBe('true'); expect(info.config.metadata.isolatedDataRoot).toEqual(expect.any(String));
|
||||
const records: RequestRecord[] = []; const forbidden: string[] = []; const fonts: string[] = []; const admin = await playwright.request.newContext();
|
||||
context.on('request', request => { const url = new URL(request.url()); records.push({ channel: 'browser', method: request.method(), path: url.pathname, query: url.search }); });
|
||||
context.on('response', result => { const url = new URL(result.url()); const record = [...records].reverse().find(value => value.channel === 'browser' && value.status === undefined && value.method === result.request().method() && value.path === url.pathname && value.query === url.search); if (record) record.status = result.status(); });
|
||||
await context.route('**/*', route => {
|
||||
const request = route.request(); const url = new URL(request.url());
|
||||
if (url.protocol === 'https:' && url.hostname === 'fonts.googleapis.com' && url.port === '' && url.pathname === '/css2' && request.method() === 'GET' && request.resourceType() === 'stylesheet') { fonts.push(url.href); return route.abort(); }
|
||||
const mailbox = /^\/api\/(gmail|microsoft-graph|imap)(?:\/|$)/.test(url.pathname);
|
||||
const statusRead = request.method() === 'GET' && /^\/api\/(gmail|microsoft-graph|imap)\/status$/.test(url.pathname);
|
||||
const ai = /^\/api\/ai(?:\/|$)/.test(url.pathname); const accountAiRead = request.method() === 'GET' && ['/api/ai/settings', '/api/ai/usage'].includes(url.pathname) || request.method() === 'PUT' && url.pathname === '/api/ai/settings';
|
||||
if (mailbox && !statusRead || ai && !accountAiRead || /\/api\/(?:email\/send|billing\/(?:checkout|portal)|account-lifecycle\/delete|backup\/restore)(?:\/|$)/.test(url.pathname) || !['blob:', 'data:', 'about:'].includes(url.protocol) && (!['localhost', '127.0.0.1'].includes(url.hostname) || !['3300', '5302'].includes(url.port))) { forbidden.push(`${request.method()} ${url.origin}${url.pathname}`); return route.abort(); }
|
||||
if (url.pathname.startsWith('/api/admin/system')) { forbidden.push(`${request.method()} ${url.pathname}`); return route.abort(); }
|
||||
return route.continue();
|
||||
});
|
||||
await context.addInitScript(() => { if (!localStorage.getItem('uiLanguage')) localStorage.setItem('uiLanguage', 'en'); if (!localStorage.getItem('jobtracker.themeMode')) localStorage.setItem('jobtracker.themeMode', 'light'); });
|
||||
try {
|
||||
const administrator = await login(records, admin, 'e2e@example.test'); const email = await createOwner(records, admin, administrator.headers); const owner = await login(records, page.request, email);
|
||||
expect((await json<{ entitlements: { ai: boolean } }>(await call(records, page.request, 'GET', '/auth/me'))).entitlements.ai).toBe(false);
|
||||
await provide({ owner, admin, adminHeaders: administrator.headers, requests: records }); expect(forbidden).toEqual([]);
|
||||
} finally { await info.attach('settings-preferences-boundary-and-requests', { body: JSON.stringify({ boundary, requests: records, forbiddenRequests: forbidden, abortedFontStylesheets: fonts }), contentType: 'application/json' }); await admin.dispose(); }
|
||||
},
|
||||
});
|
||||
async function start(page: Page, path = '/settings', width = 1440) { await page.setViewportSize({ width, height: width < 768 ? 844 : 900 }); await page.emulateMedia({ reducedMotion: 'reduce' }); await page.goto(path); await expect(page.getByRole('main').getByRole('heading', { level: 1 })).toBeVisible(); }
|
||||
async function keyboard(control: Locator) { await expect(control).toBeVisible(); await expect(control).toBeEnabled(); await control.focus(); await expect(control).toBeFocused(); await control.press('Enter'); }
|
||||
async function capture(page: Page, info: TestInfo, name: string) {
|
||||
const geometry = await page.getByRole('main').evaluate(main => {
|
||||
const bounds = main.getBoundingClientRect(); const targets = Array.from(main.querySelectorAll('h1,h2,h3,p,button,input,[role="combobox"],[role="status"],.MuiFormControlLabel-root'));
|
||||
// MUI Switch uses a transparent 300%-wide native input; its painted label/control remains in the checked targets.
|
||||
// System diagnostics wrap within the page; no document canvas exception applies.
|
||||
return { width: innerWidth, rootOverflow: document.documentElement.scrollWidth - document.documentElement.clientWidth, outside: targets.filter(node => !node.closest('table') && node.getClientRects().length && getComputedStyle(node).visibility !== 'hidden' && !(node instanceof HTMLInputElement && getComputedStyle(node).opacity === '0')).map(node => ({ text: node.textContent?.slice(0, 90), left: node.getBoundingClientRect().left, right: node.getBoundingClientRect().right })).filter(rect => rect.left < bounds.left - 1 || rect.right > Math.min(bounds.right, innerWidth) + 1) };
|
||||
});
|
||||
await info.attach(`${name}-reflow`, { body: JSON.stringify(geometry), contentType: 'application/json' }); expect(geometry.rootOverflow).toBeLessThanOrEqual(1); expect(geometry.outside).toEqual([]);
|
||||
await info.attach(name, { body: await page.screenshot({ fullPage: true, animations: 'disabled' }), contentType: 'image/png' });
|
||||
const axe = await new AxeBuilder({ page }).analyze(); await info.attach(`${name}-axe`, { body: JSON.stringify({ violations: axe.violations, incomplete: axe.incomplete, qualification: 'All enabled axe rules; raw incomplete contexts retained for root triage, not human screen-reader acceptance.' }), contentType: 'application/json' }); expect(axe.violations).toEqual([]);
|
||||
}
|
||||
|
||||
function response(page: Page, method: string, path: string) { return page.waitForResponse(value => value.request().method()===method && new URL(value.url()).pathname===`/api${path}`); }
|
||||
|
||||
const smtp = { enabled: true, host: 'smtp.example.test', port: 587, user: 'mailer@example.test', from: 'noreply@example.test', fromName: 'Jobbjakt', enableSsl: true, timeoutMs: 15000, usesOverrides: false, hasPassword: true };
|
||||
const status = {
|
||||
environment: 'Controlled fixture', contentRoot: '/app', version: '1.2.3', commitSha: 'abc1234', buildStamp: '2026-10-20 UTC',
|
||||
storage: { dataRoot: '/data', dbPath: '/data/jobtracker.db', dbExists: true, dbSizeBytes: 2048, companyCount: 3, jobCount: 7, deletedCount: 1 },
|
||||
email: smtp, database: { provider: 'mariadb', looksConfigured: true, canConnect: true, target: 'server=db', usesFileStorage: false, warning: null },
|
||||
runtime: { framework: '.NET 9', osDescription: 'Linux', processArchitecture: 'X64', machineName: 'fixture' }, auth: { required: true, hasJwtKey: true, googleConfigured: false, gmailConfigured: false },
|
||||
ai: { healthy: true, model: 'fixture-only', device: 'cpu', gpuAvailable: false, ocrAvailable: true, ocrLanguages: 'eng', ollamaConfigured: false, requests: 18, cacheHits: 9, cacheMisses: 9, failures: 0, probeFailures: 0, averageLatencyMs: 42.2, ocrRequests: 5, ocrFailures: 0, averageOcrLatencyMs: 88.4 }
|
||||
};
|
||||
async function fixtures(page: Page, failStatus: () => boolean = () => false) {
|
||||
await page.route('**/api/admin/system**', route => {
|
||||
const request=route.request(); const path=new URL(request.url()).pathname;
|
||||
expect(request.method()).toBe('GET');
|
||||
if (path==='/api/admin/system' && failStatus()) return route.fulfill({ status:503, json: { title:'Unavailable' } });
|
||||
const data=path.endsWith('/email-settings') ? smtp : path.endsWith('/maintenance-jobs') ? [] : path.endsWith('/cv-benchmark') ? { rootPath:'/data/fixture', indexJson:null, reportMarkdown:'Controlled benchmark report', lastUpdatedAtUtc:null } : status;
|
||||
return route.fulfill({ status:200, json:data });
|
||||
});
|
||||
}
|
||||
|
||||
test('[P7-10 System A03 E09] non-admin read denial and controlled initial failure retain GET-only focused recovery', async ({ page, session }) => {
|
||||
for (const path of ['/admin/system','/admin/system/email-settings','/admin/system/cv-benchmark','/admin/system/maintenance-jobs']) expect((await call(session.requests,page.request,'GET',path)).status()).toBe(403);
|
||||
await login(session.requests,page.request,'e2e@example.test'); let failed=true; await fixtures(page,()=>failed);
|
||||
await start(page,'/admin/system',390);
|
||||
const alert=page.getByRole('alert').filter({ hasText:'Unavailable' }); await expect(alert).toBeVisible();
|
||||
await expect(page.getByText(copy('adminSystemOffline'), { exact:true })).toHaveCount(0);
|
||||
failed=false; const count=browserRequests(session,'/admin/system').length;
|
||||
await keyboard(alert.getByRole('button',{name:copy('retry'),exact:true})); await expect(page.getByText('Controlled fixture',{exact:true})).toBeVisible();
|
||||
expect(browserRequests(session,'/admin/system').length).toBe(count+1);
|
||||
expect(session.requests.filter(value=>value.channel==='browser' && value.method!=='GET')).toEqual([]);
|
||||
await capture(page,test.info(),'system-status-read-recovery-390-en-light');
|
||||
});
|
||||
|
||||
test('[P7-10 System A03] SMTP submitted acknowledgement preserves newer edits and refresh draft without operational calls', async ({page,session},info) => {
|
||||
await login(session.requests,page.request,'e2e@example.test'); await fixtures(page); await start(page,'/admin/system');
|
||||
await keyboard(page.getByRole('tab',{name:copy('adminSystemSettingsTab'),exact:true}));
|
||||
const panel=page.getByRole('tabpanel',{name:copy('adminSystemSettingsTab'),exact:true}); await expect(panel).toBeVisible();
|
||||
await panel.getByLabel(copy('adminSystemHost'),{exact:true}).fill('submitted.example.test');
|
||||
await panel.getByLabel(copy('adminSystemPassword'),{exact:true}).fill('synthetic-submitted');
|
||||
let release!:()=>void; const held=new Promise<void>(resolve=>{release=resolve;}); let payload:Record<string,unknown>|undefined;
|
||||
await page.route('**/api/admin/system/email-settings',async route=>{ if(route.request().method()!=='PUT') return route.fallback(); payload=route.request().postDataJSON(); await held; return route.fulfill({status:200,json:{...smtp,host:'submitted.example.test',usesOverrides:true}}); });
|
||||
await keyboard(panel.getByRole('button',{name:copy('adminSystemSaveSettings'),exact:true})); await expect.poll(()=>payload?.host).toBe('submitted.example.test');
|
||||
expect(payload?.password).toBe('synthetic-submitted'); expect(payload?.clearPassword).toBe(false);
|
||||
await panel.getByLabel(copy('adminSystemHost'),{exact:true}).fill('newer.example.test'); await panel.getByLabel(copy('adminSystemPassword'),{exact:true}).fill('synthetic-newer');
|
||||
await expect(panel.getByRole('button',{name:copy('adminSystemSendTestEmail'),exact:true})).toBeDisabled(); await expect(page.getByRole('button',{name:copy('adminSystemRefresh'),exact:true})).toBeDisabled();
|
||||
release(); await expect(panel.getByRole('button',{name:copy('adminSystemSaveSettings'),exact:true})).toBeEnabled();
|
||||
await expect(panel.getByLabel(copy('adminSystemHost'),{exact:true})).toHaveValue('newer.example.test'); await expect(panel.getByLabel(copy('adminSystemPassword'),{exact:true})).toHaveValue('synthetic-newer');
|
||||
await expect(panel.getByText(copy('adminSystemUnsavedChanges'),{exact:true})).toBeVisible();
|
||||
await keyboard(page.getByRole('button',{name:copy('adminSystemRefresh'),exact:true})); await expect(page.getByRole('button',{name:copy('adminSystemRefresh'),exact:true})).toBeEnabled();
|
||||
await expect(panel.getByLabel(copy('adminSystemHost'),{exact:true})).toHaveValue('newer.example.test'); await expect(panel.getByLabel(copy('adminSystemPassword'),{exact:true})).toHaveValue('synthetic-newer');
|
||||
expect(session.requests.filter(value=>value.channel==='browser' && value.method!=='GET').map(value=>[value.method,value.path])).toEqual([['PUT','/api/admin/system/email-settings']]);
|
||||
await capture(page,info,'system-newer-smtp-draft-1440-en-light');
|
||||
});
|
||||
|
||||
test('[P7-10 System A03] bilingual diagnostic and settings panels reflow at six finite theme widths',async({page,session},info)=>{
|
||||
const administrator=await login(session.requests,page.request,'e2e@example.test'); await fixtures(page);
|
||||
for(const sample of [{width:320,language:'nb',mode:'dark'},{width:390,language:'en',mode:'light'},{width:768,language:'nb',mode:'light'},{width:1024,language:'en',mode:'dark'},{width:1440,language:'en',mode:'light'},{width:1920,language:'nb',mode:'dark'}] as const){
|
||||
expect((await call(session.requests,page.request,'PUT','/auth/preferences/language',administrator.headers,{language:sample.language==='nb'?'nb-NO':'en'})).status()).toBe(204);
|
||||
await page.addInitScript(value=>{localStorage.setItem('uiLanguage',value.language);localStorage.setItem('jobtracker.themeMode',value.mode);},sample); await start(page,'/admin/system',sample.width); await expect(page.getByText('Controlled fixture',{exact:true})).toBeVisible();
|
||||
await capture(page,info,`system-status-${sample.width}-${sample.language}-${sample.mode}`);
|
||||
await keyboard(page.getByRole('tab',{name:copy('adminSystemSettingsTab',sample.language),exact:true})); await expect(page.getByRole('tabpanel',{name:copy('adminSystemSettingsTab',sample.language),exact:true})).toBeVisible();
|
||||
await capture(page,info,`system-settings-${sample.width}-${sample.language}-${sample.mode}`);
|
||||
}
|
||||
expect(session.requests.filter(value=>value.channel==='browser' && value.method!=='GET')).toEqual([]);
|
||||
});
|
||||
@@ -1,11 +1,15 @@
|
||||
import React from 'react';
|
||||
import '@testing-library/jest-dom';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
|
||||
import AdminSystemPage from './views/AdminSystemPage';
|
||||
import { I18nProvider } from './i18n/I18nProvider';
|
||||
import { api } from './api';
|
||||
|
||||
let mockSessionContext = 'system-owner';
|
||||
let mockSessionInvalidated = false;
|
||||
jest.mock('./sessionBoundary', () => ({ checkSessionCookie: jest.fn(), getSessionContext: () => mockSessionContext, isSessionInvalidated: () => mockSessionInvalidated }));
|
||||
|
||||
jest.mock('./api', () => ({
|
||||
api: {
|
||||
get: jest.fn(),
|
||||
@@ -19,9 +23,11 @@ jest.mock('./api', () => ({
|
||||
}));
|
||||
|
||||
const mockedApi = api as jest.Mocked<typeof api>;
|
||||
function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done; }); return { promise, resolve }; }
|
||||
|
||||
describe('AdminSystemPage', () => {
|
||||
beforeEach(() => {
|
||||
mockSessionContext = 'system-owner'; mockSessionInvalidated = false;
|
||||
window.localStorage.clear();
|
||||
mockedApi.get.mockImplementation((url: string) => {
|
||||
if (url === '/admin/system') {
|
||||
@@ -180,6 +186,223 @@ describe('AdminSystemPage', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('associates each tab with its named panel', async () => {
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
const statusTab = screen.getByRole('tab', { name: 'Status' });
|
||||
const statusPanel = screen.getByRole('tabpanel', { name: 'Status' });
|
||||
expect(statusTab).toHaveAttribute('aria-controls', statusPanel.id);
|
||||
expect(statusPanel).toHaveAttribute('aria-labelledby', statusTab.id);
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
const settingsTab = screen.getByRole('tab', { name: 'Settings' });
|
||||
expect(settingsTab).toHaveAttribute('aria-controls', screen.getByRole('tabpanel', { name: 'Settings' }).id);
|
||||
expect(screen.queryByRole('tabpanel', { name: 'Status' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('never fabricates offline metrics after an initial status failure and retries only the failed read', async () => {
|
||||
const get = mockedApi.get.getMockImplementation()!;
|
||||
mockedApi.get.mockImplementation((url: string, config?: any) => url === '/admin/system' ? Promise.reject(new Error('offline')) : get(url, config));
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
const alert = await screen.findByRole('alert');
|
||||
expect(screen.queryByText('Offline')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Requests')).not.toBeInTheDocument();
|
||||
mockedApi.get.mockImplementation(get);
|
||||
mockedApi.get.mockClear();
|
||||
fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }));
|
||||
expect(await screen.findByText('Production')).toBeVisible();
|
||||
expect(mockedApi.get.mock.calls.map(call => call[0])).toEqual(['/admin/system']);
|
||||
expect(mockedApi.post).not.toHaveBeenCalled();
|
||||
expect(mockedApi.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps SMTP edits and write-only password through explicit refresh', async () => {
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
fireEvent.change(screen.getByLabelText('Host'), { target: { value: 'unsaved.example.test' } });
|
||||
fireEvent.change(screen.getByLabelText('SMTP password'), { target: { value: 'new-secret' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Refresh' })).toBeEnabled());
|
||||
expect(screen.getByLabelText('Host')).toHaveValue('unsaved.example.test');
|
||||
expect(screen.getByLabelText('SMTP password')).toHaveValue('new-secret');
|
||||
expect(screen.queryByText('new-secret')).not.toBeInTheDocument();
|
||||
expect(mockedApi.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submits one SMTP snapshot, retains newer edits and prevents competing operational actions', async () => {
|
||||
const pending = deferred<any>();
|
||||
mockedApi.put.mockReturnValueOnce(pending.promise);
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
expect(screen.queryByText('Unsaved SMTP changes.')).not.toBeInTheDocument();
|
||||
await screen.findByText('Production');
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
expect(screen.queryByText('Unsaved SMTP changes.')).not.toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText('Host'), { target: { value: 'submitted.example.test' } });
|
||||
fireEvent.change(screen.getByLabelText('SMTP password'), { target: { value: 'submitted-secret' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save settings' }));
|
||||
fireEvent.change(screen.getByLabelText('Host'), { target: { value: 'newer.example.test' } });
|
||||
fireEvent.change(screen.getByLabelText('SMTP password'), { target: { value: 'newer-secret' } });
|
||||
expect(screen.getByRole('button', { name: 'Send test email' })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: 'Run probe now' })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: 'Refresh' })).toBeDisabled();
|
||||
expect(mockedApi.put).toHaveBeenCalledTimes(1);
|
||||
expect(mockedApi.put).toHaveBeenCalledWith('/admin/system/email-settings', expect.objectContaining({ host: 'submitted.example.test', password: 'submitted-secret', clearPassword: false }));
|
||||
await act(async () => pending.resolve({ data: { enabled: true, host: 'submitted.example.test', hasPassword: true } }));
|
||||
expect(screen.getByLabelText('Host')).toHaveValue('newer.example.test');
|
||||
expect(screen.getByLabelText('SMTP password')).toHaveValue('newer-secret');
|
||||
expect(screen.getByText('SMTP settings saved.')).toBeVisible();
|
||||
expect(screen.getByText('Unsaved SMTP changes.')).toBeVisible();
|
||||
expect(mockedApi.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['/admin/system/cv-benchmark', 'CV benchmark results could not be loaded.'],
|
||||
['/admin/system/maintenance-jobs', 'Maintenance availability could not be loaded.'],
|
||||
])('reports an optional %s failure and retries that GET without operational writes', async (path, message) => {
|
||||
const get = mockedApi.get.getMockImplementation()!;
|
||||
mockedApi.get.mockImplementation((url: string, config?: any) => url === path ? Promise.reject(new Error('offline')) : get(url, config));
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
expect(await screen.findByText(message)).toBeVisible();
|
||||
expect(screen.getByText('Production')).toBeVisible();
|
||||
expect(screen.queryByText('Maintenance dispatch is unavailable.')).not.toBeInTheDocument();
|
||||
mockedApi.get.mockImplementation(get); mockedApi.get.mockClear();
|
||||
fireEvent.click(within(screen.getByText(message).closest('[role="alert"]')!).getByRole('button', { name: 'Retry' }));
|
||||
await waitFor(() => expect(screen.queryByText(message)).not.toBeInTheDocument());
|
||||
expect(mockedApi.get.mock.calls.map(call => call[0])).toEqual([path]);
|
||||
expect(mockedApi.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps explicit password clearing through refresh and acknowledges only the submitted secret', async () => {
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
const clear = screen.getByRole('checkbox', { name: /clear stored password/i });
|
||||
fireEvent.click(clear);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Refresh' })).toBeEnabled());
|
||||
expect(clear).toBeChecked();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save settings' }));
|
||||
await screen.findByText('SMTP settings saved.');
|
||||
expect(mockedApi.put).toHaveBeenCalledWith('/admin/system/email-settings', expect.objectContaining({ password: null, clearPassword: true }));
|
||||
expect(clear).not.toBeChecked();
|
||||
expect(screen.getByLabelText('SMTP password')).toHaveValue('');
|
||||
expect(screen.queryByText('Unsaved SMTP changes.')).not.toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Host')).toHaveValue('smtp.changed.test');
|
||||
});
|
||||
|
||||
it('retains failed SMTP edits and only writes again after an explicit save', async () => {
|
||||
mockedApi.put.mockRejectedValueOnce({ response: { status: 503, data: { title: 'Private object must not stringify' } } });
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
fireEvent.change(screen.getByLabelText('Host'), { target: { value: 'keep.example.test' } });
|
||||
fireEvent.change(screen.getByLabelText('SMTP password'), { target: { value: 'keep-secret' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save settings' }));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Failed to save email settings.');
|
||||
expect(screen.getByLabelText('Host')).toHaveValue('keep.example.test');
|
||||
expect(screen.getByLabelText('SMTP password')).toHaveValue('keep-secret');
|
||||
expect(screen.getByText('Unsaved SMTP changes.')).toBeVisible();
|
||||
expect(screen.queryByText('[object Object]')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Save settings' })).toBeEnabled());
|
||||
expect(mockedApi.put).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByLabelText('Host')).toHaveValue('keep.example.test');
|
||||
});
|
||||
|
||||
it('waits for one probe before allowing another action and never runs on entry or tab changes', async () => {
|
||||
const pending = deferred<any>(); mockedApi.post.mockReturnValueOnce(pending.promise);
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
expect(mockedApi.post).not.toHaveBeenCalled();
|
||||
const probe = screen.getByRole('button', { name: 'Run probe now' });
|
||||
fireEvent.click(probe); fireEvent.click(probe);
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
expect(screen.getByRole('button', { name: 'Send test email' })).toBeDisabled();
|
||||
expect(mockedApi.post).toHaveBeenCalledTimes(1);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/admin/system/ai/probe');
|
||||
await act(async () => pending.resolve({ data: {} }));
|
||||
expect(await screen.findByText('AI probe completed.')).toBeVisible();
|
||||
});
|
||||
|
||||
it('refreshes probe metrics after success and a failed follow-up read retries GET without replaying the probe', async () => {
|
||||
mockedApi.post.mockResolvedValueOnce({ data: {} } as any);
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
const get = mockedApi.get.getMockImplementation()!;
|
||||
mockedApi.get.mockImplementation((url: string, config?: any) => url === '/admin/system' ? Promise.reject(new Error('offline')) : get(url, config));
|
||||
mockedApi.get.mockClear();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Run probe now' }));
|
||||
expect(await screen.findByText('System status could not be refreshed. Previously loaded values remain.')).toBeVisible();
|
||||
expect(mockedApi.get.mock.calls.map(call => call[0])).toEqual(['/admin/system']);
|
||||
mockedApi.get.mockImplementation(get);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument());
|
||||
expect(mockedApi.post).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not acknowledge an SMTP write into a changed session', async () => {
|
||||
const pending = deferred<any>(); mockedApi.put.mockReturnValueOnce(pending.promise);
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
fireEvent.change(screen.getByLabelText('Host'), { target: { value: 'owner-a.example.test' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save settings' }));
|
||||
mockSessionContext = 'second-session';
|
||||
await act(async () => pending.resolve({ data: { enabled: true, host: 'must-not-apply.example.test', hasPassword: true } }));
|
||||
expect(screen.getByLabelText('Host')).toHaveValue('owner-a.example.test');
|
||||
expect(screen.queryByText('SMTP settings saved.')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not refresh or announce a completed probe after unmount', async () => {
|
||||
const pending = deferred<any>(); mockedApi.post.mockReturnValueOnce(pending.promise);
|
||||
const view = render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Run probe now' }));
|
||||
const count = mockedApi.get.mock.calls.length;
|
||||
view.unmount();
|
||||
await act(async () => pending.resolve({ data: {} }));
|
||||
expect(mockedApi.get).toHaveBeenCalledTimes(count);
|
||||
});
|
||||
|
||||
it('clears sensitive diagnostics after a denied refresh and offers no retry or operational action', async () => {
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
mockedApi.get.mockRejectedValue({ response: { status: 403 } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
await waitFor(() => expect(screen.queryByText('Production')).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Run probe now' })).toBeDisabled();
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
expect(screen.queryByLabelText('SMTP password')).not.toBeInTheDocument();
|
||||
expect(mockedApi.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the last diagnostic values under a qualified refresh error', async () => {
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
const get = mockedApi.get.getMockImplementation()!;
|
||||
mockedApi.get.mockImplementation((url: string, config?: any) => url === '/admin/system' ? Promise.reject({ response: { status: 503, data: 'Temporary failure' } }) : get(url, config));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
expect(await screen.findByText('System status could not be refreshed. Previously loaded values remain.')).toBeVisible();
|
||||
expect(screen.getByText('Production')).toBeVisible();
|
||||
expect(mockedApi.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not present unavailable SMTP settings as a blank editable configuration', async () => {
|
||||
const get = mockedApi.get.getMockImplementation()!;
|
||||
mockedApi.get.mockImplementation((url: string, config?: any) => url === '/admin/system/email-settings' ? Promise.reject(new Error('offline')) : get(url, config));
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
await screen.findByText('Production');
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Settings' }));
|
||||
expect(await screen.findByText('SMTP settings could not be loaded.')).toBeVisible();
|
||||
expect(screen.queryByLabelText('Host')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Send test email' })).toBeDisabled();
|
||||
mockedApi.get.mockImplementation(get); mockedApi.get.mockClear();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
|
||||
expect(await screen.findByLabelText('Host')).toHaveValue('smtp.example.test');
|
||||
expect(mockedApi.get.mock.calls.map(call => call[0])).toEqual(['/admin/system/email-settings']);
|
||||
});
|
||||
|
||||
it('renders AI service health, latency, and OCR readiness', async () => {
|
||||
render(
|
||||
<I18nProvider>
|
||||
@@ -230,7 +453,9 @@ describe('AdminSystemPage', () => {
|
||||
mockedApi.post.mockResolvedValueOnce({ data: { jobId: 'cv-benchmark', status: 'queued' } } as any);
|
||||
render(<I18nProvider><AdminSystemPage /></I18nProvider>);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /run benchmark/i }));
|
||||
const run = await screen.findByRole('button', { name: /run benchmark/i });
|
||||
await waitFor(() => expect(run).toBeEnabled());
|
||||
fireEvent.click(run);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/admin/system/maintenance-jobs/cv-benchmark/runs');
|
||||
|
||||
@@ -1841,6 +1841,14 @@ export const translations = {
|
||||
kanbanDragStartedAnnouncement: "{title} picked up.",
|
||||
adminSystemTitle: "System status",
|
||||
adminSystemLoadFailed: "Failed to load system status.",
|
||||
adminSystemBenchmarkLoadFailed: "CV benchmark results could not be loaded.",
|
||||
adminSystemMaintenanceLoadFailed: "Maintenance availability could not be loaded.",
|
||||
adminSystemEmailSettingsLoadFailed: "SMTP settings could not be loaded.",
|
||||
adminSystemSettingsSaved: "SMTP settings saved.",
|
||||
adminSystemUnsavedChanges: "Unsaved SMTP changes.",
|
||||
adminSystemTestEmailSent: "Test email sent.",
|
||||
adminSystemProbeCompleted: "AI probe completed.",
|
||||
adminSystemRefreshFailed: "System status could not be refreshed. Previously loaded values remain.",
|
||||
adminSystemTestEmailFailed: "Failed to send test email.",
|
||||
adminSystemDefaultTestMessage: "This is a test email from the Jobbjakt system panel.",
|
||||
adminSystemEmailSaveFailed: "Failed to save email settings.",
|
||||
@@ -4615,6 +4623,14 @@ export const translations = {
|
||||
kanbanDragStartedAnnouncement: "{title} er løftet.",
|
||||
adminSystemTitle: "Systemstatus",
|
||||
adminSystemLoadFailed: "Kunne ikke laste systemstatus.",
|
||||
adminSystemBenchmarkLoadFailed: "Kunne ikke hente resultatene fra CV-referansetesten.",
|
||||
adminSystemMaintenanceLoadFailed: "Kunne ikke hente tilgjengelige vedlikeholdsoppgaver.",
|
||||
adminSystemEmailSettingsLoadFailed: "Kunne ikke hente SMTP-innstillingene.",
|
||||
adminSystemSettingsSaved: "SMTP-innstillingene er lagret.",
|
||||
adminSystemUnsavedChanges: "SMTP-endringene er ikke lagret.",
|
||||
adminSystemTestEmailSent: "Test-e-posten er sendt.",
|
||||
adminSystemProbeCompleted: "KI-kontrollen er fullført.",
|
||||
adminSystemRefreshFailed: "Kunne ikke oppdatere systemstatus. Tidligere innlastede verdier beholdes.",
|
||||
adminSystemTestEmailFailed: "Kunne ikke sende test-e-post.",
|
||||
adminSystemDefaultTestMessage: "Dette er en test-e-post fra systempanelet i Jobbjakt.",
|
||||
adminSystemEmailSaveFailed: "Kunne ikke lagre e-postinnstillingene.",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
Alert,
|
||||
@@ -13,10 +13,14 @@ import {
|
||||
Typography,
|
||||
Checkbox,
|
||||
FormControlLabel,
|
||||
LinearProgress,
|
||||
} from "@mui/material";
|
||||
|
||||
import { api, getApiErrorMessage } from "../api";
|
||||
import { useI18n } from "../i18n/I18nProvider";
|
||||
import { PageHeader, PageSection } from "../layout/PageLayout";
|
||||
import type { TranslationKey } from "../i18n/translations";
|
||||
import { checkSessionCookie, getSessionContext, isSessionInvalidated } from "../sessionBoundary";
|
||||
|
||||
type AiServiceMetrics = {
|
||||
healthy: boolean;
|
||||
@@ -201,7 +205,7 @@ function benchmarkTone(value?: number | null) {
|
||||
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 }}>
|
||||
<Paper variant="outlined" sx={{ p: "var(--app-card-padding)", borderRadius: 1, minWidth: 0 }}>
|
||||
<Typography variant="overline" sx={{ color: "text.secondary" }}>{title}</Typography>
|
||||
<Typography component="p" variant="h5" sx={{ fontWeight: 950, color }}>{value}</Typography>
|
||||
<Typography variant="body2" sx={{ color: "text.secondary", mt: 1 }}>{subtitle || "-"}</Typography>
|
||||
@@ -210,9 +214,15 @@ function SummaryCard({ title, value, subtitle, tone = "default" }: { title: stri
|
||||
}
|
||||
|
||||
function DetailRow({ label, value }: { label: string; value: React.ReactNode }) {
|
||||
return <Typography variant="body2"><strong>{label}:</strong> {value}</Typography>;
|
||||
return <Typography variant="body2" sx={{ overflowWrap: "anywhere", minWidth: 0 }}><strong>{label}:</strong> {value}</Typography>;
|
||||
}
|
||||
|
||||
type ReadKind = "status" | "email" | "benchmark" | "maintenance";
|
||||
type ActionKind = "save" | "test" | "probe" | "maintenance";
|
||||
const readPaths: Record<ReadKind, string> = { status: "/admin/system", email: "/admin/system/email-settings", benchmark: "/admin/system/cv-benchmark", maintenance: "/admin/system/maintenance-jobs" };
|
||||
const readErrorKeys: Record<ReadKind, TranslationKey> = { status: "adminSystemLoadFailed", email: "adminSystemEmailSettingsLoadFailed", benchmark: "adminSystemBenchmarkLoadFailed", maintenance: "adminSystemMaintenanceLoadFailed" };
|
||||
const actionErrorKeys: Record<ActionKind, TranslationKey> = { save: "adminSystemEmailSaveFailed", test: "adminSystemTestEmailFailed", probe: "adminSystemProbeFailed", maintenance: "adminMaintenanceFailed" };
|
||||
|
||||
export default function AdminSystemPage() {
|
||||
const { language, t } = useI18n();
|
||||
const [tab, setTab] = useState(0);
|
||||
@@ -220,50 +230,114 @@ export default function AdminSystemPage() {
|
||||
const [emailSettings, setEmailSettings] = useState<EditableEmailSettings | null>(null);
|
||||
const [benchmarkStatus, setBenchmarkStatus] = useState<CvBenchmarkStatus | null>(null);
|
||||
const [maintenanceJobs, setMaintenanceJobs] = useState<MaintenanceJob[]>([]);
|
||||
const [runningMaintenanceJob, setRunningMaintenanceJob] = useState<string | null>(null);
|
||||
const [maintenanceMessage, setMaintenanceMessage] = useState<string | 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 [loading, setLoading] = useState(true);
|
||||
const [readErrors, setReadErrors] = useState<Partial<Record<ReadKind, unknown>>>({});
|
||||
const [accessDenied, setAccessDenied] = useState(false);
|
||||
const [action, setAction] = useState<ActionKind | null>(null);
|
||||
const [actionError, setActionError] = useState<{ kind: ActionKind; cause: unknown } | null>(null);
|
||||
const [message, setMessage] = useState<TranslationKey | null>(null);
|
||||
const [testEmailTo, setTestEmailTo] = useState("");
|
||||
const [testEmailSubject, setTestEmailSubject] = useState("Jobbjakt SMTP test");
|
||||
const [testEmailMessage, setTestEmailMessage] = useState(() => t("adminSystemDefaultTestMessage"));
|
||||
const [sendingTestEmail, setSendingTestEmail] = useState(false);
|
||||
const mounted = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const readPending = useRef(false);
|
||||
const actionPending = useRef(false);
|
||||
const denied = useRef(false);
|
||||
const controller = useRef<AbortController | null>(null);
|
||||
const draftRevision = useRef(0);
|
||||
const passwordRevision = useRef(0);
|
||||
const savedRevision = useRef(0);
|
||||
const bodyRef = useRef<HTMLDivElement>(null);
|
||||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||
const restoreFocus = useRef<HTMLElement | null>(null);
|
||||
const navigationId = useId();
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const load = useCallback(async (kind?: ReadKind, afterWrite = false) => {
|
||||
checkSessionCookie();
|
||||
if (!mounted.current || denied.current || isSessionInvalidated() || readPending.current || actionPending.current && !afterWrite) return;
|
||||
const context = getSessionContext();
|
||||
const lifetime = generation.current;
|
||||
const active = () => { checkSessionCookie(); return mounted.current && lifetime === generation.current && !isSessionInvalidated() && getSessionContext() === context; };
|
||||
readPending.current = true;
|
||||
const abort = new AbortController();
|
||||
controller.current = abort;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [statusRes, emailRes, benchmarkRes, maintenanceRes] = 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)),
|
||||
api.get<MaintenanceJob[]>("/admin/system/maintenance-jobs").catch(() => ({ data: [] } as any)),
|
||||
]);
|
||||
setStatus(statusRes.data);
|
||||
setEmailSettings(emailRes.data);
|
||||
setBenchmarkStatus(benchmarkRes.data ?? null);
|
||||
setMaintenanceJobs(maintenanceRes.data ?? []);
|
||||
setSmtpPassword("");
|
||||
setClearPassword(false);
|
||||
} catch (e: any) {
|
||||
setError(getApiErrorMessage(e, t("adminSystemLoadFailed")));
|
||||
setStatus(null);
|
||||
setEmailSettings(null);
|
||||
setBenchmarkStatus(null);
|
||||
setMaintenanceJobs([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [t]);
|
||||
const revision = draftRevision.current;
|
||||
await Promise.all((kind ? [kind] : Object.keys(readPaths) as ReadKind[]).map(async (part) => {
|
||||
try {
|
||||
const response = await api.get(readPaths[part], { signal: abort.signal });
|
||||
if (!active() || abort.signal.aborted || denied.current) return;
|
||||
if (part === "status") setStatus(response.data);
|
||||
if (part === "email" && revision === draftRevision.current && revision === savedRevision.current) setEmailSettings(response.data);
|
||||
if (part === "benchmark") setBenchmarkStatus(response.data ?? null);
|
||||
if (part === "maintenance") setMaintenanceJobs(response.data ?? []);
|
||||
setReadErrors(errors => { const next = { ...errors }; delete next[part]; return next; });
|
||||
} catch (cause) {
|
||||
if (active() && !abort.signal.aborted) {
|
||||
const responseStatus = (cause as { response?: { status?: number } })?.response?.status;
|
||||
if (responseStatus === 401 || responseStatus === 403) {
|
||||
denied.current = true; setAccessDenied(true);
|
||||
setStatus(null); setEmailSettings(null); setBenchmarkStatus(null); setMaintenanceJobs([]);
|
||||
setSmtpPassword(""); setClearPassword(false);
|
||||
}
|
||||
setReadErrors(errors => ({ ...errors, [part]: cause }));
|
||||
}
|
||||
}
|
||||
}));
|
||||
if (active() && !abort.signal.aborted) { readPending.current = false; setLoading(false); }
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
generation.current += 1;
|
||||
void load();
|
||||
return () => { mounted.current = false; generation.current += 1; controller.current?.abort(); readPending.current = false; };
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || action || !restoreFocus.current) return;
|
||||
const target = restoreFocus.current;
|
||||
restoreFocus.current = null;
|
||||
if (document.activeElement !== bodyRef.current) return;
|
||||
if (target.isConnected && !target.matches(":disabled")) target.focus();
|
||||
else headingRef.current?.focus();
|
||||
}, [loading, action]);
|
||||
|
||||
const rememberFocus = () => {
|
||||
const target = document.activeElement;
|
||||
if (target instanceof HTMLElement && bodyRef.current?.contains(target)) { restoreFocus.current = target; bodyRef.current.focus(); }
|
||||
};
|
||||
const refresh = (kind?: ReadKind) => { if (!readPending.current && !actionPending.current) { rememberFocus(); void load(kind); } };
|
||||
const updateSettings = (update: Partial<EditableEmailSettings>) => {
|
||||
draftRevision.current += 1;
|
||||
setEmailSettings(previous => previous ? { ...previous, ...update } : previous);
|
||||
};
|
||||
const locked = loading || action !== null || accessDenied;
|
||||
const runAction = async (kind: ActionKind, write: (active: () => boolean) => Promise<void>, success: TranslationKey) => {
|
||||
checkSessionCookie();
|
||||
if (!mounted.current || denied.current || isSessionInvalidated() || readPending.current || actionPending.current) return;
|
||||
const context = getSessionContext();
|
||||
const lifetime = generation.current;
|
||||
const active = () => { checkSessionCookie(); return mounted.current && lifetime === generation.current && !isSessionInvalidated() && getSessionContext() === context; };
|
||||
actionPending.current = true;
|
||||
rememberFocus(); setAction(kind); setActionError(null); setMessage(null);
|
||||
try { await write(active); if (active()) setMessage(success); }
|
||||
catch (cause) { if (active()) setActionError({ kind, cause }); }
|
||||
finally { actionPending.current = false; if (active()) setAction(null); }
|
||||
};
|
||||
const readNotice = (kind: ReadKind) => {
|
||||
if (!readErrors[kind]) return null;
|
||||
const title = t(kind === "status" && status ? "adminSystemRefreshFailed" : readErrorKeys[kind]);
|
||||
const detail = getApiErrorMessage(readErrors[kind], title);
|
||||
return <Alert severity="error" sx={{ overflowWrap: "anywhere", display: "grid", gridTemplateColumns: "auto minmax(0, 1fr)", "& .MuiAlert-message": { minWidth: 0 }, "& .MuiAlert-action": { gridColumn: 2, m: 0, p: 0, justifySelf: "start" } }} action={!accessDenied ? <Button color="inherit" disabled={locked} onClick={() => refresh(kind)}>{t("retry")}</Button> : undefined}>
|
||||
<Typography variant="body2">{title}</Typography>
|
||||
{detail !== title ? <Typography variant="body2">{detail}</Typography> : null}
|
||||
</Alert>;
|
||||
};
|
||||
|
||||
const dbTone = useMemo(() => {
|
||||
if (!status) return "default" as const;
|
||||
if (!status.database.looksConfigured || !status.database.canConnect) return "error" as const;
|
||||
@@ -307,106 +381,79 @@ export default function AdminSystemPage() {
|
||||
}).slice(0, 10);
|
||||
}, [benchmarkIndex, t]);
|
||||
|
||||
const sendTestEmail = async () => {
|
||||
setSendingTestEmail(true);
|
||||
try {
|
||||
const sendTestEmail = () => runAction("test", async () => {
|
||||
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, t("adminSystemTestEmailFailed")));
|
||||
} finally {
|
||||
setSendingTestEmail(false);
|
||||
}
|
||||
};
|
||||
}, "adminSystemTestEmailSent");
|
||||
|
||||
const saveEmailSettings = async () => {
|
||||
if (!emailSettings) return;
|
||||
setSavingSettings(true);
|
||||
try {
|
||||
const revision = draftRevision.current;
|
||||
const secretRevision = passwordRevision.current;
|
||||
const snapshot = emailSettings;
|
||||
await runAction("save", async (active) => {
|
||||
const res = await api.put<EditableEmailSettings>("/admin/system/email-settings", {
|
||||
enabled: emailSettings.enabled,
|
||||
host: emailSettings.host,
|
||||
port: Number(emailSettings.port) || 587,
|
||||
user: emailSettings.user,
|
||||
enabled: snapshot.enabled,
|
||||
host: snapshot.host,
|
||||
port: Number(snapshot.port) || 587,
|
||||
user: snapshot.user,
|
||||
password: smtpPassword.trim() || null,
|
||||
clearPassword,
|
||||
from: emailSettings.from,
|
||||
fromName: emailSettings.fromName,
|
||||
enableSsl: emailSettings.enableSsl,
|
||||
timeoutMs: Number(emailSettings.timeoutMs) || 15000,
|
||||
from: snapshot.from,
|
||||
fromName: snapshot.fromName,
|
||||
enableSsl: snapshot.enableSsl,
|
||||
timeoutMs: Number(snapshot.timeoutMs) || 15000,
|
||||
});
|
||||
setEmailSettings(res.data);
|
||||
setSmtpPassword("");
|
||||
setClearPassword(false);
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
setError(getApiErrorMessage(e, t("adminSystemEmailSaveFailed")));
|
||||
} finally {
|
||||
setSavingSettings(false);
|
||||
}
|
||||
if (!active()) return;
|
||||
if (draftRevision.current === revision) { setEmailSettings(res.data); savedRevision.current = revision; }
|
||||
if (passwordRevision.current === secretRevision) { setSmtpPassword(""); setClearPassword(false); }
|
||||
setReadErrors(errors => { const next = { ...errors }; delete next.email; return next; });
|
||||
}, "adminSystemSettingsSaved");
|
||||
};
|
||||
|
||||
const runMaintenanceJob = async (jobId: string) => {
|
||||
setRunningMaintenanceJob(jobId);
|
||||
setMaintenanceMessage(null);
|
||||
setError(null);
|
||||
try {
|
||||
if (jobId !== "cv-benchmark" || !cvBenchmarkJob?.available || readErrors.maintenance) return;
|
||||
await runAction("maintenance", async () => {
|
||||
await api.post(`/admin/system/maintenance-jobs/${encodeURIComponent(jobId)}/runs`);
|
||||
setMaintenanceMessage(t("adminMaintenanceQueued"));
|
||||
} catch (e: any) {
|
||||
setError(getApiErrorMessage(e, t("adminMaintenanceFailed")));
|
||||
} finally {
|
||||
setRunningMaintenanceJob(null);
|
||||
}
|
||||
}, "adminMaintenanceQueued");
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
<Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, alignItems: "center", flexWrap: "wrap" }}>
|
||||
<Box>
|
||||
<Typography component="h2" variant="h5" sx={{ fontWeight: 950 }}>{t("adminSystemTitle")}</Typography>
|
||||
<Typography sx={{ color: "text.secondary" }}>{t("adminSystemSubtitle")}</Typography>
|
||||
</Box>
|
||||
<Box ref={bodyRef} role="region" aria-label={t("adminSystemTitle")} aria-busy={locked} tabIndex={-1} sx={{ display: "flex", flexDirection: "column", gap: "var(--app-section-gap)", minWidth: 0, overflowWrap: "anywhere", "& .MuiButton-root": { whiteSpace: "normal", overflowWrap: "anywhere", maxWidth: "100%", minHeight: { xs: 44, sm: 36 }, "@media (pointer: coarse)": { minHeight: 44 } }, "& .MuiChip-root": { maxWidth: "100%", height: "auto" }, "& .MuiChip-label": { whiteSpace: "normal", overflowWrap: "anywhere", py: 0.5 } }}>
|
||||
<PageHeader level="h2" titleRef={headingRef} title={t("adminSystemTitle")} description={t("adminSystemSubtitle")} actions={
|
||||
<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, t("adminSystemProbeFailed")));
|
||||
} finally {
|
||||
setRunningProbe(false);
|
||||
}
|
||||
await runAction("probe", async (active) => { await api.post("/admin/system/ai/probe"); if (active()) await load("status", true); }, "adminSystemProbeCompleted");
|
||||
}}
|
||||
disabled={loading || runningProbe}
|
||||
disabled={locked || !status || !!readErrors.status}
|
||||
>
|
||||
{runningProbe ? t("adminSystemRunningProbe") : t("adminSystemRunProbe")}
|
||||
{action === "probe" ? t("adminSystemRunningProbe") : t("adminSystemRunProbe")}
|
||||
</Button>
|
||||
<Button variant="contained" onClick={() => void load()} disabled={loading}>
|
||||
<Button variant="contained" onClick={() => refresh()} disabled={locked}>
|
||||
{loading ? t("adminSystemRefreshing") : t("adminSystemRefresh")}
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box> } />
|
||||
|
||||
<Tabs value={tab} onChange={(_, value) => setTab(value)}>
|
||||
<Tab label={t("adminSystemStatusTab")} />
|
||||
<Tab label={t("adminSystemSettingsTab")} />
|
||||
<Tabs value={tab} aria-label={t("adminSystemTitle")} onChange={(_, value) => setTab(value)} variant="scrollable" scrollButtons="auto" allowScrollButtonsMobile>
|
||||
<Tab id={`${navigationId}-tab-0`} aria-controls={`${navigationId}-panel-0`} label={t("adminSystemStatusTab")} />
|
||||
<Tab id={`${navigationId}-tab-1`} aria-controls={`${navigationId}-panel-1`} label={t("adminSystemSettingsTab")} />
|
||||
</Tabs>
|
||||
|
||||
{error ? <Alert severity="error">{error}</Alert> : null}
|
||||
{loading ? <LinearProgress aria-label={t("loading")} /> : null}
|
||||
{actionError ? <Alert severity="error" sx={{ overflowWrap: "anywhere" }}>{getApiErrorMessage(actionError.cause, t(actionErrorKeys[actionError.kind]))}</Alert> : null}
|
||||
{message ? <Alert severity="success" role="status">{t(message)}</Alert> : null}
|
||||
{readNotice("status")}
|
||||
{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 role="tabpanel" id={`${navigationId}-panel-0`} aria-labelledby={`${navigationId}-tab-0`} hidden={tab !== 0} sx={{ minWidth: 0 }}>
|
||||
<Stack spacing={1}>{readNotice("benchmark")}{readNotice("maintenance")}</Stack>
|
||||
{status ? <Stack spacing={2}>
|
||||
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "repeat(4, 1fr)" }, gap: 2 }}>
|
||||
<SummaryCard
|
||||
title={t("adminSystemEnvironment")}
|
||||
@@ -438,8 +485,7 @@ export default function AdminSystemPage() {
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "1.2fr 1fr" }, gap: 2 }}>
|
||||
<Paper sx={{ p: 2, borderRadius: 3 }}>
|
||||
<Typography component="h3" variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemDatabaseStorage")}</Typography>
|
||||
<PageSection surface level="h3" title={t("adminSystemDatabaseStorage")}>
|
||||
<Stack spacing={0.75}>
|
||||
<DetailRow label={t("adminSystemProvider")} value={status?.database.provider || "-"} />
|
||||
<DetailRow label={t("adminSystemTarget")} value={status?.database.target || "-"} />
|
||||
@@ -454,10 +500,9 @@ export default function AdminSystemPage() {
|
||||
<DetailRow label={t("adminSystemJobs")} value={status?.storage.jobCount ?? 0} />
|
||||
<DetailRow label={t("adminSystemDeletedJobs")} value={status?.storage.deletedCount ?? 0} />
|
||||
</Stack>
|
||||
</Paper>
|
||||
</PageSection>
|
||||
|
||||
<Paper sx={{ p: 2, borderRadius: 3 }}>
|
||||
<Typography component="h3" variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemRuntimeAuth")}</Typography>
|
||||
<PageSection surface level="h3" title={t("adminSystemRuntimeAuth")}>
|
||||
<Stack spacing={0.75}>
|
||||
<DetailRow label={t("adminSystemFramework")} value={status?.runtime.framework || "-"} />
|
||||
<DetailRow label={t("adminSystemOs")} value={status?.runtime.osDescription || "-"} />
|
||||
@@ -470,12 +515,11 @@ export default function AdminSystemPage() {
|
||||
<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>
|
||||
</PageSection>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "1fr 1fr" }, gap: 2 }}>
|
||||
<Paper sx={{ p: 2, borderRadius: 3 }}>
|
||||
<Typography component="h3" variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemEmailConfig")}</Typography>
|
||||
<PageSection surface level="h3" title={t("adminSystemEmailConfig")}>
|
||||
<Stack spacing={0.75}>
|
||||
<DetailRow label={t("adminSystemEnabled")} value={status?.email.enabled ? t("yes") : t("noWord")} />
|
||||
<DetailRow label={t("adminSystemFrom")} value={status?.email.from || "-"} />
|
||||
@@ -484,10 +528,9 @@ export default function AdminSystemPage() {
|
||||
<DetailRow label={t("adminSystemPort")} value={status?.email.port ?? "-"} />
|
||||
<DetailRow label={t("adminSystemSsl")} value={status?.email.enableSsl ? t("yes") : t("noWord")} />
|
||||
</Stack>
|
||||
</Paper>
|
||||
</PageSection>
|
||||
|
||||
<Paper sx={{ p: 2, borderRadius: 3 }}>
|
||||
<Typography component="h3" variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSummarizerRuntime")}</Typography>
|
||||
<PageSection surface level="h3" title={t("adminSystemSummarizerRuntime")}>
|
||||
<Stack spacing={0.75}>
|
||||
<DetailRow label={t("adminSystemModel")} value={status?.ai.model || "-"} />
|
||||
<DetailRow label={t("adminSystemDevice")} value={status?.ai.device || "-"} />
|
||||
@@ -505,11 +548,10 @@ export default function AdminSystemPage() {
|
||||
<DetailRow label={t("adminSystemLastSuccessfulProbe")} value={formatDate(status?.ai.lastProbeSuccessAt, language === "nb" ? "nb-NO" : "en")} />
|
||||
<DetailRow label={t("adminSystemLastSummarizationSuccess")} value={formatDate(status?.ai.lastSuccessAt, language === "nb" ? "nb-NO" : "en")} />
|
||||
</Stack>
|
||||
</Paper>
|
||||
</PageSection>
|
||||
</Box>
|
||||
|
||||
<Paper sx={{ p: 2, borderRadius: 3 }}>
|
||||
<Typography component="h3" variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSummarizerTelemetry")}</Typography>
|
||||
<PageSection surface level="h3" title={t("adminSystemSummarizerTelemetry")}>
|
||||
<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 component="p" variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.requests ?? 0}</Typography></Box>
|
||||
<Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemCacheHits")}</Typography><Typography component="p" variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.cacheHits ?? 0}</Typography></Box>
|
||||
@@ -534,12 +576,11 @@ export default function AdminSystemPage() {
|
||||
<Chip key={`loaded-${model}`} label={t("adminSystemLoadedModel", { model })} color="primary" variant="outlined" size="small" />
|
||||
))}
|
||||
</Box>
|
||||
</Paper>
|
||||
</PageSection>
|
||||
|
||||
<Paper sx={{ p: 2, borderRadius: 3 }}>
|
||||
<PageSection surface level="h3" title={t("adminBenchmarkTitle")}>
|
||||
<Box sx={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 2, flexWrap: "wrap", mb: 1 }}>
|
||||
<Box>
|
||||
<Typography component="h3" variant="h6" sx={{ fontWeight: 900 }}>{t("adminBenchmarkTitle")}</Typography>
|
||||
<Typography variant="body2" sx={{ color: "text.secondary", mt: 0.25 }}>
|
||||
{cvBenchmarkJob?.description || t("adminBenchmarkRunScript")}
|
||||
</Typography>
|
||||
@@ -552,15 +593,15 @@ export default function AdminSystemPage() {
|
||||
) : null}
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!cvBenchmarkJob?.available || runningMaintenanceJob === "cv-benchmark"}
|
||||
disabled={locked || !cvBenchmarkJob?.available || !!readErrors.maintenance}
|
||||
onClick={() => void runMaintenanceJob("cv-benchmark")}
|
||||
>
|
||||
{runningMaintenanceJob === "cv-benchmark" ? t("adminMaintenanceStarting") : t("adminMaintenanceRunBenchmark")}
|
||||
{action === "maintenance" ? t("adminMaintenanceStarting") : t("adminMaintenanceRunBenchmark")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Box>
|
||||
{!cvBenchmarkJob?.available ? <Alert severity="info" sx={{ mb: 1.5 }}>{t("adminMaintenanceUnavailable")}</Alert> : null}
|
||||
{maintenanceMessage ? <Alert severity="success" sx={{ mb: 1.5 }}>{maintenanceMessage}</Alert> : null}
|
||||
{!loading && !readErrors.maintenance && !cvBenchmarkJob?.available ? <Alert severity="info" sx={{ mb: 1.5 }}>{t("adminMaintenanceUnavailable")}</Alert> : null}
|
||||
{!readErrors.benchmark && !loading ? <>
|
||||
<Stack spacing={0.75}>
|
||||
<DetailRow label={t("adminBenchmarkRoot")} value={benchmarkStatus?.rootPath || "-"} />
|
||||
<DetailRow label={t("adminBenchmarkLastUpdate")} value={formatDate(benchmarkStatus?.lastUpdatedAtUtc, language === "nb" ? "nb-NO" : "en")} />
|
||||
@@ -621,39 +662,40 @@ export default function AdminSystemPage() {
|
||||
{benchmarkStatus?.reportMarkdown || t("adminBenchmarkRunScript")}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
</>
|
||||
) : (
|
||||
<Box sx={{ display: "grid", gap: 2 }}>
|
||||
<Paper sx={{ p: 2, borderRadius: 3 }}>
|
||||
<Typography component="h3" variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemEmailSettingsTitle")}</Typography>
|
||||
)}</> : null}
|
||||
</PageSection>
|
||||
</Stack> : null}
|
||||
</Box>
|
||||
<Box role="tabpanel" id={`${navigationId}-panel-1`} aria-labelledby={`${navigationId}-tab-1`} hidden={tab !== 1} sx={{ minWidth: 0 }}>
|
||||
<Box sx={{ display: "grid", gap: 2, minWidth: 0 }}>
|
||||
{readNotice("email")}
|
||||
{emailSettings ? <PageSection surface level="h3" title={t("adminSystemEmailSettingsTitle")}>
|
||||
<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)} />}
|
||||
control={<Checkbox checked={Boolean(emailSettings?.enabled)} onChange={(e) => updateSettings({ enabled: e.target.checked })} />}
|
||||
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" } }} />
|
||||
<TextField label={t("adminSystemHost")} value={emailSettings?.host ?? ""} onChange={(e) => updateSettings({ host: e.target.value })} fullWidth />
|
||||
<TextField label={t("adminSystemPort")} type="number" value={emailSettings?.port ?? 587} onChange={(e) => updateSettings({ port: Number(e.target.value) })} fullWidth />
|
||||
<TextField label={t("adminSystemUsername")} value={emailSettings?.user ?? ""} onChange={(e) => updateSettings({ user: e.target.value })} fullWidth />
|
||||
<TextField label={t("adminSystemPassword")} type="password" value={smtpPassword} onChange={(e) => { draftRevision.current += 1; passwordRevision.current += 1; 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) => updateSettings({ from: e.target.value })} fullWidth />
|
||||
<TextField label={t("adminSystemFromName")} value={emailSettings?.fromName ?? ""} onChange={(e) => updateSettings({ fromName: e.target.value })} fullWidth />
|
||||
<TextField label={t("adminSystemTimeoutMs")} type="number" value={emailSettings?.timeoutMs ?? 15000} onChange={(e) => updateSettings({ timeoutMs: Number(e.target.value) })} fullWidth />
|
||||
<FormControlLabel control={<Checkbox checked={Boolean(emailSettings?.enableSsl)} onChange={(e) => updateSettings({ enableSsl: e.target.checked })} />} label={t("adminSystemSsl")} />
|
||||
<FormControlLabel control={<Checkbox checked={clearPassword} onChange={(e) => { draftRevision.current += 1; passwordRevision.current += 1; setClearPassword(e.target.checked); if (e.target.checked) setSmtpPassword(""); }} />} label={t("adminSystemClearStoredPassword")} sx={{ gridColumn: { xs: "1 / -1", md: "1 / -1" } }} />
|
||||
</Box>
|
||||
{draftRevision.current !== savedRevision.current ? <Typography variant="body2" color="text.secondary" role="status" sx={{ mt: 1.5 }}>{t("adminSystemUnsavedChanges")}</Typography> : null}
|
||||
<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 variant="contained" disabled={locked || !!readErrors.email} onClick={() => void saveEmailSettings()}>
|
||||
{action === "save" ? t("adminSystemSaving") : t("adminSystemSaveSettings")}
|
||||
</Button>
|
||||
</Box>
|
||||
</Paper>
|
||||
</PageSection> : null}
|
||||
|
||||
<Paper sx={{ p: 2, borderRadius: 3 }}>
|
||||
<Typography component="h3" variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSmtpTest")}</Typography>
|
||||
<PageSection surface level="h3" title={t("adminSystemSmtpTest")}>
|
||||
<Typography variant="body2" sx={{ color: "text.secondary", mb: 1.5 }}>
|
||||
{t("adminSystemSmtpTestBody")}
|
||||
</Typography>
|
||||
@@ -663,13 +705,13 @@ export default function AdminSystemPage() {
|
||||
<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 variant="contained" disabled={locked || !emailSettings || !!readErrors.email} onClick={() => void sendTestEmail()}>
|
||||
{action === "test" ? t("adminSystemSending") : t("adminSystemSendTestEmail")}
|
||||
</Button>
|
||||
</Box>
|
||||
</Paper>
|
||||
</PageSection>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user