about summary refs log tree commit diff
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi <fredmanglis@gmail.com>2026-11-12 20:02:56 +0000
committerFrederick Muriuki Muriithi <fredmanglis@gmail.com>2026-11-12 14:28:38 -0600
commitbffbd4d09948f5a5f0ad2f72bf5f39bcd1509f91 (patch)
treeada7931e099320ec1e31b0375b3580d4492f8aea
parentfd063534a9c26f3b34184e88cfeca1ad6fe10c7e (diff)
downloadgn-uploader-bffbd4d09948f5a5f0ad2f72bf5f39bcd1509f91.tar.gz
Add the Stage 03 sample-order review and hand-off
Carry the file's sample list in the QC job metadata, redirect the QC success
handler to a sample-order review page, and validate the submitted order as a
permutation of the file's samples. On acceptance, launch the next-stage job
(type genotype-stage04) with the accepted order and the preceding stage state in
its metadata; re-submitting reuses an existing Stage 04 job.

Add a minimal Stage 04 placeholder worker for the hand-off point.

Co-authored-by: pi coding agent <pi@pi.dev>
-rw-r--r--uploader/genotypes/views.py148
-rw-r--r--uploader/scripts/genotypes/stage04.py13
2 files changed, 158 insertions, 3 deletions
diff --git a/uploader/genotypes/views.py b/uploader/genotypes/views.py
index 14d1bfc..1766e8f 100644
--- a/uploader/genotypes/views.py
+++ b/uploader/genotypes/views.py
@@ -40,6 +40,7 @@ from r_qtl.utils import parse_missing_values_symbols
 from . import collector_config
 from . import collector_job
 from . import job_errors
