-- Co-Lite change add-lead-dashboard: history for event leads captured before the history existed. -- Target: `service-counter`. Idempotent: touches only event leads with no history row. Times are approximate: -- the first status at capture, the current status (if not OPEN) at the last update. USE `service-counter`; INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`) SELECT el.company_id, el.id, NULL, 'OPEN', el.captured_at, el.captured_by FROM `event_lead` el WHERE NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id); INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`) SELECT el.company_id, el.id, 'OPEN', el.status, COALESCE(el.updated_at, el.captured_at), COALESCE(el.updated_by, el.captured_by) FROM `event_lead` el WHERE el.status <> 'OPEN' AND NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id AND s.to_status = el.status);