Add application workflow and lead analytics
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user