+from . import ordering
 from .models import (genotype_markers,
                      genotype_records,
                      genotype_dataset,
@@ -63,14 +64,40 @@ def collect_genotype_stats_success_handler(job):
 
 
 def genotype_qc_success_handler(job):
-    """Placeholder QC success handler: dump the job details.
+    """Proceed to the sample-order review step."""
+    return redirect(url_for(
+        "species.populations.genotypes.sample_order",
+        species_id=job["metadata"]["species_id"],
+        population_id=job["metadata"]["population_id"],
+        dataset_id=job["metadata"]["dataset_id"],
+        job_id=job["job_id"]))
+
 
-    TODO: proceed to the next stage once it exists.
-    """
+def genotype_stage04_success_handler(job):
+    """Placeholder Stage 04 success handler: dump the job details."""
     return redirect(url_for(
         "background-jobs.job_summary", job_id=job["job_id"]))
 
 
+def _fetch_qc_job(conn, job_id, species_id, population_id, dataset_id):
+    """Fetch and validate a completed genotype QC job."""
+    try:
+        job = gnlibs_jobs.job(conn, job_id, fulldetails=True)
+    except JobNotFound:
+        return None
+    metadata = job.get("metadata", {})
+    if metadata.get("job-type") != "genotype-file-qc":
+        return None
+    if metadata.get("status") != "completed":
+        return None
+    for key, expected in (("species_id", species_id),
+                          ("population_id", population_id),
+                          ("dataset_id", dataset_id)):
+        if str(metadata.get(key)) != str(expected):
+            return None
+    return job
+
+
 def _render_job_errors(job):
     """Render the structured errors recorded by a genotype job."""
     errors = job_errors.errors_from_job(job)
@@ -169,6 +196,8 @@ def study_design(# pylint: disable=[unused-argument,too-many-locals]
                     "genotype-file-qc",
                     **{
                         "stage02": json.dumps(_saved),
+                        "samples": json.dumps(
+                            tuple(stats.get("samples_list") or tuple())),
                         "genotype_collector_job_id": str(job_id),
                         "file": _file,
                         "config": _config,
@@ -399,6 +428,119 @@ def create_dataset(species: dict, population: dict, **kwargs):# pylint: disable=
 
 @genotypesbp.route(
     "/<int:species_id>/populations/<int:population_id>/genotypes/datasets/"
+    "<int:dataset_id>/sample-order/<uuid:job_id>",
+    methods=["GET", "POST"])
+@require_login
+@with_population(species_redirect_uri="species.list_species",
+                 redirect_uri="species.populations.list_species_populations")
+@with_dataset(species_redirect_uri="species.list_species",
+              population_redirect_uri="species.populations.list_species_populations",
+              redirect_uri="species.populations.genotypes.index",
+              dataset_by_id=genotype_dataset)
+def sample_order(# pylint: disable=[unused-argument,too-many-locals]
+        species: dict,
+        population: dict,
+        dataset: dict,
+        job_id: uuid.UUID,
+        **kwargs
+):
+    """Review and confirm the order of samples from the uploaded file."""
+    def __dataset_uri_():
+        return url_for(
+            "species.populations.genotypes.view_dataset",
+            species_id=species["SpeciesId"],
+            population_id=population["Id"],
+            dataset_id=dataset["Id"])
+
+    _jobs_db = app.config["ASYNCHRONOUS_JOBS_SQLITE_DB"]
+    with sqlite3.connection(_jobs_db) as conn:
+        job = _fetch_qc_job(
+            conn, job_id, species["SpeciesId"], population["Id"],
+            dataset["Id"])
+        if job is None:
+            flash("Could not find a completed QC job for this upload.",
+                  "alert-danger")
+            return redirect(__dataset_uri__())
+        metadata = job["metadata"]
+        try:
+            samples = tuple(json.loads(metadata.get("samples") or "[]"))
+        except ValueError:
+            samples = tuple()
+        if not samples:
+            flash("The QC job did not record any samples to order.",
+                  "alert-danger")
+            return redirect(__dataset_uri__())
+
+        with database_connection(app.config["SQL_URI"]) as dbconn:
+            existing_order = ordering.population_sample_order(
+                dbconn, population["Id"])
+        proposed = ordering.proposed_order(samples, existing_order)
+
+        if request.method == "POST":
+            submitted = tuple(
+                line.strip() for line in
+                request.form.get("sample_order", "").splitlines()
+                if line.strip())
+            if not ordering.is_valid_order(submitted, samples):
+                flash("The submitted order must contain each sample exactly "
+                      "once.", "alert-danger")
+                proposed = submitted or proposed
+            else:
+                _collector_id = metadata.get(
+                    "genotype_collector_job_id", "")
+                _existing = (
+                    gnlibs_jobs.jobs_by_metadata(
+                        conn, {"genotype_collector_job_id": _collector_id,
+                               "job-type": "genotype-stage04"})
+                    if _collector_id else tuple())
+                if _existing:
+                    return redirect(url_for(
+                        "background-jobs.job_status",
+                        job_id=_existing[0]["job_id"]))
+                _stage04_id = uuid.uuid4()
+                _stage04 = gnlibs_jobs.launch_job(
+                    gnlibs_jobs.initialise_job(
+                        conn,
+                        _stage04_id,
+                        [sys.executable, "-m",
+                         "uploader.scripts.genotypes.stage04"],
+                        "genotype-stage04",
+                        **{
+                            "stage02": metadata.get("stage02", "{}"),
+                            "sample_order": json.dumps(submitted),
+                            "genotype_collector_job_id": _collector_id,
+                            "file": metadata.get("file", ""),
+                            "config": metadata.get("config", "{}"),
+                            "job_name": (
+                                "Genotype Stage 04: "
+                                f"{Path(metadata.get('file', '')).name}"),
+                            "species_id": species["SpeciesId"],
+                            "population_id": population["Id"],
+                            "dataset_id": dataset["Id"],
+                            "success_handler": (
+                                "uploader.genotypes.views."
+                                "genotype_stage04_success_handler")
+                        },
+                        external_id=session.logged_in_user_id()),
+                    _jobs_db,
+                    Path(f"{uploads_dir(app)}/job_errors").absolute(),
+                    loglevel=logging.getLevelName(
+                        app.logger.getEffectiveLevel()).lower())
+                return redirect(url_for(
+                    "background-jobs.job_status",
+                    job_id=_stage04["job_id"]))
+
+    return render_template(
+        "genotypes/sample-order.html",
+        species=species,
+        population=population,
+        dataset=dataset,
+        job_id=job_id,
+        samples=proposed)
+
+
+@genotypesbp.route(
+    "/<int:species_id>/populations/<int:population_id>/genotypes/datasets/"
     "<int:dataset_id>/add-records",
     methods=["GET", "POST"])
 @require_login
diff --git a/uploader/scripts/genotypes/stage04.py b/uploader/scripts/genotypes/stage04.py
new file mode 100644
index 0000000..f6e67d9
--- /dev/null
+++ b/uploader/scripts/genotypes/stage04.py
@@ -0,0 +1,13 @@
+"""Placeholder for Stage 04 (R/qtl2 bundle conversion)."""
+import sys
+import json
+
+
+def main():
+    """Placeholder entry point."""
+    print(json.dumps({"status": "stage04-not-implemented"}))
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())