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

SELECT
        YEAR(dv.fecha) AS Year,
        COUNT(DISTINCT dv.id_cliente) AS Num_Customers,
	IF(
		fp.dias <= 5,
		'cash',
		'credit'
	) AS Sale_conditions,
	IF(
		l.id_linea_analisis >= 7
		AND l.id_linea_analisis <= 19,
		'flat',
		'long'
	) AS Family,
        ROUND(  
                SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
        ) AS Weight_MT,
        SUM(dvi.valor) AS Value
FROM
        documento_ventas dv
        JOIN documento_ventas_has_item dvi
                USING ( id_documento,id_sucursal )
        JOIN formapago_documento fpd
		USING (id_documento, id_sucursal)
        JOIN forma_pago fp
		USING (id_formapago, id_sucursal)
        JOIN item i
                ON ( dvi.id_item = i.id_item
                        AND dvi.id_sucursal = i.id_sucursal )
	JOIN view_lineas l
		ON (l.id_linea = LEFT(i.id_linea,2))

WHERE
        LEFT(dv.id_documento,2) RLIKE "F[^0-9MPBC]"
        AND NOT (dv.id_cliente LIKE "999")
        AND YEAR(dv.fecha) >= 2012
	
GROUP BY
	Year, Family, Sale_conditions
