"""Edit log helpers for change tracking.""" import json from datetime import datetime, timezone def compute_diff(old: dict, new: dict, exclude: set = None) -> dict: """Compare old and new values, return {field: [old, new]} for changed fields.""" if exclude is None: exclude = {"edit_log", "updated_at", "created_at", "id"} changes = {} for key, new_val in new.items(): if key in exclude: continue old_val = old.get(key) # Normalize for comparison old_str = str(old_val) if old_val is not None else "" new_str = str(new_val) if new_val is not None else "" if old_str != new_str: changes[key] = [old_str, new_str] return changes def append_entry(record, editor_name: str, changes: dict, reason: str = None): """Append an edit log entry to a record's edit_log JSON list.""" log = list(record.edit_log) if record.edit_log else [] entry = { "editor": editor_name, "time": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "changes": changes, } if reason: entry["reason"] = reason log.append(entry) record.edit_log = log def init_entry(record, creator_name: str): """Initialize edit_log with a creation entry.""" record.edit_log = [{ "editor": creator_name, "time": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "changes": {}, }]