-- Sales per document with credit limit and conditions
-- For PwC

SELECT
        dv.id_cliente AS Customer_Id,
        cs.nombre_cliente AS Customer,
	cs.cupo AS Credit_limit,
	dv.id_vendedor AS Sales_Rep_Id,
	v.nombre_vendedor AS Sales_Rep,
	dv.id_documento AS Invoice,
	dv.fecha AS Date_document,
	dv.fecha_vencimiento AS Date_credit,
	fp.descripcion AS Payment_conditions,
	dv.valor_total AS Total_incl_taxes
FROM
        documento_ventas dv
	LEFT JOIN cliente_has_sucursal cs
		USING (id_cliente, id_sucursal)
	LEFT JOIN vendedor v
		ON (dv.id_vendedor = v.id_vendedor
			AND dv.id_sucursal = v.id_sucursal)
	LEFT JOIN formapago_documento fpd
		ON (dv.id_documento = fpd.id_documento
			AND dv.id_sucursal = fpd.id_sucursal)
	JOIN forma_pago fp
		USING (id_formapago)

WHERE
        (LEFT(dv.id_documento,2) = 'DV' OR
         LEFT(dv.id_documento,2) = 'EF' OR
         LEFT(dv.id_documento,1) = 'F')
        AND dv.fecha >= "2015-10-01"
        AND dv.fecha <= "2016-09-30"
