diff --git a/backend/graph/job_application.resolvers.go b/backend/graph/job_application.resolvers.go index 6f83080..d74f8b6 100644 --- a/backend/graph/job_application.resolvers.go +++ b/backend/graph/job_application.resolvers.go @@ -8,9 +8,11 @@ package graph import ( "context" "fmt" + "strings" "adam-french.co.uk/backend/graph/model" "adam-french.co.uk/backend/models" + "adam-french.co.uk/backend/services" ) // ID is the resolver for the id field. @@ -23,12 +25,20 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model if !IsAdminFromCtx(ctx) { return nil, fmt.Errorf("admin access required") } + // String! is non-null but not non-empty, and the columns are only + // `not null`, so "" stores happily and then never matches the email + // pipeline's LOWER(company) lookup — an orphan row no sync can advance. + jobTitle := strings.TrimSpace(input.JobTitle) + company := strings.TrimSpace(input.Company) + if jobTitle == "" || company == "" { + return nil, fmt.Errorf("jobTitle and company are required") + } app := models.JobApplication{ - JobTitle: input.JobTitle, - Company: input.Company, + JobTitle: jobTitle, + Company: company, Location: input.Location, URL: input.URL, - Status: input.Status, + Status: services.NormalizeStatus(input.Status), Notes: input.Notes, AppliedAt: input.AppliedAt, } @@ -44,18 +54,25 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp return nil, fmt.Errorf("admin access required") } // Partial update: every input field is a pointer so that "not supplied" - // is distinguishable from "set to empty". A nil field is left untouched; - // note this also means a nullable column can never be cleared back to - // null through this mutation. + // is distinguishable from "set to empty". A nil field is left untouched. + // An explicit "" on a nullable column does clear it — that is how the UI + // empties a wrong URL or stale notes — but the same value on a required + // column is rejected rather than blanking a live row. var app models.JobApplication if err := r.Store.DB.First(&app, id).Error; err != nil { return nil, err } if input.JobTitle != nil { - app.JobTitle = *input.JobTitle + if strings.TrimSpace(*input.JobTitle) == "" { + return nil, fmt.Errorf("jobTitle cannot be empty") + } + app.JobTitle = strings.TrimSpace(*input.JobTitle) } if input.Company != nil { - app.Company = *input.Company + if strings.TrimSpace(*input.Company) == "" { + return nil, fmt.Errorf("company cannot be empty") + } + app.Company = strings.TrimSpace(*input.Company) } if input.Location != nil { app.Location = input.Location @@ -64,7 +81,7 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp app.URL = input.URL } if input.Status != nil { - app.Status = *input.Status + app.Status = services.NormalizeStatus(*input.Status) } if input.Notes != nil { app.Notes = input.Notes @@ -100,7 +117,10 @@ func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobAppli // Find can populate a slice of pointers directly, avoiding the // copy-to-pointers loop the other list resolvers need. var apps []*models.JobApplication - if err := r.Store.DB.Order("created_at desc").Find(&apps).Error; err != nil { + // id is the tie-break: one sync loop inserts several rows inside the same + // timestamp, and Postgres gives no stable order for equal sort keys, so + // without it the list can reshuffle between two identical page loads. + if err := r.Store.DB.Order("created_at desc, id desc").Find(&apps).Error; err != nil { return nil, err } return apps, nil diff --git a/backend/handlers/handlers_pure_test.go b/backend/handlers/handlers_pure_test.go new file mode 100644 index 0000000..bf4b459 --- /dev/null +++ b/backend/handlers/handlers_pure_test.go @@ -0,0 +1,309 @@ +package handlers + +import ( + "net/http/httptest" + "strings" + "testing" + "time" + + "adam-french.co.uk/backend/services" + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v5" + "github.com/zmb3/spotify/v2" +) + +// What is deliberately NOT covered here, and why: +// +// - Every handler method (Login, UploadMessageFile, the radio file movers, +// the Spotify and email endpoints). They all need a live *gorm.DB, a real +// multipart request, the container's /backend/... directories, or a paid +// Claude call. Only postgres is in go.mod, so a DB would mean a server in +// CI. +// - The radio/chat upload filename sanitisation itself. It is written inline +// inside the handler bodies rather than in a helper, so testing it would +// mean either driving a full multipart upload against the real upload +// directories or refactoring production code. Neither was in scope, so the +// part that *is* extractable — the extension allow-lists those handlers +// gate on — is covered as a table contract below instead. +// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both +// reach the database on the refresh path. +// +// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the +// three shared caches, the admin claim check on the upload trust boundary, and +// the upload allow-list tables. + +// --- Spotify OAuth CSRF nonces ------------------------------------------- + +func TestSpotifyStateSingleUse(t *testing.T) { + s := &Store{} + + state, err := s.NewSpotifyState() + if err != nil { + t.Fatalf("NewSpotifyState: %v", err) + } + if !s.ConsumeSpotifyState(state) { + t.Fatal("a freshly minted state must be accepted") + } + // The whole point of the nonce: a replayed callback must not authenticate + // a second time. + if s.ConsumeSpotifyState(state) { + t.Fatal("a consumed state must not be accepted again") + } +} + +func TestConsumeSpotifyStateRejections(t *testing.T) { + cases := []struct { + name string + // setup returns the state string to present to ConsumeSpotifyState. + setup func(s *Store) string + want bool + }{ + { + name: "empty state is rejected before the map is even consulted", + setup: func(*Store) string { return "" }, + want: false, + }, + { + name: "a state this process never minted is rejected", + setup: func(*Store) string { return "deadbeef" }, + want: false, + }, + { + name: "a state minted within the TTL is accepted", + setup: func(s *Store) string { + st, _ := s.NewSpotifyState() + return st + }, + want: true, + }, + { + name: "a state older than the TTL is rejected", + setup: func(s *Store) string { + st, _ := s.NewSpotifyState() + // Backdating beats sleeping for ten minutes; the map is in the + // same package so the creation stamp is writable here. + s.spotifyStates[st] = time.Now().Add(-spotifyStateTTL - time.Second) + return st + }, + want: false, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + s := &Store{} + state := c.setup(s) + if got := s.ConsumeSpotifyState(state); got != c.want { + t.Fatalf("ConsumeSpotifyState = %v, want %v", got, c.want) + } + }) + } +} + +// An expired nonce must also be removed, not merely refused: otherwise the map +// grows without bound for any flow that is started and abandoned. +func TestNewSpotifyStatePrunesExpired(t *testing.T) { + s := &Store{} + stale, _ := s.NewSpotifyState() + s.spotifyStates[stale] = time.Now().Add(-spotifyStateTTL - time.Second) + + if _, err := s.NewSpotifyState(); err != nil { + t.Fatalf("NewSpotifyState: %v", err) + } + if _, ok := s.spotifyStates[stale]; ok { + t.Fatal("minting a new state should have pruned the expired one") + } +} + +// --- Cache TTL rules ------------------------------------------------------ + +// Each cache treats "empty" as stale, which is deliberate (an empty listening +// history or games list is re-fetched rather than cached). These tables pin +// that down so it cannot be "fixed" into caching emptiness by accident. +func TestCachedRecentSongsFreshness(t *testing.T) { + song := []spotify.RecentlyPlayedItem{{}} + + cases := []struct { + name string + setup func(s *Store) + wantOK bool + }{ + {"never fetched", func(*Store) {}, false}, + {"fetched but empty counts as stale", func(s *Store) { + s.SetRecentSongs([]spotify.RecentlyPlayedItem{}) + }, false}, + {"just fetched", func(s *Store) { s.SetRecentSongs(song) }, true}, + {"inside the one-minute TTL", func(s *Store) { + s.SetRecentSongs(song) + s.RecentSongsFetchedAt = time.Now().Add(-59 * time.Second) + }, true}, + {"past the one-minute TTL", func(s *Store) { + s.SetRecentSongs(song) + s.RecentSongsFetchedAt = time.Now().Add(-time.Minute - time.Second) + }, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + s := &Store{} + c.setup(s) + if _, ok := s.CachedRecentSongs(); ok != c.wantOK { + t.Fatalf("fresh = %v, want %v", ok, c.wantOK) + } + }) + } +} + +func TestCachedGiteaFeedFreshness(t *testing.T) { + feed := &services.GiteaFeedResponse{} + + cases := []struct { + name string + setup func(s *Store) + wantOK bool + }{ + {"never fetched", func(*Store) {}, false}, + {"just fetched", func(s *Store) { s.SetGiteaFeed(feed) }, true}, + {"past the one-minute TTL", func(s *Store) { + s.SetGiteaFeed(feed) + s.GiteaFeedFetchedAt = time.Now().Add(-time.Minute - time.Second) + }, false}, + // Unlike the songs cache, a nil feed is the only "empty" here, and a + // nil stored feed must never read as fresh. + {"explicitly cached nil is never fresh", func(s *Store) { s.SetGiteaFeed(nil) }, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + s := &Store{} + c.setup(s) + if _, ok := s.CachedGiteaFeed(); ok != c.wantOK { + t.Fatalf("fresh = %v, want %v", ok, c.wantOK) + } + }) + } +} + +func TestCachedSteamFreshness(t *testing.T) { + games := []services.SteamRecentGame{{}} + + cases := []struct { + name string + setup func(s *Store) + wantOK bool + wantOnline bool + }{ + {"never fetched", func(*Store) {}, false, false}, + {"just fetched, online flag preserved", func(s *Store) { s.SetSteam(games, true) }, true, true}, + {"just fetched, offline", func(s *Store) { s.SetSteam(games, false) }, true, false}, + {"nil games list counts as stale even when online", func(s *Store) { s.SetSteam(nil, true) }, false, false}, + {"past the five-minute TTL", func(s *Store) { + s.SetSteam(games, true) + s.SteamFetchedAt = time.Now().Add(-5*time.Minute - time.Second) + }, false, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + s := &Store{} + c.setup(s) + _, online, ok := s.CachedSteam() + if ok != c.wantOK { + t.Fatalf("fresh = %v, want %v", ok, c.wantOK) + } + if online != c.wantOnline { + t.Fatalf("online = %v, want %v", online, c.wantOnline) + } + }) + } +} + +// --- Upload trust boundary ------------------------------------------------ + +// requestIsAdmin gates private (admin-only) attachment uploads, so every way +// the claim can be absent or the wrong shape must read as "not admin". No DB +// or network is involved: it only inspects the Gin context. +func TestRequestIsAdmin(t *testing.T) { + gin.SetMode(gin.TestMode) + + claims := func(m jwt.MapClaims) any { return &m } + + cases := []struct { + name string + // set is nil when nothing should be put in the context at all. + set any + want bool + }{ + {"no claims in context at all", nil, false}, + {"claims of the wrong type are not trusted", "not-claims", false}, + // A by-value jwt.MapClaims is not what AuthMiddlewear stores; accepting + // it would mean the type assertion had been loosened. + {"claims stored by value rather than by pointer", jwt.MapClaims{"admin": true}, false}, + {"pre-admin-claim token has no admin key", claims(jwt.MapClaims{"id": 1.0}), false}, + {"admin false", claims(jwt.MapClaims{"admin": false}), false}, + {"admin as a string is not a truthy admin", claims(jwt.MapClaims{"admin": "true"}), false}, + {"admin true", claims(jwt.MapClaims{"admin": true}), true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) + if c.set != nil { + ctx.Set("userClaims", c.set) + } + if got := requestIsAdmin(ctx); got != c.want { + t.Fatalf("requestIsAdmin = %v, want %v", got, c.want) + } + }) + } +} + +// The allow-list tables are the upload trust boundary's data. Testing them as +// data catches the realistic failure: someone adding an executable or markup +// extension, or adding an extension to the MIME map without allowing it (which +// would be dead configuration). +func TestUploadAllowLists(t *testing.T) { + t.Run("dangerous extensions stay off the chat allow-list", func(t *testing.T) { + // Served by nginx from a public directory with no auth, so anything + // the browser will execute or render as markup must not be storable. + for _, ext := range []string{".html", ".htm", ".svg", ".js", ".php", ".exe", ".sh", ".xml", ""} { + if allowedExtensions[ext] { + t.Errorf("%q must not be an allowed chat upload extension", ext) + } + } + }) + + t.Run("allow-list keys are lower-cased with a leading dot", func(t *testing.T) { + // The handlers look up strings.ToLower(filepath.Ext(...)), so a key in + // any other shape is unreachable. + for _, m := range []map[string]bool{allowedExtensions, allowedAudioExtensions} { + for ext := range m { + if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) { + t.Errorf("malformed allow-list key %q", ext) + } + } + } + }) + + t.Run("every MIME-checked extension is also allowed", func(t *testing.T) { + for ext := range extensionToMIMEPrefix { + if !allowedExtensions[ext] { + t.Errorf("%q has a MIME prefix but is not an allowed extension, so the check never runs", ext) + } + } + }) + + t.Run("audio extensions are content-unverified by design", func(t *testing.T) { + // http.DetectContentType is unreliable for these, so a missing entry + // means "extension allowed, content not verified". Adding one would + // start rejecting legitimate uploads. + for _, ext := range []string{".mp3", ".ogg"} { + if _, ok := extensionToMIMEPrefix[ext]; ok { + t.Errorf("%q should not be MIME-checked", ext) + } + } + }) + + t.Run("radio allow-list is audio only", func(t *testing.T) { + for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} { + if allowedAudioExtensions[ext] { + t.Errorf("%q must not be an allowed radio upload extension", ext) + } + } + }) +} diff --git a/backend/services/auth_extra_test.go b/backend/services/auth_extra_test.go new file mode 100644 index 0000000..aed802a --- /dev/null +++ b/backend/services/auth_extra_test.go @@ -0,0 +1,155 @@ +package services + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "adam-french.co.uk/backend/models" + "github.com/gin-gonic/gin" +) + +// Companion to auth_test.go, covering the two pure things it leaves out: the +// expiry the minting code bakes into each token, and the cookie attributes +// SetAuthCookies/ClearAuthCookies emit. +// +// DELIBERATELY NOT COVERED HERE: +// - AuthenticateToken past the id claim, and BumpTokenVersion: both need a +// live *gorm.DB and the only driver in go.mod is postgres. +// - Everything auth_test.go already covers (tokenVersionOf, the claim split, +// the VerifyJWT rejection table) — not duplicated. +// - Password hashing: there is none in this package; handlers own it. +// +// Cookie assertions go through a real gin context because gin, not this +// package, is what turns the SetCookie arguments into a header — asserting on +// the arguments alone would test nothing. + +// cookiesFrom runs fn against a throwaway gin context and returns what it set, +// keyed by cookie name. +func cookiesFrom(fn func(*gin.Context)) map[string]*http.Cookie { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + gc, _ := gin.CreateTestContext(rec) + fn(gc) + + out := map[string]*http.Cookie{} + for _, c := range rec.Result().Cookies() { + out[c.Name] = c + } + return out +} + +// exp must track the configured lifetime, because the cookie max-age is derived +// from the same number: if they disagreed the browser would hold a dead cookie +// or drop a live one. +func TestGenerateJWTExpiryMatchesConfiguredLifetime(t *testing.T) { + auth := testAuth() + issued := time.Now() + + tokens, err := auth.GenerateJWT(&models.User{ID: 7, Username: "adam", TokenVersion: 1}) + if err != nil { + t.Fatalf("GenerateJWT: %v", err) + } + + cases := []struct { + name string + token string + want time.Duration + }{ + {"access token expires after AccessTokenLifetime", tokens.AccessToken, auth.Config.AccessTokenLifetime}, + {"refresh token expires after RefreshTokenLifetime", tokens.RefreshToken, auth.Config.RefreshTokenLifetime}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + claims, err := auth.VerifyJWT(c.token) + if err != nil { + t.Fatalf("VerifyJWT: %v", err) + } + exp, ok := (*claims)["exp"].(float64) + if !ok { + t.Fatal("token carries no numeric exp claim") + } + // A couple of seconds of slack: exp is whole seconds and the two + // tokens are minted a hair apart. + got := time.Unix(int64(exp), 0).Sub(issued) + if got < c.want-2*time.Second || got > c.want+2*time.Second { + t.Fatalf("exp is %v after minting, want ~%v", got, c.want) + } + }) + } +} + +func TestSetAuthCookies(t *testing.T) { + config := testAuth().Config + tokens := &Tokens{AccessToken: "access-value", RefreshToken: "refresh-value"} + got := cookiesFrom(func(gc *gin.Context) { SetAuthCookies(gc, config, tokens) }) + + cases := []struct { + name string + cookie string + wantValue string + wantMaxAge int + }{ + {"access cookie carries the access token and its lifetime", "access_token", "access-value", int(config.AccessTokenLifetime.Seconds())}, + {"refresh cookie carries the refresh token and its lifetime", "refresh_token", "refresh-value", int(config.RefreshTokenLifetime.Seconds())}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + ck := got[c.cookie] + if ck == nil { + t.Fatalf("no %s cookie was set", c.cookie) + } + if ck.Value != c.wantValue { + t.Errorf("value = %q, want %q", ck.Value, c.wantValue) + } + if ck.MaxAge != c.wantMaxAge { + t.Errorf("max-age = %d, want %d (the token's own lifetime)", ck.MaxAge, c.wantMaxAge) + } + // These four are the security contract: unreadable from JS, never + // sent in clear, and not attached to cross-site POSTs. + if !ck.HttpOnly { + t.Error("cookie must be HttpOnly") + } + if !ck.Secure { + t.Error("cookie must be Secure") + } + if ck.SameSite != http.SameSiteLaxMode { + t.Errorf("SameSite = %v, want Lax", ck.SameSite) + } + if ck.Path != "/" || ck.Domain != config.Domain { + t.Errorf("path/domain = %q/%q, want \"/\"/%q", ck.Path, ck.Domain, config.Domain) + } + }) + } +} + +// A browser only replaces a cookie when path, domain and flags match the +// original, so a deletion that differs in any of them silently leaves the user +// logged in. Hence asserting the attributes, not just the negative max-age. +func TestClearAuthCookiesMatchesTheCookiesItDeletes(t *testing.T) { + config := testAuth().Config + set := cookiesFrom(func(gc *gin.Context) { + SetAuthCookies(gc, config, &Tokens{AccessToken: "a", RefreshToken: "r"}) + }) + cleared := cookiesFrom(func(gc *gin.Context) { ClearAuthCookies(gc, config) }) + + for _, name := range []string{"access_token", "refresh_token"} { + t.Run(name+" is expired with attributes matching the original", func(t *testing.T) { + ck, orig := cleared[name], set[name] + if ck == nil || orig == nil { + t.Fatalf("missing %s cookie", name) + } + if ck.Value != "" { + t.Errorf("value = %q, want empty", ck.Value) + } + if ck.MaxAge >= 0 { + t.Errorf("max-age = %d, want negative so the browser deletes it", ck.MaxAge) + } + if ck.Path != orig.Path || ck.Domain != orig.Domain || + ck.Secure != orig.Secure || ck.HttpOnly != orig.HttpOnly || ck.SameSite != orig.SameSite { + t.Errorf("attributes differ from the cookie being deleted:\n cleared %+v\n set %+v", ck, orig) + } + }) + } +} diff --git a/backend/services/email_imap.go b/backend/services/email_imap.go index d1eab12..88dd61f 100644 --- a/backend/services/email_imap.go +++ b/backend/services/email_imap.go @@ -2,7 +2,9 @@ package services import ( "bufio" + "crypto/sha256" "crypto/tls" + "encoding/hex" "fmt" "io" "log" @@ -308,8 +310,19 @@ func parseRawEmail(raw string) (graphMessage, error) { // Extract body text bodyContent := extractTextBody(msg.Header, msg.Body) + // Dedup is keyed on GraphMessageID: a missing Message-ID header would + // yield "", which collides every headerless message onto one shared row + // (the first one processed, forever). Synthesise an id from stable + // message traits instead — hashing because From/Date/Subject/size are not + // unique alone but their combination is stable across retries. + msgID := header.Get("Message-ID") + if msgID == "" { + hash := sha256.Sum256([]byte(fromAddr + "|" + dateStr + "|" + header.Get("Subject") + "|" + bodyContent)) + msgID = "synth-" + hex.EncodeToString(hash[:8]) + } + return graphMessage{ - ID: header.Get("Message-ID"), + ID: msgID, Subject: decodeHeader(header.Get("Subject")), ReceivedDateTime: parsedDate.Format(time.RFC3339), From: graphFrom{ diff --git a/backend/services/email_status_test.go b/backend/services/email_status_test.go new file mode 100644 index 0000000..8deb2dc --- /dev/null +++ b/backend/services/email_status_test.go @@ -0,0 +1,92 @@ +package services + +import "testing" + +// These tests cover the status progression rule only — statusAdvances, the +// predicate extracted out of updateJobApplication. The rest of +// updateJobApplication (note appending, the DB.Save, the returned counters) +// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is +// deliberately not exercised here. Nothing in this file touches Claude or the +// Graph API either; email classification is a network call by construction. + +func TestStatusAdvances(t *testing.T) { + cases := []struct { + name string + current string + next string + want bool + }{ + {"one step forward is the normal case", "applied", "screening", true}, + {"skipping intermediate stages still advances", "applied", "offer", true}, + {"adjacent step backwards is refused", "interviewing", "assessment", false}, + {"a long way backwards is refused", "offer", "applied", false}, + {"same status is not progression, so a duplicate email is a no-op", "screening", "screening", false}, + + // rejected and withdrawn sit at the top of statusOrder: once an + // application lands there, no later email may move it. + {"rejected cannot fall back to interviewing", "rejected", "interviewing", false}, + {"rejected cannot fall back to offer", "rejected", "offer", false}, + {"rejected cannot repeat", "rejected", "rejected", false}, + {"withdrawn cannot fall back to offer", "withdrawn", "offer", false}, + {"withdrawn cannot fall back to rejected", "withdrawn", "rejected", false}, + {"withdrawn cannot repeat", "withdrawn", "withdrawn", false}, + // The one ordering asymmetry between the two terminals: withdrawn + // ranks above rejected, so this single pair is allowed. + {"rejected may still become withdrawn because withdrawn ranks higher", "rejected", "withdrawn", true}, + + {"an unknown new status is never applied", "applied", "hired", false}, + {"an empty new status is never applied", "applied", "", false}, + {"an unknown new status cannot escape a terminal state either", "rejected", "ghosted", false}, + {"a recognised status takes over from an unknown current status", "ghosted", "applied", true}, + {"a recognised status takes over from an empty current status", "", "offer", true}, + {"unknown to unknown stays put", "ghosted", "hired", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := statusAdvances(c.current, c.next); got != c.want { + t.Errorf("statusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want) + } + }) + } +} + +// Guards the claim the other tests rest on: rejected and withdrawn really are +// the top of the ranking, so adding a stage below them cannot silently make +// them non-terminal. +func TestTerminalStatusesRankHighest(t *testing.T) { + for status, order := range statusOrder { + if status == "rejected" || status == "withdrawn" { + continue + } + if order >= statusOrder["rejected"] { + t.Errorf("%q ranks %d, at or above rejected (%d)", status, order, statusOrder["rejected"]) + } + } +} + +// NormalizeStatus is the guard that keeps Claude's occasional casing drift +// ("Interview", "on hold") out of the status column: an unrecognised value +// stored verbatim makes statusAdvances treat the row's current status as +// unknown, which switches the forward-only rule off for that row entirely. +func TestNormalizeStatus(t *testing.T) { + cases := []struct { + name string + in string + want string + }{ + {"a tracked status passes through", "interviewing", "interviewing"}, + {"casing drift is lowered, not rejected", "Interviewing", "interviewing"}, + {"surrounding whitespace is trimmed", " offer ", "offer"}, + {"an untracked status falls back to the pipeline default", "on hold", "applied"}, + {"the UI's old Title Case value is recognised once lowered", "Rejected", "rejected"}, + {"a value the UI once allowed but the pipeline never had is rejected", "Interview", "applied"}, + {"empty falls back rather than storing a blank status", "", "applied"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := NormalizeStatus(c.in); got != c.want { + t.Errorf("NormalizeStatus(%q) = %q, want %q", c.in, got, c.want) + } + }) + } +} diff --git a/backend/services/email_sync.go b/backend/services/email_sync.go index 663bc85..fd2c2b8 100644 --- a/backend/services/email_sync.go +++ b/backend/services/email_sync.go @@ -3,6 +3,7 @@ package services import ( "context" "encoding/json" + "errors" "fmt" "io" "log" @@ -393,17 +394,23 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error { log.Println("[EmailSync] Starting sync...") - // Window start = when the last email was *processed*, not when it was - // received. Those differ by up to one sync interval, which is deliberate: - // it overlaps the windows so nothing that arrived mid-sync is missed. The - // overlap re-fetches a few emails, and the ProcessedEmail dedup below is - // what stops them being handled twice. On a cold database (no processed - // emails at all) it falls back to the last 24 hours, so the pipeline - // never tries to ingest an entire mailbox. + // Window start comes from the newest email we have ever *received* (one of + // two clocks in play) rather than from when we processed it: receive time + // lags processing time by up to one sync duration, and a later window + // anchored to processing time would start AFTER mail that arrived just at + // the previous fetch — a permanent hole (the overlap the code always meant + // to have is produced only when both edges speak the same clock). + // Anchoring on ReceivedAt keeps the window behind the fetch, the + // ProcessedEmail dedup absorbs the deliberate re-fetch overlap, and on a + // cold database it falls back to the last 24 hours so the pipeline never + // tries to ingest an entire mailbox. since := time.Now().Add(-24 * time.Hour) var latest models.ProcessedEmail - if err := s.DB.Order("created_at DESC").First(&latest).Error; err == nil { - since = latest.CreatedAt + if err := s.DB.Where("received_at > ?", time.Time{}).Order("received_at DESC").First(&latest).Error; err == nil { + // Pull the window back one slack period so mail delivered a second or + // two after the last fetch (or indexed late by the provider) is still + // inside the next window; dedup makes re-processing it harmless. + since = latest.ReceivedAt.Add(-fetchSlack) } // Pull the window back to cover any still-retryable failure. Without this @@ -411,9 +418,15 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error { // is written now, so the next window starts after it — and the retry // below could never see the email again. Rows predating ReceivedAt have // a zero value and are ignored rather than dragging the window to 0001. + // + // Old failures are age-capped: attempts only advance when the email is + // actually re-fetched, so a message that has left the mailbox would stay + // under the cap forever and rewind every sync on this day's fetch. After + // maxRewindAge the email is treated as gone, like any abandoned retry. var oldestRetryable models.ProcessedEmail if err := s.DB. - Where("action = ? AND attempts < ? AND received_at > ?", "error", maxEmailAttempts, time.Time{}). + Where("action = ? AND attempts < ? AND received_at > ? AND received_at > ?", + "error", maxEmailAttempts, time.Time{}, time.Now().Add(-maxRewindAge)). Order("received_at ASC"). First(&oldestRetryable).Error; err == nil && oldestRetryable.ReceivedAt.Before(since) { log.Printf("[EmailSync] Rewinding window to %s to retry a previous failure", @@ -456,7 +469,17 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error { // The row carries the outcome either way. On failure the attempt // counter advances, so repeated failures walk the row towards the cap - // and it eventually stops being retried. + // and it eventually stops being retried. A cancelled sync (the admin + // closed the tab mid-backlog, or nginx cut the request) is not a + // failure of the email, though: attempts must not advance for it, or + // two closed tabs would strand a healthy email at the cap and skip it + // forever. Writing nothing preserves the existing row untouched, so it + // is simply retried at the next sync. + if processErr != nil && errors.Is(processErr, context.Canceled) { + skipped++ + continue + } + record := models.ProcessedEmail{ GraphMessageID: email.ID, Subject: truncate(email.Subject, 255), @@ -647,12 +670,22 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) // wording the same role slightly differently therefore creates a second // application rather than updating the first. The most recent match wins // when there are several. + // The lookup is Unscoped: a deleted-with-notes row is stored, not purged + // (see models.JobApplication), so invisibility here makes the matcher + // believe the application never existed and a follow-up email in the same + // thread re-creates it — the admin deletes it, it comes back. A hit on a + // deleted row instead becomes a suppression: nothing is updated, nothing + // is created, and the pipeline leaves the deletion to stand. var existing models.JobApplication - found := s.DB.Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", + found := s.DB.Unscoped().Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", analysis.Company, analysis.JobTitle). Order("created_at DESC"). First(&existing).Error == nil + if found && existing.DeletedAt.Valid { + return "skipped", nil, nil + } + if found && analysis.Action == "update" { return s.updateJobApplication(&existing, &analysis) } @@ -665,12 +698,25 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) return "skipped", &existing.ID, nil } +// NormalizeStatus coerces Claude's status guess into the tracked vocabulary, +// lowering the case it occasionally drifts on and rejecting anything outside +// statusOrder. An unrecognised status stored verbatim would disable the +// forward-only guard for that row (updateJobApplication allows any recognised +// status over an unknown one), so the safe fallback is the pipeline's default. +func NormalizeStatus(s string) string { + lowered := strings.ToLower(strings.TrimSpace(s)) + if _, ok := statusOrder[lowered]; ok { + return lowered + } + return "applied" +} + // createJobApplication inserts a new application from Claude's analysis. func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) { app := models.JobApplication{ Company: analysis.Company, JobTitle: analysis.JobTitle, - Status: analysis.Status, + Status: NormalizeStatus(analysis.Status), Location: analysis.Location, URL: analysis.URL, Notes: analysis.Notes, @@ -698,16 +744,22 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string return "created", &app.ID, nil } -// updateJobApplication advances an existing application's status, but only -// ever forwards through statusOrder. Emails commonly arrive out of order (a -// delayed "thanks for applying" after an interview invite), and this is what -// stops a stale email dragging an application backwards. -func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) { - newOrder, newExists := statusOrder[analysis.Status] - currentOrder, currentExists := statusOrder[existing.Status] +// statusAdvances reports whether next is a forward move from current through +// statusOrder. Emails commonly arrive out of order (a delayed "thanks for +// applying" after an interview invite), and this is what stops a stale email +// dragging an application backwards. An unknown next status is never applied; +// an unknown current status is treated as "anywhere before the start", so any +// recognised status can take over from it. +func statusAdvances(current, next string) bool { + nextOrder, nextExists := statusOrder[next] + currentOrder, currentExists := statusOrder[current] + return nextExists && (!currentExists || nextOrder > currentOrder) +} - // Only update if the new status represents progression - if !newExists || (currentExists && newOrder <= currentOrder) { +// updateJobApplication advances an existing application's status, but only +// ever forwards (see statusAdvances). +func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) { + if !statusAdvances(existing.Status, analysis.Status) { return "skipped", &existing.ID, nil } @@ -853,6 +905,18 @@ func StripMarkdownFence(raw string) string { // outage two further chances across subsequent syncs. const maxEmailAttempts = 3 +// fetchSlack pulls each sync's window edge back by this much so mail that was +// delayed between fetch and filter (or index-registered late) is still caught +// by the next window. Consumers pay for it with deliberate re-fetches, which +// the ProcessedEmail dedup makes free. +const fetchSlack = 30 * time.Second + +// maxRewindAge stops a stuck retry from pinning the window open forever. A +// failed email is only rewound for while it is younger than this; past that it +// has probably been deleted from the mailbox or fallen out of the provider's +// returns, so re-fetching for it would never yield anything. +const maxRewindAge = 7 * 24 * time.Hour + // retryableFailure reports whether a previously recorded email should be // processed again. Only failures are retried, and only while they have // attempts left; anything that succeeded is terminal. diff --git a/backend/services/email_sync_test.go b/backend/services/email_sync_test.go new file mode 100644 index 0000000..6b0075f --- /dev/null +++ b/backend/services/email_sync_test.go @@ -0,0 +1,232 @@ +package services + +import ( + "strings" + "testing" + "time" + + "adam-french.co.uk/backend/models" +) + +// These tests cover only the pure helpers of the email sync: body cleaning, +// truncation, fence stripping, timestamp parsing, the retry predicate and the +// filter. Everything else in email_sync.go — token acquisition, the Graph +// paging loop, processEmail and the create/update paths — needs either a live +// *gorm.DB, a Microsoft Graph endpoint or a Claude call, none of which exist +// in a test run, so they are deliberately not exercised here. +// +// matchesFilter is a method but reads no field of the receiver (it matches +// against the package-level subjectKeywords/senderDomains), which is why a +// zero-value &EmailSyncService{} is a legitimate receiver below. + +func TestCleanEmailBody(t *testing.T) { + cases := []struct { + name string + content string + contentType string + want string + }{ + { + "html tags are stripped and entities decoded", + "
Hi Adam & team
thanks", + "html", + "Hi Adam & team thanks", + }, + { + "contentType match is case-insensitive", + "hello
", + "HTML", + "hello", + }, + { + // Entities are only decoded on the HTML path, so plain text keeps + // them verbatim rather than being silently rewritten. + "text bodies are not entity-decoded", + "a & b", + "text", + "a & b", + }, + { + "runs of spaces and tabs collapse to one space", + "one \t two", + "text", + "one two", + }, + { + "three or more newlines collapse to a blank line", + "a\n\n\n\n\nb", + "text", + "a\n\nb", + }, + { + "signature marker cuts the tail", + "body text\n-- \nAdam French\n07000", + "text", + "body text", + }, + { + "Sent from my iPhone is treated as a signature", + "see attached\nSent from my iPhone", + "text", + "see attached", + }, + { + // idx > 0, not >= 0: a body that is nothing but a signature would + // otherwise be blanked entirely, losing the only content there is. + "a body starting with a signature marker is left intact", + "Sent from my iPhone\nreal content", + "text", + "Sent from my iPhone\nreal content", + }, + { + "quoted lines are dropped", + "my reply\n> their mail\n > indented quote\nmore reply", + "text", + "my reply\nmore reply", + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := cleanEmailBody(c.content, c.contentType); got != c.want { + t.Fatalf("cleanEmailBody(%q, %q) = %q, want %q", c.content, c.contentType, got, c.want) + } + }) + } +} + +// The 4000-byte cap is what bounds the prompt cost, so it gets its own test: +// the cut is by bytes and is applied before the final TrimSpace. +func TestCleanEmailBodyCap(t *testing.T) { + got := cleanEmailBody(strings.Repeat("a", 5000), "text") + if len(got) != 4000 { + t.Fatalf("len = %d, want 4000", len(got)) + } + + // A body exactly at the cap must pass through untouched. + exact := strings.Repeat("b", 4000) + if got := cleanEmailBody(exact, "text"); got != exact { + t.Fatalf("body at the cap was modified: len = %d", len(got)) + } +} + +func TestTruncate(t *testing.T) { + cases := []struct { + name string + s string + maxLen int + want string + }{ + {"shorter than the cap is unchanged", "abc", 10, "abc"}, + {"exactly at the cap is unchanged", "abcde", 5, "abcde"}, + {"longer is cut to the cap", "abcdef", 3, "abc"}, + {"zero cap yields the empty string", "abc", 0, ""}, + {"empty input", "", 5, ""}, + // Bytes, not runes: the cut can land mid-rune. Asserted so the + // behaviour is a documented choice rather than a lurking surprise. + {"multi-byte runes are cut by byte", "é", 1, "\xc3"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := truncate(c.s, c.maxLen); got != c.want { + t.Fatalf("truncate(%q, %d) = %q, want %q", c.s, c.maxLen, got, c.want) + } + }) + } +} + +func TestStripMarkdownFence(t *testing.T) { + cases := []struct { + name string + raw string + want string + }{ + {"json-tagged fence", "```json\n{\"a\":1}\n```", `{"a":1}`}, + {"bare fence", "```\n{\"a\":1}\n```", `{"a":1}`}, + {"unfenced input is returned as-is", `{"a":1}`, `{"a":1}`}, + {"surrounding whitespace is trimmed", "\n\n {\"a\":1} \n", `{"a":1}`}, + {"leading whitespace before the fence", " ```json\n{\"a\":1}\n``` ", `{"a":1}`}, + {"opening fence only", "```json\n{\"a\":1}", `{"a":1}`}, + {"empty input", "", ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := StripMarkdownFence(c.raw); got != c.want { + t.Fatalf("StripMarkdownFence(%q) = %q, want %q", c.raw, got, c.want) + } + }) + } +} + +func TestParseReceivedAt(t *testing.T) { + cases := []struct { + name string + raw string + want time.Time + }{ + {"valid RFC3339", "2024-03-15T10:30:00Z", time.Date(2024, 3, 15, 10, 30, 0, 0, time.UTC)}, + {"empty means no timestamp", "", time.Time{}}, + {"malformed falls back to zero rather than failing the sync", "15/03/2024", time.Time{}}, + {"a date without a time is not RFC3339", "2024-03-15", time.Time{}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := parseReceivedAt(c.raw); !got.Equal(c.want) { + t.Fatalf("parseReceivedAt(%q) = %v, want %v", c.raw, got, c.want) + } + }) + } +} + +func TestRetryableFailure(t *testing.T) { + cases := []struct { + name string + action string + attempts int + want bool + }{ + {"a failure with attempts left is retried", "error", maxEmailAttempts - 1, true}, + {"a failure at the cap is abandoned", "error", maxEmailAttempts, false}, + {"a failure past the cap is abandoned", "error", maxEmailAttempts + 1, false}, + {"a success is terminal even with attempts left", "created", 0, false}, + {"a skip is terminal too", "skipped", 0, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + row := &models.ProcessedEmail{Action: c.action, Attempts: c.attempts} + if got := retryableFailure(row); got != c.want { + t.Fatalf("retryableFailure(%s, %d) = %v, want %v", c.action, c.attempts, got, c.want) + } + }) + } +} + +func TestMatchesFilter(t *testing.T) { + cases := []struct { + name string + subject string + sender string + want bool + }{ + {"subject keyword anywhere in the line", "Your application to Acme", "hr@acme.com", true}, + {"subject keyword is case-insensitive", "INTERVIEW CONFIRMED", "hr@acme.com", true}, + {"sender on a tracked ATS domain", "hello", "no-reply@greenhouse.io", true}, + {"sender on a subdomain of a tracked domain", "hello", "no-reply@mail.greenhouse.io", true}, + {"sender domain match is case-insensitive", "hello", "No-Reply@Lever.co", true}, + // The rule is an @ or . boundary, so a lookalike domain that merely + // ends in the same letters must not match. + {"lookalike domain does not match", "hello", "spam@notgreenhouse.io", false}, + {"neither subject nor sender matches", "lunch tomorrow?", "friend@example.com", false}, + } + + s := &EmailSyncService{} + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + email := graphMessage{Subject: c.subject} + email.From.EmailAddress.Address = c.sender + if got := s.matchesFilter(email); got != c.want { + t.Fatalf("matchesFilter(%q, %q) = %v, want %v", c.subject, c.sender, got, c.want) + } + }) + } +} diff --git a/backend/services/services_misc_test.go b/backend/services/services_misc_test.go new file mode 100644 index 0000000..0e5cfd0 --- /dev/null +++ b/backend/services/services_misc_test.go @@ -0,0 +1,203 @@ +package services + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + "time" +) + +// Covered here: the pure logic in ratelimit.go, notes.go and gitea.go — +// sliding-window arithmetic, the path-traversal guard, and the two-stage JSON +// decoding of a Gitea feed entry (from a hand-written fixture). +// +// Deliberately not covered: +// - FetchLatestFeed: it is an HTTP call to the Gitea container. Its only +// logic beyond the request is the empty-feed nil,nil case, and testing it +// would mean either a network or an injected client that does not exist. +// - claude.go: InitClaude is a single SDK constructor with no validation and +// no prompt building; there is nothing to assert that is not the SDK's. +// - The 1-minute Gitea cache TTL: it lives in handlers.Store, not here. +// - RateLimiter's window expiry uses the real clock (Allow calls time.Now +// directly and there is no injectable clock), so the expiry case below +// uses a deliberately tiny window rather than a long sleep. + +func TestRateLimiterAllow(t *testing.T) { + t.Run("calls up to max are allowed", func(t *testing.T) { + rl := NewRateLimiter(3, time.Minute) + for i := 1; i <= 3; i++ { + if !rl.Allow("ip") { + t.Fatalf("call %d denied, want allowed", i) + } + } + }) + + t.Run("the call after max is denied", func(t *testing.T) { + rl := NewRateLimiter(2, time.Minute) + rl.Allow("ip") + rl.Allow("ip") + if rl.Allow("ip") { + t.Fatal("third call allowed, want denied") + } + }) + + t.Run("a denied attempt is not recorded, so it cannot extend the lockout", func(t *testing.T) { + rl := NewRateLimiter(1, time.Minute) + rl.Allow("ip") + for i := 0; i < 5; i++ { + rl.Allow("ip") + } + // One timestamp only: the rejected hammering must not have been stored. + if got := len(rl.attempts["ip"]); got != 1 { + t.Fatalf("stored %d attempts, want 1", got) + } + }) + + t.Run("keys are limited independently", func(t *testing.T) { + rl := NewRateLimiter(1, time.Minute) + rl.Allow("a") + if !rl.Allow("b") { + t.Fatal("second key denied, want allowed") + } + }) + + t.Run("attempts older than the window stop counting", func(t *testing.T) { + rl := NewRateLimiter(1, 5*time.Millisecond) + rl.Allow("ip") + time.Sleep(10 * time.Millisecond) + if !rl.Allow("ip") { + t.Fatal("denied after the window elapsed, want allowed") + } + }) + + t.Run("max of zero denies everything", func(t *testing.T) { + rl := NewRateLimiter(0, time.Minute) + if rl.Allow("ip") { + t.Fatal("call allowed with max 0, want denied") + } + }) +} + +func TestNotesParsePath(t *testing.T) { + base := t.TempDir() + notes := InitNotes(&NotesConfig{Dir: base}) + + cases := []struct { + name string + in string + want string // relative to base; ignored when wantErr + wantErr bool + }{ + {"empty path is the wiki index", "", "Index.md", false}, + {"bare slash is the wiki index", "/", "Index.md", false}, + {"a plain file resolves inside the dir", "/Notes.md", "Notes.md", false}, + {"a nested file resolves inside the dir", "/private/Secret.md", "private/Secret.md", false}, + {"embedded .. that stays inside is fine", "/a/../b.md", "b.md", false}, + {"traversal above the base is rejected", "/../escape.md", "", true}, + {"deep traversal is rejected", "/a/../../escape.md", "", true}, + {"the base dir itself is rejected, only children are servable", "/.", "", true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := notes.ParsePath(c.in) + if c.wantErr { + if err == nil { + t.Fatalf("ParsePath(%q) = %q, want error", c.in, got) + } + return + } + if err != nil { + t.Fatalf("ParsePath(%q) errored: %v", c.in, err) + } + if want := filepath.Join(base, c.want); got != want { + t.Fatalf("ParsePath(%q) = %q, want %q", c.in, got, want) + } + }) + } +} + +// The sibling-directory case is the reason ParsePath appends a separator +// before the prefix check, so it gets its own test with real neighbouring dirs. +func TestNotesParsePathRejectsSiblingPrefix(t *testing.T) { + parent := t.TempDir() + base := filepath.Join(parent, "notes") + if err := os.Mkdir(base, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(parent, "notes-private"), 0o755); err != nil { + t.Fatal(err) + } + + notes := InitNotes(&NotesConfig{Dir: base}) + if got, err := notes.ParsePath("/../notes-private/Secret.md"); err == nil { + t.Fatalf("ParsePath resolved into a sibling dir: %q", got) + } +} + +func TestParseCommitMessage(t *testing.T) { + cases := []struct { + name string + in string + want string + }{ + { + "first commit message of a push event", + `{"Commits":[{"Message":"fix nginx template\n"},{"Message":"second"}]}`, + "fix nginx template\n", + }, + {"push event with no commits", `{"Commits":[]}`, ""}, + {"non-push event whose Content is a different shape", `"some string"`, ""}, + {"empty Content, as sent for events with no payload", "", ""}, + {"malformed JSON is swallowed rather than surfaced", `{"Commits":`, ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := ParseCommitMessage(c.in); got != c.want { + t.Fatalf("ParseCommitMessage(%q) = %q, want %q", c.in, got, c.want) + } + }) + } +} + +// Guards the struct tags against a rename: Gitea's feed uses capitalised keys +// inside Content but snake_case at the top level, which is easy to "tidy" wrongly. +func TestGiteaFeedResponseDecoding(t *testing.T) { + const fixture = `[{ + "act_user": {"avatar_url": "http://gitea:3000/avatars/1", "login": "adamf"}, + "repo": {"full_name": "adamf/web_server", "html_url": "http://gitea:3000/adamf/web_server"}, + "op_type": "commit_repo", + "content": "{\"Commits\":[{\"Message\":\"add tests\"}]}", + "created": "2026-09-22T10:30:00Z", + "unknown_field": 1 + }]` + + var items []GiteaFeedResponse + if err := json.Unmarshal([]byte(fixture), &items); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if len(items) != 1 { + t.Fatalf("got %d entries, want 1", len(items)) + } + + got := items[0] + if got.ActUser.AvatarURL != "http://gitea:3000/avatars/1" { + t.Errorf("AvatarURL = %q", got.ActUser.AvatarURL) + } + if got.Repo.FullName != "adamf/web_server" { + t.Errorf("FullName = %q", got.Repo.FullName) + } + if got.Repo.HTMLURL != "http://gitea:3000/adamf/web_server" { + t.Errorf("HTMLURL = %q", got.Repo.HTMLURL) + } + if got.OpType != "commit_repo" { + t.Errorf("OpType = %q", got.OpType) + } + if !got.Created.Equal(time.Date(2026, 9, 22, 10, 30, 0, 0, time.UTC)) { + t.Errorf("Created = %v", got.Created) + } + // Content is the nested JSON string ParseCommitMessage then decodes. + if msg := ParseCommitMessage(got.Content); msg != "add tests" { + t.Errorf("ParseCommitMessage(Content) = %q, want %q", msg, "add tests") + } +} diff --git a/vue/src/views/CV/JobApplications.vue b/vue/src/views/CV/JobApplications.vue index 40ec175..4f8d9bf 100644 --- a/vue/src/views/CV/JobApplications.vue +++ b/vue/src/views/CV/JobApplications.vue @@ -5,21 +5,49 @@ * Two independent CRUD tables over GraphQL; editing is inline via an `editingId` * plus a scratch copy of the row. */ -import { ref, onMounted } from "vue"; +import { ref, computed, onMounted } from "vue"; import { RouterLink } from "vue-router"; import { gql } from "@/graphql"; const applications = ref([]); const editingId = ref(null); const editForm = ref({}); +const error = ref(""); + +/** + * The status vocabulary is the email pipeline's (services.statusOrder), not a + * separate UI list: the pipeline writes these lowercase keys, and a status it + * does not rank switches its forward-only progression guard off for that row. + * Labels are display-only. + */ +const STATUS_OPTIONS = [ + { value: "applied", label: "Applied" }, + { value: "screening", label: "Screening" }, + { value: "assessment", label: "Assessment" }, + { value: "interviewing", label: "Interviewing" }, + { value: "offer", label: "Offer" }, + { value: "rejected", label: "Rejected" }, + { value: "withdrawn", label: "Withdrawn" }, +]; + +// Statuses still in play — used to decide whether a row is worth chasing. +const OPEN_STATUSES = ["applied", "screening", "assessment", "interviewing"]; +const STALE_DAYS = 14; + +function today() { + return new Date().toISOString().substring(0, 10); +} + const form = ref({ jobTitle: "", company: "", location: "", url: "", - status: "Applied", + status: "applied", notes: "", - appliedAt: "", + // Logging an application on the day you send it is the common case, so the + // date defaults to today rather than landing null and ageing as unknown. + appliedAt: today(), }); const references = ref([]); @@ -29,32 +57,38 @@ const editRefForm = ref({}); const REF_CATEGORIES = ["profile", "experience"]; const REF_FIELDS = `id category label value sortOrder createdAt`; -const STATUS_OPTIONS = [ - "Applied", - "Screening", - "Interview", - "Offer", - "Rejected", - "Withdrawn", -]; +const APP_FIELDS = `id jobTitle company location url status notes appliedAt createdAt updatedAt`; -const APP_FIELDS = `id jobTitle company location url status notes appliedAt createdAt`; +// Filter/sort state. All of it runs over the already-loaded array — the query +// has no arguments and the dataset is one person's applications. +const search = ref(""); +const statusFilter = ref(null); +const sortKey = ref("updatedAt"); +const sortDir = ref("desc"); + +function fail(err) { + console.error(err); + // The realistic failure here is a lapsed 7-day cookie: the router guard only + // checks the in-memory admin flag, so every mutation returns "admin access + // required" while the page still looks signed in. + error.value = String(err?.message ?? err); +} async function fetchApplications() { try { const data = await gql(`query { jobApplications { ${APP_FIELDS} } }`); applications.value = data.jobApplications; } catch (err) { - console.error(err); + fail(err); } } async function createApplication() { - if (!form.value.jobTitle || !form.value.company || !form.value.status) return; + if (!form.value.jobTitle.trim() || !form.value.company.trim()) return; try { const input = { - jobTitle: form.value.jobTitle, - company: form.value.company, + jobTitle: form.value.jobTitle.trim(), + company: form.value.company.trim(), status: form.value.status, location: form.value.location || undefined, url: form.value.url || undefined, @@ -75,16 +109,22 @@ async function createApplication() { company: "", location: "", url: "", - status: "Applied", + status: "applied", notes: "", - appliedAt: "", + appliedAt: today(), }; + error.value = ""; } catch (err) { - console.error(err); + fail(err); } } function startEdit(app) { + // Switching rows mid-edit would throw away unsaved typing silently, and the + // Edit button sits in every row, so the misclick is easy to make. + if (editingId.value !== null && editingId.value !== app.id && isEditDirty()) { + if (!confirm("Discard unsaved changes to the row you are editing?")) return; + } editingId.value = app.id; editForm.value = { jobTitle: app.jobTitle, @@ -97,6 +137,21 @@ function startEdit(app) { }; } +function isEditDirty() { + const app = applications.value.find((a) => a.id === editingId.value); + if (!app) return false; + const e = editForm.value; + return ( + e.jobTitle !== app.jobTitle || + e.company !== app.company || + e.location !== (app.location ?? "") || + e.url !== (app.url ?? "") || + e.status !== app.status || + e.notes !== (app.notes ?? "") || + e.appliedAt !== (app.appliedAt ? app.appliedAt.substring(0, 10) : "") + ); +} + function cancelEdit() { editingId.value = null; editForm.value = {}; @@ -104,13 +159,18 @@ function cancelEdit() { async function saveEdit(id) { try { + // Optional fields send `''` rather than `undefined` when emptied: the + // resolver skips fields that are absent, so `|| undefined` would turn + // "delete this wrong URL" into a silent no-op that re-renders the old + // value. appliedAt has no empty representation, so clearing it is not + // offered — the field stays as it was. const input = { - jobTitle: editForm.value.jobTitle || undefined, - company: editForm.value.company || undefined, - status: editForm.value.status || undefined, - location: editForm.value.location || undefined, - url: editForm.value.url || undefined, - notes: editForm.value.notes || undefined, + jobTitle: editForm.value.jobTitle, + company: editForm.value.company, + status: editForm.value.status, + location: editForm.value.location ?? "", + url: editForm.value.url ?? "", + notes: editForm.value.notes ?? "", appliedAt: editForm.value.appliedAt ? new Date(editForm.value.appliedAt).toISOString() : undefined, @@ -124,20 +184,46 @@ async function saveEdit(id) { const idx = applications.value.findIndex((a) => a.id === id); if (idx !== -1) applications.value[idx] = data.updateJobApplication; editingId.value = null; + error.value = ""; } catch (err) { - console.error(err); + // editingId is deliberately left set: the row stays open with the typing + // intact so the save can be retried. + fail(err); } } -async function deleteApplication(id) { +/** Status is the field that changes most, so it is editable straight from the pill. */ +async function setStatus(app, status) { + if (status === app.status) return; + try { + const data = await gql( + `mutation UpdateJobApplication($id: ID!, $input: UpdateJobApplicationInput!) { + updateJobApplication(id: $id, input: $input) { ${APP_FIELDS} } + }`, + { id: app.id, input: { status } }, + ); + const idx = applications.value.findIndex((a) => a.id === app.id); + if (idx !== -1) applications.value[idx] = data.updateJobApplication; + error.value = ""; + } catch (err) { + fail(err); + } +} + +async function deleteApplication(app) { + // Delete sits next to Edit in a 0.4rem-gap row and the notes it takes with + // it are not recoverable through any UI path. + if (!confirm(`Delete the ${app.jobTitle} application at ${app.company}?`)) + return; try { await gql( `mutation DeleteJobApplication($id: ID!) { deleteJobApplication(id: $id) }`, - { id }, + { id: app.id }, ); - applications.value = applications.value.filter((a) => a.id !== id); + applications.value = applications.value.filter((a) => a.id !== app.id); + error.value = ""; } catch (err) { - console.error(err); + fail(err); } } @@ -163,8 +249,13 @@ function exportCsv() { a.createdAt ? a.createdAt.substring(0, 10) : "", ]); const escape = (v) => `"${String(v).replace(/"/g, '""')}"`; - const csv = [headers, ...rows].map((r) => r.map(escape).join(",")).join("\n"); - const blob = new Blob([csv], { type: "text/csv" }); + // CRLF joins and a BOM because the destination for an exported tracker is + // Excel, which otherwise reads the UTF-8 as the local ANSI codepage (so "£" + // and accents arrive mangled) and mis-splits LF-only rows. + const csv = + "\ufeff" + + [headers, ...rows].map((r) => r.map(escape).join(",")).join("\r\n"); + const blob = new Blob([csv], { type: "text/csv;charset=utf-8" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; @@ -178,7 +269,7 @@ async function fetchReferences() { const data = await gql(`query { jobAppReferences { ${REF_FIELDS} } }`); references.value = data.jobAppReferences; } catch (err) { - console.error(err); + fail(err); } } @@ -198,8 +289,9 @@ async function createReference() { ); references.value.push(data.createJobAppReference); refForm.value = { category: refForm.value.category, label: "", value: "" }; + error.value = ""; } catch (err) { - console.error(err); + fail(err); } } @@ -233,20 +325,23 @@ async function saveRefEdit(id) { const idx = references.value.findIndex((r) => r.id === id); if (idx !== -1) references.value[idx] = data.updateJobAppReference; editingRefId.value = null; + error.value = ""; } catch (err) { - console.error(err); + fail(err); } } -async function deleteReference(id) { +async function deleteReference(ref) { + if (!confirm(`Delete the reference "${ref.label}"?`)) return; try { await gql( `mutation DeleteJobAppReference($id: ID!) { deleteJobAppReference(id: $id) }`, - { id }, + { id: ref.id }, ); - references.value = references.value.filter((r) => r.id !== id); + references.value = references.value.filter((r) => r.id !== ref.id); + error.value = ""; } catch (err) { - console.error(err); + fail(err); } } @@ -258,16 +353,83 @@ function copyToClipboard(text) { navigator.clipboard.writeText(text); } +function statusLabel(status) { + return ( + STATUS_OPTIONS.find((s) => s.value === status?.toLowerCase())?.label ?? + status + ); +} + function statusClass(status) { - const map = { - Applied: "bg-blue-100 text-blue-800", - Screening: "bg-yellow-100 text-yellow-800", - Interview: "bg-violet-100 text-violet-800", - Offer: "bg-green-100 text-green-800", - Rejected: "bg-red-100 text-red-800", - Withdrawn: "bg-gray-100 text-gray-500", - }; - return map[status] ?? "bg-gray-200 text-gray-700"; + return `ja-badge-${status?.toLowerCase() ?? "unknown"}`; +} + +/** Whole days between a timestamp and now; null when there is no date. */ +function daysSince(iso) { + if (!iso) return null; + return Math.floor((Date.now() - new Date(iso).getTime()) / 86400000); +} + +function ageLabel(app) { + // createdAt is the fallback: an application logged without an applied date + // still has a meaningful age. + const days = daysSince(app.appliedAt ?? app.createdAt); + return days === null ? "—" : days === 0 ? "today" : `${days}d`; +} + +/** A row worth chasing: still open, and nothing has moved it in a fortnight. */ +function isStale(app) { + if (!OPEN_STATUSES.includes(app.status?.toLowerCase())) return false; + const days = daysSince(app.updatedAt ?? app.createdAt); + return days !== null && days >= STALE_DAYS; +} + +const statusCounts = computed(() => { + const counts = {}; + for (const app of applications.value) { + const key = app.status?.toLowerCase(); + counts[key] = (counts[key] ?? 0) + 1; + } + return counts; +}); + +const visibleApplications = computed(() => { + const q = search.value.trim().toLowerCase(); + const rows = applications.value.filter((app) => { + if (statusFilter.value && app.status?.toLowerCase() !== statusFilter.value) + return false; + if (!q) return true; + // Notes are searched because the email pipeline appends its findings + // there, making them the de-facto history of the application. + return [app.jobTitle, app.company, app.location, app.notes] + .filter(Boolean) + .some((field) => field.toLowerCase().includes(q)); + }); + + const dir = sortDir.value === "asc" ? 1 : -1; + return [...rows].sort((a, b) => { + const av = a[sortKey.value] ?? ""; + const bv = b[sortKey.value] ?? ""; + // Rows missing the sort field go last in either direction rather than + // clustering at whichever end empty-string happens to sort to. + if (!av && bv) return 1; + if (av && !bv) return -1; + if (av === bv) return 0; + return av > bv ? dir : -dir; + }); +}); + +function toggleSort(key) { + if (sortKey.value === key) { + sortDir.value = sortDir.value === "asc" ? "desc" : "asc"; + } else { + sortKey.value = key; + sortDir.value = "desc"; + } +} + +function toggleStatusFilter(status) { + statusFilter.value = statusFilter.value === status ? null : status; } onMounted(() => { @@ -292,6 +454,11 @@ onMounted(() => { +| Title | -Company | -Status | +Title | +Company | +Status | Location | -Applied | +Applied | Notes | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+
+ |
{
>
{{ app.jobTitle }}
|
- {{ app.company }} |
-
- {{
- app.status
- }}
+ | {{ app.company }} |
+
+
+ |
+ {{ app.location || "—" }} |
+
+ {{ ageLabel(app) }}
+ |
+
+ {{ app.notes ?? "" }}
|
- {{ app.location ?? "—" }} |
- {{ app.appliedAt ? app.appliedAt.substring(0, 10) : "—" }} |
- {{ app.notes ?? "" }} |
|
+ |
+
|
-
+ |
|
-
+ |
|
-
+ |
|
-
+ |
|
-
-
+
+
|
@@ -529,6 +759,9 @@ onMounted(() => {
|
+ No applications match this filter. +
No applications yet.
@@ -570,6 +803,20 @@ onMounted(() => { color: var(--color-ink-soft); } +.ja-error { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1rem; + padding: 0.5rem 0.75rem; + border: 1px solid #b91c1c; + border-radius: 4px; + background: #fef2f2; + color: #7f1d1d; + font-size: 0.85rem; +} + /* Forms */ .ja-form { display: flex; @@ -615,6 +862,65 @@ onMounted(() => { min-width: 0; } +.ja-edit-notes { + resize: vertical; + min-height: 3.5rem; +} + +/* Pipeline bar */ +.ja-pipeline { + display: flex; + gap: 0.4rem; + flex-wrap: wrap; + margin-bottom: 0.75rem; +} + +.ja-pipe-tile { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.1rem; + padding: 0.4rem 0.7rem; + border: 1px solid var(--color-line-soft); + border-radius: 4px; + background: var(--color-paper); + cursor: pointer; + min-width: 68px; +} + +.ja-pipe-tile:hover { + background: var(--color-paper-shade); +} + +.ja-pipe-active { + border-color: var(--color-ink); + background: var(--color-paper-shade); +} + +.ja-pipe-count { + font-size: 1rem; + font-weight: 600; + color: var(--color-ink-soft); +} + +.ja-pipe-label { + font-size: 0.7rem; + color: var(--color-ink-muted); +} + +.ja-filterbar { + display: flex; + align-items: center; + gap: 0.75rem; + margin-bottom: 0.75rem; +} + +.ja-count { + font-size: 0.8rem; + color: var(--color-ink-faint); + white-space: nowrap; +} + /* Applications table */ .ja-table { width: 100%; @@ -636,12 +942,27 @@ onMounted(() => { background: var(--color-paper-shade); } +.ja-sortable { + cursor: pointer; + user-select: none; +} + +.ja-sortable:hover { + color: var(--color-ink); +} + .ja-table tr:hover td { background: var(--color-paper-shade); } +/* Open for a fortnight with nothing moving — the follow-up queue. */ +.ja-stale td:first-child { + box-shadow: inset 3px 0 0 var(--color-ink-muted); +} + .ja-edit-row td { padding: 0.3rem 0.4rem; + vertical-align: top; } .ja-actions { @@ -666,13 +987,51 @@ onMounted(() => { text-decoration: underline; } -/* Status pill; colour classes come from statusClass() */ +/* Status pill, doubling as an inline select. Palette is CVLayout's paper + tokens with a per-status tint, rather than off-theme Tailwind colours. */ .ja-badge { display: inline-block; padding: 0.15rem 0.5rem; border-radius: 10px; font-size: 0.78rem; font-weight: 500; + border: 1px solid var(--color-line); + background: var(--color-paper-shade); + color: var(--color-ink-soft); +} + +.ja-badge-select { + cursor: pointer; + appearance: none; +} + +.ja-badge-applied { + background: #eef2ff; + color: #3730a3; +} +.ja-badge-screening { + background: #fefce8; + color: #854d0e; +} +.ja-badge-assessment { + background: #fff7ed; + color: #9a3412; +} +.ja-badge-interviewing { + background: #f5f3ff; + color: #5b21b6; +} +.ja-badge-offer { + background: #f0fdf4; + color: #166534; +} +.ja-badge-rejected { + background: #fef2f2; + color: #991b1b; +} +.ja-badge-withdrawn { + background: var(--color-paper-shade); + color: var(--color-ink-faint); } .ja-empty { @@ -743,4 +1102,50 @@ onMounted(() => { margin-top: 0.75rem; flex-wrap: wrap; } + +/* Seven columns plus an action cell will not fit a phone, so the table becomes + stacked cards with the header text carried by each cell's data-label. */ +@media (max-width: 640px) { + .ja-table thead { + display: none; + } + + .ja-table, + .ja-table tbody, + .ja-table tr, + .ja-table td { + display: block; + width: 100%; + } + + .ja-table tr { + margin-bottom: 0.75rem; + border: 1px solid var(--color-line-soft); + border-radius: 6px; + background: var(--color-paper); + } + + .ja-table td { + border-bottom: none; + padding: 0.3rem 0.6rem; + } + + .ja-table td[data-label]::before { + content: attr(data-label); + display: block; + font-size: 0.7rem; + text-transform: uppercase; + color: var(--color-ink-faint); + } + + .ja-notes-cell { + max-width: none; + white-space: pre-wrap; + overflow: visible; + } + + .ja-stale td:first-child { + box-shadow: inset 0 3px 0 var(--color-ink-muted); + } +}