Files
jobtrackingapp/JobTrackerApi/Services/CareerProfileService.cs
T
cesnimda 992f89e619 feat: integrate Career Workspace foundation from feature/career-workspace
Recover the F1 Career Profile foundation + AI-workspace persistence from the
unmerged feature/career-workspace branch, so Phase 2 builds on the documented,
tested target state instead of re-deriving it. Foundation only — CV Builder
commits (variants, ATS badge, rewrite diff) stay deferred per "do not build CV
Builder yet". See docs/career-workspace-branch-assessment.md.

Squashed from 3 branch commits (235e291, 5916f09, 00a035e), resolved against
main + Phase 0:

- CareerProfile + CareerProfileVersion (append-only history), dual-written from
  every profile save path via CareerProfileService. ApplicationUser.
  ProfileCvStructureJson stays authoritative; the tables mirror it. Stable item
  IDs assigned to jobs/education/certifications/projects (the prerequisite for
  future variant lineage). CvDateNormalizer for free-text -> YYYY-MM.
- InterviewPrepNote + AiWorkspaceNote: cache AI interview prep / candidate fit /
  focus plan keyed by an attachment-context signature, so they stop regenerating
  (and re-spending the provider) on every open.

Conflict resolutions (union, favouring current code + Phase 0):
- JobTrackerContext / StartupInitializationExtensions: kept Phase 0's tables and
  reconciler blocks, added the career/interview/ai-note tables (both SQLite and
  MySQL dialects).
- ProfileCvController: dropped the branch's in-file DTO records (main defines them
  in ProfileCvDtos.cs) and the LayoutFamily/AtsRating template fields (deferred
  ATS-badge work), keeping main's 7-arg CvTemplateDescriptor.
- JobApplicationsController: kept the branch's cache-check, restored main's
  AsNoTracking on the read-only user load.

Tables ship empty (verified dev); nothing to migrate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 19:11:42 +02:00

170 lines
6.6 KiB
C#

