SET NAMES 'utf8';

SELECT 
	f.subfamilia AS Family,
	l.id_linea AS Line,
       	i.id_linea AS Sub_line,
	i.id_item AS Item,
       	i.descripcion AS Description,
       	SUM(dvi.valor) AS Net_Sales, 
	ROUND(
		SUM(
			dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
		),
		2
	) AS Amount_Kg,
	SUM(
		dvi.cantidad * (IF(dvi.valor >0, 1 , -1))
	) AS Amount_UoM,
       	SUM(dvi.costo) AS Cost_of_goods_sold

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 )
	LEFT JOIN view_lineas l
		ON ( l.id_linea = LEFT( i.id_linea, 2 ) )
	LEFT JOIN linea_has_subfamilia f
		ON ( l.id_linea = f.id_linea )

WHERE
	(LEFT(dv.id_documento,2) = 'DV' 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
	i.id_item

ORDER BY
	Amount_Kg DESC
