Add browser job capture to the job tracker
Deploy with Docker Compose / deploy (push) Successful in 1m31s
Deploy with Docker Compose / deploy (push) Successful in 1m31s
A Violentmonkey userscript, served by the site and installed from /cv/jobs, adds the posting open in the browser (LinkedIn, an ATS, any company page) to the tracker. Claude reads the title, company and location off the page text. - Three token-guarded REST routes under /api/jobs/capture (status, extract, upsert). They take a bearer token, JOB_CAPTURE_TOKEN, because the auth cookies are SameSite=Lax and never sent from another origin. An unset token switches the routes off. - The upsert matches on a canonical posting URL, then (company, job title), so a capture and the email pipeline do not make two rows for one job. - The Claude call is a new internal Python route, /internal/jobs/extract, alongside the rowing reader; the client and fence stripping they share move to python/app/claude.py. - New "saved" status ranked below "applied", and a description column holding the posting text, shown per row on the tracker. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+34
-2
@@ -83,6 +83,33 @@ for the things GraphQL cannot do:
|
||||
| `/notes/*path` | streams a file download, not JSON |
|
||||
| `/ws` | WebSocket upgrade |
|
||||
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
||||
| `/jobs/capture`, `/jobs/capture/status`, `/jobs/capture/extract` | called by a userscript on other sites' origins, where the `SameSite=Lax` auth cookies are never sent; they take a bearer token instead |
|
||||
|
||||
### Job capture
|
||||
|
||||
`handlers/handle_job_capture.go` is the server half of the browser userscript
|
||||
(`vue/public/job-capture.user.js`, installed from the tracker page) that adds
|
||||
the posting open in the browser to the job tracker.
|
||||
|
||||
- **Auth** is `Authorization: Bearer $JOB_CAPTURE_TOKEN`, checked by
|
||||
`CaptureTokenMiddleware`. The token opens these three routes and nothing
|
||||
else — it cannot read the tracker or reach GraphQL. **An unset token turns
|
||||
the routes off (503)**; it never means "no auth".
|
||||
- `GET /jobs/capture/status?url=` — is this posting already tracked, and at
|
||||
what status. Drives the script's badge.
|
||||
- `POST /jobs/capture/extract` — page text in, `{jobTitle, company, location,
|
||||
notes}` out, read by Claude through the Python service
|
||||
(`/internal/jobs/extract`). Stores nothing.
|
||||
- `POST /jobs/capture` — an **upsert**. A posting is matched by its canonical
|
||||
URL (`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
|
||||
forwards, empty fields are filled, nothing is overwritten.
|
||||
|
||||
The upsert is what keeps this and the email pipeline from making two rows for
|
||||
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.
|
||||
|
||||
## Services
|
||||
|
||||
@@ -108,8 +135,9 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
it, ask Claude to extract structured data, create or advance a
|
||||
`JobApplication`. Runs on a timer and can be triggered by an admin.
|
||||
- **claude.go** — the Anthropic client, used by the email pipeline. (The
|
||||
rowing photo reader's Claude call lives in the Python service; `POST /rowing`
|
||||
reaches it directly at `http://$PYTHON_HOST:$PYTHON_PORT/internal/rowing/read`.)
|
||||
rowing photo reader's and the job posting reader's Claude calls live in the
|
||||
Python service; `POST /rowing` and `POST /jobs/capture/extract` reach it
|
||||
directly at `http://$PYTHON_HOST:$PYTHON_PORT/internal/...`.)
|
||||
- **notes.go** — path-traversal-safe file lookup for the notes directory.
|
||||
- **seed.go** — dev-only test data. Creates an admin with the password
|
||||
`password`, so it must never run in production (`SEED_DB=true` is set only
|
||||
@@ -123,6 +151,10 @@ The `.graphql` files are the source of truth.
|
||||
cd backend && go run github.com/99designs/gqlgen generate
|
||||
```
|
||||
|
||||
If that stops with `missing go.sum entry ... urfave/cli`, the generator's own
|
||||
dependencies are not in `go.sum`. `go get github.com/99designs/gqlgen@<the
|
||||
version in go.mod>` adds them.
|
||||
|
||||
This rewrites `graph/generated.go` and `graph/model/models_gen.go` and adds
|
||||
stubs for new fields to the matching `*.resolvers.go`. Existing resolver bodies
|
||||
are preserved, but hand-written code in a regenerated file can be relocated to
|
||||
|
||||
+63
-12
@@ -100,16 +100,17 @@ type ComplexityRoot struct {
|
||||
}
|
||||
|
||||
JobApplication struct {
|
||||
AppliedAt func(childComplexity int) int
|
||||
Company func(childComplexity int) int
|
||||
CreatedAt func(childComplexity int) int
|
||||
ID func(childComplexity int) int
|
||||
JobTitle func(childComplexity int) int
|
||||
Location func(childComplexity int) int
|
||||
Notes func(childComplexity int) int
|
||||
Status func(childComplexity int) int
|
||||
URL func(childComplexity int) int
|
||||
UpdatedAt func(childComplexity int) int
|
||||
AppliedAt func(childComplexity int) int
|
||||
Company func(childComplexity int) int
|
||||
CreatedAt func(childComplexity int) int
|
||||
Description func(childComplexity int) int
|
||||
ID func(childComplexity int) int
|
||||
JobTitle func(childComplexity int) int
|
||||
Location func(childComplexity int) int
|
||||
Notes func(childComplexity int) int
|
||||
Status func(childComplexity int) int
|
||||
URL func(childComplexity int) int
|
||||
UpdatedAt func(childComplexity int) int
|
||||
}
|
||||
|
||||
Message struct {
|
||||
@@ -571,6 +572,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.JobApplication.CreatedAt(childComplexity), true
|
||||
case "JobApplication.description":
|
||||
if e.ComplexityRoot.JobApplication.Description == nil {
|
||||
break
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.JobApplication.Description(childComplexity), true
|
||||
case "JobApplication.id":
|
||||
if e.ComplexityRoot.JobApplication.ID == nil {
|
||||
break
|
||||
@@ -1560,6 +1567,8 @@ func (ec *executionContext) childFields_JobApplication(ctx context.Context, fiel
|
||||
return ec.fieldContext_JobApplication_notes(ctx, field)
|
||||
case "appliedAt":
|
||||
return ec.fieldContext_JobApplication_appliedAt(ctx, field)
|
||||
case "description":
|
||||
return ec.fieldContext_JobApplication_description(ctx, field)
|
||||
}
|
||||
return nil, fmt.Errorf("no field named %q was found under type JobApplication", field.Name)
|
||||
}
|
||||
@@ -3275,6 +3284,29 @@ func (ec *executionContext) fieldContext_JobApplication_appliedAt(_ context.Cont
|
||||
return graphql.NewScalarFieldContext("JobApplication", field, false, false, errors.New("field of type Time does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _JobApplication_description(ctx context.Context, field graphql.CollectedField, obj *models.JobApplication) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
ec.OperationContext,
|
||||
field,
|
||||
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.fieldContext_JobApplication_description(ctx, field)
|
||||
},
|
||||
func(ctx context.Context) (any, error) {
|
||||
return obj.Description, nil
|
||||
},
|
||||
nil,
|
||||
func(ctx context.Context, selections ast.SelectionSet, v *string) graphql.Marshaler {
|
||||
return ec.marshalOString2ᚖstring(ctx, selections, v)
|
||||
},
|
||||
true,
|
||||
false,
|
||||
)
|
||||
}
|
||||
func (ec *executionContext) fieldContext_JobApplication_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
|
||||
return graphql.NewScalarFieldContext("JobApplication", field, false, false, errors.New("field of type String does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _Message_id(ctx context.Context, field graphql.CollectedField, obj *models.Message) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
@@ -7456,7 +7488,7 @@ func (ec *executionContext) unmarshalInputCreateJobApplicationInput(ctx context.
|
||||
asMap[k] = v
|
||||
}
|
||||
|
||||
fieldsInOrder := [...]string{"jobTitle", "company", "location", "url", "status", "notes", "appliedAt"}
|
||||
fieldsInOrder := [...]string{"jobTitle", "company", "location", "url", "status", "notes", "appliedAt", "description"}
|
||||
for _, k := range fieldsInOrder {
|
||||
v, ok := asMap[k]
|
||||
if !ok {
|
||||
@@ -7512,6 +7544,13 @@ func (ec *executionContext) unmarshalInputCreateJobApplicationInput(ctx context.
|
||||
return it, err
|
||||
}
|
||||
it.AppliedAt = data
|
||||
case "description":
|
||||
ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description"))
|
||||
data, err := ec.unmarshalOString2ᚖstring(ctx, v)
|
||||
if err != nil {
|
||||
return it, err
|
||||
}
|
||||
it.Description = data
|
||||
}
|
||||
}
|
||||
return it, nil
|
||||
@@ -7769,7 +7808,7 @@ func (ec *executionContext) unmarshalInputUpdateJobApplicationInput(ctx context.
|
||||
asMap[k] = v
|
||||
}
|
||||
|
||||
fieldsInOrder := [...]string{"jobTitle", "company", "location", "url", "status", "notes", "appliedAt"}
|
||||
fieldsInOrder := [...]string{"jobTitle", "company", "location", "url", "status", "notes", "appliedAt", "description"}
|
||||
for _, k := range fieldsInOrder {
|
||||
v, ok := asMap[k]
|
||||
if !ok {
|
||||
@@ -7825,6 +7864,13 @@ func (ec *executionContext) unmarshalInputUpdateJobApplicationInput(ctx context.
|
||||
return it, err
|
||||
}
|
||||
it.AppliedAt = data
|
||||
case "description":
|
||||
ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description"))
|
||||
data, err := ec.unmarshalOString2ᚖstring(ctx, v)
|
||||
if err != nil {
|
||||
return it, err
|
||||
}
|
||||
it.Description = data
|
||||
}
|
||||
}
|
||||
return it, nil
|
||||
@@ -8539,6 +8585,11 @@ func (ec *executionContext) _JobApplication(ctx context.Context, sel ast.Selecti
|
||||
if out.Values[i] == graphql.RequiredNull {
|
||||
atomic.AddUint32(&out.Invalids, 1)
|
||||
}
|
||||
case "description":
|
||||
out.Values[i] = ec._JobApplication_description(ctx, field, obj)
|
||||
if out.Values[i] == graphql.RequiredNull {
|
||||
atomic.AddUint32(&out.Invalids, 1)
|
||||
}
|
||||
default:
|
||||
panic("unknown field " + strconv.Quote(field.Name))
|
||||
}
|
||||
|
||||
@@ -34,13 +34,14 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
|
||||
return nil, fmt.Errorf("jobTitle and company are required")
|
||||
}
|
||||
app := models.JobApplication{
|
||||
JobTitle: jobTitle,
|
||||
Company: company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: services.NormalizeStatus(input.Status),
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
JobTitle: jobTitle,
|
||||
Company: company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: services.NormalizeStatus(input.Status),
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
Description: input.Description,
|
||||
}
|
||||
if err := r.Store.DB.Create(&app).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -89,6 +90,9 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
if input.AppliedAt != nil {
|
||||
app.AppliedAt = input.AppliedAt
|
||||
}
|
||||
if input.Description != nil {
|
||||
app.Description = input.Description
|
||||
}
|
||||
if err := r.Store.DB.Save(&app).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -38,13 +38,14 @@ type CreateJobAppReferenceInput struct {
|
||||
}
|
||||
|
||||
type CreateJobApplicationInput struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
type CreatePlaceInput struct {
|
||||
@@ -138,13 +139,14 @@ type UpdateJobAppReferenceInput struct {
|
||||
}
|
||||
|
||||
type UpdateJobApplicationInput struct {
|
||||
JobTitle *string `json:"jobTitle,omitempty"`
|
||||
Company *string `json:"company,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
JobTitle *string `json:"jobTitle,omitempty"`
|
||||
Company *string `json:"company,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
type UpdatePlaceInput struct {
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
# Job application tracker. Rows come from these mutations or automatically
|
||||
# from the email sync pipeline (backend/services/email_sync.go). These are
|
||||
# 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-only as well as the mutations.
|
||||
#
|
||||
# status is a free-form String, but only the values ranked in
|
||||
# services.statusOrder can be advanced automatically by the email pipeline:
|
||||
# applied, screening, assessment, interviewing, offer, rejected, withdrawn.
|
||||
# saved, applied, screening, assessment, interviewing, offer, rejected,
|
||||
# withdrawn.
|
||||
#
|
||||
# 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.
|
||||
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
@@ -17,6 +22,7 @@ type JobApplication {
|
||||
status: String!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
input CreateJobApplicationInput {
|
||||
@@ -27,6 +33,7 @@ input CreateJobApplicationInput {
|
||||
status: String!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
input UpdateJobApplicationInput {
|
||||
@@ -37,6 +44,7 @@ input UpdateJobApplicationInput {
|
||||
status: String
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
|
||||
@@ -38,6 +38,7 @@ var configVars = []ConfigVar{
|
||||
{"STEAM_API_KEY", "Steam status widget", false},
|
||||
{"STEAM_ID", "Steam status widget", false},
|
||||
{"CLAUDE_API_KEY", "Email summarisation", false},
|
||||
{"JOB_CAPTURE_TOKEN", "Job capture userscript", false},
|
||||
{"EMAIL_BACKEND", "Email sync (graph/imap)", false},
|
||||
{"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false},
|
||||
{"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false},
|
||||
@@ -81,6 +82,7 @@ func (store *Store) ConfigCheck(ctx *gin.Context) {
|
||||
"SPOTIFY_CLIENT_SECRET": true,
|
||||
"MSGRAPH_CLIENT_SECRET": true,
|
||||
"CLAUDE_API_KEY": true,
|
||||
"JOB_CAPTURE_TOKEN": true,
|
||||
"STEAM_API_KEY": true,
|
||||
"IMAP_PASSWORD": true,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"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 userscripts/job-capture.user.js,
|
||||
// which adds the posting open in the browser to the job tracker.
|
||||
//
|
||||
// These are REST, and token-authenticated, because the caller is a userscript
|
||||
// running on someone else's origin (linkedin.com, an ATS). The auth cookies
|
||||
// are SameSite=Lax and never accompany such a request, so the GraphQL
|
||||
// mutations, which rely on them, are out of reach from there.
|
||||
//
|
||||
// The token is deliberately narrow: it opens these routes and nothing else,
|
||||
// so a token leaked from the browser can add rows to the tracker and spend
|
||||
// Claude calls, but cannot read the tracker, edit other data or log in.
|
||||
//
|
||||
// As with rowing, the Claude call lives in the Python service
|
||||
// (python/app/jobs.py) and everything touching the database stays here.
|
||||
|
||||
const (
|
||||
// jobExtractPath is internal in the same way as rowingReadPath: nginx
|
||||
// refuses /py/internal/ and the route refuses anything nginx forwarded.
|
||||
jobExtractPath = "/internal/jobs/extract"
|
||||
|
||||
// maxCaptureBody bounds a capture request. A long posting is tens of
|
||||
// kilobytes of text; the userscript trims the page to maxPageRunes before
|
||||
// sending, so anything near this limit is not a job page.
|
||||
maxCaptureBody = 512 << 10
|
||||
|
||||
// maxPageRunes caps both the text sent to Claude and the description
|
||||
// stored. It mirrors MAX_TEXT_CHARS in python/app/jobs.py, which rejects
|
||||
// anything longer, so the cut has to happen on this side.
|
||||
maxPageRunes = 40_000
|
||||
)
|
||||
|
||||
// jobExtractClient bounds the wait on the Python service; see
|
||||
// rowingReadClient for why two minutes.
|
||||
var jobExtractClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// CaptureTokenMiddleware guards the capture routes with JOB_CAPTURE_TOKEN,
|
||||
// presented as "Authorization: Bearer <token>".
|
||||
//
|
||||
// An unset token turns the routes off (503) rather than leaving them open:
|
||||
// an empty env var is the stack's failure mode for a forgotten secret (see
|
||||
// .env.example), and comparing "" to "" would otherwise let everyone in.
|
||||
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
|
||||
if store.JobCaptureToken == "" {
|
||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
|
||||
return
|
||||
}
|
||||
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
|
||||
if !ok || subtle.ConstantTimeCompare([]byte(presented), []byte(store.JobCaptureToken)) != 1 {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// 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.
|
||||
type capturedJob struct {
|
||||
ID uint `json:"id"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
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)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
|
||||
return
|
||||
}
|
||||
app, err := store.findByURL(canonical, raw)
|
||||
if err != nil {
|
||||
log.Println("Job capture status lookup failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
if app == nil {
|
||||
ctx.JSON(http.StatusOK, gin.H{"found": false})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"found": true, "application": capturedJobOf(app)})
|
||||
}
|
||||
|
||||
// ExtractedJobPosting is the JSON contract for what Claude reads off a job
|
||||
// page: the body of the Python service's reply (JobPosting in
|
||||
// python/app/jobs.py). Empty strings and nulls mean "not found on the page".
|
||||
type ExtractedJobPosting struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// postingReadError is a failure the Python service reported in words that are
|
||||
// safe to show in the capture popup (its 502 detail); the job-capture
|
||||
// counterpart of displayReadError.
|
||||
type postingReadError struct{ detail string }
|
||||
|
||||
func (e *postingReadError) Error() string { return e.detail }
|
||||
|
||||
// extractJobPosting sends a page's text to the Python service and returns the
|
||||
// fields Claude picked out. It mirrors readRowingDisplay, including which
|
||||
// replies are relayed and which are only logged.
|
||||
func (store *Store) extractJobPosting(ctx context.Context, pageURL, title, text string) (ExtractedJobPosting, error) {
|
||||
var posting ExtractedJobPosting
|
||||
|
||||
body, err := json.Marshal(struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}{pageURL, title, text})
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+jobExtractPath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := jobExtractClient.Do(req)
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var failure struct {
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
|
||||
return posting, &postingReadError{detail: failure.Detail}
|
||||
}
|
||||
return posting, fmt.Errorf("job extractor returned %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&posting); err != nil {
|
||||
return posting, fmt.Errorf("decoding job extractor response: %w", err)
|
||||
}
|
||||
return posting, nil
|
||||
}
|
||||
|
||||
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
|
||||
// is still valid UTF-8 for Postgres and for JSON.
|
||||
func truncateRunes(s string, max int) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= max {
|
||||
return s
|
||||
}
|
||||
return string(runes[:max])
|
||||
}
|
||||
|
||||
// bindCapture decodes a size-limited JSON body, answering 400 itself when it
|
||||
// cannot.
|
||||
func bindCapture(ctx *gin.Context, into any) bool {
|
||||
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxCaptureBody)
|
||||
if err := ctx.ShouldBindJSON(into); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// JobCaptureExtract backs POST /jobs/capture/extract: page text in, the
|
||||
// popup's pre-filled fields out. Nothing is stored; saving is a separate
|
||||
// request made once the fields have been checked by eye.
|
||||
func (store *Store) JobCaptureExtract(ctx *gin.Context) {
|
||||
var input struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if !bindCapture(ctx, &input) {
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(input.Text)
|
||||
if text == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "text is required"})
|
||||
return
|
||||
}
|
||||
|
||||
posting, err := store.extractJobPosting(ctx.Request.Context(),
|
||||
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
|
||||
if err != nil {
|
||||
log.Println("Job extract failed:", err)
|
||||
var readErr *postingReadError
|
||||
if errors.As(err, &readErr) {
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.detail})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": "failed to read the page"})
|
||||
return
|
||||
}
|
||||
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.
|
||||
func (store *Store) JobCapture(ctx *gin.Context) {
|
||||
var input captureInput
|
||||
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)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusCreated, gin.H{"action": "created", "application": capturedJobOf(&app)})
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// The capture handlers themselves need a database, and the only driver in
|
||||
// go.mod is postgres, so what is covered here is everything around the
|
||||
// queries: the token gate, the URL key that decides whether a posting is
|
||||
// already tracked, the merge rule for a repeat capture, and the call to the
|
||||
// Python service.
|
||||
|
||||
func TestCaptureTokenMiddleware(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
cases := []struct {
|
||||
name string
|
||||
configured string
|
||||
header string
|
||||
want int
|
||||
}{
|
||||
{"the right token is let through", "s3cret", "Bearer s3cret", http.StatusOK},
|
||||
{"a wrong token is refused", "s3cret", "Bearer nope", http.StatusUnauthorized},
|
||||
{"no header is refused", "s3cret", "", http.StatusUnauthorized},
|
||||
{"the bare token without the scheme is refused", "s3cret", "s3cret", http.StatusUnauthorized},
|
||||
// The case the middleware exists to get right: an unset token must
|
||||
// not match the empty credential of an anonymous request.
|
||||
{"an unset token switches the routes off", "", "", http.StatusServiceUnavailable},
|
||||
{"an unset token is not matched by an empty bearer", "", "Bearer ", http.StatusServiceUnavailable},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
store := &Store{JobCaptureToken: c.configured}
|
||||
r := gin.New()
|
||||
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/x", nil)
|
||||
if c.header != "" {
|
||||
req.Header.Set("Authorization", c.header)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
if rec.Code != c.want {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
if got := truncateRunes("short", 10); got != "short" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func jobExtractor(t *testing.T, handler http.HandlerFunc) *Store {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &Store{PythonURL: srv.URL}
|
||||
}
|
||||
|
||||
func TestExtractJobPostingRequestAndReply(t *testing.T) {
|
||||
var got map[string]string
|
||||
var path string
|
||||
var forwarded bool
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
// As with the rowing reader, either header makes the Python route
|
||||
// answer 404.
|
||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": null}`))
|
||||
})
|
||||
|
||||
posting, err := store.extractJobPosting(context.Background(), "https://x.com/1", "Engineer | Acme", "page text")
|
||||
if err != nil {
|
||||
t.Fatalf("extractJobPosting: %v", err)
|
||||
}
|
||||
if posting.JobTitle != "Engineer" || posting.Company != "Acme" || posting.Location == nil || *posting.Location != "London" || posting.Notes != nil {
|
||||
t.Fatalf("got %+v", posting)
|
||||
}
|
||||
if path != jobExtractPath {
|
||||
t.Fatalf("path = %q, want %q", path, jobExtractPath)
|
||||
}
|
||||
if forwarded {
|
||||
t.Fatal("request carried a proxy header the Python route rejects")
|
||||
}
|
||||
if got["url"] != "https://x.com/1" || got["title"] != "Engineer | Acme" || got["text"] != "page text" {
|
||||
t.Fatalf("request body = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractJobPostingErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a postingReadError with this message
|
||||
}{
|
||||
{"extractor failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse the posting"}`, "failed to parse the posting"},
|
||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"malformed success body", http.StatusOK, `not json`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
_, err := store.extractJobPosting(context.Background(), "https://x.com/1", "t", "text")
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var readErr *postingReadError
|
||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if readErr != nil && readErr.detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The extract handler runs without a database, so it can be driven whole: the
|
||||
// page text must be cut to the limit the Python side enforces before it is
|
||||
// forwarded, or a long page would come back as an opaque 422.
|
||||
func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
var forwardedLen int
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]string
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
forwardedLen = len([]rune(body["text"]))
|
||||
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": null, "notes": null}`))
|
||||
})
|
||||
r := gin.New()
|
||||
r.POST("/extract", store.JobCaptureExtract)
|
||||
|
||||
post := func(body string) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/extract", strings.NewReader(body)))
|
||||
return rec
|
||||
}
|
||||
|
||||
long, _ := json.Marshal(map[string]string{"url": "https://x.com/1", "title": "t", "text": strings.Repeat("é", maxPageRunes+500)})
|
||||
rec := post(string(long))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
if forwardedLen != maxPageRunes {
|
||||
t.Fatalf("forwarded %d runes, want %d", forwardedLen, maxPageRunes)
|
||||
}
|
||||
var out ExtractedJobPosting
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.Company != "Acme" {
|
||||
t.Fatalf("body = %s (%v)", rec.Body, err)
|
||||
}
|
||||
|
||||
if rec := post(`{"url": "https://x.com/1", "text": " "}`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("blank text: status = %d", rec.Code)
|
||||
}
|
||||
if rec := post(`not json`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("bad body: status = %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -35,10 +35,14 @@ type Store struct {
|
||||
EmailSync *services.EmailSyncService
|
||||
|
||||
// Base URL of the Python service on the Docker network, no trailing
|
||||
// slash. Used for the one call that bypasses nginx: reading a rowing
|
||||
// display photo (see handle_rowing.go).
|
||||
// slash. Used for the calls that bypass nginx: reading a rowing display
|
||||
// photo (handle_rowing.go) and a job posting (handle_job_capture.go).
|
||||
PythonURL string
|
||||
|
||||
// Bearer token for the browser capture routes (handle_job_capture.go).
|
||||
// Empty means those routes are switched off, not open.
|
||||
JobCaptureToken string
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
// mean "never fetched" distinctly from "fetched, empty".
|
||||
|
||||
+14
-1
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql/handler"
|
||||
@@ -160,7 +161,12 @@ func main() {
|
||||
// and the GraphQL login mutation. Nginx rate-limits the login route too.
|
||||
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
||||
|
||||
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}
|
||||
// JOB CAPTURE
|
||||
// Trimmed because a stray newline in .env would otherwise make every
|
||||
// request fail the comparison with nothing to show why.
|
||||
jobCaptureToken := strings.TrimSpace(os.Getenv("JOB_CAPTURE_TOKEN"))
|
||||
|
||||
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, JobCaptureToken: jobCaptureToken}
|
||||
|
||||
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||
// the Gin context, so the order in the admin group matters.
|
||||
@@ -169,6 +175,13 @@ func main() {
|
||||
protected := r.Group("/", store.AuthMiddlewear)
|
||||
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
||||
|
||||
// JOB CAPTURE: called by the browser userscript from other origins, so
|
||||
// these authenticate with a bearer token instead of the session cookies.
|
||||
capture := r.Group("/jobs/capture", store.CaptureTokenMiddleware)
|
||||
capture.GET("/status", store.JobCaptureStatus)
|
||||
capture.POST("/extract", store.JobCaptureExtract)
|
||||
capture.POST("", store.JobCapture)
|
||||
|
||||
// ROWING
|
||||
r.GET("/rowing", store.GetRowing)
|
||||
admin.POST("/rowing", store.CreateRowing)
|
||||
|
||||
+19
-13
@@ -207,23 +207,29 @@ type Place struct {
|
||||
}
|
||||
|
||||
// JobApplication is a tracked job application. Rows are created by hand
|
||||
// through GraphQL or automatically by the email pipeline.
|
||||
// through GraphQL, automatically by the email pipeline, or from the browser
|
||||
// by the capture userscript (handlers/handle_job_capture.go).
|
||||
//
|
||||
// Status is a free-form string, but only the values ranked in
|
||||
// services.statusOrder ("applied", "screening", "assessment",
|
||||
// services.statusOrder ("saved", "applied", "screening", "assessment",
|
||||
// "interviewing", "offer", "rejected", "withdrawn") can be advanced
|
||||
// automatically; the pipeline matches an existing application on
|
||||
// (Company, JobTitle) compared case-insensitively.
|
||||
//
|
||||
// Description is the posting's text as captured from the page, kept because
|
||||
// postings are usually taken down long before the interview. It is large, so
|
||||
// list queries should not select it.
|
||||
type JobApplication struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
JobTitle string `gorm:"not null" json:"jobTitle"`
|
||||
Company string `gorm:"not null" json:"company"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
Status string `gorm:"not null" json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
AppliedAt *time.Time `json:"appliedAt"`
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
JobTitle string `gorm:"not null" json:"jobTitle"`
|
||||
Company string `gorm:"not null" json:"company"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
Status string `gorm:"not null" json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
AppliedAt *time.Time `json:"appliedAt"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package services
|
||||
|
||||
import "testing"
|
||||
|
||||
// These tests cover the status progression rule only — statusAdvances, the
|
||||
// These tests cover the status progression rule only — StatusAdvances, the
|
||||
// predicate extracted out of updateJobApplication. The rest of
|
||||
// updateJobApplication (note appending, the DB.Save, the returned counters)
|
||||
// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is
|
||||
@@ -34,6 +34,10 @@ func TestStatusAdvances(t *testing.T) {
|
||||
// ranks above rejected, so this single pair is allowed.
|
||||
{"rejected may still become withdrawn because withdrawn ranks higher", "rejected", "withdrawn", true},
|
||||
|
||||
// saved is a browser capture that has not been applied to yet.
|
||||
{"a saved posting advances once the application is confirmed", "saved", "applied", true},
|
||||
{"an applied row cannot fall back to saved", "applied", "saved", false},
|
||||
|
||||
{"an unknown new status is never applied", "applied", "hired", false},
|
||||
{"an empty new status is never applied", "applied", "", false},
|
||||
{"an unknown new status cannot escape a terminal state either", "rejected", "ghosted", false},
|
||||
@@ -43,8 +47,8 @@ func TestStatusAdvances(t *testing.T) {
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := statusAdvances(c.current, c.next); got != c.want {
|
||||
t.Errorf("statusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
|
||||
if got := StatusAdvances(c.current, c.next); got != c.want {
|
||||
t.Errorf("StatusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -66,7 +70,7 @@ func TestTerminalStatusesRankHighest(t *testing.T) {
|
||||
|
||||
// NormalizeStatus is the guard that keeps Claude's occasional casing drift
|
||||
// ("Interview", "on hold") out of the status column: an unrecognised value
|
||||
// stored verbatim makes statusAdvances treat the row's current status as
|
||||
// stored verbatim makes StatusAdvances treat the row's current status as
|
||||
// unknown, which switches the forward-only rule off for that row entirely.
|
||||
func TestNormalizeStatus(t *testing.T) {
|
||||
cases := []struct {
|
||||
@@ -75,6 +79,7 @@ func TestNormalizeStatus(t *testing.T) {
|
||||
want string
|
||||
}{
|
||||
{"a tracked status passes through", "interviewing", "interviewing"},
|
||||
{"saved is tracked, so a capture keeps it", "saved", "saved"},
|
||||
{"casing drift is lowered, not rejected", "Interviewing", "interviewing"},
|
||||
{"surrounding whitespace is trimmed", " offer ", "offer"},
|
||||
{"an untracked status falls back to the pipeline default", "on hold", "applied"},
|
||||
|
||||
@@ -151,14 +151,19 @@ var senderDomains = []string{
|
||||
// map is treated as unknown and never applied. Note that "rejected" and
|
||||
// "withdrawn" sit at the top, so once an application reaches them nothing can
|
||||
// move it back.
|
||||
//
|
||||
// "saved" is the one status no email can produce: it marks a posting captured
|
||||
// from the browser but not applied to yet (handlers/handle_job_capture.go).
|
||||
// It ranks lowest so that the "thanks for applying" email advances the row.
|
||||
var statusOrder = map[string]int{
|
||||
"applied": 0,
|
||||
"screening": 1,
|
||||
"assessment": 2,
|
||||
"interviewing": 3,
|
||||
"offer": 4,
|
||||
"rejected": 5,
|
||||
"withdrawn": 6,
|
||||
"saved": 0,
|
||||
"applied": 1,
|
||||
"screening": 2,
|
||||
"assessment": 3,
|
||||
"interviewing": 4,
|
||||
"offer": 5,
|
||||
"rejected": 6,
|
||||
"withdrawn": 7,
|
||||
}
|
||||
|
||||
// Token persistence
|
||||
@@ -744,27 +749,36 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string
|
||||
return "created", &app.ID, nil
|
||||
}
|
||||
|
||||
// statusAdvances reports whether next is a forward move from current through
|
||||
// StatusAdvances reports whether next is a forward move from current through
|
||||
// statusOrder. Emails commonly arrive out of order (a delayed "thanks for
|
||||
// applying" after an interview invite), and this is what stops a stale email
|
||||
// dragging an application backwards. An unknown next status is never applied;
|
||||
// an unknown current status is treated as "anywhere before the start", so any
|
||||
// recognised status can take over from it.
|
||||
func statusAdvances(current, next string) bool {
|
||||
//
|
||||
// Exported because the browser capture endpoint applies the same rule.
|
||||
func StatusAdvances(current, next string) bool {
|
||||
nextOrder, nextExists := statusOrder[next]
|
||||
currentOrder, currentExists := statusOrder[current]
|
||||
return nextExists && (!currentExists || nextOrder > currentOrder)
|
||||
}
|
||||
|
||||
// updateJobApplication advances an existing application's status, but only
|
||||
// ever forwards (see statusAdvances).
|
||||
// ever forwards (see StatusAdvances).
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
if !statusAdvances(existing.Status, analysis.Status) {
|
||||
if !StatusAdvances(existing.Status, analysis.Status) {
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
existing.Status = analysis.Status
|
||||
|
||||
// A row captured as "saved" has no applied date; the email that moves it
|
||||
// to "applied" is the best evidence of when that happened.
|
||||
if existing.AppliedAt == nil && existing.Status == "applied" {
|
||||
now := time.Now()
|
||||
existing.AppliedAt = &now
|
||||
}
|
||||
|
||||
// Append to notes if Claude provided any
|
||||
if analysis.Notes != nil && *analysis.Notes != "" {
|
||||
if existing.Notes != nil && *existing.Notes != "" {
|
||||
@@ -864,7 +878,8 @@ func truncate(s string, maxLen int) string {
|
||||
|
||||
// emailClassificationPrompt must stay in sync with the EmailAnalysis struct:
|
||||
// every key it names is a field there, and the status values it lists are the
|
||||
// keys of statusOrder.
|
||||
// keys of statusOrder — all but "saved", which only the browser capture sets
|
||||
// and no email can mean.
|
||||
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
|
||||
|
||||
Return ONLY a JSON object with these exact keys:
|
||||
|
||||
Reference in New Issue
Block a user