ALTER TABLE `vn`.`client` MODIFY COLUMN `credit` decimal(10,2) unsigned DEFAULT 0.00 NOT NULL;

DELETE FROM `salix`.`ACL` WHERE `model` = 'Client' AND `property` = 'create';

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_beforeUpdate`
	BEFORE UPDATE ON `client`
	FOR EACH ROW
BEGIN
	DECLARE vText VARCHAR(255) DEFAULT NULL;
    DECLARE vPayMethodFk INT;

	SET NEW.editorFk = account.myUser_getId();

	IF NOT(NEW.credit <=> OLD.credit) THEN
		INSERT INTO clientCredit
			SET clientFk = NEW.id,
				amount = NEW.credit,
				workerFk = NEW.editorFk;
	END IF;
	-- Comprueba que el formato de los teléfonos es válido

	IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN
		CALL pbx.phone_isValid(NEW.phone);
	END IF;

    IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN
		CALL pbx.phone_isValid(NEW.mobile);
	END IF;

	SELECT id INTO vPayMethodFk
		FROM vn.payMethod
		WHERE code = 'bankDraft';

	IF NEW.payMethodFk = vPayMethodFk AND NEW.dueDay = 0 THEN
		SET NEW.dueDay = 5;
    END IF;

	-- Avisar al comercial si ha llegado la documentación sepa/core

	IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN
		SET vText = 'Sepa de VNL';
	END IF;

	IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN
		SET vText = 'Core de VNL';
	END IF;

	IF vText IS NOT NULL
    THEN
		INSERT INTO mail(receiver, replyTo, `subject`, body)
			SELECT
					CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'),
                    'administracion@verdnatura.es',
                    CONCAT('Cliente ', NEW.id),
					CONCAT('Recibida la documentación: ', vText)
				FROM worker w
					LEFT JOIN account.user u ON w.id = u.id AND u.active
					LEFT JOIN account.account ac ON ac.id = u.id
				WHERE w.id = NEW.salesPersonFk;
	END IF;

    IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN
		IF (SELECT COUNT(clientFk)
				FROM clientProtected
                WHERE clientFk = NEW.id
			) > 0 THEN
			CALL util.throw("HAS_CLIENT_PROTECTED");
		END IF;
	END IF;

	IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN
		SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk);
	END IF;

	IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN
		SET NEW.isTaxDataChecked = 0;
	END IF;
END$$
DELIMITER ;

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticket_afterInsert`
	AFTER INSERT ON `ticket`
	FOR EACH ROW
BEGIN
	DECLARE vClientType VARCHAR(255);
	DECLARE vStateCode VARCHAR(255);
	DECLARE vTransferorFirstShipped DATE;

	IF NEW.credit NOT NULL AND NEW.credit <> 0 THEN 
		INSERT INTO clientCredit
			SET clientFk = NEW.id,
				workerFk = NEW.editorFk,
				amount = NEW.credit;
	END IF;

	-- Borrar cuando se cambie el insert ticket en la APP móvil

	SELECT typeFk INTO vClientType
		FROM vn.`client` WHERE id = NEW.clientFk;

	IF vClientType = 'loses' THEN
		SET vStateCode = 'DELIVERED';
	ELSE
		SET vStateCode = 'FREE';
	END IF;

	CALL ticket_setState(NEW.id, vStateCode);

	IF YEAR(NEW.shipped) > 2000 THEN
		SELECT cnb.firstShipped INTO vTransferorFirstShipped
				FROM bs.clientNewBorn cnb
					JOIN `client` c ON c.transferorFk = cnb.clientFk
				WHERE c.id = NEW.clientFk;

		INSERT INTO bs.clientNewBorn(clientFk, firstShipped, lastShipped)
			VALUES(NEW.clientFk, IFNULL(vTransferorFirstShipped, util.VN_CURDATE()), util.VN_CURDATE())
		ON DUPLICATE KEY UPDATE lastShipped = util.VN_CURDATE();
	END IF;
END$$
DELIMITER ;

