108 行
4.5 KiB
Python
108 行
4.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Deterministic plan/actual reconciliation for the local agenda."""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
try:
|
|
from .agenda_contracts import agenda_entry_from_activity, agenda_entry_from_plan, normalize_observed_activity
|
|
from .calendar_system import parse_datetime
|
|
except ImportError:
|
|
from agenda_contracts import agenda_entry_from_activity, agenda_entry_from_plan, normalize_observed_activity
|
|
from calendar_system import parse_datetime
|
|
|
|
PRIORITY = {"L0": 0, "L1": 1, "L2": 2, "L3": 3, "L4": 4, "L5": 5}
|
|
|
|
|
|
def _tokens(value: Any) -> set[str]:
|
|
text = str(value or "").lower()
|
|
return {token for token in text.replace(",", " ").replace("。", " ").split() if len(token) >= 2}
|
|
|
|
|
|
def _interval(item: dict[str, Any], now: datetime) -> tuple[datetime | None, datetime | None]:
|
|
try:
|
|
start = parse_datetime(item.get("start_at"), default=now)
|
|
except Exception:
|
|
return None, None
|
|
try:
|
|
end = parse_datetime(item.get("end_at"), default=start)
|
|
except Exception:
|
|
end = start
|
|
return start, end
|
|
|
|
|
|
def _overlaps(plan: dict[str, Any], activity: dict[str, Any], now: datetime) -> bool:
|
|
ps, pe = _interval(plan, now)
|
|
a_s, a_e = _interval(activity, now)
|
|
if not ps or not a_s:
|
|
return False
|
|
if pe <= ps:
|
|
pe = ps
|
|
if a_e <= a_s:
|
|
a_e = a_s
|
|
return ps < a_e and a_s < pe
|
|
|
|
|
|
def _title_matches(plan: dict[str, Any], activity: dict[str, Any]) -> bool:
|
|
plan_tokens = _tokens(plan.get("title") or plan.get("activity"))
|
|
activity_tokens = _tokens(activity.get("title"))
|
|
return bool(plan_tokens and activity_tokens and plan_tokens.intersection(activity_tokens))
|
|
|
|
|
|
def reconcile(
|
|
plans: list[dict[str, Any]],
|
|
activities: list[dict[str, Any]],
|
|
*,
|
|
now: datetime,
|
|
) -> dict[str, Any]:
|
|
normalized_activities = []
|
|
for activity in activities:
|
|
try:
|
|
normalized_activities.append(normalize_observed_activity(activity, now=now))
|
|
except Exception:
|
|
continue
|
|
matched: dict[str, list[dict[str, Any]]] = {}
|
|
used_activity_ids: set[str] = set()
|
|
results = []
|
|
entries = []
|
|
for raw_plan in plans:
|
|
plan = dict(raw_plan)
|
|
plan_id = str(plan.get("plan_id") or plan.get("event_id") or "")
|
|
overlaps = [activity for activity in normalized_activities if _overlaps(plan, activity, now)]
|
|
matching = [activity for activity in overlaps if _title_matches(plan, activity)]
|
|
selected = matching or overlaps
|
|
if selected:
|
|
matched[plan_id] = selected
|
|
used_activity_ids.update(str(item.get("activity_id")) for item in selected)
|
|
strongest = max((PRIORITY.get(str(item.get("evidence_level")), 0) for item in selected), default=0)
|
|
if matching:
|
|
status = "completed" if all(item.get("status") == "completed" for item in selected) else "active"
|
|
reason = "实际活动与计划主题和时间匹配"
|
|
elif strongest >= PRIORITY["L2"]:
|
|
status = "overridden"
|
|
reason = "实际活动覆盖原计划"
|
|
else:
|
|
status = "unknown"
|
|
reason = "活动证据不足"
|
|
plan["status"] = status
|
|
plan["reconciliation_reason"] = reason
|
|
plan["reconciled_activity_ids"] = [item.get("activity_id") for item in selected]
|
|
entries.append(agenda_entry_from_plan(plan, reason=reason))
|
|
entries.extend(agenda_entry_from_activity(item, source_refs=[plan_id, item.get("activity_id")]) for item in selected)
|
|
else:
|
|
if plan.get("status") not in {"cancelled", "deferred"} and _plan_is_past(plan, now):
|
|
plan["status"] = "unknown"
|
|
plan["reconciliation_reason"] = "窗口结束但没有足够实际证据"
|
|
entries.append(agenda_entry_from_plan(plan, reason=plan.get("reconciliation_reason", "")))
|
|
results.append(plan)
|
|
for activity in normalized_activities:
|
|
if str(activity.get("activity_id")) not in used_activity_ids:
|
|
entries.append(agenda_entry_from_activity(activity))
|
|
entries.sort(key=lambda item: (0 if item.get("kind") == "observed_activity" else 1, str(item.get("start_at") or "")))
|
|
return {"plans": results, "activities": normalized_activities, "entries": entries, "matched": matched}
|
|
|
|
|
|
def _plan_is_past(plan: dict[str, Any], now: datetime) -> bool:
|
|
_, end = _interval(plan, now)
|
|
return bool(end and end <= now)
|