Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7286909bdf | |||
| 2ec595db3b |
@@ -88,6 +88,7 @@ internal sealed class MariaDbDatabase : IAsyncDisposable
|
||||
builder.Services.AddSingleton<IStartupReadiness, StartupReadiness>();
|
||||
builder.Services.AddDbContext<JobTrackerContext>(options => database.Configure(options));
|
||||
builder.Services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<JobTrackerContext>();
|
||||
builder.Services.AddControllers();
|
||||
database.App = builder.Build();
|
||||
await database.App.InitializeJobTrackerAsync();
|
||||
return database;
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Security.Claims;
|
||||
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.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace JobTrackerApi.MariaDb.Tests;
|
||||
|
||||
public sealed class PreferenceConcurrencyTests(ITestOutputHelper output)
|
||||
{
|
||||
[Fact]
|
||||
public async Task Concurrent_language_and_notification_writes_preserve_the_winner_and_allow_a_fresh_retry()
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
await using (var seed = database.Context())
|
||||
{
|
||||
seed.Users.AddRange(
|
||||
new ApplicationUser { Id = "preference-owner", UserName = "owner@example.test", UiLanguage = "en", EmailFollowUpRemindersEnabled = true },
|
||||
new ApplicationUser { Id = "preference-other", UserName = "other@example.test", UiLanguage = "nb-NO", EmailFollowUpRemindersEnabled = false });
|
||||
await seed.SaveChangesAsync();
|
||||
}
|
||||
|
||||
await using var languageScope = database.App.Services.CreateAsyncScope();
|
||||
await using var notificationScope = database.App.Services.CreateAsyncScope();
|
||||
await using var otherScope = database.App.Services.CreateAsyncScope();
|
||||
var language = LanguageController(languageScope.ServiceProvider, "preference-owner");
|
||||
var notification = NotificationController(notificationScope.ServiceProvider, "preference-owner");
|
||||
var otherLanguage = LanguageController(otherScope.ServiceProvider, "preference-other");
|
||||
var otherNotification = NotificationController(otherScope.ServiceProvider, "preference-other");
|
||||
|
||||
// Model two requests that have read the same Identity version before either writes.
|
||||
var languageSnapshot = await languageScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>().GetUserAsync(language.User);
|
||||
var notificationSnapshot = await notificationScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>().GetUserAsync(notification.User);
|
||||
Assert.NotNull(languageSnapshot);
|
||||
Assert.NotNull(notificationSnapshot);
|
||||
Assert.NotSame(languageSnapshot, notificationSnapshot);
|
||||
var originalStamp = languageSnapshot.ConcurrencyStamp;
|
||||
Assert.Equal(originalStamp, notificationSnapshot.ConcurrencyStamp);
|
||||
|
||||
var languageWrite = language.UpdateLanguagePreference(new("nb-NO"));
|
||||
var notificationWrite = notification.Put(new(false));
|
||||
var otherWrite = otherLanguage.UpdateLanguagePreference(new("en"));
|
||||
await Task.WhenAll(languageWrite, notificationWrite, otherWrite);
|
||||
Assert.IsType<NoContentResult>(await otherWrite);
|
||||
Assert.IsType<BadRequestObjectResult>(await otherLanguage.UpdateLanguagePreference(new("fr-FR")));
|
||||
Assert.IsType<OkObjectResult>((await otherNotification.Put(new(true))).Result);
|
||||
|
||||
var languageWon = await languageWrite is NoContentResult;
|
||||
if (languageWon)
|
||||
{
|
||||
var error = Assert.IsType<ObjectResult>((await notificationWrite).Result);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, error.StatusCode);
|
||||
}
|
||||
else
|
||||
{
|
||||
var error = Assert.IsType<BadRequestObjectResult>(await languageWrite);
|
||||
Assert.Contains(new IdentityErrorDescriber().ConcurrencyFailure().Description, Assert.IsType<string>(error.Value));
|
||||
Assert.IsType<OkObjectResult>((await notificationWrite).Result);
|
||||
}
|
||||
|
||||
await using (var read = database.Context())
|
||||
{
|
||||
var owner = await read.Users.AsNoTracking().SingleAsync(user => user.Id == "preference-owner");
|
||||
Assert.Equal(languageWon ? "nb-NO" : "en", owner.UiLanguage);
|
||||
Assert.Equal(languageWon, owner.EmailFollowUpRemindersEnabled);
|
||||
Assert.NotEqual(originalStamp, owner.ConcurrencyStamp);
|
||||
}
|
||||
|
||||
await using var retryScope = database.App.Services.CreateAsyncScope();
|
||||
if (languageWon)
|
||||
Assert.IsType<OkObjectResult>((await NotificationController(retryScope.ServiceProvider, "preference-owner").Put(new(false))).Result);
|
||||
else
|
||||
Assert.IsType<NoContentResult>(await LanguageController(retryScope.ServiceProvider, "preference-owner").UpdateLanguagePreference(new("nb-NO")));
|
||||
|
||||
await using var reload = database.Context();
|
||||
var users = await reload.Users.AsNoTracking().Where(user => user.Id.StartsWith("preference-")).OrderBy(user => user.Id).ToListAsync();
|
||||
Assert.Collection(users,
|
||||
other => { Assert.Equal("preference-other", other.Id); Assert.Equal("en", other.UiLanguage); Assert.True(other.EmailFollowUpRemindersEnabled); },
|
||||
owner => { Assert.Equal("preference-owner", owner.Id); Assert.Equal("nb-NO", owner.UiLanguage); Assert.False(owner.EmailFollowUpRemindersEnabled); });
|
||||
output.WriteLine($"MariaDB {database.ActualVersion}: {(languageWon ? "language" : "notification")} won the overlapping writes; fresh retry preserved both preferences and the other owner's independent writes.");
|
||||
}
|
||||
|
||||
private static AuthController LanguageController(IServiceProvider services, string owner) => new(
|
||||
services.GetRequiredService<IConfiguration>(), services.GetRequiredService<UserManager<ApplicationUser>>(),
|
||||
Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(),
|
||||
NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), services.GetRequiredService<JobTrackerContext>(),
|
||||
externalOrigin: ExternalOrigin.Parse("http://localhost:3300", production: false))
|
||||
{ ControllerContext = Principal(services, owner) };
|
||||
|
||||
private static NotificationSettingsController NotificationController(IServiceProvider services, string owner) => new(
|
||||
services.GetRequiredService<UserManager<ApplicationUser>>()) { ControllerContext = Principal(services, owner) };
|
||||
|
||||
private static ControllerContext Principal(IServiceProvider services, string owner) => new()
|
||||
{
|
||||
HttpContext = new DefaultHttpContext
|
||||
{
|
||||
RequestServices = services,
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, owner)], "test")),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
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(db.Database.GetMigrations(), migrations);
|
||||
Assert.Equal("20261028090000_AddUserOperationEvents", migrations[^1]);
|
||||
// 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,12 +1,10 @@
|
||||
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;
|
||||
@@ -81,39 +79,6 @@ public sealed class BackgroundWorkerTenantTests
|
||||
Assert.Equal("Applied", jobs[1].Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Paused_owner_keeps_applied_jobs_while_other_owner_runs_and_resume_takes_effect_next_run()
|
||||
{
|
||||
await using var fixture = await Fixture.CreateAsync(new Dictionary<string, string?> { ["Workers:RulesEnabled"] = "true" });
|
||||
await fixture.SeedJobsAsync();
|
||||
var worker = new RulesHostedService(fixture.Runner, fixture.Configuration, NullLogger<RulesHostedService>.Instance,
|
||||
Mock.Of<IStartupReadiness>(), new MutableTimeProvider(FixedNow));
|
||||
|
||||
await SaveOwnerRules("user-1", true);
|
||||
await SaveOwnerRules("user-2", null);
|
||||
await SaveOwnerRules("user-1", null);
|
||||
Assert.Equal(new BackgroundWorkerRunResult(true, 2, 2, 0), await worker.RunOnceAsync(default));
|
||||
await using var verification = fixture.Provider.CreateAsyncScope();
|
||||
var db = verification.ServiceProvider.GetRequiredService<JobTrackerContext>();
|
||||
Assert.Equal(new[] { "Applied", "Ghosted" }, await ReadStatuses());
|
||||
|
||||
await SaveOwnerRules("user-1", false);
|
||||
Assert.Equal(new BackgroundWorkerRunResult(true, 2, 2, 0), await worker.RunOnceAsync(default));
|
||||
Assert.Equal(new[] { "Ghosted", "Ghosted" }, await ReadStatuses());
|
||||
|
||||
async Task SaveOwnerRules(string owner, bool? paused)
|
||||
{
|
||||
await using var scope = fixture.Provider.CreateAsyncScope();
|
||||
using var user = scope.ServiceProvider.GetRequiredService<CurrentUserService>().UseBackgroundUser(owner);
|
||||
var controller = new RulesController(scope.ServiceProvider.GetRequiredService<JobTrackerContext>());
|
||||
Assert.IsType<NoContentResult>(await controller.Update(
|
||||
new RuleSettings { AppliedGhostDays = 5, AutomaticGhostingPaused = paused }, default));
|
||||
}
|
||||
|
||||
Task<string[]> ReadStatuses() => db.JobApplications.IgnoreQueryFilters().AsNoTracking()
|
||||
.OrderBy(job => job.OwnerUserId).Select(job => job.Status).ToArrayAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Affected_workers_are_disabled_by_default()
|
||||
{
|
||||
|
||||
@@ -15,28 +15,6 @@ 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,7 +32,6 @@ namespace JobTrackerApi.Controllers
|
||||
return Ok(new RuleSettings
|
||||
{
|
||||
Id = 1,
|
||||
AutomaticGhostingPaused = u.AutomaticGhostingPaused,
|
||||
AppliedFollowUpDays = u.AppliedFollowUpDays,
|
||||
AppliedGhostDays = u.AppliedGhostDays,
|
||||
OfferFollowUpDays = u.OfferFollowUpDays,
|
||||
@@ -61,8 +60,6 @@ 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);
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
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,9 +2458,6 @@ namespace JobTrackerApi.Migrations
|
||||
b.Property<string>("OwnerUserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("AutomaticGhostingPaused")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("AppliedFollowUpDays")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace JobTrackerApi.Models
|
||||
{
|
||||
// Single-row table to store workflow automation thresholds.
|
||||
@@ -8,11 +5,6 @@ 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;
|
||||
|
||||
@@ -3,7 +3,6 @@ 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;
|
||||
|
||||
@@ -21,7 +21,6 @@ namespace JobTrackerApi.Services
|
||||
return new RuleSettings
|
||||
{
|
||||
Id = 1,
|
||||
AutomaticGhostingPaused = u.AutomaticGhostingPaused,
|
||||
AppliedFollowUpDays = u.AppliedFollowUpDays,
|
||||
AppliedGhostDays = u.AppliedGhostDays,
|
||||
OfferFollowUpDays = u.OfferFollowUpDays,
|
||||
|
||||
@@ -40,9 +40,6 @@ 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)
|
||||
|
||||
@@ -54,54 +54,6 @@ 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);
|
||||
@@ -139,7 +91,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 < 1024) {
|
||||
if (page.viewportSize()!.width < 768) {
|
||||
const selector = main.getByRole("combobox", { name: t.settingsNavigation, exact: true });
|
||||
await selector.focus();
|
||||
await selector.press("Enter");
|
||||
|
||||
@@ -93,3 +93,110 @@ test('MariaDB native Career conflict and network failure retain drafts; reviewed
|
||||
limits:'Native browser/API and independent read-only MariaDB connections; controlled request abort; no production or power-loss durability claim.' }), contentType:'application/json' });
|
||||
} finally { await admin.dispose(); await second.dispose(); await fresh.dispose(); }
|
||||
});
|
||||
|
||||
test('MariaDB preference writes overlap across owners and rejected language changes do not survive reload', async ({ page, browser, playwright, baseURL }, info) => {
|
||||
expect(info.config.metadata.mariaDbDatabase).toMatch(/^jt_it_[a-f0-9]{32}$/);
|
||||
const admin = await playwright.request.newContext();
|
||||
const phoneContext = await browser.newContext({ viewport: { width: 390, height: 844 } });
|
||||
const phone = await phoneContext.newPage();
|
||||
const suffix = Date.now();
|
||||
const emails = [`preferences-desktop-${suffix}@example.test`, `preferences-phone-${suffix}@example.test`];
|
||||
const languageUrl = `${api}/auth/preferences/language`;
|
||||
const notificationUrl = `${api}/notification-settings`;
|
||||
const en = translations.en;
|
||||
const nb = translations.nb;
|
||||
let releaseRequests!: () => void;
|
||||
const held = new Promise<void>(resolve => { releaseRequests = resolve; });
|
||||
try {
|
||||
const fixtureOrigins = new Set([new URL(api).origin, new URL(baseURL!).origin]);
|
||||
for (const context of [page.context(), phoneContext]) {
|
||||
await context.route('**/*', route => fixtureOrigins.has(new URL(route.request().url()).origin) ? route.continue() : route.abort());
|
||||
}
|
||||
const administrator = await login(admin, 'e2e@example.test');
|
||||
for (const email of emails) {
|
||||
expect((await admin.post(`${api}/users`, { headers: administrator.headers, data: { email, password, roles: [] } })).status()).toBe(200);
|
||||
}
|
||||
const desktop = await login(page.request, emails[0]);
|
||||
const mobile = await login(phone.request, emails[1]);
|
||||
expect(desktop.id).not.toBe(mobile.id);
|
||||
for (const [request, headers] of [[page.request, desktop.headers], [phone.request, mobile.headers]] as const) {
|
||||
expect((await request.put(languageUrl, { headers, data: { language: 'nb-NO' } })).status()).toBe(204);
|
||||
}
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await page.addInitScript(() => localStorage.setItem('jobtracker.themeMode', 'light'));
|
||||
await phone.addInitScript(() => localStorage.setItem('jobtracker.themeMode', 'dark'));
|
||||
await Promise.all([page.goto('/settings'), phone.goto('/settings')]);
|
||||
await expect(page.locator('html')).toHaveAttribute('lang', 'nb-NO');
|
||||
await expect(phone.locator('html')).toHaveAttribute('lang', 'nb-NO');
|
||||
|
||||
const openNotifications = async () => {
|
||||
const navigation = phone.getByRole('combobox', { name: nb.settingsNavigation });
|
||||
await navigation.press('Enter');
|
||||
await phone.getByRole('option', { name: nb.settingsTabNotifications, exact: true }).press('Enter');
|
||||
await expect(navigation).toBeFocused();
|
||||
};
|
||||
const chooseLanguage = async (label: string, option: string) => {
|
||||
const select = page.getByRole('combobox', { name: label });
|
||||
await select.press('Enter');
|
||||
await page.getByRole('option', { name: option, exact: true }).press('Enter');
|
||||
};
|
||||
const reminders = phone.getByRole('switch', { name: nb.settingsNotificationsFollowUpReminders, exact: true });
|
||||
await openNotifications();
|
||||
await expect(reminders).toBeChecked();
|
||||
await reminders.uncheck();
|
||||
const save = phone.getByRole('button', { name: nb.settingsNotificationsSave, exact: true });
|
||||
await save.focus();
|
||||
await expect(save).toBeFocused();
|
||||
|
||||
const arrived: string[] = [];
|
||||
await page.route(languageUrl, async route => {
|
||||
if (route.request().method() === 'PUT') { arrived.push('language'); await held; }
|
||||
await route.continue();
|
||||
});
|
||||
await phone.route(notificationUrl, async route => {
|
||||
if (route.request().method() === 'PUT') { arrived.push('notification'); await held; }
|
||||
await route.continue();
|
||||
});
|
||||
const languageAccepted = page.waitForResponse(response => response.url() === languageUrl && response.request().method() === 'PUT');
|
||||
const notificationAccepted = phone.waitForResponse(response => response.url() === notificationUrl && response.request().method() === 'PUT');
|
||||
await Promise.all([chooseLanguage(nb.settingsPreferredLanguage, nb.settingsEnglish), save.press('Enter')]);
|
||||
await expect.poll(() => [...arrived].sort()).toEqual(['language', 'notification']);
|
||||
releaseRequests();
|
||||
const accepted = await Promise.all([languageAccepted, notificationAccepted]);
|
||||
expect(accepted.map(response => response.status())).toEqual([204, 200]);
|
||||
await page.unroute(languageUrl);
|
||||
await phone.unroute(notificationUrl);
|
||||
await expect(page.locator('html')).toHaveAttribute('lang', 'en');
|
||||
|
||||
// Send one invalid value to the real server through the native language control.
|
||||
await page.route(languageUrl, route => route.continue({ postData: JSON.stringify({ language: 'fr-FR' }) }), { times: 1 });
|
||||
const rejection = page.waitForResponse(response => response.url() === languageUrl && response.request().method() === 'PUT');
|
||||
await chooseLanguage(en.settingsPreferredLanguage, en.settingsNorwegian);
|
||||
expect((await rejection).status()).toBe(400);
|
||||
await expect(page.getByText(nb.settingsLanguageSaveFailed, { exact: true })).toBeVisible();
|
||||
|
||||
await Promise.all([page.reload(), phone.reload()]);
|
||||
await expect(page.locator('html')).toHaveAttribute('lang', 'en');
|
||||
await expect(page.locator('html')).toHaveAttribute('data-color-scheme', 'light');
|
||||
await expect(phone.locator('html')).toHaveAttribute('lang', 'nb-NO');
|
||||
await expect(phone.locator('html')).toHaveAttribute('data-color-scheme', 'dark');
|
||||
await openNotifications();
|
||||
await expect(reminders).not.toBeChecked();
|
||||
|
||||
const observed = [];
|
||||
for (const email of emails) {
|
||||
const fresh = await playwright.request.newContext();
|
||||
try {
|
||||
await login(fresh, email);
|
||||
const user = await fresh.get(`${api}/auth/me`);
|
||||
const notifications = await fresh.get(notificationUrl);
|
||||
expect(user.status()).toBe(200);
|
||||
expect(notifications.status()).toBe(200);
|
||||
observed.push({ language: (await user.json()).uiLanguage, reminders: (await notifications.json()).emailFollowUpRemindersEnabled });
|
||||
} finally { await fresh.dispose(); }
|
||||
}
|
||||
expect(observed).toEqual([{ language: 'en', reminders: true }, { language: 'nb-NO', reminders: false }]);
|
||||
await info.attach('mariadb-preference-readback', { body: JSON.stringify({ accepted: [204, 200], rejected: 400, observed,
|
||||
desktop: { width: 1440, height: 900, theme: 'light' }, phone: { width: 390, height: 844, theme: 'dark' } }), contentType: 'application/json' });
|
||||
} finally { releaseRequests(); await phoneContext.close(); await admin.dispose(); }
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from "react";
|
||||
|
||||
import { Alert, Box, Button, FormControlLabel, FormHelperText, Switch, TextField, Typography } from "@mui/material";
|
||||
import { Alert, Box, Button, TextField, Typography } from "@mui/material";
|
||||
import { PageSection } from "../layout/PageLayout";
|
||||
|
||||
import { useI18n } from "../i18n/I18nProvider";
|
||||
@@ -13,12 +13,11 @@ 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> & Pick<RuleSettings, "automaticGhostingPaused">;
|
||||
export type RuleDraft = Record<RuleField, string>;
|
||||
|
||||
type Props = {
|
||||
draft: RuleDraft | null;
|
||||
@@ -28,15 +27,13 @@ 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, onPauseChange, onSave, onDiscard, onRetry }: Props) {
|
||||
export default function RulesSettingsCard({ draft, loadError, saveError, invalid, saving, dirty, onChange, onSave, onDiscard, onRetry }: Props) {
|
||||
const { t } = useI18n();
|
||||
const pauseDescription = React.useId();
|
||||
if (!draft) {
|
||||
return (
|
||||
<PageSection title={t("rulesTitle")}>
|
||||
@@ -67,14 +64,6 @@ 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>
|
||||
|
||||
@@ -54,10 +54,7 @@ type NotificationPrefs = {
|
||||
};
|
||||
|
||||
function ruleDraft(settings: RuleSettings): RuleDraft {
|
||||
return {
|
||||
...Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])),
|
||||
automaticGhostingPaused: settings.automaticGhostingPaused,
|
||||
} as RuleDraft;
|
||||
return Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])) as RuleDraft;
|
||||
}
|
||||
|
||||
export default function SettingsView({
|
||||
@@ -91,10 +88,7 @@ export default function SettingsView({
|
||||
const aiControls = useRef<HTMLDivElement>(null);
|
||||
const notificationRetryFocus = useRef<HTMLElement | null>(null);
|
||||
const currentTranslation = useRef(t);
|
||||
const rulesDirty = Boolean(rulesDraft && savedRules && (
|
||||
rulesDraft.automaticGhostingPaused !== savedRules.automaticGhostingPaused ||
|
||||
RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field]))
|
||||
));
|
||||
const rulesDirty = Boolean(rulesDraft && savedRules && RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field])));
|
||||
const notificationsDirty = Boolean(notificationPrefs && savedNotificationPrefs && notificationPrefs.emailFollowUpRemindersEnabled !== savedNotificationPrefs.emailFollowUpRemindersEnabled);
|
||||
|
||||
useEffect(() => { currentTranslation.current = t; }, [t]);
|
||||
@@ -145,15 +139,11 @@ export default function SettingsView({
|
||||
setSavingRules(true);
|
||||
setRulesSaveError(false);
|
||||
try {
|
||||
const pauseChanged = submittedDraft.automaticGhostingPaused !== savedRules.automaticGhostingPaused;
|
||||
await api.put("/rules", pauseChanged ? { ...submitted, automaticGhostingPaused: submittedDraft.automaticGhostingPaused } : submitted);
|
||||
await api.put("/rules", submitted);
|
||||
if (!session.mounted) return;
|
||||
const accepted = { ...submitted, automaticGhostingPaused: submittedDraft.automaticGhostingPaused };
|
||||
setSavedRules(accepted);
|
||||
setSavedRules(submitted);
|
||||
// A completed save acknowledges its snapshot, not edits made while it was pending.
|
||||
setRulesDraft(current => current &&
|
||||
current.automaticGhostingPaused === submittedDraft.automaticGhostingPaused &&
|
||||
RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(accepted) : current);
|
||||
setRulesDraft(current => current && RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(submitted) : current);
|
||||
toast(currentTranslation.current("rulesSaved"), "success");
|
||||
} catch {
|
||||
if (session.mounted) setRulesSaveError(true);
|
||||
@@ -270,7 +260,7 @@ export default function SettingsView({
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<FormControl fullWidth sx={{ display: { xs: "flex", md: "none" }, mb: 1 }}>
|
||||
<FormControl fullWidth sx={{ display: { xs: "flex", sm: "none" }, mb: 1 }}>
|
||||
<InputLabel id="settings-section-label">{t("settingsNavigation")}</InputLabel>
|
||||
<Select
|
||||
labelId="settings-section-label"
|
||||
@@ -286,7 +276,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", md: "flex" }, mb: 1 }}>
|
||||
<Tabs aria-label={t("settings")} value={tab} onChange={(_, v) => selectSection(v)} variant="scrollable" scrollButtons="auto" sx={{ display: { xs: "none", sm: "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")} />
|
||||
@@ -389,7 +379,6 @@ 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));
|
||||
|
||||
@@ -3105,8 +3105,6 @@ 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",
|
||||
@@ -6355,8 +6353,6 @@ 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",
|
||||
|
||||
@@ -4,7 +4,6 @@ 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';
|
||||
@@ -246,31 +245,6 @@ 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: '' } });
|
||||
|
||||
Reference in New Issue
Block a user