diff --git a/db/changes/10141-zoneDoCalc/00-ticket.sql b/db/changes/10141-zoneDoCalc/00-ticket.sql deleted file mode 100644 index fa091f111..000000000 --- a/db/changes/10141-zoneDoCalc/00-ticket.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE `vn`.`ticket` -ADD COLUMN `zonePrice` DECIMAL(10,2) NULL DEFAULT NULL AFTER `collectionFk`, -ADD COLUMN `zoneBonus` DECIMAL(10,2) NULL DEFAULT NULL AFTER `zonePrice`; diff --git a/db/changes/10141-zoneDoCalc/01-ticketCreateWithUser.sql b/db/changes/10141-zoneDoCalc/01-ticketCreateWithUser.sql deleted file mode 100644 index 867cd1c0d..000000000 --- a/db/changes/10141-zoneDoCalc/01-ticketCreateWithUser.sql +++ /dev/null @@ -1,96 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCreateWithUser`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - DECLARE vPrice DECIMAL(10,2); - DECLARE vBonus DECIMAL(10,2); - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF vAgencyModeFk IS NOT NULL THEN - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus - FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - IF vZoneFk IS NULL OR vZoneFk = 0 THEN - CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); - END IF; - END IF; - INSERT INTO ticket ( - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - routeFk, - companyFk, - landed, - zoneFk, - zonePrice, - zoneBonus - ) - SELECT - vClientId, - vShipped, - a.id, - vAgencyModeFk, - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk, - vPrice, - vBonus - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END$$ - -DELIMITER ; - diff --git a/db/changes/10141-zoneDoCalc/01-ticket_componentUpdate.sql b/db/changes/10141-zoneDoCalc/01-ticket_componentUpdate.sql deleted file mode 100644 index 14ff6f484..000000000 --- a/db/changes/10141-zoneDoCalc/01-ticket_componentUpdate.sql +++ /dev/null @@ -1,82 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticket_componentUpdate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentUpdate`( - vTicketFk INT, - vClientFk INT, - vAgencyModeFk INT, - vAddressFk INT, - vZoneFk INT, - vWarehouseFk TINYINT, - vCompanyFk SMALLINT, - vShipped DATETIME, - vLanded DATE, - vIsDeleted BOOLEAN, - vHasToBeUnrouted BOOLEAN, - vOption INT) -BEGIN - DECLARE vPrice DECIMAL(10,2); - DECLARE vBonus DECIMAL(10,2); - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t - JOIN address a ON a.id = vAddressFk - SET t.nickname = a.nickname - WHERE t.id = vTicketFk; - - END IF; - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus - FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - UPDATE ticket t - SET - t.clientFk = vClientFk, - t.agencyModeFk = vAgencyModeFk, - t.addressFk = vAddressFk, - t.zoneFk = vZoneFk, - t.zonePrice = vPrice, - t.zoneBonus = vBonus, - t.warehouseFk = vWarehouseFk, - t.companyFk = vCompanyFk, - t.landed = vLanded, - t.shipped = vShipped, - t.isDeleted = vIsDeleted - WHERE - t.id = vTicketFk; - - IF vHasToBeUnrouted THEN - UPDATE ticket t SET t.routeFk = NULL - WHERE t.id = vTicketFk; - END IF; - - IF vOption <> 8 THEN - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) - ENGINE = MEMORY - SELECT id AS saleFk, vWarehouseFk warehouseFk - FROM sale s WHERE s.ticketFk = vTicketFk; - - CALL ticketComponentUpdateSale (vOption); - - DROP TEMPORARY TABLE tmp.sale; - END IF; - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/changes/10141-zoneDoCalc/01-zoneClosure_recalc.sql b/db/changes/10141-zoneDoCalc/01-zoneClosure_recalc.sql deleted file mode 100644 index b7dbf675a..000000000 --- a/db/changes/10141-zoneDoCalc/01-zoneClosure_recalc.sql +++ /dev/null @@ -1,49 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneClosure_recalc`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneClosure_recalc`() -proc: BEGIN -/** - * Recalculates the delivery time (hour) for every zone in days + scope in future - */ - DECLARE vScope INT; - DECLARE vCounter INT DEFAULT 0; - DECLARE vShipped DATE DEFAULT CURDATE(); - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('vn.zoneClosure_recalc'); - RESIGNAL; - END; - - IF NOT GET_LOCK('vn.zoneClosure_recalc', 0) THEN - LEAVE proc; - END IF; - - SELECT scope INTO vScope - FROM zoneConfig; - - DROP TEMPORARY TABLE IF EXISTS tmp.zone; - CREATE TEMPORARY TABLE tmp.zone - (INDEX (id)) - ENGINE = MEMORY - SELECT id FROM zone; - - TRUNCATE TABLE zoneClosure; - - WHILE vCounter <= vScope DO - CALL zone_getOptionsForShipment(vShipped, TRUE); - INSERT INTO zoneClosure(zoneFk, dated, `hour`) - SELECT zoneFk, vShipped, `hour` FROM tmp.zoneOption; - - SET vCounter = vCounter + 1; - SET vShipped = TIMESTAMPADD(DAY, 1, vShipped); - END WHILE; - - DROP TEMPORARY TABLE tmp.zone; - DO RELEASE_LOCK('vn.zoneClosure_recalc'); -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10141-zoneDoCalc/02-insertPastTickets.sql b/db/changes/10141-zoneDoCalc/02-insertPastTickets.sql deleted file mode 100644 index 864bf04c6..000000000 --- a/db/changes/10141-zoneDoCalc/02-insertPastTickets.sql +++ /dev/null @@ -1,62 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_doCalcInitialize`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_doCalcInitialize`() -proc: BEGIN -/** - * Initialize ticket - * si en 01-07-20 aun esta este proc, kkear - */ - DECLARE vDone BOOL; - DECLARE vTicketFk INT; - DECLARE vLanded DATE; - DECLARE vZoneFk INT; - - DECLARE cCur CURSOR FOR - SELECT t.id, t.landed, t.zoneFk - FROM ticket t - WHERE (zonePrice IS NULL OR zoneBonus IS NULL) - AND landed >= '2019-01-01' AND shipped >= '2019-01-01' - GROUP BY landed, zoneFk; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - OPEN cCur; - - myLoop: LOOP - SET vDone = FALSE; - FETCH cCur INTO vTicketFk, vLanded, vZoneFk; - - IF vDone THEN - LEAVE myLoop; - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.zone; - CREATE TEMPORARY TABLE tmp.zone - (INDEX (id)) - ENGINE = MEMORY - SELECT vZoneFk id; - - CALL zone_getOptionsForLanding(vLanded, TRUE); - - UPDATE ticket t - LEFT JOIN tmp.zoneOption zo ON TRUE - SET zonePrice = zo.price, zoneBonus = zo.bonus - WHERE t.zoneFk = vZoneFk AND landed = vLanded; - - UPDATE ticket t - LEFT JOIN vn.zone z ON z.id = t.zoneFk - SET zonePrice = z.price, zoneBonus = z.bonus - WHERE t.zonePrice IS NULL AND z.id = vZoneFk - AND landed >= '2019-01-01' AND shipped >= '2019-01-01'; - - END LOOP; - - CLOSE cCur; - -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10141-zoneDoCalc/02-procNoOverlap.sql b/db/changes/10141-zoneDoCalc/02-procNoOverlap.sql deleted file mode 100644 index 253264ce9..000000000 --- a/db/changes/10141-zoneDoCalc/02-procNoOverlap.sql +++ /dev/null @@ -1,30 +0,0 @@ -USE `util`; -DROP procedure IF EXISTS `procNoOverlap`; - -DELIMITER $$ -USE `util`$$ -CREATE PROCEDURE `procNoOverlap` (procName VARCHAR(255)) -SQL SECURITY INVOKER -proc: BEGIN -/** - * call procedure without overlap - */ - DECLARE vIsChanged BOOL; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK(procName); - RESIGNAL; - END; - - IF !GET_LOCK(procName, 0) THEN - LEAVE proc; - END IF; - - CALL exec(CONCAT('CALL ', procName)); - - DO RELEASE_LOCK(procName); -END$$ - -DELIMITER ; - diff --git a/db/changes/10141-zoneDoCalc/03-getOptionsForLanding.sql b/db/changes/10141-zoneDoCalc/03-getOptionsForLanding.sql deleted file mode 100644 index e0f5f9a48..000000000 --- a/db/changes/10141-zoneDoCalc/03-getOptionsForLanding.sql +++ /dev/null @@ -1,66 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getOptionsForLanding`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE, vShowExpiredZones BOOLEAN) -BEGIN -/** - * Gets computed options for the passed zones and delivery date. - * - * @table tmp.zones(id) The zones ids - * @param vLanded The delivery date - * @return tmp.zoneOption The computed options - */ - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT - zoneFk, - `hour`, - travelingDays, - price, - bonus, - TIMESTAMPADD(DAY, -travelingDays, vLanded) shipped - FROM ( - SELECT t.id zoneFk, - TIME(IFNULL(e.`hour`, z.`hour`)) `hour`, - IFNULL(e.travelingDays, z.travelingDays) travelingDays, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - WHERE ( - e.`type` = 'day' - AND e.dated = vLanded - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(vLanded)) - AND (e.`started` IS NULL OR vLanded >= e.`started`) - AND (e.`ended` IS NULL OR vLanded <= e.`ended`) - ) - ORDER BY - zoneFk, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END - ) t - GROUP BY zoneFk; - - DELETE t FROM tmp.zoneOption t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; - - IF NOT vShowExpiredZones THEN - DELETE FROM tmp.zoneOption - WHERE shipped < CURDATE() - OR (shipped = CURDATE() AND CURTIME() > `hour`); - END IF; -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10141-zoneDoCalc/03-rutasAnalyze.sql b/db/changes/10141-zoneDoCalc/03-rutasAnalyze.sql deleted file mode 100644 index 313f2f797..000000000 --- a/db/changes/10141-zoneDoCalc/03-rutasAnalyze.sql +++ /dev/null @@ -1,171 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `rutasAnalyze`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `rutasAnalyze`(vYear INT, vMonth INT) -BEGIN - -/* Analiza los costes de las rutas de reparto y lo almacena en la tabla Rutas_Master -* -* PAK 15/4/2019 -*/ - - DELETE FROM bi.rutasBoard - WHERE year = vYear AND month = vMonth; - - -- Rellenamos la tabla con los datos de las rutas VOLUMETRICAS, especialmente con los bultos "virtuales" - INSERT INTO bi.rutasBoard(year, - month, - warehouse_id, - Id_Ruta, - Id_Agencia, - km, - Dia, - Fecha, - Bultos, - Matricula, - Tipo, - Terceros) - SELECT YEAR(r.created), - MONTH(r.created), - GREATEST(1,a.warehouseFk), - r.id, - r.agencyModeFk, - r.kmEnd - r.kmStart, - DAYNAME(r.created), - r.created, - SUM(sv.volume / ebv.m3), - v.numberPlate, - IF(ISNULL(`r`.`cost`), 'P', 'A'), - r.cost - FROM vn.route r - JOIN vn.ticket t ON t.routeFk = r.id - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.agency a ON a.id = am.agencyFk - LEFT JOIN vn.vehicle v ON v.id = r.vehicleFk - JOIN vn.saleVolume sv ON sv.ticketFk = t.id - JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = 71 - WHERE YEAR(r.created) = vYear AND MONTH(r.created) = vMonth - AND z.isVolumetric - GROUP BY r.id; - - -- Rellenamos la tabla con los datos de las rutas NO VOLUMETRICAS, especialmente con los bultos "virtuales" - INSERT INTO bi.rutasBoard(year, - month, - warehouse_id, - Id_Ruta, - Id_Agencia, - km, - Dia, - Fecha, - Bultos, - Matricula, - Tipo, - Terceros) - SELECT YEAR(r.created), - MONTH(r.created), - GREATEST(1,a.warehouseFk), - r.id, - r.agencyModeFk, - r.kmEnd - r.kmStart, - DAYNAME(r.created), - r.created, - SUM(t.packages), - v.numberPlate, - IF(ISNULL(`r`.`cost`), 'P', 'A'), - r.cost - FROM vn.route r - JOIN vn.ticket t ON t.routeFk = r.id - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.agency a ON a.id = am.agencyFk - LEFT JOIN vn.vehicle v ON v.id = r.vehicleFk - WHERE YEAR(r.created) = vYear AND MONTH(r.created) = vMonth - AND z.isVolumetric = FALSE - GROUP BY r.id - ON DUPLICATE KEY UPDATE Bultos = Bultos + VALUES(Bultos); - - -- Coste REAL de cada bulto "virtual", de acuerdo con el valor apuntado a mano en la ruta - UPDATE bi.rutasBoard r - INNER JOIN vn2008.Rutas_Master rm ON rm.año = r.year AND rm.mes = r.month AND rm.warehouse_id = r.warehouse_id - SET r.coste_bulto = IF(r.Tipo ='A', r.Terceros, r.km * rm.coste_km ) / r.Bultos - WHERE r.Bultos > 0 - AND rm.año = vYear - AND rm.mes = vMonth; - - -- Coste PRACTICO de cada bulto, de acuerdo con los componentes de tipo AGENCIA en cada linea de venta - UPDATE bi.rutasBoard r - JOIN ( - SELECT t.routeFk, sum(s.quantity * sc.value) practicoTotal - FROM vn.route r - JOIN vn.time tm ON tm.dated = r.created - JOIN vn.ticket t ON t.routeFk = r.id - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.saleComponent sc ON sc.saleFk = s.id - JOIN vn.`component` c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk - WHERE ct.type = 'agencia' - AND tm.year = vYear - AND tm.month = vMonth - GROUP BY r.id - ) sub ON sub.routeFk = r.Id_Ruta - SET r.practico = sub.practicoTotal / r.Bultos; - - -- Coste TEORICO de una caja "virtual" para cada ruta, teniendo en cuenta que hay carros, pallets, etc - UPDATE bi.rutasBoard r - JOIN ( - SELECT t.routeFk, - SUM(t.zonePrice/ ebv.ratio)/ count(*) AS BultoTeoricoMedio - FROM vn.ticket t - JOIN vn.route r ON r.id = t.routeFk - JOIN vn.time tm ON tm.dated = r.created - JOIN vn.expedition e ON e.ticketFk = t.id - JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.isBox - JOIN vn.address ad ON ad.id = t.addressFk - JOIN vn.client c ON c.id = ad.clientFk - LEFT JOIN vn.zone z ON z.id = t.zoneFk - WHERE tm.year = vYear - AND tm.month = vMonth - AND z.isVolumetric = FALSE - GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk - SET r.teorico = sub.BultoTeoricoMedio; - - -- Coste VOLUMETRICO TEORICO de una caja "virtual" para cada ruta - UPDATE bi.rutasBoard r - JOIN ( - SELECT t.routeFk, - SUM(freight) AS BultoTeoricoMedio - FROM vn.ticket t - JOIN vn.route r ON r.id = t.routeFk - JOIN vn.time tm ON tm.dated = r.created - JOIN vn.saleVolume sf ON sf.ticketFk = t.id - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.zone z ON z.id = t.zoneFk - WHERE tm.year = vYear - AND tm.month = vMonth - AND z.isVolumetric != FALSE - GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk - SET r.teorico = sub.BultoTeoricoMedio / r.Bultos; - - -- La diferencia entre el teorico y el practico se deberia de cobrar en greuges, cada noche - UPDATE bi.rutasBoard r - JOIN ( - SELECT t.routeFk, - Sum(g.amount) AS greuge - FROM vn.ticket t - JOIN vn.route r ON r.id = t.routeFk - JOIN vn.time tm ON tm.dated = r.created - JOIN vn.greuge g ON g.ticketFk = t.id - JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk - WHERE tm.year = vYear - AND tm.month = vMonth - AND gt.name = 'Diferencia portes' - GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk - SET r.greuge = sub.greuge / r.Bultos; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10141-zoneDoCalc/03-saleVolume.sql b/db/changes/10141-zoneDoCalc/03-saleVolume.sql deleted file mode 100644 index 2ded49a8d..000000000 --- a/db/changes/10141-zoneDoCalc/03-saleVolume.sql +++ /dev/null @@ -1,26 +0,0 @@ -USE `vn`; -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `saleVolume` AS - SELECT - `s`.`ticketFk` AS `ticketFk`, - `s`.`id` AS `saleFk`, - IFNULL(ROUND(((((`i`.`compression` * (GREATEST(`i`.`density`, 167) / 167)) * `ic`.`cm3`) * `s`.`quantity`) / 1000), - 2), - 0) AS `litros`, - `t`.`routeFk` AS `routeFk`, - `t`.`shipped` AS `shipped`, - (((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) / 1000000) AS `volume`, - ((((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) * (GREATEST(`i`.`density`, 167) / 167)) / 1000000) AS `physicalWeight`, - (((`s`.`quantity` * `ic`.`cm3`) * `i`.`density`) / 1000000) AS `weight`, - (((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) / 1000000) AS `physicalVolume`, - ((((`s`.`quantity` * `ic`.`cm3`) * `t`.`zonePrice`) * `i`.`compression`) / `cb`.`volume`) AS `freight` - FROM - ((((`sale` `s` - JOIN `item` `i` ON ((`i`.`id` = `s`.`itemFk`))) - JOIN `ticket` `t` ON ((`t`.`id` = `s`.`ticketFk`))) - JOIN `packaging` `cb` ON ((`cb`.`id` = '94'))) - JOIN `itemCost` `ic` ON (((`ic`.`itemFk` = `s`.`itemFk`) - AND (`ic`.`warehouseFk` = `t`.`warehouseFk`)))); diff --git a/db/changes/10141-zoneDoCalc/03-viewSaleFreight__.sql b/db/changes/10141-zoneDoCalc/03-viewSaleFreight__.sql deleted file mode 100644 index 903c8b48a..000000000 --- a/db/changes/10141-zoneDoCalc/03-viewSaleFreight__.sql +++ /dev/null @@ -1,24 +0,0 @@ -DROP VIEW IF EXISTS `vn`.`saleFreight` ; -USE `vn`; -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `saleFreight__` AS - SELECT - `s`.`ticketFk` AS `ticketFk`, - `t`.`clientFk` AS `clientFk`, - `t`.`routeFk` AS `routeFk`, - `s`.`id` AS `saleFk`, - `t`.`zoneFk` AS `zoneFk`, - `t`.`companyFk` AS `companyFk`, - `t`.`shipped` AS `shipped`, - `t`.`zonePrice` AS `price`, - ((((`s`.`quantity` * `r`.`cm3`) * `t`.`zonePrice`) * `i`.`compression`) / `cb`.`volume`) AS `freight` - FROM - ((((`vn`.`sale` `s` - JOIN `vn`.`item` `i` ON ((`i`.`id` = `s`.`itemFk`))) - JOIN `vn`.`ticket` `t` ON ((`t`.`id` = `s`.`ticketFk`))) - JOIN `vn`.`packaging` `cb` ON ((`cb`.`id` = '94'))) - JOIN `bi`.`rotacion` `r` ON (((`r`.`Id_Article` = `s`.`itemFk`) - AND (`r`.`warehouse_id` = `t`.`warehouseFk`)))); diff --git a/db/changes/10141-zoneDoCalc/03-zone_geShippedWarehouse.sql b/db/changes/10141-zoneDoCalc/03-zone_geShippedWarehouse.sql deleted file mode 100644 index b4605ec04..000000000 --- a/db/changes/10141-zoneDoCalc/03-zone_geShippedWarehouse.sql +++ /dev/null @@ -1,43 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getShippedWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForLanding(vLanded,TRUE); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CREATE TEMPORARY TABLE tmp.zoneGetShipped - ENGINE = MEMORY - SELECT * FROM ( - SELECT zo.zoneFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - zo.`hour`, - zw.warehouseFk, - z.agencyModeFk, - zo.price, - zo.bonus - FROM tmp.zoneOption zo - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - JOIN zone z ON z.id = zo.zoneFk - WHERE z.agencyModeFk = vAgencyModeFk - ORDER BY shipped) t - GROUP BY warehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10141-zoneDoCalc/03-zone_getAgency.sql b/db/changes/10141-zoneDoCalc/03-zone_getAgency.sql deleted file mode 100644 index b2837d43c..000000000 --- a/db/changes/10141-zoneDoCalc/03-zone_getAgency.sql +++ /dev/null @@ -1,42 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getAgency`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded, FALSE); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; - CREATE TEMPORARY TABLE tmp.zoneGetAgency - (INDEX (agencyModeFk)) ENGINE = MEMORY - SELECT am.name agencyMode, - am.description, - z.agencyModeFk, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - TRUE isIncluded, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - GROUP BY agencyModeFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10141-zoneDoCalc/03-zone_getAvailable.sql b/db/changes/10141-zoneDoCalc/03-zone_getAvailable.sql deleted file mode 100644 index 2ef1a1ae9..000000000 --- a/db/changes/10141-zoneDoCalc/03-zone_getAvailable.sql +++ /dev/null @@ -1,18 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getAvailable`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAvailable`(vAddress INT, vLanded DATE) -BEGIN - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded, FALSE); - - SELECT * FROM tmp.zoneOption; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10141-zoneDoCalc/03-zone_getWarehouse.sql b/db/changes/10141-zoneDoCalc/03-zone_getWarehouse.sql deleted file mode 100644 index c1cea8b13..000000000 --- a/db/changes/10141-zoneDoCalc/03-zone_getWarehouse.sql +++ /dev/null @@ -1,41 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha, - * dirección y almacén pasados. - * - * @param vAddress - * @param vWarehouse warehouse - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded, FALSE); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, - zw.warehouseFk, - z.id zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - WHERE zw.warehouseFk - GROUP BY z.agencyModeFk - ORDER BY agencyMode; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10142-kings/00-ACL.sql b/db/changes/10142-kings/00-ACL.sql deleted file mode 100644 index 9a43990d0..000000000 --- a/db/changes/10142-kings/00-ACL.sql +++ /dev/null @@ -1 +0,0 @@ -REPLACE INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('CustomsAgent', '*', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/10142-kings/01-customsAgent.sql b/db/changes/10142-kings/01-customsAgent.sql deleted file mode 100644 index 34f77f20f..000000000 --- a/db/changes/10142-kings/01-customsAgent.sql +++ /dev/null @@ -1,11 +0,0 @@ -CREATE TABLE `vn`.`customsAgent` ( - `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, - `fiscalName` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, - `street` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `nif` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, - `phone` varchar(16) COLLATE utf8mb4_unicode_ci DEFAULT NULL, - `email` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - -ALTER TABLE `vn`.`customsAgent` - ADD UNIQUE KEY `nif_UNIQUE` (`nif`); \ No newline at end of file diff --git a/db/changes/10142-kings/02-incoterms.sql b/db/changes/10142-kings/02-incoterms.sql deleted file mode 100644 index 3e31b0c89..000000000 --- a/db/changes/10142-kings/02-incoterms.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE TABLE `vn`.`incoterms` ( - `code` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Internacional Commercial Terms'; - -ALTER TABLE `vn`.`incoterms` - ADD PRIMARY KEY (`code`); - -REPLACE INTO `vn`.`incoterms` (`code`, `name`) VALUES -('FAS', 'Free Alongside Ship'); diff --git a/db/changes/10142-kings/03-address.sql b/db/changes/10142-kings/03-address.sql deleted file mode 100644 index 042c2e17e..000000000 --- a/db/changes/10142-kings/03-address.sql +++ /dev/null @@ -1,26 +0,0 @@ -ALTER TABLE `vn`.`address` -ADD COLUMN `customsAgentFk` INT NULL DEFAULT NULL AFTER `isEqualizated`; - -ALTER TABLE `vn`.`address` -ADD COLUMN `incotermsFk` VARCHAR(3) NULL DEFAULT NULL AFTER `customsAgentFk`; - - -ALTER TABLE `vn`.`address` -ADD INDEX `address_customsAgentFk_idx` (`customsAgentFk` ASC); - -ALTER TABLE `vn`.`address` -ADD INDEX `address_incotermsFk_idx` (`incotermsFk` ASC); - -ALTER TABLE `vn`.`address` -ADD CONSTRAINT `address_customsAgentFk` - FOREIGN KEY (`customsAgentFk`) - REFERENCES `vn`.`customsAgent` (`id`) - ON DELETE RESTRICT - ON UPDATE CASCADE; - -ALTER TABLE `vn`.`address` -ADD CONSTRAINT `address_incotermsFk` - FOREIGN KEY (`incotermsFk`) - REFERENCES `vn`.`incoterms` (`code`) - ON DELETE RESTRICT - ON UPDATE CASCADE; \ No newline at end of file diff --git a/db/changes/10150-entry/00-ticketUpdateAction.sql b/db/changes/10150-entry/00-ticketUpdateAction.sql deleted file mode 100644 index a05c65d7a..000000000 --- a/db/changes/10150-entry/00-ticketUpdateAction.sql +++ /dev/null @@ -1,5 +0,0 @@ -ALTER TABLE `vn`.`ticketUpdateAction` -ADD COLUMN `code` VARCHAR(45) NOT NULL AFTER `description`; - -UPDATE `vn`.`ticketUpdateAction` SET `code`='changePrice' WHERE `id`='1'; -UPDATE `vn`.`ticketUpdateAction` SET `code`='turnInMana' WHERE `id`='3'; diff --git a/db/changes/10160-postValentineDay/00-ACL.sql b/db/changes/10160-postValentineDay/00-ACL.sql deleted file mode 100644 index 5b6301e3d..000000000 --- a/db/changes/10160-postValentineDay/00-ACL.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES ('Intrastat', '*', '*', 'ALLOW', 'ROLE', 'buyer'); diff --git a/db/changes/10160-postValentineDay/00-sample.sql b/db/changes/10160-postValentineDay/00-sample.sql deleted file mode 100644 index d34835888..000000000 --- a/db/changes/10160-postValentineDay/00-sample.sql +++ /dev/null @@ -1,6 +0,0 @@ -ALTER TABLE `vn`.`sample` -ADD COLUMN `hasPreview` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1' AFTER `hasCompany`, -CHANGE COLUMN `isVisible` `isVisible` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1' , -CHANGE COLUMN `hasCompany` `hasCompany` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' ; - -UPDATE `vn`.`sample` SET `hasPreview` = '0' WHERE (`id` = '14'); diff --git a/db/changes/10161-postValentineDay/00-ACL.sql b/db/changes/10161-postValentineDay/00-ACL.sql deleted file mode 100644 index a7ac79486..000000000 --- a/db/changes/10161-postValentineDay/00-ACL.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES ('EntryLog', '*', 'READ', 'ALLOW', 'ROLE', 'buyer'); diff --git a/db/changes/10161-postValentineDay/00-borrame.sql b/db/changes/10161-postValentineDay/00-borrame.sql deleted file mode 100644 index 22d1f5dec..000000000 --- a/db/changes/10161-postValentineDay/00-borrame.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE `vn`.`workerDocument` -ADD COLUMN `isReadableByWorker` TINYINT(1) NOT NULL DEFAULT 0 AFTER `document`; - -UPDATE `vn`.`workerDocument` SET `isReadableByWorker` = '1' WHERE (`id` = '1'); diff --git a/db/changes/10161-postValentineDay/00-workerTimeControlCheck.sql b/db/changes/10161-postValentineDay/00-workerTimeControlCheck.sql deleted file mode 100644 index 31bc4922b..000000000 --- a/db/changes/10161-postValentineDay/00-workerTimeControlCheck.sql +++ /dev/null @@ -1,182 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`workerTimeControl_check`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`workerTimeControl_check`(vUserFk INT, vTabletFk VARCHAR(100), vTimed DATETIME) -BEGIN - -/** - * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a vn.workerTimeControlAdd - * @param vUserFk Identificador del trabajador - * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ; - * En caso de tener algun problema retorna el primero que encuentra - */ - DECLARE vLastIn DATETIME ; - DECLARE vLastOut DATETIME ; - DECLARE vDayWorkMax INT; - DECLARE vDayBreak INT; - DECLARE vWeekBreak INT ; - DECLARE vWeekMaxBreak INT; - DECLARE vWeekScope INT; - DECLARE vWeekMaxScope INT; - DECLARE vDayStayMax INT; - DECLARE vAskInOut INT; - DECLARE vTimedWorked INT; - DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; - DECLARE vDepartmentFk INT; - DECLARE vTo VARCHAR(50) DEFAULT NULL; - DECLARE vUserName VARCHAR(50) DEFAULT NULL; - DECLARE vBody VARCHAR(255) DEFAULT NULL; - - IF (vTimed IS NULL) THEN - SET vTimed = NOW(); - END IF; - - SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax, weekMaxBreak, weekMaxScope, askInOut - INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax, vWeekMaxBreak, vWeekMaxScope, vAskInOut - FROM vn.workerTimeControlParams; - - SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl - WHERE userFk = vUserFk AND - direction = 'in'; - - SELECT MAX(timed) INTO vLastOut - FROM vn.workerTimeControl - WHERE userFk = vUserFk AND - direction = 'out'; - - SELECT email INTO vTo - FROM vn.worker w - WHERE w.id = (SELECT bossFk FROM vn.worker WHERE id = vUserFk); - - SELECT CONCAT(firstName,' ',lastName) INTO vUserName - FROM vn.worker w - WHERE w.id = vUserFk; - - -- VERIFICAR CONTRATO EN VIGOR - IF (SELECT COUNT(*) - FROM postgresql.business b - JOIN postgresql.profile pr ON pr.profile_id = b.client_id - JOIN postgresql.person p ON p.person_id = pr.person_id - JOIN vn.worker w ON w.id = p.id_trabajador - WHERE w.userFk = vUserFk AND - b.date_start <= CURDATE() AND - IFNULL(b.date_end,CURDATE()) >= CURDATE() - ) = 0 THEN - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - CALL util.throw("No hay un contrato en vigor"); - END IF; - - -- VERIFICAR DEPARTAMENTO - IF vTabletFk IS NOT NULL THEN - IF ( SELECT COUNT(*) - FROM vn.tabletDepartment td - JOIN vn.workerTimeControlUserInfo wtcu ON wtcu.departmentFk = td.departmentFk - WHERE td.tabletFk = vTabletFk AND wtcu.userFk = vUserFk - ) = 0 THEN - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - CALL util.throw("No perteneces a este departamento."); - END IF; - END IF; - - SELECT IFNULL(dayBreak, vDayBreak) INTO vDayBreak - FROM postgresql.business b - JOIN postgresql.profile pr ON pr.profile_id = b.client_id - JOIN postgresql.person p ON p.person_id = pr.person_id - JOIN postgresql. business_labour bl ON b.business_id = bl.business_id - JOIN postgresql.professional_category pc ON bl.professional_category_id = pc.professional_category_id - WHERE p.id_trabajador = vUserFk AND - b.date_start <= DATE(vTimed) AND - IFNULL(b.date_end, DATE(vTimed)) >= DATE(vTimed); - -- VERIFICAR DESCANSO DIARIO - -- 12 / 9 horas dependiendo del valor de vDayBreak - IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos ", FORMAT(vDayBreak/3600,0) ," h") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - CALL util.throw(CONCAT("Descansos ", FORMAT(vDayBreak/3600,0) ," h")); - END IF; - - -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ - IF (SELECT MOD(COUNT(*),2) -- <>0 - FROM vn.workerTimeControl - WHERE userFk = vUserFk AND - timed >= vLastIn - ) THEN - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - CALL util.throw("Dias con fichadas impares"); - END IF; - -- VERIFICAR VACACIONES - SELECT cs.type INTO vCalendarStateType - FROM postgresql.calendar_employee ce - JOIN postgresql.business b USING(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 USING(calendar_state_id) - JOIN vn.worker w ON w.id = p.id_trabajador - WHERE ce.date = CURDATE() AND - cs.isAllowedToWork = FALSE AND - w.userFk = vUserFk - LIMIT 1; - - IF(LENGTH(vCalendarStateType)) THEN - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - CALL util.throw(vCalendarStateType); - END IF; - - -- VERIFICAR DESCANSO SEMANAL - SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((vTimed - INTERVAL vWeekScope SECOND)); - - DROP TEMPORARY TABLE IF EXISTS tmp.trash; - CREATE TEMPORARY TABLE tmp.trash - SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, - @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed>= (vTimed - INTERVAL vWeekScope SECOND) AND - userFk= vUserFk AND - direction IN ('in','out') - ORDER BY timed ASC; - - IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA - SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((vTimed - INTERVAL vWeekMaxScope SECOND)); - DROP TEMPORARY TABLE tmp.trash; - CREATE TEMPORARY TABLE tmp.trash - SELECT IF(vWeekMaxBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, - @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed>= (vTimed - INTERVAL vWeekMaxScope SECOND) AND - userFk= vUserFk AND - direction IN ('in','out') - ORDER BY timed ASC; - IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) < vWeekMaxBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos ", FORMAT(vWeekMaxBreak/3600,0) ," h") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - CALL util.throw(CONCAT( "Descansos ", FORMAT(vWeekMaxBreak/3600,0) ," h")); - END IF; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos ", FORMAT(vWeekBreak/3600,0) ," h") INTO vBody; - CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); - CALL util.warn(CONCAT( "Descansos ", FORMAT(vWeekBreak/3600,0) ," h")); - END IF; - DROP TEMPORARY TABLE tmp.trash; - - -- Preguntar dirección de la fichada - IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastIn) >= vAskInOut AND (SELECT MOD(COUNT(*),2) - FROM vn.workerTimeControl WHERE userFk = vUserFk AND timed >= vLastIn) THEN - CALL util.warn("AskInOut"); - END IF ; -END$$ - -DELIMITER ; diff --git a/db/changes/10162-fallas/00-acl.sql b/db/changes/10162-fallas/00-acl.sql deleted file mode 100644 index 376788af1..000000000 --- a/db/changes/10162-fallas/00-acl.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('WorkerLog', '*', 'READ', 'ALLOW', 'ROLE', 'hr'); diff --git a/db/changes/10162-fallas/00-workerLog.sql b/db/changes/10162-fallas/00-workerLog.sql deleted file mode 100644 index 730b60aa5..000000000 --- a/db/changes/10162-fallas/00-workerLog.sql +++ /dev/null @@ -1,6 +0,0 @@ -ALTER TABLE `vn`.`workerLog` - ADD COLUMN `changedModel` VARCHAR(45) NULL DEFAULT NULL AFTER `description`, - ADD COLUMN `oldInstance` text CHARACTER SET utf8 COLLATE utf8_unicode_ci, - ADD COLUMN `newInstance` text CHARACTER SET utf8 COLLATE utf8_unicode_ci, - ADD COLUMN `changedModelId` int(11) DEFAULT NULL, - ADD COLUMN `changedModelValue` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql b/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql deleted file mode 100644 index d89f6a801..000000000 --- a/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql +++ /dev/null @@ -1,108 +0,0 @@ -DROP procedure IF EXISTS `vn`.`collectionPlacement_get`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collectionPlacement_get`(vCollectionFk INT) -BEGIN - - DECLARE vCalcFk INT; - DECLARE vWarehouseFk INT; - DECLARE vWarehouseAliasFk INT; - - SELECT t.warehouseFk, w.aliasFk - INTO vWarehouseFk, vWarehouseAliasFk - FROM vn.ticket t - JOIN vn.ticketCollection tc ON tc.ticketFk = t.id - JOIN vn.warehouse w ON w.id = t.warehouseFk - WHERE tc.collectionFk = vCollectionFk - LIMIT 1; - - CALL cache.visible_refresh(vCalcFk,FALSE,vWarehouseFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.parked; - CREATE TEMPORARY TABLE tmp.parked - ENGINE MEMORY - SELECT s.itemFk, 0 as quantity - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk; - - UPDATE tmp.parked pk - JOIN ( SELECT itemFk, sum(visible) as visible - FROM vn.itemShelvingStock iss - JOIN vn.warehouse w ON w.id = iss.warehouseFk - WHERE w.aliasFk = vWarehouseAliasFk - GROUP BY iss.itemFk ) iss ON iss.itemFk = pk.itemFk - SET pk.quantity = iss.visible; - - DROP TEMPORARY TABLE IF EXISTS tmp.`grouping`; - CREATE TEMPORARY TABLE tmp.`grouping` - ENGINE MEMORY - SELECT itemFk, `grouping` - FROM ( - SELECT itemFk, - CASE groupingMode - WHEN 0 THEN 1 - WHEN 2 THEN packing - ELSE `grouping` - END AS `grouping` - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - WHERE tr.warehouseInFk = vWarehouseFk - AND landed BETWEEN (SELECT inventoried FROM vn.config LIMIT 1) AND CURDATE() - AND b.isIgnored = FALSE - ORDER BY tr.landed DESC - ) sub - GROUP BY sub.itemFk ; - - DROP TEMPORARY TABLE IF EXISTS tmp.grouping2; - CREATE TEMPORARY TABLE tmp.grouping2 - ENGINE MEMORY - SELECT * FROM tmp.`grouping`; - - - SELECT s.id as saleFk, s.itemFk, - p.code COLLATE utf8_general_ci as placement , - sh.code COLLATE utf8_general_ci as shelving, - ish.created, - ish.visible, - 0 as `order`, - IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`) as `grouping` - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - JOIN vn.warehouse w ON w.id = sc.warehouseFk - JOIN tmp.`grouping` g ON g.itemFk = s.itemFk - WHERE tc.collectionFk = vCollectionFk - AND w.aliasFk = vWarehouseAliasFk - AND ish.visible > 0 - UNION ALL - SELECT s.id as saleFk, s.itemFk, - ip.code COLLATE utf8_general_ci as placement, - '' COLLATE latin1_general_ci as shelving, - modificationDate as created, - v.visible - p.quantity as visible, - 0 as `order`, - g.`grouping` - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.itemPlacement ip ON ip.itemFk = s.itemFk AND ip.warehouseFk = vWarehouseFk - JOIN tmp.parked p ON p.itemFk = s.itemFk - JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vCalcFk - LEFT JOIN tmp.grouping2 g ON g.itemFk = s.itemFk - WHERE tc.collectionFk = vCollectionFk - AND v.visible - p.quantity > 0; - - DROP TEMPORARY TABLE - tmp.parked, - tmp.`grouping`, - tmp.grouping2; -END - - -$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-collection_faults.sql b/db/changes/10162-postValentineDay/00-collection_faults.sql deleted file mode 100644 index 5faa42ca4..000000000 --- a/db/changes/10162-postValentineDay/00-collection_faults.sql +++ /dev/null @@ -1,39 +0,0 @@ -DROP procedure IF EXISTS `vn`.`collection_faults`; - -DELIMITER $$ - -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collection_faults`( - vShelvingFk VARCHAR(10), - vQuantity INT, - vItemFk INT) -BEGIN - DECLARE vQuantityTotal INT DEFAULT 0; - DECLARE vshelve VARCHAR(2); - DECLARE vdeep INT(11); - DECLARE vpriority INT(11); - DECLARE vgrouping SMALLINT(5); - DECLARE vpacking INT(11); - DECLARE vpackagingFk VARCHAR(10); - DECLARE vlevel VARCHAR(45); - DECLARE vuserFk INT(10); - - - SELECT SUM(quantity),shelve,deep,priority,`grouping`,packing,packagingFk,`level`,userFk - INTO vQuantityTotal,vshelve,vdeep,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk - FROM vn.itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk - GROUP BY itemFk; - - SELECT vQuantityTotal - vQuantity INTO vQuantityTotal; - - DELETE FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk; - - INSERT INTO vn.itemShelving (itemFk, shelvingFk,shelve,deep,quantity,visible,available,priority,`grouping`,packing,packagingFk,`level`,userFk ) - VALUES (vItemFk,vShelvingFk,vshelve,vdeep,vQuantityTotal,vQuantityTotal,vQuantityTotal,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk ); - - SELECT * FROM vn.itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk; - -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-collection_updateSale.sql b/db/changes/10162-postValentineDay/00-collection_updateSale.sql deleted file mode 100644 index cce8f4ff5..000000000 --- a/db/changes/10162-postValentineDay/00-collection_updateSale.sql +++ /dev/null @@ -1,42 +0,0 @@ -DROP procedure IF EXISTS `vn`.`collection_updateSale`; - - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collection_updateSale`( - vSaleFk INT, - vOriginalQuantity INT, - vWorkerFk INT, - vStateFk INT, - vTicketFk INT) -BEGIN - - DECLARE vNumPrepared INT; - DECLARE vNumTotal INT; - - REPLACE INTO vn.saleTracking(saleFk,isChecked, originalQuantity, workerFk, actionFk,stateFk) - VALUES(vSaleFk,1,vOriginalQuantity,vWorkerFk,vStateFk,vStateFk); - - UPDATE vn.sale SET isPicked = 1 - WHERE id = vSaleFk; - - SELECT COUNT(s.id) INTO vNumPrepared - FROM vn.sale s - WHERE s.ticketFk = vTicketFk AND s.isPicked = 1; - - SELECT COUNT(s.id) INTO vNumTotal - FROM vn.sale s - WHERE s.ticketFk = vTicketFk; - - IF vNumPrepared = vNumTotal THEN - - INSERT INTO vncontrol.inter - SET state_id = vStateFk, Id_Ticket = vTicketFk, Id_Trabajador = vWorkerFk; - - CALL vn.collection_update(vTicketFk); - - END IF; - - -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-coolerPathDetail.sql b/db/changes/10162-postValentineDay/00-coolerPathDetail.sql deleted file mode 100644 index 7d3006544..000000000 --- a/db/changes/10162-postValentineDay/00-coolerPathDetail.sql +++ /dev/null @@ -1,13 +0,0 @@ -/*DROP view IF EXISTS `vn`.`coolerPathDetail`; - -CREATE - ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn`.`coolerPathDetail` AS - SELECT - `c`.`cooler_path_detail_id` AS `id`, - `c`.`cooler_path_id` AS `coolerPathFk`, - `c`.`pasillo` AS `hallway` - FROM - `vn2008`.`cooler_path_detail` `c`*/ \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql b/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql deleted file mode 100644 index debdd3ac2..000000000 --- a/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql +++ /dev/null @@ -1,15 +0,0 @@ -DROP procedure IF EXISTS `vn`.`sale_updateOriginalQuantity`; - -DELIMITER $$ - -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`sale_updateOriginalQuantity`(vSale INT, vQuantity INT) -proc: BEGIN - -UPDATE vn.sale SET originalQuantity = vQuantity -WHERE id = vSale; - -SELECT * FROM vn.sale WHERE id = vSale; - -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql b/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql deleted file mode 100644 index 90611b559..000000000 --- a/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql +++ /dev/null @@ -1,14 +0,0 @@ -DROP procedure IF EXISTS `vn`.`sector_getWarehouse`; - -DELIMITER $$ - -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`sector_getWarehouse`(vSectorFk INT) -BEGIN - - SELECT s.warehouseFk - FROM vn.sector s - WHERE s.id = vSectorFk; - -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10180-holyWeek/00-claim.sql b/db/changes/10180-holyWeek/00-claim.sql new file mode 100644 index 000000000..e3b979efe --- /dev/null +++ b/db/changes/10180-holyWeek/00-claim.sql @@ -0,0 +1,2 @@ +ALTER TABLE `vn`.`claim` +ADD COLUMN `hasToPickUp` TINYINT(1) NOT NULL AFTER `ticketFk`; diff --git a/db/changes/10180-holyWeek/00-claimState.sql b/db/changes/10180-holyWeek/00-claimState.sql new file mode 100644 index 000000000..b4e8c68da --- /dev/null +++ b/db/changes/10180-holyWeek/00-claimState.sql @@ -0,0 +1,17 @@ +ALTER TABLE `vn`.`claimState` +DROP FOREIGN KEY `roleFgn`; +ALTER TABLE `vn`.`claimState` +ADD COLUMN `code` VARCHAR(45) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL AFTER `id`, +CHANGE COLUMN `roleFk` `roleFk` INT(10) UNSIGNED NOT NULL DEFAULT '1' ; +ALTER TABLE `vn`.`claimState` +ADD CONSTRAINT `roleFgn` + FOREIGN KEY (`roleFk`) + REFERENCES `account`.`role` (`id`) + ON UPDATE CASCADE; + +UPDATE `vn`.`claimState` SET `code` = 'pending' WHERE (`id` = '1'); +UPDATE `vn`.`claimState` SET `code` = 'canceled' WHERE (`id` = '4'); +UPDATE `vn`.`claimState` SET `code` = 'resolved' WHERE (`id` = '3'); +UPDATE `vn`.`claimState` SET `code` = 'disputed' WHERE (`id` = '5'); +UPDATE `vn`.`claimState` SET `code` = 'mana' WHERE (`id` = '6'); +UPDATE `vn`.`claimState` SET `code` = 'managed' WHERE (`id` = '2'); diff --git a/db/changes/10180-holyWeek/00-workerLog.sql b/db/changes/10180-holyWeek/00-workerLog.sql new file mode 100644 index 000000000..f3f76f274 --- /dev/null +++ b/db/changes/10180-holyWeek/00-workerLog.sql @@ -0,0 +1,6 @@ +ALTER TABLE `vn`.`workerLog` +ADD COLUMN `changedModel` VARCHAR(45) NULL DEFAULT NULL AFTER `description`, +ADD COLUMN `oldInstance` TEXT NULL DEFAULT NULL AFTER `changedModel`, +ADD COLUMN `newInstance` TEXT NULL DEFAULT NULL AFTER `oldInstance`, +ADD COLUMN `changedModelId` INT(11) NULL DEFAULT NULL AFTER `newInstance`, +ADD COLUMN `changedModelValue` VARCHAR(45) NULL DEFAULT NULL AFTER `changedModelId`; diff --git a/db/changes/10180-holyWeek/03-ekt_load.sql b/db/changes/10180-holyWeek/03-ekt_load.sql index 0c83569b8..6766cdfaf 100644 --- a/db/changes/10180-holyWeek/03-ekt_load.sql +++ b/db/changes/10180-holyWeek/03-ekt_load.sql @@ -1,3 +1,9 @@ + +USE `edi`; +DROP procedure IF EXISTS `ekt_load`; + +DELIMITER $$ +USE `edi`$$ CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) BEGIN DECLARE vRef INT; diff --git a/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__.sql similarity index 100% rename from db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql rename to db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__.sql diff --git a/db/changes/10190-postRegulation/00-claimState.sql b/db/changes/10190-postRegulation/00-claimState.sql new file mode 100644 index 000000000..72159d102 --- /dev/null +++ b/db/changes/10190-postRegulation/00-claimState.sql @@ -0,0 +1,10 @@ +ALTER TABLE `vn`.`claimState` +ADD COLUMN `priority` INT NOT NULL DEFAULT 1 AFTER `roleFk`; + +UPDATE `vn`.`claimState` SET `priority` = '1' WHERE (`id` = '1'); +UPDATE `vn`.`claimState` SET `priority` = '5' WHERE (`id` = '2'); +UPDATE `vn`.`claimState` SET `priority` = '7' WHERE (`id` = '3'); +UPDATE `vn`.`claimState` SET `priority` = '6' WHERE (`id` = '4'); +UPDATE `vn`.`claimState` SET `priority` = '3' WHERE (`id` = '5'); +UPDATE `vn`.`claimState` SET `priority` = '4' WHERE (`id` = '6'); +UPDATE `vn`.`claimState` SET `priority` = '2' WHERE (`id` = '7'); \ No newline at end of file diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 2f2f826a1..801e4a25f 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -23,7 +23,7 @@ USE `util`; LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; -INSERT INTO `config` VALUES (1,'10161',0,'production',NULL); +INSERT INTO `config` VALUES (1,'10170',0,'production',NULL); /*!40000 ALTER TABLE `config` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -36,7 +36,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-03-16 9:45:09 +-- Dump completed on 2020-05-13 12:18:35 USE `account`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -94,7 +94,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-03-16 9:45:11 +-- Dump completed on 2020-05-13 12:18:36 USE `salix`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -142,7 +142,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-03-16 9:45:12 +-- Dump completed on 2020-05-13 12:18:38 USE `vn`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -287,7 +287,7 @@ UNLOCK TABLES; LOCK TABLES `state` WRITE; /*!40000 ALTER TABLE `state` DISABLE KEYS */; -INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0,0),(2,'Libre',2,0,'FREE',NULL,2,0,0,0,0,1,0),(3,'OK',3,0,'OK',3,28,1,0,0,0,1,1),(4,'Impreso',4,1,'PRINTED',2,29,1,0,1,0,0,0),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0,0,2,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0,0),(7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,1,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0,0),(9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0,0),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1,0,0,0,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0,0),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0,0),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0,0,0,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0,0,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0,0,0,0,0),(24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0,0,0,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0,1,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0,0,1,1,1),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0,1,1,0,0),(30,'Embarcado',4,0,'BOARD',5,30,0,0,0,2,0,0); +INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0,0,4),(2,'Libre',2,0,'FREE',NULL,2,0,0,0,0,1,0,4),(3,'OK',3,0,'OK',3,28,1,0,0,0,1,1,3),(4,'Impreso',4,1,'PRINTED',2,29,1,0,1,0,0,0,2),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0,0,2,0,0,2),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0,0,1),(7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,1,0,4),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0,0,1),(9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0,0,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0,0,0),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1,0,0,0,0,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0,4),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0,0,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0,0,1),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0,0,0),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0,0,0,0,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0,2),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0,0,2),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0,0,0,0,4),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0,0,0,0,0,4),(24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0,3),(25,'Embarcando',3,0,'BOARDING',5,25,0,0,0,0,0,0,3),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0,1,0,0,2),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0,2),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0,0,1,1,1,3),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0,1,1,0,0,3),(30,'Embarcado',4,0,'BOARD',5,30,0,0,0,2,0,0,3),(31,'Polizon Impreso',4,1,'PRINTED STOWAWAY',2,29,1,0,1,0,0,0,3),(32,'Polizon OK',3,1,'OK STOWAWAY',3,31,1,0,0,1,1,1,3),(33,'Auto_Impreso',4,1,'PRINTED_AUTO',2,29,1,0,1,0,0,0,2); /*!40000 ALTER TABLE `state` ENABLE KEYS */; UNLOCK TABLES; @@ -307,7 +307,7 @@ UNLOCK TABLES; LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; -INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/',NULL),(23,'CAMARA',14,19,NULL,72,604,2,6,1,0,1,2,37,'/37/',NULL),(31,'INFORMATICA',5,6,NULL,72,127,3,9,0,0,0,0,NULL,'/','informatica'),(34,'CONTABILIDAD',7,8,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(35,'FINANZAS',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(36,'LABORAL',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(37,'PRODUCCION',13,46,NULL,72,230,3,11,1,0,0,14,NULL,'/',NULL),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,1,0,37,'/37/',NULL),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,1,0,37,'/37/',NULL),(41,'ADMINISTRACION',47,48,NULL,72,599,3,8,0,0,0,0,NULL,'/',NULL),(43,'VENTAS',49,70,NULL,0,NULL,NULL,NULL,0,0,0,10,NULL,'/',NULL),(44,'GERENCIA',71,72,NULL,72,300,2,7,0,0,0,0,NULL,'/',NULL),(45,'LOGISTICA',73,74,NULL,72,596,3,19,0,0,0,0,NULL,'/',NULL),(46,'REPARTO',75,78,NULL,72,659,3,10,0,0,0,1,NULL,'/',NULL),(48,'ALMACENAJE',79,80,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(49,'PROPIEDAD',81,82,NULL,72,1008,1,1,0,0,0,0,NULL,'/',NULL),(52,'CARGA AEREA',83,84,NULL,72,163,4,28,0,0,0,0,NULL,'/',NULL),(53,'MARKETING Y COMUNICACIÓN',85,86,NULL,72,1238,0,0,0,0,0,0,NULL,'/',NULL),(54,'ORNAMENTALES',87,88,NULL,72,433,3,21,0,0,0,0,NULL,'/',NULL),(55,'TALLER NATURAL',89,90,NULL,72,695,2,23,0,0,0,0,NULL,'/',NULL),(56,'TALLER ARTIFICIAL',91,92,NULL,72,1780,2,24,0,0,0,0,NULL,'/',NULL),(58,'CAMPOS',93,94,NULL,72,225,2,2,0,0,0,0,NULL,'/',NULL),(59,'MANTENIMIENTO',95,96,NULL,72,1907,4,16,0,0,0,0,NULL,'/',NULL),(60,'RECLAMACIONES',97,98,NULL,72,563,3,20,0,0,0,0,NULL,'/',NULL),(61,'VNH',99,100,NULL,73,1297,3,17,0,0,0,0,NULL,'/',NULL),(63,'VENTAS FRANCIA',50,51,NULL,72,277,2,27,0,0,1,0,43,'/43/',NULL),(66,'VERDNAMADRID',101,102,NULL,72,163,3,18,0,0,0,0,NULL,'/',NULL),(68,'COMPLEMENTOS',24,25,NULL,72,617,3,26,1,0,1,0,37,'/37/',NULL),(69,'VERDNABARNA',103,104,NULL,74,432,3,22,0,0,0,0,NULL,'/',NULL),(77,'PALETIZADO',76,77,NULL,72,230,4,15,0,0,1,0,46,'/46/',NULL),(80,'EQUIPO J VALLES',52,53,NULL,72,693,3,4,0,0,1,0,43,'/43/','jvp_equipo'),(86,'LIMPIEZA',105,106,NULL,72,599,0,0,0,0,0,0,NULL,'/',NULL),(89,'COORDINACION',107,108,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(90,'TRAILER',109,110,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(91,'ARTIFICIAL',26,27,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(92,'EQUIPO SILVERIO',54,55,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','sdc_equipo'),(93,'CONFECCION',111,112,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(94,'EQUIPO J BROCAL',56,57,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jes_equipo'),(95,'EQUIPO C ZAMBRANO',58,59,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','czg_equipo'),(96,'EQUIPO C LOPEZ',60,61,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','cla_equipo'),(97,'EQUIPO D SARRION',62,63,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','dsr_equipo'),(98,'EQUIPO RODRIGO',64,65,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','rhr_equipo'),(99,'EQUIPO MANOLI',66,67,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','man_equipo'),(101,'EQUIPO J IBAÑEZ',68,69,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jmi_equipo'),(102,'EQ ROJO FV RUBEN C',28,29,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(103,'EQ AZUL FV A FOLQUES',30,31,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(104,'EQ AMARILLO FV NORMAN G',32,33,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(105,'EQ MORADO FV MATOU',34,35,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(106,'EQ VERDE PCA KEVIN GIMENEZ',36,37,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(107,'EQ NARANJA PCA RUBEN ZANON',38,39,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(110,'EQ ROSA PCA J BONDIA',40,41,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(111,'EQ REPONEDOR CAJAS',42,43,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(112,'CAMARA EQ EDGAR LLEO',15,16,NULL,0,NULL,NULL,NULL,0,0,2,0,23,'/37/23/',NULL),(113,'CAMARA EQ MARC ROCA',17,18,NULL,0,NULL,NULL,NULL,0,0,2,0,23,'/37/23/',NULL),(114,'EQ MARRON PCA JL NUEVO',44,45,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL); +INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/',NULL),(23,'CAMARA',14,19,NULL,72,604,2,6,1,0,1,2,37,'/37/',NULL),(31,'INFORMATICA',5,6,NULL,72,127,3,9,0,0,0,0,NULL,'/','informatica'),(34,'CONTABILIDAD',7,8,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(35,'FINANZAS',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(36,'LABORAL',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(37,'PRODUCCION',13,46,NULL,72,230,3,11,1,0,0,14,NULL,'/',NULL),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,1,0,37,'/37/',NULL),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,1,0,37,'/37/',NULL),(41,'ADMINISTRACION',47,48,NULL,72,599,3,8,0,0,0,0,NULL,'/',NULL),(43,'VENTAS',49,72,NULL,0,NULL,NULL,NULL,0,0,0,11,NULL,'/',NULL),(44,'GERENCIA',73,74,NULL,72,300,2,7,0,0,0,0,NULL,'/',NULL),(45,'LOGISTICA',75,76,NULL,72,596,3,19,0,0,0,0,NULL,'/',NULL),(46,'REPARTO',77,80,NULL,72,659,3,10,0,0,0,1,NULL,'/',NULL),(48,'ALMACENAJE',81,82,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(49,'PROPIEDAD',83,84,NULL,72,1008,1,1,0,0,0,0,NULL,'/',NULL),(52,'CARGA AEREA',85,86,NULL,72,163,4,28,0,0,0,0,NULL,'/',NULL),(53,'MARKETING Y COMUNICACIÓN',87,88,NULL,72,1238,0,0,0,0,0,0,NULL,'/',NULL),(54,'ORNAMENTALES',89,90,NULL,72,433,3,21,0,0,0,0,NULL,'/',NULL),(55,'TALLER NATURAL',91,92,NULL,72,695,2,23,0,0,0,0,NULL,'/',NULL),(56,'TALLER ARTIFICIAL',93,94,NULL,72,1780,2,24,0,0,0,0,NULL,'/',NULL),(58,'CAMPOS',95,96,NULL,72,225,2,2,0,0,0,0,NULL,'/',NULL),(59,'MANTENIMIENTO',97,98,NULL,72,1907,4,16,0,0,0,0,NULL,'/',NULL),(60,'RECLAMACIONES',99,100,NULL,72,563,3,20,0,0,0,0,NULL,'/',NULL),(61,'VNH',101,102,NULL,73,1297,3,17,0,0,0,0,NULL,'/',NULL),(63,'VENTAS FRANCIA',50,51,NULL,72,277,2,27,0,0,1,0,43,'/43/',NULL),(66,'VERDNAMADRID',103,104,NULL,72,163,3,18,0,0,0,0,NULL,'/',NULL),(68,'COMPLEMENTOS',24,25,NULL,72,617,3,26,1,0,1,0,37,'/37/',NULL),(69,'VERDNABARNA',105,106,NULL,74,432,3,22,0,0,0,0,NULL,'/',NULL),(77,'PALETIZADO',78,79,NULL,72,230,4,15,0,0,1,0,46,'/46/',NULL),(80,'EQUIPO J VALLES',52,53,NULL,72,693,3,4,0,0,1,0,43,'/43/','jvp_equipo'),(86,'LIMPIEZA',107,108,NULL,72,599,0,0,0,0,0,0,NULL,'/',NULL),(89,'COORDINACION',109,110,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(90,'TRAILER',111,112,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(91,'ARTIFICIAL',26,27,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(92,'EQUIPO SILVERIO',54,55,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','sdc_equipo'),(93,'CONFECCION',113,114,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL),(94,'EQUIPO J BROCAL',56,57,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jes_equipo'),(95,'EQUIPO C ZAMBRANO',58,59,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','czg_equipo'),(96,'EQUIPO C LOPEZ',60,61,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','cla_equipo'),(97,'EQUIPO D SARRION',62,63,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','dsr_equipo'),(98,'EQUIPO RODRIGO',64,65,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','rhr_equipo'),(99,'EQUIPO MANOLI',66,67,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','man_equipo'),(101,'EQUIPO J IBAÑEZ',68,69,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jmi_equipo'),(102,'EQ ROJO FV RUBEN C',28,29,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(103,'EQ AZUL FV A FOLQUES',30,31,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(104,'EQ AMARILLO FV NORMAN G',32,33,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(105,'EQ MORADO FV MATOU',34,35,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(106,'EQ VERDE PCA KEVIN GIMENEZ',36,37,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(107,'EQ NARANJA PCA RUBEN ZANON',38,39,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(110,'EQ ROSA PCA J BONDIA',40,41,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(111,'EQ REPONEDOR CAJAS',42,43,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL),(112,'CAMARA EQ EDGAR LLEO',15,16,NULL,0,NULL,NULL,NULL,0,0,2,0,23,'/37/23/',NULL),(113,'CAMARA EQ MARC ROCA',17,18,NULL,0,NULL,NULL,NULL,0,0,2,0,23,'/37/23/',NULL),(114,'EQ MARRON PCA JL NUEVO',44,45,NULL,0,NULL,NULL,NULL,0,0,1,0,37,'/37/',NULL),(115,'EQUIPO CLAUDI',70,71,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','csr_equipo'); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; @@ -317,7 +317,7 @@ UNLOCK TABLES; LOCK TABLES `component` WRITE; /*!40000 ALTER TABLE `component` DISABLE KEYS */; -INSERT INTO `component` VALUES (10,'Precios Especiales',4,NULL,NULL,1,'specialPrices'),(14,'porte extra por dia semana',6,NULL,NULL,1,'extraCostPerWeekDay'),(15,'reparto',6,NULL,NULL,1,'delivery'),(17,'recobro',5,NULL,NULL,1,'debtCollection'),(21,'ajuste',12,NULL,NULL,1,'adjustment'),(22,'venta por paquete',9,1,NULL,0,'salePerPackage'),(23,'venta por caja',9,2,NULL,0,'salePerBox'),(28,'valor de compra',1,NULL,NULL,1,'purchaseValue'),(29,'margen',4,NULL,NULL,1,'margin'),(32,'descuento ultimas unidades',9,3,-0.05,0,'lastUnitsDiscount'),(33,'venta por caja',9,1,NULL,0,'salePerBox'),(34,'descuento comprador',4,NULL,NULL,1,'buyerDiscount'),(35,'cartera comprador',10,NULL,NULL,1,NULL),(36,'descuadre',11,NULL,NULL,1,'mismatch'),(37,'maná',7,4,NULL,0,'mana'),(38,'embolsado',9,NULL,NULL,1,'bagged'),(39,'maná auto',7,NULL,NULL,1,'autoMana'),(40,'cambios Santos 2016',4,NULL,NULL,1,NULL),(41,'bonificacion porte',4,NULL,NULL,1,'freightCharge'); +INSERT INTO `component` VALUES (10,'Precios Especiales',4,NULL,NULL,1,'specialPrices'),(14,'porte extra por dia semana',6,NULL,NULL,1,'extraCostPerWeekDay'),(15,'reparto',6,NULL,NULL,1,'delivery'),(17,'recobro',5,NULL,NULL,1,'debtCollection'),(21,'ajuste',12,NULL,NULL,1,'adjustment'),(22,'venta por paquete',9,1,NULL,0,'salePerPackage'),(23,'venta por caja',9,2,NULL,0,'salePerBox'),(28,'valor de compra',1,NULL,NULL,1,'purchaseValue'),(29,'margen',4,NULL,NULL,1,'margin'),(32,'descuento ultimas unidades',9,3,-0.05,0,'lastUnitsDiscount'),(33,'venta por caja',9,1,NULL,0,'salePerBox'),(34,'descuento comprador',4,NULL,NULL,1,'buyerDiscount'),(35,'cartera comprador',10,NULL,NULL,1,NULL),(36,'descuadre',11,NULL,NULL,1,'imbalance'),(37,'maná',7,4,NULL,0,'mana'),(38,'embolsado',9,NULL,NULL,1,'bagged'),(39,'maná auto',7,NULL,NULL,1,'autoMana'),(40,'cambios Santos 2016',4,NULL,NULL,1,NULL),(41,'bonificacion porte',4,NULL,NULL,1,'freightCharge'); /*!40000 ALTER TABLE `component` ENABLE KEYS */; UNLOCK TABLES; @@ -340,7 +340,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-03-16 9:45:18 +-- Dump completed on 2020-05-13 12:18:43 USE `cache`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -378,7 +378,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-03-16 9:45:19 +-- Dump completed on 2020-05-13 12:18:44 USE `hedera`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -436,7 +436,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-03-16 9:45:21 +-- Dump completed on 2020-05-13 12:18:45 USE `postgresql`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -511,7 +511,7 @@ UNLOCK TABLES; LOCK TABLES `workcenter` WRITE; /*!40000 ALTER TABLE `workcenter` DISABLE KEYS */; -INSERT INTO `workcenter` VALUES (1,'Silla',20,1033,1),(2,'Mercaflor',19,NULL,NULL),(3,'Marjales',26,20008,NULL),(4,'VNH',NULL,NULL,3),(5,'Madrid',28,2852,5),(6,'Vilassar',88,88031,2),(7,'Tenerife',NULL,NULL,10); +INSERT INTO `workcenter` VALUES (1,'Silla',20,1033,1,'Av espioca 100',552703),(2,'Mercaflor',19,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL),(4,'VNH',NULL,NULL,3,NULL,NULL),(5,'Madrid',28,2852,5,'Av constitución 3',554145),(6,'Vilassar',88,88031,2,'Cami del Crist, 33',556412),(7,'Tenerife',NULL,NULL,10,NULL,NULL); /*!40000 ALTER TABLE `workcenter` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -524,4 +524,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-03-16 9:45:23 +-- Dump completed on 2020-05-13 12:18:47 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 792787154..6b3e1905e 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -39,8 +39,8 @@ INSERT INTO `account`.`user`(`id`,`name`, `nickname`, `password`,`role`,`active` FROM `account`.`role` WHERE id <> 20 ORDER BY id; -INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `userFk`, `bossFk`, `email`) - SELECT id,UPPER(LPAD(role, 3, '0')), name, name, id, 9, 'test@nightmare.es' +INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `userFk`, `bossFk`) + SELECT id,UPPER(LPAD(role, 3, '0')), name, name, id, 9 FROM `vn`.`user`; UPDATE `vn`.`worker` SET bossFk = NULL WHERE id = 20; @@ -68,13 +68,13 @@ INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`, (111, 'Missing', 'Missing', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'en'), (112, 'Trash', 'Trash', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'en'); -INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`, `userFk`,`bossFk`, `phone`, `email`) +INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`, `userFk`,`bossFk`, `phone`) VALUES - (106, 'LGN', 'David Charles', 'Haller', 106, 19, 432978106, 'test@nightmare.es'), - (107, 'ANT', 'Hank' , 'Pym' , 107, 19, 432978107, 'test@nightmare.es'), - (108, 'DCX', 'Charles' , 'Xavier', 108, 19, 432978108, 'test@nightmare.es'), - (109, 'HLK', 'Bruce' , 'Banner', 109, 19, 432978109, 'test@nightmare.es'), - (110, 'JJJ', 'Jessica' , 'Jones' , 110, 19, 432978110, 'test@nightmare.es'); + (106, 'LGN', 'David Charles', 'Haller', 106, 19, 432978106), + (107, 'ANT', 'Hank' , 'Pym' , 107, 19, 432978107), + (108, 'DCX', 'Charles' , 'Xavier', 108, 19, 432978108), + (109, 'HLK', 'Bruce' , 'Banner', 109, 19, 432978109), + (110, 'JJJ', 'Jessica' , 'Jones' , 110, 19, 432978110); INSERT INTO `vn`.`country`(`id`, `country`, `isUeeMember`, `code`, `currencyFk`, `ibanLength`) VALUES @@ -975,10 +975,10 @@ INSERT INTO `vn`.`itemBarcode`(`id`, `itemFk`, `code`) INSERT INTO `vn`.`itemPlacement`(`id`, `itemFk`, `warehouseFk`, `code`) VALUES - (1, 1, 1, 'A1'), - (2, 1, 2, 'A2'), - (3, 1, 3, 'A3'), - (4, 2, 1, 'A4'); + (1, 1, 1, 'A11'), + (2, 1, 2, 'A22'), + (3, 1, 3, 'A33'), + (4, 2, 1, 'A44'); INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`) @@ -1473,14 +1473,15 @@ INSERT INTO `vn`.`clientSample`(`id`, `clientFk`, `typeFk`, `created`, `workerFk (4, 102, 2, CURDATE(), 18, 18, 567), (5, 102, 3, CURDATE(), 19, 19, 567); -INSERT INTO `vn`.`claimState`(`id`, `description`, `roleFk`) +INSERT INTO `vn`.`claimState`(`id`, `code`, `description`, `roleFk`, `priority`) VALUES - ( 1, 'Pendiente', 1), - ( 2, 'Gestionado', 1), - ( 3, 'Resuelto', 21), - ( 4, 'Anulado', 1), - ( 5, 'Cuestionado', 21), - ( 6, 'Mana', 1); + ( 1, 'pending', 'Pendiente', 1, 1), + ( 2, 'managed', 'Gestionado', 1, 5), + ( 3, 'resolved', 'Resuelto', 21, 7), + ( 4, 'canceled', 'Anulado', 1, 6), + ( 5, 'disputed', 'Cuestionado', 21, 3), + ( 6, 'mana', 'Mana', 1, 4), + ( 7, 'inProgress', 'En Curso', 1, 2); INSERT INTO `vn`.`claim`(`id`, `ticketCreated`, `claimStateFk`, `observation`, `clientFk`, `workerFk`, `responsibility`, `isChargedToMana`, `created` ) VALUES @@ -2039,12 +2040,14 @@ REPLACE INTO `vn`.`customsAgent`(`id`, `fiscalName`, `street`, `nif`, `phone`, ` (1, 'Agent one', '1007 Mountain Drive, Gotham', 'N1111111111', '111111111', 'agentone@gotham.com'), (2, 'Agent two', '1007 Mountain Drive, Gotham', 'N2222222222', '222222222', 'agenttwo@gotham.com'); +INSERT INTO `vn`.`tablet`(`uuid`, `name`, `place`, `macwifi`) + VALUES + ('1', 'TEST', 'ON THE FIXTURES', '0'), + ('2', 'DEV', 'OTHER TABLET', '0'); + INSERT INTO `vn`.`tabletDepartment`(`tabletFk`, `departmentFk`) VALUES (1, 23), (2, 1); -INSERT INTO `vn`.`tablet`(`uuid`, `name`, `place`, `macwifi`) - VALUES - ('1', 'TEST', 'ON THE FIXTURES', '0'), - ('2', 'DEV', 'OTHER TABLET', '0'); + diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 2a1a168d7..31426900c 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -1838,12 +1838,12 @@ DROP TABLE IF EXISTS `bancos_evolution`; 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', + `saldo` decimal(10,2) NOT NULL DEFAULT '0.00', + `quilla` decimal(10,2) NOT NULL DEFAULT '0.00', + `deuda` decimal(10,2) NOT NULL DEFAULT '0.00', + `liquidez` decimal(10,2) NOT NULL DEFAULT '0.00', + `disponibilidad ajena` decimal(10,2) NOT NULL DEFAULT '0.00', + `saldo_aux` decimal(10,2) NOT NULL DEFAULT '0.00' 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 @@ -2520,6 +2520,29 @@ CREATE TABLE `salesByWeek` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `salesPersonClient` +-- + +DROP TABLE IF EXISTS `salesPersonClient`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `salesPersonClient` ( + `salesPersonFk` int(11) NOT NULL, + `clientFk` int(11) NOT NULL, + `year` int(4) NOT NULL, + `month` int(2) NOT NULL, + `amount` decimal(10,2) DEFAULT NULL, + `comission` decimal(10,2) DEFAULT NULL, + `comissionBorrowed` decimal(10,2) DEFAULT NULL, + `comissionLended` decimal(10,2) DEFAULT NULL, + `comissionNewClient` decimal(10,2) DEFAULT NULL, + `substitutionBorrowed` decimal(10,2) DEFAULT NULL, + `itemTypeBorrowed` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`salesPersonFk`,`clientFk`,`year`,`month`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Ventas por comercial por cliente'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `vendedores` -- @@ -2659,13 +2682,13 @@ SET character_set_client = utf8; SET character_set_client = @saved_cs_client; -- --- Table structure for table `workerSpeed` +-- Table structure for table `workerSpeed__` -- -DROP TABLE IF EXISTS `workerSpeed`; +DROP TABLE IF EXISTS `workerSpeed__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerSpeed` ( +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', @@ -2790,13 +2813,129 @@ 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 ;; CREATE DEFINER=`root`@`%` PROCEDURE `bancos_evolution_add`() +BEGIN +/** + * Inserta en la tabla bancos_evolution los saldos acumulados de cada banco + */ + 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 + 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 + + )sub + GROUP BY Id_Banco; + + SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); + + END WHILE; + + -- Ahora actualizamos la quilla + UPDATE bs.bancos_evolution be + JOIN + ( + SELECT bp.Id_Banco, - sum(bp.importe) as quilla, t.dated + FROM vn.time t + JOIN vn2008.Bancos_poliza bp ON t.dated between apertura AND IFNULL(cierre, t.dated) + GROUP BY Id_Banco, t.dated + ) sub ON be.Id_Banco = sub.Id_Banco AND sub.dated = be.Fecha + SET be.quilla = sub.quilla; + + -- pagos futuros no concilidados + INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) + SELECT t.dated, p.id_banco, - importe + FROM vn.time t + join vn2008.pago p ON p.fecha <= t.dated + WHERE p.fecha >= CURDATE() + AND NOT conciliado + ON DUPLICATE KEY UPDATE saldo = saldo - VALUES(saldo); + + -- cobros futuros + INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) + SELECT t.dated, r.Id_Banco, SUM(Entregado) + FROM vn.time t + JOIN vn2008.Recibos r ON r.Fechacobro <= t.dated + WHERE r.Fechacobro > CURDATE() + GROUP BY t.dated, r.Id_Banco + ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo); + + -- saldos de la tabla prevision + INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) + SELECT t.dated, sp.Id_Banco, SUM(Importe) + FROM vn.time t + JOIN vn2008.Saldos_Prevision sp ON sp.Fecha <= t.dated + JOIN vn2008.Bancos b ON sp.Id_Banco = b.Id_Banco + WHERE b.cash IN (0,3) + GROUP BY t.dated, sp.Id_Banco + ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo); + + -- Utilizamos el saldo_auxiliar para calcular lo dispuesto en las polizas + UPDATE bs.bancos_evolution be + SET saldo_aux = saldo; + + -- 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 `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 = 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 `bancos_evolution_add__`() BEGIN /* @@ -4055,16 +4194,16 @@ BEGIN * 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))) ; - + + 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 */ ; @@ -4897,6 +5036,201 @@ 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 PROCEDURE IF EXISTS `salesPersonClient_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 `salesPersonClient_add`(intYEAR INT, vQuarter INT) +BEGIN + + DECLARE vCommissionRate DOUBLE DEFAULT 0.029; + + DELETE s.* FROM salesPersonClient s + JOIN vn.`time` t ON t.`year` = s.year AND t.`month` = s.month + WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter; + + REPLACE salesPersonClient(salesPersonFk,clientFk, year, month, amount, comission) + SELECT c.salesPersonFk, + c.id, + intYEAR, + MONTH(v.fecha), + SUM(v.importe), + SUM(v.importe) * vCommissionRate + FROM ventas v + JOIN vn.client c on v.Id_Cliente = c.id + JOIN vn.`time` t on t.dated = v.fecha + WHERE c.salesPersonFk IS NOT NULL AND + t.`year` = intYEAR AND + QUARTER(t.dated) = vQuarter + GROUP BY c.salesPersonFk, + c.id, + t.`month`; + + -- Ventas nuevas + UPDATE salesPersonClient s + JOIN (SELECT c.salesPersonFk, + c.id, + SUM(importe) * vCommissionRate AS comissionNewClient, + t.`month`, + t.`year` + FROM ventas v + JOIN bs.clientNewBorn cnb ON v.Id_Cliente = cnb.clientFk + JOIN vn.client c ON c.id = v.Id_Cliente + JOIN vn.`time` t ON t.dated = v.fecha + WHERE c.salesPersonFk IS NOT NULL AND + t.`year` = intYEAR AND + QUARTER(v.fecha) = vQuarter + GROUP BY c.salesPersonFk, + c.id, + t.`month` + ) sub ON sub.salesPersonFk = s.salesPersonFk AND + sub.id = s.clientFk AND + sub.`month` = s.month AND + sub.`year` = s.year + SET s.comissionNewClient = sub.comissionNewClient, + s.comission = s.comission - sub.comissionNewClient; + + -- Ventas cedidas + INSERT INTO salesPersonClient (salesPersonFk, clientFk, month, year, comissionLended) + SELECT cc.Id_Trabajador_old AS workerFk, + c.id, + t.`month`, + t.`year`, + SUM(importe) * vCommissionRate * cc.comision_old AS comissionLended + FROM ventas v + JOIN vn.client c ON c.id = v.Id_Cliente + JOIN vn2008.Clientes_cedidos cc ON cc.Id_Cliente = c.id AND v.fecha BETWEEN datSTART AND datEND + JOIN vn.`time` t ON t.dated = v.fecha + WHERE c.salesPersonFk IS NOT NULL AND + t.`year` = intYEAR AND + QUARTER(v.fecha) = vQuarter + GROUP BY cc.Id_Trabajador_old, + c.id, + t.`month` + ON DUPLICATE KEY UPDATE comissionLended = IFNULL(comissionLended,0) + VALUES(comissionLended); + + -- Ventas arrendadas + INSERT INTO salesPersonClient (salesPersonFk, clientFk, month, year, comissionBorrowed) + SELECT cc.Id_Trabajador_new AS workerFk, + c.id, + t.`month`, + t.`year`, + SUM(importe) * vCommissionRate * cc.comision_new AS comissionBorrowed + FROM ventas v + JOIN vn.client c ON c.id = v.Id_Cliente + JOIN vn2008.Clientes_cedidos cc ON cc.Id_Cliente = c.id AND v.fecha BETWEEN datSTART AND datEND + JOIN vn.`time` t ON t.dated = v.fecha + WHERE c.salesPersonFk IS NOT NULL AND + t.`year` = intYEAR AND + QUARTER(v.fecha) = vQuarter + GROUP BY cc.Id_Trabajador_new, + c.id, + t.`month` + ON DUPLICATE KEY UPDATE comissionBorrowed = IFNULL(comissionBorrowed,0) + VALUES(comissionBorrowed); + + -- Actualización del campo comisión restando las comisiones arrendadas y cedidas + UPDATE salesPersonClient s + JOIN ( SELECT clientFk, `month`, year, SUM(comissionBorrowed) comissionBorrowed,SUM(comissionLended) comissionLended, QUARTER(CONCAT("2000-",`month`, "-01")) vQuarterMonth + FROM salesPersonClient + WHERE (comissionLended IS NOT NULL OR comissionBorrowed IS NOT NULL) AND + year = intYEAR + GROUP BY clientFk, `month` + HAVING vQuarterMonth = vQuarter + ) sub ON sub.clientFk = s.clientFk AND + sub.month = s.month AND + sub.year = s.year + SET s.comission = s.comission - sub.comissionBorrowed - sub.comissionLended + WHERE s.comission IS NOT NULL; + + -- Sustitucion cedidas - lended + INSERT INTO salesPersonClient (salesPersonFk, clientFk, month, year, comission) + SELECT c.salesPersonFk, + c.id, + t.`month`, + t.`year`, + SUM(importe) * vCommissionRate AS lended + FROM ventas v + JOIN vn.client c ON c.id = v.Id_Cliente + JOIN vn.sharingCartDaily scd ON scd.ownerFk = c.salesPersonFk AND scd.dated = v.fecha + JOIN vn.`time` t ON t.dated = v.fecha + WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter + GROUP BY c.salesPersonFk, + c.id, + t.`month` + ON DUPLICATE KEY UPDATE comission = comission - VALUES(comission); + + -- Sustitucion arrendadas - borrowed + INSERT INTO salesPersonClient (salesPersonFk, clientFk, month, year, substitutionBorrowed) + SELECT scd.substituteFk, + c.id, + t.`month`, + t.`year`, + SUM(importe) * vCommissionRate AS borrowed + FROM ventas v + JOIN vn.client c ON c.id = v.Id_Cliente + JOIN vn.sharingCartDaily scd on scd.ownerFk = c.salesPersonFk AND scd.dated = v.fecha + JOIN vn.`time` t ON t.dated = v.fecha + WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter + GROUP BY scd.substituteFk, c.id, t.`month` + ON DUPLICATE KEY UPDATE substitutionBorrowed = VALUES(substitutionBorrowed); + + DROP TEMPORARY TABLE IF EXISTS tmp.workerItemType; + + CREATE TEMPORARY TABLE tmp.workerItemType + (INDEX(ownerWorkerFk, itemTypeFk)) + SELECT wd.workerFk ownerWorkerFk, itemTypeFk, dit.workerFk substituteFk + FROM vn.departmentItemType dit + JOIN vn.workerDepartment wd ON wd.departmentFk = dit.departmentFk; + + -- itemType Lended, prestado + UPDATE salesPersonClient s + JOIN (SELECT c.salespersonFk, + c.id, + SUM(importe) * vCommissionRate AS amount, + t.`month`, + t.`year` + FROM ventas v + JOIN vn.client c on c.id = v.Id_Cliente + JOIN tmp.workerItemType wit ON wit.ownerWorkerFk = c.salespersonFk AND wit.itemTypeFk = v.tipo_id + JOIN vn.`time` t on t.dated = v.fecha + WHERE t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY c.salespersonFk, + c.id, + t.`month` + ) sub ON sub.salespersonFk = s.salespersonFk AND + sub.id = s.clientFk AND + sub.`month` = s.`month` AND + sub.`year` = s.`year` + SET s.comission = s.comission - sub.amount; + + -- itemType borrowed, tomado prestado + INSERT INTO salesPersonClient (salesPersonFk, clientFk, `year`, `month`, itemTypeBorrowed) + SELECT wit.substituteFk, + c.id, + t.`year`, + t.`month`, + importe * vCommissionRate + FROM ventas v + JOIN vn.client c on v.Id_Cliente = c.id + JOIN tmp.workerItemType wit ON wit.ownerWorkerFk = c.salesPersonFk AND wit.itemTypeFk = v.tipo_id + JOIN vn.`time` t on t.`dated` = v.fecha + WHERE t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + ON DUPLICATE KEY UPDATE itemTypeBorrowed = itemTypeBorrowed + values(itemTypeBorrowed); + + DROP TEMPORARY TABLE tmp.workerItemType; + +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 */ ; @@ -5091,18 +5425,18 @@ 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 ;; CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add_launcher`() BEGIN - call bs.vendedores_add(YEAR(CURDATE()),QUARTER(CURDATE())); - - call bs.vendedores_evolution_add; + CALL bs.vendedores_add(YEAR(CURDATE()),QUARTER(CURDATE())); + CALL bs.vendedores_evolution_add; + CALL bs.salesPersonClient_add(YEAR(CURDATE()), QUARTER(CURDATE())); END ;; DELIMITER ; @@ -5972,7 +6306,7 @@ 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 PROCEDURE IF EXISTS `workerSpeed` */; +/*!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 */ ; @@ -5982,7 +6316,46 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed`() +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 */ ; +/*!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 @@ -6093,45 +6466,6 @@ BEGIN 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 */ ; @@ -6265,7 +6599,7 @@ CREATE TABLE `prod_graphic_source` ( `warehouse_id` int(11) NOT NULL, `hora` int(11) NOT NULL, `order` int(11) NOT NULL DEFAULT '0', - `alert_level` int(11) NOT NULL DEFAULT '0', + `graphCategory` int(11) NOT NULL DEFAULT '0', `Agencia` varchar(45) CHARACTER SET utf8 NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -6703,9 +7037,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 */ ; @@ -6723,27 +7057,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 */ ; @@ -6761,88 +7095,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 */ ; @@ -6860,24 +7194,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 */ ; @@ -6896,9 +7230,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 */ ; @@ -6916,13 +7250,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 */ ; @@ -6956,13 +7290,13 @@ DECLARE vLoadingDelay DECIMAL(5) DEFAULT 2; DECLARE rs CURSOR FOR SELECT Departure - , Sum(pb.m3)/(GREATEST(v.m3,IFNULL(minSpeed,0))/1.3) AS Horas - , curDate()+(Departure + vLoadingDelay -(Sum(pb.m3)/(GREATEST(v.m3,IFNULL(minSpeed,0))/1.3))/24) AS InicioPreparacion + , Sum(pb.m3)/(GREATEST(IFNULL(v.m3,0),IFNULL(dp.minSpeed,0))) AS Horas + , curDate()+(Departure + vLoadingDelay -(Sum(pb.m3)/(GREATEST(IFNULL(v.m3,0),IFNULL(minSpeed,0))))/24) AS InicioPreparacion FROM tmp.production_buffer pb - JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id + LEFT JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id LEFT JOIN cache.departure_limit dp ON dp.warehouse_id = pb.warehouse_id AND dp.fecha = CURDATE() WHERE pb.Fecha = CURDATE() - AND alert_level < 2 + AND pb.graphCategory > 1 AND IFNULL(Departure,0) > 0 GROUP BY Departure ORDER BY Departure DESC; @@ -7006,7 +7340,7 @@ DECLARE rs CURSOR FOR AND fecha = CURDATE(); REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed) - VALUES (vWarehouseId, CURDATE(), IFNULL(departureLimit,24), IFNULL(myMinSpeed,0)); + VALUES (vWarehouseId, CURDATE(), departureLimit, IFNULL(myMinSpeed,0)); CLOSE rs; @@ -7249,15 +7583,16 @@ proc: BEGIN DELETE FROM prod_graphic_source; - INSERT INTO prod_graphic_source (warehouse_id, alert_level, m3, hora, `order`, Agencia) + INSERT INTO prod_graphic_source (warehouse_id, graphCategory, m3, hora, `order`, Agencia) SELECT wh_id, - pb.alert_level, + st.graphCategory, m3, pb.Hora, pb.state_order, pb.Agencia FROM tmp.production_buffer pb + JOIN vn.state st ON st.id = pb.state WHERE Fecha = CURDATE() ; @@ -8379,9 +8714,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 = 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 ;; @@ -8518,6 +8853,7 @@ BEGIN ,Productor ,Etiquetas ,Id_Cubo + ,weight ) SELECT cfg.edi_entry @@ -8531,6 +8867,7 @@ BEGIN ,s.company_name ,e.qty ,IFNULL(c.Id_Cubo, e.package) + , a.density * (vn.item_getVolume(a.Id_Article, IFNULL(c.Id_Cubo, e.package))/ 1000000) 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 @@ -8544,6 +8881,175 @@ 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 PROCEDURE IF EXISTS `ekt_load__` */; +/*!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 `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; +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 `exchange_new` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -8587,154 +9093,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 */ ; @@ -10810,30 +11316,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 */ ; @@ -11690,7 +12196,7 @@ BEGIN DECLARE vMerchant INT; DECLARE vUrl VARCHAR(255); DECLARE vKey VARCHAR(50); - DECLARE vTestMode BOOLEAN; + DECLARE vEnvironment VARCHAR(255); DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN @@ -11709,10 +12215,10 @@ BEGIN SELECT merchantFk INTO vMerchant FROM tpvMerchantEnable WHERE companyFk = vCompany; - SELECT testMode INTO vTestMode - FROM tpvConfig; + SELECT environment INTO vEnvironment + FROM util.config; - IF NOT vTestMode + IF vEnvironment = 'production' THEN SELECT c.url, m.secretKey INTO vUrl, vKey FROM tpvMerchant m @@ -12121,7 +12627,6 @@ BEGIN DECLARE vClientId INT; DECLARE vCompanyId INT; DECLARE vAgencyModeId INT; - DECLARE TICKET_FREE INT DEFAULT 2; DECLARE cDates CURSOR FOR @@ -12269,27 +12774,38 @@ BEGIN IF vDone THEN LEAVE lRows; END IF; + SET vSale = NULL; + SELECT s.id INTO vSale + FROM vn.sale s + WHERE ticketFk = vTicket + AND price = vPrice + AND itemFk = vItem + LIMIT 1; + IF vSale THEN + UPDATE vn.sale + SET quantity = quantity + vAmount + WHERE id = vSale; + ELSE + INSERT INTO vn.sale + SET + itemFk = vItem, + ticketFk = vTicket, + concept = vConcept, + quantity = vAmount, + price = vPrice, + priceFixed = 0, + isPriceFixed = TRUE; - INSERT INTO vn.sale - SET - itemFk = vItem, - ticketFk = vTicket, - concept = vConcept, - quantity = vAmount, - price = vPrice, - priceFixed = 0, - isPriceFixed = TRUE; - - SET vSale = LAST_INSERT_ID(); - - INSERT INTO vn.saleComponent - (saleFk, componentFk, `value`) - SELECT vSale, cm.component_id, cm.price - FROM order_component cm - JOIN vn.component c ON c.id = cm.component_id - WHERE cm.order_row_id = vRowId - GROUP BY vSale, cm.component_id; + SET vSale = LAST_INSERT_ID(); + INSERT INTO vn.saleComponent + (saleFk, componentFk, `value`) + SELECT vSale, cm.component_id, cm.price + FROM order_component cm + JOIN vn.component c ON c.id = cm.component_id + WHERE cm.order_row_id = vRowId + GROUP BY vSale, cm.component_id; + END IF; UPDATE order_row SET Id_Movimiento = vSale WHERE id = vRowId; @@ -12419,13 +12935,13 @@ BEGIN SELECT COUNT(*) > 0 INTO vOk FROM order_row WHERE order_id = vOrder AND amount > 0; - IF !vOk THEN + IF NOT vOk THEN CALL util.throw ('ORDER_EMPTY'); END IF; -- Carga las fechas de salida de cada almacén - CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE); -- Trabajador que realiza la acción @@ -15368,7 +15884,11 @@ CREATE TABLE `workcenter` ( `center_id` int(11) DEFAULT NULL, `counter` bigint(20) DEFAULT NULL, `warehouseFk` smallint(6) DEFAULT NULL, - PRIMARY KEY (`workcenter_id`) + `street` varchar(255) DEFAULT NULL, + `geoFk` int(11) DEFAULT NULL, + PRIMARY KEY (`workcenter_id`), + KEY `workcenter_geoFk_idx` (`geoFk`), + CONSTRAINT `workCenter_geoFk` FOREIGN KEY (`geoFk`) REFERENCES `vn`.`zoneGeo` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -16189,8 +16709,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; @@ -16198,20 +16718,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 @@ -16241,7 +16761,7 @@ proc: BEGIN END IF; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16509,29 +17029,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 ( @@ -16564,7 +17084,7 @@ BEGIN FROM tValues WHERE !isIn; - DROP TEMPORARY TABLE tValues; + DROP TEMPORARY TABLE tValues; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16978,7 +17498,7 @@ CREATE TABLE `debug` ( `variable` varchar(255) CHARACTER SET utf8 DEFAULT NULL, `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Log de depuración'; +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Log de depuración'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -17994,6 +18514,33 @@ CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf USE `vn`; +-- +-- Table structure for table `WorkerLog` +-- + +DROP TABLE IF EXISTS `WorkerLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `WorkerLog` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `originFk` int(11) NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `workerLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `workerLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`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 `XDiario` -- @@ -18122,6 +18669,20 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Temporary table structure for view `__coolerPathDetail` +-- + +DROP TABLE IF EXISTS `__coolerPathDetail`; +/*!50001 DROP VIEW IF EXISTS `__coolerPathDetail`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `__coolerPathDetail` AS SELECT + 1 AS `id`, + 1 AS `coolerPathFk`, + 1 AS `hallway`*/; +SET character_set_client = @saved_cs_client; + -- -- Temporary table structure for view `absenceType` -- @@ -18417,7 +18978,6 @@ CREATE TABLE `agencyMode` ( `cod71` tinyint(3) unsigned DEFAULT '0', `web` smallint(1) unsigned zerofill NOT NULL DEFAULT '0', `agencyFk` smallint(5) unsigned NOT NULL, - `agencyServiceFk__` tinyint(4) NOT NULL DEFAULT '1', `inflation` decimal(5,2) NOT NULL DEFAULT '0.00' COMMENT 'Este valor se utiliza para aumentar el valor del componente porte.', `isVolumetric` tinyint(1) NOT NULL DEFAULT '0', `reportMail` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, @@ -18466,6 +19026,20 @@ CREATE TABLE `alertLevel` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `amortizationType` +-- + +DROP TABLE IF EXISTS `amortizationType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `amortizationType` ( + `code` varchar(45) CHARACTER SET utf8 NOT NULL, + `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `annualAverageInvoiced` -- @@ -18852,14 +19426,19 @@ 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 ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterUpdate` AFTER UPDATE ON `buy` FOR EACH ROW trig: BEGIN - IF !(NEW.id <=> OLD.id) + DECLARE vLanded DATE; + DECLARE vBuyerFk INT; + DECLARE vIsBuyerToBeEmailed BOOL; + DECLARE vItemName VARCHAR(50); + + IF !(NEW.id <=> OLD.id) OR !(NEW.entryFk <=> OLD.entryFk) OR !(NEW.itemFk <=> OLD.itemFk) OR !(NEW.quantity <=> OLD.quantity) @@ -18878,6 +19457,36 @@ DELIMITER ;; SET density = NEW.weight / (item_getVolume(NEW.itemFk, NEW.packageFk) / 1000000) WHERE id = NEW.itemFk; END IF; + + SELECT w.isBuyerToBeEmailed, t.landed + INTO vIsBuyerToBeEmailed, vLanded + FROM entry e + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE e.id = NEW.entryFk; + + SELECT it.workerFk, i.longName + INTO vBuyerFk, vItemName + FROM itemCategory k + JOIN itemType it ON it.categoryFk = k.id + JOIN item i ON i.typeFk = it.id + WHERE i.id = OLD.itemFk; + + IF vIsBuyerToBeEmailed AND + vBuyerFk != account.myUserGetId() AND + vLanded = CURDATE() THEN + IF !(NEW.itemFk <=> OLD.itemFk) OR + !(NEW.quantity <=> OLD.quantity) OR + !(NEW.packing <=> OLD.packing) OR + !(NEW.grouping <=> OLD.grouping) OR + !(NEW.packageFk <=> OLD.packageFk) OR + !(NEW.weight <=> OLD.weight) THEN + CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUserGetName(),'@verdnatura.es'), + CONCAT('E ', NEW.entryFk ,' Se ha modificado item ', NEW.itemFk, ' ', vItemName), + 'Este email se ha generado automáticamente'); + END IF; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -20437,8 +21046,6 @@ CREATE TABLE `country` ( `code` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT '1', `politicalCountryFk` mediumint(8) unsigned NOT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)', - `nstGeoFk` int(11) DEFAULT NULL, - `nstName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `geoFk` int(11) DEFAULT NULL, `hasDailyInvoice` tinyint(4) NOT NULL DEFAULT '0', `isUeeMember` tinyint(4) NOT NULL DEFAULT '0', @@ -21632,6 +22239,27 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Temporary table structure for view `entryList` +-- + +DROP TABLE IF EXISTS `entryList`; +/*!50001 DROP VIEW IF EXISTS `entryList`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `entryList` AS SELECT + 1 AS `entryFk`, + 1 AS `isHere`, + 1 AS `landed`, + 1 AS `supplier`, + 1 AS `entryRef`, + 1 AS `agency`, + 1 AS `travelRef`, + 1 AS `appointment`, + 1 AS `supplierFk`, + 1 AS `warehouseInFk`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `entryLog` -- @@ -21755,6 +22383,30 @@ CREATE TABLE `errorLogApp` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Guarda un registro de errores e la app de almacén'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `erte` +-- + +DROP TABLE IF EXISTS `erte`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `erte` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) NOT NULL, + `started` date DEFAULT NULL, + `ended` date DEFAULT NULL, + `reduction` int(3) NOT NULL DEFAULT '1', + `monday` tinyint(1) DEFAULT NULL, + `tuesday` tinyint(1) DEFAULT NULL, + `wednesday` tinyint(1) DEFAULT NULL, + `thursday` tinyint(1) DEFAULT NULL, + `friday` tinyint(1) DEFAULT NULL, + `saturday` tinyint(1) DEFAULT NULL, + `sunday` tinyint(1) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `exchangeInsuranceEntry` -- @@ -21841,22 +22493,25 @@ CREATE TABLE `expedition` ( `id` int(11) NOT NULL AUTO_INCREMENT, `agencyModeFk` int(11) NOT NULL, `ticketFk` int(10) NOT NULL, - `isBox` int(11) DEFAULT '1', + `isBox` int(11) DEFAULT '1' COMMENT 'Este campo realmente en un campo itemFk, haciendo referencia al artículo que nos va a facturar el proveedor de transporte.\nSe debería llamar freightItemFk', `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `isRefund` bit(1) DEFAULT b'0', `isPickUp` bit(1) DEFAULT b'0', - `itemFk` int(11) DEFAULT NULL, + `itemFk` int(11) DEFAULT NULL COMMENT 'Este campo hace referencia al artículo que habria que facturar si las cajas no fueran incluidos.\\nSe debería llamar packageItemFk', `counter` smallint(5) unsigned NOT NULL, `checked` tinyint(4) NOT NULL DEFAULT '0', `workerFk` int(11) DEFAULT NULL, `externalId` bigint(25) DEFAULT NULL, + `packagingFk` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), KEY `index1` (`agencyModeFk`), KEY `index2` (`isBox`), KEY `index3` (`created`), KEY `index4` (`ticketFk`), - CONSTRAINT `Id_Agencia` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE, - CONSTRAINT `ticket_id` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE + KEY `expedition_fk3_idx` (`packagingFk`), + CONSTRAINT `expedition_fk1` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE, + CONSTRAINT `expedition_fk2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `expedition_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -22705,6 +23360,7 @@ CREATE TABLE `item` ( `upToDown` decimal(10,0) unsigned NOT NULL DEFAULT '0' COMMENT 'Se muestra el precio por kilo ', `hasKgPrice` tinyint(1) NOT NULL DEFAULT '0', `sectorFk` int(11) DEFAULT '2', + `isFloramondo` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `Article` (`name`), KEY `Color` (`inkFk`), @@ -23025,6 +23681,7 @@ CREATE TABLE `itemCost` ( `extraCharge` decimal(10,4) NOT NULL DEFAULT '0.0000', `wasted` decimal(10,4) NOT NULL DEFAULT '0.0000', `cm3delivery` int(11) NOT NULL DEFAULT '0', + `grams` int(11) NOT NULL DEFAULT '0' COMMENT 'peso en gramos de una unidad de venta', PRIMARY KEY (`itemFk`,`warehouseFk`), KEY `warehouse_id_rotacion_idx` (`warehouseFk`), CONSTRAINT `id_article_rotaci` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, @@ -23175,7 +23832,7 @@ CREATE TABLE `itemPlacement` ( `id` int(11) NOT NULL AUTO_INCREMENT, `itemFk` int(11) NOT NULL, `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', - `code` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `code` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `modificationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `reserve` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `pickable` int(11) unsigned NOT NULL DEFAULT '0', @@ -23193,19 +23850,37 @@ CREATE TABLE `itemPlacement` ( /*!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 ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemPlacement_AFTER_DELETE` AFTER DELETE ON `itemPlacement` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemPlacement_BEFORE_INSERT` BEFORE INSERT ON `itemPlacement` FOR EACH ROW BEGIN - INSERT INTO vn.mail SET - `sender` = 'jgallego@verdnatura.es', - `replyTo` = 'jgallego@verdnatura.es', - `subject` = 'Nicho modificado', - `body` = CONCAT(account.myUserGetName(), ' ha eliminado la linea de ', OLD.`itemFk`); + IF LENGTH(NEW.code) < 3 THEN + CALL util.throw('code too short'); + 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 `vn`.`itemPlacement_BEFORE_UPDATE` BEFORE UPDATE ON `itemPlacement` FOR EACH ROW +BEGIN + IF LENGTH(NEW.code) < 3 THEN + CALL util.throw('code too short'); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -23307,9 +23982,9 @@ CREATE TABLE `itemShelving` ( `shelvingFk` varchar(10) CHARACTER SET utf8 NOT NULL, `shelve` varchar(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'A', `deep` int(11) unsigned NOT NULL DEFAULT '1', - `quantity` decimal(10,0) NOT NULL DEFAULT '0', - `visible` decimal(10,0) NOT NULL DEFAULT '0', - `available` decimal(10,0) NOT NULL DEFAULT '0', + `quantity` int(11) NOT NULL DEFAULT '0', + `visible` int(11) NOT NULL DEFAULT '0', + `available` int(11) NOT NULL DEFAULT '0', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `priority` int(11) unsigned DEFAULT NULL COMMENT 'El 0 es la mínima prioridad', `grouping` smallint(5) unsigned DEFAULT NULL, @@ -23816,6 +24491,8 @@ CREATE TABLE `itemType` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL, `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `gramsMin` int(11) DEFAULT NULL, + `gramsMax` int(11) DEFAULT NULL, `order` int(11) DEFAULT '0', `temperature` tinyint(1) unsigned NOT NULL DEFAULT '0', `categoryFk` int(10) unsigned NOT NULL, @@ -24228,6 +24905,20 @@ CREATE TABLE `messageInbox` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `mistakeType` +-- + +DROP TABLE IF EXISTS `mistakeType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `mistakeType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci 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 `mobileAppVersionControl` -- @@ -24257,7 +24948,7 @@ CREATE TABLE `mrw` ( `shipped` date DEFAULT NULL, `price` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -24467,9 +25158,12 @@ CREATE TABLE `packaging` ( `cubicPackage` decimal(10,2) DEFAULT NULL, `returnCost` decimal(10,2) NOT NULL DEFAULT '0.00', `cmrName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `freightItemFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), - KEY `Article` (`itemFk`), - CONSTRAINT `Article` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE + KEY `packaging_fk1` (`itemFk`), + KEY `packaging_fk2_idx` (`freightItemFk`), + CONSTRAINT `packaging_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE, + CONSTRAINT `packaging_fk2` FOREIGN KEY (`freightItemFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -24598,6 +25292,20 @@ CREATE TABLE `pedidosInternos` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `periodicityType` +-- + +DROP TABLE IF EXISTS `periodicityType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `periodicityType` ( + `code` varchar(45) CHARACTER SET utf8 NOT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `person` -- @@ -24820,6 +25528,63 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Table structure for table `ppe` +-- + +DROP TABLE IF EXISTS `ppe`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ppe` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `amortization` decimal(10,2) NOT NULL DEFAULT '0.00', + `firstAmortizated` date DEFAULT NULL, + `lastAmortizated` date DEFAULT NULL, + `finished` date DEFAULT NULL, + `value` decimal(10,2) NOT NULL DEFAULT '0.00', + `planFk` int(11) NOT NULL, + `groupFk` int(11) NOT NULL, + `account` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `endowment` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `nature` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, + `location` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, + `discharged` date DEFAULT NULL, + `cause` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `photo` blob, + `isInvestmentAsset` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Property, plant & equipment\nInmvolizado, en español'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ppeGroup` +-- + +DROP TABLE IF EXISTS `ppeGroup`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ppeGroup` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tipo de inmovilizado'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ppePlan` +-- + +DROP TABLE IF EXISTS `ppePlan`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ppePlan` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `rate` decimal(3,2) NOT NULL DEFAULT '1.00', + `days` int(11) NOT NULL DEFAULT '365', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Plan de amortizacion para la tabla ppe'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `priceBuilderTag__` -- @@ -25117,8 +25882,6 @@ CREATE TABLE `province` ( `countryFk` mediumint(8) unsigned NOT NULL, `warehouseFk` smallint(6) unsigned DEFAULT NULL COMMENT 'warehouse responsable de las rutas', `zoneFk` tinyint(4) DEFAULT NULL, - `nstGeoFk` int(11) DEFAULT NULL, - `nstName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `geoFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `Paises_Id` (`countryFk`), @@ -25743,6 +26506,7 @@ CREATE TABLE `sale` ( `isPicked` tinyint(1) NOT NULL DEFAULT '0', `isPriceFixed` tinyint(1) NOT NULL DEFAULT '0', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `isAdded` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `Id_Ticket` (`ticketFk`), KEY `itemFk_ticketFk` (`itemFk`,`ticketFk`), @@ -25867,6 +26631,23 @@ CREATE TABLE `saleChecked` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `saleCloned` +-- + +DROP TABLE IF EXISTS `saleCloned`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `saleCloned` ( + `saleClonedFk` int(11) NOT NULL, + `saleOriginalFk` int(11) NOT NULL, + PRIMARY KEY (`saleClonedFk`), + KEY `saleOriginalFk_idx` (`saleOriginalFk`), + CONSTRAINT `saleClonedFk_fk2` FOREIGN KEY (`saleClonedFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `saleOriginalFk_fk1` FOREIGN KEY (`saleOriginalFk`) REFERENCES `sale` (`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 `saleComponent` -- @@ -25926,6 +26707,28 @@ CREATE TABLE `saleItemShelving` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `saleMistake` +-- + +DROP TABLE IF EXISTS `saleMistake`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `saleMistake` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `saleFk` int(11) NOT NULL, + `userFk` int(11) NOT NULL, + `typeFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `saleMistake_fk1_idx` (`saleFk`), + KEY `saleMistake_fk2_idx` (`userFk`), + KEY `saleMistake_fk3_idx` (`typeFk`), + CONSTRAINT `saleMistake_fk1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `saleMistake_fk2` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `saleMistake_fk3` FOREIGN KEY (`typeFk`) REFERENCES `mistakeType` (`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 `saleState` -- @@ -26126,6 +26929,7 @@ CREATE TABLE `sector` ( `isPreviousPrepared` tinyint(1) NOT NULL DEFAULT '0', `isPackagingArea` tinyint(1) NOT NULL DEFAULT '0', `labelReport` int(11) DEFAULT NULL, + `sonFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`,`warehouseFk`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), @@ -26235,7 +27039,7 @@ CREATE TABLE `sharingClient` ( KEY `Client` (`clientFk`), CONSTRAINT `Clients_key` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, CONSTRAINT `Trabajadores_key` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +) ENGINE=InnoDB DEFAULT 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 */ ; @@ -26503,6 +27307,7 @@ CREATE TABLE `state` ( `semaphore` int(11) NOT NULL DEFAULT '0', `isPrintable` tinyint(4) NOT NULL DEFAULT '0', `isOK` tinyint(4) NOT NULL DEFAULT '0', + `graphCategory` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -26557,7 +27362,6 @@ CREATE TABLE `supplier` ( `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `account` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `street` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, - `postCode__` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'deprecada', `city` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `provinceFk` smallint(5) unsigned DEFAULT NULL, `countryFk` mediumint(8) unsigned DEFAULT NULL, @@ -26585,7 +27389,7 @@ CREATE TABLE `supplier` ( KEY `pay_met_id` (`payMethodFk`), KEY `province_id` (`provinceFk`), KEY `pay_dem_id` (`payDemFk`), - KEY `codpos` (`postCode`,`postCode__`), + KEY `codpos` (`postCode`), CONSTRAINT `Id_Pais` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE, CONSTRAINT `pay_dem_id` FOREIGN KEY (`payDemFk`) REFERENCES `payDem` (`id`) ON UPDATE CASCADE, CONSTRAINT `pay_met_id` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON UPDATE CASCADE, @@ -26699,7 +27503,8 @@ CREATE TABLE `tabletDepartment` ( `departmentFk` int(11) NOT NULL, PRIMARY KEY (`tabletFk`,`departmentFk`), KEY `departmentFk_idx` (`departmentFk`), - CONSTRAINT `departmentFk` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE + CONSTRAINT `departmentFk` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `tablet_uuid` FOREIGN KEY (`tabletFk`) REFERENCES `tablet` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -26833,7 +27638,10 @@ CREATE TABLE `taxCode` ( `link` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT 'las que tienen el mismo valor se contabilizan emparejadas', `isActive` tinyint(2) NOT NULL DEFAULT '1', `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `transactionCode` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, + `transactionCode` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Código de Transacción de SAGE', + `operationCode` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Código de operaciones de SAGE', + `taxCode` int(4) DEFAULT NULL COMMENT 'Código de IVA SAGE', + `isIntracommunity` tinyint(2) DEFAULT '0', PRIMARY KEY (`id`), KEY `iva_tipo_id` (`taxTypeFk`), KEY `codigo` (`code`), @@ -26937,7 +27745,7 @@ CREATE TABLE `ticket` ( CONSTRAINT `ticket_ibfk_5` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticket_ibfk_6` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticket_ibfk_8` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`), - CONSTRAINT `ticket_ibfk_9` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticket_ibfk_9` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `tickets_fk10` FOREIGN KEY (`refFk`) REFERENCES `invoiceOut` (`ref`) ON UPDATE CASCADE, CONSTRAINT `tickets_fk11` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `tickets_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE @@ -27089,6 +27897,7 @@ CREATE TABLE `ticketCollection` ( `collectionFk` int(11) NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `level` int(11) DEFAULT NULL, + `wagon` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `ticketCollection_fk2_idx` (`ticketFk`), KEY `ticketCollection_fk1_idx` (`collectionFk`), @@ -27851,6 +28660,32 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Temporary table structure for view `tr2` +-- + +DROP TABLE IF EXISTS `tr2`; +/*!50001 DROP VIEW IF EXISTS `tr2`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `tr2` AS SELECT + 1 AS `id`, + 1 AS `shipped`, + 1 AS `shipmentHour`, + 1 AS `landed`, + 1 AS `landingHour`, + 1 AS `warehouseInFk`, + 1 AS `warehouseOutFk`, + 1 AS `agencyFk`, + 1 AS `ref`, + 1 AS `isDelivered`, + 1 AS `isReceived`, + 1 AS `m3`, + 1 AS `kg`, + 1 AS `cargoSupplierFk`, + 1 AS `totalEntries`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `trainingCenter` -- @@ -27930,6 +28765,7 @@ CREATE TABLE `travel` ( `kg` decimal(10,0) unsigned DEFAULT NULL, `cargoSupplierFk` int(11) DEFAULT NULL, `totalEntries` tinyint(4) unsigned DEFAULT '0', + `appointment` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `shipment_2` (`shipped`,`landed`,`warehouseInFk`,`warehouseOutFk`,`agencyFk`,`ref`), KEY `agency_id` (`agencyFk`), @@ -28344,7 +29180,11 @@ CREATE TABLE `workCenter` ( `payrollCenterFk` int(11) DEFAULT NULL, `counter` bigint(20) DEFAULT NULL, `warehouseFk` smallint(6) DEFAULT NULL, - PRIMARY KEY (`id`) + `street` varchar(255) DEFAULT NULL, + `geoFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `workCenter_geoFk_idx` (`geoFk`), + CONSTRAINT `workCenter_geoFk` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -28375,35 +29215,35 @@ CREATE TABLE `worker` ( `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL, `firstName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `lastName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `password` varchar(50) CHARACTER SET utf8 DEFAULT NULL, - `email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `extension` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `password__` varchar(50) CHARACTER SET utf8 DEFAULT NULL, + `email__` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `extension__` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `sub` int(11) unsigned DEFAULT NULL, - `user` varchar(20) CHARACTER SET utf8 DEFAULT NULL, - `typeBussines` varchar(30) CHARACTER SET utf8 DEFAULT 'no dejar vacio' COMMENT 'campo obsoleto, actualmente se rellena en laboral', - `laborCategory` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `started` datetime DEFAULT NULL, - `ended` datetime DEFAULT NULL, - `notes` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL, + `user__` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `typeBussines__` varchar(30) CHARACTER SET utf8 DEFAULT 'no dejar vacio' COMMENT 'campo obsoleto, actualmente se rellena en laboral', + `laborCategory__` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `started__` datetime DEFAULT NULL, + `ended__` datetime DEFAULT NULL, + `notes__` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL, `photo` blob, `fi` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL, - `address` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `birthed` date NOT NULL, - `maritalStatus` enum('soltero/a','casado/a') COLLATE utf8_unicode_ci NOT NULL, + `address__` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `birthed__` date NOT NULL, + `maritalStatus__` enum('soltero/a','casado/a') COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(9) COLLATE utf8_unicode_ci NOT NULL, - `clientFk` int(11) DEFAULT NULL, + `clientFk__` int(11) DEFAULT NULL, `userFk` int(10) unsigned DEFAULT NULL, `bossFk` int(11) NOT NULL DEFAULT '2', `fiDueDate` datetime DEFAULT NULL, `hasMachineryAutorized` tinyint(2) DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `CodigoTrabajador_UNIQUE` (`code`), - UNIQUE KEY `user` (`user`), + UNIQUE KEY `user` (`user__`), UNIQUE KEY `user_id_UNIQUE` (`userFk`), - UNIQUE KEY `Id_Cliente_Interno` (`clientFk`), + UNIQUE KEY `Id_Cliente_Interno` (`clientFk__`), KEY `sub` (`sub`), KEY `boss_idx` (`bossFk`), - CONSTRAINT `Clientes` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, + CONSTRAINT `Clientes` FOREIGN KEY (`clientFk__`) REFERENCES `client` (`id`) ON UPDATE CASCADE, CONSTRAINT `worker_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -29495,96 +30335,114 @@ 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, sysadmin@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, sysadmin@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 */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `sale_checkWithoutComponents` */;; +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 `sale_checkWithoutComponents` ON SCHEDULE EVERY 10 MINUTE STARTS '2020-05-04 11:56:23' ON COMPLETION PRESERVE ENABLE DO call sale_checkNoComponents(DATE_ADD(NOW(), INTERVAL -10 MINUTE),DATE_ADD(NOW(), INTERVAL -1 MINUTE)) */ ;; +/*!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 */ ;; /*!50106 DROP EVENT IF EXISTS `ticketClosure` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -32819,12 +33677,65 @@ CREATE DEFINER=`root`@`%` FUNCTION `validationCode`(vString VARCHAR(255)) RETURN DETERMINISTIC BEGIN - DECLARE vTail VARCHAR(3); - DECLARE vCode INT; - - SET vTail = LEFT(LPAD(vString,3,'0'),3); + DECLARE vSeed DOUBLE DEFAULT 0; + DECLARE vCode INT; + DECLARE vLength INT; + DECLARE vChar INT; - SET vCode = (ASCII(MID(vTail,1,1)) * ASCII(MID(vTail,2,1)) * ASCII(MID(vTail,3,1))) mod 1000; + SET vLength = length(vString); + + WHILE vLength > 0 DO + + SET vChar = MID(vString,vLength,1); + + SET vSeed = vSeed + ASCII(vChar); + + SET vLength = vLength - 1; + + END WHILE; + + SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; + + RETURN vCode; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!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_beta` */; +/*!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_beta`(vString VARCHAR(255)) RETURNS int(11) + DETERMINISTIC +BEGIN + + DECLARE vSeed DOUBLE DEFAULT 0; + DECLARE vCode INT; + DECLARE vLength INT; + DECLARE vChar INT; + + SET vLength = length(vString); + + WHILE vLength > 0 DO + + SET vChar = MID(vString,vLength,1); + + SET vSeed = vSeed + ASCII(vChar); + + SET vLength = vLength - 1; + + END WHILE; + + SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; @@ -33694,14 +34605,88 @@ 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 ;; CREATE DEFINER=`root`@`%` PROCEDURE `buy_afterUpsert`(vSelf INT) BEGIN +/** + * Triggered actions when a buy is updated or inserted. + * + * @param vSelf The buy reference + */ + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vStickers INT; + DECLARE vPacking INT; + DECLARE vWarehouse INT; + DECLARE vWarehouseOut INT; + DECLARE vIsMerchandise BOOL; + DECLARE vIsFeedStock BOOL; + + + SELECT entryFk, itemFk, stickers, packing + INTO vEntryFk, vItemFk, vStickers, vPacking + FROM buy + WHERE id = vSelf; + + SELECT t.warehouseInFk, t.warehouseOutFk + INTO vWarehouse, vWarehouseOut + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = vEntryFk; + + SELECT k.merchandise + INTO vIsMerchandise + FROM itemCategory k + JOIN itemType it ON it.categoryFk = k.id + JOIN item i ON i.typeFk = it.id + WHERE i.id = vItemFk; + + IF vIsMerchandise THEN + REPLACE itemCost SET + itemFk = vItemFk, + warehouseFk = vWarehouse, + cm3 = buy_getUnitVolume(vSelf); + END IF; + + SELECT isFeedStock INTO vIsFeedStock + FROM warehouse WHERE id = vWarehouseOut AND id <> 13; + + IF vIsFeedStock THEN + INSERT IGNORE INTO producer(`name`) + SELECT es.company_name + FROM buy b + JOIN edi.ekt be ON be.id = b.ektFk + JOIN edi.supplier es ON es.supplier_id = be.pro + WHERE b.id = vSelf; + + IF buy_hasNotifyPassport(vSelf, vItemFk) THEN + CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking); + END IF; + 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 `buy_afterUpsert__` */; +/*!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 `buy_afterUpsert__`(vSelf INT) +BEGIN /** * Triggered actions when a buy is updated or inserted. * @@ -33779,74 +34764,6 @@ 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 PROCEDURE IF EXISTS `buy_afterUpsert__` */; -/*!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 `buy_afterUpsert__`(vSelf INT) -BEGIN -/** - * Triggered actions when a buy is updated or inserted. - * - * @param vSelf The buy reference - */ - DECLARE vEntryFk INT; - DECLARE vItemFk INT; - DECLARE vStickers INT; - DECLARE vPacking INT; - DECLARE vWarehouse INT; - DECLARE vWarehouseOut INT; - DECLARE vIsMerchandise BOOL; - DECLARE vIsFeedStock BOOL; - - SELECT entryFk, itemFk, stickers, packing - INTO vEntryFk, vItemFk, vStickers, vPacking - FROM buy - WHERE id = vSelf; - - SELECT t.warehouseInFk, t.warehouseOutFk - INTO vWarehouse, vWarehouseOut - FROM entry e - JOIN travel t ON t.id = e.travelFk - WHERE e.id = vEntryFk; - - SELECT k.merchandise INTO vIsMerchandise - FROM itemCategory k - JOIN itemType it ON it.categoryFk = k.id - JOIN item i ON i.typeFk = it.id - WHERE i.id = vItemFk; - - IF vIsMerchandise THEN - REPLACE bi.rotacion SET - Id_Article = vItemFk, - warehouse_id = vWarehouse, - cm3 = buy_getUnitVolume(vSelf); - END IF; - - SELECT isFeedStock INTO vIsFeedStock - FROM warehouse WHERE id = vWarehouseOut AND id <> 13; - - IF vIsFeedStock AND buy_hasNotifyPassport(vSelf, vItemFk) THEN - CALL buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking); - INSERT IGNORE INTO producer(`name`) - SELECT es.company_name - FROM buy b - JOIN edi.ekt be ON be.id = b.ektFk - JOIN edi.supplier es ON es.supplier_id = be.pro - WHERE b.id = vSelf; - 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 `buy_checkGrouping` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -33911,6 +34828,66 @@ BEGIN LEFT JOIN edi.ekt e ON b.ektFk = e.id LEFT JOIN edi.supplier es ON es.supplier_id = e.pro WHERE i.id = vItemFk; +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 `buy_updateGrouping` */; +/*!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 `buy_updateGrouping`(vWarehouseFk INT,vItemFk INT,vGrouping INT) +BEGIN + +DECLARE lastId INT; + +CALL vn2008.item_last_buy_(vWarehouseFk,vItemFk); + +SELECT b.buy_id INTO lastId +FROM vn2008.t_item_last_buy b +INNER JOIN vn2008.Compres c ON c.Id_Compra = b.buy_id +where b.warehouse_id = vWarehouseFk AND b.item_id =vItemFk; + +UPDATE vn.buy SET grouping = vGrouping WHERE id = lastId; + +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 `buy_updatePacking` */; +/*!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 `buy_updatePacking`(vWarehouseFk INT,vItemFk INT,vPacking INT) +BEGIN + +DECLARE lastId INT; + +CALL vn2008.item_last_buy_(vWarehouseFk,vItemFk); + +SELECT b.buy_id INTO lastId +FROM vn2008.t_item_last_buy b +INNER JOIN vn2008.Compres c ON c.Id_Compra = b.buy_id +where b.warehouse_id = vWarehouseFk AND b.item_id =vItemFk; + +UPDATE vn.buy SET packing = vPacking WHERE id = lastId; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34246,6 +35223,161 @@ CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`( vAddressFk INT, vAgencyModeFk INT) proc: BEGIN +/** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + * @return tmp.zoneGetShipped + */ + + DECLARE vAvailableCalc INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + -- Establece los almacenes y las fechas que van a entrar al disponible + + CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', + `zoneFk` int(11) NOT NULL, + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + CALL catalog_componentPrepare(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem( + itemFk INT(11) NOT NULL, + available INT(11), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), + image VARCHAR(50), + origin VARCHAR(3), + price DECIMAL(10,2), + priceKg DECIMAL(10,2), + KEY `itemFk` (`itemFk`) + ) ENGINE = MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL buyUltimate (vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk) + SELECT vWarehouseFk, + i.item_id, + IFNULL(i.available, 0), + bu.buyFk, + vZoneFk + FROM `cache`.available i + JOIN tmp.item br ON br.itemFk = i.item_id + LEFT JOIN item it ON it.id = i.item_id + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id + WHERE i.calc_id = vAvailableCalc + AND i.available > 0; + + DROP TEMPORARY TABLE tmp.buyUltimate; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + INSERT INTO tmp.ticketCalculateItem ( + itemFk, + available, + producer, + item, + size, + stems, + category, + inkFk, + image, + origin, + price, + priceKg) + SELECT + tl.itemFk, + SUM(tl.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot tl + JOIN item i ON tl.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT MIN(price) price, itemFk, priceKg + FROM tmp.ticketComponentPrice + WHERE warehouseFk = vWarehouseFk + GROUP BY itemFk + ) bl ON bl.itemFk = tl.itemFk + WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk + GROUP BY tl.itemFk; + -- on duplicatekey update + + END LOOP; + + CLOSE cTravelTree; + +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 `catalog_calculate__` */; +/*!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 `catalog_calculate__`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN /** * Calcula los articulos disponibles y sus precios * @@ -34357,7 +35489,7 @@ 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 PROCEDURE IF EXISTS `catalog_calculate__` */; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentCalculate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -34367,115 +35499,258 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate__`( - vLanded DATE, +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( + vZoneFk INT, vAddressFk INT, - vAgencyModeFk INT) + vShipped DATE, + vWarehouseFk INT) proc: BEGIN /** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - * @return tmp.zoneGetShipped + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAddressFk Consignatario + * @param vShipped dia de salida del pedido + * @param tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) + * + * @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 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; - **/ - - DECLARE vAvailableCalc INT; - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT clientFk INTO vClient - FROM address WHERE id = vAddressFk; - - CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) - SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), - bu.buyFk - FROM `cache`.available i - JOIN tmp.item br ON br.itemFk = i.item_id - LEFT JOIN item it ON it.id = i.item_id - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id - WHERE i.calc_id = vAvailableCalc - AND it.id != 100 - AND i.available > 0; + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; - DROP TEMPORARY TABLE tmp.buyUltimate; - END LOOP; + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; - CLOSE cTravelTree; + SET @rate2 := 0; + SET @rate3 := 0; - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem - ENGINE = MEMORY + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY SELECT - b.itemFk, - SUM(b.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot b - JOIN item i ON b.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT MIN(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - GROUP BY itemFk - ) bl ON bl.itemFk = b.itemFk - GROUP BY b.itemFk; + 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 + AND tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk; + + 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 + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.priceIncreasing, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN claimRatio cr ON cr.clientFk = vClientFk + WHERE cr.priceIncreasing > 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, + c.id, + GREATEST(IFNULL(ROUND(tcb.base * c.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN component c + 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 c.id = vDiscountLastItemComponent AND c.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; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.zone (INDEX (id)) + ENGINE = MEMORY + SELECT vZoneFk id; + + CALL zone_getOptionsForShipment(vShipped, TRUE); + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * ic.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((zo.price - zo.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + AND ic.itemFk = tcc.itemFk + HAVING cost <> 0; + + DROP TEMPORARY TABLE tmp.zoneOption; + + 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 component c ON c.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE c.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, c.classRate + FROM tmp.ticketComponent tc + JOIN component c ON c.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, c.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; + + INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + 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 ; @@ -34483,17 +35758,17 @@ 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 PROCEDURE IF EXISTS `catalog_componentCalculate` */; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentCalculate__` */; /*!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 `catalog_componentCalculate`( +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate__`( vZoneFk INT, vAddressFk INT, vShipped DATE) @@ -34759,7 +36034,7 @@ 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 PROCEDURE IF EXISTS `catalog_componentCalculate__` */; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentPrepare` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -34769,80 +36044,9 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `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; - +CREATE DEFINER=`z-sysadmin`@`%` PROCEDURE `catalog_componentPrepare`() +BEGIN + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; CREATE TEMPORARY TABLE tmp.ticketComponent ( `warehouseFk` INT UNSIGNED NOT NULL, @@ -34850,174 +36054,42 @@ proc: BEGIN `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.priceIncreasing, 0.25), 3) - FROM tmp.ticketComponentBase tcb - JOIN claimRatio cr ON cr.clientFk = vClientFk - WHERE cr.priceIncreasing > 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, - c.id, - GREATEST(IFNULL(ROUND(tcb.base * c.tax, 4), 0), tcc.minPrice - tcc.rate3) - FROM tmp.ticketComponentBase tcb - JOIN component c - 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 c.id = vDiscountLastItemComponent AND c.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 - * ic.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 itemCost ic ON ic.warehouseFk = tcc.warehouseFk - AND ic.itemFk = 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; + UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC) + )ENGINE=MEMORY DEFAULT CHARSET=utf8; - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - vSpecialPriceComponent, - sp.value - SUM(tcc.cost) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN component c ON c.id = tcc.componentFk - JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk - WHERE c.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, c.classRate - FROM tmp.ticketComponent tc - JOIN component c ON c.id = tc.componentFk - GROUP BY tc.itemFk, tc.warehouseFk, c.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; + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `rate` INT NOT NULL, + `grouping` INT UNSIGNED NOT NULL, + `price` DECIMAL(10,4) NOT NULL, + `priceKg` DECIMAL(10,4), + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC) + )ENGINE=MEMORY DEFAULT CHARSET=utf8; +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 `catalog_componentPurge` */; +/*!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 `catalog_componentPurge`() +BEGIN + DROP TEMPORARY TABLE + tmp.ticketComponentPrice, + tmp.ticketComponent, + tmp.ticketLot; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35028,9 +36100,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 ;; @@ -35063,6 +36135,93 @@ BEGIN DELETE FROM saleTracking WHERE created < vDateShort; DELETE tobs FROM ticketObservation tobs JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < vDateShort; + DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo; + DELETE FROM sharingCart where ended < vDateShort; + DELETE FROM sharingClient where ended < vDateShort; + DELETE tw.* FROM ticketWeekly tw + LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL; + DELETE FROM claim WHERE ticketCreated < v18Month; + DELETE FROM message WHERE sendDate < vDateShort; + DELETE FROM travelLog WHERE creationDate < v3Month; + DELETE sc FROM saleChecked sc + JOIN sale s ON sc.saleFk = s.id WHERE s.created < vDateShort; + DELETE bm + FROM buyMark bm + JOIN buy b ON b.id = bm.id + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed <= vDateShort; + DELETE FROM stowaway WHERE created < v3Month; + + -- Equipos duplicados + DELETE w.* + FROM workerTeam w + JOIN (SELECT id, team, workerFk, COUNT(*) - 1 as duplicated + FROM workerTeam + GROUP BY team,workerFk + HAVING duplicated + ) d ON d.team = w.team AND d.workerFk = w.workerFk AND d.id != w.id; + + DELETE sc + FROM saleComponent sc + JOIN sale s ON s.id= sc.saleFk + JOIN ticket t ON t.id= s.ticketFk + WHERE t.shipped < v18Month; + + DELETE c + FROM vn.claim c + JOIN vn.claimState cs ON cs.id = c.claimStateFk + WHERE cs.description = "Anulado" AND + c.created < vDateShort; + + CALL shelving_clean; + CALL ticketPackagingRecovery; +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 `clean__` */; +/*!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 `clean__`() +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vOneYearAgo DATE; + DECLARE vFourYearsAgo DATE; + DECLARE v18Month DATE; + DECLARE v26Month DATE; + DECLARE v3Month DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET vFourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + SET v18Month = TIMESTAMPADD(MONTH, -18,CURDATE()); + SET v26Month = TIMESTAMPADD(MONTH, -26,CURDATE()); + SET v3Month = TIMESTAMPADD(MONTH, -3, CURDATE()); + + DELETE FROM workerTimeControlLog WHERE created < vDateShort; + DELETE FROM `message` WHERE sendDate < vDateShort; + DELETE FROM messageInbox WHERE sendDate < vDateShort; + DELETE FROM messageInbox WHERE sendDate < vDateShort; + DELETE FROM workerTimeControl WHERE timed < vFourYearsAgo; + DELETE FROM itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + DELETE FROM entryLog WHERE creationDate < vDateShort; + DELETE FROM expedition WHERE created < v26Month; + DELETE FROM sms WHERE created < v18Month; + DELETE FROM saleTracking WHERE created < vDateShort; + DELETE tobs FROM ticketObservation tobs + JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < vDateShort; + DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo; DELETE FROM sharingCart where ended < vDateShort; DELETE FROM sharingClient where ended < vDateShort; DELETE tw.* FROM ticketWeekly tw @@ -35106,44 +36265,6 @@ 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 PROCEDURE IF EXISTS `clean__` */; -/*!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 `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 */ ; -/*!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 `clearShelvingList` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -35809,9 +36930,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 = 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 ;; @@ -35819,18 +36940,21 @@ CREATE DEFINER=`root`@`%` PROCEDURE `clientPackagingOverstockReturn`(vClientFk I BEGIN DECLARE vNewTicket INT DEFAULT 0; + + -- SET vGraceDays = GREATEST(vGraceDays, 90); CALL vn.clientPackagingOverstock(vClientFk,vGraceDays); - CALL vn.ticketCreate( + CALL vn.ticketCreateWithUser( vClientFk - ,curdate() + ,CURDATE() ,1 -- Silla FV ,442 -- Verdnatura ,NULL -- address - ,2 -- Rec_Silla + ,NULL -- agencia ,NULL -- route - ,curdate() + ,CURDATE() + ,account.myUserGetId() ,vNewTicket); INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price) @@ -35846,7 +36970,7 @@ BEGIN JOIN vn.packaging p ON p.itemFk = cpo.itemFk WHERE cpo.abonables > 0; - SELECT vNewTicket; + SELECT vNewTicket; END ;; DELIMITER ; @@ -35922,47 +37046,52 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker`() BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vClientFk INT; + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; - DECLARE rs CURSOR FOR - SELECT c.clientFk - FROM tmp.clientGetDebt c - LEFT JOIN clientRisk r ON r.clientFk = c.clientFk - WHERE IFNULL(r.amount,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; - - OPEN rs; - FETCH rs INTO vClientFk; - - WHILE NOT done DO + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN clientRisk r ON r.clientFk = c.clientFk + GROUP BY r.clientFk + HAVING SUM(IFNULL(r.amount,0)) = 0; - CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); - UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; + 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; + + OPEN rs; + + FETCH rs INTO vClientFk; + + WHILE NOT done DO + + 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')); + 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; + REPLACE bs.clientNewBorn(clientFk, shipped) + VALUES(vClientFk, CURDATE()); + + FETCH rs INTO vClientFk; + + END WHILE; - CLOSE rs; + CLOSE rs; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35980,54 +37109,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 */ ; @@ -36215,107 +37344,162 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `collectionPlacement_get`(vCollectionFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `collectionPlacement_get`(vParamFk INT(11)) BEGIN DECLARE vCalcFk INT; DECLARE vWarehouseFk INT; DECLARE vWarehouseAliasFk INT; + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + ENGINE = MEMORY + SELECT 0000000 as ticketFk, + 0000000 as saleFk, + 0000000 as itemFk, + 0 as quantity; + + INSERT INTO tmp.sale(ticketFk, saleFk, itemFk) + SELECT s.ticketFk, s.id, s.itemFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vParamFk; + + INSERT INTO tmp.sale(ticketFk, saleFk, itemFk) + SELECT s.ticketFk, s.id, s.itemFk + FROM vn.sale s + WHERE s.ticketFk = vParamFk; + + DELETE FROM tmp.sale + WHERE saleFk = 0; + SELECT t.warehouseFk, w.aliasFk INTO vWarehouseFk, vWarehouseAliasFk FROM vn.ticket t - JOIN vn.ticketCollection tc ON tc.ticketFk = t.id + JOIN tmp.sale ts ON ts.ticketFk = t.id JOIN vn.warehouse w ON w.id = t.warehouseFk - WHERE tc.collectionFk = vCollectionFk LIMIT 1; CALL cache.visible_refresh(vCalcFk,FALSE,vWarehouseFk); - DROP TEMPORARY TABLE IF EXISTS tmp.parked; - CREATE TEMPORARY TABLE tmp.parked - ENGINE MEMORY - SELECT s.itemFk, 0 as quantity - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk; - - UPDATE tmp.parked pk + UPDATE tmp.sale ts JOIN ( SELECT itemFk, sum(visible) as visible FROM vn.itemShelvingStock iss JOIN vn.warehouse w ON w.id = iss.warehouseFk WHERE w.aliasFk = vWarehouseAliasFk - GROUP BY iss.itemFk ) iss ON iss.itemFk = pk.itemFk - SET pk.quantity = iss.visible; + GROUP BY iss.itemFk ) iss ON iss.itemFk = ts.itemFk + SET ts.quantity = iss.visible; + DROP TEMPORARY TABLE IF EXISTS tmp.sale2; + CREATE TEMPORARY TABLE tmp.sale2 + ENGINE = MEMORY + SELECT * FROM tmp.sale; + DROP TEMPORARY TABLE IF EXISTS tmp.`grouping`; CREATE TEMPORARY TABLE tmp.`grouping` ENGINE MEMORY - SELECT itemFk, `grouping` - FROM ( - SELECT itemFk, - CASE groupingMode - WHEN 0 THEN 1 - WHEN 2 THEN packing - ELSE `grouping` - END AS `grouping` - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - WHERE tr.warehouseInFk = vWarehouseFk - AND landed BETWEEN (SELECT FechaInventario FROM vn2008.tblContadores LIMIT 1) AND CURDATE() - AND b.isIgnored = FALSE - ORDER BY tr.landed DESC - ) sub - GROUP BY sub.itemFk ; - + SELECT b.itemFk, + CASE b.groupingMode + WHEN 0 THEN 1 + WHEN 2 THEN b.packing + ELSE b.`grouping` + END AS `grouping` + FROM buy b + JOIN cache.last_buy lb ON lb.buy_id = b.id + WHERE lb.warehouse_id = vWarehouseFk + ; + DROP TEMPORARY TABLE IF EXISTS tmp.grouping2; CREATE TEMPORARY TABLE tmp.grouping2 ENGINE MEMORY SELECT * FROM tmp.`grouping`; - SELECT s.id as saleFk, s.itemFk, - p.code COLLATE utf8_general_ci as placement , + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList; + CREATE TEMPORARY TABLE tmp.salePlacementList + ENGINE MEMORY + + SELECT ts.saleFk, + ts.itemFk, + CONCAT( + IF( iss.id, + CONCAT('< ', IFNULL(wk.`code`, '---'),' >'), + ''), + p.`code`) COLLATE utf8_general_ci as placement , sh.code COLLATE utf8_general_ci as shelving, ish.created, ish.visible, - IFNULL(cpd.id,0) as `order`, - IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`) as `grouping` - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk + IF(ish.visible > 0 OR iss.id, 1, 100000) * p.pickingOrder as `order`, + IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`) as `grouping`, + IF(iss.id, TO_SECONDS(iss.created), TO_SECONDS(ish.created) + TO_SECONDS(NOW())) as priority, + 0 as saleOrder, + sc.isPreviousPrepared, + iss.id as itemShelvingSaleFk + FROM tmp.sale ts + JOIN vn.itemShelving ish ON ish.itemFk = ts.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk - LEFT JOIN vn.coolerPathDetail cpd ON CAST(cpd.hallway AS DECIMAL(3,0)) = p.column JOIN vn.sector sc ON sc.id = p.sectorFk JOIN vn.warehouse w ON w.id = sc.warehouseFk - JOIN tmp.`grouping` g ON g.itemFk = s.itemFk - WHERE tc.collectionFk = vCollectionFk - AND w.aliasFk = vWarehouseAliasFk - AND ish.visible > 0 + JOIN tmp.`grouping` g ON g.itemFk = ts.itemFk + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = ts.saleFk AND iss.itemShelvingFk = ish.id + LEFT JOIN vn.worker wk ON wk.id = iss.userFk + WHERE w.aliasFk = vWarehouseAliasFk UNION ALL - SELECT s.id as saleFk, s.itemFk, - ip.code COLLATE utf8_general_ci as placement, - '' COLLATE utf8_general_ci as shelving, - modificationDate as created, - v.visible - p.quantity as visible, - IFNULL(cpd.id,0) as `order`, - g.`grouping` - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.itemPlacement ip ON ip.itemFk = s.itemFk AND ip.warehouseFk = vWarehouseFk - LEFT JOIN vn.coolerPathDetail cpd ON cpd.hallway = LEFT(ip.`code`,3) - JOIN tmp.parked p ON p.itemFk = s.itemFk - JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vCalcFk - LEFT JOIN tmp.grouping2 g ON g.itemFk = s.itemFk - WHERE tc.collectionFk = vCollectionFk - AND v.visible - p.quantity > 0 - AND IFNULL(cpd.id,0); + SELECT ts.saleFk, + ts.itemFk, + ip.`code` COLLATE utf8_general_ci as placement, + '' COLLATE utf8_general_ci as shelving, + ip.modificationDate as created, + v.visible - SUM(IFNULL(iss.visible,0)) as visible, + IF(iss.visible <= 0, 1, 100000) * pk.pickingOrder as `order`, + g.`grouping`, + TO_SECONDS(NOW()) as priority, + 0 as saleOrder, + 0 as isPreviousPrepared, + 0 + FROM tmp.sale2 ts + JOIN vn.itemPlacement ip ON ip.itemFk = ts.itemFk AND ip.warehouseFk = vWarehouseFk + LEFT JOIN vn.parking pk ON CAST(pk.column AS DECIMAL(3,0)) = CAST(LEFT(ip.`code`,3) AS DECIMAL(3,0)) + JOIN cache.visible v ON v.item_id = ts.itemFk AND v.calc_id = vCalcFk + LEFT JOIN tmp.grouping2 g ON g.itemFk = ts.itemFk + LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = ts.itemFk AND iss.warehouseFk = vWarehouseFk + GROUP BY ts.saleFk + HAVING length(placement) >= 3 AND `grouping` + AND visible > 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_2; + CREATE TEMPORARY TABLE tmp.salePlacementList_2 + ENGINE MEMORY + SELECT saleFk, priority as olderPriority + FROM (SELECT saleFk, priority + FROM tmp.salePlacementList + ORDER BY IF(isPreviousPrepared,2,1), IF(visible > 0 OR itemShelvingSaleFk,1,2), priority + ) sub + GROUP BY saleFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_3; + CREATE TEMPORARY TABLE tmp.salePlacementList_3 + ENGINE MEMORY + SELECT s1.saleFk, `order`as saleOrder + FROM tmp.salePlacementList s1 + JOIN tmp.salePlacementList_2 s2 ON s2.saleFk = s1.saleFk AND s2.olderPriority = s1.priority; + UPDATE tmp.salePlacementList s1 + JOIN tmp.salePlacementList_3 s3 ON s3.saleFk = s1.saleFk + SET s1.saleOrder = s3.saleOrder; + + SELECT * + FROM tmp.salePlacementList + ORDER BY saleOrder, IF(isPreviousPrepared,2,1), IF(visible > 0 OR itemShelvingSaleFk,1,2),priority; + DROP TEMPORARY TABLE - tmp.parked, + tmp.sale, + tmp.sale2, tmp.`grouping`, - tmp.grouping2; + tmp.grouping2, + tmp.salePlacementList_2, + tmp.salePlacementList_3; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36326,9 +37510,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 = 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 ;; @@ -36352,7 +37536,11 @@ BEGIN stems, category, origin, - clientFk + clientFk, + originalQuantity as quantityPicked, + line1, + line2, + line3 FROM ( SELECT s.ticketFk, s.id as saleFk, @@ -36371,7 +37559,11 @@ BEGIN i.stems, i.category, o.code AS origin, - t.clientFk + t.clientFk, + s.originalQuantity, + TRIM(CONCAT(LPAD(i.longName,30,' '), ' ',RPAD(IFNULL(i.size,''),5,' '))) as line1, + TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) as line2, + ic.color as line3 FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.saleTracking str ON str.saleFk = s.id AND str.isChecked = 1 @@ -36407,6 +37599,10 @@ BEGIN NULL, NULL, NULL, + NULL, + NULL, + NULL, + NULL, NULL FROM vn.ticketCollection tc JOIN vn.stowaway stow ON stow.shipFk = tc.ticketFk @@ -36470,9 +37666,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 = 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 ;; @@ -36480,7 +37676,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `collectionTicket_get`(vCollectionFk INT) BEGIN SELECT tc.ticketFk, - tc.level, + tc.wagon * 100 + tc.level `level`, am.name as agencyName, t.warehouseFk , w.id as salesPersonFk @@ -36492,6 +37688,406 @@ BEGIN LEFT JOIN vn.worker w ON w.id = c.salesPersonFk WHERE tc.collectionFk = vCollectionFk; +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 `collectionTrain_new` */; +/*!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 `collectionTrain_new`(vSectorFk INT, vWagons INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vMaxTickets INT DEFAULT 4 * vWagons; + DECLARE vStateFk INT; + DECLARE vFirstTicketFk INT; + DECLARE vWorkerCode VARCHAR(3); + DECLARE vWagon INT; + DECLARE vWagonCounter INT; + DECLARE vShelve INT; + DECLARE vTicket INT; + DECLARE myUserIsSalesPersonRole BOOLEAN; + DECLARE vPrintedTickets INT; + DECLARE vMaxTicketPrinted INT DEFAULT 5 * vWagons; + + -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando + SELECT isPreviousPrepared, warehouseFk + INTO vIsPreviousPrepared, vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + IF vIsPreviousPrepared THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + -- Averiguamos si es comercial el usuario + SELECT (r.name = 'salesPerson') + INTO myUserIsSalesPersonRole + FROM account.user u + JOIN account.role r ON r.id = u.role + WHERE u.id = vn.getUser(); + + -- Obtenemos el código del usuario + SELECT w.code + INTO vWorkerCode + FROM vn.worker w + WHERE w.id = account.myUserGetId(); + + -- Se obtiene nº de colección y el buffer con los pedidos preparables + INSERT INTO vn.collection + SET workerFk = account.myUserGetId(); + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + CALL vn2008.production_control_source(vWarehouseFk, 0); + + SELECT COUNT(*) INTO vPrintedTickets + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.Fecha = CURDATE() + AND s.isPreparable; + + SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; + + -- AutoPRINT + + IF vMaxTicketPrinted > 0 THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s2.id, pb.Id_Ticket, vn.getUser() + FROM tmp.production_buffer pb + JOIN vn.agency a ON a.id = pb.agency_id + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED' + LEFT JOIN vn.route r ON r.id = pb.Id_Ruta + WHERE pb.Fecha = CURDATE() + AND NOT pb.problems + AND a.name != 'REC_SILLA' + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , + s.order DESC, + Hora, + minuto, + IFNULL(r.priority,99999), + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + END IF; + + -- SELECT vMaxTicketPrinted; + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. + + INSERT IGNORE INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT pb.Id_Ticket, + vCollectionFk + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.collectionFk IS NULL + AND ( + (s.isPreparable AND NOT myUserIsSalesPersonRole AND pb.Agencia != 'REC_SILLA') + OR + (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) + ) + ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, pb.Hora, pb.Minuto + LIMIT vMaxTickets; + + + -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT pb.Id_Ticket ticketFk, + pb.lines, + pb.m3 * 1000 liters, + 0 as height, + 0 as shelve, + 0 as wagon + FROM tmp.production_buffer pb + JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE tc.collectionFk = vCollectionFk; + + /* El criterio para formar la colección es el siguiente: + * + * 1º.- Los tickets asignados son prioritarios, y por ello ya vienen ordenados en las primeras posiciones. + * + */ + + SELECT ticketFk + INTO vFirstTicketFk + FROM tmp.ticket + LIMIT 1; + + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. + UPDATE tmp.ticket t + JOIN + ( SELECT MAX(i.size) maxHeigth, + tc.ticketFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.isReclining = FALSE + AND tc.collectionFk = vCollectionFk + GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk + SET t.height = sub.maxHeigth; + + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido + DROP TEMPORARY TABLE IF EXISTS tmp.wagonsVolumetry; + CREATE TEMPORARY TABLE tmp.wagonsVolumetry + SELECT cv.`level` as shelve, + 1 as wagon, + cv.lines, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv; + + SET vWagonCounter = 1; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + INSERT INTO tmp.wagonsVolumetry(shelve, wagon, `lines`, liters, height) + SELECT cv.`level` as shelve, + vWagonCounter as wagon, + cv.lines, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv; + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; + CREATE TEMPORARY TABLE tmp.ticketShelve + SELECT ticketFk, shelve, wagon, linesDif, LitersDif, heightDif + FROM ( + SELECT t.ticketFk, + wv.shelve, + wv.wagon, + CAST(wv.lines AS SIGNED) - t.lines as linesDif, + CAST(wv.liters AS SIGNED) - t.liters as litersDif, + CAST(wv.height AS SIGNED) - t.height as heightDif + FROM tmp.wagonsVolumetry wv + JOIN tmp.ticket t + ORDER BY (t.ticketFk = vFirstTicketFk) DESC, linesDif + ) sub + WHERE linesDif >= 0 + AND litersDif >= 0 + AND heightDif >= 0 + ORDER BY linesDif; + + -- Insertamos una opcion virtual para carro completo. Todo ticket tiene que poder entrar en un carro completo.... + INSERT INTO tmp.ticketShelve(ticketFk, shelve, wagon, linesDif, LitersDif, heightDif) + SELECT t.ticketFk, 0, wv.wagon, 999, 999,999 + FROM tmp.ticket t + JOIN tmp.wagonsVolumetry wv + GROUP BY t.ticketFk, wv.wagon; + /* + DROP TEMPORARY TABLE IF EXISTS tmp.tsKKK; + + CREATE TEMPORARY TABLE tmp.tsKKK + SELECT t.ticketFk, + wv.shelve, + wv.wagon, + CAST(wv.lines AS SIGNED) - t.lines as linesDif, + CAST(wv.liters AS SIGNED) - t.liters as litersDif, + CAST(wv.height AS SIGNED) - t.height as heightDif + FROM tmp.wagonsVolumetry wv + JOIN tmp.ticket t + ORDER BY (t.ticketFk = vFirstTicketFk) DESC, linesDif; + + + DROP TEMPORARY TABLE IF EXISTS tmp.tsKK; + + CREATE TEMPORARY TABLE tmp.tsKK + SELECT * FROM tmp.ticketShelve; + + SELECT * FROM tmp.tsKK; + + SELECT * FROM tmp.ticket; + */ + SET vWagonCounter = 0; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + -- Asignamos la primera balda util al primer pedido + IF vWagonCounter = 1 THEN + + SELECT shelve INTO vShelve + FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + ELSE + + SELECT shelve, ticketFk INTO vShelve, vFirstTicketFk + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + END IF; + + IF vShelve > 0 THEN + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + OR (shelve = vShelve AND wagon = vWagonCounter); + + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve WHERE wagon = vWagonCounter) DO + + SELECT ticketFk, shelve + INTO vTicket, vShelve + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + LIMIT 1; + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vTicket; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR (shelve = vShelve AND wagon = vWagonCounter); + + END WHILE; + + ELSE + + UPDATE tmp.ticket + SET shelve = 1, wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon != vWagonCounter; + + END IF; + + END WHILE; + + -- Eliminamos los que se han quedado sin balda + DELETE FROM tmp.ticket WHERE shelve = 0; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + -- Actualiza el estado de la colección + UPDATE vn.collection c + JOIN vn.state st ON st.code = 'ON_PREPARATION' + SET c.stateFk = st.id + WHERE c.id = vCollectionFk; + + -- Asigna las bandejas + UPDATE vn.ticketCollection tc + JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + SET tc.level = t.shelve, tc.wagon = t.wagon; + + -- Actualiza el estado de los tickets + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT vStateFk, ticketFk, account.myUserGetId() + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + -- Avisa los preparados previos que hay que bajar del altillo imprimiendo etiqueta + INSERT IGNORE INTO vn.ticketDown(ticketFk) + SELECT DISTINCT tc.ticketFk + FROM vn.ticketCollection tc + JOIN vncontrol.inter vi ON vi.Id_Ticket = tc.ticketFk + JOIN vn.state st ON st.id = vi.state_id + JOIN vn.ticket t ON t.id = tc.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + WHERE tc.collectionFk = vCollectionFk + AND w.name = 'Silla FV' + AND st.code = 'PREVIOUS_PREPARATION'; + + SELECT vCollectionFk; + +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 `collection_faults` */; +/*!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 `collection_faults`( + vShelvingFk VARCHAR(10), + vQuantity INT, + vItemFk INT) +BEGIN + DECLARE vQuantityTotal INT DEFAULT 0; + DECLARE vshelve VARCHAR(2); + DECLARE vdeep INT(11); + DECLARE vpriority INT(11); + DECLARE vgrouping SMALLINT(5); + DECLARE vpacking INT(11); + DECLARE vpackagingFk VARCHAR(10); + DECLARE vlevel VARCHAR(45); + DECLARE vuserFk INT(10); + + + SELECT SUM(quantity),shelve,deep,priority,`grouping`,packing,packagingFk,`level`,userFk + INTO vQuantityTotal,vshelve,vdeep,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk + FROM vn.itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci AND itemFk = vItemFk + GROUP BY itemFk; + + SELECT vQuantityTotal - vQuantity INTO vQuantityTotal; + + DELETE FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci AND itemFk = vItemFk; + + INSERT INTO vn.itemShelving (itemFk, shelvingFk,shelve,deep,quantity,visible,available,priority,`grouping`,packing,packagingFk,`level`,userFk ) + VALUES (vItemFk,vShelvingFk,vshelve,vdeep,vQuantityTotal,vQuantityTotal,vQuantityTotal,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk ); + + SELECT * FROM vn.itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci AND itemFk = vItemFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36546,7 +38142,38 @@ proc:BEGIN DECLARE vTicket INT; DECLARE myUserIsSalesPersonRole BOOLEAN; DECLARE vPrintedTickets INT; - DECLARE vMaxTicketPrinted INT DEFAULT 10; + DECLARE vMaxTicketPrinted INT DEFAULT 20; + + -- Se comprueba si existe coleccion pendiente, en cuyo caso se devuelve esa colección + SELECT collectionFk INTO vCollectionFk + FROM + ( + SELECT tc.collectionFk, COUNT(*) as lineas, sum(IF(st.id,0,1)) as libres + FROM vn.collection c + JOIN vn.ticketCollection tc ON tc.collectionFk = c.id + JOIN vn.ticket t ON t.id = tc.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.saleTracking st ON st.saleFk = s.id + WHERE c.workerFk = vn.getUser() + AND s.quantity + AND c.created > CURDATE() + GROUP BY c.id + HAVING libres = lineas) sub + LIMIT 1; + + IF vCollectionFk THEN + + SELECT vCollectionFk; + + LEAVE proc; + + END IF; + + IF /*vSectorFk = 18*/ FALSE THEN + + CALL vn.collectionTrain_new(9,3); + + ELSE -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando SELECT isPreviousPrepared, warehouseFk @@ -36568,7 +38195,7 @@ proc:BEGIN END IF; -- Averiguamos si es comercial el usuario - SELECT (r.name = 'salesPerson') + SELECT FALSE -- (r.name = 'salesPerson') INTO myUserIsSalesPersonRole FROM account.user u JOIN account.role r ON r.id = u.role @@ -36605,8 +38232,9 @@ proc:BEGIN FROM tmp.production_buffer pb JOIN vn.agency a ON a.id = pb.agency_id JOIN vn.state s ON s.id = pb.state - JOIN vn.state s2 ON s2.code = 'PRINTED' + JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' LEFT JOIN vn.route r ON r.id = pb.Id_Ruta + LEFT JOIN vn.stowaway sa ON sa.id = pb.Id_Ticket WHERE pb.Fecha = CURDATE() AND NOT pb.problems AND a.name != 'REC_SILLA' @@ -36618,7 +38246,9 @@ proc:BEGIN Hora, minuto, IFNULL(r.priority,99999), - pb.m3 DESC + IFNULL(sa.id, 0) DESC, + IFNULL(r.id,999999), + pb.m3 DESC LIMIT vMaxTicketPrinted; END IF; @@ -36630,14 +38260,21 @@ proc:BEGIN SELECT pb.Id_Ticket, vCollectionFk FROM tmp.production_buffer pb - JOIN vn.state s ON s.id = pb.state + JOIN vn.ticketStateToday tst ON tst.ticket = pb.Id_Ticket + JOIN vn.state s ON s.id = tst.state + LEFT JOIN vn.route r ON r.id = pb.Id_Ruta WHERE pb.collectionFk IS NULL AND ( (s.isPreparable AND NOT myUserIsSalesPersonRole AND pb.Agencia != 'REC_SILLA') OR (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) ) - ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, pb.Hora, pb.Minuto + ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, + pb.Hora, + pb.Minuto, + IF(IFNULL(r.priority,0) = 0, 999, r.priority), + IFNULL(r.id,99999), + pb.m3 DESC LIMIT vMaxTickets; @@ -36652,15 +38289,6 @@ proc:BEGIN FROM tmp.production_buffer pb JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket WHERE tc.collectionFk = vCollectionFk; - - /* El criterio para formar la colección es el siguiente: - * - * 1º.- Los tickets asignados son prioritarios, y por ello ya vienen ordenados en las primeras posiciones. - * 2º.- Las recogidas en Silla tienen que ir en carros independientes. - * - * Por tanto, si el primer pedido es recogida, nos olvidamos del resto. - * Si el primer pedido no es recogida, eliminamos las recogidas posteriores. - */ SELECT ticketFk INTO vFirstTicketFk @@ -36798,293 +38426,21 @@ proc:BEGIN WHERE tc.collectionFk = vCollectionFk AND w.name = 'Silla FV' AND st.code = 'PREVIOUS_PREPARATION'; + + IF (SELECT COUNT(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN - SELECT vCollectionFk; - -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 `collection_newBeta` */; -/*!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 `collection_newBeta`(vSectorFk INT,vWorkerFk INT) -proc:BEGIN - - DECLARE vIsPreviousPrepared BOOLEAN; - DECLARE vCollectionFk INT; - DECLARE vWarehouseFk INT; - DECLARE vMaxTickets INT DEFAULT 4; - DECLARE vStateFk INT; - DECLARE vFirstTicketFk INT; - DECLARE vWorkerCode VARCHAR(3); - DECLARE vShelve INT; - DECLARE vTicket INT; - DECLARE myUserIsSalesPersonRole BOOLEAN; - DECLARE vPrintedTickets INT; - DECLARE vMaxTicketPrinted INT DEFAULT 10; - - -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando - SELECT isPreviousPrepared, warehouseFk - INTO vIsPreviousPrepared, vWarehouseFk - FROM vn.sector - WHERE id = vSectorFk; - - IF vIsPreviousPrepared THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE `code` = 'PREVIOUS_PREPARATION'; + CALL vn.salesMerge_byCollection(vCollectionFk); + + SELECT vCollectionFk; + ELSE - SELECT id INTO vStateFk - FROM vn.state - WHERE `code` = 'ON_PREPARATION'; - + DELETE FROM vn.collection WHERE id = vCollectionFk; + SELECT 0; + + END IF; + END IF; - - -- Averiguamos si es comercial el usuario - SELECT (r.name = 'salesPerson') - INTO myUserIsSalesPersonRole - FROM account.user u - JOIN account.role r ON r.id = u.role - WHERE u.id = vWorkerFk; - - -- Obtenemos el código del usuario - SELECT w.code - INTO vWorkerCode - FROM vn.worker w - WHERE w.id = vWorkerFk; - - -- Se obtiene nº de colección y el buffer con los pedidos preparables - INSERT INTO vn.collection - SET workerFk = vWorkerFk; - - SELECT LAST_INSERT_ID() INTO vCollectionFk; - - CALL vn2008.production_control_source(vWarehouseFk, 0); - - SELECT COUNT(*) INTO vPrintedTickets - FROM tmp.production_buffer pb - JOIN vn.state s ON s.id = pb.state - WHERE pb.Fecha = CURDATE() - AND s.isPreparable; - - SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; - - -- AutoPRINT - - IF vMaxTicketPrinted > 0 THEN - - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT s2.id, pb.Id_Ticket, vWorkerFk - FROM tmp.production_buffer pb - JOIN vn.agency a ON a.id = pb.agency_id - JOIN vn.state s ON s.id = pb.state - JOIN vn.state s2 ON s2.code = 'PRINTED' - LEFT JOIN vn.route r ON r.id = pb.Id_Ruta - WHERE pb.Fecha = CURDATE() - AND NOT pb.problems - AND a.name != 'REC_SILLA' - AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) - AND s.isPrintable - AND (pb.m3 > 0.05 OR s.isOK) - ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , - s.order DESC, - Hora, - minuto, - IFNULL(r.priority,99999), - pb.m3 DESC - LIMIT vMaxTicketPrinted; - - END IF; - - -- SELECT vMaxTicketPrinted; - -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. - - INSERT IGNORE INTO vn.ticketCollection(ticketFk, collectionFk) - SELECT pb.Id_Ticket, - vCollectionFk - FROM tmp.production_buffer pb - JOIN vn.state s ON s.id = pb.state - WHERE pb.collectionFk IS NULL - AND ( - (s.isPreparable AND NOT myUserIsSalesPersonRole AND pb.Agencia != 'REC_SILLA') - OR - (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) - ) - ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, pb.Hora, pb.Minuto - LIMIT vMaxTickets; - - - -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - SELECT pb.Id_Ticket ticketFk, - pb.lines, - pb.m3 * 1000 liters, - 0 as height, - 0 as shelve - FROM tmp.production_buffer pb - JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket - WHERE tc.collectionFk = vCollectionFk; - - /* El criterio para formar la colección es el siguiente: - * - * 1º.- Los tickets asignados son prioritarios, y por ello ya vienen ordenados en las primeras posiciones. - * 2º.- Las recogidas en Silla tienen que ir en carros independientes. - * - * Por tanto, si el primer pedido es recogida, nos olvidamos del resto. - * Si el primer pedido no es recogida, eliminamos las recogidas posteriores. - */ - - SELECT ticketFk - INTO vFirstTicketFk - FROM tmp.ticket - LIMIT 1; - - IF (SELECT pb.Agencia FROM tmp.production_buffer pb WHERE Id_Ticket = vFirstTicketFk) = 'REC_SILLA' THEN - - DELETE FROM tmp.ticket WHERE ticketFk != vFirstTicketFk; - - UPDATE tmp.ticket SET shelve = 1; - -- Como sólo hay un ticket, se le asigna el nivel 1 y acabamos - - ELSE - - -- Eliminamos los de recogida, puesto que el primero sabemos que no es de rec_silla - DELETE t.* - FROM tmp.ticket t - JOIN tmp.production_buffer pb ON pb.Id_Ticket = t.ticketFk - WHERE pb.Agencia = 'REC_SILLA'; - - -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. - UPDATE tmp.ticket t - JOIN - ( SELECT MAX(i.size) maxHeigth, - tc.ticketFk - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - WHERE ic.isReclining = FALSE - AND tc.collectionFk = vCollectionFk - GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk - SET t.height = sub.maxHeigth; - - -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido - DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; - CREATE TEMPORARY TABLE tmp.ticketShelve - SELECT ticketFk, shelve, linesDif, LitersDif, heightDif - FROM ( - SELECT t.ticketFk, - cv.`level` shelve, - CAST(cv.lines AS SIGNED) - t.lines as linesDif, - CAST(cv.liters AS SIGNED) - t.liters as litersDif, - CAST(cv.height AS SIGNED) - t.height as heightDif - FROM vn.collectionVolumetry cv - JOIN tmp.ticket t - ORDER BY (t.ticketFk = vFirstTicketFk) DESC, linesDif - ) sub - WHERE linesDif >= 0 - AND litersDif >= 0 - AND heightDif >= 0 - ORDER BY linesDif; - - -- Asignamos la primera balda util al primer pedido - SELECT IFNULL(shelve,0) INTO vShelve - FROM tmp.ticketShelve - WHERE ticketFk = vFirstTicketFk - ORDER BY heightDif, litersDif, linesDif - LIMIT 1; - - IF vShelve THEN - - UPDATE tmp.ticket - SET shelve = vShelve - WHERE ticketFk = vFirstTicketFk; - - DELETE FROM tmp.ticketShelve - WHERE ticketFk = vFirstTicketFk - OR shelve = vShelve; - - WHILE (SELECT COUNT(*) FROM tmp.ticketShelve) DO - - SELECT ticketFk, shelve - INTO vTicket, vShelve - FROM tmp.ticketShelve - LIMIT 1; - - UPDATE tmp.ticket - SET shelve = vShelve - WHERE ticketFk = vTicket; - - DELETE FROM tmp.ticketShelve - WHERE ticketFk = vTicket - OR shelve = vShelve; - - END WHILE; - - ELSE - - UPDATE tmp.ticket - SET shelve = 1 - WHERE ticketFk = vFirstTicketFk; - - END IF; - - END IF; - - -- Eliminamos los que se han quedado sin balda - DELETE FROM tmp.ticket WHERE shelve = 0 ; - - -- Elimina los tickets bloqueados que no se van a preparar - DELETE tc.* - FROM vn.ticketCollection tc - LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND t.ticketFk IS NULL; - - -- Actualiza el estado de la colección - UPDATE vn.collection c - JOIN vn.state st ON st.code = 'ON_PREPARATION' - SET c.stateFk = st.id - WHERE c.id = vCollectionFk; - - -- Asigna las bandejas - UPDATE vn.ticketCollection tc - JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - SET tc.level = t.shelve; - - -- Actualiza el estado de los tickets - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT vStateFk, ticketFk, vWorkerFk - FROM vn.ticketCollection tc - WHERE tc.collectionFk = vCollectionFk; - - -- Avisa los preparados previos que hay que bajar del altillo imprimiendo etiqueta - INSERT IGNORE INTO vn.ticketDown(ticketFk) - SELECT DISTINCT tc.ticketFk - FROM vn.ticketCollection tc - JOIN vncontrol.inter vi ON vi.Id_Ticket = tc.ticketFk - JOIN vn.state st ON st.id = vi.state_id - JOIN vn.ticket t ON t.id = tc.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - WHERE tc.collectionFk = vCollectionFk - AND w.name = 'Silla FV' - AND st.code = 'PREVIOUS_PREPARATION'; - - SELECT vCollectionFk; END ;; DELIMITER ; @@ -37092,7 +38448,7 @@ 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 PROCEDURE IF EXISTS `collection_new_test` */; +/*!50003 DROP PROCEDURE IF EXISTS `collection_placement_ticket_get` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -37102,392 +38458,143 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `collection_new_test`(vSectorFk INT) -proc:BEGIN +CREATE DEFINER=`root`@`%` PROCEDURE `collection_placement_ticket_get`(vTicketFk INT) +BEGIN - DECLARE vIsPreviousPrepared BOOLEAN; - DECLARE vCollectionFk INT; + DECLARE vCalcFk INT; DECLARE vWarehouseFk INT; - DECLARE vMaxTickets INT DEFAULT 4; - DECLARE vStateFk INT; - DECLARE vFirstTicketFk INT; - DECLARE vWorkerCode VARCHAR(3); - DECLARE vShelve INT; - DECLARE vTicket INT; - DECLARE myUserIsSalesPersonRole BOOLEAN; - DECLARE vPrintedTickets INT; - DECLARE vMaxTicketPrinted INT DEFAULT 10; + DECLARE vWarehouseAliasFk INT; - DROP TEMPORARY TABLE IF EXISTS tmp.log; - CREATE TEMPORARY TABLE tmp.log - SELECT CURTIME() as hora, - 'Comienza el proc ' as accion, - ' -- ' as valor; - - -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando - SELECT isPreviousPrepared, warehouseFk - INTO vIsPreviousPrepared, vWarehouseFk - FROM vn.sector - WHERE id = vSectorFk; - - IF vIsPreviousPrepared THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE `code` = 'PREVIOUS_PREPARATION'; - ELSE - - SELECT id INTO vStateFk - FROM vn.state - WHERE `code` = 'ON_PREPARATION'; - - END IF; - - -- Averiguamos si es comercial el usuario - SELECT (r.name = 'salesPerson') - INTO myUserIsSalesPersonRole - FROM account.user u - JOIN account.role r ON r.id = u.role - WHERE u.id = vn.getUser(); - - INSERT INTO tmp.log(hora, - accion, - valor) - VALUES( CURTIME(), - 'Determina si es comercial el usuario', - myUserIsSalesPersonRole); - - -- Obtenemos el código del usuario - SELECT w.code - INTO vWorkerCode - FROM vn.worker w - WHERE w.id = account.myUserGetId(); - - -- Se obtiene nº de colección y el buffer con los pedidos preparables - INSERT INTO vn.collection - SET workerFk = account.myUserGetId(); - - SELECT LAST_INSERT_ID() INTO vCollectionFk; - - INSERT INTO tmp.log(hora, - accion, - valor) - VALUES( CURTIME(), - 'Obtiene numero de coleccion', - vCollectionFk); - - - - CALL vn2008.production_control_source(vWarehouseFk, 0); - - SELECT COUNT(*) INTO vPrintedTickets - FROM tmp.production_buffer pb - JOIN vn.state s ON s.id = pb.state - WHERE pb.Fecha = CURDATE() - AND s.isPreparable; - - - INSERT INTO tmp.log(hora, - accion, - valor) - VALUES( CURTIME(), - 'Calcula tickets impresos', - vPrintedTickets); - - - - SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; - - -- AutoPRINT - - IF vMaxTicketPrinted > 0 THEN - - - INSERT INTO tmp.log(hora, - accion, - valor) - SELECT CURTIME(), - CONCAT('T', pb.Id_Ticket), -'PRINTED' - FROM tmp.production_buffer pb - JOIN vn.agency a ON a.id = pb.agency_id - JOIN vn.state s ON s.id = pb.state - JOIN vn.state s2 ON s2.code = 'PRINTED' - LEFT JOIN vn.route r ON r.id = pb.Id_Ruta - WHERE pb.Fecha = CURDATE() - AND NOT pb.problems - AND a.name != 'REC_SILLA' - AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) - AND s.isPrintable - AND (pb.m3 > 0.05 OR s.isOK) - ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , - s.order DESC, - Hora, - minuto, - IFNULL(r.priority,99999), - pb.m3 DESC - LIMIT vMaxTicketPrinted; - - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT s2.id, pb.Id_Ticket, vn.getUser() - FROM tmp.production_buffer pb - JOIN vn.agency a ON a.id = pb.agency_id - JOIN vn.state s ON s.id = pb.state - JOIN vn.state s2 ON s2.code = 'PRINTED' - LEFT JOIN vn.route r ON r.id = pb.Id_Ruta - WHERE pb.Fecha = CURDATE() - AND NOT pb.problems - AND a.name != 'REC_SILLA' - AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) - AND s.isPrintable - AND (pb.m3 > 0.05 OR s.isOK) - ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , - s.order DESC, - Hora, - minuto, - IFNULL(r.priority,99999), - pb.m3 DESC - LIMIT vMaxTicketPrinted; - - END IF; - - -- SELECT vMaxTicketPrinted; - -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. - - INSERT IGNORE INTO vn.ticketCollection(ticketFk, collectionFk) - SELECT pb.Id_Ticket, - vCollectionFk - FROM tmp.production_buffer pb - JOIN vn.state s ON s.id = pb.state - WHERE pb.collectionFk IS NULL - AND ( - (s.isPreparable AND NOT myUserIsSalesPersonRole AND pb.Agencia != 'REC_SILLA') - OR - (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) - ) - ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, pb.Hora, pb.Minuto - LIMIT vMaxTickets; - - - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),ticketFk,vCollectionFk - FROM vn.ticketCollection - WHERE collectionFk = vCollectionFk; - - - -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - SELECT pb.Id_Ticket ticketFk, - pb.lines, - pb.m3 * 1000 liters, - 0 as height, - 0 as shelve - FROM tmp.production_buffer pb - JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket - WHERE tc.collectionFk = vCollectionFk; - - - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),ticketFk,CONCAT('Ln:',`lines`,' Lt:',liters,' h:',height,' sh:',shelve) - FROM tmp.ticket; - - /* El criterio para formar la colección es el siguiente: - * - * 1º.- Los tickets asignados son prioritarios, y por ello ya vienen ordenados en las primeras posiciones. - * 2º.- Las recogidas en Silla tienen que ir en carros independientes. - * - * Por tanto, si el primer pedido es recogida, nos olvidamos del resto. - * Si el primer pedido no es recogida, eliminamos las recogidas posteriores. - */ - - SELECT ticketFk - INTO vFirstTicketFk - FROM tmp.ticket - LIMIT 1; - - - INSERT INTO tmp.log(hora, accion, valor) - VALUES( CURTIME(),'Primer ticket',vFirstTicketFk) - ; - - IF (SELECT pb.Agencia FROM tmp.production_buffer pb WHERE Id_Ticket = vFirstTicketFk) = 'REC_SILLA' THEN - - DELETE FROM tmp.ticket WHERE ticketFk != vFirstTicketFk; - - UPDATE tmp.ticket SET shelve = 1; - -- Como sólo hay un ticket, se le asigna el nivel 1 y acabamos - - ELSE - - -- Eliminamos los de recogida, puesto que el primero sabemos que no es de rec_silla - DELETE t.* - FROM tmp.ticket t - JOIN tmp.production_buffer pb ON pb.Id_Ticket = t.ticketFk - WHERE pb.Agencia = 'REC_SILLA'; - - -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. - UPDATE tmp.ticket t - JOIN - ( SELECT MAX(i.size) maxHeigth, - tc.ticketFk - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - WHERE ic.isReclining = FALSE - AND tc.collectionFk = vCollectionFk - GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk - SET t.height = sub.maxHeigth; - - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),ticketFk,CONCAT('Ln:',`lines`,' Lt:',liters,' h:',height,' sh:',shelve) - FROM tmp.ticket; - - - -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido - DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; - CREATE TEMPORARY TABLE tmp.ticketShelve - SELECT ticketFk, shelve, linesDif, litersDif, heightDif - FROM ( - SELECT t.ticketFk, - cv.`level` shelve, - CAST(cv.lines AS SIGNED) - t.lines as linesDif, - CAST(cv.liters AS SIGNED) - t.liters as litersDif, - CAST(cv.height AS SIGNED) - t.height as heightDif - FROM vn.collectionVolumetry cv - JOIN tmp.ticket t - ORDER BY (t.ticketFk = vFirstTicketFk) DESC, linesDif - ) sub - WHERE linesDif >= 0 - AND litersDif >= 0 - AND heightDif >= 0 - ORDER BY linesDif; - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),'Todas las posibilidades',COUNT(*) - FROM tmp.ticketShelve; - - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),ticketFk,CONCAT('Lnd:',`linesDif`,' Ltd',litersDif,' hd:',heightDif,' sh:',shelve) - FROM tmp.ticketShelve; - - -- Asignamos la primera balda util al primer pedido - SELECT IFNULL(shelve,0) INTO vShelve - FROM tmp.ticketShelve - WHERE ticketFk = vFirstTicketFk - ORDER BY heightDif, litersDif, linesDif - LIMIT 1; - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),'vShelve',vShelve; - IF vShelve THEN - - UPDATE tmp.ticket - SET shelve = vShelve - WHERE ticketFk = vFirstTicketFk; - - DELETE FROM tmp.ticketShelve - WHERE ticketFk = vFirstTicketFk - OR shelve = vShelve; - - WHILE (SELECT COUNT(*) FROM tmp.ticketShelve) DO - - SELECT ticketFk, shelve - INTO vTicket, vShelve - FROM tmp.ticketShelve - LIMIT 1; - - UPDATE tmp.ticket - SET shelve = vShelve - WHERE ticketFk = vTicket; - - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),'Quedan', COUNT(*) - FROM tmp.ticketShelve; - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),ticketFk,CONCAT(' sh:',shelve) - FROM tmp.ticket; - - DELETE FROM tmp.ticketShelve - WHERE ticketFk = vTicket - OR shelve = vShelve; - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),'Borrar los asignados', COUNT(*) - FROM tmp.ticketShelve - WHERE ticketFk = vTicket - OR shelve = vShelve; - - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),ticketFk,CONCAT(' sh:',shelve) - FROM tmp.ticket; - - END WHILE; - - - ELSE - - UPDATE tmp.ticket - SET shelve = 1 - WHERE ticketFk = vFirstTicketFk; - - END IF; - - END IF; - - -- Eliminamos los que se han quedado sin balda - DELETE FROM tmp.ticket WHERE shelve = 0 ; - - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),ticketFk,CONCAT('Borrar sh:',shelve) - FROM tmp.ticket - WHERE shelve = 0; - - -- Elimina los tickets bloqueados que no se van a preparar - DELETE tc.* - FROM vn.ticketCollection tc - LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND t.ticketFk IS NULL; - - INSERT INTO tmp.log(hora, accion, valor) - SELECT CURTIME(),'Elimina tickets bloqueados', tc.ticketFk - FROM vn.ticketCollection tc - LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND t.ticketFk IS NULL; - - - -- Actualiza el estado de la colección - UPDATE vn.collection c - JOIN vn.state st ON st.code = 'ON_PREPARATION' - SET c.stateFk = st.id - WHERE c.id = vCollectionFk; - - -- Asigna las bandejas - UPDATE vn.ticketCollection tc - JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - SET tc.level = t.shelve; - - -- Actualiza el estado de los tickets - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT vStateFk, ticketFk, account.myUserGetId() - FROM vn.ticketCollection tc - WHERE tc.collectionFk = vCollectionFk; - - -- Avisa los preparados previos que hay que bajar del altillo imprimiendo etiqueta - INSERT IGNORE INTO vn.ticketDown(ticketFk) - SELECT DISTINCT tc.ticketFk - FROM vn.ticketCollection tc - JOIN vncontrol.inter vi ON vi.Id_Ticket = tc.ticketFk - JOIN vn.state st ON st.id = vi.state_id - JOIN vn.ticket t ON t.id = tc.ticketFk + SELECT t.warehouseFk, w.aliasFk + INTO vWarehouseFk, vWarehouseAliasFk + FROM vn.ticket t + JOIN vn.ticketCollection tc ON tc.ticketFk = t.id JOIN vn.warehouse w ON w.id = t.warehouseFk - WHERE tc.collectionFk = vCollectionFk - AND w.name = 'Silla FV' - AND st.code = 'PREVIOUS_PREPARATION'; - - SELECT * FROM tmp.log; + WHERE tc.ticketFk = vTicketFk + LIMIT 1; + + CALL cache.visible_refresh(vCalcFk,FALSE,vWarehouseFk); + DROP TEMPORARY TABLE IF EXISTS tmp.parked; + CREATE TEMPORARY TABLE tmp.parked + ENGINE MEMORY + SELECT s.itemFk, 0 as quantity + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + WHERE tc.ticketFk = vTicketFk; + + UPDATE tmp.parked pk + JOIN ( SELECT itemFk, sum(visible) as visible + FROM vn.itemShelvingStock iss + JOIN vn.warehouse w ON w.id = iss.warehouseFk + WHERE w.aliasFk = vWarehouseAliasFk + GROUP BY iss.itemFk ) iss ON iss.itemFk = pk.itemFk + SET pk.quantity = iss.visible; + + DROP TEMPORARY TABLE IF EXISTS tmp.`grouping`; + CREATE TEMPORARY TABLE tmp.`grouping` + ENGINE MEMORY + SELECT itemFk, `grouping` + FROM ( + SELECT itemFk, + CASE groupingMode + WHEN 0 THEN 1 + WHEN 2 THEN packing + ELSE `grouping` + END AS `grouping` + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseInFk = vWarehouseFk + AND landed BETWEEN (SELECT inventoried FROM vn.config LIMIT 1) AND CURDATE() + AND b.isIgnored = FALSE + ORDER BY tr.landed DESC + ) sub + GROUP BY sub.itemFk ; + + DROP TEMPORARY TABLE IF EXISTS tmp.grouping2; + CREATE TEMPORARY TABLE tmp.grouping2 + ENGINE MEMORY + SELECT * FROM tmp.`grouping`; + + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList; + CREATE TEMPORARY TABLE tmp.salePlacementList + ENGINE MEMORY + + SELECT s.id as saleFk, + s.itemFk, + CONCAT(IF(iss.id, '>',''), p.`code`) COLLATE utf8_general_ci as placement , + sh.code COLLATE utf8_general_ci as shelving, + ish.created, + ish.visible as visible, + IF(ish.visible > 0, 1, 100000) * p.pickingOrder as `order`, + IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`) as `grouping`, + TO_SECONDS(ish.created) as priority, + 0 as saleOrder, + iss.created as picked + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + JOIN vn.warehouse w ON w.id = sc.warehouseFk + JOIN tmp.`grouping` g ON g.itemFk = s.itemFk + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id AND iss.itemShelvingFk = ish.id + WHERE tc.ticketFk = vTicketFk + AND w.aliasFk = vWarehouseAliasFk + UNION ALL + SELECT s.id as saleFk, + s.itemFk, + ip.`code` as placement, + '' as shelving, + ip.modificationDate as created, + v.visible - p.quantity as visible, + IF(v.visible > 0, 1, 100000) * pk.pickingOrder as `order`, + g.`grouping`, + TO_SECONDS(ip.modificationDate) as priority, + 0 as saleOrder, + NULL + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.itemPlacement ip ON ip.itemFk = s.itemFk AND ip.warehouseFk = vWarehouseFk + LEFT JOIN vn.parking pk ON CAST(pk.column AS DECIMAL(3,0)) = CAST(LEFT(ip.`code`,3) AS DECIMAL(3,0)) + LEFT JOIN tmp.parked p ON p.itemFk = s.itemFk + JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vCalcFk + LEFT JOIN tmp.grouping2 g ON g.itemFk = s.itemFk + WHERE tc.ticketFk = vTicketFk + AND v.visible - p.quantity > 0 + GROUP BY s.id + HAVING length(placement) >= 3; + + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_2; + CREATE TEMPORARY TABLE tmp.salePlacementList_2 + ENGINE MEMORY + SELECT saleFk, min(priority) as olderPriority + FROM tmp.salePlacementList + GROUP BY saleFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_3; + CREATE TEMPORARY TABLE tmp.salePlacementList_3 + ENGINE MEMORY + SELECT s1.saleFk, `order`as saleOrder + FROM tmp.salePlacementList s1 + JOIN tmp.salePlacementList_2 s2 ON s2.saleFk = s1.saleFk AND s2.olderPriority = s1.priority; + + UPDATE tmp.salePlacementList s1 + JOIN tmp.salePlacementList_3 s3 ON s3.saleFk = s1.saleFk + SET s1.saleOrder = s3.saleOrder; + + SELECT * + FROM tmp.salePlacementList + ORDER BY picked, saleOrder, priority; + + DROP TEMPORARY TABLE + tmp.parked, + tmp.`grouping`, + tmp.grouping2, + tmp.salePlacementList_2, + tmp.salePlacementList_3; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37527,6 +38634,57 @@ BEGIN WHERE id = vCollectionFk; 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 `collection_updateSale` */; +/*!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 `collection_updateSale`( + vSaleFk INT, + vOriginalQuantity INT, + vWorkerFk INT, + vStateFk INT, + vTicketFk INT) +BEGIN + + DECLARE vNumPrepared INT; + DECLARE vNumTotal INT; + + REPLACE INTO vn.saleTracking(saleFk,isChecked, originalQuantity, workerFk, actionFk,stateFk) + VALUES(vSaleFk,1,vOriginalQuantity,vWorkerFk,vStateFk,vStateFk); + + UPDATE vn.sale SET isPicked = 1 + WHERE id = vSaleFk; + + SELECT COUNT(s.id) INTO vNumPrepared + FROM vn.sale s + WHERE s.ticketFk = vTicketFk AND s.isPicked = 1; + + SELECT COUNT(s.id) INTO vNumTotal + FROM vn.sale s + WHERE s.ticketFk = vTicketFk; + + IF vNumPrepared = vNumTotal THEN + + INSERT INTO vncontrol.inter + SET state_id = vStateFk, Id_Ticket = vTicketFk, Id_Trabajador = vWorkerFk; + + CALL vn.collection_update(vTicketFk); + + END IF; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38951,216 +40109,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 */ ; @@ -39222,62 +40380,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 */ ; @@ -39574,6 +40732,91 @@ BEGIN SET exp.checked = vChecked WHERE exp.id = vExpeditionFk; +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 `faultsReview` */; +/*!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 `faultsReview`(vWarehouseFk INT) +BEGIN + + DECLARE vCalcVisibleFk INT; + + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; + + CREATE TEMPORARY TABLE tmp.itemShelvingRadar + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT iss.itemFk, + i.size, + i.subName producer, + SUM(IF(s.sonFk, iss.visible,0)) upstairs, + SUM(IF(s.sonFk, 0, iss.visible)) downstairs, + v.visible + FROM vn.itemShelvingStock iss + JOIN vn.sector s ON s.id = iss.sectorFk + JOIN vn.item i on i.id = iss.itemFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + WHERE iss.warehouseFk = vWarehouseFk + GROUP BY iss.itemFk; + + SELECT ishr.*, sub.longName, + CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, + CAST(sub.fault AS DECIMAL(10,0)) as faltas + FROM tmp.itemShelvingRadar ishr + JOIN (SELECT s.itemFk, s.quantity as fault, s.concept as longName + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.client c ON c.id = t.clientFk + WHERE c.typeFk = 'loses' COLLATE utf8_unicode_ci + AND s.isPicked = FALSE + AND date(t.shipped) = CURDATE() + AND t.warehouseFk = vWarehouseFk + ) sub ON sub.itemFk = ishr.itemFk + ; + + +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 `faultsReview_isChecked` */; +/*!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 `faultsReview_isChecked`(vItemFk INT, vWarehouseFk INT) +BEGIN + + UPDATE vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.client c ON c.id = t.clientFk + SET s.isPicked = TRUE + WHERE c.typeFk = 'loses' COLLATE utf8_unicode_ci + AND date(t.shipped) = CURDATE() + AND t.warehouseFk = vWarehouseFk + AND s.itemFk = vItemFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39821,9 +41064,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 = 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 ;; @@ -39833,13 +41076,12 @@ proc: BEGIN * Recalcula los inventarios de todos los almacenes, si vWh = 0 * * @param vDate Fecha de los nuevos inventarios + * @param vWh almacen al cual hacer el inventario */ DECLARE vDone BOOL; DECLARE vEntryFk INT; DECLARE vTravelFk INT; - DECLARE vDateTime DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00'); - DECLARE vDeleteDate DATE DEFAULT TIMESTAMPADD(DAY, -2, vDate); DECLARE vDateLastInventory DATE; DECLARE vDateYesterday DATETIME DEFAULT TIMESTAMPADD(SECOND,-1,vDate); @@ -39891,7 +41133,7 @@ proc: BEGIN INSERT INTO travel SET warehouseOutFk = 13, warehouseInFk = vWh, - shipped = vDateTime, + shipped = vDate, landed = vDate, agencyFk = 53, ref = 'inventario', @@ -40028,7 +41270,7 @@ proc: BEGIN producer, entryFk) SELECT itemFk, - quantity, + GREATEST(quantity,0), buyingValue, freightValue, packing, @@ -42541,6 +43783,30 @@ BEGIN DROP TEMPORARY TABLE tmp.ticketTax; DROP TEMPORARY TABLE tmp.ticketAmount; +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 `itemBarcode_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 = 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 `itemBarcode_update`(vItemFk INT,vCode VARCHAR(22), vDelete BOOL) +BEGIN +IF vDelete THEN + DELETE FROM vn.itemBarcode WHERE itemFk = vItemFk AND code = vCode; +ELSE + INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode); +END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42580,7 +43846,7 @@ BEGIN SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; END IF; - + CALL cache.visible_refresh(vCacheVisibleFk, FALSE,vWarehouseFk); CALL cache.available_refresh(vCacheAvailableFk, FALSE,vWarehouseFk, CURDATE()); @@ -42604,10 +43870,10 @@ BEGIN WHERE ish.itemFk = vItemFk AND s.warehouseFk = vWarehouseFk; */ - SELECT visible INTO vVisibleAltillo + SELECT SUM(visible) INTO vVisibleAltillo FROM vn.itemShelvingStock WHERE itemFk = vItemFk AND warehouseFk = vWarehouseFk; - + CALL vn2008.item_last_buy_(vWarehouseFk,vItemFk); SELECT i.id, @@ -42633,7 +43899,9 @@ BEGIN vVisibleAltillo as enAltillo, v.visible as total, c.`grouping` as `grouping`, - c.Packing as packing + c.Packing as packing, + CONCAT('https://verdnatura.es/vn-image-data/catalog/200x200/', i.image) as urlImage200, + CONCAT('https://verdnatura.es/vn-image-data/catalog/1600x900/', i.image) as urlImage FROM vn.item i LEFT JOIN vn.producer p ON p.id = i.producerFk LEFT JOIN vn.origin o ON o.id = i.originFk @@ -42647,7 +43915,7 @@ BEGIN where b.warehouse_id = vWarehouseFk) c ON i.id= c.item_id WHERE i.id = vItemFk - AND IFNULL(ip.warehouseFk, vWarehouseFk) = vWarehouseFk; + ; DROP TEMPORARY TABLE vn2008.t_item_last_buy; @@ -43012,38 +44280,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 DATE_ADD(CURDATE(), INTERVAl + 10 DAY) - 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 DATE_ADD(CURDATE(), INTERVAl + 10 DAY) + ORDER BY tr.landed DESC , b.id DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43297,43 +44565,6 @@ BEGIN WHERE id = vId AND sectorFk = vSector; -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 `itemPlacementSupplyGetOrder__` */; -/*!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 `itemPlacementSupplyGetOrder__`(vSector INT ) -BEGIN - - DECLARE vId INT; - - SELECT id INTO vId - FROM vn.itemPlacementSupplyList ipsl - WHERE Saldo > 0 - AND (repoUserFk is NULL OR repoUserFk = getUser()) - AND ipsl.sectorFk = vSector - ORDER BY priority DESC, parking DESC, created - LIMIT 1; - - UPDATE vn.itemPlacementSupply - SET repoUserFk = getUser() - WHERE id = vId; - - SELECT * FROM vn.itemPlacementSupplyList - WHERE id = vId - AND sectorFk = vSector; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43378,7 +44609,7 @@ BEGIN `ispss`.`priority` AS `priority`, `ispss`.`parkingFk` AS `parkingFk`, `ispss`.`sectorFk` AS `sectorFk`, - IFNULL(cpd.id,0) as `order` + IFNULL(p.pickingOrder,0) as `order` FROM vn.itemShelvingPlacementSupplyStock ispss JOIN vn.itemShelving ish ON ish.itemFk = vItemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk @@ -44057,10 +45288,33 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingRadar`(vSectorFk INT) BEGIN - DECLARE vWarehouseFk INT; + DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; + DECLARE hasFatherSector BOOLEAN; + DECLARE vBuyerFk INT DEFAULT 0; + DECLARE vWarehouseFk INT DEFAULT 0; + + SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk + FROM vn.worker w + JOIN vn.sector s ON s.code = w.code + WHERE s.id = vSectorFk; + + IF vWarehouseFk = 1 THEN + + SET vSectorFk = 9; + + ELSEIF vWarehouseFk = 44 THEN + + SET vSectorFk = 6; + + END IF; + + SELECT COUNT(*) INTO hasFatherSector + FROM vn.sector + WHERE sonFk = vSectorFk; + SELECT warehouseFk INTO vWarehouseFk FROM vn.sector WHERE id = vSectorFk; @@ -44068,79 +45322,151 @@ BEGIN CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, CURDATE()); - DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; - CREATE TEMPORARY TABLE tmp.itemShelvingRadar - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT iss.itemFk, - 0 `hour`, - 0 `minute`, - ip.`code` itemPlacementCode, - i.longName, - i.size, - i.subName producer, - i.upToDown, - a.available, - IFNULL(v.visible,0) - IFNULL(iss.visible,0) dayEndVisible, - IFNULL(v.visible,0) - IFNULL(iss.visible,0) firstNegative, - IFNULL(v.visible,0) - IFNULL(iss.visible,0) itemPlacementVisible, - i.minimum * b.packing itemPlacementSize, - ips.onTheWay, - iss.visible itemShelvingStock, - IFNULL(v.visible,0) visible, - b.isPickedOff, - iss.sectorFk - FROM vn.itemShelvingStock iss - JOIN vn.item i on i.id = iss.itemFk - LEFT JOIN vn.itemPlacement ip ON ip.itemFk = iss.itemFk AND ip.warehouseFk = vWarehouseFk - LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk - LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk - LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 - GROUP BY itemFk - ) ips ON ips.itemFk = i.id - WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) - AND iss.sectorFk = vSectorFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; - CREATE TEMPORARY TABLE tmp.itemOutTime - SELECT *,SUM(amount) quantity - FROM - (SELECT item_id itemFk, - amount, - IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, - IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes - FROM vn2008.item_out io - JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id - JOIN vn.ticket t on t.id= io.ticketFk - JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk - JOIN vn.state s ON s.id = ts.stateFk - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM vn.saleTracking st - WHERE st.created > CURDATE() - AND st.isChecked - ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk - WHERE t.warehouseFk = vWarehouseFk - AND s.isPicked = 0 - AND NOT io.Reservado - AND stPrevious.saleFk IS NULL - AND io.dat >= CURDATE() - AND io.dat < CURDATE()+1 - ) sub - GROUP BY itemFk, hours, minutes; - - INSERT INTO tmp.itemShelvingRadar (itemFk) - SELECT itemFk FROM tmp.itemOutTime - ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, - firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), - `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), - `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; + + IF hasFatherSector THEN + + CREATE TEMPORARY TABLE tmp.itemShelvingRadar + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT iss.itemFk, + i.longName, + i.size, + i.subName producer, + a.available, + SUM(IF(s.sonFk = vSectorFk, iss.visible, 0)) upstairs, + SUM(IF(iss.sectorFk = vSectorFk, iss.visible, 0)) downstairs, + IFNULL(v.visible,0) as visible, + vSectorFk as sectorFk + + FROM vn.itemShelvingStock iss + JOIN vn.sector s ON s.id = iss.sectorFk + JOIN vn.item i on i.id = iss.itemFk + JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) + LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + WHERE vSectorFk IN (iss.sectorFk, s.sonFk) + GROUP BY iss.itemFk + + UNION ALL + + SELECT v.item_id, + i.longName, + i.size, + i.subName producer, + IFNULL(a.available,0) as available, + 0 upstairs, + 0 downstairs, + v.visible, + vSectorFk as sectorFk + FROM cache.visible v + JOIN vn.item i on i.id = v.item_id + JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) + LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk + LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk + WHERE v.calc_id = vCalcVisibleFk + AND iss.itemFk IS NULL + AND it.isInventory; + + SELECT ishr.*, + CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, + CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente + FROM tmp.itemShelvingRadar ishr + JOIN vn.item i ON i.id = ishr.itemFk + LEFT JOIN (SELECT s.itemFk, sum(s.quantity) as notPickedYed + FROM vn.ticket t + JOIN vn.ticketStateToday tst ON tst.ticket = t.id + JOIN vn.sale s ON s.ticketFk = t.id + WHERE t.warehouseFk = vWarehouseFk + AND tst.alertLevel = 0 + GROUP BY s.itemFk + ) sub ON sub.itemFk = ishr.itemFk + ORDER BY i.typeFk, i.longName + ; + + + ELSE + + CREATE TEMPORARY TABLE tmp.itemShelvingRadar + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT iss.itemFk, + 0 `hour`, + 0 `minute`, + IFNULL(ip.`code`,'--') itemPlacementCode, + i.longName, + i.size, + i.subName producer, + i.upToDown, + IFNULL(a.available,0) available, + IFNULL(v.visible - iss.visible,0) dayEndVisible, + IFNULL(v.visible - iss.visible,0) firstNegative, + IFNULL(v.visible - iss.visible,0) itemPlacementVisible, + IFNULL(i.minimum * b.packing,0) itemPlacementSize, + ips.onTheWay, + iss.visible itemShelvingStock, + IFNULL(v.visible,0) visible, + b.isPickedOff, + iss.sectorFk + FROM vn.itemShelvingStock iss + JOIN vn.item i on i.id = iss.itemFk + LEFT JOIN vn.itemPlacement ip ON ip.itemFk = iss.itemFk AND ip.warehouseFk = vWarehouseFk + LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 + GROUP BY itemFk + ) ips ON ips.itemFk = i.id + WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) + AND iss.sectorFk = vSectorFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; + CREATE TEMPORARY TABLE tmp.itemOutTime + SELECT *,SUM(amount) quantity + FROM + (SELECT item_id itemFk, + amount, + IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, + IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes + FROM vn2008.item_out io + JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id + JOIN vn.ticket t on t.id= io.ticketFk + JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk + JOIN vn.state s ON s.id = ts.stateFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN (SELECT DISTINCT saleFk + FROM vn.saleTracking st + WHERE st.created > CURDATE() + AND st.isChecked + ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk + WHERE t.warehouseFk = vWarehouseFk + AND s.isPicked = 0 + AND NOT io.Reservado + AND stPrevious.saleFk IS NULL + AND io.dat >= CURDATE() + AND io.dat < CURDATE()+1 + ) sub + GROUP BY itemFk, hours, minutes; + + INSERT INTO tmp.itemShelvingRadar (itemFk) + SELECT itemFk FROM tmp.itemOutTime + ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, + firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), + `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), + `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); - SELECT * FROM tmp.itemShelvingRadar; + UPDATE tmp.itemShelvingRadar + SET itemPlacementVisible = 0, + dayEndVisible = 0, + firstNegative = 0 + WHERE itemPlacementVisible = - itemShelvingStock; + + SELECT * FROM tmp.itemShelvingRadar; + + END IF; DROP TEMPORARY TABLE tmp.itemShelvingRadar; @@ -44341,30 +45667,13 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingTransfer`(vItemFk INT,shelvingFkO VARCHAR(22),shelvingFkD VARCHAR(22),vQuantity INT) +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingTransfer`(vItemShelvingFk INT,shelvingFkD VARCHAR(22)) BEGIN - - DECLARE vPacking INT; - DECLARE vDate VARCHAR(22); - - SELECT packing INTO vPacking - FROM vn.itemShelving - WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci AND itemFk = vItemFk - LIMIT 1; - - SELECT created INTO vDate - FROM vn.itemShelving - WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci AND itemFk = vItemFk - LIMIT 1; - - UPDATE vn.itemShelving - SET shelvingFk = shelvingFkD - WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci - AND itemFk = vItemFk - AND visible = ( vPacking * vQuantity ); - - /*CALL vn.itemShelvingMakeFromDate(shelvingFkD,vItemFk,'A',0,( vPacking * vQuantity ),'',0,vPacking,1,1,vDate); */ - + + UPDATE vn.itemShelving + SET shelvingFk = shelvingFkD + WHERE id = vItemShelvingFk; + SELECT true; END ;; @@ -44458,6 +45767,7 @@ BEGIN DECLARE vVisible INT DEFAULT 0; DECLARE vCalc INT; DECLARE vCurrentTime VARCHAR(5); + DECLARE vParkedStuff INT; CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk); @@ -44465,6 +45775,13 @@ BEGIN FROM cache.visible WHERE calc_id = vCalc AND item_id = vItemFk; + + SELECT sum(visible) INTO vParkedStuff + FROM vn.itemShelvingStock + WHERE warehouseFk = vWarehouseFk + AND itemFk = vItemFk; + + SET vNewVisible = vNewVisible + IFNULL(vParkedStuff,0); SELECT IF(vIsTrash,200,400) INTO vClientFk; @@ -44868,9 +46185,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 = 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 ;; @@ -45389,6 +46706,145 @@ 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 PROCEDURE IF EXISTS `kk` */; +/*!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=`z-sysadmin`@`%` PROCEDURE `kk`(IN vItemId INT, IN vWarehouse INT) +BEGIN + DECLARE vDateInventory DATETIME; + DECLARE vCurdate DATE DEFAULT CURDATE(); + DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate); + + SELECT inventoried INTO vDateInventory FROM config; + SET @a = 0; + SET @currentLineFk = 0; + + SELECT @shipped:= shipped, + alertLevel, + stateName, + origin, + reference, + clientFk, + name, + `in`, + `out`, + @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, + @currentLineFk := IF (@shipped < CURDATE() + OR (@shipped =CURDATE() AND isPicked), + lineFk,@currentLineFk) isPicked, + isTicket, + lineFk + FROM + ( SELECT tr.landed as shipped, + b.quantity as `in`, + NULL as `out`, + IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + TRUE isPicked, + FALSE AS isTicket, + b.id lineFk, + NULL `order` + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + JOIN supplier s ON s.id = e.supplierFk + JOIN alertLevel al ON al.alertLevel = + CASE + WHEN tr.isReceived != FALSE THEN 3 + WHEN tr.isDelivered THEN 1 + ELSE 0 + END + JOIN state st ON st.code = al.code + WHERE tr.landed >= vDateInventory + AND vWarehouse = tr.warehouseInFk + AND b.itemFk = vItemId + AND e.isInventory = 0 + AND e.isRaid = 0 + UNION ALL + + SELECT tr.shipped, + NULL as `in`, + b.quantity as `out`, + IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + TRUE isPicked, + FALSE AS isTicket, + b.id, + NULL `order` + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + JOIN warehouse w ON w.id = tr.warehouseOutFk + JOIN supplier s ON s.id = e.supplierFk + JOIN alertLevel al ON al.alertLevel = + CASE + WHEN tr.isReceived != FALSE THEN 3 + WHEN tr.isDelivered THEN 1 + ELSE 0 + END + JOIN state st ON st.code = al.code + WHERE tr.shipped >= vDateInventory + AND vWarehouse =tr.warehouseOutFk + AND s.id <> 4 + AND b.itemFk = vItemId + AND e.isInventory = 0 + AND w.isFeedStock = 0 + AND e.isRaid = 0 + UNION ALL + + SELECT DATE(t.shipped), + NULL as `in`, + s.quantity as `out`, + al.alertLevel as alertLevel, + st.name AS stateName, + t.nickname as name, + t.refFk as reference, + t.id as origin, + t.clientFk, + stk.id as isPicked, + TRUE as isTicket, + s.id, + st.`order` + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN ticketState ts ON ts.ticket = t.id + LEFT JOIN state st ON st.code = ts.code + JOIN client c ON c.id = t.clientFk + JOIN alertLevel al ON al.alertLevel = + CASE + WHEN t.shipped < curdate() THEN 3 + WHEN t.shipped > util.dayEnd(curdate()) THEN 0 + ELSE IFNULL(ts.alertLevel, 0) + END + LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED' + LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = stPrep.id + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemId + AND vWarehouse =t.warehouseFk + ORDER BY shipped, isTicket, alertLevel DESC, `order` DESC, isPicked DESC, `in` DESC, `out` DESC + ) AS itemDiary; + +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 `ledger_next` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -45808,110 +47264,6 @@ BEGIN DROP TEMPORARY TABLE vn2008.Tickets_to_fusion; 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 `mergeTicketWithArray__` */; -/*!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 `mergeTicketWithArray__`(IN vMainTicket INT(11), IN arrayTickets VARCHAR(50)) -BEGIN - - DECLARE isBilled BOOLEAN; - DECLARE messageLog VARCHAR(50); - DECLARE company INT; - DECLARE messageForSplit VARCHAR(255); - DECLARE vMainSplit INT; - DECLARE worker INT(3); - - SELECT Factura IS NOT NULL INTO isBilled FROM vn2008.Tickets WHERE Id_Ticket = vMainTicket; - - IF NOT isBilled THEN - - SELECT Id_Trabajador INTO worker from vn2008.Trabajadores where user_id = account.userGetId(); - IF worker IS NULL THEN - SET worker = 20; - END IF; - - DROP TEMPORARY TABLE IF EXISTS vn2008.Tickets_to_fusion; - - -- He usado el util.exec porque da error la variable strId_Tickets puesta dentro del IN() - CALL util.exec(sql_printf(' - CREATE TEMPORARY TABLE vn2008.Tickets_to_fusion - SELECT Id_Ticket, Localizacion - FROM vn2008.Tickets T - WHERE Id_Ticket IN (%s);',arrayTickets)); - - INSERT INTO vn2008.ticket_observation (Id_Ticket,observation_type_id,text) - SELECT vMainTicket,observation_type_id,CONCAT(' Ticket ', Id_Ticket, ':' , tco.text, '. ') - FROM vn2008.Tickets_to_fusion tf - INNER JOIN vn2008.ticket_observation tco USING(Id_Ticket) - ON DUPLICATE KEY UPDATE `text` = CONCAT(ticket_observation.`text`,CONCAT(' Ticket ', VALUES(Id_Ticket), ':' , VALUES(`text`), '. ')); - - UPDATE vn2008.Movimientos M - JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) - SET M.Id_Ticket = vMainTicket; - - UPDATE vn2008.expeditions M - JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = M.ticket_id - SET M.ticket_id = vMainTicket; - - UPDATE vn.ticketPackaging tp - JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tp.ticketFk - SET tp.ticketFk = vMainTicket; - - UPDATE vn2008.Tickets - SET Bultos = (SELECT COUNT(*) FROM vn2008.expeditions WHERE ticket_id = vMainTicket AND EsBulto) - WHERE Id_Ticket = vMainTicket; - - UPDATE vn2008.Tickets - JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) - SET Fecha = TIMESTAMPADD(YEAR,-1 * (YEAR(Fecha)-2000), Fecha), Id_Ruta = NULL; - - UPDATE vn.ticketLog tl - JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tl.originFk - SET tl.originFk = vMainTicket; - - UPDATE vn2008.Tickets - SET Localizacion = CONCAT(Tickets.Localizacion,' ',IFNULL((SELECT GROUP_CONCAT(Localizacion SEPARATOR ' ') FROM vn2008.Tickets_to_fusion),'')) - WHERE Id_Ticket = vMainTicket; - - UPDATE vn2008.Splits s - RIGHT JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket) - SET s.Id_Ticket = vMainTicket; - - UPDATE vn2008.Ordenes o - RIGHT JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = o.ticketFk - SET o.ticketFk = vMainTicket; - - IF (SELECT COUNT(*) FROM vn2008.Splits WHERE Id_Ticket=vMainTicket) > 1 THEN - - SELECT Id_Split INTO vMainSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket LIMIT 1; - - SELECT group_concat(Notas,',') INTO messageForSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket; - UPDATE vn2008.Splits SET Notas = messageForSplit WHERE Id_Split=vMainSplit; - UPDATE vn2008.Split_lines sl JOIN vn2008.Splits s USING (Id_Split) SET sl.Id_Split=vMainSplit WHERE Id_Ticket=vMainTicket; - DELETE FROM vn2008.Splits WHERE Id_Ticket=vMainTicket AND Id_Split<>vMainSplit; - END IF; - - SELECT GROUP_CONCAT(Id_Ticket SEPARATOR ',') into messageLog FROM vn2008.Tickets_to_fusion; - CALL vn2008.Ditacio(vMainTicket,'Fusion','T',worker,messageLog,NULL); - - DELETE ts FROM vn2008.Tickets_state ts JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket); - - DROP TEMPORARY TABLE vn2008.Tickets_to_fusion; - END IF; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46334,6 +47686,128 @@ BEGIN DECLARE vDateStart DATE DEFAULT '2017-11-21'; DECLARE vIsInvoiceable BOOLEAN; DECLARE vWarehouse INT DEFAULT 13; + DECLARE vComponentCost INT DEFAULT 28; + DECLARE vGraceDate DATE; + + SET vGraceDays = IF(vIsAllInvoiceable,0,30); + SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate); + + /* Clientes especiales: + 3240 MADEFLOR + 992 JAVIER FELIU + 4 TONI VENDRELL + */ + + IF vClient IN (992, 3240, 4) THEN + + SET vGraceDays = 365; + + END IF; + + /* Fin clientes especiales */ + + DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice; + + CREATE TEMPORARY TABLE tmp.packageToInvoice + SELECT p.itemFk, + tp.packagingFk, + IF(tp.quantity < 0 OR t.shipped < vGraceDate, tp.quantity, 0) quantity, + tp.ticketFk, + p.price + FROM ticketPackaging tp + JOIN packaging p ON p.id = tp.packagingFk + JOIN ticket t ON t.id = tp.ticketFk + WHERE t.shipped BETWEEN vDateStart AND vDate + AND t.clientFk = vClient; + + DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoicePositives; + + CREATE TEMPORARY TABLE tmp.packageToInvoicePositives + SELECT itemFk, sum(quantity) as totalQuantity + FROM tmp.packageToInvoice + GROUP BY itemFk + HAVING totalQuantity > 0; + + SELECT GREATEST(COUNT(*),vIsAllInvoiceable) + INTO vIsInvoiceable + FROM tmp.packageToInvoicePositives; + + IF vIsInvoiceable THEN + + CALL vn.ticketCreateWithUser(vClient, vDate, vWarehouse, vCompany, NULL, NULL, NULL, vDate, account.userGetId(), vNewTicket); + + INSERT INTO ticketPackaging( + ticketFk, + packagingFk, + quantity, + pvp) + SELECT vNewTicket, + pti.packagingFk, + - SUM(pti.quantity) AS totalQuantity, + pti.price + FROM tmp.packageToInvoice pti + LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk + WHERE ptip.itemFK IS NOT NULL + OR vIsAllInvoiceable + GROUP BY packagingFk + HAVING totalQuantity; + + INSERT INTO sale( + ticketFk, + itemFk, + concept, + quantity, + price + ) + SELECT vNewTicket, + pti.itemFk, + i.name as concept, + sum(pti.quantity) as totalQuantity, + pti.price + FROM tmp.packageToInvoice pti + JOIN item i ON i.id = pti.itemFk + LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk + WHERE ptip.itemFK IS NOT NULL + OR vIsAllInvoiceable + GROUP BY pti.itemFk + HAVING totalQuantity; + + INSERT INTO saleComponent(saleFk, componentFk, value) + SELECT id, vComponentCost, price + FROM sale + WHERE ticketFk = vNewTicket; + + 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 `packageInvoicing__` */; +/*!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 `packageInvoicing__`( + IN vClient INT, + IN vDate DATE, + IN vCompany INT, + IN vIsAllInvoiceable BOOLEAN, + OUT vNewTicket INT(11) + ) +BEGIN + + DECLARE vGraceDays INT; + DECLARE vDateStart DATE DEFAULT '2017-11-21'; + DECLARE vIsInvoiceable BOOLEAN; + DECLARE vWarehouse INT DEFAULT 13; DECLARE vAgenciaEmbalajes INT DEFAULT 628; DECLARE vComponentCost INT DEFAULT 28; DECLARE vGraceDate DATE; @@ -47362,76 +48836,98 @@ 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); + + +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 `saleMistake_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 `saleMistake_Add`(vSaleFk INT, vUserFk INT, vTypeFk 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); + INSERT INTO vn.saleMistake(saleFk, userFk, typeFk) + VALUES(vSaleFk, vUserFk, vTypeFk); END ;; DELIMITER ; @@ -47524,103 +49020,6 @@ BEGIN 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 `saleMove__` */; -/*!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 `saleMove__`(IN vSaleFk BIGINT, IN vQuantity BIGINT) -BEGIN - - 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 - 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'); - - 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 - LIMIT 1; - -IF vNewTicket IS NULL - THEN - CALL ticketCreate(vclientFk , vShipped , vWarehouseFk , vCompanyFk , vAddressFk , vAgencyModeFk , NULL,vLanded , vNewTicket); - /*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'; - - - /*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 - 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; - -END IF; -END IF; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47679,6 +49078,96 @@ BEGIN WHERE t.id = ticketFk GROUP BY s.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 `salesMerge` */; +/*!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 `salesMerge`(vTicketFk INT) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.salesToPreserve; + + CREATE TEMPORARY TABLE tmp.salesToPreserve + SELECT id, itemFk, sum(quantity) as newQuantity + FROM vn.sale s + WHERE s.ticketFk = vTicketFk + AND s.itemFk NOT IN (95,98,100) + GROUP by itemFk, price, discount; + + UPDATE vn.sale s + JOIN tmp.salesToPreserve stp ON stp.id = s.id + SET quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM vn.sale s + LEFT JOIN tmp.salesToPreserve stp ON stp.id = s.id + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND s.itemFk NOT IN (95,98,100); + +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 `salesMerge_byCollection` */; +/*!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 `salesMerge_byCollection`(vCollectionFk INT) +BEGIN + + DECLARE vDone BOOL; + -- Fetch variables + DECLARE vTicketFk INT; + + DECLARE cCur CURSOR FOR + SELECT ticketFk + FROM vn.ticketCollection + WHERE collectionFk = vCollectionFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + OPEN cCur; + + myLoop: LOOP + + SET vDone = FALSE; + + FETCH cCur INTO vTicketFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + CALL vn.salesMerge(vTicketFk); + + END LOOP; + + CLOSE cCur; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47822,6 +49311,116 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `sale_calculateComponent`(vSale INT, vOption INT) proc: BEGIN +/** + * Actualiza los componentes + * + * @param vSale Delivery date + * @param vOption indica en que componente pone el descuadre, NULL en casos habituales + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vTicketFk BIGINT; + DECLARE vItem BIGINT; + DECLARE vLanded DATE; + DECLARE vIsEditable BOOLEAN; + DECLARE vZoneFk INTEGER; + + SELECT t.refFk IS NULL AND (IFNULL(ts.alertLevel, 0) = 0 OR s.price = 0), + s.ticketFk, + s.itemFk , + t.zoneFk, + t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, + t.landed + INTO vIsEditable, + vTicketFk, + vItem, + vZoneFk, + vWarehouseFk, + vShipped, + vAddressFk, + vAgencyModeFk, + vLanded + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + WHERE s.id = vSale; + + IF vLanded IS NULL OR vZoneFk IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN + CALL util.throw('There is no zone for these parameters'); + END IF; + + UPDATE ticket t + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + WHERE t.id = vTicketFk AND t.landed IS NULL; + + IF vZoneFk IS NULL THEN + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + UPDATE ticket t + SET t.zoneFk = vZoneFk + WHERE t.id = vTicketFk AND t.zoneFk IS NULL; + END IF; + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + IF vOption IS NULL THEN + SET vOption = IF(vIsEditable, 1, 6); + END IF; + + CALL ticketComponentUpdateSale(vOption); + + INSERT INTO ticketLog (originFk, userFk, `action`, description) + VALUES (vTicketFk, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.sale; +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 `sale_calculateComponent__` */; +/*!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 `sale_calculateComponent__`(vSale INT, vOption INT) +proc: BEGIN /** * Actualiza los componentes * @@ -47885,6 +49484,107 @@ proc: BEGIN VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); DROP TEMPORARY TABLE tmp.buyUltimate; +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 `sale_checkNoComponents` */; +/*!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 `sale_checkNoComponents`(vCreatedFrom DATETIME, vCreatedTo DATETIME) +BEGIN +/** + * Comprueba que las ventas creadas entre un rango de fechas tienen componentes + * + * @param vCreatedFrom inicio del rango + * @param vCreatedTo fin del rango + */ + DECLARE v_done BOOL DEFAULT FALSE; + DECLARE vSaleFk INTEGER; + DECLARE vTicketFk INTEGER; + DECLARE vConcept VARCHAR(50); + DECLARE vCur CURSOR FOR + SELECT s.id + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType tp ON tp.id = i.typeFk + JOIN itemCategory ic ON ic.id = tp.categoryFk + LEFT JOIN tmp.coste c ON c.id = s.id + WHERE s.created >= vCreatedFrom AND s.created <= vCreatedTo + AND c.id IS NULL + AND ic.merchandise != FALSE + GROUP BY s.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET v_done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.coste; + + DROP TEMPORARY TABLE IF EXISTS tmp.coste; + CREATE TEMPORARY TABLE tmp.coste + (primary key (id)) ENGINE = MEMORY + SELECT s.id + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType tp ON tp.id = i.typeFk + JOIN itemCategory ic ON ic.id = tp.categoryFk + JOIN saleComponent sc ON sc.saleFk = s.id + JOIN component c ON c.id = sc.componentFk + JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 1 + WHERE s.created >= vCreatedFrom + AND ic.merchandise != FALSE; + + OPEN vCur; + + l: LOOP + SET v_done = FALSE; + FETCH vCur INTO vSaleFk; + + IF v_done THEN + LEAVE l; + END IF; + select ticketFk INTO vTicketFk FROM sale where id = vSaleFk; + select concept INTO vConcept FROM sale where id = vSaleFk; + + CALL util.debug(ticketFk, concept); + -- CALL sale_calculateComponent(vSaleFk, 1); + END LOOP; + + CLOSE vCur; + DROP TEMPORARY TABLE tmp.coste; + 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 `sale_updateOriginalQuantity` */; +/*!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 `sale_updateOriginalQuantity`(vSale INT, vQuantity INT) +proc: BEGIN + +UPDATE vn.sale SET originalQuantity = vQuantity +WHERE id = vSale; + +SELECT * FROM vn.sale WHERE id = vSale; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47925,33 +49625,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 */ ; @@ -47974,6 +49674,29 @@ BEGIN SELECT s.id,s.description,s.warehouseFk FROM vn.sector s; +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 `sector_getWarehouse` */; +/*!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 `sector_getWarehouse`(vSectorFk INT) +BEGIN + + SELECT s.warehouseFk + FROM vn.sector s + WHERE s.id = vSectorFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48256,13 +49979,15 @@ proc: BEGIN IF idParking IS NULL THEN LEAVE proc; - /*IF LOCATE('-',vParkingCode) = 4 THEN - SELECT SUBSTRING_INDEX(vParkingCode,'-',1) INTO vColumn; - SELECT SUBSTRING_INDEX(vParkingCode,'-',-1) INTO vRow; - INSERT INTO vn.parking(`column`,`row`,code,sectorFk) - VALUES(vColumn,vRow,vParkingCode,1); - END IF; - */ + + END IF; + + IF vParkingCode = 'POL-IZON' THEN + + CALL vn.stowaway_launchShip(vShelvingFk); + SELECT TRUE; + LEAVE proc; + END IF; SELECT id INTO vParkingFk @@ -48274,8 +49999,8 @@ proc: BEGIN REPLACE vn.ticketParking(ticketFk,parkingFk) VALUES (vShelvingFk, vParkingFk); -- deprecated: eliminar despues de campaña PAK 2019-10-08 - REPLACE vn.shelving(code, parkingFk, isPrinted, parked) - VALUES(vShelvingFk, vParkingFk, TRUE, NOW()); + -- REPLACE vn.shelving(code, parkingFk, isPrinted, parked) + -- VALUES(vShelvingFk, vParkingFk, TRUE, NOW()); -- fin deprecated CALL vn.ticketStatePrevious(vShelvingFk); @@ -48301,7 +50026,7 @@ 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 PROCEDURE IF EXISTS `shelvingPark_Beta__` */; +/*!50003 DROP PROCEDURE IF EXISTS `shelvingParking_get` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48311,64 +50036,26 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `shelvingPark_Beta__`(IN `vShelvingFk` VARCHAR(8), IN `vParkingCode` VARCHAR(8)) +CREATE DEFINER=`root`@`%` PROCEDURE `shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT) BEGIN - DECLARE vParkingFk INT DEFAULT 0; - DECLARE idParking INT; - DECLARE vColumn VARCHAR(3); - DECLARE vRow VARCHAR(2); - DECLARE vReturn VARCHAR(50); - - /*ELIMINAR ESPACIOS*/ - SET vParkingCode = replace(vParkingCode,' ','') ; - - /*SINO EXISTE EL PARKING LO CREAMOS*/ - SELECT id INTO idParking - FROM vn.parking - WHERE code = vParkingCode COLLATE utf8_unicode_ci; + +SELECT s.itemFk, + s.concept, + CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, + CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado + FROM vn.sale s + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + JOIN vn.ticket t ON t.id = s.ticketFk + LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk + JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + WHERE t.shipped BETWEEN CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), CURDATE())) + AND iss.saleFk IS NULL + AND t.warehouseFk = vWarehouseFk + GROUP BY s.itemFk + HAVING sinServir > aparcado; + - IF idParking IS NULL THEN - IF LOCATE('-',vParkingCode) = 4 THEN - SELECT SUBSTRING_INDEX(vParkingCode,'-',1) INTO vColumn; - SELECT SUBSTRING_INDEX(vParkingCode,'-',-1) INTO vRow; - INSERT INTO vn.parking(`column`,`row`,code,sectorFk) - VALUES(vColumn,vRow,vParkingCode,2); - END IF; - END IF; - /*FIN INSERTAR PARKING*/ - - - SELECT id INTO vParkingFk - FROM vn.parking - WHERE `code` = vParkingCode COLLATE utf8_unicode_ci; - - IF length(vShelvingFk) > 6 THEN - - REPLACE vn.ticketParking(ticketFk,parkingFk) - VALUES (vShelvingFk, vParkingFk); - - REPLACE vn.shelving(code, parkingFk, isPrinted, parked) - VALUES(vShelvingFk, vParkingFk, TRUE, NOW()); - - CALL vn.ticketStatePrevious(vShelvingFk); - - ELSE - - - UPDATE vn.shelving - SET parkingFk = vParkingFk, parked = NOW() - WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; - - SELECT (COUNT(*) > 0) AS IsUpdated - FROM vn.shelving - WHERE parkingFk = vParkingFk - AND `code` = vShelvingFk COLLATE utf8_unicode_ci; - - END IF; - - - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48391,6 +50078,10 @@ BEGIN DELETE FROM vn.shelving WHERE length(code) > 3 AND parked < TIMESTAMPADD(WEEK,-1,CURDATE()); + + DELETE FROM vn.itemShelving + WHERE visible <= 0 + AND created < TIMESTAMPADD(MONTH,-1,CURDATE()); UPDATE vn.shelving sh LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code` @@ -48693,6 +50384,40 @@ 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 PROCEDURE IF EXISTS `stowaway_launchShip` */; +/*!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 `stowaway_launchShip`(vStowawayFk INT) +BEGIN + + DECLARE myShipFk INT; + + SELECT shipFk INTO myShipFk + FROM vn.stowaway + WHERE id = vStowawayFk; + + IF myShipFk THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, myShipFk, myWorker_getId() + FROM state + WHERE code = 'OK STOWAWAY'; + + 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 `stowaway_unboarding` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -49012,29 +50737,6 @@ 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 PROCEDURE IF EXISTS `ticketCalculate` */; -/*!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 `ticketCalculate`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN --- OBSOLETO utilizar catalog_calculate - CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); -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 `ticketCalculateClon` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -49046,6 +50748,106 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT) +BEGIN +/* + * Recalcula los componentes un ticket clonado, + * las lineas a precio cero fuerza para que tengan precio, el resto lo respeta + * @param vTicketNew nuevo ticket clonado + * @param vTicketOld icket original, a partir del qual se clonara el nuevo +*/ + DECLARE vShipped DATE; + DECLARE vClient INT; + DECLARE vWarehouse SMALLINT; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; + DECLARE vLanded DATE; + DECLARE vAgency INT; + DECLARE vZoneFk INT; + + REPLACE INTO orderTicket(orderFk,ticketFk) + SELECT orderFk, vTicketNew + FROM orderTicket + WHERE ticketFk = vTicketOld; + + SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk + INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicketNew; + + IF vLanded IS NULL THEN + CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); + UPDATE ticket t + JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk + SET t.landed = zgl.landed, + t.zone = zgl.zoneFk + WHERE t.id = vTicketNew; + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + END IF; + + -- rellena la tabla tmp.buyUltimate con la ultima compra + CALL buyUltimate(vWarehouse, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode, vWarehouse); + + -- Bionizamos lineas con Preu = 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT s.id saleFk, vWarehouse warehouseFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0; + + CALL ticketComponentUpdateSale(1); + + -- Bionizamos lineas con Preu > 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT s.id saleFk, vWarehouse warehouseFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew + AND s.price > 0; + + CALL ticketComponentUpdateSale(6); + + -- Log + CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); + + -- Limpieza + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE IF EXISTS + tmp.buyUltimate, + tmp.sale, + tmp.zoneGetLanded; + +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 `ticketCalculateClon__` */; +/*!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 `ticketCalculateClon__`(IN vTicketNew INT, vTicketOld INT) BEGIN /* * @vTicketNew id del nuevo ticket clonado @@ -49186,7 +50988,7 @@ 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 PROCEDURE IF EXISTS `ticketCalculateSale` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateSaleForcePrice2__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -49196,77 +50998,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale`(IN vSale BIGINT) -proc: BEGIN --- OBSOLETO USAR: sale_calculateComponent(vSale, NULL) - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vTicket BIGINT; - DECLARE vItem BIGINT; - DECLARE vLanded DATE; - DECLARE vTicketFree BOOLEAN DEFAULT TRUE; - DECLARE vZoneFk INTEGER; - - SELECT NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk - INTO vTicketFree, vTicket, vItem, vZoneFk - FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - WHERE s.id = vSale - LIMIT 1; - - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM agencyMode a - JOIN ticket t ON t.agencyModeFk = a.id - WHERE t.id = vTicket; - - IF IFNULL(vZoneFk,0) = 0 THEN - CALL util.throw('ticket dont have zone'); - END IF; - - CALL buyUltimate (vWarehouseFk, vShipped); - - DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk - FROM tmp.buyUltimate - WHERE itemFk = vItem; - - CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT vSale saleFk,vWarehouseFk warehouseFk; - - CALL ticketComponentUpdateSale(IF(vTicketFree,1,6)); - - INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) - VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); - - DROP TEMPORARY TABLE tmp.buyUltimate; -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 `ticketCalculateSaleForcePrice` */; -/*!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 `ticketCalculateSaleForcePrice`(IN vSale BIGINT) +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice2__`(IN vSale BIGINT) proc: BEGIN DECLARE vShipped DATE; @@ -49274,8 +51006,8 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vTicket BIGINT; DECLARE vItem BIGINT; - DECLARE vZoneFk INT; - + DECLARE vZoneFk INT; + SELECT ticketFk, itemFk INTO vTicket, vItem FROM sale @@ -49320,7 +51052,7 @@ 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 PROCEDURE IF EXISTS `ticketCalculateSaleForcePrice2` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateSaleForcePrice__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -49330,7 +51062,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice2`(IN vSale BIGINT) +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice__`(IN vSale BIGINT) proc: BEGIN DECLARE vShipped DATE; @@ -49338,8 +51070,8 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vTicket BIGINT; DECLARE vItem BIGINT; - DECLARE vZoneFk INT; - + DECLARE vZoneFk INT; + SELECT ticketFk, itemFk INTO vTicket, vItem FROM sale @@ -49396,7 +51128,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale__`(IN vSale BIGINT) proc: BEGIN - +-- OBSOLETO USAR: sale_calculateComponent(vSale, NULL) DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; @@ -49407,35 +51139,22 @@ proc: BEGIN DECLARE vTicketFree BOOLEAN DEFAULT TRUE; DECLARE vZoneFk INTEGER; - SELECT FALSE - INTO vTicketFree + SELECT NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk + INTO vTicketFree, vTicket, vItem, vZoneFk FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id WHERE s.id = vSale - AND (t.refFk != "" OR (ts.alertLevel > 0 AND s.price != 0)) LIMIT 1; - - SELECT ticketFk, itemFk - INTO vTicket, vItem - FROM sale - WHERE id = vSale; SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded FROM agencyMode a JOIN ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicket; - - CALL zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - SELECT id INTO vZoneFk - FROM tmp.zoneGetShipped - WHERE warehouseFk = vWarehouseFk - AND shipped = vShipped; IF IFNULL(vZoneFk,0) = 0 THEN - CALL util.throw('not zone with this parameters'); + CALL util.throw('ticket dont have zone'); END IF; CALL buyUltimate (vWarehouseFk, vShipped); @@ -49444,11 +51163,12 @@ proc: BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk, vZoneFk zoneFk FROM tmp.buyUltimate WHERE itemFk = vItem; - CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + CALL vn.catalog_componentCalculate; + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -49460,7 +51180,33 @@ proc: BEGIN INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + CALL catalog_componentPurge(); DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + +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 `ticketCalculate__` */; +/*!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 `ticketCalculate__`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +-- OBSOLETO utilizar catalog_calculate + CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49921,9 +51667,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 = 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 ;; @@ -49931,9 +51677,8 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCollection_get`(vTicketFk INT) BEGIN SELECT collectionFk - FROM vn.collectionReportSource - WHERE ticketFk = vTicketFk - GROUP BY collectionFk; + FROM vn.ticketCollection + WHERE ticketFk = vTicketFk; END ;; DELIMITER ; @@ -50047,23 +51792,23 @@ BEGIN SET vRenewComponents = TRUE; SET vKeepPrices = FALSE; WHEN 2 THEN - SET vComponentFk = 17; + SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; WHEN 3 THEN - SET vComponentFk = 37; + SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; WHEN 4 THEN - SET vComponentFk = 34; + SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - WHEN 5 THEN + /* WHEN 5 THEN SET vComponentFk = 35; SET vRenewComponents = TRUE; - SET vKeepPrices = TRUE; + SET vKeepPrices = TRUE;*/ WHEN 6 THEN - SET vComponentFk = 36; + SELECT id INTO vComponentFk FROM component WHERE `code` = 'imbalance'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; WHEN 7 THEN @@ -51333,7 +53078,6 @@ BEGIN DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vCompanyFk INT; - DECLARE vAgenciaEmbalajesFk INT DEFAULT 628; DECLARE rs CURSOR FOR SELECT DISTINCT tp.ticketFk, a.clientFk, t.warehouseFk, t.shipped, t.companyFk @@ -51835,13 +53579,96 @@ 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 PROCEDURE IF EXISTS `ticket_checkNoComponents__` */; +/*!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 `ticket_checkNoComponents__`(vShippedFrom DATETIME, vShippedTo DATETIME) +BEGIN + +/** + * Comprueba que los tickets entre un rango de fechas tienen componentes + * + * @param vShippedFrom inicio del rango + * @param vShippedTo fin del rango + */ + DECLARE v_done BOOL DEFAULT FALSE; + DECLARE vSaleFk INTEGER; + DECLARE vTicketFk INTEGER; + DECLARE vConcept VARCHAR(50); + DECLARE vCur CURSOR FOR + SELECT s.id + FROM ticket t + JOIN client clt ON clt.id = t.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType tp ON tp.id = i.typeFk + JOIN itemCategory ic ON ic.id = tp.categoryFk + LEFT JOIN tmp.coste c ON c.id = s.id + WHERE t.shipped >= vShippedFrom AND t.shipped <= vShippedTo + AND c.id IS NULL + AND clt.isActive != 0 + AND ic.merchandise != 0 + GROUP BY s.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET v_done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.coste; + + DROP TEMPORARY TABLE IF EXISTS tmp.coste; + CREATE TEMPORARY TABLE tmp.coste + (primary key (id)) ENGINE = MEMORY + SELECT s.id + FROM ticket t + JOIN client clt ON clt.id = t.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType tp ON tp.id = i.typeFk + JOIN itemCategory ic ON ic.id = tp.categoryFk + JOIN saleComponent sc ON sc.saleFk = s.id + JOIN component c ON c.id = sc.componentFk + JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 1 + WHERE t.shipped >= vShippedFrom + AND ic.merchandise != 0; + + OPEN vCur; + + l: LOOP + SET v_done = FALSE; + FETCH vCur INTO vSaleFk; + + IF v_done THEN + LEAVE l; + END IF; + select ticketFk INTO vTicketFk FROM sale where id = vSaleFk; + select concept INTO vConcept FROM sale where id = vSaleFk; + + CALL util.debug(ticketFk, concept); + -- CALL sale_calculateComponent(vSaleFk, 1); + END LOOP; + + CLOSE vCur; + DROP TEMPORARY TABLE tmp.coste; + 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 `ticket_Clone` */; /*!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 ;; @@ -51856,20 +53683,24 @@ BEGIN warehouseFk, companyFk, landed, - zoneFk + zoneFk, + zonePrice, + zoneBonus ) SELECT - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - companyFk, - landed, - zoneFk - FROM ticket - WHERE id = vOriginalTicket; + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus + FROM ticket + WHERE id = vOriginalTicket; SET vNewTicket = LAST_INSERT_ID(); @@ -51901,38 +53732,103 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentMakeUpdate`( vTicketFk INT, - vClientFk INT, + vClientFk INT, vAgencyModeFk INT, vAddressFk INT, - vZoneFk INT, + vZoneFk INT, vWarehouseFk TINYINT, - vCompanyFk SMALLINT, + vCompanyFk SMALLINT, vShipped DATETIME, vLanded DATE, - vIsDeleted BOOLEAN, - vHasToBeUnrouted BOOLEAN, + vIsDeleted BOOLEAN, + vHasToBeUnrouted BOOLEAN, vOption INT) BEGIN +/** + * Modifica en el ticket los campos que se le pasan por parámetro + * y cambia sus componentes + * + * @param vTicketFk Id del ticket a modificar + * @param vClientFk nuevo cliente + * @param vAgencyModeFk nueva agencia + * @param vAddressFk nuevo consignatario + * @param vZoneFk nueva zona + * @param vWarehouseFk nuevo almacen + * @param vCompanyFk nueva empresa + * @param vShipped nueva fecha del envio de mercancia + * @param vLanded nueva fecha de recepcion de mercancia + * @param vIsDeleted si se borra el ticket + * @param vHasToBeUnrouted si se le elimina la ruta al ticket + * @param vOption opcion para el case del proc ticketComponentUpdateSale + */ + DECLARE vPrice DECIMAL(10,2); + DECLARE vBonus DECIMAL(10,2); + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; - CALL vn.ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); - CALL vn.ticket_componentUpdate ( - vTicketFk, - vClientFk, - vAgencyModeFk, - vAddressFk, - vZoneFk, - vWarehouseFk, - vCompanyFk, - vShipped, - vLanded, - vIsDeleted, - vHasToBeUnrouted, - vOption - ); + CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); - DROP TEMPORARY TABLE - tmp.ticketComponent, - tmp.ticketComponentPrice; + START TRANSACTION; + + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN + + UPDATE ticket t + JOIN address a ON a.id = vAddressFk + SET t.nickname = a.nickname + WHERE t.id = vTicketFk; + + END IF; + + CALL zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); + + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + UPDATE ticket t + SET + t.clientFk = vClientFk, + t.agencyModeFk = vAgencyModeFk, + t.addressFk = vAddressFk, + t.zoneFk = vZoneFk, + t.zonePrice = vPrice, + t.zoneBonus = vBonus, + t.warehouseFk = vWarehouseFk, + t.companyFk = vCompanyFk, + t.landed = vLanded, + t.shipped = vShipped, + t.isDeleted = vIsDeleted + WHERE + t.id = vTicketFk; + + IF vHasToBeUnrouted THEN + UPDATE ticket t SET t.routeFk = NULL + WHERE t.id = vTicketFk; + END IF; + + IF vOption <> 8 THEN + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) + ENGINE = MEMORY + SELECT id AS saleFk, vWarehouseFk warehouseFk + FROM sale s WHERE s.ticketFk = vTicketFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent + SELECT * FROM tmp.ticketComponentPreview; + + CALL ticketComponentUpdateSale (vOption); + + DROP TEMPORARY TABLE tmp.sale; + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + END IF; + COMMIT; + + DROP TEMPORARY TABLE tmp.zoneGetShipped, tmp.ticketComponentPreview; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51943,9 +53839,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 = 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 ;; @@ -51956,6 +53852,126 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentPreview`( vZoneFk INT, vWarehouseFk SMALLINT) BEGIN +/** + * Calcula los componentes de los articulos de un ticket + * + * @param vTicketFk id del ticket + * @param vLanded nueva fecha de entrega + * @param vAddressFk nuevo consignatario + * @param vZoneFk nueva zona + * @param vWarehouseFk nuevo warehouse + * + * @return tmp.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost) + */ + DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasAddressChanged BOOL; + DECLARE vHasZoneChanged BOOL DEFAULT FALSE; + DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; + + DECLARE vShipped DATE; + DECLARE vAddressTypeRateFk INT DEFAULT NULL; + DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL; + + DECLARE vHasChangeAll BOOL DEFAULT FALSE; + + SELECT DATE(landed) <> vLanded, + addressFk <> vAddressFk, + zoneFk <> vZoneFk, + warehouseFk <> vWarehouseFk + INTO + vHasDataChanged, + vHasAddressChanged, + vHasZoneChanged, + vHasWarehouseChanged + FROM vn.ticket t + WHERE t.id = vTicketFk; + + IF vHasDataChanged OR vHasWarehouseChanged THEN + SET vHasChangeAll = TRUE; + END IF; + + IF vHasAddressChanged THEN + SET vAddressTypeRateFk = 5; + END IF; + + IF vHasZoneChanged THEN + SET vAgencyModeTypeRateFk = 6; + END IF; + + SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped + FROM zone + WHERE id = vZoneFk; + + CALL buyUltimate(vWarehouseFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + SELECT + vWarehouseFk AS warehouseFk, + NULL AS available, + s.itemFk, + bu.buyFk, + vZoneFk zoneFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY bu.warehouseFk, bu.itemFk); + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + REPLACE INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT t.warehouseFk, s.itemFk, sc.componentFk, sc.value + FROM saleComponent sc + JOIN sale s ON s.id = sc.saleFk + JOIN ticket t ON t.id = s.ticketFk + JOIN `component` c ON c.id = sc.componentFk + WHERE s.ticketFk = vTicketFk + AND (c.isRenewable = FALSE + OR + (NOT vHasChangeAll + AND (NOT (c.typeFk <=> vAddressTypeRateFk + OR c.typeFk <=> vAgencyModeTypeRateFk)))); + + SET @shipped = vShipped; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPreview; + CREATE TEMPORARY TABLE tmp.ticketComponentPreview + SELECT * FROM tmp.ticketComponent; + + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE tmp.buyUltimate; + + IF vShipped IS NULL THEN + CALL util.throw('NO_ZONE_AVAILABLE'); + END IF; + + IF vShipped < CURDATE() THEN + CALL util.throw('ERROR_PAST_SHIPMENT'); + 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 `ticket_componentPreview__` */; +/*!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 `ticket_componentPreview__`( + vTicketFk INT, + vLanded DATE, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk SMALLINT) +BEGIN /** * Calcula los componentes de los articulos de un ticket * @@ -52057,7 +54073,7 @@ 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 PROCEDURE IF EXISTS `ticket_componentUpdate` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_componentUpdate__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -52067,7 +54083,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentUpdate`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentUpdate__`( vTicketFk INT, vClientFk INT, vAgencyModeFk INT, @@ -52146,6 +54162,26 @@ 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 PROCEDURE IF EXISTS `ticket_getShip` */; +/*!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 `ticket_getShip`(vTicketFk INT) +BEGIN + SELECT s.shipFk FROM vn.stowaway s + WHERE s.id = vTicketFk; +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 `ticket_getTax` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -52278,7 +54314,7 @@ BEGIN DECLARE vWarehouseFk INT; DECLARE vCursor CURSOR FOR SELECT id, landed, addressFk, agencyModeFk, warehouseFk - FROM vn.ticket WHERE shipped BETWEEN '2019-10-20' and '2019-11-01' AND zoneFk is null; + FROM vn.ticket WHERE shipped > '2020-01-01' AND zoneFk is null; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1; OPEN vCursor; @@ -52305,9 +54341,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 = 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 ;; @@ -52319,8 +54355,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticket_priceDifference`( vWarehouseFk INT) BEGIN /** - * Devuelve las diferencias de precio - * de los movimientos de un ticket. + * Devuelve las diferencias de precio de los movimientos de un ticket. * * @param vTicketFk Id del ticket * @param vLanded Fecha de recepcion @@ -52342,20 +54377,17 @@ BEGIN FROM sale s JOIN item i ON i.id = s.itemFk JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk + LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = t.warehouseFk LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk LEFT JOIN `component` c ON c.id = tc.componentFk - WHERE - t.id = vTicketFk + WHERE t.id = vTicketFk AND IF(sc.componentFk IS NULL - AND c.classRate IS NOT NULL, FALSE, TRUE) + AND c.classRate IS NOT NULL, FALSE, TRUE) GROUP BY s.id ORDER BY s.id; - DROP TEMPORARY TABLE - tmp.ticketComponent, - tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponentPreview; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52372,15 +54404,15 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT ) +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT) proc: BEGIN /** - * Este procedimiento trata de "rebionizar" un ticket, + * Este procedimiento recalcula los componentes de un ticket, * eliminando los componentes existentes e insertandolos de nuevo * * @param vTicketFk Id del ticket - * @return tmp.buyUltimate + * @param vIsTicketEditable si no se quiere forzar llamar con NULL */ DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; @@ -52389,141 +54421,69 @@ proc: BEGIN DECLARE vLanded DATE; DECLARE vIsTicketEditable BOOLEAN; DECLARE vZoneFk INTEGER; - - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk + + SELECT t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, + t.landed, + IFNULL(ts.alertLevel,0) = 0 AND IFNULL(t.refFk,'') = '' , + t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded, vIsTicketEditable, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; + WHERE t.id = vTicketFk; + + IF vLanded IS NULL OR vZoneFk IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN + CALL util.throw('There is no zone for these parameters'); + END IF; + + UPDATE ticket t + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + WHERE t.id = vTicketFk AND t.landed IS NULL; + + IF vZoneFk IS NULL THEN + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + UPDATE ticket t + SET t.zoneFk = vZoneFk + WHERE t.id = vTicketFk AND t.zoneFk IS NULL; + END IF; + DROP TEMPORARY TABLE tmp.zoneGetLanded; - CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios - - IF vLanded IS NULL THEN - - CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; -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 `ticket_recalcComponentsForcePrice` */; -/*!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 `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) -proc: BEGIN - -/** - * Este procedimiento trata de "rebionizar" un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @return tmp.buyUltimate - */ - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vLanded DATE; - DECLARE vZoneFk INTEGER; - - IF vIsTicketEditable IS NULL THEN - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; END IF; - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; - - CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, TRUE); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk + s.itemFk, bu.buyFk, vZoneFk zoneFk FROM sale s LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk WHERE s.ticketFk = vTicketFk GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + -- si el ticket esta facturado, respeta los precios + CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6)); - IF vLanded IS NULL THEN - - CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE + tmp.buyUltimate, + tmp.sale; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52567,8 +54527,8 @@ proc: BEGIN INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded FROM ticket WHERE id = vTicketFk; - - CALL zone_getShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); + + CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, TRUE); CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra @@ -52652,7 +54612,7 @@ proc: BEGIN FROM ticket WHERE id = vTicketFk; - CALL zone_getShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); + CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra @@ -52698,76 +54658,6 @@ 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 PROCEDURE IF EXISTS `ticket_withoutComponents` */; -/*!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 `ticket_withoutComponents`(vDatedFrom DATETIME, vDatedTo DATETIME) -BEGIN - DECLARE v_done BOOL DEFAULT FALSE; - DECLARE vSaleFk INTEGER; - DECLARE vCur CURSOR FOR - SELECT s.id - FROM vn.ticket t - JOIN vn.client clt ON clt.id = t.clientFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType tp ON tp.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = tp.categoryFk - LEFT JOIN tmp.coste c ON c.id = s.id - WHERE t.shipped >= vDatedFrom AND t.shipped <= vDatedTo - AND c.id IS NULL - AND clt.isActive != 0 - AND ic.merchandise != 0 - GROUP BY s.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.coste; - - DROP TEMPORARY TABLE IF EXISTS tmp.coste; - CREATE TEMPORARY TABLE tmp.coste - (primary key (id)) ENGINE = MEMORY - SELECT s.id - FROM vn.ticket t - JOIN vn.client clt ON clt.id = t.clientFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType tp ON tp.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = tp.categoryFk - JOIN vn.saleComponent sc ON sc.saleFk = s.id - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.id = 1 - WHERE t.shipped >= vDatedFrom - AND ic.merchandise != 0; - - OPEN vCur; - - l: LOOP - SET v_done = FALSE; - FETCH vCur INTO vSaleFk; - - IF v_done THEN - LEAVE l; - END IF; - - CALL vn.ticketCalculateSaleForcePrice2(vSaleFk); - END LOOP; - - CLOSE vCur; - 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 `timeBusiness_calculate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -53640,6 +55530,66 @@ BEGIN CALL vn.warehouseFitting(vWhOrigin, vWhDestiny); +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 `weight_Put` */; +/*!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 `weight_Put`() +BEGIN + + SET @isModeInventory := TRUE; + + CALL cache.last_buy_refresh(TRUE); + + DROP TEMPORARY TABLE IF EXISTS tmp.peso; + + CREATE TEMPORARY TABLE tmp.peso + SELECT lb.item_id, + i.longName, + lb.warehouse_id, + b.weight, + it.gramsMin * b.packing / 1000 as pesMin, + it.gramsMax * b.packing / 1000 as pesMax, + b.entryFk, + CAST(GREATEST(it.gramsMin * b.packing / 1000 , LEAST(IFNULL(b.weight, (it.gramsMax - it.gramsMin) * b.packing / 1000 / 2) , it.gramsMax * b.packing / 1000)) as decimal(10,2)) pesocorrecto + FROM cache.last_buy lb + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.intrastat itr ON itr.id = i.intrastatFk + HAVING pesocorrecto > 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.buyTochange; + + CREATE TEMPORARY TABLE tmp.buyTochange + SELECT DISTINCT b.id, b.itemFk, b.entryFk + FROM cache.last_buy lb + JOIN vn.buy b ON b.id = lb.buy_id + JOIN (SELECT DISTINCT item_id itemFk FROM tmp.peso) sub using(itemFk) + WHERE b.weight is null; + + UPDATE tmp.buyTochange btc + JOIN vn.buy b ON b.id = btc.id + JOIN (SELECT item_id , pesocorrecto FROM tmp.peso GROUP BY item_id) p ON p.item_id = b.itemFk + SET b.weight = p.pesocorrecto; + + UPDATE vn.itemCost ic + JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + SET ic.grams = b.weight * 1000 / b.packing; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53790,7 +55740,8 @@ BEGIN d.id as departmentFk, b.date_start, d.isProduction, - CAST(12 * blp.importepactado / clt.hours_week / 52 AS DECIMAL(10,2)) as costeHora + CAST(12 * blp.importepactado / clt.hours_week / 52 AS DECIMAL(10,2)) as costeHora , + p.nif FROM postgresql.person p JOIN postgresql.profile pr ON p.person_id = pr.person_id @@ -56331,19 +58282,17 @@ CREATE DEFINER=`root`@`%` PROCEDURE `zone_doCalcInitialize`() proc: BEGIN /** * Initialize ticket - * si en 01-07-20 aun esta este proc, kkear */ DECLARE vDone BOOL; - DECLARE vTicketFk INT; DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE cCur CURSOR FOR - SELECT t.id, t.landed, t.zoneFk + SELECT t.landed, t.zoneFk FROM ticket t - WHERE shipped >= '2020-01-01' AND shipped <= '2020-01-31' - AND zoneFk in (34, 43,51,55,66) - GROUP BY landed, zoneFk; + WHERE shipped >= '2020-03-01' + AND zoneFk IS NOT NULL and zonePrice IS NULL + GROUP BY zoneFk, shipped; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -56352,7 +58301,7 @@ proc: BEGIN myLoop: LOOP SET vDone = FALSE; - FETCH cCur INTO vTicketFk, vLanded, vZoneFk; + FETCH cCur INTO vLanded, vZoneFk; IF vDone THEN LEAVE myLoop; @@ -56369,8 +58318,8 @@ proc: BEGIN UPDATE ticket t LEFT JOIN tmp.zoneOption zo ON TRUE SET zonePrice = zo.price, zoneBonus = zo.bonus - WHERE t.zoneFk = vZoneFk AND landed = vLanded; - + WHERE t.zoneFk = vZoneFk AND t.landed = vLanded + AND t.zonePrice IS NULL; END LOOP; @@ -56386,9 +58335,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 ;; @@ -56400,31 +58349,30 @@ BEGIN * * @param vAddress Id de dirección de envío, %NULL si es recogida * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles + * @return tmp.zoneGetAgency Listado de agencias disponibles */ - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded, FALSE); + CALL zone_getOptionsForLanding(vLanded, FALSE); DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; CREATE TEMPORARY TABLE tmp.zoneGetAgency - (INDEX (agencyModeFk)) ENGINE = MEMORY + (INDEX (agencyModeFk)) ENGINE = MEMORY SELECT am.name agencyMode, - am.description, - z.agencyModeFk, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - TRUE isIncluded, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - GROUP BY agencyModeFk; - + am.description, + z.agencyModeFk, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + TRUE isIncluded, + zo.zoneFk, + am.web AS isVisible + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + GROUP BY agencyModeFk; + DROP TEMPORARY TABLE tmp.zone, - tmp.zoneOption; - + tmp.zoneOption; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56468,6 +58416,79 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`( + vGeoFk INT, + vAgencyModeFk INT) +BEGIN +/** + * Returns available events for the passed province/postcode and agency. + * + * @param vGeoFk The geo id + * @param vAgencyModeFk The agency mode id + */ + DECLARE vDeliveryMethodFk VARCHAR(255); + + DROP TEMPORARY TABLE IF EXISTS tZone; + CREATE TEMPORARY TABLE tZone + (id INT PRIMARY KEY) + ENGINE = MEMORY; + + SELECT dm.`code` INTO vDeliveryMethodFk + FROM agencyMode am + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE am.id = vAgencyModeFk; + + IF vDeliveryMethodFk = 'PICKUP' THEN + INSERT INTO tZone + SELECT id + FROM zone + WHERE agencyModeFk = vAgencyModeFk; + ELSE + CALL zone_getFromGeo(vGeoFk); + + IF vAgencyModeFk IS NOT NULL THEN + INSERT INTO tZone + SELECT t.id + FROM tmp.zone t + JOIN zone z ON z.id = t.id + WHERE z.agencyModeFk = vAgencyModeFk; + ELSE + INSERT INTO tZone + SELECT t.id + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE dm.`code` IN ('AGENCY', 'DELIVERY'); + END IF; + DROP TEMPORARY TABLE tmp.zone; + END IF; + + SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays + FROM tZone t + JOIN zoneEvent e ON e.zoneFk = t.id; + + SELECT e.zoneFk, e.dated + FROM tZone t + JOIN zoneExclusion e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE tZone; +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 `zone_getEvents__` */; +/*!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 `zone_getEvents__`( vProvinceFk INT, vPostCode VARCHAR(255), vAgencyModeFk INT) @@ -56479,6 +58500,7 @@ BEGIN * @param vProvinceFk The province id * @param vPostCode The postcode or %NULL to use the province */ + DECLARE vGeoFk INT; IF vPostCode IS NOT NULL THEN @@ -57195,6 +59217,56 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha, + * dirección y almacén pasados. + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded, FALSE); + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.id zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + WHERE zw.warehouseFk = vWarehouse + GROUP BY z.agencyModeFk + ORDER BY agencyMode; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +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 `zone_getWarehouse__` */; +/*!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 `zone_getWarehouse__`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN /** * Devuelve el listado de agencias disponibles para la fecha, * dirección y almacén pasados. @@ -57226,6 +59298,7 @@ BEGIN DROP TEMPORARY TABLE tmp.zone, tmp.zoneOption; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57302,9 +59375,9 @@ CREATE TABLE `inter` ( /*!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 ;; @@ -57314,6 +59387,8 @@ DELIMITER ;; BEGIN DECLARE vState VARCHAR(15); DECLARE vZoneFk INT; + DECLARE vHasStowAway BOOLEAN; + DECLARE vBoardingStateFk INT; SELECT s.code INTO vState FROM vn.state s @@ -57326,6 +59401,25 @@ BEGIN IF vState = 'OK' AND vZoneFk IS NULL THEN CALL util.throw("ASSIGN_ZONE_FIRST"); END IF; + + IF vState IN ('OK','FREE') THEN + + SELECT COUNT(*) INTO vHasStowAway + FROM vn.stowaway + WHERE shipFk = NEW.Id_Ticket; + + IF vHasStowAway THEN + + SELECT id INTO vBoardingStateFk + FROM vn.state + WHERE `code`= 'BOARDING'; + + SET NEW.state_id = vBoardingStateFk; + + END IF; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58291,6 +60385,24 @@ USE `util`; USE `vn`; +-- +-- Final view structure for view `__coolerPathDetail` +-- + +/*!50001 DROP VIEW IF EXISTS `__coolerPathDetail`*/; +/*!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 `__coolerPathDetail` AS select `c`.`cooler_path_detail_id` AS `id`,`c`.`cooler_path_id` AS `coolerPathFk`,`c`.`pasillo` AS `hallway` from `vn2008`.`cooler_path_detail` `c` */; +/*!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 `absenceType` -- @@ -58412,7 +60524,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`t`.`addressFk` AS `addressFk`,`t`.`shipped` AS `shipped`,`a`.`nickname` AS `clientName`,`a`.`postalCode` AS `clientPostalCode`,`a`.`street` AS `clientStreet`,`a`.`city` AS `clientCity`,`p`.`name` AS `clientProvince`,`co`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode__` AS `companyPostCode`,`su`.`city` AS `companyCity`,`sc`.`country` AS `companyCountry`,`w`.`addressName` AS `warehouseAddress`,`c`.`name` AS `clientOficialName`,ifnull(`ags`.`name`,`agm`.`name`) AS `carrierName`,`ags`.`street` AS `carrierStreet`,`ags`.`postCode` AS `carrierPostCode`,`ags`.`city` AS `carrierCity`,`sco`.`country` AS `carrierCountry`,ifnull(`a`.`phone`,`c`.`phone`) AS `phone`,ifnull(`a`.`mobile`,`c`.`mobile`) AS `mobile` from ((((((((((((`cmr` join `ticket` `t` on((`t`.`id` = `cmr`.`ticketFk`))) join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) join `country` `co` on((`co`.`id` = `p`.`countryFk`))) join `warehouse` `w` on((`w`.`id` = `t`.`warehouseFk`))) join `supplier` `su` on((`su`.`id` = `t`.`companyFk`))) join `country` `sc` on((`sc`.`id` = `su`.`countryFk`))) join `client` `c` on((`c`.`id` = `t`.`clientFk`))) join `agencyMode` `agm` on((`agm`.`id` = `t`.`agencyModeFk`))) join `agency` `ag` on((`ag`.`id` = `agm`.`agencyFk`))) left join `supplier` `ags` on((`ags`.`id` = `ag`.`supplierFk`))) left join `country` `sco` on((`sco`.`id` = `ags`.`countryFk`))) */; +/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`t`.`addressFk` AS `addressFk`,`t`.`shipped` AS `shipped`,`a`.`nickname` AS `clientName`,`a`.`postalCode` AS `clientPostalCode`,`a`.`street` AS `clientStreet`,`a`.`city` AS `clientCity`,`p`.`name` AS `clientProvince`,`co`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode` AS `companyPostCode`,`su`.`city` AS `companyCity`,`sc`.`country` AS `companyCountry`,`w`.`addressName` AS `warehouseAddress`,`c`.`name` AS `clientOficialName`,ifnull(`ags`.`name`,`agm`.`name`) AS `carrierName`,`ags`.`street` AS `carrierStreet`,`ags`.`postCode` AS `carrierPostCode`,`ags`.`city` AS `carrierCity`,`sco`.`country` AS `carrierCountry`,ifnull(`a`.`phone`,`c`.`phone`) AS `phone`,ifnull(`a`.`mobile`,`c`.`mobile`) AS `mobile` from ((((((((((((`cmr` join `ticket` `t` on((`t`.`id` = `cmr`.`ticketFk`))) join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) join `country` `co` on((`co`.`id` = `p`.`countryFk`))) join `warehouse` `w` on((`w`.`id` = `t`.`warehouseFk`))) join `supplier` `su` on((`su`.`id` = `t`.`companyFk`))) join `country` `sc` on((`sc`.`id` = `su`.`countryFk`))) join `client` `c` on((`c`.`id` = `t`.`clientFk`))) join `agencyMode` `agm` on((`agm`.`id` = `t`.`agencyModeFk`))) join `agency` `ag` on((`ag`.`id` = `agm`.`agencyFk`))) left join `supplier` `ags` on((`ags`.`id` = `ag`.`supplierFk`))) left join `country` `sco` on((`sco`.`id` = `ags`.`countryFk`))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -58430,7 +60542,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `collectionReportSource` AS select `tc`.`collectionFk` AS `collectionFk`,`tc`.`ticketFk` AS `ticketFk`,`s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`i`.`size` AS `size`,`s`.`quantity` AS `quantity`,`ip`.`code` AS `nicho`,`tc`.`level` AS `level` from (((((`collection` `c` join `ticketCollection` `tc` on((`tc`.`collectionFk` = `c`.`id`))) join `ticket` `t` on((`t`.`id` = `tc`.`ticketFk`))) join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `item` `i` on((`i`.`id` = `s`.`itemFk`))) join `itemPlacement` `ip` on(((`ip`.`itemFk` = `s`.`itemFk`) and (`ip`.`warehouseFk` = `t`.`warehouseFk`)))) */; +/*!50001 VIEW `collectionReportSource` AS select `tc`.`collectionFk` AS `collectionFk`,`tc`.`ticketFk` AS `ticketFk`,`s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`i`.`size` AS `size`,`s`.`quantity` AS `quantity`,`ip`.`code` AS `nicho`,`tc`.`level` AS `level` from (((((`collection` `c` join `ticketCollection` `tc` on((`tc`.`collectionFk` = `c`.`id`))) join `ticket` `t` on((`t`.`id` = `tc`.`ticketFk`))) join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `item` `i` on((`i`.`id` = `s`.`itemFk`))) left join `itemPlacement` `ip` on(((`ip`.`itemFk` = `s`.`itemFk`) and (`ip`.`warehouseFk` = `t`.`warehouseFk`)))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -58579,6 +60691,24 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `entryList` +-- + +/*!50001 DROP VIEW IF EXISTS `entryList`*/; +/*!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 `entryList` AS select `e`.`id` AS `entryFk`,if(`tr`.`isReceived`,' x','') AS `isHere`,`tr`.`landed` AS `landed`,ifnull(`s`.`nickname`,`s`.`name`) AS `supplier`,`e`.`ref` AS `entryRef`,`a`.`name` AS `agency`,`tr`.`ref` AS `travelRef`,`tr`.`appointment` AS `appointment`,`e`.`supplierFk` AS `supplierFk`,`tr`.`warehouseInFk` AS `warehouseInFk` from (((`entry` `e` join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `supplier` `s` on((`s`.`id` = `e`.`supplierFk`))) left join `agency` `a` on((`tr`.`agencyFk` = `a`.`id`))) where (`tr`.`landed` between (curdate() + interval -(1) week) and (curdate() + interval 3 month)) order by (`tr`.`landed` < (curdate() + interval 3 day)),`tr`.`landed` desc,`s`.`name`,`e`.`id` desc */; +/*!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 `exchangeInsuranceEntry` -- @@ -59294,7 +61424,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `saleVolume` AS select `s`.`ticketFk` AS `ticketFk`,`s`.`id` AS `saleFk`,ifnull(round(((((`i`.`compression` * (greatest(`i`.`density`,167) / 167)) * `ic`.`cm3`) * `s`.`quantity`) / 1000),2),0) AS `litros`,`t`.`routeFk` AS `routeFk`,`t`.`shipped` AS `shipped`,(((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) / 1000000) AS `volume`,((((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) * (greatest(`i`.`density`,167) / 167)) / 1000000) AS `physicalWeight`,(((`s`.`quantity` * `ic`.`cm3`) * `i`.`density`) / 1000000) AS `weight`,(((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) / 1000000) AS `physicalVolume`,((((`s`.`quantity` * `ic`.`cm3`) * `t`.`zonePrice`) * `i`.`compression`) / `cb`.`volume`) AS `freight`,`t`.`zoneFk` AS `zoneFk`,`t`.`clientFk` AS `clientFk` from ((((`sale` `s` join `item` `i` on((`i`.`id` = `s`.`itemFk`))) join `ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `packaging` `cb` on((`cb`.`id` = '94'))) join `itemCost` `ic` on(((`ic`.`itemFk` = `s`.`itemFk`) and (`ic`.`warehouseFk` = `t`.`warehouseFk`)))) */; +/*!50001 VIEW `saleVolume` AS select `s`.`ticketFk` AS `ticketFk`,`s`.`id` AS `saleFk`,ifnull(round(((((`i`.`compression` * (greatest(`i`.`density`,167) / 167)) * `ic`.`cm3`) * `s`.`quantity`) / 1000),2),0) AS `litros`,`t`.`routeFk` AS `routeFk`,`t`.`shipped` AS `shipped`,(((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) / 1000000) AS `volume`,((`s`.`quantity` * `ic`.`grams`) / 1000) AS `physicalWeight`,((((`s`.`quantity` * `ic`.`cm3`) * greatest(`i`.`density`,167)) / 167) / 1000000) AS `weight`,(((`s`.`quantity` * `ic`.`cm3`) * `i`.`compression`) / 1000000) AS `physicalVolume`,((((`s`.`quantity` * `ic`.`cm3`) * `t`.`zonePrice`) * `i`.`compression`) / `cb`.`volume`) AS `freight`,`t`.`zoneFk` AS `zoneFk`,`t`.`clientFk` AS `clientFk` from ((((`sale` `s` join `item` `i` on((`i`.`id` = `s`.`itemFk`))) join `ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `packaging` `cb` on((`cb`.`id` = '94'))) join `itemCost` `ic` on(((`ic`.`itemFk` = `s`.`itemFk`) and (`ic`.`warehouseFk` = `t`.`warehouseFk`)))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -59497,6 +61627,24 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `tr2` +-- + +/*!50001 DROP VIEW IF EXISTS `tr2`*/; +/*!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 `tr2` AS select `travel`.`id` AS `id`,`travel`.`shipped` AS `shipped`,`travel`.`shipmentHour` AS `shipmentHour`,`travel`.`landed` AS `landed`,`travel`.`landingHour` AS `landingHour`,`travel`.`warehouseInFk` AS `warehouseInFk`,`travel`.`warehouseOutFk` AS `warehouseOutFk`,`travel`.`agencyFk` AS `agencyFk`,`travel`.`ref` AS `ref`,`travel`.`isDelivered` AS `isDelivered`,`travel`.`isReceived` AS `isReceived`,`travel`.`m3` AS `m3`,`travel`.`kg` AS `kg`,`travel`.`cargoSupplierFk` AS `cargoSupplierFk`,`travel`.`totalEntries` AS `totalEntries` from `travel` */; +/*!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 `user` -- @@ -59764,4 +61912,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-03-16 9:43:30 +-- Dump completed on 2020-05-15 11:21:29 diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 6ee2f98aa..0a5e307e6 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -479,7 +479,7 @@ export default { secondSaleIdInput: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(4) > vn-autocomplete', secondSaleIdAutocomplete: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(4) > vn-autocomplete', secondSaleQuantity: 'vn-ticket-sale vn-table vn-tr:nth-child(2) vn-input-number', - secondSaleConceptCell: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(2) > vn-td-editable:nth-child(6) > div', + secondSaleConceptCell: 'vn-ticket-sale > vn-vertical > vn-card > vn-vertical > vn-table > div > vn-tbody > vn-tr:nth-child(2) > vn-td-editable:nth-child(6)', secondSaleConceptInput: 'vn-ticket-sale vn-table vn-tr:nth-child(2) > vn-td-editable.ng-isolate-scope.selected vn-textfield', totalImport: 'vn-ticket-sale > vn-vertical > vn-card > vn-vertical > vn-horizontal > vn-one > p:nth-child(3) > strong', selectAllSalesCheckbox: 'vn-ticket-sale vn-thead vn-check', @@ -613,7 +613,8 @@ export default { firstLineDestination: 'vn-claim-action vn-tr:nth-child(1) vn-autocomplete[ng-model="saleClaimed.claimDestinationFk"]', secondLineDestination: 'vn-claim-action vn-tr:nth-child(2) vn-autocomplete[ng-model="saleClaimed.claimDestinationFk"]', firstDeleteLine: 'vn-claim-action vn-tr:nth-child(1) vn-icon-button[icon="delete"]', - isPaidWithManaCheckbox: 'vn-check[ng-model="$ctrl.claim.isChargedToMana"]' + isPaidWithManaCheckbox: 'vn-claim-action vn-check[ng-model="$ctrl.claim.isChargedToMana"]', + hasToPickUpCheckbox: 'vn-claim-action vn-check[ng-model="$ctrl.claim.hasToPickUp"]' }, ordersIndex: { searchResult: 'vn-order-index vn-card > vn-table > div > vn-tbody > a.vn-tr', diff --git a/e2e/paths/04-item/05_niche.spec.js b/e2e/paths/04-item/05_niche.spec.js index 4ad0398c2..355dd2b0f 100644 --- a/e2e/paths/04-item/05_niche.spec.js +++ b/e2e/paths/04-item/05_niche.spec.js @@ -21,7 +21,7 @@ describe('Item create niche path', () => { await page.waitToClick(selectors.itemNiches.addNicheButton); await page.waitToClick(selectors.itemNiches.secondNicheRemoveButton); await page.autocompleteSearch(selectors.itemNiches.thirdWarehouse, 'Warehouse Two'); - await page.write(selectors.itemNiches.thirdCode, 'A4'); + await page.write(selectors.itemNiches.thirdCode, 'A44'); await page.waitToClick(selectors.itemNiches.submitNichesButton); const message = await page.waitForSnackbar(); @@ -39,7 +39,7 @@ describe('Item create niche path', () => { result = await page .waitToGetProperty(selectors.itemNiches.firstCode, 'value'); - expect(result).toEqual('A1'); + expect(result).toEqual('A11'); }); it(`should confirm the second niche is the expected one`, async() => { @@ -50,7 +50,7 @@ describe('Item create niche path', () => { result = await page .waitToGetProperty(selectors.itemNiches.secondCode, 'value'); - expect(result).toEqual('A3'); + expect(result).toEqual('A33'); }); it(`should confirm the third niche is the expected one`, async() => { @@ -61,6 +61,6 @@ describe('Item create niche path', () => { result = await page .waitToGetProperty(selectors.itemNiches.thirdCode, 'value'); - expect(result).toEqual('A4'); + expect(result).toEqual('A44'); }); }); diff --git a/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js b/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js index e8b0ad8e7..f97447c06 100644 --- a/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js +++ b/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js @@ -79,9 +79,8 @@ describe('Ticket List sale path', () => { expect(message.type).toBe('success'); }); - // #1865 - xit('should update the description of the new sale', async() => { - await page.focusElement(selectors.ticketSales.secondSaleConceptCell); + it('should update the description of the new sale', async() => { + await page.click(selectors.ticketSales.secondSaleConceptCell); await page.write(selectors.ticketSales.secondSaleConceptInput, 'Aegis of Valor'); await page.keyboard.press('Enter'); const message = await page.waitForSnackbar(); diff --git a/e2e/paths/06-claim/04_claim_action.spec.js b/e2e/paths/06-claim/04_claim_action.spec.js index 9897a3ef3..67c936898 100644 --- a/e2e/paths/06-claim/04_claim_action.spec.js +++ b/e2e/paths/06-claim/04_claim_action.spec.js @@ -66,17 +66,25 @@ describe('Claim action path', () => { }); it('should check the "is paid with mana" checkbox', async() => { - page.waitFor(3000); // can't use waitForNavigation here and needs more time than a single second to get the section ready... await page.waitToClick(selectors.claimAction.isPaidWithManaCheckbox); const message = await page.waitForSnackbar(); expect(message.type).toBe('success'); }); - it('should confirm the "is paid with mana" checkbox is checked', async() => { - await page.reloadSection('claim.card.action'); - const result = await page.checkboxState(selectors.claimAction.isPaidWithManaCheckbox); + it('should check the "Pick up" checkbox', async() => { + await page.waitToClick(selectors.claimAction.hasToPickUpCheckbox); + const message = await page.waitForSnackbar(); - expect(result).toBe('checked'); + expect(message.type).toBe('success'); + }); + + it('should confirm the "is paid with mana" and "Pick up" checkbox are checked', async() => { + await page.reloadSection('claim.card.action'); + const isPaidWithManaCheckbox = await page.checkboxState(selectors.claimAction.isPaidWithManaCheckbox); + const hasToPickUpCheckbox = await page.checkboxState(selectors.claimAction.hasToPickUpCheckbox); + + expect(isPaidWithManaCheckbox).toBe('checked'); + expect(hasToPickUpCheckbox).toBe('checked'); }); }); diff --git a/e2e/paths/07-order/03_lines.spec.js b/e2e/paths/07-order/03_lines.spec.js index 6f87b45f0..9a214cfeb 100644 --- a/e2e/paths/07-order/03_lines.spec.js +++ b/e2e/paths/07-order/03_lines.spec.js @@ -35,7 +35,7 @@ describe('Order lines', () => { const result = await page .waitToGetProperty(selectors.orderLine.orderSubtotal, 'innerText'); - expect(result).toContain('90.10'); + expect(result).toContain('80.54'); }); it('should confirm the whole order and redirect to ticket index filtered by clientFk', async() => { diff --git a/front/core/components/range/index.js b/front/core/components/range/index.js index 88463e7cf..b2525d00d 100644 --- a/front/core/components/range/index.js +++ b/front/core/components/range/index.js @@ -47,7 +47,7 @@ export default class Range extends FormInput { } onValueUpdate() { - this.change(this.input.value); + this.change(parseInt(this.input.value)); this.$.$applyAsync(); } } diff --git a/front/core/components/tooltip/tooltip.js b/front/core/components/tooltip/tooltip.js index 7ec188653..72d69f83d 100644 --- a/front/core/components/tooltip/tooltip.js +++ b/front/core/components/tooltip/tooltip.js @@ -47,7 +47,7 @@ export default class Tooltip extends Component { } /** - * Repositions the tooltip acording to it's own size and parent location. + * Repositions the tooltip acording to it's own size, position and parent location. */ relocate() { let axis; diff --git a/front/core/components/tooltip/tooltip.spec.js b/front/core/components/tooltip/tooltip.spec.js index 74cb410ff..62e021bd1 100644 --- a/front/core/components/tooltip/tooltip.spec.js +++ b/front/core/components/tooltip/tooltip.spec.js @@ -2,119 +2,154 @@ import './tooltip'; describe('Component vnTooltip', () => { let $element; - let controller; + let tooltip; + let tooltipCtrl; let $parent; - let element; let window; beforeEach(ngModule('vnCore')); - beforeEach(inject(($componentController, $compile, $templateRequest, $document) => { - $element = angular.element(`test`); + beforeEach(inject(($rootScope, $compile, $document) => { + let scope = $rootScope.$new(); + $element = $compile(`test`)(scope); $document.find('body').append($element); - controller = $componentController('vnTooltip', {$document, $compile, $templateRequest, $element}); - element = $element[0]; - window = controller.window; - + tooltip = $element[0]; + tooltipCtrl = tooltip.$ctrl; + window = tooltipCtrl.window; $parent = angular.element('
'); - $parent.css({ - backgroundColor: 'red', - position: 'absolute', - width: '100px', - height: '100px', - top: '0', - left: '0' - }); - $document.find('body').append($parent); - })); - afterEach(() => { - $element.remove(); - $parent.remove(); - }); + $document.find('body').append($parent); + + $parent[0].getBoundingClientRect = () => {}; + + jest.spyOn(tooltip, 'getBoundingClientRect').mockReturnValue({bottom: 0, height: 40, left: 0, right: 0, top: 0, width: 40}); + })); describe('show()', () => { it(`should check that tooltip is visible into the screen`, () => { - expect(element.classList).not.toContain('show'); + jest.spyOn($parent[0], 'getBoundingClientRect').mockReturnValue({ + height: window.innerHeight - 120, + width: window.innerWidth - 120, + top: 60, + left: 60, + }); - controller.show($parent[0]); + expect(tooltip.classList).not.toContain('show'); - let rect = element.getBoundingClientRect(); + tooltipCtrl.show($parent[0]); - expect(element.classList).toContain('show'); + let tooltipStyle = tooltip.style; - expect(0).toBeLessThanOrEqual(rect.top); - expect(0).toBeLessThanOrEqual(rect.left); - expect(window.innerHeight).toBeGreaterThan(rect.bottom); - expect(window.innerWidth).toBeGreaterThan(rect.right); + let tooltipTop = parseInt(tooltipStyle['top']); + let tooltipLeft = parseInt(tooltipStyle['left']); + + expect(tooltip.classList).toContain('show'); + + expect(tooltipTop).toBeLessThanOrEqual(window.innerHeight); + expect(tooltipTop).toBeGreaterThanOrEqual(0); + expect(tooltipLeft).toBeLessThanOrEqual(window.innerWidth); + expect(tooltipLeft).toBeGreaterThanOrEqual(0); }); }); describe('hide()', () => { - it(`should check that tooltip is not visible`, () => { - controller.show($parent[0]); + it('should check that tooltip is not visible', () => { + jest.spyOn($parent[0], 'getBoundingClientRect').mockReturnValue({ + height: window.innerHeight, + width: window.innerWidth - 80, + top: 0, + left: 60, + }); + tooltipCtrl.show($parent[0]); - expect(element.classList).toContain('show'); - controller.hide(); + expect(tooltip.classList).toContain('show'); + tooltipCtrl.hide(); - expect(element.classList).not.toContain('show'); + expect(tooltip.classList).not.toContain('show'); }); }); - // #1892 reparar unitarios front tooltip.js - xdescribe('relocate()', () => { - it(`should reallocate tooltip on top-left`, () => { - controller.show($parent[0]); - let rect = element.getBoundingClientRect(); + describe('relocate()', () => { + it('should reallocate tooltip to the left', () => { + jest.spyOn($parent[0], 'getBoundingClientRect').mockReturnValue({ + height: window.innerHeight, + width: window.innerWidth - 80, + top: 0, + left: 60, + }); - expect(controller.margin).toBeLessThan(rect.top); - expect(controller.margin).toEqual(rect.left); + tooltipCtrl.position = 'left'; + tooltipCtrl.show($parent[0]); + + let tooltipStyle = tooltip.style; + + let tooltipTop = parseInt(tooltipStyle['top']); + let tooltipLeft = parseInt(tooltipStyle['left']); + + expect(tooltipTop).toEqual((window.innerHeight / 2) - (tooltipCtrl.margin * 2)); + expect(tooltipLeft).toEqual(tooltipCtrl.margin); }); - it(`should reallocate tooltip on bottom-left`, () => { - $parent.css({ - top: `${window.innerHeight}px` + it('should reallocate tooltip on bottom', () => { + let parentHeight = window.innerHeight - 80; + jest.spyOn($parent[0], 'getBoundingClientRect').mockReturnValue({ + height: parentHeight, + width: window.innerWidth, + top: 0, + left: 0, }); - controller.show($parent[0]); - let rect = element.getBoundingClientRect(); - expect(window.innerHeight).toBeGreaterThan(rect.top); - expect(controller.margin).toEqual(rect.left); + tooltipCtrl.position = 'bottom'; + tooltipCtrl.show($parent[0]); + + let tooltipStyle = tooltip.style; + + let tooltipTop = parseInt(tooltipStyle['top']); + let tooltipLeft = parseInt(tooltipStyle['left']); + + expect(tooltipLeft).toEqual((window.innerWidth / 2) - (tooltipCtrl.margin * 2)); + expect(tooltipTop).toEqual(parentHeight + tooltipCtrl.margin); }); - it(`should reallocate tooltip on bottom-right`, () => { - $parent.css({ - top: `${window.innerHeight}px`, - left: `${window.innerWidth}px` + it(`should reallocate tooltip on right`, () => { + let parentWidth = window.innerWidth - 80; + jest.spyOn($parent[0], 'getBoundingClientRect').mockReturnValue({ + height: window.innerHeight, + width: parentWidth, + top: 0, + left: 0, }); - controller.show($parent[0]); - let rect = element.getBoundingClientRect(); - expect(window.innerWidth).toBeGreaterThan(rect.left); - expect(window.innerWidth - controller.margin).toEqual(rect.right); + tooltipCtrl.position = 'right'; + tooltipCtrl.show($parent[0]); + + let tooltipStyle = tooltip.style; + + let tooltipTop = parseInt(tooltipStyle['top']); + let tooltipLeft = parseInt(tooltipStyle['left']); + + expect(tooltipLeft).toEqual(parentWidth + tooltipCtrl.margin); + expect(tooltipTop).toEqual((window.innerHeight / 2) - (tooltipCtrl.margin * 2)); }); - it(`should reallocate tooltip on top-right`, () => { - $parent.css({ - left: `${window.innerWidth}px` + it(`should reallocate tooltip on top`, () => { + jest.spyOn($parent[0], 'getBoundingClientRect').mockReturnValue({ + height: window.innerHeight - 80, + width: window.innerWidth, + top: 60, + left: 0, }); - controller.show($parent[0]); - let rect = element.getBoundingClientRect(); - expect(controller.margin).toBeLessThan(rect.top); - expect(window.innerWidth - controller.margin).toEqual(rect.right); - }); + tooltipCtrl.position = 'top'; + tooltipCtrl.show($parent[0]); - it(`should reallocate tooltip on center`, () => { - $parent.css({ - top: `${window.window.innerHeight / 2}px`, - left: `${window.window.innerWidth / 2}px` - }); - controller.show($parent[0]); - let rect = element.getBoundingClientRect(); + let tooltipStyle = tooltip.style; - expect(window.innerHeight / 2).toBeLessThan(rect.top); - expect(window.innerWidth / 2).toBeGreaterThan(rect.left); + let tooltipTop = parseInt(tooltipStyle['top']); + let tooltipLeft = parseInt(tooltipStyle['left']); + + expect(tooltipLeft).toEqual((window.innerWidth / 2) - (tooltipCtrl.margin * 2)); + expect(tooltipTop).toEqual(tooltipCtrl.margin); }); }); }); diff --git a/front/core/filters/specs/currency.spec.js b/front/core/filters/specs/currency.spec.js index ecb94efe0..ed0262b45 100644 --- a/front/core/filters/specs/currency.spec.js +++ b/front/core/filters/specs/currency.spec.js @@ -1,8 +1,9 @@ describe('Currency filter', () => { beforeEach(ngModule('vnCore')); let currencyFilter; - beforeEach(inject(_currencyFilter_ => { + beforeEach(inject((_currencyFilter_, $translate) => { currencyFilter = _currencyFilter_; + jest.spyOn($translate, 'use').mockReturnValue('en-US'); })); it('should return a ONE decimal number as per the argument', () => { diff --git a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js index 48b67528a..5319b185a 100644 --- a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js +++ b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js @@ -8,7 +8,7 @@ describe('Model rewriteDbError()', () => { }); it('should handle a duplicated warehouse error', async() => { - let itemNiche = {itemFk: 1, warehouseFK: 1, code: 'A1'}; + let itemNiche = {itemFk: 1, warehouseFK: 1, code: 'A11'}; let error; await app.models.ItemNiche.create(itemNiche).catch(e => { error = e; diff --git a/loopback/locale/en.json b/loopback/locale/en.json index dc62e35f4..6f20b947b 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -62,6 +62,7 @@ "MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} (#{{clientId}})]({{{url}}}) to *{{credit}} €*", "MESSAGE_CHANGED_PAYMETHOD": "I have changed the pay method for client [{{clientName}} (#{{clientId}})]({{{url}}})", "Sent units from ticket": "I sent *{{quantity}}* units of [{{concept}} (#{{itemId}})]({{{itemUrl}}}) to *\"{{nickname}}\"* coming from ticket id [#{{ticketId}}]({{{ticketUrl}}})", + "Claim will be picked": "The product from the claim (#{{claimId}})]({{{claimUrl}}}) from the client *{{clientName}}* will be picked", "This ticket is not an stowaway anymore": "The ticket id [#{{ticketId}}]({{{ticketUrl}}}) is not an stowaway anymore", "Customs agent is required for a non UEE member": "Customs agent is required for a non UEE member", "Incoterms is required for a non UEE member": "Incoterms is required for a non UEE member", diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 21fe03884..eeb18fb73 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -125,6 +125,7 @@ "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} (#{{clientId}})]({{{url}}}) a *{{credit}} €*", "MESSAGE_CHANGED_PAYMETHOD": "He cambiado la forma de pago del cliente [{{clientName}} (#{{clientId}})]({{{url}}})", "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} (#{{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [#{{ticketId}}]({{{ticketUrl}}})", + "Claim will be picked": "Se recogerá el género de la reclamación (#{{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", "This ticket is not an stowaway anymore": "El ticket id [#{{ticketId}}]({{{ticketUrl}}}) ha dejado de ser un polizón", "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", diff --git a/modules/claim/back/methods/claim/filter.js b/modules/claim/back/methods/claim/filter.js index 33909eedc..1caa120be 100644 --- a/modules/claim/back/methods/claim/filter.js +++ b/modules/claim/back/methods/claim/filter.js @@ -114,7 +114,6 @@ module.exports = Self => { LEFT JOIN claimState cs ON cs.id = cl.claimStateFk` ); - stmt.merge(conn.makeSuffix(filter)); let itemsIndex = stmts.push(stmt) - 1; diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index adf1623c6..77e5f6504 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -3,21 +3,22 @@ module.exports = Self => { description: 'Imports lines from claimBeginning to a new ticket with specific shipped, landed dates, agency and company', accessType: 'WRITE', accepts: [{ - arg: 'params', - type: 'object', - http: {source: 'body'} + arg: 'id', + type: 'number', + description: 'The claim id', + http: {source: 'path'} }], returns: { type: ['Object'], root: true }, http: { - path: `/regularizeClaim`, + path: `/:id/regularizeClaim`, verb: 'POST' } }); - Self.regularizeClaim = async(ctx, params) => { + Self.regularizeClaim = async(ctx, claimFk) => { const models = Self.app.models; const $t = ctx.req.__; // $translate const resolvedState = 3; @@ -31,7 +32,7 @@ module.exports = Self => { relation: 'claimDestination', fields: ['addressFk'] }, - where: {claimFk: params.claimFk} + where: {claimFk: claimFk} }, options); for (let i = 0; i < claimEnds.length; i++) { @@ -87,11 +88,32 @@ module.exports = Self => { }, options); } - let claim = await Self.findById(params.claimFk, null, options); + let claim = await Self.findById(claimFk, { + include: { + relation: 'client', + scope: { + include: { + relation: 'salesPerson' + } + } + } + }, options); claim = await claim.updateAttributes({ claimStateFk: resolvedState }, options); + // Get sales person from claim client + const salesPerson = claim.client().salesPerson(); + if (salesPerson && claim.hasToPickUp) { + const origin = ctx.req.headers.origin; + const message = $t('Claim will be picked', { + claimId: claim.id, + clientName: claim.client().name, + claimUrl: `${origin}/#!/claim/${claim.id}/summary` + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + } + await tx.commit(); return claim; diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index c7aa1cf0a..8ebe41f25 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -12,7 +12,10 @@ describe('regularizeClaim()', () => { afterAll(async done => { let claim = await app.models.Claim.findById(claimFk); - await claim.updateAttributes({claimStateFk: pendentState}); + await claim.updateAttributes({ + claimStateFk: pendentState, + hasToPickUp: false + }); await app.models.Ticket.destroyById(trashTicket.id); claimEnds.forEach(async line => { @@ -33,7 +36,6 @@ describe('regularizeClaim()', () => { return params.nickname; }; - let params = {claimFk: claimFk}; const chatModel = app.models.Chat; spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); @@ -46,9 +48,9 @@ describe('regularizeClaim()', () => { claimEnd.updateAttributes({claimDestinationFk: trashDestination}); }); - let claimBefore = await app.models.Claim.findById(params.claimFk); - await app.models.Claim.regularizeClaim(ctx, params); - let claimAfter = await app.models.Claim.findById(params.claimFk); + let claimBefore = await app.models.Claim.findById(claimFk); + await app.models.Claim.regularizeClaim(ctx, claimFk); + let claimAfter = await app.models.Claim.findById(claimFk); trashTicket = await app.models.Ticket.findOne({where: {addressFk: 12}}); @@ -70,7 +72,6 @@ describe('regularizeClaim()', () => { return params.nickname; }; - let params = {claimFk: claimFk}; const chatModel = app.models.Chat; spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); @@ -78,9 +79,35 @@ describe('regularizeClaim()', () => { claimEnd.updateAttributes({claimDestinationFk: okDestination}); }); - await app.models.Claim.regularizeClaim(ctx, params); + await app.models.Claim.regularizeClaim(ctx, claimFk); expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno'); expect(chatModel.sendCheckingPresence).toHaveBeenCalledTimes(4); }); + + it('should send a chat message to the salesPerson when claim isPickUp is enabled', async() => { + const ctx = { + req: { + accessToken: {userId: 18}, + headers: {origin: 'http://localhost'} + } + }; + ctx.req.__ = (value, params) => { + return params.nickname; + }; + + const chatModel = app.models.Chat; + spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); + + claimEnds.forEach(async claimEnd => { + claimEnd.updateAttributes({claimDestinationFk: okDestination}); + }); + + const claim = await app.models.Claim.findById(claimFk); + await claim.updateAttribute('hasToPickUp', true); + await app.models.Claim.regularizeClaim(ctx, claimFk); + + expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno'); + expect(chatModel.sendCheckingPresence).toHaveBeenCalledTimes(5); + }); }); diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js index 3d3404ac5..4848974fe 100644 --- a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -26,16 +26,16 @@ describe('Update Claim', () => { }); it('should update the claim isChargedToMana attribute', async() => { - const data = {isChargedToMana: false}; - const result = await app.models.Claim.updateClaimAction(newInstance.id, data); + const ctx = {args: {isChargedToMana: false}}; + const result = await app.models.Claim.updateClaimAction(ctx, newInstance.id); expect(result.id).toEqual(newInstance.id); expect(result.isChargedToMana).toBeFalsy(); }); it('should update the claim responsibility attribute', async() => { - const data = {responsibility: 2}; - const result = await app.models.Claim.updateClaimAction(newInstance.id, data); + const ctx = {args: {responsibility: 2}}; + const result = await app.models.Claim.updateClaimAction(ctx, newInstance.id); expect(result.id).toEqual(newInstance.id); expect(result.responsibility).toEqual(2); diff --git a/modules/claim/back/methods/claim/updateClaimAction.js b/modules/claim/back/methods/claim/updateClaimAction.js index c9c4f1043..69691897c 100644 --- a/modules/claim/back/methods/claim/updateClaimAction.js +++ b/modules/claim/back/methods/claim/updateClaimAction.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethod('updateClaimAction', { + Self.remoteMethodCtx('updateClaimAction', { description: 'Update a claim with privileges', accessType: 'WRITE', accepts: [{ @@ -10,11 +10,17 @@ module.exports = Self => { description: 'Claim id', http: {source: 'path'} }, { - arg: 'data', - type: 'object', - required: true, - description: 'Data to update on the model', - http: {source: 'body'} + arg: 'responsibility', + type: 'number', + required: false + }, { + arg: 'isChargedToMana', + type: 'boolean', + required: false + }, { + arg: 'hasToPickUp', + type: 'boolean', + required: false }], returns: { type: 'object', @@ -22,22 +28,16 @@ module.exports = Self => { }, http: { path: `/:id/updateClaimAction`, - verb: 'post' + verb: 'patch' } }); - Self.updateClaimAction = async(id, data) => { - let models = Self.app.models; + Self.updateClaimAction = async(ctx, id) => { + const models = Self.app.models; + const claim = await models.Claim.findById(id); + const args = ctx.args; + delete args.ctx; - let claim = await models.Claim.findById(id); - let updatedData = {}; - - if (data.hasOwnProperty('responsibility')) - updatedData.responsibility = data.responsibility; - - if (data.hasOwnProperty('isChargedToMana')) - updatedData.isChargedToMana = data.isChargedToMana; - - return await claim.updateAttributes(updatedData); + return await claim.updateAttributes(args); }; }; diff --git a/modules/claim/back/models/claim-state.json b/modules/claim/back/models/claim-state.json index bf2554f38..c905aacba 100644 --- a/modules/claim/back/models/claim-state.json +++ b/modules/claim/back/models/claim-state.json @@ -12,9 +12,17 @@ "id": true, "description": "Identifier" }, + "code": { + "type": "String", + "required": true + }, "description": { "type": "String", "required": true + }, + "priority": { + "type": "nomber", + "required": true } }, "relations": { diff --git a/modules/claim/back/models/claim.json b/modules/claim/back/models/claim.json index 1462c4222..3cb64e31d 100644 --- a/modules/claim/back/models/claim.json +++ b/modules/claim/back/models/claim.json @@ -13,7 +13,7 @@ "description": "Identifier" }, "observation": { - "type": "String" + "type": "string" }, "ticketCreated": { "type": "date", @@ -26,16 +26,19 @@ "type": "date" }, "responsibility": { - "type": "Number" + "type": "number" + }, + "hasToPickUp": { + "type": "boolean" }, "ticketFk": { - "type": "Number" + "type": "number" }, "claimStateFk": { - "type": "Number" + "type": "number" }, "workerFk": { - "type": "Number" + "type": "number" } }, "relations": { diff --git a/modules/claim/front/action/index.html b/modules/claim/front/action/index.html index 19cb5c06e..692a1f4d2 100644 --- a/modules/claim/front/action/index.html +++ b/modules/claim/front/action/index.html @@ -1,6 +1,7 @@ @@ -39,15 +40,18 @@ max="$ctrl.maxResponsibility" min="1" step="1" - vn-acl="salesAssistant" - on-change="$ctrl.saveResponsibility(value)"> + on-change="$ctrl.save({responsibility: value})"> + + + on-change="$ctrl.save({isChargedToMana: value})"> @@ -83,7 +87,7 @@ {{::saleClaimed.sale.ticketFk}} - + @@ -116,46 +120,11 @@ - - - -

Claimable sales from ticket

{{$ctrl.claim.ticketFk}}

- - - - Id - Landed - Quantity - Description - Price - Disc. - Total - - - - - {{sale.saleFk}} - {{sale.landed | date: 'dd/MM/yyyy'}} - {{sale.quantity}} - {{sale.concept}} - {{sale.price | currency: 'EUR':2}} - {{sale.discount}} % - - {{sale.quantity * sale.price * ((100 - sale.discount) * / 100) | currency: 'EUR':2}} - - - - -
-
{ - if (res.data) - this.claimedSales = res.data; - }); - } - - addClaimedSale(saleFk) { - let saleToAdd = {saleFk: saleFk, claimFk: this.claim.id, workerFk: this.claim.workerFk, claimDestinationFk: 1}; - let query = `ClaimEnds/`; - this.$http.post(query, saleToAdd).then(() => { - this.$.model.refresh(); - this.$.addSales.hide(); - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); - }); - } - - deleteClaimedSale(id) { - let query = `ClaimEnds/${id}`; - this.$http.delete(query).then(() => { - this.$.model.refresh(); - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); - }); + getResolvedState() { + const query = `ClaimStates/findOne`; + const params = { + filter: { + where: { + code: 'resolved' + } + } + }; + this.$http.get(query, params).then(res => + this.resolvedStateId = res.data.id + ); } importToNewRefundTicket() { let query = `ClaimBeginnings/${this.$params.id}/importToNewRefundTicket`; return this.$http.post(query).then(() => { this.$.model.refresh(); - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.vnApp.showSuccess(this.$t('Data saved!')); }); } @@ -72,7 +54,9 @@ export default class Controller extends Section { calculateTotals() { this.claimedTotal = 0; this.salesClaimed.forEach(sale => { - this.claimedTotal += (sale.sale.quantity * sale.sale.price) - ((sale.sale.discount * (sale.sale.quantity * sale.sale.price)) / 100); + const price = sale.sale.quantity * sale.sale.price; + const discount = (sale.sale.discount * (sale.sale.quantity * sale.sale.price)) / 100; + this.claimedTotal += price - discount; }); } @@ -101,20 +85,19 @@ export default class Controller extends Section { let query = `ClaimEnds/importTicketSales`; this.$http.post(query, data).then(() => { - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.vnApp.showSuccess(this.$t('Data saved!')); this.$.lastTicketsPopover.hide(); this.$.model.refresh(); }); } regularize() { - let data = {claimFk: this.$params.id}; - let query = `Claims/regularizeClaim`; - return this.$http.post(query, data).then(() => { + const query = `Claims/${this.$params.id}/regularizeClaim`; + return this.$http.post(query).then(() => { if (this.claim.responsibility >= Math.ceil(this.maxResponsibility) / 2) this.$.updateGreuge.show(); else - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.vnApp.showSuccess(this.$t('Data saved!')); this.card.reload(); }); @@ -148,7 +131,7 @@ export default class Controller extends Section { return Promise.all(promises).then(() => { const data = { clientFk: this.claim.clientFk, - description: this.$translate.instant('ClaimGreugeDescription', { + description: this.$t('ClaimGreugeDescription', { claimId: this.claim.id }).toUpperCase(), amount: this.freightPickUpPrice, @@ -156,32 +139,22 @@ export default class Controller extends Section { ticketFk: this.claim.ticketFk }; return this.$http.post(`Greuges/`, data).then(() => { - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); - this.vnApp.showMessage(this.$translate.instant('Greuge inserted')); + this.vnApp.showSuccess(this.$t('Data saved!')); + this.vnApp.showMessage(this.$t('Greuge inserted')); }); }); } else - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.vnApp.showSuccess(this.$t('Data saved!')); } - saveResponsibility(value) { - let query = `Claims/${this.$params.id}/updateClaimAction`; - - this.$http.post(query, {responsibility: value}).then(() => { - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); - }); - } - - saveMana(value) { - let query = `Claims/${this.$params.id}/updateClaimAction`; - - this.$http.post(query, {isChargedToMana: value}).then(() => { - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); - }); + save(data) { + const query = `Claims/${this.$params.id}/updateClaimAction`; + this.$http.patch(query, data) + .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))); } onSave() { - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.vnApp.showSuccess(this.$t('Data saved!')); } } diff --git a/modules/claim/front/action/index.spec.js b/modules/claim/front/action/index.spec.js index 639e90827..503571f5b 100644 --- a/modules/claim/front/action/index.spec.js +++ b/modules/claim/front/action/index.spec.js @@ -32,56 +32,16 @@ describe('claim', () => { show: () => {} }; controller.card = {reload: () => {}}; + $httpBackend.expectGET(`ClaimStates/findOne`).respond({}); })); - describe('openAddSalesDialog()', () => { - it('should call getClaimableFromTicket and $.addSales.show', () => { - controller.$ = {addSales: {show: () => {}}}; - jest.spyOn(controller, 'getClaimedSales'); - jest.spyOn(controller.$.addSales, 'show'); - controller.openAddSalesDialog(); - - expect(controller.getClaimedSales).toHaveBeenCalledWith(); - expect(controller.$.addSales.show).toHaveBeenCalledWith(); - }); - }); - - describe('getClaimedSales()', () => { - it('should make a query and set salesToClaim', () => { - controller.claim.id = 1; - $httpBackend.expectGET(`ClaimBeginnings/1`).respond(200, 1); - controller.getClaimedSales(); + describe('getResolvedState()', () => { + it('should return the resolved state id', () => { + $httpBackend.expectGET(`ClaimStates/findOne`).respond({id: 1}); + controller.getResolvedState(); $httpBackend.flush(); - expect(controller.claimedSales).toEqual(1); - }); - }); - - describe('addClaimedSale(saleFk)', () => { - it('should make a post and call refresh, hide and showSuccess', () => { - jest.spyOn(controller.$.model, 'refresh'); - jest.spyOn(controller.$.addSales, 'hide'); - jest.spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expectPOST(`ClaimEnds/`).respond({}); - controller.addClaimedSale(1); - $httpBackend.flush(); - - expect(controller.$.model.refresh).toHaveBeenCalledWith(); - expect(controller.$.addSales.hide).toHaveBeenCalledWith(); - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); - }); - }); - - describe('deleteClaimedSale(id)', () => { - it('should make a delete and call refresh and showSuccess', () => { - jest.spyOn(controller.$.model, 'refresh'); - jest.spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expectDELETE(`ClaimEnds/1`).respond({}); - controller.deleteClaimedSale(1); - $httpBackend.flush(); - - expect(controller.$.model.refresh).toHaveBeenCalledWith(); - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + expect(controller.resolvedStateId).toEqual(1); }); }); @@ -102,6 +62,7 @@ describe('claim', () => { it('should perform a post query and add lines from a new ticket', () => { jest.spyOn(controller.$.model, 'refresh'); jest.spyOn(controller.vnApp, 'showSuccess'); + $httpBackend.expect('POST', `ClaimBeginnings/1/importToNewRefundTicket`).respond({}); controller.importToNewRefundTicket(); $httpBackend.flush(); @@ -115,6 +76,7 @@ describe('claim', () => { it('should get a list of tickets and call lastTicketsPopover show() method', () => { jest.spyOn(controller.$.lastTicketsModel, 'refresh'); jest.spyOn(controller.$.lastTicketsPopover, 'show'); + controller.showLastTickets({}); expect(controller.$.lastTicketsModel.refresh).toHaveBeenCalledWith(); @@ -127,6 +89,7 @@ describe('claim', () => { jest.spyOn(controller.$.model, 'refresh'); jest.spyOn(controller.vnApp, 'showSuccess'); jest.spyOn(controller.$.lastTicketsPopover, 'hide'); + let data = {claimFk: 1, ticketFk: 1}; $httpBackend.expect('POST', `ClaimEnds/importTicketSales`, data).respond({}); controller.importTicketLines(1); @@ -143,8 +106,7 @@ describe('claim', () => { jest.spyOn(controller.card, 'reload'); jest.spyOn(controller.vnApp, 'showSuccess'); - let data = {claimFk: $state.params.id}; - $httpBackend.expect('POST', `Claims/regularizeClaim`, data).respond({}); + $httpBackend.expect('POST', `Claims/1/regularizeClaim`).respond({}); controller.regularize(); $httpBackend.flush(); @@ -153,6 +115,19 @@ describe('claim', () => { }); }); + describe('save()', () => { + it('should perform a patch query and show a success message', () => { + jest.spyOn(controller.vnApp, 'showSuccess'); + + const data = {hasToPickUp: true}; + $httpBackend.expect('PATCH', `Claims/1/updateClaimAction`, data).respond({}); + controller.save(data); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + describe('onUpdateGreugeResponse()', () => { const greugeTypeId = 7; const freightPickUpPrice = 11; diff --git a/modules/claim/front/action/locale/es.yml b/modules/claim/front/action/locale/es.yml index db1a25755..bdf4bf8e9 100644 --- a/modules/claim/front/action/locale/es.yml +++ b/modules/claim/front/action/locale/es.yml @@ -9,4 +9,5 @@ Regularize: Regularizar Do you want to insert greuges?: Desea insertar greuges? Insert greuges on client card: Insertar greuges en la ficha del cliente Greuge inserted: Greuge insertado -ClaimGreugeDescription: Reclamación id {{claimId}} \ No newline at end of file +ClaimGreugeDescription: Reclamación id {{claimId}} +Pick up: Recoger \ No newline at end of file diff --git a/modules/claim/front/basic-data/index.html b/modules/claim/front/basic-data/index.html index 948ac6b18..63a3d0294 100644 --- a/modules/claim/front/basic-data/index.html +++ b/modules/claim/front/basic-data/index.html @@ -40,6 +40,7 @@ show-field="description" value-field="id" label="Claim state" + order="priority ASC" vn-focus> diff --git a/modules/claim/front/main/index.html b/modules/claim/front/main/index.html index c66c02f14..8a9447125 100644 --- a/modules/claim/front/main/index.html +++ b/modules/claim/front/main/index.html @@ -2,7 +2,7 @@ vn-id="model" url="Claims/filter" limit="20" - order="claimStateFk ASC, created DESC" + order="priority ASC, created DESC" auto-load="true"> diff --git a/modules/client/front/descriptor/index.html b/modules/client/front/descriptor/index.html index 5cc9bef41..112bfca26 100644 --- a/modules/client/front/descriptor/index.html +++ b/modules/client/front/descriptor/index.html @@ -34,7 +34,12 @@ value="{{$ctrl.client.creditInsurance | currency: 'EUR': 2}}"> + +
diff --git a/modules/client/front/index/index.html b/modules/client/front/index/index.html index a501b68cf..6a64954aa 100644 --- a/modules/client/front/index/index.html +++ b/modules/client/front/index/index.html @@ -32,6 +32,14 @@ + + + + { } } } - }, - { + }, { relation: 'address', scope: { fields: ['street', 'city', 'provinceFk', 'phone', 'mobile'], @@ -81,8 +80,7 @@ module.exports = Self => { } } } - }, - { + }, { relation: 'notes', scope: { fields: ['id', 'observationTypeFk', 'description'], @@ -91,8 +89,7 @@ module.exports = Self => { fields: ['description'] } } - }, - { + }, { relation: 'state', scope: { fields: ['stateFk'], @@ -101,6 +98,11 @@ module.exports = Self => { fields: ['name'] } } + }, { + relation: 'invoiceOut', + scope: { + fields: ['id'] + } } ], where: {id: ticketFk} diff --git a/modules/ticket/front/routes.json b/modules/ticket/front/routes.json index 6f54a8efd..cfb2d07c9 100644 --- a/modules/ticket/front/routes.json +++ b/modules/ticket/front/routes.json @@ -3,7 +3,7 @@ "name": "Tickets", "icon": "icon-ticket", "validations": true, - "dependencies": ["worker", "item", "client", "route"], + "dependencies": ["worker", "item", "client", "route", "invoiceOut"], "menus": { "main": [ {"state": "ticket.index", "icon": "icon-ticket"}, diff --git a/modules/ticket/front/summary/index.html b/modules/ticket/front/summary/index.html index f15db1b56..3ea2b7234 100644 --- a/modules/ticket/front/summary/index.html +++ b/modules/ticket/front/summary/index.html @@ -37,8 +37,12 @@ {{$ctrl.summary.routeFk}} - + + + {{$ctrl.summary.refFk | dashIfEmpty}} + @@ -235,3 +239,6 @@ warehouse-fk="$ctrl.ticket.warehouseFk", ticket-fk="$ctrl.ticket.id"> + + \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 4a597175a..6affdde84 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3244,7 +3244,7 @@ }, "util": { "version": "0.10.3", - "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", + "resolved": "http://registry.npmjs.org/util/-/util-0.10.3.tgz", "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", "dev": true, "requires": { @@ -4060,7 +4060,7 @@ "base": { "version": "0.11.2", "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", - "integrity": "sha1-e95c7RRbbVUakNuH+DxVi060io8=", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", "dev": true, "requires": { "cache-base": "^1.0.1", @@ -4577,7 +4577,7 @@ "cache-base": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", - "integrity": "sha1-Cn9GQWgxyLZi7jb+TnxZ129marI=", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", "dev": true, "requires": { "collection-visit": "^1.0.0", @@ -4754,7 +4754,7 @@ "class-utils": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", - "integrity": "sha1-+TNprouafOAv1B+q0MqDAzGQxGM=", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", "dev": true, "requires": { "arr-union": "^3.1.0", @@ -5816,7 +5816,7 @@ "dot-prop": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-4.2.0.tgz", - "integrity": "sha1-HxngwuGqDjJ5fEl5nyg3rGr2nFc=", + "integrity": "sha512-tUMXrxlExSW6U2EXiiKGSBVdYgtV8qlHL+C10TsW4PURY/ic+eaysnSkwB4kA/mBlCyy/IKDJ+Lc3wbWeaXtuQ==", "requires": { "is-obj": "^1.0.0" } @@ -6751,7 +6751,7 @@ }, "file-loader": { "version": "1.1.11", - "resolved": "https://registry.npmjs.org/file-loader/-/file-loader-1.1.11.tgz", + "resolved": "http://registry.npmjs.org/file-loader/-/file-loader-1.1.11.tgz", "integrity": "sha512-TGR4HU7HUsGg6GCOPJnFk06RhWgEWFLAGWiT6rcD+GRC2keU3s9RGJ+b3Z6/U73jwwNb2gKLJ7YCrp+jvU4ALg==", "dev": true, "requires": { @@ -7918,7 +7918,7 @@ "global-modules": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", - "integrity": "sha1-bXcPDrUjrHgWTXK15xqIdyZcw+o=", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", "dev": true, "requires": { "global-prefix": "^1.0.1", @@ -8500,7 +8500,7 @@ "dependencies": { "es6-promise": { "version": "3.3.1", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", + "resolved": "http://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", "integrity": "sha1-oIzd6EzNvzTQJ6FFG8kdS80ophM=", "dev": true }, @@ -9579,7 +9579,7 @@ "is-plain-object": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", - "integrity": "sha1-LBY7P6+xtgbZ0Xko8FwqHDjgdnc=", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", "dev": true, "requires": { "isobject": "^3.0.1" @@ -9935,7 +9935,7 @@ "jasmine-spec-reporter": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/jasmine-spec-reporter/-/jasmine-spec-reporter-4.2.1.tgz", - "integrity": "sha1-HWMq7ANBZwrTJPkrqEtLMrNeniI=", + "integrity": "sha512-FZBoZu7VE5nR7Nilzy+Np8KuVIOxF4oXDPDknehCYBDE080EnlPu0afdZNmpGDBRCUBv3mj5qgqCRmk6W/K8vg==", "dev": true, "requires": { "colors": "1.1.2" @@ -11932,7 +11932,7 @@ }, "minimist": { "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" }, "mississippi": { @@ -12972,7 +12972,7 @@ "dependencies": { "minimist": { "version": "0.0.10", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=", "dev": true }, @@ -14180,7 +14180,7 @@ "dependencies": { "jsesc": { "version": "0.5.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "resolved": "http://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", "dev": true } @@ -14558,7 +14558,7 @@ }, "safe-regex": { "version": "1.1.0", - "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "resolved": "http://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", "dev": true, "requires": { @@ -14648,7 +14648,7 @@ "dependencies": { "source-map": { "version": "0.4.4", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", + "resolved": "http://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", "dev": true, "requires": { @@ -15006,7 +15006,7 @@ "snapdragon-node": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", - "integrity": "sha1-bBdfhv8UvbByRWPo88GwIaKGhTs=", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", "dev": true, "requires": { "define-property": "^1.0.0", @@ -15057,7 +15057,7 @@ "snapdragon-util": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", - "integrity": "sha1-+VZHlIbyrNeXAGk/b3uAXkWrVuI=", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", "dev": true, "requires": { "kind-of": "^3.2.0" @@ -15332,7 +15332,7 @@ "split-string": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", - "integrity": "sha1-fLCd2jqGWFcFxks5pkZgOGguj+I=", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", "dev": true, "requires": { "extend-shallow": "^3.0.0" @@ -16409,7 +16409,7 @@ "touch": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz", - "integrity": "sha1-/jZfX3XsntTlaCXgu3bSSrdK+Ds=", + "integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==", "dev": true, "requires": { "nopt": "~1.0.10" @@ -17888,7 +17888,7 @@ }, "xmlbuilder": { "version": "9.0.7", - "resolved": "http://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", "integrity": "sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0=" }, "xmlcreate": {