-- Saldo de Cartera por documento con corte al ultimo dia del mes anterior

-- Parametros: @DIA: Fecha del ultimo dia del mes, formato YYYY-MM-DD

SET NAMES 'utf8';

SELECT 
	ch.fecha_historico AS Date_Current,
	ch.id_cliente AS Customer_Id,
	cs.nombre_cliente AS Customer_Name,
	"" AS Insurance_Concept,
	"" AS Customer_Credit_Limit_Insurance,
	MAX(cs.cupo) AS Customer_Credit_Limit_Agofer,
	ch.id_documento AS Invoice_No,
	ch.fecha AS Invoice_Date,
	ch.fecha_vencimiento AS Invoice_Due_Date,
	ch.plazo AS Payment_Terms,
	ROUND(SUM(i.peso * dvi.cantidad),0) AS Invoice_Qty_Kg,
	MAX(ch.valor) AS Amount_due,
	"COP" AS Currency,
	"" AS Comments,
	s.nombre_sucursal AS Branch

FROM 
	cartera_historico ch 
	JOIN cliente_has_sucursal cs
		USING (id_sucursal, id_cliente)
	LEFT JOIN documento_ventas_has_item dvi
		USING (id_documento, id_sucursal)
	LEFT JOIN item i
		USING (id_item, id_sucursal)
	JOIN sucursal s
		USING (id_sucursal)

WHERE 
	ch.fecha_historico = @DIA

GROUP BY 
	ch.id_sucursal, ch.id_cliente, ch.id_documento

