diff --git a/db/dump/structure.sql b/db/dump/structure.sql
index cd168c2f9..929d1cc64 100644
--- a/db/dump/structure.sql
+++ b/db/dump/structure.sql
@@ -503,7 +503,7 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
CALL hedera.image_ref('user', NEW.image);
-
+
INSERT IGNORE INTO userSync SET `name` = NEW.`name`;
END */;;
DELIMITER ;
@@ -568,7 +568,7 @@ BEGIN
'jgallego@verdnatura.es',
'Rol modificado',
CONCAT(
- myUser_getName(),
+ myUser_getName(),
' ha modificado el rol del usuario ',
NEW.`name`, ' de ', OLD.role, ' a ', NEW.role)
);
@@ -684,7 +684,7 @@ BEGIN
SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey);
RETURN vSignature = @userSignature;
END IF;
-
+
RETURN FALSE;
END ;;
@@ -713,7 +713,7 @@ BEGIN
* @return The user id
*/
DECLARE vUser INT DEFAULT NULL;
-
+
IF myUser_checkLogin()
THEN
SET vUser = @userId;
@@ -721,7 +721,7 @@ BEGIN
SELECT id INTO vUser FROM user
WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1);
END IF;
-
+
RETURN vUser;
END ;;
DELIMITER ;
@@ -756,7 +756,7 @@ BEGIN
ELSE
SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1);
END IF;
-
+
RETURN vUser;
END ;;
DELIMITER ;
@@ -851,10 +851,10 @@ BEGIN
DECLARE vDigitChars TEXT DEFAULT '1234567890';
DECLARE vPunctChars TEXT DEFAULT '!$%&()=.';
- SELECT length, nAlpha, nUpper, nDigits, nPunct
+ SELECT length, nAlpha, nUpper, nDigits, nPunct
INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword;
- WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha
+ WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha
OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO
SET vRandIndex = FLOOR((RAND() * 4) + 1);
@@ -929,7 +929,7 @@ BEGIN
DECLARE vRole VARCHAR(255);
SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole
- FROM role r
+ FROM role r
JOIN user u ON u.role = r.id
JOIN roleConfig c
WHERE u.name = vUserName;
@@ -956,16 +956,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `user_getNameFromId`(vSelf INT) RETUR
BEGIN
/**
* Gets user name from it's id.
- *
+ *
* @param vSelf The user id
* @return The user name
*/
DECLARE vName VARCHAR(30);
-
- SELECT `name` INTO vName
- FROM user
+
+ SELECT `name` INTO vName
+ FROM user
WHERE id = vSelf;
-
+
RETURN vName;
END ;;
DELIMITER ;
@@ -1037,7 +1037,7 @@ BEGIN
JOIN role r ON r.id = rr.inheritsFrom
WHERE u.`name` = vUser
AND r.id = vRoleId;
-
+
RETURN vHasRole;
END ;;
DELIMITER ;
@@ -1096,7 +1096,7 @@ BEGIN
AND password = MD5(vPassword)
AND active;
- IF vAuthIsOk
+ IF vAuthIsOk
THEN
CALL myUser_loginWithName (vUserName);
ELSE
@@ -1157,7 +1157,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_loginWithName`(vUserName VAR
BEGIN
/**
* Logs in using only the user name. This procedure is intended to be executed
- * by users with a high level of privileges so that normal users should not have
+ * by users with a high level of privileges so that normal users should not have
* execute permissions on it.
*
* @param vUserName The user name
@@ -1193,7 +1193,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_logout`()
BEGIN
/**
* Logouts the user.
- */
+ */
SET @userId = NULL;
SET @userName = NULL;
SET @userSignature = NULL;
@@ -1316,9 +1316,9 @@ BEGIN
SELECT COUNT(*) > 0 INTO vIsRoot
FROM tmp.role t
- JOIN role r ON r.id = t.id
+ JOIN role r ON r.id = t.id
WHERE r.`name` = 'root';
-
+
IF vIsRoot THEN
INSERT IGNORE INTO tmp.role (id)
SELECT id FROM role;
@@ -2001,7 +2001,7 @@ BEGIN
SELECT `password` = MD5(vOldPassword), `name`
INTO vPasswordOk, vUserName
FROM user WHERE id = vSelf;
-
+
IF NOT vPasswordOk THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Invalid password';
@@ -2075,7 +2075,7 @@ BEGIN
IF vChr REGEXP '[[:alpha:]]'
THEN
SET vNAlpha = vNAlpha+1;
-
+
IF vChr REGEXP '[A-Z]'
THEN
SET vNUpper = vNUpper+1;
@@ -2135,7 +2135,7 @@ BEGIN
SELECT verificationToken = vVerificationToken, `name`
INTO vTokenVerified, vUserName
FROM user WHERE id = vSelf;
-
+
IF NOT vTokenVerified THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Invalid verification token';
@@ -2564,7 +2564,7 @@ BEGIN
IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN
CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED');
-
+
END IF;
END */;;
@@ -2590,7 +2590,7 @@ BEGIN
IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN
CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED');
-
+
END IF;
END */;;
@@ -3065,11 +3065,11 @@ BEGIN
DECLARE vTramo VARCHAR(20);
DECLARE vHour INT;
-
+
SET vHour = HOUR(vDateTime) ;
-
+
SET vTramo =
- CASE
+ CASE
WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana'
WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde'
END ;
@@ -3097,7 +3097,7 @@ BEGIN
* Inserta en la tabla bancos_evolution los saldos acumulados de cada banco
*
* @param vStartingDate Fecha desde la cual se recalculan la tabla bs.bancos_evolution
- */
+ */
DECLARE vCurrentDate DATE;
DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, util.VN_CURDATE());
IF IFNULL(vStartingDate,0) < TIMESTAMPADD(YEAR, -5, util.VN_CURDATE()) THEN
@@ -3111,49 +3111,49 @@ BEGIN
SELECT vCurrentDate, Id_Banco, deuda
FROM bs.bancos_evolution
WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate);
-
+
WHILE vCurrentDate < vMaxDate DO
-- insertar solo el dia de ayer
INSERT INTO bs.bancos_evolution(Fecha ,Id_Banco, saldo)
- SELECT vCurrentDate, Id_Banco, SUM(saldo)
+ SELECT vCurrentDate, Id_Banco, SUM(saldo)
FROM (
SELECT Id_Banco ,saldo
FROM bs.bancos_evolution
WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior
UNION ALL
-
+
SELECT c.Id_Banco, IFNULL(SUM(Entrada),0) - IFNULL(SUM(Salida),0) as saldo
FROM vn2008.Cajas c
JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas
- JOIN vn.accountingType at2 ON at2.id = b.cash
+ JOIN vn.accountingType at2 ON at2.id = b.cash
WHERE at2.code IN ('wireTransfer','fundingLine')
AND Cajafecha = vCurrentDate
AND (Serie = 'MB' OR at2.code = 'fundingLine')
GROUP BY Id_Banco
- )sub
+ )sub
GROUP BY Id_Banco
ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo);
-
+
SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate);
END WHILE;
- -- Ahora actualizamos la quilla
+ -- Ahora actualizamos la quilla
UPDATE bs.bancos_evolution be
JOIN
(
SELECT bp.Id_Banco, - sum(bp.importe) as quilla, t.dated
- FROM vn.time t
+ FROM vn.time t
JOIN vn2008.Bancos_poliza bp ON t.dated between apertura AND IFNULL(cierre, t.dated)
WHERE t.dated BETWEEN vStartingDate AND vMaxDate
GROUP BY Id_Banco, t.dated
) sub ON be.Id_Banco = sub.Id_Banco AND sub.dated = be.Fecha
- SET be.quilla = sub.quilla;
+ SET be.quilla = sub.quilla;
-- pagos futuros no concilidados
INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo)
SELECT t.dated, p.id_banco, - importe
- FROM vn.time t
+ FROM vn.time t
join vn2008.pago p ON p.fecha <= t.dated
WHERE t.dated BETWEEN util.VN_CURDATE() AND vMaxDate
AND p.fecha BETWEEN util.VN_CURDATE() AND vMaxDate
@@ -3163,7 +3163,7 @@ BEGIN
-- cobros futuros
INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo)
SELECT t.dated, r.Id_Banco, SUM(Entregado)
- FROM vn.time t
+ FROM vn.time t
JOIN vn2008.Recibos r ON r.Fechacobro <= t.dated
WHERE r.Fechacobro > util.VN_CURDATE() AND r.Fechacobro <= vMaxDate
AND t.dated BETWEEN util.VN_CURDATE() AND vMaxDate
@@ -3173,10 +3173,10 @@ BEGIN
-- saldos de la tabla prevision
INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo)
SELECT t.dated, sp.Id_Banco, SUM(Importe)
- FROM vn.time t
+ FROM vn.time t
JOIN vn2008.Saldos_Prevision sp ON sp.Fecha <= t.dated
JOIN vn2008.Bancos b ON sp.Id_Banco = b.Id_Banco
- JOIN vn.accountingType at2 ON at2.id = b.cash
+ JOIN vn.accountingType at2 ON at2.id = b.cash
WHERE at2.code IN ('wireTransfer','fundingLine')
AND t.dated BETWEEN vStartingDate AND vMaxDate
GROUP BY t.dated, sp.Id_Banco
@@ -3190,12 +3190,12 @@ BEGIN
-- Deuda
UPDATE bs.bancos_evolution be
JOIN vn2008.Bancos b using(Id_Banco)
- JOIN vn.accountingType at2 ON at2.id = b.cash
+ JOIN vn.accountingType at2 ON at2.id = b.cash
SET be.deuda = IF(at2.code = 'fundingLine', be.saldo_aux, 0)
, be.saldo = IF(at2.code = 'fundingLine', 0, be.saldo_aux)
WHERE Fecha >= vStartingDate;
- -- Liquidez
+ -- Liquidez
update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate;
-- Disponibilidad
update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate;
@@ -3218,14 +3218,14 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE)
BEGIN
- SELECT
- workerName,
- id,
- name,
- CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount,
- CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount
+ SELECT
+ workerName,
+ id,
+ name,
+ CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount,
+ CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount
FROM (
- (SELECT
+ (SELECT
CONCAT(w.firstname, ' ', w.lastName) AS workerName,
c.id,
c.name,
@@ -3234,11 +3234,11 @@ BEGIN
FROM bs.ventas v
INNER JOIN vn.`client` c ON v.Id_Cliente = c.id
INNER JOIN vn.worker w ON c.salesPersonFk = w.id
- WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR)
+ WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR)
AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR)
GROUP BY w.id, v.Id_Cliente)
UNION ALL
- (SELECT
+ (SELECT
CONCAT(w.firstname, ' ', w.lastName) AS workerName,
c.id,
c.name,
@@ -3284,7 +3284,7 @@ BEGIN
FROM vn.time t
JOIN bs.ventas v on t.dated = v.fecha
JOIN vn.client c on c.id = v.Id_Cliente
- JOIN vn.worker w ON w.id = c.salesPersonFk
+ JOIN vn.worker w ON w.id = c.salesPersonFk
WHERE t.year >= YEAR(util.VN_CURDATE()) - 1
GROUP BY w.code, t.year , t.month;
END ;;
@@ -3318,24 +3318,24 @@ BEGIN
DELETE FROM bs.clientNewBorn
WHERE lastShipped < vOneYearAgo;
-
+
DELETE FROM ventas
WHERE fecha < vFourYearsAgo;
-
+
DELETE FROM payMethodClient
WHERE dated < vOneYearAgo;
DELETE FROM payMethodClientEvolution
WHERE dated < vFourYearsAgo;
- DELETE FROM bs.salesByclientSalesPerson
+ DELETE FROM bs.salesByclientSalesPerson
WHERE dated < vFourYearsAgo;
-
- DELETE FROM bs.m3
+
+ DELETE FROM bs.m3
WHERE fecha < vTwoYearAgo;
DELETE FROM salesByItemTypeDay
- WHERE dated < vThreeYearAgo;
+ WHERE dated < vThreeYearAgo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -3403,16 +3403,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `clientNewBorn_recalc`()
BLOCK1: BEGIN
DECLARE vClientFk INT;
- DECLARE vShipped DATE;
+ DECLARE vShipped DATE;
DECLARE vPreviousShipped DATE;
- DECLARE vDone boolean;
- DECLARE cur cursor for
-
- SELECT clientFk, firstShipped
- FROM bs.clientNewBorn;
-
- DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE;
- SET vDone := FALSE;
+ DECLARE vDone boolean;
+ DECLARE cur cursor for
+
+ SELECT clientFk, firstShipped
+ FROM bs.clientNewBorn;
+
+ DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE;
+ SET vDone := FALSE;
DELETE FROM bs.clientNewBorn WHERE isModified = FALSE;
@@ -3424,7 +3424,7 @@ BLOCK1: BEGIN
WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null
GROUP BY c.id;
OPEN cur;
-
+
LOOP1: LOOP
SET vDone := FALSE;
FETCH cur INTO vClientFk, vShipped;
@@ -3435,37 +3435,37 @@ BLOCK1: BEGIN
END IF;
BLOCK2: BEGIN
- DECLARE vCurrentShipped DATE;
- DECLARE vDone2 boolean;
+ DECLARE vCurrentShipped DATE;
+ DECLARE vDone2 boolean;
DECLARE cur2 CURSOR FOR
- SELECT shipped
- FROM vn.ticket
+ SELECT shipped
+ FROM vn.ticket
WHERE clientFk = vClientFk AND shipped <= util.VN_CURDATE()
ORDER BY shipped DESC;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE;
SET vDone2 := FALSE;
OPEN cur2;
-
+
SET vPreviousShipped := vShipped;
LOOP2: LOOP
SET vDone2 := FALSE;
FETCH cur2 INTO vCurrentShipped;
-
+
IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN
- UPDATE bs.clientNewBorn
- SET firstShipped = vPreviousShipped
+ UPDATE bs.clientNewBorn
+ SET firstShipped = vPreviousShipped
WHERE clientFk= vClientFk;
-
+
CLOSE cur2;
- LEAVE LOOP2;
+ LEAVE LOOP2;
END IF;
-
+
SET vPreviousShipped := vCurrentShipped;
IF vDone2 THEN
- UPDATE bs.clientNewBorn
- SET firstShipped = vCurrentShipped
+ UPDATE bs.clientNewBorn
+ SET firstShipped = vCurrentShipped
WHERE clientFk= vClientFk;
CLOSE cur2;
LEAVE LOOP2;
@@ -3475,14 +3475,14 @@ BLOCK1: BEGIN
END BLOCK2;
END LOOP LOOP1;
- UPDATE bs.clientNewBorn cnb
+ UPDATE bs.clientNewBorn cnb
LEFT JOIN (SELECT DISTINCT t.clientFk
FROM vn.ticket t
JOIN vn.productionConfig pc
WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH
AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk
- SET cnd.isRookie = ISNULL(notRookie.clientFk);
-
+ SET cnd.isRookie = ISNULL(notRookie.clientFk);
+
END BLOCK1 ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -3503,16 +3503,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `comercialesCompleto`(IN vWorker INT
BEGIN
DECLARE vAYearAgoStarted DATE DEFAULT DATE_FORMAT(TIMESTAMPADD(YEAR, - 1, vDate), '%Y-%m-01');
DECLARE vAYearAgoEnded DATE DEFAULT TIMESTAMPADD(YEAR, - 1, LAST_DAY(vDate));
-
+
CALL vn.worker_GetHierarchy(vWorker);
-
+
INSERT IGNORE INTO tmp.workerHierarchyList (workerFk)
SELECT wd2.workerFk
FROM vn.workerDepartment wd2
WHERE wd2.workerFk = vWorker;
-
+
-- Falta que en algunos casos solo tenga en cuenta los tipos afectados.
- SELECT
+ SELECT
c.Id_Cliente id_cliente,
c.calidad,
c.Cliente cliente,
@@ -3538,7 +3538,7 @@ BEGIN
FROM
vn2008.Clientes c
LEFT JOIN
- (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge
+ (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge
FROM vn2008.Greuges g
JOIN vn.`client` c ON c.id = g.Id_Cliente
LEFT JOIN vn.worker w ON c.salesPersonFk = w.id
@@ -3560,14 +3560,14 @@ BEGIN
WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate
GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente
LEFT JOIN
- (SELECT
+ (SELECT
Id_Cliente, SUM(importe) consumo
FROM
bs.ventas v
INNER JOIN vn2008.Clientes c USING (Id_Cliente)
LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
WHERE
- (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
+ (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate))
GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente
LEFT JOIN
@@ -3628,17 +3628,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add`(IN vYear INT, IN v
BEGIN
/**
* Sustituye los registros de "bs.compradores".
- *
+ *
* @param vYear: año ventas
* @param vWeekFrom: semana desde
* @param vWeekTo: semana hasta
*/
REPLACE bs.compradores
- SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision
+ SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision
FROM bs.ventas v
JOIN vn.time tm ON tm.dated = v.fecha
- JOIN vn.itemType it ON it.id = v.tipo_id
- WHERE tm.year = vYear
+ JOIN vn.itemType it ON it.id = v.tipo_id
+ WHERE tm.year = vYear
AND tm.week BETWEEN vWeekFrom AND vWeekTo
AND it.categoryFk != 6
GROUP BY it.workerFk, tm.week;
@@ -3664,22 +3664,22 @@ BEGIN
DECLARE vYear INT;
DECLARE vWeek INT;
DECLARE done BOOL DEFAULT FALSE;
-
+
DECLARE rs CURSOR FOR
SELECT year, week
FROM vn.time
- WHERE dated <= util.VN_CURDATE()
- AND year = vYear
+ WHERE dated <= util.VN_CURDATE()
+ AND year = vYear
AND week >= vWeek;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-
- SELECT MAX(año) INTO vYear
+
+ SELECT MAX(año) INTO vYear
FROM compradores;
-
+
SELECT MAX(semana) INTO vWeek
- FROM compradores
- WHERE año = vYear;
+ FROM compradores
+ WHERE año = vYear;
OPEN rs;
@@ -3688,7 +3688,7 @@ BEGIN
WHILE NOT done DO
CALL compradores_add(vYear, vWeek, vWeek);
-
+
FETCH rs INTO vYear, vWeek;
END WHILE;
@@ -3696,7 +3696,7 @@ BEGIN
CLOSE rs;
CALL compradores_evolution_add;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -3728,10 +3728,10 @@ DECLARE i INT DEFAULT 1;
SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution;
IF ISNULL(datFEC) THEN
-
- SELECT min(fecha) INTO datFEC
+
+ SELECT min(fecha) INTO datFEC
FROM bs.ventas;
-
+
INSERT INTO bs.compradores_evolution( Id_Trabajador
, fecha
, importe)
@@ -3740,19 +3740,19 @@ SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution;
JOIN vn2008.Tipos tp using(tipo_id)
WHERE fecha = datFEC
GROUP BY Id_Trabajador;
-
+
SET datFEC = TIMESTAMPADD(DAY, 1, datFEC);
-
+
END IF;
WHILE datFEC < util.VN_CURDATE() DO
-
- IF i mod 150 = 0 THEN
+
+ IF i mod 150 = 0 THEN
SELECT datFEC;
END IF;
-
+
SET i = i + 1;
-
+
REPLACE bs.compradores_evolution( Id_Trabajador
, fecha
, importe)
@@ -3760,7 +3760,7 @@ SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution;
SELECT Id_Trabajador
, datFEC as fecha
, sum(importe) as importe
-
+
FROM
(
@@ -3768,17 +3768,17 @@ SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution;
, importe
FROM bs.compradores_evolution
WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC) -- las ventas acumuladas del dia anterior
-
+
UNION ALL
-
+
SELECT Id_Trabajador
, importe * IF(v.fecha < datFEC,-1,1) -- se restan las ventas del año anterior y se suman las del actual
FROM bs.ventas v
JOIN vn2008.Tipos tp using(tipo_id)
WHERE fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC))
AND reino_id != 6
-
- )sub
+
+ )sub
GROUP BY Id_Trabajador;
SET datFEC = TIMESTAMPADD(DAY,1,datFEC);
@@ -3808,49 +3808,49 @@ BEGIN
* Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias
*/
DECLARE datFEC DATE DEFAULT '2015-01-01';
-
- SELECT TIMESTAMPADD(DAY,1,MAX(fecha))
- INTO datFEC
+
+ SELECT TIMESTAMPADD(DAY,1,MAX(fecha))
+ INTO datFEC
FROM bs.fondo_maniobra;
-
+
WHILE datFEC < util.VN_CURDATE() DO
-
+
IF DAY(datFEC) MOD 28 = 0 THEN -- esto solo sirve para no aburrirse mientras esperamos...
SELECT datFEC;
END IF;
-
+
REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo)
SELECT datFEC AS Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos
FROM (
SELECT SUM(io.amount) AS Facturas
FROM vn.invoiceOut io
- JOIN vn.client c ON io.clientFk = c.id
+ JOIN vn.client c ON io.clientFk = c.id
WHERE c.isRelevant
- AND io.companyFk <> 1381
+ AND io.companyFk <> 1381
AND io.issued BETWEEN '2011-01-01' AND datFEC
) fac
JOIN (
SELECT - SUM(r.amountPaid) AS Cobros
- FROM vn.receipt r
- JOIN vn.client c ON r.clientFk = c.id
- WHERE c.isRelevant
+ FROM vn.receipt r
+ JOIN vn.client c ON r.clientFk = c.id
+ WHERE c.isRelevant
AND r.companyFk <> 1381
AND r.payed BETWEEN '2011-01-01' AND datFEC
) cob
JOIN (
SELECT - SUM(id.amount) AS Recibidas
- FROM vn.invoiceIn ii
- JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk
+ FROM vn.invoiceIn ii
+ JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk
WHERE ii.companyFk <> 1381
AND ii.issued BETWEEN '2015-01-01' AND datFEC
) rec
JOIN (
SELECT SUM(p.amount) AS Pagos
- FROM vn.payment p
- WHERE p.companyFk <>1381
+ FROM vn.payment p
+ WHERE p.companyFk <>1381
AND p.received BETWEEN '2015-01-01' AND datFEC
) pag;
-
+
UPDATE bs.fondo_maniobra
JOIN (
SELECT AVG(fondo) AS media
@@ -3858,7 +3858,7 @@ BEGIN
WHERE fecha <= datFEC
) sub
SET fondo_medio = media WHERE fecha = datFEC;
-
+
SET datFEC = TIMESTAMPADD(DAY,1,datFEC);
END WHILE;
@@ -3882,7 +3882,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fruitsEvolution`()
BEGIN
-select Id_Cliente,
+select Id_Cliente,
Cliente, count(semana) as semanas, (w.code IS NOT NULL) isWorker
from (
select distinct v.Id_Cliente, c.name as Cliente, week(fecha, 3) as semana
@@ -3923,40 +3923,40 @@ BEGIN
-- Ventas totales del ultimo año
UPDATE indicators
- SET lastYearSales =
+ SET lastYearSales =
(SELECT SUM(importe + recargo)
FROM ventas v
JOIN vn2008.empresa e ON e.id = v.empresa_id
JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo
WHERE fecha BETWEEN oneYearBefore AND vDated
AND eg.grupo = 'Verdnatura'
- )
+ )
WHERE updated = vDated;
-
+
-- Greuge total acumulado
UPDATE indicators
- SET totalGreuge =
+ SET totalGreuge =
(SELECT SUM(amount)
FROM vn.greuge
WHERE shipped <= vDated
- )
+ )
WHERE updated = vDated;
-- Tasa de morosidad con respecto a las ventas del último mes
UPDATE indicators
- SET latePaymentRate =
- (SELECT SUM(amount)
- FROM bi.defaulters
+ SET latePaymentRate =
+ (SELECT SUM(amount)
+ FROM bi.defaulters
WHERE date = vDated AND amount > 0)
/
- (SELECT SUM(importe + recargo)
- FROM ventas
+ (SELECT SUM(importe + recargo)
+ FROM ventas
WHERE fecha BETWEEN oneMonthBefore AND vDated)
WHERE updated = vDated;
-- Número de trabajadores activos
UPDATE indicators
- SET countEmployee =
+ SET countEmployee =
(SELECT CAST(SUM(cl.hours_week) / 40 AS DECIMAL (10, 2))
FROM vn.business b
JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = b.calendarTypeFk
@@ -3975,7 +3975,7 @@ BEGIN
-- Número de clientes que han comprado en los últimos 30 dias
UPDATE indicators
- SET lastMonthActiveClients =
+ SET lastMonthActiveClients =
(SELECT COUNT(DISTINCT t.clientFk)
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
@@ -3984,9 +3984,9 @@ BEGIN
-- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores
UPDATE indicators
- SET lastMonthLostClients =
+ SET lastMonthLostClients =
(SELECT COUNT(lm.clientFk)
- FROM
+ FROM
(SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
@@ -4003,9 +4003,9 @@ BEGIN
-- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores
UPDATE indicators
- SET lastMonthNewClients =
+ SET lastMonthNewClients =
(SELECT COUNT(cm.clientFk)
- FROM
+ FROM
(SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
@@ -4031,7 +4031,7 @@ BEGIN
-- Cálculo de las ventas agrupado por semanas
SELECT week INTO vWeek
- FROM vn.time
+ FROM vn.time
WHERE dated = vDated;
TRUNCATE salesByWeek;
@@ -4045,12 +4045,12 @@ BEGIN
-- Indicador Ventas semana actual
UPDATE indicators i
- JOIN salesByWeek s ON s.week= vWeek
+ JOIN salesByWeek s ON s.week= vWeek
AND s.year = YEAR(vDated)
SET i.thisWeekSales = s.sales
WHERE updated = vDated;
- -- Indicador ventas semana actual en el año pasado
+ -- Indicador ventas semana actual en el año pasado
UPDATE indicators i
JOIN salesByWeek s ON s.week = vWeek
AND s.year = YEAR(vDated)-1
@@ -4081,15 +4081,15 @@ BEGIN
SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01')
INTO vDated
FROM bs.indicators;
-
+
WHILE vDated < util.VN_CURDATE() DO
-
+
CALL indicatorsUpdate(vDated);
-
+
SELECT TIMESTAMPADD(DAY,1,MAX(updated))
INTO vDated
FROM bs.indicators;
-
+
END WHILE;
END ;;
@@ -4114,30 +4114,30 @@ BEGIN
TRUNCATE bs.inspeccionSS_2021;
INSERT INTO bs.inspeccionSS_2021
- SELECT wbd.businessFk ,
- w.id,
- w.firstName,
- w.lastName,
- d.name ,
- wtc.timed ,
- cl.hours_week ,
- t.`year` ,
- t.week ,
+ SELECT wbd.businessFk ,
+ w.id,
+ w.firstName,
+ w.lastName,
+ d.name ,
+ wtc.timed ,
+ cl.hours_week ,
+ t.`year` ,
+ t.week ,
t.dated ,
0 AS orden
FROM vn.workerTimeControl wtc
JOIN vn.worker w ON w.id = wtc.userFk
- JOIN vn.workerBusinessDated wbd ON wbd.workerFk = wtc.userFk
+ JOIN vn.workerBusinessDated wbd ON wbd.workerFk = wtc.userFk
AND wbd.dated = date(wtc.timed)
JOIN vn.time t ON t.dated = wbd.dated
- JOIN vn.business b ON b.id = wbd.businessFk
- JOIN postgresql.calendar_labour_type AS cl ON b.calendarTypeFk = cl.calendar_labour_type_id
- JOIN vn.department d ON d.id = b.departmentFk
+ JOIN vn.business b ON b.id = wbd.businessFk
+ JOIN postgresql.calendar_labour_type AS cl ON b.calendarTypeFk = cl.calendar_labour_type_id
+ JOIN vn.department d ON d.id = b.departmentFk
JOIN vn.department d2 ON d2.id = d.parentFk AND d2.name = 'PRODUCCION'
WHERE wtc.timed BETWEEN '2020-10-01' AND '2021-04-19'
AND d.lft BETWEEN d2.lft AND d2.rgt
AND lastName NOT LIKE 'FERRER%';
-
+
SET @orden := 1;
SET @id := 0;
SET @day := 0;
@@ -4146,7 +4146,7 @@ BEGIN
SET orden = IF(id = @id AND day(timed) = @day, @orden := @orden + 1, @orden := 1),
id = @id := id + (0 * @day := day(timed))
ORDER BY id, timed;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4168,15 +4168,15 @@ BEGIN
DECLARE datSTART DATE;
DECLARE datEND DATE;
-
+
SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART
FROM bs.m3;
-
+
SET datEND = TIMESTAMPADD(DAY,-1,util.VN_CURDATE());
-
- DELETE FROM bs.m3
+
+ DELETE FROM bs.m3
WHERE fecha >= datSTART;
-
+
INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros)
SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(s.quantity * ic.cm3delivery) / 1000000 AS m3,
tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe)
@@ -4219,51 +4219,51 @@ BEGIN
DECLARE vManaBankId INT;
DECLARE vManaGreugeTypeId INT;
- SELECT id INTO vManaId
+ SELECT id INTO vManaId
FROM vn.component WHERE code = 'mana';
-
- SELECT id INTO vManaAutoId
+
+ SELECT id INTO vManaAutoId
FROM vn.component WHERE code = 'autoMana';
-
+
SELECT id INTO vClaimManaId
FROM vn.component WHERE code = 'manaClaim';
-
- SELECT id INTO vManaBankId
+
+ SELECT id INTO vManaBankId
FROM vn.bank WHERE code = 'mana';
-
- SELECT id INTO vManaGreugeTypeId
+
+ SELECT id INTO vManaGreugeTypeId
FROM vn.greugeType WHERE code = 'mana';
SELECT IFNULL(MAX(dated), '2016-01-01')
- INTO vFromDated
+ INTO vFromDated
FROM vn.clientManaCache;
-
+
DELETE
FROM vn.clientManaCache
WHERE dated = vFromDated;
SELECT IFNULL(MAX(dated), '2016-01-01')
- INTO vFromDated
+ INTO vFromDated
FROM vn.clientManaCache;
WHILE timestampadd(DAY,30,vFromDated) < util.VN_CURDATE() DO
SELECT
timestampadd(DAY,30,vFromDated),
- timestampadd(DAY,-90,vFromDated)
- INTO
+ timestampadd(DAY,-90,vFromDated)
+ INTO
vToDated,
vForDeleteDated;
-
+
DELETE FROM vn.clientManaCache
WHERE dated <= vForDeleteDated;
INSERT INTO vn.clientManaCache(clientFk, mana, dated)
- SELECT
+ SELECT
Id_Cliente,
cast(sum(mana) as decimal(10,2)) as mana,
- vToDated as dated
- FROM
+ vToDated as dated
+ FROM
(
SELECT cs.Id_Cliente, Cantidad * Valor as mana
FROM vn2008.Tickets t
@@ -4271,20 +4271,20 @@ BEGIN
JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket
JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento
WHERE Id_Componente IN (vManaAutoId, vManaId, vClaimManaId)
- AND t.Fecha > vFromDated
+ AND t.Fecha > vFromDated
AND date(t.Fecha) <= vToDated
UNION ALL
SELECT r.Id_Cliente, - Entregado
FROM vn2008.Recibos r
WHERE Id_Banco = vManaBankId
- AND Fechacobro > vFromDated
+ AND Fechacobro > vFromDated
AND Fechacobro <= vToDated
-
+
UNION ALL
SELECT g.Id_Cliente, g.Importe
FROM vn2008.Greuges g
WHERE Greuges_type_id = vManaGreugeTypeId
- AND Fecha > vFromDated
+ AND Fecha > vFromDated
AND Fecha <= vToDated
UNION ALL
SELECT clientFk, mana
@@ -4295,7 +4295,7 @@ BEGIN
HAVING Id_Cliente;
SET vFromDated = vToDated;
-
+
END WHILE;
END ;;
@@ -4316,20 +4316,20 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellers_actualize`()
BEGIN
-/**
- * Recalcula el valor del campo con el modificador de precio
+/**
+ * Recalcula el valor del campo con el modificador de precio
* para el componente de maná automático.
*/
UPDATE vn.workerMana wm
JOIN(
- SELECT sb.salespersonFk, FLOOR(SUM(sb.amount) / 12) monthlyAmount
- FROM salesByclientSalesPerson sb
+ SELECT sb.salespersonFk, FLOOR(SUM(sb.amount) / 12) monthlyAmount
+ FROM salesByclientSalesPerson sb
JOIN vn.time t ON t.dated = sb.dated
- WHERE t.year * 100 + t.month >=
+ WHERE t.year * 100 + t.month >=
(YEAR(util.VN_CURDATE()) - 1) * 100 + MONTH(util.VN_CURDATE())
GROUP BY salespersonFk
) lastYearSales ON wm.workerFk = lastYearSales.salespersonFk
- SET pricesModifierRate = GREATEST(minRate,
+ SET pricesModifierRate = GREATEST(minRate,
LEAST(maxRate, ROUND( - amount / lastYearSales.monthlyAmount, 3)));
END ;;
DELIMITER ;
@@ -4362,8 +4362,8 @@ BEGIN
DECLARE vId INT;
DECLARE rs CURSOR FOR
- SELECT id, `schema`, `procedure`
- FROM nightTask
+ SELECT id, `schema`, `procedure`
+ FROM nightTask
WHERE finished <= util.VN_CURDATE()
OR finished IS NULL
ORDER BY `order`;
@@ -4396,7 +4396,7 @@ BEGIN
vError,
vErrorCode
);
-
+
IF vError IS NOT NULL THEN
SET vNErrors = vNErrors + 1;
@@ -4466,7 +4466,7 @@ BEGIN
vError = MESSAGE_TEXT,
vErrorCode = RETURNED_SQLSTATE;
- CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`'));
+ CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`'));
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4485,22 +4485,22 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `payMethodClientAdd`()
BEGIN
- INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk)
+ INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk)
SELECT util.VN_CURDATE(), c.payMethodFk, c.id
- FROM vn.client c
+ FROM vn.client c
JOIN vn.payMethod p ON c.payMethodFk = p.id;
-
+
TRUNCATE `bs`.`payMethodClientEvolution` ;
-
+
INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax)
- SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo)
+ SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo)
FROM bs.payMethodClient p
- JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente
+ JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente
FROM bs.ventas v
WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient)
GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk
JOIN vn.payMethod pm ON p.payMethodFk = pm.id
- GROUP BY dated,payMethodFk;
+ GROUP BY dated,payMethodFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4520,12 +4520,12 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGraphic`(IN vItemFk INT, IN vTypeFk INT, IN vCategoryFk INT, IN vFromDate DATE,
IN vToDate DATE, IN vProducerFk INT)
BEGIN
-
+
DECLARE vFromDateLastYear DATE;
DECLARE vToDateLastYear DATE;
DECLARE vFromDateTwoYearsAgo DATE;
DECLARE vToDateTwoYearsAgo DATE;
-
+
SET vItemFk = IFNULL(vItemFk,0);
SET vTypeFk = IFNULL(vTypeFk, 0);
SET vCategoryFk = IFNULL(vCategoryFk,0);
@@ -4540,19 +4540,19 @@ BEGIN
SELECT s.quantity, CAST(v.importe AS DECIMAL(10,0)) importe, v.fecha
FROM bs.ventas v
- JOIN vn.sale s ON s.id = v.Id_Movimiento
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.sale s ON s.id = v.Id_Movimiento
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
WHERE vItemFk IN (i.id, 0)
AND vTypeFk IN (i.typeFk, 0)
AND vCategoryFk IN (it.categoryFk, 0)
AND vProducerFk IN (i.producerFk, 0)
AND (v.fecha BETWEEN vFromDate AND vToDate
OR v.fecha BETWEEN vFromDateLastYear AND vToDateLastYear
- OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo
+ OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo
);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4571,21 +4571,21 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME)
BEGIN
- DELETE FROM bs.salePersonEvolution
+ DELETE FROM bs.salePersonEvolution
WHERE dated <= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR);
-
-
+
+
INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk)
- SELECT fecha dated,
- CAST(SUM(importe) AS DECIMAL(10,2) ) amount,
+ SELECT fecha dated,
+ CAST(SUM(importe) AS DECIMAL(10,2) ) amount,
CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax ,
IFNULL(salesPersonFk,0) salesPersonFk
FROM bs.ventas v
- JOIN vn.client c ON v.Id_Cliente = c.id
+ JOIN vn.client c ON v.Id_Cliente = c.id
JOIN vn.company co ON co.id = v.empresa_id
WHERE co.code = "VNL" AND fecha >= vDateStart
GROUP BY v.fecha,c.salesPersonFk
- ORDER BY salesPersonFk,dated ASC;
+ ORDER BY salesPersonFk,dated ASC;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4607,7 +4607,7 @@ BEGIN
/**
* Agrupa las ventas por cliente/comercial/fecha en la tabla bs.salesByclientSalesPerson
* El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo
- *
+ *
* @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer
*/
@@ -4615,17 +4615,17 @@ BEGIN
SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH;
END IF;
- UPDATE salesByclientSalesPerson
+ UPDATE salesByclientSalesPerson
SET amount = 0,
equalizationTax = 0,
amountNewBorn = 0
WHERE dated BETWEEN vDatedFrom AND util.yesterday();
-
- INSERT INTO salesByclientSalesPerson(
- dated,
- salesPersonFk,
- clientFk,
- amount,
+
+ INSERT INTO salesByclientSalesPerson(
+ dated,
+ salesPersonFk,
+ clientFk,
+ amount,
equalizationTax)
SELECT s.dated,
c.salesPersonFk,
@@ -4634,7 +4634,7 @@ BEGIN
SUM(s.surcharge)
FROM sale s
JOIN vn.client c on s.clientFk = c.id
- WHERE s.dated BETWEEN vDatedFrom AND util.yesterday()
+ WHERE s.dated BETWEEN vDatedFrom AND util.yesterday()
GROUP BY s.dated, c.salesPersonFk, s.clientFk
ON DUPLICATE KEY UPDATE amount= VALUES(amount),
equalizationTax= VALUES(equalizationTax);
@@ -4666,163 +4666,163 @@ BEGIN
/**
* Almacena datos relativos a las ventas de artículos agrupados por reino y familia
*
- * @param vDateStart
- * @param vDateEnd
+ * @param vDateStart
+ * @param vDateEnd
*/
-
- DELETE FROM bs.salesByItemTypeDay
+
+ DELETE FROM bs.salesByItemTypeDay
WHERE dated BETWEEN vDateStart AND vDateEnd;
-
+
INSERT INTO bs.salesByItemTypeDay (itemTypeFk, itemCategoryFk, dated)
- SELECT id, categoryFk, dated
+ SELECT id, categoryFk, dated
FROM vn.itemType
JOIN vn.`time`
WHERE dated BETWEEN vDateStart AND vDateEnd;
-
+
UPDATE bs.salesByItemTypeDay it
- JOIN (SELECT ic.id itemCategoryFk,
+ JOIN (SELECT ic.id itemCategoryFk,
it.id itemTypeFk,
bs.dated,
SUM(bs.amount) netSale
FROM bs.sale bs
JOIN vn.itemType it ON it.id = bs.typeFk
- JOIN vn .itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn .itemCategory ic ON ic.id = it.categoryFk
JOIN vn.client c on c.id = bs.clientFk
JOIN vn.sale s ON s.id = bs.saleFk
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.`time` ti ON ti.dated = bs.dated
- WHERE ic.merchandise
+ WHERE ic.merchandise
AND bs.dated BETWEEN vDateStart AND vDateEnd
GROUP BY ic.id, it.id, bs.dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk
SET it.netSale = sub.netSale;
-
-
+
+
UPDATE bs.salesByItemTypeDay it
- JOIN (SELECT ic.id AS itemCategoryFk,
+ JOIN (SELECT ic.id AS itemCategoryFk,
it.id AS itemTypeFk,
bs.dated,
SUM(i.stems * s.quantity) stems
FROM bs.sale bs
JOIN vn.itemType it ON it.id = bs.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
JOIN vn.sale s ON s.id = bs.saleFk
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.item i ON i.id = s.itemFk
JOIN vn.`time` tm ON tm.dated = bs.dated
- WHERE ic.merchandise
+ WHERE ic.merchandise
AND bs.dated BETWEEN vDateStart AND vDateEnd
- GROUP BY ic.id, it.id, bs.dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk
+ GROUP BY ic.id, it.id, bs.dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk
SET it.stems = sub.stems;
-
-
+
+
UPDATE bs.salesByItemTypeDay it
- JOIN (SELECT ic.id AS itemCategoryFk,
+ JOIN (SELECT ic.id AS itemCategoryFk,
it.id AS itemTypeFk,
DATE(t.shipped) dated,
COUNT(DISTINCT(i.id)) `references`
FROM vn.ticket t
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- WHERE ic.merchandise
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ WHERE ic.merchandise
AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY ic.id, it.id, dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk
SET it.`references` = sub.`references`;
-
+
UPDATE bs.salesByItemTypeDay it
- JOIN (SELECT ic.id AS itemCategoryFk,
+ JOIN (SELECT ic.id AS itemCategoryFk,
it.id AS itemTypeFk,
DATE(t.shipped) dated,
SUM(i.stems*s.quantity) AS trash
FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- JOIN vn.client c ON c.id = t.clientFk
- WHERE c.name = 'BASURA'
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.client c ON c.id = t.clientFk
+ WHERE c.name = 'BASURA'
AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY ic.id, it.id, dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk
- SET it.trash = sub.trash;
-
+ SET it.trash = sub.trash;
+
UPDATE bs.salesByItemTypeDay it
- JOIN (SELECT ic.id AS itemCategoryFk,
+ JOIN (SELECT ic.id AS itemCategoryFk,
it.id AS itemTypeFk,
DATE(t.shipped) dated,
SUM(IFNULL(i.stems, 1) * s.quantity) AS faults
FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- JOIN vn.client c ON c.id = t.clientFk
- WHERE c.name = 'FALTAS'
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.client c ON c.id = t.clientFk
+ WHERE c.name = 'FALTAS'
AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY ic.id, it.id, dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk
- SET it.`faults` = sub.`faults`;
-
+ SET it.`faults` = sub.`faults`;
+
UPDATE bs.salesByItemTypeDay it
- JOIN (SELECT ic.id AS itemCategoryFk,
+ JOIN (SELECT ic.id AS itemCategoryFk,
it.id AS itemTypeFk,
DATE(t.shipped) dated,
- SUM((cb.quantity * s.price * (100 - s.discount) / 100) * ((cc.maxResponsibility - c.responsibility )/4 )) accepted,
+ SUM((cb.quantity * s.price * (100 - s.discount) / 100) * ((cc.maxResponsibility - c.responsibility )/4 )) accepted,
SUM(cb.quantity * s.price * (100 - s.discount) / 100) claimed
FROM vn.claim c
JOIN vn.claimBeginning cb ON cb.claimFk = c.id
JOIN vn.sale s ON s.id = cb.saleFk
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
JOIN vn.claimConfig cc
- WHERE ic.merchandise
+ WHERE ic.merchandise
AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY ic.id, it.id, dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk
SET it.accepted = sub.accepted,
it.claimed = sub.claimed;
-
+
UPDATE bs.salesByItemTypeDay it
- JOIN(SELECT itemCategoryFk,
- itemTypeFk,
- dated,
- CAST(SUM(sale) AS DECIMAL(10,2)) sale,
+ JOIN(SELECT itemCategoryFk,
+ itemTypeFk,
+ dated,
+ CAST(SUM(sale) AS DECIMAL(10,2)) sale,
CAST(SUM(buy) AS DECIMAL(10,2))buy
- FROM(SELECT ic.id itemCategoryFk,
+ FROM(SELECT ic.id itemCategoryFk,
it.id itemTypeFk,
bs.dated,
SUM(bs.amount) sale,
0 buy
FROM bs.sale bs
JOIN vn.itemType it ON it.id = bs.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
JOIN vn.client c on c.id = bs.clientFk
JOIN vn.`time` tm ON tm.dated = bs.dated
JOIN vn.sale s ON s.id = bs.saleFk
- JOIN vn.item i ON i.id = s.itemFk
- WHERE ic.merchandise
+ JOIN vn.item i ON i.id = s.itemFk
+ WHERE ic.merchandise
AND bs.dated BETWEEN vDateStart AND vDateEnd
GROUP BY ic.id, it.id, bs.dated
- UNION ALL
- SELECT ic.id,
+ UNION ALL
+ SELECT ic.id,
it.id,
t.landed,
0 ,
SUM(b.buyingValue * b.quantity)
- FROM vn.entry e
- JOIN vn.travel t ON t.id = e.travelFk
- JOIN vn.buy b ON b.entryFk = e.id
- JOIN vn.item i ON i.id = b.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ FROM vn.entry e
+ JOIN vn.travel t ON t.id = e.travelFk
+ JOIN vn.buy b ON b.entryFk = e.id
+ JOIN vn.item i ON i.id = b.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
WHERE ic.merchandise
AND t.landed BETWEEN vDateStart AND vDateEnd
- GROUP BY ic.id, it.id, t.landed) sub
+ GROUP BY ic.id, it.id, t.landed) sub
GROUP BY itemCategoryFk, itemTypeFk, dated) sub2 ON sub2.dated = it.dated AND sub2.itemCategoryFk = it.itemCategoryFk AND sub2.itemTypeFk = it.itemTypeFk
SET it.sale = sub2.sale,
it.buy = sub2.buy;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.`component`;
CREATE TEMPORARY TABLE tmp.`component`
(PRIMARY KEY (`itemTypeFk`,`dated`),
@@ -4830,18 +4830,18 @@ BEGIN
KEY `salesByItemTypeDay_dated_idx` (`dated`))
ENGINE = MEMORY
SELECT DATE(t.shipped) dated,
- ic.id itemCategoryFk,
+ ic.id itemCategoryFk,
it.id itemTypeFk,
SUM(s.quantity * IF(c.code = 'purchaseValue', sc.value,0)) costComponent,
SUM(s.quantity * IF(ct.isMargin, sc.value,0)) marginComponent
FROM vn.ticket t
- JOIN vn.sale s ON t.id = s.ticketFk
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- JOIN vn.saleComponent sc ON sc.saleFk = s.id
- STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk
- JOIN vn.componentType ct ON ct.id = c.typeFk
+ JOIN vn.sale s ON t.id = s.ticketFk
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.saleComponent sc ON sc.saleFk = s.id
+ STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
WHERE t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY ic.id, it.id, dated;
@@ -4850,23 +4850,23 @@ BEGIN
SET it.costComponent = c.costComponent,
it.marginComponent = c.marginComponent,
it.saleComponent = c.costComponent + c.marginComponent;
-
- DROP TEMPORARY TABLE tmp.`component`;
-
+
+ DROP TEMPORARY TABLE tmp.`component`;
+
/* UPDATE bs.salesByItemTypeDay it
JOIN(SELECT DATE(t.shipped) dated,
- ic.id itemCategoryFk,
+ ic.id itemCategoryFk,
it.id itemTypeFk,
SUM(s.quantity * IF(c.code = 'purchaseValue', sc.value,0)) costComponent,
SUM(s.quantity * IF(ct.isMargin, sc.value,0)) marginComponent
FROM vn.ticket t
- JOIN vn.sale s ON t.id = s.ticketFk
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- JOIN vn.saleComponent sc ON sc.saleFk = s.id
- STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk
- JOIN vn.componentType ct ON ct.id = c.typeFk
+ JOIN vn.sale s ON t.id = s.ticketFk
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.itemCategory ic ON ic.id = it.categoryFk
+ JOIN vn.saleComponent sc ON sc.saleFk = s.id
+ STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
JOIN vn.`time` tm ON tm.dated = DATE(t.shipped)
WHERE t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY ic.id, it.id, dated)sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk
@@ -4914,35 +4914,35 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salesPersonEvolution_add`()
BEGIN
/**
- * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día.
+ * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día.
* Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio.
*/
DECLARE vDated DATE;
DECLARE vCont INT DEFAULT 1;
- SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated
+ SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated
FROM salesPersonEvolution;
- DELETE FROM salesPersonEvolution
+ DELETE FROM salesPersonEvolution
WHERE dated >= vDated;
IF ISNULL(vDated) THEN
- SELECT MIN(dated) INTO vDated
+ SELECT MIN(dated) INTO vDated
FROM salesByclientSalesPerson;
-
+
INSERT INTO salesPersonEvolution(
- salesPersonFk,
- dated,
- amount,
- equalizationTax,
+ salesPersonFk,
+ dated,
+ amount,
+ equalizationTax,
amountNewBorn
)
- SELECT salesPersonFk,
- dated,
- amount,
- equalizationTax,
+ SELECT salesPersonFk,
+ dated,
+ amount,
+ equalizationTax,
amountNewBorn
- FROM salesByclientSalesPerson
+ FROM salesByclientSalesPerson
WHERE dated = vDated
GROUP BY salesPersonFk;
@@ -4950,21 +4950,21 @@ BEGIN
END IF;
WHILE vDated < util.VN_CURDATE() DO
-
+
SET vCont = vCont + 1;
REPLACE salesPersonEvolution(salesPersonFk, dated, amount)
SELECT salesPersonFk, vDated, amount
FROM(SELECT salesPersonFk, SUM(amount) amount
FROM(SELECT salesPersonFk, amount
- FROM salesPersonEvolution
+ FROM salesPersonEvolution
WHERE dated = vDated - INTERVAL 1 DAY
UNION ALL
- SELECT salesPersonFk, amount
- FROM salesByclientSalesPerson
+ SELECT salesPersonFk, amount
+ FROM salesByclientSalesPerson
WHERE dated = vDated
UNION ALL
SELECT salesPersonFk, - amount
- FROM salesByclientSalesPerson
+ FROM salesByclientSalesPerson
WHERE dated = vDated - INTERVAL 1 YEAR
)sub
GROUP BY salesPersonFk
@@ -4993,7 +4993,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `vendedores_add_launcher`()
BEGIN
CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 45 DAY);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -5017,7 +5017,7 @@ BEGIN
/**
* Añade las ventas que se realizaron de hace
* una semana hasta hoy
-*
+*
* @param vStarted Fecha de inicio
* @param vEnded Fecha de finalizacion
*
@@ -5025,7 +5025,7 @@ BEGIN
DECLARE vStartingDate DATETIME;
DECLARE vEndingDate DATETIME;
- IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE())
+ IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE())
OR vEnded < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) THEN
CALL util.throw('fechaDemasiadoAntigua');
END IF;
@@ -5034,8 +5034,8 @@ BEGIN
SET vStartingDate = vStarted ;
SET vEndingDate = vn2008.dayend(vStartingDate);
- DELETE
- FROM sale
+ DELETE
+ FROM sale
WHERE dated BETWEEN vStartingDate AND vEnded;
WHILE vEndingDate <= vEnded DO
@@ -5056,28 +5056,28 @@ BEGIN
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.address a ON a.id = t.addressFk
+ JOIN vn.address a ON a.id = t.addressFk
JOIN vn.client cl ON cl.id = a.clientFk
WHERE t.shipped BETWEEN vStartingDate AND vEndingDate
AND s.quantity <> 0
AND s.discount <> 100
- AND ic.merchandise
+ AND ic.merchandise
GROUP BY sc.saleFk
HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0;
UPDATE sale s
JOIN (
- SELECT s.id,
+ SELECT s.id,
SUM(s.quantity * sc.value ) margen,
s.quantity * s.price * (100 - s.discount ) / 100 pvp
FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.saleComponent sc ON sc.saleFk = s.id
- JOIN vn.component c ON c.id = sc.componentFk
- JOIN vn.componentType ct ON ct.id = c.typeFk
+ JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk
WHERE t.shipped BETWEEN vStartingDate AND vEndingDate
AND ct.isMargin = TRUE
- GROUP BY s.id) sub ON sub.id = s.saleFk
+ GROUP BY s.id) sub ON sub.id = s.saleFk
SET s.margin = sub.margen + s.amount + s.surcharge - sub.pvp;
SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate);
@@ -5103,7 +5103,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_add_launcher`()
BEGIN
-
+
/**
* Añade las ventas que se realizaron de hace
* una semana hasta hoy
@@ -5130,7 +5130,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT)
BEGIN
-
+
/**
* Reemplaza las ventas contables del último año.
* Es el origen de datos para el balance de Entradas
@@ -5142,8 +5142,8 @@ BEGIN
DECLARE TIPO_PATRIMONIAL INT DEFAULT 188;
- DELETE FROM bs.ventas_contables
- WHERE year = vYear
+ DELETE FROM bs.ventas_contables
+ WHERE year = vYear
AND month = vMonth;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
@@ -5154,7 +5154,7 @@ BEGIN
FROM vn2008.Tickets t
JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura
WHERE year(f.Fecha) = vYear
- AND month(f.Fecha) = vMonth;
+ AND month(f.Fecha) = vMonth;
INSERT INTO bs.ventas_contables(year
, month
@@ -5164,7 +5164,7 @@ BEGIN
, tipo_id
, empresa_id
, gasto)
-
+
SELECT vYear
, vMonth
, round(sum(Cantidad * Preu * (100 - m.Descuento)/100))
@@ -5176,13 +5176,13 @@ BEGIN
, tp.reino_id
, a.tipo_id
, t.empresa_id
- , 7000000000
+ , 7000000000
+ IF(e.empresa_grupo = e2.empresa_grupo
,1
,IF(e2.empresa_grupo,2,0)
- ) * 1000000
+ ) * 1000000
+ tp.reino_id * 10000 as Gasto
- FROM vn2008.Movimientos m
+ FROM vn2008.Movimientos m
JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket
JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna
JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente
@@ -5196,7 +5196,7 @@ BEGIN
AND m.Descuento <> 100
AND a.tipo_id != TIPO_PATRIMONIAL
GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto;
-
+
INSERT INTO bs.ventas_contables(year
, month
, venta
@@ -5215,17 +5215,17 @@ BEGIN
) as grupo
, NULL
, NULL
- , t.companyFk
+ , t.companyFk
, 7050000000
- FROM vn.ticketService ts
+ FROM vn.ticketService ts
JOIN vn.ticket t ON ts.ticketFk = t.id
- JOIN vn.address a on a.id = t.addressFk
- JOIN vn.client cl on cl.id = a.clientFk
+ JOIN vn.address a on a.id = t.addressFk
+ JOIN vn.client cl on cl.id = a.clientFk
JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id
- JOIN vn.company c on c.id = t.companyFk
+ JOIN vn.company c on c.id = t.companyFk
LEFT JOIN vn.company c2 on c2.clientFk = cl.id
- GROUP BY grupo, t.companyFk ;
-
+ GROUP BY grupo, t.companyFk ;
+
DROP TEMPORARY TABLE tmp.ticket_list;
END ;;
DELIMITER ;
@@ -5245,13 +5245,13 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add_launcher`()
BEGIN
-
+
/**
* Reemplaza las ventas contables del último año.
* Es el origen de datos para el balance de Entradas
*
**/
-
+
CALL bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())));
END ;;
@@ -5272,12 +5272,12 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT)
BEGIN
-
+
/**
* Muestra las ventas (€) de cada cliente
* dependiendo del año
*/
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
CREATE TEMPORARY TABLE tmp.ticket_list
@@ -5286,8 +5286,8 @@ BEGIN
FROM vn2008.Tickets t
JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura
WHERE year(f.Fecha) = vYear
- AND month(f.Fecha) = vMonth;
-
+ AND month(f.Fecha) = vMonth;
+
SELECT vYear Año,
vMonth Mes,
t.Id_Cliente,
@@ -5297,7 +5297,7 @@ BEGIN
IF(e2.empresa_grupo,2,0))
AS grupo,
t.empresa_id empresa
- FROM vn2008.Movimientos m
+ FROM vn2008.Movimientos m
JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
JOIN vn2008.Clientes c ON c.Id_Cliente = cs.Id_Cliente
@@ -5311,9 +5311,9 @@ BEGIN
AND m.Descuento <> 100
AND a.tipo_id != 188
GROUP BY t.Id_Cliente, grupo,t.empresa_id;
-
+
DROP TEMPORARY TABLE tmp.ticket_list;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -5332,7 +5332,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `vivosMuertos`()
BEGIN
-
+
/**
* Devuelve el número de clientes nuevos y muertos,
* dependiendo de la fecha actual.
@@ -5343,9 +5343,9 @@ BEGIN
SET @datSTART = TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
SET @datEND = TIMESTAMPADD(DAY,-DAY(util.VN_CURDATE()),util.VN_CURDATE());
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos;
-
+
CREATE TEMPORARY TABLE tmp.VivosMuertos
SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto
FROM vn2008.Clientes c
@@ -5361,10 +5361,10 @@ BEGIN
WHERE Fecha BETWEEN @datSTART
AND @datEND) f ON f.yearMonth = tm.yearMonth
AND f.Id_Cliente = c.Id_Cliente;
-
+
UPDATE tmp.VivosMuertos vm
JOIN
- (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente
+ (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente
FROM vn2008.Facturas f
JOIN vn2008.time tm ON tm.date = f.Fecha
WHERE Fecha BETWEEN @datSTART AND @datEND
@@ -5372,9 +5372,9 @@ BEGIN
AND fm.Id_Cliente = vm.Id_Cliente
SET Nuevo = 1;
-
+
SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos;
-
+
UPDATE tmp.VivosMuertos vm
JOIN (
SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente
@@ -5415,23 +5415,23 @@ BEGIN
INTO vWeek, vYear
FROM vn.time
WHERE dated = util.VN_CURDATE();
-
+
REPLACE bs.waste
SELECT *, 100 * mermas / total as porcentaje
FROM (
- SELECT buyer,
- year,
+ SELECT buyer,
+ year,
week,
family,
itemFk,
itemTypeFk,
- floor(sum(value)) as total,
+ floor(sum(value)) as total,
floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas
- FROM vn.saleValue
+ FROM vn.saleValue
where year = vYear and week = vWeek
-
+
GROUP BY family, itemFk
-
+
) sub
ORDER BY mermas DESC;
END ;;
@@ -5463,56 +5463,56 @@ BEGIN
DECLARE vDateEnded DATE;
DECLARE vCursor CURSOR FOR
- SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated)
+ SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated)
FROM vn.time t
WHERE t.dated BETWEEN vDateStarted AND vDateEnded
- GROUP BY year,month;
+ GROUP BY year,month;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
IF DAY(util.VN_CURDATE()) = 21 THEN
-
+
SELECT util.firstDayOfMonth(DATE_SUB(util.VN_CURDATE(), INTERVAL 12 MONTH)),
LAST_DAY(DATE_SUB(util.VN_CURDATE(), INTERVAL 1 MONTH))
- INTO vDateStarted,
+ INTO vDateStarted,
vDateEnded;
-
- DELETE FROM workerLabourDataByMonth
+
+ DELETE FROM workerLabourDataByMonth
WHERE CONCAT(`year`, '-',`month`, '-01') BETWEEN vDateStarted AND vDateEnded;
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
-
+
FETCH vCursor INTO vFristDay, vLastDay;
-
+
IF vDone THEN
LEAVE l;
END IF;
-
+
-- Altas periodo
- INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
- SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
+ INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
+ SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
JOIN vn.worker w ON w.id = b.workerFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
LEFT JOIN (SELECT b.id, b.workerFk
FROM vn.business b
- LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl
+ LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl
ON wl.ended = DATE_SUB(b.started, INTERVAL 1 DAY) AND wl.workerFk = b.workerFk
- WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended
+ WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended
)sub ON sub.workerFk = b.workerFk
WHERE wc.payrollCenterFk IS NOT NULL
AND b.workCenterFk IS NOT NULL
AND b.started BETWEEN vFristDay AND vLastDay
AND sub.workerFk IS NULL
- AND NOT w.isFreelance;
+ AND NOT w.isFreelance;
-- Bajas periodo
- INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
- SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
+ INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
+ SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
@@ -5523,12 +5523,12 @@ BEGIN
AND b.ended BETWEEN vFristDay AND vLastDay
AND wl.started IS NULL
AND NOT w.isFreelance;
-
+
-- Anterior al periodo
SET vLastDay = LAST_DAY(DATE_SUB(vFristDay, INTERVAL 1 DAY));
- INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
- SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
+ INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
+ SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
@@ -5538,8 +5538,8 @@ BEGIN
AND NOT w.isFreelance;
-- Discapacidad
- INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
- SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
+ INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
+ SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
@@ -5573,8 +5573,8 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `workerProductivity_add`()
BEGIN
DECLARE vDateFrom DATE;
SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL 30 DAY) INTO vDateFrom;
-
- DELETE FROM workerProductivity
+
+ DELETE FROM workerProductivity
WHERE dated >= vDateFrom;
-- SACADORES Y ARTIFICIAL
@@ -5600,8 +5600,8 @@ BEGIN
JOIN vn.state s2 ON s2.id = st.stateFk
LEFT JOIN vn.workerDepartment wd ON wd.workerFk = st.workerFk
JOIN workerProductivityConfig wc ON TRUE
- WHERE t.shipped >= vDateFrom
- AND ISNULL(sp.saleFk)
+ WHERE t.shipped >= vDateFrom
+ AND ISNULL(sp.saleFk)
AND (s2.code IN ('OK PREVIOUS', 'PREVIOUS_PREPARATION', 'PREPARED', 'OK'))
GROUP BY t.id, t.warehouseFk, st.workerFk
) sub
@@ -5611,8 +5611,8 @@ BEGIN
INSERT INTO workerProductivity(dated, wareHouseFk, workerFk, volume, seconds, stateFk)
SELECT sub2.shipped,
sub2.warehouseFk,
- sub2.workerFK,
- SUM(sub2.volume),
+ sub2.workerFK,
+ SUM(sub2.volume),
SUM(sub2.seconds),
s2.id stateFk
FROM (SELECT t.warehouseFk,
@@ -5620,14 +5620,14 @@ BEGIN
sub.workerFk,
DATE(t.shipped) shipped,
sub.seconds + w.minSeconsPackager seconds,
- s.saleFk
+ s.saleFk
FROM vn.saleVolume s
JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN(SELECT e.workerFk, e.ticketFk,TIME_TO_SEC(TIMEDIFF( MAX(e.created), MIN(e.created))) seconds
+ JOIN(SELECT e.workerFk, e.ticketFk,TIME_TO_SEC(TIMEDIFF( MAX(e.created), MIN(e.created))) seconds
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE e.workerFk IS NOT NULL AND
- t.shipped >= vDateFrom
+ t.shipped >= vDateFrom
GROUP BY e.ticketFk
)sub ON sub.ticketFk = t.id
JOIN workerProductivityConfig w ON TRUE
@@ -5640,8 +5640,8 @@ BEGIN
INSERT INTO workerProductivity(dated, wareHouseFk, workerFk, volume, seconds, stateFk)
SELECT sub2.shipped,
sub2.warehouseFk,
- sub2.workerFK,
- SUM(sub2.volume),
+ sub2.workerFK,
+ SUM(sub2.volume),
SUM(sub2.seconds),
sub2.stateFk
FROM (SELECT t.warehouseFk,
@@ -5948,7 +5948,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `addressFriendship_Update`()
BEGIN
- REPLACE cache.addressFriendship
+ REPLACE cache.addressFriendship
SELECT addressFk1, addressFk2, count(*) friendship
FROM
(
@@ -5959,7 +5959,7 @@ BEGIN
AND t2.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE())
AND t.addressFk != t2.addressFk) sub
GROUP BY addressFk1, addressFk2;
-
+
REPLACE cache.zoneAgencyFriendship
SELECT r.agencyModeFk, t.zoneFk, count(*) friendship
FROM vn.route r
@@ -6133,12 +6133,12 @@ BEGIN
FROM available a
LEFT JOIN tCalc c ON c.id = a.calc_id
WHERE c.id IS NULL;
-
+
DELETE a
FROM availableNoRaids a
LEFT JOIN tCalc c ON c.id = a.calc_id
WHERE c.id IS NULL;
-
+
DROP TEMPORARY TABLE tCalc;
END ;;
DELIMITER ;
@@ -6400,9 +6400,9 @@ proc: BEGIN
INTO v_cache_id, v_calc, v_expires
FROM cache c
LEFT JOIN cache_calc ca
- ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci'
+ ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci'
WHERE c.name = v_cache_name COLLATE 'utf8_general_ci';
-
+
-- Si existe una calculo valido libera el bloqueo y devuelve su identificador.
IF !v_refresh AND util.VN_NOW() < v_expires
@@ -6466,7 +6466,7 @@ proc: BEGIN
FROM cache c
JOIN cache_calc ca ON c.id = ca.cache_id
WHERE ca.id = v_calc;
-
+
DELETE FROM cache_calc WHERE id = v_calc;
IF v_cache_name IS NOT NULL THEN
@@ -6511,8 +6511,8 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
-
- DECLARE vDateShort DATETIME;
+
+ DECLARE vDateShort DATETIME;
SET vDateShort = TIMESTAMPADD(MONTH, -1, util.VN_CURDATE());
@@ -6563,7 +6563,7 @@ DECLARE rs CURSOR FOR
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
- SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60;
+ SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60;
OPEN rs;
@@ -6572,23 +6572,23 @@ DECLARE rs CURSOR FOR
WHILE NOT done DO
SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0);
-
+
SET inicioProd = rsDeparture - rsHoras;
-
+
IF inicioProd - resto < myTime THEN
-
+
SET done = TRUE;
-
+
ELSE
-
+
SET departureLimit = rsDeparture;
-
+
FETCH rs INTO rsDeparture, rsHoras , rsInicio;
-
+
-- SELECT rsDeparture, rsHoras , rsInicio;
-
+
END IF;
-
+
END WHILE;
SET departureLimit = IFNULL(departureLimit,24);
@@ -6633,7 +6633,7 @@ proc: BEGIN
DECLARE started DATE;
DECLARE ended DATE;
DECLARE vLastRefresh DATE;
-
+
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
CALL cache_calc_unlock (vCalc);
@@ -6683,14 +6683,14 @@ proc: BEGIN
DECLARE datEQ DATETIME;
DECLARE timDIF TIME;
DECLARE v_calc INT;
-
+
CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id);
-
+
IF !v_refresh
THEN
LEAVE proc;
END IF;
-
+
CALL vn2008.production_control_source(wh_id, 0);
DELETE FROM prod_graphic_source;
@@ -6708,8 +6708,8 @@ proc: BEGIN
WHERE Fecha = util.VN_CURDATE()
GROUP BY wh_id, graphCategory
;
-
-
+
+
CALL cache_calc_end (v_calc);
END ;;
DELIMITER ;
@@ -6730,7 +6730,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `stock_refresh`(v_refresh BOOL)
proc: BEGIN
/**
- * Crea o actualiza la cache con el disponible hasta el dÃa de
+ * Crea o actualiza la cache con el disponible hasta el dÃa de
* ayer. Esta cache es usada como base para otros procedimientos
* como el cáculo del visible o del ATP.
*
@@ -6756,21 +6756,21 @@ proc: BEGIN
SET v_date_inv = (SELECT inventoried FROM vn.config LIMIT 1);
SET v_curdate = util.VN_CURDATE();
-
+
DELETE FROM stock;
-
+
INSERT INTO stock (item_id, warehouse_id, amount)
SELECT item_id, warehouse_id, SUM(amount) amount FROM
(
- SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount
+ SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount
FROM vn.itemTicketOut
WHERE shipped >= v_date_inv AND shipped < v_curdate
UNION ALL
- SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount
+ SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount
FROM vn.itemEntryIn
WHERE landed >= v_date_inv AND landed < v_curdate AND isVirtualStock is FALSE
UNION ALL
- SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount
+ SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount
FROM vn.itemEntryOut
WHERE shipped >= v_date_inv AND shipped < v_curdate
) t
@@ -6800,12 +6800,12 @@ BEGIN
(INDEX (id))
ENGINE = MEMORY
SELECT id FROM cache_calc;
-
+
DELETE v
FROM visible v
LEFT JOIN tCalc c ON c.id = v.calc_id
WHERE c.id IS NULL;
-
+
DROP TEMPORARY TABLE tCalc;
END ;;
DELIMITER ;
@@ -6836,11 +6836,11 @@ proc: BEGIN
IF !v_refresh THEN
LEAVE proc;
END IF;
-
+
-- Calculamos el stock hasta ayer
-
+
CALL `cache`.stock_refresh(false);
-
+
DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item;
CREATE TEMPORARY TABLE vn2008.tmp_item
(PRIMARY KEY (item_id))
@@ -6849,9 +6849,9 @@ proc: BEGIN
WHERE warehouse_id = v_warehouse;
-- Calculamos los movimientos confirmados de hoy
- CALL vn.item_GetVisible(v_warehouse, NULL);
+ CALL vn.item_GetVisible(v_warehouse, NULL);
DELETE FROM visible WHERE calc_id = v_calc;
-
+
INSERT INTO visible (calc_id, item_id,visible)
SELECT v_calc, item_id, visible FROM vn2008.tmp_item;
@@ -7717,9 +7717,9 @@ DELIMITER ;;
BEGIN
DECLARE nextID INT;
-
+
SELECT 1 + MAX(id) INTO nextID FROM putOrder ;
-
+
SET NEW.orderTradelineItemID = nextID;
END */;;
@@ -7741,36 +7741,36 @@ DELIMITER ;;
BEFORE UPDATE ON `putOrder`
FOR EACH ROW
BEGIN
-
+
DECLARE vError VARCHAR(100) DEFAULT 'Orderregel niet meer teruggevonden op basis van de orderps';
DECLARE vVmpIdError INT DEFAULT 7;
DECLARE vVmpFk INT;
DECLARE vSupplyResponseNumberOfUnits INT;
-
- SELECT sr.vmpID INTO vVmpFk
- FROM edi.supplyResponse sr
+
+ SELECT sr.vmpID INTO vVmpFk
+ FROM edi.supplyResponse sr
WHERE sr.id = NEW.supplyResponseID;
-
- IF NEW.OrderStatus = 3
- AND NOT (NEW.OrderStatus <=> OLD.OrderStatus)
- AND NEW.error = vError
- AND vVmpFk = vVmpIdError
-
- THEN
-
+
+ IF NEW.OrderStatus = 3
+ AND NOT (NEW.OrderStatus <=> OLD.OrderStatus)
+ AND NEW.error = vError
+ AND vVmpFk = vVmpIdError
+
+ THEN
+
SET NEW.OrderStatus = 2;
-
+
END IF;
-
+
-- Error de disponible menor de lo solicitado
IF NEW.error LIKE 'error2602%' THEN
-
+
SELECT NumberOfUnits INTO vSupplyResponseNumberOfUnits
- FROM edi.supplyResponse sr
+ FROM edi.supplyResponse sr
WHERE sr.ID = NEW.supplyResponseID;
-
+
SET NEW.error = CONCAT('(',vSupplyResponseNumberOfUnits,') ', NEW.error);
-
+
END IF;
END */;;
DELIMITER ;
@@ -7797,16 +7797,16 @@ BEGIN
DECLARE vIsEktSender BOOLEAN;
IF NEW.OrderStatus = vOrderStatusDenied AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN
-
+
SELECT s.id INTO vSaleFk
- FROM vn.sale s
+ FROM vn.sale s
JOIN vn.ticket t ON s.ticketFk = t.id
JOIN vn.item i ON i.id = s.itemFk
JOIN deliveryInformation di ON di.ID = NEW.deliveryInformationID
WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE()
AND i.supplyResponseFk = NEW.supplyResponseID
LIMIT 1;
-
+
UPDATE vn.sale s
JOIN vn.ticket t ON s.ticketFk = t.id
JOIN vn.item i ON i.id = s.itemFk
@@ -7814,7 +7814,7 @@ BEGIN
SET s.quantity = 0
WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE()
AND i.supplyResponseFk = NEW.supplyResponseID;
-
+
INSERT INTO vn.mail (sender, `subject`, body)
SELECT IF(u.id IS NOT NULL AND c.email IS NOT NULL,
c.email,
@@ -7826,26 +7826,26 @@ BEGIN
IF (u.id IS NOT NULL AND c.email IS NOT NULL ,
CONCAT('https://shop.verdnatura.es/#!form=ecomerce%2Fticket&ticket=', t.id ),
CONCAT('https://salix.verdnatura.es/#!/ticket/', t.id ,'/summary')))
- FROM vn.sale s
+ FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.`client` c ON c.id = t.clientFk
LEFT JOIN account.user u ON u.id= c.salesPersonFk AND u.name IN ('ruben', 'ismaelalcolea')
WHERE s.id = vSaleFk;
-
+
END IF;
IF NEW.OrderStatus = vOrderStatusOK AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN
- SELECT v.isEktSender INTO vIsEktSender
+ SELECT v.isEktSender INTO vIsEktSender
FROM edi.VMPSettings v
- JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID
+ JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID
WHERE sr.id = NEW.supplyResponseID;
-
+
IF NOT vIsEktSender THEN
CALL edi.ekt_add(NEW.id);
-
+
END IF;
IF NEW.barcode THEN
@@ -7854,7 +7854,7 @@ BEGIN
SELECT i.id, NEW.barcode
FROM vn.item i
WHERE i.supplyResponseFk = NEW.supplyResponseID;
-
+
END IF;
END IF;
@@ -8053,8 +8053,8 @@ BEGIN
UPDATE vn.buy b
JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel tr ON tr.id = e.travelFk
- JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
+ JOIN vn.travel tr ON tr.id = e.travelFk
+ JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
JOIN vn.item i ON i.id = b.itemFk
JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID
SET b.quantity = NEW.NumberOfItemsPerCask * NEW.NumberOfUnits,
@@ -8063,7 +8063,7 @@ BEGIN
AND am.name = 'LOGIFLORA'
AND e.isRaid
AND tr.landed >= util.VN_CURDATE();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -8205,7 +8205,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `imageName`(vPictureReference VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 COLLATE utf8_unicode_ci
DETERMINISTIC
BEGIN
-
+
SET vPictureReference = REPLACE(vPictureReference,'.','');
SET vPictureReference = REPLACE(vPictureReference,'/','');
@@ -8217,7 +8217,7 @@ BEGIN
SET vPictureReference = REPLACE(vPictureReference,'?','');
SET vPictureReference = REPLACE(vPictureReference,'=','');
-
+
RETURN vPictureReference;
END ;;
@@ -8243,15 +8243,15 @@ BEGIN
DECLARE vOneWeekAgo DATE DEFAULT TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
DELETE FROM ekt WHERE fec < vFourYearsAgo;
-
+
DELETE IGNORE sr.*
FROM supplyResponse sr
LEFT JOIN edi.deliveryInformation di ON sr.ID = di.supplyResponseID
WHERE di.LatestOrderDateTime < vOneWeekAgo OR di.ID IS NULL;
-
- DELETE FROM putOrder
+
+ DELETE FROM putOrder
WHERE created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE());
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -8270,27 +8270,27 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryInformation_Delete`()
BEGIN
-
+
DECLARE vID INT;
DECLARE vGap INT DEFAULT 100;
DECLARE vTope INT;
-
- SELECT MIN(ID), MAX(ID)
+
+ SELECT MIN(ID), MAX(ID)
INTO vID, vTope
FROM edi.deliveryInformation;
- WHILE vID <= vTope DO
-
+ WHILE vID <= vTope DO
+
SET vID = vID + vGap;
-
- DELETE
- FROM edi.deliveryInformation
+
+ DELETE
+ FROM edi.deliveryInformation
WHERE ID < vID
AND EarliestDespatchDateTime IS NULL;
-
+
END WHILE;
-
-
+
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -8309,15 +8309,15 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_add`(vPutOrderFk INT)
BEGIN
-
+
/**
* Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email
- *
+ *
* @param vPutOrderFk PutOrderId de donde coger los datos
**/
-
- INSERT INTO edi.ekt(entryYear,
- deliveryNumber,
+
+ INSERT INTO edi.ekt(entryYear,
+ deliveryNumber,
fec,
hor,
item,
@@ -8357,17 +8357,17 @@ BEGIN
i.value10 s6,
p.id putOrderFk,
sr.Item_ArticleCode,
- sr.vmpID
+ sr.vmpID
FROM edi.putOrder p
- JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID
- JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID
- JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
- JOIN vn.item i ON i.supplyResponseFk = sr.ID
- JOIN vn.origin o ON o.id = i.originFk
+ JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID
+ JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID
+ JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
+ JOIN vn.item i ON i.supplyResponseFk = sr.ID
+ JOIN vn.origin o ON o.id = i.originFk
WHERE p.id = vPutOrderFk;
-
+
CALL edi.ekt_load(LAST_INSERT_ID());
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -8386,7 +8386,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_load`(IN `vSelf` INT)
proc:BEGIN
-
+
DECLARE vRef INT;
DECLARE vBuy INT;
DECLARE vItem INT;
@@ -8411,51 +8411,51 @@ proc:BEGIN
FROM edi.ekt e
LEFT JOIN edi.item i ON e.ref = i.id
LEFT JOIN edi.putOrder po ON po.id = e.putOrderFk
- LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID
+ LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID
LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
LEFT JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id
WHERE e.id = vSelf
LIMIT 1;
-
+
IF NOT vHasItemGroup THEN
-
+
CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription);
-
+
CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription);
-
+
LEAVE proc;
-
+
END IF;
-
+
-- Asigna la entrada
SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk;
-
+
-- Inserta el cubo si no existe
IF vPackage = 800 THEN
-
+
SET vHasToChangePackagingFk = TRUE;
-
+
IF vItem THEN
-
+
SELECT vn.item_getPackage(vItem) INTO vPackage ;
-
+
ELSE
-
+
SET vPackage = 8000 + vQty;
INSERT IGNORE INTO vn.packaging(id, width, `depth`)
SELECT vPackage, vc.ccLength / vQty, vc.ccWidth
FROM vn.volumeConfig vc;
-
+
END IF;
-
+
ELSE
-
+
INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z)
SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10)
FROM bucket WHERE bucket_id = vPackage;
-
+
IF ROW_COUNT() > 0
THEN
INSERT INTO vn2008.mail SET
@@ -8464,27 +8464,27 @@ proc:BEGIN
`to` = 'ekt@verdnatura.es';
END IF;
END IF;
-
+
-- Si es una compra de Logiflora obtiene el articulo
IF vPutOrderFk THEN
-
+
SELECT i.id INTO vItem
FROM edi.putOrder po
JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID
WHERE po.id = vPutOrderFk
LIMIT 1;
-
+
END IF;
INSERT IGNORE INTO item_track SET
item_id = vRef;
-
+
IF IFNULL(vItem,0) = 0 THEN
-
+
-- Intenta obtener el artículo en base a los atributos holandeses
-
+
SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem
- FROM edi.ekt e
+ FROM edi.ekt e
JOIN edi.item_track t ON t.item_id = e.ref
LEFT JOIN edi.ekt l ON l.ref = e.ref
LEFT JOIN vn.buy b ON b.ektFk = l.id
@@ -8505,19 +8505,19 @@ proc:BEGIN
AND IF(t.pro, l.pro = e.pro, TRUE)
AND IF(t.package, l.package = e.package, TRUE)
AND IF(t.item, l.item = e.item, TRUE)
- AND i.isFloramondo = vIsFloramondoDirect
- ORDER BY l.util.VN_NOW DESC, b.id ASC
+ AND i.isFloramondo = vIsFloramondoDirect
+ ORDER BY l.util.VN_NOW DESC, b.id ASC
LIMIT 1;
END IF;
-
+
-- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo
IF ISNULL(vItem) AND vIsFloramondoDirect THEN
-
+
CALL edi.item_getNewByEkt(vSelf, vItem);
-
+
END IF;
-
+
INSERT INTO vn.buy
(
entryFk
@@ -8540,15 +8540,15 @@ proc:BEGIN
,e.qty stickers
,@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing
,IFNULL(b.`grouping`, e.pac)
- ,@pac * e.qty
+ ,@pac * e.qty
,vForceToPacking
,IF(vHasToChangePackagingFk OR ISNULL(b.packageFk), vPackage, b.packageFk)
,(IFNULL(i.weightByPiece,0) * @pac)/1000
- FROM edi.ekt e
+ FROM edi.ekt e
LEFT JOIN vn.buy b ON b.id = vBuy
LEFT JOIN vn.item i ON i.id = b.itemFk
LEFT JOIN vn.supplier s ON e.pro = s.id
- JOIN vn2008.config cfg
+ JOIN vn2008.config cfg
WHERE e.id = vSelf
LIMIT 1;
@@ -8556,36 +8556,36 @@ proc:BEGIN
CREATE TEMPORARY TABLE tmp.buyRecalc
SELECT buy.id
- FROM vn.buy
+ FROM vn.buy
WHERE ektFk = vSelf;
CALL vn.buy_recalcPrices();
-- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy
IF vPutOrderFk THEN
-
+
REPLACE vn.saleBuy(saleFk, buyFk, workerFk)
SELECT po.saleFk, b.id, account.myUser_getId()
FROM edi.putOrder po
JOIN vn.buy b ON b.ektFk = vSelf
WHERE po.id = vPutOrderFk;
-
+
END IF;
- -- Si es una compra directa en Floramondo hay que añadirlo al ticket
+ -- Si es una compra directa en Floramondo hay que añadirlo al ticket
IF vIsFloramondoDirect THEN
SELECT t.id INTO vTicketFk
FROM vn.ticket t
- JOIN vn.ektEntryAssign eea
- ON eea.addressFk = t.addressFk
+ JOIN vn.ektEntryAssign eea
+ ON eea.addressFk = t.addressFk
AND t.warehouseFk = eea.warehouseInFk
- JOIN edi.ekt e
- ON e.sub = eea.sub
+ JOIN edi.ekt e
+ ON e.sub = eea.sub
AND e.id = vSelf
WHERE e.fec = t.shipped
LIMIT 1;
-
+
IF ISNULL(vTicketFk) THEN
INSERT INTO vn.ticket (
@@ -8613,8 +8613,8 @@ proc:BEGIN
z.id,
z.price,
z.bonus
- FROM edi.ekt e
- JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
+ FROM edi.ekt e
+ JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
JOIN vn.address a ON a.id = eea.addressFk
JOIN vn.company c ON c.code = 'VNL'
JOIN vn.`zone` z ON z.code = 'FLORAMONDO'
@@ -8622,11 +8622,11 @@ proc:BEGIN
LIMIT 1;
SET vTicketFk = LAST_INSERT_ID();
-
+
INSERT INTO vn.ticketLog
- SET originFk = vTicketFk,
- userFk = account.myUser_getId(),
- `action` = 'insert',
+ SET originFk = vTicketFk,
+ userFk = account.myUser_getId(),
+ `action` = 'insert',
description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk);
END IF;
@@ -8636,9 +8636,9 @@ proc:BEGIN
FROM edi.ekt e
JOIN edi.floraHollandConfig fhc
WHERE e.id = vSelf;
-
+
SELECT LAST_INSERT_ID() INTO vSaleFk;
-
+
REPLACE vn.saleBuy(saleFk, buyFk, workerFk)
SELECT vSaleFk, b.id, account.myUser_getId()
FROM vn.buy b
@@ -8649,9 +8649,9 @@ proc:BEGIN
FROM edi.ekt e
JOIN vn.component c ON c.code = 'purchaseValue'
WHERE e.id = vSelf;
-
+
INSERT INTO vn.saleComponent(saleFk, componentFk, value)
- SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin
+ SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin
FROM edi.ekt e
JOIN edi.floraHollandConfig fhc
JOIN vn.component c ON c.code = 'margin'
@@ -8676,7 +8676,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_loadNotBuy`()
BEGIN
-
+
/**
* Ejecuta ekt_load para aquellos ekt de hoy que no tienen vn.buy
*/
@@ -8686,24 +8686,24 @@ BEGIN
DECLARE cursor1 CURSOR FOR SELECT e.id
- FROM edi.ekt e
- LEFT JOIN vn.buy b ON b.ektFk = e.id
- WHERE e.fec >= util.VN_CURDATE()
+ FROM edi.ekt e
+ LEFT JOIN vn.buy b ON b.ektFk = e.id
+ WHERE e.fec >= util.VN_CURDATE()
AND ISNULL(b.ektFk);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cursor1;
bucle: LOOP
-
+
FETCH cursor1 INTO vEktFk;
-
+
IF done THEN
LEAVE bucle;
END IF;
-
+
CALL edi.ekt_load(vEktFk);
-
+
END LOOP bucle;
CLOSE cursor1;
@@ -8795,7 +8795,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_scan`(vBarcode VARCHAR(512))
BEGIN
/**
* Busca transaciones a partir de un código de barras, las marca como escaneadas
- * y las devuelve.
+ * y las devuelve.
* Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura
*
* @param vBarcode Código de compra de una etiqueta de subasta
@@ -8834,19 +8834,19 @@ BEGIN
ENGINE = MEMORY
SELECT id ektFk FROM ekt LIMIT 0;
- CASE
+ CASE
WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
WHERE e.cps = vBarcode
OR e.batchNumber = vBarcode;
WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN
INSERT INTO tmp.ekt
- SELECT e.id
+ SELECT e.id
FROM edi.ektRecent e
- WHERE e.pro = MID(vBarcode,2,6)
+ WHERE e.pro = MID(vBarcode,2,6)
AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5);
ELSE
@@ -8861,7 +8861,7 @@ BEGIN
-- Clásico de subasta
-- Trade standard
-- Trade que construye como la subasta
- -- Trade como el anterior pero sin trade code
+ -- Trade como el anterior pero sin trade code
INSERT INTO tmp.ekt
SELECT id
FROM ekt
@@ -8882,9 +8882,9 @@ BEGIN
-- BatchNumber largo
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
- WHERE e.batchNumber
+ WHERE e.batchNumber
= LEFT(vBarcode,vUsefulAuctionLeftSegmentLength)
AND e.batchNumber > 0;
@@ -8894,7 +8894,7 @@ BEGIN
-- Order Number
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
WHERE e.putOrderFk = vBarcode;
@@ -8904,7 +8904,7 @@ BEGIN
-- deliveryNumber incrustado
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
- SELECT id
+ SELECT id
FROM edi.ektRecent e
WHERE e.deliveryNumber
= MID(vBarcode, 4, 13)
@@ -8915,7 +8915,7 @@ BEGIN
END CASE;
IF vIsFound THEN
- UPDATE ekt e
+ UPDATE ekt e
JOIN tmp.ekt t ON t.ektFk = e.id
SET e.scanned = TRUE;
END IF;
@@ -8961,7 +8961,7 @@ proc: BEGIN
ROLLBACK;
RESIGNAL;
END;
-
+
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('edi.floramondo_offerRefresh');
@@ -8971,10 +8971,10 @@ proc: BEGIN
IF 'test' = (SELECT environment FROM util.config) THEN
LEAVE proc;
END IF;
-
+
IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN
LEAVE proc;
- END IF;
+ END IF;
SET vStartingTime = util.VN_NOW();
@@ -9479,7 +9479,7 @@ BEGIN
/**
* Devuelve un número nuevo de item a partir de un registro de la tabla edi.ekt
- *
+ *
* @param vEktFk Identificador de la tabla edi.ekt
*/
@@ -9488,17 +9488,17 @@ BEGIN
SELECT MIN(id) id INTO vItemFk
FROM edi.item_free;
- DELETE FROM edi.item_free
+ DELETE FROM edi.item_free
WHERE id = vItemFk;
-
+
COMMIT;
-
+
IF ISNULL(vItemFk) THEN
SELECT MAX(i.id) + 1
INTO vItemFk
FROM vn.item i;
END IF;
-
+
INSERT INTO vn.item(id,
@@ -9525,118 +9525,118 @@ BEGIN
least(IF((e.package = 800),((e.package * 10) + e.pac), e.package), ifnull(idt.bucket_id, '999')) packageFk,
e.cat,
TRUE
- FROM edi.ekt e
- JOIN edi.item i ON i.id = e.`ref`
- JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id
- LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref`
+ FROM edi.ekt e
+ JOIN edi.item i ON i.id = e.`ref`
+ JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id
+ LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref`
WHERE e.id = vEktFk;
SET @isTriggerDisabled = TRUE;
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.item , 1
- FROM edi.ekt e
+ SELECT vItemFk, t.id , e.item , 1
+ FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Producto'
WHERE e.id = vEktFk
AND NOT ISNULL(e.item);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.cat , 3
- FROM edi.ekt e
+ SELECT vItemFk, t.id , e.cat , 3
+ FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Calidad'
WHERE e.id = vEktFk
AND NOT ISNULL(e.cat);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , s.company_name , 4
- FROM edi.ekt e
+ SELECT vItemFk, t.id , s.company_name , 4
+ FROM edi.ekt e
JOIN edi.supplier s ON s.supplier_id = e.pro
JOIN vn.tag t ON t.`name` = 'Productor'
WHERE e.id = vEktFk
AND NOT ISNULL(s.company_name);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s1, 5
+ SELECT vItemFk, t.id , e.s1, 5
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
- AND eif.presentation_order = 1
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ AND eif.presentation_order = 1
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s1 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s1);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s2, 6
+ SELECT vItemFk, t.id , e.s2, 6
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
- AND eif.presentation_order = 2
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ AND eif.presentation_order = 2
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s2 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s2);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s3, 7
+ SELECT vItemFk, t.id , e.s3, 7
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
- AND eif.presentation_order = 3
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ AND eif.presentation_order = 3
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s3 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s3);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s4, 8
+ SELECT vItemFk, t.id , e.s4, 8
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 4
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s4 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s4);
-
+
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s5, 9
+ SELECT vItemFk, t.id , e.s5, 9
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 5
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s5 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s5);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id , e.s6, 10
+ SELECT vItemFk, t.id , e.s6, 10
FROM edi.ekt e
- LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
+ LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 6
AND eif.expiry_date IS NULL
- LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
+ LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s6 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s6);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11
- FROM edi.ekt e
+ SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11
+ FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Color'
- LEFT JOIN edi.feature f ON f.item_id = e.`ref`
+ LEFT JOIN edi.feature f ON f.item_id = e.`ref`
LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1'
LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value
LEFT JOIN vn.itemInk ik ON ik.longName = e.item
WHERE e.id = vEktFk
- AND ( ink.name IS NOT NULL
+ AND ( ink.name IS NOT NULL
OR ik.color IS NOT NULL)
LIMIT 1;
@@ -9648,8 +9648,8 @@ BEGIN
CALL vn.item_refreshTags();
- SET @isTriggerDisabled = FALSE;
-
+ SET @isTriggerDisabled = FALSE;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -9695,7 +9695,7 @@ BEGIN
sender = vSender,
senderFk = vSenderId,
messageId = vMessageId;
-
+
IF vIsDuplicated THEN
SELECT id INTO vSelf
FROM mail
@@ -9721,26 +9721,26 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_calcCompByFloramondo`(vSelf INT)
BEGIN
-
+
/**
* Recalcula "a pelo" los componentes para un ticket de Floramondo
- *
+ *
* Pendiente de concretar la solución cuando Logiflora conteste.
- *
+ *
* @param vSelf Identificador de vn.ticket
*/
-
+
CALL cache.last_buy_refresh(TRUE);
- DELETE sc.*
+ DELETE sc.*
FROM vn.saleComponent sc
- JOIN vn.sale s ON s.id = sc.saleFk
+ JOIN vn.sale s ON s.id = sc.saleFk
WHERE s.ticketFk = vSelf;
UPDATE vn.sale s
- JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.item i ON i.id = s.itemFk
JOIN edi.floraHollandConfig fhc
- LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
+ LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
LEFT JOIN vn.buy b ON b.id = lb.buy_id
LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo'
SET s.price = b.buyingValue * (1 + fhc.floramondoMargin)
@@ -9749,18 +9749,18 @@ BEGIN
INSERT INTO vn.saleComponent(saleFk, componentFk, value)
SELECT s.id, c.id, MAX(b.buyingValue)
FROM vn.sale s
- JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.item i ON i.id = s.itemFk
LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
LEFT JOIN vn.buy b ON b.id = lb.buy_id
LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo'
JOIN vn.component c ON c.code = 'purchaseValue'
WHERE s.ticketFk = vSelf
GROUP BY s.id;
-
+
INSERT INTO vn.saleComponent(saleFk, componentFk, value)
- SELECT s.id, c.id, MAX(b.buyingValue) * fhc.floramondoMargin
+ SELECT s.id, c.id, MAX(b.buyingValue) * fhc.floramondoMargin
FROM vn.sale s
- JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.item i ON i.id = s.itemFk
JOIN edi.floraHollandConfig fhc
LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
LEFT JOIN vn.buy b ON b.id = lb.buy_id
@@ -10621,7 +10621,7 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterInsert`
AFTER INSERT ON `order`
FOR EACH ROW
-BEGIN
+BEGIN
IF NEW.address_id = 2850 THEN
-- Fallo que se insertan no se sabe como tickets en este cliente
CALL vn.mail_insert(
@@ -10630,7 +10630,7 @@ BEGIN
'Creada order al address 2850',
CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id)
);
-
+
END IF;
END */;;
DELIMITER ;
@@ -10652,7 +10652,7 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
CALL stock.log_add('order', NEW.id, OLD.id);
-
+
IF !(OLD.address_id <=> NEW.address_id)
OR !(OLD.company_id <=> NEW.company_id)
OR !(OLD.customer_id <=> NEW.customer_id) THEN
@@ -10782,12 +10782,12 @@ DELIMITER ;;
BEGIN
DECLARE vIsFirst BOOL;
- SELECT (first_row_stamp IS NULL) INTO vIsFirst
- FROM `order`
+ SELECT (first_row_stamp IS NULL) INTO vIsFirst
+ FROM `order`
WHERE id = NEW.orderFk;
IF vIsFirst THEN
- UPDATE `order` SET first_row_stamp = util.VN_NOW()
+ UPDATE `order` SET first_row_stamp = util.VN_NOW()
WHERE id = NEW.orderFk;
END IF;
END */;;
@@ -11183,6 +11183,10 @@ CREATE TABLE `tpvTransaction` (
`errorCode` char(7) DEFAULT NULL,
`status` enum('started','ok','ko') NOT NULL DEFAULT 'started',
`created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `merchantParameters` text DEFAULT NULL,
+ `signature` varchar(255) DEFAULT NULL,
+ `signatureVersion` varchar(50) DEFAULT NULL,
+ `responseError` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `merchant_id` (`merchantFk`),
KEY `receipt_id` (`receiptFk`),
@@ -11192,7 +11196,7 @@ CREATE TABLE `tpvTransaction` (
CONSTRAINT `receipt_id` FOREIGN KEY (`receiptFk`) REFERENCES `vn`.`receipt` (`Id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `tpvTransaction_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `tpvTransaction_ibfk_2` FOREIGN KEY (`merchantFk`) REFERENCES `tpvMerchant` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Transactions realized through the virtual TPV';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Transactions realized through the virtual TPV';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -11400,7 +11404,7 @@ BEGIN
IF vCount = 0 THEN
RETURN FALSE;
- END IF;
+ END IF;
SELECT COUNT(*) > 0
INTO vHasRole
@@ -11481,14 +11485,14 @@ BEGIN
* @return tmp.ticketComponent
* @return tmp.ticketLot
* @return tmp.zoneGetShipped
- */
+ */
DECLARE vAgencyMode INT;
-
+
SELECT a.agencyModeFk
INTO vAgencyMode
FROM myClient c
JOIN vn.address a ON a.clientFk = c.id
- WHERE a.id = vAddress;
+ WHERE a.id = vAddress;
CALL vn.available_calc(vDelivery, vAddress, vAgencyMode);
@@ -11501,7 +11505,7 @@ BEGIN
JOIN tmp.availableCalc a ON a.calcFk = c.calc_id
WHERE c.available > 0
GROUP BY c.item_id;
-
+
CALL vn.catalog_calculate(vDelivery, vAddress, vAgencyMode);
DROP TEMPORARY TABLE tmp.item;
@@ -11553,7 +11557,7 @@ BEGIN
JOIN tmp.availableCalc a ON a.calcFk = c.calc_id
WHERE c.available > 0
GROUP BY c.item_id;
-
+
CALL vn.catalog_calculate_beta(vDelivery, vAddress, vAgencyMode);
DROP TEMPORARY TABLE tmp.item;
@@ -11655,7 +11659,7 @@ BEGIN
*/
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT vSelf itemFk;
CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
@@ -11695,7 +11699,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`(
vType INT,
vPrefix VARCHAR(255))
BEGIN
-
+
/**
* Gets visible items of the specified type at specified date.
*
@@ -11704,7 +11708,7 @@ BEGIN
* @param vType The type id
* @param vPrefix The article prefix to filter or %NULL for all
* @return tmp.itemVisible Visible items
- */
+ */
DECLARE vPrefixLen SMALLINT;
DECLARE vFilter VARCHAR(255) DEFAULT NULL;
DECLARE vDateInv DATE DEFAULT vn2008.date_inv();
@@ -11713,13 +11717,13 @@ BEGIN
GET DIAGNOSTICS CONDITION 1
@message = MESSAGE_TEXT;
CALL vn.mail_insert(
- 'cau@verdnatura.es',
- NULL,
+ 'cau@verdnatura.es',
+ NULL,
CONCAT('hedera.item_getVisible error: ', @message),
CONCAT(
- 'warehouse: ', IFNULL(vWarehouse, ''),
- ', Fecha:', IFNULL(vDate, ''),
- ', tipo: ', IFNULL(vType,''),
+ 'warehouse: ', IFNULL(vWarehouse, ''),
+ ', Fecha:', IFNULL(vDate, ''),
+ ', tipo: ', IFNULL(vType,''),
', prefijo: ', IFNULL(vPrefix,'')));
RESIGNAL;
END;
@@ -11798,7 +11802,7 @@ BEGIN
IF(p.depth > 0, p.depth, 0) depth, p.width, p.height,
CEIL(s.quantity / t.packing) etiquetas
FROM vn.item i
- JOIN `filter` f ON f.itemFk = i.id
+ JOIN `filter` f ON f.itemFk = i.id
JOIN currentStock s ON s.itemFk = i.id
LEFT JOIN tmp t ON t.itemFk = i.id
LEFT JOIN vn.packaging p ON p.id = t.packageFk
@@ -11972,7 +11976,7 @@ BEGIN
IF vStatus = 'OK'
THEN
CALL order_checkConfig(vSelf);
-
+
IF vStatus = 'OK' AND vCreated < TIMESTAMPADD(DAY, -1, util.VN_NOW())
THEN
CALL order_update(vSelf);
@@ -12128,7 +12132,7 @@ BEGIN
IF vSelf IS NOT NULL THEN
CALL order_confirm(vSelf);
-
+
DELETE FROM basketOrder
WHERE orderFk = vSelf;
END IF;
@@ -12184,9 +12188,9 @@ BEGIN
CREATE TEMPORARY TABLE tmp.`order`
ENGINE = MEMORY
SELECT myBasket_getId() orderFk;
-
+
CALL order_getTax();
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.`order`;
END ;;
DELIMITER ;
@@ -12215,7 +12219,7 @@ BEGIN
SELECT COUNT(*) INTO vIsMine
FROM myOrder
WHERE id = vSelf;
-
+
IF vIsMine THEN
CALL order_addItem(vSelf, vWarehouse, vItem, vAmount);
END IF;
@@ -12238,11 +12242,11 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_confirm`(vSelf INT)
BEGIN
DECLARE vIsMine BOOL;
-
- SELECT COUNT(*) INTO vIsMine
+
+ SELECT COUNT(*) INTO vIsMine
FROM myOrder
WHERE id = vSelf;
-
+
IF vIsMine THEN
CALL order_confirm(vSelf);
END IF;
@@ -12275,7 +12279,7 @@ BEGIN
SELECT COUNT(*) INTO isMine
FROM myOrder
WHERE id = vSelf;
-
+
IF isMine THEN
CALL order_getAvailable(vSelf);
END IF;
@@ -12321,15 +12325,15 @@ BEGIN
START TRANSACTION;
- SELECT a.agencyModeFk, a.id
+ SELECT a.agencyModeFk, a.id
INTO vAgencyMode, vAddressFk
- FROM vn.address a
+ FROM vn.address a
WHERE a.id = vAddressFk;
-
+
SELECT deliveryMethodFk INTO vDeliveryMethodId
FROM vn.agencyMode am
WHERE am.id = vAgencyMode;
-
+
IF vCompany IS NULL
THEN
SELECT defaultCompanyFk INTO vCompany
@@ -12347,7 +12351,7 @@ BEGIN
company_id = vCompany;
SET vSelf = LAST_INSERT_ID();
-
+
CALL order_checkConfig(vSelf);
COMMIT;
@@ -12393,15 +12397,15 @@ BEGIN
START TRANSACTION;
- SELECT a.agencyModeFk, a.id
+ SELECT a.agencyModeFk, a.id
INTO vAgencyMode, vAddress
FROM myClient c
JOIN vn.address a ON a.id = c.defaultAddressFk;
-
+
SELECT deliveryMethodFk INTO vDeliveryMethodId
FROM vn.agencyMode am
WHERE am.id = vAgencyMode;
-
+
IF vCompany IS NULL
THEN
SELECT defaultCompanyFk INTO vCompany
@@ -12419,7 +12423,7 @@ BEGIN
company_id = vCompany;
SET vSelf = LAST_INSERT_ID();
-
+
CALL order_checkConfig(vSelf);
COMMIT;
@@ -12602,7 +12606,7 @@ BEGIN
SELECT t.id ticketFk
FROM myTicket t
WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59');
-
+
CALL vn.ticketGetTotal;
SELECT v.id, IFNULL(v.landed, v.shipped) landed,
@@ -12788,7 +12792,7 @@ BEGIN
IF vDone THEN
LEAVE l;
END IF;
-
+
SET vAdd = vAmount - MOD(vAmount, vGrouping);
SET vAmount = vAmount - vAdd;
@@ -12804,7 +12808,7 @@ BEGIN
rate = vRate,
amount = vAdd,
price = vPrice;
-
+
SET vRow = LAST_INSERT_ID();
INSERT INTO orderRowComponent (rowFk, componentFk, price)
@@ -12822,7 +12826,7 @@ BEGIN
IF vAmount > 0 THEN
CALL util.throw ('AMOUNT_NOT_MATCH_GROUPING');
END IF;
-
+
COMMIT;
CALL vn.ticketCalculatePurge;
END ;;
@@ -12865,10 +12869,10 @@ BEGIN
CREATE TEMPORARY TABLE tmp.item
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
- SELECT itemFk FROM orderRow
+ SELECT itemFk FROM orderRow
WHERE orderFk = vSelf
GROUP BY itemFk;
-
+
CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode);
DROP TEMPORARY TABLE tmp.item;
@@ -13498,7 +13502,7 @@ BEGIN
INTO vDelivery, vAddress, vAgencyMode
FROM `order`
WHERE id = vSelf;
-
+
CALL vn.available_calc(vDelivery, vAddress, vAgencyMode);
DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable;
@@ -13540,7 +13544,7 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
CREATE TEMPORARY TABLE tmp.addressCompany
(INDEX (addressFk, companyFk))
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT DISTINCT o.address_id addressFk, o.company_id companyFk
FROM tmp.`order` tmpOrder
JOIN hedera.`order` o ON o.id = tmpOrder.orderFk;
@@ -13575,7 +13579,7 @@ BEGIN
JOIN vn.taxClass tc ON tc.id = bp.taxClassFk
GROUP BY tmpOrder.orderFk, pgc.`code`, pgc.rate
HAVING taxableBase != 0;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount;
CREATE TEMPORARY TABLE tmp.orderAmount
(INDEX (orderFk))
@@ -13584,7 +13588,7 @@ BEGIN
SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax
FROM tmp.orderTax
GROUP BY orderFk, `code`;
-
+
DROP TEMPORARY TABLE tmp.addressTaxArea;
END ;;
DELIMITER ;
@@ -13654,7 +13658,7 @@ BEGIN
CREATE TEMPORARY TABLE tmp.`order`
ENGINE = MEMORY
SELECT vSelf orderFk;
-
+
CALL order_getTax;
SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0)
@@ -13745,7 +13749,7 @@ proc: BEGIN
FROM orderRow r
JOIN orderRowComponent c ON c.rowFk = r.id
WHERE r.orderFk = vSelf;
-
+
UPDATE orderRow r
LEFT JOIN tmp.ticketComponentPrice p
ON p.warehouseFk = r.warehouseFk
@@ -13770,7 +13774,7 @@ proc: BEGIN
ON t.id = c.componentFk
AND (t.classRate IS NULL OR t.classRate = r.rate)
WHERE r.orderFk = vSelf;
-
+
CALL vn.ticketCalculatePurge;
END IF;
@@ -14232,13 +14236,13 @@ p: BEGIN
AND DATE(FECHA) = vDate
AND EURODEBE = vAmount
LIMIT 1;
-
+
-- Actualiza la transaccion
UPDATE tpvTransaction
SET response = NULL, status = 'started'
WHERE id = vSelf;
-
+
COMMIT;
END ;;
DELIMITER ;
@@ -14271,7 +14275,7 @@ BEGIN
UPDATE userSession SET userVisitFk = vUserVisit
WHERE ssid = vSsid;
-
+
DELETE FROM userSession
WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, util.VN_NOW());
END ;;
@@ -14395,7 +14399,7 @@ BEGIN
UPDATE visitAgent SET firstAccessFk = vAccessId
WHERE id = vAgentId;
END IF;
-
+
-- Returns the visit info
SELECT vVisit visit, vAccessId access;
@@ -15110,7 +15114,7 @@ BEGIN
WHILE vI < vLen
DO
SET vChr = SUBSTR(vPhone, vI + 1, 1);
-
+
IF vChr REGEXP '^[0-9]$'
THEN
SET vNewPhone = CONCAT(vNewPhone, vChr);
@@ -15118,7 +15122,7 @@ BEGIN
THEN
SET vNewPhone = CONCAT(vNewPhone, '00');
END IF;
-
+
SET vI = vI + 1;
END WHILE;
@@ -15217,18 +15221,18 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_getExtension`(vUserId INT(10))
BEGIN
-
+
/*
* Devuelve la extensión pbx del usuario
- *
- * @param vUserId Id del usuario
- *
+ *
+ * @param vUserId Id del usuario
+ *
*/
SELECT extension
- FROM sip s
+ FROM sip s
WHERE s.user_id = vUserId;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -16443,22 +16447,22 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `company_getCode`(vCompanyFk INT) RET
READS SQL DATA
BEGIN
/**
- * Devuelve la correspondencía del código de empresa de sage.
+ * Devuelve la correspondencía del código de empresa de sage.
* Tiene en cuenta el entorno
- *
+ *
* @param vSelf Id de empresa de verdnatura
* @return Código de empresa sage
*/
DECLARE vCompanySageFk INT(2);
-
- SELECT IF(c.environment = 'production',
- co.companyCode,
+
+ SELECT IF(c.environment = 'production',
+ co.companyCode,
co.companyCodeTest
) INTO vCompanySageFk
FROM util.config c
JOIN vn.company co
WHERE co.id = vCompanyFk;
-
+
RETURN vCompanySageFk;
END ;;
DELIMITER ;
@@ -16927,18 +16931,18 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientSupplier_add`(vCompanyFk INT)
BEGIN
/**
- * Prepara los datos de clientes y proveedores para exportarlos a Sage
+ * Prepara los datos de clientes y proveedores para exportarlos a Sage
* @vCompanyFk Empresa dela que se quiere trasladar datos
*/
DECLARE vCountryCeutaMelillaFk INT;
DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2);
SELECT SiglaNacion INTO vCountryCanariasCode
- FROM Naciones
+ FROM Naciones
WHERE Nacion ='ISLAS CANARIAS';
SELECT CodigoNacion, SiglaNacion INTO vCountryCeutaMelillaFk, vCountryCeutaMelillaCode
- FROM Naciones
+ FROM Naciones
WHERE Nacion ='CEUTA Y MELILLA';
TRUNCATE TABLE clientesProveedores;
@@ -16969,7 +16973,7 @@ BEGIN
CodigoRetencion,
Email1,
iban)
- SELECT
+ SELECT
company_getCode(vCompanyFk),
'C',
c.id,
@@ -16986,12 +16990,12 @@ BEGIN
IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla := IF(pr.Provincia IN ('CEUTA', 'MELILLA'), TRUE, FALSE), vCountryCeutaMelillaFk, IF (@isCanarias, vCountryCanariasCode, n.CodigoNacion)), n.CodigoNacion),
IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla, vCountryCeutaMelillaCode, IF (@isCanarias, vCountryCanariasCode, n.SiglaNacion)), n.SiglaNacion),
IF((c.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F'),
- IF(cu.code IN('ES','EX'),
- 1,
+ IF(cu.code IN('ES','EX'),
+ 1,
IF((cu.isUeeMember AND c.isVies), 2, 4)),
IFNULL(c.taxTypeSageFk,0),
- IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci,
- IF(@isCeutaMelilla, 'CEUTA Y MELILLA', IF (@isCanarias, 'ISLAS CANARIAS', n.Nacion)),
+ IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci,
+ IF(@isCeutaMelilla, 'CEUTA Y MELILLA', IF (@isCanarias, 'ISLAS CANARIAS', n.Nacion)),
n.Nacion),
IFNULL(c.phone, ''),
IFNULL(c.mobile, ''),
@@ -17005,7 +17009,7 @@ BEGIN
LEFT JOIN Naciones n ON n.countryFk = cu.id
LEFT JOIN vn.province p ON p.id = c.provinceFk
LEFT JOIN Provincias pr ON pr.provinceFk = p.id
- WHERE c.isRelevant
+ WHERE c.isRelevant
AND clm.companyFk = vCompanyFk
UNION ALL
SELECT company_getCode(vCompanyFk),
@@ -17034,15 +17038,15 @@ BEGIN
IFNULL(SUBSTR(sc.email, 1, (COALESCE(NULLIF(LOCATE(',', sc.email), 0), 99) - 1)), ''),
IFNULL(iban, '')
FROM vn.supplier s
- JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id
+ JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id
LEFT JOIN vn.country co ON co.id = s.countryFk
LEFT JOIN Naciones n ON n.countryFk = co.id
LEFT JOIN vn.province p ON p.id = s.provinceFk
LEFT JOIN Provincias pr ON pr.provinceFk = p.id
LEFT JOIN vn.supplierContact sc ON sc.supplierFk = s.id
LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id
- WHERE pl.companyFk = vCompanyFk AND
- s.isActive AND
+ WHERE pl.companyFk = vCompanyFk AND
+ s.isActive AND
s.nif <> ''
GROUP BY pl.supplierFk, pl.companyFk;
END ;;
@@ -17065,10 +17069,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_add`(vInvoiceInFk INT, vX
BEGIN
/**
* Traslada la info de contabilidad relacionada con las facturas recibidas
- *
+ *
* @vInvoiceInFk Factura recibida
* @vXDiarioFk Id tabla XDiario
- */
+ */
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vBase DOUBLE;
DECLARE vVat DOUBLE;
@@ -17084,24 +17088,24 @@ BEGIN
DECLARE vInvoiceTypeReceived VARCHAR(1);
DECLARE vInvoiceTypeInformative VARCHAR(1);
- DECLARE vCursor CURSOR FOR
+ DECLARE vCursor CURSOR FOR
SELECT it.taxableBase,
CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)),
t.PorcentajeIva,
it.transactionTypeSageFk,
it.taxTypeSageFk,
t.isIntracommunity,
- tt.ClaveOperacionDefecto
+ tt.ClaveOperacionDefecto
FROM vn.invoiceIn i
- JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id
+ JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id
JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk
JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk
LEFT JOIN vn.dua d ON d.id = vInvoiceInFk
- WHERE i.id = vInvoiceInFk
+ WHERE i.id = vInvoiceInFk
AND d.id IS NULL;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
DELETE FROM movContaIVA
WHERE id = vXDiarioFk;
@@ -17124,22 +17128,22 @@ BEGIN
vTaxCode,
vIsIntracommunity,
vOperationCode;
-
- IF vDone THEN
+
+ IF vDone THEN
LEAVE l;
END IF;
- SET vTransactionCodeOld = vTransactionCode;
- SET vTaxCodeOld = vTaxCode;
+ SET vTransactionCodeOld = vTransactionCode;
+ SET vTaxCodeOld = vTaxCode;
- IF vOperationCode IS NOT NULL THEN
+ IF vOperationCode IS NOT NULL THEN
UPDATE movContaIVA
SET ClaveOperacionFactura = vOperationCode
WHERE id = vXDiarioFk;
END IF;
-
+
SET vCounter = vCounter + 1;
- CASE vCounter
+ CASE vCounter
WHEN 1 THEN
UPDATE movContaIVA
SET BaseIva1 = vBase,
@@ -17175,21 +17179,21 @@ BEGIN
WHERE id = vXDiarioFk;
ELSE
SELECT vXDiarioFk INTO vXDiarioFk;
- END CASE;
+ END CASE;
IF vIsIntracommunity THEN
UPDATE movContaIVA
SET Intracomunitaria = TRUE
WHERE id = vXDiarioFk;
END IF;
-
- SET vTransactionCodeOld = vTransactionCode;
- SET vTaxCodeOld = vTaxCode;
-
+
+ SET vTransactionCodeOld = vTransactionCode;
+ SET vTaxCodeOld = vTaxCode;
+
END LOOP;
CLOSE vCursor;
-
+
UPDATE movContaIVA mci
JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk
JOIN vn.XDiario x ON x.id = mci.id
@@ -17201,11 +17205,11 @@ BEGIN
mci.Serie = ii.serial,
mci.Factura = ii.serialNumber,
mci.FechaFactura = ii.issued,
- mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) +
- IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) +
- IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) +
+ mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) +
+ IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) +
+ IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) +
IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0),
- mci.TipoFactura = IF(id.id, IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), vInvoiceTypeReceived),
+ mci.TipoFactura = IF(id.id, IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), vInvoiceTypeReceived),
mci.CodigoCuentaFactura = x.SUBCTA,
mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif),
mci.Nombre = s.name,
@@ -17233,7 +17237,7 @@ BEGIN
JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase
FROM vn.XDiario x1
JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN
- WHERE x2.BASEEURO <> 0
+ WHERE x2.BASEEURO <> 0
AND x1.id = vXDiarioFk
)sub
JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio'
@@ -17241,8 +17245,8 @@ BEGIN
mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura),
mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase),
mci.PorRetencion = t.PorcentajeRetencion,
- mci.ImporteRetencion = iit.taxableBase * - 1
- WHERE mci.id = vXDiarioFk
+ mci.ImporteRetencion = iit.taxableBase * - 1
+ WHERE mci.id = vXDiarioFk
AND e.name = 'Retenciones'
AND id.id IS NULL;
@@ -17265,10 +17269,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_manager`(vYear INT, vCompanyFk INT)
BEGIN
/**
- * Traslada la info de contabilidad relacionada con las facturas recibidas
- *
+ * Traslada la info de contabilidad relacionada con las facturas recibidas
+ *
* @vYear Año contable del que se quiere trasladar la información
- * @vCompany Empresa de la que se quiere trasladar datos
+ * @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
@@ -17280,22 +17284,22 @@ BEGIN
DECLARE vAccountTaxOutstanding VARCHAR(10);
DECLARE vInvoiceTypeSended VARCHAR(1);
DECLARE vCursor CURSOR FOR
- SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk,
+ SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk,
x.id XDiarioFk
- FROM vn.XDiario x
+ FROM vn.XDiario x
JOIN(SELECT DISTINCT(x.ASIEN)
FROM vn.XDiario x
LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id
LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id
- WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci)
- AND x.enlazadoSage = FALSE
+ WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci)
+ AND x.enlazadoSage = FALSE
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
- AND x.empresa_id = vCompanyFk
+ AND x.empresa_id = vCompanyFk
) sub ON sub.ASIEN = x.ASIEN
WHERE x.CLAVE IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE))
INTO vDatedFrom, vDatedTo;
@@ -17309,15 +17313,15 @@ BEGIN
SELECT codeSage INTO vInvoiceTypeSended
FROM invoiceType WHERE `code` ='sended';
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua;
CREATE TEMPORARY TABLE tmp.invoiceDua
- SELECT x.id
+ SELECT x.id
FROM vn.XDiario x
JOIN vn.company c ON c.id = x.empresa_id
JOIN (SELECT ASIEN
- FROM vn.XDiario x
- WHERE x.enlazadoSage = FALSE
+ FROM vn.XDiario x
+ WHERE x.enlazadoSage = FALSE
AND x.SUBCTA = vAccountTaxOutstanding COLLATE utf8mb3_unicode_ci
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
)sub ON sub.ASIEN = x.ASIEN
@@ -17336,7 +17340,7 @@ BEGIN
FROM vn.invoiceIn i
JOIN vn.currency c ON c.id = i.currencyFk
WHERE i.bookEntried BETWEEN vDatedFrom AND vDatedTo
- UNION ALL
+ UNION ALL
SELECT d.id,
d.code,
vSerialDua,
@@ -17345,8 +17349,8 @@ BEGIN
FALSE,
d.id,
'' -- EUROS
- FROM vn.dua d
- WHERE d.issued IS NOT NULL
+ FROM vn.dua d
+ WHERE d.issued IS NOT NULL
AND code IS NOT NULL;
OPEN vCursor;
@@ -17354,7 +17358,7 @@ BEGIN
l: LOOP
FETCH vCursor INTO vInvoiceFk, vXDiarioFk;
- IF vDone THEN
+ IF vDone THEN
LEAVE l;
END IF;
CALL invoiceIn_add(vInvoiceFk, vXDiarioFk);
@@ -17442,21 +17446,21 @@ BEGIN
JOIN (SELECT x.ASIEN, x.id
FROM vn.XDiario x
JOIN(SELECT DISTINCT(x.ASIEN) ASIEN
- FROM vn.XDiario x
+ FROM vn.XDiario x
JOIN (SELECT DISTINCT(ASIEN)
FROM vn.XDiario x
- WHERE SUBCTA LIKE '472%'
+ WHERE SUBCTA LIKE '472%'
AND x.enlazadoSage = FALSE
AND x.empresa_id = vCompanyFk
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
) sub ON sub.ASIEN = x.ASIEN
WHERE x.SUBCTA LIKE '477%'
)sub2 ON sub2.ASIEN = x.ASIEN
- WHERE x.CONTRA IS NOT NULL
+ WHERE x.CONTRA IS NOT NULL
AND x.SUBCTA LIKE '477%'
GROUP BY x.ASIEN
)sub3 ON sub3.ASIEN = x.ASIEN;
-
+
INSERT INTO movContaIVA
(`id`,
`CodigoDivisa`,
@@ -17527,9 +17531,9 @@ BEGIN
`FechaGrabacion`,
`Intracomunitaria`,
`moveData`)
- SELECT *
+ SELECT *
FROM tmp.movContaIVA;
-
+
DROP TEMPORARY TABLE tmp.movContaIVA;
END ;;
@@ -17551,10 +17555,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_add`(IN vInvoiceOutFk INT, IN vXDiarioFk INT)
BEGIN
/**
- * Traslada la info de contabilidad relacionada con las facturas emitidas
- *
+ * Traslada la info de contabilidad relacionada con las facturas emitidas
+ *
* @vYear Año contable del que se quiere trasladar la información
- * @vCompany Empresa de la que se quiere trasladar datos
+ * @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vMaxLengthName INT DEFAULT 35;
@@ -17574,12 +17578,12 @@ BEGIN
DECLARE vHasCustomsAccountingNote BOOL;
DECLARE vCursor CURSOR FOR
- SELECT oit.taxableBase,
- oit.vat,
- pgc.rate,
- pgc.mod347,
- pgcRE.rate,
- oitRE.vat,
+ SELECT oit.taxableBase,
+ oit.vat,
+ pgc.rate,
+ pgc.mod347,
+ pgcRE.rate,
+ oitRE.vat,
tc.transactionCode,
tc.taxCode,
tc.isIntracommunity,
@@ -17588,7 +17592,7 @@ BEGIN
JOIN vn.pgc ON pgc.code = oit.pgcFk
LEFT JOIN vn.pgcEqu e ON e.vatFk = oit.pgcFk
LEFT JOIN vn.pgcEqu eRE ON eRE.equFk = oit.pgcFk
- LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk
+ LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk
AND oitRE.pgcFk = e.equFk
LEFT JOIN vn.pgc pgcRE ON pgcRE.code = oitRE.pgcFk
LEFT JOIN vn.taxCode tc ON tc.code = pgc.code COLLATE 'utf8mb3_unicode_ci'
@@ -17604,12 +17608,12 @@ BEGIN
WHERE ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioFk);
SELECT codeSage INTO vInvoiceTypeSended
- FROM invoiceType
+ FROM invoiceType
WHERE code = IF(vHasCustomsAccountingNote, 'informative', 'sended');
-
+
DELETE FROM movContaIVA
WHERE id = vXDiarioFk;
-
+
INSERT INTO movContaIVA(id) VALUES (vXDiarioFk);
OPEN vCursor;
@@ -17626,13 +17630,13 @@ BEGIN
vIsIntracommunity,
vOperationCode;
- IF vDone THEN
+ IF vDone THEN
LEAVE l;
END IF;
SET vCounter = vCounter + 1;
-
- CASE vCounter
+
+ CASE vCounter
WHEN 1 THEN
UPDATE movContaIVA
SET BaseIva1 = vBase,
@@ -17673,7 +17677,7 @@ BEGIN
CodigoTransaccion4 = vTransactionCode,
CodigoIva4 = vTaxCode
WHERE id = vXDiarioFk;
- END CASE;
+ END CASE;
UPDATE movContaIVA
SET Exclusion347 = NOT vMod347,
@@ -17684,7 +17688,7 @@ BEGIN
END LOOP;
CLOSE vCursor;
-
+
UPDATE movContaIVA mci
JOIN vn.invoiceOut i ON i.id = vInvoiceOutFk
LEFT JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutFk
@@ -17709,25 +17713,25 @@ BEGIN
mci.MantenerAsiento = TRUE,
mci.FechaFacturaOriginal = x.FECHA_EX
WHERE mci.id = vXDiarioFk;
-
+
SELECT correctedFk INTO vInvoiceOutCorrectedFk
FROM vn.invoiceCorrection
WHERE correctingFk = vInvoiceOutFk;
-
- IF vInvoiceOutCorrectedFk THEN
+
+ IF vInvoiceOutCorrectedFk THEN
UPDATE movContaIVA mci
JOIN vn.invoiceOut i ON i.id = vInvoiceOutCorrectedFk
JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk
- JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase,
+ JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase,
SUM(IF(IFNULL(e.vatFk, TRUE), iot.vat, 0)) vat,
SUM(IF(IFNULL(e.vatFk, TRUE), 0, iot.vat)) equ
FROM vn.invoiceOutTax iot
- LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk
+ LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk
WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk
) tax
JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
SET mci.TipoRectificativa = 2,
- mci.ClaseAbonoRectificativas = 1,
+ mci.ClaseAbonoRectificativas = 1,
mci.FechaFacturaOriginal = i.issued,
mci.FechaOperacion = i.issued,
mci.BaseImponibleOriginal = tax.taxableBase,
@@ -17758,10 +17762,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_manager`(vYear INT, vCompanyFk INT)
BEGIN
/**
- * Traslada la info de contabilidad relacionada con las facturas emitidas
- *
+ * Traslada la info de contabilidad relacionada con las facturas emitidas
+ *
* @vYear Año contable del que se quiere trasladar la información
- * @vCompany Empresa de la que se quiere trasladar datos
+ * @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
@@ -17778,7 +17782,7 @@ BEGIN
JOIN (SELECT x.ASIEN, CONCAT(x.SERIE, x.FACTURA) refFk
FROM vn.XDiario x
WHERE x.enlazadoSage = FALSE
- AND x.FACTURA
+ AND x.FACTURA
AND x.empresa_id = vCompanyFk
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
GROUP BY refFk
@@ -17787,19 +17791,19 @@ BEGIN
)sub2 ON sub2.refFk = i.ref;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE))
INTO vDatedFrom, vDatedTo;
-
+
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vInvoiceFk, vXDiarioFk;
- IF vDone THEN
+ IF vDone THEN
LEAVE l;
END IF;
-
+
CALL invoiceOut_add(vInvoiceFk, vXDiarioFk);
END LOOP;
@@ -17825,7 +17829,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `pgc_add`(vCompanyFk INT)
BEGIN
/**
- * Añade cuentas del plan general contable para exportarlos a Sage
+ * Añade cuentas del plan general contable para exportarlos a Sage
* @vCompanyFk Empresa de la que se quiere trasladar datos
*/
TRUNCATE TABLE planCuentasPGC;
@@ -17835,25 +17839,25 @@ BEGIN
CodigoCuenta,
Cuenta,
ClienteOProveedor)
- SELECT *
+ SELECT *
FROM (SELECT company_getCode(vCompanyFk) companyFk,
e.id accountFk,
UCASE(e.name),
''
FROM vn.expence e
- UNION
+ UNION
SELECT company_getCode(vCompanyFk),
- b.account,
+ b.account,
UCASE(b.bank),
- ''
+ ''
FROM vn.bank b
WHERE b.isActive
AND b.`account`
- UNION
+ UNION
SELECT CodigoEmpresa,
CodigoCuenta,
Nombre,
- ClienteOProveedor
+ ClienteOProveedor
FROM clientesProveedores)sub
GROUP BY companyFk, accountFk;
END ;;
@@ -18127,7 +18131,7 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE();
-
+
CALL visible_log(
NEW.isPicked,
NEW.warehouseFk,
@@ -18251,7 +18255,7 @@ DELIMITER ;;
BEGIN
SET NEW.lack = NEW.quantity;
SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE();
-
+
CALL visible_log(
NEW.isPicked,
NEW.warehouseFk,
@@ -18462,7 +18466,7 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
-
+
SET vSupplied = 0;
OPEN vPicks;
@@ -18478,7 +18482,7 @@ BEGIN
SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity);
SET vSupplied = vSupplied + vPickGranted;
CALL inbound_removePick(vSelf, vOutboundFk, vPickGranted, vPickQuantity);
-
+
UPDATE outbound
SET isSync = FALSE,
lack = lack + vPickGranted
@@ -18558,7 +18562,7 @@ BEGIN
END IF;
SET vSupplied = LEAST(vAvailable, vLack);
-
+
IF vSupplied > 0 THEN
SET vAvailable = vAvailable - vSupplied;
UPDATE outbound
@@ -18571,7 +18575,7 @@ BEGIN
SET vSupplied = vSupplied + vSuppliedFromRequest;
SET vAvailable = vAvailable - vSuppliedFromRequest;
END IF;
-
+
IF vSupplied > 0 THEN
CALL inbound_addPick(vSelf, vOutboundFk, vSupplied);
END IF;
@@ -18700,7 +18704,7 @@ BEGIN
DO RELEASE_LOCK('stock.log_sync');
RESIGNAL;
END;
-
+
IF !GET_LOCK('stock.log_sync', 30) THEN
CALL util.throw('Lock timeout exceeded');
END IF;
@@ -19171,7 +19175,7 @@ BEGIN
SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity);
SET vSupplied = vSupplied + vPickGranted;
CALL inbound_removePick(vInboundFk, vSelf, vPickGranted, vPickQuantity);
-
+
UPDATE inbound
SET isSync = FALSE,
available = available + vPickGranted
@@ -19606,11 +19610,11 @@ BEGIN
WHILE vI < vLen
DO
SET vSpaceIni = vI;
-
+
WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO
SET vI = vI + 1;
END WHILE;
-
+
SET vWordIni = vI;
SET vI = vWordIni + 1;
@@ -19647,11 +19651,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `crypt`(vText VARCHAR(255), vKey VARC
BEGIN
DECLARE vResult VARCHAR(255);
-
+
CALL vn.crypt(vText, vKey, vResult);
RETURN vResult;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -19673,11 +19677,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `cryptOff`(vText VARCHAR(255), vKey V
BEGIN
DECLARE vResult VARCHAR(255);
-
+
CALL vn.cryptOff(vText, vKey, vResult);
RETURN vResult;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -19845,7 +19849,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasDateOverlapped`(vSarted1 DATE, vEnded1 DATE, vSarted2 DATE, vEnded2 DATE) RETURNS tinyint(1)
DETERMINISTIC
-BEGIN
+BEGIN
RETURN GREATEST(vSarted1, vSarted2) <= LEAST(vEnded1,vEnded2);
@@ -19874,7 +19878,7 @@ BEGIN
*/
DECLARE vHashlen INT UNSIGNED;
DECLARE vOpad, vIpad TINYBLOB;
-
+
CASE vAlg
WHEN 224 THEN SET vHashlen = 64;
WHEN 256 THEN SET vHashlen = 64;
@@ -19882,16 +19886,16 @@ BEGIN
WHEN 512 THEN SET vHashlen = 128;
ELSE CALL throw ('WRONG_ALGORYTHM_IDENTIFICATOR_USED');
END CASE;
-
+
IF LENGTH(vKey) > vHashlen THEN
SET vKey = UNHEX(SHA2(vKey, vAlg));
END IF;
-
+
SET vKey = RPAD(vKey, vHashlen, 0x00);
-
+
SET vIpad = stringXor(vKey, 0x36);
SET vOpad = stringXor(vKey, 0x5C);
-
+
RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg);
END ;;
DELIMITER ;
@@ -19914,7 +19918,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `isLeapYear`(vYear INT) RETURNS tinyi
BEGIN
RETURN (DAYOFYEAR(CONCAT(vYear, "-02-29")) IS NOT NULL);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -20029,7 +20033,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime
READS SQL DATA
BEGIN
-
+
RETURN TIMESTAMP(util.VN_CURDATE(), '23:59:59');
END ;;
@@ -20057,7 +20061,7 @@ BEGIN
* modo 3.
*/
DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100);
-
+
IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN
RETURN vYearWeek + 1;
ELSE
@@ -20163,16 +20167,16 @@ BEGIN
*/
DECLARE vLen, vPos INT UNSIGNED;
DECLARE vResult MEDIUMBLOB;
-
+
SET vLen = LENGTH(vString);
SET vPos = 1;
SET vResult = '';
-
+
WHILE vPos <= vLen DO
SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0'));
SET vPos = vPos + 1;
END WHILE;
-
+
RETURN UNHEX(vResult);
END ;;
DELIMITER ;
@@ -20282,11 +20286,11 @@ BEGIN
IF vYear = vCurYear THEN
RETURN 'curYear';
END IF;
-
+
IF vYear = vCurYear - 1 THEN
RETURN 'lastYear';
END IF;
-
+
IF vYear = vCurYear - 2 THEN
RETURN 'twoYearsAgo';
END IF;
@@ -20373,10 +20377,10 @@ BEGIN
*/
SET vChain = CONCAT('%', vChain, '%');
SET vCompare = CONCAT('%', vCompare, '%');
- SELECT * FROM
+ SELECT * FROM
(
SELECT t1.* FROM
- (
+ (
SELECT
`db`,
`name`,
@@ -20403,7 +20407,7 @@ BEGIN
'TRIGGER',
`ACTION_STATEMENT`,
NULL,
- NULL
+ NULL
FROM `information_schema`.`TRIGGERS`
WHERE `ACTION_STATEMENT` LIKE vChain COLLATE utf8_general_ci
UNION ALL
@@ -20413,7 +20417,7 @@ BEGIN
'VIEW',
`VIEW_DEFINITION`,
NULL,
- NULL
+ NULL
FROM `information_schema`.`VIEWS`
WHERE `VIEW_DEFINITION` LIKE vChain COLLATE utf8_general_ci
) t1
@@ -20444,7 +20448,7 @@ BEGIN
'TRIGGER',
`ACTION_STATEMENT`,
NULL,
- NULL
+ NULL
FROM `information_schema`.`TRIGGERS`
WHERE `ACTION_STATEMENT` LIKE vCompare COLLATE utf8_general_ci
UNION ALL
@@ -20454,7 +20458,7 @@ BEGIN
'VIEW',
`VIEW_DEFINITION`,
NULL,
- NULL
+ NULL
FROM `information_schema`.`VIEWS`
WHERE `VIEW_DEFINITION` LIKE vCompare COLLATE utf8_general_ci) t2 ON t2.name = t1.name
ORDER BY t1.`db`, t1.`name`
@@ -20485,7 +20489,7 @@ BEGIN
* @param vValue Valor de la variable
*/
DECLARE vIndex INT DEFAULT INSTR(USER(), '@');
-
+
INSERT INTO debug SET
`connectionId` = CONNECTION_ID(),
`user` = LEFT(USER(), vIndex - 1),
@@ -20552,7 +20556,7 @@ BEGIN
SET vChain = CONCAT('%', vChain, '%');
SELECT * FROM
- (
+ (
SELECT
`routine_schema` `schema`,
`routine_name` `name`,
@@ -20579,7 +20583,7 @@ BEGIN
'TRIGGER',
`ACTION_STATEMENT`,
NULL,
- NULL
+ NULL
FROM `information_schema`.`TRIGGERS`
WHERE `ACTION_STATEMENT` LIKE vChain COLLATE utf8_general_ci
UNION ALL
@@ -20589,7 +20593,7 @@ BEGIN
'VIEW',
`VIEW_DEFINITION`,
NULL,
- NULL
+ NULL
FROM `information_schema`.`VIEWS`
WHERE `VIEW_DEFINITION` LIKE vChain COLLATE utf8_general_ci
) t
@@ -20916,7 +20920,7 @@ BEGIN
INSERT INTO tmp.time (dated) VALUES (vCurrentDate);
SET vCurrentDate = DATE_ADD(vCurrentDate, INTERVAL 1 DAY);
END WHILE;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -21323,11 +21327,11 @@ BEGIN
END IF;
IF NEW.isEqualizated IS NULL THEN
- SELECT isEqualizated
+ SELECT isEqualizated
INTO vIsEqualizated
FROM client
WHERE id = NEW.clientFk;
-
+
SET NEW.isEqualizated = vIsEqualizated;
END IF;
END */;;
@@ -21349,11 +21353,11 @@ DELIMITER ;;
BEFORE UPDATE ON `address`
FOR EACH ROW
BEGIN
-
+
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;
@@ -21379,16 +21383,16 @@ DELIMITER ;;
BEGIN
-- Recargos de equivalencia distintos implican facturacion por consignatario
IF NEW.isEqualizated != OLD.isEqualizated THEN
- IF
+ IF
(SELECT COUNT(*) FROM
(
SELECT DISTINCT (isEqualizated = FALSE) as Equ
- FROM address
+ FROM address
WHERE clientFk = NEW.clientFk
) t1
) > 1
- THEN
- UPDATE client
+ THEN
+ UPDATE client
SET hasToInvoiceByAddress = TRUE
WHERE id = NEW.clientFk;
END IF;
@@ -21396,10 +21400,10 @@ BEGIN
IF NEW.isDefaultAddress AND NEW.isActive = FALSE THEN
CALL util.throw ('Cannot desactivate the default address');
END IF;
-
+
IF NOT (NEW.isEqualizated <=> OLD.isEqualizated) THEN
INSERT IGNORE INTO ticketRecalc (ticketFk)
- SELECT id FROM ticket t
+ SELECT id FROM ticket t
WHERE t.addressFk = NEW.id
AND t.refFk IS NULL;
END IF;
@@ -21788,8 +21792,8 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`autonomy_BI`
BEFORE INSERT ON `autonomy`
FOR EACH ROW
-BEGIN
-
+BEGIN
+
SET NEW.geoFk = zoneGeo_new('autonomy', NEW.`name`, (SELECT geoFk FROM country WHERE id = NEW.countryFk));
END */;;
@@ -21839,7 +21843,7 @@ DELIMITER ;;
AFTER DELETE ON `autonomy`
FOR EACH ROW
BEGIN
- CALL zoneGeo_delete(OLD.geoFk);
+ CALL zoneGeo_delete(OLD.geoFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -21915,7 +21919,7 @@ DELIMITER ;;
BEFORE INSERT ON `awb`
FOR EACH ROW
BEGIN
-
+
SET NEW.year= year(util.VN_CURDATE());
@@ -22275,11 +22279,11 @@ DELIMITER ;;
BEFORE INSERT ON `budgetNotes`
FOR EACH ROW
BEGIN
-
+
IF ISNULL(NEW.userFk) THEN
-
+
SET NEW.userFk = account.myUser_getId();
-
+
END IF;
END */;;
@@ -22395,28 +22399,28 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
DECLARE isOverlapping BOOL;
-
+
IF NEW.ended IS NULL THEN
SET NEW.payedHolidays = 0;
END IF;
IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN
-
+
SELECT COUNT(*) > 0 INTO isOverlapping
FROM business b
WHERE (util.hasDateOverlapped(
- NEW.started,
+ NEW.started,
IFNULL(NEW.ended, b.started),
b.started,
IFNULL(b.ended, NEW.started))
OR (NEW.ended <=> NULL AND b.ended <=> NULL))
AND b.id <> OLD.id
AND workerFk = OLD.workerFk;
-
- IF isOverlapping THEN
+
+ IF isOverlapping THEN
CALL util.throw ('IS_OVERLAPPING');
END IF;
-
+
END IF;
END */;;
@@ -22663,7 +22667,7 @@ trig: BEGIN
LEAVE trig;
END IF;
- IF @isTriggerDisabled THEN
+ IF @isTriggerDisabled THEN
LEAVE trig;
END IF;
@@ -22769,12 +22773,12 @@ trig: BEGIN
OR !(NEW.created <=> OLD.created) THEN
CALL stock.log_add('buy', NEW.id, OLD.id);
END IF;
-
+
IF @isModeInventory THEN
LEAVE trig;
END IF;
- IF @isTriggerDisabled THEN
+ IF @isTriggerDisabled THEN
LEAVE trig;
END IF;
@@ -22784,24 +22788,24 @@ trig: BEGIN
INTO vIsBuyerToBeEmailed, vLanded
FROM entry e
JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseInFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
WHERE e.id = NEW.entryFk;
-
- SELECT it.workerFk, i.longName
+
+ SELECT it.workerFk, i.longName
INTO vBuyerFk, vItemName
FROM itemCategory k
JOIN itemType it ON it.categoryFk = k.id
JOIN item i ON i.typeFk = it.id
WHERE i.id = OLD.itemFk;
- IF vIsBuyerToBeEmailed AND
- vBuyerFk != account.myUser_getId() AND
+ IF vIsBuyerToBeEmailed AND
+ vBuyerFk != account.myUser_getId() AND
vLanded = util.VN_CURDATE() THEN
- IF !(NEW.itemFk <=> OLD.itemFk) OR
- !(NEW.quantity <=> OLD.quantity) OR
+ IF !(NEW.itemFk <=> OLD.itemFk) OR
+ !(NEW.quantity <=> OLD.quantity) OR
!(NEW.packing <=> OLD.packing) OR
- !(NEW.grouping <=> OLD.grouping) OR
- !(NEW.packageFk <=> OLD.packageFk) OR
+ !(NEW.grouping <=> OLD.grouping) OR
+ !(NEW.packageFk <=> OLD.packageFk) OR
!(NEW.weight <=> OLD.weight) THEN
CALL vn.mail_insert(
CONCAT(account.user_getNameFromId(vBuyerFk),'@verdnatura.es'),
@@ -22830,7 +22834,7 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeDelete`
BEFORE DELETE ON buy
FOR EACH ROW
-BEGIN
+BEGIN
IF OLD.printedStickers <> 0 THEN
CALL util.throw("it is not possible to delete buys with printed labels ");
END IF;
@@ -22852,10 +22856,10 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_afterDelete`
AFTER DELETE ON `buy`
FOR EACH ROW
-trig: BEGIN
+trig: BEGIN
DECLARE vValues VARCHAR(255);
- IF @isTriggerDisabled THEN
+ IF @isTriggerDisabled THEN
LEAVE trig;
END IF;
@@ -23163,7 +23167,7 @@ BEGIN
FROM sale
WHERE id = NEW.saleFk;
- UPDATE claim
+ UPDATE claim
SET ticketFk = vTicket
WHERE id = NEW.claimFk;
END */;;
@@ -23562,7 +23566,7 @@ BEGIN
END IF;
SET NEW.accountingAccount = 4300000000 + NEW.id;
-
+
SET NEW.lastSalesPersonFk = NEW.salesPersonFk;
END */;;
DELIMITER ;
@@ -23590,19 +23594,19 @@ BEGIN
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
+ 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
@@ -23615,7 +23619,7 @@ BEGIN
IF vText IS NOT NULL
THEN
- INSERT INTO mail(receiver, replyTo, `subject`, body)
+ INSERT INTO mail(receiver, replyTo, `subject`, body)
SELECT
CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'),
'administracion@verdnatura.es',
@@ -23626,16 +23630,16 @@ BEGIN
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)
+ 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;
@@ -23666,18 +23670,18 @@ BEGIN
IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN
UPDATE `address` SET isDefaultAddress = 0
WHERE clientFk = NEW.id;
-
+
UPDATE `address` SET isDefaultAddress = 1
- WHERE id = NEW.defaultAddressFk;
+ WHERE id = NEW.defaultAddressFk;
END IF;
IF NOT (NEW.provinceFk <=> OLD.provinceFk) OR NOT (NEW.isVies <=> OLD.isVies) THEN
INSERT IGNORE INTO ticketRecalc (ticketFk)
- SELECT id FROM ticket t
+ SELECT id FROM ticket t
WHERE t.clientFk = NEW.id
AND t.refFk IS NULL;
END IF;
-
+
IF NOT NEW.isActive THEN
UPDATE account.`user`
SET active = FALSE
@@ -23792,15 +23796,15 @@ DELIMITER ;;
AFTER INSERT
ON clientCredit FOR EACH ROW
BEGIN
-
+
DECLARE vSender VARCHAR(50);
SELECT u.name INTO vSender
FROM account.`user` u
WHERE u.id = NEW.workerFk;
-
+
IF vSender IN ('juanvi','pepe') THEN
-
+
CALL `vn`.`mail_insert`('pako@verdnatura.es',
NULL,
CONCAT('ClientCredit ',vSender, ' ', NEW.clientFk, ' ' , NEW.amount, ' €'),
@@ -24145,23 +24149,23 @@ BEGIN
DECLARE vLastSenderInstructions VARCHAR(255);
DECLARE vLastId INT;
DECLARE vCurrentAgency INT;
-
+
SELECT am.agencyFk INTO vCurrentAgency
FROM vn.agencyMode am
JOIN vn.ticket t ON t.agencyModeFk = am.id
WHERE t.id = NEW.ticketFk;
-
+
SELECT MAX(cmr.id) INTO vLastId
FROM cmr
JOIN vn.ticket t ON t.id = cmr.ticketFk
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
- WHERE am.agencyFk = vCurrentAgency
+ WHERE am.agencyFk = vCurrentAgency
;
-
+
SELECT senderInstruccions INTO vLastSenderInstructions
FROM cmr
WHERE id = vLastId;
-
+
SET NEW.senderInstruccions = vLastSenderInstructions;
END */;;
@@ -24296,33 +24300,33 @@ DELIMITER ;;
BEFORE UPDATE ON `collection`
FOR EACH ROW
BEGIN
-
+
DECLARE vStateFk INT;
DECLARE vTotalLines INT;
DECLARE vPickedLines INT;
- IF NEW.saleTotalCount <= NEW.salePickedCount
- AND (NEW.saleTotalCount != OLD.saleTotalCount
+ IF NEW.saleTotalCount <= NEW.salePickedCount
+ AND (NEW.saleTotalCount != OLD.saleTotalCount
OR NEW.salePickedCount != OLD.salePickedCount)
- THEN
-
+ THEN
+
SELECT id INTO vStateFk
- FROM vn.state
+ FROM vn.state
WHERE code = 'PREPARED';
-
+
SET NEW.stateFk = vStateFk;
-
+
END IF;
- IF NEW.saleTotalCount > NEW.salePickedCount
- AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN
+ IF NEW.saleTotalCount > NEW.salePickedCount
+ AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN
SELECT id INTO vStateFk
- FROM vn.state
+ FROM vn.state
WHERE code = 'ON_PREPARATION';
-
+
SET NEW.stateFk = vStateFk;
-
+
END IF;
END */;;
@@ -25209,7 +25213,7 @@ BEGIN
UPDATE `client` c
JOIN vn.creditClassification cc ON cc.client = c.id
SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -25469,7 +25473,7 @@ BEGIN
JOIN vn.department d ON d.id = b.departmentFk
SET b.departmentFk = d.parentFk
WHERE b.departmentFk = OLD.id;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -25489,9 +25493,9 @@ DELIMITER ;;
AFTER DELETE ON `department`
FOR EACH ROW
BEGIN
-
+
UPDATE vn.department_recalc SET isChanged = TRUE;
-
+
UPDATE vn.business b
JOIN vn.department d ON d.id = b.departmentFk
SET b.departmentFk = d.parentFk
@@ -25581,10 +25585,10 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceLog_beforeInsert`
BEFORE INSERT
ON deviceLog FOR EACH ROW
-BEGIN
+BEGIN
DECLARE vDeviceProductionFk INTEGER;
SELECT dp.id INTO vDeviceProductionFk
- FROM deviceProduction dp
+ FROM deviceProduction dp
WHERE dp.android_id = NEW.android_id;
SET NEW.deviceProductionFk = vDeviceProductionFk;
END */;;
@@ -25653,9 +25657,9 @@ DELIMITER ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProduction_afterUpdate`
- BEFORE UPDATE
+ BEFORE UPDATE
ON vn.deviceProduction FOR EACH ROW
-BEGIN
+BEGIN
INSERT INTO deviceProductionLog (originFk, userFk, newInstance, oldInstance , action, changedModel, changedModelId)
VALUES(OLD.id, account.myUser_getId(), NEW.stateFk, OLD.stateFk , 'update', 'deviceProduction', OLD.id);
END */;;
@@ -25786,12 +25790,12 @@ DELIMITER ;;
ON deviceProductionUser FOR EACH ROW
BEGIN
INSERT INTO deviceProductionLog (originFk, userFk, oldInstance, action, changedModel, changedModelId)
- SELECT
+ SELECT
OLD.deviceProductionFk,
- account.myUser_getId(),
- stateFk,
- 'DELETE',
- 'deviceProductionUser',
+ account.myUser_getId(),
+ stateFk,
+ 'DELETE',
+ 'deviceProductionUser',
OLD.deviceProductionFk
FROM deviceProduction
WHERE id = OLD.deviceProductionFk;
@@ -25863,20 +25867,20 @@ DELIMITER ;;
BEGIN
DECLARE vHardCopyNumber INT;
DECLARE vDmsTypeCode INT;
-
+
IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN
CALL util.throw('this warehouse has not dms');
END IF;
IF NEW.hasFile THEN
- SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber
- FROM dms
+ SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber
+ FROM dms
WHERE warehouseFk = NEW.warehouseFk;
-
+
SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1);
END IF;
-
- SELECT code INTO vDmsTypeCode
+
+ SELECT code INTO vDmsTypeCode
FROM dmsType WHERE NEW.dmsTypeFk = id;
IF (vDmsTypeCode ='ticket') THEN
UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference;
@@ -25901,24 +25905,24 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
DECLARE vHardCopyNumber INT;
-
+
IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL)
- OR
+ OR
(NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN
-
- IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN
+
+ IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN
SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi');
END IF;
-
- SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber
- FROM dms
+
+ SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber
+ FROM dms
WHERE warehouseFk = NEW.warehouseFk;
-
+
SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1);
END IF;
-
+
IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN
-
+
SET NEW.hasFile = 0;
END IF;
END */;;
@@ -25939,14 +25943,14 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeDelete`
BEFORE DELETE ON `dms`
FOR EACH ROW
-BEGIN
+BEGIN
DECLARE vCanNotBeDeleted INT;
- SELECT COUNT(*) INTO vCanNotBeDeleted
- FROM dmsType dt
- WHERE NOT (code <=> 'trash')
+ SELECT COUNT(*) INTO vCanNotBeDeleted
+ FROM dmsType dt
+ WHERE NOT (code <=> 'trash')
AND dt.id = OLD.dmsTypeFk;
-
- IF vCanNotBeDeleted THEN
+
+ IF vCanNotBeDeleted THEN
CALL util.throw('A dms can not be deleted');
END IF;
END */;;
@@ -26471,7 +26475,7 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_afterInsert`
AFTER INSERT ON `entry`
FOR EACH ROW
-BEGIN
+BEGIN
CALL travel_requestRecalc(NEW.travelFk);
END */;;
DELIMITER ;
@@ -26511,7 +26515,7 @@ BEGIN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses';
END IF;
-
+
IF NEW.travelFk IS NULL THEN
SELECT COUNT(*) INTO vPrintedCount
FROM buy
@@ -26531,7 +26535,7 @@ BEGIN
END IF;
IF !(NEW.travelFk <=> OLD.travelFk)
- OR !(NEW.currencyFk <=> OLD.currencyFk) THEN
+ OR !(NEW.currencyFk <=> OLD.currencyFk) THEN
SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk);
END IF;
@@ -26566,7 +26570,7 @@ BEGIN
OR !(NEW.isRaid <=> OLD.isRaid) THEN
CALL stock.log_add('entry', NEW.id, OLD.id);
END IF;
-
+
IF !(NEW.travelFk <=> OLD.travelFk) THEN
CALL travel_requestRecalc(OLD.travelFk);
CALL travel_requestRecalc(NEW.travelFk);
@@ -26619,7 +26623,7 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_afterDelete`
AFTER DELETE ON `entry`
FOR EACH ROW
-BEGIN
+BEGIN
CALL travel_requestRecalc(OLD.travelFk);
END */;;
DELIMITER ;
@@ -26972,17 +26976,17 @@ BEGIN
DECLARE intcounter INT;
DECLARE vShipFk INT;
- IF NEW.freightItemFk IS NOT NULL THEN
+ IF NEW.freightItemFk IS NOT NULL THEN
UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk;
- SELECT IFNULL(MAX(counter),0) +1 INTO intcounter
- FROM expedition e
- INNER JOIN ticket t1 ON e.ticketFk = t1.id
+ SELECT IFNULL(MAX(counter),0) +1 INTO intcounter
+ FROM expedition e
+ INNER JOIN ticket t1 ON e.ticketFk = t1.id
LEFT JOIN ticketState ts ON ts.ticket = t1.id
- INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
+ INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
AND t1.warehouseFk = t2.warehouseFk
- WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk
+ WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk
AND t1.agencyModeFk = t2.agencyModeFk;
SET NEW.`counter` = intcounter;
@@ -27007,9 +27011,9 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
IF NEW.counter <> OLD.counter THEN
- IF (SELECT COUNT(*) FROM expedition e
+ IF (SELECT COUNT(*) FROM expedition e
INNER JOIN ticket t1 ON e.ticketFk = t1.id
- INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
+ INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
WHERE t1.id = NEW.ticketFk AND counter = NEW.counter) > 0 THEN
SET NEW.id = NULL;
END IF;
@@ -27033,11 +27037,11 @@ DELIMITER ;;
BEFORE DELETE ON `expedition`
FOR EACH ROW
BEGIN
- UPDATE ticket t
- SET packages = (SELECT COUNT(counter)-1
+ UPDATE ticket t
+ SET packages = (SELECT COUNT(counter)-1
FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.freightItemFk)
- WHERE t.id = OLD.ticketFk;
-
+ WHERE t.id = OLD.ticketFk;
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -27152,13 +27156,13 @@ DELIMITER ;;
BEGIN
DECLARE vNewPosition INT;
-
+
SELECT MAX(position) + 1 INTO vNewPosition
FROM vn.expeditionPallet
WHERE truckFk = NEW.truckFk;
-
+
SET NEW.position = IFNULL(vNewPosition,1);
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -27260,7 +27264,7 @@ DELIMITER ;;
BEGIN
SET NEW.workerFk = vn.getUser();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -27322,9 +27326,9 @@ DELIMITER ;;
BEFORE INSERT
ON expeditionState FOR EACH ROW
BEGIN
-
+
SET NEW.userFk = account.myUser_getId();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -27348,7 +27352,7 @@ BEGIN
UPDATE vn.expedition e
SET e.stateTypeFk = NEW.typeFk
WHERE e.id = NEW.expeditionFk;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -28193,49 +28197,49 @@ BEGIN
DECLARE vIssuingCountry, vhostCountry INT;
DECLARE vActive TINYINT;
DECLARE vWithholdingSageFk INT;
-
- SELECT withholdingSageFk INTO vWithholdingSageFk
- FROM vn.supplier
+
+ SELECT withholdingSageFk INTO vWithholdingSageFk
+ FROM vn.supplier
WHERE id = NEW.supplierFk;
- SET NEW.withholdingSageFk = vWithholdingSageFk;
-
- SELECT countryFk, isActive INTO vIssuingCountry, vActive
- FROM vn.supplier
+ SET NEW.withholdingSageFk = vWithholdingSageFk;
+
+ SELECT countryFk, isActive INTO vIssuingCountry, vActive
+ FROM vn.supplier
WHERE id = NEW.supplierFk;
-
- SELECT countryFk INTO vhostCountry
- FROM vn.supplier
+
+ SELECT countryFk INTO vhostCountry
+ FROM vn.supplier
WHERE id = NEW.companyFk;
IF vActive = 0 THEN
CALL util.throw('INACTIVE_PROVIDER');
END IF;
-
- IF (SELECT COUNT(*) FROM vn.invoiceIn
- WHERE supplierRef = NEW.supplierRef
- AND supplierFk = NEW.supplierFk
+
+ IF (SELECT COUNT(*) FROM vn.invoiceIn
+ WHERE supplierRef = NEW.supplierRef
+ AND supplierFk = NEW.supplierFk
AND YEAR(issued) = YEAR(NEW.issued)
) THEN
CALL util.throw('reference duplicated');
END IF;
-
+
SELECT CASE WHEN (SELECT account FROM vn.supplier where id = NEW.supplierFk) LIKE '___3______' THEN 'C'
- WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry
+ WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry
where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'R'
- WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry
- where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E'
+ WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry
+ where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E'
WHEN (SELECT vIssuingCountry<>vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry
- where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W'
+ where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W'
END INTO vSerie;
-
+
SET NEW.serial = IFNULL(vSerie,'R');
IF vSerie LIKE 'W' THEN
- SELECT IFNULL(MAX(serialNumber) + 1,1) INTO vNumReceived
- FROM invoiceIn
- WHERE `serial` LIKE NEW.serial AND
- YEAR(issued) = YEAR(NEW.issued) AND
+ SELECT IFNULL(MAX(serialNumber) + 1,1) INTO vNumReceived
+ FROM invoiceIn
+ WHERE `serial` LIKE NEW.serial AND
+ YEAR(issued) = YEAR(NEW.issued) AND
companyFk = NEW.companyFk;
SET NEW.serialNumber = vNumReceived;
END IF;
@@ -28261,9 +28265,9 @@ BEGIN
DECLARE vWithholdingSageFk INT;
- IF (SELECT COUNT(*) FROM vn.invoiceIn
- WHERE supplierRef = NEW.supplierRef
- AND supplierFk = NEW.supplierFk
+ IF (SELECT COUNT(*) FROM vn.invoiceIn
+ WHERE supplierRef = NEW.supplierRef
+ AND supplierFk = NEW.supplierFk
AND YEAR(issued) = YEAR(NEW.issued)
AND id <> NEW.id
) THEN
@@ -28273,7 +28277,7 @@ BEGIN
IF NEW.supplierFk != OLD.supplierFk THEN
CALL supplier_checkIsActive(NEW.supplierFk);
SELECT withholdingSageFk INTO vWithholdingSageFk
- FROM vn.supplier
+ FROM vn.supplier
WHERE id = NEW.supplierFk;
SET NEW.withholdingSageFk = vWithholdingSageFk;
END IF;
@@ -28298,23 +28302,23 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
- IF NEW.issued != OLD.issued
+ IF NEW.issued != OLD.issued
OR NEW.currencyFk != OLD.currencyFk THEN
UPDATE invoiceInTax iit
JOIN invoiceIn ii ON ii.id = iit.invoiceInFk
LEFT JOIN referenceRate rr ON rr.dated = ii.issued
- AND rr.currencyFk = ii.currencyFk
+ AND rr.currencyFk = ii.currencyFk
SET iit.taxableBase = IF(iit.foreignValue IS NULL, iit.taxableBase, iit.foreignValue / rr.value)
WHERE ii.id = NEW.id;
-
+
UPDATE invoiceInDueDay iidd
JOIN invoiceIn ii ON ii.id = iidd.invoiceInFk
LEFT JOIN referenceRate rr ON rr.dated = ii.issued
- AND rr.currencyFk = ii.currencyFk
+ AND rr.currencyFk = ii.currencyFk
SET iidd.amount = IF(iidd.foreignValue IS NULL, iidd.amount, iidd.foreignValue / rr.value)
- WHERE ii.id = NEW.id;
-
+ WHERE ii.id = NEW.id;
+
END IF;
END */;;
@@ -28378,13 +28382,13 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
DECLARE vIsNotified BOOLEAN;
-
- SELECT isNotified INTO vIsNotified
- FROM vn.invoiceIn ii
+
+ SELECT isNotified INTO vIsNotified
+ FROM vn.invoiceIn ii
JOIN vn.supplier s ON s.id = ii.supplierFk
JOIN vn.payMethod pm ON pm.id = s.payMethodFk
WHERE ii.id = NEW.invoiceInFk;
-
+
IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified)
THEN
CALL mail_insert(
@@ -28392,12 +28396,12 @@ BEGIN
'begonya@verdnatura.es',
'Añadido vencimiento en el pasado',
CONCAT(
- account.myUser_getName(), ' ha añadido un vencimiento de ',
+ account.myUser_getName(), ' ha añadido un vencimiento de ',
NEW.amount, '€ en una fecha pasada en la recibida ', NEW.invoiceInFk
)
);
END IF;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -28418,13 +28422,13 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
DECLARE vIsNotified BOOLEAN;
-
- SELECT isNotified INTO vIsNotified
- FROM vn.invoiceIn ii
+
+ SELECT isNotified INTO vIsNotified
+ FROM vn.invoiceIn ii
JOIN vn.supplier s ON s.id = ii.supplierFk
JOIN vn.payMethod pm ON pm.id = s.payMethodFk
WHERE ii.id = NEW.invoiceInFk;
-
+
IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified)
THEN
CALL mail_insert(
@@ -28432,12 +28436,12 @@ BEGIN
'begonya@verdnatura.es',
'Añadido vencimiento en el pasado',
CONCAT(
- account.myUser_getName(), ' ha añadido un vencimiento de ',
+ account.myUser_getName(), ' ha añadido un vencimiento de ',
NEW.amount,'€ en una fecha pasada en la recibida ',NEW.invoiceInFk
)
);
END IF;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -28709,15 +28713,15 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
CALL clientRisk_update(NEW.clientFk, NEW.companyFk, NEW.amount);
- IF (SELECT COUNT(*)
- FROM client
- WHERE id = NEW.clientFk
+ IF (SELECT COUNT(*)
+ FROM client
+ WHERE id = NEW.clientFk
AND businessTypeFk = 'officialOrganism'
) THEN
CALL mail_insert('administracion@verdnatura.es',
NULL,
CONCAT('Se ha emitido una factura al organismo: ', NEW.clientFk),
- CONCAT('Presentar factura en FACE https://salix.verdnatura.es/#!/invoice-out/',
+ CONCAT('Presentar factura en FACE https://salix.verdnatura.es/#!/invoice-out/',
NEW.id,
'/summary'));
END IF;
@@ -28969,13 +28973,13 @@ BEGIN
DECLARE vItemPackingType VARCHAR(1);
IF NEW.itemPackingTypeFk IS NULL THEN
-
+
SELECT itemPackingTypeFk INTO vItemPackingType
- FROM vn.itemType it
+ FROM vn.itemType it
WHERE id = NEW.typeFk;
SET NEW.itemPackingTypeFk = vItemPackingType;
-
+
END IF;
END */;;
DELIMITER ;
@@ -29031,23 +29035,23 @@ DELIMITER ;;
BEFORE UPDATE ON `item`
FOR EACH ROW
BEGIN
-
+
DECLARE vNewPackingShelve INT;
- IF ISNULL(NEW.packingShelve) AND NOT ISNULL(NEW.packingOut) THEN
-
- SELECT NEW.packingOut * vc.shelveVolume / vc.standardFlowerBox
+ IF ISNULL(NEW.packingShelve) AND NOT ISNULL(NEW.packingOut) THEN
+
+ SELECT NEW.packingOut * vc.shelveVolume / vc.standardFlowerBox
INTO vNewPackingShelve
FROM vn.volumeConfig vc;
-
+
SET NEW.packingShelve = vNewPackingShelve;
-
+
END IF;
IF NEW.itemPackingTypeFk = '' THEN
SET NEW.itemPackingTypeFk = NULL;
-
+
END IF;
END */;;
@@ -29352,15 +29356,15 @@ BEGIN
IF NEW.itemFk IN (95, 98) THEN
SET NEW.cm3 = 0;
END IF;
-
+
IF !(NEW.cm3delivery <=> OLD.cm3delivery) THEN
INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
+ SELECT r.id
FROM vn.itemCost ic
JOIN vn.sale s ON s.itemFk = ic.itemFk
- JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk
+ JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk
JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
+ WHERE r.isOk = FALSE
AND ic.itemFk = NEW.itemFk
AND r.created >= util.VN_CURDATE()
GROUP BY r.id;
@@ -29685,10 +29689,10 @@ DELIMITER ;;
BEFORE INSERT ON `itemShelving`
FOR EACH ROW
BEGIN
-
+
SET NEW.userFk = account.myUser_getId();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -29795,8 +29799,8 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_DELETE`
BEFORE DELETE ON `itemShelving`
FOR EACH ROW
-INSERT INTO vn.itemShelvingLog(itemShelvingFk,
- workerFk,
+INSERT INTO vn.itemShelvingLog(itemShelvingFk,
+ workerFk,
accion,
shelvingFk,
itemFk)
@@ -29981,7 +29985,7 @@ DELIMITER ;;
BEGIN
UPDATE vn.sale
- SET isPicked = TRUE
+ SET isPicked = TRUE
WHERE id = NEW.saleFk;
END */;;
@@ -30158,7 +30162,7 @@ trig: BEGIN
IF @isTriggerDisabled OR visTriggerDisabled THEN
LEAVE trig;
END IF;
-
+
SET vItemFk = NEW.itemFk;
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
@@ -30183,7 +30187,7 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeUpdate`
BEFORE UPDATE ON `itemTag`
FOR EACH ROW
-BEGIN
+BEGIN
IF !(OLD.`value` <=> NEW.`value`)
OR !(OLD.intValue <=> NEW.intValue) THEN
SET NEW.intValue = itemTag_getIntValue(NEW.`value`);
@@ -30216,7 +30220,7 @@ trig: BEGIN
IF @isTriggerDisabled OR visTriggerDisabled THEN
LEAVE trig;
END IF;
-
+
SET vItemFk = NEW.itemFk;
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
@@ -30252,7 +30256,7 @@ trig: BEGIN
IF @isTriggerDisabled OR visTriggerDisabled THEN
LEAVE trig;
END IF;
-
+
SET vItemFk = OLD.itemFk;
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
@@ -30668,7 +30672,7 @@ DELIMITER ;;
BEFORE INSERT ON `machine`
FOR EACH ROW
BEGIN
-
+
SET NEW.workerFk = vn.getUser();
END */;;
@@ -30802,9 +30806,9 @@ DELIMITER ;;
BEGIN
IF NEW.sender IS NOT NULL THEN
-
+
SET NEW.receiver = NEW.sender;
-
+
END IF;
END */;;
@@ -30867,8 +30871,8 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
IF (NEW.code IS NULL) THEN
- SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT
- FROM information_schema.TABLES
+ SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT
+ FROM information_schema.TABLES
WHERE TABLE_SCHEMA='vn' and TABLE_NAME='mandate'));
END IF;
END */;;
@@ -31804,7 +31808,7 @@ DELIMITER ;;
BEGIN
-- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -31929,13 +31933,13 @@ BEGIN
SELECT account INTO cuenta_banco
FROM bank
WHERE id = NEW.bankFk;
-
+
SELECT account INTO cuenta_proveedor
FROM supplier
WHERE id = NEW.supplierFk;
-
+
CALL vn.ledger_next(vNewBookEntry);
-
+
INSERT INTO XDiario ( ASIEN,
FECHA,
SUBCTA,
@@ -31961,7 +31965,7 @@ BEGIN
cuenta_banco CONTRA,
NEW.amount EURODEBE,
0 EUROHABER) gf;
-
+
IF NEW.bankingFees <> 0 THEN
INSERT INTO XDiario ( ASIEN,
FECHA,
@@ -31983,7 +31987,7 @@ BEGIN
FROM supplier s
JOIN country c ON s.countryFk = c.id
WHERE s.id = NEW.supplierFk;
- END IF;
+ END IF;
END IF;
SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received);
@@ -31991,15 +31995,15 @@ BEGIN
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 ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -32021,12 +32025,12 @@ DELIMITER ;;
BEGIN
DECLARE vIsPayMethodChecked BOOLEAN;
DECLARE vEmail VARCHAR(150);
-
+
SELECT isPayMethodChecked INTO vIsPayMethodChecked
FROM supplier
WHERE id = NEW.supplierFk;
-
-
+
+
IF vIsPayMethodChecked = FALSE THEN
SELECT notificationEmail INTO vEmail
@@ -32896,11 +32900,11 @@ DELIMITER ;;
BEFORE INSERT
ON projectNotes FOR EACH ROW
BEGIN
-
+
IF ISNULL(NEW.userFk) THEN
-
+
SET NEW.userFk = account.myUser_getId();
-
+
END IF;
END */;;
@@ -33058,10 +33062,10 @@ DELIMITER ;;
BEFORE INSERT ON `province`
FOR EACH ROW
BEGIN
-
+
SET NEW.geoFk = zoneGeo_new('province', NEW.`name`,
(SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk));
-
+
SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk);
END */;;
@@ -33082,14 +33086,14 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_beforeUpdate`
BEFORE UPDATE ON `province`
FOR EACH ROW
-BEGIN
-
+BEGIN
+
IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN
-
+
SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk);
END IF;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -33137,7 +33141,7 @@ DELIMITER ;;
AFTER DELETE ON `province`
FOR EACH ROW
BEGIN
- CALL zoneGeo_delete(OLD.geoFk);
+ CALL zoneGeo_delete(OLD.geoFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -33277,7 +33281,7 @@ BEGIN
FROM accounting a
JOIN accountingType at2 ON at2.id = a.accountingTypeFk
WHERE a.id = NEW.bankFk;
-
+
SET NEW.isConciliate = vIsAutoConciliated;
END IF;
END */;;
@@ -33664,14 +33668,14 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
DECLARE vKmMax INT;
-
+
IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN
- SET NEW.m3 = ( SELECT SUM(litros)/1000
- FROM vn.saleVolume s
- JOIN vn.ticket t ON s.ticketFk = t.id
+ SET NEW.m3 = ( SELECT SUM(litros)/1000
+ FROM vn.saleVolume s
+ JOIN vn.ticket t ON s.ticketFk = t.id
WHERE t.routeFk = NEW.id);
END IF;
-
+
IF NEW.kmEnd < NEW.kmStart AND NEW.kmEnd <> 0 THEN
CALL util.throw ('KmEnd menor que kmStart');
END IF;
@@ -33705,15 +33709,15 @@ BEGIN
IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN
-- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets
-
+
-- Inserta el gestdoc en todos los tickets de la ruta
INSERT INTO ticketDms(ticketFk,dmsFk)
SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id
ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk;
- -- Update del firmado
- UPDATE ticket t
- JOIN ticketDms tg ON t.id = tg.ticketFk
+ -- Update del firmado
+ UPDATE ticket t
+ JOIN ticketDms tg ON t.id = tg.ticketFk
SET isSigned = 1 WHERE t.routeFk = NEW.id;
END IF;
@@ -34063,7 +34067,7 @@ BEGIN
CALL ticket_requestRecalc(NEW.ticketFk);
IF NEW.quantity > 0 THEN
-
+
UPDATE vn.collection c
JOIN vn.ticketCollection tc ON tc.collectionFk = c.id
AND tc.ticketFk = NEW.ticketFk
@@ -34071,13 +34075,13 @@ BEGIN
AND (c.itemPackingTypeFk = i.itemPackingTypeFk
OR c.itemPackingTypeFk IS NULL)
SET c.saleTotalCount = c.saleTotalCount + 1;
-
+
INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
+ SELECT r.id
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
+ WHERE r.isOk = FALSE
AND s.id = NEW.id
AND r.created >= util.VN_CURDATE()
GROUP BY r.id;
@@ -34106,7 +34110,7 @@ DELIMITER ;;
BEFORE UPDATE ON `sale`
FOR EACH ROW
BEGIN
-/*
+/*
IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN
CALL util.throw('Cannot insert a service item into a ticket');
END IF;
@@ -34117,7 +34121,7 @@ BEGIN
IF old.discount > 0 AND NEW.discount = 0 THEN
INSERT INTO ticketLog
- SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert',
+ SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert',
description = CONCAT('Cambio de descuento del item :', ' ', new.itemFk, ' de ', old.discount ,' a 0 ');
END IF;
END */;;
@@ -34143,7 +34147,7 @@ BEGIN
DECLARE vPickedLines INT;
DECLARE vCollectionFk INT;
DECLARE vUserRole VARCHAR(255);
-
+
IF !(NEW.id <=> OLD.id)
OR !(NEW.ticketFk <=> OLD.ticketFk)
OR !(NEW.itemFk <=> OLD.itemFk)
@@ -34166,45 +34170,45 @@ BEGIN
UPDATE ticketRequest SET ticketFk = NEW.ticketFk
WHERE saleFk = NEW.id;
END IF;
-
+
SELECT account.myUser_getName() INTO vUserRole;
SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole;
IF !(OLD.quantity <=> NEW.quantity) THEN
- SELECT COUNT(*) INTO vIsToSendMail
+ SELECT COUNT(*) INTO vIsToSendMail
FROM ticketTracking tt
JOIN vn.state s ON s.id = tt.stateFk
- WHERE s.code='PACKED'
+ WHERE s.code='PACKED'
AND tt.ticketFk = OLD.ticketFk
AND vUserRole IN ('salesPerson', 'salesTeamBoss')
LIMIT 1;
-
+
IF vIsToSendMail THEN
CALL vn.mail_insert('jefesventas@verdnatura.es',
'noreply@verdnatura.es',
CONCAT('Ticket ', OLD.ticketFk ,' modificada cantidad tras encajado'),
CONCAT('Ticket ', OLD.ticketFk ,'.
',
- 'Modificada la catidad de ', OLD.quantity, ' a ' , NEW.quantity,
+ 'Modificada la catidad de ', OLD.quantity, ' a ' , NEW.quantity,
' del artículo ', OLD.itemFk, ' tras estado encajado del ticket.
',
'Este email se ha generado automáticamente' )
);
END IF;
IF (OLD.quantity > NEW.quantity) THEN
INSERT INTO saleComponent(saleFk, componentFk, value)
- SELECT NEW.id, cm.id, sc.value
+ SELECT NEW.id, cm.id, sc.value
FROM saleComponent sc
JOIN component cd ON cd.id = sc.componentFk
JOIN component cm ON cm.code = 'mana'
WHERE saleFk = NEW.id AND cd.code = 'lastUnitsDiscount'
ON DUPLICATE KEY UPDATE value = sc.value + VALUES(value);
-
- DELETE sc.*
+
+ DELETE sc.*
FROM vn.saleComponent sc
JOIN component c ON c.id = sc.componentFk
WHERE saleFk = NEW.id AND c.code = 'lastUnitsDiscount';
- END IF;
+ END IF;
INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
+ SELECT r.id
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.route r ON r.id = t.routeFk
@@ -34251,11 +34255,11 @@ DELIMITER ;;
BEGIN
IF OLD.quantity > 0 THEN
INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
+ SELECT r.id
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
+ WHERE r.isOk = FALSE
AND s.id = OLD.id
AND r.created >= util.VN_CURDATE()
GROUP BY r.id;
@@ -34288,15 +34292,15 @@ BEGIN
SELECT account.myUser_getName() INTO vUserRole;
SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole;
- SELECT COUNT(*) INTO vIsToSendMail
+ SELECT COUNT(*) INTO vIsToSendMail
FROM ticketTracking tt
JOIN vn.state s ON s.id = tt.stateFk
- WHERE s.code='PACKED'
+ WHERE s.code='PACKED'
AND tt.ticketFk = OLD.ticketFk
AND vUserRole IN ('salesPerson', 'salesBoss')
LIMIT 1;
- IF vIsToSendMail THEN
+ IF vIsToSendMail THEN
CALL vn.mail_insert('jefesventas@verdnatura.es',
'noreply@verdnatura.es',
CONCAT('Ticket ', OLD.ticketFk ,' eliminado artículo tras encajado' ),
@@ -34308,8 +34312,8 @@ BEGIN
IF OLD.quantity > 0 THEN
UPDATE vn.collection c
JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = OLD.ticketFk
- JOIN vn.item i ON i.id = OLD.itemFk
- AND (c.itemPackingTypeFk = i.itemPackingTypeFk
+ JOIN vn.item i ON i.id = OLD.itemFk
+ AND (c.itemPackingTypeFk = i.itemPackingTypeFk
OR ISNULL(c.itemPackingTypeFk))
SET c.saleTotalCount = c.saleTotalCount - 1,
c.salePickedCount = c.salePickedCount - ABS(OLD.isPicked);
@@ -34351,10 +34355,10 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`BEFORE_INSERT`
BEFORE INSERT ON `saleBuy`
FOR EACH ROW
-BEGIN
-
+BEGIN
+
SET NEW.workerFk = vn.getUser();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -34373,13 +34377,13 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleBuy_AI`
AFTER INSERT ON `saleBuy`
FOR EACH ROW
-BEGIN
+BEGIN
/* Activar de nuevo cuando volvamos a vender fruta y verdura
- *
+ *
UPDATE vn.sale s
SET s.concept = CONCAT(s.concept, ' Lote: ', NEW.buyFk)
WHERE s.id = NEW.saleFk;
-*/
+*/
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -34650,14 +34654,14 @@ DELIMITER ;;
AFTER INSERT ON `saleTracking`
FOR EACH ROW
BEGIN
-
- IF NEW.isChecked THEN
-
+
+ IF NEW.isChecked THEN
+
UPDATE vn.sale s
- SET s.isPicked = TRUE
+ SET s.isPicked = TRUE
WHERE s.id = NEW.saleFk
AND s.isPicked = 0;
-
+
END IF;
END */;;
@@ -34972,9 +34976,9 @@ BEGIN
IF NEW.workerFk = NEW.workerSubstitute THEN
CALL util.throw ('worker and workerSubstitute must be different');
ELSE
- INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated)
- SELECT NEW.workerFk, NEW.workerSubstitute, dated
- FROM time
+ INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated)
+ SELECT NEW.workerFk, NEW.workerSubstitute, dated
+ FROM time
WHERE dated BETWEEN NEW.started AND NEW.ended;
END IF;
END */;;
@@ -34999,14 +35003,14 @@ BEGIN
IF NEW.workerFk = NEW.workerSubstitute THEN
CALL util.throw ('worker and workerSubstitute must be different');
ELSE
- DELETE sc FROM sharingCartDaily sc
- WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND
- sc.ownerFk = OLD.workerFk AND
+ DELETE sc FROM sharingCartDaily sc
+ WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND
+ sc.ownerFk = OLD.workerFk AND
sc.substituteFk = OLD.workerSubstitute;
-
- INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated)
- SELECT NEW.workerFk, NEW.workerSubstitute, dated
- FROM time
+
+ INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated)
+ SELECT NEW.workerFk, NEW.workerSubstitute, dated
+ FROM time
WHERE dated BETWEEN NEW.started AND NEW.ended;
END IF;
@@ -35029,9 +35033,9 @@ DELIMITER ;;
BEFORE DELETE ON `sharingCart`
FOR EACH ROW
BEGIN
- DELETE sc FROM sharingCartDaily sc
- WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND
- sc.ownerFk = OLD.workerFk AND
+ DELETE sc FROM sharingCartDaily sc
+ WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND
+ sc.ownerFk = OLD.workerFk AND
sc.substituteFk = OLD.workerSubstitute;
END */;;
DELIMITER ;
@@ -35164,9 +35168,9 @@ DELIMITER ;;
BEGIN
IF NEW.code = "" THEN
-
+
CALL util.throw('NOT_EMPTY_CODE_ALLOWED');
-
+
END IF;
END */;;
@@ -35188,13 +35192,13 @@ DELIMITER ;;
BEFORE UPDATE ON `shelving`
FOR EACH ROW
BEGIN
-
+
IF NEW.code = "" THEN
-
+
CALL util.throw('NOT_EMPTY_CODE_ALLOWED');
-
+
END IF;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -35386,7 +35390,7 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
UPDATE vn2008.Clientes c
- JOIN creditClassification cc ON c.Id_Cliente = cc.client
+ JOIN creditClassification cc ON c.Id_Cliente = cc.client
JOIN creditInsurance ci ON ci.creditClassification = cc.id
SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance;
END */;;
@@ -35410,12 +35414,12 @@ DELIMITER ;;
BEGIN
IF NEW.dateLeaving IS NOT NULL THEN
UPDATE vn2008.Clientes c
- JOIN creditClassification cc ON c.Id_Cliente = cc.client
+ JOIN creditClassification cc ON c.Id_Cliente = cc.client
JOIN creditInsurance ci ON ci.creditClassification = cc.id
SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance;
ELSE
UPDATE vn2008.Clientes c
- JOIN creditClassification cc ON c.Id_Cliente = cc.client
+ JOIN creditClassification cc ON c.Id_Cliente = cc.client
JOIN creditInsurance ci ON ci.creditClassification = cc.id
SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance;
END IF;
@@ -35439,7 +35443,7 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
UPDATE vn2008.Clientes c
- JOIN creditClassification cc ON c.Id_Cliente = cc.client
+ JOIN creditClassification cc ON c.Id_Cliente = cc.client
JOIN creditInsurance ci ON ci.creditClassification = cc.id
SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance;
END */;;
@@ -35906,7 +35910,7 @@ BEGIN
FROM vn.supplier s
JOIN vn.payMethod pm ON pm.id = s.payMethodFk
WHERE s.id = OLD.supplierFk;
-
+
IF OLD.iban <> NEW.iban OR OLD.bankEntityFk <> NEW.bankEntityFk AND vPayMethodHasVerified THEN
UPDATE vn.supplier
SET isPayMethodChecked = FALSE
@@ -36449,11 +36453,11 @@ DELIMITER ;;
AFTER INSERT ON `ticket`
FOR EACH ROW
BEGIN
-
+
DECLARE vClientType VARCHAR(255);
DECLARE vStateCode VARCHAR(255);
DECLARE vTransferorFirstShipped DATE;
-
+
-- Borrar cuando se cambie el insert ticket en la APP móvil
SELECT typeFk INTO vClientType
@@ -36466,8 +36470,8 @@ BEGIN
END IF;
INSERT INTO ticketTracking(ticketFk, stateFk, workerFk)
- SELECT NEW.id, id, account.myUser_getId()
- FROM state
+ SELECT NEW.id, id, account.myUser_getId()
+ FROM state
WHERE `code` = vStateCode COLLATE utf8_general_ci;
IF YEAR(NEW.shipped) > 2000 THEN
@@ -36480,7 +36484,7 @@ BEGIN
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 */;;
@@ -36503,17 +36507,17 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
DECLARE vNewTime TIME;
-
+
IF !(NEW.routeFk <=> OLD.routeFk) THEN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
+ INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
+ SELECT r.id
FROM vn.route r
- WHERE r.isOk = FALSE
+ WHERE r.isOk = FALSE
AND r.id IN (OLD.routeFk,NEW.routeFk)
AND r.created >= util.VN_CURDATE()
GROUP BY r.id;
END IF;
-
+
IF !(DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN
IF YEAR(NEW.shipped) < 2000 THEN
SIGNAL SQLSTATE '46000'
@@ -36525,13 +36529,13 @@ BEGIN
END IF;
END IF;
-
+
IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
+ INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
+ SELECT r.id
FROM vn.ticket t
JOIN vn.route r ON r.id = t.routeFk
- WHERE r.isOk = FALSE
+ WHERE r.isOk = FALSE
AND t.id = NEW.id
AND r.created >= util.VN_CURDATE()
GROUP BY r.id;
@@ -36541,7 +36545,7 @@ BEGIN
SET NEW.zoneFk = NULL;
END IF;
- IF NEW.routeFk AND NEW.isDeleted THEN
+ IF NEW.routeFk AND NEW.isDeleted THEN
CALL util.throw ('This ticket is deleted');
END IF;
@@ -36550,22 +36554,22 @@ BEGIN
FROM vn.ticket
WHERE routeFk = NEW.routeFk
HAVING MAX(TIME(shipped)) > TIME(NEW.shipped);
-
+
IF vNewTime THEN
SET NEW.shipped = TIMESTAMP(DATE(NEW.shipped), vNewTime);
INSERT INTO vn.ticketLog
- SET originFk = NEW.id,
- userFk = account.myUser_getId(),
- `action` = 'update',
+ SET originFk = NEW.id,
+ userFk = account.myUser_getId(),
+ `action` = 'update',
description = CONCAT('Cambia la hora por cambio de ruta de ',
TIME(OLD.shipped),
' a ',
TIME(NEW.shipped));
END IF;
INSERT IGNORE INTO zoneAgencyMode (agencyModeFk,zoneFk)
- SELECT r.agencyModeFk, NEW.zoneFk FROM route r
+ SELECT r.agencyModeFk, NEW.zoneFk FROM route r
WHERE r.id = NEW.routeFk;
-
+
CALL vn.routeUpdateM3(NEW.routeFk);
END IF;
END */;;
@@ -36599,7 +36603,7 @@ BEGIN
OR !(NEW.companyFk <=> OLD.companyFk) THEN
CALL ticket_requestRecalc(NEW.id);
END IF;
-
+
IF NEW.clientFk = 2067 AND !(NEW.clientFk <=> OLD.clientFk) THEN
-- Fallo que se insertan no se sabe como tickets en este cliente
CALL mail_insert(
@@ -36609,10 +36613,10 @@ BEGIN
CONCAT(account.myUser_getName(), ' ha modificado el ticket ',NEW.id)
);
END IF;
-
+
IF NEW.routeFk <> OLD.routeFk THEN
- UPDATE expedition
+ UPDATE expedition
SET hasNewRoute = TRUE
WHERE ticketFk = NEW.id;
@@ -36636,11 +36640,11 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_beforeDelete`
BEFORE DELETE ON `ticket`
FOR EACH ROW
-BEGIN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
+BEGIN
+ INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
+ SELECT r.id
FROM vn.route r
- WHERE r.isOk = FALSE
+ WHERE r.isOk = FALSE
AND r.id = OLD.routeFk
AND r.created >= util.VN_CURDATE()
GROUP BY r.id;
@@ -36696,28 +36700,28 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete
AFTER DELETE
ON ticketCollection FOR EACH ROW
-BEGIN
-
+BEGIN
+
DECLARE vSalesRemaining INT;
SELECT count(*) INTO vSalesRemaining
FROM vn.ticketCollection tc
- JOIN sale s ON s.ticketFk = tc.ticketFk
+ JOIN sale s ON s.ticketFk = tc.ticketFk
WHERE collectionFk = OLD.collectionFk
AND tc.id != OLD.id;
-
+
IF NOT vSalesRemaining THEN
-
+
DELETE FROM vn.collection WHERE id = OLD.collectionFk;
-
+
ELSE
-
- UPDATE vn.collection
+
+ UPDATE vn.collection
SET saleTotalCount = vSalesRemaining
WHERE id = OLD.collectionFk;
-
+
END IF;
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -36770,13 +36774,13 @@ DELIMITER ;;
BEFORE DELETE ON `ticketDms`
FOR EACH ROW
BEGIN
- UPDATE dms
- SET dmsTypeFk = (SELECT id
- FROM dmsType
+ UPDATE dms
+ SET dmsTypeFk = (SELECT id
+ FROM dmsType
WHERE `code` = 'trash'
)
- WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE)
- FROM ticketDms
+ WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE)
+ FROM ticketDms
WHERE dmsFk = OLD.dmsFk
) ;
END */;;
@@ -37118,7 +37122,7 @@ DELIMITER ;;
BEGIN
SET NEW.workerFk = vn.getUser();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -37364,7 +37368,7 @@ DELIMITER ;;
BEGIN
CALL ticket_requestRecalc(NEW.ticketFk);
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -37540,18 +37544,18 @@ BEGIN
DECLARE vState VARCHAR(15);
DECLARE vZoneFk INT;
DECLARE vBoardingStateFk INT;
-
+
SELECT s.code INTO vState
FROM state s
WHERE s.id = NEW.stateFk;
-
+
SELECT t.zonefk INTO vZoneFk
FROM ticket t
- WHERE t.id = NEW.ticketFk;
-
+ WHERE t.id = NEW.ticketFk;
+
IF vState = 'OK' AND vZoneFk IS NULL THEN
CALL util.throw("ASSIGN_ZONE_FIRST");
- END IF;
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -37572,11 +37576,11 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
DECLARE vNumTicketsPrepared INT;
-
+
REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name)
SELECT NEW.ticketFk, NEW.id, `name`
FROM state
- WHERE id = NEW.stateFk;
+ WHERE id = NEW.stateFk;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -37599,21 +37603,21 @@ BEGIN
DECLARE vTicketFk INT;
DECLARE vTicketTrackingFk INT;
DECLARE vStateName VARCHAR(15);
-
+
IF NEW.stateFk <> OLD.stateFk THEN
REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name)
SELECT NEW.ticketFk, NEW.id, `name`
FROM state
WHERE id = NEW.stateFk;
END IF;
-
+
IF NEW.ticketFk <> OLD.ticketFk THEN
SELECT i.ticketFk, i.id, s.`name`
- INTO vTicketFk, vTicketTrackingFk, vStateName
- FROM ticketTracking i
- JOIN state s ON i.stateFk = s.id
- WHERE ticketFk = NEW.ticketFk
- ORDER BY created DESC
+ INTO vTicketFk, vTicketTrackingFk, vStateName
+ FROM ticketTracking i
+ JOIN state s ON i.stateFk = s.id
+ WHERE ticketFk = NEW.ticketFk
+ ORDER BY created DESC
LIMIT 1;
IF vTicketFk > 0 THEN
@@ -37649,18 +37653,18 @@ BEGIN
DELETE FROM vn.ticketLastState
WHERE ticketFk = OLD.ticketFk;
END;
-
+
CALL util.debugAdd('deletedState',
CONCAT('interFk: ', OLD.id,
' ticketFk: ', OLD.ticketFk,
' stateFk: ', OLD.stateFk));
SELECT i.ticketFk, i.id, s.`name`
- INTO vTicketFk, vTicketTrackingFk, vStateName
- FROM ticketTracking i
- JOIN state s ON i.stateFk = s.id
- WHERE ticketFk = OLD.ticketFk
- ORDER BY created DESC
+ INTO vTicketFk, vTicketTrackingFk, vStateName
+ FROM ticketTracking i
+ JOIN state s ON i.stateFk = s.id
+ WHERE ticketFk = OLD.ticketFk
+ ORDER BY created DESC
LIMIT 1;
IF vTicketFk > 0 THEN
@@ -38243,7 +38247,7 @@ BEGIN
CALL stock.log_add('travel', NEW.id, OLD.id);
IF !(NEW.shipped <=> OLD.shipped) THEN
- UPDATE entry
+ UPDATE entry
SET commission = entry_getCommission(travelFk, currencyFk,supplierFk)
WHERE travelFk = NEW.id;
END IF;
@@ -38752,7 +38756,7 @@ DELIMITER ;;
BEGIN
IF NEW.isFeedStock THEN
INSERT INTO warehouseAlias(`name`) VALUES(NEW.`name`);
- INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk)
+ INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk)
VALUES(NEW.id,LAST_INSERT_ID());
END IF;
END */;;
@@ -38776,7 +38780,7 @@ DELIMITER ;;
BEGIN
IF NEW.isFeedStock IS TRUE and OLD.isFeedStock IS FALSE then
INSERT INTO warehouseAlias(`name`) VALUES(NEW.`name`);
- INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk)
+ INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk)
VALUES(NEW.id,LAST_INSERT_ID());
END IF;
END */;;
@@ -38924,7 +38928,7 @@ DELIMITER ;;
BEFORE UPDATE
ON worker FOR EACH ROW
BEGIN
- IF NOT (NEW.labelerFk <=> OLD.labelerFk AND NEW.sectorFk <=> OLD.sectorFk) THEN
+ IF NOT (NEW.labelerFk <=> OLD.labelerFk AND NEW.sectorFk <=> OLD.sectorFk) THEN
CALL vn.printer_checkSector(NEW.labelerFk, NEW.sectorFk);
END IF;
END */;;
@@ -39499,9 +39503,9 @@ DELIMITER ;;
AFTER INSERT ON `workerTimeControl`
FOR EACH ROW
BEGIN
- IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN
+ IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN
CALL util.throw('date in the future');
- END IF;
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -40075,10 +40079,10 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BI`
BEFORE INSERT ON `zoneExclusion`
FOR EACH ROW
-BEGIN
-
+BEGIN
+
SET NEW.userFk = account.myUser_getId();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -40097,10 +40101,10 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BU`
BEFORE UPDATE ON `zoneExclusion`
FOR EACH ROW
-BEGIN
-
+BEGIN
+
SET NEW.userFk = account.myUser_getId();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -40765,7 +40769,7 @@ BEGIN
DECLARE vGeoFk INT;
SELECT p.geoFk INTO vGeoFk
- FROM address a
+ FROM address a
JOIN town t ON t.provinceFk = a.provinceFk
JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode
WHERE a.id = vSelf
@@ -40792,12 +40796,12 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11)
DETERMINISTIC
BEGIN
-
+
/**
* Obtiene el id del artículo
*
* @param vBarcode código de barras
- *
+ *
* return id del item
*/
@@ -40807,35 +40811,35 @@ BEGIN
FROM vn.item
WHERE id = vBarcode OR comment = vBarcode
LIMIT 1;
-
- IF vItemFk THEN
+
+ IF vItemFk THEN
RETURN vItemFk;
END IF;
- SELECT itemFk INTO vItemFk
- FROM buy
+ SELECT itemFk INTO vItemFk
+ FROM buy
WHERE id = vBarcode;
-
- IF vItemFk THEN
- RETURN vItemFk;
- END IF;
-
- SELECT itemFk INTO vItemFk
- FROM itemBarcode
- WHERE code = vBarcode;
-
- IF vItemFk THEN
+
+ IF vItemFk THEN
RETURN vItemFk;
END IF;
- SELECT i.id INTO vItemFk
+ SELECT itemFk INTO vItemFk
+ FROM itemBarcode
+ WHERE code = vBarcode;
+
+ IF vItemFk THEN
+ RETURN vItemFk;
+ END IF;
+
+ SELECT i.id INTO vItemFk
FROM vn.item i
WHERE i.name LIKE CONCAT('%',vBarcode,'%')
ORDER BY i.id ASC
LIMIT 1;
-
+
RETURN vItemFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -40857,9 +40861,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `botanicExport_isUpdatable`(vEdiGenus
DETERMINISTIC
BEGIN
DECLARE vIsUpdatable INTEGER;
- SELECT COUNT(*) INTO vIsUpdatable
- FROM botanicExport
- WHERE ediGenusFk = vEdiGenusFk
+ SELECT COUNT(*) INTO vIsUpdatable
+ FROM botanicExport
+ WHERE ediGenusFk = vEdiGenusFk
AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL)
AND (vCountryFk = countryFk OR IFNULL(vCountryFk,countryFk) IS NULL)
AND vRestriction = restriction;
@@ -40956,16 +40960,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `catalog_componentReverse`(vWarehouse
DETERMINISTIC
BEGIN
/* Calcula los componentes para un cliente a partir de un coste y volumen
- * @param vWarehouse
+ * @param vWarehouse
* @param vCost Valor de coste del articulo
* @param vM3 m3 del articulo
- * @param vAddressFk
+ * @param vAddressFk
* @param vZoneFk
- * @return vRetailedPrice precio de venta sin iva
+ * @return vRetailedPrice precio de venta sin iva
* @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
*/
-
- DECLARE vBoxVolume BIGINT;
+
+ DECLARE vBoxVolume BIGINT;
DECLARE vCustomer INT;
DECLARE vComponentRecovery INT DEFAULT 17;
DECLARE vComponentMana INT DEFAULT 39;
@@ -40974,11 +40978,11 @@ BEGIN
DECLARE vComponentCost INT DEFAULT 28;
DECLARE vRetailedPrice DECIMAL(10,2);
DECLARE vItem INT DEFAULT 98;
-
+
SELECT volume INTO vBoxVolume
FROM vn.packaging
WHERE id = '94';
-
+
SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk;
DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component;
@@ -41002,7 +41006,7 @@ BEGIN
-- Margen
-- No se aplica margen, cau 12589
/* INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
- SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost
+ SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost
FROM vn.rate
WHERE dated <= util.VN_CURDATE()
AND warehouseFk = vWarehouse
@@ -41011,7 +41015,7 @@ BEGIN
*/
-- Recobro
INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
- SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3)
+ SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3)
FROM bi.claims_ratio
WHERE Id_Cliente = vCustomer AND recobro > 0.009;
@@ -41028,7 +41032,7 @@ BEGIN
ROUND(
vM3
* (z.price - z.bonus)
- * z.inflation
+ * z.inflation
/ vBoxVolume, 4
)
FROM zone z
@@ -41100,30 +41104,30 @@ BEGIN
DECLARE vAutoManaComponent INT;
DECLARE vManaBank INT;
DECLARE vManaGreugeType INT;
-
+
SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana';
SELECT id INTO vManaBank FROM bank WHERE code = 'mana';
SELECT id INTO vManaComponent FROM component WHERE code = 'mana';
SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana';
-
+
SELECT COUNT(*) INTO vHasMana
FROM `client` c
WHERE c.id = vClient AND c.typeFk = 'normal';
-
+
IF NOT vHasMana THEN
RETURN 0;
END IF;
-
+
SELECT max(dated) INTO vFromDated
FROM clientManaCache;
SELECT sum(mana) INTO vMana
- FROM
+ FROM
(
SELECT mana
FROM clientManaCache
WHERE clientFk = vClient
- AND dated = vFromDated
+ AND dated = vFromDated
UNION ALL
SELECT s.quantity * value
FROM ticket t
@@ -41131,7 +41135,7 @@ BEGIN
JOIN sale s on s.ticketFk = t.id
JOIN saleComponent sc on sc.saleFk = s.id
WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent)
- AND t.shipped > vFromDated
+ AND t.shipped > vFromDated
AND t.shipped < TIMESTAMPADD(DAY,1,util.VN_CURDATE())
AND a.clientFk = vClient
UNION ALL
@@ -41195,7 +41199,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `clientTaxArea`(vClientId INT, vCompa
READS SQL DATA
BEGIN
/**
- * Devuelve el area de un cliente,
+ * Devuelve el area de un cliente,
* intracomunitario, extracomunitario o nacional.
*
* @param vClient Id del cliente
@@ -41242,7 +41246,7 @@ BEGIN
SELECT COUNT(*) INTO vHasDebt
FROM `client` c
WHERE c.id = vClient AND c.typeFk = 'normal';
-
+
IF NOT vHasDebt THEN
RETURN 0;
END IF;
@@ -41330,8 +41334,8 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `client_getSalesPerson`(vClientFk INT
DETERMINISTIC
BEGIN
/**
- * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo
- * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de
+ * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo
+ * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de
* sharingcart y tercero la de clientes.
*
* @param vClientFk El id del cliente
@@ -41369,29 +41373,29 @@ BEGIN
l: LOOP
SELECT workerSubstitute INTO vWorkerSubstituteFk
- FROM sharingCart
+ FROM sharingCart
WHERE util.VN_CURDATE() BETWEEN started AND ended
AND workerFk = vSalesPersonFk
ORDER BY id
LIMIT 1;
-
+
IF vWorkerSubstituteFk IS NULL THEN
LEAVE l;
END IF;
-
+
SELECT COUNT(*) > 0 INTO vLoop
FROM tmp.stack WHERE substitute = vWorkerSubstituteFk;
IF vLoop THEN
LEAVE l;
END IF;
-
+
INSERT INTO tmp.stack SET
substitute = vWorkerSubstituteFk;
-
+
SET vSalesPersonFk = vWorkerSubstituteFk;
END LOOP;
-
+
DROP TEMPORARY TABLE tmp.stack;
END IF;
@@ -41425,11 +41429,11 @@ BEGIN
**/
DECLARE vClientFk INT;
DECLARE vDated DATE;
-
+
SELECT clientFk, shipped
INTO vClientFk, vDated
FROM ticket WHERE id = vTicketFk;
-
+
RETURN client_getSalesPerson(vClientFk, vDated);
END ;;
DELIMITER ;
@@ -41460,12 +41464,12 @@ BEGIN
**/
DECLARE vWorkerCode CHAR(3);
DECLARE vSalesPersonFk INT;
-
+
SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated);
SELECT code
INTO vWorkerCode
- FROM worker
+ FROM worker
WHERE id = vSalesPersonFk;
RETURN vWorkerCode;
@@ -41498,11 +41502,11 @@ BEGIN
**/
DECLARE vClientFk INT;
DECLARE vDated DATE;
-
+
SELECT clientFk, shipped
INTO vClientFk, vDated
FROM ticket WHERE id = vTicketFk;
-
+
RETURN client_getSalesPersonCode(vClientFk, vDated);
END ;;
DELIMITER ;
@@ -41630,7 +41634,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `currentRate`(vCurrencyFk INT, vDated
BEGIN
DECLARE curRate DECIMAL(10,4);
-
+
SELECT value INTO curRate
FROM referenceRate
WHERE dated <= vDated
@@ -41661,23 +41665,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `deviceProductionUser_accessGranted`(
BEGIN
/*
* Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil
- *
+ *
* */
-
+
/*DECLARE vIsGranted BOOLEAN;
DECLARE vDeviceProductionFk INT(11) DEFAULT NULL;
- SELECT dp.id INTO vDeviceProductionFk
- FROM vn.deviceProduction dp
+ SELECT dp.id INTO vDeviceProductionFk
+ FROM vn.deviceProduction dp
WHERE dp.android_id = android_id;
IF vDeviceProductionFk THEN
-
- SELECT COUNT(*) INTO vIsGranted
- FROM vn.deviceProductionUser dpu
- WHERE dpu.userFk = vUserFK
+
+ SELECT COUNT(*) INTO vIsGranted
+ FROM vn.deviceProductionUser dpu
+ WHERE dpu.userFk = vUserFK
AND dpu.deviceProductionFk = vDeviceProductionFk;
-
+
RETURN vIsGranted;
END IF;*/
RETURN TRUE;
@@ -41701,16 +41705,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass
DETERMINISTIC
BEGIN
DECLARE vCountryFk INTEGER;
-
+
SELECT s.countryFk INTO vCountryFk
FROM dua d
JOIN supplier s ON s.id = d.companyFk
WHERE d.id = vDua;
-
+
RETURN (SELECT rate
FROM
(SELECT taxClassFk, rate
- FROM invoiceInTaxBookingAccount
+ FROM invoiceInTaxBookingAccount
WHERE effectived <= util.VN_CURDATE()
AND countryFk = vCountryFk
AND taxClassFk = vTaxClass
@@ -41738,24 +41742,24 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getEntry`(vEktFk INT) RETURNS in
READS SQL DATA
BEGIN
/**
- * Devuelve el numero de entrada para el ekt
- *
+ * Devuelve el numero de entrada para el ekt
+ *
* @param vEktFk Identificador de edi.ekt
- */
+ */
DECLARE vTravelFk INT;
DECLARE vEntryFk INT DEFAULT 0;
DECLARE vEntryAssignFk INT;
- SELECT ea.id
+ SELECT ea.id
INTO vEntryAssignFk
FROM edi.ekt e
- JOIN vn.ektEntryAssign ea ON
+ JOIN vn.ektEntryAssign ea ON
IFNULL(ea.sub, e.sub) <=> e.sub AND
IFNULL(ea.kop, e.kop) <=> e.kop AND
IFNULL(ea.pro, e.pro) <=> e.pro AND
IFNULL(ea.auction, e.auction) <=> e.auction
WHERE e.id = vEktFk
- ORDER BY
+ ORDER BY
IF(ea.sub,1,0) * 1000 +
IF(ea.kop,1,0) * 100 +
IF(ea.pro,1,0) * 10 +
@@ -41766,7 +41770,7 @@ BEGIN
IF vTravelFk THEN
- SELECT MAX(e.id)
+ SELECT MAX(e.id)
INTO vEntryFk
FROM vn.entry e
JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk
@@ -41781,13 +41785,13 @@ BEGIN
INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, reference, pro, auction)
SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction
FROM vn.ektEntryAssign ea
- JOIN vn.currency cu ON cu.code = 'EUR'
+ JOIN vn.currency cu ON cu.code = 'EUR'
WHERE ea.id = vEntryAssignFk;
SET vEntryFk = LAST_INSERT_ID();
END IF;
- UPDATE vn.ektEntryAssign
+ UPDATE vn.ektEntryAssign
SET entryFk = vEntryFk
WHERE id = vEntryAssignFk;
@@ -41821,7 +41825,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getTravel`(vEntryAssignFk INT, v
BEGIN
/**
* Devuelve un vn.travel.id
- *
+ *
* @param vEntryAssignFk Identificador de vn.entryAssign
*/
DECLARE vTravelFk INT;
@@ -41883,36 +41887,36 @@ BEGIN
DECLARE vCurrentCommission INT;
DECLARE vIsCurrencyUsd INT;
DECLARE vLastEntryFk INT;
-
+
SELECT count(*) INTO vIsCurrencyUsd
FROM currency c
WHERE c.code = 'USD' AND id = vCurrencyFk;
-
+
IF NOT vIsCurrencyUsd THEN
-
+
SELECT e.id INTO vLastEntryFk
FROM vn.entry e
JOIN vn.travel tr ON tr.id = e.travelFk
WHERE e.supplierFk = vSupplierFk
ORDER BY tr.landed DESC
LIMIT 1;
-
+
IF vLastEntryFk THEN
-
+
SELECT commission INTO vCurrentCommission
FROM vn.entry
WHERE id = vLastEntryFk;
-
+
ELSE
-
+
SELECT commission INTO vCurrentCommission
FROM supplier s
WHERE s.id = vSupplierFk;
-
+
END IF;
-
+
RETURN vCurrentCommission;
-
+
ELSE
SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission
@@ -41921,11 +41925,11 @@ BEGIN
WHERE t.id = vTravelFk
ORDER BY r.`dated` DESC
LIMIT 1;
-
+
RETURN IFNULL(vCommission, 0);
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -41977,10 +41981,10 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
-
+
/**
* Devuelve una entrada para Logiflora. Si no existe la crea.
- *
+ *
* @param vLanded Fecha de llegada al almacén
* @param vWarehouseFk Identificador de vn.warehouse
*/
@@ -41988,51 +41992,51 @@ BEGIN
DECLARE vTravelFk INT;
DECLARE vEntryFk INT;
DECLARE previousEntryFk INT;
-
+
SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk);
-
+
IF vLanded THEN
-
- SELECT IFNULL(MAX(id),0) INTO vEntryFk
+
+ SELECT IFNULL(MAX(id),0) INTO vEntryFk
FROM vn.entry
- WHERE travelFk = vTravelFk
+ WHERE travelFk = vTravelFk
AND isRaid;
IF NOT vEntryFk THEN
-
+
INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid)
SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE
FROM vn.supplier s
JOIN vn.company c ON c.code = 'VNL'
JOIN vn.currency cu ON cu.code = 'EUR'
WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN';
-
- SELECT MAX(id) INTO vEntryFk
+
+ SELECT MAX(id) INTO vEntryFk
FROM vn.entry
WHERE travelFk = vTravelFk;
-
- END IF;
-
- END IF;
- SELECT entryFk INTO previousEntryFk
+ END IF;
+
+ END IF;
+
+ SELECT entryFk INTO previousEntryFk
FROM edi.warehouseFloramondo wf
WHERE wf.warehouseFk = vWarehouseFk;
-
+
IF IFNULL(previousEntryFk,0) != vEntryFk THEN
-
- UPDATE buy b
- SET b.printedStickers = 0
+
+ UPDATE buy b
+ SET b.printedStickers = 0
WHERE entryFk = previousEntryFk;
DELETE FROM buy WHERE entryFk = previousEntryFk;
-
+
DELETE FROM entry WHERE id = previousEntryFk;
-
+
END IF;
-
+
RETURN vEntryFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -42094,17 +42098,17 @@ BEGIN
DECLARE vHasDistinctRoutes BOOL;
SELECT t.routeFk INTO vRouteFk
- FROM vn.expedition e
+ FROM vn.expedition e
JOIN vn.ticket t ON e.ticketFk = t.id
WHERE e.id = vExpeditionFk;
-
+
SELECT COUNT(*) > 0 INTO vHasDistinctRoutes
FROM vn.expeditionScan es
JOIN vn.expedition e ON es.expeditionFk = e.id
JOIN vn.ticket t ON e.ticketFk = t.id
WHERE es.palletFk = vPalletFk
AND t.routeFk <> vRouteFk;
-
+
RETURN vHasDistinctRoutes;
END ;;
@@ -42165,27 +42169,27 @@ BEGIN
DECLARE vDeliveryType INTEGER DEFAULT 0;
DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
DECLARE vCode VARCHAR(45);
-
+
SELECT am.deliveryMethodFk
- INTO vDeliveryType
+ INTO vDeliveryType
FROM ticket t
JOIN agencyMode am ON am.id = t.agencyModeFk
WHERE t.id = vTicket;
-
+
CASE vDeliveryType
WHEN 1 THEN -- AGENCIAS
SET vCode = 'DELIVERED';
-
+
WHEN 2 THEN -- REPARTO
SET vCode = 'ON_DELIVERY';
-
+
ELSE -- MERCADO, OTROS
SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp
- FROM ticket t
+ FROM ticket t
LEFT JOIN warehouse w
ON w.pickUpagencyModeFk = t.agencyModeFk
WHERE t.id = vTicket;
-
+
IF isWaitingForPickUp THEN
SET vCode = 'WAITING_FOR_PICKUP';
ELSE
@@ -42215,28 +42219,28 @@ BEGIN
DECLARE vDeliveryType INTEGER DEFAULT 0;
DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
DECLARE vCode VARCHAR(45);
-
- SELECT
+
+ SELECT
a.Vista
- INTO vDeliveryType
+ INTO vDeliveryType
FROM vn2008.Tickets t
JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
WHERE Id_Ticket = vTicket;
-
+
CASE vDeliveryType
WHEN 1 THEN -- AGENCIAS
SET vCode = 'DELIVERED';
-
+
WHEN 2 THEN -- REPARTO
SET vCode = 'ON_DELIVERY';
-
+
ELSE -- MERCADO, OTROS
SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp
- FROM vn2008.Tickets t
- LEFT JOIN vn2008.warehouse_pickup w
+ FROM vn2008.Tickets t
+ LEFT JOIN vn2008.warehouse_pickup w
ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id
WHERE t.Id_Ticket = vTicket;
-
+
IF isWaitingForPickUp THEN
SET vCode = 'WAITING_FOR_PICKUP';
ELSE
@@ -42344,16 +42348,16 @@ BEGIN
DECLARE vReturn DATE;
DECLARE vDuaDate DATE;
DECLARE vDuaDateDay INT;
-
+
SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate;
IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN
- SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate);
+ SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate);
ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN
- SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate);
+ SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate);
END IF;
- IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN
+ IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN
IF util.isLeapYear(YEAR(vDuaDate)) THEN
SET vPayDay = 29;
ELSE
@@ -42361,7 +42365,7 @@ BEGIN
END IF;
END IF;
- SELECT DAY(vDuaDate) INTO vDuaDateDay;
+ SELECT DAY(vDuaDate) INTO vDuaDateDay;
RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay)));
END ;;
DELIMITER ;
@@ -42383,11 +42387,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getShipmentHour`(vTicket INT) RETURN
READS SQL DATA
BEGIN
DECLARE vShipmentHour INT;
-
+
SELECT HOUR(shipped) INTO vShipmentHour
FROM ticket
WHERE id = vTicket;
-
+
IF vShipmentHour = 0
THEN
DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
@@ -42402,11 +42406,11 @@ BEGIN
JOIN agencyMode am on am.id = t.agencyModeFk
JOIN address a on a.id = t.addressFk
WHERE t.id = vTicket;
-
- SELECT Hora INTO vShipmentHour
+
+ SELECT Hora INTO vShipmentHour
FROM tmp.production_buffer;
END IF;
-
+
RETURN vShipmentHour;
END ;;
DELIMITER ;
@@ -42431,12 +42435,12 @@ BEGIN
SELECT rate3 INTO price
FROM vn.priceFixed
- WHERE itemFk = vItemFk
+ WHERE itemFk = vItemFk
AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1;
- SELECT `value` INTO price
+ SELECT `value` INTO price
FROM vn.specialPrice
- WHERE itemFk = vItemFk
+ WHERE itemFk = vItemFk
AND clientFk = vClientFk ;
RETURN price;
END ;;
@@ -42461,14 +42465,14 @@ BEGIN
/**
* Devuelve el ticket que debe de preparar el trabajador
*
- * @param vWorker Id del trabajador
+ * @param vWorker Id del trabajador
* @param vWarehouse Id del almacén
* @return Id del ticket
*
* #UPDATED PAK 2019/08/16
* #PENDING REVIEW
**/
-
+
DECLARE vToday DATETIME DEFAULT util.VN_CURDATE();
DECLARE vYesterday DATETIME;
DECLARE vTodayvMidniight DATETIME DEFAULT midnight(vToday);
@@ -42481,20 +42485,20 @@ BEGIN
WHERE code LIKE 'PREVIOUS_PREPARATION';
SET vYesterday = TIMESTAMPADD(DAY,-1,vToday);
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.workerComercial;
CREATE TEMPORARY TABLE tmp.workerComercial
ENGINE = MEMORY
- SELECT workerFk as worker FROM `grant` g
- JOIN grantGroup gg ON g.`groupFk` = gg.id
+ SELECT workerFk as worker FROM `grant` g
+ JOIN grantGroup gg ON g.`groupFk` = gg.id
WHERE gg.description = 'Comerciales';
-
- DELETE wc.*
+
+ DELETE wc.*
FROM tmp.workerComercial wc
JOIN `grant` g ON g.workerFk = wc.worker
- JOIN grantGroup gg ON g.`groupFk` = gg.id
- WHERE gg.description = 'Gerencia';
-
+ JOIN grantGroup gg ON g.`groupFk` = gg.id
+ WHERE gg.description = 'Gerencia';
+
DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
CREATE TEMPORARY TABLE tmp.production_buffer
ENGINE = MEMORY
@@ -42515,18 +42519,18 @@ BEGIN
LEFT JOIN vn.zone z ON z.id = t.zoneFk
WHERE t.shipped BETWEEN vYesterday AND vTodayvMidniight
AND t.warehouseFk = vWarehouse
- AND
+ AND
(
(tls.code = 'PRINTED' AND wc.worker IS NULL)
- OR
+ OR
(tls.code ='PICKER_DESIGNED' AND tls.worker = vWorker)
- OR
+ OR
(tls.code = 'PRINTED_BACK')
- OR
+ OR
(tls.code = 'PRINTED PREVIOUS')
);
-
-
+
+
SELECT ticket INTO vTicket
FROM tmp.production_buffer
ORDER BY (code = 'PICKER_DESIGNED') DESC, (code = 'PRINTED PREVIOUS') DESC ,Hora, Minuto, loadingOrder
@@ -42537,15 +42541,15 @@ BEGIN
FROM ticketTracking
WHERE ticketFk = vTicket
AND stateFk = PREVIOUS_PREPARATION;
-
- IF vHasBeenPreviouslyPrepared AND ticketWarehouseGet(vTicket) = 1 THEN
-
+
+ IF vHasBeenPreviouslyPrepared AND ticketWarehouseGet(vTicket) = 1 THEN
+
INSERT IGNORE INTO vn.ticketDown(ticketFk) VALUES(vTicket);
-
+
END IF;
-- END IF;
-
+
RETURN vTicket;
END ;;
@@ -42569,7 +42573,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getTicketTrolleyLabelCount`(vTicket
BEGIN
DECLARE vLabelCount INT DEFAULT 0;
- SELECT labelCount INTO vLabelCount
+ SELECT labelCount INTO vLabelCount
FROM ticketTrolley
WHERE ticket = vTicket;
@@ -42673,7 +42677,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasAnyNegativeBase`() RETURNS tinyint(1)
DETERMINISTIC
-BEGIN
+BEGIN
/* Calcula si existe alguna base imponible negativa
* Requiere la tabla temporal vn.ticketToInvoice(id)
@@ -42681,14 +42685,14 @@ BEGIN
* returns BOOLEAN
*/
DECLARE hasAnyNegativeBase BOOLEAN;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
CREATE TEMPORARY TABLE tmp.ticket
(KEY (ticketFk))
ENGINE = MEMORY
SELECT id ticketFk
FROM ticketToInvoice;
-
+
CALL ticket_getTax(NULL);
SELECT COUNT(*) INTO hasAnyNegativeBase
@@ -42701,9 +42705,9 @@ BEGIN
DROP TEMPORARY TABLE tmp.ticketTax;
DROP TEMPORARY TABLE tmp.ticket;
-
+
RETURN hasAnyNegativeBase;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -42725,17 +42729,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `hasItemsInSector`(vTicketFk INT, vSe
BEGIN
DECLARE vItemCount INT;
-
+
SELECT count(*) INTO vItemCount
- FROM vn.sale s
+ FROM vn.sale s
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
-
+
RETURN vItemCount;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -42758,7 +42762,7 @@ BEGIN
DECLARE vCountry INT;
DECLARE hasSomeNegativeBase BOOLEAN;
- SELECT s.countryFk
+ SELECT s.countryFk
INTO vCountry
FROM supplier s
JOIN ticket t ON t.companyFk = s.id
@@ -42767,9 +42771,9 @@ BEGIN
SELECT COUNT(*) INTO hasSomeNegativeBase
FROM (
SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase
- FROM sale s
+ FROM sale s
JOIN item i ON i.id = s.itemFk
- JOIN itemTaxCountry itc
+ JOIN itemTaxCountry itc
ON itc.itemFk = i.id AND itc.countryFk = vCountry
WHERE s.ticketFk = vTicket
GROUP BY itc.taxClassFk
@@ -42799,12 +42803,12 @@ BEGIN
DECLARE totalAmount DECIMAL(10,2);
SELECT SUM(vat) INTO totalAmount
- FROM (
+ FROM (
SELECT iot.vat
FROM invoiceOutTax iot
JOIN invoiceOut io ON io.id = iot.invoiceOutFk
WHERE io.ref = vInvoiceRef
- UNION ALL
+ UNION ALL
SELECT ioe.amount
FROM invoiceOutExpence ioe
JOIN invoiceOut io ON io.id = ioe.invoiceOutFk
@@ -42834,7 +42838,7 @@ BEGIN
DECLARE vIssued DATE;
DECLARE vSerial VARCHAR(15);
- SELECT issued, ref
+ SELECT issued, ref
INTO vIssued, vSerial
FROM invoiceOut WHERE id = vSelf;
@@ -42905,9 +42909,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceSerial`(vClientFk INT, vCompa
DETERMINISTIC
BEGIN
/**
- * Obtiene la serie de de una factura
+ * Obtiene la serie de de una factura
* dependiendo del area del cliente.
- *
+ *
* @param vClientFk Id del cliente
* @param vCompanyFk Id de la empresa
* @param vType Tipo de factura ["R", "M", "G"]
@@ -43006,7 +43010,7 @@ BEGIN
JOIN vn.entry e ON e.companyFk = co.id
WHERE e.id = vEntryFk
AND c.isUeeMember = TRUE;
-
+
IF vSupplierCountry != vClientCountry AND vSupplierCountry * vClientCountry > 0 THEN
SET isIntrastatOperation = TRUE;
END IF;
@@ -43031,18 +43035,18 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `isLogifloraDay`(vShipped DATE, vWarehouse INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
-
+
DECLARE vIsLogifloraDay BOOLEAN;
SELECT COUNT(*) INTO vIsLogifloraDay
FROM edi.warehouseFloramondo wf
- JOIN vn.floramondoConfig fc
+ JOIN vn.floramondoConfig fc
WHERE wf.warehouseFk = vWarehouse
AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded))
AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded));
-
+
RETURN vIsLogifloraDay;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -43079,7 +43083,7 @@ BEGIN
WHERE sl.scan_id = vScanId
AND t.Id_Ruta
) t1;
-
+
RETURN vDistinctRoutesInThePallet = 1;
END ;;
DELIMITER ;
@@ -43103,20 +43107,20 @@ BEGIN
DECLARE vPacking INTEGER DEFAULT 0;
DECLARE vItemFk INTEGER;
-
+
SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
-
- SELECT IFNULL(packing,0) INTO vPacking
- FROM vn.buy
+
+ SELECT IFNULL(packing,0) INTO vPacking
+ FROM vn.buy
WHERE id = CAST(vBarcode AS DECIMAL(18,0));
-
-
-
-
+
+
+
+
IF NOT vPacking THEN
CALL cache.last_buy_refresh(FALSE);
SELECT IFNULL(packing,1) INTO vPacking
- FROM
+ FROM
(SELECT packing , created
FROM vn.itemShelving
WHERE itemFk = vItemFk
@@ -43129,11 +43133,11 @@ BEGIN
) packings
ORDER BY created desc
LIMIT 1;
-
+
END IF;
-
+
RETURN vPacking;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -43158,11 +43162,11 @@ BEGIN
DECLARE vColumn INT;
DECLARE vClosestParkingFk INT;
DECLARE vSectorFk INT;
-
+
SELECT p.column, sectorFk INTO vColumn, vSectorFk
FROM vn.parking p
WHERE p.id = vParkingFk;
-
+
SELECT itemShelvingFk INTO vClosestParkingFk
FROM
(
@@ -43172,12 +43176,12 @@ BEGIN
JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk
WHERE p.sectorFk = vSectorFk
AND ipsl.saldo > 0
- ) sub
+ ) sub
ORDER BY distance
LIMIT 1;
-
+
RETURN vClosestParkingFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -43199,17 +43203,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `itemsInSector_get`(vTicketFk INT, vS
BEGIN
DECLARE vItemCount INT;
-
+
SELECT count(*) INTO vItemCount
- FROM vn.sale s
+ FROM vn.sale s
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
-
+
RETURN vItemCount;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -43282,29 +43286,29 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `item_getPackage`(vItemFk INT) RETURNS varchar(50) CHARSET utf8 COLLATE utf8_unicode_ci
DETERMINISTIC
BEGIN
-
+
DECLARE vDiameter INT;
DECLARE vPackageFk VARCHAR(50);
DECLARE vCoeficient DOUBLE DEFAULT 1.08;
-
+
SELECT MAX(LEFT(value,3)) INTO vDiameter
- FROM vn.itemTag it
+ FROM vn.itemTag it
JOIN vn.tag t ON t.id = it.tagFk
WHERE it.itemFk = vItemFk
AND t.overwrite = 'diameter';
-
+
SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2)))
INTO vPackageFk
FROM vn.volumeConfig vc;
-
+
INSERT IGNORE INTO vn.packaging(id, width, `depth`)
- SELECT vPackageFk,
- FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)),
+ SELECT vPackageFk,
+ FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)),
FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter))
FROM vn.volumeConfig vc;
-
+
RETURN vPackageFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -43341,7 +43345,7 @@ BEGIN
FROM packaging p
JOIN item i ON i.id = vSelf
WHERE p.id = vPackaging;
-
+
RETURN vVolume;
END ;;
@@ -43362,7 +43366,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `lastDayOfWeek`(vYear INT, vWeek INT) RETURNS date
DETERMINISTIC
-BEGIN
+BEGIN
/**
* Returns the date of the last day of the week
*
@@ -43401,16 +43405,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `machine_checkPlate`(vPlate VARCHAR(1
BEGIN
/**
* Comprueba si existe matrícula
- *
+ *
* @param vPlate matrícula del vehículo
* @return Devuelve TRUE en caso de que exista
- *
+ *
*/
-
+
IF (SELECT COUNT(*)
- FROM machine m
+ FROM machine m
WHERE m.plate = vPlate
- ) THEN
+ ) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
@@ -43437,9 +43441,9 @@ BEGIN
DECLARE result INT;
DECLARE vSenderFk INT;
- SELECT id INTO vSenderFk
+ SELECT id INTO vSenderFk
FROM account.user WHERE `name` = account.myUser_getName();
-
+
RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage));
END ;;
DELIMITER ;
@@ -43466,9 +43470,9 @@ BEGIN
DECLARE vSendDate DATETIME DEFAULT util.VN_NOW();
DECLARE vSender VARCHAR(255) CHARSET utf8;
- SELECT `name` INTO vSender
+ SELECT `name` INTO vSender
FROM account.user WHERE id = vSenderFK;
-
+
SET vRecipient = LOWER(vRecipient);
DROP TEMPORARY TABLE IF EXISTS tRecipients;
@@ -43489,7 +43493,7 @@ BEGIN
IF vCount = 0 THEN
RETURN vCount;
- END IF;
+ END IF;
SET vUuid = UUID();
@@ -43500,7 +43504,7 @@ BEGIN
message = vMessage,
sendDate = vSendDate;
- INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate)
+ INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate)
SELECT vUuid, vSender, vRecipient, finalRecipient, vMessage, vSendDate
FROM tRecipients;
@@ -43574,7 +43578,7 @@ BEGIN
-- Devuelte el volumen total de la orden sumada
DECLARE vWarehouseId INTEGER;
DECLARE vVolume DECIMAL(10,3);
-
+
SELECT IFNULL(SUM(o.amount * ic.cm3delivery)/1000000,0) INTO vVolume
FROM hedera.orderRow o
JOIN item i ON i.id = o.itemFk
@@ -43651,7 +43655,7 @@ BEGIN
WHERE cb.id = packagingReturnFk;
SET vValue = IF (vAmount IS NULL,
- IFNULL(base,0),
+ IFNULL(base,0),
vAmount / IFNULL(upload, 0) + IFNULL(base, 0));
ELSE
SET vValue = IFNULL(price, 0) + IFNULL(base, 0);
@@ -43678,7 +43682,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RET
DETERMINISTIC
BEGIN
DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci;
-SELECT
+SELECT
GROUP_CONCAT(i.id,
':',
ppa.denomination,
@@ -43767,20 +43771,20 @@ BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
-
+
DECLARE vLanded DATE;
DECLARE vZoneFk INT;
DECLARE vSignificativeFriendship INT DEFAULT 6;
DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10;
-
+
SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded
- FROM vn.ticket
+ FROM vn.ticket
WHERE id = vTicketFk;
-
+
-- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona
DROP TEMPORARY TABLE IF EXISTS tmp.route;
CREATE TEMPORARY TABLE tmp.route
- SELECT r.id routeFk,
+ SELECT r.id routeFk,
zf.friendship zoneFriendship
FROM vn.route r
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
@@ -43788,16 +43792,16 @@ BEGIN
AND zf.zoneFk = vZoneFk
AND r.created = vLanded
ORDER BY friendship;
-
+
-- Se eliminan aquellas que superan el volumen máximo
DELETE r.*
- FROM tmp.route r
+ FROM tmp.route r
JOIN (SELECT routeFk, sum(volume) volume
FROM vn.saleVolume
WHERE landed = vLanded
GROUP BY routeFk) sub ON sub.routeFk = r.routeFk
WHERE sub.volume > vVolumeMax;
-
+
-- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta
SELECT routeFk INTO vRouteFk
FROM
@@ -43809,7 +43813,7 @@ BEGIN
ORDER BY zoneFriendship DESC, friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -43834,9 +43838,9 @@ BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
DECLARE vShipped DATETIME;
-
+
SELECT addressFk, date(shipped) INTO vAddressFk, vShipped
- FROM vn.ticket
+ FROM vn.ticket
WHERE id = vTicketFk;
SELECT routeFk INTO vRouteFk
@@ -43850,7 +43854,7 @@ BEGIN
ORDER BY friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -43874,20 +43878,20 @@ BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
-
+
DECLARE vLanded DATE;
DECLARE vZoneFk INT;
DECLARE vSignificativeFriendship INT DEFAULT 6;
DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10;
-
+
SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded
- FROM vn.ticket
+ FROM vn.ticket
WHERE id = vTicketFk;
-
+
-- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona
DROP TEMPORARY TABLE IF EXISTS tmp.route;
CREATE TEMPORARY TABLE tmp.route
- SELECT r.id routeFk,
+ SELECT r.id routeFk,
zf.friendship zoneFriendship
FROM vn.route r
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
@@ -43895,16 +43899,16 @@ BEGIN
AND zf.zoneFk = vZoneFk
AND r.created = vLanded
ORDER BY friendship;
-
+
-- Se eliminan aquellas que superan el volumen máximo
DELETE r.*
- FROM tmp.route r
+ FROM tmp.route r
JOIN (SELECT routeFk, sum(volume) volume
FROM vn.saleVolume
WHERE landed = vLanded
GROUP BY routeFk) sub ON sub.routeFk = r.routeFk
WHERE sub.volume > vVolumeMax;
-
+
-- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta
SELECT routeFk INTO vRouteFk
FROM
@@ -43916,7 +43920,7 @@ BEGIN
ORDER BY zoneFriendship DESC, friendshipSum DESC
) sub
LIMIT 1;
-
+
RETURN vRouteFk;
END ;;
DELIMITER ;
@@ -43937,26 +43941,26 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
-
+
DECLARE vIsForbbiden BOOL;
DECLARE vLeft INT;
SELECT zg.lft INTO vLeft
- FROM vn.address a
- JOIN vn.zoneGeo zg ON zg.name = a.postalCode
+ FROM vn.address a
+ JOIN vn.zoneGeo zg ON zg.name = a.postalCode
WHERE a.id = vAddressFk;
-
+
SELECT sgi.isForbidden INTO vIsForbbiden
- FROM vn.specieGeoInvasive sgi
- JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk
+ FROM vn.specieGeoInvasive sgi
+ JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk
JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk)
WHERE vLeft BETWEEN zg.lft AND zg.rgt
AND ib.itemFk = vItemFk
- ORDER BY zg.`depth` DESC
+ ORDER BY zg.`depth` DESC
LIMIT 1;
RETURN IFNULL(vIsForbbiden, FALSE);
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -43976,7 +43980,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `testCIF`(vCIF VARCHAR(9)) RETURNS varchar(10) CHARSET utf8 COLLATE utf8_unicode_ci
DETERMINISTIC
BEGIN
-
+
DECLARE vLetraInicial VARCHAR(1);
DECLARE vLetraFinal VARCHAR(1);
DECLARE vParteNumerica VARCHAR(7);
@@ -43988,60 +43992,60 @@ BEGIN
SET vLetraInicial = SUBSTR(vCIF, 1, 1);
SET vLetraFinal = SUBSTR(vCIF, 9, 1);
SET vParteNumerica = SUBSTR(vCIF, 2, 7);
-
- WHILE i < 7 DO
-
+
+ WHILE i < 7 DO
+
SET i = i + 1;
-
+
SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0));
-
+
IF i MOD 2 THEN
-
+
SET vNumero = vNumero * 2;
SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10);
-
+
END IF;
-
+
SET vSuma = vSuma + vNumero;
-
+
END WHILE;
-
+
SET vSuma = vSuma MOD 10;
-
+
IF vSuma > 0 THEN
-
+
SET vSuma = 10 - vSuma;
-
+
END IF;
-
+
-- Comprobación de dígito de control
IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN
-
+
SET vResult = TRUE;
-
+
END IF;
-
+
IF vSuma = 0 THEN
-
+
SET vSuma = 10;
-
+
END IF;
-
+
IF CHAR(64 + vSuma) = vLetraFinal THEN
-
+
SET vResult = TRUE;
-
+
END IF;
-
+
-- Sólo se aceptan letras como caracter inicial
IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W
-
+
SET vResult = FALSE;
-
+
END IF;
-
+
RETURN vResult;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44061,7 +44065,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
-
+
DECLARE vIndice INT;
DECLARE vNumero VARCHAR(7);
DECLARE vOperador VARCHAR(9);
@@ -44070,45 +44074,45 @@ BEGIN
DECLARE vLetraFinal VARCHAR(1);
DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE";
DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE;
-
+
SET vLetraInicial = SUBSTR(vNIE, 1, 1);
SET vLetraFinal = SUBSTR(vNIE, 9, 1);
SET vNumero = SUBSTR(vNIE, 2, 7);
CASE vLetraInicial
-
+
WHEN 'X' THEN
-
+
SET vOperador = "0";
-
+
WHEN 'Y' THEN
-
+
SET vOperador = "1";
-
+
WHEN 'Z' THEN
-
+
SET vOperador = "2";
-
+
ELSE
-
+
SET vLetraInicialEsIncorrecta = TRUE;
-
+
END CASE;
-
+
SET vOperador = CONCAT(vOperador, vNumero);
SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0));
SET vIndice = Round(vParteNumerica Mod 23, 0) + 1;
IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN
-
+
RETURN TRUE;
-
+
ELSE
-
+
RETURN FALSE;
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44133,23 +44137,23 @@ BEGIN
DECLARE vParteNumerica DECIMAL(8,0);
DECLARE vLetra VARCHAR(1);
DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE";
-
+
SET vLetra = SUBSTRING(vNIF, 9, 1);
-
+
SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0));
-
+
SET vIndice = Round(vParteNumerica MOD 23, 0) + 1;
-
+
If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then
-
+
RETURN TRUE;
-
+
ELSE
-
+
RETURN FALSE;
-
+
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44169,21 +44173,21 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketCollection_getNoPacked`(vCollectionFk INT) RETURNS varchar(100) CHARSET utf8 COLLATE utf8_unicode_ci
DETERMINISTIC
BEGIN
-
+
/*
* return message with tickets and collection if there is tickets of a collection without expeditions
- *
+ *
* @param vCollectionFk the collection to check
* @return an array with collection and tickets without expeditions
- *
+ *
*/
-
+
DECLARE vAnswer VARCHAR(100) DEFAULT '';
IF collection_isPacked(vCollectionFk) = FALSE THEN
SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer
FROM vn.ticketCollection tc
- LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk
+ LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk
WHERE tc.collectionFk = vCollectionFk
AND ISNULL(e.id);
END IF;
@@ -44229,9 +44233,9 @@ BEGIN
DROP TEMPORARY TABLE
tmp.ticket,
tmp.ticketTotal;
-
+
RETURN vTotal;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44251,7 +44255,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8
DETERMINISTIC
BEGIN
-
+
DECLARE vRestTicketsMaxOrder INT;
DECLARE vRestTicketsMinOrder INT;
DECLARE vRestTicketsPacking INT;
@@ -44263,7 +44267,7 @@ BEGIN
DECLARE vExpeditionsCount INT;
DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE;
-SELECT `order`
+SELECT `order`
INTO PACKING_ORDER
FROM state
WHERE code = 'PACKING';
@@ -44274,7 +44278,7 @@ SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0)
LEFT JOIN ticketState ts on ts.ticket = t.id
WHERE t.id = vTicketId;
-SELECT (ag.`name` = 'VN_VALENCIA')
+SELECT (ag.`name` = 'VN_VALENCIA')
INTO vIsValenciaPath
FROM vn2008.Rutas r
JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia
@@ -44288,7 +44292,7 @@ IF vIsValenciaPath THEN -- Rutas Valencia
FROM expedition e
JOIN ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vMyPath;
-
+
SELECT MAX(ts.productionOrder), MIN(ts.productionOrder)
INTO vRestTicketsMaxOrder, vRestTicketsMinOrder
FROM ticket t
@@ -44297,7 +44301,7 @@ IF vIsValenciaPath THEN -- Rutas Valencia
AND t.warehouseFk = vMyWarehouse
AND t.id != vTicketid;
- SELECT COUNT(*)
+ SELECT COUNT(*)
INTO vRestTicketsPacking
FROM ticket t
LEFT JOIN ticketState ts on t.id = ts.ticket
@@ -44352,9 +44356,9 @@ BEGIN
LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id
WHERE ticketFk = vTicketFk
) sub;
-
+
RETURN IFNULL(vSplitCounter,'--');
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44403,21 +44407,21 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticketTotalVolumeBoxes`(vTicketId IN
DETERMINISTIC
BEGIN
-/*
+/*
* Devuelve el volumen estimado del ticket sumado, en cajas
*
* vTicketId Numero de ticket
- *
+ *
*/
DECLARE vVolumeBoxM3 DOUBLE;
DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1);
DECLARE vVnBoxId VARCHAR(10) DEFAULT '94';
-
+
SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId;
-
+
SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3;
-
+
RETURN vTicketTotalVolumeBoxes;
END ;;
@@ -44442,7 +44446,7 @@ BEGIN
DECLARE vWarehouseFk INT;
SELECT warehouseFk INTO vWarehouseFk
- FROM ticket
+ FROM ticket
WHERE id = vTicketFk;
RETURN vWarehouseFk;
@@ -44465,18 +44469,18 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_CC_volume`(vTicketFk INT) RETURNS decimal(10,1)
READS SQL DATA
BEGIN
-
+
DECLARE vCC DECIMAL(10,1);
SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000)
INTO vCC
- FROM vn.saleVolume sv
- JOIN vn.sale s ON s.id = sv.saleFk
- JOIN vn.item i ON i.id = s.itemFk
+ FROM vn.saleVolume sv
+ JOIN vn.sale s ON s.id = sv.saleFk
+ JOIN vn.item i ON i.id = s.itemFk
JOIN vn.packaging p ON p.id = 'CC'
- JOIN vn.volumeConfig vc
+ JOIN vn.volumeConfig vc
WHERE sv.ticketFk = vTicketFk;
-
+
RETURN vCC;
END ;;
@@ -44498,44 +44502,44 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11)
READS SQL DATA
proc:BEGIN
-
+
/* Devuelve el número de ticket o collection consultando en varias tablas posibles
- *
+ *
* @param vParamFk Número a validar
* @return vValidFk Identificador validado
*/
-
+
DECLARE vValidFk INT;
-- Tabla vn.saleGroup
SELECT s.ticketFk INTO vValidFk
FROM vn.sale s
JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
- JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
+ JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
WHERE sg.id = vParamFk
AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE())
LIMIT 1;
-
+
IF vValidFk THEN
-
+
RETURN vValidFk;
-
+
LEAVE proc;
-
+
END IF;
-- Tabla vn.collection
SELECT c.id INTO vValidFk
- FROM vn.collection c
+ FROM vn.collection c
WHERE c.id = vParamFk
AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
-
+
IF vValidFk THEN
-
+
RETURN vValidFk;
-
+
LEAVE proc;
-
+
END IF;
-- Tabla vn.ticket
@@ -44543,17 +44547,17 @@ proc:BEGIN
FROM vn.ticket t
WHERE t.id = vParamFk
AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
-
+
IF vValidFk THEN
-
+
RETURN vValidFk;
-
+
LEAVE proc;
-
+
END IF;
RETURN NULL;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -44579,8 +44583,8 @@ BEGIN
* @vTicketFk Id del ticket a calcular
*/
DECLARE deliveryPrice DECIMAL (10,2);
-
- IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id
+
+ IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id
WHERE t.id = vTicketFk) THEN
SELECT SUM(sv.freight) INTO deliveryPrice
FROM vn.saleVolume sv
@@ -44591,7 +44595,7 @@ BEGIN
LEFT JOIN expedition e ON e.ticketFk = t.id
JOIN expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
WHERE t.id = vTicketFk;
-
+
END IF;
RETURN deliveryPrice;
END ;;
@@ -44615,16 +44619,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getWeight`(vTicketFk INT) RET
BEGIN
/**
* Devuelve el peso total del ticket
- *
+ *
* @return Total peso
*/
-
+
DECLARE vWeight DECIMAL(10,3);
SELECT sum(weight) INTO vWeight
FROM saleVolume
WHERE ticketFk = vTicketFk;
-
+
RETURN vWeight;
END ;;
@@ -44655,10 +44659,10 @@ BEGIN
* @param vAddressFk Consignatario
* @param vCompanyFk Empresa
* @param vAgencyModeFk agencia
- */
-
+ */
+
DECLARE vTicket INT;
-
+
SELECT t.id INTO vTicket
FROM vn.ticket t
WHERE (t.clientFk <=> vClientFk OR vClientFk IS NULL)
@@ -44668,7 +44672,7 @@ BEGIN
AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL)
AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL)
LIMIT 1;
-
+
IF vTicket IS NULL THEN
CALL vn.ticket_add(
vClientFk,
@@ -44684,7 +44688,7 @@ BEGIN
vTicket
);
END IF;
-
+
RETURN vTicket;
END ;;
DELIMITER ;
@@ -44705,15 +44709,15 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_HasUbication`(vTicketFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
-
+
DECLARE hasUbication BOOL;
SELECT COUNT(*) INTO hasUbication
FROM vn.ticket t
JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
- WHERE rm.beachFk
+ WHERE rm.beachFk
AND t.id = vTicketFk;
-
+
RETURN hasUbication;
END ;;
@@ -44745,9 +44749,9 @@ BEGIN
SELECT TIMEDIFF(util.VN_CURTIME(), zc.hour + INTERVAL tc.packingDelay HOUR) > 0 INTO vIsTicketInTime
FROM vn.ticket t
- JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk
+ JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk
LEFT JOIN vn.ticketConfig tc ON TRUE
- WHERE t.id = vSelf
+ WHERE t.id = vSelf
AND zc.dated = util.VN_CURDATE();
RETURN vIsTicketInTime;
@@ -44863,7 +44867,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `timeWorkerControl_getDirection`(vUse
READS SQL DATA
BEGIN
/**
- * Verifica la dirección de la fichada
+ * Verifica la dirección de la fichada
* @param vUserFk Identificador del trabajador
* @param vTimed Hora de la fichada
* @return Retorna sentido de la fichada 'in, out, middle'
@@ -44876,40 +44880,40 @@ BEGIN
DECLARE vDayStayMax INT;
DECLARE vTimedSeconds INT;
DECLARE vLastTimeIn INT;
-
+
SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds;
-
+
SELECT dayStayMax INTO vDayStayMax
FROM vn.workerTimeControlParams;
SELECT timed, direction INTO vNext,vNextDirection
- FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
AND direction IN ('in','out')
AND timed > vTimed
ORDER BY timed ASC
LIMIT 1;
-
+
SELECT timed, direction INTO vPrevious, vPreviousDirection
- FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
AND direction IN ('in','out')
AND timed < vTimed
ORDER BY timed DESC
- LIMIT 1;
-
- IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN
+ LIMIT 1;
+
+ IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN
RETURN 'middle';
END IF;
-
-
+
+
IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN
- IF vPreviousDirection = 'in' THEN
+ IF vPreviousDirection = 'in' THEN
RETURN 'out';
ELSE
SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn
- FROM vn.workerTimeControl
- WHERE userFk = vUserFk
+ FROM vn.workerTimeControl
+ WHERE userFk = vUserFk
AND direction ='in'
AND timed < vPrevious;
IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN
@@ -44963,11 +44967,11 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
-
+
/**
* Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén.
* Si no existe lo genera.
- *
+ *
* @param vLanded Fecha de llegada al almacén
* @param vWarehouseFk Identificador de vn.warehouse
*/
@@ -44975,8 +44979,8 @@ BEGIN
DECLARE vTravelFk INT;
IF vLanded THEN
-
- SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
+
+ SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
FROM vn.travel tr
JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
@@ -44987,14 +44991,14 @@ BEGIN
AND landed = vLanded;
IF NOT vTravelFk THEN
-
+
INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
- SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id
- FROM vn.warehouse wOut
+ SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id
+ FROM vn.warehouse wOut
JOIN vn.agencyMode am ON am.name = 'LOGIFLORA'
WHERE wOut.name = 'Holanda';
-
- SELECT MAX(tr.id) INTO vTravelFk
+
+ SELECT MAX(tr.id) INTO vTravelFk
FROM vn.travel tr
JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
@@ -45002,11 +45006,11 @@ BEGIN
AND wOut.name = 'Holanda'
AND landed = vLanded;
END IF;
-
+
END IF;
-
+
RETURN vTravelFk;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45033,21 +45037,21 @@ BEGIN
DECLARE vChar INT;
SET vLength = length(vString);
-
+
WHILE vLength > 0 DO
-
+
SET vChar = MID(vString,vLength,1);
-
+
SET vSeed = vSeed + ASCII(vChar);
-
+
SET vLength = vLength - 1;
-
+
END WHILE;
SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000;
RETURN vCode;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45074,21 +45078,21 @@ BEGIN
DECLARE vChar INT;
SET vLength = length(vString);
-
+
WHILE vLength > 0 DO
-
+
SET vChar = MID(vString,vLength,1);
-
+
SET vSeed = vSeed + ASCII(vChar);
-
+
SET vLength = vLength - 1;
-
+
END WHILE;
SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000;
RETURN vCode;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45169,16 +45173,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `workerMachinery_isRegistered`(vWorke
BEGIN
/**
* Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo)
- *
+ *
* @param vWorkerFk id del trabajador
* @return Devuelve TRUE/FALSE en caso de que haya o no registros
*/
-
- IF (SELECT COUNT(*)
+
+ IF (SELECT COUNT(*)
FROM machineWorker m
WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), util.VN_NOW()) AND ISNULL(m.outTimed))
- THEN
+ AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), util.VN_NOW()) AND ISNULL(m.outTimed))
+ THEN
RETURN TRUE;
ELSE
RETURN FALSE;
@@ -45210,15 +45214,15 @@ BEGIN
* @param vTimeOut
* @return vNigthlyHours
*/
- DECLARE vNigthlyHours DECIMAL(5,2);
+ DECLARE vNigthlyHours DECIMAL(5,2);
DECLARE vSecondsPerHour INT(4) DEFAULT 3600;
-
+
SELECT GREATEST(0, TIMESTAMPDIFF(SECOND,
- IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours,
- CONCAT(DATE(vTimeIn), ' ', startNightlyHours),
+ IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours,
+ CONCAT(DATE(vTimeIn), ' ', startNightlyHours),
vTimeIn),
- IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours,
- CONCAT(DATE(vTimeOut), ' ', endNightlyHours),
+ IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours,
+ CONCAT(DATE(vTimeOut), ' ', endNightlyHours),
vTimeOut))) / vSecondsPerHour INTO vNigthlyHours
FROM vn.workerTimeControlConfig;
@@ -45250,47 +45254,47 @@ BEGIN
SELECT dayStayMax INTO vDayStayMax
FROM workerTimeControlParams;
-
+
SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection;
IF vDirection = 'out' THEN
-
+
SELECT MAX(timed) INTO vLastIn
- FROM workerTimeControl
- WHERE userFk = vUserFk
+ FROM workerTimeControl
+ WHERE userFk = vUserFk
AND direction = 'in'
AND timed < vTimed;
-
+
UPDATE workerTimeControl wtc
SET wtc.direction = 'middle'
WHERE userFk = vUserFk
AND direction = 'out'
AND timed BETWEEN vLastIn AND vTimed;
-
+
ELSE IF vDirection = 'in' THEN
-
- SELECT COUNT(*) INTO vHasDirectionOut
+
+ SELECT COUNT(*) INTO vHasDirectionOut
FROM workerTimeControl wtc
- WHERE userFk = vUserFk
+ WHERE userFk = vUserFk
AND direction = 'out'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
+ AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
UPDATE workerTimeControl wtc
SET wtc.direction = IF (vHasDirectionOut,'middle','out')
WHERE userFk = vUserFk
AND direction = 'in'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
+ AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
END IF;
END IF;
-
+
INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual)
VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual);
-
+
SET vLastInsertedId = LAST_INSERT_ID();
-
+
CALL workerTimeControlSOWP(vUserFk, vTimed);
-
+
RETURN vLastInsertedId;
END ;;
DELIMITER ;
@@ -45319,47 +45323,47 @@ BEGIN
SELECT dayStayMax INTO vDayStayMax
FROM workerTimeControlParams;
-
+
SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection;
IF vDirection = 'out' THEN
-
+
SELECT MAX(timed) INTO vLastIn
- FROM workerTimeControl
- WHERE userFk = vUserFk
+ FROM workerTimeControl
+ WHERE userFk = vUserFk
AND direction = 'in'
AND timed < vTimed;
-
+
UPDATE workerTimeControl wtc
SET wtc.direction = 'middle'
WHERE userFk = vUserFk
AND direction = 'out'
AND timed BETWEEN vLastIn AND vTimed;
-
+
ELSE IF vDirection = 'in' THEN
-
- SELECT COUNT(*) INTO vHasDirectionOut
+
+ SELECT COUNT(*) INTO vHasDirectionOut
FROM workerTimeControl wtc
- WHERE userFk = vUserFk
+ WHERE userFk = vUserFk
AND direction = 'out'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
+ AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
UPDATE workerTimeControl wtc
SET wtc.direction = IF (vHasDirectionOut,'middle','out')
WHERE userFk = vUserFk
AND direction = 'in'
- AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
+ AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);
END IF;
END IF;
-
+
INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual)
VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual);
-
+
SET vLastInsertedId = LAST_INSERT_ID();
-
+
CALL workerTimeControlSOWP(vUserFk, vTimed);
-
+
RETURN vLastInsertedId;
END ;;
DELIMITER ;
@@ -45385,17 +45389,17 @@ BEGIN
* @return Devuelve TRUE en caso de que este trabajando. Si se encuentra en un descanso devolverá FALSE
*/
DECLARE vLastIn DATETIME ;
-
+
SELECT MAX(timed) INTO vLastIn
- FROM vn.workerTimeControl
+ FROM vn.workerTimeControl
WHERE userFk = vWorkerFk AND
direction = 'in';
- IF (SELECT MOD(COUNT(*),2)
- FROM vn.workerTimeControl
- WHERE userFk = vWorkerFk AND
+ IF (SELECT MOD(COUNT(*),2)
+ FROM vn.workerTimeControl
+ WHERE userFk = vWorkerFk AND
timed >= vLastIn
- ) THEN
+ ) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
@@ -45490,7 +45494,7 @@ BEGIN
SET `type` = vType,
`name` = vName,
parentFk = vParentFk;
-
+
SET vSelf = LAST_INSERT_ID();
UPDATE zoneGeoRecalc SET isChanged = TRUE;
@@ -45514,7 +45518,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `addNoteFromDelivery`(idTicket INT,nota TEXT)
BEGIN
-
+
DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/
INSERT INTO ticketObservation(ticketFk,observationTypeFk,description)
@@ -45542,24 +45546,24 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `addressTaxArea`()
READS SQL DATA
BEGIN
/**
- * Devuelve el taxArea para un conjunto de Consignatarios y empresas,
+ * Devuelve el taxArea para un conjunto de Consignatarios y empresas,
*
* @table tmp.addressCompany(addressFk, companyFk) valores a calcular
* @return tmp.addressTaxArea(addressFk,companyFk)
*/
DECLARE vSpainCountryCode INT DEFAULT 1;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
CREATE TEMPORARY TABLE tmp.addressTaxArea
(PRIMARY KEY (addressFk, companyFk))
ENGINE = MEMORY
- SELECT CASE
- WHEN (NOT cClient.isUeeMember OR NOT cSupplier.isUeeMember) AND s.countryFk != c.countryFk THEN
+ SELECT CASE
+ WHEN (NOT cClient.isUeeMember OR NOT cSupplier.isUeeMember) AND s.countryFk != c.countryFk THEN
'WORLD'
- WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN
+ WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN
'CEE'
- WHEN a.isEqualizated AND c.countryFk = vSpainCountryCode THEN
+ WHEN a.isEqualizated AND c.countryFk = vSpainCountryCode THEN
'EQU'
ELSE
'NATIONAL'
@@ -45596,27 +45600,27 @@ BEGIN
* @param vAddress id de la direccion
* @param vWarehouse id del warehouse
* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida
-*/
+*/
DECLARE vAgency INT;
DECLARE vShipped DATE;
DECLARE vLanded DATE DEFAULT util.VN_CURDATE();
SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode;
l: LOOP
-
+
CALL agencyHourGetShipped(vLanded,vAddress,vAgency);
- SELECT shipped INTO vShipped
+ SELECT shipped INTO vShipped
FROM tmp.agencyHourGetShipped
WHERE warehouseFk = vWarehouse LIMIT 1;
-
+
IF vShipped THEN
LEAVE l;
END IF;
-
+
SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY);
-
+
END LOOP;
-
+
SELECT vShipped,vLanded;
END ;;
DELIMITER ;
@@ -45667,7 +45671,7 @@ BEGIN
LIMIT 1
) t
WHERE IF(vDated = util.VN_CURDATE(), t.maxHour > HOUR(util.VN_NOW()), TRUE) AND t.substractDay < 225;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45690,14 +45694,14 @@ BEGIN
* DEPRECATED usar zoneGetWarehouse
* Devuelve el listado de agencias disponibles para la fecha,
* dirección y warehouuse pasadas
- *
+ *
* @param vAddress no puede ser NULL
* @param vWarehouse warehouse donde comprobaremos las agencias y fecha
* @param vDate Fecha de recogida
* @table agencyModeWarehouseList Listado de agencias disponibles
*/
DECLARE vAgency INT;
- DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vCur CURSOR FOR
SELECT DISTINCT a.id
FROM agency a
@@ -45721,13 +45725,13 @@ BEGIN
PRIMARY KEY(id)
)
ENGINE = MEMORY;
-
+
OPEN vCur;
FETCH vCur INTO vAgency;
WHILE NOT vDone
DO
-
+
INSERT INTO tmp.agencyModeWarehouseList
SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name
FROM agencyHour ah
@@ -45756,7 +45760,7 @@ BEGIN
END WHILE;
CLOSE vCur;
-
+
SELECT * FROM tmp.agencyModeWarehouseList;
DROP TEMPORARY TABLE tmp.agencyModeWarehouseList;
END ;;
@@ -45782,9 +45786,9 @@ BEGIN
CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency);
SELECT * FROM tmp.agencyHourGetShipped;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -45822,7 +45826,7 @@ BEGIN
DECLARE cWarehouses CURSOR FOR
SELECT warehouseFk, shipped FROM tmp.zoneGetShipped;
-
+
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
@@ -45831,7 +45835,7 @@ BEGIN
CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE);
DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc;
- CREATE TEMPORARY TABLE tmp.availableCalc(
+ CREATE TEMPORARY TABLE tmp.availableCalc(
calcFk INT UNSIGNED,
PRIMARY KEY (calcFk)
)
@@ -45842,7 +45846,7 @@ BEGIN
l: LOOP
SET vDone = FALSE;
FETCH cWarehouses INTO vWarehouse, vShipment;
-
+
IF vDone THEN
LEAVE l;
END IF;
@@ -45875,7 +45879,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `bankEntity_checkBic`(vBic VARCHAR(2
BEGIN
/**
* If the bic length is Incorrect throw exception
- *
+ *
* @param vBic bic code
*/
@@ -45883,7 +45887,7 @@ BEGIN
SELECT bicLength INTO vConfigBicLenght
FROM vn.bankEntityConfig bec;
-
+
IF LENGTH(vBic) <> vConfigBicLenght THEN
CALL util.throw(CONCAT('bic must be of length ', vConfigBicLenght ));
END IF;
@@ -45910,14 +45914,14 @@ BEGIN
* Manda correo cuando caduca un seguro
* de los leasing
*
-*/
+*/
INSERT INTO mail (receiver,replyTo,subject,body)
SELECT 'administracion@verdnatura.es' receiver,
'noreply@verdnatura.es' replyTo,
CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') subject,
CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') body
- FROM vn.bankPolicy bp
- LEFT JOIN vn.supplier s
+ FROM vn.bankPolicy bp
+ LEFT JOIN vn.supplier s
ON s.id = bp.supplierFk
LEFT JOIN vn.bank b
ON b.id = bp.bankFk
@@ -46148,19 +46152,19 @@ BEGIN
DECLARE vIsFeedStock BOOL;
DECLARE vWeight DECIMAL(10,2);
DECLARE vPacking INT;
-
- SELECT b.entryFk,
- b.itemFk,
- i.packingOut,
- ic.merchandise,
+
+ SELECT b.entryFk,
+ b.itemFk,
+ i.packingOut,
+ ic.merchandise,
vc.standardFlowerBox,
b.weight,
- b.packing
- INTO
- vEntryFk,
- vItemFk,
- vPackingOut,
- vIsMerchandise,
+ b.packing
+ INTO
+ vEntryFk,
+ vItemFk,
+ vPackingOut,
+ vIsMerchandise,
vStandardFlowerBox,
vWeight,
vPacking
@@ -46168,7 +46172,7 @@ BEGIN
LEFT JOIN item i ON i.id = b.itemFk
LEFT JOIN itemType it ON it.id = i.typeFk
LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox
+ LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox
JOIN volumeConfig vc ON TRUE
WHERE b.id = vSelf;
@@ -46185,7 +46189,7 @@ BEGIN
warehouseFk = vWarehouse,
cm3 = buy_getUnitVolume(vSelf),
cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf));
-
+
IF vWeight AND vPacking THEN
UPDATE itemCost SET
grams = vWeight * 1000 / vPacking
@@ -46206,7 +46210,7 @@ BEGIN
WHERE b.id = vSelf;
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46254,7 +46258,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getSplit`(vSelf INT, vDated DAT
BEGIN
/**
* Devuelve las ventas de una compra
- *
+ *
* @param vSelf Identificador de vn.buy
*/
DECLARE vItemFk INT;
@@ -46350,11 +46354,11 @@ BEGIN
-- Devuelve los splits creados
SELECT CONCAT(sp.counter,'/',sp.labels) labels,
COALESCE(sfc.nickname, sfa.nickname, a.nickname) destination,
- s.itemFk,
- i.longName,
- i.`size`,
- vn.ticketSplitCounter(t.id) counter,
- IF(sfa.id OR sfc.id,
+ s.itemFk,
+ i.longName,
+ i.`size`,
+ vn.ticketSplitCounter(t.id) counter,
+ IF(sfa.id OR sfc.id,
a.nickname,
CONCAT(a.id, ' ', p.`name`,' (', c.`code`,')')) destination2
FROM tmp.split sp
@@ -46400,12 +46404,12 @@ BEGIN
item_getVolume(b.itemFk, b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros ,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
item_getVolume(b.itemFk, b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais
- FROM buy b
+ FROM buy b
JOIN tmp.buy tb ON tb.buyFk = b.id
JOIN volumeConfig vc
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
- LEFT JOIN temperature t ON t.code = it.temperatureFk
+ LEFT JOIN temperature t ON t.code = it.temperatureFk
GROUP BY Temp;
END ;;
DELIMITER ;
@@ -46425,21 +46429,21 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT)
BEGIN
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.buy;
CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
- INSERT INTO tmp.buy
+ INSERT INTO tmp.buy
SELECT b.id
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
WHERE t.landed = vDated
AND t.agencyModeFk IN (0, vAgencyFk);
CALL buy_getVolume();
DROP TEMPORARY TABLE tmp.buy;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46458,19 +46462,19 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByEntry`(vEntryFk INT)
BEGIN
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.buy;
CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
-
- INSERT INTO tmp.buy
+
+ INSERT INTO tmp.buy
SELECT b.id
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
WHERE e.id = vEntryFk;
CALL buy_getVolume();
DROP TEMPORARY TABLE tmp.buy;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46558,12 +46562,12 @@ BEGIN
* inserta en tmp.buyRecalc las compras de un awb
*
* @param awbFk
- */
+ */
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
SELECT b.id
- FROM buy b
+ FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN duaEntry de ON de.entryFk = e.id
JOIN dua d ON d.id = de.duaFk
@@ -46595,7 +46599,7 @@ BEGIN
* Recalcula los precios de una compra
*
* @param vBuyFk
- */
+ */
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
@@ -46626,12 +46630,12 @@ BEGIN
* Recalcula los precios de una entrada
*
* @param vEntryFk
- */
+ */
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
SELECT b.id
- FROM buy b
+ FROM buy b
WHERE b.entryFk = vEntryFk;
CALL buy_recalcPrices();
@@ -46671,12 +46675,12 @@ BEGIN
LIMIT 0;
INSERT INTO tBuy(buyFk)
- SELECT b.id
+ SELECT b.id
FROM buy b
JOIN tmp.ekt t ON t.ektFk = b.ektFk
JOIN vn.entry en ON en.id = b.entryFk
JOIN vn.travel tr ON tr.id = en.travelFk
- JOIN vn.warehouse w ON w.id = tr.warehouseInFk
+ JOIN vn.warehouse w ON w.id = tr.warehouseInFk
JOIN vn.country c ON c.id = w.countryFk AND c.code = 'NL';
SELECT b.id buy, i.doPhoto do_photo, b.stickers - b.printedStickers stickersToPrint
@@ -46713,14 +46717,14 @@ BEGIN
* @param vWarehouseFk Id del almacén
* @param vItemFk Id del Artículo
* @param vGrouping Cantidad de grouping
- */
-
+ */
+
CALL vn.buyUltimate(vWarehouseFk, util.VN_CURDATE());
UPDATE vn.buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
- SET b.`grouping` = vGrouping
- WHERE bu.warehouseFk = vWarehouseFk
+ SET b.`grouping` = vGrouping
+ WHERE bu.warehouseFk = vWarehouseFk
AND bu.itemFk = vItemFk;
DROP TEMPORARY TABLE tmp.buyUltimate;
@@ -46743,7 +46747,7 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updatePacking`(vWarehouseFk INT, vItemFk INT, vPacking INT)
BEGIN
/**
- * Actualiza packing
+ * Actualiza packing
*
* @param vWarehouseFk warehouse del item
* @param vItemFk id del item
@@ -46753,8 +46757,8 @@ BEGIN
UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
- SET b.packing = vPacking
- WHERE bu.warehouseFk = vWarehouseFk
+ SET b.packing = vPacking
+ WHERE bu.warehouseFk = vWarehouseFk
AND bu.itemFk = vItemFk;
DROP TEMPORARY TABLE tmp.buyUltimate;
@@ -46793,7 +46797,7 @@ BEGIN
*/
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT vItemFk itemFk;
CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
@@ -46815,7 +46819,7 @@ DELIMITER ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT)
-BEGIN
+BEGIN
/**
* Calcula los articulos disponibles y sus precios
*
@@ -46823,7 +46827,7 @@ BEGIN
* @param vLanded Fecha de recepcion de mercancia
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
- * @return tmp.ticketCalculateItem(itemFk, available, producer,
+ * @return tmp.ticketCalculateItem(itemFk, available, producer,
* item, size, stems, category, inkFk, image, origin, price)
* @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk)
* @return tmp.ticketComponent
@@ -46858,22 +46862,22 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
CREATE TEMPORARY TABLE tmp.ticketCalculateItem(
- itemFk INT(11) NOT NULL,
+ itemFk INT(11) NOT NULL,
available INT(11),
- producer VARCHAR(50),
- item VARCHAR(50),
- size INT(10) UNSIGNED,
- stems INT(11),
- category VARCHAR(3),
- inkFk VARCHAR(3),
+ producer VARCHAR(50),
+ item VARCHAR(50),
+ size INT(10) UNSIGNED,
+ stems INT(11),
+ category VARCHAR(3),
+ inkFk VARCHAR(3),
image VARCHAR(50),
- origin VARCHAR(3),
+ origin VARCHAR(3),
price DECIMAL(10,2),
priceKg DECIMAL(10,2),
`grouping` INT(10) UNSIGNED,
PRIMARY KEY `itemFk` (`itemFk`)
) ENGINE = MEMORY DEFAULT CHARSET=utf8;
-
+
OPEN cTravelTree;
l: LOOP
@@ -46895,20 +46899,20 @@ BEGIN
bu.buyFk,
vZoneFk
FROM `cache`.available a
- LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
+ LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
AND anr.calc_id = vAvailableNoRaidsCalc
JOIN tmp.item i ON i.itemFk = a.item_id
JOIN vn.item it ON it.id = i.itemFk
JOIN vn.`zone` z ON z.id = vZoneFk
- LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
- LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
- LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
+ LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
+ LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed
FROM vn.addressFilter af
- JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
- FROM vn.address ad
- JOIN vn.province p ON p.id = ad.provinceFk
+ JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
+ FROM vn.address ad
+ JOIN vn.province p ON p.id = ad.provinceFk
WHERE ad.id = vAddressFk
) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk)
AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk)
@@ -46925,13 +46929,13 @@ BEGIN
JOIN vn.itemType itt ON itt.id = it.typeFk
JOIN vn.itemCategory itc on itc.id = itt.categoryFk
JOIN vn.address ad ON ad.id = vAddressFk
- LEFT JOIN vn.clientItemType cit
+ LEFT JOIN vn.clientItemType cit
ON cit.clientFk = ad.clientFk
AND cit.itemTypeFk = itt.id
- LEFT JOIN vn.zoneItemType zit
+ LEFT JOIN vn.zoneItemType zit
ON zit.zoneFk = vZoneFk
AND zit.itemTypeFk = itt.id
- LEFT JOIN vn.agencyModeItemType ait
+ LEFT JOIN vn.agencyModeItemType ait
ON ait.agencyModeFk = vAgencyModeFk
AND ait.itemTypeFk = itt.id
WHERE a.calc_id = vAvailableCalc
@@ -47024,7 +47028,7 @@ BEGIN
* Calcula los componentes de los articulos de tmp.ticketLot
*
* @param vZoneFk para calcular el transporte
- * @param vAddressFk Consignatario
+ * @param vAddressFk Consignatario
* @param vShipped dia de salida del pedido
* @param vWarehouseFk warehouse de salida del pedido
* @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk)
@@ -47038,7 +47042,7 @@ BEGIN
SELECT clientFk INTO vClientFK
FROM address
WHERE id = vAddressFk;
-
+
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate
(PRIMARY KEY (itemFk, warehouseFk))
ENGINE = MEMORY
@@ -47050,7 +47054,7 @@ BEGIN
IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing,
IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
- tl.buyFk,
+ tl.buyFk,
i.typeFk,
IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping
FROM tmp.ticketLot tl
@@ -47058,7 +47062,7 @@ BEGIN
JOIN item i ON i.id = tl.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN specialPrice sp ON sp.itemFk = i.id
+ LEFT JOIN specialPrice sp ON sp.itemFk = i.id
AND sp.clientFk = vClientFk
LEFT JOIN (
SELECT * FROM (
@@ -47077,7 +47081,7 @@ BEGIN
LIMIT 10000000000000000000
) tpf
GROUP BY tpf.itemFk, tpf.warehouseFk
- ) pf ON pf.itemFk = tl.itemFk
+ ) pf ON pf.itemFk = tl.itemFk
AND pf.warehouseFk = tl.warehouseFk
WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01
AND ic.merchandise
@@ -47109,10 +47113,10 @@ BEGIN
FROM tmp.ticketComponent tc
JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk
GROUP BY tc.itemFk, warehouseFk;
-
+
-- RECOBRO
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
- SELECT tcb.warehouseFk, tcb.itemFk, c2.id,
+ SELECT tcb.warehouseFk, tcb.itemFk, c2.id,
ROUND(tcb.base *
LEAST(
MAX(GREATEST(IFNULL(cr.priceIncreasing,0),
@@ -47143,29 +47147,29 @@ BEGIN
ROUND(base * (0.01 + wm.pricesModifierRate), 3) manaAuto
FROM tmp.ticketComponentBase tcb
JOIN `client` c on c.id = vClientFk
- JOIN workerMana wm ON c.salesPersonFk = wm.workerFk
+ JOIN workerMana wm ON c.salesPersonFk = wm.workerFk
JOIN vn.component c2 ON c2.code = 'autoMana'
WHERE wm.isPricesModifierActivated
HAVING manaAuto <> 0;
-
+
-- Precios especiales
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk,
tcb.itemFk,
c2.id,
GREATEST(
- IFNULL(ROUND(tcb.base * c2.tax, 4), 0),
+ IFNULL(ROUND(tcb.base * c2.tax, 4), 0),
IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3
) cost
FROM tmp.ticketComponentBase tcb
JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount'
- JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk
+ JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk
LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
JOIN vn.item i ON i.id = tcb.itemFk
WHERE sp.value IS NULL
AND i.supplyResponseFk IS NULL;
- -- Individual
+ -- Individual
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk,
tcb.itemFk,
@@ -47176,10 +47180,10 @@ BEGIN
JOIN vn.client c ON c.id = vClientFk
JOIN vn.businessType bt ON bt.code = c.businessTypeFk
WHERE bt.code = 'individual';
-
+
-- Venta por paquetes
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
- SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3
+ SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3
FROM tmp.ticketComponentCalculate tcc
JOIN vn.component c2 ON c2.code = 'salePerPackage'
JOIN buy b ON b.id = tcc.buyFk
@@ -47191,7 +47195,7 @@ BEGIN
SELECT vZoneFk id;
CALL zone_getOptionsForShipment(vShipped, TRUE);
-
+
-- Reparto
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFK,
@@ -47205,7 +47209,7 @@ BEGIN
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN vn.volumeConfig vc
JOIN vn.component c2 ON c2.code = 'delivery'
- LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk
+ LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk
AND ic.itemFk = tcc.itemFk
HAVING cost <> 0;
@@ -47258,9 +47262,9 @@ BEGIN
CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price,
CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg
FROM tmp.ticketComponentCalculate tcc
- JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
+ JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk
AND tcs.warehouseFk = tcc.warehouseFk
- WHERE IFNULL(tcs.classRate, 1) = 1
+ WHERE IFNULL(tcs.classRate, 1) = 1
AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
GROUP BY tcs.warehouseFk, tcs.itemFk;
@@ -47297,7 +47301,7 @@ BEGIN
SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000
) t
GROUP BY itemFk, warehouseFk, `grouping`;
-
+
DROP TEMPORARY TABLE
tmp.ticketComponentCalculate,
tmp.ticketComponentSum,
@@ -47322,7 +47326,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPrepare`()
BEGIN
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
CREATE TEMPORARY TABLE tmp.ticketComponent (
`warehouseFk` INT UNSIGNED NOT NULL,
@@ -47332,9 +47336,9 @@ BEGIN
INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)
)ENGINE=MEMORY DEFAULT CHARSET=utf8;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice;
- CREATE TEMPORARY TABLE tmp.ticketComponentPrice (
+ CREATE TEMPORARY TABLE tmp.ticketComponentPrice (
`warehouseFk` INT UNSIGNED NOT NULL,
`itemFk` INT NOT NULL,
`rate` INT NOT NULL,
@@ -47343,7 +47347,7 @@ BEGIN
`priceKg` DECIMAL(10,4),
INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC)
- )ENGINE=MEMORY DEFAULT CHARSET=utf8;
+ )ENGINE=MEMORY DEFAULT CHARSET=utf8;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47362,7 +47366,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPurge`()
BEGIN
- DROP TEMPORARY TABLE
+ DROP TEMPORARY TABLE
tmp.ticketComponentPrice,
tmp.ticketComponent,
tmp.ticketLot;
@@ -47386,12 +47390,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_test`()
proc: BEGIN
/**
* Calcula los articulos disponibles y sus precios
- *
+ *
* @table tmp.item(itemFk) Listado de artÃculos a calcular
* @param vLanded Fecha de recepcion de mercancia
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
- * @return tmp.ticketCalculateItem(itemFk, available, producer,
+ * @return tmp.ticketCalculateItem(itemFk, available, producer,
* item, size, stems, category, inkFk, image, origin, price)
* @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk)
* @return tmp.ticketComponent
@@ -47413,10 +47417,10 @@ proc: BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
- ENGINE = MEMORY
+ ENGINE = MEMORY
SELECT 10 itemFk;
-- Establece los almacenes y las fechas que van a entrar al disponible
-SELECT 1;
+SELECT 1;
CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE);
SELECT 2;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
@@ -47431,25 +47435,25 @@ SELECT 2;
KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
CALL catalog_componentPrepare();
-
+
SELECT 3;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
CREATE TEMPORARY TABLE tmp.ticketCalculateItem(
- itemFk INT(11) NOT NULL,
+ itemFk INT(11) NOT NULL,
available INT(11),
- producer VARCHAR(50),
- item VARCHAR(50),
- size INT(10) UNSIGNED,
- stems INT(11),
- category VARCHAR(3),
- inkFk VARCHAR(3),
+ producer VARCHAR(50),
+ item VARCHAR(50),
+ size INT(10) UNSIGNED,
+ stems INT(11),
+ category VARCHAR(3),
+ inkFk VARCHAR(3),
image VARCHAR(50),
- origin VARCHAR(3),
+ origin VARCHAR(3),
price DECIMAL(10,2),
priceKg DECIMAL(10,2),
PRIMARY KEY `itemFk` (`itemFk`)
) ENGINE = MEMORY DEFAULT CHARSET=utf8;
-
+
OPEN cTravelTree;
l: LOOP
@@ -47476,35 +47480,35 @@ SELECT 5;
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id
WHERE i.calc_id = vAvailableCalc
AND i.available > 0;
-
+
DROP TEMPORARY TABLE tmp.buyUltimate;
-
+
CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
SELECT 6;
INSERT INTO tmp.ticketCalculateItem (
- itemFk,
- available,
- producer,
- item,
- size,
- stems,
- category,
+ itemFk,
+ available,
+ producer,
+ item,
+ size,
+ stems,
+ category,
inkFk,
image,
origin,
price,
priceKg)
- SELECT
- tl.itemFk,
+ SELECT
+ tl.itemFk,
SUM(tl.available) available,
- p.name producer,
- i.name item,
- i.size size,
- i.stems,
- i.category,
- i.inkFk,
+ p.name producer,
+ i.name item,
+ i.size size,
+ i.stems,
+ i.category,
+ i.inkFk,
i.image,
- o.code origin,
+ o.code origin,
bl.price,
bl.priceKg
FROM tmp.ticketLot tl
@@ -47512,11 +47516,11 @@ SELECT 6;
LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
JOIN origin o ON o.id = i.originFk
JOIN (
- SELECT *
+ SELECT *
FROM (SELECT price, itemFk, priceKg
FROM tmp.ticketComponentPrice
WHERE warehouseFk = vWarehouseFk
- ORDER BY (rate = 2) DESC
+ ORDER BY (rate = 2) DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk
) bl ON bl.itemFk = tl.itemFk
@@ -47528,8 +47532,8 @@ SELECT 6;
CLOSE cTravelTree;
DROP TEMPORARY TABLE tmp.item;
-SELECT 7;
-
+SELECT 7;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47859,9 +47863,9 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientCreate`(
vFirstname VARCHAR(50),
- vSurnames VARCHAR(50),
- vFi VARCHAR(9),
- vAddress TEXT,
+ vSurnames VARCHAR(50),
+ vFi VARCHAR(9),
+ vAddress TEXT,
vPostcode CHAR(5),
vCity VARCHAR(25),
vProvinceFk SMALLINT(5),
@@ -47880,7 +47884,7 @@ BEGIN
DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1;
DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE;
DECLARE vMandateTypeFk INT DEFAULT 2;
-
+
INSERT INTO `client` (
id,
name,
@@ -47908,21 +47912,21 @@ BEGIN
vProvinceFk,
vCity,
vPostcode,
- CONCAT(vSurnames, ' ', vFirstname),
+ CONCAT(vSurnames, ' ', vFirstname),
vPayMethodFk,
vDueDay,
vDefaultCredit,
vIsTaxDataChecked,
vHasCoreVnl,
FALSE
- ) ON duplicate key update
+ ) ON duplicate key update
payMethodFk = vPayMethodFk,
dueDay = vDueDay,
credit = vDefaultCredit,
isTaxDataChecked = vIsTaxDataChecked,
hasCoreVnl = vHasCoreVnl,
isActive = TRUE;
-
+
IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN
INSERT INTO mandate (clientFk, companyFk, mandateTypeFk)
VALUES (vUserFk, vCompanyFk, vMandateTypeFk);
@@ -47952,21 +47956,21 @@ BEGIN
*/
DECLARE vClientDebt DOUBLE;
-
+
SELECT vn.clientGetDebt(vClientFk, util.VN_CURDATE()) INTO vClientDebt;
-
+
INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
VALUES (vClientFk, 'Saldo pendiente', vClientDebt, util.VN_CURDATE(), 5);
-
+
CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE);
-
+
INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
SELECT vClientFk, 'Liquidación cliente', sum(amount), util.VN_CURDATE(), 5
FROM vn.greuge
WHERE clientFk = vClientFk;
-
- UPDATE vn.client
- SET salesPersonFk = NULL
+
+ UPDATE vn.client
+ SET salesPersonFk = NULL
WHERE id = vClientFk;
END ;;
@@ -47988,24 +47992,24 @@ DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientFreeze`()
BEGIN
/**
-* Congela diariamente aquellos clientes que son morosos sin recobro,
-* pero que no sean trabajadores,
+* Congela diariamente aquellos clientes que son morosos sin recobro,
+* pero que no sean trabajadores,
* y que el riesgo no sea menor que cero
* hasta que no se gire la remesa no se congelan a los clientes de giro
*/
DECLARE vIsRemittanced BOOLEAN;
- SELECT id into vIsRemittanced
- FROM receipt
- WHERE invoiceFk LIKE 'REMESA%'
+ SELECT id into vIsRemittanced
+ FROM receipt
+ WHERE invoiceFk LIKE 'REMESA%'
AND payed > util.firstDayOfMonth(util.VN_CURDATE())
LIMIT 1;
DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
CREATE TEMPORARY TABLE tmp.clientGetDebt
SELECT clientFk
- FROM bs.defaulter
+ FROM bs.defaulter
WHERE created = util.VN_CURDATE()
AND amount;
@@ -48015,11 +48019,11 @@ BEGIN
JOIN bi.defaulters d ON d.client = c.id AND d.date = util.VN_CURDATE()
JOIN config ON TRUE
LEFT JOIN recovery r ON r.clientFk = c.id AND r.finished IS NULL
- LEFT JOIN payMethod pm ON pm.id = c.payMethodFk
+ LEFT JOIN payMethod pm ON pm.id = c.payMethodFk
LEFT JOIN tmp.risk rk ON rk.clientFk = c.id
- SET c.isFreezed = TRUE,
+ SET c.isFreezed = TRUE,
d.frozened = util.VN_CURDATE()
- WHERE (d.amount > config.defaultersMaxAmount
+ WHERE (d.amount > config.defaultersMaxAmount
AND rk.risk > 0)
AND c.typeFk = 'normal'
AND r.id IS NULL
@@ -48083,33 +48087,33 @@ BEGIN
DECLARE vIssued DATETIME;
DECLARE vBalance DOUBLE DEFAULT 0.00;
DECLARE cur CURSOR FOR
- SELECT
- created,
- issued,
+ SELECT
+ created,
+ issued,
ROUND(amount, 2) AS balance
FROM invoiceOut
- WHERE clientFk = vClientFk AND companyFk = vCompanyFk
- UNION ALL
- SELECT
- created,
- payed,
+ WHERE clientFk = vClientFk AND companyFk = vCompanyFk
+ UNION ALL
+ SELECT
+ created,
+ payed,
ROUND(-1 * amountPaid, 2) AS balance
- FROM receipt
+ FROM receipt
WHERE clientFk = vClientFk AND companyFk = vCompanyFk
ORDER BY issued, created;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-
+
OPEN cur;
-
+
proc: LOOP
SET vDone = FALSE;
-
+
FETCH cur INTO vCreated, vIssued, vBalance;
IF vDate IS NULL THEN
SET vDate=vIssued;
END IF;
-
+
IF vDone THEN
LEAVE proc;
END IF;
@@ -48121,66 +48125,66 @@ BEGIN
SET vDone = TRUE;
END IF;
END LOOP;
-
+
CLOSE cur;
-
- SELECT
- issued,
- CAST(debtOut AS DECIMAL(10,2)) debtOut,
+
+ SELECT
+ issued,
+ CAST(debtOut AS DECIMAL(10,2)) debtOut,
CAST(debtIn AS DECIMAL(10,2)) debtIn,
- ref,
- companyFk,
+ ref,
+ companyFk,
priority
FROM
- (SELECT
- NULL AS issued,
- SUM(amountUnpaid) AS debtOut,
- NULL AS debtIn,
- 'Saldo Anterior' AS ref,
+ (SELECT
+ NULL AS issued,
+ SUM(amountUnpaid) AS debtOut,
+ NULL AS debtIn,
+ 'Saldo Anterior' AS ref,
companyFk,
- 0 as priority
- FROM
- (SELECT SUM(amount) AS amountUnpaid, companyFk, 0
+ 0 as priority
+ FROM
+ (SELECT SUM(amount) AS amountUnpaid, companyFk, 0
FROM invoiceOut
- WHERE clientFk = vClientFK
- AND issued < vDate
- GROUP BY companyFk
-
- UNION ALL
-
- SELECT SUM(-1 * amountPaid), companyFk, 0
- FROM receipt
- WHERE clientFk = vClientFK
- AND payed < vDate
- GROUP BY companyFk) AS transactions
- GROUP BY companyFk
-
- UNION ALL
-
- SELECT
- issued,
- amount as debtOut,
- NULL AS debtIn,
+ WHERE clientFk = vClientFK
+ AND issued < vDate
+ GROUP BY companyFk
+
+ UNION ALL
+
+ SELECT SUM(-1 * amountPaid), companyFk, 0
+ FROM receipt
+ WHERE clientFk = vClientFK
+ AND payed < vDate
+ GROUP BY companyFk) AS transactions
+ GROUP BY companyFk
+
+ UNION ALL
+
+ SELECT
+ issued,
+ amount as debtOut,
+ NULL AS debtIn,
ref,
companyFk,
- 1
- FROM invoiceOut
- WHERE clientFk = vClientFK
+ 1
+ FROM invoiceOut
+ WHERE clientFk = vClientFK
AND issued >= vDate
- UNION ALL
-
- SELECT
- r.payed,
- NULL as debtOut,
- r.amountPaid,
- r.invoiceFk,
+ UNION ALL
+
+ SELECT
+ r.payed,
+ NULL as debtOut,
+ r.amountPaid,
+ r.invoiceFk,
r.companyFk,
- 0
+ 0
FROM receipt r
- WHERE r.clientFk = vClientFK
- AND r.payed >= vDate) t
- INNER JOIN `client` c ON c.id = vClientFK
- HAVING debtOut <> 0 OR debtIn <> 0
+ WHERE r.clientFk = vClientFK
+ AND r.payed >= vDate) t
+ INNER JOIN `client` c ON c.id = vClientFK
+ HAVING debtOut <> 0 OR debtIn <> 0
ORDER BY issued, priority DESC, debtIn;
END ;;
DELIMITER ;
@@ -48238,13 +48242,13 @@ BEGIN
WHERE id = vClientFk;
ELSE
-
+
SELECT id INTO vOwner
FROM vn.worker
WHERE code = vWorkerCode COLLATE utf8_general_ci;
END IF;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.clientList;
CREATE TEMPORARY TABLE tmp.clientList
SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale
@@ -48256,7 +48260,7 @@ BEGIN
AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())
AND c.id != vClientFk
HAVING monthSale > 100;
-
+
SELECT SUM(monthSale) INTO vTotalSale
FROM tmp.clientList;
@@ -48267,7 +48271,7 @@ BEGIN
SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk;
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48288,12 +48292,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `clientPackagingOverstock`(vClientFk
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock;
CREATE TEMPORARY TABLE tmp.clientPackagingOverstock
- ENGINE = MEMORY
- SELECT itemFk,
- sum(GotfromClient) - sum(SenttoClient) as devueltos,
+ ENGINE = MEMORY
+ SELECT itemFk,
+ sum(GotfromClient) - sum(SenttoClient) as devueltos,
sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados,
- LEAST(
- sum(GotfromClient) - sum(SenttoClient),
+ LEAST(
+ sum(GotfromClient) - sum(SenttoClient),
sum(InvoicedtoClient) - sum(InvoicedfromClient)
) as abonables
FROM
@@ -48301,14 +48305,14 @@ BEGIN
SELECT t.*,
IF(@month = month, 0, 1) monthEnd,
@month := month
- FROM
+ FROM
(
- SELECT x.id as ticketFk,
- date(x.shipped) as shipped,
- x.itemFk,
- IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient,
- IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient,
- IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient,
+ SELECT x.id as ticketFk,
+ date(x.shipped) as shipped,
+ x.itemFk,
+ IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient,
+ IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient,
+ IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient,
IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient,
i.name as concept,
x.refFk as invoice,
@@ -48327,11 +48331,11 @@ BEGIN
@month := 0 month,
t.companyFk
FROM sale s
- JOIN ticket t on t.id = s.ticketFk
- JOIN packaging p ON p.itemFk = s.itemFk
+ JOIN ticket t on t.id = s.ticketFk
+ JOIN packaging p ON p.itemFk = s.itemFk
LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk
WHERE t.clientFk = vClientFk
- AND t.shipped > '2017-11-30'
+ AND t.shipped > '2017-11-30'
AND p.isPackageReturnable
UNION ALL
SELECT NULL,
@@ -48344,7 +48348,7 @@ BEGIN
'Histórico',
NULL,
NULL
-
+
FROM ticketPackagingStartingStock tps
LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk
WHERE tps.clientFk = vClientFk
@@ -48360,8 +48364,8 @@ BEGIN
NULL AS refFk,
NULL,
t.companyFk
- FROM ticketPackaging tp
- JOIN ticket t on t.id = tp.ticketFk
+ FROM ticketPackaging tp
+ JOIN ticket t on t.id = tp.ticketFk
JOIN packaging p ON p.id = tp.packagingFk
LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk
WHERE t.clientFk = vClientFk
@@ -48398,11 +48402,11 @@ BEGIN
-- SET vGraceDays = GREATEST(vGraceDays, 90);
CALL vn.clientPackagingOverstock(vClientFk,vGraceDays);
-
+
SELECT id INTO vWarehouseFk
FROM vn.warehouse
WHERE hasConfectionTeam;
-
+
CALL vn.ticket_add(
vClientFk
,util.VN_CURDATE()
@@ -48415,22 +48419,22 @@ BEGIN
,account.myUser_getId()
,TRUE
,vNewTicket);
-
+
INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price)
SELECT vNewTicket, cpo.itemFk, - cpo.abonables, i.longName, p.price
FROM tmp.clientPackagingOverstock cpo
JOIN vn.item i ON i.id = cpo.itemFk
JOIN vn.packaging p ON p.itemFk = cpo.itemFk
WHERE cpo.abonables > 0;
-
+
INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity)
SELECT vNewTicket, p.id, cpo.abonables
FROM tmp.clientPackagingOverstock cpo
JOIN vn.packaging p ON p.itemFk = cpo.itemFk
WHERE cpo.abonables > 0;
-
+
SELECT vNewTicket;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48468,9 +48472,9 @@ BEGIN
JOIN vn.client c ON c.id = cd.id
JOIN vn.province p ON p.id = c.provinceFk
JOIN vn.country co ON co.id = p.countryFk
- WHERE cd.Aviso = 'TERCER AVISO' AND
- cp.clientFk IS NULL AND
- co.country NOT IN ('Portugal','Francia','España exento') AND
+ WHERE cd.Aviso = 'TERCER AVISO' AND
+ cp.clientFk IS NULL AND
+ co.country NOT IN ('Portugal','Francia','España exento') AND
c.salesPersonFk IS NOT NULL;
OPEN rs;
@@ -48582,7 +48586,7 @@ BEGIN
JOIN client c ON c.accountingAccount = lc.account
WHERE lc.`date` BETWEEN vDateFrom AND vDateTo
)sub
- GROUP BY companyFk, clientFk
+ GROUP BY companyFk, clientFk
) sub1 ON sub1.clientFk = c.id
JOIN supplier s ON s.id = sub1.companyFk
JOIN company co ON co.id = sub1.companyFk
@@ -48626,13 +48630,13 @@ BEGIN
SET vEnded = TIMESTAMP(IFNULL(vDate, util.VN_CURDATE()), '23:59:59');
DROP TEMPORARY TABLE IF EXISTS tClientRisk;
- CREATE TEMPORARY TABLE tClientRisk
+ CREATE TEMPORARY TABLE tClientRisk
ENGINE = MEMORY
SELECT cr.clientFk, SUM(cr.amount) amount
FROM clientRisk cr
JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk
GROUP BY cr.clientFk;
-
+
INSERT INTO tClientRisk
SELECT c.clientFk, SUM(r.amountPaid)
FROM receipt r
@@ -48647,7 +48651,7 @@ BEGIN
WHERE t.receiptFk IS NULL
AND t.status = 'ok'
GROUP BY t.clientFk;
-
+
INSERT INTO tClientRisk
SELECT t.clientFk, totalWithVat
FROM ticket t
@@ -48663,7 +48667,7 @@ BEGIN
FROM client c
JOIN tClientRisk cr ON cr.clientFk = c.id
GROUP BY c.id;
-
+
DROP TEMPORARY TABLE tClientRisk;
END ;;
DELIMITER ;
@@ -48687,9 +48691,9 @@ BEGIN
DECLARE i INT DEFAULT 0;
DECLARE c INT DEFAULT 0;
DECLARE maxClientFk INT;
-
+
DROP TEMPORARY TABLE IF EXISTS tmp.client;
-
+
CREATE TEMPORARY TABLE tmp.`client`
(id INT AUTO_INCREMENT,
clientFk INT,
@@ -48697,40 +48701,40 @@ BEGIN
PRIMARY KEY(id),
UNIQUE KEY clientFk (clientFk))
ENGINE = MEMORY;
-
+
INSERT INTO tmp.client(clientFk)
SELECT DISTINCT clientFk
FROM vn.invoiceOut
WHERE issued > TIMESTAMPADD(MONTH, -2, util.VN_CURDATE());
-
+
SELECT max(id) INTO maxClientFk
FROM tmp.client;
-
-
+
+
WHILE i < vNumber DO
-
+
SET i = i + 1;
-
+
WHILE c = 0 DO
-
+
SELECT id INTO c
FROM tmp.client
WHERE id = floor(RAND() * maxClientFk) + 1
AND isSelected = FALSE
LIMIT 1;
-
+
END WHILE;
-
+
-- SELECT i, maxClientFk, c;
-
- UPDATE tmp.client
- SET isSelected = TRUE
+
+ UPDATE tmp.client
+ SET isSelected = TRUE
WHERE id = c;
-
+
SET c = 0;
-
+
END WHILE;
-
+
SELECT c.id, c.name FROM tmp.client tc
JOIN vn.client c ON c.id = tc.clientFk
WHERE isSelected
@@ -48807,35 +48811,35 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_getByTicket`(vTicketFk INT)
BEGIN
DECLARE vLanded DATE;
-
+
SELECT DATE_ADD(util.VN_CURDATE(), INTERVAL landingDays DAY) INTO vLanded
FROM vn.cmrConfig;
IF vTicketFk THEN
-
+
IF (SELECT count(ticketFk) FROM vn.cmr WHERE ticketFk = vTicketFk) THEN
-
+
SELECT id FROM vn.cmr WHERE ticketFk = vTicketFk;
-
+
ELSE
-
+
INSERT INTO vn.cmr(ticketFk, companyFk, addressFromFk, addressToFk, ead)
SELECT vTicketFk, t.companyFk, a.id, t.addressFk, vLanded
FROM vn.ticket t
- JOIN vn.warehouse w ON w.id = t.warehouseFk
- JOIN vn.address a ON a.id = w.addressFk
+ JOIN vn.warehouse w ON w.id = t.warehouseFk
+ JOIN vn.address a ON a.id = w.addressFk
WHERE t.id = vTicketFk;
-
+
SELECT LAST_INSERT_ID();
-
+
END IF;
-
+
ELSE
-
+
INSERT INTO vn.cmr(ead) VALUES(vLanded);
-
+
SELECT LAST_INSERT_ID();
-
+
END IF;
END ;;
DELIMITER ;
@@ -48858,7 +48862,7 @@ BEGIN
/**
* Insert the monthly CMR summary in vn.mail on the 5th of each month.
*/
-
+
SET SESSION group_concat_max_len = 1000000;
-- IF (DAY(util.VN_CURDATE()) = 5) THEN
INSERT INTO
@@ -48886,7 +48890,7 @@ BEGIN
@@ -48904,7 +48908,7 @@ BEGIN -- Actualizamos el estado a 'Enviado' UPDATE vn.cmr c SET c.state = 'Sent' - WHERE c.state = 'Pending' + WHERE c.state = 'Pending' AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH) AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH); -- END IF; @@ -48927,7 +48931,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collectionPlacement_get`(vParamFk INT(11), vIsPicker bool) BEGIN /** Devuelve el listado de ubicaciones a las que hay que ir para preparar una colección o ticket - * + * * @param vParamFk Identificador de vn.collection o Identificador de vn.ticket * @param vIsPicker Booleano para distinguer el sacador del revisador */ @@ -48944,7 +48948,7 @@ BEGIN FROM vn.ticketCollection tc JOIN vn.sale s ON s.ticketFk = tc.ticketFk WHERE tc.collectionFk = vParamFk - UNION ALL + UNION ALL SELECT s.ticketFk, s.id, s.itemFk, s.quantity FROM vn.sale s WHERE s.ticketFk = vParamFk; @@ -48969,8 +48973,8 @@ BEGIN (INDEX(itemFk)) ENGINE = MEMORY SELECT b.itemFk, - CASE b.groupingMode - WHEN 0 THEN 1 + CASE b.groupingMode + WHEN 0 THEN 1 WHEN 2 THEN b.packing ELSE b.`grouping` END AS `grouping` @@ -49010,10 +49014,10 @@ BEGIN , st.saleFk as salePreviousPrepared , iss.userFk , ts.quantity - FROM tmp.sale ts - LEFT JOIN (SELECT DISTINCT saleFk + FROM tmp.sale ts + LEFT JOIN (SELECT DISTINCT saleFk FROM vn.saleTracking st - JOIN vn.state s ON s.id = st.stateFk + JOIN vn.state s ON s.id = st.stateFk WHERE st.isChecked AND s.semaphore = 1) st ON st.saleFk = ts.saleFk JOIN vn.itemShelving ish ON ish.itemFk = ts.itemFk @@ -49034,13 +49038,13 @@ BEGIN SELECT saleFk, priority as olderPriority FROM (SELECT saleFk, priority FROM tmp.salePlacementList - ORDER BY isPreviousPrepared DESC, + ORDER BY isPreviousPrepared DESC, itemShelvingSaleFk IS NULL DESC, - visible >= quantity DESC, + visible >= quantity DESC, visible > 0 DESC, IFNULL(shelvingPriority,0) DESC, priority - LIMIT 10000000000000000000 + LIMIT 10000000000000000000 ) sub GROUP BY saleFk; @@ -49049,7 +49053,7 @@ BEGIN ENGINE MEMORY SELECT s1.saleFk, `order`as saleOrder FROM tmp.salePlacementList s1 - JOIN tmp.salePlacementList_2 s2 ON s2.saleFk = s1.saleFk AND s2.olderPriority = s1.priority; + JOIN tmp.salePlacementList_2 s2 ON s2.saleFk = s1.saleFk AND s2.olderPriority = s1.priority; UPDATE tmp.salePlacementList s1 JOIN tmp.salePlacementList_3 s3 ON s3.saleFk = s1.saleFk @@ -49063,10 +49067,10 @@ BEGIN FROM tmp.salePlacementList spl JOIN vn.sale s ON s.id = spl.saleFk ORDER BY saleOrder, - isPreviousPrepared DESC, + isPreviousPrepared DESC, itemShelvingSaleFk DESC, IF(vIsPicker, visible = 0, TRUE), - s.quantity <= spl.visible DESC, + s.quantity <= spl.visible DESC, shelvingPriority DESC, -- PAK 05/11/2021 priority; @@ -49099,27 +49103,27 @@ BEGIN DECLARE vConcept VARCHAR(50); DECLARE itemFk INT; DECLARE vSaleFk INT default 0; - + DECLARE vDescription VARCHAR(50); DECLARE vItemName VARCHAR(50); - + SELECT barcodeToItem(vItemFk) INTO itemFk; - + SELECT CONCAT(vn.getUser()," ",DATE_FORMAT(util.VN_NOW( ), "%H:%i" )," ",i.name) INTO vConcept FROM vn.item i WHERE i.id = itemFk; - + SELECT name INTO vItemName FROM vn.item WHERE id = vItemFk; SELECT CONCAT("Añadido articulo ", vItemName, " cantidad:", vQuantity) INTO vDescription; - - INSERT INTO vn.ticketLog (originFk, userFk, action , description) + + INSERT INTO vn.ticketLog (originFk, userFk, action , description) VALUES(vTicketFk, vn.getUser(), 'update', vDescription); - + INSERT INTO vn.sale (itemFk,ticketFk,concept,quantity,isAdded) VALUES (itemFk,vTicketFk,vConcept,vQuantity,1); SELECT last_insert_id() INTO vSaleFk; - + CALL vn.sale_calculateComponent(vSaleFk, null); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49137,7 +49141,7 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`(vUserFk INT, OUT vCollectionFk INT) -proc:BEGIN +proc:BEGIN /* Comprueba si existen colecciones libres que se ajustan al perfil del usuario * y le asigna la más antigua. * Añade un registro al semillero de colecciones @@ -49170,14 +49174,14 @@ proc:BEGIN FROM vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id JOIN vn.state s ON s.code = 'PRINTED_AUTO' - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* FROM vn.collection c - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; -- Se a�ade registro al semillero @@ -49187,8 +49191,8 @@ proc:BEGIN -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion SELECT MIN(c.id) INTO vCollectionFk - FROM vn.collection c - JOIN vn.operator o + FROM vn.collection c + JOIN vn.operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) AND o.numberOfWagons = c.wagons AND o.trainFk = c.trainFk @@ -49223,11 +49227,11 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_get`(vWorkerFk INT) BEGIN - + /* Obtiene colección del sacador si tiene líneas pendientes - * + * * @param vWorkerFk id del worker - * + * * @table Devuelve tabla temporal con las colecciones pendientes. */ DROP TEMPORARY TABLE IF EXISTS tCollection; @@ -49235,18 +49239,18 @@ BEGIN CREATE TEMPORARY TABLE tCollection SELECT c.id collectionFk, date(c.created) created - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk JOIN ticketState ts ON ts.ticketFk = tc.ticketFk JOIN state s2 ON s2.id = ts.stateFk JOIN productionConfig pc JOIN vn.state ss on ss.code = 'PREPARED' LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk + WHERE c.workerFk = vWorkerFk AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder + AND s2.order < pc.pendingCollectionsOrder GROUP BY c.id HAVING COUNT(*) > COUNT(DISTINCT st.id); @@ -49273,15 +49277,15 @@ BEGIN * Selecciona los tickets de una colección/ticket * @param vParamFk ticketFk/collectionFk * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones - */ + */ DECLARE vItemPackingTypeFk VARCHAR(1); -- Si los sacadores son los de pruebas, pinta los colores SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + FROM vn.collection WHERE id = vParamFk; - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, am.name agencyName, t.warehouseFk, @@ -49291,20 +49295,20 @@ BEGIN FROM vn.ticket t LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk + WHERE t.id = vParamFk AND t.shipped >= util.yesterday() UNION ALL - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, @@ -49314,15 +49318,15 @@ BEGIN FROM vn.ticket t JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 WHERE tc.collectionFk = vParamFk; @@ -49344,20 +49348,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_kill`(vSelf INT) BEGIN - + /* Elimina una coleccion y coloca sus tickets en OK - * + * */ - + INSERT INTO ticketTracking(stateFk, ticketFk) SELECT s.id, ticketFk FROM vn.ticketCollection tc JOIN vn.state s ON s.code = 'OK' WHERE tc.collectionFk = vSelf; - - DELETE FROM vn.collection + + DELETE FROM vn.collection WHERE id = vSelf; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49688,8 +49692,8 @@ proc:BEGIN -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo DELETE tt.* FROM tTrain tt - LEFT JOIN (SELECT DISTINCT wagon - FROM tTrain + LEFT JOIN (SELECT DISTINCT wagon + FROM tTrain WHERE ticketFk IS NOT NULL ) nn ON nn.wagon = tt.wagon WHERE nn.wagon IS NULL; @@ -49784,7 +49788,7 @@ proc:BEGIN WHERE w.id = vn.getUser(); SELECT COUNT(ws.id) INTO vWagons - FROM workerShelving ws + FROM workerShelving ws WHERE ws.workerFk = vWorkerFk AND ws.collectionFk IS NULL; @@ -49814,7 +49818,7 @@ proc:BEGIN ORDER BY wagon ASC, level ASC; UPDATE vn.ticketCollection tc - JOIN tmp.smartTags ts ON tc.wagon = ts.wagon AND tc.level = ts.level + JOIN tmp.smartTags ts ON tc.wagon = ts.wagon AND tc.level = ts.level SET tc.smartTagFk = ts.code WHERE tc.collectionFk = vCollectionFk; @@ -49861,14 +49865,14 @@ proc:BEGIN DECLARE vTrainFk INT DEFAULT 1; DECLARE vUserFk INT; DECLARE vHourMatters BOOL DEFAULT TRUE; - + SELECT pc.ticketPrintedMax * vWagons, pc.ticketTrolleyMax * vWagons, pc.maxNotReadyCollections INTO vMaxTicketPrinted, vMaxTickets, vMaxNotReadyCollections FROM vn.productionConfig pc; /*IF NOT vn.deviceProductionUser_Exists(vUserFk) THEN - + LEAVE proc; - + END IF;*/ SELECT w.code, w.id INTO vWorkerCode, vUserFk @@ -49880,44 +49884,44 @@ proc:BEGIN INTO vIsPreviousPrepared, vWarehouseFk, vItemPackingTypeFk FROM vn.sector WHERE id = vSectorFk; -- Hola - + -- Si está habilitado el modo cazador para las motos, y el usuario no esta registrado, se sale. - - IF (SELECT isTractorHuntingMode FROM vn.deviceProductionConfig dpc) AND vItemPackingTypeFk = 'H' THEN - IF (SELECT COUNT(*) FROM vn.workerWithoutTractor wwt WHERE wwt.workerFk = vUserFk) THEN + + IF (SELECT isTractorHuntingMode FROM vn.deviceProductionConfig dpc) AND vItemPackingTypeFk = 'H' THEN + IF (SELECT COUNT(*) FROM vn.workerWithoutTractor wwt WHERE wwt.workerFk = vUserFk) THEN CALL util.throw('Usuario no registrado con moto'); LEAVE proc; END IF; END IF; - - + + -- Si hay colecciones sin terminar, sale del proceso SELECT count(*) INTO vNotReadyCollections FROM ( SELECT count(DISTINCT s.id) totalRow, count(DISTINCT st.id) pickedRow - FROM vn.collection c - JOIN vn.ticketCollection tc ON tc.collectionFk = c.id - JOIN vn.sale s ON s.ticketFk = tc.ticketFk + FROM vn.collection c + JOIN vn.ticketCollection tc ON tc.collectionFk = c.id + JOIN vn.sale s ON s.ticketFk = tc.ticketFk JOIN vn.state ss ON ss.code = 'PREPARED' LEFT JOIN vn.saleTracking st ON st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vUserFk + WHERE c.workerFk = vUserFk AND c.created >= TIMESTAMPADD(HOUR , -6,util.VN_NOW()) AND s.quantity != 0 GROUP BY c.id - HAVING totalRow > pickedRow) sub; + HAVING totalRow > pickedRow) sub; IF vMaxNotReadyCollections < vNotReadyCollections THEN - + CALL util.throw('Hay colecciones pendientes'); LEAVE proc; - + END IF; IF vIsPreviousPrepared THEN CALL util.throw('Es de preparación previa'); LEAVE proc; -- Hasta que tengamos el altillo, vamos a cancelar esta opcion - + SELECT id INTO vStateFk FROM vn.state WHERE `code` = 'PREVIOUS_PREPARATION'; @@ -49929,37 +49933,37 @@ proc:BEGIN END IF; - CALL vn.productionControl(vWarehouseFk, 0); + CALL vn.productionControl(vWarehouseFk, 0); -- Esto hay que corregirlo añadiendo un nuevo parámetro al proc. PAK 23/12/21 IF vSectorFk = 65 THEN -- Pedidos pequeños - + SET vTrainFk = 2; - + SET vHourMatters = FALSE; - - DELETE pb.* + + DELETE pb.* FROM tmp.productionBuffer pb - JOIN vn.volumeConfig vc + JOIN vn.volumeConfig vc WHERE pb.m3 * 1000 > vc.minTicketVolume; - + END IF; - -- Se obtiene nº de colección y el buffer con los pedidos preparables + -- Se obtiene nº de colección y el buffer con los pedidos preparables INSERT INTO vn.collection SET workerFk = vUserFk, itemPackingTypeFk = vItemPackingTypeFk, trainFk = vTrainFk; - + SELECT LAST_INSERT_ID() INTO vCollectionFk; - + -- 05/08/2021 PAK Jose Frau pide que los tickets de recogida en Algemesí sólo se saquen si están asignados. DELETE pb.* FROM tmp.productionBuffer pb JOIN vn.state s ON s.id = pb.state WHERE pb.agency = 'REC_ALGEMESI' AND s.code != 'PICKER_DESIGNED'; - + -- 2/3/2022 PAK Se acuerda con Pepe que los pedidos con riesgo no se sacan aunque se asignen. DELETE pb.* FROM tmp.productionBuffer pb @@ -49972,13 +49976,13 @@ proc:BEGIN JOIN vn.state s ON s.id = pb.state WHERE s.code = 'PICKER_DESIGNED' AND pb.workerCode = vWorkerCode; - + IF hasAssignedTickets THEN - - UPDATE vn.collection - SET itemPackingTypeFk = NULL + + UPDATE vn.collection + SET itemPackingTypeFk = NULL WHERE id = vCollectionFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; CREATE TEMPORARY TABLE tmp.ticketToSplit SELECT pb.ticketFk @@ -49986,42 +49990,42 @@ proc:BEGIN JOIN vn.state s ON s.id = pb.state WHERE s.code = 'PICKER_DESIGNED' AND pb.workerCode = vWorkerCode - ORDER BY HH, - mm, - s.`order` DESC, + ORDER BY HH, + mm, + s.`order` DESC, pb.m3 DESC; - - WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO - + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + SELECT MIN(ticketFk) INTO vTicketToSplit FROM tmp.ticketToSplit; - + CALL vn.ticket_splitItemPackingType(vTicketToSplit,IFNULL(vItemPackingTypeFk, 'H')); - + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) SELECT ticketFk, vCollectionFk FROM tmp.ticketIPT - WHERE (itemPackingTypeFk = vItemPackingTypeFk) ; - + WHERE (itemPackingTypeFk = vItemPackingTypeFk) ; + DELETE FROM tmp.ticketToSplit WHERE ticketFk = vTicketToSplit; - + DROP TEMPORARY TABLE tmp.ticketIPT; - + END WHILE; - + CALL vn.productionControl(vWarehouseFk, 0); - + ELSE - + SELECT COUNT(*) INTO vPrintedTickets FROM tmp.productionBuffer pb JOIN vn.state s ON s.id = pb.state JOIN vn.agencyMode am ON am.id = pb.agencyModeFk JOIN vn.agency a ON a.id = am.agencyFk - JOIN vn.productionConfig pc + JOIN vn.productionConfig pc WHERE pb.shipped = util.VN_CURDATE() - AND (pb.ubicacion IS NOT NULL + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) AND s.isPreparable AND ( @@ -50029,7 +50033,7 @@ proc:BEGIN OR (pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV)) OR (pb.H = 0 AND pb.V = 0 AND pb.N > 0 AND ISNULL(pb.collectionH) AND ISNULL(pb.collectionV)) ) - AND (pc.isPreviousPreparationRequired = FALSE + AND (pc.isPreviousPreparationRequired = FALSE OR pb.previousWithoutParking = FALSE); SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; @@ -50040,16 +50044,16 @@ proc:BEGIN SELECT s2.id, pb.ticketFk, vUserFk FROM tmp.productionBuffer pb JOIN vn.agencyMode am ON am.id = pb.agencyModeFk - JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.agency a ON a.id = am.agencyFk JOIN vn.state s ON s.id = pb.state JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' JOIN vn.ticket t ON t.id = pb.ticketFk JOIN vn.ticketConfig tc JOIN vn.productionConfig pc WHERE pb.shipped = util.VN_CURDATE() - AND (LENGTH(pb.problem) = 0 + AND (LENGTH(pb.problem) = 0 OR (pb.problem = 'PEQUEÑO' AND vTrainFk = 2)) - AND (pb.ubicacion IS NOT NULL + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) AND s.isPrintable AND s.isOK @@ -50059,23 +50063,23 @@ proc:BEGIN OR (pb.H = 0 AND pb.V = 0 AND pb.N > 0 AND ISNULL(pb.collectionH) AND ISNULL(pb.collectionV)) ) AND t.created < TIMESTAMPADD(MINUTE, - tc.pickingDelay , util.VN_NOW()) - AND (pc.isPreviousPreparationRequired = FALSE + AND (pc.isPreviousPreparationRequired = FALSE OR pb.previousWithoutParking = FALSE) - ORDER BY HH, + ORDER BY HH, mm, s.`order` DESC, pb.m3 DESC LIMIT vMaxTicketPrinted; - + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. -- Se splitan los tickets preparables, para que solo tengan un tipo de empaquetado - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; CREATE TEMPORARY TABLE tmp.ticketToSplit SELECT pb.ticketFk, (pb.H + pb.V = 0) isNeutral FROM tmp.productionBuffer pb JOIN vn.agencyMode am ON am.id = pb.agencyModeFk - JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.agency a ON a.id = am.agencyFk JOIN vn.ticketStateToday tst ON tst.ticket = pb.ticketFk JOIN vn.state s ON s.id = tst.state JOIN vn.productionConfig pc @@ -50084,46 +50088,46 @@ proc:BEGIN OR (pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV)) OR (pb.H = 0 AND pb.V = 0 AND pb.N > 0 AND ISNULL(pb.collectionH) AND ISNULL(pb.collectionV)) ) - AND (pb.ubicacion IS NOT NULL + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) AND LENGTH(pb.problem) = 0 AND s.isPreparable - AND (pc.isPreviousPreparationRequired = FALSE + AND (pc.isPreviousPreparationRequired = FALSE OR pb.previousWithoutParking = FALSE) ORDER BY pb.HH, pb.mm, s.`order` DESC LIMIT vMaxTickets; - - WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO - + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + SELECT MIN(ticketFk) INTO vTicketToSplit FROM tmp.ticketToSplit; - - - IF (SELECT isNeutral - FROM tmp.ticketToSplit + + + IF (SELECT isNeutral + FROM tmp.ticketToSplit WHERE ticketFk = vTicketToSplit) THEN - + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) VALUES(vTicketToSplit, vCollectionFk); - + ELSE - + CALL vn.ticket_splitItemPackingType(vTicketToSplit, vItemPackingTypeFk); - + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) SELECT ticketFk, vCollectionFk FROM tmp.ticketIPT WHERE itemPackingTypeFk = vItemPackingTypeFk; - + DROP TEMPORARY TABLE tmp.ticketIPT; - + END IF; - + DELETE FROM tmp.ticketToSplit WHERE ticketFk = vTicketToSplit; - + END WHILE; - + END IF; -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección @@ -50150,20 +50154,20 @@ proc:BEGIN SELECT t.ticketFk, SUM(s.quantity * vc.shelveVolume / i.packingShelve) shelveLiters FROM tmp.ticket t JOIN vn.sale s ON s.ticketFk = t.ticketFk - JOIN vn.item i ON i.id = s.itemFk + JOIN vn.item i ON i.id = s.itemFk JOIN vn.volumeConfig vc - WHERE i.packingShelve + WHERE i.packingShelve GROUP BY t.ticketFk; - UPDATE tmp.ticket t + UPDATE tmp.ticket t JOIN tmp.ticketShelveLiters tsl ON tsl.ticketFk = t.ticketFk SET t.shelveLiters = tsl.shelveLiters; -- Es importante que el primer ticket se coja en todos los casos - + SET vFirstTicketFk = 0; - SELECT ticketFk, HH, mm + SELECT ticketFk, HH, mm INTO vFirstTicketFk, vHour, vMinute FROM tmp.ticket ORDER BY productionOrder DESC, HH, mm @@ -50171,47 +50175,47 @@ proc:BEGIN -- Hay que excluir aquellos que no tengan la misma hora de preparación IF vHourMatters THEN - - DELETE + + DELETE FROM tmp.ticket - WHERE HH != vHour + WHERE HH != vHour OR mm != vMinute; - + END IF; - + -- En el caso de pedidos de más volumen de un carro, la colección será monoticket. Pero si el primer pedido -- no es monoticket, excluimos a los de más de un carro IF (SELECT (t.shelveLiters > vc.trolleyM3 * 1000) FROM tmp.ticket t - JOIN vn.volumeConfig vc + JOIN vn.volumeConfig vc WHERE t.ticketFk = vFirstTicketFk) THEN - DELETE - FROM tmp.ticket + DELETE + FROM tmp.ticket WHERE ticketFk != vFirstTicketFk; - + ELSE - + DELETE t.* - FROM tmp.ticket t - JOIN vn.volumeConfig vc + FROM tmp.ticket t + JOIN vn.volumeConfig vc WHERE t.shelveLiters > vc.trolleyM3 * 1000; - + END IF; -- Elimina los tickets bloqueados que no se van a preparar - DELETE tc.* + DELETE tc.* FROM vn.ticketCollection tc LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND t.ticketFk IS NULL; - + -- Construccion del tren - + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. UPDATE tmp.ticket t JOIN - ( SELECT MAX(i.size) maxHeigth, + ( SELECT MAX(i.size) maxHeigth, tc.ticketFk FROM vn.ticketCollection tc JOIN vn.sale s ON s.ticketFk = tc.ticketFk @@ -50220,11 +50224,11 @@ proc:BEGIN AND tc.collectionFk = vCollectionFk GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk SET t.height = IFNULL(sub.maxHeigth,0); - + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido DROP TEMPORARY TABLE IF EXISTS tmp.wagonsVolumetry; CREATE TEMPORARY TABLE tmp.wagonsVolumetry - SELECT cv.`level` as shelve, + SELECT cv.`level` as shelve, 1 as wagon, cv.`lines`, cv.liters, @@ -50240,7 +50244,7 @@ proc:BEGIN SET vWagonCounter = vWagonCounter + 1; INSERT INTO tmp.wagonsVolumetry(shelve, wagon, `lines`, liters, height) - SELECT cv.`level` as shelve, + SELECT cv.`level` as shelve, vWagonCounter as wagon, cv.`lines`, cv.liters, @@ -50256,11 +50260,11 @@ proc:BEGIN SELECT ticketFk, shelve, wagon, linesDif, LitersDif, heightDif FROM ( SELECT t.ticketFk, - wv.shelve, + wv.shelve, wv.wagon, t.productionOrder, - CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, - CAST(wv.liters AS SIGNED) - t.shelveLiters as litersDif, + CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, + CAST(wv.liters AS SIGNED) - t.shelveLiters as litersDif, CAST(wv.height AS SIGNED) - t.height as heightDif FROM tmp.wagonsVolumetry wv JOIN tmp.ticket t @@ -50269,14 +50273,14 @@ proc:BEGIN AND litersDif >= 0 AND heightDif >= 0 ORDER BY productionOrder DESC, linesDif, LitersDif, heightDif ; - + -- Insertamos una opcion virtual para carro completo. Todo ticket tiene que poder entrar en un carro completo.... INSERT INTO tmp.ticketShelve(ticketFk, shelve, wagon, linesDif, LitersDif, heightDif) SELECT t.ticketFk, 0, wv.wagon, 999, 999,999 FROM tmp.ticket t JOIN tmp.wagonsVolumetry wv GROUP BY t.ticketFk, wv.wagon; - + SET vWagonCounter = 0; WHILE vWagonCounter < vWagons DO @@ -50292,57 +50296,57 @@ proc:BEGIN AND wagon = vWagonCounter ORDER BY heightDif, litersDif, linesDif LIMIT 1; - + ELSE SELECT shelve, ticketFk INTO vShelve, vFirstTicketFk FROM tmp.ticketShelve WHERE wagon = vWagonCounter - ORDER BY heightDif, litersDif, linesDif + ORDER BY heightDif, litersDif, linesDif LIMIT 1; END IF; IF vShelve > 0 THEN - - UPDATE tmp.ticket + + UPDATE tmp.ticket SET shelve = vShelve, wagon = vWagonCounter WHERE ticketFk = vFirstTicketFk; - + DELETE FROM tmp.ticketShelve WHERE ticketFk = vFirstTicketFk OR (shelve = vShelve AND wagon = vWagonCounter); - + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve WHERE wagon = vWagonCounter) DO - + SELECT ticketFk, shelve INTO vTicket, vShelve FROM tmp.ticketShelve WHERE wagon = vWagonCounter LIMIT 1; - - UPDATE tmp.ticket + + UPDATE tmp.ticket SET shelve = vShelve, wagon = vWagonCounter WHERE ticketFk = vTicket; - + DELETE FROM tmp.ticketShelve WHERE ticketFk = vTicket OR (shelve = vShelve AND wagon = vWagonCounter); - + END WHILE; ELSE - - UPDATE tmp.ticket + + UPDATE tmp.ticket SET shelve = 1, wagon = vWagonCounter WHERE ticketFk = vFirstTicketFk; DELETE FROM tmp.ticketShelve WHERE ticketFk = vFirstTicketFk AND wagon != vWagonCounter; - + END IF; END WHILE; @@ -50351,29 +50355,29 @@ proc:BEGIN DELETE FROM tmp.ticket WHERE shelve = 0; -- Elimina los tickets bloqueados que no se van a preparar - DELETE tc.* + DELETE tc.* FROM vn.ticketCollection tc LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND t.ticketFk IS NULL; -- Elimina los tickets que ya estan en otra coleccion - DELETE tc.* + DELETE tc.* FROM vn.ticketCollection tc - JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk + JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND tc2.collectionFk != vCollectionFk; - + -- Actualiza el estado de la colección UPDATE vn.collection c JOIN vn.state st ON st.code = 'ON_PREPARATION' SET c.stateFk = st.id - WHERE c.id = vCollectionFk; + WHERE c.id = vCollectionFk; -- Asigna las bandejas UPDATE vn.ticketCollection tc JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - SET tc.level = t.shelve, + SET tc.level = t.shelve, tc.wagon = t.wagon, tc.itemCount = t.`lines`, tc.liters = t.shelveLiters; @@ -50381,38 +50385,38 @@ proc:BEGIN -- Actualiza el estado de los tickets INSERT INTO ticketTracking(stateFk, ticketFk, workerFk) SELECT vStateFk, ticketFk, vUserFk - FROM vn.ticketCollection tc + FROM vn.ticketCollection tc WHERE tc.collectionFk = vCollectionFk; - + -- Aviso para la preparacion previa INSERT INTO vn.ticketDown(ticketFk, collectionFk) SELECT tc.ticketFk, tc.collectionFk FROM vn.ticketCollection tc WHERE tc.collectionFk = vCollectionFk; - IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN + IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN CALL vn.sales_mergeByCollection(vCollectionFk); UPDATE vn.collection c - JOIN (SELECT count(*) saleTotalCount , + JOIN (SELECT count(*) saleTotalCount , sum(s.isPicked != 0) salePickedCount FROM vn.ticketCollection tc JOIN vn.sale s ON s.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND s.quantity > 0 - ) sub - SET c.saleTotalCount = sub.saleTotalCount, + ) sub + SET c.saleTotalCount = sub.saleTotalCount, c.salePickedCount = sub.salePickedCount WHERE c.id = vCollectionFk; - - SELECT vCollectionFk; + + SELECT vCollectionFk; ELSE CALL util.throw('No ha sido posible obtener colección'); DELETE FROM vn.collection WHERE id = vCollectionFk; - + END IF; DROP TEMPORARY TABLE @@ -50422,8 +50426,8 @@ proc:BEGIN tmp.wagonsVolumetry, tmp.ticketShelve, tmp.productionBuffer; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50441,22 +50445,22 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_printSticker`( - vSelf INT, + vSelf INT, vLabelCount INT ) BEGIN /** - * Prints a yellow label from a collection or a ticket + * Prints a yellow label from a collection or a ticket * * @param vSelf collection or ticket * @param vLabelCount number of times the collection has been printed */ DECLARE vPrintArgs JSON DEFAULT JSON_OBJECT('collectionOrTicketFk', vSelf); - IF vLabelCount IS NULL THEN + IF vLabelCount IS NULL THEN INSERT INTO ticketTrolley SELECT ticketFk, 1 - FROM ticketCollection + FROM ticketCollection WHERE collectionFk = vSelf ON DUPLICATE KEY UPDATE labelCount = labelCount + 1; ELSE @@ -50464,9 +50468,9 @@ BEGIN END IF; CALL report_print( - 'LabelCollection', + 'LabelCollection', (SELECT w.labelerFk FROM worker w WHERE w.id = account.myUser_getId()), - account.myUser_getId(), + account.myUser_getId(), vPrintArgs, 'high' ); @@ -50525,10 +50529,10 @@ BEGIN DECLARE vNumPrepared INT; DECLARE vNumTotal INT; - REPLACE INTO vn.saleTracking(saleFk, isChecked, originalQuantity, workerFk, stateFk) + REPLACE INTO vn.saleTracking(saleFk, isChecked, originalQuantity, workerFk, stateFk) VALUES(vSaleFk,1,vOriginalQuantity,vWorkerFk,vStateFk); - UPDATE vn.sale SET isPicked = 1 + UPDATE vn.sale SET isPicked = 1 WHERE id = vSaleFk; SELECT COUNT(s.id) INTO vNumPrepared @@ -50547,7 +50551,7 @@ BEGIN CALL vn.collection_update(vTicketFk); END IF; - + END ;; DELIMITER ; @@ -50567,25 +50571,25 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getFiscaldata`(workerFk INT) BEGIN - + DECLARE vCompanyFk INT; - - SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) + + SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) INTO vCompanyFk FROM vn.routeConfig rc LEFT JOIN userConfig uc ON uc.userFk = workerFk; - - + + SELECT s.name AS name , s.NIF AS nif , s.street AS street , s.city AS city , - s.postCode AS postCode - - FROM vn.company c + s.postCode AS postCode + + FROM vn.company c JOIN vn.worker w ON w.id = c.workerManagerFk - JOIN vn.supplier s ON s.id = c.id + JOIN vn.supplier s ON s.id = c.id WHERE c.id = vCompanyFk; END ;; DELIMITER ; @@ -50642,7 +50646,7 @@ BEGIN IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount, p.dueDated < vStartingDate isBeforeStarting, p.currencyFk - FROM payment p + FROM payment p WHERE p.received > vStartDate AND p.companyFk = vSelf UNION ALL @@ -50650,9 +50654,9 @@ BEGIN r.companyFk, - IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total, rv.dueDated < vStartingDate isBeforeStarting, - r.currencyFk - FROM invoiceIn r - INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk + r.currencyFk + FROM invoiceIn r + INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk WHERE r.issued > vStartDate AND r.isBooked AND r.companyFk = vSelf @@ -50704,11 +50708,11 @@ BEGIN -IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue), r.currencyFk, FALSE isPayment, - TRUE - FROM invoiceIn r + TRUE + FROM invoiceIn r LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk AND r.supplierFk = si.supplierFk - AND r.currencyFk = si.currencyFk + AND r.currencyFk = si.currencyFk JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk WHERE rv.dueDated >= vStartingDate AND (si.closingBalances IS NULL OR si.closingBalances <> 0) @@ -50763,7 +50767,7 @@ BEGIN FROM tPendingDuedates WHERE balance < vInvalidBalances AND balance > - vInvalidBalances; - + DELETE vp.* FROM tPendingDuedates vp JOIN tRowsToDelete rd ON ( @@ -50792,7 +50796,7 @@ BEGIN LEFT JOIN supplier s ON s.id = vp.supplierFk LEFT JOIN vn.client c ON c.fi = s.nif LEFT JOIN vn.clientRisk cr ON cr.clientFk = c.id; - + DROP TEMPORARY TABLE tOpeningBalances; DROP TEMPORARY TABLE tPendingDuedates; DROP TEMPORARY TABLE tRowsToDelete; @@ -50815,7 +50819,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME) BEGIN - + DECLARE startingMinute INT; TRUNCATE vn.conveyorExpedition; @@ -50832,23 +50836,23 @@ BEGIN conveyorBuildingClassFk) SELECT e.id, e.created, - 10 * p.depth as depth, + 10 * p.depth as depth, 10 * p.width as width, 10 * p.height as height, IFNULL(t.routeFk,am.agencyFk) routeFk, hour(e.created) * 60 + minute(e.created), IFNULL(et.description , a.name), IFNULL(t.routeFk,am.agencyFk) criterion, - IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) + IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.packaging p ON p.id = e.packagingFk LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.agency a ON a.id = am.agencyFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk - JOIN vn.packagingConfig pc + LEFT JOIN vn.agency a ON a.id = am.agencyFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded AND p.height < 140 @@ -50857,8 +50861,8 @@ BEGIN SELECT MIN(productionMinute) INTO startingMinute FROM vn.conveyorExpedition ce ; - - UPDATE vn.conveyorExpedition + + UPDATE vn.conveyorExpedition SET productionMinute = productionMinute - startingMinute; END ;; @@ -50927,7 +50931,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT) BEGIN - + UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk; END ;; @@ -50950,52 +50954,52 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `crypt`(vText VARCHAR(255), vKey VAR BEGIN DECLARE vEncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vEncryptedChar VARCHAR(1); DECLARE vEncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - + DECLARE vInvalidadChars VARCHAR(255) DEFAULT ''; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar)); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition; - + IF vEncryptedCharPosition > vChainLength THEN - + SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength; - + END IF; - + SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1); - + SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText); @@ -51020,49 +51024,49 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cryptOff`(vText VARCHAR(255), vKey BEGIN DECLARE vUncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vUncryptedChar VARCHAR(1); DECLARE vUncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition; - + IF vUncryptedCharPosition < 1 THEN - + SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength; - + END IF; - + SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1); - + SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = vUncryptedText; @@ -51158,7 +51162,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -51169,11 +51173,11 @@ BEGIN IF vDone THEN LEAVE myLoop; END IF; - + SET vIndex = vIndex + 1; SET vLft = vIndex; SET vSons = vSons + 1; - + CALL department_calcTreeRec( vChildFk, CONCAT(vPath, vChildFk, '/'), @@ -51228,7 +51232,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM department_recalc; - + IF vIsChanged THEN UPDATE department_recalc SET isChanged = FALSE; CALL vn.department_calcTree; @@ -51253,17 +51257,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `department_getHasMistake`() BEGIN - + /** * Obtiene los sectores a los cuales les ponemos errores * */ - + SELECT id, name FROM department WHERE hasToMistake <> FALSE; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51322,19 +51326,19 @@ BEGIN FROM department g JOIN tChilds c ON c.id = g.id WHERE g.parentFk IS NOT NULL; - + INSERT IGNORE INTO tNodes SELECT id FROM tParents; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; - + DELETE FROM tChilds; INSERT INTO tChilds SELECT id FROM tParents; END LOOP; - + DROP TEMPORARY TABLE tChilds, tParents; @@ -51376,10 +51380,10 @@ BEGIN /* * Inserta registro en tabla devicelog el log del usuario conectado * @param vAppName es el nombre de la app - * @param vAppVersion es la versión de la app - * @param vAndroid_id es el android_id del dispositivo que se ha logueado + * @param vAppVersion es la versión de la app + * @param vAndroid_id es el android_id del dispositivo que se ha logueado */ - + INSERT INTO deviceLog (userFK, nameApp, versionApp, android_id) VALUES(vWorkerFk, vAppName, vAppVersion, vAndroid_id); @@ -51402,12 +51406,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_exists`(vUserFk INT) BEGIN - + /* SELECT COUNT(*) AS UserExists - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu WHERE dpu.userFk = vUserFk;*/ SELECT TRUE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51456,14 +51460,14 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProduction_getnameDevice`(vAn BEGIN /** * Selecciona el id del dispositivo que corresponde al vAndroid_id - * - * @param vAndroid_id el número android_id del dispositivo - * + * + * @param vAndroid_id el número android_id del dispositivo + * */ - SELECT dp.id + SELECT dp.id FROM deviceProduction dp - WHERE dp.android_id = vAndroid_id; + WHERE dp.android_id = vAndroid_id; END ;; DELIMITER ; @@ -51483,10 +51487,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `device_checkLogin`(vUserFk INT, vAndroidID VARCHAR(50)) BEGIN - + /* * Comprueba si está registrado el dispositivo mediante su androidId - * + * * @param vUSerFk el id del user * @param vAndroidID es el identificador android_id del dispositivo */ @@ -51498,20 +51502,20 @@ BEGIN SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed FROM vn.deviceProductionConfig dpc; - IF NOT vIsAllUsersAllowed THEN - + IF NOT vIsAllUsersAllowed THEN + SELECT COUNT(*) INTO vIsDepartment - FROM vn.workerDepartment dp + FROM vn.workerDepartment dp JOIN department d ON d.id = dp.departmentFk WHERE dp.workerFk = vUserFk AND d.hasToCheckLogin; - + IF vIsDepartment THEN SELECT COUNT(*) INTO vIsAuthorized - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu JOIN vn.deviceProduction dp ON dp.id = dpu.deviceProductionFk WHERE dpu.userFk = vUserFk AND dp.android_id = vAndroidID; - + IF NOT vIsAuthorized THEN SET vMessage = 'Usuario no autorizado'; END IF; @@ -51541,15 +51545,15 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaEntryValueUpdate`(vDuaFk INT) BEGIN UPDATE duaEntry de - JOIN + JOIN ( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total FROM buy b JOIN duaEntry de ON de.entryFk = b.entryFk WHERE duaFk = vDuaFk GROUP BY b.entryFk ) sub ON sub.entryFk = de.entryFk - - LEFT JOIN + + LEFT JOIN (SELECT e.id, sum(iit.taxableBase) as euros FROM entry e JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk @@ -51557,11 +51561,11 @@ BEGIN WHERE de.duaFk = vDuaFk GROUP BY e.id ) sub2 ON sub2.id = de.entryFk - + SET de.value = sub.total, de.euroValue = sub2.euros WHERE duaFk = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51585,7 +51589,7 @@ BEGIN DECLARE vInvoiceFk INT; DECLARE vASIEN BIGINT DEFAULT 0; DECLARE vCounter INT DEFAULT 0; - + DECLARE rs CURSOR FOR SELECT e.invoiceInFk FROM entry e @@ -51598,7 +51602,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN rs; - + UPDATE invoiceIn ii JOIN entry e ON e.invoiceInFk = ii.id JOIN duaEntry de ON de.entryFk = e.id @@ -51610,41 +51614,41 @@ BEGIN ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), e.isConfirmed = TRUE WHERE d.id = vDuaFk; - + SELECT IFNULL(ASIEN,0) INTO vASIEN FROM dua WHERE id = vDuaFk; - + FETCH rs INTO vInvoiceFk; - + WHILE NOT done DO CALL invoiceInBookingMain(vInvoiceFk); - + IF vCounter > 0 OR vASIEN > 0 THEN - + UPDATE vn2008.XDiario x JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN SET x.ASIEN = vASIEN; - + ELSE - + SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; - + END IF; - + SET vCounter = vCounter + 1; - + FETCH rs INTO vInvoiceFk; END WHILE; - + CLOSE rs; - - UPDATE dua + + UPDATE dua SET ASIEN = vASIEN WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51670,9 +51674,9 @@ BEGIN SELECT awbFk,companyFk FROM dua WHERE id = vDuaFk; - + SELECT LAST_INSERT_ID() INTO vNewDuaFk; - + INSERT INTO duaEntry(duaFk, entryFk, value, customsValue) SELECT vNewDuaFk, entryFk, value, value - customsValue FROM duaEntry @@ -51701,29 +51705,29 @@ BEGIN DECLARE vBookDated DATE; DECLARE vDiff DECIMAL(10,2); DECLARE vApunte BIGINT; - + SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) INTO vBookNumber, vBookDated - FROM dua + FROM dua WHERE id = vDuaFk; - + IF vBookNumber IS NULL OR NOT vBookNumber THEN CALL ledger_next(vBookNumber); END IF; - + -- Apunte de la aduana INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONCEPTO, + CONCEPTO, EUROHABER, SERIE, empresa_id, CLAVE, FACTURA) - SELECT + SELECT vBookNumber, d.bookEntried, '4700000999', @@ -51736,20 +51740,20 @@ BEGIN FROM duaTax dt JOIN dua d ON d.id = dt.duaFk WHERE dt.duaFk = vDuaFk; - + -- Apuntes por tipo de IVA y proveedor - + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, FECHA_EX, FECHA_OP, @@ -51769,17 +51773,17 @@ BEGIN FECREGCON ) - SELECT + SELECT vBookNumber ASIEN, vBookDated FECHA, tr.account SUBCTA, '4330002067' CONTRA, sum(dt.tax) EURODEBE, - sum(dt.base) BASEEURO, + sum(dt.base) BASEEURO, CONCAT('DUA nº',d.code) CONCEPTO, d.id FACTURA, dt.rate IVA, - '*' AUXILIAR, + '*' AUXILIAR, 'D' SERIE, d.issued FECHA_EX, d.operated FECHA_OP, @@ -51806,10 +51810,10 @@ BEGIN WHERE ta.effectived <= vBookDated AND taxAreaFk = 'WORLD' ORDER BY ta.effectived DESC - LIMIT 10000000000000000000 + LIMIT 10000000000000000000 ) tba GROUP BY rate - ) tr ON tr.rate = dt.rate + ) tr ON tr.rate = dt.rate JOIN supplier s ON s.id = d.companyFk WHERE d.id = vDuaFk GROUP BY dt.rate; @@ -51817,16 +51821,16 @@ BEGIN SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte FROM XDiario WHERE ASIEN = vBookNumber; - + UPDATE XDiario SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA, - EURODEBE = EURODEBE - vDiff + EURODEBE = EURODEBE - vDiff WHERE id = vApunte; - + UPDATE dua SET ASIEN = vBookNumber WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51847,21 +51851,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTax_doRecalc`(vDuaFk INT) BEGIN /** * Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry - * + * * @param vDuaFk Id del dua a recalcular **/ DELETE FROM duaTax WHERE duaFk = vDuaFk; - - INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) + + INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) SELECT vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base FROM intrastat ist JOIN (SELECT - e.supplierFk, + e.supplierFk, i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) * di.amount/ tei.Base AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id @@ -51869,15 +51873,15 @@ BEGIN ( SELECT i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id WHERE de.duaFk = vDuaFk GROUP BY i.intrastatFk - + ) tei ON tei.intrastatFk = i.intrastatFk - JOIN + JOIN ( SELECT intrastatFk, sum(amount) as amount FROM duaIntrastat @@ -51886,7 +51890,7 @@ BEGIN ) di ON di.intrastatFk = i.intrastatFk WHERE de.duaFk = vDuaFk GROUP BY e.supplierFk, i.intrastatFk - HAVING Base + HAVING Base ) sub ON ist.id = sub.intrastatFk GROUP BY ist.taxClassFk, sub.supplierFk; END ;; @@ -51907,13 +51911,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ediTables_Update`() BEGIN - - INSERT IGNORE INTO vn.genus(name) + + INSERT IGNORE INTO vn.genus(name) SELECT latin_genus_name FROM edi.genus ; - INSERT IGNORE INTO vn.specie(name) - SELECT LCASE(latin_species_name) + INSERT IGNORE INTO vn.specie(name) + SELECT LCASE(latin_species_name) FROM edi.specie ; END ;; DELIMITER ; @@ -51953,71 +51957,71 @@ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cur1; read_loop: LOOP - + SET done = FALSE; SET vEntryFk = 0; - + FETCH cur1 INTO vId; - + IF done THEN LEAVE read_loop; END IF; - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk AND ea.supplierFk = e.supplierFk WHERE ea.id = vId AND tr.landed = vLanded LIMIT 1; - + IF NOT vEntryFk THEN - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded AND ea.supplierFk IS NULL LIMIT 1; - + END IF; - + IF NOT vEntryFk THEN - + SET vTravelFk = 0; - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded; - + IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) SELECT vLanded, vLanded, warehouseInFk, warehouseOutFk, agencyModeFk - FROM vn.ektEntryAssign + FROM vn.ektEntryAssign WHERE id = vId; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyFk WHERE ea.id = vId AND tr.landed = vLanded; - + END IF; - + INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk) SELECT vTravelFk, IFNULL(ea.supplierFk,s.id), c.id, cu.id FROM vn.supplier s @@ -52025,13 +52029,13 @@ OPEN cur1; JOIN vn.currency cu ON cu.code = 'EUR' JOIN vn.ektEntryAssign ea ON ea.id = vId WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - + END IF; - + UPDATE vn.ektEntryAssign SET entryFk = vEntryFk WHERE id = vId; @@ -52039,7 +52043,7 @@ OPEN cur1; END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52059,18 +52063,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `energyMeter_record`(vInput INT, vActiveTime INT) BEGIN DECLARE vConsumption INT; - + SELECT consumption INTO vConsumption FROM energyInput WHERE input = vInput; - INSERT INTO vn.energyMeter - SET - `input` = vInput, - `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), + INSERT INTO vn.energyMeter + SET + `input` = vInput, + `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), `activeTime` = vActiveTime, `consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2)) - ON DUPLICATE KEY UPDATE + ON DUPLICATE KEY UPDATE `activeTime` = `activeTime` + vActiveTime, `consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,2)); END ;; @@ -52093,28 +52097,28 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entryDelivered`(vDated DATE, vEntry BEGIN DECLARE vTravelFk INT; - + SELECT travelFk INTO vTravelFk - FROM vn.entry + FROM vn.entry WHERE id = vEntryFk; - + IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN - + UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated WHERE id = vTravelFk; - + ELSE - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, ref, isDelivered, isReceived) SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', vEntryFk), TRUE, TRUE FROM vn.travel WHERE id = vTravelFk; - + SELECT LAST_INSERT_ID() INTO vTravelFk; - - UPDATE vn.entry - SET travelFk = vTravelFk + + UPDATE vn.entry + SET travelFk = vTravelFk WHERE id = vEntryFk; - + END IF; END ;; @@ -52143,7 +52147,7 @@ BEGIN WHERE b.entryFk = vEntryFk; CALL vn.ticket_recalcComponents(vTicketFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52167,29 +52171,29 @@ BEGIN DECLARE vEntry INT; DECLARE vBucket VARCHAR(10); DECLARE vSupplierFk INT; - + SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 963); -- seleccionamos travel SELECT t.id, e.id INTO vTravel, vEntry FROM travel t LEFT JOIN entry e ON t.id = e.travelFk - WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse + WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse AND t.warehouseInFk = vLandingWarehouse AND t.agencyModeFk IS NULL AND e.supplierFk = vSupplierFk - LIMIT 1; - + LIMIT 1; + -- creamos el travel si es necesario IF IFNULL(vTravel, FALSE) = FALSE THEN INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk) VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse); SELECT LAST_INSERT_ID() INTO vTravel; END IF; - + -- creamos la Entrada si es necesario IF IFNULL(vEntry, FALSE) = FALSE THEN INSERT INTO entry (supplierFk, travelFk) VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL' SELECT LAST_INSERT_ID() INTO vEntry; END IF; - + -- creamos el cubo si es necesario SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; IF vBucket IS NULL THEN @@ -52199,7 +52203,7 @@ BEGIN SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; END IF; - INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) + INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) SELECT itemFk, quantity, vEntry, @@ -52502,7 +52506,7 @@ BEGIN -- Obtiene fecha de llegada y almacén entrante - SELECT landed, warehouseInFk INTO vLanded, vWarehouseFk + SELECT landed, warehouseInFk INTO vLanded, vWarehouseFk FROM vn.travel t JOIN vn.entry e ON t.id = e.travelFk WHERE e.id = vEntry; @@ -52515,13 +52519,13 @@ BEGIN SELECT * FROM ( SELECT * FROM - ( + ( SELECT rate0, rate1, rate2, rate3 FROM vn.rate WHERE dated <= vLanded AND warehouseFk = vWarehouseFk ORDER BY dated DESC - + ) sub UNION ALL SELECT rate0, rate1, rate2, rate3 @@ -52575,14 +52579,14 @@ BEGIN SET e.travelFk = vNewTravelFk, e.evaNotes = CONCAT('No impresas de: ', vSelf, ' ', IFNULL(e.evaNotes,'')) WHERE e.id = vNewEntryFk; - + IF vChangeEntry THEN UPDATE buy b SET b.entryFk = vNewEntryFk WHERE b.printedStickers = 0 AND b.entryFk = vSelf; END IF; - + INSERT INTO buy(entryFk, itemFk, quantity, @@ -52628,7 +52632,7 @@ BEGIN FROM buy b WHERE b.entryFk = vSelf AND b.printedStickers != b.stickers; - + IF vChangeEntry THEN UPDATE buy SET stickers = printedStickers, @@ -52640,7 +52644,7 @@ BEGIN FROM item i WHERE i.description = 'MISFIT' LIMIT 1; - + INSERT INTO buy(entryFk, itemFk, quantity, @@ -52715,11 +52719,11 @@ BEGIN description = CONCAT('Se ha creado la entrada ', vNewEntryFk,' transferida desde la ', vSelf), userFk = account.myUser_getId(), originFk = vNewEntryFk; - + UPDATE entry SET gestDocFk = (SELECT gestDocFk FROM entry WHERE id = vSelf LIMIT 1) WHERE id = vNewEntryFk; - + INSERT INTO duaEntry (duaFk, entryFk) SELECT duaFk, vNewEntryFk FROM duaEntry WHERE entryFk = vSelf LIMIT 1; END ;; @@ -52793,12 +52797,12 @@ BEGIN */ DECLARE v_done BOOL DEFAULT FALSE; DECLARE vEntryFk INTEGER; - + DECLARE vCur CURSOR FOR SELECT id FROM tmp.recalcEntryCommision; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; OPEN vCur; @@ -52809,7 +52813,7 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + CALL vn2008.buy_tarifas_entry(vEntryFk); END LOOP; @@ -52834,7 +52838,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitByShelving`(vShelvingFk BEGIN /** * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula - * + * * @param vShelvingFk Identificador de vn.shelving * @param vFromEntryFk Entrada origen * @param vToEntryFk Entrada destino @@ -52844,49 +52848,49 @@ BEGIN DECLARE buyStickers INT; DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE cur CURSOR FOR + DECLARE cur CURSOR FOR SELECT bb.id buyFk, FLOOR(ish.visible / ish.packing) AS ishStickers, bb.stickers buyStickers FROM vn.itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk AND bb.stickers >= FLOOR(ish.visible / ish.packing) WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci GROUP BY ish.id; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Cantidades de la matrícula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, + + -- Cantidades de la matrícula que exceden la de las entradas + SELECT ish.itemFk, + i.longName, FLOOR(ish.visible / ish.packing) AS etiEnMatricula, bb.stickers etiEnEntrada FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN vn.item i ON i.id = ish.itemFk + LEFT JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) GROUP BY ish.id; - + OPEN cur; read_loop: LOOP SET vDone = FALSE; - + FETCH cur INTO vBuyFk, ishStickers, buyStickers; - + IF vDone THEN LEAVE read_loop; END IF; - + IF ishStickers = buyStickers THEN UPDATE vn.buy SET entryFk = vToEntryFk @@ -52894,9 +52898,9 @@ BEGIN ELSE UPDATE vn.buy SET stickers = stickers - ishStickers, - quantity = stickers * packing + quantity = stickers * packing WHERE id = vBuyFk; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, @@ -52954,7 +52958,7 @@ BEGIN itemOriginalFk FROM vn.buy WHERE id = vBuyFk; - + END IF; END LOOP; @@ -52977,16 +52981,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitMisfit`(vSelf INT) BEGIN - + /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original * a la nueva */ - + DECLARE vNewEntryFk INT; DECLARE vBuyFk INT; SELECT MAX(b.id) INTO vBuyFk - FROM vn.buy b + FROM vn.buy b JOIN vn.item i ON i.id = b.itemFk WHERE b.entryFk = vSelf AND i.description = 'MISFIT'; @@ -52995,17 +52999,17 @@ BEGIN SELECT supplierFk, dated, CONCAT('E:',vSelf), travelFk, currencyFk, companyFk FROM vn.entry e WHERE e.id = vSelf; - - SET vNewEntryFk = LAST_INSERT_ID(); - UPDATE vn.buy b + SET vNewEntryFk = LAST_INSERT_ID(); + + UPDATE vn.buy b SET b.entryFk = vNewEntryFk WHERE b.entryFk = vSelf AND b.id > vBuyFk; - + SELECT vNewEntryFk; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53030,14 +53034,14 @@ BEGIN * @param vCurrency id del tipo de moneda(SAR,EUR,USD,GBP,JPY) */ CREATE OR REPLACE TEMPORARY TABLE tmp.recalcEntryCommision - SELECT e.id + SELECT e.id FROM vn.entry e JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse w ON w.id = t.warehouseInFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk WHERE t.shipped >= util.VN_CURDATE() AND e.currencyFk = vCurrency; - UPDATE vn.entry e + UPDATE vn.entry e JOIN tmp.recalcEntryCommision tmp ON tmp.id = e.id SET e.commission = currency_getCommission(vCurrency); @@ -53122,7 +53126,7 @@ BEGIN WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = vDepartment GROUP BY cd.workerFk; - + CREATE OR REPLACE TEMPORARY TABLE volume ENGINE = MEMORY SELECT SUM(w.volume) volume, @@ -53133,15 +53137,15 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE errorsByChecker ENGINE = MEMORY - SELECT sub1.workerFk, COUNT(id) errors + SELECT sub1.workerFk, COUNT(id) errors FROM ( SELECT st.workerFk, t.id FROM saleMistake sm JOIN saleTracking st ON sm.saleFk = st.saleFk JOIN `state` s2 ON s2.id = st.stateFk - JOIN sale s ON s.id = sm.saleFk - JOIN ticket t on t.id = s.ticketFk + JOIN sale s ON s.id = sm.saleFk + JOIN ticket t on t.id = s.ticketFk WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') GROUP BY s.ticketFk @@ -53153,13 +53157,13 @@ BEGIN SELECT COUNT(t.id) errors, e.workerFk FROM vn.expeditionMistake pm - JOIN vn.expedition e ON e.id = pm.expeditionFk + JOIN vn.expedition e ON e.id = pm.expeditionFk JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo GROUP BY e.workerFk; IF (vDepartment = 'Sacadores') THEN - + INSERT INTO errorProduction(userFk, firstname, lastname, @@ -53192,12 +53196,12 @@ BEGIN LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores FROM vn.collection c - JOIN vn.state s ON s.id = c.stateFk + JOIN vn.state s ON s.id = c.stateFk JOIN vn.train tn ON tn.id = c.trainFk - JOIN vn.worker w ON w.id = c.workerFk + JOIN vn.worker w ON w.id = c.workerFk WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id GROUP BY w.id; - + CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores ENGINE = MEMORY SELECT COUNT(c.ticketFk) errors, @@ -53217,7 +53221,7 @@ BEGIN JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk SET ep.error = ep.error + ipe.errors WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; - + DROP TEMPORARY TABLE itemPickerErrors; ELSE INSERT INTO errorProduction(userFk, @@ -53253,7 +53257,7 @@ BEGIN LEFT JOIN expeditionErrors pe ON pe.workerFk = t.workerFk GROUP BY w.id; END IF; - + DROP TEMPORARY TABLE total, errorsByClaim, volume, @@ -53279,7 +53283,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_addLauncher`() BEGIN DECLARE vDatedFrom DATETIME; DECLARE vDatedTo DATETIME; - + SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo; CALL vn.errorProduction_add('SACAR', vDatedFrom, vDatedTo); @@ -53310,7 +53314,7 @@ BEGIN DECLARE vRouteFk INT DEFAULT 0; SELECT t.routeFk INTO vRouteFk - FROM vn.expedition exp + FROM vn.expedition exp INNER JOIN ticket t on t.id = exp.ticketFk WHERE exp.id = vExpeditionFk; @@ -53513,14 +53517,14 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT) BEGIN /** - * Calls the report_print procedure and passes it + * Calls the report_print procedure and passes it * the necessary parameters for printing. * * @param vSelf expeditioPallet id. */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + SELECT w.labelerFk INTO vPrinterFk FROM worker w WHERE w.id = vUserFk; @@ -53587,22 +53591,22 @@ BEGIN DECLARE vTotal INT DEFAULT 0; IF vPalletFk = 0 THEN -- Nuevo pallet - - INSERT INTO vn.expeditionPallet(truckFk) + + INSERT INTO vn.expeditionPallet(truckFk) VALUES(vTruckFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END IF; - + SELECT COUNT(expeditionFk) INTO vTotal FROM vn.expeditionScan WHERE palletFk = vPalletFk; - + IF vTotal <> 0 THEN - SELECT expeditionFk, + SELECT expeditionFk, palletFk - FROM vn.expeditionScan + FROM vn.expeditionScan WHERE palletFk = vPalletFk; - ELSE + ELSE SELECT 0 expeditionFk,vPalletFk palletFk; END IF; END ;; @@ -53675,12 +53679,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT) BEGIN - - REPLACE vn.expeditionScan(expeditionFk, palletFk) + + REPLACE vn.expeditionScan(expeditionFk, palletFk) VALUES(vExpeditionFk, vPalletFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53699,32 +53703,32 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_add`(vParam INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro - * + * * @param vParam Identificador de vn.expedition o de vn.route * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT e.id, est.id FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.expeditionStateType est ON est.code = vStateCode WHERE t.routeFk = vParam; - + ELSE - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT vParam, est.id FROM vn.expeditionStateType est WHERE est.code = vStateCode; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53756,7 +53760,7 @@ BEGIN SELECT e.id, est.id FROM vn.expedition e JOIN vn.expeditionStateType est ON est.code = vStateCode - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk; END ;; @@ -53777,14 +53781,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vExpeditionFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT vExpeditionFk, est.id FROM vn.expeditionStateType est @@ -53810,7 +53814,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByPallet`(vPalle BEGIN /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vPalletFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ @@ -53827,7 +53831,7 @@ BEGIN IF NOT hasExpeditions THEN DROP TEMPORARY TABLE tExpeditionScan; - CALL util.throw('palletDoesNotExist'); + CALL util.throw('palletDoesNotExist'); END IF; INSERT INTO vn.expeditionState(expeditionFk, typeFk) @@ -53852,21 +53856,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState, por rutas - * + * * @param vRouteFk Identificador de vn.route * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT e.id, est.id FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.expeditionStateType est ON est.code = vStateCode WHERE t.routeFk = vRouteFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53908,8 +53912,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`() BEGIN - SELECT id truckFk, - ETD, + SELECT id truckFk, + ETD, description Destino FROM vn.expeditionTruck WHERE ETD BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -53953,7 +53957,7 @@ BEGIN JOIN address a ON t.addressFk = a.id JOIN route r ON r.id = t.routeFk LEFT JOIN warehouse w ON t.warehouseFk = w.id - LEFT JOIN (SELECT sub.ticketFk, + LEFT JOIN (SELECT sub.ticketFk, CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeConcat FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items FROM ticket t @@ -53984,7 +53988,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getState`(vExpeditionFk INT) BEGIN - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -53994,24 +53998,24 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -54025,17 +54029,17 @@ BEGIN vTicketsPendientes AS ticketsPendientes, vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54054,12 +54058,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_StateGet`(vExpeditionFk INT) BEGIN - + /* Devuelve una "ficha" con todos los datos relativos a la expedición - * - * param vExpeditionFk + * + * param vExpeditionFk */ - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -54070,34 +54074,34 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasLeidasSorter - FROM srt.expedition e + FROM srt.expedition e JOIN vn.expedition ve ON ve.id = e.id LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id - JOIN vn.ticket t ON t.id = ve.ticketFk + JOIN vn.ticket t ON t.id = ve.ticketFk WHERE t.routeFk = vRouteFk AND e.created != e.updated - AND ISNULL(es.expeditionFk); - - + AND ISNULL(es.expeditionFk); + + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -54112,17 +54116,17 @@ BEGIN vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas, vEtiquetasLeidasSorter AS etiquetasSorter - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54143,14 +54147,14 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `faultsReview`(vWarehouseFk INT) BEGIN DECLARE vCalcVisibleFk INT; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; - + CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT iss.itemFk, i.size, i.subName producer, @@ -54163,7 +54167,7 @@ BEGIN LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE iss.warehouseFk = vWarehouseFk GROUP BY iss.itemFk; - + SELECT ishr.*, sub.longName, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, CAST(sub.fault AS DECIMAL(10,0)) as faltas @@ -54178,7 +54182,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk ) sub ON sub.itemFk = ishr.itemFk ; - + END ;; DELIMITER ; @@ -54253,7 +54257,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE) BEGIN - + DECLARE vSijsnerClientFk INT DEFAULT 19752; DECLARE vDateStart DATETIME; @@ -54262,68 +54266,68 @@ BEGIN SET vDateStart = vFromDated; SET vDateEnd = util.Dayend(vToDated); - SELECT p.id FustCode, - CAST(sent.stucks AS DECIMAL(10,0)) FH, - CAST(tp.stucks AS DECIMAL(10,0)) Tickets, - CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, + SELECT p.id FustCode, + CAST(sent.stucks AS DECIMAL(10,0)) FH, + CAST(tp.stucks AS DECIMAL(10,0)) Tickets, + CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo FROM vn.packaging p LEFT JOIN ( SELECT FustCode, sum(fustQuantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - JOIN vn.packaging p ON p.id = b.packageFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.packaging p ON p.id = b.packageFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vDateStart AND vDateEnd AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA') sub + AND p.isPackageReturnable + AND c.country = 'FRANCIA') sub GROUP BY FustCode) sent ON sent.FustCode = p.id LEFT JOIN ( SELECT FustCode, sum(quantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vDateStart AND vDateEnd AND wa.name = 'VNH' - AND p.isPackageReturnable + AND p.isPackageReturnable AND c.country = 'FRANCIA' AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0) sub + AND tp.quantity > 0) sub GROUP BY FustCode) tp ON tp.FustCode = p.id LEFT JOIN ( SELECT FustCode, sum(quantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) AND wa.name = 'VNH' - AND p.isPackageReturnable - AND t.clientFk = vSijsnerClientFk) sub + AND p.isPackageReturnable + AND t.clientFk = vSijsnerClientFk) sub GROUP BY FustCode) sj ON sj.FustCode = p.id - WHERE sent.stucks + WHERE sent.stucks OR tp.stucks OR sj.stucks; @@ -54345,7 +54349,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControlDetail`(vFromDated DATE, vToDated DATE) BEGIN - + DECLARE vSijsnerClientFk INT DEFAULT 19752; DECLARE vDateStart DATETIME; @@ -54353,29 +54357,29 @@ BEGIN SET vDateStart = vFromDated; SET vDateEnd = util.Dayend(vToDated); - + SELECT a.nickname shopName, - a.city , - IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, + a.city , + IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity, tp.ticketFk, CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) AND wa.name = 'VNH' - AND p.isPackageReturnable + AND p.isPackageReturnable AND c.country = 'FRANCIA' AND t.clientFk != vSijsnerClientFk AND tp.quantity > 0; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54401,8 +54405,8 @@ DECLARE vTicketFk INT; DECLARE vSaleFk INT; DECLARE vClonTicket INT DEFAULT 0; -DECLARE cur1 CURSOR FOR -SELECT s.ticketFk, s.id +DECLARE cur1 CURSOR FOR +SELECT s.ticketFk, s.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.item i ON i.id = s.itemFk @@ -54418,17 +54422,17 @@ OPEN cur1; FETCH cur1 INTO vTicketFk, vSaleFk; WHILE done = 0 DO - + SELECT t.id INTO vClonTicket FROM vn.ticket t JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped) WHERE t.warehouseFk = 44 LIMIT 1; - + SELECT vTicketFk, vClonTicket; - + IF vClonTicket = 0 THEN - + INSERT INTO ticket ( clientFk, shipped, @@ -54456,12 +54460,12 @@ FETCH cur1 INTO vTicketFk, vSaleFk; zonePrice, zoneBonus, routeFk - + FROM ticket WHERE id = vTicketFk; SET vClonTicket = LAST_INSERT_ID(); - + SELECT 'lstID', vClonTicket; /* INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) @@ -54471,20 +54475,20 @@ FETCH cur1 INTO vTicketFk, vSaleFk; WHERE t.id = vClonTicket; */ INSERT INTO ticketLog - SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk); - + END IF; - + UPDATE vn.sale SET ticketFk = vClonTicket WHERE id = vSaleFk; SET vClonTicket = 0; - + SET done = 0; FETCH cur1 INTO vTicketFk, vSaleFk; - + END WHILE; CLOSE cur1; @@ -54509,8 +54513,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `getDayExpeditions`() BEGIN - SELECT - e.expeditions_id as expeditionFk, + SELECT + e.expeditions_id as expeditionFk, date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate, e.ticket_id as ticketFk, t.routeFk as routeFk @@ -54559,12 +54563,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `getItemUbication`(vItemFk VARCHAR(22)) BEGIN - + /* * @deprecated Utilizar itemShelving_getInfo - * + * */ - + CALL itemshelving_getInfo(vItemFk); END ;; @@ -54613,7 +54617,7 @@ BEGIN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated FROM vn.greugeConfig; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk) SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk FROM vn.greuge @@ -54646,8 +54650,8 @@ DECLARE done BOOL DEFAULT FALSE; DECLARE vTicketFk INT; DECLARE rs CURSOR FOR - SELECT id FROM vn.ticket - WHERE shipped = util.yesterday() + SELECT id FROM vn.ticket + WHERE shipped = util.yesterday() AND clientFk = 400 AND warehouseFk IN (1,44); @@ -54658,13 +54662,13 @@ OPEN rs; FETCH rs INTO vTicketFk; WHILE NOT done DO - + INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk) - SELECT t.shipped, - s.itemFk, - s.quantity, + SELECT t.shipped, + s.itemFk, + s.quantity, b.buyingValue + b.freightValue + b.packageValue + b.comissionValue, - t.warehouseFk, + t.warehouseFk, w.id FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -54675,7 +54679,7 @@ WHILE NOT done DO AND s.quantity > 0; FETCH rs INTO vTicketFk; - + END WHILE; @@ -54833,7 +54837,7 @@ proc: BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseInFk = vWh - AND tr.landed BETWEEN vDateLastInventory + AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday AND NOT isRaid GROUP BY b.itemFk; @@ -54888,7 +54892,7 @@ proc: BEGIN inv.price3 = b.price3, inv.minPrice = b.minPrice, inv.producer = p.name; - + INSERT INTO buy( itemFk, quantity, buyingValue, @@ -54922,15 +54926,15 @@ proc: BEGIN FROM tmp.inventory; SELECT vWh, count(*), util.VN_NOW() FROM tmp.inventory; - + -- Actualizamos el campo lastUsed de vn.item UPDATE vn.item i JOIN tmp.inventory i2 ON i2.itemFk = i.id SET i.lastUsed = util.VN_NOW() WHERE i2.quantity; - + -- DROP TEMPORARY TABLE tmp.inventory; - + END LOOP; CLOSE cWarehouses; @@ -54944,11 +54948,11 @@ proc: BEGIN SELECT e.id as entryId, t.id as travelId FROM vn.travel t - JOIN vn.entry e ON e.travelFk = t.id + JOIN vn.entry e ON e.travelFk = t.id WHERE e.supplierFk = 4 AND t.shipped <= TIMESTAMPADD(DAY, -2, TIMESTAMPADD(DAY, -10, util.VN_CURDATE())) AND (DAY(t.shipped) <> 1 OR shipped < TIMESTAMPADD(MONTH, -12, util.VN_CURDATE())); - + DELETE e FROM vn.entry e JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; @@ -55010,7 +55014,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -55024,20 +55028,20 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + RIGHT JOIN (entry e LEFT JOIN supplier s ON s.id = e.supplierFk RIGHT JOIN buy b ON b.entryFk = e.id LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN travel tr ON tr.id = e.travelFk LEFT JOIN warehouse w ON w.id = tr.warehouseInFk LEFT JOIN origin o ON o.id = i.originFk ) ON it.id = i.typeFk LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE (b.packageFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; - CREATE TEMPORARY TABLE tmp.lastEntryOk + CREATE TEMPORARY TABLE tmp.lastEntryOk (PRIMARY KEY (buyFk)) SELECT i.id AS itemFk, @@ -55047,7 +55051,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -55061,11 +55065,11 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + RIGHT JOIN (entry e LEFT JOIN supplier s ON s.id = e.supplierFk RIGHT JOIN buy b ON b.entryFk = e.id LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN travel tr ON tr.id = e.travelFk LEFT JOIN warehouse w ON w.id = tr.warehouseInFk LEFT JOIN origin o ON o.id = i.originFk @@ -55073,34 +55077,34 @@ BEGIN LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE b.packageFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) ORDER BY tr.landed DESC; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; - CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup (INDEX (warehouseFk,itemFk)) SELECT * FROM tmp.lastEntryOk tmp GROUP BY tmp.itemFk,tmp.warehouseFk; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packageFk = eo.packageFk WHERE b.packageFk = "--"; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.price2 = eo.price2 WHERE b.price2 = 0 ; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packing = eo.packing WHERE b.packing = 0; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; - + DROP TEMPORARY TABLE tmp.lastEntry; DROP TEMPORARY TABLE tmp.lastEntryOk; DROP TEMPORARY TABLE tmp.lastEntryOkGroup; @@ -55138,7 +55142,7 @@ BEGIN JOIN item i ON i.id = s.itemFk GROUP BY i.expenceFk HAVING amount != 0; - + INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount) SELECT vInvoice, tst.expenceFk, @@ -55146,7 +55150,7 @@ BEGIN FROM ticketToInvoice t JOIN ticketService ts ON ts.ticketFk = t.id JOIN ticketServiceType tst ON tst.id = ts.ticketServiceTypeFk - HAVING amount != 0; + HAVING amount != 0; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55164,19 +55168,19 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromAddress`(vMaxTicketDate DATETIME,vAddress INT,vCompany INT) -BEGIN +BEGIN DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()); - + SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate); - + DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; - + CREATE TEMPORARY TABLE `ticketToInvoice` (PRIMARY KEY (`id`)) ENGINE = MEMORY SELECT Id_Ticket id FROM vn2008.Tickets WHERE (Fecha BETWEEN vMinDateTicket - AND vMaxTicketDate) AND Id_Consigna = vAddress + AND vMaxTicketDate) AND Id_Consigna = vAddress AND Factura IS NULL AND empresa_id = vCompany; END ;; @@ -55196,12 +55200,12 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromClient`( - IN vMaxTicketDate datetime, - IN vClientFk INT, + IN vMaxTicketDate datetime, + IN vClientFk INT, IN vCompanyFk INT) BEGIN DECLARE vMinTicketDate DATE; - + SET vMinTicketDate = util.firstDayOfYear(vMaxTicketDate - INTERVAL 1 YEAR); SET vMaxTicketDate = util.dayend(vMaxTicketDate); @@ -55231,10 +55235,10 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromTicket`(IN vTicket INT) -BEGIN +BEGIN DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; - + CREATE TEMPORARY TABLE `ticketToInvoice` (PRIMARY KEY (`id`)) ENGINE = MEMORY @@ -55263,10 +55267,10 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS newInvoiceIn; CREATE TEMPORARY TABLE newInvoiceIn - SELECT + SELECT i.*, YEAR(i.booked) datedYear, - CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, + CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, (cc.id = c.id) isSameCountry, cit.id invoicesCount FROM invoiceIn i @@ -55279,7 +55283,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS newSupplier; CREATE TEMPORARY TABLE newSupplier - SELECT + SELECT s.*, REPLACE(s.account,' ','') supplierAccount, IF(c.CEE < 2, TRUE, FALSE) isUeeMember @@ -55292,11 +55296,11 @@ BEGIN CALL util.throw('INACTIVE_PROVIDER'); END IF; - SELECT IFNULL(MAX(i.serialNumber) + 1,1) + SELECT IFNULL(MAX(i.serialNumber) + 1,1) INTO vSerialNumber FROM invoiceIn i JOIN newInvoiceIn n - WHERE i.serial LIKE n.serial + WHERE i.serial LIKE n.serial AND YEAR(i.booked) = n.datedYear AND i.companyFk = n.companyFk GROUP BY i.companyFk; @@ -55325,7 +55329,7 @@ BEGIN CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber); - SELECT SUM(iit.taxableBase * IF( i.serial= 'R' AND ti.Iva <> 'HP DEVENGADO 21 ISP', 1 +(ti.PorcentajeIva/100),1)), + SELECT SUM(iit.taxableBase * IF( i.serial= 'R' AND ti.Iva <> 'HP DEVENGADO 21 ISP', 1 +(ti.PorcentajeIva/100),1)), SUM(iit.foreignValue * IF( i.serial= 'R', 1 + (ti.PorcentajeIva/100),1)), iit.taxableBase/iit.foreignValue INTO vTotalAmount, vTotalAmountDivisa, vRate @@ -55348,7 +55352,7 @@ BEGIN CLAVE, empresa_id ) - SELECT + SELECT vBookNumber, n.bookEntried, s.supplierAccount, @@ -55359,7 +55363,7 @@ BEGIN n.invoicesCount, vInvoiceInId, n.companyFk - FROM newInvoiceIn n + FROM newInvoiceIn n JOIN newSupplier s; -- Línea de Gastos @@ -55369,7 +55373,7 @@ BEGIN CONTRA, EURODEBE, EUROHABER, - CONCEPTO, + CONCEPTO, CAMBIO, DEBEME, HABERME, @@ -55389,7 +55393,7 @@ BEGIN n.invoicesCount NFACTICK, n.companyFk empresa_id FROM newInvoiceIn n - JOIN newSupplier s + JOIN newSupplier s JOIN invoiceInTax iit ON iit.invoiceInFk = n.id JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = iit.expenceFk WHERE e.name != 'Suplidos Transitarios nacionales' @@ -55400,13 +55404,13 @@ BEGIN INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -55455,34 +55459,34 @@ BEGIN n.booked FECREGCON, n.companyFk FROM newInvoiceIn n - JOIN newSupplier s + JOIN newSupplier s JOIN invoiceInTax it ON n.id = it.invoiceInFk JOIN sage.TiposIva ti ON ti.CodigoIva = it.taxTypeSageFk JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = it.transactionTypeSageFk JOIN invoiceInSerial iis ON iis.code = n.serial JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = it.expenceFk LEFT JOIN ( - SELECT eWithheld.id - FROM invoiceInTax hold - JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld + SELECT eWithheld.id + FROM invoiceInTax hold + JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld WHERE hold.invoiceInFk = vInvoiceInId LIMIT 1 - ) eWithheld ON TRUE - WHERE it.taxTypeSageFk IS NOT NULL + ) eWithheld ON TRUE + WHERE it.taxTypeSageFk IS NOT NULL AND it.taxTypeSageFk NOT IN (22, 90) GROUP BY ti.PorcentajeIva, e.id; -- Línea iva inversor sujeto pasivo - + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -55528,37 +55532,37 @@ BEGIN s.nif AS TERNIF, s.name AS TERNOM, n.companyFk - FROM newInvoiceIn n - JOIN newSupplier s + FROM newInvoiceIn n + JOIN newSupplier s JOIN invoiceInTax it ON n.id = it.invoiceInFk JOIN sage.TiposIva ti ON ti.CodigoIva = it.taxTypeSageFk JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = it.transactionTypeSageFk - JOIN invoiceInSerial iis ON iis.code = n.serial + JOIN invoiceInSerial iis ON iis.code = n.serial JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = it.expenceFk WHERE ti.Iva = 'HP DEVENGADO 21 ISP' OR MID(s.account, 4, 1) = '1' GROUP BY ti.PorcentajeIva, e.id; - - -- Actualización del registro original + + -- Actualización del registro original UPDATE invoiceIn ii JOIN newInvoiceIn ni ON ii.id = ni.id SET ii.serialNumber = vSerialNumber, ii.isBooked = TRUE; - + -- Problemas derivados de la precisión en los decimales al calcular los impuestos - UPDATE XDiario - SET EURODEBE = EURODEBE - + UPDATE XDiario + SET EURODEBE = EURODEBE - (SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0) FROM( - SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference + SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference FROM XDiario WHERE ASIEN = vBookNumber )sub ) - WHERE ASIEN = vBookNumber + WHERE ASIEN = vBookNumber AND EURODEBE <> 0 ORDER BY id DESC LIMIT 1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55579,39 +55583,39 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(vInvoice BEGIN IF !(SELECT COUNT(*) - FROM invoiceInDueDay iid + FROM invoiceInDueDay iid WHERE iid.invoiceInFk = vInvoiceInFk) THEN - INSERT INTO invoiceInDueDay (invoiceInFk, - dueDated, - amount, - foreignValue) + INSERT INTO invoiceInDueDay (invoiceInFk, + dueDated, + amount, + foreignValue) SELECT vInvoiceInFk, - IF(payDay, + IF(payDay, IF(vn.getNextDueDate(issued, detail, payDay) < DATE_ADD(created, INTERVAL 2 DAY), DATE_ADD(created, INTERVAL 2 DAY), - vn.getNextDueDate(issued, detail, payDay)), + vn.getNextDueDate(issued, detail, payDay)), GREATEST(TIMESTAMPADD(DAY, 2, created), TIMESTAMPADD(DAY, detail, issued))), - IF((@cont:=@cont + 1) < cont, TRUNCATE(venc / cont, 2),venc-(TRUNCATE(venc / cont, 2) * (cont - 1))), - IF(@cont < cont, TRUNCATE(foreignValue / cont, 2), foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) - FROM ( SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100)*(s.countryFk = s2.countryFk)) * iit.taxableBase)/COUNT(DISTINCT(pdd.detail)) venc, + IF((@cont:=@cont + 1) < cont, TRUNCATE(venc / cont, 2),venc-(TRUNCATE(venc / cont, 2) * (cont - 1))), + IF(@cont < cont, TRUNCATE(foreignValue / cont, 2), foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) + FROM ( SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100)*(s.countryFk = s2.countryFk)) * iit.taxableBase)/COUNT(DISTINCT(pdd.detail)) venc, SUM(iit.foreignValue)/COUNT(DISTINCT(pdd.detail)) foreignValue, - s.payDemFk, + s.payDemFk, ii.companyFk, COUNT(DISTINCT(pdd.detail)) cont, s.payDay, ii.issued, DATE(ii.created) created - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - LEFT JOIN sage.TiposIva AS ti ON ti.CodigoIva= iit.taxTypeSageFk - JOIN supplier s ON s.id = ii.supplierFk - JOIN supplier s2 ON s2.id = ii.companyFk - JOIN vn.payDemDetail pdd ON pdd.id = s.payDemFk - WHERE ii.id = vInvoiceInFk + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN sage.TiposIva AS ti ON ti.CodigoIva= iit.taxTypeSageFk + JOIN supplier s ON s.id = ii.supplierFk + JOIN supplier s2 ON s2.id = ii.companyFk + JOIN vn.payDemDetail pdd ON pdd.id = s.payDemFk + WHERE ii.id = vInvoiceInFk GROUP BY ii.id ) sub - JOIN (SELECT @cont:=0) sub2 + JOIN (SELECT @cont:=0) sub2 JOIN vn.payDemDetail pdd ON pdd.id = sub.payDemFk GROUP BY detail; END IF; @@ -55637,9 +55641,9 @@ BEGIN DELETE FROM invoiceInDueDay WHERE invoiceInFk = vInvoiceInFk; - + CALL invoiceInDueDay_calculate(vInvoiceInFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55678,7 +55682,7 @@ BEGIN CALL vn2008.recibidaIvaInsert(vInvoiceInFk); CALL vn2008.recibidaVencimientoReplace(vInvoiceInFk); - + FETCH rs INTO vInvoiceInFk; END WHILE; @@ -55723,7 +55727,7 @@ BEGIN CALL invoiceInTax_getFromEntries(vInvoiceInFk); CALL invoiceInDueDay_calculate(vInvoiceInFk); - + FETCH rs INTO vInvoiceInFk; END WHILE; @@ -55755,7 +55759,7 @@ BEGIN SELECT MAX(rr.dated) INTO vDated FROM referenceRate rr JOIN invoiceIn ii ON ii.id = vId - WHERE rr.dated <= ii.issued + WHERE rr.dated <= ii.issued AND rr.currencyFk = ii.currencyFk ; IF vDated THEN @@ -55764,13 +55768,13 @@ BEGIN WHERE dated = vDated; END IF; - SELECT id INTO vExpenceFk - FROM vn.expence - WHERE `name` = 'Adquisición mercancia Extracomunitaria' - GROUP BY id + SELECT id INTO vExpenceFk + FROM vn.expence + WHERE `name` = 'Adquisición mercancia Extracomunitaria' + GROUP BY id LIMIT 1; - - DELETE FROM invoiceInTax + + DELETE FROM invoiceInTax WHERE invoiceInFk = vId; INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) @@ -55784,9 +55788,9 @@ BEGIN JOIN entry e ON e.invoiceInFk = ii.id JOIN supplier s ON s.id = e.supplierFk JOIN buy b ON b.entryFk = e.id - LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk + LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk AND rr.dated = ii.issued - WHERE ii.id = vId + WHERE ii.id = vId HAVING taxableBase IS NOT NULL; END ;; DELIMITER ; @@ -55817,15 +55821,15 @@ BEGIN DECLARE vCountry INT; DECLARE vTaxArea VARCHAR(15); DECLARE vSpainCountryCode INT DEFAULT 1; - + SELECT id INTO vInvoiceFk - FROM invoiceOut + FROM invoiceOut WHERE ref = vInvoiceRef; - - UPDATE invoiceOut + + UPDATE invoiceOut SET hasPdf = 0 WHERE id = vInvoiceFk; - + SELECT s.countryFk INTO vCountry FROM supplier s JOIN invoiceOut io ON io.companyFk = s.id @@ -55834,30 +55838,30 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS ticketToInvoice; CREATE TEMPORARY TABLE ticketToInvoice - SELECT id - FROM ticket + SELECT id + FROM ticket WHERE refFk = vInvoiceRef; CALL invoiceExpenceMake(vInvoiceFk); - + CALL invoiceTaxMake(vInvoiceFk,vTaxArea); - + UPDATE invoiceOut io JOIN ( SELECT SUM(amount) AS total - FROM invoiceOutExpence + FROM invoiceOutExpence WHERE invoiceOutFk = vInvoiceFk ) base JOIN ( SELECT SUM(vat) AS total - FROM invoiceOutTax + FROM invoiceOutTax WHERE invoiceOutFk = vInvoiceFk ) vat SET io.amount = base.total + vat.total WHERE io.id = vInvoiceFk; - + CALL vn.invoiceOutBooking(vInvoiceFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55902,7 +55906,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS rs; CREATE TEMPORARY TABLE rs - SELECT + SELECT c.accountingAccount AS clientBookingAccount, io.amount as totalAmount, CONCAT('n/fra ', io.ref) as simpleConcept, @@ -55936,19 +55940,19 @@ BEGIN WHERE io.id = vInvoice; CALL vn.ledger_next(vBookNumber); - + -- Linea del cliente INSERT INTO XDiario( ASIEN, FECHA, - SUBCTA, + SUBCTA, EURODEBE, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, rs.clientBookingAccount AS SUBCTA, @@ -55964,14 +55968,14 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, ioe.expenceFk AS SUBCTA, @@ -55985,8 +55989,8 @@ BEGIN JOIN invoiceOutExpence ioe WHERE ioe.invoiceOutFk = vInvoice; - SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenceConcept FROM expence e JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id WHERE ioe.invoiceOutFk = vInvoice; @@ -55996,7 +56000,7 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, CONCEPTO, @@ -56024,7 +56028,7 @@ BEGIN TIPORECTIF, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, iot.pgcFk AS SUBCTA, @@ -56044,11 +56048,11 @@ BEGIN rs.FECHA_OP, rs.FECHA_EX, rs.TIPOOPE, - rs.NFACTICK, + rs.NFACTICK, rs.TERIDNIF, rs.TERNIF, rs.TERNOM, - pgc.mod340 AS L340, + pgc.mod340 AS L340, pgc.cplusTrascendency477Fk AS TIPOCLAVE, pgc.cplusTaxBreakFk as TIPOEXENCI, rs.TIPONOSUJE, @@ -56056,13 +56060,13 @@ BEGIN rs.TIPORECTIF, rs.companyFk AS empresa_id FROM rs - JOIN invoiceOutTax iot + JOIN invoiceOutTax iot JOIN pgc ON pgc.code = iot.pgcFk LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk -- --------------- Comprueba si la linea es de iva con rec.equiv. asociado - LEFT JOIN pgc pgce ON pgce.code = pe.equFk + LEFT JOIN pgc pgce ON pgce.code = pe.equFk LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv. WHERE iot.invoiceOutFk = vInvoice; - + UPDATE invoiceOut SET booked = util.VN_CURDATE() WHERE id = vInvoice; @@ -56094,7 +56098,7 @@ BEGIN DECLARE done BOOL DEFAULT FALSE; - DECLARE rs CURSOR FOR + DECLARE rs CURSOR FOR SELECT io.id FROM invoiceOut io WHERE RIGHT(ref,7) BETWEEN 1724215 AND 1724224 @@ -56109,15 +56113,15 @@ BEGIN WHILE NOT done DO CALL invoiceOutBooking(vInvoice); - + FETCH rs INTO vInvoice ; - + SET vContador = vContador + 1; - + IF vContador MOD 50 = 0 THEN - + SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - + END IF; END WHILE; @@ -56147,14 +56151,14 @@ BEGIN DECLARE vAsien INTEGER; DECLARE vSendMail BOOL; DECLARE vBody TEXT; - + SELECT ASIEN INTO vAsien - FROM XDiario + FROM XDiario WHERE SERIE = SUBSTRING(vRef, 1, 1) AND FACTURA = SUBSTRING(vRef, 2, LENGTH(vRef)-1) LIMIT 1; - SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), + SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), CONCAT( '
FECHA | @@ -56163,7 +56167,7 @@ BEGINCONCEPTO | EURODEBE | EUROHABER | -
', IFNULL(FECHA,''), ' | @@ -56176,14 +56180,14 @@ BEGIN ) SEPARATOR ' ' ), '
C.Postal | @@ -77066,39 +77070,39 @@ BEGINAlmacén | Salix |
---|