-- Sales per Client with credit limit and conditions
-- For Board of Directors

SELECT
	dv.id_cliente AS Customer_Id,
	cs.nombre_cliente AS Customer,
	cs.cupo AS Credit_limit,
	su.nombre_sucursal AS Branch,
	dv.id_documento AS Invoice,
	ROUND(  
		SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
	) AS Weight_MT,
	dv.fecha AS Date_document,
	EXTRACT(YEAR_MONTH FROM dv.fecha) AS Month_document,
	dv.fecha_vencimiento AS Date_credit,
	fp.formapago AS Payment_condition,
	dv.valor_total AS Total_incl_taxes
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
		USING (id_item)
	JOIN sucursal su
		ON (dv.id_sucursal = su.id_sucursal)
	LEFT JOIN cliente_has_sucursal cs
		ON (dv.id_cliente = cs.id_cliente
			AND dv.id_sucursal = cs.id_sucursal)
	LEFT JOIN formapago_documento fpd
		ON (dv.id_documento = fpd.id_documento
			AND dv.id_sucursal = fpd.id_sucursal)
	LEFT JOIN forma_pago fp
		USING (id_formapago)

WHERE
	dv.fecha >= "2021-01-01"
	AND dv.fecha <= "2021-09-30"
GROUP BY
	Customer_Id, Invoice
