DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`remittance_calc`(
	vDated DATE
)
BEGIN
/**
* Calcula los datos de remesa, incluyendo el importe,
* el vencimiento, y otros datos relevantes.
*
* @param vDated Fecha a calcular
* @return tmp.remittance
*/
	CREATE OR REPLACE TEMPORARY TABLE tmp.remittance
		SELECT CONCAT(s.nif, REPEAT('0', 12 - LENGTH(s.nif))) cif,
				c.id clientFk,
				c.name client,
				c.fi,
				sub.paymentDate,
				0 invoiceAmount,
				CAST(sub.receipt AS DECIMAL(10,2)) receiptAmount,
				0 currentAmount,
				sub.companyFk,
				c.socialName,
				CAST(sub.receipt AS DECIMAL(10,2)) totalAmount,
				CAST(sub.receipt AS DECIMAL(10,2)) balance,
				s.name company,
				co.code companyCode,
				c.accountingAccount,
				c.iban,
				c.hasSepaVnl,
				c.hasCoreVnl,
				c.hasLcr,
				be.bic,
				be.`name` entityName
			FROM client c
				JOIN (
					SELECT risk.companyFk,
							c.id,
							SUM(risk.amount) receipt,
							IF((c.dueDay + graceDays) MOD 30.001 <= DAY(vDated),
								LAST_DAY(vDated - INTERVAL 1 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY,
								LAST_DAY(vDated - INTERVAL 2 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY
							) paymentDate												
						FROM client c
							JOIN payMethod pm ON pm.id = c.payMethodFk
							JOIN (
									SELECT cr.companyFk, cr.clientFk, cr.amount
										FROM client c
											JOIN clientRisk cr ON cr.clientFk = c.id
											JOIN payMethod pm ON pm.id = c.payMethodFk
										WHERE pm.code = 'bankDraft'
									UNION ALL
									SELECT io.companyFk, io.clientFk, - io.amount
										FROM invoiceOut io 
											JOIN client c ON c.id = io.clientFk
											JOIN payMethod pm ON pm.id = c.payMethodFk
										WHERE io.dued > vDated
											AND pm.code = 'bankDraft'
											AND pm.outstandingDebt
											AND io.amount > 0
										
							) risk ON risk.clientFk = c.id
						GROUP BY risk.companyFk, c.id
						HAVING receipt > 10
				) sub ON sub.id = c.id
			JOIN supplier s ON s.id = sub.companyFk
			JOIN company co ON co.id = sub.companyFk
			LEFT JOIN bankEntity be ON be.id = c.bankEntityFk; 
END$$
DELIMITER ;