DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`payment_beforeInsert`
	BEFORE INSERT ON `payment`
	FOR EACH ROW
BEGIN
		DECLARE cuenta_banco,cuenta_proveedor DOUBLE;
		DECLARE vNewBookEntry INT;
		DECLARE bolCASH BOOLEAN;
		DECLARE isSupplierActive BOOLEAN;

		-- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH
		SELECT (at2.code = 'cash') INTO bolCASH
			FROM accounting a
				JOIN accountingType at2 ON at2.id = a.accountingTypeFk
			WHERE a.id = NEW.bankFk;

		IF bolCASH  THEN

			SELECT account INTO cuenta_banco
				FROM accounting
				WHERE id = NEW.bankFk;
				
			SELECT account INTO cuenta_proveedor
				FROM supplier
				WHERE id = NEW.supplierFk;
			
			CALL ledger_next(vNewBookEntry);
			
			INSERT INTO XDiario (	ASIEN,
									FECHA,
									SUBCTA,
									CONTRA,
									CONCEPTO,
									EURODEBE,
									EUROHABER,
									empresa_id)
				SELECT 	vNewBookEntry,
						NEW.received,
						SUBCTA,
						CONTRA,
						NEW.concept,
						EURODEBE,
						EUROHABER,
						NEW.companyFk
					FROM (	SELECT 	cuenta_banco SUBCTA,
									cuenta_proveedor CONTRA,
									0 EURODEBE,
									NEW.amount + NEW.bankingFees EUROHABER
							UNION ALL
							SELECT 	cuenta_proveedor SUBCTA,
									cuenta_banco CONTRA,
									NEW.amount EURODEBE,
									0 EUROHABER) gf;
				
			IF NEW.bankingFees <> 0 THEN
				INSERT INTO XDiario (	ASIEN,
										FECHA,
										SUBCTA,
										CONTRA,
										CONCEPTO,
										EURODEBE,
										EUROHABER,
										empresa_id)
					SELECT 	vNewBookEntry,
							NEW.received,
							IF(c.id = 1,6260000002,
							IF(CEE = 1,6260000003,6260000004)),
							cuenta_banco,
							NEW.concept,
							NEW.bankingFees,
							0,
							NEW.companyFk
						FROM supplier s
							JOIN country c ON s.countryFk = c.id
						WHERE s.id = NEW.supplierFk;
			END IF;		
		END IF;

		SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received);

		SELECT isActive INTO isSupplierActive
			FROM supplier
			WHERE id = NEW.supplierFk;
			
		IF isSupplierActive = FALSE THEN
			CALL util.throw('SUPPLIER_INACTIVE');
		END IF;
	
		IF ISNULL(NEW.workerFk) THEN
			SET NEW.workerFk = account.myUser_getId();
		END IF;
	
	END$$
DELIMITER ;
