-- ============================================================
--  Rollback de 2026-10-14_05_margen_por_item.sql
--  Cada línea toma el margen de su ítem (su precio se recalcula).
-- ============================================================
USE tinsa_db;

UPDATE cotizacion_venta_material m
  JOIN cotizacion_venta_oferta_item i ON i.id = m.id_item
   SET m.margen          = i.margen,
       m.precio_unitario = IF(i.margen IS NULL, 0, ROUND(m.costo_unitario / (1 - i.margen / 100), 2)),
       m.subtotal_venta  = IF(i.margen IS NULL, 0, m.cantidad * ROUND(m.costo_unitario / (1 - i.margen / 100), 2));

ALTER TABLE `cotizacion_venta_oferta_item`
  DROP COLUMN `precio`,
  DROP COLUMN `margen`,
  DROP COLUMN `costo_total`;
