audit_report/periods.py
69 lines · 2730 bytes
4 symbols in this file
1"""Row-level period checks for rules that declare a timestamp column (ruleset schema 2).
2
3Evidence for a test period should be dated inside it and should not leave long
4stretches with no rows (a log that stops for three weeks, a ticket export that
5skips a month). :func:`check` reports, for one table and one period, which rows
6fall outside it, which rows have no readable date, and the gaps longer than
7``max_gap_days`` between the period start, each dated row, and the period end.
8
9Multi-table logic (joins across packages) is not part of the rule schema; it
10is done by analytics whose outputs are ordinary tables that rules evaluate.
11"""
12
13from __future__ import annotations
14
15from dataclasses import dataclass, field
16from datetime import date, timedelta
17
18
19@dataclass
20class PeriodCheck:
21 column: str
22 start: str
23 end: str
24 rows_in_period: int = 0
25 outside: list[dict] = field(default_factory=list) # {"row": index, "date": value}
26 undated: list[int] = field(default_factory=list)
27 gaps: list[dict] = field(default_factory=list) # {"from", "to", "days"}
28 first: str = ""
29 last: str = ""
30
31 @property
32 def ok(self) -> bool:
33 return not self.outside and not self.undated and not self.gaps
34
35
36def _date(value: str) -> date | None:
37 text = str(value or "").strip()[:10]
38 try:
39 return date.fromisoformat(text)
40 except ValueError:
41 return None
42
43
44def check(rows: list[dict], column: str, start: str, end: str, max_gap_days: int | None = None) -> PeriodCheck:
45 """Check that ``rows`` are dated by ``column`` within ``start``..``end`` (inclusive)."""
46 p_start, p_end = date.fromisoformat(start), date.fromisoformat(end)
47 result = PeriodCheck(column=column, start=start, end=end)
48 dated: list[date] = []
49 for i, row in enumerate(rows):
50 d = _date(row.get(column, ""))
51 if d is None:
52 result.undated.append(i)
53 elif d < p_start or d > p_end:
54 result.outside.append({"row": i, "date": d.isoformat()})
55 else:
56 dated.append(d)
57 result.rows_in_period = len(dated)
58 if dated:
59 result.first, result.last = min(dated).isoformat(), max(dated).isoformat()
60 if max_gap_days:
61 # Runs of consecutive days in the period with no rows; a sentinel past each edge.
62 prev = p_start - timedelta(days=1)
63 for d in [*sorted(set(dated)), p_end + timedelta(days=1)]:
64 empty = (d - prev).days - 1
65 if empty > max_gap_days:
66 first_empty, last_empty = prev + timedelta(days=1), d - timedelta(days=1)
67 result.gaps.append({"from": first_empty.isoformat(), "to": last_empty.isoformat(), "days": empty})
68 prev = d
69 return result