DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`addAccountReconciliation`()
BEGIN
/**
 * Updates duplicate records in the accountReconciliation table,
 * by assigning them a new identifier and then inserts a new entry in the till table.
 */
	UPDATE accountReconciliation ar
			JOIN (
				SELECT id,
						calculatedCode,
						CONCAT(
							calculatedCode, 
							'(', 
							ROW_NUMBER() OVER (PARTITION BY calculatedCode ORDER BY id),
							')'
						) newId
					FROM accountReconciliation ar
					WHERE calculatedCode IN (
						SELECT calculatedCode
							FROM accountReconciliation
							GROUP BY calculatedCode
							HAVING COUNT(*) > 1
					)
					ORDER BY calculatedCode, id
			) sub2 ON ar.id = sub2.id
		SET ar.calculatedCode = sub2.newId;
	
	INSERT INTO till(
		dated,
		isAccountable,
		serie,
		concept,
		`in`,
		`out`,
		bankFk,
		companyFk,
		warehouseFk,
		supplierAccountFk,
		calculatedCode,
		InForeignValue,
		OutForeignValue,
		workerFk
	)
		SELECT ar.operationDated,
				TRUE,
				'MB',
				ar.concept, 
				IF(ar.debitCredit = 'credit' AND a.currencyFk = arc.currencyFk, ar.amount, NULL),
				IF(ar.debitCredit = 'debit' AND a.currencyFk = arc.currencyFk, ar.amount, NULL),
				a.id,
				sa.supplierFk,
				arc.warehouseFk,
				ar.supplierAccountFk,
				ar.calculatedCode,
				IF(ar.debitCredit = 'credit' AND NOT a.currencyFk = arc.currencyFk, ar.amount, NULL),
				IF(ar.debitCredit = 'debit' AND NOT a.currencyFk = arc.currencyFk, ar.amount, NULL),
				account.myUser_getId()
			FROM accountReconciliation ar
				JOIN supplierAccount sa ON sa.id = ar.supplierAccountFk
				JOIN accounting a ON a.id = sa.accountingFk
				LEFT JOIN till t ON t.calculatedCode = ar.calculatedCode
				JOIN accountReconciliationConfig arc
			WHERE t.id IS NULL;
END$$
DELIMITER ;