Show NextPath employability outlook

This commit is contained in:
juvenal.diaz 2026-12-05 14:03:53 -06:00
parent 64dd4e1eee
commit 6c7bcc7c1b
6 changed files with 106 additions and 9 deletions

View File

@ -0,0 +1,37 @@
package opportunity
import (
"encoding/json"
"fmt"
"os"
)
type Snapshot struct {
Version string `json:"version"`
GeneratedAt string `json:"generated_at"`
Occupations map[string]Evidence `json:"occupations"`
}
// Load reads the latest complete snapshot. A missing cache is an expected
// state: NextPath can still provide interest matches without inventing labor
// evidence.
func Load(path string) (Snapshot, error) {
if path == "" {
return Snapshot{}, nil
}
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return Snapshot{}, nil
}
if err != nil {
return Snapshot{}, fmt.Errorf("read opportunity cache: %w", err)
}
var snapshot Snapshot
if err := json.Unmarshal(data, &snapshot); err != nil {
return Snapshot{}, fmt.Errorf("decode opportunity cache: %w", err)
}
if snapshot.Version == "" || len(snapshot.Occupations) == 0 {
return Snapshot{}, fmt.Errorf("opportunity cache is empty")
}
return snapshot, nil
}

View File

@ -0,0 +1,24 @@
package opportunity
import (
"os"
"path/filepath"
"testing"
)
func TestLoadMissingSnapshotIsAvailableState(t *testing.T) {
snapshot, err := Load(filepath.Join(t.TempDir(), "missing.json"))
if err != nil || len(snapshot.Occupations) != 0 {
t.Fatalf("Load missing = %#v, %v", snapshot, err)
}
}
func TestLoadRejectsMalformedSnapshot(t *testing.T) {
path := filepath.Join(t.TempDir(), "opportunity.json")
if err := os.WriteFile(path, []byte(`{"version":"v1","occupations":{}}`), 0o600); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err == nil {
t.Fatal("Load accepted empty snapshot")
}
}

View File

@ -15,6 +15,7 @@ import (
"my-homelab-configs/cmd/nextpath/internal/account"
"my-homelab-configs/cmd/nextpath/internal/assessment"
"my-homelab-configs/cmd/nextpath/internal/career"
"my-homelab-configs/cmd/nextpath/internal/opportunity"
)
const (
@ -24,9 +25,15 @@ const (
)
type Config struct {
SecureCookies bool
SessionTTL time.Duration
Logger *slog.Logger
SecureCookies bool
SessionTTL time.Duration
Logger *slog.Logger
OpportunityStorePath string
}
type careerResult struct {
career.Match
Outlook *opportunity.Outlook
}
type session struct {
@ -216,11 +223,28 @@ func (server *Server) results(writer http.ResponseWriter, request *http.Request)
return
}
matches := career.Rank(result, catalog, 5)
snapshot, err := opportunity.Load(server.config.OpportunityStorePath)
if err != nil {
server.config.Logger.Warn("load NextPath opportunity evidence", "error", err)
}
careerResults := make([]careerResult, 0, len(matches))
for _, match := range matches {
view := careerResult{Match: match}
if evidence, exists := snapshot.Occupations[match.Occupation.ONETSOC]; exists {
if outlook, calculateErr := opportunity.Calculate(evidence); calculateErr == nil {
view.Outlook = &outlook
} else {
server.config.Logger.Warn("calculate NextPath employability outlook", "occupation", match.Occupation.ONETSOC, "error", calculateErr)
}
}
careerResults = append(careerResults, view)
}
server.mu.Lock()
csrf := server.sessions[token].CSRFToken
server.mu.Unlock()
server.render(writer, http.StatusOK, "Your interest profile", resultsPage, map[string]any{
"Name": user.DisplayName, "Result": result, "Matches": matches, "CSRF": csrf,
"Name": user.DisplayName, "Result": result, "Matches": careerResults, "CSRF": csrf,
"OpportunityGeneratedAt": snapshot.GeneratedAt,
})
}

View File

