From b7029faaec43ed64a3d16f42ff2771bb6fd29389 Mon Sep 17 00:00:00 2001 From: cesnimda Date: Mon, 31 Aug 2026 22:12:52 +0200 Subject: [PATCH 1/9] feat(discovery): schedule saved-search alerts --- .env.example | 2 + .../JobDiscoveryControllerTests.cs | 7 +- .../SavedJobSearchAlertTests.cs | 98 ++++++++++++++ .../Controllers/JobDiscoveryController.cs | 126 ++++-------------- JobTrackerApi/Models/DiscoveredJob.cs | 15 +++ JobTrackerApi/Program.cs | 3 + .../Services/BackgroundTenantRunner.cs | 25 +++- .../Services/JobDiscoverySearchService.cs | 80 +++++++++++ .../SavedJobSearchAlertHostedService.cs | 86 ++++++++++++ .../Services/SavedJobSearchRunner.cs | 44 ++++++ JobTrackerApi/appsettings.json | 4 + docker-compose.yml | 2 + docs/architecture/background-workers.md | 3 +- job-tracker-ui/src/i18n/translations.ts | 8 +- job-tracker-ui/src/job-discovery.test.tsx | 14 ++ job-tracker-ui/src/views/JobDiscoveryPage.tsx | 19 ++- 16 files changed, 423 insertions(+), 113 deletions(-) create mode 100644 JobTrackerApi.Tests/SavedJobSearchAlertTests.cs create mode 100644 JobTrackerApi/Models/DiscoveredJob.cs create mode 100644 JobTrackerApi/Services/JobDiscoverySearchService.cs create mode 100644 JobTrackerApi/Services/SavedJobSearchAlertHostedService.cs create mode 100644 JobTrackerApi/Services/SavedJobSearchRunner.cs diff --git a/.env.example b/.env.example index 914a4436..e2853bd8 100644 --- a/.env.example +++ b/.env.example @@ -104,6 +104,8 @@ EMAIL_FOLLOWUPREMINDERS_ENABLED=false EMAIL_FOLLOWUPREMINDERS_UPCOMINGDAYS=2 WORKER_RULES_ENABLED=false WORKER_FOLLOWUP_REMINDERS_ENABLED=false +WORKER_SAVED_SEARCH_ALERTS_ENABLED=true +SAVED_SEARCH_INTERVAL_HOURS=6 WORKER_DAILY_EXPORT_ENABLED=false WORKER_JOB_ENRICHMENT_ENABLED=false diff --git a/JobTrackerApi.Tests/JobDiscoveryControllerTests.cs b/JobTrackerApi.Tests/JobDiscoveryControllerTests.cs index aa3b2a7b..261511de 100644 --- a/JobTrackerApi.Tests/JobDiscoveryControllerTests.cs +++ b/JobTrackerApi.Tests/JobDiscoveryControllerTests.cs @@ -3,6 +3,7 @@ using System.Net; using System.Text; using JobTrackerApi.Controllers; using JobTrackerApi.Data; +using JobTrackerApi.Models; using JobTrackerApi.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; @@ -25,7 +26,7 @@ public sealed class JobDiscoveryControllerTests var result = await controller.Search("backend", "oslo", CancellationToken.None); var ok = Assert.IsType(result.Result); - var job = Assert.Single(Assert.IsAssignableFrom>(ok.Value)); + var job = Assert.Single(Assert.IsAssignableFrom>(ok.Value)); Assert.Equal("Backend Developer", job.Title); Assert.Equal("nav", job.Source); Assert.Equal("NAV Arbeidsplassen", job.SourceName); @@ -46,7 +47,7 @@ public sealed class JobDiscoveryControllerTests var result = await controller.Search(null, null, CancellationToken.None); var ok = Assert.IsType(result.Result); - var job = Assert.Single(Assert.IsAssignableFrom>(ok.Value)); + var job = Assert.Single(Assert.IsAssignableFrom>(ok.Value)); Assert.Equal("1", job.Id); Assert.Equal("Current title", job.Title); } @@ -71,6 +72,8 @@ public sealed class JobDiscoveryControllerTests Assert.IsType(await controller.DismissSavedSearchResult(created.Id, "job-1", new(true), default)); var listed = Assert.IsAssignableFrom>(Assert.IsType((await controller.ListSavedSearches(default)).Result).Value); Assert.Equal(1, Assert.Single(listed).DismissedCount); + var paused = Assert.IsType(Assert.IsType((await controller.UpdateSavedSearch(created.Id, new(false), default)).Result).Value); + Assert.False(paused.IsActive); } private sealed class ClientFactory(HttpClient client) : IHttpClientFactory diff --git a/JobTrackerApi.Tests/SavedJobSearchAlertTests.cs b/JobTrackerApi.Tests/SavedJobSearchAlertTests.cs new file mode 100644 index 00000000..91b7ce26 --- /dev/null +++ b/JobTrackerApi.Tests/SavedJobSearchAlertTests.cs @@ -0,0 +1,98 @@ +using JobTrackerApi.Data; +using JobTrackerApi.Models; +using JobTrackerApi.Services; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace JobTrackerApi.Tests; + +public sealed class SavedJobSearchAlertTests +{ + [Fact] + public async Task Worker_establishes_baseline_then_notifies_only_for_later_results() + { + var clock = new MutableTimeProvider(new DateTimeOffset(2026, 8, 31, 8, 0, 0, TimeSpan.Zero)); + var discovery = new FakeDiscovery(clock, "job-1"); + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Workers:SavedJobSearchAlertsEnabled"] = "true", + ["JobDiscovery:SavedSearchIntervalHours"] = "6" + }).Build(); + var services = new ServiceCollection(); + var databaseName = Guid.NewGuid().ToString(); + services.AddLogging(); + services.AddHttpContextAccessor(); + services.AddSingleton(configuration); + services.AddSingleton(clock); + services.AddSingleton(discovery); + services.AddScoped(); + services.AddScoped(provider => provider.GetRequiredService()); + services.AddDbContext((_, options) => options.UseInMemoryDatabase(databaseName)); + services.AddScoped(); + services.AddSingleton(); + await using var provider = services.BuildServiceProvider(); + + await using (var scope = provider.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.SavedJobSearches.Add(new SavedJobSearch + { + OwnerUserId = "owner-without-jobs", + Name = "Backend Oslo", + Query = "backend", + Location = "Oslo", + CreatedAtUtc = clock.GetUtcNow(), + UpdatedAtUtc = clock.GetUtcNow() + }); + await db.SaveChangesAsync(); + } + + var worker = new SavedJobSearchAlertHostedService( + provider.GetRequiredService(), + configuration, + NullLogger.Instance, + Mock.Of(), + clock); + + Assert.Equal(new BackgroundWorkerRunResult(true, 1, 1, 0), await worker.RunOnceAsync(default)); + await using (var scope = provider.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Empty(await db.UserNotifications.IgnoreQueryFilters().ToListAsync()); + Assert.Single(await db.SavedJobSearchResults.IgnoreQueryFilters().ToListAsync()); + } + + clock.SetUtcNow(clock.GetUtcNow().AddHours(7)); + discovery.Ids.Add("job-2"); + Assert.Equal(new BackgroundWorkerRunResult(true, 1, 1, 0), await worker.RunOnceAsync(default)); + + await using var verification = provider.CreateAsyncScope(); + var notification = Assert.Single(await verification.ServiceProvider.GetRequiredService() + .UserNotifications.IgnoreQueryFilters().AsNoTracking().ToListAsync()); + Assert.Equal("owner-without-jobs", notification.OwnerUserId); + Assert.Equal("saved_search_results", notification.Kind); + Assert.Equal("/discover", notification.LinkPath); + Assert.Contains("Backend Oslo", notification.Message); + } + + private sealed class FakeDiscovery(MutableTimeProvider clock, params string[] ids) : IJobDiscoverySearchService + { + public List Ids { get; } = [.. ids]; + + public Task> SearchAsync(string? query, string? location, CancellationToken cancellationToken) => + Task.FromResult>(Ids.Select(id => new DiscoveredJob( + id, "Backend Developer", "Acme", "Oslo", clock.GetUtcNow(), null, + $"https://example.test/{id}", "nav", "NAV Arbeidsplassen", "searched", clock.GetUtcNow(), "NO")).ToList()); + } + + private sealed class MutableTimeProvider(DateTimeOffset now) : TimeProvider + { + private DateTimeOffset _now = now; + public override DateTimeOffset GetUtcNow() => _now; + public void SetUtcNow(DateTimeOffset value) => _now = value; + } +} diff --git a/JobTrackerApi/Controllers/JobDiscoveryController.cs b/JobTrackerApi/Controllers/JobDiscoveryController.cs index f1922baf..a0dd39d8 100644 --- a/JobTrackerApi/Controllers/JobDiscoveryController.cs +++ b/JobTrackerApi/Controllers/JobDiscoveryController.cs @@ -1,4 +1,3 @@ -using System.Net.Http.Headers; using System.Text.Json; using JobTrackerApi.Data; using JobTrackerApi.Models; @@ -15,10 +14,8 @@ namespace JobTrackerApi.Controllers; [Authorize(AuthenticationSchemes = "local")] public sealed class JobDiscoveryController : ControllerBase { - private const string BaseUrl = "https://pam-stilling-feed.nav.no"; - private readonly IHttpClientFactory _clients; - private readonly IConfiguration _configuration; - private readonly IMemoryCache _cache; + private readonly IJobDiscoverySearchService _discovery; + private readonly SavedJobSearchRunner? _savedSearchRunner; private readonly JobTrackerContext? _db; private readonly ICurrentUserService? _currentUser; @@ -27,11 +24,12 @@ public sealed class JobDiscoveryController : ControllerBase IConfiguration configuration, IMemoryCache cache, JobTrackerContext? db = null, - ICurrentUserService? currentUser = null) + ICurrentUserService? currentUser = null, + IJobDiscoverySearchService? discovery = null, + SavedJobSearchRunner? savedSearchRunner = null) { - _clients = clients; - _configuration = configuration; - _cache = cache; + _discovery = discovery ?? new NavJobDiscoverySearchService(clients, configuration, cache, TimeProvider.System); + _savedSearchRunner = savedSearchRunner; _db = db; _currentUser = currentUser; } @@ -41,7 +39,7 @@ public sealed class JobDiscoveryController : ControllerBase { try { - return Ok(await SearchCoreAsync(q, location, cancellationToken)); + return Ok(await _discovery.SearchAsync(q, location, cancellationToken)); } catch (Exception ex) when (ex is HttpRequestException or JsonException or InvalidOperationException) { @@ -86,6 +84,19 @@ public sealed class JobDiscoveryController : ControllerBase return NoContent(); } + [HttpPatch("saved-searches/{id:int}")] + public async Task> UpdateSavedSearch(int id, [FromBody] UpdateSavedSearchRequest request, CancellationToken cancellationToken) + { + if (!TryGetPersistence(out var db, out var owner)) return Unauthorized(); + var search = await db.SavedJobSearches.Include(x => x.Results) + .FirstOrDefaultAsync(x => x.Id == id && x.OwnerUserId == owner, cancellationToken); + if (search is null) return NotFound(); + search.IsActive = request.IsActive; + search.UpdatedAtUtc = DateTimeOffset.UtcNow; + await db.SaveChangesAsync(cancellationToken); + return Ok(ToDto(search)); + } + [HttpPost("saved-searches/{id:int}/run")] public async Task> RunSavedSearch(int id, CancellationToken cancellationToken) { @@ -95,26 +106,10 @@ public sealed class JobDiscoveryController : ControllerBase try { - var jobs = await SearchCoreAsync(search.Query, search.Location, cancellationToken); - var now = DateTimeOffset.UtcNow; - var existing = search.Results.ToDictionary(x => x.ExternalJobId, StringComparer.OrdinalIgnoreCase); - var results = new List(jobs.Count); - foreach (var job in jobs) - { - var isNew = !existing.TryGetValue(job.Id, out var state); - if (state is null) - { - state = new SavedJobSearchResult { ExternalJobId = job.Id, FirstSeenAtUtc = now, LastSeenAtUtc = now }; - search.Results.Add(state); - } - else state.LastSeenAtUtc = now; - results.Add(new SavedSearchJobDto(job, isNew, state.IsDismissed)); - } - - search.LastRunAtUtc = now; - search.UpdatedAtUtc = now; + var runner = _savedSearchRunner ?? new SavedJobSearchRunner(db, _discovery, TimeProvider.System); + var run = await runner.RunAsync(search, cancellationToken); await db.SaveChangesAsync(cancellationToken); - return Ok(new SavedSearchRunDto(ToDto(search), results)); + return Ok(new SavedSearchRunDto(ToDto(search), run.Jobs.Select(item => new SavedSearchJobDto(item.Job, item.IsNew, item.IsDismissed)).ToList())); } catch (Exception ex) when (ex is HttpRequestException or JsonException or InvalidOperationException) { @@ -141,79 +136,8 @@ public sealed class JobDiscoveryController : ControllerBase return db is not null && owner.Length > 0; } - private async Task> SearchCoreAsync(string? q, string? location, CancellationToken cancellationToken) - { - var retrievedAt = DateTimeOffset.UtcNow; - var token = await GetTokenAsync(cancellationToken); - var client = _clients.CreateClient(); - var entries = new Dictionary(StringComparer.OrdinalIgnoreCase); - var next = "/api/v1/feed"; - for (var page = 0; page < 20 && !string.IsNullOrWhiteSpace(next); page++) - { - using var request = new HttpRequestMessage(HttpMethod.Get, BaseUrl + next); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); - request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - if (page == 0) request.Headers.IfModifiedSince = DateTimeOffset.UtcNow.AddDays(-14); - using var response = await client.SendAsync(request, cancellationToken); - response.EnsureSuccessStatusCode(); - using var json = JsonDocument.Parse(await response.Content.ReadAsStreamAsync(cancellationToken)); - next = json.RootElement.TryGetProperty("next_url", out var nextElement) ? nextElement.GetString() ?? "" : ""; - foreach (var item in json.RootElement.GetProperty("items").EnumerateArray()) - { - var feed = item.GetProperty("_feed_entry"); - var jobId = feed.GetProperty("uuid").GetString(); - if (string.IsNullOrWhiteSpace(jobId)) continue; - var status = feed.TryGetProperty("status", out var statusElement) ? statusElement.GetString() : null; - if (!string.Equals(status, "ACTIVE", StringComparison.OrdinalIgnoreCase)) { entries.Remove(jobId); continue; } - entries[jobId] = new DiscoveredJob(jobId, - feed.TryGetProperty("title", out var title) ? title.GetString() ?? "" : "", - feed.TryGetProperty("businessName", out var company) ? company.GetString() : null, - feed.TryGetProperty("municipal", out var municipal) ? municipal.GetString() : null, - item.TryGetProperty("date_modified", out var modified) && modified.TryGetDateTimeOffset(out var date) ? date : null, - feed.TryGetProperty("applicationDue", out var due) && due.TryGetDateTimeOffset(out var deadline) ? deadline : null, - $"https://arbeidsplassen.nav.no/stillinger/stilling/{jobId}", "nav", "NAV Arbeidsplassen", "searched", retrievedAt, "NO"); - } - } - var query = (q ?? "").Trim(); - var place = (location ?? "").Trim(); - return entries.Values.Where(job => Contains(job.Title, query) || Contains(job.Company, query)) - .Where(job => Contains(job.Location, place)).OrderByDescending(job => job.ModifiedAt).Take(100).ToList(); - } - - private async Task GetTokenAsync(CancellationToken cancellationToken) - { - var configured = _configuration["NavJobs:Token"]?.Trim(); - if (!string.IsNullOrWhiteSpace(configured)) return configured; - - return await _cache.GetOrCreateAsync("nav-jobs-public-token", async entry => - { - entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); - var text = await _clients.CreateClient().GetStringAsync(BaseUrl + "/api/publicToken", cancellationToken); - var start = text.IndexOf("eyJ", StringComparison.Ordinal); - if (start < 0) throw new InvalidOperationException("NAV public token was not returned."); - var token = text[start..].Trim(); - var end = token.IndexOfAny(['\r', '\n', ' ', '\t']); - return end < 0 ? token : token[..end]; - }) ?? throw new InvalidOperationException("NAV public token was not returned."); - } - - private static bool Contains(string? value, string filter) => - filter.Length == 0 || (value?.Contains(filter, StringComparison.OrdinalIgnoreCase) ?? false); - - public sealed record DiscoveredJob( - string Id, - string Title, - string? Company, - string? Location, - DateTimeOffset? ModifiedAt, - DateTimeOffset? Deadline, - string Url, - string Source, - string SourceName, - string AcquisitionType, - DateTimeOffset RetrievedAt, - string CountryCode); public sealed record SavedSearchRequest(string? Name, string? Query, string? Location); + public sealed record UpdateSavedSearchRequest(bool IsActive); public sealed record DismissRequest(bool IsDismissed); public sealed record SavedSearchDto(int Id, string Name, string Query, string Location, bool IsActive, DateTimeOffset? LastRunAtUtc, int ResultCount, int DismissedCount); public sealed record SavedSearchJobDto(DiscoveredJob Job, bool IsNew, bool IsDismissed); diff --git a/JobTrackerApi/Models/DiscoveredJob.cs b/JobTrackerApi/Models/DiscoveredJob.cs new file mode 100644 index 00000000..7a4d46ed --- /dev/null +++ b/JobTrackerApi/Models/DiscoveredJob.cs @@ -0,0 +1,15 @@ +namespace JobTrackerApi.Models; + +public sealed record DiscoveredJob( + string Id, + string Title, + string? Company, + string? Location, + DateTimeOffset? ModifiedAt, + DateTimeOffset? Deadline, + string Url, + string Source, + string SourceName, + string AcquisitionType, + DateTimeOffset RetrievedAt, + string CountryCode); diff --git a/JobTrackerApi/Program.cs b/JobTrackerApi/Program.cs index fdf77425..5e5e27e5 100644 --- a/JobTrackerApi/Program.cs +++ b/JobTrackerApi/Program.cs @@ -60,6 +60,8 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -174,6 +176,7 @@ builder.Services.AddSingleton builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); +builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); diff --git a/JobTrackerApi/Services/BackgroundTenantRunner.cs b/JobTrackerApi/Services/BackgroundTenantRunner.cs index 95d28cd3..d047d905 100644 --- a/JobTrackerApi/Services/BackgroundTenantRunner.cs +++ b/JobTrackerApi/Services/BackgroundTenantRunner.cs @@ -16,13 +16,28 @@ public sealed class BackgroundTenantRunner( string worker, Func work, CancellationToken cancellationToken) + { + return await RunForOwnersAsync(worker, async db => await db.JobApplications.IgnoreQueryFilters().AsNoTracking() + .Where(job => job.OwnerUserId != null).Select(job => job.OwnerUserId!).ToListAsync(cancellationToken), work, cancellationToken); + } + + public async Task RunForSavedSearchOwnersAsync( + string worker, + Func work, + CancellationToken cancellationToken) + { + return await RunForOwnersAsync(worker, async db => await db.SavedJobSearches.IgnoreQueryFilters().AsNoTracking() + .Where(search => search.IsActive).Select(search => search.OwnerUserId).ToListAsync(cancellationToken), work, cancellationToken); + } + + private async Task RunForOwnersAsync( + string worker, + Func>> findOwners, + Func work, + CancellationToken cancellationToken) { await using var enumerationScope = scopes.CreateAsyncScope(); - var ownerIds = await enumerationScope.ServiceProvider.GetRequiredService() - .JobApplications.IgnoreQueryFilters().AsNoTracking() - .Where(job => job.OwnerUserId != null) - .Select(job => job.OwnerUserId!) - .ToListAsync(cancellationToken); + var ownerIds = await findOwners(enumerationScope.ServiceProvider.GetRequiredService()); var owners = ownerIds.Where(owner => !string.IsNullOrWhiteSpace(owner)) .Distinct(StringComparer.Ordinal) .Order(StringComparer.Ordinal) diff --git a/JobTrackerApi/Services/JobDiscoverySearchService.cs b/JobTrackerApi/Services/JobDiscoverySearchService.cs new file mode 100644 index 00000000..c985f907 --- /dev/null +++ b/JobTrackerApi/Services/JobDiscoverySearchService.cs @@ -0,0 +1,80 @@ +using System.Net.Http.Headers; +using System.Text.Json; +using JobTrackerApi.Models; +using Microsoft.Extensions.Caching.Memory; + +namespace JobTrackerApi.Services; + +public interface IJobDiscoverySearchService +{ + Task> SearchAsync(string? query, string? location, CancellationToken cancellationToken); +} + +public sealed class NavJobDiscoverySearchService( + IHttpClientFactory clients, + IConfiguration configuration, + IMemoryCache cache, + TimeProvider timeProvider) : IJobDiscoverySearchService +{ + private const string BaseUrl = "https://pam-stilling-feed.nav.no"; + + public async Task> SearchAsync(string? query, string? location, CancellationToken cancellationToken) + { + var retrievedAt = timeProvider.GetUtcNow(); + var token = await GetTokenAsync(cancellationToken); + var client = clients.CreateClient(); + var entries = new Dictionary(StringComparer.OrdinalIgnoreCase); + var next = "/api/v1/feed"; + for (var page = 0; page < 20 && !string.IsNullOrWhiteSpace(next); page++) + { + using var request = new HttpRequestMessage(HttpMethod.Get, BaseUrl + next); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (page == 0) request.Headers.IfModifiedSince = timeProvider.GetUtcNow().AddDays(-14); + using var response = await client.SendAsync(request, cancellationToken); + response.EnsureSuccessStatusCode(); + using var json = JsonDocument.Parse(await response.Content.ReadAsStreamAsync(cancellationToken)); + next = json.RootElement.TryGetProperty("next_url", out var nextElement) ? nextElement.GetString() ?? "" : ""; + foreach (var item in json.RootElement.GetProperty("items").EnumerateArray()) + { + var feed = item.GetProperty("_feed_entry"); + var jobId = feed.GetProperty("uuid").GetString(); + if (string.IsNullOrWhiteSpace(jobId)) continue; + var status = feed.TryGetProperty("status", out var statusElement) ? statusElement.GetString() : null; + if (!string.Equals(status, "ACTIVE", StringComparison.OrdinalIgnoreCase)) { entries.Remove(jobId); continue; } + entries[jobId] = new DiscoveredJob(jobId, + feed.TryGetProperty("title", out var title) ? title.GetString() ?? "" : "", + feed.TryGetProperty("businessName", out var company) ? company.GetString() : null, + feed.TryGetProperty("municipal", out var municipal) ? municipal.GetString() : null, + item.TryGetProperty("date_modified", out var modified) && modified.TryGetDateTimeOffset(out var date) ? date : null, + feed.TryGetProperty("applicationDue", out var due) && due.TryGetDateTimeOffset(out var deadline) ? deadline : null, + $"https://arbeidsplassen.nav.no/stillinger/stilling/{jobId}", "nav", "NAV Arbeidsplassen", "searched", retrievedAt, "NO"); + } + } + + var term = (query ?? "").Trim(); + var place = (location ?? "").Trim(); + return entries.Values.Where(job => Contains(job.Title, term) || Contains(job.Company, term)) + .Where(job => Contains(job.Location, place)).OrderByDescending(job => job.ModifiedAt).Take(100).ToList(); + } + + private async Task GetTokenAsync(CancellationToken cancellationToken) + { + var configured = configuration["NavJobs:Token"]?.Trim(); + if (!string.IsNullOrWhiteSpace(configured)) return configured; + + return await cache.GetOrCreateAsync("nav-jobs-public-token", async entry => + { + entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); + var text = await clients.CreateClient().GetStringAsync(BaseUrl + "/api/publicToken", cancellationToken); + var start = text.IndexOf("eyJ", StringComparison.Ordinal); + if (start < 0) throw new InvalidOperationException("NAV public token was not returned."); + var token = text[start..].Trim(); + var end = token.IndexOfAny(['\r', '\n', ' ', '\t']); + return end < 0 ? token : token[..end]; + }) ?? throw new InvalidOperationException("NAV public token was not returned."); + } + + private static bool Contains(string? value, string filter) => + filter.Length == 0 || (value?.Contains(filter, StringComparison.OrdinalIgnoreCase) ?? false); +} diff --git a/JobTrackerApi/Services/SavedJobSearchAlertHostedService.cs b/JobTrackerApi/Services/SavedJobSearchAlertHostedService.cs new file mode 100644 index 00000000..3c158c6f --- /dev/null +++ b/JobTrackerApi/Services/SavedJobSearchAlertHostedService.cs @@ -0,0 +1,86 @@ +using JobTrackerApi.Data; +using JobTrackerApi.Models; +using Microsoft.EntityFrameworkCore; + +namespace JobTrackerApi.Services; + +public sealed class SavedJobSearchAlertHostedService( + BackgroundTenantRunner tenants, + IConfiguration configuration, + ILogger logger, + IStartupReadiness startupReadiness, + TimeProvider timeProvider) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await startupReadiness.WaitUntilReadyAsync(stoppingToken); + if (!IsEnabled()) + { + logger.LogInformation("Saved job search alert worker disabled."); + return; + } + + await Task.Delay(TimeSpan.FromSeconds(30), timeProvider, stoppingToken); + while (!stoppingToken.IsCancellationRequested) + { + await RunOnceAsync(stoppingToken); + await Task.Delay(GetInterval(), timeProvider, stoppingToken); + } + } + + public Task RunOnceAsync(CancellationToken cancellationToken) => + IsEnabled() + ? tenants.RunForSavedSearchOwnersAsync("saved-job-search-alerts", ProcessOwnerAsync, cancellationToken) + : Task.FromResult(BackgroundWorkerRunResult.Disabled); + + private bool IsEnabled() => configuration.GetValue("Workers:SavedJobSearchAlertsEnabled", true); + + private TimeSpan GetInterval() => TimeSpan.FromHours(Math.Clamp( + configuration.GetValue("JobDiscovery:SavedSearchIntervalHours", 6), 1, 24)); + + private async Task ProcessOwnerAsync(IServiceProvider services, CancellationToken cancellationToken) + { + var db = services.GetRequiredService(); + var runner = services.GetRequiredService(); + var now = timeProvider.GetUtcNow(); + var dueBefore = now - GetInterval(); + var useNorwegian = string.Equals( + await db.Users.AsNoTracking().Where(user => user.Id == db.CurrentUserId).Select(user => user.UiLanguage).FirstOrDefaultAsync(cancellationToken), + "nb", + StringComparison.OrdinalIgnoreCase); + var searches = await db.SavedJobSearches.Include(search => search.Results) + .Where(search => search.IsActive) + .OrderBy(search => search.Id) + .ToListAsync(cancellationToken); + + foreach (var search in searches.Where(search => search.LastRunAtUtc is null || search.LastRunAtUtc <= dueBefore)) + { + var result = await runner.RunAsync(search, cancellationToken); + // The first automatic run establishes a baseline. Alert only for vacancies + // that appear after that baseline so existing results never look "new". + if (!result.WasInitialRun && result.NewCount > 0) + { + db.UserNotifications.Add(new UserNotification + { + Id = Guid.NewGuid(), + OwnerUserId = search.OwnerUserId, + Kind = "saved_search_results", + Title = useNorwegian + ? result.NewCount == 1 ? "Ny stilling funnet" : $"{result.NewCount} nye stillinger funnet" + : result.NewCount == 1 ? "New vacancy found" : $"{result.NewCount} new vacancies found", + Message = useNorwegian + ? result.NewCount == 1 + ? $"Det lagrede søket «{search.Name}» fant en ny stilling." + : $"Det lagrede søket «{search.Name}» fant {result.NewCount} nye stillinger." + : result.NewCount == 1 + ? $"Your saved search ‘{search.Name}’ found a new vacancy." + : $"Your saved search ‘{search.Name}’ found {result.NewCount} new vacancies.", + LinkPath = "/discover", + CreatedAtUtc = now.UtcDateTime + }); + } + } + + await db.SaveChangesAsync(cancellationToken); + } +} diff --git a/JobTrackerApi/Services/SavedJobSearchRunner.cs b/JobTrackerApi/Services/SavedJobSearchRunner.cs new file mode 100644 index 00000000..d0940365 --- /dev/null +++ b/JobTrackerApi/Services/SavedJobSearchRunner.cs @@ -0,0 +1,44 @@ +using JobTrackerApi.Data; +using JobTrackerApi.Models; + +namespace JobTrackerApi.Services; + +public sealed record SavedJobSearchRunResult( + IReadOnlyList Jobs, + int NewCount, + bool WasInitialRun); + +public sealed record SavedJobSearchJobResult(DiscoveredJob Job, bool IsNew, bool IsDismissed); + +public sealed class SavedJobSearchRunner( + JobTrackerContext db, + IJobDiscoverySearchService discovery, + TimeProvider timeProvider) +{ + public async Task RunAsync(SavedJobSearch search, CancellationToken cancellationToken) + { + var jobs = await discovery.SearchAsync(search.Query, search.Location, cancellationToken); + var now = timeProvider.GetUtcNow(); + var wasInitialRun = search.LastRunAtUtc is null; + var existing = search.Results.ToDictionary(item => item.ExternalJobId, StringComparer.OrdinalIgnoreCase); + var results = new List(jobs.Count); + var newCount = 0; + foreach (var job in jobs) + { + var isNew = !existing.TryGetValue(job.Id, out var state); + if (state is null) + { + state = new SavedJobSearchResult { ExternalJobId = job.Id, FirstSeenAtUtc = now, LastSeenAtUtc = now }; + search.Results.Add(state); + db.SavedJobSearchResults.Add(state); + newCount++; + } + else state.LastSeenAtUtc = now; + results.Add(new SavedJobSearchJobResult(job, isNew, state.IsDismissed)); + } + + search.LastRunAtUtc = now; + search.UpdatedAtUtc = now; + return new SavedJobSearchRunResult(results, newCount, wasInitialRun); + } +} diff --git a/JobTrackerApi/appsettings.json b/JobTrackerApi/appsettings.json index 23d7bff5..4b78ab57 100644 --- a/JobTrackerApi/appsettings.json +++ b/JobTrackerApi/appsettings.json @@ -13,10 +13,14 @@ "Workers": { "RulesEnabled": false, "FollowUpRemindersEnabled": false, + "SavedJobSearchAlertsEnabled": true, "DailyExportEnabled": false, "JobEnrichmentEnabled": false, "AiOperationsEnabled": false }, + "JobDiscovery": { + "SavedSearchIntervalHours": 6 + }, "Ai": { "ExternalProcessingEnabled": false, "ExternalProvider": "ollama", diff --git a/docker-compose.yml b/docker-compose.yml index 84187da7..7b8bca69 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -78,6 +78,8 @@ services: # notification/privacy/entitlement prerequisites have been explicitly rolled out. - Workers__RulesEnabled=${WORKER_RULES_ENABLED:-false} - Workers__FollowUpRemindersEnabled=${WORKER_FOLLOWUP_REMINDERS_ENABLED:-false} + - Workers__SavedJobSearchAlertsEnabled=${WORKER_SAVED_SEARCH_ALERTS_ENABLED:-true} + - JobDiscovery__SavedSearchIntervalHours=${SAVED_SEARCH_INTERVAL_HOURS:-6} - Workers__DailyExportEnabled=${WORKER_DAILY_EXPORT_ENABLED:-false} - Workers__JobEnrichmentEnabled=${WORKER_JOB_ENRICHMENT_ENABLED:-false} - Workers__AiOperationsEnabled=${WORKER_AI_OPERATIONS_ENABLED:-false} diff --git a/docs/architecture/background-workers.md b/docs/architecture/background-workers.md index 326f3494..41054d99 100644 --- a/docs/architecture/background-workers.md +++ b/docs/architecture/background-workers.md @@ -6,7 +6,7 @@ Updated: 2026-08-02 HTTP requests derive `JobTrackerContext.CurrentUserId` from the authenticated request. Hosted services have no HTTP context, so deny-on-null query filters intentionally return no tenant rows. -`BackgroundTenantRunner` is the only worker bypass for the four job-owner schedulers. It uses `IgnoreQueryFilters` only to enumerate distinct non-empty job owners, then creates a fresh scope per owner and sets `CurrentUserService` before resolving the scoped `JobTrackerContext`. All work queries run through the normal tenant filters. An owner failure is counted and isolated; logs contain worker name, exception type and aggregate counts, not owner IDs or private content. An HTTP context cannot be replaced by a background owner. +`BackgroundTenantRunner` is the only worker bypass for the tenant schedulers. It uses `IgnoreQueryFilters` only to enumerate distinct non-empty owners from the resource a worker owns, then creates a fresh scope per owner and sets `CurrentUserService` before resolving the scoped `JobTrackerContext`. All work queries run through the normal tenant filters. An owner failure is counted and isolated; logs contain worker name, exception type and aggregate counts, not owner IDs or private content. An HTTP context cannot be replaced by a background owner. This is a sequential, single-instance foundation. Generic operation leasing now exists in OPS-001A, but notifications, bounded AI handlers and multi-replica scheduling belong to OPS-001B/C and AI-001 and must precede activation that needs them. @@ -16,6 +16,7 @@ This is a sequential, single-instance foundation. Generic operation leasing now |---|---|---|---| | `RulesHostedService` | owner runner + normal filters/per-user rules | changes job status | `Workers:RulesEnabled=false` by default; keep off until user-visible notification/audit behavior is ready | | `FollowUpReminderHostedService` | owner runner + normal filters | sends email, then marks date | both `Workers:FollowUpRemindersEnabled` and `Email:FollowUpReminders:Enabled`; keep off until persistent notification/idempotency work | +| `SavedJobSearchAlertHostedService` | saved-search owner runner + normal filters | checks active NAV searches and creates in-app notifications | enabled by default; users can pause each search, interval is `JobDiscovery:SavedSearchIntervalHours` (default 6); first run establishes a silent baseline | | `DailyExportHostedService` | owner runner + normal filters; one hashed-owner atomic file | writes local JSON | both `Workers:DailyExportEnabled` and `Exports:DailyEnabled`; keep off pending retention/operator rollout | | `JobEnrichmentHostedService` | owner runner + normal filters | deterministic tags and AI summary | `Workers:JobEnrichmentEnabled=false`; do not enable before Pro/privacy/provider/queue gates | | `CvProcessingHostedService` | existing explicit run owner on every unfiltered query | user-requested CV parsing/AI | unchanged; persistent run rows recover at startup, process-local wake-up remains single-instance | diff --git a/job-tracker-ui/src/i18n/translations.ts b/job-tracker-ui/src/i18n/translations.ts index b7891069..3ec623d7 100644 --- a/job-tracker-ui/src/i18n/translations.ts +++ b/job-tracker-ui/src/i18n/translations.ts @@ -275,7 +275,9 @@ export const translations = { jobDiscoveryViewListing: "View listing", jobDiscoverySaveTracker: "Save to tracker", jobDiscoverySavedSearches: "Saved searches", - jobDiscoverySavedSearchesHelp: "Run a saved NAV search to see which vacancies are genuinely new since your last check.", + jobDiscoverySavedSearchesHelp: "Saved NAV searches are checked automatically. You will be notified when new vacancies appear.", + jobDiscoveryAutomaticAlerts: "Automatic alerts", + jobDiscoveryUpdateAlertsFailed: "The alert setting could not be updated. Try again.", jobDiscoverySavedName: "Search name", jobDiscoverySavedDefaultName: "Recent vacancies", jobDiscoverySaveSearch: "Save search", @@ -2675,7 +2677,9 @@ export const translations = { jobDiscoveryViewListing: "Vis stilling", jobDiscoverySaveTracker: "Lagre i oversikten", jobDiscoverySavedSearches: "Lagrede søk", - jobDiscoverySavedSearchesHelp: "Kjør et lagret NAV-søk for å se hvilke stillinger som faktisk er nye siden sist.", + jobDiscoverySavedSearchesHelp: "Lagrede NAV-søk kontrolleres automatisk. Du får et varsel når nye stillinger dukker opp.", + jobDiscoveryAutomaticAlerts: "Automatiske varsler", + jobDiscoveryUpdateAlertsFailed: "Varslingsinnstillingen kunne ikke oppdateres. Prøv igjen.", jobDiscoverySavedName: "Navn på søket", jobDiscoverySavedDefaultName: "Nylige stillinger", jobDiscoverySaveSearch: "Lagre søk", diff --git a/job-tracker-ui/src/job-discovery.test.tsx b/job-tracker-ui/src/job-discovery.test.tsx index dddf439f..55cb6d6b 100644 --- a/job-tracker-ui/src/job-discovery.test.tsx +++ b/job-tracker-ui/src/job-discovery.test.tsx @@ -93,3 +93,17 @@ test("runs a saved search, marks unseen vacancies, and dismisses them", async () await waitFor(() => expect(screen.queryByText("Platform Engineer")).not.toBeInTheDocument()); expect(mockedApi.patch).toHaveBeenCalledWith("/job-discovery/saved-searches/7/results/new-1/dismiss", { isDismissed: true }); }); + +test("lets the user pause automatic alerts for a saved search", async () => { + const saved = { id: 7, name: "Backend Oslo", query: "backend", location: "Oslo", isActive: true, resultCount: 1, dismissedCount: 0 }; + mockedApi.get.mockResolvedValue({ data: [saved] } as any); + mockedApi.patch.mockResolvedValue({ data: { ...saved, isActive: false } } as any); + renderPage(); + + const toggle = await screen.findByRole("switch", { name: "Automatic alerts" }); + expect(toggle).toBeChecked(); + fireEvent.click(toggle); + + await waitFor(() => expect(mockedApi.patch).toHaveBeenCalledWith("/job-discovery/saved-searches/7", { isActive: false })); + await waitFor(() => expect(toggle).not.toBeChecked()); +}); diff --git a/job-tracker-ui/src/views/JobDiscoveryPage.tsx b/job-tracker-ui/src/views/JobDiscoveryPage.tsx index 220facd1..bacc411f 100644 --- a/job-tracker-ui/src/views/JobDiscoveryPage.tsx +++ b/job-tracker-ui/src/views/JobDiscoveryPage.tsx @@ -1,5 +1,5 @@ import { FormEvent, useEffect, useMemo, useState } from "react"; -import { Alert, Box, Button, Card, CardActions, CardContent, Chip, CircularProgress, MenuItem, Stack, TextField, Typography } from "@mui/material"; +import { Alert, Box, Button, Card, CardActions, CardContent, Chip, CircularProgress, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material"; import SearchIcon from "@mui/icons-material/Search"; import AddIcon from "@mui/icons-material/Add"; import BookmarkAddOutlinedIcon from "@mui/icons-material/BookmarkAddOutlined"; @@ -26,7 +26,7 @@ type DiscoveredJob = { isNew?: boolean; }; -type SavedSearch = { id: number; name: string; query: string; location: string; lastRunAtUtc?: string; resultCount: number; dismissedCount: number }; +type SavedSearch = { id: number; name: string; query: string; location: string; isActive: boolean; lastRunAtUtc?: string; resultCount: number; dismissedCount: number }; type SavedSearchRun = { search: SavedSearch; jobs: Array<{ job: DiscoveredJob; isNew: boolean; isDismissed: boolean }> }; type SortOrder = "updated" | "deadline" | "title"; @@ -47,6 +47,7 @@ export default function JobDiscoveryPage() { const [savedName, setSavedName] = useState(""); const [savingSearch, setSavingSearch] = useState(false); const [activeSavedSearchId, setActiveSavedSearchId] = useState(null); + const [updatingSavedSearchId, setUpdatingSavedSearchId] = useState(null); useEffect(() => { let active = true; @@ -102,6 +103,15 @@ export default function JobDiscoveryPage() { } catch { setError(t("jobDiscoveryDeleteSavedFailed")); } }; + const toggleSavedSearchAlerts = async (saved: SavedSearch) => { + setUpdatingSavedSearchId(saved.id); setError(""); + try { + const response = await api.patch(`/job-discovery/saved-searches/${saved.id}`, { isActive: !saved.isActive }); + setSavedSearches((current) => current.map((item) => item.id === saved.id ? response.data : item)); + } catch { setError(t("jobDiscoveryUpdateAlertsFailed")); } + finally { setUpdatingSavedSearchId(null); } + }; + const dismissJob = async (jobId: string) => { if (activeSavedSearchId === null) return; try { @@ -148,6 +158,11 @@ export default function JobDiscoveryPage() { {[saved.query, saved.location].filter(Boolean).join(" · ") || t("jobDiscoveryAllRecent")}{saved.lastRunAtUtc ? ` · ${t("jobDiscoveryLastRun", { date: formatDate(saved.lastRunAtUtc) ?? "" })}` : ""} + void toggleSavedSearchAlerts(saved)} />} + label={{t("jobDiscoveryAutomaticAlerts")}} + /> From caf486dceba859bfc8e453423c836894c74850cd Mon Sep 17 00:00:00 2001 From: cesnimda Date: Mon, 31 Aug 2026 22:16:16 +0200 Subject: [PATCH 2/9] feat(capture): add minimal browser extension --- browser-extension/README.md | 20 +++++++++++++++++ browser-extension/background.mjs | 23 ++++++++++++++++++++ browser-extension/capture-url.mjs | 15 +++++++++++++ browser-extension/manifest.json | 14 ++++++++++++ browser-extension/tests/capture-url.test.mjs | 23 ++++++++++++++++++++ 5 files changed, 95 insertions(+) create mode 100644 browser-extension/README.md create mode 100644 browser-extension/background.mjs create mode 100644 browser-extension/capture-url.mjs create mode 100644 browser-extension/manifest.json create mode 100644 browser-extension/tests/capture-url.test.mjs diff --git a/browser-extension/README.md b/browser-extension/README.md new file mode 100644 index 00000000..3ae9c643 --- /dev/null +++ b/browser-extension/README.md @@ -0,0 +1,20 @@ +# Jobjakt Quick Capture + +The Manifest V3 extension opens the current page or selected link in Jobjakt's existing reviewed import flow. It does not scrape page content, store credentials, or submit an application automatically. + +## Install locally + +1. Open `chrome://extensions` (or the equivalent extensions page in Edge). +2. Enable developer mode. +3. Choose **Load unpacked** and select this `browser-extension` folder. +4. Open a vacancy and click the Jobjakt extension, or use **Save vacancy to Jobjakt** from the page/link context menu. + +The Jobjakt add-job dialog opens with the vacancy URL and runs the same server-side preview, validation, duplicate checking, and user review used by normal URL imports. + +## Test + +```sh +node --test browser-extension/tests/*.test.mjs +``` + +No build or package installation is required. Zip the folder contents for store submission after adding store artwork and completing the browser-store privacy declarations. diff --git a/browser-extension/background.mjs b/browser-extension/background.mjs new file mode 100644 index 00000000..a1862465 --- /dev/null +++ b/browser-extension/background.mjs @@ -0,0 +1,23 @@ +import { buildCaptureUrl } from "./capture-url.mjs"; + +const menuId = "save-vacancy-to-jobjakt"; + +function openCapture(pageUrl) { + const captureUrl = buildCaptureUrl(pageUrl); + if (captureUrl) chrome.tabs.create({ url: captureUrl }); +} + +chrome.runtime.onInstalled.addListener(() => { + chrome.contextMenus.removeAll(() => { + chrome.contextMenus.create({ + id: menuId, + title: "Save vacancy to Jobjakt", + contexts: ["page", "link"] + }); + }); +}); + +chrome.action.onClicked.addListener((tab) => openCapture(tab.url)); +chrome.contextMenus.onClicked.addListener((info, tab) => { + if (info.menuItemId === menuId) openCapture(info.linkUrl || info.pageUrl || tab?.url); +}); diff --git a/browser-extension/capture-url.mjs b/browser-extension/capture-url.mjs new file mode 100644 index 00000000..a9f1ffb6 --- /dev/null +++ b/browser-extension/capture-url.mjs @@ -0,0 +1,15 @@ +export const JOBBJAKT_CAPTURE_ORIGIN = "https://jobs.cesnimda.uk"; + +export function buildCaptureUrl(pageUrl, origin = JOBBJAKT_CAPTURE_ORIGIN) { + let source; + try { + source = new URL(pageUrl); + } catch { + return null; + } + if (source.protocol !== "http:" && source.protocol !== "https:") return null; + + const capture = new URL("/", origin); + capture.searchParams.set("add", source.href); + return capture.href; +} diff --git a/browser-extension/manifest.json b/browser-extension/manifest.json new file mode 100644 index 00000000..f30bd9e9 --- /dev/null +++ b/browser-extension/manifest.json @@ -0,0 +1,14 @@ +{ + "manifest_version": 3, + "name": "Jobjakt Quick Capture", + "version": "1.0.0", + "description": "Send the current vacancy to Jobjakt's reviewed import flow.", + "permissions": ["activeTab", "contextMenus"], + "action": { + "default_title": "Save vacancy to Jobjakt" + }, + "background": { + "service_worker": "background.mjs", + "type": "module" + } +} diff --git a/browser-extension/tests/capture-url.test.mjs b/browser-extension/tests/capture-url.test.mjs new file mode 100644 index 00000000..1813cb86 --- /dev/null +++ b/browser-extension/tests/capture-url.test.mjs @@ -0,0 +1,23 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { buildCaptureUrl } from "../capture-url.mjs"; + +test("builds the existing reviewed capture route", () => { + const result = new URL(buildCaptureUrl("https://example.test/jobs/42?from=search")); + assert.equal(result.origin, "https://jobs.cesnimda.uk"); + assert.equal(result.pathname, "/"); + assert.equal(result.searchParams.get("add"), "https://example.test/jobs/42?from=search"); +}); + +test("rejects privileged and malformed URLs", () => { + assert.equal(buildCaptureUrl("chrome://settings"), null); + assert.equal(buildCaptureUrl("javascript:alert(1)"), null); + assert.equal(buildCaptureUrl("not a url"), null); +}); + +test("supports a local application origin during development", () => { + assert.equal( + buildCaptureUrl("https://arbeidsplassen.nav.no/stillinger/stilling/abc", "http://localhost:3300"), + "http://localhost:3300/?add=https%3A%2F%2Farbeidsplassen.nav.no%2Fstillinger%2Fstilling%2Fabc" + ); +}); From 1152e05687c5ddcf21b30d648aa8133c447366fb Mon Sep 17 00:00:00 2001 From: cesnimda Date: Mon, 31 Aug 2026 22:24:38 +0200 Subject: [PATCH 3/9] feat(calendar): add application date integrations --- .../ApplicationCalendarControllerTests.cs | 119 +++++++++++++++ .../ApplicationCalendarController.cs | 144 ++++++++++++++++++ JobTrackerApi/Models/ExternalCalendarEvent.cs | 12 ++ JobTrackerApi/Services/GmailOAuthService.cs | 45 +++++- .../Services/MicrosoftGraphOAuthService.cs | 45 +++++- docs/operations/calendar-integrations.md | 29 ++++ .../src/application-calendar.test.tsx | 45 ++++++ .../components/ApplicationCalendarActions.tsx | 80 ++++++++++ job-tracker-ui/src/i18n/translations.ts | 28 ++++ .../src/views/ApplicationWorkspacePage.tsx | 2 + 10 files changed, 547 insertions(+), 2 deletions(-) create mode 100644 JobTrackerApi.Tests/ApplicationCalendarControllerTests.cs create mode 100644 JobTrackerApi/Controllers/ApplicationCalendarController.cs create mode 100644 JobTrackerApi/Models/ExternalCalendarEvent.cs create mode 100644 docs/operations/calendar-integrations.md create mode 100644 job-tracker-ui/src/application-calendar.test.tsx create mode 100644 job-tracker-ui/src/components/ApplicationCalendarActions.tsx diff --git a/JobTrackerApi.Tests/ApplicationCalendarControllerTests.cs b/JobTrackerApi.Tests/ApplicationCalendarControllerTests.cs new file mode 100644 index 00000000..06577ec6 --- /dev/null +++ b/JobTrackerApi.Tests/ApplicationCalendarControllerTests.cs @@ -0,0 +1,119 @@ +using JobTrackerApi.Controllers; +using JobTrackerApi.Data; +using JobTrackerApi.Models; +using JobTrackerApi.Services; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Moq; +using Xunit; + +namespace JobTrackerApi.Tests; + +public sealed class ApplicationCalendarControllerTests +{ + [Fact] + public async Task Status_distinguishes_connection_from_calendar_consent() + { + await using var db = CreateDb("owner-1"); + var google = new Mock(); + google.Setup(service => service.GetConnectionAsync("owner-1", It.IsAny())) + .ReturnsAsync(new GmailConnection { OwnerUserId = "owner-1", Scope = GmailOAuthService.CalendarScope }); + var microsoft = new Mock(); + microsoft.Setup(service => service.GetConnectionAsync("owner-1", It.IsAny())) + .ReturnsAsync(new MicrosoftGraphConnection { OwnerUserId = "owner-1", Scope = "Mail.Read" }); + var controller = CreateController(db, "owner-1", google.Object, microsoft.Object); + + var value = Assert.IsType(Assert.IsType((await controller.Status(default)).Result).Value); + + Assert.True(value.Google.Connected); + Assert.True(value.Google.Writable); + Assert.True(value.Microsoft.Connected); + Assert.False(value.Microsoft.Writable); + } + + [Fact] + public async Task Creates_follow_up_in_selected_connected_calendar_with_stable_job_context() + { + await using var db = CreateDb("owner-1"); + var job = await SeedJobAsync(db, "owner-1"); + ExternalCalendarEventRequest? sent = null; + var google = new Mock(); + google.Setup(service => service.CreateCalendarEventAsync("owner-1", It.IsAny(), It.IsAny())) + .Callback((_, request, _) => sent = request) + .ReturnsAsync(new ExternalCalendarEventResult("event-1", "https://calendar.google.test/event-1")); + var controller = CreateController(db, "owner-1", google.Object, Mock.Of()); + + var response = await controller.CreateEvent(job.Id, new("google", "follow-up"), default); + + var value = Assert.IsType(Assert.IsType(response.Result).Value); + Assert.Equal("google", value.Provider); + Assert.Equal("event-1", value.Id); + Assert.NotNull(sent); + Assert.Equal("Follow up: Backend Engineer at Acme", sent.Summary); + Assert.Equal(job.FollowUpAt, sent.StartsAtUtc.UtcDateTime); + Assert.False(sent.AllDay); + Assert.Equal(64, sent.StableId.Length); + } + + [Fact] + public async Task Rejects_another_owners_job_without_calling_provider() + { + await using var db = CreateDb("owner-1"); + var job = await SeedJobAsync(db, "owner-2"); + var google = new Mock(MockBehavior.Strict); + var controller = CreateController(db, "owner-1", google.Object, Mock.Of()); + + var response = await controller.CreateEvent(job.Id, new("google", "follow-up"), default); + + Assert.IsType(response.Result); + } + + [Fact] + public async Task Downloads_portable_all_day_deadline_event_without_provider_credentials() + { + await using var db = CreateDb("owner-1"); + var job = await SeedJobAsync(db, "owner-1"); + var controller = CreateController(db, "owner-1", Mock.Of(), Mock.Of()); + + var response = Assert.IsType(await controller.DownloadEvent(job.Id, "deadline", default)); + var content = System.Text.Encoding.UTF8.GetString(response.FileContents); + + Assert.Equal("text/calendar; charset=utf-8", response.ContentType); + Assert.Contains("DTSTART;VALUE=DATE:20260915", content); + Assert.Contains("DTEND;VALUE=DATE:20260916", content); + Assert.Contains("SUMMARY:Application deadline: Backend Engineer at Acme", content); + } + + private static JobTrackerContext CreateDb(string owner) + { + var current = new Mock(); + current.SetupGet(service => service.UserId).Returns(owner); + return new JobTrackerContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options, current.Object); + } + + private static async Task SeedJobAsync(JobTrackerContext db, string owner) + { + var company = new Company { OwnerUserId = owner, Name = "Acme" }; + var job = new JobApplication + { + OwnerUserId = owner, + Company = company, + JobTitle = "Backend Engineer", + Status = "Applied", + FollowUpAt = new DateTime(2026, 9, 2, 10, 30, 0, DateTimeKind.Utc), + Deadline = new DateTime(2026, 9, 15, 0, 0, 0, DateTimeKind.Utc), + Location = "Oslo" + }; + db.JobApplications.Add(job); + await db.SaveChangesAsync(); + return job; + } + + private static ApplicationCalendarController CreateController(JobTrackerContext db, string owner, IGmailOAuthService google, IMicrosoftGraphOAuthService microsoft) + { + var current = new Mock(); + current.SetupGet(service => service.UserId).Returns(owner); + return new ApplicationCalendarController(db, current.Object, google, microsoft); + } +} diff --git a/JobTrackerApi/Controllers/ApplicationCalendarController.cs b/JobTrackerApi/Controllers/ApplicationCalendarController.cs new file mode 100644 index 00000000..9aeaa265 --- /dev/null +++ b/JobTrackerApi/Controllers/ApplicationCalendarController.cs @@ -0,0 +1,144 @@ +using System.Security.Cryptography; +using System.Text; +using JobTrackerApi.Data; +using JobTrackerApi.Models; +using JobTrackerApi.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace JobTrackerApi.Controllers; + +[ApiController] +[Route("api/calendar")] +[Authorize(AuthenticationSchemes = "local")] +public sealed class ApplicationCalendarController( + JobTrackerContext db, + ICurrentUserService currentUser, + IGmailOAuthService google, + IMicrosoftGraphOAuthService microsoft) : ControllerBase +{ + [HttpGet("status")] + public async Task> Status(CancellationToken cancellationToken) + { + var owner = RequiredOwner(); + var googleConnection = await google.GetConnectionAsync(owner, cancellationToken); + var microsoftConnection = await microsoft.GetConnectionAsync(owner, cancellationToken); + return Ok(new CalendarStatusDto( + new CalendarProviderStatusDto(googleConnection is not null, GmailOAuthService.HasCalendarScope(googleConnection?.Scope)), + new CalendarProviderStatusDto(microsoftConnection is not null, MicrosoftGraphOAuthService.HasCalendarScope(microsoftConnection?.Scope)))); + } + + [HttpPost("jobs/{jobId:int}/events")] + public async Task> CreateEvent(int jobId, [FromBody] CreateCalendarEventRequest request, CancellationToken cancellationToken) + { + var owner = RequiredOwner(); + var job = await LoadJobAsync(jobId, owner, cancellationToken); + if (job is null) return NotFound(); + if (!TryBuildEvent(job, owner, request.Kind, out var calendarEvent, out var validationError)) + return ValidationProblem(validationError); + + try + { + var provider = request.Provider?.Trim().ToLowerInvariant(); + var result = provider switch + { + "google" => await google.CreateCalendarEventAsync(owner, calendarEvent!, cancellationToken), + "microsoft" => await microsoft.CreateCalendarEventAsync(owner, calendarEvent!, cancellationToken), + _ => throw new ArgumentException("Choose Google Calendar or Outlook Calendar.") + }; + return Ok(new CalendarEventDto(provider!, result.Id, result.WebUrl)); + } + catch (ArgumentException ex) + { + return ValidationProblem(ex.Message); + } + catch (InvalidOperationException ex) + { + return Conflict(new ProblemDetails { Title = "Calendar permission required", Detail = ex.Message, Status = StatusCodes.Status409Conflict }); + } + catch (HttpRequestException) + { + return Problem("The calendar provider is temporarily unavailable.", statusCode: StatusCodes.Status502BadGateway); + } + } + + [HttpGet("jobs/{jobId:int}/events.ics")] + public async Task DownloadEvent(int jobId, [FromQuery] string? kind, CancellationToken cancellationToken) + { + var owner = RequiredOwner(); + var job = await LoadJobAsync(jobId, owner, cancellationToken); + if (job is null) return NotFound(); + if (!TryBuildEvent(job, owner, kind, out var calendarEvent, out var validationError)) + return ValidationProblem(validationError); + + var value = calendarEvent!; + var start = value.AllDay ? $"DTSTART;VALUE=DATE:{value.StartsAtUtc:yyyyMMdd}" : $"DTSTART:{value.StartsAtUtc.UtcDateTime:yyyyMMdd'T'HHmmss'Z'}"; + var end = value.AllDay ? $"DTEND;VALUE=DATE:{value.EndsAtUtc:yyyyMMdd}" : $"DTEND:{value.EndsAtUtc.UtcDateTime:yyyyMMdd'T'HHmmss'Z'}"; + var ics = string.Join("\r\n", new[] + { + "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Jobjakt//Application Calendar//EN", "CALSCALE:GREGORIAN", + "BEGIN:VEVENT", $"UID:{value.StableId}@jobs.cesnimda.uk", $"DTSTAMP:{DateTime.UtcNow:yyyyMMdd'T'HHmmss'Z'}", + start, end, $"SUMMARY:{EscapeIcs(value.Summary)}", + $"DESCRIPTION:{EscapeIcs(value.Description)}", $"LOCATION:{EscapeIcs(value.Location)}", + "END:VEVENT", "END:VCALENDAR", "" + }); + return File(Encoding.UTF8.GetBytes(ics), "text/calendar; charset=utf-8", $"jobjakt-{job.Id}-{NormalizeKind(kind)}.ics"); + } + + private Task LoadJobAsync(int jobId, string owner, CancellationToken cancellationToken) => + db.JobApplications.Include(job => job.Company) + .FirstOrDefaultAsync(job => job.Id == jobId && job.OwnerUserId == owner && !job.IsDeleted, cancellationToken); + + private static bool TryBuildEvent(JobApplication job, string owner, string? requestedKind, out ExternalCalendarEventRequest? result, out string error) + { + var kind = NormalizeKind(requestedKind); + DateTimeOffset start; + DateTimeOffset end; + bool allDay; + string label; + if (kind == "follow-up" && job.FollowUpAt is { } followUp) + { + start = ToUtcOffset(followUp); + end = start.AddMinutes(30); + allDay = false; + label = "Follow up"; + } + else if (kind == "deadline" && job.Deadline is { } deadline) + { + start = new DateTimeOffset(DateTime.SpecifyKind(deadline.Date, DateTimeKind.Utc)); + end = start.AddDays(1); + allDay = true; + label = "Application deadline"; + } + else + { + result = null; + error = kind == "follow-up" ? "Set a follow-up date before adding it to a calendar." : "This application has no deadline to add."; + return false; + } + + var company = job.Company?.Name?.Trim(); + var summary = string.IsNullOrWhiteSpace(company) ? $"{label}: {job.JobTitle}" : $"{label}: {job.JobTitle} at {company}"; + var stableId = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"{owner}|{job.Id}|{kind}"))).ToLowerInvariant(); + result = new ExternalCalendarEventRequest(stableId, summary, job.NextAction, job.Location, start, end, allDay); + error = string.Empty; + return true; + } + + private static DateTimeOffset ToUtcOffset(DateTime value) => value.Kind switch + { + DateTimeKind.Utc => new DateTimeOffset(value), + DateTimeKind.Local => value.ToUniversalTime(), + _ => new DateTimeOffset(DateTime.SpecifyKind(value, DateTimeKind.Utc)) + }; + + private static string NormalizeKind(string? kind) => string.Equals(kind?.Trim(), "deadline", StringComparison.OrdinalIgnoreCase) ? "deadline" : "follow-up"; + private static string EscapeIcs(string? value) => (value ?? string.Empty).Replace("\\", "\\\\").Replace(";", "\\;").Replace(",", "\\,").Replace("\r\n", "\\n").Replace("\r", "\\n").Replace("\n", "\\n"); + private string RequiredOwner() => currentUser.UserId ?? throw new UnauthorizedAccessException("Authentication required."); + + public sealed record CalendarProviderStatusDto(bool Connected, bool Writable); + public sealed record CalendarStatusDto(CalendarProviderStatusDto Google, CalendarProviderStatusDto Microsoft); + public sealed record CreateCalendarEventRequest(string? Provider, string? Kind); + public sealed record CalendarEventDto(string Provider, string? Id, string? WebUrl); +} diff --git a/JobTrackerApi/Models/ExternalCalendarEvent.cs b/JobTrackerApi/Models/ExternalCalendarEvent.cs new file mode 100644 index 00000000..e1d219a5 --- /dev/null +++ b/JobTrackerApi/Models/ExternalCalendarEvent.cs @@ -0,0 +1,12 @@ +namespace JobTrackerApi.Models; + +public sealed record ExternalCalendarEventRequest( + string StableId, + string Summary, + string? Description, + string? Location, + DateTimeOffset StartsAtUtc, + DateTimeOffset EndsAtUtc, + bool AllDay); + +public sealed record ExternalCalendarEventResult(string? Id, string? WebUrl); diff --git a/JobTrackerApi/Services/GmailOAuthService.cs b/JobTrackerApi/Services/GmailOAuthService.cs index 55701897..a5a5d946 100644 --- a/JobTrackerApi/Services/GmailOAuthService.cs +++ b/JobTrackerApi/Services/GmailOAuthService.cs @@ -25,6 +25,7 @@ public interface IGmailOAuthService Task> ListThreadMessagesAsync(string ownerUserId, string threadId, CancellationToken cancellationToken); Task GetMessageAsync(string ownerUserId, string messageId, CancellationToken cancellationToken); Task SendAsync(string ownerUserId, GmailSendRequest request, CancellationToken cancellationToken); + Task CreateCalendarEventAsync(string ownerUserId, ExternalCalendarEventRequest request, CancellationToken cancellationToken); } public sealed record GmailOAuthExchangeResult(string GmailAddress); @@ -47,7 +48,8 @@ internal sealed class GmailTokenResponse public sealed class GmailOAuthService : IGmailOAuthService { public const string SendScope = "https://www.googleapis.com/auth/gmail.send"; - private const string Scope = $"openid email profile https://www.googleapis.com/auth/gmail.readonly {SendScope}"; + public const string CalendarScope = "https://www.googleapis.com/auth/calendar.events"; + private const string Scope = $"openid email profile https://www.googleapis.com/auth/gmail.readonly {SendScope} {CalendarScope}"; private readonly IConfiguration _cfg; private readonly JobTrackerContext _db; private readonly IDataProtector _protector; @@ -419,6 +421,47 @@ public sealed class GmailOAuthService : IGmailOAuthService public static bool HasSendScope(string? scope) => !string.IsNullOrWhiteSpace(scope) && scope.Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains(SendScope, StringComparer.OrdinalIgnoreCase); + public async Task CreateCalendarEventAsync(string ownerUserId, ExternalCalendarEventRequest request, CancellationToken cancellationToken) + { + var connection = await _db.GmailConnections.AsNoTracking().FirstOrDefaultAsync(item => item.OwnerUserId == ownerUserId, cancellationToken); + if (connection is null || !HasCalendarScope(connection.Scope)) + throw new InvalidOperationException("Reconnect Google and approve calendar access before adding events."); + + var payload = request.AllDay + ? JsonSerializer.Serialize(new + { + summary = request.Summary, + description = request.Description, + location = request.Location, + start = new { date = request.StartsAtUtc.UtcDateTime.ToString("yyyy-MM-dd") }, + end = new { date = request.EndsAtUtc.UtcDateTime.ToString("yyyy-MM-dd") } + }) + : JsonSerializer.Serialize(new + { + summary = request.Summary, + description = request.Description, + location = request.Location, + start = new { dateTime = request.StartsAtUtc.ToString("O") }, + end = new { dateTime = request.EndsAtUtc.ToString("O") } + }); + + var accessToken = await GetValidAccessTokenAsync(ownerUserId, cancellationToken); + var client = _httpClientFactory.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); + using var response = await client.PutAsync( + $"https://www.googleapis.com/calendar/v3/calendars/primary/events/{Uri.EscapeDataString(request.StableId)}", + new StringContent(payload, Encoding.UTF8, "application/json"), + cancellationToken); + response.EnsureSuccessStatusCode(); + using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken); + return new ExternalCalendarEventResult( + document.RootElement.TryGetProperty("id", out var id) ? id.GetString() : null, + document.RootElement.TryGetProperty("htmlLink", out var link) ? link.GetString() : null); + } + + public static bool HasCalendarScope(string? scope) => + !string.IsNullOrWhiteSpace(scope) && scope.Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains(CalendarScope, StringComparer.OrdinalIgnoreCase); + private static void ValidateSendRequest(string to, string subject, string bodyText) { if (string.IsNullOrWhiteSpace(to)) throw new ArgumentException("Recipient is required.", nameof(to)); diff --git a/JobTrackerApi/Services/MicrosoftGraphOAuthService.cs b/JobTrackerApi/Services/MicrosoftGraphOAuthService.cs index 9df2f084..d4e40783 100644 --- a/JobTrackerApi/Services/MicrosoftGraphOAuthService.cs +++ b/JobTrackerApi/Services/MicrosoftGraphOAuthService.cs @@ -21,6 +21,7 @@ public interface IMicrosoftGraphOAuthService Task> ListThreadMessagesAsync(string ownerUserId, string conversationId, CancellationToken cancellationToken); Task GetMessageAsync(string ownerUserId, string messageId, CancellationToken cancellationToken); Task SendAsync(string ownerUserId, MicrosoftGraphSendRequest request, CancellationToken cancellationToken); + Task CreateCalendarEventAsync(string ownerUserId, ExternalCalendarEventRequest request, CancellationToken cancellationToken); } public sealed record MicrosoftGraphOAuthExchangeResult(string MailAddress); @@ -47,7 +48,8 @@ internal sealed class MicrosoftGraphTokenResponse public sealed class MicrosoftGraphOAuthService : IMicrosoftGraphOAuthService { public const string SendScope = "https://graph.microsoft.com/Mail.Send"; - private const string Scope = $"openid email profile offline_access https://graph.microsoft.com/Mail.Read {SendScope}"; + public const string CalendarScope = "https://graph.microsoft.com/Calendars.ReadWrite"; + private const string Scope = $"openid email profile offline_access https://graph.microsoft.com/Mail.Read {SendScope} {CalendarScope}"; private readonly IConfiguration _cfg; private readonly JobTrackerContext _db; private readonly IDataProtector _protector; @@ -340,6 +342,47 @@ public sealed class MicrosoftGraphOAuthService : IMicrosoftGraphOAuthService string.Equals(value, "Mail.Send", StringComparison.OrdinalIgnoreCase)); } + public async Task CreateCalendarEventAsync(string ownerUserId, ExternalCalendarEventRequest request, CancellationToken cancellationToken) + { + var connection = await _db.MicrosoftGraphConnections.AsNoTracking().FirstOrDefaultAsync(item => item.OwnerUserId == ownerUserId, cancellationToken); + if (connection is null || !HasCalendarScope(connection.Scope)) + throw new InvalidOperationException("Reconnect Outlook and approve calendar access before adding events."); + + var startsAt = request.AllDay ? request.StartsAtUtc.UtcDateTime.Date : request.StartsAtUtc.UtcDateTime; + var endsAt = request.AllDay ? request.EndsAtUtc.UtcDateTime.Date : request.EndsAtUtc.UtcDateTime; + var payload = JsonSerializer.Serialize(new + { + subject = request.Summary, + body = new { contentType = "Text", content = request.Description ?? string.Empty }, + location = new { displayName = request.Location ?? string.Empty }, + start = new { dateTime = startsAt.ToString("yyyy-MM-ddTHH:mm:ss"), timeZone = "UTC" }, + end = new { dateTime = endsAt.ToString("yyyy-MM-ddTHH:mm:ss"), timeZone = "UTC" }, + isAllDay = request.AllDay, + transactionId = request.StableId + }); + + var accessToken = await GetValidAccessTokenAsync(ownerUserId, cancellationToken); + var client = _httpClientFactory.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); + using var response = await client.PostAsync( + "https://graph.microsoft.com/v1.0/me/events", + new StringContent(payload, System.Text.Encoding.UTF8, "application/json"), + cancellationToken); + response.EnsureSuccessStatusCode(); + using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken); + return new ExternalCalendarEventResult( + document.RootElement.TryGetProperty("id", out var id) ? id.GetString() : null, + document.RootElement.TryGetProperty("webLink", out var link) ? link.GetString() : null); + } + + public static bool HasCalendarScope(string? scope) + { + if (string.IsNullOrWhiteSpace(scope)) return false; + return scope.Split(' ', StringSplitOptions.RemoveEmptyEntries).Any(value => + string.Equals(value, CalendarScope, StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "Calendars.ReadWrite", StringComparison.OrdinalIgnoreCase)); + } + private static void ValidateSendRequest(string to, string subject, string bodyText) { if (string.IsNullOrWhiteSpace(to)) throw new ArgumentException("Recipient is required.", nameof(to)); diff --git a/docs/operations/calendar-integrations.md b/docs/operations/calendar-integrations.md new file mode 100644 index 00000000..f3e926bf --- /dev/null +++ b/docs/operations/calendar-integrations.md @@ -0,0 +1,29 @@ +# Calendar integrations + +Jobjakt can add an application's follow-up date or deadline to Google Calendar or Outlook Calendar. The same workspace panel always offers a portable `.ics` download, which requires no provider account. + +## Provider configuration + +Calendar access reuses the encrypted OAuth connections already used for Gmail and Microsoft Graph mail. No calendar tokens or credentials are stored separately. + +### Google + +1. Enable the Google Calendar API in the Google Cloud project used by `GMAIL_CLIENT_ID` / `GMAIL_CLIENT_SECRET`. +2. Keep the existing Gmail OAuth callback URI registered. +3. Reconnect Google from Settings. The consent request now includes `https://www.googleapis.com/auth/calendar.events`. + +### Microsoft + +1. In the Entra application used by `MICROSOFT_GRAPH_CLIENT_ID` / `MICROSOFT_GRAPH_CLIENT_SECRET`, add the delegated `Calendars.ReadWrite` permission. +2. Keep the existing Microsoft Graph OAuth callback URI registered. +3. Reconnect Outlook from Settings and grant the new permission. + +Existing connections remain valid for mail. The application reports them as connected but not calendar-writable until the user reconnects and grants the new scope. + +## Behaviour and rollback + +- Calendar writes happen only after an explicit user action in an application workspace. +- Jobjakt sends the job title, company, location, next-action text, and selected date; it never sends the CV or job description. +- Google uses a deterministic event ID, and Microsoft receives a deterministic transaction ID, reducing duplicate events when a request is retried. +- Disable or remove the provider's delegated calendar permission to stop direct writes. `.ics` download remains available. +- No database migration is required. diff --git a/job-tracker-ui/src/application-calendar.test.tsx b/job-tracker-ui/src/application-calendar.test.tsx new file mode 100644 index 00000000..59477bb0 --- /dev/null +++ b/job-tracker-ui/src/application-calendar.test.tsx @@ -0,0 +1,45 @@ +import "@testing-library/jest-dom"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { api } from "./api"; +import ApplicationCalendarActions from "./components/ApplicationCalendarActions"; +import { I18nProvider } from "./i18n/I18nProvider"; + +jest.mock("./api", () => ({ + api: { get: jest.fn(), post: jest.fn() }, + getApiErrorMessage: (_: unknown, fallback: string) => fallback, +})); +const mockedApi = api as jest.Mocked; + +beforeEach(() => { + window.localStorage.clear(); + mockedApi.get.mockResolvedValue({ data: { google: { connected: true, writable: true }, microsoft: { connected: false, writable: false } } } as any); + mockedApi.post.mockResolvedValue({ data: { provider: "google", id: "event-1", webUrl: "https://calendar.google.test/event-1" } } as any); +}); +afterEach(() => jest.clearAllMocks()); + +test("adds the selected application date to a writable connected calendar", async () => { + render(); + + const googleButtons = await screen.findAllByRole("button", { name: "Google Calendar" }); + fireEvent.click(googleButtons[0]); + + await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith("/calendar/jobs/42/events", { provider: "google", kind: "follow-up" })); + expect(await screen.findByText("The event was added to your calendar.")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Open event" })).toHaveAttribute("href", "https://calendar.google.test/event-1"); +}); + +test("keeps portable calendar download available without a provider connection", async () => { + mockedApi.get.mockResolvedValue({ data: { google: { connected: false, writable: false }, microsoft: { connected: false, writable: false } } } as any); + render(); + + expect(await screen.findByRole("button", { name: "Download .ics" })).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Google Calendar" })).not.toBeInTheDocument(); +}); + +test("explains when an existing connection needs renewed calendar consent", async () => { + mockedApi.get.mockResolvedValue({ data: { google: { connected: true, writable: false }, microsoft: { connected: false, writable: false } } } as any); + render(); + + expect(await screen.findByText("Reconnect your calendar account to approve calendar access.")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Reconnect" })).toHaveAttribute("href", "/settings"); +}); diff --git a/job-tracker-ui/src/components/ApplicationCalendarActions.tsx b/job-tracker-ui/src/components/ApplicationCalendarActions.tsx new file mode 100644 index 00000000..9b682180 --- /dev/null +++ b/job-tracker-ui/src/components/ApplicationCalendarActions.tsx @@ -0,0 +1,80 @@ +import { useEffect, useState } from "react"; +import { Alert, Box, Button, CircularProgress, Stack, Typography } from "@mui/material"; +import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined"; +import DownloadOutlinedIcon from "@mui/icons-material/DownloadOutlined"; +import OpenInNewIcon from "@mui/icons-material/OpenInNew"; +import { api, getApiErrorMessage } from "../api"; +import { useI18n } from "../i18n/I18nProvider"; + +type ProviderStatus = { connected: boolean; writable: boolean }; +type CalendarStatus = { google: ProviderStatus; microsoft: ProviderStatus }; +type EventKind = "follow-up" | "deadline"; +type CalendarEventResult = { provider: string; id?: string; webUrl?: string }; + +export default function ApplicationCalendarActions({ jobId, followUpAt, deadline }: { jobId: number; followUpAt?: string | null; deadline?: string | null }) { + const { t } = useI18n(); + const [status, setStatus] = useState(null); + const [busy, setBusy] = useState(""); + const [error, setError] = useState(""); + const [created, setCreated] = useState(null); + + useEffect(() => { + let active = true; + api.get("/calendar/status") + .then((response) => { if (active) setStatus(response.data); }) + .catch(() => { if (active) setStatus({ google: { connected: false, writable: false }, microsoft: { connected: false, writable: false } }); }); + return () => { active = false; }; + }, []); + + const create = async (provider: "google" | "microsoft", kind: EventKind) => { + setBusy(`${provider}-${kind}`); setError(""); setCreated(null); + try { + const response = await api.post(`/calendar/jobs/${jobId}/events`, { provider, kind }); + setCreated(response.data); + } catch (err) { setError(getApiErrorMessage(err, t("calendarCreateFailed"))); } + finally { setBusy(""); } + }; + + const download = async (kind: EventKind) => { + setBusy(`ics-${kind}`); setError(""); + try { + const response = await api.get(`/calendar/jobs/${jobId}/events.ics`, { params: { kind }, responseType: "blob" }); + const url = URL.createObjectURL(response.data); + const anchor = document.createElement("a"); + anchor.href = url; anchor.download = `jobjakt-${jobId}-${kind}.ics`; anchor.click(); + URL.revokeObjectURL(url); + } catch (err) { setError(getApiErrorMessage(err, t("calendarDownloadFailed"))); } + finally { setBusy(""); } + }; + + const rows: Array<{ kind: EventKind; title: string }> = [ + ...(followUpAt ? [{ kind: "follow-up" as const, title: t("calendarFollowUp") }] : []), + ...(deadline ? [{ kind: "deadline" as const, title: t("calendarDeadline") }] : []), + ]; + + if (rows.length === 0) return {t("calendarNoDates")}; + if (!status) return {t("loading")}; + + return ( + + {t("calendarHelp")} + {(status.google.connected && !status.google.writable) || (status.microsoft.connected && !status.microsoft.writable) ? ( + {t("calendarReconnect")}}>{t("calendarPermissionNeeded")} + ) : null} + {error ? {error} : null} + {created ? ( + }>{t("calendarOpen")} : undefined}> + {t("calendarCreated")} + + ) : null} + {rows.map((row) => ( + + {row.title} + {status.google.writable ? : null} + {status.microsoft.writable ? : null} + + + ))} + + ); +} diff --git a/job-tracker-ui/src/i18n/translations.ts b/job-tracker-ui/src/i18n/translations.ts index 3ec623d7..2bf45566 100644 --- a/job-tracker-ui/src/i18n/translations.ts +++ b/job-tracker-ui/src/i18n/translations.ts @@ -278,6 +278,20 @@ export const translations = { jobDiscoverySavedSearchesHelp: "Saved NAV searches are checked automatically. You will be notified when new vacancies appear.", jobDiscoveryAutomaticAlerts: "Automatic alerts", jobDiscoveryUpdateAlertsFailed: "The alert setting could not be updated. Try again.", + calendarTitle: "Calendar", + calendarHelp: "Add important application dates to a connected calendar, or download a portable calendar file.", + calendarFollowUp: "Application follow-up", + calendarDeadline: "Application deadline", + calendarGoogle: "Google Calendar", + calendarOutlook: "Outlook Calendar", + calendarDownload: "Download .ics", + calendarReconnect: "Reconnect", + calendarPermissionNeeded: "Reconnect your calendar account to approve calendar access.", + calendarCreated: "The event was added to your calendar.", + calendarOpen: "Open event", + calendarNoDates: "Set a follow-up date or application deadline to add it to a calendar.", + calendarCreateFailed: "The calendar event could not be created.", + calendarDownloadFailed: "The calendar file could not be downloaded.", jobDiscoverySavedName: "Search name", jobDiscoverySavedDefaultName: "Recent vacancies", jobDiscoverySaveSearch: "Save search", @@ -2680,6 +2694,20 @@ export const translations = { jobDiscoverySavedSearchesHelp: "Lagrede NAV-søk kontrolleres automatisk. Du får et varsel når nye stillinger dukker opp.", jobDiscoveryAutomaticAlerts: "Automatiske varsler", jobDiscoveryUpdateAlertsFailed: "Varslingsinnstillingen kunne ikke oppdateres. Prøv igjen.", + calendarTitle: "Kalender", + calendarHelp: "Legg viktige søknadsdatoer til i en tilkoblet kalender, eller last ned en kalenderfil.", + calendarFollowUp: "Oppfølging av søknad", + calendarDeadline: "Søknadsfrist", + calendarGoogle: "Google Kalender", + calendarOutlook: "Outlook-kalender", + calendarDownload: "Last ned .ics", + calendarReconnect: "Koble til på nytt", + calendarPermissionNeeded: "Koble til kalenderkontoen på nytt for å godkjenne kalendertilgang.", + calendarCreated: "Hendelsen ble lagt til i kalenderen.", + calendarOpen: "Åpne hendelsen", + calendarNoDates: "Angi en oppfølgingsdato eller søknadsfrist for å legge den til i en kalender.", + calendarCreateFailed: "Kalenderhendelsen kunne ikke opprettes.", + calendarDownloadFailed: "Kalenderfilen kunne ikke lastes ned.", jobDiscoverySavedName: "Navn på søket", jobDiscoverySavedDefaultName: "Nylige stillinger", jobDiscoverySaveSearch: "Lagre søk", diff --git a/job-tracker-ui/src/views/ApplicationWorkspacePage.tsx b/job-tracker-ui/src/views/ApplicationWorkspacePage.tsx index d275c6ac..c09ca96a 100644 --- a/job-tracker-ui/src/views/ApplicationWorkspacePage.tsx +++ b/job-tracker-ui/src/views/ApplicationWorkspacePage.tsx @@ -22,6 +22,7 @@ import { getApiErrorMessage } from "../api"; import Attachments from "../components/Attachments"; import Correspondence from "../components/Correspondence"; import ApplicationChecklist from "../components/ApplicationChecklist"; +import ApplicationCalendarActions from "../components/ApplicationCalendarActions"; import { ApplicationAnalysis, ApplicationMatch, ApplicationTimeline, } from "../components/ApplicationIntelligence"; @@ -387,6 +388,7 @@ function OverviewDetails({ jobId, overview, onReload, onEdit }: { jobId: number; const panels = [ { id: "details", title: t("workspaceJobDetails"), content: }, { id: "tasks", title: t("workspaceChecklist"), content: }, + { id: "calendar", title: t("calendarTitle"), content: }, { id: "timeline", title: t("workspaceActivityHistory"), content: }, { id: "documents", title: t("workspaceDocuments"), content: }, { id: "communication", title: t("workspaceCommunication"), content: }, From f8fc8d6976e4ca7b12864177d2d21659b13baee6 Mon Sep 17 00:00:00 2001 From: cesnimda Date: Mon, 31 Aug 2026 22:29:45 +0200 Subject: [PATCH 4/9] test(capture): validate extension in CI --- .gitea/workflows/ci-deploy.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitea/workflows/ci-deploy.yml b/.gitea/workflows/ci-deploy.yml index 514bd909..9030f7f1 100644 --- a/.gitea/workflows/ci-deploy.yml +++ b/.gitea/workflows/ci-deploy.yml @@ -62,6 +62,9 @@ jobs: python3 scripts/test-ollama-evaluation.py python3 scripts/test-supply-chain.py + - name: Test browser extension + run: node --test browser-extension/tests/*.test.mjs + - name: Scan tracked files and generate dependency SBOM run: | python3 scripts/supply-chain.py scan-secrets From c8b4c33acd9be086aa2587b682bb3b436624b662 Mon Sep 17 00:00:00 2001 From: cesnimda Date: Tue, 1 Sep 2026 08:54:03 +0200 Subject: [PATCH 5/9] fix(cv): restore distinct responsive templates --- JobTrackerApi.Tests/CvBuilderTests.cs | 17 +++++++ JobTrackerApi/Models/CvTheme.cs | 11 ++--- JobTrackerApi/Services/ThemedCvRenderer.cs | 5 ++- docs/architecture/cv-theme-engine.md | 6 ++- .../src/cv-builder-deep-link.test.tsx | 44 +++++++++++++++++++ job-tracker-ui/src/cvBuilder.test.ts | 39 +++++++++++++++- job-tracker-ui/src/cvBuilder.ts | 21 +++++++++ job-tracker-ui/src/views/CvBuilderEditor.tsx | 41 +++++++++++------ 8 files changed, 161 insertions(+), 23 deletions(-) diff --git a/JobTrackerApi.Tests/CvBuilderTests.cs b/JobTrackerApi.Tests/CvBuilderTests.cs index 7cb52739..387d36f4 100644 --- a/JobTrackerApi.Tests/CvBuilderTests.cs +++ b/JobTrackerApi.Tests/CvBuilderTests.cs @@ -211,6 +211,23 @@ public sealed class CvBuilderTests Assert.DoesNotContain("transform:scale", html); } + [Fact] + public void Ats_themes_keep_plain_text_content_but_use_distinct_structures_and_skill_treatments() + { + var atsThemes = CvThemeCatalog.Themes.Where(theme => theme.AtsFriendly).ToList(); + + Assert.All(atsThemes, theme => Assert.Contains(theme.Layout, new[] { "single", "header-band" })); + Assert.Contains(atsThemes, theme => theme.DefaultSkillsStyle == "text"); + Assert.Contains(atsThemes, theme => theme.DefaultSkillsStyle == "bullets"); + Assert.Contains(atsThemes, theme => theme.DefaultSkillsStyle == "tags"); + Assert.True(atsThemes.Select(theme => (theme.Layout, theme.HeaderStyle, theme.HeadingStyle, theme.NumberSections)).Distinct().Count() >= 5); + + var renderer = new ThemedCvRenderer(); + var model = CvVariantResolver.Build(Rich(), new CvVariantSettings(), "F", null); + Assert.Contains("class=\"skills-text\"", renderer.Render(model, CvThemeCatalog.Resolve("minimal"), new CvVariantSettings { ThemeId = "minimal" }).Html); + Assert.Contains("class=\"bullets skill-bullets\"", renderer.Render(model, CvThemeCatalog.Resolve("ats-classic"), new CvVariantSettings { ThemeId = "ats-classic" }).Html); + } + [Fact] public void Multi_entry_sections_flow_between_entries_instead_of_leaving_a_blank_page() { diff --git a/JobTrackerApi/Models/CvTheme.cs b/JobTrackerApi/Models/CvTheme.cs index 154b2726..ae6ab30e 100644 --- a/JobTrackerApi/Models/CvTheme.cs +++ b/JobTrackerApi/Models/CvTheme.cs @@ -53,6 +53,7 @@ public sealed class CvTheme public bool AtsFriendly { get; init; } public bool Premium { get; init; } public bool NumberSections { get; init; } + public string DefaultSkillsStyle { get; init; } = "tags"; // tags | text | bullets // Builder options this template intentionally exposes. The renderer remains generic; the // registry tells the editor which controls make sense for a selected template. @@ -86,7 +87,7 @@ public static class CvThemeCatalog Layout = "single", HeaderStyle = "plain", HeadingStyle = "plain", Accent = "#111827", HeadingColor = "#111827", Muted = "#6b7280", HeadingFont = "'Helvetica Neue', Arial, sans-serif", BodyFont = "'Helvetica Neue', Arial, sans-serif", - SectionGapMm = 7, EntryGapMm = 5, PhotoShape = "none", AtsFriendly = true, + SectionGapMm = 7, EntryGapMm = 5, PhotoShape = "none", AtsFriendly = true, DefaultSkillsStyle = "text", }, new() { @@ -95,7 +96,7 @@ public static class CvThemeCatalog Layout = "single", HeaderStyle = "centered", HeadingStyle = "underline", Accent = "#7c2d12", Ink = "#1c1917", Muted = "#57534e", Line = "#1c1917", HeadingFont = "Georgia, 'Times New Roman', serif", BodyFont = "Georgia, 'Times New Roman', serif", - NameSizePt = 27, PhotoShape = "square", AtsFriendly = true, + NameSizePt = 27, PhotoShape = "square", AtsFriendly = true, DefaultSkillsStyle = "text", }, new() { @@ -104,7 +105,7 @@ public static class CvThemeCatalog Layout = "sidebar-left", HeaderStyle = "band", HeadingStyle = "bar", Accent = "#0f4c5c", Ink = "#102a43", Muted = "#486581", SidebarBg = "#0f4c5c", SidebarInk = "#ffffff", HeadingFont = "'Roboto', Arial, sans-serif", BodyFont = "'Roboto', Arial, sans-serif", - BodySizePt = 9.5, LineHeight = 1.36, DefaultIcons = true, + BodySizePt = 9.5, LineHeight = 1.36, DefaultIcons = true, DefaultSkillsStyle = "bullets", SidebarSections = new() { "contact", "skills", "languages", "certifications" }, }, new() @@ -114,7 +115,7 @@ public static class CvThemeCatalog Layout = "single", HeaderStyle = "plain", HeadingStyle = "caps-rule", Accent = "#334155", Ink = "#111827", Muted = "#374151", HeadingFont = "Arial, Helvetica, sans-serif", BodyFont = "Arial, Helvetica, sans-serif", - PhotoShape = "none", AtsFriendly = true, + PhotoShape = "none", AtsFriendly = true, DefaultSkillsStyle = "bullets", }, new() { @@ -153,7 +154,7 @@ public static class CvThemeCatalog HeadingFont = "'Segoe UI', Roboto, Arial, sans-serif", BodyFont = "'Segoe UI', Roboto, Arial, sans-serif", UtilityFont = "Consolas, 'Courier New', monospace", NameSizePt = 25.5, HeadingSizePt = 9.5, BodySizePt = 9.4, LineHeight = 1.43, PageMarginMm = 15.24, SectionGapMm = 5.6, EntryGapMm = 4.3, - PhotoShape = "none", DefaultIcons = false, AtsFriendly = true, NumberSections = true, + PhotoShape = "none", DefaultIcons = false, AtsFriendly = true, NumberSections = true, DefaultSkillsStyle = "bullets", SupportedSettings = new() { "accent", "typography", "spacing", "skills", "page" }, }, }; diff --git a/JobTrackerApi/Services/ThemedCvRenderer.cs b/JobTrackerApi/Services/ThemedCvRenderer.cs index 591a80b7..6acbc14c 100644 --- a/JobTrackerApi/Services/ThemedCvRenderer.cs +++ b/JobTrackerApi/Services/ThemedCvRenderer.cs @@ -130,13 +130,14 @@ public sealed class ThemedCvRenderer : IThemedCvRenderer private static string RenderSection(CvRenderSection section, CvTheme theme, CvVariantSettings? settings = null) { if (section.IsEmpty) return string.Empty; + var skillsStyle = settings?.SkillsStyle ?? theme.DefaultSkillsStyle; var inner = section.Kind switch { "bullets" => $@"
    {Items(section.Bullets)}
", "paragraphs" => $@"
{string.Join("", section.Bullets.Select(item => $@"

{Inline(item)}

"))}
", "skill-groups" => $@"
{string.Join("", section.SkillGroups.Select(RenderSkillGroup))}
", - "tags" when section.Key == "skills" && settings?.SkillsStyle == "bullets" => $@"
    {Items(section.Tags)}
", - "tags" when section.Key == "skills" && settings?.SkillsStyle == "text" => $@"

{string.Join(" · ", section.Tags.Select(Enc))}

", + "tags" when section.Key == "skills" && skillsStyle == "bullets" => $@"
    {Items(section.Tags)}
", + "tags" when section.Key == "skills" && skillsStyle == "text" => $@"

{string.Join(" · ", section.Tags.Select(Enc))}

", "tags" => $@"
    {string.Join("", section.Tags.Select(t => $@"
  • {Enc(t)}
  • "))}
", _ => string.Join("", section.Entries.Select(RenderEntry)), }; diff --git a/docs/architecture/cv-theme-engine.md b/docs/architecture/cv-theme-engine.md index 7965acba..4aa4feb1 100644 --- a/docs/architecture/cv-theme-engine.md +++ b/docs/architecture/cv-theme-engine.md @@ -22,14 +22,16 @@ which is retained only for the legacy tailored-draft flow and is not used by the | Palette | `Accent`, `Ink`, `Muted`, `Line`, `Paper`, `SidebarBg`, `SidebarInk`, `HeadingColor` | | Typography | `HeadingFont`, `BodyFont`, `UtilityFont`, `NameSizePt`, `HeadingSizePt`, `BodySizePt`, `LineHeight` | | Spacing | `PageMarginMm`, `SectionGapMm`, `EntryGapMm` | -| Styling | `HeaderStyle` (`plain`\|`band`\|`centered`\|`kicker`), `HeadingStyle` (`caps-rule`\|`underline`\|`plain`\|`bar`), `PhotoShape` (`none`\|`square`\|`rounded`\|`circle`), `DefaultIcons`, `NumberSections` | +| Styling | `HeaderStyle` (`plain`\|`band`\|`centered`\|`kicker`), `HeadingStyle` (`caps-rule`\|`underline`\|`plain`\|`bar`), `DefaultSkillsStyle` (`tags`\|`text`\|`bullets`), `PhotoShape` (`none`\|`square`\|`rounded`\|`circle`), `DefaultIcons`, `NumberSections` | | Capabilities | `SupportedSettings` controls which editor panels the template exposes | The renderer computes CSS from these plus normalized variant overrides: printable palette, curated fonts, body/heading size, line height, spacing, page size, layout, sidebar width/content, header and heading treatments, skills presentation, photo and icons. `SidebarSections` decides which section keys move to the sidebar for the two-column layouts. Changing a template or override never transforms -the structured career content. +the structured career content. Selecting a different template clears previous structural overrides +(`Layout`, header/heading treatment and sidebar geometry) so its own design is immediately visible; +content and deliberate colour/typography/spacing choices remain untouched. ## Adding a theme diff --git a/job-tracker-ui/src/cv-builder-deep-link.test.tsx b/job-tracker-ui/src/cv-builder-deep-link.test.tsx index 2bfe4b88..ce443e1a 100644 --- a/job-tracker-ui/src/cv-builder-deep-link.test.tsx +++ b/job-tracker-ui/src/cv-builder-deep-link.test.tsx @@ -172,6 +172,50 @@ test('professional editor starts with templates and combines design and layout c expect(screen.getByText('Check spelling and grammar')).toBeInTheDocument(); }); +test('choosing a template restores its own structure instead of inheriting the previous template layout', async () => { + const customizedVariant = { + ...variant, + settings: { + ...emptyCvVariantSettings(), + themeId: 'minimal', + layout: 'single', + headerStyle: 'plain', + headingStyle: 'plain', + sidebarWidthMm: 72, + sidebarSections: ['skills'], + accentColor: '#123456', + }, + }; + mockedApi.get.mockImplementation((url: string) => { + if (url === '/cv/variants/3') return Promise.resolve({ data: customizedVariant } as any); + if (url === '/cv/themes') return Promise.resolve({ data: [ + { id: 'minimal', name: 'Minimal', category: 'ATS', description: 'Quiet single column', layout: 'single', available: true, swatches: ['#111827', '#fff', '#fff'] }, + { id: 'technical', name: 'Technical', category: 'Technical', description: 'Structured sidebar', layout: 'sidebar-left', available: true, swatches: ['#0f4c5c', '#0f4c5c', '#fff'] }, + ] } as any); + if (url === '/cv/outline') return Promise.resolve({ data: { sections: [] } } as any); + if (url.startsWith('/cv/themes/')) return Promise.resolve({ data: { themeId: url.includes('technical') ? 'technical' : 'minimal', html: '

preview

', suggestedFileName: 'preview.pdf' } } as any); + return Promise.resolve({ data: [] } as any); + }); + mockedApi.put.mockResolvedValue({ data: customizedVariant } as any); + renderAt(3); + + await screen.findByDisplayValue('Backend CV'); + fireEvent.click(screen.getByRole('button', { name: /Technical/ })); + fireEvent.click(screen.getByRole('button', { name: 'Save now' })); + + await waitFor(() => expect(mockedApi.put).toHaveBeenCalledWith('/cv/variants/3', expect.objectContaining({ + settings: expect.objectContaining({ + themeId: 'technical', + layout: null, + headerStyle: null, + headingStyle: null, + sidebarWidthMm: null, + sidebarSections: null, + accentColor: '#123456', + }), + }))); +}); + test('editor sections, design controls and document settings render in Bokmål', async () => { window.localStorage.setItem('uiLanguage', 'nb'); routeGet(() => Promise.resolve({ data: variant } as any)); diff --git a/job-tracker-ui/src/cvBuilder.test.ts b/job-tracker-ui/src/cvBuilder.test.ts index 5cb20be5..608b43b1 100644 --- a/job-tracker-ui/src/cvBuilder.test.ts +++ b/job-tracker-ui/src/cvBuilder.test.ts @@ -1,4 +1,4 @@ -import { getCvPageCount, getCvPageMetrics, moveItem, normalizeCvLanguage, wrapSelection } from "./cvBuilder"; +import { applyCvTheme, getCvPageCount, getCvPageMetrics, getCvPreviewFitZoom, moveItem, normalizeCvLanguage, wrapSelection } from "./cvBuilder"; describe("moveItem", () => { test("moves an item forward", () => { @@ -59,4 +59,41 @@ describe("CV language compatibility", () => { expect(normalizeCvLanguage("nb-NO")).toBe("nb-NO"); expect(normalizeCvLanguage("en")).toBe("en"); }); + + test("fits the physical page to the available preview width", () => { + expect(getCvPreviewFitZoom(500, 800)).toBeCloseTo(0.595); + expect(getCvPreviewFitZoom(1200, 800)).toBe(1); + expect(getCvPreviewFitZoom(120, 800)).toBe(0.32); + }); +}); + +describe("CV template selection", () => { + test("restores the selected template structure without discarding user content or design choices", () => { + const settings = { + themeId: "minimal", + layout: "single" as const, + headerStyle: "plain" as const, + headingStyle: "plain" as const, + sidebarWidthMm: 70, + sidebarSections: ["skills"], + accentColor: "#123456", + showPhoto: false, + showPageNumbers: false, + showIcons: true, + sections: [{ key: "experience", title: "Career" }], + overrides: {}, + customSections: [], + }; + + expect(applyCvTheme(settings, "technical")).toMatchObject({ + themeId: "technical", + layout: null, + headerStyle: null, + headingStyle: null, + sidebarWidthMm: null, + sidebarSections: null, + accentColor: "#123456", + sections: [{ key: "experience", title: "Career" }], + }); + }); }); diff --git a/job-tracker-ui/src/cvBuilder.ts b/job-tracker-ui/src/cvBuilder.ts index 8930b400..2b3f6fab 100644 --- a/job-tracker-ui/src/cvBuilder.ts +++ b/job-tracker-ui/src/cvBuilder.ts @@ -176,6 +176,27 @@ export function getCvPageCount(contentHeightPx: number, pageHeightPx: number): n return Math.max(1, Math.ceil(Math.max(0, contentHeightPx - 2) / pageHeightPx)); } +export function getCvPreviewFitZoom(containerWidthPx: number, pageWidthPx: number, gutterPx = 24, minZoom = 0.32): number { + if (!Number.isFinite(containerWidthPx) || !Number.isFinite(pageWidthPx) || pageWidthPx <= 0) return minZoom; + const usableWidth = Math.max(1, containerWidthPx - gutterPx); + return Math.min(1, Math.max(minZoom, usableWidth / pageWidthPx)); +} + +// Selecting a template is a structural choice. Clear only the presentation overrides that can +// flatten every template into the previous template's layout; keep content, colour, typography, +// spacing and document settings intact. +export function applyCvTheme(settings: CvVariantSettings, themeId: string): CvVariantSettings { + return { + ...settings, + themeId, + layout: null, + headerStyle: null, + headingStyle: null, + sidebarWidthMm: null, + sidebarSections: null, + }; +} + export function normalizeCvLanguage(language?: string | null): string { const normalized = language?.trim().toLowerCase(); return normalized === "no" || normalized === "nb" || normalized === "nb-no" ? "nb-NO" : normalized || "en"; diff --git a/job-tracker-ui/src/views/CvBuilderEditor.tsx b/job-tracker-ui/src/views/CvBuilderEditor.tsx index 418c79f1..a18f06aa 100644 --- a/job-tracker-ui/src/views/CvBuilderEditor.tsx +++ b/job-tracker-ui/src/views/CvBuilderEditor.tsx @@ -37,7 +37,7 @@ import { useDragReorder } from "../hooks/useDragReorder"; import { CUSTOM_SECTION_PRESETS, CvCustomSectionSetting, CvItemOverride, CvOutline, CvOutlineSection, CvSectionSetting, CvTheme, CvVariant, CvVariantSettings, CvVariantVersionInfo, DEFAULT_SECTION_ORDER, SECTION_LABELS, - cvBuilderApi, getCvPageCount, getCvPageMetrics, moveItem, normalizeCvLanguage, + applyCvTheme, cvBuilderApi, getCvPageCount, getCvPageMetrics, getCvPreviewFitZoom, moveItem, normalizeCvLanguage, } from "../cvBuilder"; import { useDialogActions } from "../dialogs"; import { useI18n } from "../i18n/I18nProvider"; @@ -84,6 +84,7 @@ export default function CvBuilderEditor() { const [tab, setTab] = useState(0); const [html, setHtml] = useState(""); const [zoom, setZoom] = useState(0.62); + const [autoFitPreview, setAutoFitPreview] = useState(true); const [previewing, setPreviewing] = useState(false); const [previewError, setPreviewError] = useState(false); const [previewRevision, setPreviewRevision] = useState(0); @@ -409,10 +410,24 @@ export default function CvBuilderEditor() { if (target && scrollRef.current) scrollRef.current.scrollTo({ top: Math.max(0, target.offsetTop - 12), behavior: "smooth" }); }; - const fitPreview = () => { - const availableWidth = Math.max(1, (scrollRef.current?.clientWidth ?? pageMetrics.widthPx) - 24); - setZoom(Math.min(1, Math.max(MIN_PREVIEW_ZOOM, availableWidth / pageMetrics.widthPx))); - }; + const fitPreview = useCallback(() => { + setZoom(getCvPreviewFitZoom(scrollRef.current?.clientWidth ?? pageMetrics.widthPx, pageMetrics.widthPx, 24, MIN_PREVIEW_ZOOM)); + }, [pageMetrics.widthPx]); + + useEffect(() => { + if (!autoFitPreview) return; + const container = scrollRef.current; + if (!container) return; + const resize = () => fitPreview(); + resize(); + window.addEventListener("resize", resize); + const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(resize); + observer?.observe(container); + return () => { + window.removeEventListener("resize", resize); + observer?.disconnect(); + }; + }, [autoFitPreview, compactEditor, fitPreview, mobilePane]); if (loadError) { return ( @@ -486,11 +501,11 @@ export default function CvBuilderEditor() { - setZoom((z) => Math.max(MIN_PREVIEW_ZOOM, +(z - 0.1).toFixed(2)))}> - setZoom(v as number)} sx={{ width: 90 }} aria-label={t("cvEditorZoom")} /> - setZoom((z) => Math.min(1, +(z + 0.1).toFixed(2)))}> + { setAutoFitPreview(false); setZoom((z) => Math.max(MIN_PREVIEW_ZOOM, +(z - 0.1).toFixed(2))); }}> + { setAutoFitPreview(false); setZoom(v as number); }} sx={{ width: 90 }} aria-label={t("cvEditorZoom")} /> + { setAutoFitPreview(false); setZoom((z) => Math.min(1, +(z + 0.1).toFixed(2))); }}> {Math.round(zoom * 100)}% - + {previewOverflow && {t("cvEditorOverflowWarning")}} {pages >= 3 && {t("cvEditorLongDocument", { pages })}} @@ -1137,16 +1152,16 @@ function CustomizeTab({ mode, settings, update, themes }: { {mode === "template" && {t("cvEditorTheme")} {t("cvEditorThemeHelp")} - + {themes.map((theme) => { const active = theme.id === settings.themeId; const locked = theme.available === false; return ( { if (!locked) update({ themeId: theme.id }); }} - onKeyDown={(e) => { if (!locked && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); update({ themeId: theme.id }); } }} + onClick={() => { if (!locked) update(applyCvTheme(settings, theme.id)); }} + onKeyDown={(e) => { if (!locked && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); update(applyCvTheme(settings, theme.id)); } }} sx={{ p: 1, cursor: locked ? "not-allowed" : "pointer", opacity: locked ? 0.6 : 1, outline: "none", borderColor: active ? "primary.main" : undefined, borderWidth: active ? 2 : 1, "&:focus-visible": { boxShadow: 3 } }}> - + {theme.name} {theme.category} {theme.description} From 694fdb870ab1fddcd06212b0e80686eeb4b710ef Mon Sep 17 00:00:00 2001 From: cesnimda Date: Tue, 1 Sep 2026 09:08:16 +0200 Subject: [PATCH 6/9] feat(cv): prioritize ATS template choices --- docs/architecture/cv-theme-engine.md | 7 ++- docs/work-programmes/master-progress.md | 7 ++- .../src/components/CvTemplateGallery.tsx | 56 +++++++++++++++++++ .../src/cv-builder-deep-link.test.tsx | 1 + job-tracker-ui/src/cvBuilder.test.ts | 12 +++- job-tracker-ui/src/cvBuilder.ts | 6 ++ job-tracker-ui/src/i18n/translations.ts | 8 +++ job-tracker-ui/src/views/CvBuilderEditor.tsx | 24 +------- job-tracker-ui/src/views/CvBuilderPage.tsx | 5 +- 9 files changed, 95 insertions(+), 31 deletions(-) create mode 100644 job-tracker-ui/src/components/CvTemplateGallery.tsx diff --git a/docs/architecture/cv-theme-engine.md b/docs/architecture/cv-theme-engine.md index 4aa4feb1..a090ba63 100644 --- a/docs/architecture/cv-theme-engine.md +++ b/docs/architecture/cv-theme-engine.md @@ -39,7 +39,8 @@ content and deliberate colour/typography/spacing choices remain untouched. fields that differ from the defaults and declare its `SupportedSettings` when the defaults do not apply. 2. Nothing else is wired manually. It appears in `GET /api/cv/themes`, the Template tab and dashboard create flow. `GET /api/cv/themes/{id}/preview` renders isolated in-memory sample data for a real visual thumbnail; - preview data is never persisted. + preview data is never persisted. The shared template gallery is ATS-first by default, can reveal + every design, and is reused by both the creation flow and editor. 3. Add a focused visual/PDF regression only when the template introduces a genuinely new layout behaviour. Add a `CvBuilderTests.Every_catalog_theme_renders_valid_html` already loops the whole catalog, so a new @@ -58,8 +59,8 @@ sections and monospaced utility details). `[text](url)` via `ThemedCvRenderer.Inline` — everything is HTML-escaped first, then a whitelist is re-applied, so no user tag survives. Storage stays plain text (no HTML, no sanitiser dependency). - **ATS-friendliness** is a data flag: `CvTheme.AtsFriendly` (set on the single-column themes), - surfaced in `GET /api/cv/themes` and badged in the Customize tab. Two-column (sidebar) themes are not - flagged, as sidebar layouts can trip naive resume parsers. + surfaced in `GET /api/cv/themes`, sorted first and badged in both template choosers. Two-column + (sidebar) themes are not flagged, as sidebar layouts can trip naive resume parsers. - **Print quality**: ordinary entries use `break-inside: avoid-page`; content classified as too tall for a page is allowed to flow between bullets/paragraphs so Chromium cannot clip an unsplittable block. Section headings avoid a following break, list items carry widow/orphan rules, and long diff --git a/docs/work-programmes/master-progress.md b/docs/work-programmes/master-progress.md index fbecc130..f0b11ca1 100644 --- a/docs/work-programmes/master-progress.md +++ b/docs/work-programmes/master-progress.md @@ -1,11 +1,13 @@ # JobTracker master programme progress -Updated: 2026-08-31 +Updated: 2026-09-01 ## 2026-08-29 audit implementation programme ### Completed +- Restored visibly distinct CV templates by clearing stale structural overrides when a template changes while preserving CV content and deliberate colour, typography, spacing and document settings. The live A4/Letter preview now fits its pane automatically and responds to pane and viewport resizing; manual zoom remains available. +- Consolidated both template choosers into one ATS-first gallery backed by real rendered sample documents. ATS-safe designs are prioritised and explained, decorative sidebar layouts are not falsely labelled ATS-friendly, existing non-ATS selections remain visible, and all designs remain one click away. - Diagnosed Gitea Actions run 696 from its authenticated job log: application tests passed, but repeated truncated npm/Playwright downloads were followed by a native exit 139 before browser assertions ran. CI now invokes the lockfile-installed Playwright CLI directly, extends the bounded download timeout, retries only SIGSEGV, and does not redownload the same dependency tree after a transient runner crash. - Removed the unreachable legacy `JobDetailsDialog`, its duplicate insight tabs/panels, and tests coupled only to that retired surface. Live correspondence and routed-workspace contracts retain focused coverage; the cleanup removed 2,239 lines without changing the active Job Workspace. - Began the controller-responsibility split by moving job statistics, monthly analytics, tag counts, overview analytics, and tag trends into one dedicated authenticated analytics controller. Existing `api/jobapplications/*` routes and response contracts are unchanged; the shared tag parser replaces a byte-for-byte duplicate local parser. @@ -73,11 +75,12 @@ Updated: 2026-08-31 ### In progress -- Complete the career evidence bank regression gate, then continue the prioritized product-value roadmap with saved job searches. SEC-006/SEC-007 still await a running Linux Docker daemon for image/runtime proof; production activation remains separately gated. +- Verify the already-authorised main-branch production deployment and health probes, then continue the next safe backlog package. The newer saved-search/calendar/browser-extension/CV-template feature branch remains separately gated from production. ### Remaining - Finish production deployment/health verification and revalidate the production-only blockers. +- Obtain explicit production approval before merging and deploying the newer scheduled-search, calendar, browser-extension and CV-template feature branch. - Continue visual hierarchy/responsive polish only when a concrete browser regression or reviewed design target identifies a remaining defect; the current automated desktop/mobile journeys pass. - Continue maintainability packages, accessibility automation, mobile regression coverage, and the prioritized product-value roadmap after the foundations are stable. diff --git a/job-tracker-ui/src/components/CvTemplateGallery.tsx b/job-tracker-ui/src/components/CvTemplateGallery.tsx new file mode 100644 index 00000000..20d7bd05 --- /dev/null +++ b/job-tracker-ui/src/components/CvTemplateGallery.tsx @@ -0,0 +1,56 @@ +import React, { useMemo, useState } from "react"; +import CheckCircleIcon from "@mui/icons-material/CheckCircle"; +import { Box, Button, Chip, Paper, Stack, Typography } from "@mui/material"; + +import { CvTheme, getVisibleCvThemes } from "../cvBuilder"; +import { useI18n } from "../i18n/I18nProvider"; +import CvTemplateThumbnail from "./CvTemplateThumbnail"; + +type Props = { + themes: CvTheme[]; + selectedId: string; + onSelect: (theme: CvTheme) => void; + previewHeight?: number; + showDescriptions?: boolean; +}; + +export default function CvTemplateGallery({ themes, selectedId, onSelect, previewHeight = 170, showDescriptions = true }: Props) { + const { t } = useI18n(); + const [atsOnly, setAtsOnly] = useState(true); + const visibleThemes = useMemo(() => getVisibleCvThemes(themes, atsOnly, selectedId), [atsOnly, selectedId, themes]); + + return ( + + + + + {atsOnly && {t("cvEditorAtsTemplateHelp")}} + + + {visibleThemes.map((theme) => { + const active = theme.id === selectedId; + const locked = theme.available === false; + return ( + { if (!locked) onSelect(theme); }} + onKeyDown={(event) => { if (!locked && (event.key === "Enter" || event.key === " ")) { event.preventDefault(); onSelect(theme); } }} + sx={{ p: 1, cursor: locked ? "not-allowed" : "pointer", opacity: locked ? 0.6 : 1, outline: "none", position: "relative", borderColor: active ? "primary.main" : "divider", borderWidth: active ? 2 : 1, transition: "border-color 120ms ease, transform 120ms ease", "&:hover": locked ? undefined : { borderColor: "primary.main", transform: "translateY(-1px)" }, "&:focus-visible": { outline: "3px solid", outlineColor: "primary.main", outlineOffset: 2 } }}> + {active && } + + {theme.name} + {theme.category} + {showDescriptions && {theme.description}} + + {theme.atsFriendly && } + {theme.requiresPro && } + + {theme.swatches.slice(0, 3).map((colour, index) => )} + + + + ); + })} + + + ); +} diff --git a/job-tracker-ui/src/cv-builder-deep-link.test.tsx b/job-tracker-ui/src/cv-builder-deep-link.test.tsx index ce443e1a..aa6b9548 100644 --- a/job-tracker-ui/src/cv-builder-deep-link.test.tsx +++ b/job-tracker-ui/src/cv-builder-deep-link.test.tsx @@ -200,6 +200,7 @@ test('choosing a template restores its own structure instead of inheriting the p renderAt(3); await screen.findByDisplayValue('Backend CV'); + fireEvent.click(screen.getByRole('button', { name: 'All templates' })); fireEvent.click(screen.getByRole('button', { name: /Technical/ })); fireEvent.click(screen.getByRole('button', { name: 'Save now' })); diff --git a/job-tracker-ui/src/cvBuilder.test.ts b/job-tracker-ui/src/cvBuilder.test.ts index 608b43b1..908e377d 100644 --- a/job-tracker-ui/src/cvBuilder.test.ts +++ b/job-tracker-ui/src/cvBuilder.test.ts @@ -1,4 +1,4 @@ -import { applyCvTheme, getCvPageCount, getCvPageMetrics, getCvPreviewFitZoom, moveItem, normalizeCvLanguage, wrapSelection } from "./cvBuilder"; +import { applyCvTheme, getCvPageCount, getCvPageMetrics, getCvPreviewFitZoom, getVisibleCvThemes, moveItem, normalizeCvLanguage, wrapSelection } from "./cvBuilder"; describe("moveItem", () => { test("moves an item forward", () => { @@ -96,4 +96,14 @@ describe("CV template selection", () => { sections: [{ key: "experience", title: "Career" }], }); }); + + test("shows ATS templates first and keeps an active non-ATS template visible", () => { + const themes = [ + { id: "creative", atsFriendly: false }, + { id: "classic", atsFriendly: true }, + { id: "minimal", atsFriendly: true }, + ] as never[]; + expect(getVisibleCvThemes(themes, true, "creative").map((theme) => theme.id)).toEqual(["classic", "minimal", "creative"]); + expect(getVisibleCvThemes(themes, true).map((theme) => theme.id)).toEqual(["classic", "minimal"]); + }); }); diff --git a/job-tracker-ui/src/cvBuilder.ts b/job-tracker-ui/src/cvBuilder.ts index 2b3f6fab..2209ac33 100644 --- a/job-tracker-ui/src/cvBuilder.ts +++ b/job-tracker-ui/src/cvBuilder.ts @@ -197,6 +197,12 @@ export function applyCvTheme(settings: CvVariantSettings, themeId: string): CvVa }; } +export function getVisibleCvThemes(themes: CvTheme[], atsOnly: boolean, selectedId?: string): CvTheme[] { + return themes + .filter((theme) => !atsOnly || theme.atsFriendly || theme.id === selectedId) + .sort((left, right) => Number(right.atsFriendly) - Number(left.atsFriendly)); +} + export function normalizeCvLanguage(language?: string | null): string { const normalized = language?.trim().toLowerCase(); return normalized === "no" || normalized === "nb" || normalized === "nb-no" ? "nb-NO" : normalized || "en"; diff --git a/job-tracker-ui/src/i18n/translations.ts b/job-tracker-ui/src/i18n/translations.ts index 2bf45566..dd6f27b5 100644 --- a/job-tracker-ui/src/i18n/translations.ts +++ b/job-tracker-ui/src/i18n/translations.ts @@ -626,6 +626,10 @@ export const translations = { cvEditorTheme: "Theme", cvEditorThemeHelp: "Templates change presentation only. Your content and hidden-section choices stay intact.", cvEditorAtsFriendly: "ATS-friendly", + cvEditorAtsTemplates: "ATS templates", + cvEditorAllTemplates: "All templates", + cvEditorAtsTemplateHelp: "Recommended for reliable parsing and a clear reading order.", + cvEditorSelectedTemplate: "Selected template", cvEditorPro: "Pro", cvEditorProUnlocked: "Pro unlocked", cvEditorColour: "Colour", @@ -3042,6 +3046,10 @@ export const translations = { cvEditorTheme: "Tema", cvEditorThemeHelp: "Maler endrer bare presentasjonen. Innholdet og valgene for skjulte seksjoner beholdes.", cvEditorAtsFriendly: "ATS-vennlig", + cvEditorAtsTemplates: "ATS-maler", + cvEditorAllTemplates: "Alle maler", + cvEditorAtsTemplateHelp: "Anbefalt for pålitelig tolking og tydelig leserekkefølge.", + cvEditorSelectedTemplate: "Valgt mal", cvEditorPro: "Pro", cvEditorProUnlocked: "Pro låst opp", cvEditorColour: "Farge", diff --git a/job-tracker-ui/src/views/CvBuilderEditor.tsx b/job-tracker-ui/src/views/CvBuilderEditor.tsx index a18f06aa..db894dcb 100644 --- a/job-tracker-ui/src/views/CvBuilderEditor.tsx +++ b/job-tracker-ui/src/views/CvBuilderEditor.tsx @@ -32,7 +32,7 @@ import { useAccountPlan } from "../accountPlan"; import RichTextField from "../components/RichTextField"; import AiSectionAssistant from "../components/cv/AiSectionAssistant"; import ProFeatureNotice from "../components/ProFeatureNotice"; -import CvTemplateThumbnail from "../components/CvTemplateThumbnail"; +import CvTemplateGallery from "../components/CvTemplateGallery"; import { useDragReorder } from "../hooks/useDragReorder"; import { CUSTOM_SECTION_PRESETS, CvCustomSectionSetting, CvItemOverride, CvOutline, CvOutlineSection, CvSectionSetting, @@ -1152,27 +1152,7 @@ function CustomizeTab({ mode, settings, update, themes }: { {mode === "template" && {t("cvEditorTheme")} {t("cvEditorThemeHelp")} - - {themes.map((theme) => { - const active = theme.id === settings.themeId; - const locked = theme.available === false; - return ( - { if (!locked) update(applyCvTheme(settings, theme.id)); }} - onKeyDown={(e) => { if (!locked && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); update(applyCvTheme(settings, theme.id)); } }} - sx={{ p: 1, cursor: locked ? "not-allowed" : "pointer", opacity: locked ? 0.6 : 1, outline: "none", borderColor: active ? "primary.main" : undefined, borderWidth: active ? 2 : 1, "&:focus-visible": { boxShadow: 3 } }}> - - {theme.name} - {theme.category} - {theme.description} - - {theme.atsFriendly && } - {theme.requiresPro && } - - - ); - })} - + update(applyCvTheme(settings, theme.id))} /> } {mode === "customize" && <> diff --git a/job-tracker-ui/src/views/CvBuilderPage.tsx b/job-tracker-ui/src/views/CvBuilderPage.tsx index 1e93bf41..1d00a6fd 100644 --- a/job-tracker-ui/src/views/CvBuilderPage.tsx +++ b/job-tracker-ui/src/views/CvBuilderPage.tsx @@ -13,6 +13,7 @@ import { api, getApiErrorMessage } from "../api"; import { useToast } from "../toast"; import { CvTheme, CvVariantSummary, cvBuilderApi, emptyCvVariantSettings } from "../cvBuilder"; import { useDialogActions } from "../dialogs"; +import CvTemplateGallery from "../components/CvTemplateGallery"; import CvTemplateThumbnail from "../components/CvTemplateThumbnail"; import { useI18n } from "../i18n/I18nProvider"; @@ -189,9 +190,7 @@ export default function CvBuilderPage() { {t("cvDashboardCreateHelp")} setNewName(event.target.value)} error={!newName.trim()} helperText={!newName.trim() ? t("cvDashboardEnterName") : t("cvDashboardNameExample")} sx={{ mb: 2 }} /> {t("cvDashboardChooseTemplate")} - - {(themes.length ? themes.filter((theme) => theme.available) : [{ id: "modern", name: "Modern", category: "Professional", layout: "header-band", swatches: ["#3157d5", "#eef1f4", "#fff"] } as CvTheme]).map((theme) => setNewTheme(theme.id)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); setNewTheme(theme.id); } }} variant="outlined" sx={{ p: 0.75, cursor: "pointer", borderWidth: newTheme === theme.id ? 2 : 1, borderColor: newTheme === theme.id ? "primary.main" : "divider", "&:focus-visible": { outline: "3px solid", outlineColor: "primary.main" } }}>{theme.name}{theme.category})} - + theme.available) : [{ id: "modern", name: "Modern", category: "Professional", description: "", layout: "header-band", accent: "#3157d5", photoShape: "none", supportsIcons: false, atsFriendly: true, requiresPro: false, available: true, swatches: ["#3157d5", "#eef1f4", "#fff"] }]} selectedId={newTheme} onSelect={(theme) => setNewTheme(theme.id)} previewHeight={125} showDescriptions={false} /> From 6b8c560d6338ef58ff162bbd21378a93b709ee11 Mon Sep 17 00:00:00 2001 From: cesnimda Date: Tue, 1 Sep 2026 09:15:07 +0200 Subject: [PATCH 7/9] chore(deploy): quiet optional compose variables --- docker-compose.yml | 6 +++--- docs/work-programmes/master-progress.md | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 7b8bca69..63ea1ec1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -38,7 +38,7 @@ services: # Optional: allow Google / Microsoft ID-token bearer auth (sign-in, not mail access) - Auth__GoogleClientId=${AUTH_GOOGLE_CLIENT_ID} - Auth__MicrosoftClientId=${AUTH_MICROSOFT_CLIENT_ID} - - Auth__MicrosoftTenant=${AUTH_MICROSOFT_TENANT} + - Auth__MicrosoftTenant=${AUTH_MICROSOFT_TENANT:-} - Google__GmailClientSecret=${GOOGLE_GMAIL_CLIENT_SECRET} # Optional: Outlook / Microsoft 365 mail linking via Microsoft Graph - Microsoft__ClientId=${MICROSOFT_CLIENT_ID} @@ -124,9 +124,9 @@ services: args: - NEXT_PUBLIC_GOOGLE_CLIENT_ID=${AUTH_GOOGLE_CLIENT_ID} - NEXT_PUBLIC_MICROSOFT_CLIENT_ID=${AUTH_MICROSOFT_CLIENT_ID} - - NEXT_PUBLIC_MICROSOFT_TENANT=${AUTH_MICROSOFT_TENANT} + - NEXT_PUBLIC_MICROSOFT_TENANT=${AUTH_MICROSOFT_TENANT:-} # Optional override; default in production is `/api` - - NEXT_PUBLIC_API_BASE_URL=${NEXT_PUBLIC_API_BASE_URL} + - NEXT_PUBLIC_API_BASE_URL=${NEXT_PUBLIC_API_BASE_URL:-} expose: - "80" # Compatibility ingress for the current production reverse proxy, which diff --git a/docs/work-programmes/master-progress.md b/docs/work-programmes/master-progress.md index f0b11ca1..80eb0fb5 100644 --- a/docs/work-programmes/master-progress.md +++ b/docs/work-programmes/master-progress.md @@ -8,6 +8,7 @@ Updated: 2026-09-01 - Restored visibly distinct CV templates by clearing stale structural overrides when a template changes while preserving CV content and deliberate colour, typography, spacing and document settings. The live A4/Letter preview now fits its pane automatically and responds to pane and viewport resizing; manual zoom remains available. - Consolidated both template choosers into one ATS-first gallery backed by real rendered sample documents. ATS-safe designs are prioritised and explained, decorative sidebar layouts are not falsely labelled ATS-friendly, existing non-ATS selections remain visible, and all designs remain one click away. +- Removed Docker Compose warnings for deliberately optional Microsoft-tenant and production-relative frontend API variables; missing required provider configuration remains enforced by deployment preflight. - Diagnosed Gitea Actions run 696 from its authenticated job log: application tests passed, but repeated truncated npm/Playwright downloads were followed by a native exit 139 before browser assertions ran. CI now invokes the lockfile-installed Playwright CLI directly, extends the bounded download timeout, retries only SIGSEGV, and does not redownload the same dependency tree after a transient runner crash. - Removed the unreachable legacy `JobDetailsDialog`, its duplicate insight tabs/panels, and tests coupled only to that retired surface. Live correspondence and routed-workspace contracts retain focused coverage; the cleanup removed 2,239 lines without changing the active Job Workspace. - Began the controller-responsibility split by moving job statistics, monthly analytics, tag counts, overview analytics, and tag trends into one dedicated authenticated analytics controller. Existing `api/jobapplications/*` routes and response contracts are unchanged; the shared tag parser replaces a byte-for-byte duplicate local parser. @@ -75,11 +76,11 @@ Updated: 2026-09-01 ### In progress -- Verify the already-authorised main-branch production deployment and health probes, then continue the next safe backlog package. The newer saved-search/calendar/browser-extension/CV-template feature branch remains separately gated from production. +- Continue the next safe maintainability and UX backlog package. The newer saved-search/calendar/browser-extension/CV-template feature branch remains separately gated from production. ### Remaining -- Finish production deployment/health verification and revalidate the production-only blockers. +- Revalidate the remaining production-only blockers; the authorised main-branch deployment completed successfully as version 286 with public liveness and database-readiness checks passing. - Obtain explicit production approval before merging and deploying the newer scheduled-search, calendar, browser-extension and CV-template feature branch. - Continue visual hierarchy/responsive polish only when a concrete browser regression or reviewed design target identifies a remaining defect; the current automated desktop/mobile journeys pass. - Continue maintainability packages, accessibility automation, mobile regression coverage, and the prioritized product-value roadmap after the foundations are stable. From 2a0672e1cdaa1e3744a4ab7ab2670a050ec904fe Mon Sep 17 00:00:00 2001 From: cesnimda Date: Tue, 1 Sep 2026 09:16:29 +0200 Subject: [PATCH 8/9] docs(ops): record successful production rollout --- BLOCKERS.md | 13 ++++++------- docs/work-programmes/master-progress.md | 4 ++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/BLOCKERS.md b/BLOCKERS.md index 11db887e..b85bc6c0 100644 --- a/BLOCKERS.md +++ b/BLOCKERS.md @@ -1,6 +1,6 @@ # Blockers -Updated: 2026-08-31 +Updated: 2026-09-01 ## Stripe billing @@ -19,14 +19,13 @@ Updated: 2026-08-31 - **Recommended:** Monitor Turnstile and rate-limit failures during the first public rollout; keep email verification required. - **Current status:** Production returns `allowRegistration=true`, `turnstileEnabled=true`, `googleEnabled=true`, and `microsoftEnabled=false`. A registration request without a Turnstile token is rejected with HTTP 400. SMTP is configured and enabled. The operator reports `AUTH_REQUIRE_EMAIL_VERIFICATION` is now enabled; the disposable interactive signup is still required to prove the deployed behavior end to end. -## Production verification and deployment +## Production verification -- **Blocked:** Authenticated production smoke tests, backup restore verification against real data, OAuth-provider checks, and deployment. -- **Why:** Read-only host access is available, but authenticated smoke, port/network closure, complete backup restore, provider checks and deployment require credentials and/or operator-authorized production mutations. -- **Required:** After the current pull request passes CI and is approved, follow `docs/release-candidate-review.md` and `docs/release-checklist.md` on the production host. Confirm the admin-only version badge matches the deployed commit, then run the authenticated application workspace, Career, CV, attachment, email-verification and rollback checks. +- **Blocked:** Authenticated production smoke tests, backup restore verification against real data, OAuth-provider checks, and rollback rehearsal. +- **Why:** The authorised deployment is complete, but authenticated smoke, port/network closure, complete backup restore, provider checks and failure-injection rollback require credentials and/or separately authorised production mutations. +- **Required:** Confirm the admin-only version badge matches version 286 / commit `ea7d9f3`, then run the authenticated application workspace, Career, CV, attachment, email-verification and rollback checks from `docs/release-candidate-review.md` and `docs/release-checklist.md`. - **Recommended:** Verify backup/restore before deployment, then exercise login, existing application counts, Career Workspace, public CV refresh/download, AI, and attachments in order. -- **Current access check:** Read-only SSH access is confirmed. All four JobTracker containers are healthy with zero observed restarts, but root free space is now 36 GiB (83% used). The production checkout is at `de937d25dc5e` / app version `157` and has an unreviewed mode-only change to `deploy/deploy.sh`. No production change or deployment was attempted. -- **Current status:** On 2026-08-31 the anonymous public liveness endpoint `https://jobs.cesnimda.uk/health` returned HTTP 200 with version `276`, and the Gitea host returned HTTP 200; the earlier public 502 is no longer present. Anonymous `https://jobs.cesnimda.uk/api/health` returned HTTP 401 as expected for an authenticated API route. This proves the proxy/frontend liveness path only, not authenticated application behavior or database readiness. Gitea run 696 failed after repeated truncated Playwright downloads and then a runner-level exit 139 before any test assertion; the workflow now installs through the lockfile CLI and retries only that transient process failure without hiding real test failures. Current remote CI, backup/restore, authenticated smoke and rollback still require operator-controlled environments. Read-only PROD-001 inventory found the JobTracker Ollama and frontend published on all host interfaces, the newest gzip-valid MariaDB backup dated 2026-08-02, no observed scheduled JobTracker backup, and no owner-file/key/tombstone recovery bundle. Close these rollout gates before deployment; see `docs/production/production-ai-hardware-assessment.md`. +- **Current status:** Gitea run 705 (application version 286, commit `ea7d9f3`) completed both the complete test job and remote deployment successfully on 2026-09-01. Public `/health`, `/ready`, and `/api/auth/config` returned HTTP 200 after replacement; liveness reported version 286 and readiness reported `ready`. This proves the proxy/frontend, API and database readiness path, but not authenticated application behavior, provider delivery or restore/rollback behavior. Read-only PROD-001 inventory previously found the JobTracker Ollama and frontend published on all host interfaces, the newest observed gzip-valid MariaDB backup dated 2026-08-02, no observed scheduled JobTracker backup, and no owner-file/key/tombstone recovery bundle. Those remaining gates still require operator-controlled verification; see `docs/production/production-ai-hardware-assessment.md`. - **Repository-side rollback status:** Core images are now tagged by commit, the prior running backend/frontend images are retained, and any failure after replacement triggers an automatic core rollback while preserving the failed CI status. Compose configuration validates locally. A real rollback rehearsal remains blocked because the local Linux Docker daemon is unavailable and production mutation is not authorised; run the failure-injection rehearsal on a disposable Linux Docker host before relying on it in production. ## Account deletion retention and restore policy diff --git a/docs/work-programmes/master-progress.md b/docs/work-programmes/master-progress.md index 80eb0fb5..7d1b6cc9 100644 --- a/docs/work-programmes/master-progress.md +++ b/docs/work-programmes/master-progress.md @@ -170,8 +170,8 @@ Updated: 2026-09-01 - **Immediate order:** all sixteen immediate repository items are complete locally, including the original UI/release queue plus SEC-009 cache/tombstone safety, worker restart clocks, universal AI accounting, email-token/Stripe lifecycle tests, exhaustive Job email selectors, the repaired migration chain, CV/public-edge hardening and measured admin/mail scaling. PROD-001 read-only evidence and the PROD-003 plan-only harness are also complete. The final audit is checking tooling/documentation before declaring only external blockers remain. - **Status counts:** 8 `VERIFIED LOCALLY`; 27 `IMPLEMENTED — NOT VERIFIED`; 0 `IN PROGRESS`; 0 `NOT STARTED`; 4 `BLOCKED`; 0 `DONE`; 0 `DEFERRED`. - **Test status:** backend 736/736; frontend 64/64 suites and 272/272 tests; ESLint and TypeScript zero findings; AI sidecar 37/37 without warnings; Ollama benchmark harness 5/5 plus safe dry-run; optimized production build; EF model parity; SQLite/MariaDB migration scripts; blank/idempotent/populated SQLite migration-chain tests; fresh complete-chain SQLite application startup; disposable earlier-chain MariaDB 11.8 application startup; Docker Compose config; safe-failure deployment preflight; and Playwright 10/10. Supply-chain controls pass 3/3, the tracked tree is clean, and the generated CycloneDX SBOM contains 964 components. npm audit remains at zero. The final ownership migrations have generated MariaDB SQL but still need a current MariaDB runtime rehearsal; the parser image and container scan are pending because Docker Desktop's daemon is offline. Jest's slow/open-handle behavior remains recorded. -- **Deployment status:** Gitea pull-request run 609 passed the complete CI job in 4m20s. Deploy was intentionally skipped because the workflow deploys only a `push` to `main`; live remains unchanged. No merge/deployment was performed directly, no production migrations were run and the AI operation worker remains disabled by default. -- **Production status:** State unchanged. Sanitized read-only SSH inventory was performed; no logs, prompts, private rows/content or secret values were read, and no provider/model call, model pull, service restart, file/config change, backup, restore, migration or deployment occurred. It confirmed all-interface Ollama/frontend listeners and stale database-only backups as rollout blockers. +- **Deployment status:** Gitea run 705 passed the complete test and deploy jobs. Production version 286 / commit `ea7d9f3` passed public frontend, API liveness, database readiness and auth-configuration smoke checks; the prior release stayed available until the health-checked replacement window. +- **Production status:** Public liveness and database readiness are verified for version 286. Authenticated journeys, provider delivery, complete backup/restore, failure-injection rollback, port closure and retention/tombstone behavior remain unverified and explicitly blocked. No private rows/content, secrets, model inference or provider call were inspected during this verification. - **Known regressions:** None found by automated/local browser checks. Jest still needs `--forceExit` and reports its existing open-handle notice. Email-provider/send tests are fake/local only; real delivery is not claimed. Current MAIL browser evidence is 1280×720 only because the browser surface could not resize or perform native Tab traversal. Interrupted attempts are aged after 15 minutes and notified without retry; the five-minute scan is unmeasured on a large ledger. The direct clean EF-only SQLite defect and synchronous AI accounting gap are closed; migration/reconciler dual ownership remains architectural debt. - **Outstanding security findings:** JT-001 repository ownership remains High deployment risk until migration/inventory/provider checks; production portion of JT-002; JT-006 and SEC-009 production retention/restore plus JT-011/JT-012/JT-022 prerequisites. JT-005 foundations are implemented; AI worker activation awaits controlled rollout. Production still exposes ports contrary to the release-branch contract, and JT-007/JT-008/JT-010 lack provider/production verification. From bc4394c69261a28e607aaa904929d13d6b8b2493 Mon Sep 17 00:00:00 2001 From: cesnimda Date: Tue, 1 Sep 2026 09:23:03 +0200 Subject: [PATCH 9/9] refactor(cv): extract customization panel --- docs/work-programmes/master-progress.md | 1 + .../src/components/cv/CvCustomizeTab.tsx | 102 +++++++++++++++++ job-tracker-ui/src/views/CvBuilderEditor.tsx | 105 +----------------- 3 files changed, 109 insertions(+), 99 deletions(-) create mode 100644 job-tracker-ui/src/components/cv/CvCustomizeTab.tsx diff --git a/docs/work-programmes/master-progress.md b/docs/work-programmes/master-progress.md index 7d1b6cc9..519d3316 100644 --- a/docs/work-programmes/master-progress.md +++ b/docs/work-programmes/master-progress.md @@ -9,6 +9,7 @@ Updated: 2026-09-01 - Restored visibly distinct CV templates by clearing stale structural overrides when a template changes while preserving CV content and deliberate colour, typography, spacing and document settings. The live A4/Letter preview now fits its pane automatically and responds to pane and viewport resizing; manual zoom remains available. - Consolidated both template choosers into one ATS-first gallery backed by real rendered sample documents. ATS-safe designs are prioritised and explained, decorative sidebar layouts are not falsely labelled ATS-friendly, existing non-ATS selections remain visible, and all designs remain one click away. - Removed Docker Compose warnings for deliberately optional Microsoft-tenant and production-relative frontend API variables; missing required provider configuration remains enforced by deployment preflight. +- Extracted the CV template/design/layout controls from the monolithic editor into a dedicated typed component while preserving settings, accessibility, localization and persistence behavior. The editor dropped below 1,200 lines and both creation/editor template flows continue sharing the same gallery. - Diagnosed Gitea Actions run 696 from its authenticated job log: application tests passed, but repeated truncated npm/Playwright downloads were followed by a native exit 139 before browser assertions ran. CI now invokes the lockfile-installed Playwright CLI directly, extends the bounded download timeout, retries only SIGSEGV, and does not redownload the same dependency tree after a transient runner crash. - Removed the unreachable legacy `JobDetailsDialog`, its duplicate insight tabs/panels, and tests coupled only to that retired surface. Live correspondence and routed-workspace contracts retain focused coverage; the cleanup removed 2,239 lines without changing the active Job Workspace. - Began the controller-responsibility split by moving job statistics, monthly analytics, tag counts, overview analytics, and tag trends into one dedicated authenticated analytics controller. Existing `api/jobapplications/*` routes and response contracts are unchanged; the shared tag parser replaces a byte-for-byte duplicate local parser. diff --git a/job-tracker-ui/src/components/cv/CvCustomizeTab.tsx b/job-tracker-ui/src/components/cv/CvCustomizeTab.tsx new file mode 100644 index 00000000..91526b4b --- /dev/null +++ b/job-tracker-ui/src/components/cv/CvCustomizeTab.tsx @@ -0,0 +1,102 @@ +import React from "react"; +import { + Box, Button, Divider, FormControl, FormControlLabel, IconButton, InputLabel, MenuItem, Paper, Select, Slider, Stack, Switch, TextField, Typography, +} from "@mui/material"; + +import { applyCvTheme, CvTheme, CvVariantSettings, normalizeCvLanguage, SECTION_LABELS } from "../../cvBuilder"; +import { useI18n } from "../../i18n/I18nProvider"; +import CvTemplateGallery from "../CvTemplateGallery"; + +const FONTS = [ + "'Segoe UI', Roboto, Arial, sans-serif", + "Arial, Helvetica, sans-serif", + "Georgia, 'Times New Roman', serif", + "'Helvetica Neue', Arial, sans-serif", + "'Roboto', Arial, sans-serif", + "'Poppins', 'Segoe UI', Arial, sans-serif", +]; +const FONT_LABELS = ["Segoe UI", "Arial", "Georgia (serif)", "Helvetica Neue", "Roboto", "Poppins"]; + +type Props = { + mode: "template" | "customize"; + settings: CvVariantSettings; + update: (patch: Partial) => void; + themes: CvTheme[]; + sectionLabel: (key: string, fallback: string) => string; +}; + +export default function CvCustomizeTab({ mode, settings, update, themes, sectionLabel }: Props) { + const { t } = useI18n(); + const activeTheme = themes.find((theme) => theme.id === settings.themeId); + const supports = (setting: string) => !activeTheme?.supportedSettings?.length || activeTheme.supportedSettings.includes(setting); + const sidebarSections = settings.sidebarSections ?? ["contact", "skills", "languages"]; + const toggleSidebarSection = (key: string) => update({ + sidebarSections: sidebarSections.includes(key) + ? sidebarSections.filter((item) => item !== key) + : [...sidebarSections, key], + }); + + return ( + + {mode === "template" && + {t("cvEditorTheme")} + {t("cvEditorThemeHelp")} + update(applyCvTheme(settings, theme.id))} /> + } + + {mode === "customize" && <> + {supports("accent") && <>{t("cvEditorColour")} + + {["#3157d5", "#0f766e", "#9f1239", "#7c3aed", "#b45309", "#334155"].map((color) => ( + update({ accentColor: color })} sx={{ width: 34, height: 34, bgcolor: color, border: settings.accentColor === color ? "3px solid" : "1px solid", borderColor: settings.accentColor === color ? "text.primary" : "divider", "&:hover": { bgcolor: color } }} /> + ))} + + update({ accentColor: event.target.value })} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer" }} /> + + {settings.accentColor && } + } + + {supports("typography") && <>{t("cvEditorTypography")} + + {t("cvEditorHeadingFont")} + {t("cvEditorBodyFont")} + + update({ baseFontSizePt: value })} /> + update({ headingSizePt: value })} /> + update({ lineHeight: value })} />} + {supports("heading") && {t("cvEditorHeadingTreatment")}} + {supports("header") && {t("cvEditorHeaderTreatment")}} + {supports("skills") && <>{t("cvEditorSkillsPresentation")} + {settings.skillsStyle === "grouped" && `${group.name}: ${group.items.join(", ")}`).join("\n")} onChange={(event) => update({ skillGroups: event.target.value.split("\n").filter(Boolean).map((line) => { const [name, ...items] = line.split(":"); return { name: name.trim(), items: items.join(":").split(",").map((item) => item.trim()).filter(Boolean) }; }) })} />}} + + {t("cvEditorDocument")} + + {supports("page") && <> + {t("cvEditorPageSize")} + {t("cvEditorDensity")} + } + {t("cvEditorDocumentLanguage")} + {t("cvEditorDateFormat")} + + {supports("layout") && {t("cvEditorColumns")}} + {supports("spacing") && <> + update({ pageMarginMm: value })} /> + update({ sectionGapMm: value })} /> + update({ entryGapMm: value })} /> + } + {supports("sidebar") && (settings.layout === "sidebar-left" || settings.layout === "sidebar-right") && + {t("cvEditorSidebarContent")} + update({ sidebarWidthMm: value })} /> + {["contact", "skills", "languages", "certifications", "projects", "interests"].map((key) => toggleSidebarSection(key)} />} label={key === "contact" ? t("cvEditorContactDetails") : sectionLabel(key, SECTION_LABELS[key] ?? key)} />)} + } + + {supports("photo") && update({ showPhoto: event.target.checked })} />} label={t("cvEditorShowPhoto")} />} + {supports("icons") && update({ showIcons: event.target.checked })} />} label={t("cvEditorContactIcons")} />} + } + + ); +} + +function ControlSlider({ label, value, min, max, step, suffix = "", onChange }: { label: string; value: number; min: number; max: number; step: number; suffix?: string; onChange: (value: number) => void }) { + return {label}{Number(value.toFixed(2))}{suffix} onChange(next as number)} />; +} diff --git a/job-tracker-ui/src/views/CvBuilderEditor.tsx b/job-tracker-ui/src/views/CvBuilderEditor.tsx index db894dcb..8e163b11 100644 --- a/job-tracker-ui/src/views/CvBuilderEditor.tsx +++ b/job-tracker-ui/src/views/CvBuilderEditor.tsx @@ -2,8 +2,8 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react" import { Link as RouterLink, useBlocker, useNavigate, useParams } from "react-router-dom"; import { - Alert, Box, Button, Chip, Collapse, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControl, FormControlLabel, IconButton, InputLabel, - MenuItem, Paper, Select, Skeleton, Slider, Stack, Switch, Tab, Tabs, TextField, Tooltip, Typography, + Alert, Box, Button, Chip, Collapse, Dialog, DialogActions, DialogContent, DialogTitle, Divider, IconButton, + MenuItem, Paper, Skeleton, Slider, Stack, Tab, Tabs, TextField, Tooltip, Typography, } from "@mui/material"; import useMediaQuery from "@mui/material/useMediaQuery"; import ArrowBackIcon from "@mui/icons-material/ArrowBack"; @@ -31,26 +31,17 @@ import { useToast } from "../toast"; import { useAccountPlan } from "../accountPlan"; import RichTextField from "../components/RichTextField"; import AiSectionAssistant from "../components/cv/AiSectionAssistant"; +import CvCustomizeTab from "../components/cv/CvCustomizeTab"; import ProFeatureNotice from "../components/ProFeatureNotice"; -import CvTemplateGallery from "../components/CvTemplateGallery"; import { useDragReorder } from "../hooks/useDragReorder"; import { CUSTOM_SECTION_PRESETS, CvCustomSectionSetting, CvItemOverride, CvOutline, CvOutlineSection, CvSectionSetting, CvTheme, CvVariant, CvVariantSettings, CvVariantVersionInfo, DEFAULT_SECTION_ORDER, SECTION_LABELS, - applyCvTheme, cvBuilderApi, getCvPageCount, getCvPageMetrics, getCvPreviewFitZoom, moveItem, normalizeCvLanguage, + cvBuilderApi, getCvPageCount, getCvPageMetrics, getCvPreviewFitZoom, moveItem, normalizeCvLanguage, } from "../cvBuilder"; import { useDialogActions } from "../dialogs"; import { useI18n } from "../i18n/I18nProvider"; -const FONTS = [ - "'Segoe UI', Roboto, Arial, sans-serif", - "Arial, Helvetica, sans-serif", - "Georgia, 'Times New Roman', serif", - "'Helvetica Neue', Arial, sans-serif", - "'Roboto', Arial, sans-serif", - "'Poppins', 'Segoe UI', Arial, sans-serif", -]; -const FONT_LABELS = ["Segoe UI", "Arial", "Georgia (serif)", "Helvetica Neue", "Roboto", "Poppins"]; const MIN_PREVIEW_ZOOM = 0.32; type SaveState = "idle" | "unsaved" | "saving" | "saved" | "error"; @@ -480,9 +471,9 @@ export default function CvBuilderEditor() { - {tab === 0 && } + {tab === 0 && sectionName(key, fallback, t)} />} {tab === 1 && } - {tab === 2 && } + {tab === 2 && sectionName(key, fallback, t)} />} {tab === 3 && } {tab === 4 && } @@ -1130,90 +1121,6 @@ function EntryEditor({ section, row, settings, onPatch, onUpdateSettings }: { ); } -// ---------- Customize tab ---------- - -function CustomizeTab({ mode, settings, update, themes }: { - mode: "template" | "customize"; - settings: CvVariantSettings; - update: (p: Partial) => void; - themes: CvTheme[]; -}) { - const { t } = useI18n(); - const activeTheme = themes.find((theme) => theme.id === settings.themeId); - const supports = (setting: string) => !activeTheme?.supportedSettings?.length || activeTheme.supportedSettings.includes(setting); - const sidebarSections = settings.sidebarSections ?? ["contact", "skills", "languages"]; - const toggleSidebarSection = (key: string) => update({ - sidebarSections: sidebarSections.includes(key) - ? sidebarSections.filter((item) => item !== key) - : [...sidebarSections, key], - }); - return ( - - {mode === "template" && - {t("cvEditorTheme")} - {t("cvEditorThemeHelp")} - update(applyCvTheme(settings, theme.id))} /> - } - - {mode === "customize" && <> - {supports("accent") && <>{t("cvEditorColour")} - - {["#3157d5", "#0f766e", "#9f1239", "#7c3aed", "#b45309", "#334155"].map((color) => ( - update({ accentColor: color })} sx={{ width: 34, height: 34, bgcolor: color, border: settings.accentColor === color ? "3px solid" : "1px solid", borderColor: settings.accentColor === color ? "text.primary" : "divider", "&:hover": { bgcolor: color } }} /> - ))} - - update({ accentColor: e.target.value })} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer" }} /> - - {settings.accentColor && } - } - - {supports("typography") && <>{t("cvEditorTypography")} - - {t("cvEditorHeadingFont")} - {t("cvEditorBodyFont")} - - update({ baseFontSizePt: value })} /> - update({ headingSizePt: value })} /> - update({ lineHeight: value })} />} - {supports("heading") && {t("cvEditorHeadingTreatment")}} - {supports("header") && {t("cvEditorHeaderTreatment")}} - {supports("skills") && <>{t("cvEditorSkillsPresentation")} - {settings.skillsStyle === "grouped" && `${group.name}: ${group.items.join(", ")}`).join("\n")} onChange={(event) => update({ skillGroups: event.target.value.split("\n").filter(Boolean).map((line) => { const [name, ...items] = line.split(":"); return { name: name.trim(), items: items.join(":").split(",").map((item) => item.trim()).filter(Boolean) }; }) })} />}} - } - - {mode === "customize" && <> - {t("cvEditorDocument")} - - {supports("page") && <> - {t("cvEditorPageSize")} - {t("cvEditorDensity")} - } - {t("cvEditorDocumentLanguage")} - {t("cvEditorDateFormat")} - - {supports("layout") && {t("cvEditorColumns")}} - {supports("spacing") && <> - update({ pageMarginMm: value })} /> - update({ sectionGapMm: value })} /> - update({ entryGapMm: value })} /> - } - {supports("sidebar") && (settings.layout === "sidebar-left" || settings.layout === "sidebar-right") && - {t("cvEditorSidebarContent")} - update({ sidebarWidthMm: value })} /> - {["contact", "skills", "languages", "certifications", "projects", "interests"].map((key) => toggleSidebarSection(key)} />} label={key === "contact" ? t("cvEditorContactDetails") : sectionName(key, SECTION_LABELS[key] ?? key, t)} />)} - } - - {supports("photo") && update({ showPhoto: e.target.checked })} />} label={t("cvEditorShowPhoto")} />} - {supports("icons") && update({ showIcons: e.target.checked })} />} label={t("cvEditorContactIcons")} />} - } - - ); -} - -function ControlSlider({ label, value, min, max, step, suffix = "", onChange }: { label: string; value: number; min: number; max: number; step: number; suffix?: string; onChange: (value: number) => void }) { - return {label}{Number(value.toFixed(2))}{suffix} onChange(next as number)} />; -} - function HistoryTab({ versions, onRestore }: { versions: CvVariantVersionInfo[]; onRestore: (v: number) => void }) { const { language, t } = useI18n(); if (versions.length === 0) return {t("cvEditorNoVersions")};