doseframe 0.2.0__py3-none-any.whl
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.
- doseframe/__init__.py +252 -0
- doseframe/calculation/__init__.py +34 -0
- doseframe/calculation/derivation.py +30 -0
- doseframe/calculation/errors.py +16 -0
- doseframe/calculation/infusion.py +27 -0
- doseframe/calculation/relation.py +129 -0
- doseframe/calculation/single_dose.py +54 -0
- doseframe/calculation/steps.py +20 -0
- doseframe/calculation/strategies.py +105 -0
- doseframe/calculation/strategy.py +37 -0
- doseframe/checks/__init__.py +20 -0
- doseframe/checks/chain.py +212 -0
- doseframe/checks/context.py +43 -0
- doseframe/findings/__init__.py +58 -0
- doseframe/protocols/__init__.py +103 -0
- doseframe/protocols/activation.py +51 -0
- doseframe/protocols/device.py +51 -0
- doseframe/protocols/diff.py +70 -0
- doseframe/protocols/errors.py +26 -0
- doseframe/protocols/limits.py +74 -0
- doseframe/protocols/model.py +40 -0
- doseframe/protocols/naming.py +126 -0
- doseframe/protocols/reference.py +163 -0
- doseframe/protocols/schemes.py +598 -0
- doseframe/protocols/single_dose.py +253 -0
- doseframe/protocols/version.py +690 -0
- doseframe/py.typed +0 -0
- doseframe/rounding/__init__.py +23 -0
- doseframe/rounding/policy.py +108 -0
- doseframe/units/__init__.py +49 -0
- doseframe/units/catalog.py +155 -0
- doseframe/units/decimal_context.py +17 -0
- doseframe/units/errors.py +27 -0
- doseframe/units/options.py +52 -0
- doseframe/units/quantity.py +144 -0
- doseframe/units/unit.py +137 -0
- doseframe/use_cases/__init__.py +73 -0
- doseframe/use_cases/clinical.py +735 -0
- doseframe/use_cases/gate.py +85 -0
- doseframe/use_cases/governance.py +460 -0
- doseframe/use_cases/ports.py +73 -0
- doseframe/use_cases/results.py +182 -0
- doseframe-0.2.0.dist-info/METADATA +79 -0
- doseframe-0.2.0.dist-info/RECORD +46 -0
- doseframe-0.2.0.dist-info/WHEEL +4 -0
- doseframe-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""The availability gate: no usable, approved version, no numbers (frozen spot)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
|
|
7
|
+
from doseframe.protocols import EventKind, ProtocolVersion, StateName, Workflow, activate_due
|
|
8
|
+
from doseframe.units import DoseframeError
|
|
9
|
+
from doseframe.use_cases.ports import (
|
|
10
|
+
Clock,
|
|
11
|
+
NotFoundError,
|
|
12
|
+
ProtocolRepository,
|
|
13
|
+
RepositoryUnavailableError,
|
|
14
|
+
)
|
|
15
|
+
from doseframe.use_cases.results import Unavailable, UnusableReason
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class VersionUnusableError(DoseframeError):
|
|
19
|
+
def __init__(self, unavailable: Unavailable) -> None:
|
|
20
|
+
super().__init__(unavailable.reason.value)
|
|
21
|
+
self.unavailable = unavailable
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def activate(repo: ProtocolRepository, protocol_id: str, clock: Clock) -> list[ProtocolVersion]:
|
|
25
|
+
"""Run activation for one protocol and save what changed. Call inside a transaction."""
|
|
26
|
+
versions = repo.versions_of(protocol_id)
|
|
27
|
+
changed = activate_due(versions, today=clock.today(), at=clock.now())
|
|
28
|
+
for version in changed:
|
|
29
|
+
repo.save_version(version)
|
|
30
|
+
return versions
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def require_workflow(
|
|
34
|
+
version: ProtocolVersion, expected: Workflow, fallback: str
|
|
35
|
+
) -> Unavailable | None:
|
|
36
|
+
"""The version's scheme must belong to this workflow; otherwise no numbers at all."""
|
|
37
|
+
if version.content.scheme.workflow is expected:
|
|
38
|
+
return None
|
|
39
|
+
return Unavailable(UnusableReason.WRONG_WORKFLOW, fallback)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AvailabilityGate:
|
|
43
|
+
"""Reloads the version before every calculation and refuses anything not Published.
|
|
44
|
+
|
|
45
|
+
A superseded version is refused too, so a screen that stayed open never switches silently to
|
|
46
|
+
a newer version (DA-06); the person confirms the new one.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, repo: ProtocolRepository, clock: Clock, default_fallback: str) -> None:
|
|
50
|
+
self._repo = repo
|
|
51
|
+
self._clock = clock
|
|
52
|
+
self._fallback = default_fallback
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def fallback_note(self) -> str:
|
|
56
|
+
"""What to do instead when no number can be shown."""
|
|
57
|
+
return self._fallback
|
|
58
|
+
|
|
59
|
+
def ensure_usable(self, version_id: str) -> ProtocolVersion:
|
|
60
|
+
try:
|
|
61
|
+
with self._repo.transaction():
|
|
62
|
+
version = self._repo.get_version(version_id)
|
|
63
|
+
activate(self._repo, version.protocol_id, self._clock)
|
|
64
|
+
version = self._repo.get_version(version_id)
|
|
65
|
+
except NotFoundError:
|
|
66
|
+
raise self._refuse(UnusableReason.NOT_FOUND) from None
|
|
67
|
+
except RepositoryUnavailableError:
|
|
68
|
+
raise self._refuse(UnusableReason.STORAGE_UNAVAILABLE) from None
|
|
69
|
+
match version.state:
|
|
70
|
+
case StateName.PUBLISHED:
|
|
71
|
+
return version
|
|
72
|
+
case StateName.WITHDRAWN:
|
|
73
|
+
event = version.last_event(EventKind.WITHDRAWN)
|
|
74
|
+
note = event.fallback_note if event and event.fallback_note else self._fallback
|
|
75
|
+
raise self._refuse(UnusableReason.WITHDRAWN, note, event.at if event else None)
|
|
76
|
+
case StateName.SUPERSEDED:
|
|
77
|
+
event = version.last_event(EventKind.SUPERSEDED)
|
|
78
|
+
raise self._refuse(UnusableReason.SUPERSEDED, since=event.at if event else None)
|
|
79
|
+
case _:
|
|
80
|
+
raise self._refuse(UnusableReason.NOT_PUBLISHED)
|
|
81
|
+
|
|
82
|
+
def _refuse(
|
|
83
|
+
self, reason: UnusableReason, note: str | None = None, since: datetime | None = None
|
|
84
|
+
) -> VersionUnusableError:
|
|
85
|
+
return VersionUnusableError(Unavailable(reason, note or self._fallback, since))
|
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
"""The protocol office: create, change, review, approve and withdraw protocol versions.
|
|
2
|
+
|
|
3
|
+
Every action resolves the person's roles through the user directory; it never trusts roles a
|
|
4
|
+
client claims. The domain enforces the four-eyes rule a second time.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import date
|
|
12
|
+
|
|
13
|
+
from doseframe.findings import Finding, Severity
|
|
14
|
+
from doseframe.protocols import (
|
|
15
|
+
Actor,
|
|
16
|
+
CaseResult,
|
|
17
|
+
DeviceProfile,
|
|
18
|
+
DeviceProfileChange,
|
|
19
|
+
FieldChange,
|
|
20
|
+
GovernanceError,
|
|
21
|
+
GuardFailedError,
|
|
22
|
+
Medication,
|
|
23
|
+
Operation,
|
|
24
|
+
PermissionDeniedError,
|
|
25
|
+
Protocol,
|
|
26
|
+
ProtocolTitle,
|
|
27
|
+
ProtocolVersion,
|
|
28
|
+
SingleDoseSetup,
|
|
29
|
+
StateName,
|
|
30
|
+
UserRole,
|
|
31
|
+
VersionContent,
|
|
32
|
+
diff_contents,
|
|
33
|
+
title_of,
|
|
34
|
+
)
|
|
35
|
+
from doseframe.rounding import RoundingPolicyRegistry
|
|
36
|
+
from doseframe.use_cases.gate import activate
|
|
37
|
+
from doseframe.use_cases.ports import Clock, NotFoundError, ProtocolRepository, UserDirectory
|
|
38
|
+
|
|
39
|
+
OPEN_STATES = frozenset({StateName.DRAFT, StateName.IN_REVIEW, StateName.APPROVED})
|
|
40
|
+
EVER_APPROVED = frozenset(
|
|
41
|
+
{StateName.APPROVED, StateName.PUBLISHED, StateName.SUPERSEDED, StateName.WITHDRAWN}
|
|
42
|
+
)
|
|
43
|
+
IDENTITY_CHANGED = "protocol_identity_changed"
|
|
44
|
+
_IDENTITY_PARTS = ("strength", "carrier", "syringe", "weight")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class OpenChangeExistsError(GovernanceError):
|
|
48
|
+
"""A protocol has at most one change in progress (Draft, InReview or a scheduled approval)."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True, slots=True)
|
|
52
|
+
class Evaluation:
|
|
53
|
+
"""The live check while editing: validation findings and every reference case."""
|
|
54
|
+
|
|
55
|
+
findings: tuple[Finding, ...]
|
|
56
|
+
cases: tuple[CaseResult, ...]
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def submittable(self) -> bool:
|
|
60
|
+
return not any(f.blocks for f in self.findings)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True, slots=True)
|
|
64
|
+
class VersionOverview:
|
|
65
|
+
version_id: str
|
|
66
|
+
number: int
|
|
67
|
+
state: StateName
|
|
68
|
+
author: str
|
|
69
|
+
reviewer: str | None
|
|
70
|
+
effective_from: date | None
|
|
71
|
+
review_due: date | None
|
|
72
|
+
review_overdue: bool
|
|
73
|
+
fictitious: bool
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True, slots=True)
|
|
77
|
+
class ProtocolOverview:
|
|
78
|
+
protocol: Protocol
|
|
79
|
+
medication: Medication
|
|
80
|
+
versions: tuple[VersionOverview, ...]
|
|
81
|
+
title: ProtocolTitle
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def published(self) -> VersionOverview | None:
|
|
85
|
+
return next((v for v in self.versions if v.state is StateName.PUBLISHED), None)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True, slots=True)
|
|
89
|
+
class ApprovalReasons:
|
|
90
|
+
"""Why an approver may approve (guard G1), shown next to the approve button."""
|
|
91
|
+
|
|
92
|
+
not_author: bool
|
|
93
|
+
approver_role: bool
|
|
94
|
+
complete: bool
|
|
95
|
+
cases_pass: bool
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True, slots=True)
|
|
99
|
+
class VersionDetail:
|
|
100
|
+
"""One version as the office shows it: content, live check, and what the reader may do."""
|
|
101
|
+
|
|
102
|
+
version: ProtocolVersion
|
|
103
|
+
protocol: Protocol
|
|
104
|
+
medication: Medication
|
|
105
|
+
evaluation: Evaluation
|
|
106
|
+
permitted: frozenset[Operation]
|
|
107
|
+
approval: ApprovalReasons
|
|
108
|
+
review_overdue: bool
|
|
109
|
+
today: date # the hospital's date: the earliest start date an approval accepts
|
|
110
|
+
title: ProtocolTitle
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class ProtocolOffice:
|
|
114
|
+
"""All governance interactors share these collaborators; each method is one use case."""
|
|
115
|
+
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
repo: ProtocolRepository,
|
|
119
|
+
users: UserDirectory,
|
|
120
|
+
clock: Clock,
|
|
121
|
+
registry: RoundingPolicyRegistry,
|
|
122
|
+
) -> None:
|
|
123
|
+
self._repo = repo
|
|
124
|
+
self._users = users
|
|
125
|
+
self._clock = clock
|
|
126
|
+
self._registry = registry
|
|
127
|
+
|
|
128
|
+
# --- reading ----------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
def list_protocols(self, user_id: str) -> list[ProtocolOverview]:
|
|
131
|
+
self._actor(user_id, UserRole.EDITOR, UserRole.APPROVER)
|
|
132
|
+
today = self._clock.today()
|
|
133
|
+
overviews: list[ProtocolOverview] = []
|
|
134
|
+
with self._repo.transaction():
|
|
135
|
+
for protocol in self._repo.list_protocols():
|
|
136
|
+
versions = activate(self._repo, protocol.id, self._clock)
|
|
137
|
+
medication = self._repo.get_medication(protocol.medication_id)
|
|
138
|
+
ordered = sorted(versions, key=lambda v: v.number)
|
|
139
|
+
rows = tuple(_overview(v, today) for v in ordered)
|
|
140
|
+
shown = next((v for v in ordered if v.state is StateName.PUBLISHED), ordered[-1])
|
|
141
|
+
title = self._title(protocol, medication, shown.content)
|
|
142
|
+
overviews.append(ProtocolOverview(protocol, medication, rows, title))
|
|
143
|
+
return sorted(overviews, key=lambda o: (o.medication.name, o.title.text()))
|
|
144
|
+
|
|
145
|
+
def get_version(self, user_id: str, version_id: str) -> ProtocolVersion:
|
|
146
|
+
self._actor(user_id, UserRole.EDITOR, UserRole.APPROVER)
|
|
147
|
+
with self._repo.transaction():
|
|
148
|
+
version = self._repo.get_version(version_id)
|
|
149
|
+
activate(self._repo, version.protocol_id, self._clock)
|
|
150
|
+
return self._repo.get_version(version_id)
|
|
151
|
+
|
|
152
|
+
def version_detail(self, user_id: str, version_id: str) -> VersionDetail:
|
|
153
|
+
actor = self._actor(user_id, UserRole.EDITOR, UserRole.APPROVER)
|
|
154
|
+
with self._repo.transaction():
|
|
155
|
+
protocol_id = self._repo.get_version(version_id).protocol_id
|
|
156
|
+
versions = activate(self._repo, protocol_id, self._clock)
|
|
157
|
+
version = self._repo.get_version(version_id)
|
|
158
|
+
protocol = self._repo.get_protocol(protocol_id)
|
|
159
|
+
medication = self._repo.get_medication(protocol.medication_id)
|
|
160
|
+
title = self._title(protocol, medication, version.content)
|
|
161
|
+
evaluation = self._evaluate(version.content, protocol_id)
|
|
162
|
+
permitted = version.permitted(actor)
|
|
163
|
+
if any(v.state in OPEN_STATES for v in versions):
|
|
164
|
+
permitted -= {Operation.DERIVE} # one change at a time (derive_draft refuses it)
|
|
165
|
+
approval = ApprovalReasons(
|
|
166
|
+
not_author=actor.user_id != version.author,
|
|
167
|
+
approver_role=actor.has(UserRole.APPROVER),
|
|
168
|
+
complete=evaluation.submittable,
|
|
169
|
+
cases_pass=bool(evaluation.cases) and all(c.passed for c in evaluation.cases),
|
|
170
|
+
)
|
|
171
|
+
return VersionDetail(
|
|
172
|
+
version=version,
|
|
173
|
+
protocol=protocol,
|
|
174
|
+
medication=medication,
|
|
175
|
+
evaluation=evaluation,
|
|
176
|
+
permitted=permitted,
|
|
177
|
+
approval=approval,
|
|
178
|
+
review_overdue=version.is_review_overdue(self._clock.today()),
|
|
179
|
+
today=self._clock.today(),
|
|
180
|
+
title=title,
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def diff(self, user_id: str, version_id: str) -> list[FieldChange]:
|
|
184
|
+
"""The version against the one it is based on; everything for a first version."""
|
|
185
|
+
version = self.get_version(user_id, version_id)
|
|
186
|
+
base = self._repo.get_version(version.based_on) if version.based_on else None
|
|
187
|
+
return diff_contents(base.content if base else None, version.content)
|
|
188
|
+
|
|
189
|
+
def evaluate(
|
|
190
|
+
self, user_id: str, content: VersionContent, protocol_id: str | None = None
|
|
191
|
+
) -> Evaluation:
|
|
192
|
+
"""Validation and reference cases for content being edited; changes nothing.
|
|
193
|
+
|
|
194
|
+
With the protocol it belongs to, a change to a name-defining part is reported too.
|
|
195
|
+
"""
|
|
196
|
+
self._actor(user_id, UserRole.EDITOR, UserRole.APPROVER)
|
|
197
|
+
return self._evaluate(content, protocol_id)
|
|
198
|
+
|
|
199
|
+
def list_medications(self, user_id: str) -> list[Medication]:
|
|
200
|
+
self._actor(user_id, UserRole.EDITOR, UserRole.APPROVER)
|
|
201
|
+
return self._repo.list_medications()
|
|
202
|
+
|
|
203
|
+
def list_device_profiles(self, user_id: str) -> list[DeviceProfile]:
|
|
204
|
+
self._actor(user_id, UserRole.EDITOR, UserRole.APPROVER)
|
|
205
|
+
return self._repo.list_device_profiles()
|
|
206
|
+
|
|
207
|
+
# --- content ----------------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
def create_medication(
|
|
210
|
+
self, user_id: str, *, name: str, active_ingredient: str, trade_names: tuple[str, ...] = ()
|
|
211
|
+
) -> Medication:
|
|
212
|
+
self._actor(user_id, UserRole.EDITOR)
|
|
213
|
+
if not name.strip() or not active_ingredient.strip():
|
|
214
|
+
raise GovernanceError("a medication needs a name and an active ingredient")
|
|
215
|
+
medication = Medication(
|
|
216
|
+
self._repo.new_id(), name.strip(), active_ingredient.strip(), trade_names
|
|
217
|
+
)
|
|
218
|
+
with self._repo.transaction():
|
|
219
|
+
self._repo.add_medication(medication)
|
|
220
|
+
return medication
|
|
221
|
+
|
|
222
|
+
def create_protocol(
|
|
223
|
+
self, user_id: str, *, medication_id: str, name: str, content: VersionContent
|
|
224
|
+
) -> ProtocolVersion:
|
|
225
|
+
"""A new protocol. `name` is only an optional addition to the generated name (V3-12)."""
|
|
226
|
+
actor = self._actor(user_id, UserRole.EDITOR)
|
|
227
|
+
with self._repo.transaction():
|
|
228
|
+
self._repo.get_medication(medication_id)
|
|
229
|
+
protocol = Protocol(self._repo.new_id(), medication_id, name.strip())
|
|
230
|
+
self._repo.add_protocol(protocol)
|
|
231
|
+
version = ProtocolVersion.create_first_draft(
|
|
232
|
+
id=self._repo.new_id(),
|
|
233
|
+
protocol_id=protocol.id,
|
|
234
|
+
author=actor,
|
|
235
|
+
content=content,
|
|
236
|
+
at=self._clock.now(),
|
|
237
|
+
)
|
|
238
|
+
self._repo.save_version(version)
|
|
239
|
+
return version
|
|
240
|
+
|
|
241
|
+
def derive_draft(self, user_id: str, version_id: str) -> ProtocolVersion:
|
|
242
|
+
actor = self._actor(user_id, UserRole.EDITOR)
|
|
243
|
+
with self._repo.transaction():
|
|
244
|
+
base = self._repo.get_version(version_id)
|
|
245
|
+
versions = activate(self._repo, base.protocol_id, self._clock)
|
|
246
|
+
if any(v.state in OPEN_STATES for v in versions):
|
|
247
|
+
raise OpenChangeExistsError("this protocol already has a change in progress")
|
|
248
|
+
base = self._repo.get_version(version_id)
|
|
249
|
+
draft = base.derive_draft(id=self._repo.new_id(), author=actor, at=self._clock.now())
|
|
250
|
+
self._repo.save_version(draft)
|
|
251
|
+
return draft
|
|
252
|
+
|
|
253
|
+
def edit_draft(
|
|
254
|
+
self, user_id: str, version_id: str, *, content: VersionContent, change_reason: str
|
|
255
|
+
) -> ProtocolVersion:
|
|
256
|
+
return self._transition(
|
|
257
|
+
user_id,
|
|
258
|
+
version_id,
|
|
259
|
+
lambda v, actor: v.edit(
|
|
260
|
+
actor, content=content, change_reason=change_reason, at=self._clock.now()
|
|
261
|
+
),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
# --- lifecycle --------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
def submit(self, user_id: str, version_id: str) -> ProtocolVersion:
|
|
267
|
+
self._require_same_identity(version_id)
|
|
268
|
+
return self._transition(
|
|
269
|
+
user_id,
|
|
270
|
+
version_id,
|
|
271
|
+
lambda v, actor: v.submit(
|
|
272
|
+
actor,
|
|
273
|
+
at=self._clock.now(),
|
|
274
|
+
rounding_keys=self._registry.keys(),
|
|
275
|
+
setup=self._setup(v.content),
|
|
276
|
+
),
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
def reject(self, user_id: str, version_id: str, *, reason: str) -> ProtocolVersion:
|
|
280
|
+
return self._transition(
|
|
281
|
+
user_id,
|
|
282
|
+
version_id,
|
|
283
|
+
lambda v, actor: v.reject(actor, reason=reason, at=self._clock.now()),
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
def approve(self, user_id: str, version_id: str, *, effective_from: date) -> ProtocolVersion:
|
|
287
|
+
"""Approve with a start date; if the date is today, the version is in force at once."""
|
|
288
|
+
self._require_same_identity(version_id)
|
|
289
|
+
version = self._transition(
|
|
290
|
+
user_id,
|
|
291
|
+
version_id,
|
|
292
|
+
lambda v, actor: v.approve(
|
|
293
|
+
actor,
|
|
294
|
+
effective_from=effective_from,
|
|
295
|
+
today=self._clock.today(),
|
|
296
|
+
at=self._clock.now(),
|
|
297
|
+
rounding_keys=self._registry.keys(),
|
|
298
|
+
setup=self._setup(v.content),
|
|
299
|
+
),
|
|
300
|
+
)
|
|
301
|
+
with self._repo.transaction():
|
|
302
|
+
activate(self._repo, version.protocol_id, self._clock)
|
|
303
|
+
return self._repo.get_version(version_id)
|
|
304
|
+
|
|
305
|
+
def withdraw(
|
|
306
|
+
self, user_id: str, version_id: str, *, reason: str, fallback_note: str
|
|
307
|
+
) -> ProtocolVersion:
|
|
308
|
+
return self._transition(
|
|
309
|
+
user_id,
|
|
310
|
+
version_id,
|
|
311
|
+
lambda v, actor: v.withdraw(
|
|
312
|
+
actor, reason=reason, fallback_note=fallback_note, at=self._clock.now()
|
|
313
|
+
),
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
# --- device profiles --------------------------------------------------------------------
|
|
317
|
+
|
|
318
|
+
def save_device_profile(self, user_id: str, profile: DeviceProfile) -> DeviceProfile:
|
|
319
|
+
"""Edit unused profiles; an approval makes the referenced profile immutable."""
|
|
320
|
+
actor = self._actor(user_id, UserRole.EDITOR)
|
|
321
|
+
if not profile.name.strip():
|
|
322
|
+
raise GovernanceError("a device profile needs a name")
|
|
323
|
+
with self._repo.transaction():
|
|
324
|
+
if self._repo.get_device_profile(profile.id) == profile:
|
|
325
|
+
return profile # an idempotent save must not rewrite approval history
|
|
326
|
+
if any(
|
|
327
|
+
version.content.device_profile_id == profile.id
|
|
328
|
+
and version.state not in {StateName.DRAFT, StateName.IN_REVIEW}
|
|
329
|
+
for protocol in self._repo.list_protocols()
|
|
330
|
+
for version in self._repo.versions_of(protocol.id)
|
|
331
|
+
):
|
|
332
|
+
raise GuardFailedError(
|
|
333
|
+
"an approved protocol uses this device; "
|
|
334
|
+
"create a new profile and approve a new protocol version",
|
|
335
|
+
[
|
|
336
|
+
Finding(
|
|
337
|
+
"device_profile_in_use",
|
|
338
|
+
Severity.BLOCK,
|
|
339
|
+
"create a new profile and approve a new protocol version",
|
|
340
|
+
{"device": profile.name},
|
|
341
|
+
)
|
|
342
|
+
],
|
|
343
|
+
)
|
|
344
|
+
self._repo.save_device_profile(
|
|
345
|
+
DeviceProfileChange(profile, self._clock.now(), actor.user_id)
|
|
346
|
+
)
|
|
347
|
+
return profile
|
|
348
|
+
|
|
349
|
+
def device_profile_history(self, user_id: str, profile_id: str) -> list[DeviceProfileChange]:
|
|
350
|
+
self._actor(user_id, UserRole.EDITOR, UserRole.APPROVER)
|
|
351
|
+
return self._repo.device_profile_history(profile_id)
|
|
352
|
+
|
|
353
|
+
# --- helpers ----------------------------------------------------------------------------
|
|
354
|
+
|
|
355
|
+
def _evaluate(self, content: VersionContent, protocol_id: str | None = None) -> Evaluation:
|
|
356
|
+
setup = self._setup(content)
|
|
357
|
+
findings = content.validate(self._registry.keys(), setup)
|
|
358
|
+
if protocol_id is not None:
|
|
359
|
+
findings += self._identity_findings(protocol_id, content)
|
|
360
|
+
return Evaluation(tuple(findings), tuple(content.evaluate_cases(setup)))
|
|
361
|
+
|
|
362
|
+
def _title(
|
|
363
|
+
self, protocol: Protocol, medication: Medication, content: VersionContent
|
|
364
|
+
) -> ProtocolTitle:
|
|
365
|
+
device = (
|
|
366
|
+
self._repo.get_device_profile(content.device_profile_id)
|
|
367
|
+
if content.device_profile_id
|
|
368
|
+
else None
|
|
369
|
+
)
|
|
370
|
+
return title_of(
|
|
371
|
+
medication.name, content.scheme, content.weight_scope, device, protocol.name
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
def _identity_findings(self, protocol_id: str, content: VersionContent) -> list[Finding]:
|
|
375
|
+
"""Strength, carrier, syringe and weight range are fixed once a version was approved.
|
|
376
|
+
|
|
377
|
+
They make up the protocol's name, so a syringe made up from an older version always
|
|
378
|
+
matches it. A different value is a new protocol (copy this one as a template).
|
|
379
|
+
"""
|
|
380
|
+
with self._repo.transaction():
|
|
381
|
+
protocol = self._repo.get_protocol(protocol_id)
|
|
382
|
+
approved = [v for v in self._repo.versions_of(protocol_id) if v.state in EVER_APPROVED]
|
|
383
|
+
if not approved:
|
|
384
|
+
return []
|
|
385
|
+
medication = self._repo.get_medication(protocol.medication_id)
|
|
386
|
+
anchor = self._title(
|
|
387
|
+
protocol, medication, max(approved, key=lambda v: v.number).content
|
|
388
|
+
)
|
|
389
|
+
current = self._title(protocol, medication, content)
|
|
390
|
+
changed = [
|
|
391
|
+
part
|
|
392
|
+
for part, before, after in zip(
|
|
393
|
+
_IDENTITY_PARTS, anchor.identity, current.identity, strict=True
|
|
394
|
+
)
|
|
395
|
+
if before != after
|
|
396
|
+
]
|
|
397
|
+
if not changed:
|
|
398
|
+
return []
|
|
399
|
+
return [
|
|
400
|
+
Finding(
|
|
401
|
+
IDENTITY_CHANGED,
|
|
402
|
+
Severity.BLOCK,
|
|
403
|
+
"strength, carrier, syringe and weight range are part of the protocol name and "
|
|
404
|
+
"cannot change; create a new protocol from this one instead",
|
|
405
|
+
{"fields": ", ".join(changed), "name": anchor.text()},
|
|
406
|
+
)
|
|
407
|
+
]
|
|
408
|
+
|
|
409
|
+
def _require_same_identity(self, version_id: str) -> None:
|
|
410
|
+
with self._repo.transaction():
|
|
411
|
+
version = self._repo.get_version(version_id)
|
|
412
|
+
findings = self._identity_findings(version.protocol_id, version.content)
|
|
413
|
+
if findings:
|
|
414
|
+
raise GuardFailedError(findings[0].message, findings)
|
|
415
|
+
|
|
416
|
+
def _setup(self, content: VersionContent) -> SingleDoseSetup | None:
|
|
417
|
+
"""The protocol's rounding rule and device, for single-dose evaluation at approval."""
|
|
418
|
+
if content.rounding_policy_key not in self._registry.keys(): # noqa: SIM118
|
|
419
|
+
return None
|
|
420
|
+
device = (
|
|
421
|
+
self._repo.get_device_profile(content.device_profile_id)
|
|
422
|
+
if content.device_profile_id
|
|
423
|
+
else None
|
|
424
|
+
)
|
|
425
|
+
return SingleDoseSetup(self._registry.get(content.rounding_policy_key), device)
|
|
426
|
+
|
|
427
|
+
def _transition(self, user_id: str, version_id: str, action: _Action) -> ProtocolVersion:
|
|
428
|
+
actor = self._actor(user_id)
|
|
429
|
+
with self._repo.transaction():
|
|
430
|
+
version = self._repo.get_version(version_id)
|
|
431
|
+
action(version, actor)
|
|
432
|
+
self._repo.save_version(version)
|
|
433
|
+
return version
|
|
434
|
+
|
|
435
|
+
def _actor(self, user_id: str, *roles: UserRole) -> Actor:
|
|
436
|
+
try:
|
|
437
|
+
actor = self._users.get_actor(user_id)
|
|
438
|
+
except NotFoundError:
|
|
439
|
+
raise PermissionDeniedError("unknown user") from None
|
|
440
|
+
if roles and not any(actor.has(role) for role in roles):
|
|
441
|
+
needed = " or ".join(r.value for r in roles)
|
|
442
|
+
raise PermissionDeniedError(f"the {needed} role is needed")
|
|
443
|
+
return actor
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
type _Action = Callable[[ProtocolVersion, Actor], None]
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _overview(version: ProtocolVersion, today: date) -> VersionOverview:
|
|
450
|
+
return VersionOverview(
|
|
451
|
+
version_id=version.id,
|
|
452
|
+
number=version.number,
|
|
453
|
+
state=version.state,
|
|
454
|
+
author=version.author,
|
|
455
|
+
reviewer=version.reviewer,
|
|
456
|
+
effective_from=version.effective_from,
|
|
457
|
+
review_due=version.content.review_due,
|
|
458
|
+
review_overdue=version.is_review_overdue(today),
|
|
459
|
+
fictitious=version.content.fictitious,
|
|
460
|
+
)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Ports: what the use cases need from outside, declared here and implemented by adapters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import AbstractContextManager
|
|
6
|
+
from datetime import date, datetime
|
|
7
|
+
from typing import Protocol
|
|
8
|
+
|
|
9
|
+
from doseframe.protocols import DeviceProfile, DeviceProfileChange, Medication, ProtocolVersion
|
|
10
|
+
from doseframe.protocols import Protocol as ClinicalProtocol
|
|
11
|
+
from doseframe.protocols.model import Actor
|
|
12
|
+
from doseframe.units import DoseframeError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class NotFoundError(DoseframeError):
|
|
16
|
+
"""The requested medication, protocol, version or user does not exist."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RepositoryUnavailableError(DoseframeError):
|
|
20
|
+
"""The storage cannot be reached or read. No result may be given without it (BE-06)."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ProtocolRepository(Protocol):
|
|
24
|
+
"""Stores protocol content: medications, protocols, versions and device profiles.
|
|
25
|
+
|
|
26
|
+
It never stores anything about an individual calculation.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def transaction(self) -> AbstractContextManager[None]:
|
|
30
|
+
"""A unit of work: everything inside is saved together or not at all."""
|
|
31
|
+
...
|
|
32
|
+
|
|
33
|
+
def new_id(self) -> str: ...
|
|
34
|
+
|
|
35
|
+
def list_medications(self) -> list[Medication]: ...
|
|
36
|
+
|
|
37
|
+
def get_medication(self, medication_id: str) -> Medication: ...
|
|
38
|
+
|
|
39
|
+
def add_medication(self, medication: Medication) -> None: ...
|
|
40
|
+
|
|
41
|
+
def list_protocols(self, medication_id: str | None = None) -> list[ClinicalProtocol]: ...
|
|
42
|
+
|
|
43
|
+
def get_protocol(self, protocol_id: str) -> ClinicalProtocol: ...
|
|
44
|
+
|
|
45
|
+
def add_protocol(self, protocol: ClinicalProtocol) -> None: ...
|
|
46
|
+
|
|
47
|
+
def versions_of(self, protocol_id: str) -> list[ProtocolVersion]: ...
|
|
48
|
+
|
|
49
|
+
def get_version(self, version_id: str) -> ProtocolVersion: ...
|
|
50
|
+
|
|
51
|
+
def save_version(self, version: ProtocolVersion) -> None: ...
|
|
52
|
+
|
|
53
|
+
def get_device_profile(self, profile_id: str) -> DeviceProfile | None: ...
|
|
54
|
+
|
|
55
|
+
def list_device_profiles(self) -> list[DeviceProfile]: ...
|
|
56
|
+
|
|
57
|
+
def save_device_profile(self, change: DeviceProfileChange) -> None:
|
|
58
|
+
"""Stores the profile and keeps the change in its history."""
|
|
59
|
+
...
|
|
60
|
+
|
|
61
|
+
def device_profile_history(self, profile_id: str) -> list[DeviceProfileChange]: ...
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class UserDirectory(Protocol):
|
|
65
|
+
def get_actor(self, user_id: str) -> Actor:
|
|
66
|
+
"""The person with their current roles; raises NotFoundError for an unknown user."""
|
|
67
|
+
...
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Clock(Protocol):
|
|
71
|
+
def today(self) -> date: ...
|
|
72
|
+
|
|
73
|
+
def now(self) -> datetime: ...
|