Files
job-tracker/web/src/views/JobLeads.vue
T
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

756 lines
24 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup>
/**
* Route `/jobs/leads` — the leads inbox:
* postings the server found on its own, waiting to be tracked or dismissed.
*
* The server side is internal/services/job_leads.go. On a timer, or when
* "Check now" is pressed here, it polls the sources (JobSources.vue), keeps
* the postings that pass the keyword filter and has Claude score them against
* the profile (JobSearchProfile.vue). Nothing reaches the tracker at /jobs/
* until **Track** is pressed on a lead, which adds it there as Saved.
*
* This view owns the page header, the single error banner, the run buttons
* and the list. Data access is in stores/jobLeads.js; nothing here calls gql().
*
* There are three server jobs. "Check now" polls the sources and scores up to
* forty new leads; "Score unscored" polls nothing and scores the whole
* backlog; "Rescore all" scores every inbox lead again, for after the profile
* or the model has changed. Each takes from seconds to many minutes, so the
* button does not wait: the server starts the job and this page polls its
* status, then reloads the list when it finishes.
*/
import { ref, computed, onMounted, onBeforeUnmount, watch } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { useJobLeadsStore } from "@/stores/jobLeads";
import { useJobSearchProfileStore } from "@/stores/jobSearchProfile";
import JobSources from "./JobSources.vue";
import JobSearchProfile from "./JobSearchProfile.vue";
import Icon from "@/components/Icon.vue";
const TABS = [
{ value: "new", label: "Inbox" },
{ value: "promoted", label: "Tracked" },
{ value: "dismissed", label: "Dismissed" },
];
// Labels for JobLead.sourceKind; a COPY of the kinds in JobSources.vue.
const SOURCE_LABELS = { greenhouse: "Greenhouse", lever: "Lever", ashby: "Ashby", adzuna: "Adzuna", reed: "Reed" };
const POLL_MS = 3000;
const store = useJobLeadsStore();
const route = useRoute();
const router = useRouter();
const { leads, status, loading } = storeToRefs(store);
const { profile } = storeToRefs(useJobSearchProfileStore());
const error = ref("");
const tab = ref(["new", "promoted", "dismissed"].includes(route.query.tab) ? route.query.tab : "new");
const search = ref(typeof route.query.q === "string" ? route.query.q : "");
// Two separate "show me the rest" switches: leads scored below the profile's
// minimum (already loaded, hidden here), and leads the keyword filter
// rejected (not loaded at all until asked for — that is most of every board).
const showLowScores = ref(route.query.low === "1");
const showUnmatched = ref(route.query.unmatched === "1");
// "score" is the order the server sends; "posted" re-sorts here by the
// posting's own date.
const sortBy = ref(route.query.sort === "posted" ? "posted" : "score");
const busyId = ref(null);
const selected = ref(new Set());
const sourceFilter = ref(typeof route.query.source === "string" ? route.query.source : "");
const companyFilter = ref(typeof route.query.company === "string" ? route.query.company : "");
const locationFilter = ref(typeof route.query.location === "string" ? route.query.location : "");
const minFilter = ref(typeof route.query.min === "string" ? route.query.min : "");
const maxFilter = ref(typeof route.query.max === "string" ? route.query.max : "");
const bulkBusy = ref(false);
const sourcesBox = ref(null);
function leadsQuery() {
const query = { ...route.query };
const values = { tab, q: search, sort: sortBy, source: sourceFilter, company: companyFilter, location: locationFilter, min: minFilter, max: maxFilter };
for (const [key, state] of Object.entries(values)) state.value ? (query[key] = state.value) : delete query[key];
showLowScores.value ? (query.low = "1") : delete query.low;
showUnmatched.value ? (query.unmatched = "1") : delete query.unmatched;
return query;
}
watch([tab, search, sortBy, sourceFilter, companyFilter, locationFilter, minFilter, maxFilter, showLowScores, showUnmatched], () => {
router.replace({ query: leadsQuery() });
});
// The posting text for the one lead whose description is open.
// `undefined` in the cache means "not fetched", `""` means "fetched, none".
const descriptionId = ref(null);
const descriptions = ref({});
function fail(err) {
console.error(err);
error.value = String(err?.message ?? err);
}
function clearError() {
error.value = "";
}
async function fetchLeads() {
// The store's fetch() records its failure instead of throwing.
await store.fetch({
includeUnmatched: showUnmatched.value,
filters: {
sourceKind: sourceFilter.value || undefined,
company: companyFilter.value || undefined,
location: locationFilter.value || undefined,
minScore: minFilter.value === "" ? undefined : Number(minFilter.value),
maxScore: maxFilter.value === "" ? undefined : Number(maxFilter.value),
},
});
if (store.error) fail(store.error);
}
const minScore = computed(() => profile.value?.minScore ?? 0);
/** An unscored lead is never "low": no score is not a bad score. */
const isLow = (lead) => lead.score != null && lead.score < minScore.value;
const counts = computed(() => {
const out = { new: 0, promoted: 0, dismissed: 0 };
for (const lead of leads.value) if (lead.state in out) out[lead.state]++;
return out;
});
const inTab = computed(() => leads.value.filter((lead) => lead.state === tab.value));
const hiddenLow = computed(() =>
tab.value === "new" && !showLowScores.value ? inTab.value.filter(isLow).length : 0,
);
/** When the posting went up; when we first saw it if the source gave no date. */
const postedTime = (lead) => new Date(lead.postedAt ?? lead.createdAt).getTime();
// The server already sorts best-first, unscored after scored, newest first
// within a score, so by score this only filters. By date it re-sorts a copy;
// Array.sort is stable, so postings of the same day stay best-first.
const visibleLeads = computed(() => {
const needle = search.value.trim().toLowerCase();
const shown = inTab.value.filter((lead) => {
if (tab.value === "new" && !showLowScores.value && isLow(lead)) return false;
if (sourceFilter.value && lead.sourceKind !== sourceFilter.value) return false;
if (companyFilter.value && !lead.company.toLowerCase().includes(companyFilter.value.toLowerCase())) return false;
if (locationFilter.value && !lead.location.toLowerCase().includes(locationFilter.value.toLowerCase())) return false;
if (minFilter.value !== "" && (lead.score == null || lead.score < Number(minFilter.value))) return false;
if (maxFilter.value !== "" && (lead.score == null || lead.score > Number(maxFilter.value))) return false;
if (!needle) return true;
return [lead.jobTitle, lead.company, lead.location, lead.scoreReasons]
.some((field) => field?.toLowerCase().includes(needle));
});
if (sortBy.value === "posted") shown.sort((a, b) => postedTime(b) - postedTime(a));
return shown;
});
const selectedVisible = computed(() => visibleLeads.value.filter((lead) => selected.value.has(lead.id)));
const allVisibleSelected = computed(() => visibleLeads.value.length > 0 && selectedVisible.value.length === visibleLeads.value.length);
function toggleSelected(id) { const next = new Set(selected.value); next.has(id) ? next.delete(id) : next.add(id); selected.value = next; }
function toggleAllVisible() { selected.value = allVisibleSelected.value ? new Set() : new Set(visibleLeads.value.map((lead) => lead.id)); }
function clearSelection() { selected.value = new Set(); }
async function bulkAct(action) {
if (!selectedVisible.value.length) return;
bulkBusy.value = true;
try { await store[action](selectedVisible.value.map((lead) => lead.id)); clearSelection(); error.value = ""; }
catch (err) { fail(err); }
finally { bulkBusy.value = false; }
}
function scoreClass(lead) {
if (lead.score == null) return "jl-score-none";
if (lead.score >= 80) return "jl-score-high";
if (lead.score >= 60) return "jl-score-mid";
return "jl-score-low";
}
/** Fraction of the score ring to fill; an unscored lead gets an empty ring. */
const scoreArc = (lead) => Math.max(0, Math.min(100, lead.score ?? 0));
/** The tooltip says when, which during a rescore is how to tell new from old. */
function scoreTitle(lead) {
if (lead.score == null) return "Not scored";
const when = lead.scoredAt
? `, scored ${new Date(lead.scoredAt).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })}`
: "";
return `Fit score ${lead.score} out of 100${when}`;
}
function ageLabel(lead) {
const at = lead.postedAt ?? lead.createdAt;
if (!at) return "";
const days = Math.floor((Date.now() - new Date(at).getTime()) / 86_400_000);
const age = days <= 0 ? "today" : days === 1 ? "1 day ago" : `${days} days ago`;
return lead.postedAt ? `posted ${age}` : `found ${age}`;
}
async function act(lead, action) {
busyId.value = lead.id;
try {
await store[action](lead.id);
if (descriptionId.value === lead.id) descriptionId.value = null;
error.value = "";
} catch (err) {
fail(err);
} finally {
busyId.value = null;
}
}
async function toggleDescription(lead) {
if (descriptionId.value === lead.id) {
descriptionId.value = null;
return;
}
descriptionId.value = lead.id;
if (descriptions.value[lead.id] !== undefined) return;
try {
descriptions.value[lead.id] = await store.fetchDescription(lead.id);
} catch (err) {
descriptionId.value = null;
fail(err);
}
}
watch(showUnmatched, (value, oldValue) => {
if (value !== oldValue) fetchLeads();
});
// Run and poll
let pollTimer = null;
function stopPolling() {
clearTimeout(pollTimer);
pollTimer = null;
}
/** Poll until the run finishes, then reload what it changed. */
async function pollStatus() {
const current = await store.fetchStatus();
if (current?.running) {
// Scores are saved one at a time, so reloading as it goes lets a long
// "Score unscored" fill the list in rather than sit still for minutes.
await fetchLeads();
pollTimer = setTimeout(pollStatus, POLL_MS);
return;
}
stopPolling();
if (current?.lastError) fail(current.lastError);
await Promise.all([fetchLeads(), sourcesBox.value?.refresh()]);
}
/** Start one of the server jobs ("runSync", "scoreAll", "rescoreAll") and wait on it. */
async function start(job) {
try {
// false means a job was already going (the scheduler's, say); either way
// there is now one to wait for.
await store[job]();
error.value = "";
status.value = { ...(status.value ?? {}), running: true };
stopPolling();
pollTimer = setTimeout(pollStatus, POLL_MS);
} catch (err) {
fail(err);
}
}
// Matched inbox leads that have a score: what "Rescore all" would redo, on
// top of the unscored ones.
const scoredCount = computed(
() => leads.value.filter((lead) => lead.state === "new" && lead.matched && lead.score != null).length,
);
function rescore() {
const total = scoredCount.value + unscoredCount.value;
// One Claude call per lead, and it replaces scores that were paid for.
if (!confirm(`Score all ${total} inbox leads again? This makes one Claude call per lead.`)) return;
start("rescoreAll");
}
// Matched inbox leads with no score: what "Score unscored" would work
// through. A lead Claude failed on three times stays in this count, though
// the server will not try it again.
const unscoredCount = computed(
() => leads.value.filter((lead) => lead.state === "new" && lead.matched && lead.score == null).length,
);
const running = computed(() => !!status.value?.running);
const lastRun = computed(() => {
if (running.value) return "Working…";
if (!status.value?.lastRunAt) return "";
const when = new Date(status.value.lastRunAt).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
return `Last checked ${when}`;
});
onMounted(async () => {
await fetchLeads();
// Arriving mid-run (the scheduler's, or one started before a reload) should
// look the same as having pressed the button.
const current = await store.fetchStatus();
if (current?.running) pollTimer = setTimeout(pollStatus, POLL_MS);
});
onBeforeUnmount(stopPolling);
</script>
<template>
<div class="page">
<header class="page-header">
<div>
<h1 class="page-title">Leads</h1>
<p class="page-sub jl-sub">
<span v-if="running" class="spinner" aria-hidden="true"></span>
{{ lastRun || "Postings found on the sources below, scored against your profile." }}
</p>
</div>
<div class="page-actions">
<button
v-if="scoredCount"
class="btn"
:disabled="running"
title="Score every inbox lead again, including ones already scored. Use after changing the profile or the model. Old scores stay until replaced."
@click="rescore"
>
<Icon name="refresh" />
Rescore all
</button>
<button
v-if="unscoredCount"
class="btn"
:disabled="running"
title="Score every unscored lead in the inbox against the profile, without polling the sources. One Claude call per lead."
@click="start('scoreAll')"
>
<Icon name="sparkles" />
Score unscored
<span class="count">{{ unscoredCount }}</span>
</button>
<button
class="btn btn-primary"
:disabled="running"
title="Poll every source now, then score up to 40 new leads. Profile and keyword changes take effect on a run."
@click="start('runSync')"
>
<span v-if="running" class="spinner" aria-hidden="true"></span>
<Icon v-else name="search" />
{{ running ? "Working…" : "Check now" }}
</button>
</div>
</header>
<div v-if="error" class="alert" role="alert">
<span>{{ error }}</span>
<button
class="btn btn-ghost btn-sm btn-icon"
title="Dismiss"
aria-label="Dismiss"
@click="error = ''"
>
<Icon name="x" />
</button>
</div>
<div class="jl-setup">
<JobSearchProfile @fail="fail" @ok="clearError" />
<JobSources ref="sourcesBox" @fail="fail" @ok="clearError" />
</div>
<div class="jl-tabs" role="tablist">
<button
v-for="t in TABS"
:key="t.value"
class="jl-tab"
role="tab"
:aria-selected="tab === t.value"
:class="{ 'jl-tab-active': tab === t.value }"
@click="tab = t.value"
>
{{ t.label }}
<span class="count">{{ counts[t.value] }}</span>
</button>
</div>
<div class="jl-toolbar">
<label class="search">
<Icon name="search" />
<input
v-model="search"
class="input"
type="search"
placeholder="Search title, company, location, reasons…"
aria-label="Search leads"
/>
</label>
<select v-model="sortBy" class="input jl-sort" title="Order of the list" aria-label="Sort">
<option value="score">Best score first</option>
<option value="posted">Newest posting first</option>
</select>
<select v-model="sourceFilter" class="input jl-sort" aria-label="Filter source">
<option value="">All sources</option>
<option v-for="(label, kind) in SOURCE_LABELS" :key="kind" :value="kind">{{ label }}</option>
</select>
<input v-model="companyFilter" class="input jl-filter" placeholder="Company" aria-label="Filter company" />
<input v-model="locationFilter" class="input jl-filter" placeholder="Location" aria-label="Filter location" />
<input v-model="minFilter" class="input jl-score-filter" type="number" min="0" max="100" placeholder="Min score" aria-label="Minimum score" />
<input v-model="maxFilter" class="input jl-score-filter" type="number" min="0" max="100" placeholder="Max score" aria-label="Maximum score" />
<label v-if="tab === 'new'" class="check">
<input v-model="showLowScores" type="checkbox" />
Below {{ minScore }}<template v-if="hiddenLow"> ({{ hiddenLow }} hidden)</template>
</label>
<label v-if="tab === 'new'" class="check" title="Postings the keyword filter rejected. They are never scored.">
<input v-model="showUnmatched" type="checkbox" />
Filtered out
</label>
</div>
<div v-if="visibleLeads.length" class="jl-bulkbar">
<label class="check"><input type="checkbox" :checked="allVisibleSelected" @change="toggleAllVisible" /> Select visible</label>
<span v-if="selectedVisible.length">{{ selectedVisible.length }} selected</span>
<template v-if="selectedVisible.length">
<button v-if="tab === 'new'" class="btn btn-sm" :disabled="bulkBusy" @click="bulkAct('bulkDismiss')">Dismiss selected</button>
<button v-if="tab === 'dismissed'" class="btn btn-sm" :disabled="bulkBusy" @click="bulkAct('bulkRestore')">Restore selected</button>
<button v-if="tab === 'new'" class="btn btn-primary btn-sm" :disabled="bulkBusy" @click="bulkAct('bulkPromote')">Track selected</button>
</template>
</div>
<div class="jl-list">
<article
v-for="lead in visibleLeads"
:key="lead.id"
class="card jl-lead"
:class="{ 'jl-lead-unmatched': !lead.matched && lead.state === 'new' }"
>
<div
class="jl-score"
:class="scoreClass(lead)"
:style="{ '--arc': scoreArc(lead) }"
:title="scoreTitle(lead)"
>
<input class="jl-select" type="checkbox" :checked="selected.has(lead.id)" :aria-label="`Select ${lead.jobTitle}`" @change="toggleSelected(lead.id)" />
<span>{{ lead.score ?? "–" }}</span>
</div>
<div class="jl-lead-body">
<h3 class="jl-lead-title">
<a v-if="lead.url" :href="lead.url" target="_blank" rel="noopener">{{ lead.jobTitle }}</a>
<span v-else>{{ lead.jobTitle }}</span>
</h3>
<div class="jl-lead-meta">
<span class="jl-company">{{ lead.company }}</span>
<span v-if="lead.location">{{ lead.location }}</span>
<span>{{ SOURCE_LABELS[lead.sourceKind] ?? lead.sourceKind }}</span>
<span>{{ ageLabel(lead) }}</span>
<span v-if="!lead.matched && lead.state === 'new'" class="jl-tag">filtered out</span>
</div>
<p v-if="lead.scoreReasons" class="jl-lead-reasons">{{ lead.scoreReasons }}</p>
<pre v-if="descriptionId === lead.id" class="posting jl-desc">{{
descriptions[lead.id] === undefined ? "Loading…" : descriptions[lead.id] || "The source gave no description."
}}</pre>
</div>
<div class="jl-lead-actions">
<button
class="btn btn-ghost btn-sm"
:class="{ 'jl-action-on': descriptionId === lead.id }"
:aria-expanded="descriptionId === lead.id"
@click="toggleDescription(lead)"
>
<Icon name="file" :size="14" />
{{ descriptionId === lead.id ? "Hide" : "Posting" }}
</button>
<template v-if="lead.state === 'new'">
<button class="btn btn-sm" :disabled="busyId === lead.id" @click="act(lead, 'dismiss')">
<Icon name="x" :size="14" />
Dismiss
</button>
<button
class="btn btn-primary btn-sm"
:disabled="busyId === lead.id"
title="Add to the tracker as Saved"
@click="act(lead, 'promote')"
>
<Icon name="plus" :size="14" />
Track
</button>
</template>
<button
v-else-if="lead.state === 'dismissed'"
class="btn btn-sm"
:disabled="busyId === lead.id"
@click="act(lead, 'restore')"
>
<Icon name="undo" :size="14" />
Restore
</button>
<RouterLink v-else to="/" class="btn btn-sm">
<Icon name="briefcase" :size="14" />
In tracker
</RouterLink>
</div>
</article>
<div v-if="!visibleLeads.length" class="card empty">
<template v-if="loading">Loading…</template>
<template v-else-if="tab !== 'new'">Nothing here.</template>
<template v-else-if="hiddenLow">Nothing at or above {{ minScore }}. Tick "Below {{ minScore }}" to see the rest.</template>
<template v-else-if="!leads.length">No leads yet. Add a source above, then press "Check now".</template>
<template v-else>The inbox is empty.</template>
</div>
</div>
</div>
</template>
<style scoped>
/* Shared primitives are in assets/styles.css; this block is the page's own
layout. */
.jl-sub {
display: flex;
align-items: center;
gap: 0.5rem;
}
.jl-setup {
display: grid;
grid-template-columns: minmax(0, 3fr) minmax(0, 2fr);
gap: 1rem;
align-items: start;
margin-bottom: 1.75rem;
}
@media (max-width: 1100px) {
.jl-setup {
grid-template-columns: minmax(0, 1fr);
}
}
.jl-tabs {
display: flex;
gap: 0.25rem;
margin-bottom: 1rem;
border-bottom: 1px solid var(--border);
}
.jl-tab {
display: inline-flex;
align-items: center;
gap: 0.5rem;
margin-bottom: -1px;
padding: 0.6rem 0.85rem;
border-bottom: 2px solid transparent;
color: var(--text-3);
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
}
.jl-tab:hover {
color: var(--text);
}
.jl-tab-active,
.jl-tab-active:hover {
border-bottom-color: var(--accent);
color: var(--text);
}
.jl-tab-active .count {
background: var(--accent-soft);
color: var(--accent);
}
.jl-toolbar {
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
margin-bottom: 1rem;
}
.jl-filter {
flex: 0 1 10rem;
width: auto;
}
.jl-score-filter {
flex: 0 1 7rem;
width: auto;
}
.jl-bulkbar {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
min-height: 2.5rem;
margin-bottom: 0.75rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--border);
border-radius: 0.4rem;
background: var(--surface-2);
color: var(--text-2);
font-size: 0.875rem;
}
.jl-sort {
flex: 0 0 auto;
width: auto;
}
.jl-list {
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.jl-lead {
display: flex;
align-items: flex-start;
gap: 1rem;
padding: 1rem 1.1rem;
transition: border-color 0.12s;
}
.jl-lead:hover {
border-color: var(--border-strong);
}
.jl-lead-unmatched {
opacity: 0.6;
}
/* The score reads as a number first; the ring shows it out of 100 and its
colour only groups it. */
.jl-score {
--tone: var(--text-3);
display: grid;
place-items: center;
flex: 0 0 3rem;
width: 3rem;
height: 3rem;
border-radius: 50%;
background: conic-gradient(
var(--tone) calc(var(--arc) * 1%),
color-mix(in srgb, var(--tone) 15%, var(--surface)) 0
);
}
.jl-score > span {
display: grid;
place-items: center;
width: 2.45rem;
height: 2.45rem;
border-radius: 50%;
background: var(--surface);
color: color-mix(in srgb, var(--tone) 80%, var(--text));
font-size: 0.95rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.jl-select {
position: absolute;
top: 0.35rem;
left: 0.35rem;
z-index: 1;
}
.jl-score {
position: relative;
}
.jl-score-high {
--tone: var(--ok);
}
.jl-score-mid {
--tone: var(--warn);
}
.jl-score-low {
--tone: var(--danger);
}
.jl-lead-body {
flex: 1;
min-width: 0;
}
.jl-lead-title {
font-size: 1rem;
font-weight: 600;
}
.jl-lead-title a {
color: var(--text);
}
.jl-lead-title a:hover {
color: var(--accent);
text-decoration: none;
}
.jl-lead-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.2rem 0;
margin-top: 0.15rem;
color: var(--text-3);
font-size: 0.8125rem;
}
.jl-lead-meta > span + span::before {
content: "·";
margin: 0 0.5rem;
color: var(--border-strong);
}
.jl-company {
color: var(--text-2);
font-weight: 500;
}
.jl-tag {
color: var(--warn);
}
.jl-lead-reasons {
margin-top: 0.5rem;
color: var(--text-2);
font-size: 0.875rem;
line-height: 1.55;
}
.jl-desc {
margin-top: 0.75rem;
}
.jl-lead-actions {
display: flex;
gap: 0.4rem;
flex: none;
}
.jl-action-on {
background: var(--accent-soft);
color: var(--accent);
}
@media (max-width: 720px) {
.jl-toolbar {
align-items: stretch;
gap: 0.65rem;
}
.jl-toolbar .search,
.jl-sort,
.jl-filter,
.jl-score-filter {
flex: 1 1 calc(50% - 0.65rem);
}
.jl-lead {
flex-wrap: wrap;
}
.jl-lead-body {
flex-basis: calc(100% - 4rem);
}
.jl-lead-actions {
flex-basis: 100%;
}
.jl-lead-actions > * {
flex: 1;
}
}
</style>