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
+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)})
}