Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 47f241c7f7 |
@@ -88,7 +88,6 @@ 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;
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
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")),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -93,110 +93,3 @@ 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(); }
|
||||
});
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { parseISO } from "date-fns";
|
||||
|
||||
export function storedCalendarDay(value?: string | null): string {
|
||||
if (!value || !/^\d{4}-\d{2}-\d{2}(?:T|$)/.test(value) || Number.isNaN(+parseISO(value))) return "";
|
||||
return value.slice(0, 10);
|
||||
}
|
||||
|
||||
export function formatStoredCalendarDay(value: string | null | undefined, locale: string): string {
|
||||
const day = storedCalendarDay(value);
|
||||
return day ? new Date(day).toLocaleDateString(locale, { timeZone: "UTC" }) : "";
|
||||
}
|
||||
|
||||
export function saveCalendarDay(day: string, original?: string | null): string | null {
|
||||
return day ? (day === storedCalendarDay(original) ? original! : day) : null;
|
||||
}
|
||||
@@ -19,6 +19,31 @@ beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
test.each([
|
||||
"2026-11-23",
|
||||
"2026-11-23T23:30:00Z",
|
||||
"2026-11-23T00:30:00+14:00",
|
||||
"2026-11-23T00:00:00",
|
||||
null,
|
||||
"2026-02-30",
|
||||
])("preserves the stored company day in the table and editor for %s", async nextContactAt => {
|
||||
const company = { id: 3, name: "Acme", nextContactAt };
|
||||
const day = nextContactAt?.startsWith("2026-11-23") ? "2026-11-23" : "";
|
||||
mockedApi.get.mockResolvedValue({ data: [company] });
|
||||
mockedApi.put.mockResolvedValue({ data: company });
|
||||
render(<I18nProvider><ToastProvider><MemoryRouter><CompaniesTable /></MemoryRouter></ToastProvider></I18nProvider>);
|
||||
const edit = await screen.findByRole("button", { name: "Edit: Acme" });
|
||||
const table = screen.getByRole("row", { name: /Acme/ });
|
||||
if (day) expect(table).toHaveTextContent("11/23/2026");
|
||||
else expect(table).not.toHaveTextContent(/Invalid Date|3\/2\/2026/);
|
||||
fireEvent.click(edit);
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
expect(within(dialog).getByLabelText("Next contact")).toHaveValue(day);
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mockedApi.put).toHaveBeenCalledWith("/companies/3",
|
||||
expect.objectContaining({ nextContactAt: day ? nextContactAt : null })));
|
||||
});
|
||||
|
||||
test("opens one company relationship view with applications and recent contact", async () => {
|
||||
const company = { id: 3, name: "Acme", recruiterName: "Rita", recruiterEmail: "rita@example.test" };
|
||||
mockedApi.get.mockImplementation((url) => Promise.resolve({ data: String(url).endsWith("/relationship") ? {
|
||||
@@ -42,7 +67,7 @@ test.each(["en", "nb"])("company contact dates follow the %s UI locale", async (
|
||||
const nextContactAt = "2026-11-23T12:00:00Z";
|
||||
mockedApi.get.mockResolvedValue({ data: [{ id: 3, name: "Acme", nextContactAt, pipelineStage: "Interview" }] });
|
||||
render(<I18nProvider><ToastProvider><MemoryRouter><CompaniesTable /></MemoryRouter></ToastProvider></I18nProvider>);
|
||||
const expected = new Date(nextContactAt).toLocaleDateString(language === "nb" ? "nb-NO" : "en");
|
||||
const expected = new Date(nextContactAt).toLocaleDateString(language === "nb" ? "nb-NO" : "en", { timeZone: "UTC" });
|
||||
await screen.findByRole("button", { name: `${language === "nb" ? "Rediger" : "Edit"}: Acme` });
|
||||
expect(screen.getByRole("row", { name: /Acme/ })).toHaveTextContent(expected);
|
||||
expect(screen.getByRole("row", { name: /Acme/ })).toHaveTextContent("Interview");
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||
|
||||
import { api, getApiErrorMessage } from "../api";
|
||||
import { formatStoredCalendarDay, saveCalendarDay, storedCalendarDay } from "../calendarDay";
|
||||
import ViewStateNotice from "./ViewStateNotice";
|
||||
import { Company } from "../types";
|
||||
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
|
||||
@@ -107,8 +108,8 @@ export default function CompaniesTable() {
|
||||
setRecruiterEmail(c.recruiterEmail ?? "");
|
||||
setRecruiterLinkedIn(c.recruiterLinkedIn ?? "");
|
||||
setPipelineStage(c.pipelineStage ?? "");
|
||||
setLastContactedAt((c.lastContactedAt ?? "").slice(0, 10));
|
||||
setNextContactAt((c.nextContactAt ?? "").slice(0, 10));
|
||||
setLastContactedAt(storedCalendarDay(c.lastContactedAt));
|
||||
setNextContactAt(storedCalendarDay(c.nextContactAt));
|
||||
setEditOpen(true);
|
||||
};
|
||||
|
||||
@@ -156,8 +157,8 @@ export default function CompaniesTable() {
|
||||
recruiterEmail: recruiterEmail.trim() || null,
|
||||
recruiterLinkedIn: recruiterLinkedIn.trim() || null,
|
||||
pipelineStage: pipelineStage.trim() || null,
|
||||
lastContactedAt: lastContactedAt || null,
|
||||
nextContactAt: nextContactAt || null,
|
||||
lastContactedAt: saveCalendarDay(lastContactedAt, editing.lastContactedAt),
|
||||
nextContactAt: saveCalendarDay(nextContactAt, editing.nextContactAt),
|
||||
});
|
||||
|
||||
companiesResource.setData((prev) => prev.map((x) => (x.id === res.data.id ? res.data : x)));
|
||||
@@ -212,7 +213,7 @@ export default function CompaniesTable() {
|
||||
{renderCompanyMeta(t("companiesSource"), c.source)}
|
||||
{renderCompanyMeta(t("companiesPipeline"), c.pipelineStage)}
|
||||
{renderCompanyMeta(t("companiesRecruiter"), [c.recruiterName, c.recruiterEmail].filter(Boolean).join(" · "))}
|
||||
{renderCompanyMeta(t("companiesNextContact"), c.nextContactAt ? new Date(c.nextContactAt).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : null)}
|
||||
{renderCompanyMeta(t("companiesNextContact"), formatStoredCalendarDay(c.nextContactAt, language === "nb" ? "nb-NO" : "en") || null)}
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
@@ -248,7 +249,7 @@ export default function CompaniesTable() {
|
||||
{c.recruiterName ?? ""}
|
||||
{c.recruiterEmail ? ` (${c.recruiterEmail})` : ""}
|
||||
</TableCell>
|
||||
<TableCell sx={{ whiteSpace: "nowrap" }}>{c.nextContactAt ? new Date(c.nextContactAt).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : ""}</TableCell>
|
||||
<TableCell sx={{ whiteSpace: "nowrap" }}>{formatStoredCalendarDay(c.nextContactAt, language === "nb" ? "nb-NO" : "en")}</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: "nowrap" }}>
|
||||
<IconButton size="small" data-company-relationship={c.id} aria-label={`${t("companiesRelationship")}: ${c.name}`} onClick={() => void openRelationship(c)}>
|
||||
<PeopleAltOutlinedIcon fontSize="small" />
|
||||
@@ -368,8 +369,8 @@ export default function CompaniesTable() {
|
||||
<Stack spacing={2} sx={{ mt: 0.5 }}>
|
||||
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "repeat(3, minmax(0, 1fr))" }, gap: 1.5 }}>
|
||||
{renderCompanyMeta(t("companiesRecruiter"), [relationship.company.recruiterName, relationship.company.recruiterEmail].filter(Boolean).join(" · "))}
|
||||
{renderCompanyMeta(t("companiesLastContacted"), relationship.company.lastContactedAt ? new Date(relationship.company.lastContactedAt).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : null)}
|
||||
{renderCompanyMeta(t("companiesNextContact"), relationship.company.nextContactAt ? new Date(relationship.company.nextContactAt).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : null)}
|
||||
{renderCompanyMeta(t("companiesLastContacted"), formatStoredCalendarDay(relationship.company.lastContactedAt, language === "nb" ? "nb-NO" : "en") || null)}
|
||||
{renderCompanyMeta(t("companiesNextContact"), formatStoredCalendarDay(relationship.company.nextContactAt, language === "nb" ? "nb-NO" : "en") || null)}
|
||||
</Box>
|
||||
<Box>
|
||||
<Typography component="h3" variant="sectionTitle" sx={{ mb: 1 }}>{t("companiesApplications")}</Typography>
|
||||
|
||||
@@ -19,6 +19,7 @@ import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||
import { format, parseISO } from "date-fns";
|
||||
|
||||
import { api } from "../api";
|
||||
import { saveCalendarDay, storedCalendarDay } from "../calendarDay";
|
||||
import { Company, JobApplication } from "../types";
|
||||
import { useToast } from "../toast";
|
||||
import { useCompanies } from "../hooks/useCompanies";
|
||||
@@ -74,6 +75,7 @@ export default function EditJobDialog({ open, jobId, onClose, onSaved }: Props)
|
||||
const [version, setVersion] = useState<number | null>(null);
|
||||
const session = useRef(0);
|
||||
const saving = useRef(false);
|
||||
const originalDates = useRef<Pick<JobApplication, "dateApplied" | "deadline"> | null>(null);
|
||||
const { companies } = useCompanies();
|
||||
|
||||
const [company, setCompany] = useState<Company | null>(null);
|
||||
@@ -114,13 +116,14 @@ export default function EditJobDialog({ open, jobId, onClose, onSaved }: Props)
|
||||
api.get<JobApplication>(`/jobapplications/${jobId}`).then((r) => {
|
||||
if (current !== session.current) return;
|
||||
const j = r.data;
|
||||
originalDates.current = { dateApplied: j.dateApplied, deadline: j.deadline };
|
||||
setVersion(j.version);
|
||||
setCompany(j.company ?? null);
|
||||
setJobTitle(j.jobTitle ?? "");
|
||||
setStatus(j.status ?? "Applied");
|
||||
setInitialStatus(j.status ?? "Applied");
|
||||
setStatusChangedAt(new Date().toISOString().slice(0, 10));
|
||||
setDateApplied(toDateInputValue(j.dateApplied ?? undefined));
|
||||
setDateApplied(storedCalendarDay(j.dateApplied));
|
||||
setLocation(j.location ?? "");
|
||||
setSalary(j.salary ?? "");
|
||||
setSalaryMin(j.salaryMin != null ? String(j.salaryMin) : "");
|
||||
@@ -135,7 +138,7 @@ export default function EditJobDialog({ open, jobId, onClose, onSaved }: Props)
|
||||
setTranslatedDescription((j as any).translatedDescription ?? "");
|
||||
setDescriptionLanguage((j as any).descriptionLanguage ?? "");
|
||||
setTags(parseTags((j as any).tags));
|
||||
setDeadline((j as any).deadline ? toDateInputValue((j as any).deadline) : "");
|
||||
setDeadline(storedCalendarDay(j.deadline));
|
||||
setCoverLetterText(j.coverLetterText ?? "");
|
||||
setResponseReceived(Boolean(j.responseReceived));
|
||||
setResponseDate(j.responseDate ? toDateInputValue(j.responseDate) : "");
|
||||
@@ -180,9 +183,9 @@ export default function EditJobDialog({ open, jobId, onClose, onSaved }: Props)
|
||||
translatedDescription: translatedDescription || null,
|
||||
descriptionLanguage: descriptionLanguage || null,
|
||||
tags: tags.length ? JSON.stringify(tags) : null,
|
||||
deadline: deadline || null,
|
||||
deadline: saveCalendarDay(deadline, originalDates.current?.deadline),
|
||||
coverLetterText: coverLetterText || null,
|
||||
dateApplied: dateApplied || null,
|
||||
dateApplied: saveCalendarDay(dateApplied, originalDates.current?.dateApplied),
|
||||
jobUrl: jobUrl.trim() || null,
|
||||
});
|
||||
if (current !== session.current) return;
|
||||
|
||||
@@ -38,6 +38,7 @@ import SearchIcon from "@mui/icons-material/Search";
|
||||
import WorkOutlineIcon from "@mui/icons-material/WorkOutline";
|
||||
|
||||
import { api } from "../api";
|
||||
import { formatStoredCalendarDay } from "../calendarDay";
|
||||
import ViewStateNotice from "./ViewStateNotice";
|
||||
import { useCompanies } from "../hooks/useCompanies";
|
||||
import { useDebouncedValue } from "../hooks/useDebouncedValue";
|
||||
@@ -488,7 +489,7 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
|
||||
toneName: statusTone(job.status),
|
||||
tags: parseTags(job.tags),
|
||||
actionSignals: actionSignal ? [actionSignal] : [],
|
||||
appliedDateLabel: job.dateApplied ? new Date(job.dateApplied).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : "—",
|
||||
appliedDateLabel: formatStoredCalendarDay(job.dateApplied, language === "nb" ? "nb-NO" : "en") || "—",
|
||||
isSelected: selectedIdSet.has(job.id),
|
||||
};
|
||||
}), [buildWorkflowActionSignal, filteredJobs, selectedIdSet, language]);
|
||||
@@ -915,7 +916,7 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
|
||||
{columns.status ? <TableCell><Chip label={statusLabel(t, job.status)} size="small" color={toneName as any} variant="outlined" sx={{ fontWeight: 600 }} /></TableCell> : null}
|
||||
{columns.dateApplied ? <TableCell>{appliedDateLabel}</TableCell> : null}
|
||||
{columns.daysSince ? <TableCell>{job.daysSince ?? "—"}</TableCell> : null}
|
||||
<TableCell>{job.deadline ? new Date(job.deadline).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : "—"}</TableCell>
|
||||
<TableCell>{formatStoredCalendarDay(job.deadline, language === "nb" ? "nb-NO" : "en") || "—"}</TableCell>
|
||||
{columns.jobUrl ? <TableCell>{job.jobUrl ? <Link href={job.jobUrl} target="_blank" rel="noreferrer" underline="always">{t("jobTableLink")}</Link> : ""}</TableCell> : null}
|
||||
<TableCell align="right">{rowActions(job)}</TableCell>
|
||||
</TableRow>
|
||||
|
||||
@@ -108,10 +108,19 @@ test.each(["en", "nb"] as const)("%s Edit date-only picker round trip preserves
|
||||
await waitFor(() => expect(client.put).toHaveBeenCalledWith("/jobapplications/1", expect.objectContaining({ expectedVersion: 7, dateApplied: "2026-11-23", deadline: "2026-11-23", followUpAt: "2026-11-23", responseDate: "2026-11-23" })));
|
||||
});
|
||||
|
||||
test("Edit retains its existing UTC calendar-day loading policy for a legacy offset timestamp", async () => {
|
||||
client.get.mockResolvedValue({ data: { ...job, deadline: "2026-11-23T23:30:00-08:00" } } as any);
|
||||
test.each([
|
||||
"2026-11-23",
|
||||
"2026-11-23T23:30:00Z",
|
||||
"2026-11-23T23:30:00-08:00",
|
||||
"2026-11-23T00:00:00",
|
||||
])("Edit displays the stored day and submits the original value when unchanged (%s)", async original => {
|
||||
client.get.mockResolvedValue({ data: { ...job, dateApplied: original, deadline: original } } as any);
|
||||
render(wrap(<EditJobDialog open jobId={1} onClose={jest.fn()} onSaved={jest.fn()} />));
|
||||
await screen.findByDisplayValue("Teacher");
|
||||
expect(screen.getByLabelText(translations.en.editJobDeadline)).toHaveTextContent("2026-11-24");
|
||||
expect(client.put).not.toHaveBeenCalled();
|
||||
expect(screen.getByLabelText(translations.en.editJobAppliedOn)).toHaveTextContent("2026-11-23");
|
||||
expect(screen.getByLabelText(translations.en.editJobDeadline)).toHaveTextContent("2026-11-23");
|
||||
fireEvent.click(screen.getByRole("button", { name: translations.en.save }));
|
||||
await waitFor(() => expect(client.put).toHaveBeenCalledWith("/jobapplications/1", expect.objectContaining({
|
||||
expectedVersion: 7, dateApplied: original, deadline: original,
|
||||
})));
|
||||
});
|
||||
|
||||
@@ -216,8 +216,8 @@ test("Bokmål display localizes standard statuses without changing API values or
|
||||
const row = await screen.findByRole("row", { name: /platform engineer/i });
|
||||
expect(lastParams().status).toBe("Custom review");
|
||||
expect(within(row).getByText(translations.nb.statusInterview)).toBeVisible();
|
||||
expect(within(row).getByText(new Date(standardJob.dateApplied).toLocaleDateString("nb-NO"))).toBeVisible();
|
||||
expect(within(row).getByText(new Date(standardJob.deadline).toLocaleDateString("nb-NO"))).toBeVisible();
|
||||
expect(within(row).getByText(new Date(standardJob.dateApplied).toLocaleDateString("nb-NO", { timeZone: "UTC" }))).toBeVisible();
|
||||
expect(within(row).getByText(new Date(standardJob.deadline).toLocaleDateString("nb-NO", { timeZone: "UTC" }))).toBeVisible();
|
||||
expect(screen.getByRole("combobox", { name: translations.nb.jobTableStatus })).toHaveTextContent("Custom review");
|
||||
fireEvent.click(within(row).getByRole("button", { name: `${translations.nb.jobTableActions}: ${job.jobTitle}` }));
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: translations.nb.jobTableSetStatus.replace("{status}", translations.nb.statusOffer) }));
|
||||
|
||||
Reference in New Issue
Block a user