Coverage for backend/django/Economics/shared/payloads.py: 100%

23 statements  

« prev     ^ index     » next       coverage.py v7.10.7, created at 2026-06-23 21:51 +0000

1from __future__ import annotations 

2 

3from datetime import date, datetime 

4from decimal import Decimal, ROUND_HALF_UP 

5from typing import Any 

6 

7 

8RESULT_AMOUNT_QUANTUM = Decimal("0.0001") 

9 

10 

11def result_amount(value: Decimal | None) -> Decimal | None: 

12 """Quantize persisted monetary/result values at the economics boundary.""" 

13 if value is None: 

14 return None 

15 return value.quantize(RESULT_AMOUNT_QUANTUM, rounding=ROUND_HALF_UP) 

16 

17 

18def warning_record(*, code: str, severity: str, message: str, context: dict[str, Any]) -> dict[str, Any]: 

19 """Return the normalized warning shape persisted in economics JSON payloads.""" 

20 return { 

21 "code": code, 

22 "severity": severity, 

23 "message": message, 

24 "context": json_ready(context), 

25 } 

26 

27 

28def warning_payload(warning) -> dict[str, Any]: 

29 """Serialize warning contracts without leaking Pydantic models.""" 

30 return { 

31 "code": warning.code, 

32 "severity": warning.severity, 

33 "message": warning.message, 

34 "context": json_ready(warning.context), 

35 } 

36 

37 

38def json_ready(value: Any) -> Any: 

39 """Convert economics payload values into deterministic JSON primitives.""" 

40 if isinstance(value, Decimal): 

41 return str(value) 

42 if isinstance(value, (datetime, date)): 

43 return value.isoformat() 

44 if isinstance(value, dict): 

45 return {str(key): json_ready(nested_value) for key, nested_value in value.items()} 

46 if isinstance(value, (list, tuple)): 

47 return [json_ready(nested_value) for nested_value in value] 

48 return value