diff --git a/internal/graph/resolver.go b/internal/graph/resolver.go index 1e88e93..c489559 100644 --- a/internal/graph/resolver.go +++ b/internal/graph/resolver.go @@ -10,14 +10,13 @@ import "adam-french.co.uk/job-tracker/internal/handlers" // Resolver is the root of the GraphQL schema and the only dependency every // resolver has. Rather than listing dependencies individually it holds the // same handlers.Store the REST handlers use, so GraphQL and REST share one -// database handle and one set of third-party caches. +// database handle and the same services. // // The generated code embeds *Resolver in per-type resolver structs, which is // why one-line `struct{ *Resolver }` declarations appear at the bottom of some // resolvers files. A type only gets one when a field of it needs a resolver: -// queryResolver and mutationResolver always, messageResolver and -// rowingResolver for their unsigned-to-Int fields. Most object types bind -// every field straight to the model and have none. +// queryResolver and mutationResolver always. Every object type binds its +// fields straight to the model and has none. type Resolver struct { Store *handlers.Store } diff --git a/internal/handlers/handle_job_capture.go b/internal/handlers/handle_job_capture.go index 786115e..9cc6a1d 100644 --- a/internal/handlers/handle_job_capture.go +++ b/internal/handlers/handle_job_capture.go @@ -152,16 +152,6 @@ type PostingExtractor interface { ExtractPosting(ctx context.Context, url, title, text string) (claude.JobPosting, error) } -// truncateRunes cuts s to at most max runes, on a rune boundary so the result -// is still valid UTF-8 for Postgres and for JSON. -func truncateRunes(s string, max int) string { - runes := []rune(s) - if len(runes) <= max { - return s - } - return string(runes[:max]) -} - // bindCapture decodes a size-limited JSON body, answering 400 itself when it // cannot. func bindCapture(ctx *gin.Context, into any) bool { @@ -192,7 +182,7 @@ func (store *Store) JobCaptureExtract(ctx *gin.Context) { } posting, err := store.Extractor.ExtractPosting(ctx.Request.Context(), - truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes)) + services.TruncateRunes(input.URL, 2000), services.TruncateRunes(input.Title, 500), services.TruncateRunes(text, maxPageRunes)) if err != nil { log.Println("Job extract failed:", err) var readErr *claude.ReadError @@ -215,7 +205,7 @@ func (store *Store) JobCapture(ctx *gin.Context) { if !bindCapture(ctx, &input) { return } - input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes) + input.Description = services.TruncateRunes(strings.TrimSpace(input.Description), maxPageRunes) app, action, err := services.UpsertJobApplication(store.DB, input, time.Now()) var invalid *services.JobInputError diff --git a/internal/handlers/handle_job_capture_test.go b/internal/handlers/handle_job_capture_test.go index bc748b5..b4fcf7f 100644 --- a/internal/handlers/handle_job_capture_test.go +++ b/internal/handlers/handle_job_capture_test.go @@ -140,15 +140,6 @@ func TestCaptureTokenAdminEndpoints(t *testing.T) { } } -func TestTruncateRunes(t *testing.T) { - if got := truncateRunes("££££", 2); got != "££" { - t.Fatalf("got %q; the cut must fall on a rune boundary", got) - } - if got := truncateRunes("short", 10); got != "short" { - t.Fatalf("got %q", got) - } -} - // fakeExtractor answers every page with posting and err, recording the // arguments it was called with. type fakeExtractor struct { diff --git a/internal/models/models.go b/internal/models/models.go index 8a620e7..483f60b 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -1,11 +1,3 @@ -package models - -import ( - "time" - - "gorm.io/gorm" -) - // Package models holds the GORM entities, which are also the GraphQL object // types: gqlgen.yml maps each GraphQL type straight onto the struct here, so // graph/model/ only contains generated input and payload types. That means @@ -23,6 +15,13 @@ import ( // - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the // two directly (graphql.UintID), so an `ID uint` field needs no resolver. // On the wire an id is a quoted decimal string, "12". +package models + +import ( + "time" + + "gorm.io/gorm" +) // JobAppReference is a reusable snippet for filling in job application forms // (a stock answer, a profile link, and so on), grouped by Category and @@ -41,11 +40,11 @@ type JobAppReference struct { // ProcessedEmail records that the email pipeline has already looked at a // message, so it is never classified twice. // -// Unlike every other model it has no DeletedAt and so is NOT soft deleted — -// the dedup check must see every historical row. Its CreatedAt also drives -// the next sync's time window, so the most recent row here is effectively the -// pipeline's cursor. A row is written even when classification failed, with -// Action "error", which means failures are never retried. +// Like JobLead it has no DeletedAt and so is NOT soft deleted — the dedup +// check must see every historical row. Its ReceivedAt drives the next sync's +// time window, so the newest row here is effectively the pipeline's cursor. A +// row is written even when classification failed, with Action "error"; see +// Attempts for how those are retried. type ProcessedEmail struct { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` diff --git a/internal/services/email_sync.go b/internal/services/email_sync.go index 836191a..4a1f06d 100644 --- a/internal/services/email_sync.go +++ b/internal/services/email_sync.go @@ -74,8 +74,6 @@ type EmailSyncService struct { mu sync.Mutex } -// Microsoft Graph API response types - // Microsoft Graph API response types. The IMAP backend parses raw RFC822 // messages into these same structs (see parseRawEmail) so that everything // downstream of fetchEmails is backend-agnostic. @@ -177,8 +175,8 @@ var statusOrder = map[string]int{ // Token persistence // SaveMSGraphToken persists an OAuth token to disk with 0600 permissions. -// Like the Spotify equivalent it copies into a local struct so the on-disk -// shape does not depend on the oauth2 package's own JSON tags. +// It copies into a local struct so the on-disk shape does not depend on the +// oauth2 package's own JSON tags. func SaveMSGraphToken(path string, tok *oauth2.Token) error { data := struct { AccessToken string `json:"access_token"` @@ -450,7 +448,6 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error { since = oldestRetryable.ReceivedAt } - // Fetch emails from Microsoft Graph emails, err := s.fetchEmails(ctx, since) if err != nil { return fmt.Errorf("fetching emails: %w", err) @@ -767,10 +764,6 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string } } - if app.Status == "" { - app.Status = "applied" - } - if err := s.DB.Create(&app).Error; err != nil { return "", nil, fmt.Errorf("creating job application: %w", err) } @@ -827,6 +820,13 @@ func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, return "updated", &existing.ID, nil } +// Whitespace patterns for cleanEmailBody. Tags are stripped with htmlAnyTag +// (job_sources.go). +var ( + emailSpaces = regexp.MustCompile(`[ \t]+`) + emailBlankRuns = regexp.MustCompile(`\n{3,}`) +) + // cleanEmailBody reduces an email body to plain-ish text before it is sent to // the classifier, cutting token cost and noise. // @@ -839,8 +839,7 @@ func cleanEmailBody(content string, contentType string) string { if strings.EqualFold(contentType, "html") { // Strip HTML tags - tagRegex := regexp.MustCompile(`<[^>]*>`) - text = tagRegex.ReplaceAllString(text, " ") + text = htmlAnyTag.ReplaceAllString(text, " ") // Decode common HTML entities replacer := strings.NewReplacer( @@ -856,10 +855,8 @@ func cleanEmailBody(content string, contentType string) string { } // Collapse whitespace - spaceRegex := regexp.MustCompile(`[ \t]+`) - text = spaceRegex.ReplaceAllString(text, " ") - nlRegex := regexp.MustCompile(`\n{3,}`) - text = nlRegex.ReplaceAllString(text, "\n\n") + text = emailSpaces.ReplaceAllString(text, " ") + text = emailBlankRuns.ReplaceAllString(text, "\n\n") text = strings.TrimSpace(text) // Cut everything from the first signature marker onwards. The idx > 0 @@ -953,8 +950,7 @@ func parseReceivedAt(raw string) time.Time { // saveProcessed writes the outcome of an attempt: updating the existing row // when this was a retry, inserting when it is the first attempt. Update is -// used rather than Save so the row keeps its original CreatedAt, which the -// fetch window depends on. +// used rather than Save so the row keeps its original CreatedAt. func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) { var err error if found { diff --git a/internal/services/job_leads.go b/internal/services/job_leads.go index 3703839..6e02841 100644 --- a/internal/services/job_leads.go +++ b/internal/services/job_leads.go @@ -10,6 +10,7 @@ import ( "sync" "time" "unicode" + "unicode/utf8" "adam-french.co.uk/job-tracker/internal/claude" "adam-french.co.uk/job-tracker/internal/models" @@ -432,7 +433,7 @@ func (s *JobLeadService) storeLeads(ctx context.Context, src models.JobSource, j // snippet in place rather than losing the lead. if job.detailID != "" && lead.Matched && lead.State == LeadNew { if full, err := s.fetchReedDescription(ctx, job.detailID); err == nil && full != "" { - lead.Description = truncateRunes(full, maxLeadRunes) + lead.Description = TruncateRunes(full, maxLeadRunes) } } fresh = append(fresh, lead) @@ -473,7 +474,7 @@ func newLead(src models.JobSource, job fetchedJob, filter leadFilter, tracked ma Company: company, Location: strings.TrimSpace(job.Location), URL: strings.TrimSpace(job.URL), - Description: truncateRunes(job.Description, maxLeadRunes), + Description: TruncateRunes(job.Description, maxLeadRunes), PostedAt: job.PostedAt, LastSeenAt: now, State: LeadNew, @@ -686,10 +687,10 @@ func containsWord(text, word string) bool { } start := from + i end := start + len(word) - before := []rune(text[:start]) - after := []rune(strings.TrimPrefix(text[end:], "s")) - if (len(before) == 0 || !isWordRune(before[len(before)-1])) && - (len(after) == 0 || !isWordRune(after[0])) { + before, _ := utf8.DecodeLastRuneInString(text[:start]) + after, _ := utf8.DecodeRuneInString(strings.TrimPrefix(text[end:], "s")) + // RuneError is what an empty side decodes to, and is not a word rune. + if !isWordRune(before) && !isWordRune(after) { return true } from = start + 1 @@ -777,7 +778,7 @@ func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSear } func (s *JobLeadService) scoreLead(ctx context.Context, profile string, lead *models.JobLead) (LeadScore, error) { - return s.Scorer.ScorePosting(ctx, truncateRunes(profile, maxProfileRunes), + return s.Scorer.ScorePosting(ctx, TruncateRunes(profile, maxProfileRunes), lead.JobTitle, lead.Company, lead.Location, lead.Description) } @@ -802,7 +803,7 @@ func LoadJobSearchProfile(db *gorm.DB) (*models.JobSearchProfile, error) { // SaveJobSearchProfile stores an edited profile, bounding the free text. func SaveJobSearchProfile(db *gorm.DB, profile *models.JobSearchProfile) error { profile.ID = jobSearchProfileID - profile.Profile = truncateRunes(strings.TrimSpace(profile.Profile), maxProfileRunes) + profile.Profile = TruncateRunes(strings.TrimSpace(profile.Profile), maxProfileRunes) profile.MinScore = min(max(profile.MinScore, 0), 100) return db.Save(profile).Error } diff --git a/internal/services/job_sources.go b/internal/services/job_sources.go index c69d57b..6a69493 100644 --- a/internal/services/job_sources.go +++ b/internal/services/job_sources.go @@ -491,9 +491,9 @@ func htmlToText(content string) string { return strings.TrimSpace(strings.Join(lines, "\n")) } -// truncateRunes cuts s to at most max runes, on a rune boundary so the result +// TruncateRunes cuts s to at most max runes, on a rune boundary so the result // is still valid UTF-8 for Postgres and for JSON. -func truncateRunes(s string, max int) string { +func TruncateRunes(s string, max int) string { runes := []rune(s) if len(runes) <= max { return s diff --git a/internal/services/job_sources_test.go b/internal/services/job_sources_test.go index b2912eb..10ae580 100644 --- a/internal/services/job_sources_test.go +++ b/internal/services/job_sources_test.go @@ -279,3 +279,12 @@ func TestWithWorkplace(t *testing.T) { } } } + +func TestTruncateRunes(t *testing.T) { + if got := TruncateRunes("££££", 2); got != "££" { + t.Fatalf("got %q; the cut must fall on a rune boundary", got) + } + if got := TruncateRunes("short", 10); got != "short" { + t.Fatalf("got %q", got) + } +} diff --git a/internal/services/job_upsert.go b/internal/services/job_upsert.go index 592b2ec..65d737c 100644 --- a/internal/services/job_upsert.go +++ b/internal/services/job_upsert.go @@ -101,7 +101,7 @@ func firstApplication(query *gorm.DB) (*models.JobApplication, error) { } // JobCaptureInput is a posting to add to the tracker. Its JSON form is the -// body of POST /jobs/capture: the popup's fields. +// body of POST /jobs/api/capture: the popup's fields. type JobCaptureInput struct { JobTitle string `json:"jobTitle"` Company string `json:"company"` diff --git a/web/src/api.js b/web/src/api.js index 03a0ee5..5c7593c 100644 --- a/web/src/api.js +++ b/web/src/api.js @@ -35,12 +35,11 @@ export class ApiError extends Error { * @param {string} method * @param {string} path route below the API base, with its leading slash * @param {object} [options] - * @param {*} [options.body] JSON-serialisable body, or a FormData for - * multipart uploads (axios sets the boundary itself) + * @param {*} [options.body] JSON-serialisable body * @param {string} [options.fallback] message to use when the backend sent no * `error` string — callers pass the sentence their UI shows - * Any other option (`headers`, `params`, `onUploadProgress`, `signal`, …) is - * handed to axios unchanged. + * Any other option (`headers`, `params`, `signal`, …) is handed to axios + * unchanged. */ async function request(method, path, { body, fallback, ...config } = {}) { try { @@ -67,6 +66,4 @@ export const api = { get: (path, options) => request("get", path, options), delete: (path, options) => request("delete", path, options), post: (path, body, options) => request("post", path, { ...options, body }), - put: (path, body, options) => request("put", path, { ...options, body }), - patch: (path, body, options) => request("patch", path, { ...options, body }), };