-- Documentos de venta

SELECT suc.nombre_sucursal AS Branch_Office,
    dv.id_documento AS Invoice_No,
    dv.fecha AS Invoice_Date,
    cs.id_cliente AS ID_Customer,
    cs.nombre_cliente AS Customer_Name, 
    cs.direccion AS Address,
    CONCAT_WS(', ',z.nombre_ciudad,z.nombre_depto) AS City,
    SUM(dvi.cantidad * i.peso * (IF(dvi.valor>0,1,-1))) AS Invoice_qty_Kg, 
    SUM(dvi.valor) AS Amount,
    "COP" AS Currency,
    fp.descripcion AS Payment_conditions,
    fp.formapago AS Sale_conditions
FROM 
    documento_ventas_has_item dvi 
    JOIN documento_ventas dv 
        ON ( dv.id_documento = dvi.id_documento AND dv.id_sucursal = dvi.id_sucursal ) 
    JOIN item i 
        ON ( dvi.id_item = i.id_item AND dvi.id_sucursal = i.id_sucursal ) 
    JOIN cliente_has_sucursal cs 
        ON ( dv.id_sucursal = cs.id_sucursal AND dv.id_cliente = cs.id_cliente )
    JOIN forma_pago fp
        ON ( dv.id_formapago = fp.id_formapago AND dv.id_sucursal = fp.id_sucursal ) 
    JOIN sucursal suc
        ON ( dv.id_sucursal = suc.id_sucursal )
    JOIN view_ciudades AS z
        ON (cs.ciudad = z.id_ciudad)
WHERE
    YEAR(dv.fecha) >= 2008
    AND LEFT(dv.id_documento,2) RLIKE 'F|D[^0-9MP]'
    AND NOT (dv.id_cliente LIKE "999") 
GROUP BY Branch_Office, Invoice_No
