/** * Honey ledger invariant (Spec 4.6): amount = initialAmount + sum(quantity) * / 1000, rounded to the gram. Returns the batches that break it (tolerance * 0.5 g); an empty result means the ledger is consistent. Batches without * initialAmount are not booked and therefore not checked. */ export const INVARIANT_SQL = ` SELECT hb."id" FROM "HoneyBatch" hb LEFT JOIN ( SELECT "honeyBatchId", sum("quantity") AS grams FROM "BatchMovement" WHERE "honeyBatchId" IS NOT NULL GROUP BY "honeyBatchId" ) m ON m."honeyBatchId" = hb."id" WHERE hb."initialAmount" IS NOT NULL AND hb."amount" IS NOT NULL AND abs(hb."amount" - (hb."initialAmount" + coalesce(m.grams, 0) / 1000.0)) > 0.0005 `;