-
Notifications
You must be signed in to change notification settings - Fork 1
UI features #57
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
UI features #57
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
22c3ec8
Ensured initialize_database.py inline with migrate_database.py
pendingintent 9cfd517
updated by Claude Sonnet 4.5
pendingintent a5449c3
Added info about endpoints and imported data into app_endpoints table
pendingintent 3e9ea44
Added info about endpoints and imported data into app_endpoints table
pendingintent a947dba
Reordered matrix headers
pendingintent 4254be6
Removed in favor of CSV version
pendingintent 3c32ba8
Brought README files up-to-date
pendingintent 64c52ad
New tests for all router functions
pendingintent 7cf89a1
Documentation for router tests and review of legacy tests
pendingintent 6c15f72
Fixed deprecation warning by updating TemplateResponse to use request…
pendingintent 4059437
Matrix now shown for individual timeline selected by user
pendingintent da34a3f
Matrix XLSX report now includes additional BC info
pendingintent e39aa98
Update src/soa_builder/web/initialize_database.py
pendingintent 501b55c
Update src/soa_builder/web/templates/edit.html
pendingintent File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| # SoA Workbench - Copilot Instructions | ||
|
|
||
| ## Project Overview | ||
| Clinical trial Schedule of Activities (SoA) workbench: FastAPI web app + CLI tools for normalizing, expanding, and validating study visit matrices against USDM (Unified Study Definitions Model). | ||
|
|
||
| **Core Architecture:** | ||
| - **Web Layer** (`src/soa_builder/web/`): FastAPI app with router-based endpoints, HTMX UI, SQLite persistence | ||
| - **Core Logic** (`src/soa_builder/`): Normalization, schedule expansion, validation modules | ||
| - **USDM Generators** (`src/usdm/`): Transform database state → USDM JSON artifacts | ||
| - **Data Model**: SQLite schema with audit trails, versioning (freezes), and biomedical concept linking | ||
|
|
||
| **USDM Model Entities & Relationships** (critical for understanding the domain): | ||
| - **StudyDesign**: Top-level container with arrays of: encounters, activities, arms, epochs, elements, studyCells, scheduleTimelines | ||
| - **StudyElement** (`element` table): Structural design components (e.g., treatment periods, cohorts, crossover phases) | ||
| - UIDs: `StudyElement_N`; generated by `generate_elements.py` | ||
| - Purpose: Define "what study structure exists" (design-time components) | ||
| - Grouped via: **StudyCells** (arm + epoch + elementIds array) | ||
| - Attributes: transitionStartRule, transitionEndRule, studyInterventionIds | ||
| - **ScheduledActivityInstance** (`instances` table): Temporal visit/timepoint occurrences where activities happen | ||
| - UIDs: `ScheduledActivityInstance_N`; generated by `generate_scheduled_activity_instances.py` | ||
| - Purpose: Define "when/where activities occur" (schedule-specific) | ||
| - Relationships: references epochId, encounterId, activityIds[], timelineId | ||
| - Contained by: **ScheduleTimeline** (with mainTimeline flag, entryCondition, timings[], instances[]) | ||
| - **StudyCell** (`study_cell` table): Junction entity combining armId + epochId + elementIds[] | ||
| - Defines which study elements apply to which arm/epoch combinations | ||
| - UID pattern: `StudyCell_N` | ||
| - **ScheduleTimeline** (`schedule_timelines` table): Container for temporal scheduling | ||
| - Contains: instances[] (ScheduledActivityInstance or ScheduledDecisionInstance) | ||
| - Contains: timings[] (relative timing definitions), exits[] | ||
| - Attributes: mainTimeline (boolean), entryCondition, entryId | ||
| - **Encounter** (`visit` table via encounter_uid): Physical/virtual visit where activities occur | ||
| - Referenced by: ScheduledActivityInstance.encounterId | ||
| - Linked to: Activities via matrix_cells | ||
| - **Key Distinction**: Elements = structural design (periods, cohorts) | Instances = temporal schedule (visits, timepoints) | ||
|
|
||
| ## Critical Patterns | ||
|
|
||
| ### Database & Testing | ||
| - **Test isolation**: Tests run against `soa_builder_web_tests.db` (set via `SOA_BUILDER_DB` env). `tests/conftest.py` enforces isolation by removing WAL/SHM files pre-session | ||
| - **Connection pattern**: Always use `from .db import _connect` (handles pytest detection, WAL mode, busy timeouts) | ||
| - **Schema migrations**: Lifespan event in `app.py` runs migrations in sequence—add new ones to `migrate_database.py` | ||
|
|
||
| ### Router Architecture | ||
| Endpoints organized by domain in `src/soa_builder/web/routers/`: | ||
| - Each router (visits, activities, epochs, arms, elements, etc.) handles JSON API + HTMX UI variants | ||
| - Pattern: `@router.post("/soa/{soa_id}/visits")` for API, `@router.post("/ui/soa/{soa_id}/visits/create")` for forms | ||
| - Audit trail via `_record_{entity}_audit()` helpers in `audit.py` | ||
|
|
||
| ### HTMX UI Conventions | ||
| - Templates in `templates/` use `base.html` inheritance | ||
| - Form submissions return HTML partials for HTMX swaps | ||
| - Matrix edit interface (`edit.html`): drag-drop reordering, cell toggling with status rotation (blank → X → O → blank) | ||
| - Modal pattern: target `#modal-host` for freeze/rollback/audit overlays | ||
|
|
||
| ### External API Integration | ||
| **CDISC Library API** (biomedical concepts): | ||
| - Requires `CDISC_SUBSCRIPTION_KEY` or `CDISC_API_KEY` env vars | ||
| - Caching: `fetch_biomedical_concepts()` with TTL; force refresh via `POST /ui/soa/{id}/concepts_refresh` | ||
| - Override for tests: `CDISC_CONCEPTS_JSON` env (file path or inline JSON) | ||
| - Specializations: SDTM codelists via `fetch_sdtm_specializations()` | ||
|
|
||
| ### USDM Generation Pipeline | ||
| Scripts in `src/usdm/` convert SoA database → USDM JSON: | ||
| - `generate_activities.py`, `generate_arms.py`, `generate_study_epochs.py`, etc. | ||
| - Each reads from SQLite, constructs USDM objects with UIDs, references, and terminology codes | ||
| - Run via CLI: `python -m usdm.generate_activities --soa-id 1 --output-file output/activities.json` | ||
| - Relies on junction tables (e.g., `activity_concept`, `code_junction_timings`) for terminology linkage | ||
|
|
||
| ## Key Development Workflows | ||
|
|
||
| ### Starting the Web Server | ||
| ```bash | ||
| source .venv/bin/activate | ||
| soa-builder-web # or uvicorn soa_builder.web.app:app --reload --port 8000 | ||
| ``` | ||
| Access at `http://localhost:8000` | ||
|
|
||
| ### Running Tests | ||
| ```bash | ||
| pytest # uses soa_builder_web_tests.db | ||
| pytest tests/test_specific.py -v | ||
| ``` | ||
| **Important**: Test DB auto-cleans at session start. Manual cleanup if needed: | ||
| ```bash | ||
| rm -f soa_builder_web_tests.db* | ||
| ``` | ||
|
|
||
| ### Pre-commit Hooks | ||
| ```bash | ||
| pre-commit install | ||
| pre-commit run --all-files # runs black + pytest + flake8 | ||
| ``` | ||
|
|
||
| ### CLI Commands | ||
| ```bash | ||
| # Normalize wide CSV → relational tables | ||
| soa-builder normalize --input files/SoA.csv --out-dir normalized/ | ||
|
|
||
| # Expand repeating rules → calendar instances | ||
| soa-builder expand --normalized-dir normalized/ --start-date 2025-01-01 | ||
|
|
||
| # Validate imaging intervals | ||
| soa-builder validate --normalized-dir normalized/ | ||
| ``` | ||
|
|
||
| ## Code Conventions | ||
|
|
||
| ### UID Generation | ||
| - Auto-generated UIDs follow pattern: `{EntityName}_{incrementing_id}` | ||
| - Use `get_next_code_uid()` / `get_next_concept_uid()` from `utils.py` | ||
| - Once assigned, UIDs are immutable (e.g., `arm_uid`, `element_uid`) | ||
|
|
||
| ### Audit Pattern | ||
| All entity mutations log before/after state: | ||
| ```python | ||
| from .audit import _record_element_audit | ||
| _record_element_audit(soa_id, "update", element_id, before=old_state, after=new_state) | ||
| ``` | ||
|
|
||
| ### Reorder Operations | ||
| - Client sends `order: List[int]` (entity IDs in new sequence) | ||
| - Server recomputes `sequence_index` field for all items | ||
| - Audit logged with `entity_reorder_audit` table | ||
|
|
||
| ### Freeze & Rollback | ||
| - **Freeze**: Snapshot visits/activities/cells/epochs/arms to `{entity}_freeze` tables | ||
| - **Rollback**: Restore from freeze, track diffs in `rollback_audit` | ||
| - UI: Modal shows diff summary, confirms restore | ||
|
|
||
| ## Common Gotchas | ||
|
|
||
| 1. **Always activate venv first**: `source .venv/bin/activate` before any command | ||
| 2. **Test DB separation**: Don't run tests against prod DB—conftest enforces `SOA_BUILDER_DB` | ||
| 3. **HTMX partial responses**: UI endpoints must return HTML fragments, not full pages | ||
| 4. **SQLite WAL mode**: Production uses WAL; tests use DELETE for simpler cleanup | ||
| 5. **Concept API 401s in browser**: Direct API URLs fail (no auth headers)—use internal detail pages | ||
| 6. **Migration order matters**: New migrations go at end of lifespan event sequence | ||
| 7. **Pydantic schemas**: Use `schemas.py` models for request validation, not raw dicts | ||
| 8. **Router imports**: Import routers at top of `app.py`, mount with `app.include_router()` | ||
|
|
||
| ## Reference Files | ||
| - **API endpoints catalog**: `docs/api_endpoints.csv` (165 endpoints: method, path, type, description, response format) | ||
| - **Full API docs**: `README_endpoints.md` (curl examples, response schemas) | ||
| - **Main README**: Installation, server start, test setup | ||
| - **Database schema**: Infer from `initialize_database.py` + migrations in `migrate_database.py` | ||
| - **Test patterns**: See `tests/test_bulk_import.py` for matrix operations, `test_element_audit_endpoint.py` for audit trails | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The endpoint count (165) in the copilot instructions should match the count referenced in README_endpoints.md and the actual CSV file. Verify the accurate count and update consistently across all documentation files.