cbrapitools 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,223 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ *.lcov
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ # Pipfile.lock
97
+
98
+ # uv
99
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # uv.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ # poetry.lock
110
+ # poetry.toml
111
+
112
+ # pdm
113
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
115
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
116
+ # pdm.lock
117
+ # pdm.toml
118
+ .pdm-python
119
+ .pdm-build/
120
+
121
+ # pixi
122
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
123
+ # pixi.lock
124
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
125
+ # in the .venv directory. It is recommended not to include this directory in version control.
126
+ .pixi/*
127
+ !.pixi/config.toml
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule*
134
+ celerybeat.pid
135
+
136
+ # Redis
137
+ *.rdb
138
+ *.aof
139
+ *.pid
140
+
141
+ # RabbitMQ
142
+ mnesia/
143
+ rabbitmq/
144
+ rabbitmq-data/
145
+
146
+ # ActiveMQ
147
+ activemq-data/
148
+
149
+ # SageMath parsed files
150
+ *.sage.py
151
+
152
+ # Environments
153
+ .env
154
+ .envrc
155
+ .venv
156
+ env/
157
+ venv/
158
+ ENV/
159
+ env.bak/
160
+ venv.bak/
161
+
162
+ # Spyder project settings
163
+ .spyderproject
164
+ .spyproject
165
+
166
+ # Rope project settings
167
+ .ropeproject
168
+
169
+ # mkdocs/Zensical documentation
170
+ /site
171
+
172
+ # mypy
173
+ .mypy_cache/
174
+ .dmypy.json
175
+ dmypy.json
176
+
177
+ # Pyre type checker
178
+ .pyre/
179
+
180
+ # pytype static type analyzer
181
+ .pytype/
182
+
183
+ # Cython debug symbols
184
+ cython_debug/
185
+
186
+ # PyCharm
187
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
188
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
189
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
190
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
191
+ # .idea/
192
+
193
+ # Abstra
194
+ # Abstra is an AI-powered process automation framework.
195
+ # Ignore directories containing user credentials, local state, and settings.
196
+ # Learn more at https://abstra.io/docs
197
+ .abstra/
198
+
199
+ # Visual Studio Code
200
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
201
+ # can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
202
+ # and can be added to the global gitignore or merged into this file. However, if you prefer, you
203
+ # could uncomment the following to ignore the entire vscode folder
204
+ # .vscode/
205
+ # Temporary file for partial code execution
206
+ tempCodeRunnerFile.py
207
+
208
+ # Ruff stuff:
209
+ .ruff_cache/
210
+
211
+ # PyPI configuration file
212
+ .pypirc
213
+
214
+ # Marimo
215
+ marimo/_static/
216
+ marimo/_lsp/
217
+ __marimo__/
218
+
219
+ # Streamlit
220
+ .streamlit/secrets.toml
221
+
222
+ # Others
223
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Centre for Brain Research
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.5
2
+ Name: cbrapitools
3
+ Version: 0.1.0
4
+ Summary: Python API clients and auth helpers for CBR platforms (CMP, Keystone, Keycloak)
5
+ Author: CBR Data Team
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Operating System :: OS Independent
9
+ Classifier: Programming Language :: Python :: 3
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: pydantic<3,>=2
12
+ Requires-Dist: python-keycloak<8,>=7.1
13
+ Requires-Dist: requests>=2.31
14
+ Provides-Extra: dev
15
+ Requires-Dist: build>=1.2; extra == 'dev'
16
+ Requires-Dist: pytest>=8.0; extra == 'dev'
17
+ Requires-Dist: twine>=5.0; extra == 'dev'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # cbrapitools
21
+
22
+ Python API clients and auth helpers for CBR platforms: CMP, Keystone and Keycloak.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ pip install cbrapitools
28
+ ```
29
+
30
+ Requires Python 3.11 or newer.
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from cbrapitools.cmp import CmpApiClient
36
+ from cbrapitools.keystone import KeystoneApiClient
37
+ from cbrapitools.keycloak import KeycloakClientCredentialsAuth
38
+ ```
39
+
40
+ Base URLs and credentials are passed in by the caller (constructor arguments or
41
+ environment variables). Nothing environment-specific is hard-coded in the package.
42
+
43
+ ## Modules
44
+
45
+ | Module | Purpose |
46
+ |---|---|
47
+ | `http_client` | Shared HTTP layer used by the API clients |
48
+ | `keycloak` | Token acquisition and refresh against Keycloak |
49
+ | `cmp` | Client for the Cohort Management Portal API |
50
+ | `keystone` | Client for the Keystone API |
51
+
52
+ ## Development
53
+
54
+ ```bash
55
+ python -m venv .venv
56
+ source .venv/bin/activate
57
+ pip install -e ".[dev]"
58
+ pytest
59
+ ```
60
+
61
+ ## Releasing
62
+
63
+ 1. Bump `version` in `pyproject.toml` (PyPI never accepts the same version twice).
64
+ 2. Build and check:
65
+
66
+ ```bash
67
+ rm -rf dist
68
+ python -m build
69
+ twine check dist/*
70
+ ```
71
+
72
+ 3. Upload: `twine upload dist/*`
73
+ 4. Users upgrade with `pip install -U cbrapitools`.
@@ -0,0 +1,54 @@
1
+ # cbrapitools
2
+
3
+ Python API clients and auth helpers for CBR platforms: CMP, Keystone and Keycloak.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install cbrapitools
9
+ ```
10
+
11
+ Requires Python 3.11 or newer.
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ from cbrapitools.cmp import CmpApiClient
17
+ from cbrapitools.keystone import KeystoneApiClient
18
+ from cbrapitools.keycloak import KeycloakClientCredentialsAuth
19
+ ```
20
+
21
+ Base URLs and credentials are passed in by the caller (constructor arguments or
22
+ environment variables). Nothing environment-specific is hard-coded in the package.
23
+
24
+ ## Modules
25
+
26
+ | Module | Purpose |
27
+ |---|---|
28
+ | `http_client` | Shared HTTP layer used by the API clients |
29
+ | `keycloak` | Token acquisition and refresh against Keycloak |
30
+ | `cmp` | Client for the Cohort Management Portal API |
31
+ | `keystone` | Client for the Keystone API |
32
+
33
+ ## Development
34
+
35
+ ```bash
36
+ python -m venv .venv
37
+ source .venv/bin/activate
38
+ pip install -e ".[dev]"
39
+ pytest
40
+ ```
41
+
42
+ ## Releasing
43
+
44
+ 1. Bump `version` in `pyproject.toml` (PyPI never accepts the same version twice).
45
+ 2. Build and check:
46
+
47
+ ```bash
48
+ rm -rf dist
49
+ python -m build
50
+ twine check dist/*
51
+ ```
52
+
53
+ 3. Upload: `twine upload dist/*`
54
+ 4. Users upgrade with `pip install -U cbrapitools`.
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "cbrapitools"
7
+ version = "0.1.0"
8
+ description = "Python API clients and auth helpers for CBR platforms (CMP, Keystone, Keycloak)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "CBR Data Team" }]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ dependencies = [
19
+ "pydantic>=2,<3",
20
+ "python-keycloak>=7.1,<8",
21
+ "requests>=2.31",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "pytest>=8.0",
27
+ "build>=1.2",
28
+ "twine>=5.0",
29
+ ]
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/cbrapitools"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
@@ -0,0 +1,18 @@
1
+ """Python API clients and auth helpers for CBR platforms."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("cbrapitools")
7
+ except PackageNotFoundError: # running from source without installing
8
+ __version__ = "0.0.0"
9
+
10
+ # Optional: re-export the main classes so users can write
11
+ # from cbrapitools import CmpApiClient
12
+ #
13
+ # from .cmp import CmpApiClient
14
+ # from .keystone import KeystoneApiClient
15
+ # from .keycloak import KeycloakClientCredentialsAuth
16
+ # from .http_client import HttpClient
17
+ #
18
+ # __all__ = ["CmpApiClient", "KeystoneApiClient", "KeycloakClientCredentialsAuth", "HttpClient"]
@@ -0,0 +1,242 @@
1
+ from dataclasses import dataclass, field
2
+ from datetime import date, datetime
3
+ from enum import Enum
4
+ from pydantic import BaseModel, ConfigDict
5
+ from pydantic.alias_generators import to_camel
6
+ from typing import Self
7
+
8
+ from .keycloak import KeycloakClientCredentialsAuth
9
+ from .http_client import HttpClient
10
+ from .config import EnvConfig
11
+
12
+ # Constants
13
+ DEFAULT_PAGE_NUMBER = 1
14
+ DEFAULT_PAGE_SIZE = 10
15
+ TEST_PARTICIPANT_BARCODE_PREFIX = "TESTPERSON9"
16
+
17
+ class CmpModel(BaseModel):
18
+ """Base for CMP API models: camelCase JSON keys, immutable instances."""
19
+
20
+ model_config = ConfigDict(
21
+ alias_generator=to_camel,
22
+ populate_by_name=True,
23
+ serialize_by_alias=True,
24
+ frozen=True,
25
+ coerce_numbers_to_str=True,
26
+ )
27
+
28
+ class CmpListResponseMetaData(CmpModel):
29
+ page: int
30
+ limit: int
31
+ total: int
32
+ total_pages: int
33
+
34
+ class CmpOrganization(CmpModel):
35
+ id: int
36
+ name: str
37
+ description: str
38
+ website: str
39
+
40
+ class CmpFetchOrgsResponse(CmpModel):
41
+ data: list[CmpOrganization]
42
+ meta: CmpListResponseMetaData
43
+
44
+ class CmpCohort(CmpModel):
45
+ id: int
46
+ name: str
47
+ description: str
48
+
49
+ class CmpFetchCohortsResponse(CmpModel):
50
+ data: list[CmpCohort]
51
+ meta: CmpListResponseMetaData
52
+
53
+ class CmpParticipantGender(Enum):
54
+ MALE = "MALE"
55
+ FEMALE = "FEMALE"
56
+
57
+ class CmpParticipant(CmpModel):
58
+ id: int
59
+ cbr_barcode: str
60
+ cohort_barcode: str
61
+ age_at_visit: int
62
+ gender: CmpParticipantGender
63
+
64
+ # Enums and classes
65
+ class CmpAssessmentType(Enum):
66
+ AFT = "AFT"
67
+ AUD = "AUD"
68
+ BAL = "BAL"
69
+ BBC = "BBC"
70
+ CAD = "CAD"
71
+ CLN = "CLN"
72
+ COG = "COG"
73
+ DIG = "DIG"
74
+ ECG = "ECG"
75
+ FND = "FND"
76
+ GAI = "GAI"
77
+ MRI = "MRI"
78
+ NRS = "NRS"
79
+ OCT = "OCT"
80
+ RFM = "RFM"
81
+ SCD = "SCD"
82
+ SPR = "SPR"
83
+
84
+ class CmpVisitDetailStatus(Enum):
85
+ CONFIRMED = "CONFIRMED"
86
+ COMPLETED = "COMPLETED"
87
+ CANCELLED = "CANCELLED"
88
+
89
+ class CmpVisitDetail(CmpModel):
90
+ id:int
91
+ visit_type: str
92
+ assessment_type: CmpAssessmentType
93
+ participant: CmpParticipant
94
+ site_id: int
95
+ start_ts: datetime
96
+ end_ts: datetime
97
+ slot: str | None = None
98
+ facilitator_email: str | None = None
99
+ status: CmpVisitDetailStatus
100
+
101
+ class CmpFetchVisitDetailsResponse(CmpModel):
102
+ data: list[CmpVisitDetail]
103
+ meta: CmpListResponseMetaData
104
+
105
+ class CmpVisitUpdatePayload(CmpModel):
106
+ site_id: int
107
+ assessment_type: CmpAssessmentType
108
+ start_ts: datetime
109
+ status: CmpVisitDetailStatus
110
+ end_ts: datetime | None = None
111
+ slot: str | None = None
112
+ facilitator_email: str | None = None
113
+
114
+ @classmethod
115
+ def from_visit_detail(cls, vd: CmpVisitDetail) -> Self:
116
+ """Build an update carrying over the current values of an existing appointment."""
117
+ return cls(
118
+ site_id=vd.site_id,
119
+ assessment_type=vd.assessment_type,
120
+ status=vd.status,
121
+ start_ts=vd.start_ts,
122
+ end_ts=vd.end_ts,
123
+ slot=vd.slot,
124
+ facilitator_email=vd.facilitator_email,
125
+ )
126
+
127
+ @dataclass(frozen=True)
128
+ class CmpApiClientConfig(EnvConfig):
129
+ keycloak_base_url: str
130
+ cmp_api_base_url: str
131
+ cmp_api_client_id: str
132
+ cmp_api_client_secret: str = field(repr=False)
133
+
134
+ class CmpApiClient:
135
+ """Reads and updates appointments through the CMP appointments API."""
136
+
137
+ DEFAULT_CLIENT_SCOPES: tuple[str, ...] = ("cmp:core:read", "cmp:appointments:read", "cmp:appointments:write")
138
+
139
+ def __init__(
140
+ self,
141
+ config: CmpApiClientConfig | None = None,
142
+ scopes: tuple[str, ...] = DEFAULT_CLIENT_SCOPES,
143
+ verify_ssl: bool = True
144
+ ) -> None:
145
+ config = config or CmpApiClientConfig.default()
146
+ auth = KeycloakClientCredentialsAuth(
147
+ keycloak_base_url=config.keycloak_base_url,
148
+ client_id=config.cmp_api_client_id,
149
+ client_secret=config.cmp_api_client_secret,
150
+ scopes=scopes,
151
+ )
152
+ self._http_client = HttpClient(auth, verify_ssl=verify_ssl)
153
+ self._cmp_base_url = config.cmp_api_base_url
154
+
155
+ def _appointment_url(self, cohort_id: int, visitdetail_id: int) -> str:
156
+ return f"{self._cmp_base_url}/api/appointments/v1/cohorts/{cohort_id}/{visitdetail_id}"
157
+
158
+ def _set_status(self, cohort_id: int, visitdetail_id: int, status: CmpVisitDetailStatus) -> None:
159
+ self._http_client.put_json(
160
+ url=f"{self._appointment_url(cohort_id, visitdetail_id)}/status",
161
+ json={"status": status.value},
162
+ )
163
+
164
+ def _complete_by_id(self, cohort_id: int, visitdetail_id: int) -> None:
165
+ """Mark an appointment as completed."""
166
+ self._set_status(cohort_id, visitdetail_id, CmpVisitDetailStatus.COMPLETED)
167
+
168
+ def _complete_by_bva(self, cohort_id: int, participant_cohort_barcode: str, visit_type: str, assessment_type: CmpAssessmentType) -> None:
169
+ """Mark an appointment identified using BVA as completed."""
170
+ self._http_client.put_json(
171
+ url=f"{self._cmp_base_url}/api/appointments/v1/cohorts/{cohort_id}/bva/{participant_cohort_barcode}/{visit_type}/{assessment_type.value}/status",
172
+ json={"status": CmpVisitDetailStatus.COMPLETED.value},
173
+ )
174
+
175
+ def fetch_organizations(self) -> CmpFetchOrgsResponse:
176
+ response = self._http_client.get_json(
177
+ dict,
178
+ url = f"{self._cmp_base_url}/api/core/v1/organizations"
179
+ )
180
+ return CmpFetchOrgsResponse.model_validate(response)
181
+
182
+ def fetch_cohorts(self, org_id: int) -> CmpFetchCohortsResponse:
183
+ response = self._http_client.get_json(
184
+ dict,
185
+ url = f"{self._cmp_base_url}/api/core/v1/organizations/{org_id}/cohorts"
186
+ )
187
+ return CmpFetchCohortsResponse.model_validate(response)
188
+
189
+ def fetch_visitdetails(
190
+ self,
191
+ cohort_id: int,
192
+ assessment_types: list[CmpAssessmentType] | None = None,
193
+ status: CmpVisitDetailStatus | None = None,
194
+ from_date: date | None = None,
195
+ to_date: date | None = None,
196
+ page: int = DEFAULT_PAGE_NUMBER,
197
+ page_size: int = DEFAULT_PAGE_SIZE,
198
+ sort_by: str | None = None,
199
+ ) -> CmpFetchVisitDetailsResponse:
200
+ filter_params = {
201
+ "assessmentType": [a.value for a in assessment_types] if assessment_types else None,
202
+ "status": status.value if status else None,
203
+ "fromDate": from_date.isoformat() if from_date else None,
204
+ "toDate": to_date.isoformat() if to_date else None,
205
+ "page": page,
206
+ "limit": page_size,
207
+ "sort_by": sort_by
208
+ }
209
+ filter_params = {key: value for key, value in filter_params.items() if value is not None}
210
+ response = self._http_client.get_json(
211
+ expected=dict,
212
+ url=f"{self._cmp_base_url}/api/appointments/v1/cohorts/{cohort_id}",
213
+ params=filter_params,
214
+ )
215
+ return CmpFetchVisitDetailsResponse.model_validate(response)
216
+
217
+ def fetch_visitdetail(self, cohort_id: int, visit_detail_id: int) -> CmpVisitDetail:
218
+ """Fetch an appointment; raises ValueError if CMP returns no data for it."""
219
+ response = self._http_client.get_json(
220
+ dict,
221
+ self._appointment_url(cohort_id, visit_detail_id),
222
+ )
223
+ return CmpVisitDetail.model_validate(response["data"])
224
+
225
+ def put_visitdetail(self, cohort_id: int, vd_id: int, vd_updates: CmpVisitUpdatePayload):
226
+ self._http_client.put_json(
227
+ url=self._appointment_url(cohort_id, vd_id),
228
+ json=vd_updates.model_dump(mode = "json"),
229
+ )
230
+
231
+ def complete_visitdetail(self, cohort_id: int, vd: CmpVisitDetail | int) -> None:
232
+ if isinstance(vd, CmpVisitDetail):
233
+ self._complete_by_bva(cohort_id,
234
+ vd.participant.cohort_barcode,
235
+ vd.visit_type,
236
+ vd.assessment_type)
237
+ else:
238
+ self._complete_by_id(cohort_id, vd)
239
+
240
+ def cancel_visitdetail(self, cohort_id: int, vd_id: int) -> None:
241
+ """Mark an appointment as cancelled."""
242
+ self._set_status(cohort_id, vd_id, CmpVisitDetailStatus.CANCELLED)
@@ -0,0 +1,29 @@
1
+ import os
2
+ from dataclasses import fields
3
+ from functools import cache
4
+ from typing import Any, ClassVar, Self
5
+
6
+ class EnvConfig:
7
+ """Base for config dataclasses loaded from environment variables.
8
+
9
+ Each field reads the environment variable of the same name in upper case,
10
+ for example `cmp_api_base_url` reads `CMP_API_BASE_URL`.
11
+ """
12
+
13
+ __dataclass_fields__: ClassVar[dict[str, Any]]
14
+
15
+ @classmethod
16
+ def from_env(cls) -> Self:
17
+ env_config_values = {f.name: os.environ.get(f.name.upper(), "").strip() for f in fields(cls)}
18
+ missing = [name.upper() for name, value in env_config_values.items() if not value]
19
+ if missing:
20
+ raise RuntimeError(
21
+ f"{cls.__name__}: required configurations ({', '.join(missing)}) missing in environment! Can't proceed."
22
+ )
23
+ return cls(**env_config_values)
24
+
25
+ @classmethod
26
+ @cache
27
+ def default(cls) -> Self:
28
+ """The config built from the environment, read once and reused."""
29
+ return cls.from_env()
@@ -0,0 +1,68 @@
1
+ from typing import Any, TypeVar
2
+
3
+ import requests
4
+ from requests.auth import AuthBase
5
+
6
+ DEFAULT_REQUEST_TIMEOUT_SECONDS = 60
7
+ T = TypeVar("T")
8
+
9
+ def make_session(
10
+ auth: AuthBase | None = None,
11
+ verify_ssl: bool = True,
12
+ ) -> requests.Session:
13
+ session = requests.Session()
14
+ session.auth = auth
15
+ session.headers.update({"Accept": "application/json"})
16
+ session.verify = verify_ssl
17
+ return session
18
+
19
+
20
+ class HttpClient:
21
+ """A small HTTP client for requests that return JSON responses."""
22
+
23
+ def __init__(
24
+ self,
25
+ auth: AuthBase | None = None,
26
+ verify_ssl: bool = True,
27
+ timeout_seconds: int = DEFAULT_REQUEST_TIMEOUT_SECONDS,
28
+ ) -> None:
29
+ self._session = make_session(auth, verify_ssl)
30
+ self._timeout_seconds = timeout_seconds
31
+
32
+ def get_json(
33
+ self,
34
+ expected: type[T],
35
+ url: str,
36
+ params: dict[str, Any] | None = None,
37
+ ) -> T:
38
+ response = self._session.get(
39
+ url,
40
+ params=params,
41
+ timeout=self._timeout_seconds,
42
+ )
43
+ response.raise_for_status()
44
+ data = response.json()
45
+ if not isinstance(data, expected):
46
+ raise ValueError(f"Expected {expected} from {url}, got {type(data)}")
47
+ return data
48
+
49
+ def put_json(
50
+ self,
51
+ url: str,
52
+ json: dict[str, Any] | None = None,
53
+ expected: type[T] | None = None,
54
+ timeout: int | None = None,
55
+ ) -> T | None:
56
+ """PUT a JSON body; returns the parsed response, or None if the response has no body."""
57
+ response = self._session.put(
58
+ url,
59
+ json=json,
60
+ timeout=timeout or self._timeout_seconds,
61
+ )
62
+ response.raise_for_status()
63
+ if response.status_code == 204 or not response.content:
64
+ return None
65
+ data = response.json()
66
+ if expected is not None and not isinstance(data, expected):
67
+ raise ValueError(f"Expected {expected} from {url}, got {type(data)}")
68
+ return data
@@ -0,0 +1,56 @@
1
+ import time
2
+
3
+ import requests
4
+ from keycloak import KeycloakOpenID
5
+ from keycloak.exceptions import KeycloakError
6
+ from requests.auth import AuthBase
7
+
8
+
9
+ KEYCLOAK_REALM = "cmp"
10
+ DEFAULT_REQUEST_TIMEOUT_SECONDS = 60
11
+ DEFAULT_REFRESH_MARGIN_SECONDS = 60
12
+
13
+
14
+ class KeycloakClientCredentialsAuth(AuthBase):
15
+ """Attach a client-credentials token to each request."""
16
+
17
+ def __init__(
18
+ self,
19
+ keycloak_base_url: str,
20
+ client_id: str,
21
+ client_secret: str,
22
+ scopes: tuple[str, ...],
23
+ refresh_margin_seconds: int = DEFAULT_REFRESH_MARGIN_SECONDS,
24
+ ) -> None:
25
+ self._keycloak = KeycloakOpenID(
26
+ server_url=keycloak_base_url,
27
+ realm_name=KEYCLOAK_REALM,
28
+ client_id=client_id,
29
+ client_secret_key=client_secret,
30
+ timeout=DEFAULT_REQUEST_TIMEOUT_SECONDS,
31
+ )
32
+ self._scope = " ".join(scopes)
33
+ self._refresh_margin_seconds = refresh_margin_seconds
34
+ self._token = ""
35
+ self._expires_at = 0.0
36
+ self.refresh()
37
+
38
+ def refresh(self) -> None:
39
+ """Fetch a new token; raises RuntimeError if Keycloak refuses."""
40
+ try:
41
+ payload = self._keycloak.token(
42
+ grant_type="client_credentials",
43
+ scope=self._scope,
44
+ )
45
+ except KeycloakError as exc:
46
+ raise RuntimeError(
47
+ f"Token request failed for client '{self._keycloak.client_id}': {exc}"
48
+ ) from exc
49
+ self._token = payload["access_token"]
50
+ self._expires_at = time.monotonic() + payload["expires_in"]
51
+
52
+ def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest:
53
+ if time.monotonic() >= self._expires_at - self._refresh_margin_seconds:
54
+ self.refresh()
55
+ request.headers["Authorization"] = f"Bearer {self._token}"
56
+ return request
@@ -0,0 +1,109 @@
1
+ from dataclasses import dataclass, field
2
+ from datetime import date, datetime
3
+ from enum import Enum
4
+ from pydantic import BaseModel, ConfigDict
5
+
6
+ from .keycloak import KeycloakClientCredentialsAuth
7
+ from .http_client import HttpClient
8
+ from .config import EnvConfig
9
+
10
+ DEFAULT_VISITS_EXPORT_API_PAGE_SIZE = 5
11
+
12
+ class KeystoneModel(BaseModel):
13
+ """Base for Keystone API models: snake_case JSON keys, immutable instances."""
14
+
15
+ model_config = ConfigDict(frozen=True, coerce_numbers_to_str=True)
16
+
17
+ class KeystoneOrganization(KeystoneModel):
18
+ id: int
19
+ name: str
20
+
21
+ class KeystoneCohort(KeystoneModel):
22
+ id: int
23
+ name: str
24
+ organization_id: int
25
+
26
+ class KeystoneVisitStatus(Enum):
27
+ COMPLETED = "COMPLETED"
28
+
29
+ class KeystoneParticipant(KeystoneModel):
30
+ cohort_barcode: str
31
+
32
+ class KeystoneOperator(KeystoneModel):
33
+ oid: str
34
+ preferred_username: str
35
+
36
+ class KeystoneVisitSummary(KeystoneModel):
37
+ visit_id: str
38
+ completed_at: datetime
39
+ cohort_id: int
40
+ site_id: int
41
+ visit_name: str
42
+ participant: KeystoneParticipant
43
+ operator: KeystoneOperator
44
+ appointment_ids: list[int]
45
+
46
+ @dataclass(frozen=True)
47
+ class KeystoneApiClientConfig(EnvConfig):
48
+ keycloak_base_url: str
49
+ keystone_api_base_url: str
50
+ keystone_api_client_id: str
51
+ keystone_api_client_secret: str = field(repr=False)
52
+
53
+ class KeystoneApiClient:
54
+ """Reads Keystone data through the Keystone API."""
55
+
56
+ DEFAULT_CLIENT_SCOPES: tuple[str, ...] = ("das:audit:read", "das:export:read", "das:schedule:read")
57
+
58
+ def __init__(
59
+ self,
60
+ config: KeystoneApiClientConfig | None = None,
61
+ scopes: tuple[str, ...] = DEFAULT_CLIENT_SCOPES,
62
+ verify_ssl: bool = True
63
+ ) -> None:
64
+ config = config or KeystoneApiClientConfig.default()
65
+ auth = KeycloakClientCredentialsAuth(
66
+ keycloak_base_url=config.keycloak_base_url,
67
+ client_id=config.keystone_api_client_id,
68
+ client_secret=config.keystone_api_client_secret,
69
+ scopes=scopes,
70
+ )
71
+ self._http_client = HttpClient(auth, verify_ssl=verify_ssl)
72
+ self._ks_base_url = config.keystone_api_base_url
73
+
74
+ def fetch_orgs(self) -> list[KeystoneOrganization]:
75
+ response = self._http_client.get_json(list, f"{self._ks_base_url}/v1/orgs")
76
+ return [KeystoneOrganization.model_validate(item) for item in response]
77
+
78
+ def fetch_cohorts(self, org_id: int) -> list[KeystoneCohort]:
79
+ response = self._http_client.get_json(
80
+ list,
81
+ f"{self._ks_base_url}/v1/cohorts",
82
+ {"org_id": org_id},
83
+ )
84
+ return [KeystoneCohort.model_validate(item) for item in response]
85
+
86
+ def fetch_visits(
87
+ self,
88
+ cohort_id: int,
89
+ status: KeystoneVisitStatus,
90
+ from_date: date,
91
+ to_date: date,
92
+ page: int,
93
+ page_size: int = DEFAULT_VISITS_EXPORT_API_PAGE_SIZE,
94
+ ) -> tuple[list[KeystoneVisitSummary], int]:
95
+ response = self._http_client.get_json(
96
+ dict,
97
+ f"{self._ks_base_url}/v1/export/visits",
98
+ {
99
+ "cohort_id": cohort_id,
100
+ "from": from_date.isoformat(),
101
+ "to": to_date.isoformat(),
102
+ "status": status.value,
103
+ "page": page,
104
+ "page_size": page_size,
105
+ },
106
+ )
107
+ page_visits = [KeystoneVisitSummary.model_validate(item) for item in response.get("items") or []]
108
+ total = response.get("total") or 0
109
+ return page_visits, total
@@ -0,0 +1,18 @@
1
+ """Smoke test: every module imports cleanly from the installed package."""
2
+
3
+ import importlib
4
+
5
+ import pytest
6
+
7
+ MODULES = [
8
+ "cbrapitools",
9
+ "cbrapitools.http_client",
10
+ "cbrapitools.keycloak",
11
+ "cbrapitools.cmp",
12
+ "cbrapitools.keystone",
13
+ ]
14
+
15
+
16
+ @pytest.mark.parametrize("name", MODULES)
17
+ def test_module_imports(name):
18
+ importlib.import_module(name)