using System.Text.RegularExpressions;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using Microsoft.EntityFrameworkCore;
namespace JobTrackerApi.Services;
// Career Workspace foundation (see docs/career-workspace-implementation-roadmap.md, Phase F1).
// Bounded to the profile/CV domain -- job tracking is untouched. Every existing read path still
// goes through ApplicationUser.ProfileCvStructureJson (dual-write window); this service is the
// single place stable item IDs and normalized dates get assigned, and where profile history is
// captured so it's never silently overwritten on the next rebuild/improve/upload.
public interface ICareerProfileService
{
// Mutates the given profile in place (assigns missing item IDs + normalized dates), persists
// it as the current CareerProfile snapshot plus an append-only CareerProfileVersion row, and
// returns the same profile so the caller can go on to serialize it into the legacy column.
Task<StructuredCvProfile> SaveVersionAsync(string ownerUserId, StructuredCvProfile profile, string source, CancellationToken cancellationToken);
}
public sealed class CareerProfileService : ICareerProfileService
{
private readonly JobTrackerContext _db;
public CareerProfileService(JobTrackerContext db)
{
_db = db;
}
public async Task<StructuredCvProfile> SaveVersionAsync(string ownerUserId, StructuredCvProfile profile, string source, CancellationToken cancellationToken)
{
AssignStableIds(profile);
NormalizeDates(profile);
var json = StructuredCvProfileJson.Serialize(profile);
var existing = await _db.CareerProfiles.FirstOrDefaultAsync(x => x.OwnerUserId == ownerUserId, cancellationToken);
if (existing is null)
{
existing = new CareerProfile
{
OwnerUserId = ownerUserId,
ProfileJson = json,
Version = 1,
CreatedAtUtc = DateTimeOffset.UtcNow,
UpdatedAtUtc = DateTimeOffset.UtcNow,
};
_db.CareerProfiles.Add(existing);
}
else
{
existing.ProfileJson = json;
existing.Version += 1;
existing.UpdatedAtUtc = DateTimeOffset.UtcNow;
}
await _db.SaveChangesAsync(cancellationToken);
_db.CareerProfileVersions.Add(new CareerProfileVersion
{
OwnerUserId = ownerUserId,
CareerProfileId = existing.Id,
Version = existing.Version,
ProfileJson = json,
Source = string.IsNullOrWhiteSpace(source) ? "manual" : source.Trim(),
CreatedAtUtc = DateTimeOffset.UtcNow,
});
await _db.SaveChangesAsync(cancellationToken);
return profile;
}
private static void AssignStableIds(StructuredCvProfile profile)
{
foreach (var job in profile.Jobs)
{
if (string.IsNullOrWhiteSpace(job.Id)) job.Id = NewItemId();
}
foreach (var education in profile.Education)
{
if (string.IsNullOrWhiteSpace(education.Id)) education.Id = NewItemId();
}
foreach (var certification in profile.Certifications)
{
if (string.IsNullOrWhiteSpace(certification.Id)) certification.Id = NewItemId();
}
foreach (var project in profile.Projects)
{
if (string.IsNullOrWhiteSpace(project.Id)) project.Id = NewItemId();
}
}
private static string NewItemId() => Guid.NewGuid().ToString("N")[..12];
private static void NormalizeDates(StructuredCvProfile profile)
{
foreach (var job in profile.Jobs)
{
job.StartDate = CvDateNormalizer.TryParseYearMonth(job.Start);
job.EndDate = job.IsCurrent ? null : CvDateNormalizer.TryParseYearMonth(job.End);
}
foreach (var education in profile.Education)
{
education.StartDate = CvDateNormalizer.TryParseYearMonth(education.Start);
education.EndDate = CvDateNormalizer.TryParseYearMonth(education.End);
}
foreach (var certification in profile.Certifications)
{
certification.DateNormalized = CvDateNormalizer.TryParseYearMonth(certification.Date);
}
foreach (var project in profile.Projects)
{
project.StartDate = CvDateNormalizer.TryParseYearMonth(project.Start);
project.EndDate = CvDateNormalizer.TryParseYearMonth(project.End);
}
}
}
// Best-effort free-string -> "YYYY-MM" parser. Never throws, never loses data: the original
// free-string field is always kept alongside whatever this returns (null on anything it can't
// confidently parse -- callers must not treat null as "no date", only as "unparsed").
public static class CvDateNormalizer
{
private static readonly Dictionary<string, int> MonthNames = new(StringComparer.OrdinalIgnoreCase)
{
["jan"] = 1, ["january"] = 1,
["feb"] = 2, ["february"] = 2,
["mar"] = 3, ["march"] = 3,
["apr"] = 4, ["april"] = 4,
["may"] = 5,
["jun"] = 6, ["june"] = 6,
["jul"] = 7, ["july"] = 7,
["aug"] = 8, ["august"] = 8,
["sep"] = 9, ["sept"] = 9, ["september"] = 9,
["oct"] = 10, ["october"] = 10,
["nov"] = 11, ["november"] = 11,
["dec"] = 12, ["december"] = 12,
};
public static string? TryParseYearMonth(string? raw)
{
var value = (raw ?? string.Empty).Trim();
if (value.Length == 0) return null;
if (value.Equals("present", StringComparison.OrdinalIgnoreCase) || value.Equals("current", StringComparison.OrdinalIgnoreCase)) return null;
// "2020" -> January is an assumption we don't want to make silently; year-only stays unparsed.
var monthYear = Regex.Match(value, @"^(?<month>[A-Za-z]+)\.?\s+(?<year>\d{4})$");
if (monthYear.Success && MonthNames.TryGetValue(monthYear.Groups["month"].Value, out var month))
{
return $"{monthYear.Groups["year"].Value}-{month:D2}";
}
var slash = Regex.Match(value, @"^(?<month>\d{1,2})/(?<year>\d{4})$");
if (slash.Success)
{
var m = int.Parse(slash.Groups["month"].Value);
if (m is >= 1 and <= 12) return $"{slash.Groups["year"].Value}-{m:D2}";
}
var isoLike = Regex.Match(value, @"^(?<year>\d{4})-(?<month>\d{1,2})$");
if (isoLike.Success)
{
var m = int.Parse(isoLike.Groups["month"].Value);
if (m is >= 1 and <= 12) return $"{isoLike.Groups["year"].Value}-{m:D2}";
}
return null;
}
}