2024-01-15 11:31:03 +00:00
|
|
|
DELIMITER $$
|
|
|
|
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`invoiceOut_beforeInsert`
|
|
|
|
BEFORE INSERT ON `invoiceOut`
|
|
|
|
FOR EACH ROW
|
|
|
|
BEGIN
|
2024-01-25 16:33:54 +00:00
|
|
|
/**
|
|
|
|
* Generates the next reference for the invoice serial. There cannot be gaps
|
|
|
|
* between identifiers of the same serial!
|
|
|
|
*
|
|
|
|
* Reference format:
|
|
|
|
* {0} Invoice serial
|
|
|
|
* {1} The company code
|
|
|
|
* {2-3} Last two digits of issue year
|
|
|
|
* {4-$} Autoincrement identifier
|
|
|
|
*/
|
|
|
|
DECLARE vRef INT DEFAULT 0;
|
|
|
|
DECLARE vRefLen INT;
|
|
|
|
DECLARE vRefPrefix VARCHAR(255);
|
|
|
|
DECLARE vLastRef VARCHAR(255);
|
|
|
|
DECLARE vCompanyCode INT;
|
|
|
|
DECLARE vYearLen INT DEFAULT 2;
|
|
|
|
DECLARE vPrefixLen INT;
|
2024-01-15 11:31:03 +00:00
|
|
|
|
2024-01-25 16:33:54 +00:00
|
|
|
SELECT companyCode INTO vCompanyCode
|
|
|
|
FROM company
|
|
|
|
WHERE id = NEW.companyFk;
|
2024-01-15 11:31:03 +00:00
|
|
|
|
2024-01-25 16:33:54 +00:00
|
|
|
IF vCompanyCode IS NULL THEN
|
|
|
|
CALL util.throw('companyCodeNotDefined');
|
|
|
|
END IF;
|
|
|
|
|
|
|
|
SELECT MAX(i.ref) INTO vLastRef
|
|
|
|
FROM invoiceOut i
|
|
|
|
WHERE i.serial = NEW.serial
|
|
|
|
AND i.issued BETWEEN util.firstDayOfYear(NEW.issued) AND util.lastDayOfYear(NEW.issued)
|
|
|
|
AND i.companyFk = NEW.companyFk;
|
|
|
|
|
|
|
|
IF vLastRef IS NOT NULL THEN
|
|
|
|
SET vPrefixLen = LENGTH(NEW.serial) + LENGTH(vCompanyCode) + vYearLen;
|
|
|
|
SET vRefLen = LENGTH(vLastRef) - vPrefixLen;
|
|
|
|
SET vRefPrefix = LEFT(vLastRef, vPrefixLen);
|
|
|
|
SET vRef = RIGHT(vLastRef, vRefLen);
|
2024-01-15 11:31:03 +00:00
|
|
|
ELSE
|
2024-01-25 16:33:54 +00:00
|
|
|
SELECT refLen INTO vRefLen FROM invoiceOutConfig;
|
|
|
|
SET vRefPrefix = CONCAT(
|
|
|
|
NEW.serial,
|
|
|
|
vCompanyCode,
|
|
|
|
RIGHT(YEAR(NEW.issued), vYearLen)
|
|
|
|
);
|
|
|
|
END IF;
|
2024-01-15 11:31:03 +00:00
|
|
|
|
2024-01-25 16:33:54 +00:00
|
|
|
SET vRef = vRef + 1;
|
|
|
|
IF LENGTH(vRef) > vRefLen THEN
|
|
|
|
CALL util.throw('refIdLenExceeded');
|
2024-01-15 11:31:03 +00:00
|
|
|
END IF;
|
|
|
|
|
2024-01-25 16:33:54 +00:00
|
|
|
SET NEW.ref = CONCAT(vRefPrefix, LPAD(vRef, vRefLen, '0'));
|
2024-01-15 11:31:03 +00:00
|
|
|
END$$
|
|
|
|
DELIMITER ;
|