
DROP procedure IF EXISTS `vn`.`manaSpellersRequery`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`manaSpellersRequery`(vWorkerFk INTEGER)
BEGIN

	DECLARE vWorkerIsExcluded BOOLEAN;
	DECLARE vFromDated DATE;
    DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,CURDATE());
	DECLARE vMana INT;
    DECLARE vAutoMana INT;
    DECLARE vManaBank INT;
    DECLARE vManaGreugeType INT;
    
    SELECT id INTO vMana 
		FROM `component` WHERE code = 'mana';
    
    SELECT id INTO vAutoMana 
		FROM `component` WHERE code = 'autoMana';
	
	SELECT id INTO vManaBank 
		FROM `bank` WHERE code = 'mana';
	
	SELECT id INTO vManaGreugeType 
		FROM `greugeType` WHERE code = 'mana';
        
    SELECT COUNT(*) INTO vWorkerIsExcluded
		FROM workerManaExcluded
		WHERE workerFk = vWorkerFk;
    
	IF NOT vWorkerIsExcluded THEN

		SELECT max(dated) INTO vFromDated 
			FROM clientManaCache;
            
        REPLACE workerMana (workerFk, amount)
			SELECT vWorkerFk, sum(mana) FROM 
			(
				SELECT s.quantity * sc.value as mana
					FROM ticket t
						JOIN address a ON a.id = t.addressFk
						JOIN client c ON c.id = a.clientFk
						JOIN sale s ON s.ticketFk = t.id
						JOIN saleComponent sc ON sc.saleFk = s.id
					WHERE c.salesPersonFk =  vWorkerFk AND sc.componentFk IN (vMana, vAutoMana)
						AND t.shipped > vFromDated AND t.shipped < vToDated
				UNION ALL
				SELECT  - r.amountPaid
					FROM receipt r
						JOIN client c ON c.id = r.clientFk
					WHERE c.salesPersonFk = vWorkerFk AND bankFk = vManaBank
						AND payed > vFromDated
				UNION ALL
				SELECT g.amount
					FROM greuge g
						JOIN client c ON c.id = g.clientFk
					WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType
						AND g.shipped > vFromDated and g.shipped < CURDATE()				
				UNION ALL				
				SELECT cc.mana
					FROM clientManaCache cc
						JOIN client c ON c.id = cc.clientFk
					WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated
			) sub;
	END IF;
END$$

DELIMITER ;

