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.
Files changed (46) hide show
  1. doseframe/__init__.py +252 -0
  2. doseframe/calculation/__init__.py +34 -0
  3. doseframe/calculation/derivation.py +30 -0
  4. doseframe/calculation/errors.py +16 -0
  5. doseframe/calculation/infusion.py +27 -0
  6. doseframe/calculation/relation.py +129 -0
  7. doseframe/calculation/single_dose.py +54 -0
  8. doseframe/calculation/steps.py +20 -0
  9. doseframe/calculation/strategies.py +105 -0
  10. doseframe/calculation/strategy.py +37 -0
  11. doseframe/checks/__init__.py +20 -0
  12. doseframe/checks/chain.py +212 -0
  13. doseframe/checks/context.py +43 -0
  14. doseframe/findings/__init__.py +58 -0
  15. doseframe/protocols/__init__.py +103 -0
  16. doseframe/protocols/activation.py +51 -0
  17. doseframe/protocols/device.py +51 -0
  18. doseframe/protocols/diff.py +70 -0
  19. doseframe/protocols/errors.py +26 -0
  20. doseframe/protocols/limits.py +74 -0
  21. doseframe/protocols/model.py +40 -0
  22. doseframe/protocols/naming.py +126 -0
  23. doseframe/protocols/reference.py +163 -0
  24. doseframe/protocols/schemes.py +598 -0
  25. doseframe/protocols/single_dose.py +253 -0
  26. doseframe/protocols/version.py +690 -0
  27. doseframe/py.typed +0 -0
  28. doseframe/rounding/__init__.py +23 -0
  29. doseframe/rounding/policy.py +108 -0
  30. doseframe/units/__init__.py +49 -0
  31. doseframe/units/catalog.py +155 -0
  32. doseframe/units/decimal_context.py +17 -0
  33. doseframe/units/errors.py +27 -0
  34. doseframe/units/options.py +52 -0
  35. doseframe/units/quantity.py +144 -0
  36. doseframe/units/unit.py +137 -0
  37. doseframe/use_cases/__init__.py +73 -0
  38. doseframe/use_cases/clinical.py +735 -0
  39. doseframe/use_cases/gate.py +85 -0
  40. doseframe/use_cases/governance.py +460 -0
  41. doseframe/use_cases/ports.py +73 -0
  42. doseframe/use_cases/results.py +182 -0
  43. doseframe-0.2.0.dist-info/METADATA +79 -0
  44. doseframe-0.2.0.dist-info/RECORD +46 -0
  45. doseframe-0.2.0.dist-info/WHEEL +4 -0
  46. doseframe-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,690 @@
