WB1: migration 004, cluster assignment, GET /clusters, tailor-cv endpoint, deadline integration, Dockerfile.test matching install
This commit is contained in:
parent
59ea645125
commit
b3a1f588ef
16 changed files with 1522 additions and 53 deletions
|
|
@ -20,6 +20,7 @@ WORKDIR /app/apps/api
|
||||||
RUN pip install --no-cache-dir -e ".[dev]" \
|
RUN pip install --no-cache-dir -e ".[dev]" \
|
||||||
&& pip install --no-cache-dir -e /app/packages/llm-gateway \
|
&& pip install --no-cache-dir -e /app/packages/llm-gateway \
|
||||||
&& pip install --no-cache-dir -e /app/packages/artifacts \
|
&& pip install --no-cache-dir -e /app/packages/artifacts \
|
||||||
|
&& pip install --no-cache-dir -e /app/packages/matching \
|
||||||
&& pip install --no-cache-dir pypdf python-docx apscheduler
|
&& pip install --no-cache-dir pypdf python-docx apscheduler
|
||||||
|
|
||||||
CMD ["pytest", "-q"]
|
CMD ["pytest", "-q"]
|
||||||
|
|
@ -55,6 +55,28 @@ def get_job_posting(posting_id: str) -> dict[str, Any] | None:
|
||||||
return _normalize_posting(row)
|
return _normalize_posting(row)
|
||||||
|
|
||||||
|
|
||||||
|
def update_posting_cluster_id(posting_id: str, cluster_id: str) -> dict[str, Any] | None:
|
||||||
|
"""Set the cluster_id on a job posting."""
|
||||||
|
row = execute(
|
||||||
|
"UPDATE job_posting SET cluster_id = %s WHERE id = %s RETURNING *",
|
||||||
|
(cluster_id, posting_id),
|
||||||
|
)
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return _normalize_posting(row)
|
||||||
|
|
||||||
|
|
||||||
|
def update_posting_apply_by(posting_id: str, apply_by: Any) -> dict[str, Any] | None:
|
||||||
|
"""Set the apply_by date on a job posting."""
|
||||||
|
row = execute(
|
||||||
|
"UPDATE job_posting SET apply_by = %s WHERE id = %s RETURNING *",
|
||||||
|
(apply_by, posting_id),
|
||||||
|
)
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return _normalize_posting(row)
|
||||||
|
|
||||||
|
|
||||||
def list_postings() -> list[dict[str, Any]]:
|
def list_postings() -> list[dict[str, Any]]:
|
||||||
rows = fetch_all("SELECT * FROM job_posting ORDER BY fetched_at DESC")
|
rows = fetch_all("SELECT * FROM job_posting ORDER BY fetched_at DESC")
|
||||||
return [_normalize_posting(r) for r in rows]
|
return [_normalize_posting(r) for r in rows]
|
||||||
|
|
@ -71,6 +93,8 @@ def _normalize_posting(row: dict[str, Any]) -> dict[str, Any]:
|
||||||
"location": row.get("location"),
|
"location": row.get("location"),
|
||||||
"description": row.get("description", ""),
|
"description": row.get("description", ""),
|
||||||
"fetched_at": row["fetched_at"].isoformat() if row.get("fetched_at") else None,
|
"fetched_at": row["fetched_at"].isoformat() if row.get("fetched_at") else None,
|
||||||
|
"cluster_id": row.get("cluster_id"),
|
||||||
|
"apply_by": row.get("apply_by").isoformat() if row.get("apply_by") else None,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -483,3 +507,31 @@ def get_digest(limit: int = 20) -> list[dict[str, Any]]:
|
||||||
(limit,),
|
(limit,),
|
||||||
)
|
)
|
||||||
return [_normalize_application(r) for r in rows]
|
return [_normalize_application(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def get_upcoming_deadlines(days: int = 7) -> list[dict[str, Any]]:
|
||||||
|
"""Return applications whose job_posting has apply_by within the next *days* days.
|
||||||
|
|
||||||
|
Returns list of dicts: {application_id, title, company, apply_by}.
|
||||||
|
"""
|
||||||
|
rows = fetch_all(
|
||||||
|
"""
|
||||||
|
SELECT a.id AS application_id, j.title, j.company, j.apply_by
|
||||||
|
FROM application a
|
||||||
|
JOIN job_posting j ON a.job_posting_id = j.id
|
||||||
|
WHERE j.apply_by IS NOT NULL
|
||||||
|
AND j.apply_by >= CURRENT_DATE
|
||||||
|
AND j.apply_by <= CURRENT_DATE + %s * INTERVAL '1 day'
|
||||||
|
ORDER BY j.apply_by ASC
|
||||||
|
""",
|
||||||
|
(days,),
|
||||||
|
)
|
||||||
|
result: list[dict[str, Any]] = []
|
||||||
|
for row in rows:
|
||||||
|
result.append({
|
||||||
|
"application_id": str(row["application_id"]),
|
||||||
|
"title": row["title"],
|
||||||
|
"company": row["company"],
|
||||||
|
"apply_by": row["apply_by"].isoformat() if row.get("apply_by") else None,
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
|
@ -128,6 +128,36 @@ MOCK_OUTPUTS: dict[str, dict[str, Any]] = {
|
||||||
"state_proposal": "interviewing",
|
"state_proposal": "interviewing",
|
||||||
"reason": "The email mentions an interview invitation.",
|
"reason": "The email mentions an interview invitation.",
|
||||||
},
|
},
|
||||||
|
"cv_tailor": {
|
||||||
|
"tailored_cv": {
|
||||||
|
"summary": "Senior Python Developer with 6+ years building scalable backend systems.",
|
||||||
|
"skills": [
|
||||||
|
"Python",
|
||||||
|
"Fast API",
|
||||||
|
"PostgreSQL",
|
||||||
|
"Docker",
|
||||||
|
"Kubernetes",
|
||||||
|
"AWS",
|
||||||
|
],
|
||||||
|
"experience": [
|
||||||
|
{
|
||||||
|
"company": "TechCorp",
|
||||||
|
"role": "Senior Backend Engineer",
|
||||||
|
"bullets": [
|
||||||
|
"Led migration of monolith to microservices using Fast API",
|
||||||
|
"Reduced API latency by 40% through query optimization and caching",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"change_log": [
|
||||||
|
{"action": "reordered", "detail": "Moved Python and Fast API to top of skills"},
|
||||||
|
{"action": "rephrased", "detail": "Rewrote first experience bullet to emphasize Fast API"},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"deadline_extract": {
|
||||||
|
"apply_by": None,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,8 @@ from app.schemas import (
|
||||||
BatchScoreRequest,
|
BatchScoreRequest,
|
||||||
BatchScoreResponse,
|
BatchScoreResponse,
|
||||||
BatchScoreResult,
|
BatchScoreResult,
|
||||||
|
ClusterOut,
|
||||||
|
ClusterPostingOut,
|
||||||
CoverLetterRequest,
|
CoverLetterRequest,
|
||||||
CoverLetterResponse,
|
CoverLetterResponse,
|
||||||
CvImportConfirmRequest,
|
CvImportConfirmRequest,
|
||||||
|
|
@ -36,6 +38,7 @@ from app.schemas import (
|
||||||
CvSectionCreate,
|
CvSectionCreate,
|
||||||
CvSectionOut,
|
CvSectionOut,
|
||||||
CvSectionUpdate,
|
CvSectionUpdate,
|
||||||
|
DeadlineItem,
|
||||||
DigestItem,
|
DigestItem,
|
||||||
EmailSuggestionOut,
|
EmailSuggestionOut,
|
||||||
ErrorOut,
|
ErrorOut,
|
||||||
|
|
@ -52,6 +55,7 @@ from app.schemas import (
|
||||||
ProfileUpdate,
|
ProfileUpdate,
|
||||||
ScoreResponse,
|
ScoreResponse,
|
||||||
SeedDemoResponse,
|
SeedDemoResponse,
|
||||||
|
TailorCvResponse,
|
||||||
TaskRunOut,
|
TaskRunOut,
|
||||||
TodayResponse,
|
TodayResponse,
|
||||||
TransitionRequest,
|
TransitionRequest,
|
||||||
|
|
@ -59,6 +63,20 @@ from app.schemas import (
|
||||||
from app.statemachine import TransitionContext, check_transition, InvalidTransition
|
from app.statemachine import TransitionContext, check_transition, InvalidTransition
|
||||||
from app.transport import get_transport, reset_transport
|
from app.transport import get_transport, reset_transport
|
||||||
|
|
||||||
|
# v1.1: matching package for cluster + coverage
|
||||||
|
try:
|
||||||
|
from matching import cluster as _cluster_postings, coverage as _keyword_coverage
|
||||||
|
HAS_MATCHING = True
|
||||||
|
except ImportError:
|
||||||
|
HAS_MATCHING = False
|
||||||
|
|
||||||
|
# v1.1: artifacts package for PDF rendering
|
||||||
|
try:
|
||||||
|
from artifacts import render_cv_pdf as _render_cv_pdf, hash_bytes as _hash_bytes, next_version as _next_version
|
||||||
|
HAS_ARTIFACTS = True
|
||||||
|
except ImportError:
|
||||||
|
HAS_ARTIFACTS = False
|
||||||
|
|
||||||
# Defensive import for connectors (may not exist yet)
|
# Defensive import for connectors (may not exist yet)
|
||||||
try:
|
try:
|
||||||
from packages.connectors.arbetsformedlingen import ArbetsformedlingenConnector # type: ignore
|
from packages.connectors.arbetsformedlingen import ArbetsformedlingenConnector # type: ignore
|
||||||
|
|
@ -159,6 +177,71 @@ def ai_assist(section_id: str, body: AiAssistRequest) -> Any:
|
||||||
|
|
||||||
# --- Job Postings ---
|
# --- Job Postings ---
|
||||||
|
|
||||||
|
def _assign_cluster_id(new_posting_id: str) -> str | None:
|
||||||
|
"""Run cluster() over the new posting + all existing postings.
|
||||||
|
|
||||||
|
Reconcile for stability: if the new posting joins an existing cluster,
|
||||||
|
reuse the existing cluster_id. Otherwise assign a fresh cluster_id from
|
||||||
|
the clustering output.
|
||||||
|
|
||||||
|
Returns the cluster_id assigned to the new posting (or None if matching
|
||||||
|
package is unavailable or no postings exist).
|
||||||
|
"""
|
||||||
|
if not HAS_MATCHING:
|
||||||
|
return None
|
||||||
|
|
||||||
|
all_postings = repo_app.list_postings()
|
||||||
|
if not all_postings:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Build posting dicts for cluster() -- needs id, employer, title, description
|
||||||
|
posting_dicts = [
|
||||||
|
{
|
||||||
|
"id": p["id"],
|
||||||
|
"employer": p.get("company", ""),
|
||||||
|
"title": p.get("title", ""),
|
||||||
|
"description": p.get("description", ""),
|
||||||
|
}
|
||||||
|
for p in all_postings
|
||||||
|
]
|
||||||
|
|
||||||
|
clusters = _cluster_postings(posting_dicts)
|
||||||
|
|
||||||
|
# Find which cluster the new posting ended up in
|
||||||
|
for cluster_id, posting_ids in clusters.items():
|
||||||
|
if new_posting_id in posting_ids:
|
||||||
|
# Check if any existing posting in this cluster already has a cluster_id
|
||||||
|
existing_cluster_ids: set[str] = set()
|
||||||
|
for pid in posting_ids:
|
||||||
|
if pid == new_posting_id:
|
||||||
|
continue
|
||||||
|
for p in all_postings:
|
||||||
|
if p["id"] == pid and p.get("cluster_id"):
|
||||||
|
existing_cluster_ids.add(p["cluster_id"])
|
||||||
|
|
||||||
|
if existing_cluster_ids:
|
||||||
|
# Prefer existing cluster_id for stability
|
||||||
|
stable_id = sorted(existing_cluster_ids)[0]
|
||||||
|
else:
|
||||||
|
# New cluster: use the computed cluster_id
|
||||||
|
stable_id = cluster_id
|
||||||
|
|
||||||
|
# Assign cluster_id to all postings in the cluster that don't have one yet
|
||||||
|
for pid in posting_ids:
|
||||||
|
# Check if this posting already has the cluster_id
|
||||||
|
p_row = None
|
||||||
|
for p in all_postings:
|
||||||
|
if p["id"] == pid:
|
||||||
|
p_row = p
|
||||||
|
break
|
||||||
|
if p_row and p_row.get("cluster_id") != stable_id:
|
||||||
|
repo_app.update_posting_cluster_id(pid, stable_id)
|
||||||
|
|
||||||
|
return stable_id
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/postings", response_model=ApplicationOut, status_code=201)
|
@app.post("/api/postings", response_model=ApplicationOut, status_code=201)
|
||||||
def create_posting(body: JobPostingCreate) -> Any:
|
def create_posting(body: JobPostingCreate) -> Any:
|
||||||
"""Create a job posting from a URL. For POC: manual_url source."""
|
"""Create a job posting from a URL. For POC: manual_url source."""
|
||||||
|
|
@ -177,6 +260,10 @@ def create_posting(body: JobPostingCreate) -> Any:
|
||||||
description="",
|
description="",
|
||||||
raw={"url": url},
|
raw={"url": url},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Cluster assignment
|
||||||
|
_assign_cluster_id(posting["id"])
|
||||||
|
|
||||||
application = repo_app.create_application(posting["id"])
|
application = repo_app.create_application(posting["id"])
|
||||||
return application
|
return application
|
||||||
|
|
||||||
|
|
@ -186,6 +273,60 @@ def get_postings() -> Any:
|
||||||
return repo_app.list_postings()
|
return repo_app.list_postings()
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/clusters", response_model=list[ClusterOut])
|
||||||
|
def get_clusters() -> Any:
|
||||||
|
"""Return job postings grouped by cluster_id, sorted by best score desc.
|
||||||
|
|
||||||
|
Each cluster includes postings with their id, title, company, source, url, score.
|
||||||
|
Clusters with no cluster_id are excluded.
|
||||||
|
"""
|
||||||
|
if not HAS_MATCHING:
|
||||||
|
return []
|
||||||
|
|
||||||
|
postings = repo_app.list_postings()
|
||||||
|
# Build a map of cluster_id -> list of postings
|
||||||
|
cluster_map: dict[str, list[dict[str, Any]]] = {}
|
||||||
|
for p in postings:
|
||||||
|
cid = p.get("cluster_id")
|
||||||
|
if not cid:
|
||||||
|
continue
|
||||||
|
cluster_map.setdefault(cid, []).append(p)
|
||||||
|
|
||||||
|
# For each cluster, look up application scores
|
||||||
|
apps = repo_app.list_applications()
|
||||||
|
# Build posting_id -> score map
|
||||||
|
score_map: dict[str, float | None] = {}
|
||||||
|
for a in apps:
|
||||||
|
score_map[a["job_posting_id"]] = a.get("score")
|
||||||
|
|
||||||
|
result: list[dict[str, Any]] = []
|
||||||
|
for cid, cluster_postings in cluster_map.items():
|
||||||
|
cluster_postings_out: list[dict[str, Any]] = []
|
||||||
|
best_score: float | None = None
|
||||||
|
for p in cluster_postings:
|
||||||
|
score = score_map.get(p["id"])
|
||||||
|
cluster_postings_out.append({
|
||||||
|
"id": p["id"],
|
||||||
|
"title": p.get("title", ""),
|
||||||
|
"company": p.get("company", ""),
|
||||||
|
"source": p.get("source", ""),
|
||||||
|
"url": p.get("url", ""),
|
||||||
|
"score": score,
|
||||||
|
})
|
||||||
|
if score is not None:
|
||||||
|
if best_score is None or score > best_score:
|
||||||
|
best_score = score
|
||||||
|
result.append({
|
||||||
|
"cluster_id": cid,
|
||||||
|
"postings": cluster_postings_out,
|
||||||
|
"_best_score": best_score,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Sort by best score descending
|
||||||
|
result.sort(key=lambda c: (-(c.pop("_best_score") or -1)))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/postings/{posting_id}/score", response_model=ScoreResponse)
|
@app.post("/api/postings/{posting_id}/score", response_model=ScoreResponse)
|
||||||
def score_posting(posting_id: str) -> Any:
|
def score_posting(posting_id: str) -> Any:
|
||||||
"""Score a job posting against the profile."""
|
"""Score a job posting against the profile."""
|
||||||
|
|
@ -217,6 +358,32 @@ def score_posting(posting_id: str) -> Any:
|
||||||
rationale = result.get("rationale", {})
|
rationale = result.get("rationale", {})
|
||||||
|
|
||||||
repo_app.update_application_score(app_for_posting["id"], score, rationale)
|
repo_app.update_application_score(app_for_posting["id"], score, rationale)
|
||||||
|
|
||||||
|
# Deadline extraction (CHEAP task)
|
||||||
|
deadline_result = llm.run_task(
|
||||||
|
"deadline_extract",
|
||||||
|
f"Extract apply-by deadline from: {posting['title']} at {posting['company']}. Description: {posting.get('description', '')}",
|
||||||
|
telemetry_sink=lambda info: repo_app.create_task_run({
|
||||||
|
**info,
|
||||||
|
"application_id": app_for_posting["id"],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
apply_by = deadline_result.get("apply_by")
|
||||||
|
if apply_by is not None:
|
||||||
|
# Parse and persist
|
||||||
|
try:
|
||||||
|
from datetime import date as date_cls
|
||||||
|
if isinstance(apply_by, str):
|
||||||
|
parsed_date = date_cls.fromisoformat(apply_by)
|
||||||
|
elif isinstance(apply_by, date_cls):
|
||||||
|
parsed_date = apply_by
|
||||||
|
else:
|
||||||
|
parsed_date = None
|
||||||
|
if parsed_date is not None:
|
||||||
|
repo_app.update_posting_apply_by(posting["id"], parsed_date)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass # Skip invalid date
|
||||||
|
|
||||||
return {"score": score, "rationale": rationale}
|
return {"score": score, "rationale": rationale}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -654,6 +821,8 @@ def _fetch_and_create_postings(query: str, region: str | None = None) -> dict[st
|
||||||
raw=rp.get("raw", {}),
|
raw=rp.get("raw", {}),
|
||||||
)
|
)
|
||||||
repo_app.create_application(posting["id"])
|
repo_app.create_application(posting["id"])
|
||||||
|
# Cluster assignment
|
||||||
|
_assign_cluster_id(posting["id"])
|
||||||
new_count += 1
|
new_count += 1
|
||||||
|
|
||||||
return {"new": new_count, "dupes": dupe_count}
|
return {"new": new_count, "dupes": dupe_count}
|
||||||
|
|
@ -713,6 +882,31 @@ def _batch_score_internal(application_ids: list[str]) -> list[dict[str, Any]]:
|
||||||
red_flags = result.get("red_flags", [])
|
red_flags = result.get("red_flags", [])
|
||||||
|
|
||||||
repo_app.update_application_score(app_id, score, rationale)
|
repo_app.update_application_score(app_id, score, rationale)
|
||||||
|
|
||||||
|
# Deadline extraction (CHEAP task)
|
||||||
|
deadline_result = llm.run_task(
|
||||||
|
"deadline_extract",
|
||||||
|
f"Extract apply-by deadline from: {posting['title']} at {posting['company']}. Description: {posting.get('description', '')}",
|
||||||
|
telemetry_sink=lambda info, aid=app_id: repo_app.create_task_run({
|
||||||
|
**info,
|
||||||
|
"application_id": aid,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
apply_by = deadline_result.get("apply_by")
|
||||||
|
if apply_by is not None:
|
||||||
|
try:
|
||||||
|
from datetime import date as date_cls
|
||||||
|
if isinstance(apply_by, str):
|
||||||
|
parsed_date = date_cls.fromisoformat(apply_by)
|
||||||
|
elif isinstance(apply_by, date_cls):
|
||||||
|
parsed_date = apply_by
|
||||||
|
else:
|
||||||
|
parsed_date = None
|
||||||
|
if parsed_date is not None:
|
||||||
|
repo_app.update_posting_apply_by(posting["id"], parsed_date)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass # Skip invalid date
|
||||||
|
|
||||||
results.append({
|
results.append({
|
||||||
"application_id": app_id,
|
"application_id": app_id,
|
||||||
"score": score,
|
"score": score,
|
||||||
|
|
@ -763,10 +957,23 @@ def get_today() -> Any:
|
||||||
# Pending approvals count
|
# Pending approvals count
|
||||||
pending = repo_app.count_pending_approvals()
|
pending = repo_app.count_pending_approvals()
|
||||||
|
|
||||||
|
# Deadlines: apply_by within next 7 days
|
||||||
|
deadline_rows = repo_app.get_upcoming_deadlines(days=7)
|
||||||
|
deadlines = [
|
||||||
|
DeadlineItem(
|
||||||
|
application_id=d["application_id"],
|
||||||
|
title=d["title"],
|
||||||
|
company=d["company"],
|
||||||
|
apply_by=d.get("apply_by"),
|
||||||
|
)
|
||||||
|
for d in deadline_rows
|
||||||
|
]
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"digest": digest,
|
"digest": digest,
|
||||||
"nudges": nudges,
|
"nudges": nudges,
|
||||||
"pending_approvals": pending,
|
"pending_approvals": pending,
|
||||||
|
"deadlines": deadlines,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1040,3 +1247,174 @@ def get_notification_log() -> Any:
|
||||||
"""Return last 50 notification log entries."""
|
"""Return last 50 notification log entries."""
|
||||||
from app.notify import list_notification_log
|
from app.notify import list_notification_log
|
||||||
return list_notification_log(limit=50)
|
return list_notification_log(limit=50)
|
||||||
|
|
||||||
|
|
||||||
|
# --- v1.1: Tailor CV ---
|
||||||
|
|
||||||
|
@app.post("/api/applications/{app_id}/tailor-cv", response_model=TailorCvResponse)
|
||||||
|
def tailor_cv(app_id: str) -> Any:
|
||||||
|
"""Tailor the user's CV for the posting linked to this application.
|
||||||
|
|
||||||
|
Uses cv_tailor (STRONG task) to generate a tailored CV variant.
|
||||||
|
Validates the output: every tailored bullet must map to a source bullet
|
||||||
|
id from the input (hallucination guard). Rejects + 502 on unmapped bullets.
|
||||||
|
Stores artifact kind='cv' origin='ai_drafted' + renders PDF via packages/artifacts.
|
||||||
|
Returns {artifact_id, change_log, keyword_coverage}.
|
||||||
|
"""
|
||||||
|
app_row = repo_app.get_application(app_id)
|
||||||
|
if app_row is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Application not found")
|
||||||
|
|
||||||
|
posting = repo_app.get_job_posting(app_row["job_posting_id"])
|
||||||
|
if posting is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Posting not found")
|
||||||
|
|
||||||
|
# Build profile + sections from the profile repo
|
||||||
|
profile = repo_profile.get_or_create_profile()
|
||||||
|
if profile is None:
|
||||||
|
raise HTTPException(status_code=500, detail="No profile found")
|
||||||
|
sections = repo_profile.list_sections()
|
||||||
|
|
||||||
|
# Build the prompt with profile + sections + posting description
|
||||||
|
import json as _json
|
||||||
|
prompt_parts = [
|
||||||
|
f"Profile: {_json.dumps({k: profile.get(k) for k in ('full_name', 'headline', 'email', 'phone', 'location', 'summary')}, default=str)}",
|
||||||
|
f"Sections: {_json.dumps(sections, default=str)}",
|
||||||
|
f"Posting: title={posting.get('title', '')}, company={posting.get('company', '')}, description={posting.get('description', '')}",
|
||||||
|
]
|
||||||
|
prompt = "\n".join(prompt_parts)
|
||||||
|
|
||||||
|
# Run cv_tailor (STRONG task)
|
||||||
|
result = llm.run_task(
|
||||||
|
"cv_tailor",
|
||||||
|
prompt,
|
||||||
|
telemetry_sink=lambda info: repo_app.create_task_run({
|
||||||
|
**info,
|
||||||
|
"application_id": app_id,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
tailored_cv = result.get("tailored_cv", {})
|
||||||
|
change_log = result.get("change_log", [])
|
||||||
|
|
||||||
|
# Hallucination guard: every tailored bullet must map to a source bullet id.
|
||||||
|
# We collect all source bullet texts from sections and check that each
|
||||||
|
# bullet in the tailored output is a rephrase/reorder of an existing one.
|
||||||
|
source_bullets: set[str] = set()
|
||||||
|
for s in sections:
|
||||||
|
for b in s.get("bullets", []):
|
||||||
|
source_bullets.add(str(b).lower().strip())
|
||||||
|
|
||||||
|
# Check bullets in tailored experience sections
|
||||||
|
unmapped_bullets: list[str] = []
|
||||||
|
for exp in tailored_cv.get("experience", []):
|
||||||
|
for bullet in exp.get("bullets", []):
|
||||||
|
bullet_lower = str(bullet).lower().strip()
|
||||||
|
# Check if this bullet is a rephrase of any source bullet.
|
||||||
|
# We use a simple containment check: at least 50% of the words
|
||||||
|
# in the tailored bullet should appear in some source bullet.
|
||||||
|
bullet_words = set(bullet_lower.split())
|
||||||
|
if not bullet_words:
|
||||||
|
continue
|
||||||
|
found = False
|
||||||
|
for sb in source_bullets:
|
||||||
|
sb_words = set(sb.split())
|
||||||
|
if not sb_words:
|
||||||
|
continue
|
||||||
|
overlap = len(bullet_words & sb_words) / len(bullet_words)
|
||||||
|
if overlap >= 0.5:
|
||||||
|
found = True
|
||||||
|
break
|
||||||
|
if not found and source_bullets:
|
||||||
|
unmapped_bullets.append(bullet)
|
||||||
|
|
||||||
|
if unmapped_bullets:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=502,
|
||||||
|
detail={
|
||||||
|
"code": "hallucination_guard",
|
||||||
|
"message": f"Tailored CV contains bullets that do not map to source bullets: {unmapped_bullets}",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build sections for PDF rendering
|
||||||
|
pdf_sections: list[dict[str, Any]] = []
|
||||||
|
# Add experience sections from tailored CV
|
||||||
|
for exp in tailored_cv.get("experience", []):
|
||||||
|
pdf_sections.append({
|
||||||
|
"kind": "experience",
|
||||||
|
"title": exp.get("role", ""),
|
||||||
|
"org": exp.get("company", ""),
|
||||||
|
"bullets": exp.get("bullets", []),
|
||||||
|
})
|
||||||
|
# Add skills section
|
||||||
|
if tailored_cv.get("skills"):
|
||||||
|
pdf_sections.append({
|
||||||
|
"kind": "skills",
|
||||||
|
"title": "Technical Skills",
|
||||||
|
"bullets": tailored_cv.get("skills", []),
|
||||||
|
})
|
||||||
|
# If no experience sections from tailor, fall back to original sections
|
||||||
|
if not pdf_sections:
|
||||||
|
pdf_sections = sections
|
||||||
|
|
||||||
|
# Render PDF
|
||||||
|
if not HAS_ARTIFACTS:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500,
|
||||||
|
detail={"code": "missing_dependency", "message": "artifacts package not installed"},
|
||||||
|
)
|
||||||
|
|
||||||
|
pdf_profile = {
|
||||||
|
"full_name": profile.get("full_name", ""),
|
||||||
|
"headline": profile.get("headline", ""),
|
||||||
|
"email": profile.get("email", ""),
|
||||||
|
"phone": profile.get("phone", ""),
|
||||||
|
"location": profile.get("location", ""),
|
||||||
|
"summary": tailored_cv.get("summary", profile.get("summary", "")),
|
||||||
|
}
|
||||||
|
|
||||||
|
pdf_bytes = _render_cv_pdf(pdf_profile, pdf_sections)
|
||||||
|
|
||||||
|
# Store artifact
|
||||||
|
storage_dir = os.path.join(tempfile.gettempdir(), "jobhunt_artifacts")
|
||||||
|
os.makedirs(storage_dir, exist_ok=True)
|
||||||
|
filename = f"cv_tailored_{app_id[:8]}.pdf"
|
||||||
|
storage_path = os.path.join(storage_dir, filename)
|
||||||
|
with open(storage_path, "wb") as f:
|
||||||
|
f.write(pdf_bytes)
|
||||||
|
|
||||||
|
# Get existing CV artifacts for version numbering
|
||||||
|
existing_artifacts = repo_app.list_artifacts(app_id)
|
||||||
|
cv_versions = [a["version"] for a in existing_artifacts if a["kind"] == "cv"]
|
||||||
|
version = _next_version(cv_versions)
|
||||||
|
|
||||||
|
artifact = repo_app.create_artifact(
|
||||||
|
application_id=app_id,
|
||||||
|
kind="cv",
|
||||||
|
filename=filename,
|
||||||
|
content_bytes=pdf_bytes,
|
||||||
|
storage_path=storage_path,
|
||||||
|
origin="ai_drafted",
|
||||||
|
version=version,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Compute keyword coverage
|
||||||
|
# Build CV text from the tailored sections
|
||||||
|
cv_text_parts = [
|
||||||
|
pdf_profile.get("summary", ""),
|
||||||
|
]
|
||||||
|
for s in pdf_sections:
|
||||||
|
cv_text_parts.append(s.get("title", ""))
|
||||||
|
cv_text_parts.append(s.get("org", ""))
|
||||||
|
cv_text_parts.extend(s.get("bullets", []))
|
||||||
|
cv_text = " ".join(str(p) for p in cv_text_parts)
|
||||||
|
posting_description = posting.get("description", "") or f"{posting.get('title', '')} at {posting.get('company', '')}"
|
||||||
|
|
||||||
|
keyword_coverage = _keyword_coverage(cv_text, posting_description) if HAS_MATCHING else {"matched": [], "missing": [], "ratio": 0.0}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"artifact_id": artifact["id"],
|
||||||
|
"change_log": change_log,
|
||||||
|
"keyword_coverage": keyword_coverage,
|
||||||
|
}
|
||||||
|
|
@ -108,6 +108,8 @@ class JobPostingOut(BaseModel):
|
||||||
location: str | None = None
|
location: str | None = None
|
||||||
description: str = ""
|
description: str = ""
|
||||||
fetched_at: str | None = None
|
fetched_at: str | None = None
|
||||||
|
cluster_id: str | None = None
|
||||||
|
apply_by: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class ScoreResponse(BaseModel):
|
class ScoreResponse(BaseModel):
|
||||||
|
|
@ -304,6 +306,7 @@ class TodayResponse(BaseModel):
|
||||||
digest: list[DigestItem]
|
digest: list[DigestItem]
|
||||||
nudges: list[NudgeItem]
|
nudges: list[NudgeItem]
|
||||||
pending_approvals: int
|
pending_approvals: int
|
||||||
|
deadlines: list[DeadlineItem] = []
|
||||||
|
|
||||||
|
|
||||||
# --- v1: Interview Prep ---
|
# --- v1: Interview Prep ---
|
||||||
|
|
@ -347,3 +350,36 @@ class NotificationLogOut(BaseModel):
|
||||||
delivered: bool
|
delivered: bool
|
||||||
error: str | None = None
|
error: str | None = None
|
||||||
created_at: str | None = None
|
created_at: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# --- v1.1: Clusters ---
|
||||||
|
|
||||||
|
class ClusterPostingOut(BaseModel):
|
||||||
|
id: str
|
||||||
|
title: str
|
||||||
|
company: str
|
||||||
|
source: str
|
||||||
|
url: str
|
||||||
|
score: float | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ClusterOut(BaseModel):
|
||||||
|
cluster_id: str
|
||||||
|
postings: list[ClusterPostingOut] = []
|
||||||
|
|
||||||
|
|
||||||
|
# --- v1.1: Tailor CV ---
|
||||||
|
|
||||||
|
class TailorCvResponse(BaseModel):
|
||||||
|
artifact_id: str
|
||||||
|
change_log: list[dict[str, Any]]
|
||||||
|
keyword_coverage: dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
# --- v1.1: Deadlines ---
|
||||||
|
|
||||||
|
class DeadlineItem(BaseModel):
|
||||||
|
application_id: str
|
||||||
|
title: str
|
||||||
|
company: str
|
||||||
|
apply_by: str | None = None
|
||||||
4
apps/api/migrations/004_dedupe_deadline.sql
Normal file
4
apps/api/migrations/004_dedupe_deadline.sql
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
-- 004_dedupe_deadline.sql -- cluster_id for dedupe + apply_by deadline
|
||||||
|
|
||||||
|
ALTER TABLE job_posting ADD COLUMN IF NOT EXISTS cluster_id text;
|
||||||
|
ALTER TABLE job_posting ADD COLUMN IF NOT EXISTS apply_by date;
|
||||||
|
|
@ -7,18 +7,22 @@ import type {
|
||||||
Approval,
|
Approval,
|
||||||
Artifact,
|
Artifact,
|
||||||
BatchScoringResponse,
|
BatchScoringResponse,
|
||||||
|
Cluster,
|
||||||
CoverLetterResponse,
|
CoverLetterResponse,
|
||||||
CritiqueComment,
|
CritiqueComment,
|
||||||
CvImportConfirmResponse,
|
CvImportConfirmResponse,
|
||||||
CvImportResponse,
|
CvImportResponse,
|
||||||
CvSection,
|
CvSection,
|
||||||
DemoSeedResponse,
|
DemoSeedResponse,
|
||||||
|
EmailSuggestion,
|
||||||
InterviewPrepResponse,
|
InterviewPrepResponse,
|
||||||
JobPosting,
|
JobPosting,
|
||||||
|
NotificationLogEntry,
|
||||||
PostingsFetchResponse,
|
PostingsFetchResponse,
|
||||||
Profile,
|
Profile,
|
||||||
RenderCvResponse,
|
RenderCvResponse,
|
||||||
ScoreResponse,
|
ScoreResponse,
|
||||||
|
TailorCvResponse,
|
||||||
TaskRun,
|
TaskRun,
|
||||||
TodayResponse
|
TodayResponse
|
||||||
} from '@/types'
|
} from '@/types'
|
||||||
|
|
@ -214,6 +218,34 @@ export function seedDemo(): Promise<DemoSeedResponse> {
|
||||||
return request<DemoSeedResponse>('/concierge/seed-demo', { method: 'POST' })
|
return request<DemoSeedResponse>('/concierge/seed-demo', { method: 'POST' })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- v1.1 additions (wave A/B) ---
|
||||||
|
|
||||||
|
export function getSuggestions(): Promise<EmailSuggestion[]> {
|
||||||
|
return request<EmailSuggestion[]>('/suggestions')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function acceptSuggestion(id: string): Promise<EmailSuggestion> {
|
||||||
|
return request<EmailSuggestion>(`/suggestions/${id}/accept`, { method: 'POST' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dismissSuggestion(id: string): Promise<EmailSuggestion> {
|
||||||
|
return request<EmailSuggestion>(`/suggestions/${id}/dismiss`, { method: 'POST' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getNotificationLog(): Promise<NotificationLogEntry[]> {
|
||||||
|
return request<NotificationLogEntry[]>('/notifications/log')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getClusters(): Promise<Cluster[]> {
|
||||||
|
return request<Cluster[]>('/clusters')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function tailorCv(applicationId: string): Promise<TailorCvResponse> {
|
||||||
|
return request<TailorCvResponse>(`/applications/${applicationId}/tailor-cv`, {
|
||||||
|
method: 'POST'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// Re-export types for convenience
|
// Re-export types for convenience
|
||||||
export type {
|
export type {
|
||||||
AiAssistResponse,
|
AiAssistResponse,
|
||||||
|
|
@ -221,18 +253,22 @@ export type {
|
||||||
Approval,
|
Approval,
|
||||||
Artifact,
|
Artifact,
|
||||||
BatchScoringResponse,
|
BatchScoringResponse,
|
||||||
|
Cluster,
|
||||||
CoverLetterResponse,
|
CoverLetterResponse,
|
||||||
CritiqueComment,
|
CritiqueComment,
|
||||||
CvImportConfirmResponse,
|
CvImportConfirmResponse,
|
||||||
CvImportResponse,
|
CvImportResponse,
|
||||||
CvSection,
|
CvSection,
|
||||||
DemoSeedResponse,
|
DemoSeedResponse,
|
||||||
|
EmailSuggestion,
|
||||||
InterviewPrepResponse,
|
InterviewPrepResponse,
|
||||||
JobPosting,
|
JobPosting,
|
||||||
|
NotificationLogEntry,
|
||||||
PostingsFetchResponse,
|
PostingsFetchResponse,
|
||||||
Profile,
|
Profile,
|
||||||
RenderCvResponse,
|
RenderCvResponse,
|
||||||
ScoreResponse,
|
ScoreResponse,
|
||||||
|
TailorCvResponse,
|
||||||
TaskRun,
|
TaskRun,
|
||||||
TodayResponse
|
TodayResponse
|
||||||
}
|
}
|
||||||
|
|
@ -18,6 +18,23 @@ const totalCost = computed(() =>
|
||||||
)
|
)
|
||||||
const hasCost = computed(() => tasks.value.some((t) => t.cost != null))
|
const hasCost = computed(() => tasks.value.some((t) => t.cost != null))
|
||||||
|
|
||||||
|
// Group task runs by model name (proxy for provider) and compute totals per group
|
||||||
|
const byProvider = computed(() => {
|
||||||
|
const map = new Map<string, { model: string; tokensIn: number; tokensOut: number; cost: number; count: number }>()
|
||||||
|
for (const t of tasks.value) {
|
||||||
|
const key = t.model || 'unknown'
|
||||||
|
if (!map.has(key)) {
|
||||||
|
map.set(key, { model: key, tokensIn: 0, tokensOut: 0, cost: 0, count: 0 })
|
||||||
|
}
|
||||||
|
const entry = map.get(key)!
|
||||||
|
entry.tokensIn += t.tokens_in ?? 0
|
||||||
|
entry.tokensOut += t.tokens_out ?? 0
|
||||||
|
entry.cost += t.cost ?? 0
|
||||||
|
entry.count += 1
|
||||||
|
}
|
||||||
|
return Array.from(map.values()).sort((a, b) => b.cost - a.cost)
|
||||||
|
})
|
||||||
|
|
||||||
async function loadTasks() {
|
async function loadTasks() {
|
||||||
try {
|
try {
|
||||||
tasks.value = await api.getTelemetryTasks()
|
tasks.value = await api.getTelemetryTasks()
|
||||||
|
|
@ -50,6 +67,31 @@ onMounted(loadTasks)
|
||||||
<span class="font-medium">{{ totalCost.toFixed(4) }}</span>
|
<span class="font-medium">{{ totalCost.toFixed(4) }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-xs text-gray-400 mt-1">{{ tasks.length }} task runs</div>
|
<div class="text-xs text-gray-400 mt-1">{{ tasks.length }} task runs</div>
|
||||||
|
|
||||||
|
<!-- Provider breakdown -->
|
||||||
|
<div v-if="byProvider.length > 0" class="mt-3 border-t border-gray-100 pt-2">
|
||||||
|
<div class="text-xs font-medium text-gray-500 mb-1">By Provider</div>
|
||||||
|
<table class="w-full text-xs" data-testid="provider-breakdown">
|
||||||
|
<thead class="text-left text-gray-400">
|
||||||
|
<tr>
|
||||||
|
<th class="py-1">Model</th>
|
||||||
|
<th class="py-1 text-right">In</th>
|
||||||
|
<th class="py-1 text-right">Out</th>
|
||||||
|
<th class="py-1 text-right">Cost</th>
|
||||||
|
<th class="py-1 text-right">Runs</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="p in byProvider" :key="p.model" class="border-t border-gray-50">
|
||||||
|
<td class="py-1">{{ p.model }}</td>
|
||||||
|
<td class="py-1 text-right">{{ p.tokensIn.toLocaleString() }}</td>
|
||||||
|
<td class="py-1 text-right">{{ p.tokensOut.toLocaleString() }}</td>
|
||||||
|
<td class="py-1 text-right">{{ p.cost.toFixed(4) }}</td>
|
||||||
|
<td class="py-1 text-right">{{ p.count }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
@ -209,3 +209,67 @@ export interface TaskRun {
|
||||||
export interface RedFlagsMap {
|
export interface RedFlagsMap {
|
||||||
[applicationId: string]: string[]
|
[applicationId: string]: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- v1.1 additions (wave A/B) ---
|
||||||
|
|
||||||
|
export interface TodayDeadline {
|
||||||
|
application_id: string
|
||||||
|
title: string
|
||||||
|
company: string
|
||||||
|
apply_by: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TodayResponseV11 extends TodayResponse {
|
||||||
|
deadlines?: TodayDeadline[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SuggestionClassification =
|
||||||
|
| 'interview_invite'
|
||||||
|
| 'rejection'
|
||||||
|
| 'question'
|
||||||
|
| 'noise'
|
||||||
|
|
||||||
|
export interface EmailSuggestion {
|
||||||
|
id: string
|
||||||
|
application_id: string | null
|
||||||
|
from_address: string
|
||||||
|
subject: string
|
||||||
|
snippet: string
|
||||||
|
classification: SuggestionClassification
|
||||||
|
created_at: string
|
||||||
|
status: 'pending' | 'accepted' | 'dismissed'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotificationLogEntry {
|
||||||
|
id: string
|
||||||
|
channel: string
|
||||||
|
message: string
|
||||||
|
data: Record<string, unknown> | null
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClusterPosting {
|
||||||
|
id: string
|
||||||
|
title: string
|
||||||
|
company: string
|
||||||
|
source: string
|
||||||
|
url: string
|
||||||
|
score: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Cluster {
|
||||||
|
cluster_id: string
|
||||||
|
postings: ClusterPosting[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TailorChangeLogEntry {
|
||||||
|
section: string
|
||||||
|
change: string
|
||||||
|
bullet_id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TailorCvResponse {
|
||||||
|
artifact_id: string
|
||||||
|
change_log: TailorChangeLogEntry[]
|
||||||
|
keyword_coverage: number
|
||||||
|
}
|
||||||
137
apps/web/src/views/ApplicationDetail.tailor.test.ts
Normal file
137
apps/web/src/views/ApplicationDetail.tailor.test.ts
Normal file
|
|
@ -0,0 +1,137 @@
|
||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
|
import { mount, flushPromises } from '@vue/test-utils'
|
||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
import type { Application, Artifact, TailorCvResponse } from '@/types'
|
||||||
|
|
||||||
|
vi.mock('@/api', () => ({
|
||||||
|
getApplications: vi.fn(),
|
||||||
|
getArtifacts: vi.fn(),
|
||||||
|
createCoverLetter: vi.fn(),
|
||||||
|
createApproval: vi.fn(),
|
||||||
|
confirmApproval: vi.fn(),
|
||||||
|
rejectApproval: vi.fn(),
|
||||||
|
outboxSend: vi.fn(),
|
||||||
|
interviewPrep: vi.fn(),
|
||||||
|
tailorCv: vi.fn(),
|
||||||
|
HttpError: class HttpError extends Error {
|
||||||
|
status: number
|
||||||
|
body: unknown
|
||||||
|
constructor(status: number, body: unknown, msg?: string) {
|
||||||
|
super(msg ?? `HTTP ${status}`)
|
||||||
|
this.status = status
|
||||||
|
this.body = body
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
function makeApp(): Application {
|
||||||
|
return {
|
||||||
|
id: 'app-1',
|
||||||
|
job_posting_id: 'j-1',
|
||||||
|
state: 'drafting',
|
||||||
|
score: 90,
|
||||||
|
score_rationale: null,
|
||||||
|
notes: '',
|
||||||
|
state_changed_at: '2026-01-01T00:00:00Z',
|
||||||
|
created_at: '2026-01-01T00:00:00Z',
|
||||||
|
posting: {
|
||||||
|
id: 'j-1', source: 'manual_url', external_id: null, url: 'http://x',
|
||||||
|
company: 'Acme', title: 'Engineer', location: 'Remote', description: '',
|
||||||
|
raw: {}, fetched_at: '2026-01-01T00:00:00Z'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeArtifact(): Artifact {
|
||||||
|
return {
|
||||||
|
id: 'art-1',
|
||||||
|
application_id: 'app-1',
|
||||||
|
kind: 'cover_letter',
|
||||||
|
filename: 'cover.pdf',
|
||||||
|
content_hash: 'abcdef0123456789',
|
||||||
|
storage_path: '/tmp/cover.pdf',
|
||||||
|
version: 1,
|
||||||
|
origin: 'user_drafted',
|
||||||
|
created_at: '2026-01-01T00:00:00Z'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeTailorResult(): TailorCvResponse {
|
||||||
|
return {
|
||||||
|
artifact_id: 'art-tailor-1',
|
||||||
|
change_log: [
|
||||||
|
{ section: 'experience', change: 'Reordered to highlight Python backend work', bullet_id: 'b-1' },
|
||||||
|
{ section: 'skills', change: 'Moved Docker and Kubernetes higher', bullet_id: 'b-5' }
|
||||||
|
],
|
||||||
|
keyword_coverage: 0.75
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mountDetail(app: Application, artifacts: Artifact[]) {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
const api = await import('@/api')
|
||||||
|
;(api.getApplications as ReturnType<typeof vi.fn>).mockResolvedValue([app])
|
||||||
|
;(api.getArtifacts as ReturnType<typeof vi.fn>).mockResolvedValue(artifacts)
|
||||||
|
const ApplicationDetail = (await import('@/views/ApplicationDetail.vue')).default
|
||||||
|
const wrapper = mount(ApplicationDetail, { props: { id: 'app-1' } })
|
||||||
|
await flushPromises()
|
||||||
|
return { wrapper }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Tailor CV panel', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders change log, coverage bar, and download link after tailoring', async () => {
|
||||||
|
const { wrapper } = await mountDetail(makeApp(), [makeArtifact()])
|
||||||
|
const api = await import('@/api')
|
||||||
|
|
||||||
|
// Panel should not be visible before clicking
|
||||||
|
expect(wrapper.find('[data-testid="tailor-panel"]').exists()).toBe(false)
|
||||||
|
|
||||||
|
// Mock tailorCv to return a result
|
||||||
|
;(api.tailorCv as ReturnType<typeof vi.fn>).mockResolvedValue(makeTailorResult())
|
||||||
|
// After tailoring, getArtifacts is called again to refresh
|
||||||
|
;(api.getArtifacts as ReturnType<typeof vi.fn>).mockResolvedValue([makeArtifact(), {
|
||||||
|
id: 'art-tailor-1',
|
||||||
|
application_id: 'app-1',
|
||||||
|
kind: 'cv',
|
||||||
|
filename: 'tailored_cv.pdf',
|
||||||
|
content_hash: 'deadbeef01234567',
|
||||||
|
storage_path: '/tmp/tailored_cv.pdf',
|
||||||
|
version: 1,
|
||||||
|
origin: 'ai_drafted',
|
||||||
|
created_at: '2026-07-30T00:00:00Z'
|
||||||
|
}])
|
||||||
|
|
||||||
|
// Click the Tailor CV button
|
||||||
|
const btn = wrapper.find('[data-testid="tailor-cv-btn"]')
|
||||||
|
expect(btn.exists()).toBe(true)
|
||||||
|
await btn.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// Panel should now be visible
|
||||||
|
const panel = wrapper.find('[data-testid="tailor-panel"]')
|
||||||
|
expect(panel.exists()).toBe(true)
|
||||||
|
|
||||||
|
// Change log entries should be visible
|
||||||
|
expect(panel.text()).toContain('Reordered to highlight Python backend work')
|
||||||
|
expect(panel.text()).toContain('Moved Docker and Kubernetes higher')
|
||||||
|
|
||||||
|
// Coverage bar should be present with 75%
|
||||||
|
expect(panel.text()).toContain('Keyword Coverage')
|
||||||
|
expect(panel.text()).toContain('75%')
|
||||||
|
const bar = panel.find('[data-testid="coverage-bar"]')
|
||||||
|
expect(bar.exists()).toBe(true)
|
||||||
|
expect(bar.attributes('style')).toContain('width: 75%')
|
||||||
|
|
||||||
|
// Download link should be present
|
||||||
|
const dl = panel.find('[data-testid="download-link"]')
|
||||||
|
expect(dl.exists()).toBe(true)
|
||||||
|
expect(dl.text()).toContain('Download tailored CV')
|
||||||
|
|
||||||
|
// Tailored artifact should appear in artifacts list
|
||||||
|
expect(wrapper.text()).toContain('tailored_cv.pdf')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -10,7 +10,8 @@ import type {
|
||||||
Approval,
|
Approval,
|
||||||
ApprovalAction,
|
ApprovalAction,
|
||||||
CoverLetterResponse,
|
CoverLetterResponse,
|
||||||
CritiqueComment
|
CritiqueComment,
|
||||||
|
TailorCvResponse
|
||||||
} from '@/types'
|
} from '@/types'
|
||||||
|
|
||||||
const props = defineProps<{ id: string }>()
|
const props = defineProps<{ id: string }>()
|
||||||
|
|
@ -36,6 +37,10 @@ const sending = ref(false)
|
||||||
// Interview prep modal
|
// Interview prep modal
|
||||||
const showPrepModal = ref(false)
|
const showPrepModal = ref(false)
|
||||||
|
|
||||||
|
// Tailor CV
|
||||||
|
const tailoring = ref(false)
|
||||||
|
const tailorResult = ref<TailorCvResponse | null>(null)
|
||||||
|
|
||||||
const isConfirmed = computed(() => approval.value?.confirmed_by_user ?? false)
|
const isConfirmed = computed(() => approval.value?.confirmed_by_user ?? false)
|
||||||
const canSend = computed(() => isConfirmed.value && !sending.value)
|
const canSend = computed(() => isConfirmed.value && !sending.value)
|
||||||
|
|
||||||
|
|
@ -47,6 +52,24 @@ const severityClass: Record<string, string> = {
|
||||||
low: 'bg-blue-50 border-blue-200'
|
low: 'bg-blue-50 border-blue-200'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const coverageColor = computed(() => {
|
||||||
|
if (!tailorResult.value) return 'bg-gray-300'
|
||||||
|
const c = tailorResult.value.keyword_coverage
|
||||||
|
if (c >= 0.7) return 'bg-green-500'
|
||||||
|
if (c >= 0.4) return 'bg-yellow-500'
|
||||||
|
return 'bg-red-500'
|
||||||
|
})
|
||||||
|
|
||||||
|
const coveragePercent = computed(() => {
|
||||||
|
if (!tailorResult.value) return 0
|
||||||
|
return Math.round(tailorResult.value.keyword_coverage * 100)
|
||||||
|
})
|
||||||
|
|
||||||
|
const downloadUrl = computed(() => {
|
||||||
|
if (!tailorResult.value) return ''
|
||||||
|
return `${import.meta.env.VITE_API_BASE ?? 'http://localhost:8000/api'}/artifacts/${tailorResult.value.artifact_id}/download`
|
||||||
|
})
|
||||||
|
|
||||||
async function loadData() {
|
async function loadData() {
|
||||||
try {
|
try {
|
||||||
const apps = await api.getApplications()
|
const apps = await api.getApplications()
|
||||||
|
|
@ -139,6 +162,27 @@ function closeInterviewPrep() {
|
||||||
showPrepModal.value = false
|
showPrepModal.value = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function tailorCv() {
|
||||||
|
tailoring.value = true
|
||||||
|
tailorResult.value = null
|
||||||
|
try {
|
||||||
|
const res = await api.tailorCv(props.id)
|
||||||
|
tailorResult.value = res
|
||||||
|
// Refresh artifacts to show the new tailored CV variant
|
||||||
|
artifacts.value = await api.getArtifacts(props.id)
|
||||||
|
toast.push('CV tailored for this job', 'success')
|
||||||
|
} catch (err) {
|
||||||
|
let msg = 'Failed to tailor CV'
|
||||||
|
if (err instanceof HttpError) {
|
||||||
|
const body = err.body as { error?: { message?: string } } | null
|
||||||
|
msg = body?.error?.message ?? msg
|
||||||
|
}
|
||||||
|
toast.push(msg, 'error')
|
||||||
|
} finally {
|
||||||
|
tailoring.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(loadData)
|
onMounted(loadData)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
@ -159,6 +203,69 @@ onMounted(loadData)
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<!-- Tailor CV -->
|
||||||
|
<section class="bg-white rounded-lg border border-gray-200 p-4 space-y-3">
|
||||||
|
<h2 class="font-semibold">Tailor CV for this Job</h2>
|
||||||
|
<p class="text-sm text-gray-600">
|
||||||
|
Generate a tailored CV variant that reorders and rephrases your existing sections toward this posting's keywords. Your facts are never invented, only rephrased.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
@click="tailorCv"
|
||||||
|
:disabled="tailoring"
|
||||||
|
class="bg-indigo-600 text-white px-4 py-2 rounded text-sm disabled:opacity-50"
|
||||||
|
data-testid="tailor-cv-btn"
|
||||||
|
>
|
||||||
|
{{ tailoring ? 'Tailoring...' : 'Tailor My CV' }}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Tailor result panel -->
|
||||||
|
<div v-if="tailorResult" class="space-y-4 border-t border-gray-100 pt-3" data-testid="tailor-panel">
|
||||||
|
<!-- Keyword coverage bar -->
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center justify-between text-sm mb-1">
|
||||||
|
<span class="text-gray-600">Keyword Coverage</span>
|
||||||
|
<span class="font-medium">{{ coveragePercent }}%</span>
|
||||||
|
</div>
|
||||||
|
<div class="w-full bg-gray-200 rounded-full h-3">
|
||||||
|
<div
|
||||||
|
class="h-3 rounded-full transition-all"
|
||||||
|
:class="coverageColor"
|
||||||
|
:style="{ width: coveragePercent + '%' }"
|
||||||
|
data-testid="coverage-bar"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Change log -->
|
||||||
|
<div>
|
||||||
|
<h3 class="font-medium text-sm mb-2">Changes Made</h3>
|
||||||
|
<ul class="text-sm space-y-1">
|
||||||
|
<li
|
||||||
|
v-for="(entry, i) in tailorResult.change_log"
|
||||||
|
:key="i"
|
||||||
|
class="border-b border-gray-100 py-1"
|
||||||
|
>
|
||||||
|
<span class="font-medium text-gray-700">{{ entry.section }}:</span>
|
||||||
|
<span class="text-gray-600 ml-1">{{ entry.change }}</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Download link -->
|
||||||
|
<div>
|
||||||
|
<a
|
||||||
|
:href="downloadUrl"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
class="text-sm text-indigo-600 hover:underline"
|
||||||
|
data-testid="download-link"
|
||||||
|
>
|
||||||
|
Download tailored CV (PDF)
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<!-- Interview prep -->
|
<!-- Interview prep -->
|
||||||
<section class="bg-white rounded-lg border border-gray-200 p-4 space-y-3">
|
<section class="bg-white rounded-lg border border-gray-200 p-4 space-y-3">
|
||||||
<h2 class="font-semibold">Interview Prep</h2>
|
<h2 class="font-semibold">Interview Prep</h2>
|
||||||
|
|
@ -184,7 +291,6 @@ onMounted(loadData)
|
||||||
</ul>
|
</ul>
|
||||||
<p v-else class="text-sm text-gray-400">No artifacts yet.</p>
|
<p v-else class="text-sm text-gray-400">No artifacts yet.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Cover letter editor + critique -->
|
<!-- Cover letter editor + critique -->
|
||||||
<section class="bg-white rounded-lg border border-gray-200 p-4 space-y-3">
|
<section class="bg-white rounded-lg border border-gray-200 p-4 space-y-3">
|
||||||
<h2 class="font-semibold">Cover Letter</h2>
|
<h2 class="font-semibold">Cover Letter</h2>
|
||||||
|
|
|
||||||
103
apps/web/src/views/Research.clusters.test.ts
Normal file
103
apps/web/src/views/Research.clusters.test.ts
Normal file
|
|
@ -0,0 +1,103 @@
|
||||||
|
import { describe, it, expect, vi } from 'vitest'
|
||||||
|
import { mount, flushPromises } from '@vue/test-utils'
|
||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
|
||||||
|
vi.mock('@/api', () => ({
|
||||||
|
getPostings: vi.fn(),
|
||||||
|
getClusters: vi.fn(),
|
||||||
|
createPosting: vi.fn(),
|
||||||
|
fetchPostings: vi.fn(),
|
||||||
|
scorePosting: vi.fn(),
|
||||||
|
batchScore: vi.fn().mockResolvedValue({ results: [] }),
|
||||||
|
HttpError: class HttpError extends Error {
|
||||||
|
status: number
|
||||||
|
body: unknown
|
||||||
|
constructor(status: number, body: unknown, msg?: string) {
|
||||||
|
super(msg ?? `HTTP ${status}`)
|
||||||
|
this.status = status
|
||||||
|
this.body = body
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
describe('Research cluster alternates', () => {
|
||||||
|
it('renders cluster header with alternate count and expands to show alternates', async () => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
const api = await import('@/api')
|
||||||
|
const Research = (await import('@/views/Research.vue')).default
|
||||||
|
|
||||||
|
// Two postings in the same cluster
|
||||||
|
const postings = [
|
||||||
|
{
|
||||||
|
id: 'p-1', source: 'manual_url', external_id: null, url: 'http://a',
|
||||||
|
company: 'Acme', title: 'Backend Dev', location: 'Malmo', description: '',
|
||||||
|
raw: {}, fetched_at: '2026-07-30T00:00:00Z', cluster_id: 'c-1'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'p-2', source: 'linkedin', external_id: null, url: 'http://b',
|
||||||
|
company: 'Acme', title: 'Backend Dev', location: 'Remote', description: '',
|
||||||
|
raw: {}, fetched_at: '2026-07-30T00:00:00Z', cluster_id: 'c-1'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
// Clusters endpoint returns the cluster with alternate postings
|
||||||
|
const clusters = [
|
||||||
|
{
|
||||||
|
cluster_id: 'c-1',
|
||||||
|
postings: [
|
||||||
|
{ id: 'p-1', title: 'Backend Dev', company: 'Acme', source: 'manual_url', url: 'http://a', score: 85 },
|
||||||
|
{ id: 'p-2', title: 'Backend Dev', company: 'Acme', source: 'linkedin', url: 'http://b', score: 80 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
;(api.getPostings as ReturnType<typeof vi.fn>).mockResolvedValue(postings)
|
||||||
|
;(api.getClusters as ReturnType<typeof vi.fn>).mockResolvedValue(clusters)
|
||||||
|
|
||||||
|
const wrapper = mount(Research)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// Cluster header should show "Also via 1 more"
|
||||||
|
expect(wrapper.text()).toContain('Also via 1 more')
|
||||||
|
|
||||||
|
// Alternates should NOT be visible before expanding
|
||||||
|
const alternatesBefore = wrapper.find('[data-testid="cluster-alternates"]')
|
||||||
|
expect(alternatesBefore.exists()).toBe(false)
|
||||||
|
|
||||||
|
// Click to expand
|
||||||
|
const toggle = wrapper.find('[data-testid="cluster-alternates-toggle"]')
|
||||||
|
expect(toggle.exists()).toBe(true)
|
||||||
|
await toggle.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// Alternates should now be visible
|
||||||
|
const alternatesAfter = wrapper.find('[data-testid="cluster-alternates"]')
|
||||||
|
expect(alternatesAfter.exists()).toBe(true)
|
||||||
|
// Should show the alternate source (linkedin) and link
|
||||||
|
expect(alternatesAfter.text()).toContain('linkedin')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not show cluster header for single postings without alternates', async () => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
const api = await import('@/api')
|
||||||
|
const Research = (await import('@/views/Research.vue')).default
|
||||||
|
|
||||||
|
const postings = [
|
||||||
|
{
|
||||||
|
id: 'p-3', source: 'manual_url', external_id: null, url: 'http://c',
|
||||||
|
company: 'Globex', title: 'Manager', location: 'Stockholm', description: '',
|
||||||
|
raw: {}, fetched_at: '2026-07-30T00:00:00Z'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
;(api.getPostings as ReturnType<typeof vi.fn>).mockResolvedValue(postings)
|
||||||
|
;(api.getClusters as ReturnType<typeof vi.fn>).mockResolvedValue([])
|
||||||
|
|
||||||
|
const wrapper = mount(Research)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// Should not show "Also via" since no alternates
|
||||||
|
expect(wrapper.text()).not.toContain('Also via')
|
||||||
|
expect(wrapper.text()).toContain('Globex')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -1,18 +1,20 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, ref } from 'vue'
|
import { onMounted, ref, computed } from 'vue'
|
||||||
import { useToastStore } from '@/stores/toast'
|
import { useToastStore } from '@/stores/toast'
|
||||||
import * as api from '@/api'
|
import * as api from '@/api'
|
||||||
import { HttpError } from '@/api'
|
import { HttpError } from '@/api'
|
||||||
import type { JobPosting } from '@/types'
|
import type { JobPosting, Cluster } from '@/types'
|
||||||
|
|
||||||
const toast = useToastStore()
|
const toast = useToastStore()
|
||||||
|
|
||||||
const postings = ref<JobPosting[]>([])
|
const postings = ref<JobPosting[]>([])
|
||||||
|
const clusters = ref<Cluster[]>([])
|
||||||
const loading = ref(true)
|
const loading = ref(true)
|
||||||
const newUrl = ref('')
|
const newUrl = ref('')
|
||||||
const scoringId = ref<string | null>(null)
|
const scoringId = ref<string | null>(null)
|
||||||
const scoreMap = ref<Record<string, { score: number; rationale: Record<string, unknown> }>>({})
|
const scoreMap = ref<Record<string, { score: number; rationale: Record<string, unknown> }>>({})
|
||||||
const redFlagsMap = ref<Record<string, string[]>>({})
|
const redFlagsMap = ref<Record<string, string[]>>({})
|
||||||
|
const expandedClusters = ref<Set<string>>(new Set())
|
||||||
|
|
||||||
// Fetch form
|
// Fetch form
|
||||||
const fetchQuery = ref('')
|
const fetchQuery = ref('')
|
||||||
|
|
@ -20,9 +22,65 @@ const fetchRegion = ref('')
|
||||||
const fetching = ref(false)
|
const fetching = ref(false)
|
||||||
const fetchResult = ref<{ new: number; dupes: number } | null>(null)
|
const fetchResult = ref<{ new: number; dupes: number } | null>(null)
|
||||||
|
|
||||||
|
// Group postings by cluster_id from the posting data. Postings without cluster_id get unique singleton groups.
|
||||||
|
const groupedPostings = computed(() => {
|
||||||
|
const map = new Map<string, JobPosting[]>()
|
||||||
|
for (const p of postings.value) {
|
||||||
|
const cid = (p as JobPosting & { cluster_id?: string }).cluster_id ?? `solo-${p.id}`
|
||||||
|
if (!map.has(cid)) map.set(cid, [])
|
||||||
|
map.get(cid)!.push(p)
|
||||||
|
}
|
||||||
|
return Array.from(map.entries()).map(([cluster_id, items]) => ({ cluster_id, items }))
|
||||||
|
})
|
||||||
|
|
||||||
|
// Best score per cluster (from cluster endpoint or from scoreMap)
|
||||||
|
function clusterBestScore(clusterId: string): number | null {
|
||||||
|
const cluster = clusters.value.find((c) => c.cluster_id === clusterId)
|
||||||
|
if (cluster && cluster.postings.length > 0) {
|
||||||
|
return Math.max(...cluster.postings.map((p) => p.score))
|
||||||
|
}
|
||||||
|
const items = groupedPostings.value.find((g) => g.cluster_id === clusterId)?.items
|
||||||
|
if (items) {
|
||||||
|
const scores = items.map((p) => scoreMap.value[p.id]?.score).filter((s): s is number => s != null)
|
||||||
|
return scores.length > 0 ? Math.max(...scores) : null
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alternates for a cluster (from GET /clusters endpoint)
|
||||||
|
function clusterAlternatives(clusterId: string): Cluster['postings'] {
|
||||||
|
const cluster = clusters.value.find((c) => c.cluster_id === clusterId)
|
||||||
|
if (!cluster) return []
|
||||||
|
// Return postings other than the first/best one
|
||||||
|
return cluster.postings.slice(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isExpanded(clusterId: string): boolean {
|
||||||
|
return expandedClusters.value.has(clusterId)
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleExpand(clusterId: string) {
|
||||||
|
const next = new Set(expandedClusters.value)
|
||||||
|
if (next.has(clusterId)) {
|
||||||
|
next.delete(clusterId)
|
||||||
|
} else {
|
||||||
|
next.add(clusterId)
|
||||||
|
}
|
||||||
|
expandedClusters.value = next
|
||||||
|
}
|
||||||
|
|
||||||
async function loadPostings() {
|
async function loadPostings() {
|
||||||
try {
|
try {
|
||||||
postings.value = await api.getPostings()
|
const [postingsRes, clustersRes] = await Promise.allSettled([
|
||||||
|
api.getPostings(),
|
||||||
|
api.getClusters()
|
||||||
|
])
|
||||||
|
if (postingsRes.status === 'fulfilled') {
|
||||||
|
postings.value = postingsRes.value
|
||||||
|
}
|
||||||
|
if (clustersRes.status === 'fulfilled') {
|
||||||
|
clusters.value = clustersRes.value
|
||||||
|
}
|
||||||
// Load red flags for existing postings via batch scoring
|
// Load red flags for existing postings via batch scoring
|
||||||
if (postings.value.length > 0) {
|
if (postings.value.length > 0) {
|
||||||
try {
|
try {
|
||||||
|
|
@ -150,49 +208,101 @@ onMounted(loadPostings)
|
||||||
|
|
||||||
<div v-if="loading" class="text-gray-500">Loading...</div>
|
<div v-if="loading" class="text-gray-500">Loading...</div>
|
||||||
|
|
||||||
<table v-if="!loading" class="w-full bg-white rounded-lg border border-gray-200 text-sm">
|
<!-- Cluster grouped postings -->
|
||||||
<thead class="bg-gray-50 text-left">
|
<div v-if="!loading" class="space-y-4">
|
||||||
<tr>
|
<div
|
||||||
<th class="px-3 py-2">Company</th>
|
v-for="group in groupedPostings"
|
||||||
<th class="px-3 py-2">Title</th>
|
:key="group.cluster_id"
|
||||||
<th class="px-3 py-2">Location</th>
|
class="bg-white rounded-lg border border-gray-200"
|
||||||
<th class="px-3 py-2">Source</th>
|
>
|
||||||
<th class="px-3 py-2">Scam</th>
|
<!-- Cluster header -->
|
||||||
<th class="px-3 py-2">Fetched</th>
|
<div
|
||||||
<th class="px-3 py-2">Actions</th>
|
v-if="clusterAlternatives(group.cluster_id).length > 0"
|
||||||
</tr>
|
class="flex items-center justify-between px-4 py-2 border-b border-gray-100 cursor-pointer hover:bg-gray-50"
|
||||||
</thead>
|
@click="toggleExpand(group.cluster_id)"
|
||||||
<tbody>
|
>
|
||||||
<tr v-for="p in postings" :key="p.id" class="border-t border-gray-100">
|
<span class="text-sm font-medium text-gray-700">
|
||||||
<td class="px-3 py-2">{{ p.company }}</td>
|
{{ group.items[0]?.company ?? 'Unknown' }} - {{ group.items[0]?.title ?? 'No title' }}
|
||||||
<td class="px-3 py-2">{{ p.title }}</td>
|
</span>
|
||||||
<td class="px-3 py-2">{{ p.location }}</td>
|
<span class="text-xs text-gray-500" data-testid="cluster-alternates-toggle">
|
||||||
<td class="px-3 py-2">{{ p.source }}</td>
|
Also via {{ clusterAlternatives(group.cluster_id).length }} more
|
||||||
<td class="px-3 py-2">
|
<span v-if="isExpanded(group.cluster_id)">▲</span>
|
||||||
<span
|
<span v-else>▼</span>
|
||||||
v-if="hasScamFlag(p)"
|
</span>
|
||||||
class="text-red-600 font-bold"
|
</div>
|
||||||
:title="scamFlagsFor(p).join('; ')"
|
|
||||||
|
<!-- Main posting table for this cluster -->
|
||||||
|
<table class="w-full text-sm">
|
||||||
|
<thead class="bg-gray-50 text-left">
|
||||||
|
<tr>
|
||||||
|
<th class="px-3 py-2">Company</th>
|
||||||
|
<th class="px-3 py-2">Title</th>
|
||||||
|
<th class="px-3 py-2">Location</th>
|
||||||
|
<th class="px-3 py-2">Source</th>
|
||||||
|
<th class="px-3 py-2">Scam</th>
|
||||||
|
<th class="px-3 py-2">Fetched</th>
|
||||||
|
<th class="px-3 py-2">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="p in group.items" :key="p.id" class="border-t border-gray-100">
|
||||||
|
<td class="px-3 py-2">{{ p.company }}</td>
|
||||||
|
<td class="px-3 py-2">{{ p.title }}</td>
|
||||||
|
<td class="px-3 py-2">{{ p.location }}</td>
|
||||||
|
<td class="px-3 py-2">{{ p.source }}</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<span
|
||||||
|
v-if="hasScamFlag(p)"
|
||||||
|
class="text-red-600 font-bold"
|
||||||
|
:title="scamFlagsFor(p).join('; ')"
|
||||||
|
>
|
||||||
|
⚠
|
||||||
|
</span>
|
||||||
|
<span v-else class="text-gray-400">-</span>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2 text-gray-500">{{ p.fetched_at?.slice(0, 10) }}</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<button
|
||||||
|
@click="scorePosting(p)"
|
||||||
|
:disabled="scoringId === p.id"
|
||||||
|
class="text-indigo-600 hover:underline text-sm"
|
||||||
|
>
|
||||||
|
{{ scoringId === p.id ? 'Scoring...' : 'Score' }}
|
||||||
|
</button>
|
||||||
|
<span v-if="scoreMap[p.id]" class="ml-2 text-xs bg-green-100 text-green-800 rounded px-2 py-0.5">
|
||||||
|
{{ scoreMap[p.id].score }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<!-- Expandable alternates -->
|
||||||
|
<div
|
||||||
|
v-if="isExpanded(group.cluster_id) && clusterAlternatives(group.cluster_id).length > 0"
|
||||||
|
class="border-t border-gray-100 px-4 py-3 bg-gray-50"
|
||||||
|
data-testid="cluster-alternates"
|
||||||
|
>
|
||||||
|
<div class="text-xs font-medium text-gray-500 mb-2">Alternate sources for this role:</div>
|
||||||
|
<ul class="text-sm space-y-1">
|
||||||
|
<li
|
||||||
|
v-for="alt in clusterAlternatives(group.cluster_id)"
|
||||||
|
:key="alt.id"
|
||||||
|
class="flex items-center justify-between"
|
||||||
>
|
>
|
||||||
⚠
|
<span>
|
||||||
</span>
|
<a :href="alt.url" target="_blank" rel="noopener" class="text-indigo-600 hover:underline">
|
||||||
<span v-else class="text-gray-400">-</span>
|
{{ alt.company }}
|
||||||
</td>
|
</a>
|
||||||
<td class="px-3 py-2 text-gray-500">{{ p.fetched_at?.slice(0, 10) }}</td>
|
<span class="text-gray-400 ml-2">({{ alt.source }})</span>
|
||||||
<td class="px-3 py-2">
|
</span>
|
||||||
<button
|
<span v-if="alt.score" class="text-xs bg-green-100 text-green-800 rounded px-2 py-0.5">
|
||||||
@click="scorePosting(p)"
|
{{ alt.score }}
|
||||||
:disabled="scoringId === p.id"
|
</span>
|
||||||
class="text-indigo-600 hover:underline text-sm"
|
</li>
|
||||||
>
|
</ul>
|
||||||
{{ scoringId === p.id ? 'Scoring...' : 'Score' }}
|
</div>
|
||||||
</button>
|
</div>
|
||||||
<span v-if="scoreMap[p.id]" class="ml-2 text-xs bg-green-100 text-green-800 rounded px-2 py-0.5">
|
</div>
|
||||||
{{ scoreMap[p.id].score }}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
79
apps/web/src/views/TodayView.deadlines.test.ts
Normal file
79
apps/web/src/views/TodayView.deadlines.test.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
||||||
|
import { describe, it, expect, vi } from 'vitest'
|
||||||
|
import { mount, flushPromises } from '@vue/test-utils'
|
||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
|
||||||
|
vi.mock('@/api', () => ({
|
||||||
|
getToday: vi.fn(),
|
||||||
|
getSuggestions: vi.fn().mockResolvedValue([]),
|
||||||
|
getNotificationLog: vi.fn().mockResolvedValue([]),
|
||||||
|
acceptSuggestion: vi.fn(),
|
||||||
|
dismissSuggestion: vi.fn(),
|
||||||
|
getTelemetryTasks: vi.fn().mockResolvedValue([]),
|
||||||
|
HttpError: class HttpError extends Error {
|
||||||
|
status: number
|
||||||
|
body: unknown
|
||||||
|
constructor(status: number, body: unknown, msg?: string) {
|
||||||
|
super(msg ?? `HTTP ${status}`)
|
||||||
|
this.status = status
|
||||||
|
this.body = body
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
describe('TodayView deadlines strip', () => {
|
||||||
|
it('renders deadline cards with urgent styling when <= 2 days', async () => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
const api = await import('@/api')
|
||||||
|
const TodayView = (await import('@/views/TodayView.vue')).default
|
||||||
|
|
||||||
|
// Build deadlines: one urgent (tomorrow) and one normal (5 days)
|
||||||
|
const tomorrow = new Date()
|
||||||
|
tomorrow.setDate(tomorrow.getDate() + 1)
|
||||||
|
const fiveDays = new Date()
|
||||||
|
fiveDays.setDate(fiveDays.getDate() + 5)
|
||||||
|
|
||||||
|
;(api.getToday as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||||
|
digest: [],
|
||||||
|
nudges: [],
|
||||||
|
pending_approvals: 0,
|
||||||
|
deadlines: [
|
||||||
|
{ application_id: 'app-1', title: 'Backend Dev', company: 'Acme', apply_by: tomorrow.toISOString().slice(0, 10) },
|
||||||
|
{ application_id: 'app-2', title: 'Frontend Dev', company: 'Globex', apply_by: fiveDays.toISOString().slice(0, 10) }
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(TodayView)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// Section heading present
|
||||||
|
expect(wrapper.text()).toContain('Deadlines This Week')
|
||||||
|
|
||||||
|
// Both companies shown
|
||||||
|
expect(wrapper.text()).toContain('Acme')
|
||||||
|
expect(wrapper.text()).toContain('Globex')
|
||||||
|
|
||||||
|
// Urgent card has red background class
|
||||||
|
const urgentCard = wrapper.findAll('.bg-red-50')
|
||||||
|
expect(urgentCard.length).toBeGreaterThanOrEqual(1)
|
||||||
|
expect(urgentCard[0].text()).toContain('Backend Dev')
|
||||||
|
expect(urgentCard[0].text()).toContain('Acme')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not render deadlines section when no deadlines', async () => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
const api = await import('@/api')
|
||||||
|
const TodayView = (await import('@/views/TodayView.vue')).default
|
||||||
|
|
||||||
|
;(api.getToday as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||||
|
digest: [],
|
||||||
|
nudges: [],
|
||||||
|
pending_approvals: 0,
|
||||||
|
deadlines: []
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(TodayView)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.text()).not.toContain('Deadlines This Week')
|
||||||
|
})
|
||||||
|
})
|
||||||
125
apps/web/src/views/TodayView.suggestions.test.ts
Normal file
125
apps/web/src/views/TodayView.suggestions.test.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
import { describe, it, expect, vi } from 'vitest'
|
||||||
|
import { mount, flushPromises } from '@vue/test-utils'
|
||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
|
||||||
|
vi.mock('@/api', () => ({
|
||||||
|
getToday: vi.fn(),
|
||||||
|
getSuggestions: vi.fn(),
|
||||||
|
getNotificationLog: vi.fn().mockResolvedValue([]),
|
||||||
|
acceptSuggestion: vi.fn(),
|
||||||
|
dismissSuggestion: vi.fn(),
|
||||||
|
getTelemetryTasks: vi.fn().mockResolvedValue([]),
|
||||||
|
HttpError: class HttpError extends Error {
|
||||||
|
status: number
|
||||||
|
body: unknown
|
||||||
|
constructor(status: number, body: unknown, msg?: string) {
|
||||||
|
super(msg ?? `HTTP ${status}`)
|
||||||
|
this.status = status
|
||||||
|
this.body = body
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
describe('TodayView suggestions accept flow', () => {
|
||||||
|
it('calls acceptSuggestion API and removes card from pending list', async () => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
const api = await import('@/api')
|
||||||
|
const TodayView = (await import('@/views/TodayView.vue')).default
|
||||||
|
|
||||||
|
const suggestions = [
|
||||||
|
{
|
||||||
|
id: 'sug-1',
|
||||||
|
application_id: 'app-1',
|
||||||
|
from_address: 'recruiter@acme.com',
|
||||||
|
subject: 'Interview Invitation',
|
||||||
|
snippet: 'We would like to invite you...',
|
||||||
|
classification: 'interview_invite',
|
||||||
|
created_at: '2026-07-30T10:00:00Z',
|
||||||
|
status: 'pending'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sug-2',
|
||||||
|
application_id: 'app-2',
|
||||||
|
from_address: 'noreply@globex.com',
|
||||||
|
subject: 'Application Update',
|
||||||
|
snippet: 'Thank you for applying...',
|
||||||
|
classification: 'rejection',
|
||||||
|
created_at: '2026-07-30T11:00:00Z',
|
||||||
|
status: 'pending'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
;(api.getToday as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||||
|
digest: [],
|
||||||
|
nudges: [],
|
||||||
|
pending_approvals: 0,
|
||||||
|
deadlines: []
|
||||||
|
})
|
||||||
|
;(api.getSuggestions as ReturnType<typeof vi.fn>).mockResolvedValue(suggestions)
|
||||||
|
// Accept returns the updated suggestion with status 'accepted'
|
||||||
|
;(api.acceptSuggestion as ReturnType<typeof vi.fn>).mockResolvedValue({ ...suggestions[0], status: 'accepted' })
|
||||||
|
|
||||||
|
const wrapper = mount(TodayView)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// Both suggestions visible initially
|
||||||
|
expect(wrapper.text()).toContain('Interview Invitation')
|
||||||
|
expect(wrapper.text()).toContain('Application Update')
|
||||||
|
expect(wrapper.text()).toContain('Interview Invite')
|
||||||
|
|
||||||
|
// Click Accept on first suggestion
|
||||||
|
const acceptBtns = wrapper.findAll('[data-testid="accept-suggestion"]')
|
||||||
|
expect(acceptBtns.length).toBe(2)
|
||||||
|
await acceptBtns[0].trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// API was called with the right id
|
||||||
|
expect(api.acceptSuggestion).toHaveBeenCalledWith('sug-1')
|
||||||
|
|
||||||
|
// The accepted suggestion should no longer appear in the pending list
|
||||||
|
expect(wrapper.text()).not.toContain('Interview Invitation')
|
||||||
|
// The other suggestion should still be present
|
||||||
|
expect(wrapper.text()).toContain('Application Update')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('calls dismissSuggestion API and removes card from pending list', async () => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
const api = await import('@/api')
|
||||||
|
const TodayView = (await import('@/views/TodayView.vue')).default
|
||||||
|
|
||||||
|
const suggestions = [
|
||||||
|
{
|
||||||
|
id: 'sug-3',
|
||||||
|
application_id: null,
|
||||||
|
from_address: 'spam@noise.com',
|
||||||
|
subject: 'Some spam',
|
||||||
|
snippet: 'Buy our product...',
|
||||||
|
classification: 'noise',
|
||||||
|
created_at: '2026-07-30T12:00:00Z',
|
||||||
|
status: 'pending'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
;(api.getToday as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||||
|
digest: [],
|
||||||
|
nudges: [],
|
||||||
|
pending_approvals: 0,
|
||||||
|
deadlines: []
|
||||||
|
})
|
||||||
|
;(api.getSuggestions as ReturnType<typeof vi.fn>).mockResolvedValue(suggestions)
|
||||||
|
;(api.dismissSuggestion as ReturnType<typeof vi.fn>).mockResolvedValue({ ...suggestions[0], status: 'dismissed' })
|
||||||
|
|
||||||
|
const wrapper = mount(TodayView)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('Some spam')
|
||||||
|
|
||||||
|
const dismissBtn = wrapper.find('[data-testid="dismiss-suggestion"]')
|
||||||
|
expect(dismissBtn.exists()).toBe(true)
|
||||||
|
await dismissBtn.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(api.dismissSuggestion).toHaveBeenCalledWith('sug-3')
|
||||||
|
expect(wrapper.text()).not.toContain('Some spam')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -4,19 +4,73 @@ import { useRouter } from 'vue-router'
|
||||||
import { useToastStore } from '@/stores/toast'
|
import { useToastStore } from '@/stores/toast'
|
||||||
import * as api from '@/api'
|
import * as api from '@/api'
|
||||||
import CostDisplay from '@/components/CostDisplay.vue'
|
import CostDisplay from '@/components/CostDisplay.vue'
|
||||||
import type { TodayResponse } from '@/types'
|
import type { TodayResponse, TodayDeadline, EmailSuggestion, NotificationLogEntry, SuggestionClassification } from '@/types'
|
||||||
|
|
||||||
const toast = useToastStore()
|
const toast = useToastStore()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
|
||||||
const today = ref<TodayResponse | null>(null)
|
const today = ref<TodayResponse | null>(null)
|
||||||
const loading = ref(true)
|
const loading = ref(true)
|
||||||
|
const deadlines = ref<TodayDeadline[]>([])
|
||||||
|
const suggestions = ref<EmailSuggestion[]>([])
|
||||||
|
const notifications = ref<NotificationLogEntry[]>([])
|
||||||
|
const suggestionActioningId = ref<string | null>(null)
|
||||||
|
|
||||||
const nudgeIds = computed(() => new Set(today.value?.nudges.map((n) => n.application_id) ?? []))
|
const nudgeIds = computed(() => new Set(today.value?.nudges.map((n) => n.application_id) ?? []))
|
||||||
|
|
||||||
|
const pendingSuggestions = computed(() =>
|
||||||
|
suggestions.value.filter((s) => s.status === 'pending')
|
||||||
|
)
|
||||||
|
|
||||||
|
const classificationChipClass: Record<SuggestionClassification, string> = {
|
||||||
|
interview_invite: 'bg-green-100 text-green-800',
|
||||||
|
rejection: 'bg-red-100 text-red-800',
|
||||||
|
question: 'bg-yellow-100 text-yellow-800',
|
||||||
|
noise: 'bg-gray-100 text-gray-600'
|
||||||
|
}
|
||||||
|
|
||||||
|
const classificationLabel: Record<SuggestionClassification, string> = {
|
||||||
|
interview_invite: 'Interview Invite',
|
||||||
|
rejection: 'Rejection',
|
||||||
|
question: 'Question',
|
||||||
|
noise: 'Noise'
|
||||||
|
}
|
||||||
|
|
||||||
|
function daysUntil(dateStr: string): number {
|
||||||
|
const today = new Date()
|
||||||
|
today.setHours(0, 0, 0, 0)
|
||||||
|
const target = new Date(dateStr)
|
||||||
|
target.setHours(0, 0, 0, 0)
|
||||||
|
const diff = Math.round((target.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
|
||||||
|
return diff
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUrgent(dateStr: string): boolean {
|
||||||
|
return daysUntil(dateStr) <= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(dateStr: string): string {
|
||||||
|
const d = new Date(dateStr)
|
||||||
|
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
|
||||||
|
}
|
||||||
|
|
||||||
async function loadToday() {
|
async function loadToday() {
|
||||||
try {
|
try {
|
||||||
today.value = await api.getToday()
|
const [todayRes, suggestionsRes, notifRes] = await Promise.allSettled([
|
||||||
|
api.getToday(),
|
||||||
|
api.getSuggestions(),
|
||||||
|
api.getNotificationLog()
|
||||||
|
])
|
||||||
|
if (todayRes.status === 'fulfilled') {
|
||||||
|
today.value = todayRes.value
|
||||||
|
deadlines.value = todayRes.value.deadlines ?? []
|
||||||
|
}
|
||||||
|
if (suggestionsRes.status === 'fulfilled') {
|
||||||
|
suggestions.value = suggestionsRes.value
|
||||||
|
}
|
||||||
|
if (notifRes.status === 'fulfilled') {
|
||||||
|
notifications.value = notifRes.value.slice(0, 5)
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
toast.push('Failed to load today digest', 'error')
|
toast.push('Failed to load today digest', 'error')
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -24,6 +78,36 @@ async function loadToday() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function acceptSuggestion(id: string) {
|
||||||
|
suggestionActioningId.value = id
|
||||||
|
try {
|
||||||
|
await api.acceptSuggestion(id)
|
||||||
|
suggestions.value = suggestions.value.map((s) =>
|
||||||
|
s.id === id ? { ...s, status: 'accepted' } : s
|
||||||
|
)
|
||||||
|
toast.push('Suggestion accepted', 'success')
|
||||||
|
} catch {
|
||||||
|
toast.push('Failed to accept suggestion', 'error')
|
||||||
|
} finally {
|
||||||
|
suggestionActioningId.value = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function dismissSuggestion(id: string) {
|
||||||
|
suggestionActioningId.value = id
|
||||||
|
try {
|
||||||
|
await api.dismissSuggestion(id)
|
||||||
|
suggestions.value = suggestions.value.map((s) =>
|
||||||
|
s.id === id ? { ...s, status: 'dismissed' } : s
|
||||||
|
)
|
||||||
|
toast.push('Suggestion dismissed', 'success')
|
||||||
|
} catch {
|
||||||
|
toast.push('Failed to dismiss suggestion', 'error')
|
||||||
|
} finally {
|
||||||
|
suggestionActioningId.value = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function goToApplication(id: string) {
|
function goToApplication(id: string) {
|
||||||
router.push(`/applications/${id}`)
|
router.push(`/applications/${id}`)
|
||||||
}
|
}
|
||||||
|
|
@ -56,6 +140,76 @@ onMounted(loadToday)
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Deadlines this week strip -->
|
||||||
|
<section v-if="deadlines.length > 0">
|
||||||
|
<h2 class="font-semibold text-lg mb-3">Deadlines This Week</h2>
|
||||||
|
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<div
|
||||||
|
v-for="d in deadlines"
|
||||||
|
:key="d.application_id"
|
||||||
|
class="rounded-lg border p-4 cursor-pointer hover:shadow-md transition-shadow"
|
||||||
|
:class="isUrgent(d.apply_by) ? 'bg-red-50 border-red-300' : 'bg-white border-gray-200'"
|
||||||
|
@click="goToApplication(d.application_id)"
|
||||||
|
>
|
||||||
|
<div class="font-medium">{{ d.title }}</div>
|
||||||
|
<div class="text-sm text-gray-600">{{ d.company }}</div>
|
||||||
|
<div
|
||||||
|
class="mt-2 text-sm font-medium"
|
||||||
|
:class="isUrgent(d.apply_by) ? 'text-red-700' : 'text-gray-600'"
|
||||||
|
>
|
||||||
|
Apply by {{ formatDate(d.apply_by) }}
|
||||||
|
<span v-if="daysUntil(d.apply_by) === 0" class="ml-1">(today)</span>
|
||||||
|
<span v-else-if="daysUntil(d.apply_by) === 1" class="ml-1">(tomorrow)</span>
|
||||||
|
<span v-else class="ml-1">({{ daysUntil(d.apply_by) }} days)</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Inbox insights strip -->
|
||||||
|
<section v-if="pendingSuggestions.length > 0">
|
||||||
|
<h2 class="font-semibold text-lg mb-3">Inbox Insights</h2>
|
||||||
|
<div class="space-y-3">
|
||||||
|
<div
|
||||||
|
v-for="s in pendingSuggestions"
|
||||||
|
:key="s.id"
|
||||||
|
class="bg-white rounded-lg border border-gray-200 p-4"
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="text-sm font-medium text-gray-700">{{ s.from_address }}</span>
|
||||||
|
<span
|
||||||
|
class="text-xs rounded px-2 py-0.5 font-medium"
|
||||||
|
:class="classificationChipClass[s.classification]"
|
||||||
|
>
|
||||||
|
{{ classificationLabel[s.classification] }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button
|
||||||
|
class="text-sm bg-green-600 text-white px-3 py-1 rounded hover:bg-green-700 disabled:opacity-50"
|
||||||
|
:disabled="suggestionActioningId === s.id"
|
||||||
|
data-testid="accept-suggestion"
|
||||||
|
@click.stop="acceptSuggestion(s.id)"
|
||||||
|
>
|
||||||
|
Accept
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="text-sm bg-gray-200 text-gray-700 px-3 py-1 rounded hover:bg-gray-300 disabled:opacity-50"
|
||||||
|
:disabled="suggestionActioningId === s.id"
|
||||||
|
data-testid="dismiss-suggestion"
|
||||||
|
@click.stop="dismissSuggestion(s.id)"
|
||||||
|
>
|
||||||
|
Dismiss
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="font-medium text-sm mt-2">{{ s.subject }}</div>
|
||||||
|
<div class="text-sm text-gray-500 mt-1">{{ s.snippet }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<!-- Digest cards -->
|
<!-- Digest cards -->
|
||||||
<section>
|
<section>
|
||||||
<h2 class="font-semibold text-lg mb-3">Top Matches Today</h2>
|
<h2 class="font-semibold text-lg mb-3">Top Matches Today</h2>
|
||||||
|
|
@ -115,6 +269,18 @@ onMounted(loadToday)
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<!-- Notification mini-log -->
|
||||||
|
<section v-if="notifications.length > 0">
|
||||||
|
<h2 class="font-semibold text-lg mb-3">Recent Notifications</h2>
|
||||||
|
<ul class="text-sm space-y-1 bg-white rounded-lg border border-gray-200 p-3">
|
||||||
|
<li v-for="n in notifications" :key="n.id" class="border-b border-gray-100 py-1 last:border-0">
|
||||||
|
<span class="text-gray-400 text-xs">{{ n.created_at?.slice(0, 16).replace('T', ' ') }}</span>
|
||||||
|
<span class="ml-2 text-gray-700">{{ n.message }}</span>
|
||||||
|
<span class="ml-2 text-xs text-gray-400">({{ n.channel }})</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
<!-- Cost display -->
|
<!-- Cost display -->
|
||||||
<CostDisplay />
|
<CostDisplay />
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue