From 0827b998a1f5dc2fe07c09c3fbabbfde36aae073 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Mon, 23 Dec 2019 15:15:58 +0100 Subject: [PATCH] update structure sql --- .../00-catalog_componentCalculate.sql | 254 + .../00-manaSpellersRequery.sql | 70 + db/dump/structure.sql | 6776 ++++------------- db/export-structure.sh | 1 - .../back/methods/client/updateFiscalData.js | 1 - modules/worker/back/models/worker-mana.json | 2 +- 6 files changed, 1984 insertions(+), 5120 deletions(-) create mode 100644 db/changes/10130-christmas/00-catalog_componentCalculate.sql create mode 100644 db/changes/10130-christmas/00-manaSpellersRequery.sql diff --git a/db/changes/10130-christmas/00-catalog_componentCalculate.sql b/db/changes/10130-christmas/00-catalog_componentCalculate.sql new file mode 100644 index 000000000..6eb30bbfd --- /dev/null +++ b/db/changes/10130-christmas/00-catalog_componentCalculate.sql @@ -0,0 +1,254 @@ +DROP procedure IF EXISTS `vn`.`catalog_componentCalculate`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_componentCalculate`( + vZoneFk INT, + vAddressFk INT, + vShipped DATE) +proc: BEGIN +/** + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAgencyModeFk Id del modo de agencia + * @param tmp.ticketLot (warehouseFk,available,itemFk,buyFk) + * + * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, + * packing, grouping, groupingMode, buyFk, typeFk) + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) + */ + DECLARE vClientFk INT; + DECLARE vGeneralInflationCoefficient INT DEFAULT 1; + DECLARE vMinimumDensityWeight INT DEFAULT 167; + DECLARE vBoxFreightItem INT DEFAULT 71; + DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; + DECLARE vSpecialPriceComponent INT DEFAULT 10; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vRecoveryComponent INT DEFAULT 17; + DECLARE vSellByPacketComponent INT DEFAULT 22; + DECLARE vBuyValueComponent INT DEFAULT 28; + DECLARE vMarginComponent INT DEFAULT 29; + DECLARE vDiscountLastItemComponent INT DEFAULT 32; + DECLARE vExtraBaggedComponent INT DEFAULT 38; + DECLARE vManaAutoComponent INT DEFAULT 39; + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SET @rate2 := 0; + SET @rate3 := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, tl.warehouseFk, tl.available, + IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, + IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, + IFNULL(pf.rate3, 0) AS minPrice, + IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk + FROM priceFixed pf + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) + WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vBuyValueComponent, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vMarginComponent, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk + WHERE cr.recobro > 0.009; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + WHERE wm.isPricesModifierActivated + HAVING manaAuto <> 0; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, + tcb.itemFk, + cr.id, + GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN componentRate cr + 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 + WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * r.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((z.price - z.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk + AND r.Id_Article = tcc.itemFk + HAVING cost <> 0; + + IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + WHERE ap.addressFk = vAddressFk; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + vSpecialPriceComponent, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN componentRate cr ON cr.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE cr.classRate IS NULL + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate + FROM tmp.ticketComponent tc + JOIN componentRate cr ON cr.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + 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 + AND tcs.warehouseFk = tcc.warehouseFk + 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; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10130-christmas/00-manaSpellersRequery.sql b/db/changes/10130-christmas/00-manaSpellersRequery.sql new file mode 100644 index 000000000..cc185fdba --- /dev/null +++ b/db/changes/10130-christmas/00-manaSpellersRequery.sql @@ -0,0 +1,70 @@ + +DROP procedure IF EXISTS `vn`.`manaSpellersRequery`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`manaSpellersRequery`(vWorkerFk INTEGER) +BEGIN + + DECLARE vWorkerIsExcluded BOOLEAN; + DECLARE vFromDated DATE; + DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,CURDATE()); + DECLARE vMana INT; + DECLARE vAutoMana INT; + DECLARE vManaBank INT; + DECLARE vManaGreugeType INT; + + SELECT id INTO vMana + FROM `component` WHERE code = 'mana'; + + SELECT id INTO vAutoMana + FROM `component` WHERE code = 'autoMana'; + + SELECT id INTO vManaBank + FROM `bank` WHERE code = 'mana'; + + SELECT id INTO vManaGreugeType + FROM `greugeType` WHERE code = 'mana'; + + SELECT COUNT(*) INTO vWorkerIsExcluded + FROM workerManaExcluded + WHERE workerFk = vWorkerFk; + + IF NOT vWorkerIsExcluded THEN + + SELECT max(dated) INTO vFromDated + FROM clientManaCache; + + REPLACE workerMana (workerFk, amount) + SELECT vWorkerFk, sum(mana) FROM + ( + SELECT s.quantity * sc.value as mana + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN client c ON c.id = a.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN saleComponent sc ON sc.saleFk = s.id + WHERE c.salesPersonFk = vWorkerFk AND sc.componentFk IN (vMana, vAutoMana) + AND t.shipped > vFromDated AND t.shipped < vToDated + UNION ALL + SELECT - r.amountPaid + FROM receipt r + JOIN client c ON c.id = r.clientFk + WHERE c.salesPersonFk = vWorkerFk AND bankFk = vManaBank + AND payed > vFromDated + UNION ALL + SELECT g.amount + FROM greuge g + JOIN client c ON c.id = g.clientFk + WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType + AND g.shipped > vFromDated and g.shipped < CURDATE() + UNION ALL + SELECT cc.mana + FROM clientManaCache cc + JOIN client c ON c.id = cc.clientFk + WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated + ) sub; + END IF; +END$$ + +DELIMITER ; + diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 901153a58..c56b2a0a1 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -2919,55 +2919,55 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - tp.Tipo AS Familia, - r.reino AS Reino, - tr.CodigoTrabajador AS Comercial, - tr2.CodigoTrabajador AS Comprador, - p.name AS Provincia, - w.name AS almacen, - tm.year AS Año, - tm.month AS Mes, - tm.week AS Semana, - v.vista AS Vista, - bt.importe AS Importe - FROM bs.ventas bt - LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador - LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador - JOIN vn2008.time tm ON tm.date = bt.fecha - JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento - LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista - LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna - LEFT JOIN vn2008.province p ON p.province_id = cs.province_id - LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE bt.fecha >= vLastMonth AND r.mercancia; +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + tp.Tipo AS Familia, + r.reino AS Reino, + tr.CodigoTrabajador AS Comercial, + tr2.CodigoTrabajador AS Comprador, + p.name AS Provincia, + w.name AS almacen, + tm.year AS Año, + tm.month AS Mes, + tm.week AS Semana, + v.vista AS Vista, + bt.importe AS Importe + FROM bs.ventas bt + LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id + LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id + LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador + LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador + JOIN vn2008.time tm ON tm.date = bt.fecha + JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento + LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia + LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista + LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna + LEFT JOIN vn2008.province p ON p.province_id = cs.province_id + LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id + WHERE bt.fecha >= vLastMonth AND r.mercancia; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2985,33 +2985,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `call_add`() -BEGIN - DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; - - -- Seleccionamos la ultima fecha introducida - SELECT MAX(Fecha) INTO datSTART FROM `call`; - - -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos - DELETE FROM `call` WHERE Fecha = datSTART; - - INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) - SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, - dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone - FROM ( - SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, - hour(calldate) as Hora,src as phone - FROM vn2008.Trabajadores T - JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') - WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration - UNION ALL - SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst - FROM vn2008.Trabajadores T - JOIN vn2008.cdr C ON C.src = T.extension - WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration - ) ll - JOIN vn2008.Permisos USING(Id_Trabajador) - LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone - WHERE Id_Grupo = 6; +BEGIN + DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; + + -- Seleccionamos la ultima fecha introducida + SELECT MAX(Fecha) INTO datSTART FROM `call`; + + -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos + DELETE FROM `call` WHERE Fecha = datSTART; + + INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) + SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, + dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone + FROM ( + SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, + hour(calldate) as Hora,src as phone + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') + WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration + UNION ALL + SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.src = T.extension + WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration + ) ll + JOIN vn2008.Permisos USING(Id_Trabajador) + LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone + WHERE Id_Grupo = 6; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3029,205 +3029,205 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `claim_ratio_routine`() -BEGIN - DECLARE vMonthToRefund INT DEFAULT 4; - - /* - * PAK 2015-11-20 - * Se trata de añadir a la tabla Greuges todos los - * cargos que luego vamos a utilizar para calcular el recobro - */ - - -- descuentos comerciales COD 11 - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) - SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * - Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01' - HAVING nz(Importe) <> 0; - - DELETE mc.* - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - - INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - - UPDATE vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - SET Concepte = CONCAT('$ ',Concepte) - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01'; - - -- Reclamaciones demasiado sensibles - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe, Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim ',cm.id,' : ', m.Concepte) - ,round( -1 * ((sensib -1)/4) * Cantidad * - Preu * (100 - Descuento) / 100, 2) AS Reclamaciones - , 4 - , m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Reclamaciones que pasan a Maná - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe , Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim_mana ',cm.id,' : ', m.Concepte) - ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) - AS Reclamaciones - ,3 - ,m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3 - AND cm.mana; - - -- Marcamos para no repetir - UPDATE vn2008.cl_act ca - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - SET greuge = 1 - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Recobros - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT DISTINCT t.Id_Ticket - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN vn2008.state s ON s.id = i.state_id - WHERE mc.Id_Componente = 17 - AND mc.greuge = 0 - AND t.Fecha >= '2016-10-01' - AND t.Fecha < CURDATE() - AND s.alert_level >= 3; - - DELETE g.* - FROM vn2008.Greuges g - JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket - WHERE Greuges_type_id = 2; - - INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, - Greuges_type_id, Id_Ticket) - SELECT Id_Cliente - ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) - AS dif - ,date(t.Fecha) - , 2 - ,tt.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc - ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 - GROUP BY t.Id_Ticket - HAVING ABS(dif) > 1; - - UPDATE vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket - SET greuge = 1 - WHERE Id_Componente = 17; - - /* - * Recalculamos la ratio de las reclamaciones, que luego - * se va a utilizar en el recobro - */ - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT Id_Cliente, 0,0,0,0 - FROM vn2008.Clientes; - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * - Cantidad * Preu * (100 - Descuento) / 100)) - AS Reclamaciones - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca - ON ca.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND cm.cl_est_id = 3 - AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) - GROUP BY cm.Id_Cliente - ) claims ON claims.Id_Cliente = fm.Id_Cliente; - - - -- Calculamos el porcentaje del recobro para añadirlo al precio de venta - UPDATE bi.claims_ratio cr - JOIN ( - SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge - FROM vn2008.Greuges - WHERE Fecha <= CURDATE() - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(nz(Greuge) / - (nz(Consumo) * vMonthToRefund / 12 ) ,3)); - - -- Protección neonatos - UPDATE bi.claims_ratio cr - JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente - SET recobro = 0, Ratio = 0 - WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,CURDATE()); - - -- CLIENTE 7983, JULIAN SUAU - UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; - - -- CLIENTE 4358 - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; - - -- CLIENTE 5523, VERDECORA +BEGIN + DECLARE vMonthToRefund INT DEFAULT 4; + + /* + * PAK 2015-11-20 + * Se trata de añadir a la tabla Greuges todos los + * cargos que luego vamos a utilizar para calcular el recobro + */ + + -- descuentos comerciales COD 11 + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) + SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * + Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01' + HAVING nz(Importe) <> 0; + + DELETE mc.* + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) + SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + UPDATE vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + SET Concepte = CONCAT('$ ',Concepte) + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01'; + + -- Reclamaciones demasiado sensibles + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe, Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim ',cm.id,' : ', m.Concepte) + ,round( -1 * ((sensib -1)/4) * Cantidad * + Preu * (100 - Descuento) / 100, 2) AS Reclamaciones + , 4 + , m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Reclamaciones que pasan a Maná + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe , Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim_mana ',cm.id,' : ', m.Concepte) + ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) + AS Reclamaciones + ,3 + ,m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3 + AND cm.mana; + + -- Marcamos para no repetir + UPDATE vn2008.cl_act ca + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + SET greuge = 1 + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Recobros + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT DISTINCT t.Id_Ticket + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket + JOIN vncontrol.inter i ON i.inter_id = ts.inter_id + JOIN vn2008.state s ON s.id = i.state_id + WHERE mc.Id_Componente = 17 + AND mc.greuge = 0 + AND t.Fecha >= '2016-10-01' + AND t.Fecha < CURDATE() + AND s.alert_level >= 3; + + DELETE g.* + FROM vn2008.Greuges g + JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket + WHERE Greuges_type_id = 2; + + INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, + Greuges_type_id, Id_Ticket) + SELECT Id_Cliente + ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) + AS dif + ,date(t.Fecha) + , 2 + ,tt.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc + ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 + GROUP BY t.Id_Ticket + HAVING ABS(dif) > 1; + + UPDATE vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket + SET greuge = 1 + WHERE Id_Componente = 17; + + /* + * Recalculamos la ratio de las reclamaciones, que luego + * se va a utilizar en el recobro + */ + + REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) + SELECT Id_Cliente, 0,0,0,0 + FROM vn2008.Clientes; + + REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) + SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, + round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 + FROM bi.facturacion_media_anual fm + LEFT JOIN( + SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * + Cantidad * Preu * (100 - Descuento) / 100)) + AS Reclamaciones + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca + ON ca.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND cm.cl_est_id = 3 + AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) + GROUP BY cm.Id_Cliente + ) claims ON claims.Id_Cliente = fm.Id_Cliente; + + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE bi.claims_ratio cr + JOIN ( + SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge + FROM vn2008.Greuges + WHERE Fecha <= CURDATE() + GROUP BY Id_Cliente + ) g ON g.Id_Cliente = cr.Id_Cliente + SET recobro = GREATEST(0,round(nz(Greuge) / + (nz(Consumo) * vMonthToRefund / 12 ) ,3)); + + -- Protección neonatos + UPDATE bi.claims_ratio cr + JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente + SET recobro = 0, Ratio = 0 + WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,CURDATE()); + + -- CLIENTE 7983, JULIAN SUAU + UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; + + -- CLIENTE 4358 + UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; + + -- CLIENTE 5523, VERDECORA UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523; -- CLIENTE 15979, SERVEIS VETERINARIS - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; - - -- CLIENTE 5189 i 8942, son de CSR i son el mateix client - UPDATE bi.claims_ratio cr - JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro - FROM bi.claims_ratio - WHERE Id_Cliente IN ( 5189,8942) - ) sub - SET cr.recobro = sub.recobro - WHERE Id_Cliente IN ( 5189,8942); + UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; + + -- CLIENTE 5189 i 8942, son de CSR i son el mateix client + UPDATE bi.claims_ratio cr + JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro + FROM bi.claims_ratio + WHERE Id_Cliente IN ( 5189,8942) + ) sub + SET cr.recobro = sub.recobro + WHERE Id_Cliente IN ( 5189,8942); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3245,23 +3245,23 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); - - -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); + + -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3739,18 +3739,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bi.facturacion_media_anual; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bi.facturacion_media_anual; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3870,116 +3870,116 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `Greuge_Evolution_Add`() -BEGIN -/* - Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, - así como las ventas acumuladas en los ultimos 365 dias, para poder controlar - su evolucion. -*/ - DECLARE datFEC DATE; - DECLARE datFEC_TOMORROW DATE; - DECLARE datFEC_LASTYEAR DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - - GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; - SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - - END; - - SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; +BEGIN +/* + Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, + así como las ventas acumuladas en los ultimos 365 dias, para poder controlar + su evolucion. +*/ + DECLARE datFEC DATE; + DECLARE datFEC_TOMORROW DATE; + DECLARE datFEC_LASTYEAR DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + + GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; + SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + + END; + + SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; DELETE FROM bi.Greuge_Evolution WHERE Fecha >= TIMESTAMPADD(MONTH,-1,CURDATE()); - - SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), - TIMESTAMPADD(DAY,2,MAX(Fecha)) - INTO datFEC, - datFEC_TOMORROW - FROM bi.Greuge_Evolution; - - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; - - CREATE TEMPORARY TABLE maxInvoice - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha - FROM vn2008.Facturas - GROUP BY Id_Cliente - HAVING maxFecha < timestampadd(month,-2,datFEC); - - WHILE datFEC < CURDATE() DO - - REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) - - SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 - FROM ( - SELECT Id_Cliente, sum(Importe) as Greuge - FROM vn2008.Greuges - where Fecha <= datFEC - group by Id_Cliente - ) sub - RIGHT JOIN - - ( - - SELECT Id_Cliente, sum(Ventas) as Ventas - FROM - ( - - SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas - FROM bs.ventas - WHERE fecha = datFEC or fecha = datFEC_LASTYEAR - - UNION ALL - - SELECT Id_Cliente, Ventas - FROM bi.Greuge_Evolution - WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) - - ) sub - group by Id_Cliente - - ) v using(Id_Cliente) - ; - - -- Ahora calcularemos el greuge muerto - - UPDATE bi.Greuge_Evolution ge - JOIN maxInvoice m using(Id_Cliente) - SET FOSIL = GREUGE - WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); - - -- Recobro - - UPDATE bi.Greuge_Evolution ge - JOIN ( - SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - WHERE t.Fecha >= datFEC - AND t.Fecha < datFEC_TOMORROW - AND mc.Id_Componente = 17 -- Recobro - GROUP BY cs.Id_Cliente - ) sub using(Id_Cliente) - SET Recobro = Importe - WHERE ge.Fecha = datFEC; - - SET datFEC = datFEC_TOMORROW; - SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - - END WHILE; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), + TIMESTAMPADD(DAY,2,MAX(Fecha)) + INTO datFEC, + datFEC_TOMORROW + FROM bi.Greuge_Evolution; + + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + CREATE TEMPORARY TABLE maxInvoice + (PRIMARY KEY (Id_Cliente)) + ENGINE = MEMORY + SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha + FROM vn2008.Facturas + GROUP BY Id_Cliente + HAVING maxFecha < timestampadd(month,-2,datFEC); + + WHILE datFEC < CURDATE() DO + + REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) + + SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 + FROM ( + SELECT Id_Cliente, sum(Importe) as Greuge + FROM vn2008.Greuges + where Fecha <= datFEC + group by Id_Cliente + ) sub + RIGHT JOIN + + ( + + SELECT Id_Cliente, sum(Ventas) as Ventas + FROM + ( + + SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas + FROM bs.ventas + WHERE fecha = datFEC or fecha = datFEC_LASTYEAR + + UNION ALL + + SELECT Id_Cliente, Ventas + FROM bi.Greuge_Evolution + WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) + + ) sub + group by Id_Cliente + + ) v using(Id_Cliente) + ; + + -- Ahora calcularemos el greuge muerto + + UPDATE bi.Greuge_Evolution ge + JOIN maxInvoice m using(Id_Cliente) + SET FOSIL = GREUGE + WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); + + -- Recobro + + UPDATE bi.Greuge_Evolution ge + JOIN ( + SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe + FROM vn2008.Tickets t + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento + WHERE t.Fecha >= datFEC + AND t.Fecha < datFEC_TOMORROW + AND mc.Id_Componente = 17 -- Recobro + GROUP BY cs.Id_Cliente + ) sub using(Id_Cliente) + SET Recobro = Importe + WHERE ge.Fecha = datFEC; + + SET datFEC = datFEC_TOMORROW; + SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4063,10 +4063,10 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `nigthlyAnalisisVentas`() -BEGIN - CALL analisis_ventas_update; - CALL analisis_ventas_simple; - CALL analisis_ventas_evolution_add; +BEGIN + CALL analisis_ventas_update; + CALL analisis_ventas_simple; + CALL analisis_ventas_evolution_add; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4845,3460 +4845,6 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; --- --- Current Database: `bs` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `bs`; - --- --- Temporary table structure for view `bajasLaborales` --- - -DROP TABLE IF EXISTS `bajasLaborales`; -/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `bajasLaborales` AS SELECT - 1 AS `firstname`, - 1 AS `name`, - 1 AS `business_id`, - 1 AS `lastDate`, - 1 AS `endContract`, - 1 AS `type`, - 1 AS `dias`, - 1 AS `userFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `bancos_evolution` --- - -DROP TABLE IF EXISTS `bancos_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `bancos_evolution` ( - `Fecha` date NOT NULL, - `Id_Banco` int(11) NOT NULL, - `saldo` double NOT NULL DEFAULT '0', - `quilla` double NOT NULL DEFAULT '0', - `deuda` double NOT NULL DEFAULT '0', - `liquidez` double NOT NULL DEFAULT '0', - `disponibilidad ajena` double NOT NULL DEFAULT '0', - `saldo_aux` double NOT NULL DEFAULT '0' COMMENT 'Saldo auxiliar para el calculo de lo dispuesto en las polizas', - PRIMARY KEY (`Fecha`,`Id_Banco`), - KEY `fk_banco_evolution_idx` (`Id_Banco`), - CONSTRAINT `fk_banco_evolution` FOREIGN KEY (`Id_Banco`) REFERENCES `vn`.`bank` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los saldos bancarios'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `carteras` --- - -DROP TABLE IF EXISTS `carteras`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `carteras` ( - `CodigoTrabajador` varchar(3) CHARACTER SET latin1 NOT NULL, - `Año` int(11) NOT NULL, - `Mes` int(11) NOT NULL, - `Peso` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`CodigoTrabajador`,`Año`,`Mes`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientDied` --- - -DROP TABLE IF EXISTS `clientDied`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientDied` ( - `id` int(11) NOT NULL DEFAULT '0', - `clientName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `lastInvoiced` date DEFAULT NULL, - `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Boss` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Aviso` varchar(13) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientNewBorn` --- - -DROP TABLE IF EXISTS `clientNewBorn`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientNewBorn` ( - `clientFk` int(11) NOT NULL, - `shipped` date NOT NULL, - PRIMARY KEY (`clientFk`), - CONSTRAINT `clientNewBorn_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `compradores` --- - -DROP TABLE IF EXISTS `compradores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores` ( - `Id_Trabajador` int(11) NOT NULL, - `año` int(4) NOT NULL, - `semana` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `comision` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`año`,`semana`), - CONSTRAINT `comprador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `compradores_evolution` --- - -DROP TABLE IF EXISTS `compradores_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores_evolution` ( - `Id_Trabajador` int(11) NOT NULL, - `fecha` date NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`fecha`), - CONSTRAINT `evo_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `experienceIberflora2016` --- - -DROP TABLE IF EXISTS `experienceIberflora2016`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `experienceIberflora2016` ( - `Id_Cliente` int(11) NOT NULL, - `isVisitor` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de clientes que participan en el estudio sobre la mejora del consumo tras la visita a las instalaciones de Silla'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `fondo_maniobra` --- - -DROP TABLE IF EXISTS `fondo_maniobra`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `fondo_maniobra` ( - `fecha` date NOT NULL, - `fondo` double DEFAULT NULL, - `clientes_facturas` double DEFAULT NULL, - `clientes_cobros` double DEFAULT NULL, - `proveedores_facturas` double DEFAULT NULL, - `proveedores_pagos` double DEFAULT NULL, - `fondo_medio` double DEFAULT NULL, - PRIMARY KEY (`fecha`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `indicators` --- - -DROP TABLE IF EXISTS `indicators`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `indicators` ( - `updated` date NOT NULL, - `lastYearSales` int(11) DEFAULT NULL, - `totalGreuge` int(11) DEFAULT NULL, - `latePaymentRate` decimal(5,4) DEFAULT NULL, - `countEmployee` decimal(10,2) DEFAULT NULL, - `averageMana` int(11) DEFAULT NULL, - `bankingPool` int(11) DEFAULT NULL, - `lastMonthActiveClients` int(11) DEFAULT NULL, - `lastMonthLostClients` int(11) DEFAULT NULL, - `lastMonthNewClients` int(11) DEFAULT NULL, - `lastMonthWebBuyingRate` decimal(5,4) DEFAULT NULL, - `productionHours` decimal(10,1) DEFAULT NULL, - `dailyWorkersCost` decimal(10,0) DEFAULT NULL, - `volumeM3` decimal(10,0) DEFAULT NULL, - `salesValue` decimal(10,0) DEFAULT NULL, - `valueM3` decimal(10,0) DEFAULT NULL, - `hoursM3` decimal(5,2) DEFAULT NULL, - `workerCostM3` decimal(10,1) DEFAULT NULL, - `salesWorkersCostRate` decimal(10,2) DEFAULT NULL, - `thisWeekSales` decimal(10,2) DEFAULT NULL, - `lastYearWeekSales` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`updated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores actuales para una consulta diaria rápida por los directivos.'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `lastIndicators` --- - -DROP TABLE IF EXISTS `lastIndicators`; -/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `lastIndicators` AS SELECT - 1 AS `updated`, - 1 AS `lastYearSales`, - 1 AS `incLastYearSales`, - 1 AS `totalGreuge`, - 1 AS `incTotalGreuge`, - 1 AS `latePaymentRate`, - 1 AS `incLatePaymentRate`, - 1 AS `countEmployee`, - 1 AS `incCountEmployee`, - 1 AS `averageMana`, - 1 AS `incAverageMana`, - 1 AS `bankingPool`, - 1 AS `incbankingPool`, - 1 AS `lastMonthActiveClients`, - 1 AS `incLastMonthActiveClients`, - 1 AS `lastMonthLostClients`, - 1 AS `incLastMonthLostClients`, - 1 AS `lastMonthNewClients`, - 1 AS `incLastMonthNewClients`, - 1 AS `lastMonthWebBuyingRate`, - 1 AS `incLastMonthWebBuyingRate`, - 1 AS `productionHours`, - 1 AS `dailyWorkersCost`, - 1 AS `volumeM3`, - 1 AS `salesValue`, - 1 AS `valueM3`, - 1 AS `hoursM3`, - 1 AS `workerCostM3`, - 1 AS `salesWorkersCostRate`, - 1 AS `thisWeekSales`, - 1 AS `lastYearWeekSales`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `m3` --- - -DROP TABLE IF EXISTS `m3`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `m3` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `fecha` date NOT NULL, - `provinceFk` smallint(5) unsigned DEFAULT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '0', - `m3` decimal(10,2) DEFAULT NULL, - `year` int(11) DEFAULT NULL, - `month` int(11) DEFAULT NULL, - `week` int(11) DEFAULT NULL, - `day` int(11) DEFAULT NULL, - `dayName` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, - `euros` decimal(10,2) DEFAULT '0.00', - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `m3Silla` --- - -DROP TABLE IF EXISTS `m3Silla`; -/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `m3Silla` AS SELECT - 1 AS `fecha`, - 1 AS `year`, - 1 AS `month`, - 1 AS `week`, - 1 AS `day`, - 1 AS `dayName`, - 1 AS `Volumen`, - 1 AS `Euros`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `m3analisis` --- - -DROP TABLE IF EXISTS `m3analisis`; -/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `m3analisis` AS SELECT - 1 AS `fecha`, - 1 AS `year`, - 1 AS `month`, - 1 AS `week`, - 1 AS `day`, - 1 AS `dayName`, - 1 AS `Volumen`, - 1 AS `Euros`, - 1 AS `Departamento`, - 1 AS `Horas`, - 1 AS `Salarios`, - 1 AS `tiempoM3`, - 1 AS `valorM3`, - 1 AS `costeLaboralM3`, - 1 AS `costeEuros`, - 1 AS `precioHora`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `manaCustomer` --- - -DROP TABLE IF EXISTS `manaCustomer`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `manaCustomer` ( - `Id_Cliente` int(11) NOT NULL, - `Mana` decimal(10,0) NOT NULL DEFAULT '0', - `dated` date NOT NULL, - PRIMARY KEY (`Id_Cliente`,`dated`), - KEY `manaCustomerIdx1` (`dated`), - CONSTRAINT `cliente_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `manaSpellersExcluded` --- - -DROP TABLE IF EXISTS `manaSpellersExcluded`; -/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `manaSpellersExcluded` AS SELECT - 1 AS `workerFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `mana_spellers` --- - -DROP TABLE IF EXISTS `mana_spellers`; -/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mana_spellers` AS SELECT - 1 AS `Id_Trabajador`, - 1 AS `size`, - 1 AS `used`, - 1 AS `prices_modifier_rate`, - 1 AS `prices_modifier_activated`, - 1 AS `minRate`, - 1 AS `maxRate`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `mana_spellers_excluded` --- - -DROP TABLE IF EXISTS `mana_spellers_excluded`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mana_spellers_excluded` ( - `Id_Trabajador` int(11) NOT NULL, - PRIMARY KEY (`Id_Trabajador`), - CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `mermas` --- - -DROP TABLE IF EXISTS `mermas`; -/*!50001 DROP VIEW IF EXISTS `mermas`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mermas` AS SELECT - 1 AS `Comprador`, - 1 AS `Familia`, - 1 AS `Referencia`, - 1 AS `Item`, - 1 AS `Cantidad`, - 1 AS `Coste_Unitario`, - 1 AS `Importe`, - 1 AS `Cliente`, - 1 AS `ticketFk`, - 1 AS `Fecha`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `mermasCache` --- - -DROP TABLE IF EXISTS `mermasCache`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mermasCache` ( - `Comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `año` int(4) NOT NULL, - `Valor_Compra` decimal(10,0) DEFAULT NULL, - `Faltas` decimal(10,0) DEFAULT NULL, - `Basura` decimal(10,0) DEFAULT NULL, - PRIMARY KEY (`Comprador`,`año`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `nightTask` --- - -DROP TABLE IF EXISTS `nightTask`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `nightTask` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `started` datetime DEFAULT NULL, - `finished` datetime DEFAULT NULL, - `lastFinished` datetime DEFAULT NULL, - `order` int(11) DEFAULT NULL, - `schema` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `procedure` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `errorCode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeInsert` BEFORE INSERT ON `nightTask` FOR EACH ROW -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 */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeUpdate` BEFORE UPDATE ON `nightTask` FOR EACH ROW -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 */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `nightTaskConfig` --- - -DROP TABLE IF EXISTS `nightTaskConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `nightTaskConfig` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `logMail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payMethodClient` --- - -DROP TABLE IF EXISTS `payMethodClient`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payMethodClient` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT '0', - `clientFk` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `FkPayMethod_idx` (`payMethodFk`), - KEY `FkClientPayMethod_idx` (`clientFk`), - KEY `FkDateClientPayMethod` (`dated`,`clientFk`), - CONSTRAINT `FkClientPayMethod` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `FkPayMethodClient` FOREIGN KEY (`payMethodFk`) REFERENCES `vn`.`payMethod` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_bin; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payMethodClientEvolution` --- - -DROP TABLE IF EXISTS `payMethodClientEvolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payMethodClientEvolution` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `payMethodName` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `amountClient` int(11) NOT NULL, - `amount` decimal(10,2) NOT NULL, - `equalizationTax` decimal(10,2) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivity` --- - -DROP TABLE IF EXISTS `productivity`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivity` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `hh` int(10) unsigned NOT NULL, - `mm` int(10) unsigned NOT NULL, - `m3` double NOT NULL DEFAULT '0', - `workers` int(11) NOT NULL DEFAULT '0', - `wCost` double NOT NULL DEFAULT '0', - `numCoordinadores` int(11) NOT NULL DEFAULT '0', - `costCoordinacion` double NOT NULL DEFAULT '0', - `numSacadores` int(11) NOT NULL DEFAULT '0', - `costSacado` double NOT NULL DEFAULT '0', - `numEncajadores` int(11) NOT NULL DEFAULT '0', - `costEncajado` double NOT NULL DEFAULT '0', - `numPaletizadores` int(11) NOT NULL DEFAULT '0', - `costPaletizado` double NOT NULL DEFAULT '0', - `numCamareros` int(11) NOT NULL DEFAULT '0', - `costCamara` double NOT NULL DEFAULT '0', - `numComplementos` int(11) NOT NULL DEFAULT '0', - `costComplementos` double NOT NULL DEFAULT '0', - `numArtificial` int(11) NOT NULL DEFAULT '0', - `costArtificial` double NOT NULL DEFAULT '0', - `m3FV` double NOT NULL DEFAULT '0', - `m3PCA` double NOT NULL DEFAULT '0', - `m3Artificial` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivityDepartment` --- - -DROP TABLE IF EXISTS `productivityDepartment`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivityDepartment` ( - `dated` date NOT NULL, - `amountCoordinacion` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountSacado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountEncajado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountPaletizado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountCamara` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountComplementos` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountArtificial` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`dated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivity_evolution` --- - -DROP TABLE IF EXISTS `productivity_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivity_evolution` ( - `dated` date NOT NULL, - `m3productionCost` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`dated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salaries2018` --- - -DROP TABLE IF EXISTS `salaries2018`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salaries2018` ( - `person_id` int(11) NOT NULL DEFAULT '0', - `sex` enum('M','F') CHARACTER SET utf8 NOT NULL DEFAULT 'F' COMMENT 'M Masculino F Femenino', - `edad` int(6) DEFAULT NULL, - `antiguedad` int(6) DEFAULT NULL, - `Modalidad` varchar(22) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', - `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `worker` varchar(82) CHARACTER SET utf8 DEFAULT NULL, - `totalDays` decimal(32,0) DEFAULT NULL, - `totalAnual` decimal(16,0) DEFAULT NULL, - `virtualMonthlySalary` decimal(16,0) DEFAULT NULL, - `departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `category_name` varchar(50) CHARACTER SET utf8 NOT NULL, - `level_name` varchar(5) CHARACTER SET utf8 DEFAULT NULL, - `thisYearDateStart` varchar(10) CHARACTER SET utf8mb4 DEFAULT NULL, - PRIMARY KEY (`person_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salePersonEvolution` --- - -DROP TABLE IF EXISTS `salePersonEvolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salePersonEvolution` ( - `dated` date NOT NULL DEFAULT '0000-00-00', - `amount` decimal(10,2) NOT NULL DEFAULT '0.00', - `equalizationTax` decimal(10,2) NOT NULL DEFAULT '0.00', - `salesPersonFk` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`dated`,`salesPersonFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salesByWeek` --- - -DROP TABLE IF EXISTS `salesByWeek`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salesByWeek` ( - `week` int(11) NOT NULL, - `year` int(11) NOT NULL, - `sales` double DEFAULT NULL, - UNIQUE KEY `week` (`week`,`year`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `vendedores` --- - -DROP TABLE IF EXISTS `vendedores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `vendedores` ( - `Id_Trabajador` int(11) NOT NULL, - `año` int(4) NOT NULL, - `mes` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `comision` decimal(10,2) DEFAULT NULL, - `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos', - `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos', - `comisionNuevos` decimal(10,2) DEFAULT NULL, - `sustitucionArrendada` decimal(10,2) DEFAULT NULL, - `sustitucionCedida` decimal(10,2) DEFAULT NULL, - `itemTypeLended` decimal(10,2) DEFAULT NULL, - `itemTypeBorrowed` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), - CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `vendedores_evolution` --- - -DROP TABLE IF EXISTS `vendedores_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `vendedores_evolution` ( - `workerFk` int(11) NOT NULL, - `year` int(11) NOT NULL, - `sales` decimal(10,2) DEFAULT NULL, - `month` int(11) NOT NULL, - PRIMARY KEY (`workerFk`,`year`,`month`), - CONSTRAINT `evo_vendedor_trabajador` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventas` --- - -DROP TABLE IF EXISTS `ventas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventas` ( - `Id_Movimiento` int(11) NOT NULL, - `importe` decimal(10,3) NOT NULL DEFAULT '0.000', - `recargo` decimal(10,3) NOT NULL DEFAULT '0.000', - `fecha` date NOT NULL, - `tipo_id` smallint(5) unsigned NOT NULL, - `Id_Cliente` int(11) NOT NULL DEFAULT '1', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`Id_Movimiento`), - KEY `tip_to_tip_idx` (`tipo_id`), - KEY `clientes_bs_ventas_idx` (`Id_Cliente`), - KEY `empresa_bs_ventas_idx` (`empresa_id`), - KEY `fecha_bs` (`fecha`), - CONSTRAINT `clientes_bs_ventas` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `empresa_bs_ventas` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `mov_to_mov` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `tip_to_tip` FOREIGN KEY (`tipo_id`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventas_contables` --- - -DROP TABLE IF EXISTS `ventas_contables`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventas_contables` ( - `year` int(4) NOT NULL, - `month` int(2) NOT NULL, - `venta` decimal(10,2) DEFAULT NULL, - `grupo` int(1) NOT NULL, - `reino_id` int(10) unsigned NOT NULL, - `tipo_id` smallint(5) unsigned NOT NULL, - `empresa_id` int(4) NOT NULL, - `gasto` varchar(10) CHARACTER SET latin1 NOT NULL, - PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouseProduction_kk` --- - -DROP TABLE IF EXISTS `warehouseProduction_kk`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouseProduction_kk` ( - `fecha` date NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - `m3` decimal(10,0) NOT NULL DEFAULT '0', - `labourCost` decimal(10,0) NOT NULL DEFAULT '0', - `workerHours` decimal(10,0) NOT NULL DEFAULT '0', - PRIMARY KEY (`fecha`,`warehouse_id`), - KEY `warehouseProduction_fk1_idx` (`warehouse_id`), - CONSTRAINT `warehouseProduction_fk1` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `workerMana` --- - -DROP TABLE IF EXISTS `workerMana`; -/*!50001 DROP VIEW IF EXISTS `workerMana`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `workerMana` AS SELECT - 1 AS `workerFk`, - 1 AS `amount`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `workerSpeed` --- - -DROP TABLE IF EXISTS `workerSpeed`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerSpeed` ( - `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `accion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', - `LitrosMinuto` decimal(10,1) DEFAULT NULL, - `LitrosMinutoLastHour` decimal(10,1) DEFAULT NULL, - `lastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - PRIMARY KEY (`workerCode`,`warehouseFk`,`accion`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'bs' --- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `nightTask_launchAll` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2017-08-27 02:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; - --- --- Dumping routines for database 'bs' --- -/*!50003 DROP FUNCTION IF EXISTS `tramo` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `tramo`(vDateTime DATETIME) RETURNS varchar(20) CHARSET utf8 COLLATE utf8_unicode_ci -BEGIN - - DECLARE vTramo VARCHAR(20); - DECLARE vHour INT; - - SET vHour = HOUR(vDateTime) ; - - SET vTramo = - CASE - WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' - WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' - END ; - -RETURN vTramo; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `analisisComponentes` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `analisisComponentes`() -BEGIN - -DECLARE vDateStart DATE DEFAULT '2016-01-01'; -DECLARE vDateEnd DATE DEFAULT '2016-11-30'; -DECLARE vDate DATE; - -SET vDate = vDateStart; - -DELETE FROM bs.ventasComponentes; - -WHILE vDate <= vDateEnd DO - - INSERT INTO bs.ventasComponentes - SELECT vDate as Fecha, mc.Id_Componente, cast(sum(m.Cantidad * mc.Valor) AS DECIMAL(10,2)) as Importe - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN bs.ventas v ON v.Id_Movimiento = mc.Id_Movimiento - WHERE v.fecha = vDate - AND empresa_id IN (442,567) - GROUP BY mc.Id_Componente; - - SET vDate = TIMESTAMPADD(DAY,1,vDate); - - IF DAY(vDate) MOD 28 = 0 THEN - - SELECT vDate; - - END IF; - -END WHILE; - - SELECT vDate; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bancos_evolution_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bancos_evolution_add`() -BEGIN - /* - - Inserta en la tabla bancos_evolution los saldos acumulados - - */ - - - DECLARE vCurrentDate DATE; - DECLARE vStartingDate DATE DEFAULT '2016-01-01'; - DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, CURDATE()); - - DELETE FROM bs.bancos_evolution WHERE Fecha > vStartingDate; - - SET vCurrentDate = vStartingDate; - - WHILE vCurrentDate < vMaxDate DO - - REPLACE bs.bancos_evolution( Fecha - ,Id_Banco - ,saldo) - - SELECT vCurrentDate - , Id_Banco - , sum(saldo) - - FROM - ( - - SELECT Id_Banco - ,saldo_aux as 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 - WHERE cash IN (0,3) - AND Cajafecha = vCurrentDate - AND (Serie = 'MB' OR cash = 3) - GROUP BY Id_Banco - - UNION ALL - - SELECT id_banco, - importe -- pagos futuros - FROM vn2008.pago - WHERE fecha = vCurrentDate - AND fecha >= CURDATE() - AND NOT conciliado - - UNION ALL - - SELECT Id_Banco, Entregado -- cobros futuros - FROM vn2008.Recibos - WHERE Fechacobro = vCurrentDate - AND Fechacobro > CURDATE() - - UNION ALL - - SELECT sp.Id_Banco, Importe -- saldos de la tabla prevision - FROM vn2008.Saldos_Prevision sp - JOIN vn2008.Bancos b using(Id_Banco) - WHERE cash IN (0,3) - AND Fecha = vCurrentDate - - - - )sub - GROUP BY Id_Banco; - - -- Utilizamos el saldo_auxiliar para calcular lo dispuesto en las polizas - - UPDATE bs.bancos_evolution be - SET saldo_aux = saldo; - - -- Ahora actualizamos la quilla - UPDATE bs.bancos_evolution be - LEFT JOIN - ( - SELECT Id_Banco, - sum(importe) as quilla - FROM vn2008.Bancos_poliza - WHERE vCurrentDate between apertura AND IFNULL(cierre, vCurrentDate) - GROUP BY Id_Banco - ) sub using(Id_Banco) - SET be.quilla = sub.quilla - WHERE be.Fecha = vCurrentDate; - - - SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); - - END WHILE; - - - -- Deuda - UPDATE bs.bancos_evolution be - JOIN vn2008.Bancos using(Id_Banco) - SET be.deuda = IF(cash = 3, be.saldo_aux, 0) - , be.saldo = IF(cash = 3, 0, be.saldo_aux) - WHERE Fecha >= vStartingDate; - - - -- 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; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `campaignComparative` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` 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 - FROM ( - (SELECT - CONCAT(w.firstname, ' ', w.lastName) AS workerName, - c.id, - c.name, - SUM(v.importe) AS previousAmmount, - 0 currentAmmount - 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) - AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) - GROUP BY w.id, v.Id_Cliente) - UNION ALL - (SELECT - CONCAT(w.firstname, ' ', w.lastName) AS workerName, - c.id, - c.name, - 0 AS previousAmmount, - SUM(s.quantity * s.price) AS currentAmmount - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE t.shipped BETWEEN vDateFrom - AND vDateTo - GROUP BY w.id, c.id) - ) comparative - GROUP BY workerName, id - HAVING (previousAmmount <> 0 OR currentAmmount <> 0) - ORDER BY workerName, id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `carteras_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `carteras_add`() -BEGIN - -DELETE FROM bs.carteras -WHERE Año >= YEAR(CURDATE()) - 1; - -INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) -SELECT year as Año, month as Mes, CodigoTrabajador, sum(importe) as Peso -FROM vn2008.time t -JOIN bs.ventas v on t.date = v.fecha -JOIN vn2008.Clientes c on c.Id_Cliente = v.Id_Cliente -JOIN vn2008.Trabajadores tr on tr.Id_Trabajador = c.Id_Trabajador -WHERE t.year >= YEAR(CURDATE()) - 1 -GROUP BY CodigoTrabajador, Año, Mes; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `clientDied` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientDied`() -BEGIN - - IF DAY(CURDATE()) = 6 THEN - - SET @primerAviso := TIMESTAMPADD(MONTH,-1,CURDATE()); - SET @segundoAviso := TIMESTAMPADD(MONTH,-2,CURDATE()); - SET @tercerAviso := TIMESTAMPADD(MONTH,-3,CURDATE()); - - TRUNCATE TABLE bs.clientDied; - - INSERT INTO bs.clientDied - SELECT c.id, - c.name as clientName, - maxIssued as lastInvoiced, - w.code AS workerCode, - b.code AS Boss, - CASE - WHEN IFNULL(maxIssued,'2000-01-01') < @tercerAviso THEN 'Tercer Aviso' - WHEN maxIssued < @segundoAviso THEN 'Segundo Aviso' - WHEN maxIssued < @primerAviso THEN 'Primer Aviso' - END as Aviso - FROM vn.client c - JOIN vn.worker w ON w.id = c.salesPersonFk - JOIN vn2008.jerarquia j ON j.worker_id = w.id - JOIN vn.worker b ON b.id = j.boss_id - JOIN bs.mana_spellers ms ON ms.Id_Trabajador = c.salesPersonFk - LEFT JOIN (SELECT clientFk, max(issued) as maxIssued FROM vn.invoiceOut GROUP BY clientFk) io ON io.clientFk = c.id - WHERE (maxIssued IS NULL OR maxIssued < @primerAviso) - AND c.created < @tercerAviso; - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clientNewBorn_Update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientNewBorn_Update`() -BEGIN - - DECLARE fromDated DATE DEFAULT '2019-04-01'; - - -- Eliminamos clientes que ya no son nuevos - DELETE FROM bs.clientNewBorn - WHERE shipped < TIMESTAMPADD(YEAR,-1,CURDATE()); - - -- Clientes nuevos - REPLACE bs.clientNewBorn(clientFk,shipped) - SELECT t.clientFk, MIN(t.shipped) as shipped - FROM vn.ticket t - WHERE shipped > '2001-01-01' - GROUP BY t.clientFk - HAVING shipped >= GREATEST(TIMESTAMPADD(YEAR,-1,CURDATE()), fromDated); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comercialesCompleto` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comercialesCompleto`(IN vWorker INT, vDate DATE) -BEGIN - -CALL vn.subordinateGetList(vWorker); - -SELECT - c.Id_Cliente id_cliente, - c.calidad, - c.Cliente cliente, - cr.recobro * 100 tarifa, - c.Telefono telefono, - c.movil, - c.POBLACION poblacion, - p.`name` provincia, - vn2008.red(f.futur) futur, - c.Credito credito, - pm.`name` forma_pago, - vn2008.red(c365 / 12) consumo_medio365, - vn2008.red(c365) consumo365, - vn2008.red(CmLy.peso) peso_mes_año_pasado, - vn2008.red(CmLy.peso * 1.19) objetivo, - tr.CodigoTrabajador, - vn2008.red(mes_actual.consumo) consumoMes, - vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, - DATE(LastTicket) ultimo_ticket, - dead.muerto, - g.Greuge, - cr.recobro -FROM - vn2008.Clientes c - LEFT JOIN - (SELECT Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge - FROM vn2008.Greuges - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = c.Id_Cliente - LEFT JOIN - vn2008.province p ON p.province_id = c.province_id - JOIN - vn2008.pay_met pm ON pm.id = c.pay_met_id - LEFT JOIN - vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - LEFT JOIN - bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3 - FROM bs.ventas v - JOIN vn2008.Clientes c USING (Id_Cliente) - - 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 - 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) - 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 - (SELECT - t.Id_Cliente, - SUM(m.preu * m.Cantidad * (1 - m.Descuento / 100)) futur - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_Cliente = t.Id_Cliente - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - AND DATE(Fecha) BETWEEN vDate AND LAST_DAY(vDate) - GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente - LEFT JOIN - (SELECT - MAX(t.Fecha) LastTicket, c.Id_Cliente - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - SUM(importe) peso, c.Id_Cliente - FROM - bs.ventas v - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - MONTH(fecha) = MONTH(vDate) - AND YEAR(fecha) = YEAR(vDate) - 1 - AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - c.Id_Cliente, - IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto - FROM - vn2008.Facturas f - JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente - - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente - JOIN tmp.subordinate s ON s.workerFk = c.Id_Trabajador; - -DROP TEMPORARY TABLE tmp.subordinate; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add`(IN intYEAR INT, IN intWEEK_START INT, IN intWEEK_END INT) -BEGIN - -REPLACE bs.compradores - -SELECT tp.Id_Trabajador - , intYEAR as año - , tm.week as semana - , sum(importe) as importe - , 0 as comision - -FROM bs.ventas v -JOIN vn2008.time tm on tm.date = v.fecha -JOIN vn2008.Tipos tp using(tipo_id) -WHERE tm.year = intYEAR and tm.week between intWEEK_START and intWEEK_END -AND reino_id != 6 -GROUP BY tp.Id_Trabajador, tm.week; - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add_launcher`() -BEGIN - - DECLARE vYear INT; - DECLARE vWeek INT; - DECLARE done BOOL DEFAULT FALSE; - - DECLARE rs CURSOR FOR - SELECT year, week - FROM vn.time - WHERE (year = vYear AND week >= vWeek) - OR year > vYear; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT MAX(año) INTO vYear - FROM compradores; - - SELECT MAX(semana) INTO vWeek - FROM compradores - WHERE año = vYear; - - OPEN rs; - - FETCH rs INTO vYear, vWeek; - - WHILE NOT done DO - - CALL compradores_add(vYear, vWeek, vWeek); - - FETCH rs INTO vYear, vWeek; - - END WHILE; - - CLOSE rs; - - CALL compradores_evolution_add; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_evolution_add`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias - -*/ - -DECLARE datFEC DATE; - - -SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; - - WHILE datFEC < CURDATE() DO - - SELECT datFEC; - - REPLACE bs.compradores_evolution( Id_Trabajador - , fecha - , importe) - - SELECT Id_Trabajador - , datFEC as fecha - , sum(importe) as importe - - FROM - ( - - SELECT Id_Trabajador - , 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 - GROUP BY Id_Trabajador; - - - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `fondo_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `fondo_evolution_add`() -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 FROM bs.fondo_maniobra; - - WHILE datFEC < CURDATE() DO - - -- esto solo sirve para no aburrirse mientras esperamos... - - IF day(datFEC) mod 28 = 0 then - 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(Facturas.Importe) AS Facturas - FROM vn2008.Facturas - INNER JOIN vn2008.Clientes ON Facturas.Id_Cliente = Clientes.Id_cliente - WHERE Clientes.`real` - AND empresa_id <>1381 - AND Fecha between '2011-01-01' and datFEC) fac - JOIN - ( - SELECT - Sum(Entregado) AS Cobros - FROM vn2008.Recibos - INNER JOIN vn2008.Clientes ON Recibos.Id_Cliente = Clientes.Id_cliente - WHERE Clientes.`real` - AND empresa_id <> 1381 - AND Fechacobro Between '2011-01-01' and datFEC) cob - JOIN - ( - SELECT - Sum(cantidad) AS Recibidas - FROM vn2008.recibida - INNER JOIN vn2008.recibida_vencimiento ON recibida.id = recibida_vencimiento.recibida_id - WHERE empresa_id <> 1381 - AND recibida.fecha Between '2015-01-01' and datFEC) rec - JOIN - ( - SELECT Sum(importe) AS Pagos - FROM vn2008.pago - WHERE empresa_id <>1381 AND pago.fecha Between '2015-01-01' and datFEC) pag; - - - - UPDATE bs.fondo_maniobra - JOIN - (SELECT avg(fondo) as media - FROM bs.fondo_maniobra - WHERE fecha <= datFEC) sub - SET fondo_medio = media - WHERE fecha = datFEC; - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdate`(vDated DATE) -BEGIN - - DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1,vDated); - DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60,vDated); - DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30,vDated); - DECLARE vWeek INT; - - REPLACE indicators(updated) - VALUES(vDated); - - -- Ventas totales del ultimo año - UPDATE indicators - SET lastYearSales = - ( - SELECT SUM(importe + recargo) - FROM bs.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 = - ( - 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 WHERE date = vDated and amount > 0) - / - ( SELECT SUM(importe + recargo) FROM bs.ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) - WHERE updated = vDated; - - -- Número de trabajadores activos - UPDATE indicators - SET countEmployee = - ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) - FROM - postgresql.business AS b - JOIN postgresql.profile p ON p.profile_id = b.provider_id - JOIN postgresql.person pe ON pe.person_id = p.person_id - LEFT JOIN - postgresql.business_labour AS bl ON bl.business_id = b.business_id - LEFT JOIN - postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id - WHERE - (vDated BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDated)) - AND pe.name = 'VERDNATURA LEVANTE SL' - ) - WHERE updated = vDated; - - -- Maná medio acumulado por comercial - UPDATE indicators - SET averageMana = - (SELECT avg(used) - FROM bs.mana_spellers - ) - WHERE updated = vDated; - - -- Número de clientes que han comprado en los últimos 30 dias - UPDATE indicators - SET lastMonthActiveClients = - (SELECT COUNT(DISTINCT t.clientFk) - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) - WHERE updated = vDated; - - -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores - UPDATE indicators - SET lastMonthLostClients = - (SELECT COUNT(lm.clientFk) - FROM - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) cm - RIGHT JOIN - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped >= twoMonthsBefore - AND t.shipped < oneMonthBefore - ) lm ON lm.clientFk = cm.clientFk - WHERE cm.clientFk IS NULL - ) - WHERE updated = vDated; - - -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores - UPDATE indicators - SET lastMonthNewClients = - (SELECT COUNT(cm.clientFk) - FROM - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) cm - LEFT JOIN - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped >= twoMonthsBefore - AND t.shipped < oneMonthBefore - ) lm ON lm.clientFk = cm.clientFk - WHERE lm.clientFk IS NULL - ) - WHERE updated = vDated; - - -- Porcentaje de autopedidos sobre los pedidos totales - UPDATE indicators - SET lastMonthWebBuyingRate = - ( SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) / SUM(source_app != '') - FROM hedera.`order` - WHERE date_send BETWEEN oneMonthBefore AND vDated - ) - WHERE updated = vDated; - - -- Indicadores de producción - UPDATE indicators i - JOIN productionIndicators pi ON pi.dated = i.updated - SET i.productionHours = pi.productionHours, - i.dailyWorkersCost = pi.dailyWorkersCost, - i.volumeM3 = pi.volumeM3, - i.salesValue = pi.salesValue, - i.valueM3 = pi.valueM3, - i.hoursM3 = pi.hoursM3, - i.workerCostM3 = pi.workerCostM3, - i.salesWorkersCostRate = pi.salesWorkersCostRate - WHERE updated BETWEEN oneMonthBefore AND vDated; - - -- CAP Para el calculo de las ventas agrupado por semanas - - SELECT week - FROM vn.time - WHERE dated=vDated INTO vWeek; - - TRUNCATE `bs`.`salesByWeek`; - - INSERT INTO `bs`.`salesByWeek` (week,year,sales) - SELECT `t`.`week` AS `week`,`t`.`year` AS `year`, SUM(`v`.`importe` + `v`.`recargo`) AS `sales` - FROM `bs`.`ventas` `v` - LEFT JOIN `vn`.`time` `t` ON `t`.`dated` = fecha - GROUP BY `t`.`week` , `t`.`year` - ORDER BY `t`.`week` , `t`.`year`; - - -- CAP Indicador Ventas semana actual - UPDATE indicators i - JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated) - SET i.thisWeekSales = s.sales - WHERE updated = vDated; - - -- CAP indicador ventas semana actual en el año pasado - UPDATE indicators i - JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated)-1 - SET i.lastYearWeekSales = s.sales - WHERE updated = vDated; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdateLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdateLauncher`() -BEGIN - - DECLARE vDated DATE; - - SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') - INTO vDated - FROM bs.indicators; - - WHILE vDated < CURDATE() DO - - CALL indicatorsUpdate(vDated); - - SELECT TIMESTAMPADD(DAY,1,MAX(updated)) - INTO vDated - FROM bs.indicators; - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `m3Add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `m3Add`() -BEGIN - - DECLARE datSTART DATE; - DECLARE datEND DATE; - - SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART - FROM bs.m3; - - SET datEND = TIMESTAMPADD(DAY,-1,CURDATE()); - - 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(i.compression * s.quantity * r.cm3) / 1000000 AS m3, - tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) - 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 bs.ventas v ON v.Id_Movimiento = s.id -- Filtra solo por ventas "buenas" - JOIN vn.time tm ON tm.dated = v.fecha - JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk - JOIN vn.address a ON a.id = t.addressFk - WHERE v.fecha BETWEEN datSTART AND datEND - AND s.quantity > 0 -- evita abonos - AND t.companyFk = 442 -- Verdnatura - GROUP BY t.warehouseFk, v.fecha, a.provinceFk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `manaCustomerUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaCustomerUpdate`() -BEGIN -DECLARE vToDated DATE; - DECLARE vFromDated DATE; - DECLARE vForDeleteDated DATE; - DECLARE vManaId INT DEFAULT 37; - DECLARE vManaAutoId INT DEFAULT 39; - DECLARE vManaBankId INT DEFAULT 66; - DECLARE vManaGreugeTypeId INT DEFAULT 3; - - SELECT IFNULL(max(dated), '2016-01-01') - INTO vFromDated - FROM bs.manaCustomer; - - DELETE - FROM bs.manaCustomer - WHERE dated = vFromDated; - - SELECT IFNULL(max(dated), '2016-01-01') - INTO vFromDated - FROM bs.manaCustomer; - - WHILE timestampadd(DAY,30,vFromDated) < CURDATE() DO - - SELECT - timestampadd(DAY,30,vFromDated), - timestampadd(DAY,-90,vFromDated) - INTO - vToDated, - vForDeleteDated; - - DELETE FROM bs.manaCustomer - WHERE dated <= vForDeleteDated; - - - INSERT INTO bs.manaCustomer(Id_Cliente, Mana, dated) - - SELECT - Id_Cliente, - cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated - FROM - - ( - SELECT cs.Id_Cliente, Cantidad * Valor as mana - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs using(Id_Consigna) - 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) - 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 <= vToDated - - UNION ALL - - SELECT g.Id_Cliente, g.Importe - FROM vn2008.Greuges g - WHERE Greuges_type_id = vManaGreugeTypeId - AND Fecha > vFromDated - AND Fecha <= vToDated - - UNION ALL - - SELECT Id_Cliente, mana - FROM bs.manaCustomer - WHERE dated = vFromDated - ) sub - - GROUP BY Id_Cliente - HAVING Id_Cliente; - - SET vFromDated = vToDated; - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `manaSpellers_actualize` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaSpellers_actualize`() -BEGIN - - /* PAK 2019/08/09 updated - * - * Recalcula el valor del campo con el modificador de precio para el componente de maná automático. - * La tabla mana_spellers es una caché - * - */ - - UPDATE mana_spellers me - JOIN - (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual - FROM bs.vendedores - WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) - GROUP BY Id_Trabajador - ) lastYearSales USING(Id_Trabajador) - SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `mermasCacheUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mermasCacheUpdate`() -BEGIN - - DECLARE vTimeRange INT DEFAULT 30; - DECLARE vCurYearStarted DATE DEFAULT TIMESTAMPADD(DAY, - vTimeRange, CURDATE()); - DECLARE vCurYearFinished DATE DEFAULT CURDATE(); - DECLARE vLastYearStarted DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearStarted); - DECLARE vLastYearFinished DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearFinished); - - REPLACE bs.mermasCache - SELECT Comprador, - IF(Fecha < vCurYearStarted, year(CURDATE()) - 1,year(CURDATE())) año, - CAST(sum(Importe) as DECIMAL(10,0)) as Valor_Compra, - CAST(sum(IF(Cliente LIKE 'FALTAS',Importe,0)) as DECIMAL(10,0)) as Faltas, - CAST(sum(IF(Cliente LIKE 'BASURA',Importe,0)) as DECIMAL(10,0)) as Basura - FROM bs.mermas - WHERE Fecha BETWEEN vCurYearStarted AND vCurYearFinished - OR Fecha BETWEEN vLastYearStarted AND vLastYearFinished - GROUP BY año, Comprador; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchAll` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vNErrors INT DEFAULT 0; - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vId INT; - - DECLARE rs CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - OPEN rs; - - myLoop: LOOP - SET vDone = FALSE; - FETCH rs INTO vId, vSchema, vProcedure; - - IF vDone THEN - LEAVE myLoop; - END IF; - - UPDATE nightTask - SET `started` = NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vId; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - SET vNErrors = vNErrors + 1; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vId; - ELSE - UPDATE nightTask - SET finished = NOW(), - lastFinished = NOW() - WHERE id = vId; - END IF; - END LOOP; - - CLOSE rs; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - IF vNErrors > 0 AND vLogMail IS NOT NULL THEN - INSERT INTO vn.mail SET - `sender` = vLogMail, - `subject` = 'Nightly task failed', - `body` = CONCAT( - vNErrors, ' procedures of nightly tasks have failed. ', - 'Please, see `', SCHEMA() ,'`.`nightTask` table for more info.' - ); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchTask` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchTask`( - vSchema VARCHAR(255), - vProcedure VARCHAR(255), - OUT vError VARCHAR(255), - OUT vErrorCode VARCHAR(255) -) -BEGIN -/** - * Runs an specific procedure from nightly tasks, if an error - * occurs, instead of throw it, #vError and #vErrorCode variables - * are setted. - * - * @param vSchema The procedure schema - * @param vProcedure The procedure name - * @param vError The error message, if any - * @param vErrorCode The error code, if any - */ - DECLARE EXIT HANDLER FOR SQLEXCEPTION - GET DIAGNOSTICS CONDITION 1 - vError = MESSAGE_TEXT, - vErrorCode = RETURNED_SQLSTATE; - - CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `payMethodClientAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `payMethodClientAdd`() -BEGIN - INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) - SELECT CURDATE(), c.payMethodFk, c.id - 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) - FROM bs.payMethodClient p - 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; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityAdd`(vDate DATE) -BEGIN - - DECLARE vDateStart DATETIME DEFAULT vDate; - DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); - DECLARE myDepLft INT; - DECLARE myDepRgt INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.productivity; - - CREATE TEMPORARY TABLE tmp.productivity - ENGINE = MEMORY - SELECT hh, - mm, - 000.00 as m3, - 000.00 as m3FV, - 000.00 as m3PCA, - 000.00 as m3Artificial, - 0 as workers, - 000.00 as wCost, - 0 as numCoordinadores, - 000.00 as costCoordinacion, - 0 as numSacadores, - 000.00 as costSacado, - 0 as numEncajadores, - 000.00 as costEncajado, - 0 as numPaletizadores, - 000.00 as costPaletizado, - 0 as numCamareros, - 000.00 as costCamara, - 0 as numComplementos, - 000.00 as costComplementos, - 0 as numArtificial, - 000.00 as costArtificial - FROM vn.dayMinute; - --- Trabajadores - CALL vn.dayMinuteWorker(vDateStart,vDateEnd); -- Genera la tabla tmp.dayMinuteWorker - CALL vn.workerDepartmentByDate(vDate); - - -- General - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - WHERE Almacen IN (1,44) - AND wdd.production - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.workers = sub.workers, p.wCost = sub.Bruto; - - -- Coordinadores - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'COORDINACION'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numCoordinadores = sub.workers, p.costCoordinacion = sub.Bruto; - - -- Sacado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'SACADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numSacadores = sub.workers, p.costSacado = sub.Bruto; - - -- Encajado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'ENCAJADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numEncajadores = sub.workers, p.costEncajado = sub.Bruto; - - -- Paletizado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'PALETIZADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numPaletizadores = sub.workers, p.costPaletizado = sub.Bruto; - - -- Cámara - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'CAMARA'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numCamareros = sub.workers, p.costCamara = sub.Bruto; - - -- Complementos - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'COMPLEMENTOS'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numComplementos = sub.workers, p.costComplementos = sub.Bruto; - - -- Artificial - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'ARTIFICIAL'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numArtificial = sub.workers, p.costArtificial = sub.Bruto; - - -- m3 - CALL vn.ticketBuiltTime(vDate); -- Genera la tabla tmp.ticketBuiltTime(ticketFk,builtTime) - CALL vn.ticketVolumeByDate_ventas(vDate); -- Genera la tabla tmp.ticketVolumeByDate(ticketFk,m3), filtrado por las ventas validas - CALL vn.ticketVolumeByDate_ventas_Artificial(vDate); -- Genera la tabla tmp.ticketVolumeByDate_ventas_Artificial - - UPDATE tmp.productivity p - JOIN - (SELECT HOUR(builtTime) hh, - MINUTE(builtTime) mm, - sum(tvd.m3) as m3, - sum(IF(t.warehouseFk = 1,tvd.m3,0)) as m3FV, - sum(IF(t.warehouseFk = 44,tvd.m3 - IFNULL(tvda.m3,0),0)) as m3PCA, - sum(IFNULL(tvda.m3,0)) as m3Artificial - FROM tmp.ticketBuiltTime tbt - JOIN tmp.ticketVolumeByDate tvd ON tvd.ticketFk = tbt.ticketFk - LEFT JOIN tmp.ticketVolumeByDate_Artificial tvda ON tvda.ticketFk = tbt.ticketFk - JOIN vn.ticket t ON t.id = tbt.ticketFk - WHERE t.warehouseFk IN (1,44) - GROUP BY hh,mm - ) v ON v.hh = p.hh AND v.mm = p.mm - SET p.m3 = v.m3, p.m3FV = v.m3FV, p.m3PCA = v.m3PCA, p.m3Artificial = v.m3Artificial; - - - - DELETE FROM bs.productivity - WHERE dated = vDate; - - INSERT INTO bs.productivity(dated, - hh, - mm, - m3, - m3FV, - m3PCA, - m3Artificial, - workers, - wCost, - numCoordinadores, - costCoordinacion, - numSacadores, - costSacado, - numEncajadores, - costEncajado, - numPaletizadores, - costPaletizado, - numCamareros, - costCamara, - numComplementos, - costComplementos, - numArtificial, - costArtificial) - SELECT vDate, - hh, - mm, - m3, - m3FV, - m3PCA, - m3Artificial, - workers, - wCost, - numCoordinadores, - costCoordinacion, - numSacadores, - costSacado, - numEncajadores, - costEncajado, - numPaletizadores, - costPaletizado, - numCamareros, - costCamara, - numComplementos, - costComplementos, - numArtificial, - costArtificial - FROM tmp.productivity p; - - -- Productivity Evolution - REPLACE bs.productivity_evolution(dated, m3productionCost) - SELECT CURDATE(), sum(wCost) / sum(m3) - FROM bs.productivity - WHERE dated BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND CURDATE(); - - DROP TEMPORARY TABLE tmp.dayMinuteWorker; - DROP TEMPORARY TABLE tmp.productivity; - DROP TEMPORARY TABLE tmp.ticketBuiltTime; - DROP TEMPORARY TABLE tmp.ticketVolumeByDate; - DROP TEMPORARY TABLE tmp.workerDepartmentByDate; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentAdd`(IN vDateStartPeriod DATETIME, IN vDateEndPeriod DATETIME, IN vDateStart DATETIME) -BEGIN - - DECLARE vEndingDate DATETIME; - - SET vEndingDate = vDateStart; - - WHILE vEndingDate <= vDateEndPeriod DO - REPLACE INTO bs.productivityDepartment - SELECT vEndingDate, - CAST(((productivityCoordinacionLastYear - productivityCoordinacion) / 2) * m3 AS DECIMAL (10,2)) AS amountCoordinacion, - CAST(((productivitySacadoLastYear - productivitySacado) / 2) * m3 AS DECIMAL (10,2)) AS amountSacado, - CAST(((productivityEncajadoLastYear - productivityEncajado) / 2) * m3 AS DECIMAL (10,2)) AS amountEncajado, - CAST(((productivityPaletizadoLastYear - productivityPaletizado) / 2) * m3 AS DECIMAL (10,2)) AS amountPaletizado, - CAST(((productivityCamaraLastYear - productivityCamara) / 2) * m3FV AS DECIMAL (10,2)) AS amountCamara, - CAST(((productivityComplementosLastYear - productivityComplementos) / 2) * m3PCA AS DECIMAL (10,2)) AS amountComplementos, - CAST(((productivityArtificialLastYear - productivityArtificial) / 2) * m3Artificial AS DECIMAL (10,2)) AS amountArtificia - FROM - (SELECT - SUM(p.m3) AS m3, SUM(p.m3FV) as m3FV, SUM(p.m3PCA) as m3PCA, SUM(p.m3Artificial) as m3Artificial, - SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacion, - SUM(p.costSacado) / SUM(p.m3) AS productivitySacado, - SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajado, - SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizado, - SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamara, - SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementos, - SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificial - FROM - bs.productivity p - WHERE - p.dated BETWEEN vDateStartPeriod AND vEndingDate) sub - JOIN - (SELECT - SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacionLastYear, - SUM(p.costSacado) / SUM(p.m3) AS productivitySacadoLastYear, - SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajadoLastYear, - SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizadoLastYear, - SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamaraLastYear, - SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementosLastYear, - SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificialLastYear - FROM - bs.productivity p - WHERE - p.dated BETWEEN DATE_ADD(vDateStartPeriod, INTERVAL - 1 YEAR) AND DATE_ADD(vEndingDate, INTERVAL - 1 YEAR)) sub1; - - SET vEndingDate = TIMESTAMPADD(DAY,1, vEndingDate); - END WHILE; - END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentLauncher`() -BEGIN - CALL bs.productivityDepartmentAdd('2019-05-06', CURDATE(),DATE_SUB(CURDATE(), INTERVAL 2 WEEK)); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher`() -BEGIN - - DECLARE vDateFrom DATE; - - SELECT LEAST(TIMESTAMPADD(MONTH, -1, CURDATE()),MAX(dated)) - INTO vDateFrom - FROM bs.productivity; - - WHILE CURDATE() > vDateFrom DO - CALL bs.productivityAdd(vDateFrom); - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - END WHILE; - - SET vDateFrom = TIMESTAMPADD(MONTH, -13, CURDATE()); - - WHILE TIMESTAMPADD(MONTH, -12, CURDATE()) > vDateFrom DO - CALL bs.productivityAdd(vDateFrom); - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher_manual` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher_manual`(vDateFrom DATE, vToDate DATE) -BEGIN - - TRUNCATE tmp.log; - - WHILE vToDate >= vDateFrom DO - - INSERT INTO tmp.log(text) VALUES (vDateFrom); - CALL bs.productivityAdd(vDateFrom); - - CALL bs.productivityAdd(TIMESTAMPADD(YEAR, -1,vDateFrom)); - INSERT INTO tmp.log(text) VALUES (TIMESTAMPADD(YEAR, -1,vDateFrom)); - - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `pruebas` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `pruebas`(IN vDateStart DATE, IN vDateEnd DATE) -BEGIN - -WHILE vDateStart <> vDateEnd -DO - UPDATE indicators - SET countEmployee = - ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) - FROM - postgresql.business AS b - JOIN postgresql.profile p ON p.profile_id = b.provider_id - JOIN postgresql.person pe ON pe.person_id = p.person_id - LEFT JOIN - postgresql.business_labour AS bl ON bl.business_id = b.business_id - LEFT JOIN - postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id - WHERE - (vDateStart BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDateStart)) - AND pe.name = 'VERDNATURA LEVANTE SL' - ) - WHERE updated = vDateStart; - SET vDateStart = DATE_ADD(vDateStart, INTERVAL 1 DAY); - -END WHILE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `salePersonEvolutionAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) -BEGIN - DELETE FROM bs.salePersonEvolution - WHERE dated <= DATE_SUB(CURDATE(), INTERVAL 1 YEAR); - - - INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) - 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.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; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userSundayRole` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userSundayRole`() -BEGIN - -- 4996 Fran Natek Echevarria - DECLARE vDay INT; - SET vDay := (SELECT DAYOFWEEK(CURDATE())); - IF vDay = 1 THEN - UPDATE account.user u - JOIN account.role r - SET u.role = r.id - WHERE u.id = 4996 AND r.name = "salesAssistant"; - ELSE - UPDATE account.user u - JOIN account.role r - SET u.role = r.id - WHERE u.id = 4996 AND r.name = "salesPerson"; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add`(intYEAR INT, vQuarter INT) -BEGIN - - DECLARE comisionRate DOUBLE DEFAULT 0.029; - - REPLACE vendedores - SELECT c.Id_Trabajador - , intYEAR - , MONTH(v.fecha) intMONTH - , sum(importe) as importe - , sum(importe) * 0.029 as comision - , 0 as comisionCedida - , 0 as comisionArrendada - , 0 as comisionNuevos - - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY c.Id_Trabajador, t.`month`; - - -- Ventas nuevas - UPDATE vendedores v - JOIN - ( - SELECT c.Id_Trabajador - , sum(importe) * 0.029 as comisionNueva - , t.`month` - , t.`year` - FROM ventas v - JOIN bs.clientNewBorn cnb on v.Id_Cliente = cnb.clientFk - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY c.Id_Trabajador, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionNuevos = sub.comisionNueva, v.comision = v.comision - sub.comisionNueva; - - -- Ventas cedidas - UPDATE vendedores v - JOIN ( - SELECT cc.Id_Trabajador_old as Id_Trabajador - , sum(importe) * 0.029 * comision_old as cedido - , sum(importe) * 0.029 * comision_new as arrendada - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY cc.Id_Trabajador_old, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionCedida = sub.cedido, v.comision = v.comision - sub.cedido - sub.arrendada; - - -- Ventas arrendadas - UPDATE vendedores v - JOIN ( - SELECT cc.Id_Trabajador_new as Id_Trabajador - , sum(importe) * 0.029 * comision_new as arrendada - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY cc.Id_Trabajador_new, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionArrendada = sub.arrendada; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add_launcher`() -BEGIN - - call bs.vendedores_add(YEAR(CURDATE()),QUARTER(CURDATE())); - - call bs.vendedores_evolution_add; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_evolution_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_evolution_add`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes - -*/ - -DECLARE vYear, vMonth INTEGER; -DECLARE vCurYear, vCurMonth INTEGER; -DECLARE vFirstYear INTEGER DEFAULT 2017; -DECLARE vFirstMonth INTEGER DEFAULT 1; - -DECLARE vDateFrom DATE; -DECLARE vDateTo DATE; - -SET vCurYear = year(CURDATE()); -SET vCurMonth = month(CURDATE()); - -SELECT IFNULL(max(year),vFirstYear), IFNULL(max(month),vFirstMonth) - INTO vYear, vMonth - FROM bs.vendedores_evolution; - - WHILE (vYear < vCurYear) OR (vYear = vCurYear AND vMonth < vCurMonth) DO - - SELECT max(dated), TIMESTAMPADD(DAY,-364,max(dated)) INTO vDateTo, vDateFrom - FROM vn.time - WHERE year = vYear - AND month = vMonth; - - SELECT vDateTo, vDateFrom, vYear, vMonth; - - REPLACE bs.vendedores_evolution( workerFk - , year - , month - , sales) - SELECT c.salesPersonFk - , vYear as year - , vMonth as month - , sum(v.importe) as sales - FROM bs.ventas v - JOIN vn.client c on c.id = v.Id_Cliente - WHERE v.fecha BETWEEN vDateFrom AND vDateTo - AND c.salesPersonFk is not null - GROUP BY c.salesPersonFk; - - SET vMonth = vMonth + 1; - - IF vMonth = 13 THEN - - SET vMonth = 1; - SET vYear = vYear + 1; - - END IF; - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add`(IN datSTART DATETIME, IN datEND DATETIME) -BEGIN - - DECLARE vStartingDate DATETIME; - DECLARE vEndingDate DATETIME; - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - IF datSTART < '2015-10-01' OR datEND < '2015-10-01' THEN - CALL util.throw('fechaDemasiadoAntigua'); - END IF; - - SET datEND = util.dayEnd(datEND); - SET vStartingDate = datSTART; - SET vEndingDate = vn2008.dayend(vStartingDate); - - DELETE - FROM ventas - WHERE fecha between vStartingDate and datEND; - - WHILE vEndingDate <= datEND DO - - REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) - SELECT Id_Movimiento, - SUM(IF(base, Cantidad * Valor, 0)) as importe, - SUM(IF(base, 0, Cantidad * Valor)) as recargo, - vStartingDate, - a.tipo_id, - cs.Id_Cliente, - t.empresa_id - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE t.Fecha between vStartingDate and vEndingDate - AND c.typeFk IN ('Normal','handMaking','internalUse') - AND m.Cantidad <> 0 - AND a.tipo_id != TIPO_PATRIMONIAL - AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) - GROUP BY mc.Id_Movimiento - HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - - SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); - SET vEndingDate = util.dayEnd(vStartingDate); - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add_launcher`() -BEGIN - - call bs.ventas_add(timestampadd(week,-1,curdate()),curdate()); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add__`(IN datSTART DATETIME, IN datEND DATETIME) -BEGIN - - DECLARE vStartingDate DATETIME; - DECLARE vEndingDate DATETIME; - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - SET datEND = util.dayEnd(datEND); - SET vStartingDate = GREATEST('2015-10-01',datSTART); - SET vEndingDate = vn2008.dayend(vStartingDate); - - DELETE - FROM ventas - WHERE fecha between vStartingDate and datEND; - - WHILE vEndingDate <= datEND DO - - REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) - SELECT Id_Movimiento, - SUM(IF(base, Cantidad * Valor, 0)) as importe, - SUM(IF(base, 0, Cantidad * Valor)) as recargo, - vStartingDate, - a.tipo_id, - cs.Id_Cliente, - t.empresa_id - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE t.Fecha between vStartingDate and vEndingDate - AND datEND >= '2015-10-01' - AND c.typeFk IN ('Normal','handMaking','internalUse') - AND m.Cantidad <> 0 - AND a.tipo_id != TIPO_PATRIMONIAL - AND c.Id_Trabajador IS NOT NULL - AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) - GROUP BY mc.Id_Movimiento - HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - - SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); - SET vEndingDate = util.dayEnd(vStartingDate); - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) -BEGIN -/** - * Reemplaza las ventas contables. Es el origen de datos para el balance de Entradas - * - * @param vYear Año a reemplazar - * @param vMonth Mes a reemplazar - * - * - **/ -DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - -DELETE FROM bs.ventas_contables - WHERE year = vYear - AND month = vMonth; - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - -INSERT INTO bs.ventas_contables(year - , month - , venta - , grupo - , reino_id - , tipo_id - , empresa_id - , gasto) - - SELECT vYear - , vMonth - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) - , if( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) as grupo - , tp.reino_id - , a.tipo_id - , t.empresa_id - , 7000000000 - + if(e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) * 1000000 - + tp.reino_id * 10000 as Gasto - 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 - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 - AND Preu <> 0 - AND m.Descuento <> 100 - AND a.tipo_id != TIPO_PATRIMONIAL - GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; - - -DROP TEMPORARY TABLE tmp.ticket_list; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add_launcher`() -BEGIN - - call bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_por_cliente` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) -BEGIN - - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - - - SELECT vYear Año - , vMonth Mes - , t.Id_Cliente - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) Venta - , if( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) as grupo - , t.empresa_id empresa - 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 - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 - AND Preu <> 0 - AND m.Descuento <> 100 - AND a.tipo_id != 188 - GROUP BY t.Id_Cliente, grupo,t.empresa_id; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vivosMuertos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vivosMuertos`() -BEGIN - -SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE()); -SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),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 -JOIN (SELECT DISTINCT yearMonth FROM vn2008.time WHERE date BETWEEN @datSTART AND @datEND ) tm -LEFT JOIN - (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - 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 - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth 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 - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente -SET Muerto = 1 -WHERE yearMonth < @lastYearMonth; - - SELECT * FROM tmp.VivosMuertos; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed`() -BEGIN - - /* #UPDATED PAK 2019/09/02 - * #PENDING REVIEW - * - * - * - * - */ - - DECLARE vLastUpdated DATETIME; - DECLARE vSecondsDelay INT DEFAULT 300; - - SELECT IFNULL(MAX(lastUpdated),CURDATE()) INTO vLastUpdated - FROM bs.workerSpeed; - - IF TIMESTAMPDIFF(SECOND, vLastUpdated, NOW()) > vSecondsDelay THEN - - DELETE FROM bs.workerSpeed ; - -- WHERE lastUpdated < CURDATE(); - - -- Sacadores - REPLACE bs.workerSpeed - SELECT workerCode, - accion, - warehouseFk, - CAST(60 * sumaLitros / time_to_sec(timediff(finished, started)) AS DECIMAL(10,1)) as LitrosMinuto, - CAST(sumaLitrosLastHour / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, - now() as lastUpdated - FROM - ( - SELECT warehouseFk, - accion, - workerCode, - sum(litros) as sumaLitros, - min(created) as started, - max(created) as finished, - sum(IF(created >= TIMESTAMPADD(HOUR, -1, NOW()),litros, 0)) as sumaLitrosLastHour - FROM - ( - SELECT t.warehouseFk, - st.saleFk, - st.isChecked, - st.originalQuantity, - a.accion, - st.created, - e.code, - w.firstname, - w.lastName, - w.code as workerCode, - r.cm3 * s.quantity / 1000 as litros, - s.concept - FROM vn.saleTracking st - LEFT JOIN - (SELECT saleFk - FROM vn.saleTracking st - JOIN vn.state e ON e.id = st.stateFk - WHERE st.created > CURDATE() - AND e.code LIKE 'PREVIOUS_PREPARATION') prevPrepSales ON prevPrepSales.saleFk = st.saleFk - JOIN vn.sale s ON s.id = st.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.state e ON e.id = st.stateFk - JOIN vncontrol.accion a ON a.accion_id = st.actionFk - WHERE st.created > TIMESTAMPADD(HOUR,-1,NOW()) - AND prevPrepSales.saleFk IS NULL - ) sub - GROUP BY warehouseFk, accion, workerCode - ) sub2; - - -- Encajadores - REPLACE bs.workerSpeed - SELECT code as workerCode, - 'ENCAJAR' as accion, - warehouseFk, - CAST(60 * sum(Litros) / time_to_sec(timediff(MAX(finished), MIN(started))) AS DECIMAL(10,1)) as LitrosMinuto, - CAST(sum(litrosUltimaHora) / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, - now() as lastUpdated - FROM ( - SELECT sv.ticketFk, - sum(sv.litros) as litros, - sum(IF(started > TIMESTAMPADD(HOUR,-1,NOW()),sv.litros,0)) as litrosUltimaHora, - code, - started, - finished, - cajas, - warehouseFk - FROM vn.saleVolume sv - JOIN - ( - SELECT ticketFk, - min(e.created) as started, - max(e.created) as finished, - max(counter) as cajas, - w.code, - t.warehouseFk - FROM vn.expedition e - JOIN vn.worker w ON w.id = e.workerFk - JOIN vn.ticket t ON t.id = e.ticketFk - WHERE e.created > CURDATE() - GROUP BY ticketFk - ) sub ON sub.ticketFk = sv.ticketFk - GROUP BY sv.ticketFk) sub2 - GROUP BY code; - - END IF; - - SELECT * FROM bs.workerSpeed; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed_detail` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed_detail`(vWorkerCode VARCHAR(3), vAction VARCHAR(25)) -BEGIN - - SELECT * FROM - ( - SELECT time_format(st.created,'%H:%i') as hora, - t.warehouseFk as Almacen, - t.id as ticketFk, - floor(sum(s.quantity * r.cm3) / 1000) as Litros - - FROM vn.saleTracking st - JOIN vn.sale s ON s.id = st.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.state e ON e.id = st.stateFk - JOIN vncontrol.accion a ON a.accion_id = st.actionFk - WHERE st.created > CURDATE() - AND a.accion LIKE vAction - AND w.code LIKE vWorkerCode - GROUP BY t.id) sub - ORDER BY hora; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - -- -- Current Database: `cache` -- @@ -8863,9 +5409,9 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalc_clean`() -BEGIN - DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); - DELETE FROM cache_calc WHERE expires < vCleanTime; +BEGIN + DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); + DELETE FROM cache_calc WHERE expires < vCleanTime; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8883,27 +5429,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8921,88 +5467,88 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires - 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' - 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 NOW() < v_expires - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires + 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' + 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 NOW() < v_expires + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9020,24 +5566,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT) -proc: BEGIN - DECLARE v_cache_name VARCHAR(50); - DECLARE v_params VARCHAR(100); - - IF v_calc IS NULL THEN - LEAVE proc; - END IF; - - SELECT c.name, ca.params INTO v_cache_name, v_params - 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 - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +proc: BEGIN + DECLARE v_cache_name VARCHAR(50); + DECLARE v_params VARCHAR(100); + + IF v_calc IS NULL THEN + LEAVE proc; + END IF; + + SELECT c.name, ca.params INTO v_cache_name, v_params + 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 + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9056,9 +5602,9 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_clean`() NO SQL -BEGIN - CALL available_clean; - CALL visible_clean; +BEGIN + CALL available_clean; + CALL visible_clean; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9076,13 +5622,13 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10546,158 +7092,158 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) -BEGIN - DECLARE vRef INT; - DECLARE vBuy INT; - DECLARE vItem INT; - DECLARE vQty INT; - DECLARE vPackage INT; - DECLARE vIsLot BOOLEAN; - DECLARE vForceToPacking INT DEFAULT 2; - - -- Carga los datos necesarios del EKT - - SELECT ref, qty, package INTO vRef, vQty, vPackage - FROM ekt e - LEFT JOIN item i ON e.ref = i.id - WHERE e.id = vSelf; - - -- Inserta el cubo si no existe - - IF vPackage = 800 - THEN - SET vPackage = 800 + vQty; - - INSERT IGNORE INTO vn2008.Cubos SET - Id_Cubo = vPackage, - x = 7200 / vQty, - y = 1; - 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 - `subject` = 'Cubo añadido', - `text` = CONCAT('Se ha añadido el cubo: ', vPackage), - `to` = 'ekt@verdnatura.es'; - END IF; - END IF; - - -- Intenta obtener el artículo en base a los atributos holandeses - - INSERT IGNORE INTO item_track SET - item_id = vRef; - - SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem - FROM vn2008.buy_edi e - JOIN item_track t ON t.item_id = e.ref - LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref - LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id - JOIN vn2008.config cfg - WHERE e.id = vSelf - AND l.id != vSelf - AND c.Id_Article != cfg.generic_item - AND IF(t.s1, l.s1 = e.s1, TRUE) - AND IF(t.s2, l.s2 = e.s2, TRUE) - AND IF(t.s3, l.s3 = e.s3, TRUE) - AND IF(t.s4, l.s4 = e.s4, TRUE) - AND IF(t.s5, l.s5 = e.s5, TRUE) - AND IF(t.s6, l.s6 = e.s6, TRUE) - AND IF(t.kop, l.kop = e.kop, TRUE) - AND IF(t.pac, l.pac = e.pac, TRUE) - AND IF(t.cat, l.cat = e.cat, TRUE) - AND IF(t.ori, l.ori = e.ori, TRUE) - AND IF(t.pro, l.pro = e.pro, TRUE) - AND IF(t.sub, l.sub = e.sub, TRUE) - AND IF(t.package, l.package = e.package, TRUE) - AND c.Id_Article < 170000 - ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; - - -- Determina si el articulo se vende por lotes - - IF vItem - THEN - SELECT COUNT(*) > 0 INTO vIsLot - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE a.Id_Article = vItem - AND t.`transaction`; - - -- Si el articulo se vende por lotes se inserta un nuevo artículo - - IF vIsLot - THEN - INSERT INTO vn2008.Articles ( - Article - ,Medida - ,Categoria - ,Id_Origen - ,iva_group_id - ,Foto - ,Color - ,Codintrastat - ,tipo_id - ,Tallos - ) - SELECT - i.`name` - ,IFNULL(e.s1, e.pac) - ,e.cat - ,IFNULL(o.id, 17) - ,IFNULL(a.iva_group_id, 1) - ,a.Foto - ,a.Color - ,a.Codintrastat - ,IFNULL(a.tipo_id, 10) - ,IF(a.tipo_id = 15, 0, 1) - FROM vn2008.buy_edi e - LEFT JOIN item i ON i.id = e.ref - LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori - LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem - WHERE e.id = vSelf; - - SET vItem = LAST_INSERT_ID(); - END IF; - END IF; - - -- Inserta la compra asociada al EKT - - INSERT INTO vn2008.Compres - ( - Id_Entrada - ,buy_edi_id - ,Costefijo - ,Id_Article - ,`grouping` - ,caja - ,Packing - ,Cantidad - ,Productor - ,Etiquetas - ,Id_Cubo - ) - SELECT - cfg.edi_entry - ,vSelf - ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri - ,IFNULL(vItem, cfg.generic_item) - ,IFNULL(c.`grouping`, e.pac) - ,vForceToPacking - ,@pac := e.pac / @t - ,@pac * e.qty - ,s.company_name - ,e.qty - ,IFNULL(c.Id_Cubo, e.package) - FROM vn2008.buy_edi e - LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy - LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN supplier s ON e.pro = s.supplier_id - JOIN vn2008.config cfg - WHERE e.id = vSelf - LIMIT 1; +BEGIN + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + + -- Carga los datos necesarios del EKT + + SELECT ref, qty, package INTO vRef, vQty, vPackage + FROM ekt e + LEFT JOIN item i ON e.ref = i.id + WHERE e.id = vSelf; + + -- Inserta el cubo si no existe + + IF vPackage = 800 + THEN + SET vPackage = 800 + vQty; + + INSERT IGNORE INTO vn2008.Cubos SET + Id_Cubo = vPackage, + x = 7200 / vQty, + y = 1; + 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 + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Intenta obtener el artículo en base a los atributos holandeses + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem + FROM vn2008.buy_edi e + JOIN item_track t ON t.item_id = e.ref + LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref + LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND c.Id_Article != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.kop, l.kop = e.kop, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.sub, l.sub = e.sub, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND c.Id_Article < 170000 + ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; + + -- Determina si el articulo se vende por lotes + + IF vItem + THEN + SELECT COUNT(*) > 0 INTO vIsLot + FROM vn2008.Articles a + LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + WHERE a.Id_Article = vItem + AND t.`transaction`; + + -- Si el articulo se vende por lotes se inserta un nuevo artículo + + IF vIsLot + THEN + INSERT INTO vn2008.Articles ( + Article + ,Medida + ,Categoria + ,Id_Origen + ,iva_group_id + ,Foto + ,Color + ,Codintrastat + ,tipo_id + ,Tallos + ) + SELECT + i.`name` + ,IFNULL(e.s1, e.pac) + ,e.cat + ,IFNULL(o.id, 17) + ,IFNULL(a.iva_group_id, 1) + ,a.Foto + ,a.Color + ,a.Codintrastat + ,IFNULL(a.tipo_id, 10) + ,IF(a.tipo_id = 15, 0, 1) + FROM vn2008.buy_edi e + LEFT JOIN item i ON i.id = e.ref + LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori + LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem + WHERE e.id = vSelf; + + SET vItem = LAST_INSERT_ID(); + END IF; + END IF; + + -- Inserta la compra asociada al EKT + + INSERT INTO vn2008.Compres + ( + Id_Entrada + ,buy_edi_id + ,Costefijo + ,Id_Article + ,`grouping` + ,caja + ,Packing + ,Cantidad + ,Productor + ,Etiquetas + ,Id_Cubo + ) + SELECT + cfg.edi_entry + ,vSelf + ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri + ,IFNULL(vItem, cfg.generic_item) + ,IFNULL(c.`grouping`, e.pac) + ,vForceToPacking + ,@pac := e.pac / @t + ,@pac * e.qty + ,s.company_name + ,e.qty + ,IFNULL(c.Id_Cubo, e.package) + FROM vn2008.buy_edi e + LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy + LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + LEFT JOIN supplier s ON e.pro = s.supplier_id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10747,154 +7293,154 @@ CREATE DEFINER=`root`@`%` PROCEDURE `exchange_new`( IN `vAuction` SMALLINT, IN `vPackage` INT, IN `vPutOrderFk` INT) -BEGIN +BEGIN /** * Adds a new exchange, generates it's barcode and * inserts/updates the transaction. When the referenced * transaction exists as provisional, updates it with - * the new values. - */ - DECLARE vEkt INT; - DECLARE vRewriteKop INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; - DECLARE vIsDuplicated BOOL; + * the new values. + */ + DECLARE vEkt INT; + DECLARE vRewriteKop INT DEFAULT NULL; + DECLARE vBarcode CHAR(15) DEFAULT NULL; + DECLARE vIsDuplicated BOOL; DECLARE vUpdateExistent BOOL DEFAULT FALSE; - DECLARE duplicateKey CONDITION FOR 1062; + DECLARE duplicateKey CONDITION FOR 1062; + + DECLARE CONTINUE HANDLER FOR duplicateKey + SET vIsDuplicated = TRUE; + + -- Generates the barcode + + IF vAgj != 0 AND vAgj IS NOT NULL + THEN + SET vBarcode = CONCAT( + LPAD(vAuction, 2, 0), + LPAD(IFNULL(vClock, 99), 2, 0), + LPAD(DAYOFYEAR(vDate), 3, 0), + IF(vClock IS NULL OR vClock = 99, + LPAD(vAgj, 7, 0), + CONCAT(LPAD(vAgj, 5, 0), '01') + ), + '0' + ); + END IF; + + -- Rewrites the kop parameter + + IF vKop IS NULL THEN + SELECT defaultKop INTO vKop FROM exchangeConfig; + END IF; + + SELECT e.kop INTO vRewriteKop + FROM mailSender e + JOIN mail m ON m.senderFk = e.id + WHERE m.id = vMailFk; + + SET vKop = IFNULL(vRewriteKop, vKop); + + -- Inserts the new transaction - DECLARE CONTINUE HANDLER FOR duplicateKey - SET vIsDuplicated = TRUE; - - -- Generates the barcode - - IF vAgj != 0 AND vAgj IS NOT NULL - THEN - SET vBarcode = CONCAT( - LPAD(vAuction, 2, 0), - LPAD(IFNULL(vClock, 99), 2, 0), - LPAD(DAYOFYEAR(vDate), 3, 0), - IF(vClock IS NULL OR vClock = 99, - LPAD(vAgj, 7, 0), - CONCAT(LPAD(vAgj, 5, 0), '01') - ), - '0' - ); - END IF; - - -- Rewrites the kop parameter - - IF vKop IS NULL THEN - SELECT defaultKop INTO vKop FROM exchangeConfig; - END IF; - - SELECT e.kop INTO vRewriteKop - FROM mailSender e - JOIN mail m ON m.senderFk = e.id - WHERE m.id = vMailFk; - - SET vKop = IFNULL(vRewriteKop, vKop); - - -- Inserts the new transaction - - SET vIsDuplicated = FALSE; - INSERT INTO ekt SET - barcode = IFNULL(vBarcode, barcode) - ,deliveryNumber = vDeliveryNumber - ,entryYear = YEAR(vDate) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk; - - -- If it exists duplicado updates it - - IF NOT vIsDuplicated - THEN - SET vEkt = LAST_INSERT_ID(); - CALL ekt_load (vEkt); - - ELSEIF vDeliveryNumber != 0 - AND vDeliveryNumber IS NOT NULL - THEN - SELECT id INTO vEkt - FROM ekt - WHERE deliveryNumber = vDeliveryNumber; - - SELECT COUNT(*) = 0 INTO vUpdateExistent - FROM ekt t - JOIN `exchange` b ON b.ektFk = t.id - JOIN exchangeConfig c - WHERE t.deliveryNumber = vDeliveryNumber - AND t.entryYear = YEAR(vDate) - AND b.typeFk != c.presaleFk; - END IF; - - IF vUpdateExistent - THEN - UPDATE ekt SET - barcode = IFNULL(vBarcode, barcode) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk - WHERE id = vEkt; - END IF; - - -- Registers the exchange - - INSERT INTO `exchange` SET - mailFk = vMailFk - ,typeFk = vType - ,ektFk = vEkt; + SET vIsDuplicated = FALSE; + INSERT INTO ekt SET + barcode = IFNULL(vBarcode, barcode) + ,deliveryNumber = vDeliveryNumber + ,entryYear = YEAR(vDate) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk; + + -- If it exists duplicado updates it + + IF NOT vIsDuplicated + THEN + SET vEkt = LAST_INSERT_ID(); + CALL ekt_load (vEkt); + + ELSEIF vDeliveryNumber != 0 + AND vDeliveryNumber IS NOT NULL + THEN + SELECT id INTO vEkt + FROM ekt + WHERE deliveryNumber = vDeliveryNumber; + + SELECT COUNT(*) = 0 INTO vUpdateExistent + FROM ekt t + JOIN `exchange` b ON b.ektFk = t.id + JOIN exchangeConfig c + WHERE t.deliveryNumber = vDeliveryNumber + AND t.entryYear = YEAR(vDate) + AND b.typeFk != c.presaleFk; + END IF; + + IF vUpdateExistent + THEN + UPDATE ekt SET + barcode = IFNULL(vBarcode, barcode) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk + WHERE id = vEkt; + END IF; + + -- Registers the exchange + + INSERT INTO `exchange` SET + mailFk = vMailFk + ,typeFk = vType + ,ektFk = vEkt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12970,30 +9516,30 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN) -BEGIN -/** - * Lists visible items and it's box sizes of the specified - * type at specified date. - * - * @param vWh The warehouse id - * @param vDate The visible date - * @param vType The type id - * @param vPrefix The article prefix to filter or %NULL for all - * @param vUseIds Whether to order the result by item id - * @select List of visible items with it's box sizes - */ - CALL item_getVisible(vWh, vDate, vType, vPrefix); - - IF vUseIds - THEN - SELECT * FROM tmp.itemVisible - ORDER BY Id_Article; - ELSE - SELECT * FROM tmp.itemVisible - ORDER BY Article, packing; - END IF; - - DROP TEMPORARY TABLE tmp.itemVisible; +BEGIN +/** + * Lists visible items and it's box sizes of the specified + * type at specified date. + * + * @param vWh The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @param vUseIds Whether to order the result by item id + * @select List of visible items with it's box sizes + */ + CALL item_getVisible(vWh, vDate, vType, vPrefix); + + IF vUseIds + THEN + SELECT * FROM tmp.itemVisible + ORDER BY Id_Article; + ELSE + SELECT * FROM tmp.itemVisible + ORDER BY Article, packing; + END IF; + + DROP TEMPORARY TABLE tmp.itemVisible; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18334,8 +14880,8 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `log_add_beta`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) -proc: BEGIN - -- XXX: Disabled while testing +proc: BEGIN + -- XXX: Disabled while testing DECLARE vLanded DATE; DECLARE vWarehouseFk INT; DECLARE vBuyerFk INT; @@ -18343,20 +14889,20 @@ proc: BEGIN DECLARE vItemFk INT; DECLARE vItemName VARCHAR(50); - -- LEAVE proc; + -- LEAVE proc; - IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vOldId, - operation = 'delete'; - END IF; - - IF vNewId IS NOT NULL THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vNewId, - operation = 'insert'; + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; END IF; IF vTableName = 'buy' THEN @@ -18386,7 +14932,7 @@ proc: BEGIN END IF; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18654,29 +15200,29 @@ CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshSale`( BEGIN DROP TEMPORARY TABLE IF EXISTS tValues; CREATE TEMPORARY TABLE tValues - ENGINE = MEMORY - SELECT - m.id saleFk, - m.ticketFk, - m.itemFk, - t.warehouseFk, - t.shipped, + ENGINE = MEMORY + SELECT + m.id saleFk, + m.ticketFk, + m.itemFk, + t.warehouseFk, + t.shipped, ABS(m.quantity) quantity, m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked - FROM vn.sale m - JOIN vn.ticket t ON t.id = m.ticketFk + m.isPicked OR s.alertLevel > 1 isPicked + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.item i ON i.id = m.itemFk - JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.itemType tp ON tp.id = i.typeFk WHERE ( - vTableId IS NULL - OR (vTableName = 'ticket' AND t.id = vTableId) - OR (vTableName = 'sale' AND m.id = vTableId) - ) - AND t.shipped >= vn.getInventoryDate() + vTableId IS NULL + OR (vTableName = 'ticket' AND t.id = vTableId) + OR (vTableName = 'sale' AND m.id = vTableId) + ) + AND t.shipped >= vn.getInventoryDate() AND m.quantity != 0; REPLACE INTO inbound ( @@ -18709,7 +15255,7 @@ BEGIN FROM tValues WHERE !isIn; - DROP TEMPORARY TABLE tValues; + DROP TEMPORARY TABLE tValues; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21664,14 +18210,31 @@ CREATE TABLE `clientLog` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Temporary table structure for view `clientManaCache` +-- Table structure for table `clientManaCache` -- DROP TABLE IF EXISTS `clientManaCache`; -/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientManaCache` ( + `clientFk` int(11) NOT NULL, + `mana` decimal(10,0) NOT NULL DEFAULT '0', + `dated` date NOT NULL, + PRIMARY KEY (`clientFk`,`dated`), + KEY `manaCustomerIdx1` (`dated`), + CONSTRAINT `cliente_fk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `clientManaCache__` +-- + +DROP TABLE IF EXISTS `clientManaCache__`; +/*!50001 DROP VIEW IF EXISTS `clientManaCache__`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientManaCache` AS SELECT +/*!50001 CREATE VIEW `clientManaCache__` AS SELECT 1 AS `clientFk`, 1 AS `mana`, 1 AS `dated`*/; @@ -30053,6 +26616,20 @@ CREATE TABLE `workerMana` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `workerManaExcluded` +-- + +DROP TABLE IF EXISTS `workerManaExcluded`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `workerManaExcluded` ( + `workerFk` int(11) NOT NULL, + PRIMARY KEY (`workerFk`), + CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `workerMana__` -- @@ -30747,90 +27324,90 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN - - DECLARE vCurrentCount INT; - DECLARE vCheckSum INT; - DECLARE vIsAlreadyNotified BOOLEAN; - DECLARE vTableQueue TEXT; - DECLARE vLineQueue TEXT; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCur CURSOR FOR - SELECT CONCAT(' - ', IFNULL(pq.id, ''), ' - ', IFNULL(p.path, ''),' - ', IFNULL(i.Informe, ''),' - ', IFNULL(e.Estado, ''),' - ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' - ', IFNULL(pq.`error`, ''),' - ') - FROM vn.printingQueue pq - LEFT JOIN vn.worker w ON w.id = pq.worker - LEFT JOIN vn.printer p ON p.id = pq.printer - LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report - JOIN vn2008.Estados e ON e.Id_Estado = pq.state - LIMIT 30; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum - FROM vn.printingQueue WHERE state = 1; - - SELECT isAlreadyNotified INTO vIsAlreadyNotified - FROM printingQueueCheck; - - IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND - (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND - vIsAlreadyNotified = FALSE AND vCurrentCount > 0 - THEN - - SELECT ' - - - - - - - - ' INTO vTableQueue; - - OPEN vCur; - - l: LOOP - - SET vDone = FALSE; - - FETCH vCur INTO vLineQueue; - - IF vDone THEN - LEAVE l; - END IF; - - SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; - - END LOOP; - - CLOSE vCur; - - INSERT INTO vn2008.mail (`to`, subject, text) - VALUES ('cau@verdnatura.es', - 'servidor de impresion parado', - CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); - - UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; - END IF; - - IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND - vIsAlreadyNotified = TRUE - THEN - UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; - END IF; - - UPDATE printingQueueCheck - SET lastCount = vCurrentCount, - lastCheckSum = vCheckSum; - +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN + + DECLARE vCurrentCount INT; + DECLARE vCheckSum INT; + DECLARE vIsAlreadyNotified BOOLEAN; + DECLARE vTableQueue TEXT; + DECLARE vLineQueue TEXT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCur CURSOR FOR + SELECT CONCAT(' + ', IFNULL(pq.id, ''), ' + ', IFNULL(p.path, ''),' + ', IFNULL(i.Informe, ''),' + ', IFNULL(e.Estado, ''),' + ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' + ', IFNULL(pq.`error`, ''),' + ') + FROM vn.printingQueue pq + LEFT JOIN vn.worker w ON w.id = pq.worker + LEFT JOIN vn.printer p ON p.id = pq.printer + LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report + JOIN vn2008.Estados e ON e.Id_Estado = pq.state + LIMIT 30; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum + FROM vn.printingQueue WHERE state = 1; + + SELECT isAlreadyNotified INTO vIsAlreadyNotified + FROM printingQueueCheck; + + IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND + (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND + vIsAlreadyNotified = FALSE AND vCurrentCount > 0 + THEN + + SELECT ' + + + + + + + + ' INTO vTableQueue; + + OPEN vCur; + + l: LOOP + + SET vDone = FALSE; + + FETCH vCur INTO vLineQueue; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; + + END LOOP; + + CLOSE vCur; + + INSERT INTO vn2008.mail (`to`, subject, text) + VALUES ('cau@verdnatura.es', + 'servidor de impresion parado', + CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); + + UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; + END IF; + + IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND + vIsAlreadyNotified = TRUE + THEN + UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; + END IF; + + UPDATE printingQueueCheck + SET lastCount = vCurrentCount, + lastCheckSum = vCheckSum; + END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -34153,6 +30730,35 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `validationCode` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `validationCode`(vString VARCHAR(255)) RETURNS int(11) + DETERMINISTIC +BEGIN + + DECLARE vTail VARCHAR(3); + DECLARE vCode INT; + + SET vTail = LEFT(LPAD(vString,3,'0'),3); + + SET vCode = (ASCII(MID(vTail,1,1)) * ASCII(MID(vTail,2,1)) * ASCII(MID(vTail,3,1))) mod 1000; + + RETURN vCode; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `workerIsBoss` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -35855,27 +32461,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean__`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE oneYearAgo DATE; - DECLARE twoYearsAgo DATE; - DECLARE fourYearsAgo DATE; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); - SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); - SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); - - DELETE FROM vn.message WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; - DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; - DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); - CALL shelving_clean; - +BEGIN + DECLARE vDateShort DATETIME; + DECLARE oneYearAgo DATE; + DECLARE twoYearsAgo DATE; + DECLARE fourYearsAgo DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); + SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + + DELETE FROM vn.message WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; + DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + CALL shelving_clean; + CALL vn.ticketPackagingRecovery; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36663,54 +33269,54 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker`() -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vClientFk INT; - - DECLARE rs CURSOR FOR - SELECT c.clientFk - FROM tmp.clientGetDebt c - LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk - WHERE IFNULL(r.risk,0) = 0; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT cd.id as clientFk - FROM bs.clientDied cd - LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id - 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 c.salesPersonFk IS NOT NULL; - - CALL vn.clientGetDebt(curdate()); - - DROP TEMPORARY TABLE IF EXISTS tmp.contador; - CREATE TEMPORARY TABLE tmp.contador (id INT) - ENGINE = MEMORY; - - OPEN rs; - FETCH rs INTO vClientFk; - - WHILE NOT done DO - INSERT INTO tmp.contador SET id = vClientFk; - CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk + WHERE IFNULL(r.risk,0) = 0; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT cd.id as clientFk + FROM bs.clientDied cd + LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id + 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 c.salesPersonFk IS NOT NULL; + + CALL vn.clientGetDebt(curdate()); + + DROP TEMPORARY TABLE IF EXISTS tmp.contador; + CREATE TEMPORARY TABLE tmp.contador (id INT) + ENGINE = MEMORY; + + OPEN rs; + FETCH rs INTO vClientFk; + + WHILE NOT done DO + INSERT INTO tmp.contador SET id = vClientFk; + CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; INSERT INTO vn.clientLog (originFk, userFk, `action`, description) VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses')); - + REPLACE bs.clientNewBorn(clientFk, shipped) - VALUES(vClientFk, CURDATE()); - FETCH rs INTO vClientFk; - END WHILE; - - CLOSE rs; + VALUES(vClientFk, CURDATE()); + FETCH rs INTO vClientFk; + END WHILE; + + CLOSE rs; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37774,6 +34380,89 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) +BEGIN + + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceFk INT; + DECLARE vASIEN BIGINT DEFAULT 0; + DECLARE vCounter INT DEFAULT 0; + + DECLARE rs CURSOR FOR + SELECT e.invoiceInFk + FROM entry e + JOIN duaEntry de ON de.entryFk = e.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk + WHERE de.duaFk = vDuaFk + AND de.customsValue + AND ii.isBooked = FALSE; + + 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 + JOIN dua d ON d.id = de.duaFk + SET ii.isBooked = TRUE, + ii.booked = IFNULL(ii.booked,d.booked), + ii.operated = IFNULL(ii.operated,d.operated), + ii.issued = IFNULL(ii.issued,d.issued), + 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 + SET ASIEN = vASIEN + WHERE id = vDuaFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `duaInvoiceInBooking__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking__`(vDuaFk INT) BEGIN DECLARE done BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -38326,216 +35015,216 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(IN `vEntry` INT) -BEGIN - - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vTravel INT; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE vId_Entrada INT; - DECLARE vId_Article INT; - DECLARE vEtiquetas INT; - DECLARE vId_Cubo VARCHAR(10); - DECLARE vPacking INT; - DECLARE vGrouping INT; - DECLARE vCantidad INT; - DECLARE vCostefijo DECIMAL(10,3); - DECLARE vPortefijo DECIMAL(10,3); - DECLARE vEmbalajefijo DECIMAL(10); - DECLARE vComisionfija DECIMAL(10,3); - DECLARE vCaja INT; - DECLARE vNicho VARCHAR(5); - DECLARE vTarifa1 DECIMAL(10,2); - DECLARE vTarifa2 DECIMAL(10,2); - DECLARE vTarifa3 DECIMAL(10,2); - DECLARE vPVP DECIMAL(10,2); - DECLARE vCompra INT; - - DECLARE rs CURSOR FOR - SELECT - b.Id_Entrada, - b.Id_Article, - b.Etiquetas, - b.Id_Cubo, - b.Packing, - b.`grouping`, - b.Cantidad, - b.Costefijo, - b.Portefijo, - b.Embalajefijo, - b.Comisionfija, - b.caja, - b.Nicho, - b.Tarifa1, - b.Tarifa2, - b.Tarifa3, - b.PVP - FROM vn2008.Compres b - JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article - WHERE Id_Entrada = vEntry; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT warehouseInFk, warehouseOutFk, tr.id - INTO vWarehouseIn, vWarehouseOut, vTravel - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - WHERE e.id = vEntry; - - UPDATE travel - SET warehouseInFk = vWarehouseOut, - warehouseOutFk = vWarehouseIn - WHERE id = vTravel; - - UPDATE vn2008.Compres c - LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article - SET Etiquetas = 0, Cantidad = 0 - WHERE c.Id_Entrada = vEntry - AND ic.espItemFk IS NULL; - - OPEN rs; - - DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - WHILE NOT done DO - - -- Primero la linea original con las cantidades invertidas - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - VALUES - ( - vId_Entrada, - vId_Article, - - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP); - - -- Ahora la linea nueva, con el item genérico - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - SELECT - vId_Entrada, - genItemFk as Id_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP - FROM itemConversor - WHERE espItemFk = vId_Article; - - SELECT LAST_INSERT_ID() - INTO vCompra; - - REPLACE vn2008.Compres_mark(Id_Compra,`comment`) - SELECT vCompra, vId_Article; - - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - END WHILE; - - - CLOSE rs; - - - +BEGIN + + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vTravel INT; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE vId_Entrada INT; + DECLARE vId_Article INT; + DECLARE vEtiquetas INT; + DECLARE vId_Cubo VARCHAR(10); + DECLARE vPacking INT; + DECLARE vGrouping INT; + DECLARE vCantidad INT; + DECLARE vCostefijo DECIMAL(10,3); + DECLARE vPortefijo DECIMAL(10,3); + DECLARE vEmbalajefijo DECIMAL(10); + DECLARE vComisionfija DECIMAL(10,3); + DECLARE vCaja INT; + DECLARE vNicho VARCHAR(5); + DECLARE vTarifa1 DECIMAL(10,2); + DECLARE vTarifa2 DECIMAL(10,2); + DECLARE vTarifa3 DECIMAL(10,2); + DECLARE vPVP DECIMAL(10,2); + DECLARE vCompra INT; + + DECLARE rs CURSOR FOR + SELECT + b.Id_Entrada, + b.Id_Article, + b.Etiquetas, + b.Id_Cubo, + b.Packing, + b.`grouping`, + b.Cantidad, + b.Costefijo, + b.Portefijo, + b.Embalajefijo, + b.Comisionfija, + b.caja, + b.Nicho, + b.Tarifa1, + b.Tarifa2, + b.Tarifa3, + b.PVP + FROM vn2008.Compres b + JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article + WHERE Id_Entrada = vEntry; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT warehouseInFk, warehouseOutFk, tr.id + INTO vWarehouseIn, vWarehouseOut, vTravel + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + WHERE e.id = vEntry; + + UPDATE travel + SET warehouseInFk = vWarehouseOut, + warehouseOutFk = vWarehouseIn + WHERE id = vTravel; + + UPDATE vn2008.Compres c + LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article + SET Etiquetas = 0, Cantidad = 0 + WHERE c.Id_Entrada = vEntry + AND ic.espItemFk IS NULL; + + OPEN rs; + + DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + WHILE NOT done DO + + -- Primero la linea original con las cantidades invertidas + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + VALUES + ( + vId_Entrada, + vId_Article, + - vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + - vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP); + + -- Ahora la linea nueva, con el item genérico + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + SELECT + vId_Entrada, + genItemFk as Id_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP + FROM itemConversor + WHERE espItemFk = vId_Article; + + SELECT LAST_INSERT_ID() + INTO vCompra; + + REPLACE vn2008.Compres_mark(Id_Compra,`comment`) + SELECT vCompra, vId_Article; + + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + END WHILE; + + + CLOSE rs; + + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38597,62 +35286,62 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryPrepare`(IN `idE` BIGINT) -BEGIN - SELECT - b.quantity / b.packing AS Paquetes, - b.packing AS `Grouping`, - barcode, - 'ASEGURADO' AS asegurado, - ic.name, - ic.order, - s.name AS Consignatario, - e.supplierFk AS Id_Cliente, - e.isOrdered, - e.isConfirmed, - 10 AS Calidad, - LPAD(IFNULL(cpd.id, ip.code), - 5, - '0') AS path, - b.entryFk AS Id_Ticket, - t.landed AS Fecha, - b.itemFk, - b.quantity, - i.name AS Concepte, - i.size, - i.inkFk, - i.category, - o.code AS Origen, - 0 AS Bultos, - wIn.`name` AS Tipo, - 0 AS OK, - 0 AS Reservado, - i.stems, - b.id AS Id_Movimiento, - ip.code, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - i.image, - pr.name AS producer - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk - 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 - JOIN vn.packaging pkg ON pkg.id = b.packageFk - LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk - LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk - LEFT JOIN vn.origin o ON o.id = i.originFk - LEFT JOIN vn.supplier s ON s.id = e.supplierFk - LEFT JOIN vn.producer pr on pr.id = i.producerFk - LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway - WHERE - NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid - AND e.id = 158772 - AND i.typeFk IS NOT NULL - AND ic.merchandise IS NOT FALSE; +BEGIN + SELECT + b.quantity / b.packing AS Paquetes, + b.packing AS `Grouping`, + barcode, + 'ASEGURADO' AS asegurado, + ic.name, + ic.order, + s.name AS Consignatario, + e.supplierFk AS Id_Cliente, + e.isOrdered, + e.isConfirmed, + 10 AS Calidad, + LPAD(IFNULL(cpd.id, ip.code), + 5, + '0') AS path, + b.entryFk AS Id_Ticket, + t.landed AS Fecha, + b.itemFk, + b.quantity, + i.name AS Concepte, + i.size, + i.inkFk, + i.category, + o.code AS Origen, + 0 AS Bultos, + wIn.`name` AS Tipo, + 0 AS OK, + 0 AS Reservado, + i.stems, + b.id AS Id_Movimiento, + ip.code, + 'PEDIDO ASEGURADO' AS MSG, + 0 AS Seguro, + i.image, + pr.name AS producer + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk + 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 + JOIN vn.packaging pkg ON pkg.id = b.packageFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk + LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.supplier s ON s.id = e.supplierFk + LEFT JOIN vn.producer pr on pr.id = i.producerFk + LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway + WHERE + NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid + AND e.id = 158772 + AND i.typeFk IS NOT NULL + AND ic.merchandise IS NOT FALSE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42249,38 +38938,38 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemLastEntries`(IN `vItem` INT, IN `vDays` DATE) -BEGIN - SELECT - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.`grouping`, - b.groupingMode, - i.stems, - b.quantity, - b.buyingValue, - b.packageFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - 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 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.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() - ORDER BY tr.landed DESC , b.id DESC; +BEGIN + SELECT + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.`grouping`, + b.groupingMode, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + 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 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.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() + ORDER BY tr.landed DESC , b.id DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45553,9 +42242,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -46187,77 +42876,77 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT) -BEGIN - - SET @rest:= CAST(0 AS DECIMAL(10,0)); - SET @saleFk := CAST(0 AS DECIMAL(10,0)); - SET @reserved := CAST(0 AS DECIMAL(10,0)); - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN sale s ON s.id = sis.saleFk - SET ish.visible = sis.quantity + ish.visible, - ish.available = sis.quantity + ish.visible - WHERE s.ticketFk = vTicketFk; - - DELETE sis.* - FROM saleItemShelving sis - JOIN sale s ON s.id = sis.saleFk - WHERE s.ticketFk = vTicketFk; - - INSERT INTO saleItemShelving( saleFk, - itemShelvingFk, - quantity, - ubication) - SELECT saleFk, - itemShelvingFk, - CAST(Reserved as DECIMAL(10,0)) as Reserved, - ubication - FROM - (SELECT saleFk, - itemShelvingFk, - ubication, - @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, - @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, - @rest := @rest - @reserved, - @saleFk := saleFk - FROM - ( SELECT s.id as saleFk, - ish.created, - ish.id as itemShelvingFk, - ish.available, - s.quantity, - ish.packing, - CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk - JOIN vn.parking p ON p.sectorFk = sc.id - JOIN vn.shelving sh ON sh.parkingFk = p.id - JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk - WHERE t.id = vTicketFk - AND sc.id = vSectorFk - AND s.quantity MOD ish.packing = 0 - AND s.quantity >= ish.packing - ORDER BY s.id, - sh.priority DESC, - ish.packing DESC, - ish.created - ) sub - ) sub2 - WHERE Reserved > 0; - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN vn.sale s ON s.id = sis.saleFk - SET ish.available = ish.visible - sis.quantity, - ish.visible = ish.visible - sis.quantity - WHERE s.ticketFk = vTicketFk - AND s.isPicked = FALSE; - - CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); - - +BEGIN + + SET @rest:= CAST(0 AS DECIMAL(10,0)); + SET @saleFk := CAST(0 AS DECIMAL(10,0)); + SET @reserved := CAST(0 AS DECIMAL(10,0)); + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN sale s ON s.id = sis.saleFk + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE s.ticketFk = vTicketFk; + + DELETE sis.* + FROM saleItemShelving sis + JOIN sale s ON s.id = sis.saleFk + WHERE s.ticketFk = vTicketFk; + + INSERT INTO saleItemShelving( saleFk, + itemShelvingFk, + quantity, + ubication) + SELECT saleFk, + itemShelvingFk, + CAST(Reserved as DECIMAL(10,0)) as Reserved, + ubication + FROM + (SELECT saleFk, + itemShelvingFk, + ubication, + @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, + @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, + @rest := @rest - @reserved, + @saleFk := saleFk + FROM + ( SELECT s.id as saleFk, + ish.created, + ish.id as itemShelvingFk, + ish.available, + s.quantity, + ish.packing, + CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk + JOIN vn.parking p ON p.sectorFk = sc.id + JOIN vn.shelving sh ON sh.parkingFk = p.id + JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk + WHERE t.id = vTicketFk + AND sc.id = vSectorFk + AND s.quantity MOD ish.packing = 0 + AND s.quantity >= ish.packing + ORDER BY s.id, + sh.priority DESC, + ish.packing DESC, + ish.created + ) sub + ) sub2 + WHERE Reserved > 0; + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN vn.sale s ON s.id = sis.saleFk + SET ish.available = ish.visible - sis.quantity, + ish.visible = ish.visible - sis.quantity + WHERE s.ticketFk = vTicketFk + AND s.isPicked = FALSE; + + CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46268,92 +42957,92 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleMove`(IN vSaleFk BIGINT, IN vQuantity BIGINT) BEGIN +-- JGF is working in this file 2019-12-20 + DECLARE vclientFk INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk INT; + DECLARE vCompanyFk INT; + DECLARE vAddressFk INT; + DECLARE vAgencyModeFk INT; + DECLARE vNewTicket BIGINT; + DECLARE vNewSale BIGINT; + DECLARE vLanded DATE; + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + DECLARE vAuxId INT; + DECLARE vNumLine INT; + DECLARE vItemFk INT; - DECLARE vclientFk INT; - DECLARE vShipped DATE; - DECLARE vWarehouseFk INT; - DECLARE vCompanyFk INT; - DECLARE vAddressFk INT; - DECLARE vAgencyModeFk INT; - DECLARE vNewTicket BIGINT; - DECLARE vNewSale BIGINT; - DECLARE vLanded DATE; - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - DECLARE vAuxId INT; - DECLARE vNumLine INT; - DECLARE vItemFk INT; - - SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id + SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id INTO vclientFk,vShipped,vWarehouseFk,vCompanyFk,vAddressFk,vAgencyModeFk,vLanded,vAuxId FROM ticket t JOIN sale s ON s.ticketFk=t.id WHERE s.id = vSaleFk; - SET vDateStart = TIMESTAMP(vShipped); - SET vDateEnd = TIMESTAMP(vShipped, '23:59:59'); + SET vDateStart = TIMESTAMP(vShipped); + SET vDateEnd = TIMESTAMP(vShipped, '23:59:59'); - SELECT t.id INTO vNewTicket + SELECT t.id INTO vNewTicket FROM ticket t JOIN ticketState ts ON ts.ticketFk=t.id WHERE t.addressFk = vAddressFk AND t.warehouseFk = vWarehouseFk - AND t.agencyModeFk = vAgencyModeFk - AND t.landed <=> vLanded - AND t.shipped BETWEEN vDateStart AND vDateEnd - AND t.refFk IS NULL - AND t.clientFk <> 1118 - AND t.id <> vAuxId - AND IFNULL(ts.alertLevel,0) = 0 + AND t.agencyModeFk = vAgencyModeFk + AND t.landed <=> vLanded + AND t.shipped BETWEEN vDateStart AND vDateEnd + AND t.refFk IS NULL + AND t.clientFk <> 1118 + AND t.id <> vAuxId + AND IFNULL(ts.alertLevel,0) = 0 LIMIT 1; -IF vNewTicket IS NULL - THEN + IF vNewTicket IS NULL THEN CALL vn.ticket_Clone(vAuxId, vNewTicket); - /*CALL vn2008.bionic_calc_ticket(vNewTicket);*/ - END IF; + /*CALL vn2008.bionic_calc_ticket(vNewTicket);*/ + END IF; - INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) - SELECT vNewTicket, getWorker(), s.id - FROM state s - WHERE s.code = 'FIXING'; + INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) + SELECT vNewTicket, getWorker(), s.id + FROM state s + WHERE s.code = 'FIXING'; - /*parche para campapña, eliminar y modificar el front*/ -SELECT COUNT(id) INTO vNumLine - FROM sale s - WHERE s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk); - - IF vNumLine = 0 THEN - - INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicket, itemFk, concept, vQuantity, price, discount + /*parche para campapña, eliminar y modificar el front*/ + SELECT COUNT(id) INTO vNumLine FROM sale s - WHERE s.id = vSaleFk; + WHERE s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk); - SELECT LAST_INSERT_ID() INTO vNewSale; + IF vNumLine = 0 THEN - INSERT INTO saleComponent(saleFk, componentFk, `value`) - SELECT vNewSale, componentFk, `value` - FROM saleComponent - WHERE saleFk = vSaleFk; - -ELSE IF vQuantity <> 0 THEN + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vNewTicket, itemFk, concept, vQuantity, price, discount + FROM sale s + WHERE s.id = vSaleFk; + + SELECT LAST_INSERT_ID() INTO vNewSale; + + INSERT INTO saleComponent(saleFk, componentFk, `value`) + SELECT vNewSale, componentFk, `value` + FROM saleComponent + WHERE saleFk = vSaleFk; + + ELSE + IF vQuantity <> 0 THEN - SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk; - UPDATE sale SET quantity = vQuantity - WHERE ticketFk = vNewTicket AND itemFk = vItemFk; + SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk; + UPDATE sale SET quantity = vQuantity + WHERE ticketFk = vNewTicket AND itemFk = vItemFk; -END IF; -END IF; + END IF; + END IF; END ;; DELIMITER ; @@ -46756,33 +43445,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`() -BEGIN - CALL nestTree( - 'vn2008', - 'scan', - 'vn2008', - 'scanTree' - ); - - UPDATE vn2008.scanTree st - JOIN ( - SELECT sl.scan_id, - MAX(sl.odbc_date) lastScanned, - COUNT(DISTINCT t.routeFk) routeCount, - MIN(t.routeFk) mod 1000 as minRoute, - MAX(t.routeFk) mod 1000 as maxRoute, - COUNT(sl.scan_line_id) as scanned - FROM vn2008.scan_line sl - JOIN expedition e ON e.id = sl.`code` - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk - GROUP BY sl.scan_id - ) rs ON rs.scan_id = st.id - SET st.lastScanned = rs.lastScanned, - st.routeCount = rs.routeCount, - st.minRoute = rs.minRoute, - st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), - st.scanned = rs.scanned; +BEGIN + CALL nestTree( + 'vn2008', + 'scan', + 'vn2008', + 'scanTree' + ); + + UPDATE vn2008.scanTree st + JOIN ( + SELECT sl.scan_id, + MAX(sl.odbc_date) lastScanned, + COUNT(DISTINCT t.routeFk) routeCount, + MIN(t.routeFk) mod 1000 as minRoute, + MAX(t.routeFk) mod 1000 as maxRoute, + COUNT(sl.scan_line_id) as scanned + FROM vn2008.scan_line sl + JOIN expedition e ON e.id = sl.`code` + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk + GROUP BY sl.scan_id + ) rs ON rs.scan_id = st.id + SET st.lastScanned = rs.lastScanned, + st.routeCount = rs.routeCount, + st.minRoute = rs.minRoute, + st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), + st.scanned = rs.scanned; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48348,9 +45037,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -48453,6 +45142,9 @@ BEGIN ELSE -- Albaran_print CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); + -- Comentar al pasar a nuevo cierre + INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); + -- INSERT INTO END IF; -- ticketClosure end @@ -55655,156 +52347,6 @@ USE `bi`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Current Database: `bs` --- - -USE `bs`; - --- --- Final view structure for view `bajasLaborales` --- - -/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `bajasLaborales` AS select `p`.`firstname` AS `firstname`,`p`.`name` AS `name`,`b`.`business_id` AS `business_id`,max(`ce`.`date`) AS `lastDate`,max(ifnull(`b`.`date_end`,curdate())) AS `endContract`,`cs`.`type` AS `type`,cast(count(0) as decimal(10,0)) AS `dias`,`w`.`userFk` AS `userFk` from (((((`postgresql`.`calendar_employee` `ce` join `postgresql`.`business` `b` on((`b`.`business_id` = `ce`.`business_id`))) join `postgresql`.`profile` `pr` on((`pr`.`profile_id` = `b`.`client_id`))) join `postgresql`.`person` `p` on((`p`.`person_id` = `pr`.`person_id`))) join `postgresql`.`calendar_state` `cs` on((`cs`.`calendar_state_id` = `ce`.`calendar_state_id`))) join `vn`.`worker` `w` on((`w`.`id` = `p`.`id_trabajador`))) where ((`ce`.`date` >= (curdate() + interval -(1) year)) and (`cs`.`type` not in ('Vacaciones','Vacaciones 1/2 día','Compensar','Festivo'))) group by `p`.`firstname`,`p`.`name`,`cs`.`type` having (`endContract` >= curdate()) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `lastIndicators` --- - -/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `lastIndicators` AS select `i`.`updated` AS `updated`,`i`.`lastYearSales` AS `lastYearSales`,(`i`.`lastYearSales` - `yi`.`lastYearSales`) AS `incLastYearSales`,`i`.`totalGreuge` AS `totalGreuge`,(`i`.`totalGreuge` - `yi`.`totalGreuge`) AS `incTotalGreuge`,`i`.`latePaymentRate` AS `latePaymentRate`,(`i`.`latePaymentRate` - `yi`.`latePaymentRate`) AS `incLatePaymentRate`,`i`.`countEmployee` AS `countEmployee`,(`i`.`countEmployee` - `yi`.`countEmployee`) AS `incCountEmployee`,`i`.`averageMana` AS `averageMana`,(`i`.`averageMana` - `yi`.`averageMana`) AS `incAverageMana`,`i`.`bankingPool` AS `bankingPool`,(`i`.`bankingPool` - `yi`.`bankingPool`) AS `incbankingPool`,`i`.`lastMonthActiveClients` AS `lastMonthActiveClients`,(`i`.`lastMonthActiveClients` - `yi`.`lastMonthActiveClients`) AS `incLastMonthActiveClients`,`i`.`lastMonthLostClients` AS `lastMonthLostClients`,(`i`.`lastMonthLostClients` - `yi`.`lastMonthLostClients`) AS `incLastMonthLostClients`,`i`.`lastMonthNewClients` AS `lastMonthNewClients`,(`i`.`lastMonthNewClients` - `yi`.`lastMonthNewClients`) AS `incLastMonthNewClients`,`i`.`lastMonthWebBuyingRate` AS `lastMonthWebBuyingRate`,(`i`.`lastMonthWebBuyingRate` - `yi`.`lastMonthWebBuyingRate`) AS `incLastMonthWebBuyingRate`,`i`.`productionHours` AS `productionHours`,`i`.`dailyWorkersCost` AS `dailyWorkersCost`,`i`.`volumeM3` AS `volumeM3`,`i`.`salesValue` AS `salesValue`,`i`.`valueM3` AS `valueM3`,`i`.`hoursM3` AS `hoursM3`,`i`.`workerCostM3` AS `workerCostM3`,`i`.`salesWorkersCostRate` AS `salesWorkersCostRate`,`i`.`thisWeekSales` AS `thisWeekSales`,`i`.`lastYearWeekSales` AS `lastYearWeekSales` from (`indicators` `i` join `indicators` `yi` on((`yi`.`updated` = (select (max(`indicators`.`updated`) + interval -(1) day) from `indicators`)))) where (`i`.`updated` = (select max(`indicators`.`updated`) from `indicators`)) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `m3Silla` --- - -/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `m3Silla` AS select `m3`.`fecha` AS `fecha`,`m3`.`year` AS `year`,`m3`.`month` AS `month`,`m3`.`week` AS `week`,`m3`.`day` AS `day`,`m3`.`dayName` AS `dayName`,cast(sum(`m3`.`m3`) as decimal(10,0)) AS `Volumen`,cast(sum(`m3`.`euros`) as decimal(10,0)) AS `Euros` from `m3` where (`m3`.`warehouseFk` in (1,44)) group by `m3`.`fecha` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `m3analisis` --- - -/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `m3analisis` AS select `m`.`fecha` AS `fecha`,`m`.`year` AS `year`,`m`.`month` AS `month`,`m`.`week` AS `week`,`m`.`day` AS `day`,`m`.`dayName` AS `dayName`,`m`.`Volumen` AS `Volumen`,`m`.`Euros` AS `Euros`,`h`.`Departamento` AS `Departamento`,`h`.`Horas` AS `Horas`,`h`.`Salarios` AS `Salarios`,(`h`.`Horas` / `m`.`Volumen`) AS `tiempoM3`,(`m`.`Euros` / `m`.`Volumen`) AS `valorM3`,(`h`.`Salarios` / `m`.`Volumen`) AS `costeLaboralM3`,(`h`.`Salarios` / `m`.`Euros`) AS `costeEuros`,(`h`.`Salarios` / `h`.`Horas`) AS `precioHora` from (`bs`.`m3Silla` `m` join `bs`.`horasSilla` `h` on((`h`.`Fecha` = `m`.`fecha`))) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `manaSpellersExcluded` --- - -/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `manaSpellersExcluded` AS select `m`.`Id_Trabajador` AS `workerFk` from `mana_spellers_excluded` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `mana_spellers` --- - -/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mana_spellers` AS select `wm`.`workerFk` AS `Id_Trabajador`,`wm`.`size` AS `size`,`wm`.`amount` AS `used`,`wm`.`pricesModifierRate` AS `prices_modifier_rate`,`wm`.`isPricesModifierActivated` AS `prices_modifier_activated`,`wm`.`minRate` AS `minRate`,`wm`.`maxRate` AS `maxRate` from `vn`.`workerMana` `wm` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `mermas` --- - -/*!50001 DROP VIEW IF EXISTS `mermas`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mermas` AS select `w`.`code` AS `Comprador`,`it`.`name` AS `Familia`,`i`.`id` AS `Referencia`,`i`.`name` AS `Item`,`s`.`quantity` AS `Cantidad`,(((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`) AS `Coste_Unitario`,(`s`.`quantity` * (((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`)) AS `Importe`,`c`.`name` AS `Cliente`,`s`.`ticketFk` AS `ticketFk`,`t`.`shipped` AS `Fecha` from (((((((`vn`.`worker` `w` join `vn`.`itemType` `it` on((`it`.`workerFk` = `w`.`id`))) join `vn`.`item` `i` on((`i`.`typeFk` = `it`.`id`))) join `vn`.`sale` `s` on((`s`.`itemFk` = `i`.`id`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`client` `c` on((`c`.`id` = `t`.`clientFk`))) left join `bi`.`Last_buy_id` `lb` on(((`lb`.`Id_Article` = `s`.`itemFk`) and (`lb`.`warehouse_id` = `t`.`warehouseFk`)))) left join `vn`.`buy` `b` on((`b`.`id` = `lb`.`Id_Compra`))) where ((`t`.`shipped` > '2018-01-01') and (`c`.`isRelevant` or (`c`.`id` in (200,400)))) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `workerMana` --- - -/*!50001 DROP VIEW IF EXISTS `workerMana`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerMana` AS select `m`.`Id_Trabajador` AS `workerFk`,`m`.`used` AS `amount` from `bs`.`mana_spellers` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Current Database: `cache` -- @@ -56430,10 +52972,10 @@ USE `vn`; /*!50001 SET collation_connection = @saved_col_connection */; -- --- Final view structure for view `clientManaCache` +-- Final view structure for view `clientManaCache__` -- -/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; +/*!50001 DROP VIEW IF EXISTS `clientManaCache__`*/; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; @@ -56442,7 +52984,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientManaCache` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */; +/*!50001 VIEW `clientManaCache__` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -57632,4 +54174,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-20 11:02:02 +-- Dump completed on 2019-12-23 14:34:48 diff --git a/db/export-structure.sh b/db/export-structure.sh index 1959463ff..5e1b62f03 100755 --- a/db/export-structure.sh +++ b/db/export-structure.sh @@ -3,7 +3,6 @@ SCHEMAS=( account bi - bs cache edi hedera diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index ea6a787b0..0f7810ed2 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -56,7 +56,6 @@ module.exports = Self => { ]; for (const key in params) { - console.log('key', key); if (validUpdateParams.indexOf(key) === -1) throw new UserError(`You don't have enough privileges to do that`); } diff --git a/modules/worker/back/models/worker-mana.json b/modules/worker/back/models/worker-mana.json index 8de7c1fe1..b98b2a325 100644 --- a/modules/worker/back/models/worker-mana.json +++ b/modules/worker/back/models/worker-mana.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "bs.workerMana" + "table": "workerMana" } }, "properties": {