Files
adamf 1147bc5697
Test and publish / test (push) Successful in 2m33s
Test and publish / publish (push) Successful in 11m9s
Add application workflow and lead analytics
2026-10-23 20:45:48 +01:00

200 lines
6.3 KiB
Go

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
}