Compare commits

..

1 Commits

Author SHA1 Message Date
cesnimda e9fa42eccf Allow users to pause automatic Ghosted updates
CI and Deploy / test (pull_request) Failing after 4m31s
CI and Deploy / deploy (pull_request) Has been skipped
2026-12-04 18:27:24 +01:00
28 changed files with 291 additions and 179 deletions
@@ -0,0 +1,47 @@
using JobTrackerApi.Controllers;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Xunit;
namespace JobTrackerApi.MariaDb.Tests;
public sealed class RulesPauseMigrationTests
{
[Fact]
public async Task Existing_thresholds_survive_pause_migration_and_numeric_writes_preserve_pause()
{
const string owner = "existing-rules-owner";
const string previous = "20261028090000_AddUserOperationEvents";
await using var database = await MariaDbDatabase.CreateAsync();
await using var db = database.Context(owner);
var migrator = db.GetService<IMigrator>();
await migrator.MigrateAsync(previous);
await db.Database.ExecuteSqlInterpolatedAsync($"""
INSERT INTO UserRuleSettings
(OwnerUserId, AppliedFollowUpDays, AppliedGhostDays, OfferFollowUpDays, OfferGhostDays, FeedbackFollowUpDays, FeedbackGhostDays)
VALUES ({owner}, 9, 31, 7, 14, 7, 14)
""");
await migrator.MigrateAsync();
var initial = await RulesEngine.GetSettings(db, default);
Assert.Equal(31, initial.AppliedGhostDays);
Assert.Equal(false, initial.AutomaticGhostingPaused);
var controller = new RulesController(db);
Assert.IsType<NoContentResult>(await controller.Update(
new RuleSettings { AppliedGhostDays = 31, AutomaticGhostingPaused = true }, default));
Assert.IsType<NoContentResult>(await controller.Update(new RuleSettings { AppliedGhostDays = 32 }, default));
var committed = await RulesEngine.GetSettings(db, default);
Assert.Equal(true, committed.AutomaticGhostingPaused);
Assert.Equal(32, committed.AppliedGhostDays);
await migrator.MigrateAsync(previous);
var threshold = await db.Database.SqlQuery<int>($"""
SELECT AppliedGhostDays AS Value FROM UserRuleSettings WHERE OwnerUserId = {owner}
""").ToListAsync();
Assert.Equal(32, Assert.Single(threshold));
}
}
@@ -79,7 +79,7 @@ public sealed class StartupAndLockTests(ITestOutputHelper output)
db.Add(job);
await db.SaveChangesAsync();
var migrations = (await db.Database.GetAppliedMigrationsAsync()).ToArray();
Assert.Equal("20261028090000_AddUserOperationEvents", migrations[^1]);
Assert.Equal(db.Database.GetMigrations(), migrations);
// Only this test's newly-created schema is downgraded; no existing database is selected.
const string beforeRd21 = "20261021090000_AddDashboardLayoutPreference";
await db.GetService<IMigrator>().MigrateAsync(beforeRd21);
@@ -3,9 +3,7 @@ using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
@@ -20,39 +18,6 @@ namespace JobTrackerApi.Tests;
public sealed class AccountDeletionTests
{
[Fact]
public async Task Administrator_queues_only_the_confirmed_account_for_deletion()
{
await InFixtureAsync(enabled: true, async fixture =>
{
var owner = User("owner");
fixture.Db.Users.AddRange(owner, User("admin"));
await fixture.Db.SaveChangesAsync();
using var roles = new RoleManager<IdentityRole>(Mock.Of<IRoleStore<IdentityRole>>(), [],
new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), NullLogger<RoleManager<IdentityRole>>.Instance);
using var users = TestHostFactory.CreateUserManager(owner).Object;
var identity = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "admin"), new Claim(ClaimTypes.Role, "Admin")], "test");
var controller = new UsersController(users, roles, Mock.Of<IAppEmailSender>(), new ConfigurationBuilder().Build(),
NullLogger<UsersController>.Instance, ExternalOrigin.Parse("http://localhost:3000", production: false), deletions: fixture.Service)
{
ControllerContext = new() { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(identity) } }
};
controller.Request.Headers["X-Confirm-Account-Deletion"] = "other@example.test";
Assert.IsType<BadRequestObjectResult>(await controller.Delete(owner.Id, CancellationToken.None));
Assert.Empty(await fixture.Db.AccountDeletionRequests.ToListAsync());
controller.Request.Headers["X-Confirm-Account-Deletion"] = owner.Email;
Assert.IsType<AcceptedResult>(await controller.Delete(owner.Id, CancellationToken.None));
var request = Assert.Single(await fixture.Db.AccountDeletionRequests.ToListAsync());
Assert.Equal(owner.Id, request.OwnerUserId);
Assert.Equal("admin", request.RequestedByUserId);
Assert.Equal(AccountDeletionStatuses.Pending, (await fixture.Db.Users.SingleAsync(user => user.Id == owner.Id)).DeletionStatus);
Assert.Equal(AccountDeletionStatuses.Active, (await fixture.Db.Users.SingleAsync(user => user.Id == "admin")).DeletionStatus);
});
}
[Fact]
public async Task Disabled_lifecycle_never_accepts_a_deletion_request()
{
@@ -1,10 +1,12 @@
using System.Collections.Concurrent;
using System.Text.Json;
using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
@@ -79,6 +81,39 @@ public sealed class BackgroundWorkerTenantTests
Assert.Equal("Applied", jobs[1].Status);
}
[Fact]
public async Task Paused_owner_keeps_applied_jobs_while_other_owner_runs_and_resume_takes_effect_next_run()
{
await using var fixture = await Fixture.CreateAsync(new Dictionary<string, string?> { ["Workers:RulesEnabled"] = "true" });
await fixture.SeedJobsAsync();
var worker = new RulesHostedService(fixture.Runner, fixture.Configuration, NullLogger<RulesHostedService>.Instance,
Mock.Of<IStartupReadiness>(), new MutableTimeProvider(FixedNow));
await SaveOwnerRules("user-1", true);
await SaveOwnerRules("user-2", null);
await SaveOwnerRules("user-1", null);
Assert.Equal(new BackgroundWorkerRunResult(true, 2, 2, 0), await worker.RunOnceAsync(default));
await using var verification = fixture.Provider.CreateAsyncScope();
var db = verification.ServiceProvider.GetRequiredService<JobTrackerContext>();
Assert.Equal(new[] { "Applied", "Ghosted" }, await ReadStatuses());
await SaveOwnerRules("user-1", false);
Assert.Equal(new BackgroundWorkerRunResult(true, 2, 2, 0), await worker.RunOnceAsync(default));
Assert.Equal(new[] { "Ghosted", "Ghosted" }, await ReadStatuses());
async Task SaveOwnerRules(string owner, bool? paused)
{
await using var scope = fixture.Provider.CreateAsyncScope();
using var user = scope.ServiceProvider.GetRequiredService<CurrentUserService>().UseBackgroundUser(owner);
var controller = new RulesController(scope.ServiceProvider.GetRequiredService<JobTrackerContext>());
Assert.IsType<NoContentResult>(await controller.Update(
new RuleSettings { AppliedGhostDays = 5, AutomaticGhostingPaused = paused }, default));
}
Task<string[]> ReadStatuses() => db.JobApplications.IgnoreQueryFilters().AsNoTracking()
.OrderBy(job => job.OwnerUserId).Select(job => job.Status).ToArrayAsync();
}
[Fact]
public async Task Affected_workers_are_disabled_by_default()
{
@@ -15,6 +15,28 @@ public sealed class MigrationChainTests
{
private const string SnapshotMigration = "20260711181039_SyncModelSnapshot";
[Fact]
public async Task Automatic_ghosting_pause_upgrade_and_rollback_preserve_existing_thresholds()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
await using var db = Context(connection);
var migrator = db.GetService<IMigrator>();
const string previous = "20261028090000_AddUserOperationEvents";
await migrator.MigrateAsync(previous);
await ExecuteAsync(connection, """
INSERT INTO UserRuleSettings
(OwnerUserId, AppliedFollowUpDays, AppliedGhostDays, OfferFollowUpDays, OfferGhostDays, FeedbackFollowUpDays, FeedbackGhostDays)
VALUES ('existing-owner', 9, 31, 7, 14, 7, 14);
""");
await migrator.MigrateAsync();
Assert.Equal(0L, await ScalarAsync<long>(connection, "SELECT AutomaticGhostingPaused FROM UserRuleSettings;"));
await ExecuteAsync(connection, "UPDATE UserRuleSettings SET AutomaticGhostingPaused=1;");
await migrator.MigrateAsync(previous);
Assert.Equal(31L, await ScalarAsync<long>(connection, "SELECT AppliedGhostDays FROM UserRuleSettings;"));
Assert.Equal(0L, await ScalarAsync<long>(connection, "SELECT COUNT(*) FROM pragma_table_info('UserRuleSettings') WHERE name='AutomaticGhostingPaused';"));
}
[Fact]
public async Task Letter_document_upgrade_adds_nullable_fields_without_rewriting_old_letters_or_frozen_bytes()
{
@@ -135,7 +135,6 @@ public sealed partial class ProfileCvController : ControllerBase
{
public static readonly NoOpEmailSender Instance = new();
public Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task<bool> TrySendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default) => Task.FromResult(false);
}
private sealed class ThrowingCvPdfExporter : ICvPdfExporter
@@ -32,6 +32,7 @@ namespace JobTrackerApi.Controllers
return Ok(new RuleSettings
{
Id = 1,
AutomaticGhostingPaused = u.AutomaticGhostingPaused,
AppliedFollowUpDays = u.AppliedFollowUpDays,
AppliedGhostDays = u.AppliedGhostDays,
OfferFollowUpDays = u.OfferFollowUpDays,
@@ -60,6 +61,8 @@ namespace JobTrackerApi.Controllers
{
var s = await GetOrCreateUserSettingsAsync(_db.CurrentUserId, cancellationToken);
if (incoming.AutomaticGhostingPaused is bool paused)
s.AutomaticGhostingPaused = paused;
s.AppliedFollowUpDays = Clamp(incoming.AppliedFollowUpDays, 1, 365);
s.AppliedGhostDays = Clamp(incoming.AppliedGhostDays, 1, 365);
s.OfferFollowUpDays = Clamp(incoming.OfferFollowUpDays, 1, 365);
+4 -3
View File
@@ -245,19 +245,20 @@ public sealed class UsersController : ControllerBase
try
{
if (await _email.TrySendAsync(
await _email.SendAsync(
u.Email,
"Password reset",
$"An admin initiated a password reset for your Jobbjakt account.\n\nReset link:\n{link}\n",
cancellationToken
)) return NoContent();
);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send admin-initiated password reset email to {Email}", u.Email);
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: "Password reset email could not be sent right now. Please try again later.");
}
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: "Password reset email could not be sent right now. Please try again later.");
return NoContent();
}
public sealed record SendTestEmailRequest(string? ToEmail, string? Subject, string? Message);
@@ -0,0 +1,25 @@
using JobTrackerApi.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
namespace JobTrackerApi.Migrations;
[DbContext(typeof(JobTrackerContext))]
[Migration("20261204180000_AddUserAutomaticGhostingPause")]
public sealed class AddUserAutomaticGhostingPause : Migration
{
protected override void Up(MigrationBuilder migrationBuilder) =>
migrationBuilder.AddColumn<bool>(
name: "AutomaticGhostingPaused",
table: "UserRuleSettings",
nullable: false,
defaultValue: false);
protected override void Down(MigrationBuilder migrationBuilder)
{
if (ActiveProvider?.Contains("Sqlite", StringComparison.OrdinalIgnoreCase) == true)
migrationBuilder.Sql("ALTER TABLE \"UserRuleSettings\" DROP COLUMN \"AutomaticGhostingPaused\";");
else
migrationBuilder.DropColumn("AutomaticGhostingPaused", "UserRuleSettings");
}
}
@@ -2458,6 +2458,9 @@ namespace JobTrackerApi.Migrations
b.Property<string>("OwnerUserId")
.HasColumnType("TEXT");
b.Property<bool>("AutomaticGhostingPaused")
.HasColumnType("INTEGER");
b.Property<int>("AppliedFollowUpDays")
.HasColumnType("INTEGER");
+8
View File
@@ -1,3 +1,6 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
namespace JobTrackerApi.Models
{
// Single-row table to store workflow automation thresholds.
@@ -5,6 +8,11 @@ namespace JobTrackerApi.Models
{
public int Id { get; set; } = 1;
// The API accepts this only as a per-user override. Older clients can omit it.
[NotMapped]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public bool? AutomaticGhostingPaused { get; set; }
// Applied / no response yet
public int AppliedFollowUpDays { get; set; } = 14;
public int AppliedGhostDays { get; set; } = 30;
+1
View File
@@ -3,6 +3,7 @@ namespace JobTrackerApi.Models;
public sealed class UserRuleSettings
{
public string OwnerUserId { get; set; } = "";
public bool AutomaticGhostingPaused { get; set; }
// Applied / no response yet
public int AppliedFollowUpDays { get; set; } = 14;
+1
View File
@@ -21,6 +21,7 @@ namespace JobTrackerApi.Services
return new RuleSettings
{
Id = 1,
AutomaticGhostingPaused = u.AutomaticGhostingPaused,
AppliedFollowUpDays = u.AppliedFollowUpDays,
AppliedGhostDays = u.AppliedGhostDays,
OfferFollowUpDays = u.OfferFollowUpDays,
@@ -40,6 +40,9 @@ public sealed class RulesHostedService(
{
var db = services.GetRequiredService<JobTrackerContext>();
var settings = await RulesEngine.GetSettings(db, cancellationToken);
if (settings.AutomaticGhostingPaused == true)
return;
var now = timeProvider.GetLocalNow().DateTime;
var lastMessages = await db.Correspondences
.GroupBy(message => message.JobApplicationId)
+2 -7
View File
@@ -6,7 +6,6 @@ namespace JobTrackerApi.Services;
public interface IAppEmailSender
{
Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default);
Task<bool> TrySendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default);
}
public sealed class SmtpEmailSender : IAppEmailSender
@@ -20,10 +19,7 @@ public sealed class SmtpEmailSender : IAppEmailSender
_logger = logger;
}
public Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default)
=> TrySendAsync(toEmail, subject, bodyText, cancellationToken);
public async Task<bool> TrySendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default)
public async Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default)
{
var snapshot = await _settings.GetSnapshotAsync(cancellationToken);
var host = snapshot.Host;
@@ -39,7 +35,7 @@ public sealed class SmtpEmailSender : IAppEmailSender
if (!enabled)
{
_logger.LogWarning("Email sending is disabled. Suppressed email to {To} subject={Subject}", toEmail, subject);
return false;
return;
}
if (string.IsNullOrWhiteSpace(host)) throw new InvalidOperationException("Email:SmtpHost is not configured.");
@@ -65,6 +61,5 @@ public sealed class SmtpEmailSender : IAppEmailSender
}
await Task.Run(() => smtp.Send(msg), cancellationToken);
return true;
}
}
+5 -78
View File
@@ -2,7 +2,6 @@ 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';
import { enUS, nbNO } from '@mui/x-data-grid/locales';
import { startLocalSMTPFixture } from '../scripts/localSMTPfixture.mjs';
const apiUrl = 'http://localhost:5302/api';
const password = 'E2ePassword123!';
@@ -11,10 +10,10 @@ 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 API/Identity/CSRF accounts exercise admin actions, target-session revocation, final-admin protection and non-admin denial. Reset mail reaches a loopback fixture for synthetic .test accounts. Deletion stays disabled. The unavailable-list case returns controlled GET503 responses until Retry. Read Retry does not replay writes. No provider/model/billing/restore/probe/maintenance, production or Phase8 action occurs. Google Fonts css2 requests are aborted and all other nonlocal requests rejected. Chromium viewport/keyboard evidence does not establish physical touch, real zoom or human screen-reader acceptance.';
const boundary = 'Actual isolated API/Identity/CSRF admin and ordinary accounts exercise Users create/read/role persistence, target-session revocation, final-admin conflict, non-admin denial and deletion-disabled 503 without deleting an account. Only the explicitly named first GET503 is controlled. Read Retry does not replay writes. No password-reset mail, provider/model/billing/restore/probe/maintenance, production or Phase8 action occurs. Google Fonts css2 stylesheets are aborted and all other nonlocal requests rejected. Desktop grid horizontal scrolling is intentional and its action reachability is keyboard checked. Chromium viewport/keyboard evidence does not establish physical touch, real zoom or human screen-reader 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' | 'DELETE', path: string, headers?: Headers, data?: unknown) {
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;
}
@@ -70,74 +69,6 @@ async function capture(page: Page, info: TestInfo, name: string) {
function response(page: Page, method: string, path: string) { return page.waitForResponse(value => value.request().method()===method && new URL(value.url()).pathname===`/api${path}`); }
for (const { language, width, theme } of [
{ language: 'en', width: 1440, theme: 'light' },
{ language: 'nb', width: 390, theme: 'dark' },
] as const) {
test(`[U-ADMIN] ${language} ${theme} ${width} reset delivery and deletion denial`, async ({ page, session }) => {
const userPath = `/users/${session.owner.id}`;
const resetPath = `${userPath}/send-password-reset`;
expect((await call(session.requests, page.request, 'POST', resetPath, session.owner.headers)).status()).toBe(403);
expect((await call(session.requests, page.request, 'DELETE', userPath, {
...session.owner.headers, 'X-Confirm-Account-Deletion': session.owner.email,
})).status()).toBe(403);
const administrator = await login(session.requests, page.request, 'e2e@example.test');
expect((await call(session.requests, page.request, 'PUT', '/auth/preferences/language', administrator.headers, { language })).status()).toBe(204);
await page.addInitScript(({ language, theme }) => {
localStorage.setItem('uiLanguage', language);
localStorage.setItem('jobtracker.themeMode', theme);
}, { language, theme });
await start(page, '/admin/users', width);
await expect(page.locator('html')).toHaveAttribute('data-color-scheme', theme);
const actions = page.getByRole('button', {
name: copy('adminUsersActionsFor', language).replace('{name}', session.owner.email), exact: true,
});
const reset = async () => {
const result = response(page, 'POST', resetPath);
await keyboard(actions);
await keyboard(page.getByRole('menuitem', { name: copy('adminUsersSendReset', language), exact: true }));
return (await result).status();
};
expect(await reset()).toBe(503);
await expect(page.getByText(copy('adminUsersResetFailed', language), { exact: true })).toBeVisible();
const settingsPath = '/admin/system/email-settings';
const original = await json<{ enabled: boolean; hasPassword: boolean }>(await call(session.requests, session.admin, 'GET', settingsPath));
expect(original).toMatchObject({ enabled: false, hasPassword: false });
const smtp = await startLocalSMTPFixture();
try {
expect((await call(session.requests, session.admin, 'PUT', settingsPath, session.adminHeaders, {
enabled: true, host: '127.0.0.1', port: smtp.smtpPort, clearPassword: true,
from: 'fixture@example.test', enableSsl: false, timeoutMs: 5000,
})).status()).toBe(200);
expect(await reset()).toBe(204);
await expect(page.getByText(copy('adminUsersResetSent', language), { exact: true })).toBeVisible();
const receipt = await fetch(`http://127.0.0.1:${smtp.controlPort}/messages?recipient=${encodeURIComponent(session.owner.email)}`);
expect(receipt.status).toBe(200);
const messages: Array<{ body: string }> = await receipt.json();
expect(messages.length).toBe(1);
expect(messages[0].body.includes('/reset-password?')).toBe(true);
} finally {
try {
expect((await call(session.requests, session.admin, 'PUT', settingsPath, session.adminHeaders, {
...original, clearPassword: true,
})).status()).toBe(200);
} finally { await smtp.close(); }
}
await keyboard(actions);
await keyboard(page.getByRole('menuitem', { name: copy('adminUsersDelete', language), exact: true }));
const dialog = page.getByRole('dialog', { name: copy('adminUsersDeleteConfirmTitle', language), exact: true });
const deletion = response(page, 'DELETE', userPath);
await keyboard(dialog.getByRole('button', { name: copy('adminUsersDelete', language), exact: true }));
expect((await deletion).status()).toBe(503);
await expect(page.getByText('Account deletion remains disabled until retention and restore safeguards are approved.', { exact: true })).toBeVisible();
await expect(actions).toBeVisible();
});
}
test('[P7-10 Users A01 E09] real admin creation/role persistence revoke sessions while final-admin and disabled deletion remain protected', async ({ page, playwright, session }) => {
const administrator=await login(session.requests, page.request, 'e2e@example.test');
const administrators=(await json<Array<{ id: string; roles: string[] }>>(await call(session.requests, page.request, 'GET', '/users'))).filter(value => value.roles.includes('Admin'));
@@ -174,16 +105,12 @@ test('[P7-10 Users A01 E09] real admin creation/role persistence revoke sessions
});
test('[P7-10 Users A01 E08] unavailable user list recovers by GET without fabricating empty state', async ({ page, session }, info) => {
await login(session.requests, page.request, 'e2e@example.test');
let failReads = true;
await page.route(`${apiUrl}/users`, route => failReads && route.request().method() === 'GET'
? route.fulfill({ status: 503, json: { title: 'Controlled Users read failure' } })
: route.continue());
await login(session.requests, page.request, 'e2e@example.test'); let failed=false;
await page.route(`${apiUrl}/users`, route => { if (route.request().method()==='GET' && !failed) { failed=true; return route.fulfill({ status: 503, json: { title: 'Controlled Users read failure' } }); } return route.continue(); });
await start(page, '/admin/users', 390);
await expect(page.getByRole('alert').filter({ hasText: copy('adminUsersLoadFailed') })).toBeVisible();
await expect(page.getByText(copy('adminUsersNoUsers'), { exact: true })).toHaveCount(0);
const before=session.requests.filter(value => value.channel==='browser' && value.method!=='GET').length;
failReads = false;
await keyboard(page.getByRole('button', { name: copy('retry'), exact: true }));
await expect(page.getByRole('group', { name: copy('adminUsersTitle'), exact: true })).toBeFocused();
await expect(page.getByText('e2e@example.test', { exact: true }).first()).toBeVisible();
@@ -203,7 +130,7 @@ test('[P7-10 Users A01] finite bilingual light/dark widths retain long identitie
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/users', sample.width);
await expect(page.getByRole('heading', { level: 2, name: copy('adminUsersCreateUser', sample.language), exact: true })).toBeVisible();
await expect(page.getByRole('heading', { level: 3, name: copy('adminUsersCreateUser', sample.language), exact: true })).toBeVisible();
if (sample.width>=768) {
const grid=page.getByRole('grid');
await expect(grid.getByRole('row').nth(1)).toBeVisible();
@@ -54,6 +54,54 @@ async function reflow(page: Page, info: TestInfo, name: string) {
expect(outside).toEqual([]);
}
for (const [language, width, mode] of [["en", 1440, "light"], ["nb", 390, "dark"]] as const) {
test(`automatic Ghosted pause keeps its draft and persists after retry in ${language}`, async ({ page, headers }, info) => {
const t = translations[language];
const rulesUrl = `${apiUrl}/rules`;
await page.setViewportSize({ width, height: 900 });
await page.addInitScript(({ mode, language }) => {
localStorage.setItem("jobtracker.themeMode", mode);
localStorage.setItem("uiLanguage", language);
}, { mode, language });
expect((await page.request.put(`${apiUrl}/auth/preferences/language`, {
headers, data: { language: language === "nb" ? "nb-NO" : "en" },
})).status()).toBe(204);
const openRules = async () => {
if (width === 390) {
await page.getByRole("combobox", { name: t.settingsNavigation }).press("Enter");
await page.getByRole("option", { name: t.settingsTabFollowUps, exact: true }).press("Enter");
} else {
await page.getByRole("tab", { name: t.settingsTabFollowUps, exact: true }).click();
}
};
const readPause = async () => (await (await page.request.get(rulesUrl, { headers })).json()).automaticGhostingPaused;
await page.goto("/settings");
await openRules();
const pause = page.getByRole("switch", { name: t.rulesPauseAutomaticGhosting, exact: true });
await expect(pause).not.toBeChecked();
await expect(pause).toHaveAccessibleDescription(t.rulesPauseAutomaticGhostingHelp);
await pause.press("Space");
await expect(pause).toBeChecked();
await expect(pause).toBeFocused();
await page.route(rulesUrl, route => route.fulfill({ status: 503, json: {} }), { times: 1 });
const save = page.getByRole("button", { name: t.rulesSave, exact: true });
await save.click();
await expect(page.getByRole("tabpanel", { name: t.settingsTabFollowUps }).getByRole("alert")).toHaveText(t.rulesSaveFailed);
expect(await readPause()).toBe(false);
await expect(pause).toBeChecked();
const saved = page.waitForResponse(response => response.url() === rulesUrl && response.request().method() === "PUT");
await save.click();
expect((await saved).status()).toBe(204);
expect(await readPause()).toBe(true);
await page.reload();
await openRules();
await expect(pause).toBeChecked();
await scan(page, info, `ghosted-pause-${language}`);
await reflow(page, info, `ghosted-pause-${language}`);
await capture(page, info, `ghosted-pause-${language}`);
});
}
for (const mode of ["light", "dark"] as const) for (const language of ["en", "nb"] as const) {
test(`[PRES-E07 E08 E09 S03 S04 S05 J05 J10 M06 W11] ${mode}/${language} Settings headings, reflow and retained actions`, async ({ page, headers }, info) => {
test.setTimeout(180_000);
@@ -91,7 +139,7 @@ for (const mode of ["light", "dark"] as const) for (const language of ["en", "nb
await capture(page, info, `long-heading-${suffix}`);
const chooseSection = async (name: string) => {
if (page.viewportSize()!.width < 768) {
if (page.viewportSize()!.width < 1024) {
const selector = main.getByRole("combobox", { name: t.settingsNavigation, exact: true });
await selector.focus();
await selector.press("Enter");
@@ -10,7 +10,7 @@ const [backend, app] = base.webServer;
const smtpPort = process.env.AUTH_RECOVERY_SMTP_PORT ?? "2527";
const mailPort = process.env.AUTH_RECOVERY_MAIL_PORT ?? "5303";
const nodeCommand = `"${process.execPath.replaceAll('"', '\\"')}"`;
const captureCommand = `"${path.resolve("scripts/runLocalSMTPfixture.mjs").replaceAll('"', '\\"')}"`;
const captureCommand = `"${path.resolve("scripts/localSMTPfixture.mjs").replaceAll('"', '\\"')}"`;
export default defineConfig({
testDir: "./auth-tests",
-6
View File
@@ -53,12 +53,6 @@ export default defineConfig({
// Temporary SQLite browser lane until all fixture/DB proof helpers migrate to MariaDB.
Database__Provider: "sqlite",
ConnectionStrings__JobTracker: "",
Email__Enabled: "false",
Email__SmtpHost: "127.0.0.1",
Email__SmtpUser: "",
Email__SmtpPassword: "",
Email__From: "fixture@example.test",
AccountLifecycle__DeletionEnabled: "false",
Workers__AiOperationsEnabled: "false",
Workers__CvDocumentImportsEnabled: "false",
// Browser provider responses are fixtures; the server must not start a real NAV search.
@@ -1,6 +1,8 @@
// Test-only mail capture. Never imported by the application.
import { createServer as createSMTPServer } from "node:net";
import { createServer as createHTTPServer } from "node:http";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
const maxMailBytes = 128 * 1024;
@@ -112,3 +114,12 @@ export function decodePlainMessage(raw) {
}
return Buffer.from(body, "latin1").toString("utf8");
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const fixture = await startLocalSMTPFixture({
smtpPort: Number.parseInt(process.env.AUTH_RECOVERY_SMTP_PORT ?? "2527", 10),
controlPort: Number.parseInt(process.env.AUTH_RECOVERY_MAIL_PORT ?? "5303", 10),
});
process.stdout.write(`Local SMTP fixture ready on 127.0.0.1:${fixture.smtpPort}; control 127.0.0.1:${fixture.controlPort}\n`);
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => { void fixture.close(); });
}
@@ -1,8 +0,0 @@
import { startLocalSMTPFixture } from "./localSMTPfixture.mjs";
const fixture = await startLocalSMTPFixture({
smtpPort: Number.parseInt(process.env.AUTH_RECOVERY_SMTP_PORT ?? "2527", 10),
controlPort: Number.parseInt(process.env.AUTH_RECOVERY_MAIL_PORT ?? "5303", 10),
});
process.stdout.write(`Local SMTP fixture ready on 127.0.0.1:${fixture.smtpPort}; control 127.0.0.1:${fixture.controlPort}\n`);
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => { void fixture.close(); });
@@ -1,6 +1,6 @@
import React from "react";
import { Alert, Box, Button, TextField, Typography } from "@mui/material";
import { Alert, Box, Button, FormControlLabel, FormHelperText, Switch, TextField, Typography } from "@mui/material";
import { PageSection } from "../layout/PageLayout";
import { useI18n } from "../i18n/I18nProvider";
@@ -13,11 +13,12 @@ export type RuleSettings = {
offerGhostDays: number;
feedbackFollowUpDays: number;
feedbackGhostDays: number;
automaticGhostingPaused?: boolean;
};
export const RULE_FIELDS = ["appliedFollowUpDays", "appliedGhostDays", "offerFollowUpDays", "offerGhostDays", "feedbackFollowUpDays", "feedbackGhostDays"] as const;
export type RuleField = typeof RULE_FIELDS[number];
export type RuleDraft = Record<RuleField, string>;
export type RuleDraft = Record<RuleField, string> & Pick<RuleSettings, "automaticGhostingPaused">;
type Props = {
draft: RuleDraft | null;
@@ -27,13 +28,15 @@ type Props = {
saving: boolean;
dirty: boolean;
onChange: (field: RuleField, value: string) => void;
onPauseChange: (paused: boolean) => void;
onSave: () => void;
onDiscard: () => void;
onRetry: () => void;
};
export default function RulesSettingsCard({ draft, loadError, saveError, invalid, saving, dirty, onChange, onSave, onDiscard, onRetry }: Props) {
export default function RulesSettingsCard({ draft, loadError, saveError, invalid, saving, dirty, onChange, onPauseChange, onSave, onDiscard, onRetry }: Props) {
const { t } = useI18n();
const pauseDescription = React.useId();
if (!draft) {
return (
<PageSection title={t("rulesTitle")}>
@@ -64,6 +67,14 @@ export default function RulesSettingsCard({ draft, loadError, saveError, invalid
<TextField label={t("rulesFeedbackFollowUpDays")} {...num("feedbackFollowUpDays")} />
<TextField label={t("rulesFeedbackGhostDays")} {...num("feedbackGhostDays")} />
</Box>
{typeof draft.automaticGhostingPaused === "boolean" && (
<Box sx={{ mt: 2 }}>
<FormControlLabel label={t("rulesPauseAutomaticGhosting")}
control={<Switch checked={draft.automaticGhostingPaused} onChange={(_, paused) => onPauseChange(paused)}
slotProps={{ input: { role: "switch", "aria-describedby": pauseDescription } }} />} />
<FormHelperText id={pauseDescription}>{t("rulesPauseAutomaticGhostingHelp")}</FormHelperText>
</Box>
)}
<Box sx={{ display: "flex", justifyContent: "flex-end", flexWrap: "wrap", gap: 1, mt: 2 }}>
<Button onClick={onDiscard} disabled={!dirty || saving}>{t("assetsDiscardChanges")}</Button>
+18 -7
View File
@@ -54,7 +54,10 @@ type NotificationPrefs = {
};
function ruleDraft(settings: RuleSettings): RuleDraft {
return Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])) as RuleDraft;
return {
...Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])),
automaticGhostingPaused: settings.automaticGhostingPaused,
} as RuleDraft;
}
export default function SettingsView({
@@ -88,7 +91,10 @@ export default function SettingsView({
const aiControls = useRef<HTMLDivElement>(null);
const notificationRetryFocus = useRef<HTMLElement | null>(null);
const currentTranslation = useRef(t);
const rulesDirty = Boolean(rulesDraft && savedRules && RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field])));
const rulesDirty = Boolean(rulesDraft && savedRules && (
rulesDraft.automaticGhostingPaused !== savedRules.automaticGhostingPaused ||
RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field]))
));
const notificationsDirty = Boolean(notificationPrefs && savedNotificationPrefs && notificationPrefs.emailFollowUpRemindersEnabled !== savedNotificationPrefs.emailFollowUpRemindersEnabled);
useEffect(() => { currentTranslation.current = t; }, [t]);
@@ -139,11 +145,15 @@ export default function SettingsView({
setSavingRules(true);
setRulesSaveError(false);
try {
await api.put("/rules", submitted);
const pauseChanged = submittedDraft.automaticGhostingPaused !== savedRules.automaticGhostingPaused;
await api.put("/rules", pauseChanged ? { ...submitted, automaticGhostingPaused: submittedDraft.automaticGhostingPaused } : submitted);
if (!session.mounted) return;
setSavedRules(submitted);
const accepted = { ...submitted, automaticGhostingPaused: submittedDraft.automaticGhostingPaused };
setSavedRules(accepted);
// A completed save acknowledges its snapshot, not edits made while it was pending.
setRulesDraft(current => current && RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(submitted) : current);
setRulesDraft(current => current &&
current.automaticGhostingPaused === submittedDraft.automaticGhostingPaused &&
RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(accepted) : current);
toast(currentTranslation.current("rulesSaved"), "success");
} catch {
if (session.mounted) setRulesSaveError(true);
@@ -260,7 +270,7 @@ export default function SettingsView({
return (
<Box sx={{ minWidth: 0 }}>
<FormControl fullWidth sx={{ display: { xs: "flex", sm: "none" }, mb: 1 }}>
<FormControl fullWidth sx={{ display: { xs: "flex", md: "none" }, mb: 1 }}>
<InputLabel id="settings-section-label">{t("settingsNavigation")}</InputLabel>
<Select
labelId="settings-section-label"
@@ -276,7 +286,7 @@ export default function SettingsView({
</Select>
</FormControl>
<Tabs aria-label={t("settings")} value={tab} onChange={(_, v) => selectSection(v)} variant="scrollable" scrollButtons="auto" sx={{ display: { xs: "none", sm: "flex" }, mb: 1 }}>
<Tabs aria-label={t("settings")} value={tab} onChange={(_, v) => selectSection(v)} variant="scrollable" scrollButtons="auto" sx={{ display: { xs: "none", md: "flex" }, mb: 1 }}>
<Tab value={0} id="settings-tab-0" aria-controls="settings-panel-0" label={t("settingsTabGeneral")} />
<Tab value={4} id="settings-tab-4" aria-controls="settings-panel-4" label={t("settingsTabAutomation")} />
<Tab value={1} id="settings-tab-1" aria-controls="settings-panel-1" label={t("settingsTabFollowUps")} />
@@ -379,6 +389,7 @@ export default function SettingsView({
<TabPanel value={tab} index={1} label={t("settingsTabFollowUps")}>
<RulesSettingsCard draft={rulesDraft} loadError={rulesLoadError ? getApiErrorMessage(rulesLoadError.cause, t("rulesLoadFailed")) : null} saveError={rulesSaveError} invalid={invalidRules}
saving={savingRules} dirty={rulesDirty} onSave={() => void saveRules()} onRetry={() => void loadRules()} onDiscard={discardRules}
onPauseChange={paused => setRulesDraft(current => current ? { ...current, automaticGhostingPaused: paused } : current)}
onChange={(field, value) => {
setRulesDraft(current => current ? { ...current, [field]: value } : current);
setInvalidRules(current => current.filter(key => key !== field));
+4
View File
@@ -3105,6 +3105,8 @@ export const translations = {
jobDetailsNothingHighlighted: "Nothing highlighted yet.",
rulesTitle: "Follow-up rules by scenario",
rulesBody: "Set how long to wait before a follow-up is due and when a thread should be treated as ghosted.",
rulesPauseAutomaticGhosting: "Pause automatic Ghosted updates",
rulesPauseAutomaticGhostingHelp: "Applies from the next rules run. Follow-up reminders and manual status changes stay available.",
rulesLoading: "Loading your follow-up settings…",
rulesLoadFailed: "Could not load your follow-up settings.",
rulesAppliedFollowUpDays: "Applied: follow-up days",
@@ -6353,6 +6355,8 @@ export const translations = {
jobDetailsNothingHighlighted: "Ingenting fremhevet ennå.",
rulesTitle: "Oppfølgingsregler per scenario",
rulesBody: "Velg hvor lenge du vil vente før oppfølging forfaller, og når en tråd skal regnes som ghostet.",
rulesPauseAutomaticGhosting: "Sett automatiske Ghostet-oppdateringer på pause",
rulesPauseAutomaticGhostingHelp: "Gjelder fra neste regelkjøring. Oppfølgingspåminnelser og manuelle statusendringer er fortsatt tilgjengelige.",
rulesLoading: "Laster inn oppfølgingsinnstillingene dine…",
rulesLoadFailed: "Kunne ikke laste oppfølgingsinnstillingene dine.",
rulesAppliedFollowUpDays: "Søkt: oppfølgingsdager",
+26
View File
@@ -4,6 +4,7 @@ import { act, fireEvent, render, screen, waitFor, within } from '@testing-librar
import { MemoryRouter } from 'react-router-dom';
import SettingsView from './components/SettingsView';
import type { RuleSettings } from './components/RulesSettingsCard';
import { I18nProvider } from './i18n/I18nProvider';
import { ToastProvider } from './toast';
import { api } from './api';
@@ -245,6 +246,31 @@ test('[PRES-S03] failed Rules save remains actionable after tab return and expli
expect(screen.queryByText('Failed to save rules.')).not.toBeInTheDocument();
});
test('the supported Ghosted pause retains its draft after failure and persists only after an explicit retry', async () => {
const ordinaryGet = mockedApi.get.getMockImplementation()!;
mockedApi.get.mockImplementation(async (url, options) => {
const response = await ordinaryGet(url, options);
if (url !== '/rules') return response;
const { data } = response as { data: RuleSettings };
return { data: { ...data, automaticGhostingPaused: false } };
});
renderView();
await openRules();
const pause = () => screen.getByRole('switch', { name: translations.en.rulesPauseAutomaticGhosting });
expect(pause()).not.toBeChecked();
fireEvent.click(pause());
mockedApi.put.mockRejectedValueOnce(new Error('offline'));
const save = () => screen.getByRole('button', { name: /save rules/i });
fireEvent.click(save());
expect(await screen.findByRole('alert')).toHaveTextContent(translations.en.rulesSaveFailed);
rulesRoundTrip();
expect(pause()).toBeChecked();
fireEvent.click(save());
await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
expect(mockedApi.put).toHaveBeenLastCalledWith('/rules', expect.objectContaining({ automaticGhostingPaused: true }));
expect(pause()).toBeChecked();
});
test('[PRES-S03] invalid and empty Rules input and associated validation survive internal navigation', async () => {
renderView();
fireEvent.change(await openRules(), { target: { value: '' } });
+3 -13
View File
@@ -13,17 +13,16 @@ const mockedApi = api as jest.Mocked<typeof api>;
// jest.fn() in setupTests.ts before every test -- re-arm it here so error-derived text is testable.
const mockedGetApiErrorMessage = getApiErrorMessage as jest.Mock;
function renderVerifyEmailPage(search: string, emailChange = false, strict = false) {
function renderVerifyEmailPage(search: string, emailChange = false) {
const path = emailChange ? '/confirm-email-change' : '/verify-email';
window.history.pushState({}, '', `${path}${search}`);
const tree = (
return render(
<MemoryRouter initialEntries={[`${path}${search}`]}>
<I18nProvider>
<VerifyEmailPage emailChange={emailChange} />
</I18nProvider>
</MemoryRouter>
</MemoryRouter>,
);
return render(strict ? <React.StrictMode>{tree}</React.StrictMode> : tree);
}
describe('VerifyEmailPage', () => {
@@ -69,15 +68,6 @@ describe('VerifyEmailPage', () => {
expect(mockedApi.post).toHaveBeenCalledWith('/auth/email-change/confirm', { userId: 'user-1', email: 'new@example.com', token: 'change-token' });
});
it.each([false, true])('submits a one-use link once across effect replays: emailChange=%s', async emailChange => {
mockedApi.post.mockResolvedValueOnce({ data: {} } as any);
mockedApi.post.mockRejectedValue({ response: { status: 400, data: 'Invalid or expired link.' } });
renderVerifyEmailPage('?userId=user-1&email=new%40example.test&token=one-use', emailChange, true);
expect(await screen.findByText(translations.en[emailChange ? 'confirmEmailChangeSuccess' : 'verifyEmailSuccess'])).toBeInTheDocument();
expect(mockedApi.post).toHaveBeenCalledTimes(1);
});
it.each([false, true])('changing UI language never resubmits a pending confirmation: emailChange=%s', async emailChange => {
let finish!: (value: any) => void;
mockedApi.post.mockReturnValue(new Promise(resolve => { finish = resolve; }));
+1 -4
View File
@@ -209,10 +209,7 @@ export default function AdminUsersPage() {
await api.post(`/users/${u.id}/send-password-reset`);
if (active()) toast(currentTranslation.current("adminUsersResetSent"), "success");
} catch (e: any) {
if (active()) {
const fallback = currentTranslation.current("adminUsersResetFailed");
toast(e?.response?.status === 503 ? fallback : getApiErrorMessage(e, fallback), "error");
}
if (active()) toast(getApiErrorMessage(e, currentTranslation.current("adminUsersResetFailed")), "error");
}
finally { finishAction(active); }
}, [beginAction, finishAction, toast]);
+4 -11
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useState } from "react";
import { Alert, Box, Button, CircularProgress, Typography } from "@mui/material";
@@ -17,14 +17,12 @@ export default function VerifyEmailPage({ emailChange = false }: { emailChange?:
const [status, setStatus] = useState<Status>("verifying");
const [verificationError, setVerificationError] = useState<unknown>(null);
const [missingLink, setMissingLink] = useState(false);
const submission = useRef<{ key: string; result: Promise<unknown> } | null>(null);
useEffect(() => {
setStatus("verifying");
setMissingLink(false);
setVerificationError(null);
const search = window.location.search;
const params = new URLSearchParams(search);
const params = new URLSearchParams(window.location.search);
const userId = params.get("userId") || "";
const email = params.get("email") || "";
const token = params.get("token") || "";
@@ -35,14 +33,9 @@ export default function VerifyEmailPage({ emailChange = false }: { emailChange?:
return;
}
const endpoint = emailChange ? "/auth/email-change/confirm" : "/auth/verify-email";
const key = endpoint + search;
// React can replay the effect while the same one-use token is being consumed.
if (submission.current?.key !== key) {
submission.current = { key, result: api.post(endpoint, emailChange ? { userId, email, token } : { userId, token }) };
}
let active = true;
submission.current.result
api
.post(emailChange ? "/auth/email-change/confirm" : "/auth/verify-email", emailChange ? { userId, email, token } : { userId, token })
.then(() => { if (active) setStatus("success"); })
.catch((cause: unknown) => {
if (!active) return;