cometric 0.1.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 (83) hide show
  1. cometric/__init__.py +50 -0
  2. cometric/cli.py +210 -0
  3. cometric/core/__init__.py +0 -0
  4. cometric/core/api.py +835 -0
  5. cometric/core/engine.py +1386 -0
  6. cometric/core/enums.py +273 -0
  7. cometric/core/fingerprint.py +91 -0
  8. cometric/core/issues.py +68 -0
  9. cometric/core/ledger.py +165 -0
  10. cometric/core/models.py +450 -0
  11. cometric/core/money.py +110 -0
  12. cometric/core/packs.py +446 -0
  13. cometric/core/periods.py +102 -0
  14. cometric/core/predicates.py +139 -0
  15. cometric/core/quantities.py +138 -0
  16. cometric/core/schema.py +97 -0
  17. cometric/core/templates.py +338 -0
  18. cometric/core/tiers.py +78 -0
  19. cometric/core/validation.py +738 -0
  20. cometric/examples/case_a.json +293 -0
  21. cometric/examples/case_b.json +212 -0
  22. cometric/examples/case_c.json +233 -0
  23. cometric/examples/case_d.json +253 -0
  24. cometric/examples/case_e.json +258 -0
  25. cometric/examples/case_f.json +298 -0
  26. cometric/examples/case_g.json +243 -0
  27. cometric/examples/case_h.json +271 -0
  28. cometric/examples/spec_example.json +134 -0
  29. cometric/mcp/__init__.py +0 -0
  30. cometric/mcp/__main__.py +3 -0
  31. cometric/mcp/server.py +470 -0
  32. cometric/packs/alsp/concepts/provider_types.yaml +154 -0
  33. cometric/packs/alsp/concepts/service_categories.yaml +132 -0
  34. cometric/packs/alsp/concepts/unit_templates.yaml +132 -0
  35. cometric/packs/alsp/coverage.yaml +17 -0
  36. cometric/packs/alsp/evidence/claims.yaml +446 -0
  37. cometric/packs/alsp/evidence/sources.yaml +545 -0
  38. cometric/packs/alsp/overlays/levers.yaml +82 -0
  39. cometric/packs/alsp/overlays/mechanisms.yaml +19 -0
  40. cometric/packs/alsp/overlays/metrics.yaml +15 -0
  41. cometric/packs/alsp/overlays/pricing_models.yaml +186 -0
  42. cometric/packs/alsp/pack.yaml +9 -0
  43. cometric/packs/alsp/rules/rules.yaml +303 -0
  44. cometric/packs/base/concepts/automation_structures.yaml +207 -0
  45. cometric/packs/base/concepts/billing_bases.yaml +239 -0
  46. cometric/packs/base/concepts/cost_categories.yaml +494 -0
  47. cometric/packs/base/concepts/dimensions.yaml +404 -0
  48. cometric/packs/base/concepts/fee_components.yaml +105 -0
  49. cometric/packs/base/concepts/layers.yaml +146 -0
  50. cometric/packs/base/concepts/levers.yaml +1449 -0
  51. cometric/packs/base/concepts/mechanisms.yaml +295 -0
  52. cometric/packs/base/concepts/metrics.yaml +1149 -0
  53. cometric/packs/base/concepts/negotiation_exchanges.yaml +226 -0
  54. cometric/packs/base/concepts/offers.yaml +88 -0
  55. cometric/packs/base/concepts/pricing_models.yaml +821 -0
  56. cometric/packs/base/concepts/schema_map.yaml +1100 -0
  57. cometric/packs/base/concepts/selection_framework.yaml +215 -0
  58. cometric/packs/base/concepts/selection_heuristics.yaml +285 -0
  59. cometric/packs/base/coverage.yaml +33 -0
  60. cometric/packs/base/evidence/claims.yaml +442 -0
  61. cometric/packs/base/evidence/sources.yaml +293 -0
  62. cometric/packs/base/excluded.yaml +42 -0
  63. cometric/packs/base/pack.yaml +10 -0
  64. cometric/packs/base/rules/rules.yaml +521 -0
  65. cometric/packs/consulting/concepts/consulting_concepts.yaml +82 -0
  66. cometric/packs/consulting/concepts/provider_types.yaml +35 -0
  67. cometric/packs/consulting/concepts/service_categories.yaml +41 -0
  68. cometric/packs/consulting/concepts/unit_templates.yaml +36 -0
  69. cometric/packs/consulting/coverage.yaml +17 -0
  70. cometric/packs/consulting/overlays/pricing_models.yaml +29 -0
  71. cometric/packs/consulting/pack.yaml +11 -0
  72. cometric/packs/consulting/rules/rules.yaml +45 -0
  73. cometric/packs/consulting/templates/capped_tm.json +132 -0
  74. cometric/packs/consulting/templates/fixed_fee_plus_success.json +163 -0
  75. cometric/packs/consulting/templates/phased_fixed_fee.json +133 -0
  76. cometric/packs/consulting/templates/retainer_hours_drawdown.json +144 -0
  77. cometric/packs/consulting/templates/role_based_tm.json +123 -0
  78. cometric/py.typed +0 -0
  79. cometric-0.1.0.dist-info/METADATA +137 -0
  80. cometric-0.1.0.dist-info/RECORD +83 -0
  81. cometric-0.1.0.dist-info/WHEEL +4 -0
  82. cometric-0.1.0.dist-info/entry_points.txt +2 -0
  83. cometric-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,1386 @@
