SET NAMES 'utf8';

SELECT
    YEAR(dv.fecha) AS year,
    l.id_linea,
    l.descripcion AS linea,
    f.id_formapago AS id_formapago,
    f.descripcion AS formapago,
    SUM(dvi.valor) AS valor,
    SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0,1,-1))) AS peso,
    SUM(dvi.valor-dvi.costo) AS utilidad
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 
        ON ( dvi.id_item=i.id_item ) 
    LEFT JOIN linea l 
        ON ( l.id_linea = i.id_linea AND l.tipo= i.tipo ) 
    LEFT JOIN formapago_documento fd 
        ON ( fd.id_documento=dv.id_documento AND fd.id_sucursal=dv.id_sucursal )
    LEFT JOIN forma_pago f 
        ON ( f.id_formapago=fd.id_formapago ) 

GROUP BY
    year, linea, id_formapago 
