-- Ventas mensuales por linea por cliente version ODOO
-- Incluye familia, sector, y linea de analisis de Directorio
-- Excluye traslados
-- Cambios solicitados en 2013-06-25: Zona y Suc2

SET NAMES 'utf8';

SELECT
	dv.id_sucursal AS Branch,
	se.id_sector AS Id_Sector,
	se.descripcion AS Sector,
	'' AS Subsector,
	cs.id_cliente AS Id_Client,
	cs.nombre_cliente AS Client,
	dv.id_vendedor AS Id_Salesrep,
	vdr.nombre_vendedor AS Salesrep,
	YEAR(dv.fecha) AS Year,
	MONTH(dv.fecha) + ((YEAR(dv.fecha)-2011)*12) AS Month_seq,
	l.familia AS 'Type',
	'' AS Subtype,
	RIGHT(l.id_linea,2) AS Id_Line1,
	l.descripcion AS Line1,
	'' AS Id_Line2,
	'' AS Line2,
	ROUND(
		SUM(
			dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
		),
		2
	) AS Sales_Kg,
	SUM(dvi.valor) AS Sales_COP,
	SUM(dvi.valor-dvi.costo) AS Gross_Margin,
	ROUND(
		SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
	) AS Sales_MT

FROM
	documento_ventas dv
	JOIN documento_ventas_has_item dvi
		ON ( dv.id_documento=dvi.id_documento 
			AND dv.id_sucursal=dvi.id_sucursal )
	JOIN item i
		USING ( id_item )
	JOIN cliente_has_sucursal cs
		ON ( dv.id_sucursal=cs.id_sucursal 
			AND dv.id_cliente=cs.id_cliente )
        LEFT JOIN linea l
		ON ( i.id_linea = l.id_linea )
	LEFT JOIN sector se
		ON ( LEFT(cs.id_sector,2) = se.id_sector )
	LEFT JOIN vendedor vdr
		ON ( dv.id_vendedor = vdr.id_vendedor
			AND dv.id_sucursal = vdr.id_sucursal)

WHERE
	(LEFT(dv.id_documento,2) = 'DV' OR
         LEFT(dv.id_documento,2) = 'DE' OR
	 LEFT(dv.id_documento,2) = 'EF' OR
	 LEFT(dv.id_documento,2) = 'EI' OR
	 LEFT(dv.id_documento,2) = 'AI' OR
	 LEFT(dv.id_documento,2) = 'CF' OR
	 LEFT(dv.id_documento,1) = 'F')
	AND EXTRACT(YEAR_MONTH FROM dv.fecha) = @MES

GROUP BY
	Branch,Id_Client,Month_seq,Id_Line1,Id_Line2,Id_Salesrep

ORDER BY
	Branch,Id_Client,Month_seq,Id_Line1,Id_Line2,Id_Salesrep
