Compare commits

..

8 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
cesnimda ac64d2ee22 fix(a11y): announce singular calendar and search counts
Preserve the real result count and localized date. Zero and multiple entries keep the existing translations. The Bokmål search noun has the same form in both cases.

Verified from f6143b9c with 37 component tests and six isolated Chromium/SQLite journeys on ports 4397/5397. New zero/one/two checks reproduced three singular failures before the fix. Next static export, TypeScript and scoped lint passed.

(cherry picked from commit 86d2305e64)
2026-11-20 19:31:15 +01:00
cesnimda 8b9aa1dafe test(cv): qualify concurrent library renames in two browser tabs
(cherry picked from commit 68f33253a8)
2026-11-20 19:29:09 +01:00
cesnimda 925b2033e3 Record ten successful concept history round trips
(cherry picked from commit 859bb8544a)
2026-11-20 19:24:33 +01:00
cesnimda d555e1d932 Preserve browser navigation through the five design journeys
(cherry picked from commit 9795a491e0)
2026-11-20 19:24:33 +01:00
cesnimda f6143b9c7d fix(cv): preserve concurrent names when renaming from the library
(cherry picked from commit 89128e1c33)
2026-11-20 13:59:48 +01:00
cesnimda a6a95e81d0 Reserve landing preview geometry and defer secondary images
(cherry picked from commit c7f79a4b96)
2026-11-20 13:56:39 +01:00
cesnimda 910573f836 fix(test): resolve PDF fixture from SDK build output
(cherry picked from commit 2aaf7a2426)
2026-11-20 08:58:58 +01:00
34 changed files with 538 additions and 44 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);
@@ -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()
{
+10 -4
View File
@@ -5,6 +5,7 @@
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<DefaultItemExcludes>$(DefaultItemExcludes);PdfBrowserStub/**</DefaultItemExcludes>
</PropertyGroup>
<ItemGroup>
@@ -24,14 +25,19 @@
<ProjectReference Include="..\JobTrackerApi\JobTrackerApi.csproj" />
<!-- Build the fixture, but only our explicit subdirectory copy owns its output.
The Linux apphost has no .exe suffix and collides with that directory if copied to root. -->
<ProjectReference Include="PdfBrowserStub/PdfBrowserStub.csproj" ReferenceOutputAssembly="false" Private="false" />
<Compile Remove="PdfBrowserStub/**/*.cs" />
<ProjectReference Include="PdfBrowserStub/PdfBrowserStub.csproj" ReferenceOutputAssembly="false" Private="false" OutputItemType="PdfBrowserStubAssembly" />
</ItemGroup>
<Target Name="CopyPdfBrowserStub" AfterTargets="Build">
<Error Condition="'@(PdfBrowserStubAssembly)' == ''" Text="The PDF browser stub project returned no output assembly." />
<PropertyGroup>
<PdfBrowserStubOutput>@(PdfBrowserStubAssembly->'%(RootDir)%(Directory)%(Filename)')</PdfBrowserStubOutput>
</PropertyGroup>
<ItemGroup>
<PdfBrowserFiles Include="PdfBrowserStub/bin/$(Configuration)/net9.0/*" />
<PdfBrowserFiles Include="$(PdfBrowserStubOutput).*" />
<!-- The Unix apphost is the only fixture file without an extension. -->
<PdfBrowserFiles Include="$(PdfBrowserStubOutput)" Condition="$([System.IO.File]::Exists('$(PdfBrowserStubOutput)'))" />
</ItemGroup>
<Copy SourceFiles="@(PdfBrowserFiles)" DestinationFolder="$(TargetDir)PdfBrowserStub" />
<Copy SourceFiles="@(PdfBrowserFiles)" DestinationFolder="$(TargetDir)PdfBrowserStub" SkipUnchangedFiles="true" />
</Target>
</Project>
@@ -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()
{
@@ -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);
@@ -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)
@@ -0,0 +1,28 @@
# Public landing preview measurements
The landing page now reserves the space occupied by its three 1440 × 900 SVG previews while the files are in flight. The dashboard preview begins within the first viewport on desktop and tablet and keeps its default eager load. The two subsequent previews use the browser’s native lazy loading. All three retain their original files, order and translated alternative text.
## Local browser results
Each row covers two cold Chromium 151.0.7922.34 contexts, English/light and Norwegian Bokmål/dark. The probe served the real static exports on loopback with synthetic signed-out authentication responses. It held the SVG response bodies until it could measure their pending layout. The displacement column measures the change in the last preview’s bottom edge in CSS pixels between pending and decoded states. The request and byte columns cover the three previews and the favicon only. The server served these assets uncompressed.
| Viewport | Preview displacement before → after | Initial asset requests before → after | Initial body bytes before → after |
| --- | ---: | ---: | ---: |
| 1440 × 900 | 1,132 → 0 | 4 → 4 | 28,397 → 28,397 |
| 768 × 1024 | 1,346 → 0 | 4 → 4 | 28,397 → 28,397 |
| 390 × 844 | 668 → 0 | 4 → 4 | 28,397 → 28,397 |
| 320 × 568 | 537 → 0 | 4 → 4 | 28,397 → 28,397 |
| 844 × 390 | 1,488 → 0 | 4 → 3 | 28,397 → 18,036 |
All ten comparisons retained the exact settled top, width, height and alternative text of each image. Chromium loaded the 10,361-byte workspace preview on scroll in both landscape-phone samples. Scrolling through the page decoded every image once per sample. In the other eight samples Chromium prefetched the secondary images before scrolling.
Every cold context requested the 1,017-byte SVG favicon. Requests for the ICO, manifest and PWA PNGs totaled zero in this navigation sample. Those assets remain available for other browser and install flows. Browser prefetch distances can vary. Production latency, field Core Web Vitals, other browser engines, physical devices and the future launch design remain open.
## Reproduction and verification
From an installed `job-tracker-ui` checkout, run `node ../docs/performance/landing-previews/measure.mjs <static-export-directory>` for each build. The JSON output includes pending and settled image rectangles, local request paths, response-body sizes and the browser version. The probe checks the document language, successful image decoding, accessible labels and absence of unexpected application requests or errors. The paired receipts are [before](before.json.gz) and [after](after.json.gz).
- Application source baseline `245f2feaa8bee2db8f5da0797b3e33f6ef8b056e`. The baseline export resided at checkout `171e616b`. Git reported an empty `job-tracker-ui` diff between those commits. Baseline index SHA-256 `31dfd9b2d2e7ea7d9e696b5485d24d7b8daf0b1e078e6539e94a04955b8ff1f8`.
- Candidate landing component blob `a73053174690588c5764f09683d5cabb0fe270e8`. Candidate index SHA-256 `8a8c1121f8a54fad47b91348346ca483bc0e4c06bd1211c85de525931a9d46d8`. Both checkouts used lockfile SHA-256 `1f718d8faa55f5e540d3d7886a51dd19b02b916b6cb23a462ae229e388d7ab98`.
- The new regression check caught missing native width and height attributes on the first implementation with MUI Box. The final native images passed. Three suites passed 41 tests covering landing content, language, auth redirect and public auth presentation. Scoped ESLint passed. The ordinary Next 16.4.6 production build passed TypeScript checking and static export.
- PERF-04 and PERF-15 remain partial. Launch image selection and rights, install-specific devices, other app routes and deployed delivery require their own evidence. A revert of this application change restores the previous eager previews and loading geometry.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,95 @@
// Run from an installed job-tracker-ui checkout. The argument is a built static export.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { createRequire } from 'node:module';
import path from 'node:path';
const { chromium } = createRequire(path.resolve('package.json'))('playwright');
const root = path.resolve(process.argv[2] || 'out');
const previews = ['/mockups/dashboard.svg', '/mockups/pipeline.svg', '/mockups/workspace.svg'];
const tracked = new Set([...previews, '/favicon.svg', '/favicon.ico', '/logo192.png', '/logo512.png', '/manifest.json']);
const mime = { '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.png': 'image/png', '.json': 'application/json' };
const requests = [];
let imageGate;
const server = createServer(async (req, res) => {
try {
const pathname = new URL(req.url, 'http://localhost').pathname;
const file = path.resolve(root, '.' + (pathname === '/' ? '/index.html' : pathname));
if (req.method !== 'GET' || !file.startsWith(root + path.sep)) {
res.writeHead(400).end();
return;
}
const body = await readFile(file);
if (tracked.has(pathname)) requests.push({ path: pathname, bytes: body.length });
if (previews.includes(pathname)) await imageGate;
res.writeHead(200, { 'Content-Type': mime[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' });
res.end(body);
} catch {
res.writeHead(404).end();
}
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const origin = 'http://127.0.0.1:' + server.address().port;
const browser = await chromium.launch({ channel: 'chromium', args: ['--disable-background-networking'] });
try {
const states = [];
for (const [width, height] of [[1440, 900], [768, 1024], [390, 844], [320, 568], [844, 390]]) {
for (const [lang, theme] of [['en', 'light'], ['nb', 'dark']]) {
const begin = requests.length;
let release;
imageGate = new Promise(resolve => { release = resolve; });
const context = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: 1, colorScheme: theme, serviceWorkers: 'block' });
const page = await context.newPage();
const unexpected = [];
page.on('pageerror', error => unexpected.push(error.message));
await page.addInitScript(({ lang, theme }) => {
localStorage.setItem('uiLanguage', lang);
localStorage.setItem('jobtracker.themeMode', theme);
}, { lang, theme });
await context.route('**/*', route => {
const url = new URL(route.request().url());
const local = ['127.0.0.1', 'localhost'].includes(url.hostname);
if (local && route.request().method() === 'GET' && url.pathname === '/api/auth/me') return route.fulfill({ status: 401, json: {} });
if (local && route.request().method() === 'GET' && url.pathname === '/api/auth/config') {
return route.fulfill({ json: { requireAuth: true, localEnabled: true, allowRegistration: true } });
}
if (origin === url.origin && !url.pathname.startsWith('/api/')) return route.continue();
unexpected.push(url.pathname);
return route.abort();
});
const images = page.locator('main img[src^="/mockups/"]');
const boxes = () => images.evaluateAll(nodes => nodes.map(image => {
const rect = image.getBoundingClientRect();
return { src: image.getAttribute('src'), top: Math.round(rect.top + scrollY), width: Math.round(rect.width), height: Math.round(rect.height), alt: image.alt, naturalWidth: image.naturalWidth, naturalHeight: image.naturalHeight };
}));
await page.goto(origin, { waitUntil: 'domcontentloaded' });
await page.getByRole('heading', { level: 1 }).waitFor();
await images.nth(2).waitFor({ state: 'attached' });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
const pending = await boxes();
release();
await page.waitForLoadState('networkidle');
const before = await boxes();
const initial = requests.slice(begin);
assert.equal(await page.locator('html').getAttribute('lang'), lang === 'nb' ? 'nb-NO' : 'en');
for (const image of await images.all()) {
await image.scrollIntoViewIfNeeded();
await image.evaluate(element => element.decode());
}
const after = await boxes();
assert.deepEqual(after.map(image => image.src), previews);
assert.ok(after.every(image => image.alt && image.naturalWidth === 1440 && image.naturalHeight === 900));
assert.deepEqual(unexpected, []);
states.push({ width, height, lang, theme, pending, before, after, initial, settled: requests.slice(begin) });
await context.close();
}
}
console.log(JSON.stringify({ browser: browser.version(), states }, null, 2));
} finally {
await browser.close();
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
}
@@ -0,0 +1,15 @@
# PDF admission test fixture
Verified on Windows x64 with SDK 9.0.317, VSTest 17.14.1 and a locked restore from the local NuGet package cache. The source baseline was `245f2feaa8bee2db8f5da0797b3e33f6ef8b056e`.
| Build | Test selection | Result |
| --- | --- | --- |
| Before fix, Release with a fresh `--artifacts-path` | `Default_limit_refuses_second_actual_browser_until_first_exits` | FAILED. The SDK built the stub in the requested location. The test output lacked the stub and the exporter reported that no browser was available. |
| After fix, Release with a fresh `--artifacts-path` | `PdfRenderAdmissionTests` | PASSED, 22 of 22. |
| After fix, Debug with the conventional output directory | `PdfRenderAdmissionTests` | PASSED, the same 22 of 22. |
Both successful runs built and launched the fixture through `dotnet test`. In each output layout the fixture directory contained exactly the apphost, assembly, symbols, dependency manifest and runtime configuration. All five SHA-256 hashes matched the corresponding stub project output. The conventional stub project's `bin` and `obj` directories already existed during the final relocated run and were excluded from the test content.
To repeat with restored dependencies, use `dotnet test JobTrackerApi.Tests/JobTrackerApi.Tests.csproj -c Debug --filter FullyQualifiedName~PdfRenderAdmissionTests`. For the relocated case, use `-c Release` and add `--artifacts-path <fresh-directory>`.
These tests exercise local process admission, cancellation and cleanup with the synthetic browser. Linux execution, visual PDF acceptance and production rendering remain separate qualifications.
@@ -10,6 +10,8 @@ python -m http.server 4327 --bind 127.0.0.1 --directory docs/ui-modernisation/re
## Compare the experiences
Browser Back and Forward retrace screens and selected opportunities within a concept. For example, open a filtered job, enter its CV workspace and go back twice to return to the filtered results. The ten desktop/phone selected-job journeys exercised this round trip and its forward path on 20 November. Drafts and filters are held in memory for the review session.
| Direction | First interaction | Desktop and phone | Implementation implication |
| --- | --- | --- | --- |
| A · Clear Desk | Scan the activity list and agenda | Compact top navigation, high density, horizontally scrollable on a phone | Existing tracker and agenda owners fit. Check legibility as text size increases. |
@@ -1,5 +1,4 @@
const $ = (s) => document.querySelector(s),
q = new URLSearchParams(location.search);
const $ = (s) => document.querySelector(s);
const screens = [
"home",
"discover",
@@ -14,14 +13,20 @@ const screens = [
"admin",
"onboarding",
];
const selected = (key, allowed, fallback) =>
allowed.includes(q.get(key)) ? q.get(key) : fallback;
function routeFromLocation() {
const query = new URLSearchParams(location.search);
const selected = (key, allowed, fallback) =>
allowed.includes(query.get(key)) ? query.get(key) : fallback;
return {
concept: selected("concept", "ABCDE".split(""), ""),
screen: selected("screen", screens, "home"),
lang: selected("lang", ["en", "nb"], "en"),
theme: selected("theme", ["light", "dark"], "light"),
phone: query.get("mobile") === "1",
};
}
const state = {
concept: selected("concept", "ABCDE".split(""), ""),
screen: selected("screen", screens, "home"),
lang: selected("lang", ["en", "nb"], "en"),
theme: selected("theme", ["light", "dark"], "light"),
phone: q.get("mobile") === "1",
...routeFromLocation(),
calendarView: "agenda",
trackerView: "list",
query: "",
@@ -343,7 +348,11 @@ const records = jobs.map((job, i) => ({
function trackedCount() {
return records.filter((r) => r.stage === "saved").length;
}
let current = records.find((r) => r.id === q.get("job")) || records[0];
function jobFromLocation() {
const id = new URLSearchParams(location.search).get("job");
return records.find((r) => r.id === id) || records[0];
}
let current = jobFromLocation();
const detailText = [
[
"Coordinate community care, support families and work with local healthcare teams.",
@@ -550,7 +559,7 @@ function gallery() {
"",
)}</div><section style="margin-top:45px"><h2>What to compare</h2><p>Try finding a job, saving it, preparing a CV, reviewing a letter and scheduling a follow-up. Switch between desktop and mobile, English and Bokmål, light and dark. These are design prototypes with synthetic data, not provider or production qualification.</p><a href="compare.html">Compare screenshots and tradeoffs</a> · <a href="RESEARCH.md">Research notes</a></section></main>`;
}
function render() {
function render(navigating = false) {
if (!state.concept) {
$("#app").innerHTML = gallery();
return;
@@ -607,20 +616,26 @@ function render() {
.join(
"",
)}</select></label><label><select aria-label="Language" id="lang"><option value="en" ${state.lang === "en" ? "selected" : ""}>English</option><option value="nb" ${state.lang === "nb" ? "selected" : ""}>Norsk</option></select></label><button data-action="theme">${state.theme === "dark" ? "☀ Light" : "☾ Dark"}</button><button data-action="mobile">${state.phone ? t("desktop") : t("mobile")}</button></div><div class="shell"><header class="top"><a class="brand" href="#" data-screen="home"><span>${state.concept === "E" ? "↗" : "j"}</span>${c.name}</a><nav class="nav" aria-label="Primary">${nav.map((s) => link(s, t(s), state.screen === s ? "active" : "")).join("")}</nav><div class="actions">${link("mail", "✉ " + t("mail"))}${link("settings", t("settings"))}<span class="avatar">AO</span></div></header><main class="content" id="main">${(screens[state.screen] || home)()}<details style="margin-top:35px"><summary>${t("help")}</summary><div class="actions" style="margin-top:12px">${["cv", "letter", "mail", "settings", "admin", "onboarding"].map((s) => link(s, t(s))).join("")}</div></details></main>${state.concept === "E" ? `<nav class="journey-nav" aria-label="Journey">${["home", "discover", "applications", "profile", "calendar"].map((s) => link(s, t(s), state.screen === s ? "active" : "")).join("")}</nav>` : ""}</div><footer class="footnote">${t("synthetic")}</footer>`;
history.replaceState(
null,
"",
`?concept=${state.concept}&screen=${state.screen}&lang=${state.lang}&theme=${state.theme}&job=${current.id}${state.phone ? "&mobile=1" : ""}`,
);
const search = `?concept=${state.concept}&screen=${state.screen}&lang=${state.lang}&theme=${state.theme}&job=${current.id}${state.phone ? "&mobile=1" : ""}`;
if (search !== location.search) {
if (navigating) history.pushState(null, "", search);
else history.replaceState(null, "", search);
}
}
window.addEventListener("popstate", () => {
Object.assign(state, routeFromLocation());
current = jobFromLocation();
render();
});
document.addEventListener("click", (event) => {
const a = event.target.closest("[data-screen]");
if (a) {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
if (a.dataset.job)
current = records.find((r) => r.id === a.dataset.job) || records[0];
state.screen = a.dataset.screen;
render();
render(true);
window.scrollTo(0, 0);
return;
}
@@ -630,7 +645,7 @@ document.addEventListener("click", (event) => {
if (screens.includes(action)) {
if (state.screen === "home" && action === "detail") current = records[0];
state.screen = action;
render();
render(true);
window.scrollTo(0, 0);
} else if (action === "theme") {
state.theme = state.theme === "light" ? "dark" : "light";
@@ -659,7 +674,7 @@ document.addEventListener("click", (event) => {
current.followup = true;
state.calendarView = "agenda";
state.screen = "calendar";
render();
render(true);
toast(
state.lang === "nb"
? "Oppfølging lagt til i prototypen"
@@ -706,7 +721,7 @@ document.addEventListener("change", (e) => {
}
if (["concept", "screen", "lang"].includes(e.target.id)) {
state[e.target.id] = e.target.value;
render();
render(e.target.id !== "lang");
}
if (e.target.id === "settingLanguage") {
state.lang = e.target.value;
@@ -5,6 +5,7 @@
"width": 1440,
"lang": "en",
"theme": "light",
"historyRoundTrip": true,
"passed": true
},
{
@@ -12,6 +13,7 @@
"width": 390,
"lang": "nb",
"theme": "dark",
"historyRoundTrip": true,
"passed": true
},
{
@@ -19,6 +21,7 @@
"width": 1440,
"lang": "en",
"theme": "light",
"historyRoundTrip": true,
"passed": true
},
{
@@ -26,6 +29,7 @@
"width": 390,
"lang": "nb",
"theme": "dark",
"historyRoundTrip": true,
"passed": true
},
{
@@ -33,6 +37,7 @@
"width": 1440,
"lang": "en",
"theme": "light",
"historyRoundTrip": true,
"passed": true
},
{
@@ -40,6 +45,7 @@
"width": 390,
"lang": "nb",
"theme": "dark",
"historyRoundTrip": true,
"passed": true
},
{
@@ -47,6 +53,7 @@
"width": 1440,
"lang": "en",
"theme": "light",
"historyRoundTrip": true,
"passed": true
},
{
@@ -54,6 +61,7 @@
"width": 390,
"lang": "nb",
"theme": "dark",
"historyRoundTrip": true,
"passed": true
},
{
@@ -61,6 +69,7 @@
"width": 1440,
"lang": "en",
"theme": "light",
"historyRoundTrip": true,
"passed": true
},
{
@@ -68,6 +77,7 @@
"width": 390,
"lang": "nb",
"theme": "dark",
"historyRoundTrip": true,
"passed": true
}
],
@@ -111,8 +111,18 @@ async function verify() {
await page.locator("#summary").inputValue(),
"Field electrician CV.",
);
await page.goBack();
assert.equal(new URL(page.url()).searchParams.get("screen"), "detail");
assert.equal(await page.locator("main h1").innerText(), "Front-of-house supervisor");
await page.goBack();
assert.equal(await page.locator("#country").inputValue(), "Denmark");
assert.equal(await page.locator("#search").inputValue(), "supervisor");
await page.goForward();
assert.equal(await page.locator("main h1").innerText(), "Front-of-house supervisor");
await page.goForward();
assert.match(await page.locator("main .heading").innerText(), /Harbour House/);
assert.deepEqual(errors, []);
results.push({ concept, width, lang, theme, passed: true });
results.push({ concept, width, lang, theme, historyRoundTrip: true, passed: true });
await page.close();
}
}
+1 -1
View File
@@ -232,7 +232,7 @@ for (const sample of [desktop, { language: 'nb', theme: 'dark', width: 390, heig
await expect(original.locator('xpath=..').locator('time')).toHaveAttribute('datetime', items.find(item => item.jobApplicationId === row.id)!.recordedAt);
await keyboard(page, page.getByRole('button', { name: t.calendarMonth, exact: true }));
const date = await page.evaluate(language => new Intl.DateTimeFormat(language === 'nb' ? 'nb-NO' : 'en-GB', { dateStyle: 'medium', timeZone: 'UTC' }).format(new Date('2026-10-16T12:00:00Z')), sample.language);
const dayName = text(t.calendarDayEvents, { date, count: 1 });
const dayName = text(t.calendarDayEvent, { date, count: 1 });
await keyboard(page, agenda.getByRole('button', { name: dayName, exact: true }));
await expect(original).toBeVisible();
await capture(page, info, sample, 'connected-status-scheduled-month');
@@ -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");
@@ -200,7 +200,13 @@ for (const mode of ["light", "dark"] as const) for (const language of ["en", "nb
await page.keyboard.press("Escape");
await expect(trigger).toBeFocused();
await page.keyboard.press("Control+k");
const announcement = dialog.locator('[aria-live="polite"]');
await input.fill("no-such-workshop-729");
await expect(announcement).toHaveText(t.searchResultsCount.replace("{count}", "0"));
await input.fill("plattformutvikler");
await expect(announcement).toHaveText(t.searchResultCount.replace("{count}", "1"));
await input.fill("Nordlys");
await expect(announcement).toHaveText(t.searchResultsCount.replace("{count}", "2"));
const job = dialog.getByRole("button", { name: /Nordlys.*Tilgjengelig/ });
await expect(job).toBeVisible();
await job.focus();
@@ -45,6 +45,24 @@ test('month toggle persists only view preference and selecting a day keeps linke
expect(await screen.findByRole('table', { name: translations.en.calendarMonth })).toBeVisible();
});
test.each([
['en', 'en-GB', '0 recorded dates', '1 recorded date', '2 recorded dates'],
['nb', 'nb-NO', '0 registrerte datoer', '1 registrert dato', '2 registrerte datoer'],
] as const)('month day names announce the date and its recorded count in %s', async (language, locale, zero, one, two) => {
localStorage.setItem('uiLanguage', language);
const nextDay = { ...row, date: `${month}-16`, recordedAt: `${month}-16T12:00:00` };
get.mockResolvedValue({ data: [row, nextDay, { ...nextDay, jobApplicationId: 43, kind: 'follow-up' }] });
mount();
await screen.findAllByRole('link', { name: /Recorded teacher role/ });
fireEvent.click(screen.getByRole('button', { name: translations[language].calendarMonth }));
const table = within(screen.getByRole('table'));
const formatter = new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' });
for (const [day, expected] of [['14', zero], ['15', one], ['16', two]]) {
const date = formatter.format(new Date(`${month}-${day}T12:00:00Z`));
expect(table.getByText(day, { selector: 'button' })).toHaveAccessibleName(`${date}, ${expected}`);
}
});
test('locale changes translate controls without repeating the read or translating source text', async () => {
mount(); await screen.findByRole('link', { name: /Recorded teacher role/ });
act(() => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: 'nb' })));
@@ -41,6 +41,10 @@ export default function CalendarAgenda({ refreshToken = 0 }: { refreshToken?: nu
return new Map([...result.entries()].sort(([a], [b]) => Number(a < today) - Number(b < today) || a.localeCompare(b)));
}, [resource.data, today]);
const changeMonth = (value: string) => { if (/^[1-9]\d{3}-(0[1-9]|1[0-2])$/.test(value) && Number(value.slice(0, 4)) <= 9998) { setMonth(value); setSelectedDate(null); } };
const dayLabel = (date: string) => {
const count = byDay.get(date)?.length ?? 0;
return t(count === 1 ? 'calendarDayEvent' : 'calendarDayEvents', { date: formatDate(date), count });
};
const offsetMonth = (offset: number) => changeMonth(monthValue(new Date(year, monthNumber - 1 + offset, 1)));
const firstWeekday = (calendarDate(from)!.getUTCDay() + 6) % 7;
const cells = Array.from({ length: Math.ceil((firstWeekday + days) / 7) * 7 }, (_, index) => {
@@ -71,7 +75,7 @@ export default function CalendarAgenda({ refreshToken = 0 }: { refreshToken?: nu
{!resource.loading && !resource.refreshing && !resource.error && <Stack spacing={2}>
{view === 'month' && <Table size="small" aria-label={t('calendarMonth')} sx={{ tableLayout: 'fixed', '& th, & td': { p: 0.25, textAlign: 'center', verticalAlign: 'top' } }}>
<TableHead><TableRow>{Array.from({ length: 7 }, (_, index) => <TableCell component="th" scope="col" key={index} abbr={new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone: 'UTC' }).format(new Date(Date.UTC(2026, 10, 2 + index)))}>{new Intl.DateTimeFormat(locale, { weekday: 'narrow', timeZone: 'UTC' }).format(new Date(Date.UTC(2026, 10, 2 + index)))}</TableCell>)}</TableRow></TableHead>
<TableBody>{Array.from({ length: cells.length / 7 }, (_, week) => <TableRow key={week}>{cells.slice(week * 7, week * 7 + 7).map((date, day) => <TableCell key={day}>{date && <Button size="small" aria-pressed={selectedDate === date} aria-label={t('calendarDayEvents', { date: formatDate(date), count: byDay.get(date)?.length ?? 0 })} onClick={() => setSelectedDate(date)} variant={selectedDate === date ? 'contained' : 'text'} sx={{ minWidth: 0, width: '100%', minHeight: 44, px: 0, flexDirection: 'column' }}>{new Intl.NumberFormat(locale).format(Number(date.slice(-2)))}{byDay.has(date) && <Box component="span" aria-hidden="true" sx={{ width: 5, height: 5, bgcolor: 'currentColor', borderRadius: '50%' }} />}</Button>}</TableCell>)}</TableRow>)}</TableBody>
<TableBody>{Array.from({ length: cells.length / 7 }, (_, week) => <TableRow key={week}>{cells.slice(week * 7, week * 7 + 7).map((date, day) => <TableCell key={day}>{date && <Button size="small" aria-pressed={selectedDate === date} aria-label={dayLabel(date)} onClick={() => setSelectedDate(date)} variant={selectedDate === date ? 'contained' : 'text'} sx={{ minWidth: 0, width: '100%', minHeight: 44, px: 0, flexDirection: 'column' }}>{new Intl.NumberFormat(locale).format(Number(date.slice(-2)))}{byDay.has(date) && <Box component="span" aria-hidden="true" sx={{ width: 5, height: 5, bgcolor: 'currentColor', borderRadius: '50%' }} />}</Button>}</TableCell>)}</TableRow>)}</TableBody>
</Table>}
{view === 'agenda' ? [...byDay].map(([date, items]) => eventList(date, items)) : selectedDate ? (byDay.has(selectedDate) ? eventList(selectedDate, byDay.get(selectedDate)!) : <Typography>{t('calendarDayEmpty')}</Typography>) : <Typography>{t('calendarSelectDay')}</Typography>}
{!resource.data.length && <Typography color="text.secondary">{t('calendarAgendaEmpty')}</Typography>}
@@ -168,7 +168,7 @@ export default function QuickCommandDialog({ open, onClose, onNavigate, onOpenAd
</Box>
<Box aria-live="polite" sx={{ position: "absolute", width: 1, height: 1, overflow: "hidden", clipPath: "inset(50%)" }}>
{searchState === "loading" ? t("loading") : searchState === "ready" ? t("searchResultsCount", { count: allItems.length }) : ""}
{searchState === "loading" ? t("loading") : searchState === "ready" ? t(allItems.length === 1 ? "searchResultCount" : "searchResultsCount", { count: allItems.length }) : ""}
{activeIndex >= 0 ? ` ${allItems[activeIndex]?.label ?? ""}` : ""}
</Box>
{searchState === "error" ? <Alert severity="error" sx={{ mt: 1 }} action={<Button color="inherit" size="small" onClick={() => setSearchAttempt((value) => value + 1)}>{t("retry")}</Button>}>{t("searchLoadFailed")}</Alert> : null}
@@ -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));
+8
View File
@@ -39,6 +39,7 @@ export const translations = {
calendarSelectedMonth: "Selected month",
calendarAgendaFailed: "Could not load recorded calendar dates.",
calendarAgendaEmpty: "No recorded deadlines or follow-up dates in this month.",
calendarDayEvent: "{date}, {count} recorded date",
calendarDayEvents: "{date}, {count} recorded dates",
calendarDayEmpty: "No recorded dates on this day.",
calendarSelectDay: "Select a day to see linked applications.",
@@ -533,6 +534,7 @@ export const translations = {
commandJobs: "Jobs",
commandCompanies: "Companies",
searchLoadFailed: "Search could not be loaded.",
searchResultCount: "{count} result available.",
searchResultsCount: "{count} results available.",
goToDashboard: "Go to dashboard",
analyticsOverview: "Analytics overview",
@@ -3103,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",
@@ -3285,6 +3289,7 @@ export const translations = {
calendarSelectedMonth: "Valgt måned",
calendarAgendaFailed: "Kunne ikke laste registrerte kalenderdatoer.",
calendarAgendaEmpty: "Ingen registrerte søknadsfrister eller oppfølgingsdatoer denne måneden.",
calendarDayEvent: "{date}, {count} registrert dato",
calendarDayEvents: "{date}, {count} registrerte datoer",
calendarDayEmpty: "Ingen registrerte datoer denne dagen.",
calendarSelectDay: "Velg en dag for å se tilknyttede søknader.",
@@ -3779,6 +3784,7 @@ export const translations = {
commandJobs: "Jobber",
commandCompanies: "Selskaper",
searchLoadFailed: "Søket kunne ikke lastes.",
searchResultCount: "{count} treff tilgjengelig.",
searchResultsCount: "{count} treff tilgjengelig.",
goToDashboard: "Gå til dashboard",
analyticsOverview: "Analyseoversikt",
@@ -6349,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",
+16
View File
@@ -50,6 +50,22 @@ test("shows exactly Free and Pro without invented commercial terms", async () =>
expect(mockNavigate).toHaveBeenCalledWith("/login", { state: { from: "/settings" } });
});
test("reserves preview dimensions and keeps the first preview eager", async () => {
render(<MemoryRouter><I18nProvider><LandingPage /></I18nProvider></MemoryRouter>);
const previews = await screen.findAllByRole("img");
expect(previews.map(image => image.getAttribute("src"))).toEqual([
"/mockups/dashboard.svg", "/mockups/pipeline.svg", "/mockups/workspace.svg",
]);
for (const image of previews) {
expect(image).toHaveAttribute("width", "1440");
expect(image).toHaveAttribute("height", "900");
expect(image).toHaveAccessibleName();
}
expect(previews[0]).not.toHaveAttribute("loading", "lazy");
expect(previews[1]).toHaveAttribute("loading", "lazy");
expect(previews[2]).toHaveAttribute("loading", "lazy");
});
test.each([
["en", "Norsk bokmål", "nb", "nb-NO", "To tydelige alternativer"],
["nb", "English", "en", "en", "Two clear plans"],
@@ -60,6 +60,23 @@ test("[P5-00 PRES-E07] command and empty results use valid list semantics", asyn
expect(mockedApi.post).not.toHaveBeenCalled();
});
test.each([
["en", 0, "0 results available."],
["en", 1, "1 result available."],
["en", 2, "2 results available."],
["nb", 0, "0 treff tilgjengelig."],
["nb", 1, "1 treff tilgjengelig."],
["nb", 2, "2 treff tilgjengelig."],
] as const)("quick search announces %s result count %i in the live region", async (language, count, expected) => {
localStorage.setItem("uiLanguage", language);
const jobs = Array.from({ length: count }, (_, index) => ({ id: index + 1, jobTitle: "Radar technician", company: { name: "Workshop" } }));
mockedApi.get.mockImplementation((url: string) => Promise.resolve({ data: url === "/companies" ? [] : { items: jobs } }) as never);
render(<I18nProvider><QuickCommandDialog open onClose={jest.fn()} onNavigate={jest.fn()} onOpenAddJob={jest.fn()} /></I18nProvider>);
fireEvent.change(screen.getByRole("textbox"), { target: { value: "radar" } });
expect(await screen.findByText(expected, { selector: '[aria-live="polite"]' })).toBeInTheDocument();
expect(screen.queryAllByRole("listitem")).toHaveLength(count);
});
test("[P5-02 PRES-E07] search failure is distinct from no matches and Retry recovers", async () => {
mockedApi.get.mockRejectedValueOnce(new Error("offline"));
render(<I18nProvider><QuickCommandDialog open onClose={jest.fn()} onNavigate={jest.fn()} onOpenAddJob={jest.fn()} /></I18nProvider>);
+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: '' } });
+4 -4
View File
@@ -138,20 +138,20 @@ export default function LandingPage() {
</Box>
{/* Product preview */}
<Container maxWidth="lg" sx={{ py: { xs: 6, md: 9 } }}>
<Container maxWidth="lg" sx={{ py: { xs: 6, md: 9 }, "& img": { width: "100%", height: "auto", display: "block" } }}>
<Box sx={{ textAlign: "center", mb: 5 }}>
<Typography sx={{ color: "primary.main", fontWeight: 700, letterSpacing: 1, fontSize: 13 }}>{t("landingPreviewEyebrow")}</Typography>
<Typography component="h2" sx={{ fontWeight: 800, fontSize: { xs: 26, md: 34 }, lineHeight: 1.4, mt: 1 }}>{t("landingPreviewTitle")}</Typography>
</Box>
<Box sx={{ borderRadius: 3, overflow: "hidden", border: "1px solid", borderColor: "divider", boxShadow: 10, mb: 3, bgcolor: "background.paper" }}>
<Box component="img" src="/mockups/dashboard.svg" alt={t("landingDashboardAlt")} sx={{ width: "100%", display: "block" }} />
<img src="/mockups/dashboard.svg" alt={t("landingDashboardAlt")} width={1440} height={900} />
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 3 }}>
<Box sx={{ borderRadius: 3, overflow: "hidden", border: "1px solid", borderColor: "divider", boxShadow: 6, bgcolor: "background.paper" }}>
<Box component="img" src="/mockups/pipeline.svg" alt={t("landingPipelineAlt")} sx={{ width: "100%", display: "block" }} />
<img src="/mockups/pipeline.svg" alt={t("landingPipelineAlt")} width={1440} height={900} loading="lazy" />
</Box>
<Box sx={{ borderRadius: 3, overflow: "hidden", border: "1px solid", borderColor: "divider", boxShadow: 6, bgcolor: "background.paper" }}>
<Box component="img" src="/mockups/workspace.svg" alt={t("landingWorkspaceAlt")} sx={{ width: "100%", display: "block" }} />
<img src="/mockups/workspace.svg" alt={t("landingWorkspaceAlt")} width={1440} height={900} loading="lazy" />
</Box>
</Box>
<Typography sx={{ textAlign: "center", color: "text.secondary", fontSize: 13, mt: 2 }}>{t("landingPreviewCaption")}</Typography>