-- Sales per payment type per customer/line/branch year to year
-- For Board Meeting presentation

SELECT
	YEAR(dv.fecha) AS Year,
        dv.id_sucursal AS Branch,
        dv.id_cliente AS Customer,
        COUNT(DISTINCT dv.id_cliente) AS Count_Customers,
	IF(
		fp.dias <= 5,
		'cash',
		'credit'
	) AS Sale_conditions,
	l.linea_analisis AS Line,
        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 formapago_documento fpd
                USING (id_documento,id_sucursal)
	JOIN forma_pago fp
		USING (id_formapago,id_sucursal)
        JOIN documento_ventas_has_item dvi
                USING (id_documento,id_sucursal)
        JOIN item i
                USING (id_item,id_sucursal)
        JOIN view_lineas l
                ON (l.id_linea = LEFT(i.id_linea,2))

WHERE
        LEFT( dv.id_documento, 2 ) RLIKE "F|D[^0-9MPBC]"
        AND NOT (dv.id_cliente LIKE "999")
        AND YEAR(dv.fecha) = 2015
	
GROUP BY
	Year, Branch, Sale_conditions, Customer, Line
