-- Clientes consolidados por año con ventas y devoluciones

-- Instrucciones de uso:
-- mysql --defaults-file=$HOME/.my_comercial_consultas.cnf < YEARLY-Customers_per_fiscal_year.sql > ../Agofer_Customers_per_year_FY$(date +%Y).csv

-- Nota: El campo Vendedor solo muestra el de una sucursal

SELECT c.id_cliente AS Customer_Id,
	c.nombre_cliente AS Customer,
	SUM(dvi.valor) AS Net_Sales,
	SUM(dvi.costo) AS Cost_of_goods_sold,
        EXTRACT(YEAR_MONTH FROM dv.fecha) AS Month,
	dv.id_sucursal AS Branch

FROM documento_ventas dv
	JOIN documento_ventas_has_item dvi
		USING ( id_documento,id_sucursal )
	LEFT JOIN cliente_has_sucursal c
		USING ( id_cliente,id_sucursal )

WHERE
	(LEFT(dv.id_documento,2) = 'DV' OR
	 LEFT(dv.id_documento,2) = 'EF' OR
	 LEFT(dv.id_documento,1) = 'F')
	AND dv.fecha >= DATE(CONCAT(YEAR(now()),'-01-01'))
	AND dv.fecha <= DATE(CONCAT(YEAR(now()),'-10-26'))

GROUP BY Branch,Customer_Id,Month

HAVING Net_Sales > 0

ORDER BY Net_Sales DESC
