-- Sales per payment type year to year
-- For Board Meeting presentation

SELECT
        YEAR(dv.fecha) AS Year,
        dv.id_sucursal AS Branch,
	COUNT(DISTINCT dv.id_documento) AS Number_of_Documents,
	IF(
		(dv.fecha_vencimiento - dv.fecha) <= 5,
		'cash',
		'credit'
	) AS Sale_conditions,
        ROUND(  
                SUM(dvi.cantidad * i.peso * (IF(dvi.valor>0,1,-1))), 4
        ) AS Weight_Kg,
        SUM(dvi.valor) AS Value
FROM
        documento_ventas dv
        JOIN documento_ventas_has_item dvi
                USING ( id_documento,id_sucursal )
        JOIN item i
                USING (id_item)

WHERE
        (LEFT(dv.id_documento,2) = 'DV' OR
         LEFT(dv.id_documento,2) = 'EF' OR
         LEFT(dv.id_documento,1) = 'F')
        AND NOT (dv.id_cliente LIKE "999")
        AND YEAR(dv.fecha) >= 2016
	
GROUP BY
	Year, Sale_conditions
