[
  {
    "type": "raw_sql",
    "description": "Remove rows with NULL dates from closeSalesReport (garbage data from early 2019 before date was reliably populated)",
    "database": "{{store}}",
    "sql": "DELETE FROM closeSalesReport WHERE date IS NULL"
  },
  {
    "type": "raw_sql",
    "description": "Remove duplicate rows from closeSalesReport keeping only the best row per date (highest grossSalesRetail, then highest id as tiebreaker). This fixes a historical duplication bug where SalesReport::insert() was called once per email recipient.",
    "database": "{{store}}",
    "sql": "DELETE FROM closeSalesReport WHERE id NOT IN (SELECT keep_id FROM (SELECT MAX(id) as keep_id FROM closeSalesReport WHERE (date, COALESCE(grossSalesRetail, 0)) IN (SELECT date, MAX(COALESCE(grossSalesRetail, 0)) FROM closeSalesReport GROUP BY date) GROUP BY date) AS keep)"
  },
  {
    "type": "raw_sql",
    "description": "Add UNIQUE index on date column to prevent future duplicate rows in closeSalesReport",
    "database": "{{store}}",
    "check_query": "SELECT COUNT(*) as cnt FROM information_schema.STATISTICS WHERE table_schema = DATABASE() AND table_name = 'closeSalesReport' AND index_name = 'uk_date'",
    "check_value": "0",
    "sql": "ALTER TABLE closeSalesReport ADD UNIQUE KEY `uk_date` (`date`)"
  }
]
