|
| 1 | +"""Programmatic attach-to-existing-facility entrypoint for sandbox callers. |
| 2 | +
|
| 3 | +Seeds pack content onto a facility that already exists (e.g. Experience sandbox |
| 4 | +shell). Does not create a second facility. Runs DemoSeedRunner.execute() |
| 5 | +synchronously — never enqueue_seed_run / .delay(). |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +from care_demo_facility_setup.models import SeedRun, SeedRunStatus, SeedRunStepStatus |
| 11 | +from care_demo_facility_setup.services.runner import DemoSeedRunner |
| 12 | +from care_demo_facility_setup.services.seed_errors import SeedRunExecutionError |
| 13 | +from care_demo_facility_setup.services.seed_packs import DEFAULT_PACK_SLUG |
| 14 | +from care_demo_facility_setup.services.seed_runs import create_attached_seed_run |
| 15 | + |
| 16 | +# Clearer panel keys than raw step keys (title-case still works either way). |
| 17 | +_SUMMARY_KEYS = { |
| 18 | + "inventory_items": "product_knowledges", |
| 19 | +} |
| 20 | + |
| 21 | +_STAT_LABELS = { |
| 22 | + "created": "created", |
| 23 | + "attached": "attached", |
| 24 | + "reused": "reused", |
| 25 | + "products_received": "received", |
| 26 | + "transferred": "transferred", |
| 27 | + "categories_created": "categories", |
| 28 | + "departments_created": "departments", |
| 29 | + "departments_reused": "departments reused", |
| 30 | + "locations_created": "locations", |
| 31 | + "healthcare_services_created": "services", |
| 32 | + "op_closed": "OP", |
| 33 | + "ip_in_progress": "IP", |
| 34 | + "emergency": "emergency", |
| 35 | + "beds_assigned": "beds", |
| 36 | +} |
| 37 | + |
| 38 | + |
| 39 | +def seed_existing_facility( |
| 40 | + *, |
| 41 | + facility_external_id: str, |
| 42 | + geo_organization_external_id: str, |
| 43 | + requested_by, |
| 44 | + pack_slug: str = DEFAULT_PACK_SLUG, |
| 45 | + profile_slug: str = "local", |
| 46 | +) -> SeedRun: |
| 47 | + """Attach pack seed data to an existing facility and execute synchronously. |
| 48 | +
|
| 49 | + Returns the SeedRun on SUCCEEDED. Raises SeedRunExecutionError (or the |
| 50 | + underlying step exception) on failure so the sandbox task can mark the job |
| 51 | + failed. |
| 52 | + """ |
| 53 | + if not requested_by or not getattr(requested_by, "is_superuser", False): |
| 54 | + raise SeedRunExecutionError("Seed run must be requested by a superuser.") |
| 55 | + |
| 56 | + run = create_attached_seed_run( |
| 57 | + facility_external_id=str(facility_external_id), |
| 58 | + geo_organization_external_id=str(geo_organization_external_id), |
| 59 | + requested_by=requested_by, |
| 60 | + pack_slug=pack_slug, |
| 61 | + profile_slug=profile_slug, |
| 62 | + ) |
| 63 | + DemoSeedRunner(run).execute() |
| 64 | + run.refresh_from_db() |
| 65 | + if run.status != SeedRunStatus.SUCCEEDED: |
| 66 | + raise SeedRunExecutionError(run.error or "Attached seed run did not succeed.") |
| 67 | + return run |
| 68 | + |
| 69 | + |
| 70 | +def _is_int(value) -> bool: |
| 71 | + return isinstance(value, int) and not isinstance(value, bool) |
| 72 | + |
| 73 | + |
| 74 | +def _join_parts(parts: list[str]) -> str | None: |
| 75 | + return " · ".join(parts) if parts else None |
| 76 | + |
| 77 | + |
| 78 | +def _format_stats_summary(key: str, stats) -> str | None: |
| 79 | + """Build a short labeled string from step stats when message is absent.""" |
| 80 | + if stats is True or stats is None or stats == {}: |
| 81 | + return None |
| 82 | + if isinstance(stats, bool): |
| 83 | + return None |
| 84 | + if _is_int(stats): |
| 85 | + return str(stats) |
| 86 | + if not isinstance(stats, dict): |
| 87 | + return None |
| 88 | + |
| 89 | + if key in {"inventory_items", "product_knowledges"}: |
| 90 | + created = stats.get("created") |
| 91 | + received = stats.get("products_received") |
| 92 | + transferred = stats.get("transferred") |
| 93 | + parts = [] |
| 94 | + if _is_int(created): |
| 95 | + parts.append(f"{created} product knowledges") |
| 96 | + if _is_int(received): |
| 97 | + parts.append(f"{received} received") |
| 98 | + if _is_int(transferred): |
| 99 | + parts.append(f"{transferred} transferred") |
| 100 | + if parts: |
| 101 | + return _join_parts(parts) |
| 102 | + |
| 103 | + if key == "clinical_visits": |
| 104 | + created = stats.get("created") |
| 105 | + if _is_int(created): |
| 106 | + breakdown = [] |
| 107 | + for stat_key, label in ( |
| 108 | + ("op_closed", "OP"), |
| 109 | + ("ip_in_progress", "IP"), |
| 110 | + ("emergency", "emergency"), |
| 111 | + ): |
| 112 | + value = stats.get(stat_key) |
| 113 | + if _is_int(value) and value: |
| 114 | + breakdown.append(f"{value} {label}") |
| 115 | + if breakdown: |
| 116 | + return f"{created} ({', '.join(breakdown)})" |
| 117 | + return str(created) |
| 118 | + |
| 119 | + if key == "facility": |
| 120 | + attached = stats.get("attached") |
| 121 | + created = stats.get("created") |
| 122 | + parts = [] |
| 123 | + if _is_int(attached) and attached: |
| 124 | + parts.append(f"{attached} attached") |
| 125 | + if _is_int(created) and created: |
| 126 | + parts.append(f"{created} created") |
| 127 | + if parts: |
| 128 | + return ", ".join(parts) |
| 129 | + if _is_int(attached): |
| 130 | + return "attached" if attached else "0 attached" |
| 131 | + if _is_int(created): |
| 132 | + return f"{created} created" |
| 133 | + |
| 134 | + if key == "facility_foundation": |
| 135 | + parts = [] |
| 136 | + for stat_key, label in ( |
| 137 | + ("departments_created", "departments"), |
| 138 | + ("departments_reused", "departments reused"), |
| 139 | + ("locations_created", "locations"), |
| 140 | + ("healthcare_services_created", "services"), |
| 141 | + ): |
| 142 | + value = stats.get(stat_key) |
| 143 | + if _is_int(value) and value: |
| 144 | + parts.append(f"{value} {label}") |
| 145 | + if parts: |
| 146 | + return _join_parts(parts) |
| 147 | + |
| 148 | + if key == "questionnaires": |
| 149 | + created = stats.get("created") |
| 150 | + reused = stats.get("reused") |
| 151 | + parts = [] |
| 152 | + if _is_int(created): |
| 153 | + parts.append(f"{created} created") |
| 154 | + if _is_int(reused): |
| 155 | + parts.append(f"{reused} reused") |
| 156 | + if parts: |
| 157 | + return ", ".join(parts) |
| 158 | + |
| 159 | + parts = [] |
| 160 | + for stat_key, value in stats.items(): |
| 161 | + if not _is_int(value): |
| 162 | + continue |
| 163 | + label = _STAT_LABELS.get(stat_key, stat_key.replace("_", " ")) |
| 164 | + parts.append(f"{value} {label}") |
| 165 | + return _join_parts(parts) |
| 166 | + |
| 167 | + |
| 168 | +def _step_summary(step) -> str | None: |
| 169 | + """Human-readable value for one succeeded seed step.""" |
| 170 | + message = getattr(step, "message", None) |
| 171 | + if isinstance(message, str) and message.strip(): |
| 172 | + return message.strip() |
| 173 | + return _format_stats_summary(step.key, getattr(step, "stats", None)) |
| 174 | + |
| 175 | + |
| 176 | +def summarize_seed_run(run: SeedRun) -> dict: |
| 177 | + """Map SeedRun steps into readable summaries for the Experience sandbox panel. |
| 178 | +
|
| 179 | + Values are short strings (or rarely plain ints) derived from each step's |
| 180 | + seeder ``message`` when present, otherwise from labeled ``stats``. Debug |
| 181 | + identifiers live under ``_meta`` (Experience skips ``_`` keys). Failed |
| 182 | + steps are omitted. |
| 183 | + """ |
| 184 | + loaded: dict = { |
| 185 | + "_meta": { |
| 186 | + "seed_run_id": str(run.external_id), |
| 187 | + "pack_slug": run.pack_slug, |
| 188 | + "profile_slug": run.profile_slug, |
| 189 | + }, |
| 190 | + } |
| 191 | + for step in run.steps.all().order_by("order"): |
| 192 | + if step.key == "validate": |
| 193 | + continue |
| 194 | + status = step.status.value if hasattr(step.status, "value") else step.status |
| 195 | + if status != SeedRunStepStatus.SUCCEEDED: |
| 196 | + continue |
| 197 | + summary = _step_summary(step) |
| 198 | + if summary is not None: |
| 199 | + loaded[_SUMMARY_KEYS.get(step.key, step.key)] = summary |
| 200 | + return loaded |
0 commit comments