"""Conservative historical attribution decisions and orchestration, without SQL.""" from dataclasses import dataclass from datetime import datetime, time, timedelta from zoneinfo import ZoneInfo from production_analytics.context import build_enlyze_production_order BERLIN = ZoneInfo("Europe/Berlin") def reconciliation_window(now: datetime, lookback_days: int = 3): """Previous N complete Berlin calendar days, as a half-open interval.""" if now.utcoffset() is None or isinstance(lookback_days, bool) or lookback_days < 1: raise ValueError("An aware clock and positive lookback-days are required") end = datetime.combine(now.astimezone(BERLIN).date(), time(), BERLIN) return end - timedelta(days=lookback_days), end @dataclass(frozen=True) class HistoricalRecord: table: str identity: tuple machine_id: str timestamp: datetime production_order: str run_id: str @dataclass(frozen=True) class Decision: record: HistoricalRecord order: str | None reason: str desired_run_id: str | None = None def decide(record, runs, confirmations, workplace, format_template): """Keep physical counter/run identities; never infer boundaries from ERP points.""" candidates = [r for r in runs if r.machine_id == record.machine_id and r.start.timestamp() <= record.timestamp.timestamp() and (r.end is None or record.timestamp.timestamp() < r.end.timestamp())] if len(candidates) != 1 or candidates[0].end is None: return Decision(record, None, "unresolved: missing or overlapping closed ENLYZE runs") run = candidates[0] orders = {build_enlyze_production_order(c.production_order, format_template) for c in confirmations if c.workplace == workplace and c.is_finished_goods and run.start.timestamp() < c.timestamp.timestamp() < run.end.timestamp()} if orders != {run.production_order}: return Decision(record, None, "unresolved: ERP evidence missing or conflicts with ENLYZE") return Decision(record, run.production_order, f"closed ENLYZE run {run.uuid} [{run.start.isoformat()}, " f"{run.end.isoformat()}) corroborated by ERP order {run.production_order}", run.uuid) def reconcile_machine(repository, source, erp, config, template, start, end, dry_run=False): records = repository.read(config.machine_id, start, end) runs = source.get_production_runs(config.machine_id) # Query complete overlapping runs so partial-window evidence cannot conceal conflicts. relevant = [r for r in runs if r.end is not None and r.start.timestamp() < end.timestamp() and r.end.timestamp() > start.timestamp()] evidence_start = min([start, *(r.start for r in relevant)], key=datetime.timestamp) evidence_end = max([end, *(r.end for r in relevant)], key=datetime.timestamp) confirmations = erp.get_confirmations( workplace=config.erp_workplace, start=evidence_start, end=evidence_end, ) decisions = [decide(r, runs, confirmations, config.erp_workplace, template) for r in records] # Require complete, unambiguous evidence, allowing orders within a physical run. decisions = repository.guard_runs(decisions) applied = repository.apply(decisions) if not dry_run else 0 return decisions, applied def grouped_counts(decisions): """Count physical identities and contiguous attribution segments, not snapshot rows.""" groups = {} for d in decisions: r = d.record key = (r.table, r.machine_id, r.identity[0], r.run_id) groups.setdefault(key, []).append(d) proposed_runs = unresolved_runs = corrected_segments = unresolved_segments = 0 for peers in groups.values(): proposed_runs += any(d.order is not None and d.order != d.record.production_order for d in peers) unresolved_runs += any(d.order is None for d in peers) streams = {} for d in peers: streams.setdefault(d.record.identity[3:], []).append(d) for stream in streams.values(): previous = object() for d in sorted(stream, key=lambda d: d.record.timestamp.timestamp()): state = (d.order, d.order is not None and d.order != d.record.production_order) if state != previous: unresolved_segments += d.order is None corrected_segments += state[1] previous = state return (len(groups), proposed_runs, corrected_segments, unresolved_runs, unresolved_segments)