-- ===========================================================================
-- Migration: put "what was sold" into existing sale ledger memos
-- Date: 2026-07-28
--
-- Going forward SalesController writes the item list into each sale's journal
-- memo (so the Journal and Cashbook show e.g. "Sale INV-000123 — John · Eggs
-- (trays) ×30, Spent hens ×5"). This backfills the SAME detail onto sale entries
-- posted before that change, by rebuilding the memo from sale_items. Idempotent
-- (re-running just rewrites the same string). Only touches source_type = 'sale'.
-- ===========================================================================

SET NAMES utf8mb4;

UPDATE journal_entries je
JOIN sales s ON s.id = je.source_id AND s.farm_id = je.farm_id
JOIN (
  SELECT sale_id,
         GROUP_CONCAT(CONCAT(item, ' ×', qty) ORDER BY sort_order, id SEPARATOR ', ') AS items
  FROM sale_items
  GROUP BY sale_id
) si ON si.sale_id = s.id
SET je.memo = LEFT(CONCAT('Sale ', s.invoice_no, ' — ', s.customer, ' · ', si.items), 255)
WHERE je.source_type = 'sale';
