Add a job leads inbox that finds and scores postings
Test and deploy / test (push) Successful in 1m55s
Test and deploy / deploy (push) Successful in 59s

The tracker recorded applications but could not find jobs. A new
pipeline (services/job_leads.go, job_sources.go) polls a watch list of
sources on a timer or on request, files unseen postings as leads, marks
which pass a keyword and location pre-filter, and has Claude score those
against a single search profile through a fourth internal Python route,
/internal/jobs/score.

Sources are Greenhouse, Lever and Ashby company boards (public JSON) and
Adzuna and Reed keyword searches (API keys). The two search fetchers are
written from the providers' documentation and tested only against stubs.

Leads are their own table, not a job status, and are not soft deleted:
the (source_kind, external_id) index is the dedup, so a dismissed lead
has to remain a row. A lead reaches the tracker only by promotion, which
goes through UpsertJobApplication. That upsert moves from the capture
handler into services so promotion and the fetcher can share it; the
capture endpoint's behaviour is unchanged.

/cv/leads is the page: inbox, watch list and profile form. The timer is
off unless JOB_LEADS_ENABLED=true and never runs at start-up, so a
deploy spends no Claude calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-12 15:03:46 +01:00
co-authored by Claude Opus 5.5
parent 810d3118b3
commit af50e6c8ab
40 changed files with 7295 additions and 407 deletions
+65 -5
View File
@@ -245,9 +245,10 @@ the posting open in the browser to the job tracker.
(`/internal/jobs/extract`, see [Calling the Python service](#calling-the-python-service)).
Stores nothing.
- `POST /jobs/capture` — an **upsert**. A posting is matched by its canonical
URL (`canonicalJobURL` strips tracking parameters and folds LinkedIn's
URL (`services.CanonicalJobURL` strips tracking parameters and folds LinkedIn's
several URL shapes into one), then by `(company, job title)` the way the
email pipeline matches. A repeat capture only ever adds: status moves
email pipeline matches (`services.UpsertJobApplication`, shared with lead
promotion). A repeat capture only ever adds: status moves
forwards, empty fields are filled, nothing is overwritten.
The upsert is what keeps this and the email pipeline from making two rows for
@@ -255,10 +256,61 @@ one application. It is not watertight: the pipeline still matches on the exact
title, so a posting captured as "Senior Engineer" whose confirmation email
says "Senior Engineer (Platform)" becomes a second row.
### Job leads
Where the tracker records applications, this finds postings. It is GraphQL
throughout (`graph/schema/job_lead.graphql`, all `@admin`) with the work in
`services/job_leads.go` and `services/job_sources.go`; the page is `/cv/leads`.
- **Three tables.** `JobSource` is one thing to poll: a company's board on
Greenhouse, Lever or Ashby (public JSON, no key), or a keyword search on
Adzuna or Reed (keys in `.env`). `JobLead` is one posting found. It is
**not soft deleted**, like `ProcessedEmail`: the unique index on
`(source_kind, external_id)` is the dedup, and it only keeps a dismissed
lead dismissed if that lead is still a row. `JobSearchProfile` is a single
row: the profile text, three keyword lists and a minimum score.
- **A run** (`JobLeadService.Run`) is fetch → store → pre-filter → score.
Every enabled source is polled; one failing records its error on the source
and the rest carry on. Postings not seen before become leads; ones already
known only have `last_seen_at` moved. A posting whose canonical URL is
already in the tracker is filed as `promoted`, linked to that application,
so the inbox never offers it.
- **The pre-filter** is keywords on the title and location, no Claude. It
exists because a company board is mostly irrelevant, and it decides which
leads are shown and which cost a call. `matched` is recomputed for every
inbox lead on each run, so editing the keywords applies to old leads too.
- **Scoring** sends each matched, unscored lead and the profile text to the
Python service's `/internal/jobs/score`. At most 40 a run, newest first; a
lead Claude cannot score is retried on three runs and then left. With an
empty profile nothing is scored. If scoring is unavailable (no API key,
Python down) the run stops scoring without spending an attempt on any lead.
- **When it runs.** `JOB_LEADS_ENABLED=true` starts a timer
(`JOB_LEADS_INTERVAL`, default `6h`); it does not run at start-up, so a
deploy spends nothing. The `runJobLeadSync` mutation starts a run in a
goroutine and returns at once, whether or not the timer is on, and
`jobLeadSyncStatus` reports on it — a run can take minutes, so unlike
`POST /email/sync` it does not hold the request open. The status is in
memory and resets on restart.
- **Promotion** (`promoteJobLead`) is the only way a lead reaches the tracker.
It calls `services.UpsertJobApplication` with status `saved`, the lead's
text and a notes line carrying the score — the same upsert as the capture
endpoint, so a posting captured from the browser in the meantime is linked
to, not duplicated.
The Adzuna and Reed response structs were written from the providers'
documentation, not against live responses (they need keys). If one of those
sources reports a decode error or zero results, compare its struct in
`job_sources.go` with a real reply first. Adzuna only returns a snippet of
each description, so its leads are scored on less text.
Most of this needs Postgres and has no unit test: what is tested is the
fetchers (against stub servers), the pre-filter, how a fetched posting becomes
a row, and the scoring call.
## Calling the Python service
Every Claude call the site makes lives in the Python service; this backend has
no Anthropic client and does not read `CLAUDE_API_KEY`. It reaches three
no Anthropic client and does not read `CLAUDE_API_KEY`. It reaches four
internal routes directly over the Docker network
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
nginx, which answers 404 for `/py/internal/`:
@@ -267,9 +319,10 @@ nginx, which answers 404 for `/py/internal/`:
| --- | --- | --- | --- |
| `/internal/rowing/read` | `POST /rowing` (`handlers/handle_rowing.go`) | `{media_type, data}` (image, base64) | `{timeMinutes, timeSeconds, distance}` |
| `/internal/jobs/extract` | `POST /jobs/capture/extract` (`handlers/handle_job_capture.go`) | `{url, title, text}` | `{jobTitle, company, location, notes}` |
| `/internal/jobs/score` | the lead pipeline (`services/job_leads.go`) | `{profile, jobTitle, company, location, description}` | `{score, reasons}` |
| `/internal/email/classify` | the email pipeline (`services/email_sync.go`) | `{message}` | `EmailAnalysis` (below) |
All three go through one function, `services.CallPython[T]` in
All four go through one function, `services.CallPython[T]` in
`services/python_call.go`: marshal the body, POST it, decode a 200 into `T`.
It has the one HTTP client (two-minute timeout, above the Python side's own
worst case of a retried Claude call) and the one rule for failures:
@@ -320,6 +373,11 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
matching on (company, job title), and the forward-only status rule. Any
failure of the call, whatever its status code, is a failed attempt at that
email.
- **job_leads.go** / **job_sources.go** — the job-lead pipeline. See
[Job leads](#job-leads).
- **job_upsert.go** — `UpsertJobApplication`, the one way a posting is added
to the tracker without duplicating a row: used by the capture endpoint and
by promoting a lead.
- **python_call.go** — `CallPython`, the one way to reach the Python service's
internal routes. See [Calling the Python service](#calling-the-python-service).
- **job_status.go** — how the `JobStatus` GraphQL enum is read and written.
@@ -460,10 +518,12 @@ warning block at the end of the file.
| `SEED_DB` | seed dev test data (never in production) |
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the three Claude routes (default `python:8000`) |
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the four Claude routes (default `python:8000`) |
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) |
| `JOB_LEADS_ENABLED` / `JOB_LEADS_INTERVAL` | lead pipeline timer (default off, `6h`) |
| `ADZUNA_APP_ID` / `ADZUNA_APP_KEY` / `REED_API_KEY` | keyword-search lead sources; optional |
| `MSGRAPH_CLIENT_ID` / `_SECRET` / `_TENANT_ID` / `_REDIRECT_URI` | Microsoft Graph backend |
| `IMAP_HOST` / `_PORT` / `_EMAIL` / `_PASSWORD` | IMAP backend |
+12
View File
@@ -89,6 +89,18 @@ models:
fields:
deletedAt:
resolver: false
JobSource:
model:
- adam-french.co.uk/backend/models.JobSource
fields:
deletedAt:
resolver: false
JobLead:
model:
- adam-french.co.uk/backend/models.JobLead
JobSearchProfile:
model:
- adam-french.co.uk/backend/models.JobSearchProfile
Place:
model:
- adam-french.co.uk/backend/models.Place
+11 -6
View File
@@ -187,12 +187,17 @@ func TestSignedInMutationsArePinned(t *testing.T) {
// `spotifyNeedsReauth` is false for non-admins.
func TestGuardedQueriesArePinned(t *testing.T) {
want := map[string]string{
"users": "admin",
"user": "admin",
"jobApplications": "admin",
"jobApplication": "admin",
"jobAppReferences": "admin",
"places": "signedIn",
"users": "admin",
"user": "admin",
"jobApplications": "admin",
"jobApplication": "admin",
"jobAppReferences": "admin",
"jobSources": "admin",
"jobLeads": "admin",
"jobLead": "admin",
"jobSearchProfile": "admin",
"jobLeadSyncStatus": "admin",
"places": "signedIn",
}
got := map[string]string{}
for _, field := range schemaUnderTest().Query.Fields {
+2972 -23
View File
File diff suppressed because it is too large Load Diff
+204
View File
@@ -0,0 +1,204 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"fmt"
"strings"
"time"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
)
// CreateJobSource is the resolver for the createJobSource field.
func (r *mutationResolver) CreateJobSource(ctx context.Context, input model.CreateJobSourceInput) (*models.JobSource, error) {
src := models.JobSource{Kind: input.Kind, Label: input.Label, Enabled: true}
if input.Token != nil {
src.Token = *input.Token
}
if input.Query != nil {
src.Query = *input.Query
}
if input.Location != nil {
src.Location = *input.Location
}
if input.Enabled != nil {
src.Enabled = *input.Enabled
}
if err := services.ValidateJobSource(&src); err != nil {
return nil, err
}
if err := r.Store.DB.Create(&src).Error; err != nil {
return nil, err
}
return &src, nil
}
// UpdateJobSource is the resolver for the updateJobSource field.
func (r *mutationResolver) UpdateJobSource(ctx context.Context, id int, input model.UpdateJobSourceInput) (*models.JobSource, error) {
// Partial update, as in UpdateJobApplication: a nil field is untouched.
// The merged row is validated as a whole, because whether a token or a
// query is required depends on the kind, which may itself be changing.
var src models.JobSource
if err := r.Store.DB.First(&src, id).Error; err != nil {
return nil, err
}
if input.Kind != nil {
src.Kind = *input.Kind
}
if input.Label != nil {
src.Label = *input.Label
}
if input.Token != nil {
src.Token = *input.Token
}
if input.Query != nil {
src.Query = *input.Query
}
if input.Location != nil {
src.Location = *input.Location
}
if input.Enabled != nil {
src.Enabled = *input.Enabled
}
if err := services.ValidateJobSource(&src); err != nil {
return nil, err
}
// Named columns rather than Save: the fetcher writes last_fetched_at,
// last_count and last_error on this row during a run, and saving the
// whole struct loaded above would put stale values back over them.
if err := r.Store.DB.Model(&src).
Select("Kind", "Label", "Token", "Query", "Location", "Enabled").
Updates(&src).Error; err != nil {
return nil, err
}
return &src, nil
}
// DeleteJobSource is the resolver for the deleteJobSource field.
func (r *mutationResolver) DeleteJobSource(ctx context.Context, id int) (bool, error) {
// Loaded first so a missing id is an error; see DeleteJobApplication.
// The source's leads are deliberately left alone: they are still real
// postings, and deleting them would let a re-added source file every one
// of them again, dismissed ones included.
var src models.JobSource
if err := r.Store.DB.First(&src, id).Error; err != nil {
return false, err
}
if err := r.Store.DB.Delete(&src).Error; err != nil {
return false, err
}
return true, nil
}
// DismissJobLead is the resolver for the dismissJobLead field.
func (r *mutationResolver) DismissJobLead(ctx context.Context, id int) (*models.JobLead, error) {
return r.setLeadState(id, services.LeadNew, services.LeadDismissed)
}
// RestoreJobLead is the resolver for the restoreJobLead field.
func (r *mutationResolver) RestoreJobLead(ctx context.Context, id int) (*models.JobLead, error) {
return r.setLeadState(id, services.LeadDismissed, services.LeadNew)
}
// PromoteJobLead is the resolver for the promoteJobLead field.
func (r *mutationResolver) PromoteJobLead(ctx context.Context, id int) (*models.JobLead, error) {
return services.PromoteJobLead(r.Store.DB, uint(id), time.Now())
}
// UpdateJobSearchProfile is the resolver for the updateJobSearchProfile field.
func (r *mutationResolver) UpdateJobSearchProfile(ctx context.Context, input model.UpdateJobSearchProfileInput) (*models.JobSearchProfile, error) {
profile, err := services.LoadJobSearchProfile(r.Store.DB)
if err != nil {
return nil, err
}
if input.Profile != nil {
profile.Profile = *input.Profile
}
if input.IncludeKeywords != nil {
profile.IncludeKeywords = strings.TrimSpace(*input.IncludeKeywords)
}
if input.ExcludeKeywords != nil {
profile.ExcludeKeywords = strings.TrimSpace(*input.ExcludeKeywords)
}
if input.Locations != nil {
profile.Locations = strings.TrimSpace(*input.Locations)
}
if input.MinScore != nil {
profile.MinScore = *input.MinScore
}
if err := services.SaveJobSearchProfile(r.Store.DB, profile); err != nil {
return nil, err
}
return profile, nil
}
// RunJobLeadSync is the resolver for the runJobLeadSync field.
func (r *mutationResolver) RunJobLeadSync(ctx context.Context) (bool, error) {
if r.Store.JobLeads == nil {
return false, fmt.Errorf("job leads are not configured")
}
return r.Store.JobLeads.RunInBackground(), nil
}
// JobSources is the resolver for the jobSources field.
func (r *queryResolver) JobSources(ctx context.Context) ([]*models.JobSource, error) {
var sources []*models.JobSource
if err := r.Store.DB.Order("label ASC, id ASC").Find(&sources).Error; err != nil {
return nil, err
}
return sources, nil
}
// JobLeads is the resolver for the jobLeads field.
func (r *queryResolver) JobLeads(ctx context.Context, state *string, includeUnmatched *bool) ([]*models.JobLead, error) {
// Omit, not Select: every column but the description, which is tens of
// kilobytes a row and is fetched one lead at a time through jobLead. A
// client that asks for description here gets "".
query := r.Store.DB.Omit("description")
if state != nil {
query = query.Where("state = ?", *state)
}
if includeUnmatched == nil || !*includeUnmatched {
// A promoted or dismissed lead is shown whatever the filter now says
// about it; `matched` only decides what the inbox offers.
query = query.Where("matched = ? OR state <> ?", true, services.LeadNew)
}
var leads []*models.JobLead
// Best first, unscored after scored, newest first within a score. The
// limit is a backstop for includeUnmatched on a database holding several
// whole boards.
if err := query.Order("score DESC NULLS LAST, created_at DESC, id DESC").Limit(2000).Find(&leads).Error; err != nil {
return nil, err
}
return leads, nil
}
// JobLead is the resolver for the jobLead field.
func (r *queryResolver) JobLead(ctx context.Context, id int) (*models.JobLead, error) {
var lead models.JobLead
if err := r.Store.DB.First(&lead, id).Error; err != nil {
return nil, err
}
return &lead, nil
}
// JobSearchProfile is the resolver for the jobSearchProfile field.
func (r *queryResolver) JobSearchProfile(ctx context.Context) (*models.JobSearchProfile, error) {
return services.LoadJobSearchProfile(r.Store.DB)
}
// JobLeadSyncStatus is the resolver for the jobLeadSyncStatus field.
func (r *queryResolver) JobLeadSyncStatus(ctx context.Context) (*model.JobLeadSyncStatus, error) {
if r.Store.JobLeads == nil {
return &model.JobLeadSyncStatus{LastError: "job leads are not configured"}, nil
}
status := r.Store.JobLeads.Status()
return &model.JobLeadSyncStatus{Running: status.Running, LastRunAt: status.LastRunAt, LastError: status.LastError}, nil
}
+31
View File
@@ -0,0 +1,31 @@
package graph
import (
"fmt"
"adam-french.co.uk/backend/models"
)
// setLeadState moves a lead from one state to another and returns it. It
// lives here, not in job_lead.resolvers.go, because gqlgen moves anything in
// a resolvers file that is not a resolver to the bottom on regeneration.
//
// The move is refused unless the lead is in `from`, which is what stops a
// promoted lead being dismissed or restored: its application exists, and
// flipping the lead would only make the inbox disagree with the tracker.
func (r *mutationResolver) setLeadState(id int, from, to string) (*models.JobLead, error) {
var lead models.JobLead
if err := r.Store.DB.First(&lead, id).Error; err != nil {
return nil, err
}
if lead.State == to {
return &lead, nil
}
if lead.State != from {
return nil, fmt.Errorf("a %s lead cannot be made %s", lead.State, to)
}
if err := r.Store.DB.Model(&lead).Update("state", to).Error; err != nil {
return nil, err
}
return &lead, nil
}
+32
View File
@@ -48,6 +48,15 @@ type CreateJobApplicationInput struct {
Description *string `json:"description,omitempty"`
}
type CreateJobSourceInput struct {
Kind string `json:"kind"`
Label string `json:"label"`
Token *string `json:"token,omitempty"`
Query *string `json:"query,omitempty"`
Location *string `json:"location,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
}
type CreatePlaceInput struct {
Title string `json:"title"`
Location *string `json:"location,omitempty"`
@@ -78,6 +87,12 @@ type GiteaFeedItem struct {
CreatedAt time.Time `json:"createdAt"`
}
type JobLeadSyncStatus struct {
Running bool `json:"running"`
LastRunAt *time.Time `json:"lastRunAt,omitempty"`
LastError string `json:"lastError"`
}
type LoginInput struct {
Username string `json:"username"`
Password string `json:"password"`
@@ -149,6 +164,23 @@ type UpdateJobApplicationInput struct {
Description *string `json:"description,omitempty"`
}
type UpdateJobSearchProfileInput struct {
Profile *string `json:"profile,omitempty"`
IncludeKeywords *string `json:"includeKeywords,omitempty"`
ExcludeKeywords *string `json:"excludeKeywords,omitempty"`
Locations *string `json:"locations,omitempty"`
MinScore *int `json:"minScore,omitempty"`
}
type UpdateJobSourceInput struct {
Kind *string `json:"kind,omitempty"`
Label *string `json:"label,omitempty"`
Token *string `json:"token,omitempty"`
Query *string `json:"query,omitempty"`
Location *string `json:"location,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
}
type UpdatePlaceInput struct {
Title *string `json:"title,omitempty"`
Location *string `json:"location,omitempty"`
+4 -3
View File
@@ -1,7 +1,8 @@
# Job application tracker. Rows come from these mutations, automatically from
# the email sync pipeline (backend/services/email_sync.go), or from the browser
# capture userscript (backend/handlers/handle_job_capture.go). These are
# private data, so the queries here are @admin as well as the mutations.
# the email sync pipeline (backend/services/email_sync.go), from the browser
# capture userscript (backend/handlers/handle_job_capture.go), or from
# promoting a lead (job_lead.graphql). These are private data, so the queries
# here are @admin as well as the mutations.
#
# description is the captured posting text. It can run to tens of kilobytes,
# so the tracker's list query leaves it out and asks for it per row.
+133
View File
@@ -0,0 +1,133 @@
# Job leads: postings found automatically, as opposed to applications being
# tracked (job_application.graphql). The fetcher in
# backend/services/job_leads.go polls each JobSource, files what it finds as
# JobLead rows and has Claude score them against the JobSearchProfile. A lead
# reaches the tracker only when it is promoted from the leads page.
#
# All of it is private, so every field here is @admin, queries included.
# One place to poll. `kind` is one of greenhouse, lever, ashby (a company's
# board: `token` is its slug and `label` the company name) or adzuna, reed (a
# keyword search: `query` and `location`, with `label` only a display name).
# It is a String rather than an enum because the resolver validates it and
# the list is the fetcher's to extend (services/job_sources.go).
#
# The last* fields are written by the fetcher, never by a mutation.
type JobSource {
id: ID!
createdAt: Time!
updatedAt: Time!
kind: String!
label: String!
token: String!
query: String!
location: String!
enabled: Boolean!
lastFetchedAt: Time
lastCount: Int!
lastError: String!
}
input CreateJobSourceInput {
kind: String!
label: String!
token: String
query: String
location: String
enabled: Boolean
}
input UpdateJobSourceInput {
kind: String
label: String
token: String
query: String
location: String
enabled: Boolean
}
# description is the posting's full text, tens of kilobytes on some boards,
# so the list query on the leads page leaves it out and asks per row — the
# same arrangement as JobApplication.description.
#
# state is new, dismissed or promoted. score (0-100) and scoreReasons are
# null until Claude has scored the lead, which only happens to matched ones.
type JobLead {
id: ID!
createdAt: Time!
sourceKind: String!
jobTitle: String!
company: String!
location: String!
url: String!
description: String!
postedAt: Time
lastSeenAt: Time!
matched: Boolean!
state: String!
score: Int
scoreReasons: String
jobAppId: ID
}
# The single row a lead is judged against. profile is free text sent to
# Claude with each posting; the three keyword lists hold one entry per line
# and drive the pre-filter; minScore is the inbox's display threshold.
type JobSearchProfile {
updatedAt: Time!
profile: String!
includeKeywords: String!
excludeKeywords: String!
locations: String!
minScore: Int!
}
input UpdateJobSearchProfileInput {
profile: String
includeKeywords: String
excludeKeywords: String
locations: String
minScore: Int
}
# lastRunAt and lastError describe the most recent run in this backend
# process; both reset when it restarts.
type JobLeadSyncStatus {
running: Boolean!
lastRunAt: Time
lastError: String!
}
extend type Query {
jobSources: [JobSource!]! @admin
# state filters to one of new, dismissed, promoted; omitted returns all.
# Leads that failed the pre-filter are left out unless includeUnmatched.
jobLeads(state: String, includeUnmatched: Boolean): [JobLead!]! @admin
jobLead(id: ID!): JobLead @admin
jobSearchProfile: JobSearchProfile! @admin
jobLeadSyncStatus: JobLeadSyncStatus! @admin
}
extend type Mutation {
createJobSource(input: CreateJobSourceInput!): JobSource! @admin
updateJobSource(id: ID!, input: UpdateJobSourceInput!): JobSource! @admin
# Errors on an id that does not exist, like the other deletes; the Boolean
# is only ever true. The source's leads are kept.
deleteJobSource(id: ID!): Boolean! @admin
dismissJobLead(id: ID!): JobLead! @admin
# Puts a dismissed lead back in the inbox. A promoted lead cannot be
# restored: its application exists, and is managed on the tracker.
restoreJobLead(id: ID!): JobLead! @admin
# Adds the lead to the tracker as a saved application — or, if the posting
# is already tracked, links to that row instead of making a second — and
# returns the lead, now promoted, with jobAppId set.
promoteJobLead(id: ID!): JobLead! @admin
updateJobSearchProfile(input: UpdateJobSearchProfileInput!): JobSearchProfile! @admin
# Starts a fetch-and-score run in the background and returns at once: true
# if it started, false if one was already running. Poll jobLeadSyncStatus
# to see it finish.
runJobLeadSync: Boolean! @admin
}
+18 -220
View File
@@ -5,15 +5,12 @@ import (
"errors"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// Job capture: the three endpoints behind vue/public/job-capture.user.js,
@@ -115,65 +112,6 @@ func (store *Store) RevokeCaptureToken(ctx *gin.Context) {
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
}
// trackingParams are query parameters that say how the visitor arrived, not
// which posting this is. Anything not listed is kept: ATS boards identify the
// job in the query string often enough (gh_jid, jk, jobId) that dropping
// unknown parameters would merge different postings.
var trackingParams = map[string]bool{
"trk": true, "trackingid": true, "refid": true, "ebp": true,
"gh_src": true, "lever-source": true, "lever-origin": true,
"source": true, "src": true, "ref": true,
"fbclid": true, "gclid": true, "mc_cid": true, "mc_eid": true,
}
// linkedInJobPath matches both forms of a LinkedIn posting path: the bare
// /jobs/view/123 and the public slug form /jobs/view/some-title-at-co-123.
var linkedInJobPath = regexp.MustCompile(`^/jobs/view/(?:.*-)?(\d+)/?$`)
// canonicalJobURL reduces a posting URL to a form that is the same however
// the page was reached, so it can serve as the key that decides whether a
// posting is already tracked. ok is false for anything that is not an
// absolute http(s) URL.
//
// LinkedIn gets its own rule because the same posting appears under several
// paths (search results, collections, the recommended feed), all carrying the
// id in ?currentJobId= rather than in the path.
func canonicalJobURL(raw string) (canonical string, ok bool) {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return "", false
}
host := strings.ToLower(u.Host)
query := u.Query()
if host == "linkedin.com" || strings.HasSuffix(host, ".linkedin.com") {
id := query.Get("currentJobId")
if m := linkedInJobPath.FindStringSubmatch(u.Path); m != nil {
id = m[1]
}
if id != "" && strings.Trim(id, "0123456789") == "" {
return "https://www.linkedin.com/jobs/view/" + id + "/", true
}
}
for key := range query {
lowered := strings.ToLower(key)
if trackingParams[lowered] || strings.HasPrefix(lowered, "utm_") {
query.Del(key)
}
}
out := url.URL{
Scheme: u.Scheme,
Host: host,
// A trailing slash is not a different posting.
Path: strings.TrimRight(u.Path, "/"),
// Encode sorts by key, so parameter order does not matter either.
RawQuery: query.Encode(),
}
return out.String(), true
}
// capturedJob is the slice of an application the userscript needs back: enough
// to show "already tracked as …" and no more. The token is not meant to be
// able to read the tracker, so notes and the description stay out of it.
@@ -188,38 +126,16 @@ func capturedJobOf(app *models.JobApplication) *capturedJob {
return &capturedJob{ID: app.ID, JobTitle: app.JobTitle, Company: app.Company, Status: app.Status}
}
// findByURL returns the newest live application stored under this posting's
// URL, or nil. The raw form is tried as well as the canonical one because rows
// typed into the tracker by hand hold whatever was pasted.
func (store *Store) findByURL(canonical, raw string) (*models.JobApplication, error) {
return firstApplication(store.DB.Where("url IN ?", []string{canonical, strings.TrimSpace(raw)}))
}
// firstApplication returns the newest row the query matches, or nil for none.
// Limit(1).Find rather than First: a miss is the ordinary answer here (every
// badge lookup on an untracked posting), and First reports one as
// ErrRecordNotFound, which GORM writes to the log as an error each time.
func firstApplication(query *gorm.DB) (*models.JobApplication, error) {
var apps []models.JobApplication
if err := query.Order("created_at DESC, id DESC").Limit(1).Find(&apps).Error; err != nil {
return nil, err
}
if len(apps) == 0 {
return nil, nil
}
return &apps[0], nil
}
// JobCaptureStatus backs GET /jobs/capture/status?url=. It is what lets the
// userscript show a posting's tracked status instead of an "add" button.
func (store *Store) JobCaptureStatus(ctx *gin.Context) {
raw := ctx.Query("url")
canonical, ok := canonicalJobURL(raw)
canonical, ok := services.CanonicalJobURL(raw)
if !ok {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
return
}
app, err := store.findByURL(canonical, raw)
app, err := services.FindApplicationByURL(store.DB, canonical, raw)
if err != nil {
log.Println("Job capture status lookup failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
@@ -308,146 +224,28 @@ func (store *Store) JobCaptureExtract(ctx *gin.Context) {
ctx.JSON(http.StatusOK, posting)
}
// captureInput is the body of POST /jobs/capture: the popup's fields.
type captureInput struct {
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Location string `json:"location"`
URL string `json:"url"`
Status string `json:"status"`
Notes string `json:"notes"`
Description string `json:"description"`
}
func nonEmpty(p *string) bool { return p != nil && strings.TrimSpace(*p) != "" }
// mergeCapture folds a repeat capture into the application it matched and
// reports whether anything changed.
//
// It only ever adds: the status moves forwards or not at all (the same rule
// the email pipeline follows, so re-capturing a posting marked "saved" cannot
// pull an interviewing application back), and a field already holding a value
// is left alone, because the row may have been corrected by hand since. Title
// and company are never touched — they are the key the email pipeline matches
// on.
func mergeCapture(app *models.JobApplication, in captureInput, now time.Time) bool {
changed := false
if status := services.NormalizeStatus(in.Status); services.StatusAdvances(app.Status, status) {
app.Status = status
changed = true
}
// Saved-then-applied is the common path here, and the moment of the
// second capture is the application date.
if app.AppliedAt == nil && app.Status == "applied" {
app.AppliedAt = &now
changed = true
}
fill := func(field **string, value string) {
if value != "" && !nonEmpty(*field) {
*field = &value
changed = true
}
}
fill(&app.Location, in.Location)
fill(&app.URL, in.URL)
fill(&app.Description, in.Description)
// Notes accumulate, as they do when the pipeline updates a row, but a
// repeat capture of the same page must not append the same line twice.
if in.Notes != "" {
switch {
case !nonEmpty(app.Notes):
app.Notes = &in.Notes
changed = true
case !strings.Contains(*app.Notes, in.Notes):
combined := *app.Notes + "\n" + in.Notes
app.Notes = &combined
changed = true
}
}
return changed
}
// JobCapture backs POST /jobs/capture, an upsert.
//
// A posting already in the tracker is updated in place rather than added
// again. That matters beyond tidiness: the email pipeline identifies an
// application by (company, job title), so two rows for one posting means the
// confirmation email advances only one of them.
//
// Match order is the posting URL, then (company, job title) compared the way
// the pipeline compares them. Only live rows match — unlike the pipeline's
// lookup, which also sees deleted rows so that an email cannot resurrect one.
// A capture is a deliberate act, so capturing a posting whose row was deleted
// makes a new row.
// JobCapture backs POST /jobs/capture, an upsert: a posting already in the
// tracker is updated in place rather than added again. The matching and
// merging rules are services.UpsertJobApplication's; this handler owns the
// request body and the status codes.
func (store *Store) JobCapture(ctx *gin.Context) {
var input captureInput
var input services.JobCaptureInput
if !bindCapture(ctx, &input) {
return
}
input.JobTitle = strings.TrimSpace(input.JobTitle)
input.Company = strings.TrimSpace(input.Company)
input.Location = strings.TrimSpace(input.Location)
input.Notes = strings.TrimSpace(input.Notes)
input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
if input.JobTitle == "" || input.Company == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jobTitle and company are required"})
return
}
rawURL := input.URL
if strings.TrimSpace(rawURL) != "" {
canonical, ok := canonicalJobURL(rawURL)
if !ok {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
return
}
input.URL = canonical
} else {
input.URL = ""
}
var existing *models.JobApplication
var err error
if input.URL != "" {
existing, err = store.findByURL(input.URL, rawURL)
}
if err == nil && existing == nil {
existing, err = firstApplication(store.DB.Where(
"LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", input.Company, input.JobTitle))
}
if err != nil {
log.Println("Job capture lookup failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
return
}
now := time.Now()
if existing != nil {
action := "unchanged"
if mergeCapture(existing, input, now) {
if err := store.DB.Save(existing).Error; err != nil {
log.Println("Job capture update failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
return
}
action = "updated"
}
ctx.JSON(http.StatusOK, gin.H{"action": action, "application": capturedJobOf(existing)})
return
}
// A new row is the merge of the capture into an empty application, which
// keeps the two paths agreeing on what an empty field and "applied" mean.
// The empty status counts as unknown, so any status takes over from it.
app := models.JobApplication{JobTitle: input.JobTitle, Company: input.Company}
mergeCapture(&app, input, now)
if err := store.DB.Create(&app).Error; err != nil {
log.Println("Job capture insert failed:", err)
app, action, err := services.UpsertJobApplication(store.DB, input, time.Now())
var invalid *services.JobInputError
switch {
case errors.As(err, &invalid):
ctx.JSON(http.StatusBadRequest, gin.H{"error": invalid.Error()})
case err != nil:
log.Println("Job capture failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
return
case action == "created":
ctx.JSON(http.StatusCreated, gin.H{"action": action, "application": capturedJobOf(app)})
default:
ctx.JSON(http.StatusOK, gin.H{"action": action, "application": capturedJobOf(app)})
}
ctx.JSON(http.StatusCreated, gin.H{"action": "created", "application": capturedJobOf(&app)})
}
-115
View File
@@ -9,9 +9,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
)
@@ -141,119 +139,6 @@ func TestCaptureTokenAdminEndpoints(t *testing.T) {
}
}
func TestCanonicalJobURL(t *testing.T) {
const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/"
cases := []struct {
name string
in string
want string // "" means rejected
}{
// One LinkedIn posting, reached four ways, must be one key.
{"linkedin direct", "https://www.linkedin.com/jobs/view/4012345678/?trk=public_jobs", linkedIn},
{"linkedin slug form", "https://uk.linkedin.com/jobs/view/backend-engineer-at-acme-4012345678?refId=abc", linkedIn},
{"linkedin search pane", "https://www.linkedin.com/jobs/search/?currentJobId=4012345678&keywords=go", linkedIn},
{"linkedin collections pane", "https://www.linkedin.com/jobs/collections/recommended/?currentJobId=4012345678", linkedIn},
{"linkedin page with no job id is left as a normal URL", "https://www.linkedin.com/jobs/search/?keywords=go", "https://www.linkedin.com/jobs/search?keywords=go"},
{"a non-numeric linkedin id is not trusted", "https://www.linkedin.com/jobs/search/?currentJobId=4/../x", "https://www.linkedin.com/jobs/search?currentJobId=4%2F..%2Fx"},
{"a lookalike host does not get the linkedin rule", "https://notlinkedin.com/jobs/view/42", "https://notlinkedin.com/jobs/view/42"},
{"tracking parameters and the fragment are dropped", "https://jobs.lever.co/acme/abc-123?lever-source=LinkedIn&utm_medium=x#apply", "https://jobs.lever.co/acme/abc-123"},
// gh_jid IS the posting on an embedded Greenhouse board.
{"a parameter that identifies the job is kept", "https://acme.com/careers?gh_jid=77&gh_src=abc", "https://acme.com/careers?gh_jid=77"},
{"parameter order does not matter", "https://x.com/job?b=2&a=1", "https://x.com/job?a=1&b=2"},
{"host case and a trailing slash do not matter", "https://Boards.Greenhouse.io/acme/jobs/55/", "https://boards.greenhouse.io/acme/jobs/55"},
{"a relative path is rejected", "/jobs/view/1", ""},
{"a non-http scheme is rejected", "javascript:alert(1)", ""},
{"empty is rejected", "", ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, ok := canonicalJobURL(c.in)
if ok != (c.want != "") || got != c.want {
t.Fatalf("canonicalJobURL(%q) = %q, %v; want %q", c.in, got, ok, c.want)
}
})
}
}
func strPtr(s string) *string { return &s }
func TestMergeCapture(t *testing.T) {
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
earlier := now.Add(-48 * time.Hour)
t.Run("a new row takes every field and an applied date", func(t *testing.T) {
app := models.JobApplication{JobTitle: "Engineer", Company: "Acme"}
in := captureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Notes: "Hybrid", Description: "Full text"}
if !mergeCapture(&app, in, now) {
t.Fatal("expected a change")
}
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
if *app.Location != "London" || *app.URL != "https://x.com/1" || *app.Notes != "Hybrid" || *app.Description != "Full text" {
t.Fatalf("fields not filled: %+v", app)
}
})
t.Run("a saved posting has no applied date", func(t *testing.T) {
app := models.JobApplication{}
mergeCapture(&app, captureInput{Status: "saved"}, now)
if app.Status != "saved" || app.AppliedAt != nil {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("saved then applied advances and dates the application", func(t *testing.T) {
app := models.JobApplication{Status: "saved"}
if !mergeCapture(&app, captureInput{Status: "applied"}, now) {
t.Fatal("expected a change")
}
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("a repeat capture cannot move an application backwards", func(t *testing.T) {
app := models.JobApplication{Status: "interviewing", AppliedAt: &earlier}
if mergeCapture(&app, captureInput{Status: "saved"}, now) {
t.Fatal("expected no change")
}
if app.Status != "interviewing" || !app.AppliedAt.Equal(earlier) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("fields already set are kept, empty ones are filled", func(t *testing.T) {
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Location: strPtr("Remote"), URL: strPtr("")}
in := captureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Description: "Full text"}
if !mergeCapture(&app, in, now) {
t.Fatal("expected a change")
}
if *app.Location != "Remote" {
t.Fatalf("location overwritten: %q", *app.Location)
}
if *app.URL != "https://x.com/1" || *app.Description != "Full text" {
t.Fatalf("empty fields not filled: url=%q", *app.URL)
}
if !app.AppliedAt.Equal(earlier) {
t.Fatal("an existing applied date must not be replaced")
}
})
t.Run("notes append once", func(t *testing.T) {
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Notes: strPtr("Recruiter: Sam")}
in := captureInput{Status: "applied", Notes: "Hybrid, £70k"}
if !mergeCapture(&app, in, now) || *app.Notes != "Recruiter: Sam\nHybrid, £70k" {
t.Fatalf("notes = %q", *app.Notes)
}
if mergeCapture(&app, in, now) {
t.Fatalf("the same note was appended twice: %q", *app.Notes)
}
})
}
func TestTruncateRunes(t *testing.T) {
if got := truncateRunes("££££", 2); got != "££" {
t.Fatalf("got %q; the cut must fall on a rune boundary", got)
+6 -2
View File
@@ -33,12 +33,16 @@ type Store struct {
Notes *services.Notes
LoginLimiter *services.RateLimiter
EmailSync *services.EmailSyncService
// JobLeads is the lead fetcher (services/job_leads.go). The GraphQL
// resolvers use it to start a run and report on one.
JobLeads *services.JobLeadService
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the calls that bypass nginx, all through
// services.CallPython: reading a rowing display photo (handle_rowing.go)
// and a job posting (handle_job_capture.go). The email pipeline makes the
// third such call and holds its own copy of this value.
// and a job posting (handle_job_capture.go). The email pipeline and the
// lead pipeline make the other two such calls and hold their own copies
// of this value.
PythonURL string
// Bearer token for the browser capture routes (handle_job_capture.go),
+21 -2
View File
@@ -117,7 +117,7 @@ func main() {
// PYTHON SERVICE
// Called directly over the Docker network, not through nginx, for its
// three /internal/ Claude routes (services/python_call.go). The defaults
// four /internal/ Claude routes (services/python_call.go). The defaults
// mirror docker-compose.yml, where both variables are optional.
pythonHost := os.Getenv("PYTHON_HOST")
if pythonHost == "" {
@@ -155,6 +155,24 @@ func main() {
}
emailSync := services.InitEmailSync(&emailSyncConfig, db, pythonURL)
// JOB LEADS
// Like EMAIL_SYNC_INTERVAL, an unparseable JOB_LEADS_INTERVAL is ignored
// and the default stands. Six hours: boards change a few times a day at
// most, and every run can spend Claude calls.
jobLeadsInterval := 6 * time.Hour
if interval := os.Getenv("JOB_LEADS_INTERVAL"); interval != "" {
if parsed, err := time.ParseDuration(interval); err == nil && parsed > 0 {
jobLeadsInterval = parsed
}
}
jobLeads := services.InitJobLeads(&services.JobLeadConfig{
Enabled: os.Getenv("JOB_LEADS_ENABLED") == "true",
Interval: jobLeadsInterval,
AdzunaAppID: os.Getenv("ADZUNA_APP_ID"),
AdzunaAppKey: os.Getenv("ADZUNA_APP_KEY"),
ReedAPIKey: os.Getenv("REED_API_KEY"),
}, db, pythonURL)
// 5 login attempts per IP per minute, applied by both the REST handler
// and the GraphQL login mutation. Nginx rate-limits the login route too.
loginLimiter := services.NewRateLimiter(5, time.Minute)
@@ -176,7 +194,7 @@ func main() {
log.Fatal(err)
}
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, CaptureToken: captureToken, Env: envManager}
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, JobLeads: jobLeads, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, CaptureToken: captureToken, Env: envManager}
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
// the Gin context, so the order in the admin group matters.
@@ -302,6 +320,7 @@ func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go store.EmailSync.StartScheduler(ctx)
go store.JobLeads.StartScheduler(ctx)
port := os.Getenv("BACKEND_PORT")
// Blocks until the server stops. Any return is a failure — a port clash,
+95 -2
View File
@@ -208,8 +208,9 @@ type Place struct {
}
// JobApplication is a tracked job application. Rows are created by hand
// through GraphQL, automatically by the email pipeline, or from the browser
// by the capture userscript (handlers/handle_job_capture.go).
// through GraphQL, automatically by the email pipeline, from the browser by
// the capture userscript (handlers/handle_job_capture.go), or by promoting a
// JobLead (services.PromoteJobLead).
//
// Status is a plain string column, but its vocabulary is fixed: the values
// ranked in services.statusOrder ("saved", "applied", "screening",
@@ -238,3 +239,95 @@ type JobApplication struct {
AppliedAt *time.Time `json:"appliedAt"`
Description *string `gorm:"type:text" json:"description"`
}
// JobSource is one place the lead fetcher (services/job_leads.go) polls for
// postings. Kind decides which of the other fields mean anything:
//
// - "greenhouse", "lever", "ashby": one company's public job board. Token is
// the board's slug (the "acme" in boards.greenhouse.io/acme) and Label is
// the company name every lead from it is filed under.
// - "adzuna", "reed": a keyword search. Query and Location are the search
// terms and Label is only a display name; the company comes from each
// result.
//
// The Last* fields are written by the fetcher after every poll and are what
// the leads page shows beside the source. LastError is "" after a clean poll.
type JobSource struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Kind string `gorm:"not null" json:"kind"`
Label string `gorm:"not null" json:"label"`
Token string `json:"token"`
Query string `json:"query"`
Location string `json:"location"`
// No `default:true` tag: GORM applies a default to a zero value on
// insert, which would make it impossible to create a source disabled.
Enabled bool `gorm:"not null" json:"enabled"`
LastFetchedAt *time.Time `json:"lastFetchedAt"`
LastCount int `gorm:"not null;default:0" json:"lastCount"`
LastError string `json:"lastError"`
}
// JobLead is a posting the fetcher found, waiting in the leads inbox to be
// tracked or dismissed. It is deliberately not a JobApplication: a single
// company board is hundreds of postings, almost all irrelevant, and the
// tracker, its status vocabulary and the email matcher are about jobs
// actually applied to.
//
// Like ProcessedEmail it has no DeletedAt and is NOT soft deleted. The
// (SourceKind, ExternalID) unique index is the dedup that stops every poll
// re-adding the same posting, and it only works if a dismissed lead is still
// a row: dismissal is State "dismissed", never a delete.
//
// ExternalID is the source's own id for the posting. For the board kinds it
// is "<token>/<id>", because ids are only unique within one board.
//
// State is "new", "dismissed" or "promoted" (see the LeadState constants in
// services/job_leads.go). JobAppID is set on a promoted lead and is a plain
// nullable column, not a GORM association.
//
// Matched says whether the lead passed the keyword pre-filter the last time
// the fetcher ran; only matched leads are shown by default and only they are
// scored. Score (0-100) and ScoreReasons are Claude's, and nil until scored.
// ScoreAttempts counts failed tries, so a posting Claude can never score
// stops costing a call per run.
type JobLead struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
SourceID uint `gorm:"index" json:"sourceId"`
SourceKind string `gorm:"not null;uniqueIndex:idx_job_lead_external" json:"sourceKind"`
ExternalID string `gorm:"not null;uniqueIndex:idx_job_lead_external" json:"externalId"`
JobTitle string `gorm:"not null" json:"jobTitle"`
Company string `gorm:"not null" json:"company"`
Location string `json:"location"`
URL string `json:"url"`
Description string `gorm:"type:text" json:"description"`
PostedAt *time.Time `json:"postedAt"`
LastSeenAt time.Time `json:"lastSeenAt"`
Matched bool `gorm:"not null;default:false;index" json:"matched"`
State string `gorm:"not null;default:new;index" json:"state"`
Score *int `json:"score"`
ScoreReasons *string `json:"scoreReasons"`
ScoreAttempts int `gorm:"not null;default:0" json:"scoreAttempts"`
JobAppID *uint `json:"jobAppId"`
}
// JobSearchProfile is what a lead is judged against. There is exactly one
// row, with ID 1, created on first read (services.LoadJobSearchProfile).
//
// Profile is free text about experience and what kind of job is wanted; it is
// sent to Claude with each posting. The three keyword lists hold one entry
// per line and drive the cheap pre-filter that runs before any Claude call.
// MinScore is only a display threshold for the inbox.
type JobSearchProfile struct {
ID uint `gorm:"primarykey" json:"id"`
UpdatedAt time.Time `json:"updatedAt"`
Profile string `gorm:"type:text" json:"profile"`
IncludeKeywords string `gorm:"type:text" json:"includeKeywords"`
ExcludeKeywords string `gorm:"type:text" json:"excludeKeywords"`
Locations string `gorm:"type:text" json:"locations"`
MinScore int `gorm:"not null;default:60" json:"minScore"`
}
+3
View File
@@ -54,6 +54,9 @@ func migrateDatabase(db *gorm.DB) error {
&models.Bookmark{},
&models.Place{},
&models.ProcessedEmail{},
&models.JobSource{},
&models.JobLead{},
&models.JobSearchProfile{},
)
if err != nil {
return err
+7 -1
View File
@@ -1,5 +1,5 @@
[
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Claude calls, all made by the Python service: email classifier, rowing photo reader, job posting reader", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Claude calls, all made by the Python service: email classifier, rowing photo reader, job posting reader, job lead scorer", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
{"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"},
{"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]},
{"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"},
@@ -21,6 +21,12 @@
{"name": "IMAP_EMAIL", "group": "Email ingest", "purpose": "IMAP fallback account", "kind": "text", "editable": true, "services": ["backend"]},
{"name": "IMAP_PASSWORD", "group": "Email ingest", "purpose": "App-specific password, not the account password", "kind": "secret", "editable": true, "services": ["backend"]},
{"name": "JOB_LEADS_ENABLED", "group": "Job leads", "purpose": "Run the periodic job-lead fetch; \"Check now\" on /cv/leads works either way", "kind": "bool", "editable": true, "services": ["backend"]},
{"name": "JOB_LEADS_INTERVAL", "group": "Job leads", "purpose": "Time between fetches, as a Go duration such as 6h (default 6h)", "kind": "duration", "editable": true, "services": ["backend"]},
{"name": "ADZUNA_APP_ID", "group": "Job leads", "purpose": "Adzuna job search, for adzuna lead sources", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://developer.adzuna.com/admin/access_details"},
{"name": "ADZUNA_APP_KEY", "group": "Job leads", "purpose": "Adzuna job search, for adzuna lead sources", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://developer.adzuna.com/admin/access_details"},
{"name": "REED_API_KEY", "group": "Job leads", "purpose": "Reed job search, for reed lead sources", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://www.reed.co.uk/developers/jobseeker"},
{"name": "ICECAST_SOURCE_PASSWORD", "group": "Radio", "purpose": "Liquidsoap to Icecast, and live broadcasters to the harbor port", "kind": "generated", "editable": true, "services": ["icecast2"], "warning": "Live broadcasting clients must be given the new password."},
{"name": "ICECAST_RELAY_PASSWORD", "group": "Radio", "purpose": "Icecast relay clients", "kind": "generated", "editable": true, "services": ["icecast2"]},
{"name": "ICECAST_ADMIN_USER", "group": "Radio", "purpose": "Icecast web admin login", "kind": "text", "editable": true, "services": ["icecast2"]},
+698
View File
@@ -0,0 +1,698 @@
package services
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"strings"
"sync"
"time"
"unicode"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// Job leads: the pipeline that finds postings, as opposed to tracking
// applications. On a timer it polls every enabled models.JobSource
// (job_sources.go), files what it has not seen before as a models.JobLead,
// marks which leads pass a keyword pre-filter, and asks Claude — through the
// Python service, like every Claude call — to score those against the
// models.JobSearchProfile.
//
// Leads are a separate table from the tracker on purpose (see models.JobLead).
// The one way a lead reaches the tracker is promotion, a deliberate click on
// the leads page (graph/job_lead.resolvers.go), which goes through
// UpsertJobApplication so it cannot duplicate a posting already captured.
// Lead states, stored in JobLead.State.
const (
LeadNew = "new"
LeadDismissed = "dismissed"
LeadPromoted = "promoted"
)
const (
// jobScorePath is internal in the same way as the other /internal/
// routes: nginx refuses /py/internal/ and the route refuses anything
// nginx forwarded.
jobScorePath = "/internal/jobs/score"
// maxScoresPerRun bounds the Claude calls one run can make, and so both
// its cost and its length. A first poll of a few boards can match
// hundreds of leads; the rest are picked up by later runs, newest first.
maxScoresPerRun = 40
// maxScoreAttempts caps how many times a lead Claude failed to score is
// retried, for the same reason as maxEmailAttempts.
maxScoreAttempts = 3
// maxRunDuration bounds a whole run. Generous: forty scores at a worst
// case of two minutes each would exceed it, but a healthy call is a few
// seconds, and a run that is cut short loses nothing — unscored leads are
// simply still unscored next time.
maxRunDuration = 20 * time.Minute
// leadBatch sizes the IN lists and inserts, well inside Postgres's limit
// of 65535 bound parameters per statement.
leadBatch = 500
)
// ErrLeadSyncRunning is returned by Run when another run holds the lock.
var ErrLeadSyncRunning = errors.New("lead sync already in progress")
// JobLeadConfig configures the pipeline. The API keys are optional: a search
// source whose key is missing reports that as its own error and the rest of
// the run carries on.
type JobLeadConfig struct {
Enabled bool
Interval time.Duration
AdzunaAppID string
AdzunaAppKey string
ReedAPIKey string
}
// JobLeadService owns the lead pipeline.
type JobLeadService struct {
Config *JobLeadConfig
DB *gorm.DB
// PythonURL is the Python service's base URL on the Docker network, the
// same value as handlers.Store.PythonURL.
PythonURL string
// HTTPClient fetches the sources. Its timeout is per request, and has to
// allow for a multi-megabyte board arriving over the Pi's connection.
HTTPClient *http.Client
// mu is used with TryLock, as in EmailSyncService: a run requested while
// another is going is refused, not queued.
mu sync.Mutex
// statusMu guards the three fields below, which the leads page polls
// while a run it started is in flight.
statusMu sync.Mutex
running bool
lastRunAt *time.Time
lastError string
}
// LeadSyncStatus is what the leads page shows beside its "Check now" button.
type LeadSyncStatus struct {
Running bool
// LastRunAt is when the most recent run finished; nil until one has, in
// this process — it is not persisted, so a restart clears it.
LastRunAt *time.Time
// LastError is "" after a run in which nothing failed outright. One
// source failing is not here; it is on that JobSource.
LastError string
}
// InitJobLeads builds the service. It makes no network or database calls.
func InitJobLeads(config *JobLeadConfig, db *gorm.DB, pythonURL string) *JobLeadService {
return &JobLeadService{
Config: config,
DB: db,
PythonURL: pythonURL,
HTTPClient: &http.Client{Timeout: 60 * time.Second},
}
}
// Status reports whether a run is in flight and how the last one ended.
func (s *JobLeadService) Status() LeadSyncStatus {
s.statusMu.Lock()
defer s.statusMu.Unlock()
return LeadSyncStatus{Running: s.running, LastRunAt: s.lastRunAt, LastError: s.lastError}
}
// StartScheduler runs the pipeline on every tick until ctx is cancelled. It
// is meant to be run in its own goroutine and returns straight away when
// JOB_LEADS_ENABLED is not "true".
//
// Unlike the email scheduler it does not run at start-up: every deploy
// restarts the backend, and a deploy should not spend forty Claude calls. The
// first run is one interval in, or whenever "Check now" is pressed — which
// works whether or not the scheduler is enabled.
func (s *JobLeadService) StartScheduler(ctx context.Context) {
if !s.Config.Enabled {
log.Println("[JobLeads] Scheduler disabled; runs only on request")
return
}
log.Printf("[JobLeads] Starting scheduler, interval: %s", s.Config.Interval)
ticker := time.NewTicker(s.Config.Interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
log.Println("[JobLeads] Scheduler stopped")
return
case <-ticker.C:
if err := s.Run(ctx); err != nil {
log.Printf("[JobLeads] Run error: %v", err)
}
}
}
}
// RunInBackground starts a run and returns at once, reporting false when one
// was already going. It backs the page's "Check now": a run can take minutes,
// far longer than a request should be held open, so the page polls Status
// instead of waiting.
func (s *JobLeadService) RunInBackground() bool {
if s.Status().Running {
return false
}
go func() {
// Not the request's context: the request is over long before this is.
if err := s.Run(context.Background()); err != nil && !errors.Is(err, ErrLeadSyncRunning) {
log.Printf("[JobLeads] Manual run error: %v", err)
}
}()
return true
}
// Run is one pass of the pipeline: fetch, store, pre-filter, score.
func (s *JobLeadService) Run(ctx context.Context) (err error) {
if !s.mu.TryLock() {
return ErrLeadSyncRunning
}
defer s.mu.Unlock()
s.statusMu.Lock()
s.running = true
s.statusMu.Unlock()
// Runs before the unlock above. It also absorbs a panic, turning it into
// this run's error, so one malformed posting cannot take the backend down
// or leave `running` stuck true.
defer func() {
if r := recover(); r != nil {
log.Printf("[JobLeads] PANIC recovered: %v", r)
err = fmt.Errorf("internal error during the run")
}
now := time.Now()
s.statusMu.Lock()
s.running = false
s.lastRunAt = &now
s.lastError = ""
if err != nil {
s.lastError = err.Error()
}
s.statusMu.Unlock()
}()
ctx, cancel := context.WithTimeout(ctx, maxRunDuration)
defer cancel()
profile, err := LoadJobSearchProfile(s.DB)
if err != nil {
return fmt.Errorf("loading the search profile: %w", err)
}
filter := newLeadFilter(profile)
var sources []models.JobSource
if err := s.DB.Where("enabled = ?", true).Order("id ASC").Find(&sources).Error; err != nil {
return fmt.Errorf("loading sources: %w", err)
}
tracked, err := s.trackedURLs()
if err != nil {
return fmt.Errorf("loading tracked applications: %w", err)
}
log.Printf("[JobLeads] Starting run over %d sources", len(sources))
added := 0
for _, src := range sources {
if ctx.Err() != nil {
return ctx.Err()
}
jobs, fetchErr := s.fetchSource(ctx, src)
var n int
if fetchErr == nil {
n, fetchErr = s.storeLeads(ctx, src, jobs, filter, tracked)
added += n
}
s.recordPoll(src, len(jobs), fetchErr)
}
if err := s.refilter(filter); err != nil {
return fmt.Errorf("re-applying the filter: %w", err)
}
scored, err := s.scoreLeads(ctx, profile)
log.Printf("[JobLeads] Run finished: %d new leads, %d scored", added, scored)
return err
}
// recordPoll writes a poll's outcome onto its source for the page to show.
// Updates rather than Save, so a source edited on the page mid-run is not
// overwritten with the copy this run loaded.
func (s *JobLeadService) recordPoll(src models.JobSource, count int, fetchErr error) {
now := time.Now()
updates := map[string]any{"last_fetched_at": &now, "last_error": ""}
if fetchErr != nil {
log.Printf("[JobLeads] %s %q failed: %v", src.Kind, src.Label, fetchErr)
updates["last_error"] = truncate(fetchErr.Error(), 300)
} else {
updates["last_count"] = count
}
if err := s.DB.Model(&models.JobSource{}).Where("id = ?", src.ID).Updates(updates).Error; err != nil {
log.Printf("[JobLeads] Recording the poll of source %d failed: %v", src.ID, err)
}
}
// trackedURLs maps the canonical URL of every live application that has one
// to its id, so a fetched posting that is already in the tracker can be told
// apart from a fresh lead.
func (s *JobLeadService) trackedURLs() (map[string]uint, error) {
var apps []models.JobApplication
if err := s.DB.Select("id", "url").Where("url IS NOT NULL AND url <> ''").Find(&apps).Error; err != nil {
return nil, err
}
tracked := make(map[string]uint, len(apps))
for _, app := range apps {
if canonical, ok := CanonicalJobURL(*app.URL); ok {
tracked[canonical] = app.ID
}
}
return tracked, nil
}
// storeLeads files the postings a source returned and reports how many were
// new. A posting seen before only has its LastSeenAt moved: its state, score
// and text are left exactly as they are, which is what keeps a dismissed
// lead dismissed.
func (s *JobLeadService) storeLeads(ctx context.Context, src models.JobSource, jobs []fetchedJob, filter leadFilter, tracked map[string]uint) (int, error) {
now := time.Now()
added := 0
for start := 0; start < len(jobs); start += leadBatch {
batch := jobs[start:min(start+leadBatch, len(jobs))]
ids := make([]string, len(batch))
for i, job := range batch {
ids[i] = job.ExternalID
}
var known []string
if err := s.DB.Model(&models.JobLead{}).
Where("source_kind = ? AND external_id IN ?", src.Kind, ids).
Pluck("external_id", &known).Error; err != nil {
return added, fmt.Errorf("looking up existing leads: %w", err)
}
if len(known) > 0 {
if err := s.DB.Model(&models.JobLead{}).
Where("source_kind = ? AND external_id IN ?", src.Kind, known).
UpdateColumn("last_seen_at", now).Error; err != nil {
return added, fmt.Errorf("updating existing leads: %w", err)
}
}
seen := make(map[string]bool, len(known))
for _, id := range known {
seen[id] = true
}
var fresh []models.JobLead
for _, job := range batch {
// `seen` also catches a posting listed twice in one response.
if seen[job.ExternalID] {
continue
}
seen[job.ExternalID] = true
lead, ok := newLead(src, job, filter, tracked, now)
if !ok {
continue
}
// The full text costs a request per job, so it is fetched only
// for a lead that will be shown and scored. A failure leaves the
// 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)
}
}
fresh = append(fresh, lead)
}
if len(fresh) == 0 {
continue
}
// DoNothing covers the one way a row can appear between the lookup
// above and this insert: a second search source of the same kind
// returning the same advert. Runs themselves never overlap.
result := s.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&fresh)
if result.Error != nil {
return added, fmt.Errorf("saving new leads: %w", result.Error)
}
added += int(result.RowsAffected)
}
return added, nil
}
// newLead turns a fetched posting into the row to insert. ok is false for a
// posting with no id, title or company, which could be neither deduplicated
// nor promoted.
//
// A posting whose URL is already in the tracker is filed as promoted and
// linked to that application: it still has to be a row, or the next poll
// would consider it again, but it must not be offered in the inbox.
func newLead(src models.JobSource, job fetchedJob, filter leadFilter, tracked map[string]uint, now time.Time) (models.JobLead, bool) {
title := strings.TrimSpace(job.Title)
company := strings.TrimSpace(job.Company)
if job.ExternalID == "" || title == "" || company == "" {
return models.JobLead{}, false
}
lead := models.JobLead{
SourceID: src.ID,
SourceKind: src.Kind,
ExternalID: job.ExternalID,
JobTitle: title,
Company: company,
Location: strings.TrimSpace(job.Location),
URL: strings.TrimSpace(job.URL),
Description: truncateRunes(job.Description, maxLeadRunes),
PostedAt: job.PostedAt,
LastSeenAt: now,
State: LeadNew,
}
lead.Matched = filter.matches(lead.JobTitle, lead.Location)
if canonical, ok := CanonicalJobURL(lead.URL); ok {
lead.URL = canonical
if appID, found := tracked[canonical]; found {
lead.State = LeadPromoted
lead.JobAppID = &appID
}
}
return lead, true
}
// refilter brings Matched up to date for every lead still in the inbox, so
// that editing the keywords on the page takes effect on the next run instead
// of only for postings found afterwards.
func (s *JobLeadService) refilter(filter leadFilter) error {
var leads []models.JobLead
if err := s.DB.Select("id", "job_title", "location", "matched").
Where("state = ?", LeadNew).Find(&leads).Error; err != nil {
return err
}
var toMatch, toUnmatch []uint
for _, lead := range leads {
switch matched := filter.matches(lead.JobTitle, lead.Location); {
case matched && !lead.Matched:
toMatch = append(toMatch, lead.ID)
case !matched && lead.Matched:
toUnmatch = append(toUnmatch, lead.ID)
}
}
for value, ids := range map[bool][]uint{true: toMatch, false: toUnmatch} {
for start := 0; start < len(ids); start += leadBatch {
if err := s.DB.Model(&models.JobLead{}).
Where("id IN ?", ids[start:min(start+leadBatch, len(ids))]).
UpdateColumn("matched", value).Error; err != nil {
return err
}
}
}
return nil
}
// PromoteJobLead adds a lead to the tracker as a saved application and marks
// it promoted. It goes through UpsertJobApplication, so a posting that was
// captured from the browser in the meantime is linked to, not duplicated —
// the lead's text and score fill any fields that row was missing.
//
// Promoting twice is harmless: the second call finds the lead already
// promoted and returns it.
func PromoteJobLead(db *gorm.DB, id uint, now time.Time) (*models.JobLead, error) {
var lead models.JobLead
if err := db.First(&lead, id).Error; err != nil {
return nil, err
}
if lead.State == LeadPromoted && lead.JobAppID != nil {
return &lead, nil
}
app, _, err := UpsertJobApplication(db, JobCaptureInput{
JobTitle: lead.JobTitle,
Company: lead.Company,
Location: lead.Location,
URL: lead.URL,
Status: "saved",
Notes: leadNotes(&lead),
Description: lead.Description,
}, now)
if err != nil {
return nil, err
}
lead.State = LeadPromoted
lead.JobAppID = &app.ID
if err := db.Model(&lead).Updates(map[string]any{"state": lead.State, "job_app_id": lead.JobAppID}).Error; err != nil {
return nil, fmt.Errorf("marking the lead promoted: %w", err)
}
return &lead, nil
}
// leadNotes is the line a promoted lead leaves in the application's notes, so
// why it looked worth applying to is still there once the lead is forgotten.
func leadNotes(lead *models.JobLead) string {
if lead.Score == nil {
return ""
}
note := fmt.Sprintf("Lead score %d/100", *lead.Score)
if lead.ScoreReasons != nil && strings.TrimSpace(*lead.ScoreReasons) != "" {
note += ": " + strings.TrimSpace(*lead.ScoreReasons)
}
return note
}
// ValidateJobSource tidies a source's fields and reports the first thing
// wrong with it, in words for the page. Which fields are required depends on
// the kind; the ones a kind does not use are cleared so a source switched
// from one kind to another does not carry the old kind's settings around.
func ValidateJobSource(src *models.JobSource) error {
src.Kind = strings.ToLower(strings.TrimSpace(src.Kind))
src.Label = strings.TrimSpace(src.Label)
src.Token = strings.TrimSpace(src.Token)
src.Query = strings.TrimSpace(src.Query)
src.Location = strings.TrimSpace(src.Location)
switch {
case IsBoardSource(src.Kind):
// The token goes into a URL path. Board slugs are letters, digits
// and a little punctuation; anything else is a pasted URL or a typo.
if src.Token == "" || strings.ContainsAny(src.Token, "/?#& ") {
return fmt.Errorf("token must be the board's slug, e.g. the \"acme\" in boards.greenhouse.io/acme")
}
if src.Label == "" {
return fmt.Errorf("label is required: it is the company name its leads are filed under")
}
src.Query, src.Location = "", ""
case IsSearchSource(src.Kind):
if src.Query == "" {
return fmt.Errorf("query is required for a search source")
}
if src.Label == "" {
src.Label = src.Query
}
src.Token = ""
default:
return fmt.Errorf("kind must be one of greenhouse, lever, ashby, adzuna, reed")
}
return nil
}
// Pre-filter
// leadFilter is the keyword test a lead must pass before it is shown or
// costs a Claude call. It is intentionally crude and cheap: its job is to
// throw out the obviously irrelevant ninety percent of a company board
// (sales, legal, other countries), not to judge fit — that is the score.
type leadFilter struct {
include []string
exclude []string
locations []string
}
func newLeadFilter(profile *models.JobSearchProfile) leadFilter {
return leadFilter{
include: splitKeywords(profile.IncludeKeywords),
exclude: splitKeywords(profile.ExcludeKeywords),
locations: splitKeywords(profile.Locations),
}
}
// splitKeywords reads a keyword list as the page stores it: one entry per
// line, commas also accepted, case and surrounding space ignored.
func splitKeywords(list string) []string {
var out []string
for _, entry := range strings.FieldsFunc(list, func(r rune) bool { return r == '\n' || r == ',' }) {
if entry = strings.ToLower(strings.TrimSpace(entry)); entry != "" {
out = append(out, entry)
}
}
return out
}
// matches reports whether a posting passes. An empty list is no constraint,
// so with nothing configured every lead matches.
//
// - the title must contain one of the include keywords, and none of the
// exclude keywords, as whole words (see containsWord);
// - the location must contain one of the wanted locations as a plain
// substring ("london" finds "Cardiff, London or Remote (UK)"). A posting
// that states no location passes: unknown is not the same as wrong.
func (f leadFilter) matches(title, location string) bool {
title = strings.ToLower(title)
if len(f.include) > 0 && !containsAnyWord(title, f.include) {
return false
}
if containsAnyWord(title, f.exclude) {
return false
}
location = strings.ToLower(strings.TrimSpace(location))
if len(f.locations) == 0 || location == "" {
return true
}
for _, wanted := range f.locations {
if strings.Contains(location, wanted) {
return true
}
}
return false
}
func containsAnyWord(text string, words []string) bool {
for _, word := range words {
if containsWord(text, word) {
return true
}
}
return false
}
// containsWord reports whether word occurs in text on word boundaries, with
// an optional plural "s". Boundaries are what let "intern" be excluded
// without also excluding "Internal Tools Engineer", and the plural is what
// lets "engineer" find "Engineers". Both arguments are already lowercase.
func containsWord(text, word string) bool {
isWordRune := func(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) }
for from := 0; ; {
i := strings.Index(text[from:], word)
if i < 0 {
return false
}
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])) {
return true
}
from = start + 1
}
}
// Scoring
// LeadScore is the JSON contract for Claude's verdict on one lead: the body
// of the Python service's reply (LeadScore in python/app/job_score.py).
type LeadScore struct {
Score int `json:"score"`
Reasons string `json:"reasons"`
}
// scoreRequest is the body of POST /internal/jobs/score; the field names are
// JobScoreRequest's in python/app/main.py.
type scoreRequest struct {
Profile string `json:"profile"`
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Location string `json:"location"`
Description string `json:"description"`
}
// scoreLeads asks Claude to score the matched leads that have no score yet,
// newest first, up to maxScoresPerRun, and reports how many it scored.
//
// With no profile text there is nothing to score against, so it does nothing
// — leads still arrive and can be read, they just carry no score.
func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSearchProfile) (int, error) {
if strings.TrimSpace(profile.Profile) == "" {
return 0, nil
}
var leads []models.JobLead
if err := s.DB.
Where("state = ? AND matched = ? AND score IS NULL AND score_attempts < ?", LeadNew, true, maxScoreAttempts).
Order("created_at DESC, id DESC").Limit(maxScoresPerRun).
Find(&leads).Error; err != nil {
return 0, fmt.Errorf("loading leads to score: %w", err)
}
scored := 0
for i := range leads {
lead := &leads[i]
result, err := s.scoreLead(ctx, profile.Profile, lead)
var readErr *PythonError
switch {
case err == nil:
reasons := strings.TrimSpace(result.Reasons)
score := min(max(result.Score, 0), 100)
if dbErr := s.DB.Model(lead).Updates(map[string]any{"score": score, "score_reasons": reasons}).Error; dbErr != nil {
return scored, fmt.Errorf("saving a score: %w", dbErr)
}
scored++
case errors.As(err, &readErr):
// Claude answered badly for this posting. Count the attempt and
// move on; maxScoreAttempts stops it being retried forever.
log.Printf("[JobLeads] Scoring lead %d failed: %v", lead.ID, err)
if dbErr := s.DB.Model(lead).UpdateColumn("score_attempts", gorm.Expr("score_attempts + 1")).Error; dbErr != nil {
return scored, fmt.Errorf("recording a failed score: %w", dbErr)
}
default:
// Anything else is not about this lead: no API key, the Python
// service down, the run cancelled. The next lead would fail the
// same way, so stop, and spend no attempt on it.
// The detail names internal addresses and goes to the log; the
// returned error is shown on the leads page.
log.Printf("[JobLeads] Scoring stopped at lead %d: %v", lead.ID, err)
return scored, errors.New("scoring is unavailable: the Python service did not answer, or has no Claude key (see the backend log)")
}
}
return scored, nil
}
func (s *JobLeadService) scoreLead(ctx context.Context, profile string, lead *models.JobLead) (LeadScore, error) {
return CallPython[LeadScore](ctx, s.PythonURL, jobScorePath, scoreRequest{
Profile: truncateRunes(profile, maxProfileRunes),
JobTitle: lead.JobTitle,
Company: lead.Company,
Location: lead.Location,
Description: lead.Description,
})
}
// Search profile
// maxProfileRunes caps the profile text, both as stored and as sent. It
// mirrors MAX_PROFILE_CHARS in python/app/job_score.py.
const maxProfileRunes = 12_000
// jobSearchProfileID is the one row's id; see models.JobSearchProfile.
const jobSearchProfileID = 1
// LoadJobSearchProfile returns the single profile row, creating it empty the
// first time it is asked for.
func LoadJobSearchProfile(db *gorm.DB) (*models.JobSearchProfile, error) {
profile := models.JobSearchProfile{ID: jobSearchProfileID}
if err := db.FirstOrCreate(&profile, models.JobSearchProfile{ID: jobSearchProfileID}).Error; err != nil {
return nil, err
}
return &profile, nil
}
// 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.MinScore = min(max(profile.MinScore, 0), 100)
return db.Save(profile).Error
}
+243
View File
@@ -0,0 +1,243 @@
package services
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"adam-french.co.uk/backend/models"
)
// The parts of the lead pipeline that need no database: the pre-filter, how a
// fetched posting becomes a row, source validation, the note a promoted lead
// leaves, and the scoring call. Storing, re-filtering and the scoring loop's
// bookkeeping all run queries and are exercised in the dev stack instead.
func TestLeadFilter(t *testing.T) {
filter := newLeadFilter(&models.JobSearchProfile{
IncludeKeywords: "Engineer\ndeveloper, SRE",
ExcludeKeywords: "intern\nsenior staff\nsales",
Locations: "London\nremote",
})
cases := []struct {
title, location string
want bool
}{
{"Backend Engineer", "London, UK", true},
{"Software Engineers (Platform)", "Remote - EMEA", true},
{"SRE", "Cardiff, London or Remote (UK)", true},
{"Engineering Manager", "London", false}, // "engineer" is not a whole word here
{"Account Executive", "London", false},
{"Engineer Intern", "London", false},
{"Internal Tools Engineer", "London", true}, // "intern" must not catch "Internal"
{"Senior Staff Engineer", "London", false},
{"Sales Engineer", "London", false},
{"Backend Engineer", "New York, NY", false},
{"Backend Engineer", "", true}, // unknown location passes
}
for _, c := range cases {
if got := filter.matches(c.title, c.location); got != c.want {
t.Errorf("matches(%q, %q) = %v, want %v", c.title, c.location, got, c.want)
}
}
// Nothing configured: everything passes.
if !newLeadFilter(&models.JobSearchProfile{}).matches("Chief Vibes Officer", "Mars") {
t.Error("an empty filter should match everything")
}
}
func TestContainsWord(t *testing.T) {
cases := []struct {
text, word string
want bool
}{
{"go developer", "go", true},
{"golang developer", "go", false},
{"c++ engineer", "c++", true},
{"developers wanted", "developer", true},
{"developerss", "developer", false},
{"site reliability engineer (sre)", "sre", true},
{"ingénieur logiciel", "nieur", false},
{"", "go", false},
}
for _, c := range cases {
if got := containsWord(c.text, c.word); got != c.want {
t.Errorf("containsWord(%q, %q) = %v, want %v", c.text, c.word, got, c.want)
}
}
}
func TestNewLead(t *testing.T) {
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
src := models.JobSource{ID: 7, Kind: SourceGreenhouse, Label: "Acme", Token: "acme"}
filter := newLeadFilter(&models.JobSearchProfile{IncludeKeywords: "engineer"})
tracked := map[string]uint{"https://boards.greenhouse.io/acme/jobs/2": 42}
t.Run("a fresh posting is a new, matched lead", func(t *testing.T) {
lead, ok := newLead(src, fetchedJob{
ExternalID: "acme/1", Title: " Backend Engineer ", Company: "Acme", Location: "London",
URL: "https://boards.greenhouse.io/acme/jobs/1/?gh_src=abc", Description: "Text",
}, filter, tracked, now)
if !ok {
t.Fatal("not ok")
}
if lead.State != LeadNew || !lead.Matched || lead.JobAppID != nil || lead.SourceID != 7 ||
lead.SourceKind != SourceGreenhouse || lead.JobTitle != "Backend Engineer" || !lead.LastSeenAt.Equal(now) {
t.Errorf("lead = %+v", lead)
}
// Stored canonical, so it is the same key the tracker would hold.
if lead.URL != "https://boards.greenhouse.io/acme/jobs/1" {
t.Errorf("url = %q", lead.URL)
}
})
t.Run("a posting already in the tracker is filed as promoted", func(t *testing.T) {
lead, ok := newLead(src, fetchedJob{
ExternalID: "acme/2", Title: "Backend Engineer", Company: "Acme",
URL: "https://boards.greenhouse.io/acme/jobs/2?utm_source=x",
}, filter, tracked, now)
if !ok || lead.State != LeadPromoted || lead.JobAppID == nil || *lead.JobAppID != 42 {
t.Errorf("lead = %+v, ok = %v", lead, ok)
}
})
t.Run("a posting that fails the filter is kept, unmatched", func(t *testing.T) {
lead, ok := newLead(src, fetchedJob{ExternalID: "acme/3", Title: "Account Executive", Company: "Acme"}, filter, tracked, now)
if !ok || lead.Matched || lead.State != LeadNew {
t.Errorf("lead = %+v, ok = %v", lead, ok)
}
})
t.Run("a posting with no id, title or company is dropped", func(t *testing.T) {
for _, job := range []fetchedJob{
{Title: "Engineer", Company: "Acme"},
{ExternalID: "acme/4", Company: "Acme"},
{ExternalID: "acme/5", Title: "Engineer", Company: " "},
} {
if _, ok := newLead(src, job, filter, tracked, now); ok {
t.Errorf("%+v should be dropped", job)
}
}
})
t.Run("a long description is cut on a rune boundary", func(t *testing.T) {
lead, _ := newLead(src, fetchedJob{
ExternalID: "acme/6", Title: "Engineer", Company: "Acme", Description: strings.Repeat("é", maxLeadRunes+10),
}, filter, tracked, now)
if got := len([]rune(lead.Description)); got != maxLeadRunes {
t.Errorf("description is %d runes", got)
}
})
}
func TestValidateJobSource(t *testing.T) {
ok := []struct {
in models.JobSource
want models.JobSource
}{
// Fields the kind does not use are cleared.
{models.JobSource{Kind: " Greenhouse ", Label: " Acme ", Token: " acme ", Query: "stale"},
models.JobSource{Kind: "greenhouse", Label: "Acme", Token: "acme"}},
// A search's label defaults to its query.
{models.JobSource{Kind: "reed", Query: "golang", Location: "London", Token: "stale"},
models.JobSource{Kind: "reed", Label: "golang", Query: "golang", Location: "London"}},
}
for _, c := range ok {
src := c.in
if err := ValidateJobSource(&src); err != nil || src != c.want {
t.Errorf("ValidateJobSource(%+v) = %+v, %v; want %+v", c.in, src, err, c.want)
}
}
bad := []models.JobSource{
{Kind: "monster", Label: "x", Query: "go"},
{Kind: "lever", Label: "Acme"},
{Kind: "lever", Label: "Acme", Token: "https://jobs.lever.co/acme"},
{Kind: "ashby", Token: "acme"},
{Kind: "adzuna", Label: "x"},
}
for _, src := range bad {
if err := ValidateJobSource(&src); err == nil {
t.Errorf("ValidateJobSource(%+v) should fail", src)
}
}
}
func TestLeadNotes(t *testing.T) {
score := 82
reasons := " Strong Go match; hybrid London. "
if got := leadNotes(&models.JobLead{}); got != "" {
t.Errorf("unscored lead notes = %q", got)
}
if got := leadNotes(&models.JobLead{Score: &score}); got != "Lead score 82/100" {
t.Errorf("notes = %q", got)
}
if got := leadNotes(&models.JobLead{Score: &score, ScoreReasons: &reasons}); got != "Lead score 82/100: Strong Go match; hybrid London." {
t.Errorf("notes = %q", got)
}
}
func TestScoreLeadRequestAndErrors(t *testing.T) {
var path string
var body map[string]any
reply := func(w http.ResponseWriter) { w.Write([]byte(`{"score": 82, "reasons": "Strong match"}`)) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decoding request: %v", err)
}
reply(w)
}))
t.Cleanup(srv.Close)
s := &JobLeadService{PythonURL: srv.URL}
lead := &models.JobLead{JobTitle: "Engineer", Company: "Acme", Location: "London", Description: "Text"}
got, err := s.scoreLead(context.Background(), "Five years of Go", lead)
if err != nil || got.Score != 82 || got.Reasons != "Strong match" {
t.Fatalf("scoreLead = %+v, %v", got, err)
}
if path != "/internal/jobs/score" {
t.Errorf("path = %q", path)
}
want := map[string]any{"profile": "Five years of Go", "jobTitle": "Engineer", "company": "Acme", "location": "London", "description": "Text"}
for key, value := range want {
if body[key] != value {
t.Errorf("body[%q] = %v, want %v", key, body[key], value)
}
}
if len(body) != len(want) {
t.Errorf("body = %v", body)
}
// The two kinds of failure scoreLeads tells apart: Claude answering badly
// for this posting (a PythonError, counted against the lead) and scoring
// being unavailable altogether (anything else, which stops the run).
var readErr *PythonError
reply = func(w http.ResponseWriter) {
w.WriteHeader(http.StatusBadGateway)
w.Write([]byte(`{"detail": "failed to parse the score"}`))
}
if _, err := s.scoreLead(context.Background(), "p", lead); !errors.As(err, &readErr) {
t.Errorf("a 502 should be a PythonError, got %v", err)
}
reply = func(w http.ResponseWriter) {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(`{"detail": "CLAUDE_API_KEY is not set"}`))
}
if _, err := s.scoreLead(context.Background(), "p", lead); err == nil || errors.As(err, &readErr) {
t.Errorf("a 503 should be a plain error, got %v", err)
}
}
func TestLeadSyncStatusStartsIdle(t *testing.T) {
s := InitJobLeads(&JobLeadConfig{}, nil, "http://python:8000")
if status := s.Status(); status.Running || status.LastRunAt != nil || status.LastError != "" {
t.Errorf("status = %+v", status)
}
}
+502
View File
@@ -0,0 +1,502 @@
package services
import (
"context"
"encoding/json"
"fmt"
"html"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"adam-french.co.uk/backend/models"
)
// The job sources the lead fetcher (job_leads.go) polls: one function per
// models.JobSource.Kind, each turning that source's JSON into the common
// fetchedJob. Nothing here touches the database.
//
// The three board kinds are public, keyless endpoints that return a whole
// company board, description included, in one response. Their shapes were
// checked against live boards. The two search kinds need API keys and their
// shapes are taken from the providers' documentation — if one of them starts
// reporting zero results or a decode error, its struct here is the first
// thing to compare against a real response.
// Source kinds. The strings are stored in JobSource.Kind and JobLead.SourceKind
// and repeated in the leads page's kind picker (vue/src/views/CV/JobSources.vue).
const (
SourceGreenhouse = "greenhouse"
SourceLever = "lever"
SourceAshby = "ashby"
SourceAdzuna = "adzuna"
SourceReed = "reed"
)
// IsBoardSource reports whether kind is one company's board, identified by a
// token, rather than a keyword search.
func IsBoardSource(kind string) bool {
return kind == SourceGreenhouse || kind == SourceLever || kind == SourceAshby
}
// IsSearchSource reports whether kind is a keyword search.
func IsSearchSource(kind string) bool {
return kind == SourceAdzuna || kind == SourceReed
}
// Base URLs, variables so the tests can point each at a stub server.
var (
greenhouseBase = "https://boards-api.greenhouse.io"
leverBase = "https://api.lever.co"
ashbyBase = "https://api.ashbyhq.com"
adzunaBase = "https://api.adzuna.com"
reedBase = "https://www.reed.co.uk"
)
const (
// maxSourceBody bounds one response. A large board with every description
// inline runs to several megabytes (Palantir's Lever board is about six);
// this is far above that and only there so a misbehaving endpoint cannot
// fill the Pi's memory.
maxSourceBody = 64 << 20
// searchPages × searchPageSize is how deep a keyword search is read on
// each poll. Results are newest first and polls are hours apart, so the
// first hundred is where anything new will be.
searchPages = 2
searchPageSize = 50
// adzunaMaxDaysOld keeps a search to recent adverts; older ones were seen
// by an earlier poll or are not worth surfacing now.
adzunaMaxDaysOld = 14
// maxLeadRunes caps a stored description. It mirrors MAX_DESCRIPTION_CHARS
// in python/app/job_score.py, which rejects anything longer.
maxLeadRunes = 40_000
)
// fetchedJob is one posting as a source reported it, before it becomes a
// models.JobLead.
type fetchedJob struct {
// ExternalID is unique within the source kind; see models.JobLead.
ExternalID string
Title string
Company string
Location string
URL string
Description string
PostedAt *time.Time
// detailID is set when Description is only a snippet and the full text is
// one more request away (Reed). The fetcher makes that request only for
// a new lead that passed the pre-filter.
detailID string
}
// fetchSource returns everything src currently lists.
func (s *JobLeadService) fetchSource(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
switch src.Kind {
case SourceGreenhouse:
return s.fetchGreenhouse(ctx, src)
case SourceLever:
return s.fetchLever(ctx, src)
case SourceAshby:
return s.fetchAshby(ctx, src)
case SourceAdzuna:
return s.fetchAdzuna(ctx, src)
case SourceReed:
return s.fetchReed(ctx, src)
}
return nil, fmt.Errorf("unknown source kind %q", src.Kind)
}
// getJSON GETs target and decodes a 200 reply into out. basicUser, when set,
// is sent as the username of HTTP basic auth with an empty password, which is
// how Reed takes its API key.
//
// The error never includes the URL: Adzuna's carries the API key in its query
// string, and this error is stored in JobSource.LastError and shown on the
// page.
func (s *JobLeadService) getJSON(ctx context.Context, target, basicUser string, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
return fmt.Errorf("building request")
}
req.Header.Set("Accept", "application/json")
if basicUser != "" {
req.SetBasicAuth(basicUser, "")
}
resp, err := s.HTTPClient.Do(req)
if err != nil {
// A *url.Error's message quotes the full URL; keep only its cause.
if urlErr, ok := err.(*url.Error); ok {
err = urlErr.Err
}
return fmt.Errorf("request failed: %v", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusNotFound:
return fmt.Errorf("not found (404): check the board token")
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
return fmt.Errorf("refused (%d): check the API key", resp.StatusCode)
case resp.StatusCode != http.StatusOK:
return fmt.Errorf("source returned %d", resp.StatusCode)
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxSourceBody)).Decode(out); err != nil {
return fmt.Errorf("unexpected response: %v", err)
}
return nil
}
// Greenhouse
type greenhouseBoard struct {
Jobs []struct {
ID int64 `json:"id"`
Title string `json:"title"`
AbsoluteURL string `json:"absolute_url"`
// Content is HTML that has itself been entity-escaped ("&lt;p&gt;").
Content string `json:"content"`
FirstPublished string `json:"first_published"`
UpdatedAt string `json:"updated_at"`
Location struct {
Name string `json:"name"`
} `json:"location"`
} `json:"jobs"`
}
func (s *JobLeadService) fetchGreenhouse(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
var board greenhouseBoard
target := fmt.Sprintf("%s/v1/boards/%s/jobs?content=true", greenhouseBase, url.PathEscape(src.Token))
if err := s.getJSON(ctx, target, "", &board); err != nil {
return nil, err
}
jobs := make([]fetchedJob, 0, len(board.Jobs))
for _, j := range board.Jobs {
posted := j.FirstPublished
if posted == "" {
posted = j.UpdatedAt
}
jobs = append(jobs, fetchedJob{
ExternalID: boardExternalID(src.Token, strconv.FormatInt(j.ID, 10)),
Title: j.Title,
Company: src.Label,
Location: j.Location.Name,
URL: j.AbsoluteURL,
// Unescape once to get the HTML back; htmlToText handles the rest.
Description: htmlToText(html.UnescapeString(j.Content)),
PostedAt: parseTime(time.RFC3339, posted),
})
}
return jobs, nil
}
// Lever
type leverPosting struct {
ID string `json:"id"`
Text string `json:"text"`
HostedURL string `json:"hostedUrl"`
CreatedAt int64 `json:"createdAt"` // Unix milliseconds
Categories struct {
Location string `json:"location"`
} `json:"categories"`
WorkplaceType string `json:"workplaceType"`
DescriptionPlain string `json:"descriptionPlain"`
AdditionalPlain string `json:"additionalPlain"`
// Lists are the posting's headed bullet sections ("What you'll do"),
// which descriptionPlain does not include.
Lists []struct {
Text string `json:"text"`
Content string `json:"content"` // HTML <li> items
} `json:"lists"`
}
func (s *JobLeadService) fetchLever(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
var postings []leverPosting
target := fmt.Sprintf("%s/v0/postings/%s?mode=json", leverBase, url.PathEscape(src.Token))
if err := s.getJSON(ctx, target, "", &postings); err != nil {
return nil, err
}
jobs := make([]fetchedJob, 0, len(postings))
for _, p := range postings {
parts := []string{strings.TrimSpace(p.DescriptionPlain)}
for _, list := range p.Lists {
parts = append(parts, strings.TrimSpace(list.Text)+"\n"+htmlToText(list.Content))
}
parts = append(parts, strings.TrimSpace(p.AdditionalPlain))
var posted *time.Time
if p.CreatedAt > 0 {
t := time.UnixMilli(p.CreatedAt).UTC()
posted = &t
}
jobs = append(jobs, fetchedJob{
ExternalID: boardExternalID(src.Token, p.ID),
Title: p.Text,
Company: src.Label,
Location: withWorkplace(p.Categories.Location, p.WorkplaceType),
URL: p.HostedURL,
Description: joinNonEmpty(parts, "\n\n"),
PostedAt: posted,
})
}
return jobs, nil
}
// Ashby
type ashbyBoard struct {
Jobs []struct {
ID string `json:"id"`
Title string `json:"title"`
Location string `json:"location"`
WorkplaceType string `json:"workplaceType"`
PublishedAt string `json:"publishedAt"`
IsListed bool `json:"isListed"`
JobURL string `json:"jobUrl"`
DescriptionPlain string `json:"descriptionPlain"`
} `json:"jobs"`
}
func (s *JobLeadService) fetchAshby(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
var board ashbyBoard
target := fmt.Sprintf("%s/posting-api/job-board/%s", ashbyBase, url.PathEscape(src.Token))
if err := s.getJSON(ctx, target, "", &board); err != nil {
return nil, err
}
jobs := make([]fetchedJob, 0, len(board.Jobs))
for _, j := range board.Jobs {
// Unlisted postings are reachable by direct link only; the company
// has chosen not to advertise them.
if !j.IsListed {
continue
}
jobs = append(jobs, fetchedJob{
ExternalID: boardExternalID(src.Token, j.ID),
Title: strings.TrimSpace(j.Title),
Company: src.Label,
Location: withWorkplace(j.Location, j.WorkplaceType),
URL: j.JobURL,
Description: strings.TrimSpace(j.DescriptionPlain),
PostedAt: parseTime(time.RFC3339, j.PublishedAt),
})
}
return jobs, nil
}
// Adzuna
type adzunaResults struct {
Results []struct {
// A string in the API, though it is all digits.
ID json.Number `json:"id"`
Title string `json:"title"`
Description string `json:"description"` // a snippet, about 500 characters
RedirectURL string `json:"redirect_url"`
Created string `json:"created"`
Company struct {
DisplayName string `json:"display_name"`
} `json:"company"`
Location struct {
DisplayName string `json:"display_name"`
} `json:"location"`
} `json:"results"`
}
// fetchAdzuna runs one UK keyword search. Adzuna only ever returns a snippet
// of the description and has no endpoint for the rest, so these leads are
// scored on less text than the others.
func (s *JobLeadService) fetchAdzuna(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
if s.Config.AdzunaAppID == "" || s.Config.AdzunaAppKey == "" {
return nil, fmt.Errorf("ADZUNA_APP_ID and ADZUNA_APP_KEY are not set")
}
var jobs []fetchedJob
for page := 1; page <= searchPages; page++ {
query := url.Values{
"app_id": {s.Config.AdzunaAppID},
"app_key": {s.Config.AdzunaAppKey},
"what": {src.Query},
"results_per_page": {strconv.Itoa(searchPageSize)},
"max_days_old": {strconv.Itoa(adzunaMaxDaysOld)},
"sort_by": {"date"},
}
if src.Location != "" {
query.Set("where", src.Location)
}
var results adzunaResults
target := fmt.Sprintf("%s/v1/api/jobs/gb/search/%d?%s", adzunaBase, page, query.Encode())
if err := s.getJSON(ctx, target, "", &results); err != nil {
return nil, err
}
for _, r := range results.Results {
jobs = append(jobs, fetchedJob{
ExternalID: r.ID.String(),
// Adzuna wraps the matched search terms in <strong>.
Title: htmlToText(r.Title),
Company: r.Company.DisplayName,
Location: r.Location.DisplayName,
URL: r.RedirectURL,
Description: htmlToText(r.Description),
PostedAt: parseTime(time.RFC3339, r.Created),
})
}
if len(results.Results) < searchPageSize {
break
}
}
return jobs, nil
}
// Reed
type reedResults struct {
Results []struct {
JobID int64 `json:"jobId"`
EmployerName string `json:"employerName"`
JobTitle string `json:"jobTitle"`
LocationName string `json:"locationName"`
Date string `json:"date"` // dd/mm/yyyy
JobDescription string `json:"jobDescription"`
JobURL string `json:"jobUrl"`
} `json:"results"`
}
type reedDetail struct {
JobDescription string `json:"jobDescription"` // HTML
}
// fetchReed runs one keyword search. The search returns a snippet of each
// description; the full text is fetchReedDescription, one request per job.
func (s *JobLeadService) fetchReed(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
if s.Config.ReedAPIKey == "" {
return nil, fmt.Errorf("REED_API_KEY is not set")
}
var jobs []fetchedJob
for page := 0; page < searchPages; page++ {
query := url.Values{
"keywords": {src.Query},
"resultsToTake": {strconv.Itoa(searchPageSize)},
"resultsToSkip": {strconv.Itoa(page * searchPageSize)},
}
if src.Location != "" {
query.Set("locationName", src.Location)
}
var results reedResults
target := fmt.Sprintf("%s/api/1.0/search?%s", reedBase, query.Encode())
if err := s.getJSON(ctx, target, s.Config.ReedAPIKey, &results); err != nil {
return nil, err
}
for _, r := range results.Results {
id := strconv.FormatInt(r.JobID, 10)
jobs = append(jobs, fetchedJob{
ExternalID: id,
Title: r.JobTitle,
Company: r.EmployerName,
Location: r.LocationName,
URL: r.JobURL,
Description: htmlToText(r.JobDescription),
PostedAt: parseTime("02/01/2006", r.Date),
detailID: id,
})
}
if len(results.Results) < searchPageSize {
break
}
}
return jobs, nil
}
// fetchReedDescription returns the full text of one Reed advert.
func (s *JobLeadService) fetchReedDescription(ctx context.Context, jobID string) (string, error) {
var detail reedDetail
target := fmt.Sprintf("%s/api/1.0/jobs/%s", reedBase, url.PathEscape(jobID))
if err := s.getJSON(ctx, target, s.Config.ReedAPIKey, &detail); err != nil {
return "", err
}
return htmlToText(detail.JobDescription), nil
}
// Helpers
// boardExternalID namespaces a board's own job id with the board, because
// ids are only unique within one company's board.
func boardExternalID(token, id string) string {
return strings.ToLower(strings.TrimSpace(token)) + "/" + id
}
// withWorkplace appends a posting's remote/hybrid/on-site label to its
// location, where the source reports one separately. The pre-filter matches
// on the result, so "remote" in the wanted locations finds these.
func withWorkplace(location, workplace string) string {
location = strings.TrimSpace(location)
workplace = strings.ToLower(strings.TrimSpace(workplace))
if workplace == "" || workplace == "unspecified" || strings.Contains(strings.ToLower(location), workplace) {
return location
}
if location == "" {
return workplace
}
return location + " (" + workplace + ")"
}
func joinNonEmpty(parts []string, sep string) string {
kept := parts[:0:0]
for _, p := range parts {
if strings.TrimSpace(p) != "" {
kept = append(kept, p)
}
}
return strings.Join(kept, sep)
}
// parseTime returns nil for a value that does not parse: a missing posting
// date is not worth failing a fetch over.
func parseTime(layout, value string) *time.Time {
t, err := time.Parse(layout, strings.TrimSpace(value))
if err != nil {
return nil
}
return &t
}
var (
// Tags that end a line in rendered HTML. Replaced with a newline before
// the rest are stripped, so paragraphs and bullets survive as lines.
htmlBlockTag = regexp.MustCompile(`(?i)</?(p|div|br|li|ul|ol|h[1-6]|tr|section)\b[^>]*>`)
htmlAnyTag = regexp.MustCompile(`<[^>]*>`)
htmlSpaces = regexp.MustCompile(`[ \t\x{00a0}]+`)
htmlBlankRuns = regexp.MustCompile(`\n[ \t]*(\n[ \t]*)+`)
)
// htmlToText reduces a posting's HTML to readable plain text. Like
// cleanEmailBody it is a regex strip, not a parser, which is enough for text
// that is read by a person and by a language model and never rendered as
// HTML. Unlike cleanEmailBody it keeps the whole text and its line structure.
func htmlToText(content string) string {
text := htmlBlockTag.ReplaceAllString(content, "\n")
text = htmlAnyTag.ReplaceAllString(text, "")
text = html.UnescapeString(text)
text = htmlSpaces.ReplaceAllString(text, " ")
text = htmlBlankRuns.ReplaceAllString(text, "\n\n")
lines := strings.Split(text, "\n")
for i, line := range lines {
lines[i] = strings.TrimSpace(line)
}
return strings.TrimSpace(strings.Join(lines, "\n"))
}
// 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])
}
+281
View File
@@ -0,0 +1,281 @@
package services
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"adam-french.co.uk/backend/models"
)
// The source fetchers, each against a stub server replying with a cut-down
// copy of a real response (the board kinds) or of the documented shape (the
// search kinds, which need API keys). What is under test is the request each
// one makes and how its JSON becomes a fetchedJob.
// sourceStub points every source's base URL at one stub server for the test.
func sourceStub(t *testing.T, config JobLeadConfig, handler http.HandlerFunc) *JobLeadService {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
for _, base := range []*string{&greenhouseBase, &leverBase, &ashbyBase, &adzunaBase, &reedBase} {
old := *base
*base = srv.URL
t.Cleanup(func() { *base = old })
}
return &JobLeadService{Config: &config, HTTPClient: srv.Client()}
}
func TestFetchGreenhouse(t *testing.T) {
var path string
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.RequestURI()
w.Write([]byte(`{"jobs": [{
"absolute_url": "https://job-boards.greenhouse.io/monzo/jobs/8143930",
"location": {"name": "Cardiff, London or Remote (UK)"},
"id": 8143930,
"updated_at": "2026-09-25T05:17:09-04:00",
"title": "Backend Engineer",
"first_published": "2026-08-24T09:04:42-04:00",
"content": "&lt;div class=&quot;intro&quot;&gt;&lt;p&gt;&lt;strong&gt;About us&lt;/strong&gt;&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Go &amp;amp; Kotlin&lt;/li&gt;&lt;li&gt;On-call&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;"
}], "meta": {"total": 1}}`))
})
jobs, err := s.fetchGreenhouse(context.Background(), models.JobSource{Kind: SourceGreenhouse, Label: "Monzo", Token: "Monzo"})
if err != nil {
t.Fatalf("fetchGreenhouse: %v", err)
}
if path != "/v1/boards/Monzo/jobs?content=true" {
t.Errorf("request = %q", path)
}
if len(jobs) != 1 {
t.Fatalf("got %d jobs", len(jobs))
}
j := jobs[0]
// The id is namespaced by the board, lowercased so "Monzo" and "monzo"
// are one board.
if j.ExternalID != "monzo/8143930" || j.Title != "Backend Engineer" || j.Company != "Monzo" ||
j.Location != "Cardiff, London or Remote (UK)" || j.URL != "https://job-boards.greenhouse.io/monzo/jobs/8143930" {
t.Errorf("job = %+v", j)
}
// Doubly escaped HTML comes out as plain lines.
if j.Description != "About us\n\nGo & Kotlin\n\nOn-call" {
t.Errorf("description = %q", j.Description)
}
if j.PostedAt == nil || j.PostedAt.UTC().Format("2006-01-02") != "2026-08-24" {
t.Errorf("postedAt = %v", j.PostedAt)
}
}
func TestFetchLever(t *testing.T) {
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
if r.URL.RequestURI() != "/v0/postings/acme?mode=json" {
t.Errorf("request = %q", r.URL.RequestURI())
}
w.Write([]byte(`[{
"additionalPlain": "We are an equal opportunity employer.",
"categories": {"commitment": "Full-time", "location": "London, UK", "team": "Platform"},
"createdAt": 1786469891368,
"descriptionPlain": "A World-Changing Company\n",
"id": "6ed76ce8-4156",
"lists": [{"text": "What you'll do", "content": "<li>Build things</li><li>Run them</li>"}],
"text": "Platform Engineer",
"workplaceType": "hybrid",
"hostedUrl": "https://jobs.lever.co/acme/6ed76ce8-4156"
}]`))
})
jobs, err := s.fetchLever(context.Background(), models.JobSource{Kind: SourceLever, Label: "Acme", Token: "acme"})
if err != nil || len(jobs) != 1 {
t.Fatalf("fetchLever: %v, %d jobs", err, len(jobs))
}
j := jobs[0]
if j.ExternalID != "acme/6ed76ce8-4156" || j.Title != "Platform Engineer" || j.Location != "London, UK (hybrid)" {
t.Errorf("job = %+v", j)
}
want := "A World-Changing Company\n\nWhat you'll do\nBuild things\n\nRun them\n\nWe are an equal opportunity employer."
if j.Description != want {
t.Errorf("description = %q\nwant %q", j.Description, want)
}
if j.PostedAt == nil || j.PostedAt.Year() != 2026 {
t.Errorf("postedAt = %v", j.PostedAt)
}
}
func TestFetchAshbySkipsUnlisted(t *testing.T) {
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/posting-api/job-board/ramp" {
t.Errorf("path = %q", r.URL.Path)
}
w.Write([]byte(`{"apiVersion": "1", "jobs": [
{"id": "34413f8d", "title": " Security Engineer, Cloud", "location": "London", "workplaceType": "Remote",
"publishedAt": "2026-04-07T17:12:35.753+00:00", "isListed": true,
"jobUrl": "https://jobs.ashbyhq.com/ramp/34413f8d", "descriptionPlain": "ABOUT RAMP\n\nRamp is building."},
{"id": "hidden", "title": "Secret", "isListed": false, "jobUrl": "https://jobs.ashbyhq.com/ramp/hidden"}
]}`))
})
jobs, err := s.fetchAshby(context.Background(), models.JobSource{Kind: SourceAshby, Label: "Ramp", Token: "ramp"})
if err != nil || len(jobs) != 1 {
t.Fatalf("fetchAshby: %v, %d jobs", err, len(jobs))
}
j := jobs[0]
if j.ExternalID != "ramp/34413f8d" || j.Title != "Security Engineer, Cloud" || j.Location != "London (remote)" ||
j.Description != "ABOUT RAMP\n\nRamp is building." || j.PostedAt == nil {
t.Errorf("job = %+v", j)
}
}
func TestFetchAdzuna(t *testing.T) {
var requests []string
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "key1"}, func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.URL.Path)
q := r.URL.Query()
if q.Get("app_id") != "id1" || q.Get("app_key") != "key1" || q.Get("what") != "golang" || q.Get("where") != "London" {
t.Errorf("query = %v", q)
}
w.Write([]byte(`{"results": [{
"id": "5012345678", "title": "<strong>Golang</strong> Developer",
"description": "We need a <strong>Golang</strong> developer…",
"redirect_url": "https://www.adzuna.co.uk/jobs/land/ad/5012345678?se=abc",
"created": "2026-10-01T09:00:00Z",
"company": {"display_name": "Acme Ltd"}, "location": {"display_name": "London, UK"}
}]}`))
})
jobs, err := s.fetchAdzuna(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "golang", Location: "London"})
if err != nil || len(jobs) != 1 {
t.Fatalf("fetchAdzuna: %v, %d jobs", err, len(jobs))
}
// A short page is the last page: no second request.
if len(requests) != 1 || requests[0] != "/v1/api/jobs/gb/search/1" {
t.Errorf("requests = %v", requests)
}
j := jobs[0]
if j.ExternalID != "5012345678" || j.Title != "Golang Developer" || j.Company != "Acme Ltd" ||
j.Description != "We need a Golang developer…" || j.detailID != "" {
t.Errorf("job = %+v", j)
}
}
func TestFetchReed(t *testing.T) {
s := sourceStub(t, JobLeadConfig{ReedAPIKey: "reedkey"}, func(w http.ResponseWriter, r *http.Request) {
// The key is the basic-auth username, with an empty password.
if user, pass, ok := r.BasicAuth(); !ok || user != "reedkey" || pass != "" {
t.Errorf("basic auth = %q %q %v", user, pass, ok)
}
switch r.URL.Path {
case "/api/1.0/search":
if q := r.URL.Query(); q.Get("keywords") != "golang" || q.Get("locationName") != "London" {
t.Errorf("query = %v", q)
}
w.Write([]byte(`{"results": [{"jobId": 51234567, "employerName": "Acme", "jobTitle": "Go Engineer",
"locationName": "London", "date": "03/10/2026", "jobDescription": "Snippet…",
"jobUrl": "https://www.reed.co.uk/jobs/go-engineer/51234567"}], "totalResults": 1}`))
case "/api/1.0/jobs/51234567":
w.Write([]byte(`{"jobId": 51234567, "jobDescription": "<p>The full advert.</p><p>Second paragraph.</p>"}`))
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
})
jobs, err := s.fetchReed(context.Background(), models.JobSource{Kind: SourceReed, Query: "golang", Location: "London"})
if err != nil || len(jobs) != 1 {
t.Fatalf("fetchReed: %v, %d jobs", err, len(jobs))
}
j := jobs[0]
if j.ExternalID != "51234567" || j.Company != "Acme" || j.Description != "Snippet…" || j.detailID != "51234567" {
t.Errorf("job = %+v", j)
}
if j.PostedAt == nil || j.PostedAt.Format("2006-01-02") != "2026-10-03" {
t.Errorf("postedAt = %v", j.PostedAt)
}
full, err := s.fetchReedDescription(context.Background(), j.detailID)
if err != nil || full != "The full advert.\n\nSecond paragraph." {
t.Errorf("fetchReedDescription = %q, %v", full, err)
}
}
func TestSearchSourcesNeedTheirKeys(t *testing.T) {
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
t.Errorf("no request should be made without a key, got %s", r.URL.Path)
})
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"}); err == nil || !strings.Contains(err.Error(), "ADZUNA_APP_ID") {
t.Errorf("adzuna err = %v", err)
}
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceReed, Query: "go"}); err == nil || !strings.Contains(err.Error(), "REED_API_KEY") {
t.Errorf("reed err = %v", err)
}
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: "monster"}); err == nil {
t.Error("an unknown kind should be an error")
}
}
// The error ends up in JobSource.LastError, on the page. It must say what to
// fix and must never quote the request URL, which for Adzuna holds the key.
func TestSourceErrorsAreSafeToShow(t *testing.T) {
cases := []struct {
status int
want string
}{
{http.StatusNotFound, "check the board token"},
{http.StatusUnauthorized, "check the API key"},
{http.StatusInternalServerError, "source returned 500"},
}
for _, c := range cases {
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "sekrit"}, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(c.status)
})
_, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"})
if err == nil || !strings.Contains(err.Error(), c.want) || strings.Contains(err.Error(), "sekrit") {
t.Errorf("status %d: err = %v", c.status, err)
}
}
// A connection failure is the case where net/http would quote the URL.
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "sekrit"}, func(http.ResponseWriter, *http.Request) {})
adzunaBase = "http://127.0.0.1:1"
_, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"})
if err == nil || strings.Contains(err.Error(), "sekrit") {
t.Errorf("connection failure: err = %v", err)
}
s = sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("<html>")) })
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceLever, Token: "acme"}); err == nil || !strings.Contains(err.Error(), "unexpected response") {
t.Errorf("non-JSON reply: err = %v", err)
}
}
func TestHTMLToText(t *testing.T) {
cases := []struct{ in, want string }{
{"<p>One</p><p>Two</p>", "One\n\nTwo"},
{"<ul><li>a</li><li>b &amp; c</li></ul>", "a\n\nb & c"},
{"plain text here", "plain text here"},
{"<span>inline</span> <b>tags</b> stay on a line", "inline tags stay on a line"},
{"line<br>break<br/>twice", "line\nbreak\ntwice"},
{"", ""},
}
for _, c := range cases {
if got := htmlToText(c.in); got != c.want {
t.Errorf("htmlToText(%q) = %q, want %q", c.in, got, c.want)
}
}
}
func TestWithWorkplace(t *testing.T) {
cases := []struct{ location, workplace, want string }{
{"London", "Hybrid", "London (hybrid)"},
{"Remote - UK", "remote", "Remote - UK"},
{"", "Remote", "remote"},
{"London", "", "London"},
{"London", "unspecified", "London"},
}
for _, c := range cases {
if got := withWorkplace(c.location, c.workplace); got != c.want {
t.Errorf("withWorkplace(%q, %q) = %q, want %q", c.location, c.workplace, got, c.want)
}
}
}
+241
View File
@@ -0,0 +1,241 @@
package services
import (
"fmt"
"net/url"
"regexp"
"strings"
"time"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// Adding a posting to the job tracker without making a second row for one
// that is already there. Three callers share this: the browser capture
// endpoint (handlers/handle_job_capture.go), promoting a discovered lead
// (graph/job_lead.resolvers.go), and the lead fetcher (job_leads.go), which
// uses the URL matching to keep a posting already tracked out of the inbox.
// It lives in services because the fetcher does, and services cannot import
// handlers.
// trackingParams are query parameters that say how the visitor arrived, not
// which posting this is. Anything not listed is kept: ATS boards identify the
// job in the query string often enough (gh_jid, jk, jobId) that dropping
// unknown parameters would merge different postings.
var trackingParams = map[string]bool{
"trk": true, "trackingid": true, "refid": true, "ebp": true,
"gh_src": true, "lever-source": true, "lever-origin": true,
"source": true, "src": true, "ref": true,
"fbclid": true, "gclid": true, "mc_cid": true, "mc_eid": true,
}
// linkedInJobPath matches both forms of a LinkedIn posting path: the bare
// /jobs/view/123 and the public slug form /jobs/view/some-title-at-co-123.
var linkedInJobPath = regexp.MustCompile(`^/jobs/view/(?:.*-)?(\d+)/?$`)
// CanonicalJobURL reduces a posting URL to a form that is the same however
// the page was reached, so it can serve as the key that decides whether a
// posting is already tracked. ok is false for anything that is not an
// absolute http(s) URL.
//
// LinkedIn gets its own rule because the same posting appears under several
// paths (search results, collections, the recommended feed), all carrying the
// id in ?currentJobId= rather than in the path.
func CanonicalJobURL(raw string) (canonical string, ok bool) {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return "", false
}
host := strings.ToLower(u.Host)
query := u.Query()
if host == "linkedin.com" || strings.HasSuffix(host, ".linkedin.com") {
id := query.Get("currentJobId")
if m := linkedInJobPath.FindStringSubmatch(u.Path); m != nil {
id = m[1]
}
if id != "" && strings.Trim(id, "0123456789") == "" {
return "https://www.linkedin.com/jobs/view/" + id + "/", true
}
}
for key := range query {
lowered := strings.ToLower(key)
if trackingParams[lowered] || strings.HasPrefix(lowered, "utm_") {
query.Del(key)
}
}
out := url.URL{
Scheme: u.Scheme,
Host: host,
// A trailing slash is not a different posting.
Path: strings.TrimRight(u.Path, "/"),
// Encode sorts by key, so parameter order does not matter either.
RawQuery: query.Encode(),
}
return out.String(), true
}
// FindApplicationByURL returns the newest live application stored under this posting's
// URL, or nil. The raw form is tried as well as the canonical one because rows
// typed into the tracker by hand hold whatever was pasted.
func FindApplicationByURL(db *gorm.DB, canonical, raw string) (*models.JobApplication, error) {
return firstApplication(db.Where("url IN ?", []string{canonical, strings.TrimSpace(raw)}))
}
// firstApplication returns the newest row the query matches, or nil for none.
// Limit(1).Find rather than First: a miss is the ordinary answer here (every
// badge lookup on an untracked posting), and First reports one as
// ErrRecordNotFound, which GORM writes to the log as an error each time.
func firstApplication(query *gorm.DB) (*models.JobApplication, error) {
var apps []models.JobApplication
if err := query.Order("created_at DESC, id DESC").Limit(1).Find(&apps).Error; err != nil {
return nil, err
}
if len(apps) == 0 {
return nil, nil
}
return &apps[0], nil
}
// JobCaptureInput is a posting to add to the tracker. Its JSON form is the
// body of POST /jobs/capture: the popup's fields.
type JobCaptureInput struct {
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Location string `json:"location"`
URL string `json:"url"`
Status string `json:"status"`
Notes string `json:"notes"`
Description string `json:"description"`
}
func nonEmpty(p *string) bool { return p != nil && strings.TrimSpace(*p) != "" }
// MergeCapture folds a repeat capture into the application it matched and
// reports whether anything changed.
//
// It only ever adds: the status moves forwards or not at all (the same rule
// the email pipeline follows, so re-capturing a posting marked "saved" cannot
// pull an interviewing application back), and a field already holding a value
// is left alone, because the row may have been corrected by hand since. Title
// and company are never touched — they are the key the email pipeline matches
// on.
func MergeCapture(app *models.JobApplication, in JobCaptureInput, now time.Time) bool {
changed := false
if status := NormalizeStatus(in.Status); StatusAdvances(app.Status, status) {
app.Status = status
changed = true
}
// Saved-then-applied is the common path here, and the moment of the
// second capture is the application date.
if app.AppliedAt == nil && app.Status == "applied" {
app.AppliedAt = &now
changed = true
}
fill := func(field **string, value string) {
if value != "" && !nonEmpty(*field) {
*field = &value
changed = true
}
}
fill(&app.Location, in.Location)
fill(&app.URL, in.URL)
fill(&app.Description, in.Description)
// Notes accumulate, as they do when the pipeline updates a row, but a
// repeat capture of the same page must not append the same line twice.
if in.Notes != "" {
switch {
case !nonEmpty(app.Notes):
app.Notes = &in.Notes
changed = true
case !strings.Contains(*app.Notes, in.Notes):
combined := *app.Notes + "\n" + in.Notes
app.Notes = &combined
changed = true
}
}
return changed
}
// JobInputError is a problem with the input itself (a missing title, a URL
// that is not one), worded for the person who sent it. Anything else
// UpsertJobApplication returns is a database failure and belongs in the log.
type JobInputError struct{ msg string }
func (e *JobInputError) Error() string { return e.msg }
// UpsertJobApplication adds a posting to the tracker, or folds it into the
// application it matches, and reports which: "created", "updated" or
// "unchanged".
//
// The upsert matters beyond tidiness: the email pipeline identifies an
// application by (company, job title), so two rows for one posting means the
// confirmation email advances only one of them.
//
// Match order is the posting URL, then (company, job title) compared the way
// the pipeline compares them. Only live rows match — unlike the pipeline's
// lookup, which also sees deleted rows so that an email cannot resurrect one.
// Capturing or promoting is a deliberate act, so doing it for a posting whose
// row was deleted makes a new row.
//
// The caller bounds Description's length; everything else is trimmed here.
func UpsertJobApplication(db *gorm.DB, input JobCaptureInput, now time.Time) (*models.JobApplication, string, error) {
input.JobTitle = strings.TrimSpace(input.JobTitle)
input.Company = strings.TrimSpace(input.Company)
input.Location = strings.TrimSpace(input.Location)
input.Notes = strings.TrimSpace(input.Notes)
input.Description = strings.TrimSpace(input.Description)
if input.JobTitle == "" || input.Company == "" {
return nil, "", &JobInputError{"jobTitle and company are required"}
}
rawURL := input.URL
if strings.TrimSpace(rawURL) != "" {
canonical, ok := CanonicalJobURL(rawURL)
if !ok {
return nil, "", &JobInputError{"url must be an absolute http(s) URL"}
}
input.URL = canonical
} else {
input.URL = ""
}
var existing *models.JobApplication
var err error
if input.URL != "" {
existing, err = FindApplicationByURL(db, input.URL, rawURL)
}
if err == nil && existing == nil {
existing, err = firstApplication(db.Where(
"LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", input.Company, input.JobTitle))
}
if err != nil {
return nil, "", fmt.Errorf("looking up the application: %w", err)
}
if existing != nil {
if !MergeCapture(existing, input, now) {
return existing, "unchanged", nil
}
if err := db.Save(existing).Error; err != nil {
return nil, "", fmt.Errorf("updating the application: %w", err)
}
return existing, "updated", nil
}
// A new row is the merge of the input into an empty application, which
// keeps the two paths agreeing on what an empty field and "applied" mean.
// The empty status counts as unknown, so any status takes over from it.
app := models.JobApplication{JobTitle: input.JobTitle, Company: input.Company}
MergeCapture(&app, input, now)
if err := db.Create(&app).Error; err != nil {
return nil, "", fmt.Errorf("creating the application: %w", err)
}
return &app, "created", nil
}
+121
View File
@@ -0,0 +1,121 @@
package services
import (
"testing"
"time"
"adam-french.co.uk/backend/models"
)
func TestCanonicalJobURL(t *testing.T) {
const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/"
cases := []struct {
name string
in string
want string // "" means rejected
}{
// One LinkedIn posting, reached four ways, must be one key.
{"linkedin direct", "https://www.linkedin.com/jobs/view/4012345678/?trk=public_jobs", linkedIn},
{"linkedin slug form", "https://uk.linkedin.com/jobs/view/backend-engineer-at-acme-4012345678?refId=abc", linkedIn},
{"linkedin search pane", "https://www.linkedin.com/jobs/search/?currentJobId=4012345678&keywords=go", linkedIn},
{"linkedin collections pane", "https://www.linkedin.com/jobs/collections/recommended/?currentJobId=4012345678", linkedIn},
{"linkedin page with no job id is left as a normal URL", "https://www.linkedin.com/jobs/search/?keywords=go", "https://www.linkedin.com/jobs/search?keywords=go"},
{"a non-numeric linkedin id is not trusted", "https://www.linkedin.com/jobs/search/?currentJobId=4/../x", "https://www.linkedin.com/jobs/search?currentJobId=4%2F..%2Fx"},
{"a lookalike host does not get the linkedin rule", "https://notlinkedin.com/jobs/view/42", "https://notlinkedin.com/jobs/view/42"},
{"tracking parameters and the fragment are dropped", "https://jobs.lever.co/acme/abc-123?lever-source=LinkedIn&utm_medium=x#apply", "https://jobs.lever.co/acme/abc-123"},
// gh_jid IS the posting on an embedded Greenhouse board.
{"a parameter that identifies the job is kept", "https://acme.com/careers?gh_jid=77&gh_src=abc", "https://acme.com/careers?gh_jid=77"},
{"parameter order does not matter", "https://x.com/job?b=2&a=1", "https://x.com/job?a=1&b=2"},
{"host case and a trailing slash do not matter", "https://Boards.Greenhouse.io/acme/jobs/55/", "https://boards.greenhouse.io/acme/jobs/55"},
{"a relative path is rejected", "/jobs/view/1", ""},
{"a non-http scheme is rejected", "javascript:alert(1)", ""},
{"empty is rejected", "", ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, ok := CanonicalJobURL(c.in)
if ok != (c.want != "") || got != c.want {
t.Fatalf("CanonicalJobURL(%q) = %q, %v; want %q", c.in, got, ok, c.want)
}
})
}
}
func strPtr(s string) *string { return &s }
func TestMergeCapture(t *testing.T) {
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
earlier := now.Add(-48 * time.Hour)
t.Run("a new row takes every field and an applied date", func(t *testing.T) {
app := models.JobApplication{JobTitle: "Engineer", Company: "Acme"}
in := JobCaptureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Notes: "Hybrid", Description: "Full text"}
if !MergeCapture(&app, in, now) {
t.Fatal("expected a change")
}
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
if *app.Location != "London" || *app.URL != "https://x.com/1" || *app.Notes != "Hybrid" || *app.Description != "Full text" {
t.Fatalf("fields not filled: %+v", app)
}
})
t.Run("a saved posting has no applied date", func(t *testing.T) {
app := models.JobApplication{}
MergeCapture(&app, JobCaptureInput{Status: "saved"}, now)
if app.Status != "saved" || app.AppliedAt != nil {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("saved then applied advances and dates the application", func(t *testing.T) {
app := models.JobApplication{Status: "saved"}
if !MergeCapture(&app, JobCaptureInput{Status: "applied"}, now) {
t.Fatal("expected a change")
}
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("a repeat capture cannot move an application backwards", func(t *testing.T) {
app := models.JobApplication{Status: "interviewing", AppliedAt: &earlier}
if MergeCapture(&app, JobCaptureInput{Status: "saved"}, now) {
t.Fatal("expected no change")
}
if app.Status != "interviewing" || !app.AppliedAt.Equal(earlier) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("fields already set are kept, empty ones are filled", func(t *testing.T) {
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Location: strPtr("Remote"), URL: strPtr("")}
in := JobCaptureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Description: "Full text"}
if !MergeCapture(&app, in, now) {
t.Fatal("expected a change")
}
if *app.Location != "Remote" {
t.Fatalf("location overwritten: %q", *app.Location)
}
if *app.URL != "https://x.com/1" || *app.Description != "Full text" {
t.Fatalf("empty fields not filled: url=%q", *app.URL)
}
if !app.AppliedAt.Equal(earlier) {
t.Fatal("an existing applied date must not be replaced")
}
})
t.Run("notes append once", func(t *testing.T) {
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Notes: strPtr("Recruiter: Sam")}
in := JobCaptureInput{Status: "applied", Notes: "Hybrid, £70k"}
if !MergeCapture(&app, in, now) || *app.Notes != "Recruiter: Sam\nHybrid, £70k" {
t.Fatalf("notes = %q", *app.Notes)
}
if MergeCapture(&app, in, now) {
t.Fatalf("the same note was appended twice: %q", *app.Notes)
}
})
}
+2 -2
View File
@@ -12,8 +12,8 @@ import (
// Every Claude call the site makes lives in the Python service, behind an
// /internal/ route. This file is the one way the Go backend reaches those
// routes: the rowing photo reader and the job posting reader (handlers), and
// the email classifier (email_sync.go). It sits in services rather than
// routes: the rowing photo reader and the job posting reader (handlers), the
// email classifier (email_sync.go) and the job lead scorer (job_leads.go). It sits in services rather than
// handlers because both packages need it and handlers already imports
// services, not the other way round.
//
+31
View File
@@ -70,5 +70,36 @@ func SeedDatabase(db *gorm.DB) {
}
db.Create(&rowingEntries)
// Job leads, so /cv/leads has something to show without a poll: the dev
// stack usually has no Claude key, and the scheduler is off by default.
// The sources are real public boards, so "Check now" works against them.
db.Create(&models.JobSearchProfile{
ID: jobSearchProfileID,
Profile: "Five years of backend work in Go and Python. Looking for a mid-level or senior backend or platform role, in London or remote in the UK.",
IncludeKeywords: "engineer\ndeveloper",
ExcludeKeywords: "intern\nmanager",
Locations: "london\nremote",
MinScore: 60,
})
sources := []models.JobSource{
{Kind: SourceGreenhouse, Label: "Monzo", Token: "monzo", Enabled: true},
{Kind: SourceAshby, Label: "Ramp", Token: "ramp", Enabled: false},
}
db.Create(&sources)
high, mid, low := 86, 64, 35
highWhy := "Your Go and platform experience matches the core requirements; no payments background."
midWhy := "Backend fit is good, but the role wants Kotlin, which your profile does not mention."
lowWhy := "The role is a staff-level position leading several teams, above the level you are after."
posted := now.AddDate(0, 0, -3)
leads := []models.JobLead{
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-1", JobTitle: "Backend Engineer, Platform", Company: "Monzo", Location: "London or Remote (UK)", URL: "https://example.com/jobs/1", Description: "We are looking for a backend engineer to join our platform team.\n\nYou will build and run Go services.", PostedAt: &posted, LastSeenAt: now, Matched: true, State: LeadNew, Score: &high, ScoreReasons: &highWhy},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-2", JobTitle: "Senior Backend Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/2", Description: "Kotlin services at scale.", LastSeenAt: now, Matched: true, State: LeadNew, Score: &mid, ScoreReasons: &midWhy},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-3", JobTitle: "Staff Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/3", LastSeenAt: now, Matched: true, State: LeadNew, Score: &low, ScoreReasons: &lowWhy},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-4", JobTitle: "Software Engineer, Data", Company: "Monzo", Location: "Remote (UK)", URL: "https://example.com/jobs/4", LastSeenAt: now, Matched: true, State: LeadNew},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-5", JobTitle: "Account Executive", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/5", LastSeenAt: now, Matched: false, State: LeadNew},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-6", JobTitle: "Android Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/6", LastSeenAt: now, Matched: true, State: LeadDismissed, Score: &low},
}
db.Create(&leads)
log.Println("Database seeded successfully")
}