"""WorkflowService — stage readiness for the Workflow home. Totals are DERIVED from the source tables (assets, duplicate_clusters, safety_reviews, analysis_results) rather than a separately-maintained counter, so the home page can never drift from reality. Each stage card carries a machine ``status`` plus human ``status_label`` and ``blocker`` text — the UI communicates state with text/icons as well as color (concept §Workflow home). ``active_job`` is the one-mutating-job indicator: when a job holds the ``library_write`` lock, mutating actions across the app are disabled with a reason, while read-only browsing stays available. """ from __future__ import annotations from sqlalchemy import func, select from sqlalchemy.orm import sessionmaker from photo_pipeline.jobs.domain_handlers import ANALYSIS, SAFETY_SCORE from photo_pipeline.models import Asset, DuplicateCluster, Job from photo_pipeline.services.analysis import AnalysisService from photo_pipeline.services.jobs import ACTIVE_STATES from photo_pipeline.services.safety import SafetyService # Job type that produced each stage's last run. STAGE_JOB_TYPE = {"inventory": "scan", "safety": SAFETY_SCORE, "analysis": ANALYSIS} class WorkflowService: def __init__(self, session_factory: sessionmaker) -> None: self._session_factory = session_factory def readiness(self) -> dict: with self._session_factory() as session: asset_total = session.scalar( select(func.count()).select_from(Asset).where(Asset.canonical_asset_id.is_(None)) ) missing = session.scalar( select(func.count()).select_from(Asset).where(Asset.missing_at.is_not(None)) ) cluster_states = dict( session.execute( select(DuplicateCluster.state, func.count()).group_by(DuplicateCluster.state) ).all() ) last_run = self._last_runs(session) active = self._active_job(session) safety = SafetyService(self._session_factory).counts() # Reuse the confirmed-SFW total just computed: resolving the current decision # of every asset is the expensive part of this page (US07-06). analysis = AnalysisService(self._session_factory).counts(eligible=safety[_SFW]) undecided_clusters = cluster_states.get("open", 0) + cluster_states.get("reopened", 0) stages = [ _card( "inventory", "Inventory", status="complete" if asset_total and not missing else ("attention" if missing else "ready"), counts={"assets": asset_total or 0, "missing": missing or 0}, blocker=f"{missing} missing file(s)" if missing else None, last_run=last_run.get("inventory"), action={"label": "Rescan", "job_type": "scan", "route": "#/inventory"}, ), _card( "duplicates", "Duplicates", status="attention" if undecided_clusters else "complete", counts={"undecided": undecided_clusters, "total": sum(cluster_states.values())}, blocker=f"{undecided_clusters} cluster(s) to review" if undecided_clusters else None, last_run=None, action={"label": "Review", "route": "#/duplicates"}, ), _card( "safety", "Safety", # Blocked while duplicates are unreviewed (dedup precedes safety). status=_safety_status(safety, undecided_clusters), counts=safety, blocker=( "resolve duplicate clusters first" if undecided_clusters else (f"{safety['undecided']} undecided" if safety["undecided"] else None) ), last_run=last_run.get("safety"), action={"label": "Review safety", "job_type": SAFETY_SCORE, "route": "#/safety"}, blocked_by="duplicates" if undecided_clusters else None, ), _card( "analysis", "Analysis", status=_analysis_status(analysis, safety), counts=analysis, blocker=( "no confirmed-SFW assets yet" if analysis["eligible"] == 0 else (f"{analysis['pending']} pending" if analysis["pending"] else None) ), last_run=last_run.get("analysis"), action={"label": "Analyze", "job_type": ANALYSIS, "route": "#/analyze"}, blocked_by="safety" if analysis["eligible"] == 0 else None, ), ] return {"active_job": active, "stages": stages} def _last_runs(self, session) -> dict[str, str | None]: out: dict[str, str | None] = {} for stage, job_type in STAGE_JOB_TYPE.items(): finished = session.scalar( select(func.max(Job.finished_at)).where(Job.job_type == job_type) ) out[stage] = finished.isoformat() if finished else None return out def _active_job(self, session) -> dict | None: job = session.scalars( select(Job).where(Job.state.in_(ACTIVE_STATES)).order_by(Job.created_at.desc()) ).first() if job is None: return None return {"id": job.id, "job_type": job.job_type, "state": job.state, "lock": job.lock_key} def _safety_status(safety: dict, undecided_clusters: int) -> str: if undecided_clusters: return "blocked" if safety["undecided"]: return "attention" if safety[_SFW] or safety[_NSFW]: return "complete" return "ready" def _analysis_status(analysis: dict, safety: dict) -> str: if analysis["eligible"] == 0: return "blocked" if analysis["pending"]: return "attention" return "complete" def _card(key, title, *, status, counts, blocker, last_run, action, blocked_by=None) -> dict: return { "key": key, "title": title, "status": status, "status_label": _STATUS_LABEL[status], "counts": counts, "blocker": blocker, "blocked_by": blocked_by, "last_run": last_run, "action": action, } _SFW = "sfw" _NSFW = "nsfw" _STATUS_LABEL = { "complete": "Complete", "ready": "Ready", "attention": "Needs review", "blocked": "Blocked", }