1
+ """`ProtocolVersion`, the aggregate root, and its lifecycle (State pattern).
2
+
3
+ A version is one complete, approvable set of protocol content. Its state decides which
4
+ operations are allowed; each state is its own class, so an approval step cannot be skipped by
5
+ accident. Content can only change while the version is a Draft. Every transition is recorded.
6
+
7
+ Draft ⇄ InReview → Approved → Published → Superseded
8
+ └──────────┴────────────┴──→ Withdrawn
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable, Collection
14
+ from dataclasses import dataclass
15
+ from datetime import date, datetime
16
+ from decimal import Decimal
17
+ from enum import StrEnum
18
+ from typing import ClassVar
19
+
20
+ from doseframe.findings import UNIT_ROLE, Finding, Severity
21
+ from doseframe.protocols.errors import (
22
+ GuardFailedError,
23
+ IllegalTransitionError,
24
+ PermissionDeniedError,
25
+ )
26
+ from doseframe.protocols.limits import Limit, LimitTarget, WeightScope
27
+ from doseframe.protocols.model import Actor, UserRole
28
+ from doseframe.protocols.reference import CaseDirection, CaseResult, ReferenceCase
29
+ from doseframe.protocols.schemes import PreparationScheme, Workflow
30
+ from doseframe.protocols.single_dose import (
31
+ SingleDoseSetup,
32
+ deviation_limit_findings,
33
+ syringe_findings,
34
+ )
35
+ from doseframe.units import Role, Unit, is_allowed, unit
36
+
37
+ # --- content -------------------------------------------------------------------------------
38
+
39
+
40
+ @dataclass(frozen=True, slots=True, kw_only=True)
41
+ class VersionContent:
42
+ """Everything a reviewer approves. Immutable; a change produces a new content object."""
43
+
44
+ weight_scope: WeightScope
45
+ dose_unit: Unit
46
+ scheme: PreparationScheme
47
+ reference_cases: tuple[ReferenceCase, ...]
48
+ review_due: date | None
49
+ limits: tuple[Limit, ...] = ()
50
+ rounding_policy_key: str = "none"
51
+ device_profile_id: str | None = None
52
+ notes: tuple[str, ...] = ()
53
+ source: str = ""
54
+ fictitious: bool = False
55
+ usual_dose_units: tuple[Unit, ...] = ()
56
+ max_rounding_deviation_pct: Decimal | None = None
57
+
58
+ def evaluate_cases(self, setup: SingleDoseSetup | None = None) -> list[CaseResult]:
59
+ return [self._evaluate_case(case, setup) for case in self.reference_cases]
60
+
61
+ def _evaluate_case(self, case: ReferenceCase, setup: SingleDoseSetup | None) -> CaseResult:
62
+ if case.weight.unit != unit("kg"):
63
+ return CaseResult(case, None, passed=False, error="weight must be stored in kg")
64
+ return case.evaluate(
65
+ self.scheme, self.dose_unit, setup, self.limits, self.max_rounding_deviation_pct
66
+ )
67
+
68
+ def validate(
69
+ self, rounding_keys: Collection[str], setup: SingleDoseSetup | None = None
70
+ ) -> list[Finding]:
71
+ """All findings about this content. Any BLOCK prevents submission and approval."""
72
+ findings = list(self.scheme.validate())
73
+ findings += self._validate_units()
74
+ scope_findings = self._validate_scope()
75
+ findings += scope_findings
76
+ limit_findings = self._validate_limits()
77
+ findings += limit_findings
78
+ if not limit_findings:
79
+ findings += self._validate_plausibility()
80
+ findings += self._validate_cases(check_scope=not scope_findings, setup=setup)
81
+ if self.scheme.workflow is Workflow.SINGLE_DOSE:
82
+ findings += self._validate_single_dose(setup)
83
+ if self.rounding_policy_key not in rounding_keys:
84
+ findings.append(
85
+ _block(
86
+ "unknown_rounding_policy",
87
+ f"rounding rule {self.rounding_policy_key!r} is not registered",
88
+ key=self.rounding_policy_key,
89
+ )
90
+ )
91
+ if self.review_due is None:
92
+ findings.append(
93
+ _block("missing_field", "a review date is required", field="review_due")
94
+ )
95
+ return findings
96
+
97
+ def _validate_units(self) -> list[Finding]:
98
+ if not is_allowed(self.dose_unit, Role.DOSE):
99
+ return [
100
+ _block(
101
+ UNIT_ROLE,
102
+ f"{self.dose_unit.symbol} is not a dose unit",
103
+ field="dose_unit",
104
+ unit=self.dose_unit.symbol,
105
+ )
106
+ ]
107
+ dose_dimension = self.dose_unit.terms[0][0].dimension
108
+ for stock in self.scheme.stock_solutions:
109
+ if stock.strength.unit.terms[0][0].dimension is not dose_dimension:
110
+ return [
111
+ _block(
112
+ "dose_unit_does_not_match_stock",
113
+ f"dose in {self.dose_unit.symbol} does not fit {stock.label}",
114
+ stock=stock.label,
115
+ )
116
+ ]
117
+ return []
118
+
119
+ def _validate_scope(self) -> list[Finding]:
120
+ findings: list[Finding] = []
121
+ bounds = [b for b in (self.weight_scope.lower, self.weight_scope.upper) if b is not None]
122
+ for bound in bounds:
123
+ if not is_allowed(bound.unit, Role.WEIGHT) or bound.value < 0:
124
+ findings.append(_block("invalid_weight_scope", f"{bound} is not a weight bound"))
125
+ elif bound.unit != unit("kg"):
126
+ findings.append(_block("weight_unit_not_kg", f"{bound} must be stored in kg"))
127
+ lower, upper = self.weight_scope.lower, self.weight_scope.upper
128
+ if lower is None or upper is None:
129
+ findings.append(_block("weight_scope_open", "the weight range needs both limits"))
130
+ if not findings and lower is not None and upper is not None and lower >= upper:
131
+ findings.append(
132
+ _block("invalid_weight_scope", "the lower limit must be below the upper")
133
+ )
134
+ return findings
135
+
136
+ def _validate_limits(self) -> list[Finding]:
137
+ findings: list[Finding] = []
138
+ expected = {
139
+ LimitTarget.DOSE: self.dose_unit,
140
+ LimitTarget.RATE: unit("ml/h"),
141
+ LimitTarget.SETTING: unit("ml/h"),
142
+ LimitTarget.WITHDRAWAL_VOLUME: unit("ml"),
143
+ }
144
+ for limit in self.limits:
145
+ target = limit.target.value
146
+ if not limit.justification.strip():
147
+ findings.append(_block("limit_without_justification", "", target=target))
148
+ if limit.severity is Severity.INFO:
149
+ findings.append(_block("limit_severity", "a limit warns or blocks", target=target))
150
+ bounds = [b for b in (limit.lower, limit.upper) if b is not None]
151
+ if not bounds:
152
+ findings.append(_block("limit_without_bound", "", target=target))
153
+ if any(not b.unit.is_compatible(expected[limit.target]) for b in bounds):
154
+ findings.append(_block("limit_unit_mismatch", "", target=target))
155
+ elif limit.lower is not None and limit.upper is not None and limit.lower > limit.upper:
156
+ findings.append(_block("limit_bounds_reversed", "", target=target))
157
+ return findings
158
+
159
+ def _validate_plausibility(self) -> list[Finding]:
160
+ """V2-06: a two-sided usual range inside an upper hard limit, and fitting usual units."""
161
+ findings: list[Finding] = []
162
+ dose = [limit for limit in self.limits if limit.target is LimitTarget.DOSE]
163
+ warn = [limit for limit in dose if limit.severity is Severity.WARN]
164
+ hard = [limit for limit in dose if limit.severity is Severity.BLOCK]
165
+ if len(warn) != 1 or warn[0].lower is None or warn[0].upper is None:
166
+ findings.append(
167
+ _block("usual_range_missing", "exactly one WARN dose limit with both bounds")
168
+ )
169
+ if not any(limit.upper is not None for limit in hard):
170
+ findings.append(
171
+ _block("dose_upper_block_missing", "a BLOCK dose limit with an upper bound")
172
+ )
173
+ if not findings:
174
+ band = warn[0]
175
+ for limit in hard:
176
+ above = (
177
+ limit.upper is not None and band.upper is not None and band.upper > limit.upper
178
+ )
179
+ below = (
180
+ limit.lower is not None and band.lower is not None and band.lower < limit.lower
181
+ )
182
+ if above or below:
183
+ findings.append(
184
+ _block(
185
+ "usual_range_outside_limits",
186
+ "the usual range lies outside a hard limit",
187
+ )
188
+ )
189
+ if len(self.usual_dose_units) > 3 or any(
190
+ not u.is_compatible(self.dose_unit) for u in self.usual_dose_units
191
+ ):
192
+ findings.append(
193
+ _block("usual_unit_invalid", "at most three usual units of the dose unit's kind")
194
+ )
195
+ return findings
196
+
197
+ def _validate_single_dose(self, setup: SingleDoseSetup | None) -> list[Finding]:
198
+ findings = deviation_limit_findings(self.max_rounding_deviation_pct)
199
+ if setup is not None:
200
+ findings += syringe_findings(setup.device)
201
+ return findings
202
+
203
+ def _validate_cases(self, *, check_scope: bool, setup: SingleDoseSetup | None) -> list[Finding]:
204
+ if not self.reference_cases:
205
+ return [_block("no_reference_case", "at least one reference case is required")]
206
+ findings: list[Finding] = []
207
+ for index, case in enumerate(self.reference_cases, start=1):
208
+ if case.weight.unit != unit("kg"):
209
+ findings.append(
210
+ _block(
211
+ "weight_unit_not_kg",
212
+ f"case {index}: weight must be stored in kg",
213
+ case=str(index),
214
+ )
215
+ )
216
+ continue
217
+ if case.direction.workflow is not self.scheme.workflow:
218
+ findings.append(
219
+ _block(
220
+ "reference_case_direction",
221
+ f"case {index}: direction does not fit this protocol",
222
+ case=str(index),
223
+ )
224
+ )
225
+ continue
226
+ if (
227
+ case.direction is CaseDirection.DAILY_DOSE_TO_ADMINISTRATION
228
+ and case.expected_volume is None
229
+ ):
230
+ findings.append(
231
+ _block(
232
+ "reference_case_volume_missing",
233
+ f"case {index}: the expected volume is required",
234
+ case=str(index),
235
+ )
236
+ )
237
+ continue
238
+ if not case.units_fit(self.dose_unit):
239
+ findings.append(
240
+ _block("reference_case_units", f"case {index}: units", case=str(index))
241
+ )
242
+ continue
243
+ if check_scope and not self.weight_scope.contains(case.weight):
244
+ findings.append(
245
+ _block("reference_case_out_of_scope", f"case {index}", case=str(index))
246
+ )
247
+ result = self._evaluate_case(case, setup)
248
+ if not result.passed:
249
+ findings.append(
250
+ _block(
251
+ "reference_case_failed",
252
+ f"case {index}: expected {_expected(case)}, got {_got(result)}",
253
+ case=str(index),
254
+ expected=_expected(case),
255
+ computed=str(result.computed) if result.computed else "",
256
+ error=result.error or "",
257
+ )
258
+ )
259
+ return findings
260
+
261
+
262
+ # --- history -------------------------------------------------------------------------------
263
+
264
+
265
+ class EventKind(StrEnum):
266
+ CREATED = "created"
267
+ DERIVED = "derived"
268
+ EDITED = "edited"
269
+ SUBMITTED = "submitted"
270
+ REJECTED = "rejected"
271
+ APPROVED = "approved"
272
+ PUBLISHED = "published"
273
+ SUPERSEDED = "superseded"
274
+ WITHDRAWN = "withdrawn"
275
+
276
+
277
+ @dataclass(frozen=True, slots=True)
278
+ class LifecycleEvent:
279
+ kind: EventKind
280
+ at: datetime
281
+ actor: str | None = None
282
+ reason: str | None = None
283
+ effective_from: date | None = None
284
+ fallback_note: str | None = None
285
+
286
+
287
+ # --- states --------------------------------------------------------------------------------
288
+
289
+
290
+ class StateName(StrEnum):
291
+ DRAFT = "draft"
292
+ IN_REVIEW = "in_review"
293
+ APPROVED = "approved"
294
+ PUBLISHED = "published"
295
+ SUPERSEDED = "superseded"
296
+ WITHDRAWN = "withdrawn"
297
+
298
+
299
+ class Operation(StrEnum):
300
+ """What a person can do with a version; reviewing means approving or rejecting."""
301
+
302
+ EDIT = "edit"
303
+ SUBMIT = "submit"
304
+ REVIEW = "review"
305
+ WITHDRAW = "withdraw"
306
+ DERIVE = "derive"
307
+
308
+
309
+ class LifecycleState:
310
+ """Base state: every operation is illegal unless a subclass allows it."""
311
+
312
+ name: ClassVar[StateName]
313
+ editable: ClassVar[bool] = False
314
+
315
+ def allows(self, transition: str) -> bool:
316
+ """True when this state overrides the base refusal for the transition."""
317
+ return getattr(type(self), transition) is not getattr(LifecycleState, transition)
318
+
319
+ def submit(self, v: ProtocolVersion) -> LifecycleState:
320
+ raise self._illegal("submit")
321
+
322
+ def reject(self, v: ProtocolVersion) -> LifecycleState:
323
+ raise self._illegal("reject")
324
+
325
+ def approve(self, v: ProtocolVersion) -> LifecycleState:
326
+ raise self._illegal("approve")
327
+
328
+ def publish(self, v: ProtocolVersion) -> LifecycleState:
329
+ raise self._illegal("publish")
330
+
331
+ def supersede(self, v: ProtocolVersion) -> LifecycleState:
332
+ raise self._illegal("supersede")
333
+
334
+ def withdraw(self, v: ProtocolVersion) -> LifecycleState:
335
+ raise self._illegal("withdraw")
336
+
337
+ def derive(self, v: ProtocolVersion) -> None:
338
+ raise self._illegal("derive a draft from")
339
+
340
+ def _illegal(self, operation: str) -> IllegalTransitionError:
341
+ return IllegalTransitionError(f"cannot {operation} a version that is {self.name.value}")
342
+
343
+
344
+ class Draft(LifecycleState):
345
+ name = StateName.DRAFT
346
+ editable = True
347
+
348
+ def submit(self, v: ProtocolVersion) -> LifecycleState:
349
+ return InReview()
350
+
351
+
352
+ class InReview(LifecycleState):
353
+ name = StateName.IN_REVIEW
354
+
355
+ def reject(self, v: ProtocolVersion) -> LifecycleState:
356
+ return Draft()
357
+
358
+ def approve(self, v: ProtocolVersion) -> LifecycleState:
359
+ return Approved()
360
+
361
+
362
+ class Approved(LifecycleState):
363
+ name = StateName.APPROVED
364
+
365
+ def publish(self, v: ProtocolVersion) -> LifecycleState:
366
+ return Published()
367
+
368
+ def supersede(self, v: ProtocolVersion) -> LifecycleState:
369
+ """A newer version was published first; this one never comes into force."""
370
+ return Superseded()
371
+
372
+ def withdraw(self, v: ProtocolVersion) -> LifecycleState:
373
+ return Withdrawn()
374
+
375
+
376
+ class Published(LifecycleState):
377
+ name = StateName.PUBLISHED
378
+
379
+ def supersede(self, v: ProtocolVersion) -> LifecycleState:
380
+ return Superseded()
381
+
382
+ def withdraw(self, v: ProtocolVersion) -> LifecycleState:
383
+ return Withdrawn()
384
+
385
+ def derive(self, v: ProtocolVersion) -> None:
386
+ return None
387
+
388
+
389
+ class Superseded(LifecycleState):
390
+ name = StateName.SUPERSEDED
391
+
392
+ def withdraw(self, v: ProtocolVersion) -> LifecycleState:
393
+ return Withdrawn()
394
+
395
+
396
+ class Withdrawn(LifecycleState):
397
+ name = StateName.WITHDRAWN
398
+
399
+
400
+ _STATES: dict[StateName, type[LifecycleState]] = {
401
+ cls.name: cls for cls in (Draft, InReview, Approved, Published, Superseded, Withdrawn)
402
+ }
403
+
404
+
405
+ # --- the aggregate root --------------------------------------------------------------------
406
+
407
+
408
+ class ProtocolVersion:
409
+ """One version of a protocol. All changes go through its operations."""
410
+
411
+ def __init__(
412
+ self,
413
+ *,
414
+ id: str,
415
+ protocol_id: str,
416
+ number: int,
417
+ author: str,
418
+ content: VersionContent,
419
+ based_on: str | None = None,
420
+ change_reason: str = "",
421
+ reviewer: str | None = None,
422
+ effective_from: date | None = None,
423
+ state: StateName = StateName.DRAFT,
424
+ events: tuple[LifecycleEvent, ...] = (),
425
+ ) -> None:
426
+ self.id = id
427
+ self.protocol_id = protocol_id
428
+ self.number = number
429
+ self.author = author
430
+ self.based_on = based_on
431
+ self._content = content
432
+ self._change_reason = change_reason
433
+ self._reviewer = reviewer
434
+ self._effective_from = effective_from
435
+ self._state: LifecycleState = _STATES[state]()
436
+ self._events: list[LifecycleEvent] = list(events)
437
+
438
+ # --- creation ---------------------------------------------------------------------------
439
+
440
+ @classmethod
441
+ def create_first_draft(
442
+ cls, *, id: str, protocol_id: str, author: Actor, content: VersionContent, at: datetime
443
+ ) -> ProtocolVersion:
444
+ _require_role(author, UserRole.EDITOR, "create a protocol")
445
+ return cls(
446
+ id=id,
447
+ protocol_id=protocol_id,
448
+ number=1,
449
+ author=author.user_id,
450
+ content=content,
451
+ events=(LifecycleEvent(EventKind.CREATED, at, author.user_id),),
452
+ )
453
+
454
+ def derive_draft(self, *, id: str, author: Actor, at: datetime) -> ProtocolVersion:
455
+ """Prototype: copy this published version into a new Draft with the next number."""
456
+ self._state.derive(self)
457
+ _require_role(author, UserRole.EDITOR, "start a change")
458
+ return ProtocolVersion(
459
+ id=id,
460
+ protocol_id=self.protocol_id,
461
+ number=self.number + 1,
462
+ author=author.user_id,
463
+ content=self._content,
464
+ based_on=self.id,
465
+ events=(LifecycleEvent(EventKind.DERIVED, at, author.user_id, reason=self.id),),
466
+ )
467
+
468
+ # --- read access ------------------------------------------------------------------------
469
+
470
+ @property
471
+ def content(self) -> VersionContent:
472
+ return self._content
473
+
474
+ @property
475
+ def state(self) -> StateName:
476
+ return self._state.name
477
+
478
+ @property
479
+ def change_reason(self) -> str:
480
+ return self._change_reason
481
+
482
+ @property
483
+ def reviewer(self) -> str | None:
484
+ return self._reviewer
485
+
486
+ @property
487
+ def effective_from(self) -> date | None:
488
+ return self._effective_from
489
+
490
+ @property
491
+ def events(self) -> tuple[LifecycleEvent, ...]:
492
+ return tuple(self._events)
493
+
494
+ def is_usable(self) -> bool:
495
+ """Only a Published version reaches the calculator."""
496
+ return self._state.name is StateName.PUBLISHED
497
+
498
+ def is_review_overdue(self, today: date) -> bool:
499
+ """Only a version in force can be overdue; a flag, not an expiry (DA-04)."""
500
+ due = self._content.review_due
501
+ return self.is_usable() and due is not None and due < today
502
+
503
+ def permitted(self, actor: Actor) -> frozenset[Operation]:
504
+ """What this person may do now. The operations themselves enforce the same rules."""
505
+ checks = {
506
+ Operation.EDIT: (self._state.editable, lambda: self._require_author(actor, "edit")),
507
+ Operation.SUBMIT: (
508
+ self._state.allows("submit"),
509
+ lambda: self._require_author(actor, "submit"),
510
+ ),
511
+ Operation.REVIEW: (
512
+ self._state.allows("approve"),
513
+ lambda: self._require_reviewer(actor, "review"),
514
+ ),
515
+ Operation.WITHDRAW: (
516
+ self._state.allows("withdraw"),
517
+ lambda: _require_role(actor, UserRole.APPROVER, "withdraw a version"),
518
+ ),
519
+ Operation.DERIVE: (
520
+ self._state.allows("derive"),
521
+ lambda: _require_role(actor, UserRole.EDITOR, "start a change"),
522
+ ),
523
+ }
524
+ return frozenset(
525
+ op for op, (state_allows, check) in checks.items() if state_allows and _passes(check)
526
+ )
527
+
528
+ def last_event(self, kind: EventKind) -> LifecycleEvent | None:
529
+ return next((e for e in reversed(self._events) if e.kind is kind), None)
530
+
531
+ # --- transitions ------------------------------------------------------------------------
532
+
533
+ def edit(
534
+ self, actor: Actor, *, content: VersionContent, change_reason: str, at: datetime
535
+ ) -> None:
536
+ if not self._state.editable:
537
+ raise IllegalTransitionError(f"cannot edit a version that is {self.state.value}")
538
+ self._require_author(actor, "edit")
539
+ self._content = content
540
+ self._change_reason = change_reason
541
+ self._record(EventKind.EDITED, at, actor.user_id)
542
+
543
+ def submit(
544
+ self,
545
+ actor: Actor,
546
+ *,
547
+ at: datetime,
548
+ rounding_keys: Collection[str],
549
+ setup: SingleDoseSetup | None = None,
550
+ ) -> None:
551
+ self._require_author(actor, "submit")
552
+ if self.based_on is not None and not self._change_reason.strip():
553
+ raise GuardFailedError(
554
+ "a reason for the change is required",
555
+ [_block("missing_field", "change reason", field="change_reason")],
556
+ )
557
+ blocking = [f for f in self._content.validate(rounding_keys, setup) if f.blocks]
558
+ if blocking:
559
+ raise GuardFailedError("the version is not complete or not consistent", blocking)
560
+ self._move(self._state.submit(self), EventKind.SUBMITTED, at, actor.user_id)
561
+
562
+ def reject(self, reviewer: Actor, *, reason: str, at: datetime) -> None:
563
+ self._require_reviewer(reviewer, "reject")
564
+ if not reason.strip():
565
+ raise GuardFailedError("a reason is required to reject")
566
+ self._move(
567
+ self._state.reject(self), EventKind.REJECTED, at, reviewer.user_id, reason=reason
568
+ )
569
+
570
+ def approve(
571
+ self,
572
+ reviewer: Actor,
573
+ *,
574
+ effective_from: date,
575
+ today: date,
576
+ at: datetime,
577
+ rounding_keys: Collection[str],
578
+ setup: SingleDoseSetup | None = None,
579
+ ) -> None:
580
+ """Guard G1: another person with the approver role, complete data, all cases pass."""
581
+ next_state = self._state.approve(self)
582
+ self._require_reviewer(reviewer, "approve")
583
+ blocking = [f for f in self._content.validate(rounding_keys, setup) if f.blocks]
584
+ if blocking:
585
+ raise GuardFailedError("the version does not pass guard G1", blocking)
586
+ if effective_from < today:
587
+ raise GuardFailedError("the start date cannot be in the past")
588
+ self._reviewer = reviewer.user_id
589
+ self._effective_from = effective_from
590
+ self._move(
591
+ next_state, EventKind.APPROVED, at, reviewer.user_id, effective_from=effective_from
592
+ )
593
+
594
+ def publish(self, *, today: date, at: datetime) -> None:
595
+ """Guard G2: the start date has been reached. Called by activation, not by a person."""
596
+ next_state = self._state.publish(self)
597
+ if self._effective_from is None or today < self._effective_from:
598
+ raise GuardFailedError("the start date has not been reached")
599
+ self._move(next_state, EventKind.PUBLISHED, at)
600
+
601
+ def supersede(self, *, at: datetime) -> None:
602
+ self._move(self._state.supersede(self), EventKind.SUPERSEDED, at)
603
+
604
+ def withdraw(self, actor: Actor, *, reason: str, fallback_note: str, at: datetime) -> None:
605
+ next_state = self._state.withdraw(self)
606
+ _require_role(actor, UserRole.APPROVER, "withdraw a version")
607
+ if not reason.strip():
608
+ raise GuardFailedError("a reason is required to withdraw")
609
+ self._move(
610
+ next_state,
611
+ EventKind.WITHDRAWN,
612
+ at,
613
+ actor.user_id,
614
+ reason=reason,
615
+ fallback_note=fallback_note.strip() or None,
616
+ )
617
+
618
+ # --- helpers ----------------------------------------------------------------------------
619
+
620
+ def _move(
621
+ self,
622
+ state: LifecycleState,
623
+ kind: EventKind,
624
+ at: datetime,
625
+ actor: str | None = None,
626
+ *,
627
+ reason: str | None = None,
628
+ effective_from: date | None = None,
629
+ fallback_note: str | None = None,
630
+ ) -> None:
631
+ self._state = state
632
+ self._record(
633
+ kind,
634
+ at,
635
+ actor,
636
+ reason=reason,
637
+ effective_from=effective_from,
638
+ fallback_note=fallback_note,
639
+ )
640
+
641
+ def _record(
642
+ self,
643
+ kind: EventKind,
644
+ at: datetime,
645
+ actor: str | None,
646
+ *,
647
+ reason: str | None = None,
648
+ effective_from: date | None = None,
649
+ fallback_note: str | None = None,
650
+ ) -> None:
651
+ self._events.append(LifecycleEvent(kind, at, actor, reason, effective_from, fallback_note))
652
+
653
+ def _require_author(self, actor: Actor, action: str) -> None:
654
+ if actor.user_id != self.author:
655
+ raise PermissionDeniedError(f"only the author may {action} this draft")
656
+
657
+ def _require_reviewer(self, reviewer: Actor, action: str) -> None:
658
+ if reviewer.user_id == self.author:
659
+ raise PermissionDeniedError(f"the author cannot {action} their own change")
660
+ _require_role(reviewer, UserRole.APPROVER, action)
661
+
662
+ def __repr__(self) -> str:
663
+ return f"<ProtocolVersion {self.id} #{self.number} {self.state.value}>"
664
+
665
+
666
+ def _require_role(actor: Actor, role: UserRole, action: str) -> None:
667
+ if not actor.has(role):
668
+ raise PermissionDeniedError(f"the {role.value} role is needed to {action}")
669
+
670
+
671
+ def _passes(check: Callable[[], None]) -> bool:
672
+ try:
673
+ check()
674
+ except PermissionDeniedError:
675
+ return False
676
+ return True
677
+
678
+
679
+ def _expected(case: ReferenceCase) -> str:
680
+ if case.expected_volume is None:
681
+ return str(case.expected)
682
+ return f"{case.expected} / {case.expected_volume}"
683
+
684
+
685
+ def _got(result: CaseResult) -> str:
686
+ return f"{result.computed}" + (f" ({result.error})" if result.error else "")
687
+
688
+
689
+ def _block(code: str, message: str, **params: str) -> Finding:
690
+ return Finding(code, Severity.BLOCK, message or code, params)
doseframe/py.typed ADDED
File without changes