SELECT 
  date_trunc('day', po.create_date) AS giorno,
  COUNT(po.id) AS scontrini,
  ROUND(AVG(po.amount_total), 2) AS scontrino_medio,
  ROUND(SUM(po.amount_total), 2) AS fatturato,
  ROUND(SUM(COALESCE(po.amount_tax, 0)), 2) AS tasse,
  ROUND(SUM(pol_tot.costo_reale), 2) AS costi,
  ROUND(SUM(po.amount_total) - SUM(pol_tot.costo_reale) - SUM(COALESCE(po.amount_tax, 0)), 2) AS margine,
  ROUND(SUM(CASE WHEN po.state = 'cancel' THEN po.amount_total ELSE 0 END), 2) AS rimborsi
FROM pos_order po
LEFT JOIN (
  SELECT 
    order_id,
    SUM(pol.qty * COALESCE((pp.standard_price->'1')::numeric, 0)) AS costo_reale
  FROM pos_order_line pol
  LEFT JOIN product_product pp ON pol.product_id = pp.id
  GROUP BY order_id
) pol_tot ON po.id = pol_tot.order_id
WHERE po.state IN ('done')
GROUP BY 1
ORDER BY 1 DESC;