Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f506bb8f1d | |||
| b8fa4ae875 | |||
| ac64d2ee22 | |||
| 8b9aa1dafe | |||
| 925b2033e3 | |||
| d555e1d932 | |||
| f6143b9c7d |
@@ -3,7 +3,9 @@ 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;
|
||||
@@ -18,6 +20,39 @@ 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()
|
||||
{
|
||||
|
||||
@@ -135,6 +135,7 @@ 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
|
||||
|
||||
@@ -245,20 +245,19 @@ public sealed class UsersController : ControllerBase
|
||||
|
||||
try
|
||||
{
|
||||
await _email.SendAsync(
|
||||
if (await _email.TrySendAsync(
|
||||
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 NoContent();
|
||||
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: "Password reset email could not be sent right now. Please try again later.");
|
||||
}
|
||||
|
||||
public sealed record SendTestEmailRequest(string? ToEmail, string? Subject, string? Message);
|
||||
|
||||
@@ -6,6 +6,7 @@ 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
|
||||
@@ -19,7 +20,10 @@ public sealed class SmtpEmailSender : IAppEmailSender
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default)
|
||||
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)
|
||||
{
|
||||
var snapshot = await _settings.GetSnapshotAsync(cancellationToken);
|
||||
var host = snapshot.Host;
|
||||
@@ -35,7 +39,7 @@ public sealed class SmtpEmailSender : IAppEmailSender
|
||||
if (!enabled)
|
||||
{
|
||||
_logger.LogWarning("Email sending is disabled. Suppressed email to {To} subject={Subject}", toEmail, subject);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(host)) throw new InvalidOperationException("Email:SmtpHost is not configured.");
|
||||
@@ -61,5 +65,6 @@ public sealed class SmtpEmailSender : IAppEmailSender
|
||||
}
|
||||
|
||||
await Task.Run(() => smtp.Send(msg), cancellationToken);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,3 +20,33 @@ No fresh export build/native browser journey, real API/session/cookie-switch int
|
||||
Evidence is under [cv-library-lifetime](evidence/cv-library-lifetime/SOURCE_RECEIPTS.json). Normalised source hashes and raw receipt hashes bind this bounded result.
|
||||
|
||||
AST graph refresh PASSED on an exact 1,003-file tracked-code snapshot on E: (E:/Storage/Projects/Active/temp docs/jobjakt-local-build/a3-cv-library-source). SOURCE_MANIFEST.json binds files to source commit de2fb452; 10,345 nodes and 36,111 edges. 51 no-symbol warnings retained. Code-only snapshot excludes documentation. Stale generated integration graph: all 2,721 files (97,063,540 bytes) preserved and SHA256-verified on E before replacing its C directory with a junction; no tracked source or evidence removed.
|
||||
|
||||
## Concurrent rename in the library · 20 November 2026
|
||||
|
||||
On application source `7a2b8a95c146d67bc4584740e4a72740cfc25cbf`, the rename dialog opened with the listed name. After confirmation the library fetched the current CV and used its latest revision and settings to write the requested name. A second editor could rename the same CV while that dialog was open. The subsequent write adopted the second editor’s revision and silently replaced their name. If both editors chose the same name the redundant write also created a revision.
|
||||
|
||||
The library now compares the name shown in the dialog with the name returned by the existing detail read. When they differ it shows the latest persisted name and skips the write. If the requested name differs as well, the existing localised conflict message appears. A user can reopen Rename on the current name and explicitly retry. A concurrent change confined to settings still allows a rename, using the latest settings and expected revision. A change after the detail read remains subject to server revision checks.
|
||||
|
||||
**Reproduction and verification.** Both added component cases failed on the original source because a PUT was issued. The corrected combined run passed **77 distinct cases in three suites** (47 CV library, 15 CV helpers, 15 session boundary), zero failed or skipped. The conflict case verifies an explicit retry sends exactly one PUT with the current revision and settings. The equal-name case verifies zero PUTs and no conflict alert. TypeScript, scoped ESLint and Git whitespace checks passed. Raw Jest results are in the local `cv-library-rename-verification` evidence directory. SHA-256 values are `1841f3d9e7199d6f8e6deb886d2581a93f36b66273e3083075e5fd2dd2a46ba5` (red) and `8db570ffa120e80dc047db98ad2f3368a586cd35791a164343ee150742312495` (final). An intermediate invocation included a misspelled suite path and exited 1. Its two successful suites and the separate corrected session-suite run overlap the final 77.
|
||||
|
||||
**Evidence scope.** The tests render the real library and prompt with mocked transport. A native two-tab/browser run, real database writes, PDF rendering and full integrated acceptance were outside this execution. The earlier 85-case verification above is historical. The changed library source blob is `4b5018c6e549a4c5711dcc84a00082629af0ef80` and test blob is `448f46e977f4c733b3d99265e500fed8ee7779bf`.
|
||||
|
||||
The AST-only Graphify refresh completed with 20,198 nodes and 50,033 edges. SQL extraction was unavailable and 146 source files yielded no symbols.
|
||||
|
||||
## Native two-tab rename and SQLite readback · 20 November 2026
|
||||
|
||||
Application source `89128e1c33378bf2c65f2f28b048a63957772eb7`. Two Chromium tabs shared a signed-in synthetic owner and the same CV. Tab one opened Rename on revision 1. Tab two renamed the CV through its library and committed revision 2. Tab one submitted its still-open draft, saw the conflict and the persisted name, and issued **zero PUTs**. After the owner reopened Rename and reviewed that name, tab one issued exactly one PUT with expected revision 2. A reload in tab two displayed the reviewed name. The variant and history APIs returned revisions 1, 2, 3. A separate read-only SQLite query against the disposable database verified exactly those three rows and identical stored settings at each revision.
|
||||
|
||||
**Passed.** Two native cases ran with one worker, zero retries, zero skips and zero flaky results. The new pre-read conflict case took 7.7 s. The existing post-read race took 4.7 s and received the real server 409 before an explicit retry. Both used a freshly built .NET 9.0.317 Release API, a unique local SQLite data root and a fresh static export. The .NET build had zero warnings or errors. The exact-lock Next 16.4.6 build completed compilation, TypeScript and static generation. The three component suites passed all 77 cases on the same dependencies; these overlap the 77 earlier cases. Scoped ESLint, whitespace and the AST refresh passed (20,199 nodes and 50,038 edges).
|
||||
|
||||
**Build recovery.** The initial webpack attempt used a cross-drive dependency junction which resolved Next 16.4.1 and failed module resolution. An independent offline `npm ci` installed 806 packages from the lockfile. The successful runs used Next 16.4.6, Jest 30.4.2 and Playwright 1.62.1. The npm log retained dependency deprecation notices and a pending install script for the resolver. No dependency versions changed. The local API emitted its existing SQLite migration and development key-storage warnings. This run did not qualify production migrations, backup/restore or key storage.
|
||||
|
||||
| Evidence | Identity |
|
||||
| --- | --- |
|
||||
| New browser test, Git blob | `a57a77d87a377ae26ac0869469ab04732d93249b` |
|
||||
| Dependency lock, Git blob | `4c277d454e1164b1e24f21f463b5251052e53eaa` |
|
||||
| Playwright JSON, SHA-256 | `861352d6c00beb09d6e7fee5f0e596992d4eb2658fe07a65c0599f81e344ad10` |
|
||||
| Pinned Jest JSON, SHA-256 | `b6b5fd043f750e5a979f5ba70f81c86e314303eaaf707339b3fbc490a06d980b` |
|
||||
| Static export index / Release API DLL, SHA-256 | `78a5db16a0e85d8f3ead4cb6431d7fd021148b6d02d38007a4701769fb9f7e39` / `769e32f5c4f8bac61743dce67748dd5198cbbc472c8c6c1630ccefe81a1c91d2` |
|
||||
|
||||
Raw receipts are under `E:/Storage/Projects/Active/temp docs/jobjakt-local-build/cv-library-rename-verification/`. Reproduce with the existing isolated static-export Playwright configuration and `phase7-cv-library.spec.ts --grep 'two library tabs|concurrent rename receives ordinary409' --workers=1 --retries=0`. Both loopback servers stopped at completion. Browser coverage was desktop Chromium in English, on synthetic local SQLite records. MariaDB, human/device checks, PDF rendering, full A3, integrated security and release acceptance remain open.
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ 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!';
|
||||
@@ -10,10 +11,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 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.';
|
||||
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.';
|
||||
function copy(key: string, language: Language = 'en') { return (translations[language] as Record<string, string>)[key] ?? key; }
|
||||
function browserRequests(session: Session, path: string, method?: string) { return session.requests.filter(value => value.channel === 'browser' && value.path === `/api${path}` && (!method || value.method === method)); }
|
||||
async function call(records: RequestRecord[], api: APIRequestContext, method: 'GET' | 'POST' | 'PUT', path: string, headers?: Headers, data?: unknown) {
|
||||
async function call(records: RequestRecord[], api: APIRequestContext, method: 'GET' | 'POST' | 'PUT' | 'DELETE', 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;
|
||||
}
|
||||
@@ -69,6 +70,74 @@ 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'));
|
||||
@@ -105,12 +174,16 @@ 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 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 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 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();
|
||||
@@ -130,7 +203,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: 3, name: copy('adminUsersCreateUser', sample.language), exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { level: 2, 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();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test as base, type APIRequestContext, type APIResponse, type Page, type Response, type TestInfo } from '@playwright/test';
|
||||
import AxeBuilder from '@axe-core/playwright';
|
||||
import { translations } from '../src/i18n/translations';
|
||||
import type { CvTheme, CvVariant, CvVariantSummary } from '../src/cvBuilder';
|
||||
import type { CvTheme, CvVariant, CvVariantSummary, CvVariantVersionInfo } from '../src/cvBuilder';
|
||||
import { emptyStructuredCv } from '../src/profileCv';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createHash } from 'node:crypto';
|
||||
@@ -416,6 +416,60 @@ test('[P7-04 PRES-C05 C07 C10 W07] keyboard rename duplicate and delete persist
|
||||
sourceUnchanged: true, frozenUnchanged: true, qualification: 'Actual HTTP rename/duplicate/delete and frozen DTO readback; held duplicate continues the real request. Frozen DTO equality is not archived PDF-byte or restore qualification.' }), contentType: 'application/json' });
|
||||
});
|
||||
|
||||
test('[P7-04 PRES-C05 C10] two library tabs preserve a concurrent name and allow an explicit retry', async ({ page, context, owner }, info) => {
|
||||
const original = await createVariant(page.request, owner, 'Two-tab source CV');
|
||||
const variantUrl = `${apiUrl}/cv/variants/${original.id}`;
|
||||
const versions = async () => (await json<CvVariantVersionInfo[]>(await page.request.get(`${variantUrl}/versions`)))
|
||||
.map(item => item.version).sort((left, right) => left - right);
|
||||
const originalVersions = await versions();
|
||||
const secondTab = await context.newPage();
|
||||
const label = translations.en.cvDashboardRename;
|
||||
const firstChoice = 'CV for school applications';
|
||||
const secondChoice = 'CV for tutoring applications';
|
||||
const writes: number[] = [];
|
||||
page.on('request', request => {
|
||||
if (request.url() === variantUrl && request.method() === 'PUT') writes.push(request.postDataJSON().expectedVersion);
|
||||
});
|
||||
const submit = (tab: Page) => tab.getByRole('dialog').getByRole('button', { name: label, exact: true }).click();
|
||||
const saved = (tab: Page) => tab.waitForResponse(response => response.url() === variantUrl && response.request().method() === 'PUT');
|
||||
|
||||
await enter(page, owner);
|
||||
await enter(secondTab, owner);
|
||||
await openAction(page, original.name, label);
|
||||
await page.getByRole('dialog').getByRole('textbox').fill(firstChoice);
|
||||
|
||||
await openAction(secondTab, original.name, label);
|
||||
await secondTab.getByRole('dialog').getByRole('textbox').fill(secondChoice);
|
||||
const [otherResponse] = await Promise.all([saved(secondTab), submit(secondTab)]);
|
||||
const other = await json<CvVariant>(otherResponse);
|
||||
expect(other).toMatchObject({ name: secondChoice, settings: original.settings, version: original.version + 1 });
|
||||
await expect(card(secondTab, secondChoice)).toBeVisible();
|
||||
|
||||
await submit(page);
|
||||
await expect(page.getByRole('alert').filter({ hasText: translations.en.cvEditorConflict })).toBeVisible();
|
||||
await expect(card(page, secondChoice)).toBeVisible();
|
||||
expect(writes).toEqual([]);
|
||||
expect(await json<CvVariant>(await page.request.get(variantUrl))).toEqual(other);
|
||||
expect(await versions()).toEqual([...originalVersions, other.version]);
|
||||
|
||||
await openAction(page, secondChoice, label);
|
||||
const retry = page.getByRole('dialog').getByRole('textbox');
|
||||
await expect(retry).toHaveValue(secondChoice);
|
||||
await retry.fill(firstChoice);
|
||||
const [retryResponse] = await Promise.all([saved(page), submit(page)]);
|
||||
const reviewed = await json<CvVariant>(retryResponse);
|
||||
expect(writes).toEqual([other.version]);
|
||||
expect(reviewed).toMatchObject({ name: firstChoice, settings: original.settings, version: other.version + 1 });
|
||||
expect(await json<CvVariant>(await page.request.get(variantUrl))).toEqual(reviewed);
|
||||
expect(await versions()).toEqual([...originalVersions, other.version, reviewed.version]);
|
||||
await secondTab.reload();
|
||||
await expect(card(secondTab, firstChoice)).toBeVisible();
|
||||
await info.attach('two-tab-rename-readback', { body: JSON.stringify({
|
||||
initialVersion: original.version, secondTabVersion: other.version, firstTabPutPreconditions: writes,
|
||||
finalVersion: reviewed.version, history: await versions(),
|
||||
}), contentType: 'application/json' });
|
||||
});
|
||||
|
||||
test('[P7-04 PRES-C05 C10] concurrent rename receives ordinary409 and requires owner review before a new save', async ({ page, owner }, info) => {
|
||||
const sourceBefore = await seedSource(page, owner);
|
||||
const original = await createVariant(page.request, owner, 'Recorded conflict CV');
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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/localSMTPfixture.mjs").replaceAll('"', '\\"')}"`;
|
||||
const captureCommand = `"${path.resolve("scripts/runLocalSMTPfixture.mjs").replaceAll('"', '\\"')}"`;
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./auth-tests",
|
||||
|
||||
@@ -53,6 +53,12 @@ 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,8 +1,6 @@
|
||||
// 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;
|
||||
|
||||
@@ -114,12 +112,3 @@ 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(); });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
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(); });
|
||||
@@ -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}
|
||||
|
||||
@@ -509,6 +509,41 @@ test('a rename conflict keeps the original library entry and never retries the w
|
||||
expect(mockedApi.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.each(['My proposed name', 'Name from another editor'])(
|
||||
'a concurrent rename preserves the saved title before applying "%s"', async proposedName => {
|
||||
const latest = { ...existingCv, name: 'Name from another editor', version: 7, settings: emptyCvVariantSettings('clean') };
|
||||
mockedApi.get.mockImplementation(async url => ({ data: url === '/cv/variants' ? [existingCv]
|
||||
: url === '/cv/variants/1' ? latest : themes }) as any);
|
||||
mockedApi.put.mockResolvedValue({ data: { ...latest, name: proposedName, version: 8 } } as any);
|
||||
renderPage();
|
||||
await screen.findByText(existingCv.name);
|
||||
await selectAction('Rename');
|
||||
fireEvent.change(await screen.findByRole('textbox'), { target: { value: proposedName } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }));
|
||||
|
||||
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith('/cv/variants/1'));
|
||||
await waitFor(() => expect(screen.getByRole('link')).toHaveAttribute('aria-disabled', 'false'));
|
||||
expect(mockedApi.put).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole('link', { name: 'Open Name from another editor' })).toBeInTheDocument();
|
||||
if (proposedName === latest.name) {
|
||||
expect(screen.queryByText('CV changed elsewhere')).not.toBeInTheDocument();
|
||||
return;
|
||||
}
|
||||
expect(screen.getByText('CV changed elsewhere')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Actions for Name from another editor' }));
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: 'Rename' }));
|
||||
const retry = await screen.findByRole('textbox');
|
||||
expect(retry).toHaveValue(latest.name);
|
||||
fireEvent.change(retry, { target: { value: proposedName } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }));
|
||||
expect(await screen.findByRole('link', { name: 'Open My proposed name' })).toBeInTheDocument();
|
||||
expect(mockedApi.put).toHaveBeenCalledTimes(1);
|
||||
expect(mockedApi.put).toHaveBeenCalledWith('/cv/variants/1', {
|
||||
name: proposedName, settings: latest.settings, source: 'manual', expectedVersion: latest.version,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test('cancelling deletion returns focus to the surviving CV action control without removing the CV', async () => {
|
||||
mockedApi.get.mockImplementation(async (url) => ({ data: url === '/cv/variants' ? [existingCv] : themes }) as any);
|
||||
renderPage();
|
||||
|
||||
@@ -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",
|
||||
@@ -3285,6 +3287,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 +3782,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",
|
||||
|
||||
@@ -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>);
|
||||
|
||||
@@ -13,16 +13,17 @@ 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) {
|
||||
function renderVerifyEmailPage(search: string, emailChange = false, strict = false) {
|
||||
const path = emailChange ? '/confirm-email-change' : '/verify-email';
|
||||
window.history.pushState({}, '', `${path}${search}`);
|
||||
return render(
|
||||
const tree = (
|
||||
<MemoryRouter initialEntries={[`${path}${search}`]}>
|
||||
<I18nProvider>
|
||||
<VerifyEmailPage emailChange={emailChange} />
|
||||
</I18nProvider>
|
||||
</MemoryRouter>,
|
||||
</MemoryRouter>
|
||||
);
|
||||
return render(strict ? <React.StrictMode>{tree}</React.StrictMode> : tree);
|
||||
}
|
||||
|
||||
describe('VerifyEmailPage', () => {
|
||||
@@ -68,6 +69,15 @@ 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; }));
|
||||
|
||||
@@ -209,7 +209,10 @@ 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()) toast(getApiErrorMessage(e, currentTranslation.current("adminUsersResetFailed")), "error");
|
||||
if (active()) {
|
||||
const fallback = currentTranslation.current("adminUsersResetFailed");
|
||||
toast(e?.response?.status === 503 ? fallback : getApiErrorMessage(e, fallback), "error");
|
||||
}
|
||||
}
|
||||
finally { finishAction(active); }
|
||||
}, [beginAction, finishAction, toast]);
|
||||
|
||||
@@ -173,15 +173,23 @@ export default function CvBuilderPage() {
|
||||
if (!active) return;
|
||||
const current = variants.find((item) => item.id === id);
|
||||
try {
|
||||
const nextName = await promptForValue({ key: "cvDashboardRenameMessage" }, current?.name ?? "", { title: { key: "cvDashboardRenameCv" }, confirmLabel: { key: "cvDashboardRename" } });
|
||||
if (!active() || !nextName?.trim() || nextName.trim() === current?.name) return;
|
||||
const input = await promptForValue({ key: "cvDashboardRenameMessage" }, current?.name ?? "", { title: { key: "cvDashboardRenameCv" }, confirmLabel: { key: "cvDashboardRename" } });
|
||||
const nextName = input?.trim();
|
||||
if (!active() || !nextName || nextName === current?.name) return;
|
||||
setPending(true);
|
||||
const variant = await cvBuilderApi.get(id);
|
||||
if (!active()) return;
|
||||
const updated = await cvBuilderApi.save(id, { name: nextName.trim(), settings: variant.settings, source: "manual", expectedVersion: variant.version });
|
||||
const renamedElsewhere = variant.name !== current?.name;
|
||||
const updated = renamedElsewhere ? variant : await cvBuilderApi.save(id, {
|
||||
name: nextName, settings: variant.settings, source: "manual", expectedVersion: variant.version,
|
||||
});
|
||||
if (!active()) return;
|
||||
setVariants((items) => items.map((item) => item.id === id ? { ...item, name: updated.name, updatedAtUtc: updated.updatedAtUtc, version: updated.version } : item));
|
||||
toast(localeRef.current("cvDashboardRenamed"), "success");
|
||||
if (renamedElsewhere && updated.name !== nextName) {
|
||||
setActionError({ key: "cvEditorConflict" });
|
||||
} else {
|
||||
toast(localeRef.current("cvDashboardRenamed"), "success");
|
||||
}
|
||||
} catch (err) { if (active()) setActionError({ error: err, key: "cvDashboardRenameFailed" }); }
|
||||
finally { finishAction(active); }
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { Alert, Box, Button, CircularProgress, Typography } from "@mui/material";
|
||||
|
||||
@@ -17,12 +17,14 @@ 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 params = new URLSearchParams(window.location.search);
|
||||
const search = window.location.search;
|
||||
const params = new URLSearchParams(search);
|
||||
const userId = params.get("userId") || "";
|
||||
const email = params.get("email") || "";
|
||||
const token = params.get("token") || "";
|
||||
@@ -33,9 +35,14 @@ 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;
|
||||
api
|
||||
.post(emailChange ? "/auth/email-change/confirm" : "/auth/verify-email", emailChange ? { userId, email, token } : { userId, token })
|
||||
submission.current.result
|
||||
.then(() => { if (active) setStatus("success"); })
|
||||
.catch((cause: unknown) => {
|
||||
if (!active) return;
|
||||
|
||||
Reference in New Issue
Block a user