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

235 lines
13 KiB
Go

// Package models holds the GORM entities, which are also the GraphQL object
// types: gqlgen.yml maps each GraphQL type straight onto the struct here, so
// graph/model/ only contains generated input and payload types. That means
// these structs carry three sets of contracts at once — database columns,
// JSON field names for the REST endpoints, and the shape resolvers return —
// and renaming a field or changing a tag breaks at least one of them.
//
// Conventions across every model:
// - There are no migration files; services.migrateDatabase runs AutoMigrate,
// so a model must be listed there to get a table.
// - A gorm.DeletedAt field means soft delete: Delete sets deleted_at, and
// every subsequent query silently filters those rows out. Rows are never
// actually removed, and a uniqueIndex still sees deleted rows, so a
// soft-deleted row still blocks its key.
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
// On the wire an id is a quoted decimal string, "12".
package models
import (
"time"
"gorm.io/gorm"
)
// JobAppReference is a reusable snippet for filling in job application forms
// (a stock answer, a profile link, and so on), grouped by Category and
// ordered within it by SortOrder.
type JobAppReference struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Category string `gorm:"not null" json:"category"`
Label string `gorm:"not null" json:"label"`
Value string `gorm:"not null" json:"value"`
SortOrder int `gorm:"default:0" json:"sortOrder"`
}
// ProcessedEmail records that the email pipeline has already looked at a
// message, so it is never classified twice.
//
// DORMANT. The email pipeline was removed (it is in git at the tag
// email-pipeline-last). Nothing reads or writes this table now; the model is
// kept, and still migrated, so the table and its history are there if the
// pipeline comes back and old mail is not processed a second time.
//
// Like JobLead it has no DeletedAt and so is NOT soft deleted — the dedup
// check must see every historical row. Its ReceivedAt drives the next sync's
// time window, so the newest row here is effectively the pipeline's cursor. A
// row is written even when classification failed, with Action "error"; see
// Attempts for how those are retried.
type ProcessedEmail struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
// The provider's message id: Microsoft Graph's id on the Graph backend,
// the RFC822 Message-ID header on IMAP. Unique, which is what makes the
// dedup check safe against a concurrent sync.
GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"`
Subject string `gorm:"not null" json:"subject"`
Action string `gorm:"not null" json:"action"`
// The application this email created or updated, if any. A plain nullable
// column, not a GORM association — nothing preloads it.
JobAppID *uint `json:"jobAppId"`
// Attempts counts how many times processing this email has been tried.
// A row with Action "error" and Attempts below the cap is retryable: the
// next sync re-processes it instead of skipping it. Once Attempts reaches
// the cap the row becomes terminal, so a genuinely unprocessable email
// (one Claude can never parse) eventually stops consuming API calls.
// Rows written before this column existed default to 1 and so get their
// remaining attempts.
Attempts int `gorm:"not null;default:1" json:"attempts"`
// ReceivedAt is the provider's own timestamp for the email, as distinct
// from CreatedAt (when we processed it). It exists so a retryable failure
// can pull the fetch window back far enough to actually re-fetch the
// email: the window is otherwise anchored to processing time, which would
// have already advanced past it. Zero for rows written before this
// column existed, and for those the clamp is skipped.
ReceivedAt time.Time `json:"receivedAt"`
}
// JobApplication is a tracked job application. Rows are created by hand
// through GraphQL, from the browser by the capture userscript (handlers/handle_job_capture.go), or by promoting a
// JobLead (services.PromoteJobLead).
//
// Status is a plain string column, but its vocabulary is fixed: the values
// ranked in services.statusOrder ("saved", "applied", "screening",
// "assessment", "interviewing", "offer", "rejected", "withdrawn"), which the
// GraphQL schema repeats as `enum JobStatus`. Every writer keeps to it —
// GraphQL refuses anything else, the capture endpoint coerces with
// services.NormalizeStatus — but the column predates that, so a reader must
// not assume an old row conforms (services.MarshalJobStatus does not).
// Capture and promotion match an existing application on its URL, then 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"`
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
// postings. Kind decides which of the other fields mean anything:
//
// - "greenhouse", "lever", "ashby": one company's public job board. Token is
// the board's slug (the "acme" in boards.greenhouse.io/acme) and Label is
// the company name every lead from it is filed under.
// - "adzuna", "reed": a keyword search. Query and Location are the search
// terms and Label is only a display name; the company comes from each
// result.
//
// The Last* fields are written by the fetcher after every poll and are what
// the leads page shows beside the source. LastError is "" after a clean poll.
type JobSource struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Kind string `gorm:"not null" json:"kind"`
Label string `gorm:"not null" json:"label"`
Token string `json:"token"`
Query string `json:"query"`
Location string `json:"location"`
// No `default:true` tag: GORM applies a default to a zero value on
// insert, which would make it impossible to create a source disabled.
Enabled bool `gorm:"not null" json:"enabled"`
LastFetchedAt *time.Time `json:"lastFetchedAt"`
LastCount int `gorm:"not null;default:0" json:"lastCount"`
LastError string `json:"lastError"`
}
// JobLead is a posting the fetcher found, waiting in the leads inbox to be
// tracked or dismissed. It is deliberately not a JobApplication: a single
// company board is hundreds of postings, almost all irrelevant, and the
// tracker and its status vocabulary are about jobs actually applied to.
//
// Like ProcessedEmail it has no DeletedAt and is NOT soft deleted. The
// (SourceKind, ExternalID) unique index is the dedup that stops every poll
// re-adding the same posting, and it only works if a dismissed lead is still
// a row: dismissal is State "dismissed", never a delete.
//
// ExternalID is the source's own id for the posting. For the board kinds it
// is "<token>/<id>", because ids are only unique within one board.
//
// State is "new", "dismissed" or "promoted" (see the LeadState constants in
// services/job_leads.go). JobAppID is set on a promoted lead and is a plain
// nullable column, not a GORM association.
//
// Matched says whether the lead passed the keyword pre-filter the last time
// the fetcher ran; only matched leads are shown by default and only they are
// scored. Score (0-100) and ScoreReasons are Claude's, and nil until scored.
// ScoredAt is when that score was given, which is how a rescore tells the
// leads it has redone from the ones it has yet to reach; it is nil on a lead
// scored before the column existed. ScoreAttempts counts failed tries, so a
// posting Claude can never score stops costing a call per run.
type JobLead struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
SourceID uint `gorm:"index" json:"sourceId"`
SourceKind string `gorm:"not null;uniqueIndex:idx_job_lead_external" json:"sourceKind"`
ExternalID string `gorm:"not null;uniqueIndex:idx_job_lead_external" json:"externalId"`
JobTitle string `gorm:"not null" json:"jobTitle"`
Company string `gorm:"not null" json:"company"`
Location string `json:"location"`
URL string `json:"url"`
Description string `gorm:"type:text" json:"description"`
PostedAt *time.Time `json:"postedAt"`
LastSeenAt time.Time `json:"lastSeenAt"`
Matched bool `gorm:"not null;default:false;index" json:"matched"`
State string `gorm:"not null;default:new;index" json:"state"`
Score *int `json:"score"`
ScoreReasons *string `json:"scoreReasons"`
ScoredAt *time.Time `json:"scoredAt"`
ScoreAttempts int `gorm:"not null;default:0" json:"scoreAttempts"`
JobAppID *uint `json:"jobAppId"`
}
// JobSearchProfile is what a lead is judged against. There is exactly one
// row, with ID 1, created on first read (services.LoadJobSearchProfile).
//
// Profile is free text about experience and what kind of job is wanted; it is
// sent to Claude with each posting. The three keyword lists hold one entry
// per line and drive the cheap pre-filter that runs before any Claude call.
// MinScore is only a display threshold for the inbox.
type JobSearchProfile struct {
ID uint `gorm:"primarykey" json:"id"`
UpdatedAt time.Time `json:"updatedAt"`
Profile string `gorm:"type:text" json:"profile"`
IncludeKeywords string `gorm:"type:text" json:"includeKeywords"`
ExcludeKeywords string `gorm:"type:text" json:"excludeKeywords"`
Locations string `gorm:"type:text" json:"locations"`
MinScore int `gorm:"not null;default:60" json:"minScore"`
}