salix/db/routines/vn/procedures/addAccountConciliation.sql

66 lines
1.8 KiB
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`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,
calculatedId,
CONCAT(
calculatedId,
'(',
ROW_NUMBER() OVER (PARTITION BY calculatedId ORDER BY id),
')'
) newId
FROM accountReconciliation
WHERE calculatedId IN (
SELECT calculatedId
FROM accountReconciliation
GROUP BY calculatedId
HAVING COUNT(*) > 1
)
ORDER BY calculatedId, id
) sub2 ON ar.id = sub2.id
SET ar.calculatedId = sub2.newId;
INSERT INTO till(
dated,
isAccountable,
serie,
concept,
`in`,
`out`,
bankFk,
companyFk,
warehouseFk,
supplierAccountFk,
calculatedCode,
InForeignValue,
OutForeignValue,
workerFk
)
SELECT ar.operationDate dated,
TRUE isAccountable,
'MB' serie,
ar.concept concept,
@totalIn := IF(ar.debitCredit = arc.debitCredit2 AND a.currencyFk = arc.currencyFk, ar.amount, NULL) `in`,
@totalOut := IF(ar.debitCredit = arc.debitCredit AND a.currencyFk = arc.currencyFk, ar.amount, NULL) `out`,
a.id bankFk,
sa.supplierFk companyFk,
arc.warehouseFk warehouseFk,
ar.supplierAccountFk supplierAccountFk,
ar.calculatedId calculatedCode,
@totalIn InForeignValue,
@totalOut OutForeignValue,
account.myUser_getId() user
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.calculatedId
JOIN accountReconciliationConfig arc
WHERE t.id IS NULL;
END$$
DELIMITER ;