-- Ventas por sucursal

-- Parametro: @MES, en formato YYYYMM

SET NAMES 'utf8';

SELECT 
	su.id_sucursal AS Branch_code,
       	su.nombre_sucursal AS Branch_office,
       	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
	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 sucursal su
		ON ( su.id_sucursal = dv.id_sucursal )

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 NOT (i.tipo LIKE "5")
	AND NOT (dv.id_cliente LIKE "999")
	AND EXTRACT(YEAR_MONTH FROM dv.fecha) = @MES

GROUP BY
	su.id_sucursal

ORDER BY
	su.id_sucursal ASC
