diff --git a/JobTrackerApi.MariaDb.Tests/RulesPauseMigrationTests.cs b/JobTrackerApi.MariaDb.Tests/RulesPauseMigrationTests.cs new file mode 100644 index 00000000..659f98c3 --- /dev/null +++ b/JobTrackerApi.MariaDb.Tests/RulesPauseMigrationTests.cs @@ -0,0 +1,47 @@ +using JobTrackerApi.Controllers; +using JobTrackerApi.Models; +using JobTrackerApi.Services; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Xunit; + +namespace JobTrackerApi.MariaDb.Tests; + +public sealed class RulesPauseMigrationTests +{ + [Fact] + public async Task Existing_thresholds_survive_pause_migration_and_numeric_writes_preserve_pause() + { + const string owner = "existing-rules-owner"; + const string previous = "20261028090000_AddUserOperationEvents"; + await using var database = await MariaDbDatabase.CreateAsync(); + await using var db = database.Context(owner); + var migrator = db.GetService(); + 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(await controller.Update( + new RuleSettings { AppliedGhostDays = 31, AutomaticGhostingPaused = true }, default)); + Assert.IsType(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($""" + SELECT AppliedGhostDays AS Value FROM UserRuleSettings WHERE OwnerUserId = {owner} + """).ToListAsync(); + Assert.Equal(32, Assert.Single(threshold)); + } +} diff --git a/JobTrackerApi.MariaDb.Tests/StartupAndLockTests.cs b/JobTrackerApi.MariaDb.Tests/StartupAndLockTests.cs index b120c06f..df289b61 100644 --- a/JobTrackerApi.MariaDb.Tests/StartupAndLockTests.cs +++ b/JobTrackerApi.MariaDb.Tests/StartupAndLockTests.cs @@ -79,7 +79,7 @@ public sealed class StartupAndLockTests(ITestOutputHelper output) db.Add(job); await db.SaveChangesAsync(); var migrations = (await db.Database.GetAppliedMigrationsAsync()).ToArray(); - Assert.Equal("20261028090000_AddUserOperationEvents", migrations[^1]); + Assert.Equal(db.Database.GetMigrations(), migrations); // Only this test's newly-created schema is downgraded; no existing database is selected. const string beforeRd21 = "20261021090000_AddDashboardLayoutPreference"; await db.GetService().MigrateAsync(beforeRd21); diff --git a/JobTrackerApi.Tests/BackgroundWorkerTenantTests.cs b/JobTrackerApi.Tests/BackgroundWorkerTenantTests.cs index dcd7d873..a4adf5b2 100644 --- a/JobTrackerApi.Tests/BackgroundWorkerTenantTests.cs +++ b/JobTrackerApi.Tests/BackgroundWorkerTenantTests.cs @@ -1,10 +1,12 @@ using System.Collections.Concurrent; using System.Text.Json; +using JobTrackerApi.Controllers; using JobTrackerApi.Data; using JobTrackerApi.Models; using JobTrackerApi.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; @@ -79,6 +81,39 @@ public sealed class BackgroundWorkerTenantTests Assert.Equal("Applied", jobs[1].Status); } + [Fact] + public async Task Paused_owner_keeps_applied_jobs_while_other_owner_runs_and_resume_takes_effect_next_run() + { + await using var fixture = await Fixture.CreateAsync(new Dictionary { ["Workers:RulesEnabled"] = "true" }); + await fixture.SeedJobsAsync(); + var worker = new RulesHostedService(fixture.Runner, fixture.Configuration, NullLogger.Instance, + Mock.Of(), 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(); + 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().UseBackgroundUser(owner); + var controller = new RulesController(scope.ServiceProvider.GetRequiredService()); + Assert.IsType(await controller.Update( + new RuleSettings { AppliedGhostDays = 5, AutomaticGhostingPaused = paused }, default)); + } + + Task ReadStatuses() => db.JobApplications.IgnoreQueryFilters().AsNoTracking() + .OrderBy(job => job.OwnerUserId).Select(job => job.Status).ToArrayAsync(); + } + [Fact] public async Task Affected_workers_are_disabled_by_default() { diff --git a/JobTrackerApi.Tests/MigrationChainTests.cs b/JobTrackerApi.Tests/MigrationChainTests.cs index 07b2e378..3743b72b 100644 --- a/JobTrackerApi.Tests/MigrationChainTests.cs +++ b/JobTrackerApi.Tests/MigrationChainTests.cs @@ -15,6 +15,28 @@ public sealed class MigrationChainTests { private const string SnapshotMigration = "20260711181039_SyncModelSnapshot"; + [Fact] + public async Task Automatic_ghosting_pause_upgrade_and_rollback_preserve_existing_thresholds() + { + await using var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(); + await using var db = Context(connection); + var migrator = db.GetService(); + 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(connection, "SELECT AutomaticGhostingPaused FROM UserRuleSettings;")); + await ExecuteAsync(connection, "UPDATE UserRuleSettings SET AutomaticGhostingPaused=1;"); + await migrator.MigrateAsync(previous); + Assert.Equal(31L, await ScalarAsync(connection, "SELECT AppliedGhostDays FROM UserRuleSettings;")); + Assert.Equal(0L, await ScalarAsync(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() { diff --git a/JobTrackerApi/Controllers/RulesController.cs b/JobTrackerApi/Controllers/RulesController.cs index a6b74559..99943e5b 100644 --- a/JobTrackerApi/Controllers/RulesController.cs +++ b/JobTrackerApi/Controllers/RulesController.cs @@ -32,6 +32,7 @@ namespace JobTrackerApi.Controllers return Ok(new RuleSettings { Id = 1, + AutomaticGhostingPaused = u.AutomaticGhostingPaused, AppliedFollowUpDays = u.AppliedFollowUpDays, AppliedGhostDays = u.AppliedGhostDays, OfferFollowUpDays = u.OfferFollowUpDays, @@ -60,6 +61,8 @@ namespace JobTrackerApi.Controllers { var s = await GetOrCreateUserSettingsAsync(_db.CurrentUserId, cancellationToken); + if (incoming.AutomaticGhostingPaused is bool paused) + s.AutomaticGhostingPaused = paused; s.AppliedFollowUpDays = Clamp(incoming.AppliedFollowUpDays, 1, 365); s.AppliedGhostDays = Clamp(incoming.AppliedGhostDays, 1, 365); s.OfferFollowUpDays = Clamp(incoming.OfferFollowUpDays, 1, 365); diff --git a/JobTrackerApi/Migrations/20261204180000_AddUserAutomaticGhostingPause.cs b/JobTrackerApi/Migrations/20261204180000_AddUserAutomaticGhostingPause.cs new file mode 100644 index 00000000..9db0c5d9 --- /dev/null +++ b/JobTrackerApi/Migrations/20261204180000_AddUserAutomaticGhostingPause.cs @@ -0,0 +1,25 @@ +using JobTrackerApi.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace JobTrackerApi.Migrations; + +[DbContext(typeof(JobTrackerContext))] +[Migration("20261204180000_AddUserAutomaticGhostingPause")] +public sealed class AddUserAutomaticGhostingPause : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => + migrationBuilder.AddColumn( + 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"); + } +} diff --git a/JobTrackerApi/Migrations/JobTrackerContextModelSnapshot.cs b/JobTrackerApi/Migrations/JobTrackerContextModelSnapshot.cs index 48952d77..90633f4b 100644 --- a/JobTrackerApi/Migrations/JobTrackerContextModelSnapshot.cs +++ b/JobTrackerApi/Migrations/JobTrackerContextModelSnapshot.cs @@ -2458,6 +2458,9 @@ namespace JobTrackerApi.Migrations b.Property("OwnerUserId") .HasColumnType("TEXT"); + b.Property("AutomaticGhostingPaused") + .HasColumnType("INTEGER"); + b.Property("AppliedFollowUpDays") .HasColumnType("INTEGER"); diff --git a/JobTrackerApi/Models/RuleSettings.cs b/JobTrackerApi/Models/RuleSettings.cs index 364100d4..73897caa 100644 --- a/JobTrackerApi/Models/RuleSettings.cs +++ b/JobTrackerApi/Models/RuleSettings.cs @@ -1,3 +1,6 @@ +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; + namespace JobTrackerApi.Models { // Single-row table to store workflow automation thresholds. @@ -5,6 +8,11 @@ namespace JobTrackerApi.Models { public int Id { get; set; } = 1; + // The API accepts this only as a per-user override. Older clients can omit it. + [NotMapped] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public bool? AutomaticGhostingPaused { get; set; } + // Applied / no response yet public int AppliedFollowUpDays { get; set; } = 14; public int AppliedGhostDays { get; set; } = 30; diff --git a/JobTrackerApi/Models/UserRuleSettings.cs b/JobTrackerApi/Models/UserRuleSettings.cs index 9f580ce9..18f83409 100644 --- a/JobTrackerApi/Models/UserRuleSettings.cs +++ b/JobTrackerApi/Models/UserRuleSettings.cs @@ -3,6 +3,7 @@ namespace JobTrackerApi.Models; public sealed class UserRuleSettings { public string OwnerUserId { get; set; } = ""; + public bool AutomaticGhostingPaused { get; set; } // Applied / no response yet public int AppliedFollowUpDays { get; set; } = 14; diff --git a/JobTrackerApi/Services/RulesEngine.cs b/JobTrackerApi/Services/RulesEngine.cs index 1cf8918e..be1f205e 100644 --- a/JobTrackerApi/Services/RulesEngine.cs +++ b/JobTrackerApi/Services/RulesEngine.cs @@ -21,6 +21,7 @@ namespace JobTrackerApi.Services return new RuleSettings { Id = 1, + AutomaticGhostingPaused = u.AutomaticGhostingPaused, AppliedFollowUpDays = u.AppliedFollowUpDays, AppliedGhostDays = u.AppliedGhostDays, OfferFollowUpDays = u.OfferFollowUpDays, diff --git a/JobTrackerApi/Services/RulesHostedService.cs b/JobTrackerApi/Services/RulesHostedService.cs index 10b2919b..320b1ee2 100644 --- a/JobTrackerApi/Services/RulesHostedService.cs +++ b/JobTrackerApi/Services/RulesHostedService.cs @@ -40,6 +40,9 @@ public sealed class RulesHostedService( { var db = services.GetRequiredService(); 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) diff --git a/job-tracker-ui/e2e/settings-page-layout.spec.ts b/job-tracker-ui/e2e/settings-page-layout.spec.ts index abfbb9f2..d479c043 100644 --- a/job-tracker-ui/e2e/settings-page-layout.spec.ts +++ b/job-tracker-ui/e2e/settings-page-layout.spec.ts @@ -54,6 +54,54 @@ async function reflow(page: Page, info: TestInfo, name: string) { expect(outside).toEqual([]); } +for (const [language, width, mode] of [["en", 1440, "light"], ["nb", 390, "dark"]] as const) { + test(`automatic Ghosted pause keeps its draft and persists after retry in ${language}`, async ({ page, headers }, info) => { + const t = translations[language]; + const rulesUrl = `${apiUrl}/rules`; + await page.setViewportSize({ width, height: 900 }); + await page.addInitScript(({ mode, language }) => { + localStorage.setItem("jobtracker.themeMode", mode); + localStorage.setItem("uiLanguage", language); + }, { mode, language }); + expect((await page.request.put(`${apiUrl}/auth/preferences/language`, { + headers, data: { language: language === "nb" ? "nb-NO" : "en" }, + })).status()).toBe(204); + const openRules = async () => { + if (width === 390) { + await page.getByRole("combobox", { name: t.settingsNavigation }).press("Enter"); + await page.getByRole("option", { name: t.settingsTabFollowUps, exact: true }).press("Enter"); + } else { + await page.getByRole("tab", { name: t.settingsTabFollowUps, exact: true }).click(); + } + }; + const readPause = async () => (await (await page.request.get(rulesUrl, { headers })).json()).automaticGhostingPaused; + await page.goto("/settings"); + await openRules(); + const pause = page.getByRole("switch", { name: t.rulesPauseAutomaticGhosting, exact: true }); + await expect(pause).not.toBeChecked(); + await expect(pause).toHaveAccessibleDescription(t.rulesPauseAutomaticGhostingHelp); + await pause.press("Space"); + await expect(pause).toBeChecked(); + await expect(pause).toBeFocused(); + await page.route(rulesUrl, route => route.fulfill({ status: 503, json: {} }), { times: 1 }); + const save = page.getByRole("button", { name: t.rulesSave, exact: true }); + await save.click(); + await expect(page.getByRole("tabpanel", { name: t.settingsTabFollowUps }).getByRole("alert")).toHaveText(t.rulesSaveFailed); + expect(await readPause()).toBe(false); + await expect(pause).toBeChecked(); + const saved = page.waitForResponse(response => response.url() === rulesUrl && response.request().method() === "PUT"); + await save.click(); + expect((await saved).status()).toBe(204); + expect(await readPause()).toBe(true); + await page.reload(); + await openRules(); + await expect(pause).toBeChecked(); + await scan(page, info, `ghosted-pause-${language}`); + await reflow(page, info, `ghosted-pause-${language}`); + await capture(page, info, `ghosted-pause-${language}`); + }); +} + for (const mode of ["light", "dark"] as const) for (const language of ["en", "nb"] as const) { test(`[PRES-E07 E08 E09 S03 S04 S05 J05 J10 M06 W11] ${mode}/${language} Settings headings, reflow and retained actions`, async ({ page, headers }, info) => { test.setTimeout(180_000); @@ -91,7 +139,7 @@ for (const mode of ["light", "dark"] as const) for (const language of ["en", "nb await capture(page, info, `long-heading-${suffix}`); const chooseSection = async (name: string) => { - if (page.viewportSize()!.width < 768) { + if (page.viewportSize()!.width < 1024) { const selector = main.getByRole("combobox", { name: t.settingsNavigation, exact: true }); await selector.focus(); await selector.press("Enter"); diff --git a/job-tracker-ui/src/components/RulesSettingsCard.tsx b/job-tracker-ui/src/components/RulesSettingsCard.tsx index 99dfed4b..6b04d610 100644 --- a/job-tracker-ui/src/components/RulesSettingsCard.tsx +++ b/job-tracker-ui/src/components/RulesSettingsCard.tsx @@ -1,6 +1,6 @@ import React from "react"; -import { Alert, Box, Button, TextField, Typography } from "@mui/material"; +import { Alert, Box, Button, FormControlLabel, FormHelperText, Switch, TextField, Typography } from "@mui/material"; import { PageSection } from "../layout/PageLayout"; import { useI18n } from "../i18n/I18nProvider"; @@ -13,11 +13,12 @@ export type RuleSettings = { offerGhostDays: number; feedbackFollowUpDays: number; feedbackGhostDays: number; + automaticGhostingPaused?: boolean; }; export const RULE_FIELDS = ["appliedFollowUpDays", "appliedGhostDays", "offerFollowUpDays", "offerGhostDays", "feedbackFollowUpDays", "feedbackGhostDays"] as const; export type RuleField = typeof RULE_FIELDS[number]; -export type RuleDraft = Record; +export type RuleDraft = Record & Pick; type Props = { draft: RuleDraft | null; @@ -27,13 +28,15 @@ type Props = { saving: boolean; dirty: boolean; onChange: (field: RuleField, value: string) => void; + onPauseChange: (paused: boolean) => void; onSave: () => void; onDiscard: () => void; onRetry: () => void; }; -export default function RulesSettingsCard({ draft, loadError, saveError, invalid, saving, dirty, onChange, onSave, onDiscard, onRetry }: Props) { +export default function RulesSettingsCard({ draft, loadError, saveError, invalid, saving, dirty, onChange, onPauseChange, onSave, onDiscard, onRetry }: Props) { const { t } = useI18n(); + const pauseDescription = React.useId(); if (!draft) { return ( @@ -64,6 +67,14 @@ export default function RulesSettingsCard({ draft, loadError, saveError, invalid + {typeof draft.automaticGhostingPaused === "boolean" && ( + + onPauseChange(paused)} + slotProps={{ input: { role: "switch", "aria-describedby": pauseDescription } }} />} /> + {t("rulesPauseAutomaticGhostingHelp")} + + )} diff --git a/job-tracker-ui/src/components/SettingsView.tsx b/job-tracker-ui/src/components/SettingsView.tsx index da0c7692..62bb3ae4 100644 --- a/job-tracker-ui/src/components/SettingsView.tsx +++ b/job-tracker-ui/src/components/SettingsView.tsx @@ -54,7 +54,10 @@ type NotificationPrefs = { }; function ruleDraft(settings: RuleSettings): RuleDraft { - return Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])) as RuleDraft; + return { + ...Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])), + automaticGhostingPaused: settings.automaticGhostingPaused, + } as RuleDraft; } export default function SettingsView({ @@ -88,7 +91,10 @@ export default function SettingsView({ const aiControls = useRef(null); const notificationRetryFocus = useRef(null); const currentTranslation = useRef(t); - const rulesDirty = Boolean(rulesDraft && savedRules && RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field]))); + const rulesDirty = Boolean(rulesDraft && savedRules && ( + rulesDraft.automaticGhostingPaused !== savedRules.automaticGhostingPaused || + RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field])) + )); const notificationsDirty = Boolean(notificationPrefs && savedNotificationPrefs && notificationPrefs.emailFollowUpRemindersEnabled !== savedNotificationPrefs.emailFollowUpRemindersEnabled); useEffect(() => { currentTranslation.current = t; }, [t]); @@ -139,11 +145,15 @@ export default function SettingsView({ setSavingRules(true); setRulesSaveError(false); try { - await api.put("/rules", submitted); + const pauseChanged = submittedDraft.automaticGhostingPaused !== savedRules.automaticGhostingPaused; + await api.put("/rules", pauseChanged ? { ...submitted, automaticGhostingPaused: submittedDraft.automaticGhostingPaused } : submitted); if (!session.mounted) return; - setSavedRules(submitted); + const accepted = { ...submitted, automaticGhostingPaused: submittedDraft.automaticGhostingPaused }; + setSavedRules(accepted); // A completed save acknowledges its snapshot, not edits made while it was pending. - setRulesDraft(current => current && RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(submitted) : current); + setRulesDraft(current => current && + current.automaticGhostingPaused === submittedDraft.automaticGhostingPaused && + RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(accepted) : current); toast(currentTranslation.current("rulesSaved"), "success"); } catch { if (session.mounted) setRulesSaveError(true); @@ -260,7 +270,7 @@ export default function SettingsView({ return ( - + {t("settingsNavigation")}