-- Ventas (Facturas menos devoluciones) por año, mes a mes.

-- Instrucciones de uso:
-- mysql --defaults-file=$HOME/.my_comercial_odoo.cnf < YEARLY-Sales_per_month-odoo.sql

SELECT 
	EXTRACT(YEAR_MONTH FROM dv.fecha) AS Month,
	dv.id_cliente AS Nit,
	c.nombre_cliente AS Cliente,
       	SUM(dvi.valor) AS Net_Sales, 
	ROUND(
		SUM(
			dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
		),
		2
	) AS Amount_Kg,
       	SUM(dvi.costo) AS Cost_of_goods_sold

FROM
	documento_ventas dv
	LEFT JOIN cliente c
		USING ( id_cliente )
	JOIN documento_ventas_has_item dvi 
		ON ( dv.id_documento = dvi.id_documento )
	JOIN item i
		ON ( dvi.id_item = i.id_item )

WHERE
	LEFT( dv.id_documento, 2 ) RLIKE "E|F|D[^0-9MPBC]"
	AND NOT (dv.id_cliente LIKE "999")
	AND EXTRACT(YEAR_MONTH FROM dv.fecha) >= 201410
	AND EXTRACT(YEAR_MONTH FROM dv.fecha) <= 201509

GROUP BY
	Month,Nit

ORDER BY
	Month,Nit
