-- Facturas y devoluciones por año

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

SELECT
	su.nombre_sucursal AS Branch,
	dv.fecha AS Date,
	EXTRACT(YEAR_MONTH FROM dv.fecha) AS Month,
	dv.id_documento AS Sales_Document,
	LEFT(dv.id_documento,2) AS Type_of_Document,
	c.id_cliente AS Customer_Id,
	c.nombre_cliente AS Customer,
	vdr.nombre_vendedor AS Sales_Associate,
	c.telefono AS Phone,
	c.direccion AS Address,
	z.descripcion AS City,
	se.descripcion AS Sector,
	SUM(dvi.valor) AS Net_Sales

FROM
	documento_ventas dv
	JOIN documento_ventas_has_item dvi
		USING ( id_documento,id_sucursal )
	LEFT JOIN vendedor vdr
		USING ( id_vendedor,id_sucursal )
	LEFT JOIN cliente_has_sucursal c
		USING ( id_cliente,id_sucursal )
	JOIN sucursal su
		USING ( id_sucursal )
	LEFT JOIN sector se
		ON ( se.id_sector=LEFT(c.id_sector,2) )
	LEFT JOIN zona z
		USING ( id_zona )

WHERE 
	LEFT(dv.id_documento,2) RLIKE "C|E|F|D[^0-9MPBC]"
	AND NOT (dv.id_cliente LIKE "999")
        AND dv.fecha >= '2014-01-01'
        AND dv.fecha <= '2014-03-31'

--  AND dv.fecha >= DATE(CONCAT(YEAR(now())-1,'-10-01'))
-- AND dv.fecha <= DATE(CONCAT(YEAR(now()),  '-09-30'))

GROUP BY 
	Branch,Customer_Id, Sales_Document

HAVING
	LENGTH(Customer_Id) > 3

ORDER BY
	Net_Sales DESC
