DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInDueDay_calculate`(
vInvoiceInFk INT
)
BEGIN
/**
 * Calcula los vctos. de una factura recibida 
 * En caso de haberlos informado previamente o que el proveedor sea español, no los recalculará
 *
 * @param vInvoiceInFk Factura recibida
 */
	DECLARE vCompanyCountryCode VARCHAR(3);
	DECLARE vHasDueDayTax BOOL;
	DECLARE vHasDueDay BOOL;

	SELECT c.code, IFNULL(a.isUeeMember, TRUE AND co.code ='ES')
			INTO vCompanyCountryCode, vHasDueDayTax
		FROM invoiceIn ii
			JOIN supplier su ON su.id = ii.companyFk
			LEFT JOIN country c ON c.id = su.countryFk
			LEFT JOIN supplier s ON s.id = ii.supplierFk
			LEFT JOIN country co ON co.id = s.countryFk
			LEFT JOIN province p ON p.id = s.provinceFk
			LEFT JOIN autonomy a ON a.id = p.autonomyFk
		WHERE ii.id = vInvoiceInFk;

	SELECT COUNT(*) INTO vHasDueDay
		FROM invoiceInDueDay iid 
		WHERE iid.invoiceInFk = vInvoiceInFk;

	IF NOT vHasDueDay AND vCompanyCountryCode = 'ES' THEN

		SET @cont := 0;
		INSERT INTO invoiceInDueDay (
				invoiceInFk, 
				dueDated, 
				amount, 
				foreignValue
			)
			SELECT vInvoiceInFk,
					IF(payDay, 
						IF(getNextDueDate(issued, pdd.detail, payDay) < created,
							created,
							getNextDueDate(issued, pdd.detail, payDay)), 
						GREATEST(created, issued + INTERVAL pdd.detail DAY)),
					IF((@cont := @cont + 1) < cont, 
						TRUNCATE(venc / cont, 2), 
						venc - (TRUNCATE(venc / cont, 2) * (cont - 1))),  
					IF(@cont < cont, 
						TRUNCATE(foreignValue / cont, 2), 
						foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1)))  
				FROM ( 
					SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax) 
								* iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc,  
							SUM(iit.foreignValue) / COUNT(DISTINCT(pdd.detail)) foreignValue,
							s.payDemFk,  
							ii.companyFk,
							COUNT(DISTINCT(pdd.detail)) cont,
							s.payDay,
							ii.issued,
							DATE(ii.created) + INTERVAL iic.dueDateMarginDays DAY created
						FROM invoiceIn ii 
							JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id 
							LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk 
							JOIN supplier s ON s.id = ii.supplierFk  
							JOIN payDemDetail pdd ON pdd.id = s.payDemFk
							JOIN invoiceInConfig iic
						WHERE ii.id = vInvoiceInFk   
						GROUP BY ii.id
					)sub
					JOIN payDemDetail pdd ON pdd.id = sub.payDemFk
				GROUP BY pdd.detail;
	END IF;

END$$
DELIMITER ;
