diff --git a/JobTrackerApi.MariaDb.Tests/CalendarPrecisionTests.cs b/JobTrackerApi.MariaDb.Tests/CalendarPrecisionTests.cs new file mode 100644 index 00000000..d9e15353 --- /dev/null +++ b/JobTrackerApi.MariaDb.Tests/CalendarPrecisionTests.cs @@ -0,0 +1,38 @@ +using System.Text; +using System.Text.Json; +using JobTrackerApi.Controllers; +using JobTrackerApi.Models; +using JobTrackerApi.Services; +using Microsoft.AspNetCore.Mvc; +using Moq; +using Xunit; + +namespace JobTrackerApi.MariaDb.Tests; + +public sealed class CalendarPrecisionTests +{ + [Theory] + [InlineData("2026-10-25T02:30:00+02:00", "20261025T003000Z")] + [InlineData("2026-10-25T02:30:00+01:00", "20261025T013000Z")] + public async Task Explicit_follow_up_offset_survives_mariadb_round_trip_to_ics(string source, string expected) + { + const string owner = "calendar-owner"; + var json = JsonSerializer.Serialize(new { followUpAt = source }); + var request = JsonSerializer.Deserialize(json, new JsonSerializerOptions(JsonSerializerDefaults.Web))!; + await using var database = await MariaDbDatabase.CreateAsync(); + await using var db = database.Context(owner); + var job = new JobApplication + { + OwnerUserId = owner, Company = new Company { OwnerUserId = owner, Name = "Synthetic calendar" }, + JobTitle = "Synthetic role", Status = "Interview", FollowUpAt = request.FollowUpAt, + }; + db.JobApplications.Add(job); + await db.SaveChangesAsync(); + db.ChangeTracker.Clear(); + + var controller = new ApplicationCalendarController(db, Mock.Of(user => user.UserId == owner), + new Mock(MockBehavior.Strict).Object, new Mock(MockBehavior.Strict).Object); + var file = Assert.IsType(await controller.DownloadEvent(job.Id, "follow-up", default)); + Assert.Contains($"DTSTART:{expected}\r\n", Encoding.UTF8.GetString(file.FileContents), StringComparison.Ordinal); + } +} diff --git a/JobTrackerApi.Tests/ApplicationCalendarControllerTests.cs b/JobTrackerApi.Tests/ApplicationCalendarControllerTests.cs index c8fe9419..eafd1518 100644 --- a/JobTrackerApi.Tests/ApplicationCalendarControllerTests.cs +++ b/JobTrackerApi.Tests/ApplicationCalendarControllerTests.cs @@ -6,12 +6,41 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Data.Sqlite; using Moq; +using System.Globalization; +using System.Text.Json; using Xunit; namespace JobTrackerApi.Tests; public sealed class ApplicationCalendarControllerTests { + [Theory] + [InlineData("2026-10-25T02:30:00+02:00", "2026-10-25T00:30:00", DateTimeKind.Utc)] + [InlineData("2026-10-25T02:30:00+01:00", "2026-10-25T01:30:00", DateTimeKind.Utc)] + [InlineData("2026-10-25T00:15:00Z", "2026-10-25T00:15:00", DateTimeKind.Utc)] + [InlineData("2026-10-25T02:30:00", "2026-10-25T02:30:00", DateTimeKind.Unspecified)] + [InlineData("2026-10-25", "2026-10-25T00:00:00", DateTimeKind.Unspecified)] + [InlineData(null, null, null)] + public void Follow_up_write_contracts_preserve_explicit_instants_and_legacy_values( + string? input, string? expected, DateTimeKind? kind) + { + var json = JsonSerializer.Serialize(new { followUpAt = input }); + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); + var dates = new[] + { + JsonSerializer.Deserialize(json, options)!.FollowUpAt, + JsonSerializer.Deserialize(json, options)!.FollowUpAt, + JsonSerializer.Deserialize(json, options)!.FollowUpAt, + JsonSerializer.Deserialize(json, options)!.FollowUpAt, + }; + + Assert.All(dates, value => + { + Assert.Equal(expected, value?.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture)); + Assert.Equal(kind, value?.Kind); + }); + } + [Fact] public async Task Agenda_date_window_translates_on_sqlite_and_keeps_legacy_wall_clock_date() { diff --git a/JobTrackerApi/Controllers/FollowUpDateTimeConverter.cs b/JobTrackerApi/Controllers/FollowUpDateTimeConverter.cs new file mode 100644 index 00000000..bd93cd2f --- /dev/null +++ b/JobTrackerApi/Controllers/FollowUpDateTimeConverter.cs @@ -0,0 +1,22 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace JobTrackerApi.Controllers; + +public sealed class FollowUpDateTimeConverter : JsonConverter +{ + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (!reader.TryGetDateTime(out var value)) + throw new JsonException("Follow-up date must be an ISO 8601 date or timestamp."); + + // An explicit offset becomes server-local DateTime before storage discards its Kind. + return value.Kind == DateTimeKind.Local ? reader.GetDateTimeOffset().UtcDateTime : value; + } + + public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) + { + if (value is { } date) writer.WriteStringValue(date); + else writer.WriteNullValue(); + } +} diff --git a/JobTrackerApi/Controllers/InterviewPrepController.cs b/JobTrackerApi/Controllers/InterviewPrepController.cs index 01153472..45e0f0c3 100644 --- a/JobTrackerApi/Controllers/InterviewPrepController.cs +++ b/JobTrackerApi/Controllers/InterviewPrepController.cs @@ -3,6 +3,7 @@ using JobTrackerApi.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; +using System.Text.Json.Serialization; namespace JobTrackerApi.Controllers; @@ -17,7 +18,8 @@ namespace JobTrackerApi.Controllers; [Authorize(AuthenticationSchemes = "local")] public sealed class InterviewPrepController : ControllerBase { - public sealed record SetFollowUpRequest(DateTime? FollowUpAt, string? NextAction); + public sealed record SetFollowUpRequest( + [property: JsonConverter(typeof(FollowUpDateTimeConverter))] DateTime? FollowUpAt, string? NextAction); private readonly UserManager _users; private readonly IInterviewPrepService _prep; diff --git a/JobTrackerApi/Controllers/JobApplicationDtos.cs b/JobTrackerApi/Controllers/JobApplicationDtos.cs index 29d1a456..40bf63ec 100644 --- a/JobTrackerApi/Controllers/JobApplicationDtos.cs +++ b/JobTrackerApi/Controllers/JobApplicationDtos.cs @@ -1,5 +1,6 @@ using JobTrackerApi.Models; using JobTrackerApi.Services; +using System.Text.Json.Serialization; namespace JobTrackerApi.Controllers { @@ -94,7 +95,7 @@ namespace JobTrackerApi.Controllers string? SalaryCurrency, string? SalaryPeriod, string? NextAction, - DateTime? FollowUpAt, + [property: JsonConverter(typeof(FollowUpDateTimeConverter))] DateTime? FollowUpAt, string? Notes, string? Description, string? TranslatedDescription, @@ -122,7 +123,7 @@ namespace JobTrackerApi.Controllers string? SalaryCurrency, string? SalaryPeriod, string? NextAction, - DateTime? FollowUpAt, + [property: JsonConverter(typeof(FollowUpDateTimeConverter))] DateTime? FollowUpAt, string? Notes, string? Description, string? TranslatedDescription, @@ -153,7 +154,7 @@ namespace JobTrackerApi.Controllers DateTime? MessageDate, string? MessageSubject); - public sealed record FollowUpRequest(DateTime? FollowUpAt); + public sealed record FollowUpRequest([property: JsonConverter(typeof(FollowUpDateTimeConverter))] DateTime? FollowUpAt); public sealed record JobEventDto(int Id, string Type, string? OldValue, string? NewValue, string? Note, DateTime At); diff --git a/job-tracker-ui/e2e/calendar-precision.spec.ts b/job-tracker-ui/e2e/calendar-precision.spec.ts new file mode 100644 index 00000000..b60e8eb5 --- /dev/null +++ b/job-tracker-ui/e2e/calendar-precision.spec.ts @@ -0,0 +1,117 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import { expect, test, type APIRequestContext } from '@playwright/test'; +import { translations } from '../src/i18n/translations'; + +const apiUrl = 'http://localhost:5302/api'; +const password = 'E2ePassword123!'; +const fixtures = [ + { title: 'Date-only deadline', field: 'deadline', value: '2026-10-25', kind: 'deadline', + start: 'DTSTART;VALUE=DATE:20261025', end: 'DTEND;VALUE=DATE:20261026' }, + { title: 'UTC follow-up', field: 'followUpAt', value: '2026-10-25T00:15:00Z', kind: 'follow-up', + start: 'DTSTART:20261025T001500Z', end: 'DTEND:20261025T004500Z' }, + { title: 'First repeated hour', field: 'followUpAt', value: '2026-10-25T02:30:00+02:00', kind: 'follow-up', + start: 'DTSTART:20261025T003000Z', end: 'DTEND:20261025T010000Z' }, + { title: 'Second repeated hour', field: 'followUpAt', value: '2026-10-25T02:30:00+01:00', kind: 'follow-up', + start: 'DTSTART:20261025T013000Z', end: 'DTEND:20261025T020000Z' }, + { title: 'Legacy wall-clock follow-up', field: 'followUpAt', value: '2026-10-25T02:30:00', kind: 'follow-up', + start: 'DTSTART:20261025T023000Z', end: 'DTEND:20261025T030000Z' }, +] as const; + +async function login(api: APIRequestContext, email: string) { + expect((await api.post(`${apiUrl}/auth/login`, { data: { email, password } })).status()).toBe(200); + const me = await api.get(`${apiUrl}/auth/me`); + expect(me.status()).toBe(200); + const csrf = (await api.storageState()).cookies.find(cookie => cookie.name === 'XSRF-TOKEN'); + expect(csrf).toBeDefined(); + return { 'X-CSRF-TOKEN': csrf!.value, 'X-Session-Context': (await me.json()).sessionContext as string }; +} + +for (const variant of [ + { language: 'en', locale: 'en-GB', mode: 'light', timezoneId: 'Europe/Oslo', viewport: { width: 1440, height: 900 } }, + { language: 'nb', locale: 'nb-NO', mode: 'dark', timezoneId: 'America/Los_Angeles', viewport: { width: 390, height: 844 } }, +] as const) { + test.describe(`calendar precision ${variant.language}`, () => { + test.use({ timezoneId: variant.timezoneId, viewport: variant.viewport }); + + test('recorded dates and ICS retain precision through the autumn DST transition', async ({ page, context, playwright }, info) => { + test.setTimeout(120_000); + expect(process.env.PLAYWRIGHT_REUSE_SERVERS).not.toBe('true'); + expect(info.config.metadata.isolatedDataRoot).toEqual(expect.any(String)); + await context.route('**/*', route => { + const url = new URL(route.request().url()); + return ['localhost', '127.0.0.1'].includes(url.hostname) || ['blob:', 'data:', 'about:'].includes(url.protocol) + ? route.continue() : route.abort(); + }); + const admin = await playwright.request.newContext(); + let headers: Record; + try { + const adminHeaders = await login(admin, 'e2e@example.test'); + const email = `calendar-dst-${Date.now()}-${variant.language}@example.test`; + expect((await admin.post(`${apiUrl}/users`, { headers: adminHeaders, data: { email, password, roles: [] } })).status()).toBe(200); + headers = await login(page.request, email); + } finally { + await admin.dispose(); + } + expect((await page.request.put(`${apiUrl}/auth/preferences/language`, { + headers, data: { language: variant.language === 'nb' ? 'nb-NO' : 'en' }, + })).status()).toBe(204); + await page.addInitScript(({ language, mode }) => { + localStorage.setItem('uiLanguage', language); + localStorage.setItem('jobtracker.themeMode', mode); + }, { language: variant.language, mode: variant.mode }); + + const company = await page.request.post(`${apiUrl}/companies`, { headers, data: { name: 'Synthetic calendar company' } }); + expect(company.status()).toBe(201); + const companyId = (await company.json()).id as number; + const jobs = []; + for (const fixture of fixtures) { + const response = await page.request.post(`${apiUrl}/jobapplications`, { + headers, data: { companyId, jobTitle: fixture.title, status: 'Interview', [fixture.field]: fixture.value }, + }); + expect(response.status()).toBe(201); + jobs.push({ ...fixture, id: (await response.json()).id as number }); + } + + await page.clock.setFixedTime(new Date('2026-10-25T12:00:00Z')); + await page.goto('/reminders'); + const t = translations[variant.language]; + const calendar = page.getByRole('region', { name: t.calendarAgendaTitle, exact: true }); + const dateLabel = new Intl.DateTimeFormat(variant.locale, { dateStyle: 'medium', timeZone: 'UTC' }).format(new Date('2026-10-25T12:00:00Z')); + const dateSection = calendar.getByRole('region', { name: dateLabel, exact: true }); + await expect(dateSection.getByRole('link')).toHaveCount(jobs.length); + await expect(page.locator('html')).toHaveAttribute('data-color-scheme', variant.mode); + const observed = []; + for (const job of jobs) { + const row = dateSection.getByRole('article').filter({ hasText: job.title }); + await expect(row.getByRole('link')).toHaveAttribute('href', `/jobs/${job.id}`); + const time = row.locator('time'); + await expect(time).toHaveText(dateLabel); + observed.push({ ...job, recordedAt: await time.getAttribute('datetime') }); + } + await page.getByRole('button', { name: t.calendarMonth, exact: true }).click(); + const day = calendar.getByRole('table', { name: t.calendarMonth }).getByText('25', { exact: true, selector: 'button' }); + await day.focus(); + await page.keyboard.press('Enter'); + await expect(day).toBeFocused(); + await expect(day).toHaveAttribute('aria-pressed', 'true'); + await expect(dateSection.getByRole('link')).toHaveCount(jobs.length); + + const downloaded = []; + for (const job of jobs) { + await page.goto(`/jobs/${job.id}?section=tasks`); + const [file] = await Promise.all([ + page.waitForEvent('download'), + page.getByRole('button', { name: t.calendarDownload, exact: true }).click(), + ]); + expect(file.suggestedFilename()).toBe(`jobjakt-${job.id}-${job.kind}.ics`); + const content = await readFile(await file.path(), 'utf8'); + const timestamps = content.split('\r\n').filter(line => /^(DTSTART|DTEND)/.test(line)); + downloaded.push({ title: job.title, timestamps }); + expect.soft(timestamps, job.title).toEqual([job.start, job.end]); + } + const evidence = info.outputPath('calendar-dst-matrix.json'); + await writeFile(evidence, JSON.stringify({ variant, source: 'native API and Chromium downloads', observed, downloaded }, null, 2)); + await info.attach('calendar-dst-matrix', { path: evidence, contentType: 'application/json' }); + }); + }); +}