1
+ """Monthly calculation engine: evaluation order (4.5), costs (5.2), capacity (5.3), metrics (5.4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass, field
7
+ from decimal import Decimal
8
+
9
+ from .enums import (
10
+ AdjustmentType,
11
+ AggregationScope,
12
+ Avoidability,
13
+ BreachMode,
14
+ CalculationMethod,
15
+ ChargeCadence,
16
+ CommitmentKind,
17
+ CostBehavior,
18
+ CostPeriod,
19
+ MarginLayer,
20
+ OutcomeDirection,
21
+ OutcomeForm,
22
+ ProrationPolicy,
23
+ Recognition,
24
+ RoundingLevel,
25
+ ShortfallRule,
26
+ TestedAgainst,
27
+ TierScope,
28
+ TransitionView,
29
+ )
30
+ from .issues import CometricError, Issues, pointer
31
+ from .ledger import EntitlementLedger
32
+ from .models import (
33
+ ArrangementVersion,
34
+ CostComponent,
35
+ CostPolicy,
36
+ Engagement,
37
+ FeeComponent,
38
+ MoneyPolicy,
39
+ Scenario,
40
+ )
41
+ from .money import MINOR_UNITS, ONE, ZERO, allocate_exact, allocate_weighted, quantize, safe_ratio
42
+ from .periods import (
43
+ DaySpan,
44
+ Month,
45
+ is_period_end,
46
+ month_index,
47
+ month_of,
48
+ month_span,
49
+ month_str,
50
+ months_between,
51
+ overlap,
52
+ period_key,
53
+ period_truncated,
54
+ )
55
+ from .quantities import Quantities, build_quantities
56
+ from .tiers import incremental, price
57
+
58
+ ENGINE_VERSION = "0.1.0"
59
+
60
+ STEP_NAMES = {
61
+ 4: "price",
62
+ 5: "collar",
63
+ 6: "discount",
64
+ 7: "minimum",
65
+ 8: "performance",
66
+ 9: "cap",
67
+ }
68
+
69
+
70
+ @dataclass
71
+ class FeeLine:
72
+ period: str
73
+ step: int
74
+ ref: str
75
+ component: str | None
76
+ kind: str
77
+ amount: Decimal
78
+ rounded: Decimal
79
+ formula: str
80
+ quantity: Decimal | None = None
81
+ unit: str | None = None
82
+ rate: Decimal | None = None
83
+ segment: str | None = None
84
+ version: str | None = None
85
+
86
+ def as_dict(self) -> dict:
87
+ return {
88
+ "period": self.period,
89
+ "step": self.step,
90
+ "stage": STEP_NAMES.get(self.step, str(self.step)),
91
+ "ref": self.ref,
92
+ "component": self.component,
93
+ "kind": self.kind,
94
+ "quantity": self.quantity,
95
+ "unit": self.unit,
96
+ "rate": self.rate,
97
+ "amount_unrounded": self.amount,
98
+ "amount": self.rounded,
99
+ "formula": self.formula,
100
+ "segment": self.segment,
101
+ "version": self.version,
102
+ }
103
+
104
+
105
+ @dataclass
106
+ class CostLine:
107
+ period: str
108
+ ref: str
109
+ category: str
110
+ layer: MarginLayer
111
+ amount: Decimal
112
+ rounded: Decimal
113
+ formula: str
114
+ incurred: Decimal | None = None
115
+ amortized: Decimal | None = None
116
+ unavoidable: bool = False
117
+ driver_quantity: Decimal | None = None
118
+
119
+ def as_dict(self) -> dict:
120
+ return {
121
+ "period": self.period,
122
+ "ref": self.ref,
123
+ "category": self.category,
124
+ "layer": str(self.layer),
125
+ "amount_unrounded": self.amount,
126
+ "amount": self.rounded,
127
+ "formula": self.formula,
128
+ "incurred": self.incurred,
129
+ "amortized": self.amortized,
130
+ "driver_quantity": self.driver_quantity,
131
+ }
132
+
133
+
134
+ @dataclass
135
+ class Segment:
136
+ span: DaySpan
137
+ version: ArrangementVersion | None
138
+ factor: Decimal # share of the month's days
139
+
140
+
141
+ @dataclass
142
+ class CalculationResult:
143
+ data: dict
144
+ fee_lines: list[FeeLine]
145
+ cost_lines: list[CostLine]
146
+ ledger: list[dict]
147
+ issues: Issues
148
+ feasible: bool
149
+ status: str = "ok"
150
+ extras: dict = field(default_factory=dict)
151
+
152
+
153
+ def effective_money_policy(engagement: Engagement) -> MoneyPolicy:
154
+ mp = engagement.money_policy or MoneyPolicy()
155
+ scale = (
156
+ mp.rounding_scale
157
+ if mp.rounding_scale is not None
158
+ else MINOR_UNITS.get(engagement.currency, 2)
159
+ )
160
+ return MoneyPolicy(
161
+ rounding_mode=mp.rounding_mode, rounding_scale=scale, rounding_level=mp.rounding_level
162
+ )
163
+
164
+
165
+ class Calculator:
166
+ def __init__(
167
+ self,
168
+ engagement: Engagement,
169
+ scenario: Scenario,
170
+ cost_policy: CostPolicy | None,
171
+ issues: Issues | None = None,
172
+ ):
173
+ self.e = engagement
174
+ self.s = scenario
175
+ self.policy = cost_policy
176
+ self.issues = issues if issues is not None else Issues()
177
+ self.money = effective_money_policy(engagement)
178
+ self.scale = self.money.rounding_scale
179
+ self.anchor = month_of(engagement.start_date)
180
+ self.eng_last = month_of(engagement.end_date)
181
+ hz_from = scenario.horizon.from_ if scenario.horizon else engagement.start_date
182
+ hz_to = scenario.horizon.to if scenario.horizon else engagement.end_date
183
+ self.first = max(month_of(hz_from), self.anchor)
184
+ self.last = min(month_of(hz_to), self.eng_last)
185
+ self.months = months_between(self.first, self.last)
186
+ self.fee_lines: list[FeeLine] = []
187
+ self.cost_lines: list[CostLine] = []
188
+ self.ledgers: dict[str, EntitlementLedger] = {}
189
+ self.acc: dict[tuple, Decimal] = {}
190
+ self.pending_overage: dict[str, Decimal] = {}
191
+ self.feasible = True
192
+ self.capacity_state: dict[str, dict] = {}
193
+ self.backlog: dict[str, Decimal] = {}
194
+ self.overflow: dict[tuple[str, Month], Decimal] = {}
195
+ self.unit_kinds = {u.code: u.kind for u in engagement.unit_definitions}
196
+
197
+ # -- helpers --------------------------------------------------------------------------
198
+
199
+ def r(self, amount: Decimal) -> Decimal:
200
+ if self.money.rounding_level == RoundingLevel.LINE_ITEM:
201
+ return quantize(amount, self.scale, str(self.money.rounding_mode))
202
+ return amount
203
+
204
+ def fee(
205
+ self,
206
+ m: Month,
207
+ step: int,
208
+ ref: str,
209
+ component: str | None,
210
+ kind: str,
211
+ amount: Decimal,
212
+ formula: str,
213
+ **kw,
214
+ ) -> FeeLine:
215
+ line = FeeLine(
216
+ month_str(m), step, ref, component, kind, amount, self.r(amount), formula, **kw
217
+ )
218
+ self.fee_lines.append(line)
219
+ return line
220
+
221
+ def acc_add(self, key: tuple, value: Decimal) -> Decimal:
222
+ before = self.acc.get(key, ZERO)
223
+ self.acc[key] = before + value
224
+ return before
225
+
226
+ def qty(self, quantities: Quantities, name: str | None, m: Month, path: str) -> Decimal:
227
+ if name is None:
228
+ self.issues.error("MISSING_QUANTITY_SOURCE", "component needs a quantity_source", path)
229
+ raise CometricError(self.issues)
230
+ key = name[len("scenario.") :] if name.startswith("scenario.") else name
231
+ v = quantities.get(key, m)
232
+ if v is None:
233
+ self.issues.error(
234
+ "MISSING_ASSUMPTION", f"scenario has no assumption named {key!r}", path
235
+ )
236
+ raise CometricError(self.issues)
237
+ return v
238
+
239
+ def weighted_qty(
240
+ self, quantities: Quantities, base: str, table_id: str | None, m: Month, path: str
241
+ ) -> Decimal:
242
+ key = base[len("scenario.") :] if base.startswith("scenario.") else base
243
+ tables = [t for t in self.e.weight_tables if table_id is None or t.id == table_id]
244
+ if not tables:
245
+ self.issues.error("UNKNOWN_WEIGHT_TABLE", f"no weight table {table_id!r}", path)
246
+ raise CometricError(self.issues)
247
+ table = tables[0]
248
+ total = ZERO
249
+ found = False
250
+ for band in table.bands:
251
+ v = quantities.get(f"{key}.{band.code}", m)
252
+ if v is not None:
253
+ found = True
254
+ total += v * band.weight
255
+ if not found:
256
+ self.issues.error(
257
+ "MISSING_ASSUMPTION", f"scenario has no band quantities named {key}.<band>", path
258
+ )
259
+ raise CometricError(self.issues)
260
+ return total
261
+
262
+ # -- segments -------------------------------------------------------------------------
263
+
264
+ def version_span(self, v: ArrangementVersion) -> DaySpan:
265
+ return DaySpan(
266
+ max(v.effective_from, self.e.start_date),
267
+ min(v.effective_to or self.e.end_date, self.e.end_date),
268
+ )
269
+
270
+ def segments(self, m: Month) -> list[Segment]:
271
+ ms = month_span(m)
272
+ raw: list[tuple[DaySpan, ArrangementVersion | None]] = []
273
+ for v in self.e.arrangement_versions:
274
+ ov = overlap(self.version_span(v), ms)
275
+ if ov:
276
+ raw.append((ov, v))
277
+ raw.sort(key=lambda x: x[0].start)
278
+ # fill gaps with unpriced spans so boundaries are explicit
279
+ filled: list[tuple[DaySpan, ArrangementVersion | None]] = []
280
+ cursor = ms.start
281
+ for span, v in raw:
282
+ if span.start > cursor:
283
+ filled.append(
284
+ (DaySpan(cursor, span.start.fromordinal(span.start.toordinal() - 1)), None)
285
+ )
286
+ filled.append((span, v))
287
+ cursor = span.end.fromordinal(span.end.toordinal() + 1)
288
+ if cursor <= ms.end:
289
+ filled.append((DaySpan(cursor, ms.end), None))
290
+ # apply proration policy at each mid-month boundary
291
+ i = 1
292
+ while i < len(filled):
293
+ (sa, va), (sb, vb) = filled[i - 1], filled[i]
294
+ policy = (vb.proration_policy if vb else None) or (va.proration_policy if va else None)
295
+ if va is vb:
296
+ filled[i - 1 : i + 1] = [(DaySpan(sa.start, sb.end), va)]
297
+ continue
298
+ if policy == ProrationPolicy.FULL_MONTH_FROM_NEXT:
299
+ filled[i - 1 : i + 1] = [(DaySpan(sa.start, sb.end), va)]
300
+ continue
301
+ if policy == ProrationPolicy.FULL_MONTH_FROM_CURRENT:
302
+ filled[i - 1 : i + 1] = [(DaySpan(sa.start, sb.end), vb)]
303
+ continue
304
+ i += 1
305
+ dim = Decimal(ms.days)
306
+ return [Segment(span, v, Decimal(span.days) / dim) for span, v in filled]
307
+
308
+ # -- run ------------------------------------------------------------------------------
309
+
310
+ def run(self) -> CalculationResult:
311
+ quantities = build_quantities(self.e, self.s, self.months, self.issues)
312
+ if self.issues.has_errors:
313
+ raise CometricError(self.issues)
314
+ self.quantities = quantities
315
+ plan = self.e.delivery_plan
316
+ if plan is not None and plan.standard_rate_card:
317
+ base = (plan.worked_hours_source or "").removeprefix("scenario.")
318
+ if not base or not any(
319
+ quantities.has(f"{base}.{rr.role}") for rr in plan.standard_rate_card
320
+ ):
321
+ self.issues.error(
322
+ "MISSING_ASSUMPTION",
323
+ f"a standard rate card needs worked hours as scenario quantities {base or '<worked_hours_source>'}.<role>",
324
+ pointer("engagement", "delivery_plan", "worked_hours_source"),
325
+ )
326
+ raise CometricError(self.issues)
327
+ self._derive_demand_hours(quantities)
328
+ per_month: dict[Month, dict] = {}
329
+ for m in self.months:
330
+ self._capacity(m, quantities)
331
+ segs = self.segments(m)
332
+ self._fees_for_month(m, segs, quantities)
333
+ self._costs_for_month(m, quantities)
334
+ ended = self.last == self.eng_last
335
+ for led in self.ledgers.values():
336
+ led.finish(self.last, ended)
337
+ for p in led.check_invariant():
338
+ self.issues.error("LEDGER_INVARIANT", p)
339
+ for m in self.months:
340
+ per_month[m] = self._month_totals(m)
341
+ data = self._aggregate(per_month, quantities)
342
+ ledger = [e.as_dict() for led in self.ledgers.values() for e in led.entries]
343
+ status = "ok" if self.feasible else "infeasible"
344
+ return CalculationResult(
345
+ data, self.fee_lines, self.cost_lines, ledger, self.issues, self.feasible, status
346
+ )
347
+
348
+ # -- fees -----------------------------------------------------------------------------
349
+
350
+ def _fees_for_month(self, m: Month, segs: list[Segment], quantities: Quantities) -> None:
351
+ priced = [s for s in segs if s.version is not None]
352
+ if not priced:
353
+ return
354
+ split = len(priced) > 1
355
+ if split:
356
+ self.issues.info(
357
+ "SEGMENTED_MONTH",
358
+ f"{month_str(m)} spans {len(priced)} contract versions",
359
+ "",
360
+ month=month_str(m),
361
+ )
362
+ last_version = priced[-1].version
363
+ # open entitlement periods for this month (once per month)
364
+ for v in {id(s.version): s.version for s in priced}.values():
365
+ for ent in v.entitlements:
366
+ key = period_key(ent.accumulation_period, m, self.anchor)
367
+ led = self.ledgers.get(ent.id) or EntitlementLedger(ent)
368
+ self.ledgers[ent.id] = led
369
+ led.start_month(m, key, ent, v.id)
370
+ for idx, seg in enumerate(priced):
371
+ share = (lambda q, _i=idx: self._split(q, priced, _i)) if split else (lambda q: q)
372
+ self._price_segment(m, seg, share, quantities, first=idx == 0)
373
+ self._period_end_overage(m, last_version)
374
+ self._period_end_outcome(m, last_version)
375
+ self._adjustments(m, last_version)
376
+
377
+ def _split(self, q: Decimal, priced: list[Segment], idx: int) -> Decimal:
378
+ weights = [Decimal(s.span.days) for s in priced]
379
+ scale = 0 if q == q.to_integral_value() else 4
380
+ shares = allocate_weighted(q, weights, scale)
381
+ return shares[idx]
382
+
383
+ def _price_segment(
384
+ self, m: Month, seg: Segment, share, quantities: Quantities, first: bool = True
385
+ ) -> None:
386
+ v = seg.version
387
+ assert v is not None
388
+ schedules = {r.id: r for r in v.rate_schedules}
389
+ ents = {e.id: e for e in v.entitlements}
390
+ vi = self.e.arrangement_versions.index(v)
391
+ label = f"{seg.span.start.isoformat()}..{seg.span.end.isoformat()}"
392
+ for ci, c in enumerate(v.components):
393
+ path = pointer("engagement", "arrangement_versions", vi, "components", ci)
394
+ cspan = DaySpan(c.effective_period.from_, c.effective_period.to or self.e.end_date)
395
+ ov = overlap(cspan, seg.span)
396
+ if ov is None:
397
+ continue
398
+ factor = Decimal(ov.days) / Decimal(month_span(m).days)
399
+ kw = {"segment": label, "version": v.id}
400
+ meth = c.calculation_method
401
+ if meth == CalculationMethod.FIXED_RECURRING:
402
+ base = self._fixed_month_amount(c, m)
403
+ if base is None:
404
+ continue
405
+ amt = base * factor
406
+ self.fee(m, 4, c.id, c.id, "fixed", amt, f"{base} x {factor:.6f} of month", **kw)
407
+ elif meth == CalculationMethod.FIXED_PROJECT:
408
+ if first:
409
+ for p in c.payment_schedule:
410
+ if p.month == month_str(m):
411
+ self.fee(
412
+ m,
413
+ 4,
414
+ c.id,
415
+ c.id,
416
+ "project_payment",
417
+ p.amount,
418
+ "scheduled project payment",
419
+ **kw,
420
+ )
421
+ elif meth == CalculationMethod.DEDICATED_RESOURCE:
422
+ for res in c.resources:
423
+ amt = res.fte * res.rate_per_fte_month * factor
424
+ self.fee(
425
+ m,
426
+ 4,
427
+ c.id,
428
+ c.id,
429
+ "resource",
430
+ amt,
431
+ f"{res.fte} FTE x {res.rate_per_fte_month} x {factor:.6f}",
432
+ quantity=res.fte,
433
+ unit="FTE",
434
+ rate=res.rate_per_fte_month,
435
+ **kw,
436
+ )
437
+ elif meth == CalculationMethod.TIME:
438
+ base_name = c.quantity_source or ""
439
+ for rr in c.role_rates:
440
+ hours = share(
441
+ self.qty(quantities, f"{base_name}.{rr.role}", m, path + "/quantity_source")
442
+ )
443
+ self.fee(
444
+ m,
445
+ 4,
446
+ c.id,
447
+ c.id,
448
+ "time",
449
+ hours * rr.rate,
450
+ f"{hours} h x {rr.rate}",
451
+ quantity=hours,
452
+ unit="hours",
453
+ rate=rr.rate,
454
+ **kw,
455
+ )
456
+ elif meth in (CalculationMethod.UNIT_OUTPUT, CalculationMethod.WEIGHTED_UNIT_OUTPUT):
457
+ if meth == CalculationMethod.UNIT_OUTPUT:
458
+ q = share(self.qty(quantities, c.quantity_source, m, path + "/quantity_source"))
459
+ else:
460
+ q = share(
461
+ self.weighted_qty(
462
+ quantities,
463
+ c.quantity_source or "",
464
+ c.weight_table_id,
465
+ m,
466
+ path + "/quantity_source",
467
+ )
468
+ )
469
+ sched = schedules[c.rate_schedule_id]
470
+ key = ("tier", sched.id, period_key(sched.accumulation_period, m, self.anchor))
471
+ before = self.acc_add(key, q)
472
+ amt = incremental(before, q, sched.tiers, sched.tier_method)
473
+ self.fee(
474
+ m,
475
+ 4,
476
+ c.id,
477
+ c.id,
478
+ "unit",
479
+ amt,
480
+ f"{sched.tier_method} schedule {sched.id} over units {before}..{before + q}",
481
+ quantity=q,
482
+ unit=c.unit,
483
+ **kw,
484
+ )
485
+ elif meth == CalculationMethod.ALLOWANCE_OVERAGE:
486
+ ent = ents[c.entitlement_id]
487
+ q = share(self.qty(quantities, c.quantity_source, m, path + "/quantity_source"))
488
+ led = self.ledgers[ent.id]
489
+ in_allow, excess = led.consume(m, q)
490
+ sched = schedules[c.rate_schedule_id]
491
+ elig_key = ("elig", sched.id, period_key(sched.accumulation_period, m, self.anchor))
492
+ elig_before = self.acc_add(elig_key, q)
493
+ if ent.overage_recognition == Recognition.PERIOD_END:
494
+ self.pending_overage[c.id] = self.pending_overage.get(c.id, ZERO) + excess
495
+ continue
496
+ self._price_overage(m, c, sched, excess, elig_before + in_allow, **kw)
497
+ elif meth == CalculationMethod.OUTCOME_ADJUSTMENT:
498
+ o = c.outcome
499
+ measured = share(self.qty(quantities, o.metric, m, path + "/outcome/metric"))
500
+ self.acc_add(
501
+ ("outcome", c.id, period_key(o.accumulation_period, m, self.anchor)), measured
502
+ )
503
+ else:
504
+ self.issues.error(
505
+ "METHOD_NOT_SUPPORTED", f"{meth} is post-v1", path + "/calculation_method"
506
+ )
507
+ raise CometricError(self.issues)
508
+ # indexation applies to this segment's priced lines
509
+ for adj in v.adjustments:
510
+ if adj.type != AdjustmentType.INDEXATION or adj.percent is None:
511
+ continue
512
+ years = (month_index(m) - month_index(self.anchor)) // 12
513
+ if years <= 0:
514
+ continue
515
+ mult = (ONE + adj.percent) ** years - ONE
516
+ for line in [
517
+ ln
518
+ for ln in self.fee_lines
519
+ if ln.period == month_str(m)
520
+ and ln.step == 4
521
+ and ln.segment == label
522
+ and ln.kind != "indexation"
523
+ ]:
524
+ if adj.applies_to and line.component not in adj.applies_to:
525
+ continue
526
+ self.fee(
527
+ m,
528
+ 4,
529
+ adj.id,
530
+ line.component,
531
+ "indexation",
532
+ line.amount * mult,
533
+ f"{line.amount} x ((1+{adj.percent})^{years} - 1)",
534
+ segment=label,
535
+ version=v.id,
536
+ )
537
+
538
+ def _price_overage(
539
+ self, m: Month, c: FeeComponent, sched, excess: Decimal, elig_position: Decimal, **kw
540
+ ) -> None:
541
+ if sched.tier_scope == TierScope.EXCESS_ONLY:
542
+ key = ("tier", sched.id, period_key(sched.accumulation_period, m, self.anchor))
543
+ before = self.acc_add(key, excess)
544
+ amt = incremental(before, excess, sched.tiers, sched.tier_method)
545
+ formula = (
546
+ f"{excess} excess units on {sched.tier_method} schedule {sched.id} from {before}"
547
+ )
548
+ else:
549
+ amt = incremental(elig_position, excess, sched.tiers, sched.tier_method)
550
+ formula = f"{excess} excess units priced at eligible positions {elig_position}..{elig_position + excess}"
551
+ self.fee(m, 4, c.id, c.id, "overage", amt, formula, quantity=excess, unit=c.unit, **kw)
552
+
553
+ def _period_end_outcome(self, m: Month, v: ArrangementVersion) -> None:
554
+ """Outcome fees are measured over the accumulation period and charged at its end."""
555
+ for c in v.components:
556
+ if c.calculation_method != CalculationMethod.OUTCOME_ADJUSTMENT or c.outcome is None:
557
+ continue
558
+ o = c.outcome
559
+ if period_truncated(o.accumulation_period, m, self.anchor, self.last, self.eng_last):
560
+ self.issues.warn(
561
+ "TRUE_UP_OUTSIDE_HORIZON",
562
+ f"outcome fee for {c.id} is measured after the horizon",
563
+ )
564
+ continue
565
+ if not is_period_end(o.accumulation_period, m, self.anchor, self.eng_last):
566
+ continue
567
+ total = self.acc.get(
568
+ ("outcome", c.id, period_key(o.accumulation_period, m, self.anchor)), ZERO
569
+ )
570
+ higher = o.direction == OutcomeDirection.HIGHER_IS_BETTER
571
+ if o.form == OutcomeForm.SHARE:
572
+ improvement = (total - o.baseline) if higher else (o.baseline - total)
573
+ fee = o.share_percent * o.attribution_percent * max(ZERO, improvement)
574
+ formula = f"{o.share_percent} share x {o.attribution_percent} attributed x max(0, improvement {improvement} vs baseline {o.baseline})"
575
+ elif o.form == OutcomeForm.SUCCESS:
576
+ met = total >= o.target if higher else total <= o.target
577
+ fee = o.success_amount if met else ZERO
578
+ formula = f"success amount {o.success_amount} if {o.metric} {total} {'>=' if higher else '<='} target {o.target}: {'met' if met else 'not met'}"
579
+ else:
580
+ fee = o.share_percent * o.attribution_percent * max(ZERO, total)
581
+ formula = (
582
+ f"{o.share_percent} x {o.attribution_percent} attributed x outcome {total}"
583
+ )
584
+ if o.cap_amount is not None and fee > o.cap_amount:
585
+ formula += f"; capped at {o.cap_amount}"
586
+ fee = o.cap_amount
587
+ self.fee(
588
+ m, 4, c.id, c.id, "outcome", fee, formula, quantity=total, unit=o.unit, version=v.id
589
+ )
590
+
591
+ def _period_end_overage(self, m: Month, v: ArrangementVersion) -> None:
592
+ schedules = {r.id: r for r in v.rate_schedules}
593
+ ents = {e.id: e for e in v.entitlements}
594
+ for c in v.components:
595
+ if c.calculation_method != CalculationMethod.ALLOWANCE_OVERAGE:
596
+ continue
597
+ ent = ents.get(c.entitlement_id or "")
598
+ if ent is None or ent.overage_recognition != Recognition.PERIOD_END:
599
+ continue
600
+ if period_truncated(ent.accumulation_period, m, self.anchor, self.last, self.eng_last):
601
+ self.issues.warn(
602
+ "TRUE_UP_OUTSIDE_HORIZON",
603
+ f"overage true-up for {c.id} falls after the horizon",
604
+ "",
605
+ )
606
+ continue
607
+ if is_period_end(ent.accumulation_period, m, self.anchor, self.eng_last):
608
+ pending = self.pending_overage.pop(c.id, ZERO)
609
+ self._price_overage(
610
+ m, c, schedules[c.rate_schedule_id], pending, ZERO, version=v.id
611
+ )
612
+
613
+ def _fixed_month_amount(self, c: FeeComponent, m: Month) -> Decimal | None:
614
+ amt = c.fixed_amount or ZERO
615
+ start = month_of(c.effective_period.from_)
616
+ idx = month_index(m) - month_index(start)
617
+ if idx < 0:
618
+ return None
619
+ cad = c.charge_cadence
620
+ if cad == ChargeCadence.MONTHLY:
621
+ return amt
622
+ if cad == ChargeCadence.QUARTERLY:
623
+ return allocate_exact(amt, 3, self.scale)[(m[1] - 1) % 3]
624
+ if cad == ChargeCadence.ANNUAL:
625
+ return allocate_exact(amt, 12, self.scale)[idx % 12]
626
+ if cad == ChargeCadence.ONE_TIME:
627
+ return amt if idx == 0 else None
628
+ return None
629
+
630
+ # -- adjustments (steps 5 to 9) --------------------------------------------------------
631
+
632
+ def _subtotal(
633
+ self, m: Month, max_step: int, components: set[str] | None, include_unattributed: bool
634
+ ) -> Decimal:
635
+ ps = month_str(m)
636
+ total = ZERO
637
+ for ln in self.fee_lines:
638
+ if ln.period != ps or ln.step > max_step:
639
+ continue
640
+ if ln.component is None:
641
+ if include_unattributed:
642
+ total += ln.rounded
643
+ elif components is None or ln.component in components:
644
+ total += ln.rounded
645
+ return total
646
+
647
+ def _component_totals(self, m: Month, max_step: int) -> dict[str, Decimal]:
648
+ ps = month_str(m)
649
+ out: dict[str, Decimal] = {}
650
+ for ln in self.fee_lines:
651
+ if ln.period == ps and ln.step <= max_step and ln.component is not None:
652
+ out[ln.component] = out.get(ln.component, ZERO) + ln.rounded
653
+ return out
654
+
655
+ def _adjustments(self, m: Month, v: ArrangementVersion) -> None:
656
+ schedules = {r.id: r for r in v.rate_schedules}
657
+ comps = {c.id: c for c in v.components}
658
+ # step 5: collars
659
+ for adj in v.adjustments:
660
+ if adj.type != AdjustmentType.COLLAR:
661
+ continue
662
+ c = comps[adj.component_id]
663
+ q = self.qty(self.quantities, c.quantity_source, m, "")
664
+ base, alt = schedules[c.rate_schedule_id], schedules[adj.outside_rate_schedule_id]
665
+ if adj.upper is not None and q > adj.upper:
666
+ extra = q - adj.upper
667
+ amt = price(extra, alt.tiers, alt.tier_method) - (
668
+ price(q, base.tiers, base.tier_method)
669
+ - price(adj.upper, base.tiers, base.tier_method)
670
+ )
671
+ self.fee(
672
+ m,
673
+ 5,
674
+ adj.id,
675
+ c.id,
676
+ "collar",
677
+ amt,
678
+ f"{extra} units above band repriced on {alt.id}",
679
+ quantity=extra,
680
+ )
681
+ elif adj.lower is not None and q < adj.lower:
682
+ amt = price(q, alt.tiers, alt.tier_method) - price(q, base.tiers, base.tier_method)
683
+ self.fee(
684
+ m,
685
+ 5,
686
+ adj.id,
687
+ c.id,
688
+ "collar",
689
+ amt,
690
+ f"{q} units below band repriced on {alt.id}",
691
+ quantity=q,
692
+ )
693
+ # step 6: discounts and rebates
694
+ totals5 = self._component_totals(m, 5)
695
+ for adj in v.adjustments:
696
+ if adj.type == AdjustmentType.DISCOUNT and adj.percent is not None:
697
+ for cid, amt in totals5.items():
698
+ if adj.applies_to and cid not in adj.applies_to:
699
+ continue
700
+ self.fee(
701
+ m, 6, adj.id, cid, "discount", -adj.percent * amt, f"-{adj.percent} x {amt}"
702
+ )
703
+ elif adj.type == AdjustmentType.REBATE and adj.percent is not None:
704
+ scope = set(adj.applies_to) if adj.applies_to else None
705
+ key = ("rebate", adj.id, period_key(adj.accumulation_period, m, self.anchor))
706
+ self.acc_add(key, self._subtotal(m, 5, scope, False))
707
+ if is_period_end(adj.accumulation_period, m, self.anchor, self.eng_last):
708
+ period_total = self.acc[key]
709
+ if adj.threshold is None or period_total >= adj.threshold:
710
+ self.fee(
711
+ m,
712
+ 6,
713
+ adj.id,
714
+ None,
715
+ "rebate",
716
+ -adj.percent * period_total,
717
+ f"-{adj.percent} x period subtotal {period_total}",
718
+ )
719
+ # step 7: minimums tested gross or net of discounts
720
+ for com in v.commitments:
721
+ if (
722
+ com.kind == CommitmentKind.MINIMUM_SPEND
723
+ and com.tested_against != TestedAgainst.NET_OF_CREDITS
724
+ ):
725
+ self._minimum(m, com, v)
726
+ # step 8: performance
727
+ scope_all = None
728
+ sub7 = self._subtotal(m, 7, scope_all, True)
729
+ for adj in v.adjustments:
730
+ if adj.type not in (
731
+ AdjustmentType.SLA_CREDIT,
732
+ AdjustmentType.BONUS,
733
+ AdjustmentType.HOLDBACK,
734
+ ):
735
+ continue
736
+ scope = set(adj.applies_to) if adj.applies_to else None
737
+ base = self._subtotal(m, 7, scope, scope is None)
738
+ trig = self.quantities.get(adj.trigger, m) if adj.trigger else None
739
+ trig = trig if trig is not None else ZERO
740
+ pct = adj.percent or ZERO
741
+ if adj.type == AdjustmentType.HOLDBACK:
742
+ released = min(trig, ONE)
743
+ amt = -pct * base * (ONE - released)
744
+ formula = f"-{pct} x {base} withheld unless released ({released})"
745
+ else:
746
+ raw = pct * base * trig
747
+ if adj.cap_percent is not None:
748
+ raw = min(raw, adj.cap_percent * base)
749
+ amt = -raw if adj.type == AdjustmentType.SLA_CREDIT else raw
750
+ formula = f"{pct} x {base} x {trig} events, cap {adj.cap_percent}"
751
+ if amt != 0:
752
+ self.fee(m, 8, adj.id, None, adj.type.lower(), amt, formula)
753
+ _ = sub7
754
+ # step 7b: minimums tested net of credits
755
+ for com in v.commitments:
756
+ if (
757
+ com.kind == CommitmentKind.MINIMUM_SPEND
758
+ and com.tested_against == TestedAgainst.NET_OF_CREDITS
759
+ ):
760
+ self._minimum(m, com, v, step_basis=8)
761
+ # step 9: caps
762
+ for adj in v.adjustments:
763
+ if adj.type != AdjustmentType.CAP or adj.amount is None:
764
+ continue
765
+ scope = set(adj.applies_to) if adj.applies_to else None
766
+ month_total = self._subtotal(m, 8, scope, scope is None)
767
+ key = ("cap", adj.id, period_key(adj.accumulation_period, m, self.anchor))
768
+ before = self.acc_add(key, month_total)
769
+ after = before + month_total
770
+ reduction = max(ZERO, after - adj.amount) - max(ZERO, before - adj.amount)
771
+ if reduction != 0:
772
+ self.fee(
773
+ m,
774
+ 9,
775
+ adj.id,
776
+ None,
777
+ "cap",
778
+ -reduction,
779
+ f"cap {adj.amount} per {adj.accumulation_period}; cumulative {after}",
780
+ )
781
+
782
+ def _minimum(self, m: Month, com, v: ArrangementVersion, step_basis: int | None = None) -> None:
783
+ if com.aggregation_scope == AggregationScope.ENGAGEMENT:
784
+ scope, unattributed = None, True
785
+ elif com.aggregation_scope == AggregationScope.COMPONENT:
786
+ scope, unattributed = set(com.component_ids), False
787
+ else:
788
+ scope, unattributed = (
789
+ {c.id for c in v.components if c.service_id == com.service_id},
790
+ False,
791
+ )
792
+ basis = step_basis or (5 if com.tested_against == TestedAgainst.GROSS else 6)
793
+ tested = self._subtotal(m, basis, scope, unattributed)
794
+ key = ("min", com.id, period_key(com.accumulation_period, m, self.anchor))
795
+ if com.shortfall_rule == ShortfallRule.PER_SEGMENT:
796
+ shortfall = max(ZERO, com.amount - tested)
797
+ if shortfall > 0:
798
+ self.fee(
799
+ m,
800
+ 7,
801
+ com.id,
802
+ None,
803
+ "minimum_shortfall",
804
+ shortfall,
805
+ f"minimum {com.amount} - tested {tested}",
806
+ )
807
+ return
808
+ self.acc_add(key, tested)
809
+ if period_truncated(com.accumulation_period, m, self.anchor, self.last, self.eng_last):
810
+ self.issues.warn(
811
+ "TRUE_UP_OUTSIDE_HORIZON", f"minimum true-up for {com.id} falls after the horizon"
812
+ )
813
+ return
814
+ if is_period_end(com.accumulation_period, m, self.anchor, self.eng_last):
815
+ total = self.acc[key]
816
+ shortfall = max(ZERO, com.amount - total)
817
+ if shortfall > 0:
818
+ self.fee(
819
+ m,
820
+ 7,
821
+ com.id,
822
+ None,
823
+ "minimum_shortfall",
824
+ shortfall,
825
+ f"minimum {com.amount} - period total {total}",
826
+ )
827
+
828
+ # -- capacity -------------------------------------------------------------------------
829
+
830
+ def _derive_demand_hours(self, quantities: Quantities) -> None:
831
+ plan = self.e.delivery_plan
832
+ if plan is None or not plan.production_standards:
833
+ return
834
+ for m in self.months:
835
+ hours = ZERO
836
+ for ps in plan.production_standards:
837
+ name = f"{ps.unit}.{ps.band}" if ps.band else ps.unit
838
+ q = quantities.get(name, m)
839
+ if q is not None:
840
+ hours += q * ps.hours_per_unit
841
+ quantities.set("demand_hours", m, hours)
842
+ quantities.units["demand_hours"] = "hours"
843
+
844
+ def _breach_mode(self) -> BreachMode | None:
845
+ if self.s.breach_mode is not None:
846
+ return self.s.breach_mode
847
+ return self.e.delivery_plan.breach_mode if self.e.delivery_plan else None
848
+
849
+ def _capacity(self, m: Month, quantities: Quantities) -> None:
850
+ plan = self.e.delivery_plan
851
+ if plan is None:
852
+ return
853
+ mode = self._breach_mode()
854
+ for li, lim in enumerate(plan.capacity):
855
+ st = self.capacity_state.setdefault(
856
+ lim.id,
857
+ {
858
+ "demand": ZERO,
859
+ "served": ZERO,
860
+ "overflow": ZERO,
861
+ "capacity": ZERO,
862
+ "periods": set(),
863
+ },
864
+ )
865
+ key = period_key(lim.accumulation_period, m, self.anchor)
866
+ if key not in st["periods"]:
867
+ st["periods"].add(key)
868
+ st["capacity"] += lim.amount
869
+ base = quantities.get(lim.quantity, m)
870
+ if base is None:
871
+ self.issues.error(
872
+ "MISSING_ASSUMPTION",
873
+ f"capacity {lim.id} measures {lim.quantity!r}, which the scenario does not provide",
874
+ pointer("engagement", "delivery_plan", "capacity", li, "quantity"),
875
+ )
876
+ raise CometricError(self.issues)
877
+ carried = self.backlog.get(lim.id, ZERO)
878
+ demand = base + carried
879
+ acc_key = ("cap_use", lim.id, key)
880
+ before = self.acc.get(acc_key, ZERO)
881
+ over = max(ZERO, before + demand - lim.amount) - max(ZERO, before - lim.amount)
882
+ st["demand"] += base
883
+ if over <= 0:
884
+ self.acc[acc_key] = before + demand
885
+ st["served"] += demand
886
+ self.backlog[lim.id] = ZERO
887
+ if carried:
888
+ quantities.set(lim.quantity, m, demand)
889
+ continue
890
+ if mode == BreachMode.OVERFLOW_COST:
891
+ self.acc[acc_key] = before + demand
892
+ st["served"] += demand
893
+ st["overflow"] += over
894
+ self.overflow[(lim.id, m)] = over
895
+ if lim.overflow_cost_rate is None:
896
+ self.issues.error(
897
+ "OVERFLOW_RATE_REQUIRED",
898
+ f"capacity {lim.id} breached under OVERFLOW_COST but has no overflow_cost_rate",
899
+ pointer(
900
+ "engagement", "delivery_plan", "capacity", li, "overflow_cost_rate"
901
+ ),
902
+ )
903
+ raise CometricError(self.issues)
904
+ self.issues.warn(
905
+ "CAPACITY_BREACH",
906
+ f"{month_str(m)}: {over} {lim.quantity} above capacity {lim.id}; overflow cost applied",
907
+ "",
908
+ month=month_str(m),
909
+ overflow=str(over),
910
+ mode="OVERFLOW_COST",
911
+ )
912
+ elif mode == BreachMode.BACKLOG:
913
+ served = demand - over
914
+ self.acc[acc_key] = before + served
915
+ st["served"] += served
916
+ self.backlog[lim.id] = over
917
+ quantities.set(lim.quantity, m, served)
918
+ self.issues.warn(
919
+ "CAPACITY_BREACH",
920
+ f"{month_str(m)}: {over} {lim.quantity} carried as backlog; SLA risk",
921
+ "",
922
+ month=month_str(m),
923
+ backlog=str(over),
924
+ mode="BACKLOG",
925
+ )
926
+ else:
927
+ self.acc[acc_key] = before + demand
928
+ st["served"] += demand
929
+ st["overflow"] += over
930
+ self.feasible = False
931
+ self.issues.error(
932
+ "CAPACITY_BREACH",
933
+ f"{month_str(m)}: demand exceeds capacity {lim.id} by {over} and no breach handling is declared"
934
+ if mode is None
935
+ else f"{month_str(m)}: demand exceeds capacity {lim.id} by {over}; scenario infeasible",
936
+ "",
937
+ month=month_str(m),
938
+ overflow=str(over),
939
+ mode=str(mode) if mode else None,
940
+ )
941
+
942
+ # -- costs ----------------------------------------------------------------------------
943
+
944
+ def _layer(self, cc: CostComponent) -> MarginLayer:
945
+ assert self.policy is not None
946
+ return self.policy.mapping[cc.category]
947
+
948
+ def _driver(self, quantities: Quantities, driver: str | None, m: Month, path: str) -> Decimal:
949
+ if driver is None:
950
+ self.issues.error("DRIVER_REQUIRED", "variable cost needs a driver", path)
951
+ raise CometricError(self.issues)
952
+ if driver.startswith("weighted:"):
953
+ rest = driver[len("weighted:") :]
954
+ base, _, table = rest.partition(":")
955
+ return self.weighted_qty(quantities, base, table or None, m, path)
956
+ return self.qty(quantities, driver, m, path)
957
+
958
+ def _costs_for_month(self, m: Month, quantities: Quantities) -> None:
959
+ plan = self.e.delivery_plan
960
+ if plan is None or self.policy is None:
961
+ return
962
+ ps = month_str(m)
963
+ replaced: dict[str, Decimal] = {}
964
+ for lim in plan.capacity:
965
+ over = self.overflow.get((lim.id, m), ZERO)
966
+ for cid in lim.overflow_replaces:
967
+ replaced[cid] = replaced.get(cid, ZERO) + over
968
+ for ci, cc in enumerate(plan.cost_components):
969
+ path = pointer("engagement", "delivery_plan", "cost_components", ci)
970
+ if cc.effective_period is not None:
971
+ cs = DaySpan(cc.effective_period.from_, cc.effective_period.to or self.e.end_date)
972
+ if overlap(cs, month_span(m)) is None:
973
+ continue
974
+ layer = self._layer(cc)
975
+ unavoidable = cc.avoidability == Avoidability.UNAVOIDABLE
976
+ b = cc.behavior
977
+ if b == CostBehavior.FIXED:
978
+ amt = self._fixed_cost_month(cc, m)
979
+ self._cost(ps, cc, layer, amt, f"fixed {cc.amount} per {cc.period}", unavoidable)
980
+ elif b == CostBehavior.VARIABLE:
981
+ q = self._driver(quantities, cc.driver, m, path + "/driver")
982
+ over = replaced.get(cc.id, ZERO)
983
+ self._cost(
984
+ ps,
985
+ cc,
986
+ layer,
987
+ (q - over) * (cc.rate or ZERO),
988
+ f"{q - over} x {cc.rate}",
989
+ unavoidable,
990
+ q - over,
991
+ )
992
+ if over > 0:
993
+ lim = next(lm for lm in plan.capacity if cc.id in lm.overflow_replaces)
994
+ self.cost_lines.append(
995
+ CostLine(
996
+ ps,
997
+ f"{lim.id}:overflow",
998
+ str(cc.category),
999
+ layer,
1000
+ over * lim.overflow_cost_rate,
1001
+ self.r(over * lim.overflow_cost_rate),
1002
+ f"{over} overflow x {lim.overflow_cost_rate}",
1003
+ driver_quantity=over,
1004
+ unavoidable=unavoidable,
1005
+ )
1006
+ )
1007
+ elif b == CostBehavior.STEP:
1008
+ q = self._driver(quantities, cc.driver, m, path + "/driver")
1009
+ steps = Decimal(math.ceil(q / cc.step_size)) if cc.step_size else ZERO
1010
+ self._cost(
1011
+ ps,
1012
+ cc,
1013
+ layer,
1014
+ steps * (cc.step_cost or ZERO),
1015
+ f"ceil({q}/{cc.step_size}) x {cc.step_cost}",
1016
+ unavoidable,
1017
+ q,
1018
+ )
1019
+ elif b == CostBehavior.TIERED_VARIABLE:
1020
+ q = self._driver(quantities, cc.driver, m, path + "/driver")
1021
+ key = ("ctier", cc.id, period_key(cc.accumulation_period, m, self.anchor))
1022
+ before = self.acc_add(key, q)
1023
+ from .enums import TierMethod
1024
+
1025
+ amt = incremental(before, q, cc.tiers, TierMethod.MARGINAL)
1026
+ self._cost(
1027
+ ps,
1028
+ cc,
1029
+ layer,
1030
+ amt,
1031
+ f"marginal tiers over {before}..{before + q}",
1032
+ unavoidable,
1033
+ q,
1034
+ )
1035
+ elif b == CostBehavior.ONE_TIME:
1036
+ inc, amo = self._one_time(cc, m)
1037
+ view = self.policy.transition_view
1038
+ amt = amo if view == TransitionView.AMORTIZED else inc
1039
+ if inc != 0 or amo != 0:
1040
+ line = self._cost(
1041
+ ps, cc, layer, amt, f"one-time cost ({view.lower()} view)", unavoidable
1042
+ )
1043
+ line.incurred, line.amortized = self.r(inc), self.r(amo)
1044
+
1045
+ def _cost(
1046
+ self,
1047
+ ps: str,
1048
+ cc: CostComponent,
1049
+ layer: MarginLayer,
1050
+ amt: Decimal,
1051
+ formula: str,
1052
+ unavoidable: bool,
1053
+ q: Decimal | None = None,
1054
+ ) -> CostLine:
1055
+ line = CostLine(
1056
+ ps,
1057
+ cc.id,
1058
+ str(cc.category),
1059
+ layer,
1060
+ amt,
1061
+ self.r(amt),
1062
+ formula,
1063
+ unavoidable=unavoidable,
1064
+ driver_quantity=q,
1065
+ )
1066
+ self.cost_lines.append(line)
1067
+ return line
1068
+
1069
+ def _fixed_cost_month(self, cc: CostComponent, m: Month) -> Decimal:
1070
+ amt = cc.amount or ZERO
1071
+ if cc.period == CostPeriod.MONTHLY:
1072
+ return amt
1073
+ anchor = month_of(cc.effective_period.from_) if cc.effective_period else self.anchor
1074
+ idx = month_index(m) - month_index(anchor)
1075
+ if cc.period == CostPeriod.ANNUAL:
1076
+ return allocate_exact(amt, 12, self.scale)[idx % 12]
1077
+ term_months = months_between(self.anchor, self.eng_last)
1078
+ return allocate_exact(amt, len(term_months), self.scale)[
1079
+ month_index(m) - month_index(self.anchor)
1080
+ ]
1081
+
1082
+ def _one_time(self, cc: CostComponent, m: Month) -> tuple[Decimal, Decimal]:
1083
+ schedule = [(ln.month, ln.amount) for ln in cc.incurred_schedule] or [
1084
+ (month_str(self.anchor), cc.amount or ZERO)
1085
+ ]
1086
+ inc = ZERO
1087
+ amo = ZERO
1088
+ for month_text, amount in schedule:
1089
+ y, mo = month_text.split("-")
1090
+ start = (int(y), int(mo))
1091
+ if start == m:
1092
+ inc += amount
1093
+ n = cc.amortize_months or 1
1094
+ offset = month_index(m) - month_index(start)
1095
+ if 0 <= offset < n:
1096
+ amo += allocate_exact(amount, n, self.scale)[offset]
1097
+ return inc, amo
1098
+
1099
+ # -- aggregation ----------------------------------------------------------------------
1100
+
1101
+ def _month_totals(self, m: Month) -> dict:
1102
+ ps = month_str(m)
1103
+ fees = [ln for ln in self.fee_lines if ln.period == ps]
1104
+ costs = [ln for ln in self.cost_lines if ln.period == ps]
1105
+
1106
+ def tot(values) -> Decimal:
1107
+ s = sum(values, ZERO)
1108
+ if self.money.rounding_level == RoundingLevel.PERIOD_TOTAL:
1109
+ return quantize(s, self.scale, str(self.money.rounding_mode))
1110
+ return s
1111
+
1112
+ layers = {layer: tot(c.rounded for c in costs if c.layer == layer) for layer in MarginLayer}
1113
+ incurred_adj = sum(
1114
+ ((c.incurred - c.rounded) for c in costs if c.incurred is not None), ZERO
1115
+ )
1116
+ worked, standard = self._worked_and_standard(m)
1117
+ return {
1118
+ "period": ps,
1119
+ "contractual_fee": tot(f.rounded for f in fees),
1120
+ "overage_fee": tot(f.rounded for f in fees if f.kind == "overage"),
1121
+ "outcome_fee": tot(f.rounded for f in fees if f.kind == "outcome"),
1122
+ "worked_hours": worked,
1123
+ "standard_value": standard,
1124
+ "commitment_shortfall": tot(f.rounded for f in fees if f.kind == "minimum_shortfall"),
1125
+ "layers": layers,
1126
+ "unavoidable_direct_cost": tot(
1127
+ c.rounded for c in costs if c.layer == MarginLayer.DIRECT_DELIVERY and c.unavoidable
1128
+ ),
1129
+ "by_category": _group(costs),
1130
+ "incurred_adjustment": incurred_adj,
1131
+ }
1132
+
1133
+ def _worked_and_standard(self, m: Month) -> tuple[Decimal, Decimal]:
1134
+ """Hours worked and their value at standard rates (spec 3.4 realization prerequisite)."""
1135
+ plan = self.e.delivery_plan
1136
+ if plan is None or not plan.standard_rate_card or not plan.worked_hours_source:
1137
+ return ZERO, ZERO
1138
+ base = plan.worked_hours_source.removeprefix("scenario.")
1139
+ hours = ZERO
1140
+ value = ZERO
1141
+ for rr in plan.standard_rate_card:
1142
+ h = self.quantities.get(f"{base}.{rr.role}", m) or ZERO
1143
+ hours += h
1144
+ value += h * rr.rate
1145
+ return hours, quantize(value, self.scale, str(self.money.rounding_mode))
1146
+
1147
+ def _aggregate(self, per_month: dict[Month, dict], quantities: Quantities) -> dict:
1148
+ periods = []
1149
+ cumulative = ZERO
1150
+ cumulative_incurred = ZERO
1151
+ payback = None
1152
+ first_one_time = self._first_one_time_month()
1153
+ went_negative = False
1154
+ for m in self.months:
1155
+ t = per_month[m]
1156
+ metrics = _metrics(t)
1157
+ cumulative += metrics["contribution_profit"]
1158
+ cumulative_incurred += metrics["contribution_profit"] - t["incurred_adjustment"]
1159
+ metrics["cumulative_contribution"] = cumulative
1160
+ metrics["cumulative_contribution_incurred"] = cumulative_incurred
1161
+ periods.append(metrics)
1162
+ if first_one_time is not None and month_index(m) >= month_index(first_one_time):
1163
+ if cumulative_incurred < 0:
1164
+ went_negative = True
1165
+ elif payback is None and went_negative:
1166
+ payback = month_str(m)
1167
+ years: dict[str, dict] = {}
1168
+ for y in sorted({m[0] for m in self.months}):
1169
+ years[str(y)] = _sum_metrics(
1170
+ [p for p, m in zip(periods, self.months, strict=True) if m[0] == y]
1171
+ )
1172
+ term = _sum_metrics(periods)
1173
+ term["transition_payback_month"] = payback
1174
+ self._client_metrics(term, quantities)
1175
+ return {"periods": periods, "years": years, "term": term}
1176
+
1177
+ def _first_one_time_month(self) -> Month | None:
1178
+ plan = self.e.delivery_plan
1179
+ if plan is None:
1180
+ return None
1181
+ months = []
1182
+ for cc in plan.cost_components:
1183
+ if cc.behavior == CostBehavior.ONE_TIME:
1184
+ for ln in cc.incurred_schedule or []:
1185
+ y, mo = ln.month.split("-")
1186
+ months.append((int(y), int(mo)))
1187
+ if not cc.incurred_schedule:
1188
+ months.append(self.anchor)
1189
+ return min(months) if months else None
1190
+
1191
+ def client_value_quantity(self) -> str | None:
1192
+ if self.e.client_value_unit:
1193
+ return self.e.client_value_unit
1194
+ for v in self.e.arrangement_versions:
1195
+ for c in v.components:
1196
+ if (
1197
+ c.calculation_method
1198
+ in (CalculationMethod.UNIT_OUTPUT, CalculationMethod.ALLOWANCE_OVERAGE)
1199
+ and c.quantity_source
1200
+ ):
1201
+ return c.quantity_source.removeprefix("scenario.")
1202
+ if (
1203
+ c.calculation_method == CalculationMethod.WEIGHTED_UNIT_OUTPUT
1204
+ and c.quantity_source
1205
+ ):
1206
+ return (
1207
+ "weighted:"
1208
+ + c.quantity_source.removeprefix("scenario.")
1209
+ + (f":{c.weight_table_id}" if c.weight_table_id else "")
1210
+ )
1211
+ return None
1212
+
1213
+ def _client_metrics(self, term: dict, quantities: Quantities) -> None:
1214
+ name = self.client_value_quantity()
1215
+ total_q = None
1216
+ if name:
1217
+ if name.startswith("weighted:"):
1218
+ rest = name[len("weighted:") :]
1219
+ base, _, table = rest.partition(":")
1220
+ try:
1221
+ total_q = sum(
1222
+ (
1223
+ self.weighted_qty(quantities, base, table or None, m, "")
1224
+ for m in self.months
1225
+ ),
1226
+ ZERO,
1227
+ )
1228
+ except CometricError:
1229
+ total_q = None
1230
+ elif quantities.has(name):
1231
+ total_q = sum((quantities.get(name, m) or ZERO for m in self.months), ZERO)
1232
+ fee = term["contractual_fee"]
1233
+ cost = term["direct_delivery_cost"] + term["engagement_avoidable_cost"]
1234
+ term["client_value_quantity"] = name
1235
+ term["client_consumed_quantity"] = total_q
1236
+ term["effective_client_unit_price"] = (
1237
+ safe_ratio(fee, total_q) if total_q is not None else None
1238
+ )
1239
+ term["cost_per_unit"] = safe_ratio(cost, total_q) if total_q is not None else None
1240
+ term["unit_contribution"] = (
1241
+ safe_ratio(term["contribution_profit"], total_q) if total_q is not None else None
1242
+ )
1243
+ # commitment utilization (CHI-001) across entitlement grants
1244
+ granted = sum((led.granted() for led in self.ledgers.values()), ZERO)
1245
+ consumed = sum((led.consumed() for led in self.ledgers.values()), ZERO)
1246
+ term["allowance_granted"] = granted if self.ledgers else None
1247
+ term["allowance_consumed"] = consumed if self.ledgers else None
1248
+ term["commitment_utilization"] = safe_ratio(consumed, granted) if self.ledgers else None
1249
+ # capacity (CHI-003, CHI-011)
1250
+ cap = []
1251
+ for lim_id, st in self.capacity_state.items():
1252
+ cap.append(
1253
+ {
1254
+ "id": lim_id,
1255
+ "demand": st["demand"],
1256
+ "served": st["served"],
1257
+ "capacity": st["capacity"],
1258
+ "overflow": st["overflow"],
1259
+ "backlog_end": self.backlog.get(lim_id, ZERO),
1260
+ "capacity_utilization": safe_ratio(st["served"], st["capacity"]),
1261
+ "capacity_service_mismatch": st["capacity"] - st["demand"],
1262
+ }
1263
+ )
1264
+ term["capacity"] = cap
1265
+ plan = self.e.delivery_plan
1266
+ if plan and plan.roles:
1267
+ months = Decimal(len(self.months))
1268
+ productive = sum(
1269
+ (
1270
+ r.fte * r.available_hours_per_fte_year * r.productive_ratio * months / 12
1271
+ for r in plan.roles
1272
+ ),
1273
+ ZERO,
1274
+ )
1275
+ safe = None
1276
+ if all(r.safe_utilization_ceiling is not None for r in plan.roles):
1277
+ safe = sum(
1278
+ (
1279
+ r.fte
1280
+ * r.available_hours_per_fte_year
1281
+ * r.productive_ratio
1282
+ * r.safe_utilization_ceiling
1283
+ * months
1284
+ / 12
1285
+ for r in plan.roles
1286
+ ),
1287
+ ZERO,
1288
+ )
1289
+ hours_name = plan.demand_hours_source or (
1290
+ "demand_hours" if quantities.has("demand_hours") else None
1291
+ )
1292
+ used = (
1293
+ quantities.total(hours_name) if hours_name and quantities.has(hours_name) else None
1294
+ )
1295
+ term["productive_hours"] = productive
1296
+ term["safe_capacity_hours"] = safe
1297
+ term["demand_hours"] = used
1298
+ term["productive_hours_utilization"] = (
1299
+ safe_ratio(used, productive) if used is not None else None
1300
+ )
1301
+ term["effective_client_price_per_used_hour"] = safe_ratio(fee, used) if used else None
1302
+ if safe is not None and used is not None and used > safe:
1303
+ self.issues.warn(
1304
+ "SAFE_CAPACITY_EXCEEDED", f"demand hours {used} exceed safe capacity {safe}"
1305
+ )
1306
+
1307
+
1308
+ def _group(costs: list[CostLine]) -> dict[str, Decimal]:
1309
+ out: dict[str, Decimal] = {}
1310
+ for c in costs:
1311
+ out[c.category] = out.get(c.category, ZERO) + c.rounded
1312
+ return out
1313
+
1314
+
1315
+ def _metrics(t: dict) -> dict:
1316
+ fee = t["contractual_fee"]
1317
+ L = t["layers"]
1318
+ direct = L[MarginLayer.DIRECT_DELIVERY]
1319
+ avoid = L[MarginLayer.ENGAGEMENT_AVOIDABLE]
1320
+ gp = fee - direct
1321
+ cp = gp - avoid
1322
+ return {
1323
+ "period": t.get("period"),
1324
+ "contractual_fee": fee,
1325
+ "overage_fee": t["overage_fee"],
1326
+ "outcome_fee": t["outcome_fee"],
1327
+ "commitment_shortfall": t["commitment_shortfall"],
1328
+ "worked_hours": t["worked_hours"],
1329
+ "standard_value": t["standard_value"],
1330
+ "direct_delivery_cost": direct,
1331
+ "engagement_avoidable_cost": avoid,
1332
+ "portfolio_shared_cost": L[MarginLayer.PORTFOLIO_SHARED],
1333
+ "corporate_overhead_cost": L[MarginLayer.CORPORATE_OVERHEAD],
1334
+ "unavoidable_direct_cost": t["unavoidable_direct_cost"],
1335
+ "costs_by_category": t["by_category"],
1336
+ "gross_profit": gp,
1337
+ "contribution_profit": cp,
1338
+ "full_cost_profit": cp
1339
+ - L[MarginLayer.PORTFOLIO_SHARED]
1340
+ - L[MarginLayer.CORPORATE_OVERHEAD],
1341
+ "gross_margin": safe_ratio(gp, fee),
1342
+ "contribution_margin": safe_ratio(cp, fee),
1343
+ "incurred_adjustment": t["incurred_adjustment"],
1344
+ }
1345
+
1346
+
1347
+ SUM_KEYS = [
1348
+ "contractual_fee",
1349
+ "overage_fee",
1350
+ "outcome_fee",
1351
+ "worked_hours",
1352
+ "standard_value",
1353
+ "commitment_shortfall",
1354
+ "direct_delivery_cost",
1355
+ "engagement_avoidable_cost",
1356
+ "portfolio_shared_cost",
1357
+ "corporate_overhead_cost",
1358
+ "unavoidable_direct_cost",
1359
+ "gross_profit",
1360
+ "contribution_profit",
1361
+ "full_cost_profit",
1362
+ ]
1363
+
1364
+
1365
+ def _sum_metrics(periods: list[dict]) -> dict:
1366
+ out: dict = {k: sum((p[k] for p in periods), ZERO) for k in SUM_KEYS}
1367
+ cats: dict[str, Decimal] = {}
1368
+ for p in periods:
1369
+ for k, v in p["costs_by_category"].items():
1370
+ cats[k] = cats.get(k, ZERO) + v
1371
+ out["costs_by_category"] = cats
1372
+ out["gross_margin"] = safe_ratio(out["gross_profit"], out["contractual_fee"])
1373
+ out["contribution_margin"] = safe_ratio(out["contribution_profit"], out["contractual_fee"])
1374
+ if out["standard_value"] > 0:
1375
+ out["realization"] = safe_ratio(out["contractual_fee"], out["standard_value"])
1376
+ out["write_down"] = out["standard_value"] - out["contractual_fee"]
1377
+ else:
1378
+ out["realization"] = None
1379
+ out["write_down"] = None
1380
+ out["effective_billing_rate"] = (
1381
+ safe_ratio(out["contractual_fee"], out["worked_hours"]) if out["worked_hours"] > 0 else None
1382
+ )
1383
+ out["months"] = len(periods)
1384
+ if out["contractual_fee"] == 0:
1385
+ out["margin_note"] = "Contractual fee is zero, so margins are undefined."
1386
+ return out