Add application workflow and lead analytics
Test and publish / test (push) Successful in 2m33s
Test and publish / publish (push) Successful in 11m9s

This commit is contained in:
2026-10-23 20:45:48 +01:00
parent d0074aea46
commit 1147bc5697
35 changed files with 4337 additions and 131 deletions
+17 -5
View File
@@ -33,7 +33,11 @@ Return ONLY a JSON object with these exact keys:
- "jobTitle": string - the role advertised, as the posting words it, without the company or location. "" if the page is not a job posting.
- "company": string - the company that is hiring, not the job board hosting the advert. "" if it is not stated.
- "location": string or null - where the job is based, e.g. "London, UK".
- "notes": string or null - one short line giving salary, contract type and working arrangement where the posting states them, e.g. "£70-85k, permanent, hybrid 2 days". null if it states none of them.
- "salaryRange": string or null - stated salary or range, without inventing currency. null if absent.
- "workArrangement": string or null - remote, hybrid or onsite, including useful detail. null if absent.
- "applicationSource": string or null - the board or source named by the page, e.g. LinkedIn or Greenhouse. null if absent.
- "requisitionId": string or null - the job/requisition/reference ID if stated. null if absent.
- "notes": string or null - one short line for contract type or other useful detail not covered above. null if absent.
No text, no markdown, no explanation. Just the JSON object.`
@@ -42,10 +46,14 @@ No text, no markdown, no explanation. Just the JSON object.`
// filled in by hand, which is a better outcome than an error. The JSON tags
// are also what the capture endpoint returns to the userscript.
type JobPosting struct {
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Location *string `json:"location"`
Notes *string `json:"notes"`
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Location *string `json:"location"`
Notes *string `json:"notes"`
SalaryRange *string `json:"salaryRange,omitempty"`
WorkArrangement *string `json:"workArrangement,omitempty"`
ApplicationSource *string `json:"applicationSource,omitempty"`
RequisitionID *string `json:"requisitionId,omitempty"`
}
// tidy trims every field and turns a blank optional one into nil. A null
@@ -55,6 +63,10 @@ func (p *JobPosting) tidy() error {
p.Company = strings.TrimSpace(p.Company)
p.Location = blankIsNil(p.Location)
p.Notes = blankIsNil(p.Notes)
p.SalaryRange = blankIsNil(p.SalaryRange)
p.WorkArrangement = blankIsNil(p.WorkArrangement)
p.ApplicationSource = blankIsNil(p.ApplicationSource)
p.RequisitionID = blankIsNil(p.RequisitionID)
return nil
}
File diff suppressed because it is too large Load Diff
+106
View File
@@ -12,8 +12,14 @@ import (
"adam-french.co.uk/job-tracker/internal/graph/model"
"adam-french.co.uk/job-tracker/internal/models"
"adam-french.co.uk/job-tracker/internal/services"
)
// Events is the resolver for the events field.
func (r *jobApplicationResolver) Events(ctx context.Context, obj *models.JobApplication) ([]*models.JobApplicationEvent, error) {
return services.ListApplicationEvents(r.Store.DB, obj.ID)
}
// CreateJobApplication is the resolver for the createJobApplication field.
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
// String! is non-null but not non-empty, and the columns are only
@@ -36,10 +42,19 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
Notes: input.Notes,
AppliedAt: input.AppliedAt,
Description: input.Description,
NextAction: input.NextAction, NextActionAt: input.NextActionAt,
ContactName: input.ContactName, ContactEmail: input.ContactEmail,
ContactRole: input.ContactRole, LastContactedAt: input.LastContactedAt,
SalaryRange: input.SalaryRange, WorkArrangement: input.WorkArrangement,
ApplicationSource: input.ApplicationSource, ResumeVersion: input.ResumeVersion,
RequisitionID: input.RequisitionID,
}
if err := r.Store.DB.Create(&app).Error; err != nil {
return nil, err
}
if _, err := services.RecordApplicationEvent(r.Store.DB, app.ID, services.ApplicationEventInput{Kind: "created", Source: "graphql"}); err != nil {
return nil, err
}
return &app, nil
}
@@ -54,6 +69,7 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
if err := r.Store.DB.First(&app, id).Error; err != nil {
return nil, err
}
oldStatus := app.Status
if input.JobTitle != nil {
if strings.TrimSpace(*input.JobTitle) == "" {
return nil, fmt.Errorf("jobTitle cannot be empty")
@@ -84,9 +100,53 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
if input.Description != nil {
app.Description = input.Description
}
if input.NextAction != nil {
app.NextAction = input.NextAction
}
if input.NextActionAt != nil {
app.NextActionAt = input.NextActionAt
}
if input.ClearNextActionAt != nil && *input.ClearNextActionAt {
app.NextActionAt = nil
}
if input.ContactName != nil {
app.ContactName = input.ContactName
}
if input.ContactEmail != nil {
app.ContactEmail = input.ContactEmail
}
if input.ContactRole != nil {
app.ContactRole = input.ContactRole
}
if input.SalaryRange != nil {
app.SalaryRange = input.SalaryRange
}
if input.WorkArrangement != nil {
app.WorkArrangement = input.WorkArrangement
}
if input.ApplicationSource != nil {
app.ApplicationSource = input.ApplicationSource
}
if input.ResumeVersion != nil {
app.ResumeVersion = input.ResumeVersion
}
if input.RequisitionID != nil {
app.RequisitionID = input.RequisitionID
}
if input.LastContactedAt != nil {
app.LastContactedAt = input.LastContactedAt
}
if err := r.Store.DB.Save(&app).Error; err != nil {
return nil, err
}
if _, err := services.RecordApplicationEvent(r.Store.DB, app.ID, services.ApplicationEventInput{Kind: "updated", Source: "graphql"}); err != nil {
return nil, err
}
if oldStatus != app.Status {
if _, err := services.RecordApplicationEvent(r.Store.DB, app.ID, services.ApplicationEventInput{Kind: "status_changed", Source: "graphql", Note: stringPtr(oldStatus + " -> " + app.Status)}); err != nil {
return nil, err
}
}
return &app, nil
}
@@ -109,6 +169,19 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo
return true, nil
}
// AddJobApplicationEvent appends a user-entered follow-up or contact event.
func (r *mutationResolver) AddJobApplicationEvent(ctx context.Context, applicationID int, input model.AddJobApplicationEventInput) (*models.JobApplicationEvent, error) {
var app models.JobApplication
if err := r.Store.DB.First(&app, applicationID).Error; err != nil {
return nil, err
}
return services.RecordApplicationEvent(r.Store.DB, uint(applicationID), services.ApplicationEventInput{
Kind: input.Kind, OccurredAt: timeValue(input.OccurredAt), Note: input.Note,
Source: stringValue(input.Source), ContactName: input.ContactName,
ContactEmail: input.ContactEmail, ContactRole: input.ContactRole,
})
}
// JobApplications is the resolver for the jobApplications field.
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
// Admin-only even though it is a query (@admin in the schema): job
@@ -137,3 +210,36 @@ func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.Job
}
return &app, nil
}
// JobApplicationEvents is the explicit activity-history query for clients that
// do not need the rest of the application object.
func (r *queryResolver) JobApplicationEvents(ctx context.Context, applicationID int) ([]*models.JobApplicationEvent, error) {
return services.ListApplicationEvents(r.Store.DB, uint(applicationID))
}
// Analytics is calculated from the same application and activity history used
// by the tracker, so the dashboard does not maintain a second data model.
func (r *queryResolver) Analytics(ctx context.Context) (*model.Analytics, error) {
stats, err := services.LoadAnalytics(r.Store.DB)
if err != nil {
return nil, err
}
result := &model.Analytics{
TotalApplications: stats.TotalApplications, ResponseCount: stats.ResponseCount,
InterviewCount: stats.InterviewCount, OfferCount: stats.OfferCount,
ResponseRate: stats.ResponseRate, InterviewRate: stats.InterviewRate, OfferRate: stats.OfferRate,
AverageDaysToResponse: stats.AverageDaysToResponse, AverageDaysToInterview: stats.AverageDaysToInterview, AverageDaysToOffer: stats.AverageDaysToOffer,
}
for _, item := range stats.StatusCounts {
result.StatusCounts = append(result.StatusCounts, &model.AnalyticsStatusCount{Status: item.Status, Count: item.Count})
}
for _, item := range stats.Transitions {
result.Transitions = append(result.Transitions, &model.AnalyticsTransition{From: item.From, To: item.To, Count: item.Count})
}
return result, nil
}
// JobApplication returns JobApplicationResolver implementation.
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
type jobApplicationResolver struct{ *Resolver }
+19
View File
@@ -0,0 +1,19 @@
package graph
import "time"
func timeValue(value *time.Time) time.Time {
if value == nil {
return time.Now()
}
return *value
}
func stringValue(value *string) string {
if value == nil {
return ""
}
return *value
}
func stringPtr(value string) *string { return &value }
+33 -1
View File
@@ -112,6 +112,21 @@ func (r *mutationResolver) PromoteJobLead(ctx context.Context, id int) (*models.
return services.PromoteJobLead(r.Store.DB, uint(id), time.Now())
}
// BulkDismissJobLeads is the resolver for the bulkDismissJobLeads field.
func (r *mutationResolver) BulkDismissJobLeads(ctx context.Context, ids []int) ([]*models.JobLead, error) {
return services.BulkLeadState(r.Store.DB, ids, services.LeadNew, services.LeadDismissed)
}
// BulkRestoreJobLeads is the resolver for the bulkRestoreJobLeads field.
func (r *mutationResolver) BulkRestoreJobLeads(ctx context.Context, ids []int) ([]*models.JobLead, error) {
return services.BulkLeadState(r.Store.DB, ids, services.LeadDismissed, services.LeadNew)
}
// BulkPromoteJobLeads is the resolver for the bulkPromoteJobLeads field.
func (r *mutationResolver) BulkPromoteJobLeads(ctx context.Context, ids []int) ([]*models.JobLead, error) {
return services.BulkPromoteJobLeads(r.Store.DB, ids, 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)
@@ -173,7 +188,7 @@ func (r *queryResolver) JobSources(ctx context.Context) ([]*models.JobSource, er
}
// JobLeads is the resolver for the jobLeads field.
func (r *queryResolver) JobLeads(ctx context.Context, state *string, includeUnmatched *bool) ([]*models.JobLead, error) {
func (r *queryResolver) JobLeads(ctx context.Context, state *string, includeUnmatched *bool, filters *model.JobLeadFilters) ([]*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 "".
@@ -186,6 +201,23 @@ func (r *queryResolver) JobLeads(ctx context.Context, state *string, includeUnma
// about it; `matched` only decides what the inbox offers.
query = query.Where("(matched = ? OR state <> ?)", true, services.LeadNew)
}
if filters != nil {
if filters.SourceKind != nil && strings.TrimSpace(*filters.SourceKind) != "" {
query = query.Where("source_kind = ?", strings.TrimSpace(*filters.SourceKind))
}
if filters.MinScore != nil {
query = query.Where("score >= ?", *filters.MinScore)
}
if filters.MaxScore != nil {
query = query.Where("score <= ?", *filters.MaxScore)
}
if filters.Location != nil && strings.TrimSpace(*filters.Location) != "" {
query = query.Where("location ILIKE ?", "%"+strings.TrimSpace(*filters.Location)+"%")
}
if filters.Company != nil && strings.TrimSpace(*filters.Company) != "" {
query = query.Where("company ILIKE ?", "%"+strings.TrimSpace(*filters.Company)+"%")
}
}
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
+83 -16
View File
@@ -6,6 +6,42 @@ import (
"time"
)
type AddJobApplicationEventInput struct {
Kind string `json:"kind"`
OccurredAt *time.Time `json:"occurredAt,omitempty"`
Note *string `json:"note,omitempty"`
Source *string `json:"source,omitempty"`
ContactName *string `json:"contactName,omitempty"`
ContactEmail *string `json:"contactEmail,omitempty"`
ContactRole *string `json:"contactRole,omitempty"`
}
type Analytics struct {
TotalApplications int `json:"totalApplications"`
StatusCounts []*AnalyticsStatusCount `json:"statusCounts"`
Transitions []*AnalyticsTransition `json:"transitions"`
ResponseCount int `json:"responseCount"`
InterviewCount int `json:"interviewCount"`
OfferCount int `json:"offerCount"`
ResponseRate float64 `json:"responseRate"`
InterviewRate float64 `json:"interviewRate"`
OfferRate float64 `json:"offerRate"`
AverageDaysToResponse *float64 `json:"averageDaysToResponse,omitempty"`
AverageDaysToInterview *float64 `json:"averageDaysToInterview,omitempty"`
AverageDaysToOffer *float64 `json:"averageDaysToOffer,omitempty"`
}
type AnalyticsStatusCount struct {
Status string `json:"status"`
Count int `json:"count"`
}
type AnalyticsTransition struct {
From string `json:"from"`
To string `json:"to"`
Count int `json:"count"`
}
type CreateJobAppReferenceInput struct {
Category string `json:"category"`
Label string `json:"label"`
@@ -14,14 +50,25 @@ 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"`
Description *string `json:"description,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"`
NextAction *string `json:"nextAction,omitempty"`
NextActionAt *time.Time `json:"nextActionAt,omitempty"`
ContactName *string `json:"contactName,omitempty"`
ContactEmail *string `json:"contactEmail,omitempty"`
ContactRole *string `json:"contactRole,omitempty"`
SalaryRange *string `json:"salaryRange,omitempty"`
WorkArrangement *string `json:"workArrangement,omitempty"`
ApplicationSource *string `json:"applicationSource,omitempty"`
ResumeVersion *string `json:"resumeVersion,omitempty"`
RequisitionID *string `json:"requisitionId,omitempty"`
LastContactedAt *time.Time `json:"lastContactedAt,omitempty"`
}
type CreateJobSourceInput struct {
@@ -33,6 +80,14 @@ type CreateJobSourceInput struct {
Enabled *bool `json:"enabled,omitempty"`
}
type JobLeadFilters struct {
SourceKind *string `json:"sourceKind,omitempty"`
MinScore *int `json:"minScore,omitempty"`
MaxScore *int `json:"maxScore,omitempty"`
Location *string `json:"location,omitempty"`
Company *string `json:"company,omitempty"`
}
type JobLeadSyncStatus struct {
Running bool `json:"running"`
LastRunAt *time.Time `json:"lastRunAt,omitempty"`
@@ -53,14 +108,26 @@ 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"`
Description *string `json:"description,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"`
NextAction *string `json:"nextAction,omitempty"`
NextActionAt *time.Time `json:"nextActionAt,omitempty"`
ClearNextActionAt *bool `json:"clearNextActionAt,omitempty"`
ContactName *string `json:"contactName,omitempty"`
ContactEmail *string `json:"contactEmail,omitempty"`
ContactRole *string `json:"contactRole,omitempty"`
SalaryRange *string `json:"salaryRange,omitempty"`
WorkArrangement *string `json:"workArrangement,omitempty"`
ApplicationSource *string `json:"applicationSource,omitempty"`
ResumeVersion *string `json:"resumeVersion,omitempty"`
RequisitionID *string `json:"requisitionId,omitempty"`
LastContactedAt *time.Time `json:"lastContactedAt,omitempty"`
}
type UpdateJobSearchProfileInput struct {
@@ -43,6 +43,57 @@ type JobApplication {
notes: String
appliedAt: Time
description: String
nextAction: String
nextActionAt: Time
contactName: String
contactEmail: String
contactRole: String
salaryRange: String
workArrangement: String
applicationSource: String
resumeVersion: String
requisitionId: String
lastContactedAt: Time
events: [JobApplicationEvent!]!
}
type JobApplicationEvent {
id: ID!
createdAt: Time!
jobApplicationId: ID!
kind: String!
occurredAt: Time!
note: String
source: String!
contactName: String
contactEmail: String
contactRole: String
}
type AnalyticsStatusCount {
status: String!
count: Int!
}
type AnalyticsTransition {
from: String!
to: String!
count: Int!
}
type Analytics {
totalApplications: Int!
statusCounts: [AnalyticsStatusCount!]!
transitions: [AnalyticsTransition!]!
responseCount: Int!
interviewCount: Int!
offerCount: Int!
responseRate: Float!
interviewRate: Float!
offerRate: Float!
averageDaysToResponse: Float
averageDaysToInterview: Float
averageDaysToOffer: Float
}
input CreateJobApplicationInput {
@@ -54,6 +105,17 @@ input CreateJobApplicationInput {
notes: String
appliedAt: Time
description: String
nextAction: String
nextActionAt: Time
contactName: String
contactEmail: String
contactRole: String
salaryRange: String
workArrangement: String
applicationSource: String
resumeVersion: String
requisitionId: String
lastContactedAt: Time
}
input UpdateJobApplicationInput {
@@ -65,11 +127,25 @@ input UpdateJobApplicationInput {
notes: String
appliedAt: Time
description: String
nextAction: String
nextActionAt: Time
clearNextActionAt: Boolean
contactName: String
contactEmail: String
contactRole: String
salaryRange: String
workArrangement: String
applicationSource: String
resumeVersion: String
requisitionId: String
lastContactedAt: Time
}
extend type Query {
jobApplications: [JobApplication!]! @admin
jobApplication(id: ID!): JobApplication @admin
jobApplicationEvents(applicationId: ID!): [JobApplicationEvent!]! @admin
analytics: Analytics! @admin
}
extend type Mutation {
@@ -78,4 +154,15 @@ extend type Mutation {
# Errors on an id that does not exist, like the other deletes; the Boolean
# is only ever true.
deleteJobApplication(id: ID!): Boolean! @admin
addJobApplicationEvent(applicationId: ID!, input: AddJobApplicationEventInput!): JobApplicationEvent! @admin
}
input AddJobApplicationEventInput {
kind: String!
occurredAt: Time
note: String
source: String
contactName: String
contactEmail: String
contactRole: String
}
+12 -1
View File
@@ -99,11 +99,19 @@ type JobLeadSyncStatus {
lastError: String!
}
input JobLeadFilters {
sourceKind: String
minScore: Int
maxScore: Int
location: String
company: 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
jobLeads(state: String, includeUnmatched: Boolean, filters: JobLeadFilters): [JobLead!]! @admin
jobLead(id: ID!): JobLead @admin
jobSearchProfile: JobSearchProfile! @admin
jobLeadSyncStatus: JobLeadSyncStatus! @admin
@@ -124,6 +132,9 @@ extend type Mutation {
# 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
bulkDismissJobLeads(ids: [ID!]!): [JobLead!]! @admin
bulkRestoreJobLeads(ids: [ID!]!): [JobLead!]! @admin
bulkPromoteJobLeads(ids: [ID!]!): [JobLead!]! @admin
updateJobSearchProfile(input: UpdateJobSearchProfileInput!): JobSearchProfile! @admin
+4
View File
@@ -206,6 +206,10 @@ func (store *Store) JobCapture(ctx *gin.Context) {
return
}
input.Description = services.TruncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
input.SalaryRange = services.TruncateRunes(strings.TrimSpace(input.SalaryRange), 300)
input.WorkArrangement = services.TruncateRunes(strings.TrimSpace(input.WorkArrangement), 200)
input.ApplicationSource = services.TruncateRunes(strings.TrimSpace(input.ApplicationSource), 200)
input.RequisitionID = services.TruncateRunes(strings.TrimSpace(input.RequisitionID), 100)
app, action, err := services.UpsertJobApplication(store.DB, input, time.Now())
var invalid *services.JobInputError
+7 -3
View File
@@ -193,7 +193,11 @@ func TestJobCaptureExtractErrors(t *testing.T) {
// page text must be cut to maxPageRunes before it is sent to Claude.
func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) {
london := "London"
f := &fakeExtractor{posting: claude.JobPosting{JobTitle: "Engineer", Company: "Acme", Location: &london}}
salary := "£70k"
arrangement := "Hybrid"
source := "LinkedIn"
requisition := "REQ-9"
f := &fakeExtractor{posting: claude.JobPosting{JobTitle: "Engineer", Company: "Acme", Location: &london, SalaryRange: &salary, WorkArrangement: &arrangement, ApplicationSource: &source, RequisitionID: &requisition}}
post := extractRoute(f)
long, _ := json.Marshal(map[string]string{"url": "https://x.com/1", "title": "Engineer | Acme", "text": strings.Repeat("é", maxPageRunes+500)})
@@ -207,8 +211,8 @@ func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) {
if n := len([]rune(f.got[2])); n != maxPageRunes {
t.Fatalf("forwarded %d runes, want %d", n, maxPageRunes)
}
// The body is the userscript's contract: these four keys.
if rec.Body.String() != `{"jobTitle":"Engineer","company":"Acme","location":"London","notes":null}` {
// The body is the userscript's contract, including metadata when extracted.
if rec.Body.String() != `{"jobTitle":"Engineer","company":"Acme","location":"London","notes":null,"salaryRange":"£70k","workArrangement":"Hybrid","applicationSource":"LinkedIn","requisitionId":"REQ-9"}` {
t.Fatalf("body = %s", rec.Body)
}
+40 -12
View File
@@ -97,18 +97,46 @@ type ProcessedEmail struct {
// 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"`
Description *string `gorm:"type:text" json:"description"`
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"`
NextAction *string `json:"nextAction"`
NextActionAt *time.Time `json:"nextActionAt"`
ContactName *string `json:"contactName"`
ContactEmail *string `json:"contactEmail"`
ContactRole *string `json:"contactRole"`
SalaryRange *string `json:"salaryRange"`
WorkArrangement *string `json:"workArrangement"`
ApplicationSource *string `json:"applicationSource"`
ResumeVersion *string `json:"resumeVersion"`
RequisitionID *string `json:"requisitionId"`
LastContactedAt *time.Time `json:"lastContactedAt"`
Events []*JobApplicationEvent `gorm:"foreignKey:JobApplicationID" json:"events,omitempty"`
}
// JobApplicationEvent is an append-only audit entry for a tracked application.
// Contact fields are copied onto the event so a later contact edit does not
// rewrite the history of who was involved at the time.
type JobApplicationEvent struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
JobApplicationID uint `gorm:"index;not null" json:"jobApplicationId"`
Kind string `gorm:"not null;index" json:"kind"`
OccurredAt time.Time `gorm:"not null;index" json:"occurredAt"`
Note *string `gorm:"type:text" json:"note"`
Source string `gorm:"not null;default:manual" json:"source"`
ContactName *string `json:"contactName"`
ContactEmail *string `json:"contactEmail"`
ContactRole *string `json:"contactRole"`
}
// JobSource is one place the lead fetcher (services/job_leads.go) polls for
+199
View File
@@ -0,0 +1,199 @@
package services
import (
"sort"
"strings"
"time"
"adam-french.co.uk/job-tracker/internal/models"
"gorm.io/gorm"
)
// Analytics is the database-independent result used by the GraphQL adapter.
// Nullable averages are represented by pointers because a missing history is
// different from a measured zero-day interval.
type Analytics struct {
TotalApplications int
StatusCounts []AnalyticsStatusCount
Transitions []AnalyticsTransition
ResponseCount int
InterviewCount int
OfferCount int
ResponseRate float64
InterviewRate float64
OfferRate float64
AverageDaysToResponse *float64
AverageDaysToInterview *float64
AverageDaysToOffer *float64
}
type AnalyticsStatusCount struct {
Status string
Count int
}
type AnalyticsTransition struct {
From string
To string
Count int
}
// LoadAnalytics reads live applications and their append-only history. Events
// belonging to soft-deleted applications are intentionally excluded.
func LoadAnalytics(db *gorm.DB) (*Analytics, error) {
var apps []*models.JobApplication
if err := db.Find(&apps).Error; err != nil {
return nil, err
}
ids := make([]uint, 0, len(apps))
for _, app := range apps {
ids = append(ids, app.ID)
}
var events []*models.JobApplicationEvent
if len(ids) > 0 {
if err := db.Where("job_application_id IN ?", ids).Order("occurred_at ASC, id ASC").Find(&events).Error; err != nil {
return nil, err
}
}
return AggregateAnalytics(apps, events), nil
}
// AggregateAnalytics derives funnel facts from current status and explicit
// activity history. A status transition is a response once it enters any
// post-application stage; this makes older status-only history useful too.
func AggregateAnalytics(apps []*models.JobApplication, events []*models.JobApplicationEvent) *Analytics {
result := &Analytics{TotalApplications: len(apps)}
status := map[string]int{}
appByID := make(map[uint]*models.JobApplication, len(apps))
for _, app := range apps {
appByID[app.ID] = app
status[app.Status]++
}
for _, s := range []string{"saved", "applied", "screening", "assessment", "interviewing", "offer", "rejected", "withdrawn"} {
if status[s] > 0 {
result.StatusCounts = append(result.StatusCounts, AnalyticsStatusCount{s, status[s]})
}
}
for s, n := range status {
if !KnownStatus(s) {
result.StatusCounts = append(result.StatusCounts, AnalyticsStatusCount{s, n})
}
}
sort.Slice(result.StatusCounts, func(i, j int) bool { return result.StatusCounts[i].Status < result.StatusCounts[j].Status })
type stages struct{ response, interview, offer *time.Time }
seen := make(map[uint]stages, len(apps))
transitions := map[string]int{}
for _, event := range events {
app, ok := appByID[event.JobApplicationID]
if !ok {
continue
}
stage := seen[app.ID]
kind := strings.ToLower(strings.TrimSpace(event.Kind))
from, to, isTransition := transition(event.Note)
if isTransition {
transitions[from+"\x00"+to]++
if isResponseStage(to) && stage.response == nil {
stage.response = &event.OccurredAt
}
if to == "interviewing" && stage.interview == nil {
stage.interview = &event.OccurredAt
}
if to == "offer" && stage.offer == nil {
stage.offer = &event.OccurredAt
}
}
if kind == "response" && stage.response == nil {
stage.response = &event.OccurredAt
}
if kind == "interview" && stage.interview == nil {
stage.interview = &event.OccurredAt
}
if kind == "offer" && stage.offer == nil {
stage.offer = &event.OccurredAt
}
seen[app.ID] = stage
}
for key, count := range transitions {
parts := strings.SplitN(key, "\x00", 2)
result.Transitions = append(result.Transitions, AnalyticsTransition{parts[0], parts[1], count})
}
sort.Slice(result.Transitions, func(i, j int) bool {
if result.Transitions[i].From == result.Transitions[j].From {
return result.Transitions[i].To < result.Transitions[j].To
}
return result.Transitions[i].From < result.Transitions[j].From
})
for _, app := range apps {
stage := seen[app.ID]
// Older applications predate activity history. Their current status is
// still enough to establish that a response has happened.
if stage.response == nil && isResponseStage(app.Status) {
stage.response = &app.UpdatedAt
}
if stage.response != nil {
result.ResponseCount++
}
if stage.interview != nil || app.Status == "interviewing" || app.Status == "offer" {
result.InterviewCount++
}
if stage.offer != nil || app.Status == "offer" {
result.OfferCount++
}
}
responseDays, interviewDays, offerDays := 0.0, 0.0, 0.0
responseSamples, interviewSamples, offerSamples := 0, 0, 0
for _, app := range apps {
stage := seen[app.ID]
if days, ok := daysBetween(app.AppliedAt, stage.response); ok {
responseDays += days
responseSamples++
}
if days, ok := daysBetween(app.AppliedAt, stage.interview); ok {
interviewDays += days
interviewSamples++
}
if days, ok := daysBetween(app.AppliedAt, stage.offer); ok {
offerDays += days
offerSamples++
}
}
if responseSamples > 0 {
value := responseDays / float64(responseSamples)
result.AverageDaysToResponse = &value
}
if interviewSamples > 0 {
value := interviewDays / float64(interviewSamples)
result.AverageDaysToInterview = &value
}
if offerSamples > 0 {
value := offerDays / float64(offerSamples)
result.AverageDaysToOffer = &value
}
if result.TotalApplications > 0 {
result.ResponseRate = float64(result.ResponseCount) / float64(result.TotalApplications)
result.InterviewRate = float64(result.InterviewCount) / float64(result.TotalApplications)
result.OfferRate = float64(result.OfferCount) / float64(result.TotalApplications)
}
return result
}
func transition(note *string) (string, string, bool) {
if note == nil {
return "", "", false
}
parts := strings.SplitN(*note, " -> ", 2)
if len(parts) != 2 {
return "", "", false
}
return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), true
}
func isResponseStage(status string) bool {
return status == "screening" || status == "assessment" || status == "interviewing" || status == "offer" || status == "rejected"
}
func daysBetween(applied *time.Time, event *time.Time) (float64, bool) {
if applied == nil || event == nil || event.Before(*applied) {
return 0, false
}
return event.Sub(*applied).Hours() / 24, true
}
+41
View File
@@ -0,0 +1,41 @@
package services
import (
"testing"
"time"
"adam-french.co.uk/job-tracker/internal/models"
)
func TestAggregateAnalyticsCountsFunnelAndTransitions(t *testing.T) {
base := time.Date(2026, 1, 1, 9, 0, 0, 0, time.UTC)
applied := base.Add(24 * time.Hour)
apps := []*models.JobApplication{{ID: 1, Status: "interviewing", AppliedAt: &applied}, {ID: 2, Status: "saved"}, {ID: 3, Status: "offer", AppliedAt: &applied}}
note := func(value string) *string { return &value }
events := []*models.JobApplicationEvent{
{JobApplicationID: 1, Kind: "status_changed", OccurredAt: base.Add(3 * 24 * time.Hour), Note: note("applied -> screening")},
{JobApplicationID: 1, Kind: "interview", OccurredAt: base.Add(5 * 24 * time.Hour)},
{JobApplicationID: 3, Kind: "status_changed", OccurredAt: base.Add(4 * 24 * time.Hour), Note: note("applied -> offer")},
}
got := AggregateAnalytics(apps, events)
if got.TotalApplications != 3 || got.ResponseCount != 2 || got.InterviewCount != 2 || got.OfferCount != 1 {
t.Fatalf("counts = %+v", got)
}
if got.ResponseRate != 2.0/3.0 || got.OfferRate != 1.0/3.0 {
t.Fatalf("rates = %+v", got)
}
if len(got.Transitions) != 2 || got.Transitions[0].Count != 1 {
t.Fatalf("transitions = %+v", got.Transitions)
}
if got.AverageDaysToResponse == nil || *got.AverageDaysToResponse != 2.5 {
t.Fatalf("response days = %v", got.AverageDaysToResponse)
}
}
func TestAggregateAnalyticsLeavesUnsupportedTimeMetricsNil(t *testing.T) {
apps := []*models.JobApplication{{ID: 1, Status: "saved"}}
got := AggregateAnalytics(apps, nil)
if got.AverageDaysToResponse != nil || got.AverageDaysToInterview != nil || got.AverageDaysToOffer != nil {
t.Fatalf("metrics = %+v", got)
}
}
+1
View File
@@ -19,6 +19,7 @@ import (
func migrateDatabase(db *gorm.DB) error {
return db.AutoMigrate(
&models.JobApplication{},
&models.JobApplicationEvent{},
&models.JobAppReference{},
// Dormant since the email pipeline was removed; see the model.
&models.ProcessedEmail{},
@@ -0,0 +1,56 @@
package services
import (
"strings"
"time"
"adam-french.co.uk/job-tracker/internal/models"
"gorm.io/gorm"
)
// ApplicationEventInput is deliberately small: application changes supply
// their own source, while a manual event can include a note and contact data.
type ApplicationEventInput struct {
Kind string
OccurredAt time.Time
Note *string
Source string
ContactName *string
ContactEmail *string
ContactRole *string
}
// RecordApplicationEvent appends an event without changing the application.
func RecordApplicationEvent(db *gorm.DB, applicationID uint, input ApplicationEventInput) (*models.JobApplicationEvent, error) {
if input.OccurredAt.IsZero() {
input.OccurredAt = time.Now()
}
if strings.TrimSpace(input.Kind) == "" {
return nil, &JobInputError{"event kind is required"}
}
if input.Source == "" {
input.Source = "manual"
}
event := &models.JobApplicationEvent{
JobApplicationID: applicationID,
Kind: strings.TrimSpace(input.Kind),
OccurredAt: input.OccurredAt,
Note: input.Note,
Source: input.Source,
ContactName: input.ContactName,
ContactEmail: input.ContactEmail,
ContactRole: input.ContactRole,
}
if err := db.Create(event).Error; err != nil {
return nil, err
}
return event, nil
}
// ListApplicationEvents returns newest activity first, with id as a stable tie-break.
func ListApplicationEvents(db *gorm.DB, applicationID uint) ([]*models.JobApplicationEvent, error) {
var events []*models.JobApplicationEvent
err := db.Where("job_application_id = ?", applicationID).
Order("occurred_at DESC, id DESC").Find(&events).Error
return events, err
}
@@ -0,0 +1,19 @@
package services
import (
"errors"
"testing"
"gorm.io/gorm"
)
func TestRecordApplicationEventRequiresKind(t *testing.T) {
_, err := RecordApplicationEvent(&gorm.DB{}, 42, ApplicationEventInput{})
var inputErr *JobInputError
if !errors.As(err, &inputErr) {
t.Fatalf("error = %v, want JobInputError", err)
}
if inputErr.Error() != "event kind is required" {
t.Fatalf("error = %q", inputErr)
}
}
+112
View File
@@ -36,6 +36,113 @@ const (
LeadPromoted = "promoted"
)
const maxBulkLeadIDs = 200
// BulkLeadState validates every row before changing any of them. This keeps a
// typo or a mixed-state selection from producing a partial bulk action.
func BulkLeadState(db *gorm.DB, ids []int, from, to string) ([]*models.JobLead, error) {
if err := validateBulkLeadIDs(ids); err != nil {
return nil, err
}
tx := db.Begin()
if tx.Error != nil {
return nil, tx.Error
}
var leads []*models.JobLead
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id IN ?", ids).Find(&leads).Error; err != nil {
tx.Rollback()
return nil, err
}
if len(leads) != len(ids) {
tx.Rollback()
return nil, fmt.Errorf("one or more leads do not exist")
}
for _, lead := range leads {
if lead.State != from {
tx.Rollback()
return nil, fmt.Errorf("lead %d is %s, expected %s", lead.ID, lead.State, from)
}
}
if err := tx.Model(&models.JobLead{}).Where("id IN ?", ids).Update("state", to).Error; err != nil {
tx.Rollback()
return nil, err
}
if err := tx.Commit().Error; err != nil {
return nil, err
}
return leadsWithIDs(db, ids)
}
func leadsWithIDs(db *gorm.DB, ids []int) ([]*models.JobLead, error) {
var leads []*models.JobLead
if err := db.Where("id IN ?", ids).Find(&leads).Error; err != nil {
return nil, err
}
byID := make(map[uint]*models.JobLead, len(leads))
for _, lead := range leads {
byID[lead.ID] = lead
}
ordered := make([]*models.JobLead, 0, len(ids))
for _, id := range ids {
ordered = append(ordered, byID[uint(id)])
}
return ordered, nil
}
// BulkPromoteJobLeads deliberately promotes one at a time: PromoteJobLead
// owns the existing application deduplication and transaction semantics.
func BulkPromoteJobLeads(db *gorm.DB, ids []int, now time.Time) ([]*models.JobLead, error) {
if err := validateBulkLeadIDs(ids); err != nil {
return nil, err
}
var leads []*models.JobLead
if err := db.Where("id IN ?", ids).Find(&leads).Error; err != nil {
return nil, err
}
if len(leads) != len(ids) {
return nil, fmt.Errorf("one or more leads do not exist")
}
for _, lead := range leads {
if lead.State != LeadNew {
return nil, fmt.Errorf("lead %d is %s, expected %s", lead.ID, lead.State, LeadNew)
}
}
tx := db.Begin()
if tx.Error != nil {
return nil, tx.Error
}
result := make([]*models.JobLead, 0, len(ids))
for _, id := range ids {
lead, err := PromoteJobLead(tx, uint(id), now)
if err != nil {
tx.Rollback()
return nil, err
}
result = append(result, lead)
}
if err := tx.Commit().Error; err != nil {
return nil, err
}
return result, nil
}
func validateBulkLeadIDs(ids []int) error {
if len(ids) == 0 || len(ids) > maxBulkLeadIDs {
return fmt.Errorf("select between 1 and %d leads", maxBulkLeadIDs)
}
seen := make(map[int]struct{}, len(ids))
for _, id := range ids {
if id <= 0 {
return fmt.Errorf("lead ids must be positive")
}
if _, ok := seen[id]; ok {
return fmt.Errorf("duplicate lead id %d", id)
}
seen[id] = struct{}{}
}
return nil
}
const (
// 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
@@ -549,6 +656,11 @@ func PromoteJobLead(db *gorm.DB, id uint, now time.Time) (*models.JobLead, error
if err != nil {
return nil, err
}
if _, err := RecordApplicationEvent(db, app.ID, ApplicationEventInput{
Kind: "promoted", OccurredAt: now, Source: "lead",
}); err != nil {
return nil, fmt.Errorf("recording promotion event: %w", 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 {
+17
View File
@@ -50,6 +50,23 @@ func TestLeadFilter(t *testing.T) {
}
}
func TestValidateBulkLeadIDs(t *testing.T) {
for name, ids := range map[string][]int{
"empty": nil,
"nonpositive": {1, 0},
"duplicate": {1, 1},
} {
t.Run(name, func(t *testing.T) {
if err := validateBulkLeadIDs(ids); err == nil {
t.Fatal("expected validation error")
}
})
}
if err := validateBulkLeadIDs([]int{3, 1, 2}); err != nil {
t.Fatalf("valid ids rejected: %v", err)
}
}
func TestContainsWord(t *testing.T) {
cases := []struct {
text, word string
+51 -7
View File
@@ -103,13 +103,19 @@ func firstApplication(query *gorm.DB) (*models.JobApplication, error) {
// JobCaptureInput is a posting to add to the tracker. Its JSON form is the
// body of POST /jobs/api/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"`
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"`
SalaryRange string `json:"salaryRange"`
WorkArrangement string `json:"workArrangement"`
ApplicationSource string `json:"applicationSource"`
ResumeVersion string `json:"resumeVersion"`
RequisitionID string `json:"requisitionId"`
ContactRole string `json:"contactRole"`
}
func nonEmpty(p *string) bool { return p != nil && strings.TrimSpace(*p) != "" }
@@ -146,6 +152,12 @@ func MergeCapture(app *models.JobApplication, in JobCaptureInput, now time.Time)
fill(&app.Location, in.Location)
fill(&app.URL, in.URL)
fill(&app.Description, in.Description)
fill(&app.SalaryRange, in.SalaryRange)
fill(&app.WorkArrangement, in.WorkArrangement)
fill(&app.ApplicationSource, in.ApplicationSource)
fill(&app.ResumeVersion, in.ResumeVersion)
fill(&app.RequisitionID, in.RequisitionID)
fill(&app.ContactRole, in.ContactRole)
// 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.
@@ -186,6 +198,11 @@ func UpsertJobApplication(db *gorm.DB, input JobCaptureInput, now time.Time) (*m
input.Location = strings.TrimSpace(input.Location)
input.Notes = strings.TrimSpace(input.Notes)
input.Description = strings.TrimSpace(input.Description)
input.SalaryRange = strings.TrimSpace(input.SalaryRange)
input.WorkArrangement = strings.TrimSpace(input.WorkArrangement)
input.ApplicationSource = strings.TrimSpace(input.ApplicationSource)
input.ResumeVersion = strings.TrimSpace(input.ResumeVersion)
input.RequisitionID = strings.TrimSpace(input.RequisitionID)
if input.JobTitle == "" || input.Company == "" {
return nil, "", &JobInputError{"jobTitle and company are required"}
}
@@ -215,12 +232,32 @@ func UpsertJobApplication(db *gorm.DB, input JobCaptureInput, now time.Time) (*m
}
if existing != nil {
oldStatus := existing.Status
if !MergeCapture(existing, input, now) {
_, eventErr := RecordApplicationEvent(db, existing.ID, ApplicationEventInput{
Kind: "captured", OccurredAt: now, Source: "capture",
})
if eventErr != nil {
return nil, "", fmt.Errorf("recording capture event: %w", eventErr)
}
return existing, "unchanged", nil
}
if err := db.Save(existing).Error; err != nil {
return nil, "", fmt.Errorf("updating the application: %w", err)
}
if _, err := RecordApplicationEvent(db, existing.ID, ApplicationEventInput{
Kind: "captured", OccurredAt: now, Source: "capture",
}); err != nil {
return nil, "", fmt.Errorf("recording capture event: %w", err)
}
if oldStatus != existing.Status {
if _, err := RecordApplicationEvent(db, existing.ID, ApplicationEventInput{
Kind: "status_changed", OccurredAt: now, Source: "capture",
Note: stringPtr(oldStatus + " -> " + existing.Status),
}); err != nil {
return nil, "", fmt.Errorf("recording status event: %w", err)
}
}
return existing, "updated", nil
}
@@ -232,5 +269,12 @@ func UpsertJobApplication(db *gorm.DB, input JobCaptureInput, now time.Time) (*m
if err := db.Create(&app).Error; err != nil {
return nil, "", fmt.Errorf("creating the application: %w", err)
}
if _, err := RecordApplicationEvent(db, app.ID, ApplicationEventInput{
Kind: "created", OccurredAt: now, Source: "capture",
}); err != nil {
return nil, "", fmt.Errorf("recording creation event: %w", err)
}
return &app, "created", nil
}
func stringPtr(value string) *string { return &value }
+14
View File
@@ -118,4 +118,18 @@ func TestMergeCapture(t *testing.T) {
t.Fatalf("the same note was appended twice: %q", *app.Notes)
}
})
t.Run("structured metadata is filled without overwriting corrections", func(t *testing.T) {
app := models.JobApplication{Status: "applied", SalaryRange: strPtr("£50k")}
in := JobCaptureInput{SalaryRange: "£70k", WorkArrangement: "Hybrid", ApplicationSource: "LinkedIn", ResumeVersion: "CV-1", RequisitionID: "REQ-9"}
if !MergeCapture(&app, in, now) {
t.Fatal("expected metadata to be added")
}
if *app.SalaryRange != "£50k" || *app.WorkArrangement != "Hybrid" || *app.ApplicationSource != "LinkedIn" || *app.ResumeVersion != "CV-1" || *app.RequisitionID != "REQ-9" {
t.Fatalf("metadata merge = %+v", app)
}
if MergeCapture(&app, in, now) {
t.Fatal("same metadata should not cause another change")
}
})
}