@ -6,6 +6,7 @@ import (
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
@ -22,7 +23,17 @@ func TestCompletePrivateAssessmentFlow(t *testing.T) {
if err != nil {
t.Fatal(err)
}
testServer := httptest.NewServer(New(accounts, Config{}).Handler())
opportunityPath := filepath.Join(t.TempDir(), "opportunity.json")
if err := os.WriteFile(opportunityPath, []byte(`{
"version":"v1","generated_at":"2026-12-05T12:00:00Z","occupations":{"13-2011.00":{
"arizona_annual_graduates":100,"arizona_projected_annual_openings":100,"active_entry_level_postings":50,
"graduate_academic_year":"latest","projection_period":"2022-2032","postings_observed_at":"2026-12-05T12:00:00Z",
"geography":"Arizona","soc_to_cip_mapping_coverage":0.9,
"graduate_source_url":"https://example.test/graduates","projection_source_url":"https://example.test/projections","posting_source_url":"https://example.test/jobs"
}}}`), 0o600); err != nil {
t.Fatal(err)
}
testServer := httptest.NewServer(New(accounts, Config{OpportunityStorePath: opportunityPath}).Handler())
defer testServer.Close()
jar, _ := cookiejar.New(nil)
client := &http.Client{Jar: jar, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
@ -56,7 +67,7 @@ func TestCompletePrivateAssessmentFlow(t *testing.T) {
response = get(t, client, testServer.URL+"/results")
body := readBody(t, response)
if response.StatusCode != http.StatusOK || !strings.Contains(body, "interest profile") || !strings.Contains(body, "not ability, identity, or employability") || !strings.Contains(body, "Careers to explore next") {
if response.StatusCode != http.StatusOK || !strings.Contains(body, "interest profile") || !strings.Contains(body, "not ability or identity") || !strings.Contains(body, "Careers to explore next") || !strings.Contains(body, "Arizona employability outlook: 88%") {
t.Fatalf("unexpected results response %d: %s", response.StatusCode, body)
}
response = get(t, client, testServer.URL+"/account/export")

View File

@ -24,4 +24,4 @@ const loginPage = `{{define "content"}}<h1>Continue exploring.</h1><section clas
const assessmentPage = `{{define "content"}}<h1>What sounds interesting, {{.Name}}?</h1><p class="muted">Rate the activity itself—not whether you are already good at it.</p><div class="progress"><span style="width:{{progress .Answered .Total}}%"></span></div><p class="small muted">{{.Answered}} of {{.Total}} answered</p><section class="panel"><h2>{{.Question.Prompt}}</h2><form method="post" action="/assessment"><input type="hidden" name="csrf_token" value="{{.CSRF}}"><input type="hidden" name="question_id" value="{{.Question.ID}}"><div class="answers">{{range $value := seq}}<label><input type="radio" name="answer" value="{{$value}}" required>{{$value}}</label>{{end}}</div><div class="answers small muted"><span>Not interested</span><span></span><span>Unsure</span><span></span><span>Very interested</span></div><button type="submit">Save and continue</button></form></section>{{end}}`
const resultsPage = `{{define "content"}}<h1>Your current interest profile</h1><p>Hello {{.Name}}. Your three-letter exploration code is <code>{{.Result.Code}}</code>.</p><section class="panel">{{range .Result.Scores}}<div class="score"><strong>{{.Dimension}}</strong><div class="bar"><span style="width:{{.Percent}}%"></span></div><span>{{.Percent}}%</span></div>{{end}}</section><section class="panel"><h2>Careers to explore next</h2><p class="muted">These are personal-interest matches, not employability rankings. Arizona market and education evidence will be scored separately.</p>{{range .Matches}}<article class="panel"><div class="small muted">O*NET-SOC {{.Occupation.ONETSOC}} · interest fit {{.FitScore}}%</div><h3>{{.Occupation.Title}}</h3><p>{{.Occupation.Summary}}</p><p>{{.Reason}}</p><p><strong>Try it first:</strong> {{.Occupation.TryFirst}}</p><a href="{{.Occupation.SourceURL}}" rel="noreferrer">Review the O*NET occupation profile</a></article>{{end}}</section><section class="panel"><h2>How to use this</h2><p>{{.Result.InstrumentNotice}}</p><p class="muted">Confidence: {{.Result.Confidence}}. This describes interests, not ability, identity, or employability.</p></section><div class="actions"><a class="button" href="/account/export">Export my data</a><form method="post" action="/logout"><input type="hidden" name="csrf_token" value="{{.CSRF}}"><button class="secondary">Sign out</button></form></div><section class="panel"><h2>Delete account</h2><form method="post" action="/account/delete"><input type="hidden" name="csrf_token" value="{{.CSRF}}"><label for="confirm">Type DELETE</label><input id="confirm" name="confirm" required><button class="secondary" type="submit">Delete profile and answers</button></form></section>{{end}}`
const resultsPage = `{{define "content"}}<h1>Your current interest profile</h1><p>Hello {{.Name}}. Your three-letter exploration code is <code>{{.Result.Code}}</code>.</p><section class="panel">{{range .Result.Scores}}<div class="score"><strong>{{.Dimension}}</strong><div class="bar"><span style="width:{{.Percent}}%"></span></div><span>{{.Percent}}%</span></div>{{end}}</section><section class="panel"><h2>Careers to explore next</h2><p class="muted">Interest fit and Arizona market outlook are separate signals. The market percentage is a rough demand-to-completions comparison, not your probability of being hired.</p>{{range .Matches}}<article class="panel"><div class="small muted">O*NET-SOC {{.Occupation.ONETSOC}} · interest fit {{.FitScore}}%</div><h3>{{.Occupation.Title}}</h3><p>{{.Occupation.Summary}}</p><p>{{.Reason}}</p>{{if .Outlook}}<div class="outlook"><strong>Arizona employability outlook: {{.Outlook.EmployabilityOutlookPercent}}%</strong><p>{{.Outlook.Label}} · {{.Outlook.Confidence}} evidence confidence</p><p class="small">{{.Outlook.Evidence.ArizonaProjectedOpenings}} projected openings/year and {{.Outlook.Evidence.ActiveEntryLevelPostings}} postings observed, compared with {{.Outlook.Evidence.ArizonaAnnualGraduates}} recent Arizona completions. Demand-to-completions ratio: {{.Outlook.AnnualDemandToGraduateRatio}}.</p><p class="small muted">Formula: 75% projected annual demand coverage + 25% current posting coverage. Posting snapshot {{.Outlook.Evidence.PostingsObservedAt.Format "Jan 2, 2006"}}.</p><div class="small"><a href="{{.Outlook.Evidence.GraduateSourceURL}}" rel="noreferrer">Completion source</a> · <a href="{{.Outlook.Evidence.ProjectionSourceURL}}" rel="noreferrer">Projection source</a> · <a href="{{.Outlook.Evidence.PostingSourceURL}}" rel="noreferrer">Posting source</a></div></div>{{else}}<p class="muted"><strong>Arizona employability outlook unavailable.</strong> Complete source evidence has not been refreshed for this occupation; no percentage is estimated.</p>{{end}}<p><strong>Try it first:</strong> {{.Occupation.TryFirst}}</p><a href="{{.Occupation.SourceURL}}" rel="noreferrer">Review the O*NET occupation profile</a></article>{{end}}</section><section class="panel"><h2>How to use this</h2><p>{{.Result.InstrumentNotice}}</p><p class="muted">Confidence: {{.Result.Confidence}}. This describes interests, not ability or identity. Market outlook is contextual evidence, not a hiring promise.</p></section><div class="actions"><a class="button" href="/account/export">Export my data</a><form method="post" action="/logout"><input type="hidden" name="csrf_token" value="{{.CSRF}}"><button class="secondary">Sign out</button></form></div><section class="panel"><h2>Delete account</h2><form method="post" action="/account/delete"><input type="hidden" name="csrf_token" value="{{.CSRF}}"><label for="confirm">Type DELETE</label><input id="confirm" name="confirm" required><button class="secondary" type="submit">Delete profile and answers</button></form></section>{{end}}`

View File

@ -21,8 +21,9 @@ func main() {
os.Exit(1)
}
server := web.New(accounts, web.Config{
SecureCookies: strings.EqualFold(os.Getenv("NEXTPATH_SECURE_COOKIES"), "true"),
SessionTTL: 12 * time.Hour,
SecureCookies: strings.EqualFold(os.Getenv("NEXTPATH_SECURE_COOKIES"), "true"),
SessionTTL: 12 * time.Hour,
OpportunityStorePath: envOr("NEXTPATH_OPPORTUNITY_STORE", "./data/opportunity.json"),
})
slog.Info("NextPath listening", "address", address)
if err := http.ListenAndServe(address, server.Handler()); err != nil && !errors.Is(err, http.ErrServerClosed) {