diff --git a/.DS_Store b/.DS_Store
new file mode 100644
index 000000000..f0821349b
Binary files /dev/null and b/.DS_Store differ
diff --git a/README.md b/README.md
index ae3d01f1d..8960c8d00 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ ext install dbaeumer.vscode-eslint
You will need to install globally the following items.
```
-# npm install -g jest gulp-cli nodemon
+# sudo npm install -g jest gulp-cli nodemon
```
## Linux Only Prerequisites
diff --git a/back/.DS_Store b/back/.DS_Store
new file mode 100644
index 000000000..a15d86adb
Binary files /dev/null and b/back/.DS_Store differ
diff --git a/back/methods/.DS_Store b/back/methods/.DS_Store
new file mode 100644
index 000000000..810045cc9
Binary files /dev/null and b/back/methods/.DS_Store differ
diff --git a/back/methods/chat/send.js b/back/methods/chat/send.js
index 53e5da7cc..6205bd03e 100644
--- a/back/methods/chat/send.js
+++ b/back/methods/chat/send.js
@@ -47,8 +47,7 @@ module.exports = Self => {
'alias': sender.nickname,
'text': message
}).catch(async error => {
- if (error.statusCode === 401 && !this.resendAttempted) {
- this.resendAttempted = true;
+ if (error.statusCode === 401) {
this.auth = null;
return sendMessage(sender, channel, message);
diff --git a/back/methods/collection/collectionFaults.js b/back/methods/collection/collectionFaults.js
new file mode 100644
index 000000000..395c7e581
--- /dev/null
+++ b/back/methods/collection/collectionFaults.js
@@ -0,0 +1,35 @@
+module.exports = Self => {
+ Self.remoteMethod('collectionFaults', {
+ description: 'Update sale of a collection',
+ accessType: 'WRITE',
+ accepts: [{
+ arg: 'shelvingFk',
+ type: 'String',
+ required: true,
+ description: 'The shalving id'
+ }, {
+ arg: 'quantity',
+ type: 'Number',
+ required: true,
+ description: 'The quantity to sale'
+ }, {
+ arg: 'itemFk',
+ type: 'Number',
+ required: true,
+ description: 'The ticket id'
+ }],
+ returns: {
+ type: 'Object',
+ root: true
+ },
+ http: {
+ path: `/collectionFaults`,
+ verb: 'POST'
+ }
+ });
+
+ Self.collectionFaults = async(shelvingFk, quantity, itemFk) => {
+ query = `CALL vn.collection_faults(?,?,?)`;
+ return await Self.rawSql(query, [shelvingFk, quantity, itemFk]);
+ };
+};
diff --git a/back/methods/collection/getCollection.js b/back/methods/collection/getCollection.js
new file mode 100644
index 000000000..caf9cc521
--- /dev/null
+++ b/back/methods/collection/getCollection.js
@@ -0,0 +1,22 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('getCollection', {
+ description: 'Get pending collections from a worker',
+ accessType: 'READ',
+ returns: {
+ type: 'Object',
+ root: true
+ },
+ http: {
+ path: `/getCollection`,
+ verb: 'GET'
+ }
+ });
+
+ Self.getCollection = async ctx => {
+ const userId = ctx.req.accessToken.userId;
+ const query = `CALL vn.collection_get(?)`;
+ const [result] = await Self.rawSql(query, [userId]);
+
+ return result;
+ };
+};
diff --git a/back/methods/collection/getSectors.js b/back/methods/collection/getSectors.js
new file mode 100644
index 000000000..12ad0dc06
--- /dev/null
+++ b/back/methods/collection/getSectors.js
@@ -0,0 +1,20 @@
+module.exports = Self => {
+ Self.remoteMethod('getSectors', {
+ description: 'Get all sectors',
+ accessType: 'READ',
+ returns: {
+ type: 'Object',
+ root: true
+ },
+ http: {
+ path: `/getSectors`,
+ verb: 'GET'
+ }
+ });
+
+ Self.getSectors = async() => {
+ const query = `CALL vn.sector_get()`;
+ const [result] = await Self.rawSql(query);
+ return result;
+ };
+};
diff --git a/back/methods/collection/newCollection.js b/back/methods/collection/newCollection.js
new file mode 100644
index 000000000..31e419b67
--- /dev/null
+++ b/back/methods/collection/newCollection.js
@@ -0,0 +1,133 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('newCollection', {
+ description: 'Make a new collection of tickets',
+ accessType: 'WRITE',
+ accepts: [{
+ arg: 'collectionFk',
+ type: 'Number',
+ required: false,
+ description: 'The collection id'
+ }, {
+ arg: 'sectorFk',
+ type: 'Number',
+ required: true,
+ description: 'The sector of worker'
+ }, {
+ arg: 'vWagons',
+ type: 'Number',
+ required: true,
+ description: 'The number of wagons'
+ }],
+ returns: {
+ type: 'Object',
+ root: true
+ },
+ http: {
+ path: `/newCollection`,
+ verb: 'POST'
+ }
+ });
+
+ Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => {
+ let query = '';
+
+ if (!collectionFk) {
+ const userId = ctx.req.accessToken.userId;
+ query = `CALL vn.collectionTrain_newBeta(?,?,?)`;
+ const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId]);
+ if (result.length == 0)
+ throw new Error(`No collections for today`);
+
+ collectionFk = result[0].vCollectionFk;
+ }
+
+ query = `CALL vn.collectionTicket_get(?)`;
+ const [tickets] = await Self.rawSql(query, [collectionFk]);
+
+ query = `CALL vn.collectionSale_get(?)`;
+ const [sales] = await Self.rawSql(query, [collectionFk]);
+
+ query = `CALL vn.collectionPlacement_get(?)`;
+ const [placements] = await Self.rawSql(query, [collectionFk]);
+
+ query = `CALL vn.collectionSticker_print(?,?)`;
+ await Self.rawSql(query, [collectionFk, sectorFk]);
+
+ return makeCollection(tickets, sales, placements, collectionFk);
+ };
+
+ /**
+ * Returns a collection json
+ * @param {*} tickets - Request tickets
+ * @param {*} sales - Request sales
+ * @param {*} placements - Request placements
+ * @param {*} collectionFk - Request placements
+ * @return {Object} Collection JSON
+ */
+ async function makeCollection(tickets, sales, placements, collectionFk) {
+ let collection = [];
+
+ for (let i = 0; i < tickets.length; i++) {
+ let ticket = {};
+ ticket['ticketFk'] = tickets[i]['ticketFk'];
+ ticket['level'] = tickets[i]['level'];
+ ticket['agencyName'] = tickets[i]['agencyName'];
+ ticket['warehouseFk'] = tickets[i]['warehouseFk'];
+ ticket['salesPersonFk'] = tickets[i]['salesPersonFk'];
+
+ let ticketSales = [];
+
+ for (let x = 0; x < sales.length; x++) {
+ if (sales[x]['ticketFk'] == ticket['ticketFk']) {
+ let sale = {};
+ sale['collectionFk'] = collectionFk;
+ sale['ticketFk'] = sales[x]['ticketFk'];
+ sale['saleFk'] = sales[x]['saleFk'];
+ sale['itemFk'] = sales[x]['itemFk'];
+ sale['quantity'] = sales[x]['quantity'];
+ if (sales[x]['quantityPicked'] != null)
+ sale['quantityPicked'] = sales[x]['quantityPicked'];
+ else
+ sale['quantityPicked'] = 0;
+ sale['longName'] = sales[x]['longName'];
+ sale['size'] = sales[x]['size'];
+ sale['color'] = sales[x]['color'];
+ sale['discount'] = sales[x]['discount'];
+ sale['price'] = sales[x]['price'];
+ sale['stems'] = sales[x]['stems'];
+ sale['category'] = sales[x]['category'];
+ sale['origin'] = sales[x]['origin'];
+ sale['clientFk'] = sales[x]['clientFk'];
+ sale['productor'] = sales[x]['productor'];
+ sale['reserved'] = sales[x]['reserved'];
+ sale['isPreviousPrepared'] = sales[x]['isPreviousPrepared'];
+ sale['isPrepared'] = sales[x]['isPrepared'];
+ sale['isControlled'] = sales[x]['isControlled'];
+
+ let salePlacements = [];
+
+ for (let z = 0; z < placements.length; z++) {
+ if (placements[z]['saleFk'] == sale['saleFk']) {
+ let placement = {};
+ placement['saleFk'] = placements[z]['saleFk'];
+ placement['itemFk'] = placements[z]['itemFk'];
+ placement['placement'] = placements[z]['placement'];
+ placement['shelving'] = placements[z]['shelving'];
+ placement['created'] = placements[z]['created'];
+ placement['visible'] = placements[z]['visible'];
+ placement['order'] = placements[z]['order'];
+ placement['grouping'] = placements[z]['grouping'];
+ salePlacements.push(placement);
+ }
+ }
+ sale['placements'] = salePlacements;
+ ticketSales.push(sale);
+ }
+ }
+ ticket['sales'] = ticketSales;
+ collection.push(ticket);
+ }
+
+ return collection;
+ }
+};
diff --git a/back/methods/collection/spec/collectionFauls.spec.js b/back/methods/collection/spec/collectionFauls.spec.js
new file mode 100644
index 000000000..210dcdf63
--- /dev/null
+++ b/back/methods/collection/spec/collectionFauls.spec.js
@@ -0,0 +1,9 @@
+const app = require('vn-loopback/server/server');
+describe('collectionFaults()', () => {
+ it('return shelving afected', async() => {
+ let response = await app.models.Collection.collectionFaults('UXN', 0, 1);
+
+ expect(response.length).toBeGreaterThan(0);
+ expect(response[0][0].shelvingFk).toEqual('UXN');
+ });
+});
diff --git a/back/methods/collection/spec/getCollection.spec.js b/back/methods/collection/spec/getCollection.spec.js
new file mode 100644
index 000000000..44c7af62f
--- /dev/null
+++ b/back/methods/collection/spec/getCollection.spec.js
@@ -0,0 +1,11 @@
+const app = require('vn-loopback/server/server');
+
+describe('getCollection()', () => {
+ it('return list of collection', async() => {
+ let ctx = {req: {accessToken: {userId: 106}}};
+ let response = await app.models.Collection.getCollection(ctx);
+
+ expect(response.length).toBeGreaterThan(0);
+ expect(response[0].collectionFk).toEqual(1);
+ });
+});
diff --git a/back/methods/collection/spec/getSectors.spec.js b/back/methods/collection/spec/getSectors.spec.js
new file mode 100644
index 000000000..d453220a0
--- /dev/null
+++ b/back/methods/collection/spec/getSectors.spec.js
@@ -0,0 +1,11 @@
+const app = require('vn-loopback/server/server');
+
+describe('getSectors()', () => {
+ it('return list of sectors', async() => {
+ let response = await app.models.Collection.getSectors();
+
+ expect(response.length).toBeGreaterThan(0);
+ expect(response[0].id).toEqual(1);
+ expect(response[0].description).toEqual('First sector');
+ });
+});
diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js
new file mode 100644
index 000000000..bd574db0f
--- /dev/null
+++ b/back/methods/collection/spec/newCollection.spec.js
@@ -0,0 +1,11 @@
+const app = require('vn-loopback/server/server');
+
+describe('newCollection()', () => {
+ it('return a new collection', async() => {
+ let ctx = {req: {accessToken: {userId: 106}}};
+ let response = await app.models.Collection.newCollection(ctx, 1, 1, 1);
+
+ expect(response.length).toBeGreaterThan(0);
+ expect(response[0].ticketFk).toEqual(1);
+ });
+});
diff --git a/back/methods/collection/spec/updateCollectionSale.spec.js b/back/methods/collection/spec/updateCollectionSale.spec.js
new file mode 100644
index 000000000..4695f6eec
--- /dev/null
+++ b/back/methods/collection/spec/updateCollectionSale.spec.js
@@ -0,0 +1,12 @@
+const app = require('vn-loopback/server/server');
+
+describe('updateCollectionSale()', () => {
+ it('return a new collection', async() => {
+ let ctx = {req: {accessToken: {userId: 106}}};
+ let response = await app.models.Collection.updateCollectionSale(ctx, 1, 5, 5, 5, 1, 4, false, 'UXN', 1, 1);
+
+ expect(response.length).toBeGreaterThan(0);
+ expect(response[0][0].id).toEqual(1);
+ expect(response[0][0].quantity).toEqual(5);
+ });
+});
diff --git a/back/methods/collection/updateCollectionSale.js b/back/methods/collection/updateCollectionSale.js
new file mode 100644
index 000000000..01575c972
--- /dev/null
+++ b/back/methods/collection/updateCollectionSale.js
@@ -0,0 +1,89 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('updateCollectionSale', {
+ description: 'Update sale of a collection',
+ accessType: 'WRITE',
+ accepts: [{
+ arg: 'sale',
+ type: 'Number',
+ required: true,
+ description: 'The sale id'
+ }, {
+ arg: 'originalQuantity',
+ type: 'Number',
+ required: true,
+ description: 'The quantity to sale'
+ },
+ {
+ arg: 'quantity',
+ type: 'Number',
+ required: true,
+ description: 'The quantity to picked'
+ },
+ {
+ arg: 'quantityPicked',
+ type: 'Number',
+ required: true,
+ description: 'The quantity to picked'
+ }, {
+ arg: 'ticketFk',
+ type: 'Number',
+ required: true,
+ description: 'The ticket id'
+ }, {
+ arg: 'stateFk',
+ type: 'Number',
+ required: true,
+ description: 'The state id'
+ }, {
+ arg: 'isNicho',
+ type: 'Boolean',
+ required: true,
+ description: 'Determine if sale is picked from nicho or not'
+ }, {
+ arg: 'shelvingFk',
+ type: 'String',
+ required: false,
+ description: 'The shelving id'
+ }, {
+ arg: 'itemFk',
+ type: 'Number',
+ required: true,
+ description: 'The item id'
+ }, {
+ arg: 'sectorFk',
+ type: 'Number',
+ required: true,
+ description: 'The sector id'
+ }],
+ returns: {
+ type: 'Object',
+ root: true
+ },
+ http: {
+ path: `/updateCollectionSale`,
+ verb: 'POST'
+ }
+ });
+
+ Self.updateCollectionSale = async(ctx, sale, originalQuantity, quantity, quantityPicked, ticketFk, stateFk, isNicho, shelvingFk, itemFk, sectorFk) => {
+ const userId = ctx.req.accessToken.userId;
+
+ if (originalQuantity == quantity) {
+ query = `CALL vn.collection_updateSale(?,?,?,?,?)`;
+ await Self.rawSql(query, [sale, originalQuantity, userId, stateFk, ticketFk]);
+ }
+
+ if (!isNicho) {
+ query = `CALL vn.collection_faults(?,?,?)`;
+ await Self.rawSql(query, [shelvingFk, quantityPicked, itemFk]);
+ } else {
+ query = `CALL vn.sector_getWarehouse(?)`;
+ const [result] = await Self.rawSql(query, [sectorFk]);
+
+ query = `CALL vn.itemPlacementSave(?,?,?)`;
+ await Self.rawSql(query, [shelvingFk, quantityPicked, result[0]['warehouseFk']]);
+ }
+ query = `CALL vn.sale_updateOriginalQuantity(?,?)`;
+ return await Self.rawSql(query, [sale, quantity]);
+ };
+};
diff --git a/back/model-config.json b/back/model-config.json
index 50603be3f..872f2239e 100644
--- a/back/model-config.json
+++ b/back/model-config.json
@@ -14,6 +14,9 @@
"Container": {
"dataSource": "storage"
},
+ "Collection": {
+ "dataSource": "vn"
+ },
"Chat": {
"dataSource": "vn"
},
diff --git a/back/models/collection.js b/back/models/collection.js
new file mode 100644
index 000000000..d3670d56b
--- /dev/null
+++ b/back/models/collection.js
@@ -0,0 +1,7 @@
+module.exports = Self => {
+ require('../methods/collection/getCollection')(Self);
+ require('../methods/collection/newCollection')(Self);
+ require('../methods/collection/getSectors')(Self);
+ require('../methods/collection/updateCollectionSale')(Self);
+ require('../methods/collection/collectionFaults')(Self);
+};
diff --git a/back/models/collection.json b/back/models/collection.json
new file mode 100644
index 000000000..3e428ef60
--- /dev/null
+++ b/back/models/collection.json
@@ -0,0 +1,12 @@
+{
+ "name": "Collection",
+ "base": "VnModel",
+ "acls": [{
+ "property": "validations",
+ "accessType": "EXECUTE",
+ "principalType": "ROLE",
+ "principalId": "$everyone",
+ "permission": "ALLOW"
+ }]
+}
+
\ 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
new file mode 100644
index 000000000..d89f6a801
--- /dev/null
+++ b/db/changes/10162-postValentineDay/00-collectionPlacement_get.sql
@@ -0,0 +1,108 @@
+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
new file mode 100644
index 000000000..5faa42ca4
--- /dev/null
+++ b/db/changes/10162-postValentineDay/00-collection_faults.sql
@@ -0,0 +1,39 @@
+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
new file mode 100644
index 000000000..cce8f4ff5
--- /dev/null
+++ b/db/changes/10162-postValentineDay/00-collection_updateSale.sql
@@ -0,0 +1,42 @@
+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
new file mode 100644
index 000000000..7d3006544
--- /dev/null
+++ b/db/changes/10162-postValentineDay/00-coolerPathDetail.sql
@@ -0,0 +1,13 @@
+/*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
new file mode 100644
index 000000000..debdd3ac2
--- /dev/null
+++ b/db/changes/10162-postValentineDay/00-sale_updateOriginalQuantity.sql
@@ -0,0 +1,15 @@
+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
new file mode 100644
index 000000000..90611b559
--- /dev/null
+++ b/db/changes/10162-postValentineDay/00-sector_getWarehouse.sql
@@ -0,0 +1,14 @@
+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/01-componentRenameMismatchXImbalance.sql b/db/changes/10180-holyWeek/01-componentRenameMismatchXImbalance.sql
new file mode 100644
index 000000000..34dd3be3c
--- /dev/null
+++ b/db/changes/10180-holyWeek/01-componentRenameMismatchXImbalance.sql
@@ -0,0 +1 @@
+UPDATE `vn`.`component` SET `code` = 'imbalance' WHERE (`id` = '36');
diff --git a/db/changes/10180-holyWeek/02-catalog_calculate.sql b/db/changes/10180-holyWeek/02-catalog_calculate.sql
new file mode 100644
index 000000000..eeadb7241
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-catalog_calculate.sql
@@ -0,0 +1,148 @@
+USE `vn`;
+DROP procedure IF EXISTS `catalog_calculate`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`(
+ vLanded DATE,
+ 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 ;
+
diff --git a/db/changes/10180-holyWeek/02-catalog_componentCalculate.sql b/db/changes/10180-holyWeek/02-catalog_componentCalculate.sql
new file mode 100644
index 000000000..04ec1330a
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-catalog_componentCalculate.sql
@@ -0,0 +1,262 @@
+USE `vn`;
+DROP procedure IF EXISTS `catalog_componentCalculate`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`(
+ vZoneFk INT,
+ vAddressFk INT,
+ vShipped DATE,
+ vWarehouseFk INT)
+proc: BEGIN
+/**
+ * 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;
+
+ 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
+ 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 ;
+
diff --git a/db/changes/10180-holyWeek/02-catalog_componentPrepare.sql b/db/changes/10180-holyWeek/02-catalog_componentPrepare.sql
new file mode 100644
index 000000000..98b93a97e
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-catalog_componentPrepare.sql
@@ -0,0 +1,33 @@
+USE `vn`;
+DROP procedure IF EXISTS `catalog_componentPrepare`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE PROCEDURE `catalog_componentPrepare` ()
+BEGIN
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
+ CREATE TEMPORARY TABLE tmp.ticketComponent (
+ `warehouseFk` INT UNSIGNED NOT NULL,
+ `itemFk` INT NOT NULL,
+ `componentFk` INT UNSIGNED NOT NULL,
+ `cost` DECIMAL(10,4) NOT NULL,
+ INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
+ UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)
+ )ENGINE=MEMORY DEFAULT CHARSET=utf8;
+
+ 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 ;
+
diff --git a/db/changes/10180-holyWeek/02-catalog_componentPurge.sql b/db/changes/10180-holyWeek/02-catalog_componentPurge.sql
new file mode 100644
index 000000000..2b744b5f0
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-catalog_componentPurge.sql
@@ -0,0 +1,16 @@
+
+USE `vn`;
+DROP procedure IF EXISTS `vn`.`catalog_componentPurge`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentPurge`()
+BEGIN
+ DROP TEMPORARY TABLE
+ tmp.ticketComponentPrice,
+ tmp.ticketComponent,
+ tmp.ticketLot;
+END$$
+
+DELIMITER ;
+;
diff --git a/db/changes/10180-holyWeek/02-order_confirmWithUser.sql b/db/changes/10180-holyWeek/02-order_confirmWithUser.sql
new file mode 100644
index 000000000..c9acdc038
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-order_confirmWithUser.sql
@@ -0,0 +1,250 @@
+USE `hedera`;
+DROP procedure IF EXISTS `order_confirmWithUser`;
+
+DELIMITER $$
+USE `hedera`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser`(IN `vOrder` INT, IN `vUserId` INT)
+BEGIN
+/**
+ * Confirms an order, creating each of its tickets on the corresponding
+ * date, store and user.
+ *
+ * @param vOrder The order identifier
+ * @param vUser The user identifier
+ */
+ DECLARE vOk BOOL;
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vWarehouse INT;
+ DECLARE vShipment DATETIME;
+ DECLARE vTicket INT;
+ DECLARE vNotes VARCHAR(255);
+ DECLARE vItem INT;
+ DECLARE vConcept VARCHAR(30);
+ DECLARE vAmount INT;
+ DECLARE vPrice DECIMAL(10,2);
+ DECLARE vSale INT;
+ DECLARE vRate INT;
+ DECLARE vRowId INT;
+ DECLARE vDelivery DATE;
+ DECLARE vAddress INT;
+ DECLARE vIsConfirmed BOOL;
+ DECLARE vClientId INT;
+ DECLARE vCompanyId INT;
+ DECLARE vAgencyModeId INT;
+ DECLARE TICKET_FREE INT DEFAULT 2;
+
+ DECLARE cDates CURSOR FOR
+ SELECT zgs.shipped, r.warehouse_id
+ FROM `order` o
+ JOIN order_row r ON r.order_id = o.id
+ LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id
+ WHERE o.id = vOrder AND r.amount != 0
+ GROUP BY r.warehouse_id;
+
+ DECLARE cRows CURSOR FOR
+ SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate
+ FROM order_row r
+ JOIN vn.item i ON i.id = r.item_id
+ WHERE r.amount != 0
+ AND r.warehouse_id = vWarehouse
+ AND r.order_id = vOrder
+ ORDER BY r.rate DESC;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND
+ SET vDone = TRUE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ -- Carga los datos del pedido
+
+ SELECT o.date_send, o.address_id, o.note,
+ o.confirmed, a.clientFk, o.company_id, o.agency_id
+ INTO vDelivery, vAddress, vNotes,
+ vIsConfirmed, vClientId, vCompanyId, vAgencyModeId
+ FROM hedera.`order` o
+ JOIN vn.address a ON a.id = o.address_id
+ WHERE o.id = vOrder;
+
+ -- Comprueba que el pedido no está confirmado
+
+ IF vIsConfirmed THEN
+ CALL util.throw ('ORDER_ALREADY_CONFIRMED');
+ END IF;
+
+ -- Comprueba que el pedido no está vacío
+
+ SELECT COUNT(*) > 0 INTO vOk
+ FROM order_row WHERE order_id = vOrder AND amount > 0;
+
+ IF NOT vOk THEN
+ CALL util.throw ('ORDER_EMPTY');
+ END IF;
+
+ -- Carga las fechas de salida de cada almacén
+
+ CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE);
+
+ -- Trabajador que realiza la acción
+
+ IF vUserId IS NULL THEN
+ SELECT employeeFk INTO vUserId FROM orderConfig;
+ END IF;
+
+ -- Crea los tickets del pedido
+
+ START TRANSACTION;
+
+ OPEN cDates;
+
+ lDates:
+ LOOP
+ SET vTicket = NULL;
+ SET vDone = FALSE;
+ FETCH cDates INTO vShipment, vWarehouse;
+
+ IF vDone THEN
+ LEAVE lDates;
+ END IF;
+
+ -- Busca un ticket existente que coincida con los parametros
+
+ SELECT t.id INTO vTicket
+ FROM vn.ticket t
+ LEFT JOIN vn.ticketState tls on tls.ticket = t.id
+ JOIN `order` o
+ ON o.address_id = t.addressFk
+ AND vWarehouse = t.warehouseFk
+ AND o.agency_id = t.agencyModeFk
+ AND o.date_send = t.landed
+ AND vShipment = DATE(t.shipped)
+ WHERE o.id = vOrder
+ AND t.invoiceOutFk IS NULL
+ AND IFNULL(tls.alertLevel,0) = 0
+ AND t.clientFk <> 1118
+ LIMIT 1;
+
+ -- Crea el ticket en el caso de no existir uno adecuado
+
+ IF vTicket IS NULL
+ THEN
+ CALL vn.ticketCreateWithUser(
+ vClientId,
+ IFNULL(vShipment, CURDATE()),
+ vWarehouse,
+ vCompanyId,
+ vAddress,
+ vAgencyModeId,
+ NULL,
+ vDelivery,
+ vUserId,
+ vTicket
+ );
+ ELSE
+ INSERT INTO vncontrol.inter
+ SET Id_Ticket = vTicket,
+ Id_Trabajador = vUserId,
+ state_id = TICKET_FREE;
+ END IF;
+
+ INSERT IGNORE INTO vn.orderTicket
+ SET orderFk = vOrder,
+ ticketFk = vTicket;
+
+ -- Añade las notas
+
+ IF vNotes IS NOT NULL AND vNotes != ''
+ THEN
+ INSERT INTO vn.ticketObservation SET
+ ticketFk = vTicket,
+ observationTypeFk = 4 /* salesperson */ ,
+ `description` = vNotes
+ ON DUPLICATE KEY UPDATE
+ `description` = CONCAT(VALUES(`description`),'. ', `description`);
+ END IF;
+
+ -- Añade los movimientos y sus componentes
+
+ OPEN cRows;
+
+ lRows:
+ LOOP
+ SET vDone = FALSE;
+ FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate;
+
+ 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;
+
+ 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;
+
+ END LOOP;
+
+ CLOSE cRows;
+
+ -- Fija el coste
+
+ DROP TEMPORARY TABLE IF EXISTS tComponents;
+ CREATE TEMPORARY TABLE tComponents
+ (INDEX (saleFk))
+ ENGINE = MEMORY
+ SELECT SUM(sc.`value`) valueSum, sc.saleFk
+ FROM vn.saleComponent sc
+ JOIN vn.component c ON c.id = sc.componentFk
+ JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.isBase
+ JOIN vn.sale s ON s.id = sc.saleFk
+ WHERE s.ticketFk = vTicket
+ GROUP BY sc.saleFk;
+
+ UPDATE vn.sale s
+ JOIN tComponents mc ON mc.saleFk = s.id
+ SET s.priceFixed = valueSum;
+
+ DROP TEMPORARY TABLE tComponents;
+ END LOOP;
+
+ CLOSE cDates;
+
+ DELETE FROM basketOrder WHERE orderFk = vOrder;
+ UPDATE `order` SET confirmed = TRUE, confirm_date = NOW()
+ WHERE id = vOrder;
+
+ COMMIT;
+END$$
+
+DELIMITER ;
\ No newline at end of file
diff --git a/db/changes/10180-holyWeek/02-sale_calculateComponent.sql b/db/changes/10180-holyWeek/02-sale_calculateComponent.sql
new file mode 100644
index 000000000..979608a35
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-sale_calculateComponent.sql
@@ -0,0 +1,103 @@
+USE `vn`;
+DROP procedure IF EXISTS `sale_calculateComponent`;
+
+DELIMITER $$
+USE `vn`$$
+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 vItemFk 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,
+ vItemFk,
+ 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 != vItemFk;
+
+ DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
+ CREATE TEMPORARY TABLE tmp.ticketLot
+ SELECT vWarehouseFk warehouseFk, NULL available, vItemFk itemFk, buyFk, vZoneFk zoneFk
+ FROM tmp.buyUltimate
+ WHERE itemFk = vItemFk;
+
+ 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 ;
+
diff --git a/db/changes/10180-holyWeek/02-ticketCalculateClon.sql b/db/changes/10180-holyWeek/02-ticketCalculateClon.sql
new file mode 100644
index 000000000..6c9518b3b
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticketCalculateClon.sql
@@ -0,0 +1,93 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticketCalculateClon`;
+
+DELIMITER $$
+USE `vn`$$
+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 ;
+
diff --git a/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice.sql b/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice.sql
new file mode 100644
index 000000000..99ecf739e
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticketCalculateSaleForcePrice.sql
@@ -0,0 +1,61 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticketCalculateSaleForcePrice`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice`(IN vSale BIGINT)
+proc: BEGIN
+
+ DECLARE vShipped DATE;
+ DECLARE vWarehouseFk SMALLINT;
+ DECLARE vAddressFk INT;
+ DECLARE vTicket BIGINT;
+ DECLARE vItem BIGINT;
+ DECLARE vZoneFk INT;
+
+ SELECT ticketFk, itemFk
+ INTO vTicket, vItem
+ FROM sale
+ WHERE id = vSale;
+
+ SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk
+ INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk
+ FROM agencyMode a
+ JOIN ticket t ON t.agencyModeFk = a.id
+ WHERE t.id = vTicket;
+
+ IF vZoneFk IS NULL THEN
+ CALL util.throw('ticket without 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, 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;
+
+ CALL ticketComponentUpdateSale(1);
+
+ 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 tmp.sale;
+
+END$$
+
+DELIMITER ;
+
diff --git a/db/changes/10180-holyWeek/02-ticketComponentUpdateSale.sql b/db/changes/10180-holyWeek/02-ticketComponentUpdateSale.sql
new file mode 100644
index 000000000..b58189ae6
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticketComponentUpdateSale.sql
@@ -0,0 +1,154 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticketComponentUpdateSale`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentUpdateSale`(vOption INT)
+BEGIN
+/**
+ * A partir de la tabla tmp.sale, crea los Movimientos_componentes
+ * y modifica el campo Preu de la tabla Movimientos
+ *
+ * @param i_option integer tipo de actualizacion
+ * @param table tmp.sale tabla memory con el campo saleFk, warehouseFk
+ **/
+ DECLARE vComponentFk INT;
+ DECLARE vRenewComponents BOOLEAN;
+ DECLARE vKeepPrices BOOLEAN;
+
+ CASE vOption
+ WHEN 1 THEN
+ SET vRenewComponents = TRUE;
+ SET vKeepPrices = FALSE;
+ WHEN 2 THEN
+ SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection';
+ SET vRenewComponents = TRUE;
+ SET vKeepPrices = TRUE;
+ WHEN 3 THEN
+ SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana';
+ SET vRenewComponents = TRUE;
+ SET vKeepPrices = TRUE;
+ WHEN 4 THEN
+ SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount';
+ SET vRenewComponents = TRUE;
+ SET vKeepPrices = TRUE;
+ /* WHEN 5 THEN
+ SET vComponentFk = 35;
+ SET vRenewComponents = TRUE;
+ SET vKeepPrices = TRUE;*/
+ WHEN 6 THEN
+ SELECT id INTO vComponentFk FROM component WHERE `code` = 'imbalance';
+ SET vRenewComponents = TRUE;
+ SET vKeepPrices = TRUE;
+ WHEN 7 THEN
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3)
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ AND sc.componentFk NOT IN (28, 29)
+ GROUP BY s.id;
+
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3)
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ AND sc.componentFk NOT IN (28, 29)
+ GROUP BY s.id;
+
+ SET vRenewComponents = FALSE;
+ SET vKeepPrices = FALSE;
+ WHEN 8 THEN
+ DELETE sc.*
+ FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk;
+
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3)
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id;
+
+ SET vRenewComponents = FALSE;
+ SET vKeepPrices = FALSE;
+ WHEN 9 THEN
+ SET vRenewComponents = TRUE;
+ SET vKeepPrices = TRUE;
+ END CASE;
+
+ IF vRenewComponents THEN
+ DELETE sc.*
+ FROM tmp.sale tmps
+ JOIN saleComponent sc ON sc.saleFk = tmps.saleFk
+ JOIN `component` c ON c.id = sc.componentFk
+ WHERE c.isRenewable;
+
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, tc.componentFk, tc.cost
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.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 IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE);
+ END IF;
+
+ IF vKeepPrices THEN
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, vComponentFk, ROUND((s.price * (100 - s.discount) / 100) - SUM(sc.value), 3) dif
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ WHERE sc.saleFk <> vComponentFk
+ GROUP BY s.id
+ HAVING dif <> 0;
+ ELSE
+ UPDATE sale s
+ JOIN item i on i.id = s.itemFk
+ JOIN itemType it on it.id = i.typeFk
+ JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk
+ FROM saleComponent sc
+ JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
+ GROUP BY sc.saleFk) sc ON sc.saleFk = s.id
+ SET s.price = sumValue
+ WHERE it.code != 'PRT' ;
+
+ REPLACE INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ WHERE sc.componentFk != 21
+ GROUP BY s.id
+ HAVING ROUND(saleValue, 4) <> 0;
+ END IF;
+
+ UPDATE sale s
+ JOIN (
+ SELECT SUM(sc.value) sumValue, sc.saleFk
+ FROM saleComponent sc
+ JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
+ JOIN `component` c ON c.id = sc.componentFk
+ JOIN componentType ct on ct.id = c.typeFk AND ct.isBase
+ GROUP BY sc.saleFk) sc ON sc.saleFk = s.id
+ SET s.priceFixed = sumValue, s.isPriceFixed = 1;
+
+ DELETE sc.*
+ FROM saleComponent sc
+ JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
+ JOIN sale s on s.id = sc.saleFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ WHERE it.code = 'PRT';
+
+ INSERT INTO saleComponent(saleFk, componentFk, value)
+ SELECT s.id, 15, s.price
+ FROM sale s
+ JOIN tmp.sale tmps ON tmps.saleFk = s.id
+ JOIN item i ON i.id = s.itemFK
+ JOIN itemType it ON it.id = i.typeFk
+ WHERE it.code = 'PRT' AND s.price > 0;
+END$$
+
+DELIMITER ;
+
diff --git a/db/changes/10180-holyWeek/02-ticket_componentMakeUpdate.sql b/db/changes/10180-holyWeek/02-ticket_componentMakeUpdate.sql
new file mode 100644
index 000000000..7fdf3f193
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticket_componentMakeUpdate.sql
@@ -0,0 +1,107 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticket_componentMakeUpdate`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentMakeUpdate`(
+ 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
+/**
+ * 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 ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk);
+
+ 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 ;
\ No newline at end of file
diff --git a/db/changes/10180-holyWeek/02-ticket_componentPreview.sql b/db/changes/10180-holyWeek/02-ticket_componentPreview.sql
new file mode 100644
index 000000000..d69435bb7
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticket_componentPreview.sql
@@ -0,0 +1,111 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticket_componentPreview`;
+
+DELIMITER $$
+USE `vn`$$
+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
+ *
+ * @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))));
+
+ 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 ;
+
diff --git a/db/changes/10180-holyWeek/02-ticket_priceDifference.sql b/db/changes/10180-holyWeek/02-ticket_priceDifference.sql
new file mode 100644
index 000000000..b80ea7f88
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticket_priceDifference.sql
@@ -0,0 +1,50 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticket_priceDifference`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `ticket_priceDifference`(
+ vTicketFk INT,
+ vLanded DATE,
+ vAddressFk INT,
+ vZoneFk INT,
+ vWarehouseFk INT)
+BEGIN
+/**
+ * Devuelve las diferencias de precio de los movimientos de un ticket.
+ *
+ * @param vTicketFk Id del ticket
+ * @param vLanded Fecha de recepcion
+ * @param vAddressFk Id del consignatario
+ * @param vZoneFk Id de la zona
+ * @param vWarehouseFk Id del almacén
+ */
+ CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk);
+
+ SELECT s.itemFk,
+ i.name,
+ i.size,
+ i.category,
+ IFNULL(s.quantity, 0) AS quantity,
+ IFNULL(s.price, 0) AS price,
+ ROUND(SUM(tc.cost), 2) AS newPrice,
+ s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference,
+ s.id AS saleFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticket t ON t.id = s.ticketFk
+ 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
+ AND IF(sc.componentFk IS NULL
+ AND c.classRate IS NOT NULL, FALSE, TRUE)
+ GROUP BY s.id ORDER BY s.id;
+
+ DROP TEMPORARY TABLE tmp.ticketComponentPreview;
+END$$
+
+DELIMITER ;
+
diff --git a/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql b/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql
new file mode 100644
index 000000000..9ac4942f9
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticket_recalcComponents.sql
@@ -0,0 +1,94 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticket_recalcComponents`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN)
+proc: BEGIN
+
+/**
+ * Este procedimiento recalcula los componentes de un ticket,
+ * eliminando los componentes existentes e insertandolos de nuevo
+ *
+ * @param vTicketFk Id del ticket
+ * @param vIsTicketEditable si no se quiere forzar llamar con NULL
+ */
+ 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 AND IFNULL(t.refFk,'') = ''
+ INTO vIsTicketEditable
+ FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
+ WHERE id = vTicketFk;
+ END IF;
+
+ SELECT t.warehouseFk,
+ t.shipped,
+ t.addressFk,
+ t.agencyModeFk,
+ t.landed,
+ t.zoneFk
+ INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded, vZoneFk
+ FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
+ 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;
+
+ END IF;
+
+ -- 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, vZoneFk zoneFk
+ FROM sale s
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
+ WHERE s.ticketFk = vTicketFk
+ GROUP BY s.itemFk;
+
+ 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;
+
+ -- si el ticket esta facturado, respeta los precios
+ CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6));
+
+ CALL catalog_componentPurge();
+ DROP TEMPORARY TABLE
+ tmp.buyUltimate,
+ tmp.sale;
+END$$
+
+DELIMITER ;
+
diff --git a/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice__.sql b/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice__.sql
new file mode 100644
index 000000000..995bfbfcd
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticket_recalcComponentsForcePrice__.sql
@@ -0,0 +1,2 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`;
diff --git a/db/changes/10180-holyWeek/02-ticket_withoutComponents.sql b/db/changes/10180-holyWeek/02-ticket_withoutComponents.sql
new file mode 100644
index 000000000..de789b956
--- /dev/null
+++ b/db/changes/10180-holyWeek/02-ticket_withoutComponents.sql
@@ -0,0 +1,72 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticket_withoutComponents`;
+DROP procedure IF EXISTS `ticket_checkNoComponents`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `ticket_checkNoComponents`(vShippedFrom DATETIME, vShippedTo DATETIME)
+BEGIN
+
+/**
+ * Comprueba que los tickets entre un rango de fechas tienen componentes
+ *
+ * @param vDatedFrom Id del ticket
+ * @param vIsTicketEditable si no se quiere forzar llamar con NULL
+ */
+ DECLARE v_done BOOL DEFAULT FALSE;
+ DECLARE vSaleFk INTEGER;
+ 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 >= 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 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 >= 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 sale_calculateComponent(vSaleFk, 1);
+ END LOOP;
+
+ CLOSE vCur;
+ DROP TEMPORARY TABLE tmp.coste;
+ END$$
+
+DELIMITER ;
+
diff --git a/db/changes/10180-holyWeek/03-ekt_load.sql b/db/changes/10180-holyWeek/03-ekt_load.sql
new file mode 100644
index 000000000..0c83569b8
--- /dev/null
+++ b/db/changes/10180-holyWeek/03-ekt_load.sql
@@ -0,0 +1,156 @@
+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
+ ,`weight`
+ )
+ 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)
+ ,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
+ LEFT JOIN supplier s ON e.pro = s.supplier_id
+ JOIN vn2008.config cfg
+ WHERE e.id = vSelf
+ LIMIT 1;
+END
\ No newline at end of file
diff --git a/db/changes/10180-holyWeek/03-itemDiary.sql b/db/changes/10180-holyWeek/03-itemDiary.sql
new file mode 100644
index 000000000..d30597e14
--- /dev/null
+++ b/db/changes/10180-holyWeek/03-itemDiary.sql
@@ -0,0 +1,130 @@
+DROP procedure IF EXISTS `vn`.`item_getBalance`;
+
+DELIMITER $$
+USE `vn`$$
+CREATE DEFINER=`root`@`%` PROCEDURE `item_getBalance`(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;
+ SET @shipped = '';
+
+ SELECT DATE(@shipped:= 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 OR alertLevel >= 2)),
+ lineFk,@currentLineFk) lastPreparedLineFk,
+ isTicket,
+ lineFk,isPicked
+ FROM
+ ( SELECT tr.landed as shipped,
+ b.quantity as `in`,
+ NULL as `out`,
+ al.alertLevel as alertLevel,
+ st.name AS stateName,
+ s.name as name,
+ e.ref as reference,
+ e.id as origin,
+ s.id as clientFk,
+ IF(al.alertLevel = 3, TRUE, FALSE) 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.shipped < CURDATE() THEN 3
+ WHEN tr.shipped = CURDATE() AND tr.isReceived = TRUE THEN 3
+ 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 = FALSE
+ AND e.isRaid = FALSE
+ UNION ALL
+
+ SELECT tr.shipped,
+ NULL as `in`,
+ b.quantity as `out`,
+ al.alertLevel as alertLevel,
+ st.name AS stateName,
+ s.name as name,
+ e.ref as reference,
+ e.id as origin,
+ s.id as clientFk,
+ IF(al.alertLevel = 3, TRUE, FALSE) 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.shipped < CURDATE() THEN 3
+ WHEN tr.shipped = CURDATE() AND tr.isReceived = TRUE THEN 3
+ 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 = FALSE
+ AND w.isFeedStock = FALSE
+ AND e.isRaid = FALSE
+ 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, alertLevel DESC, isTicket, `order` DESC, isPicked DESC, `in` DESC, `out` DESC
+ ) AS itemDiary;
+
+END$$
+delimiter ;
\ No newline at end of file
diff --git a/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice2__.sql b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice2__.sql
new file mode 100644
index 000000000..a880135ba
--- /dev/null
+++ b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice2__.sql
@@ -0,0 +1,2 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticketCalculateSaleForcePrice2`;
\ No newline at end of file
diff --git a/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql
new file mode 100644
index 000000000..d7eb5d32b
--- /dev/null
+++ b/db/changes/10180-holyWeek/03-ticketCalculateSaleForcePrice__ .sql
@@ -0,0 +1,2 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticketCalculateSaleForcePrice`;
\ No newline at end of file
diff --git a/db/changes/10180-holyWeek/03-ticketCalculateSale__.sql b/db/changes/10180-holyWeek/03-ticketCalculateSale__.sql
new file mode 100644
index 000000000..acefc29d5
--- /dev/null
+++ b/db/changes/10180-holyWeek/03-ticketCalculateSale__.sql
@@ -0,0 +1,68 @@
+USE `vn`;
+DROP procedure IF EXISTS `ticketCalculateSale`;
+DROP procedure IF EXISTS `ticketCalculateSale__`;
+
+DELIMITER $$
+USE `vn`$$
+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, vZoneFk zoneFk
+ FROM tmp.buyUltimate
+ WHERE itemFk = vItem;
+
+ CALL vn.catalog_componentCalculate;
+ 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;
+
+ CALL ticketComponentUpdateSale(IF(vTicketFree,1,6));
+
+ 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 ;
+
diff --git a/db/changes/10180-holyWeek/03-ticket_componentUpdate__.sql b/db/changes/10180-holyWeek/03-ticket_componentUpdate__.sql
new file mode 100644
index 000000000..f75f157e8
--- /dev/null
+++ b/db/changes/10180-holyWeek/03-ticket_componentUpdate__.sql
@@ -0,0 +1,83 @@
+USE `vn`;
+DROP procedure IF EXISTS `vn`.`ticket_componentUpdate`;
+DROP procedure IF EXISTS `vn`.`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/dump/fixtures.sql b/db/dump/fixtures.sql
index e7cd2f3b1..792787154 100644
--- a/db/dump/fixtures.sql
+++ b/db/dump/fixtures.sql
@@ -21,7 +21,7 @@ INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVo
(1.30, 167.00, 138000, 71);
INSERT INTO `vn`.`chatConfig` (`host`, `api`)
- VALUES
+ VALUES
('https://chat.verdnatura.es', 'https://chat.verdnatura.es/api/v1');
INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`)
@@ -980,6 +980,29 @@ INSERT INTO `vn`.`itemPlacement`(`id`, `itemFk`, `warehouseFk`, `code`)
(3, 1, 3, 'A3'),
(4, 2, 1, 'A4');
+
+INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`)
+ VALUES
+ (1, 106, 5),
+ (2, 106, 14);
+
+INSERT INTO `vn`.`parking` (`column`, `row`, `sectorFk`, `code`, `pickingOrder`)
+ VALUES
+ ('100', '01', 1, '100-01', 1);
+
+INSERT INTO `vn`.`shelving` (`code`, `parkingFk`, `priority`, `userFk`)
+ VALUES
+ ('UXN', 1, 1, 106);
+
+INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `shelve`, `deep`, `quantity`, `visible`, `available`, `grouping`, `packing`, `level`, `userFk`)
+ VALUES
+ (1, 'UXN', 'A', 2, 12, 12, 12, 12, 12, 1, 106);
+
+INSERT INTO `vn`.`ticketCollection` (`ticketFk`, `collectionFk`, `level`)
+ VALUES
+ (1, 1, 1);
+
+
INSERT INTO `edi`.`genus`(`genus_id`, `latin_genus_name`, `entry_date`, `expiry_date`, `change_date_time`)
VALUES
(1, 'Abelia' , CURDATE(), NULL, CURDATE()),
diff --git a/db/dump/structure.sql b/db/dump/structure.sql
index 8e783c833..2a1a168d7 100644
--- a/db/dump/structure.sql
+++ b/db/dump/structure.sql
@@ -4055,16 +4055,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 */ ;
@@ -6703,9 +6703,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 +6723,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 +6761,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 +6860,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 +6896,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 +6916,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 */ ;
@@ -8386,158 +8386,158 @@ DELIMITER ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT)
-BEGIN
- DECLARE vRef INT;
- DECLARE vBuy INT;
- DECLARE vItem INT;
- DECLARE vQty INT;
- DECLARE vPackage INT;
- DECLARE vIsLot BOOLEAN;
- DECLARE vForceToPacking INT DEFAULT 2;
-
- -- Carga los datos necesarios del EKT
-
- SELECT ref, qty, package INTO vRef, vQty, vPackage
- FROM ekt e
- LEFT JOIN item i ON e.ref = i.id
- WHERE e.id = vSelf;
-
- -- Inserta el cubo si no existe
-
- IF vPackage = 800
- THEN
- SET vPackage = 800 + vQty;
-
- INSERT IGNORE INTO vn2008.Cubos SET
- Id_Cubo = vPackage,
- x = 7200 / vQty,
- y = 1;
- ELSE
- INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z)
- SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10)
- FROM bucket WHERE bucket_id = vPackage;
-
- IF ROW_COUNT() > 0
- THEN
- INSERT INTO vn2008.mail SET
- `subject` = 'Cubo añadido',
- `text` = CONCAT('Se ha añadido el cubo: ', vPackage),
- `to` = 'ekt@verdnatura.es';
- END IF;
- END IF;
-
- -- Intenta obtener el artículo en base a los atributos holandeses
-
- INSERT IGNORE INTO item_track SET
- item_id = vRef;
-
- SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem
- FROM vn2008.buy_edi e
- JOIN item_track t ON t.item_id = e.ref
- LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref
- LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id
- JOIN vn2008.config cfg
- WHERE e.id = vSelf
- AND l.id != vSelf
- AND c.Id_Article != cfg.generic_item
- AND IF(t.s1, l.s1 = e.s1, TRUE)
- AND IF(t.s2, l.s2 = e.s2, TRUE)
- AND IF(t.s3, l.s3 = e.s3, TRUE)
- AND IF(t.s4, l.s4 = e.s4, TRUE)
- AND IF(t.s5, l.s5 = e.s5, TRUE)
- AND IF(t.s6, l.s6 = e.s6, TRUE)
- AND IF(t.kop, l.kop = e.kop, TRUE)
- AND IF(t.pac, l.pac = e.pac, TRUE)
- AND IF(t.cat, l.cat = e.cat, TRUE)
- AND IF(t.ori, l.ori = e.ori, TRUE)
- AND IF(t.pro, l.pro = e.pro, TRUE)
- AND IF(t.sub, l.sub = e.sub, TRUE)
- AND IF(t.package, l.package = e.package, TRUE)
- AND c.Id_Article < 170000
- ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1;
-
- -- Determina si el articulo se vende por lotes
-
- IF vItem
- THEN
- SELECT COUNT(*) > 0 INTO vIsLot
- FROM vn2008.Articles a
- LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
- WHERE a.Id_Article = vItem
- AND t.`transaction`;
-
- -- Si el articulo se vende por lotes se inserta un nuevo artículo
-
- IF vIsLot
- THEN
- INSERT INTO vn2008.Articles (
- Article
- ,Medida
- ,Categoria
- ,Id_Origen
- ,iva_group_id
- ,Foto
- ,Color
- ,Codintrastat
- ,tipo_id
- ,Tallos
- )
- SELECT
- i.`name`
- ,IFNULL(e.s1, e.pac)
- ,e.cat
- ,IFNULL(o.id, 17)
- ,IFNULL(a.iva_group_id, 1)
- ,a.Foto
- ,a.Color
- ,a.Codintrastat
- ,IFNULL(a.tipo_id, 10)
- ,IF(a.tipo_id = 15, 0, 1)
- FROM vn2008.buy_edi e
- LEFT JOIN item i ON i.id = e.ref
- LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori
- LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem
- WHERE e.id = vSelf;
-
- SET vItem = LAST_INSERT_ID();
- END IF;
- END IF;
-
- -- Inserta la compra asociada al EKT
-
- INSERT INTO vn2008.Compres
- (
- Id_Entrada
- ,buy_edi_id
- ,Costefijo
- ,Id_Article
- ,`grouping`
- ,caja
- ,Packing
- ,Cantidad
- ,Productor
- ,Etiquetas
- ,Id_Cubo
- )
- SELECT
- cfg.edi_entry
- ,vSelf
- ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri
- ,IFNULL(vItem, cfg.generic_item)
- ,IFNULL(c.`grouping`, e.pac)
- ,vForceToPacking
- ,@pac := e.pac / @t
- ,@pac * e.qty
- ,s.company_name
- ,e.qty
- ,IFNULL(c.Id_Cubo, e.package)
- FROM vn2008.buy_edi e
- LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy
- LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article
- LEFT JOIN supplier s ON e.pro = s.supplier_id
- JOIN vn2008.config cfg
- WHERE e.id = vSelf
- LIMIT 1;
+BEGIN
+ DECLARE vRef INT;
+ DECLARE vBuy INT;
+ DECLARE vItem INT;
+ DECLARE vQty INT;
+ DECLARE vPackage INT;
+ DECLARE vIsLot BOOLEAN;
+ DECLARE vForceToPacking INT DEFAULT 2;
+
+ -- Carga los datos necesarios del EKT
+
+ SELECT ref, qty, package INTO vRef, vQty, vPackage
+ FROM ekt e
+ LEFT JOIN item i ON e.ref = i.id
+ WHERE e.id = vSelf;
+
+ -- Inserta el cubo si no existe
+
+ IF vPackage = 800
+ THEN
+ SET vPackage = 800 + vQty;
+
+ INSERT IGNORE INTO vn2008.Cubos SET
+ Id_Cubo = vPackage,
+ x = 7200 / vQty,
+ y = 1;
+ ELSE
+ INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z)
+ SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10)
+ FROM bucket WHERE bucket_id = vPackage;
+
+ IF ROW_COUNT() > 0
+ THEN
+ INSERT INTO vn2008.mail SET
+ `subject` = 'Cubo añadido',
+ `text` = CONCAT('Se ha añadido el cubo: ', vPackage),
+ `to` = 'ekt@verdnatura.es';
+ END IF;
+ END IF;
+
+ -- Intenta obtener el artículo en base a los atributos holandeses
+
+ INSERT IGNORE INTO item_track SET
+ item_id = vRef;
+
+ SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem
+ FROM vn2008.buy_edi e
+ JOIN item_track t ON t.item_id = e.ref
+ LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref
+ LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id
+ JOIN vn2008.config cfg
+ WHERE e.id = vSelf
+ AND l.id != vSelf
+ AND c.Id_Article != cfg.generic_item
+ AND IF(t.s1, l.s1 = e.s1, TRUE)
+ AND IF(t.s2, l.s2 = e.s2, TRUE)
+ AND IF(t.s3, l.s3 = e.s3, TRUE)
+ AND IF(t.s4, l.s4 = e.s4, TRUE)
+ AND IF(t.s5, l.s5 = e.s5, TRUE)
+ AND IF(t.s6, l.s6 = e.s6, TRUE)
+ AND IF(t.kop, l.kop = e.kop, TRUE)
+ AND IF(t.pac, l.pac = e.pac, TRUE)
+ AND IF(t.cat, l.cat = e.cat, TRUE)
+ AND IF(t.ori, l.ori = e.ori, TRUE)
+ AND IF(t.pro, l.pro = e.pro, TRUE)
+ AND IF(t.sub, l.sub = e.sub, TRUE)
+ AND IF(t.package, l.package = e.package, TRUE)
+ AND c.Id_Article < 170000
+ ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1;
+
+ -- Determina si el articulo se vende por lotes
+
+ IF vItem
+ THEN
+ SELECT COUNT(*) > 0 INTO vIsLot
+ FROM vn2008.Articles a
+ LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
+ WHERE a.Id_Article = vItem
+ AND t.`transaction`;
+
+ -- Si el articulo se vende por lotes se inserta un nuevo artículo
+
+ IF vIsLot
+ THEN
+ INSERT INTO vn2008.Articles (
+ Article
+ ,Medida
+ ,Categoria
+ ,Id_Origen
+ ,iva_group_id
+ ,Foto
+ ,Color
+ ,Codintrastat
+ ,tipo_id
+ ,Tallos
+ )
+ SELECT
+ i.`name`
+ ,IFNULL(e.s1, e.pac)
+ ,e.cat
+ ,IFNULL(o.id, 17)
+ ,IFNULL(a.iva_group_id, 1)
+ ,a.Foto
+ ,a.Color
+ ,a.Codintrastat
+ ,IFNULL(a.tipo_id, 10)
+ ,IF(a.tipo_id = 15, 0, 1)
+ FROM vn2008.buy_edi e
+ LEFT JOIN item i ON i.id = e.ref
+ LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori
+ LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem
+ WHERE e.id = vSelf;
+
+ SET vItem = LAST_INSERT_ID();
+ END IF;
+ END IF;
+
+ -- Inserta la compra asociada al EKT
+
+ INSERT INTO vn2008.Compres
+ (
+ Id_Entrada
+ ,buy_edi_id
+ ,Costefijo
+ ,Id_Article
+ ,`grouping`
+ ,caja
+ ,Packing
+ ,Cantidad
+ ,Productor
+ ,Etiquetas
+ ,Id_Cubo
+ )
+ SELECT
+ cfg.edi_entry
+ ,vSelf
+ ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri
+ ,IFNULL(vItem, cfg.generic_item)
+ ,IFNULL(c.`grouping`, e.pac)
+ ,vForceToPacking
+ ,@pac := e.pac / @t
+ ,@pac * e.qty
+ ,s.company_name
+ ,e.qty
+ ,IFNULL(c.Id_Cubo, e.package)
+ FROM vn2008.buy_edi e
+ LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy
+ LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article
+ LEFT JOIN supplier s ON e.pro = s.supplier_id
+ JOIN vn2008.config cfg
+ WHERE e.id = vSelf
+ LIMIT 1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -8587,154 +8587,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 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 duplicateKey CONDITION FOR 1062;
- 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;
+ 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;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -10810,30 +10810,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 */ ;
@@ -16189,8 +16189,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 +16198,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 +16241,7 @@ proc: BEGIN
END IF;
END IF;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -16509,29 +16509,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 +16564,7 @@ BEGIN
FROM tValues
WHERE !isIn;
- DROP TEMPORARY TABLE tValues;
+ DROP TEMPORARY TABLE tValues;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -29495,90 +29495,90 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN
-
- DECLARE vCurrentCount INT;
- DECLARE vCheckSum INT;
- DECLARE vIsAlreadyNotified BOOLEAN;
- DECLARE vTableQueue TEXT;
- DECLARE vLineQueue TEXT;
- DECLARE vDone BOOL DEFAULT FALSE;
- DECLARE vCur CURSOR FOR
- SELECT CONCAT('
- ', IFNULL(pq.id, ''), ' |
- ', IFNULL(p.path, ''),' |
- ', IFNULL(i.Informe, ''),' |
- ', IFNULL(e.Estado, ''),' |
- ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' |
- ', IFNULL(pq.`error`, ''),' |
-
')
- FROM vn.printingQueue pq
- LEFT JOIN vn.worker w ON w.id = pq.worker
- LEFT JOIN vn.printer p ON p.id = pq.printer
- LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report
- JOIN vn2008.Estados e ON e.Id_Estado = pq.state
- LIMIT 30;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
-
- SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum
- FROM vn.printingQueue WHERE state = 1;
-
- SELECT isAlreadyNotified INTO vIsAlreadyNotified
- FROM printingQueueCheck;
-
- IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND
- (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND
- vIsAlreadyNotified = FALSE AND vCurrentCount > 0
- THEN
-
- SELECT '
-
- Id Cola |
- Ruta Impresora |
- Informe |
- Estado |
- Trabajador |
- Error |
-
' 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, '
'));
-
- 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 '
+
+ Id Cola |
+ Ruta Impresora |
+ Informe |
+ Estado |
+ Trabajador |
+ Error |
+
' 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, '
'));
+
+ 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 */ ;;
@@ -35117,27 +35117,27 @@ DELIMITER ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clean__`()
-BEGIN
- DECLARE vDateShort DATETIME;
- DECLARE oneYearAgo DATE;
- DECLARE twoYearsAgo DATE;
- DECLARE fourYearsAgo DATE;
-
- SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
- SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE());
- SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE());
- SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE());
-
- DELETE FROM vn.message WHERE sendDate < vDateShort;
- DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
- DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
- DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo;
- DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0;
- DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE());
- CALL shelving_clean;
-
+BEGIN
+ DECLARE vDateShort DATETIME;
+ DECLARE oneYearAgo DATE;
+ DECLARE twoYearsAgo DATE;
+ DECLARE fourYearsAgo DATE;
+
+ SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
+ SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE());
+ SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE());
+ SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE());
+
+ DELETE FROM vn.message WHERE sendDate < vDateShort;
+ DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
+ DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
+ DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo;
+ DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0;
+ DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE());
+ CALL shelving_clean;
+
CALL vn.ticketPackagingRecovery;
-
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -35980,54 +35980,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 */ ;
@@ -38951,216 +38951,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 +39222,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 */ ;
@@ -43012,38 +43012,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 */ ;
@@ -47362,77 +47362,77 @@ DELIMITER ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT)
-BEGIN
-
- SET @rest:= CAST(0 AS DECIMAL(10,0));
- SET @saleFk := CAST(0 AS DECIMAL(10,0));
- SET @reserved := CAST(0 AS DECIMAL(10,0));
-
- UPDATE vn.itemShelving ish
- JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id
- JOIN sale s ON s.id = sis.saleFk
- SET ish.visible = sis.quantity + ish.visible,
- ish.available = sis.quantity + ish.visible
- WHERE s.ticketFk = vTicketFk;
-
- DELETE sis.*
- FROM saleItemShelving sis
- JOIN sale s ON s.id = sis.saleFk
- WHERE s.ticketFk = vTicketFk;
-
- INSERT INTO saleItemShelving( saleFk,
- itemShelvingFk,
- quantity,
- ubication)
- SELECT saleFk,
- itemShelvingFk,
- CAST(Reserved as DECIMAL(10,0)) as Reserved,
- ubication
- FROM
- (SELECT saleFk,
- itemShelvingFk,
- ubication,
- @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta,
- @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved,
- @rest := @rest - @reserved,
- @saleFk := saleFk
- FROM
- ( SELECT s.id as saleFk,
- ish.created,
- ish.id as itemShelvingFk,
- ish.available,
- s.quantity,
- ish.packing,
- CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication
- FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk
- JOIN vn.parking p ON p.sectorFk = sc.id
- JOIN vn.shelving sh ON sh.parkingFk = p.id
- JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk
- WHERE t.id = vTicketFk
- AND sc.id = vSectorFk
- AND s.quantity MOD ish.packing = 0
- AND s.quantity >= ish.packing
- ORDER BY s.id,
- sh.priority DESC,
- ish.packing DESC,
- ish.created
- ) sub
- ) sub2
- WHERE Reserved > 0;
-
- UPDATE vn.itemShelving ish
- JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id
- JOIN vn.sale s ON s.id = sis.saleFk
- SET ish.available = ish.visible - sis.quantity,
- ish.visible = ish.visible - sis.quantity
- WHERE s.ticketFk = vTicketFk
- AND s.isPicked = FALSE;
-
- CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE);
-
-
+BEGIN
+
+ SET @rest:= CAST(0 AS DECIMAL(10,0));
+ SET @saleFk := CAST(0 AS DECIMAL(10,0));
+ SET @reserved := CAST(0 AS DECIMAL(10,0));
+
+ UPDATE vn.itemShelving ish
+ JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id
+ JOIN sale s ON s.id = sis.saleFk
+ SET ish.visible = sis.quantity + ish.visible,
+ ish.available = sis.quantity + ish.visible
+ WHERE s.ticketFk = vTicketFk;
+
+ DELETE sis.*
+ FROM saleItemShelving sis
+ JOIN sale s ON s.id = sis.saleFk
+ WHERE s.ticketFk = vTicketFk;
+
+ INSERT INTO saleItemShelving( saleFk,
+ itemShelvingFk,
+ quantity,
+ ubication)
+ SELECT saleFk,
+ itemShelvingFk,
+ CAST(Reserved as DECIMAL(10,0)) as Reserved,
+ ubication
+ FROM
+ (SELECT saleFk,
+ itemShelvingFk,
+ ubication,
+ @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta,
+ @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved,
+ @rest := @rest - @reserved,
+ @saleFk := saleFk
+ FROM
+ ( SELECT s.id as saleFk,
+ ish.created,
+ ish.id as itemShelvingFk,
+ ish.available,
+ s.quantity,
+ ish.packing,
+ CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication
+ FROM vn.sale s
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk
+ JOIN vn.parking p ON p.sectorFk = sc.id
+ JOIN vn.shelving sh ON sh.parkingFk = p.id
+ JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk
+ WHERE t.id = vTicketFk
+ AND sc.id = vSectorFk
+ AND s.quantity MOD ish.packing = 0
+ AND s.quantity >= ish.packing
+ ORDER BY s.id,
+ sh.priority DESC,
+ ish.packing DESC,
+ ish.created
+ ) sub
+ ) sub2
+ WHERE Reserved > 0;
+
+ UPDATE vn.itemShelving ish
+ JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id
+ JOIN vn.sale s ON s.id = sis.saleFk
+ SET ish.available = ish.visible - sis.quantity,
+ ish.visible = ish.visible - sis.quantity
+ WHERE s.ticketFk = vTicketFk
+ AND s.isPicked = FALSE;
+
+ CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE);
+
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -47925,33 +47925,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 */ ;
diff --git a/db/tests/vn/ticket_recalcComponents.spec.js b/db/tests/vn/ticket_recalcComponents.spec.js
index e140db34c..1256528e6 100644
--- a/db/tests/vn/ticket_recalcComponents.spec.js
+++ b/db/tests/vn/ticket_recalcComponents.spec.js
@@ -24,7 +24,7 @@ describe('ticket_recalcComponents()', () => {
let modifiedSales = stmts.push(stmt) - 1;
- stmt = new ParameterizedSQL('CALL vn.ticket_recalcComponents(?)', [
+ stmt = new ParameterizedSQL('CALL vn.ticket_recalcComponents(?, NULL)', [
ticketId,
]);
stmts.push(stmt);
diff --git a/db/tests/vn/zone_getFromGeo.spec.js b/db/tests/vn/zone_getFromGeo.spec.js
new file mode 100644
index 000000000..0dccf92cc
--- /dev/null
+++ b/db/tests/vn/zone_getFromGeo.spec.js
@@ -0,0 +1,28 @@
+const app = require('vn-loopback/server/server');
+const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
+
+describe('zone zone_getFromGeo()', () => {
+ it(`should check that there are some results in table zone`, async() => {
+ let stmts = [];
+ let stmt;
+
+ stmts.push('START TRANSACTION');
+ let geoFk = 17;
+
+ stmt = new ParameterizedSQL('CALL zone_getFromGeo(?)', [
+ geoFk,
+ ]);
+ stmts.push(stmt);
+
+ let tableIndex = stmts.push('SELECT count(*) countZone FROM tmp.zone WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8)') - 1;
+
+ stmts.push('ROLLBACK');
+
+ let sql = ParameterizedSQL.join(stmts, ';');
+ let result = await app.models.Ticket.rawStmt(sql);
+
+ let [zoneTable] = result[tableIndex];
+
+ expect(zoneTable.countZone).toBe(8);
+ });
+});
diff --git a/db/tests/vn/zone_getLanded.spec.js b/db/tests/vn/zone_getLanded.spec.js
new file mode 100644
index 000000000..92c3f435b
--- /dev/null
+++ b/db/tests/vn/zone_getLanded.spec.js
@@ -0,0 +1,66 @@
+const app = require('vn-loopback/server/server');
+const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
+
+describe('zone zone_getLanded()', () => {
+ it(`should return data for a shipped in the past`, async() => {
+ let stmts = [];
+ let stmt;
+
+ stmts.push('START TRANSACTION');
+
+ let params = {
+ addressFk: 121,
+ agencyModeFk: 7,
+ warehouseFk: 1};
+
+ stmt = new ParameterizedSQL('CALL zone_getLanded(DATE_ADD(CURDATE(), INTERVAL -1 DAY), ?, ?, ?)', [
+ params.addressFk,
+ params.agencyModeFk,
+ params.warehouseFk
+
+ ]);
+ stmts.push(stmt);
+
+ let tableIndex = stmts.push('SELECT count(*) countZone FROM tmp.zoneGetLanded') - 1;
+
+ stmts.push('ROLLBACK');
+
+ let sql = ParameterizedSQL.join(stmts, ';');
+ let result = await app.models.Ticket.rawStmt(sql);
+
+ let [zoneTable] = result[tableIndex];
+
+ expect(zoneTable.countZone).toBe(1);
+ });
+
+ it(`should return data for a shipped tomorrow`, async() => {
+ let stmts = [];
+ let stmt;
+
+ stmts.push('START TRANSACTION');
+
+ let params = {
+ addressFk: 121,
+ agencyModeFk: 7,
+ warehouseFk: 1};
+
+ stmt = new ParameterizedSQL('CALL zone_getLanded(DATE_ADD(CURDATE(), INTERVAL +2 DAY), ?, ?, ?)', [
+ params.addressFk,
+ params.agencyModeFk,
+ params.warehouseFk
+
+ ]);
+ stmts.push(stmt);
+
+ let tableIndex = stmts.push('SELECT count(*) countZone FROM tmp.zoneGetLanded') - 1;
+
+ stmts.push('ROLLBACK');
+
+ let sql = ParameterizedSQL.join(stmts, ';');
+ let result = await app.models.Ticket.rawStmt(sql);
+
+ let [zoneTable] = result[tableIndex];
+
+ expect(zoneTable.countZone).toBe(1);
+ });
+});
diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js
index 4343c5e33..4e82dd12a 100644
--- a/e2e/helpers/selectors.js
+++ b/e2e/helpers/selectors.js
@@ -354,7 +354,7 @@ export default {
firstSaleItemId: 'vn-ticket-summary [name="sales"] vn-table vn-tbody > :nth-child(1) > vn-td:nth-child(2) > span',
firstSaleDescriptorImage: '.vn-popover.shown vn-item-descriptor img',
itemDescriptorPopover: '.vn-popover.shown vn-item-descriptor',
- itemDescriptorPopoverItemDiaryButton: 'vn-item-descriptor a[href="#!/item/2/diary?warehouseFk=5&ticketFk=20"]',
+ itemDescriptorPopoverItemDiaryButton: 'vn-item-descriptor a[href="#!/item/2/diary?warehouseFk=5&lineFk=16"]',
popoverDiaryButton: '.vn-popover.shown vn-item-descriptor vn-icon[icon="icon-transaction"]',
firstSaleQuantity: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(3)',
firstSaleDiscount: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(6)',
diff --git a/e2e/paths/05-ticket/11_diary.spec.js b/e2e/paths/05-ticket/11_diary.spec.js
index a75e1ae24..e4c63855a 100644
--- a/e2e/paths/05-ticket/11_diary.spec.js
+++ b/e2e/paths/05-ticket/11_diary.spec.js
@@ -1,7 +1,7 @@
import selectors from '../../helpers/selectors.js';
import getBrowser from '../../helpers/puppeteer';
-// #2221 Local MySQL8 crashes when rest method Items/getDiary is called
+// #2221 Local MySQL8 crashes when rest method Items/getBalance is called
xdescribe('Ticket diary path', () => {
let page;
diff --git a/e2e/paths/05-ticket/12_descriptor.spec.js b/e2e/paths/05-ticket/12_descriptor.spec.js
index 87990bcc5..faeae0c3f 100644
--- a/e2e/paths/05-ticket/12_descriptor.spec.js
+++ b/e2e/paths/05-ticket/12_descriptor.spec.js
@@ -87,7 +87,8 @@ describe('Ticket descriptor path', () => {
expect(message.type).toBe('success');
});
- it(`should check the state of the stowaway ticket is embarked`, async() => {
+ xit(`should check the state of the stowaway ticket is embarked`, async() => {
+ await page.wait(500);
const state = await page.waitToGetProperty(selectors.ticketDescriptor.stateLabelValue, 'innerText');
expect(state).toEqual('State Embarcando');
diff --git a/front/core/directives/specs/dialog.spec.js b/front/core/directives/specs/dialog.spec.js
index fe84cdcc7..e43fca7cf 100644
--- a/front/core/directives/specs/dialog.spec.js
+++ b/front/core/directives/specs/dialog.spec.js
@@ -1,5 +1,4 @@
describe('Directive dialog', () => {
- let $scope;
let $element;
let element;
let compile;
@@ -9,7 +8,7 @@ describe('Directive dialog', () => {
compile = _element => {
inject(($compile, $rootScope) => {
- $scope = $rootScope.$new();
+ let $scope = $rootScope.$new();
$scope.myDialog = controller;
element = angular.element(_element);
$compile(element)($scope);
@@ -17,7 +16,7 @@ describe('Directive dialog', () => {
});
};
- beforeEach(angular.mock.inject(($rootScope, $compile) => {
+ beforeEach(inject(($rootScope, $compile) => {
$element = $compile('')($rootScope);
controller = $element.controller('vnDialog');
}));
diff --git a/front/core/filters/specs/currency.spec.js b/front/core/filters/specs/currency.spec.js
index 28a4a3640..ecb94efe0 100644
--- a/front/core/filters/specs/currency.spec.js
+++ b/front/core/filters/specs/currency.spec.js
@@ -1,41 +1,23 @@
describe('Currency filter', () => {
- let compile;
- let $element;
-
beforeEach(ngModule('vnCore'));
-
- compile = html => {
- inject(($compile, $rootScope) => {
- $element = $compile(html)($rootScope);
- $rootScope.$digest();
- });
- };
+ let currencyFilter;
+ beforeEach(inject(_currencyFilter_ => {
+ currencyFilter = _currencyFilter_;
+ }));
it('should return a ONE decimal number as per the argument', () => {
- let html = `{{200 | currency: 'EUR': 1}}
`;
- compile(html);
-
- expect($element[0].innerHTML).toContain('200.0');
+ expect(currencyFilter(200, 'EUR', 1)).toContain('200.0');
});
it('should return a TWO decimals number as per the argument', () => {
- let html = `{{200 | currency: 'EUR': 2}}
`;
- compile(html);
-
- expect($element[0].innerHTML).toContain('200.00');
+ expect(currencyFilter(200, 'EUR', 2)).toContain('200.00');
});
it('should return a TEN decimals number as per the argument', () => {
- let html = `{{200 | currency: 'EUR': 10}}
`;
- compile(html);
-
- expect($element[0].innerHTML).toContain('200.0000000000');
+ expect(currencyFilter(200, 'EUR', 10)).toContain('200.0000000000');
});
it('sould return nothing when the value is not set', () => {
- let html = `{{null | currency: 'EUR': 2}}
`;
- compile(html);
-
- expect($element[0].innerHTML).toEqual('');
+ expect(currencyFilter(null, 'EUR', 2)).toBeUndefined();
});
});
diff --git a/front/core/filters/specs/dash-if-empty.spec.js b/front/core/filters/specs/dash-if-empty.spec.js
new file mode 100644
index 000000000..552e97445
--- /dev/null
+++ b/front/core/filters/specs/dash-if-empty.spec.js
@@ -0,0 +1,21 @@
+describe('Dash-if-empty filter', () => {
+ let dashIfEmptyFilter;
+
+ beforeEach(ngModule('vnCore'));
+
+ beforeEach(inject(_dashIfEmptyFilter_ => {
+ dashIfEmptyFilter = _dashIfEmptyFilter_;
+ }));
+
+ it('should return a dash if input is null', () => {
+ expect(dashIfEmptyFilter(null)).toBe('-');
+ });
+
+ it('should return a dash if input is empty', () => {
+ expect(dashIfEmptyFilter('')).toBe('-');
+ });
+
+ it('should return same input is there is something', () => {
+ expect(dashIfEmptyFilter('something')).toBe('something');
+ });
+});
diff --git a/front/core/filters/specs/percentage.spec.js b/front/core/filters/specs/percentage.spec.js
new file mode 100644
index 000000000..0936c50ae
--- /dev/null
+++ b/front/core/filters/specs/percentage.spec.js
@@ -0,0 +1,25 @@
+describe('Percentage filter', () => {
+ let percentageFilter;
+
+ beforeEach(ngModule('vnCore'));
+
+ beforeEach(inject(_percentageFilter_ => {
+ percentageFilter = _percentageFilter_;
+ }));
+
+ it('should return null for input null', () => {
+ expect(percentageFilter(null, null)).toBeNull();
+ });
+
+ it('should return null for input empty', () => {
+ expect(percentageFilter('', 2)).toBeNull();
+ });
+
+ it('should return a TWO decimals number', () => {
+ expect(percentageFilter(0, 2)).toBe('0.00%');
+ });
+
+ it('should return zero decimals number', () => {
+ expect(percentageFilter(0.5, 0)).toBe('50%');
+ });
+});
diff --git a/front/core/filters/specs/phone.spec.js b/front/core/filters/specs/phone.spec.js
new file mode 100644
index 000000000..04de345e7
--- /dev/null
+++ b/front/core/filters/specs/phone.spec.js
@@ -0,0 +1,21 @@
+describe('Phone filter', () => {
+ let phoneFilter;
+
+ beforeEach(ngModule('vnCore'));
+
+ beforeEach(inject(_phoneFilter_ => {
+ phoneFilter = _phoneFilter_;
+ }));
+
+ it('should return empty string for input null', () => {
+ expect(phoneFilter(null)).toBe('');
+ });
+
+ it('should return empty stringfor input empty', () => {
+ expect(phoneFilter('')).toBe('');
+ });
+
+ it('should format putting a space every three digits', () => {
+ expect(phoneFilter('999999999')).toBe('999 999 999 ');
+ });
+});
diff --git a/front/core/filters/specs/ucwords.spec.js b/front/core/filters/specs/ucwords.spec.js
new file mode 100644
index 000000000..0f13bd2a5
--- /dev/null
+++ b/front/core/filters/specs/ucwords.spec.js
@@ -0,0 +1,21 @@
+describe('Ucwords filter', () => {
+ let ucwordsFilter;
+
+ beforeEach(ngModule('vnCore'));
+
+ beforeEach(inject(_ucwordsFilter_ => {
+ ucwordsFilter = _ucwordsFilter_;
+ }));
+
+ it('should return empty string for input null', () => {
+ expect(ucwordsFilter(null)).toBe('');
+ });
+
+ it('should return empty stringfor input empty', () => {
+ expect(ucwordsFilter('')).toBe('');
+ });
+
+ it('should format a string uppercasing the first character of each word', () => {
+ expect(ucwordsFilter('abc def')).toBe('Abc Def');
+ });
+});
diff --git a/front/core/filters/specs/zero-fill.spec.js b/front/core/filters/specs/zero-fill.spec.js
new file mode 100644
index 000000000..97f04c655
--- /dev/null
+++ b/front/core/filters/specs/zero-fill.spec.js
@@ -0,0 +1,25 @@
+describe('ZeroFill filter', () => {
+ let zeroFillFilter;
+
+ beforeEach(ngModule('vnCore'));
+
+ beforeEach(inject(_zeroFillFilter_ => {
+ zeroFillFilter = _zeroFillFilter_;
+ }));
+
+ it('should return null for a input null', () => {
+ expect(zeroFillFilter(null, null)).toBeNull();
+ });
+
+ it('should return a positive number pads a number with five zeros', () => {
+ expect(zeroFillFilter(1, 5)).toBe('00001');
+ });
+
+ it('should return negative number pads a number with five zeros', () => {
+ expect(zeroFillFilter(-1, 5)).toBe('-00001');
+ });
+
+ it('should return zero number with zero zeros', () => {
+ expect(zeroFillFilter(0, 1)).toBe('0');
+ });
+});
diff --git a/loopback/.DS_Store b/loopback/.DS_Store
new file mode 100644
index 000000000..5eff1eaf0
Binary files /dev/null and b/loopback/.DS_Store differ
diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html
index eccf45873..abd89a6d7 100644
--- a/modules/client/front/summary/index.html
+++ b/modules/client/front/summary/index.html
@@ -93,7 +93,7 @@
- Pay method
+ Billing data
diff --git a/modules/item/back/methods/item/getDiary.js b/modules/item/back/methods/item/getBalance.js
similarity index 70%
rename from modules/item/back/methods/item/getDiary.js
rename to modules/item/back/methods/item/getBalance.js
index 5d8259867..26fc2a7dc 100644
--- a/modules/item/back/methods/item/getDiary.js
+++ b/modules/item/back/methods/item/getBalance.js
@@ -1,5 +1,5 @@
module.exports = Self => {
- Self.remoteMethod('getDiary', {
+ Self.remoteMethod('getBalance', {
description: 'Returns the ',
accessType: 'READ',
accepts: [{
@@ -14,14 +14,14 @@ module.exports = Self => {
root: true
},
http: {
- path: `/getDiary`,
+ path: `/getBalance`,
verb: 'GET'
}
});
- Self.getDiary = async filter => {
+ Self.getBalance = async filter => {
let where = filter.where;
- let [diary] = await Self.rawSql(`CALL vn.itemDiary(?, ?)`, [where.itemFk, where.warehouseFk]);
+ let [diary] = await Self.rawSql(`CALL vn.item_getBalance(?, ?)`, [where.itemFk, where.warehouseFk]);
return diary;
};
};
diff --git a/modules/item/back/methods/item/specs/getDiary.spec.js b/modules/item/back/methods/item/specs/getDiary.spec.js
index d47ac1d7d..cf9ed9320 100644
--- a/modules/item/back/methods/item/specs/getDiary.spec.js
+++ b/modules/item/back/methods/item/specs/getDiary.spec.js
@@ -1,9 +1,9 @@
const app = require('vn-loopback/server/server');
-describe('item getDiary()', () => {
+describe('item getBalance()', () => {
it('should check the property balance of the 4 resultant entries', async() => {
let params = {where: {itemFk: 1, warehouseFk: 2}};
- let result = await app.models.Item.getDiary(params);
+ let result = await app.models.Item.getBalance(params);
expect(result.length).toBe(4);
expect(result[0].balance).toBe(-100);
diff --git a/modules/item/back/models/item.js b/modules/item/back/models/item.js
index 01061ce99..d273404ea 100644
--- a/modules/item/back/models/item.js
+++ b/modules/item/back/models/item.js
@@ -4,7 +4,7 @@ module.exports = Self => {
require('../methods/item/filter')(Self);
require('../methods/item/clone')(Self);
require('../methods/item/updateTaxes')(Self);
- require('../methods/item/getDiary')(Self);
+ require('../methods/item/getBalance')(Self);
require('../methods/item/getLastEntries')(Self);
require('../methods/item/getSummary')(Self);
require('../methods/item/getCard')(Self);
diff --git a/modules/item/front/diary/index.html b/modules/item/front/diary/index.html
index f7b32621c..eca9410fe 100644
--- a/modules/item/front/diary/index.html
+++ b/modules/item/front/diary/index.html
@@ -1,6 +1,6 @@
@@ -39,11 +39,12 @@
'balanceNegative': sale.balance < 0}"
ng-repeat="sale in sales"
vn-repeat-last
- on-last="$ctrl.scrollToLine()">
+ on-last="$ctrl.scrollToLine(sale.lastPreparedLineFk)"
+ ng-attr-id="vnItemDiary-{{::sale.lineFk}}">
- {{::sale.date | date:'dd/MM/yyyy' }}
+ ng-class="::{warning: $ctrl.today == sale.shipped}">
+ {{::sale.shipped | date:'dd/MM/yyyy' }}
@@ -70,7 +71,8 @@
{{::sale.in | dashIfEmpty}}
{{::sale.out | dashIfEmpty}}
-
+
{{::sale.balance | dashIfEmpty}}
diff --git a/modules/item/front/diary/index.js b/modules/item/front/diary/index.js
index 370039e1f..f9065ca5e 100644
--- a/modules/item/front/diary/index.js
+++ b/modules/item/front/diary/index.js
@@ -3,6 +3,15 @@ import Section from 'salix/components/section';
import './style.scss';
class Controller extends Section {
+ constructor($element, $scope, $anchorScroll, $location) {
+ super($element, $scope);
+ this.$anchorScroll = $anchorScroll;
+ this.$location = $location;
+ let today = new Date();
+ today.setHours(0, 0, 0, 0);
+ this.today = today.toJSON();
+ }
+
get item() {
return this._item;
}
@@ -20,8 +29,8 @@ class Controller extends Section {
else if (value)
this.warehouseFk = value.itemType.warehouseFk;
- if (this.$params.ticketFk)
- this.ticketFk = this.$params.ticketFk;
+ if (this.$params.lineFk)
+ this.lineFk = this.$params.lineFk;
});
}
@@ -42,99 +51,16 @@ class Controller extends Section {
return this._warehouseFk;
}
- get freeLineIndex() {
- let lines = this.$.model.data;
- let minDate = new Date();
- minDate.setHours(0, 0, 0, 0);
-
- let maxDate = new Date();
- maxDate.setHours(23, 59, 59, 59);
-
- for (let i = 0; i < lines.length; i++) {
- const dated = new Date(lines[i].date);
-
- let isForFuture = dated > maxDate;
- let isForToday = (dated >= minDate && dated <= maxDate);
- if (isForFuture || isForToday)
- return i;
- }
- }
-
- get onPreparationLineIndex() {
- let lines = this.$.model.data;
- for (let i = this.freeLineIndex; i >= 0; i--) {
- let line = lines[i];
-
- let currentDate = new Date();
- currentDate.setHours(0, 0, 0, 0);
-
- let isPastDate = new Date(lines[i].date) < currentDate;
- let isPicked = line.alertLevel == 1 && line.isPicked;
-
- if ((isPicked) || line.alertLevel > 1 || isPastDate)
- return i + 1;
- }
- }
-
- get givenTicketIndex() {
- let lines = this.$.model.data;
-
- for (let i = lines.length - 1; i > 0; i--) {
- let line = lines[i];
-
- if (line.origin == this.ticketFk)
- return i;
- }
- }
-
- scrollToLine() {
- let body = this.$window.document.body;
- let selectedTicketLineIndex = this.givenTicketIndex;
- let lineIndex = this.onPreparationLineIndex;
-
- let lines = body.querySelector('vn-tbody').children;
-
- if (lineIndex == undefined || !lines.length) return;
-
- let onPreparationLine = lines[lineIndex];
-
- let balance = onPreparationLine.querySelector('.balanceSpan');
- balance.classList.add('message');
- balance.title = this.$translate.instant('Visible quantity');
-
- let headerOffset = body.querySelector('vn-topbar').getBoundingClientRect();
- let headerHeight = headerOffset.height;
-
- let offsetTop;
- if (this.ticketFk) {
- let selectedTicketLine = lines[selectedTicketLineIndex];
- let id = selectedTicketLine.querySelector('[name=origin]');
- id.classList.add('message');
- offsetTop = selectedTicketLine.offsetTop - headerHeight;
- } else
- offsetTop = onPreparationLine.offsetTop - headerHeight;
-
- this.$window.scrollTo(0, offsetTop);
- this.ticketFk = null;
- }
-
- /**
- * Compares a date with the current one
- * @param {Object} date - Date to compare
- * @return {Boolean} - Returns true if the two dates equals
- */
- isToday(date) {
- let today = new Date();
- today.setHours(0, 0, 0, 0);
-
- let comparedDate = new Date(date);
- comparedDate.setHours(0, 0, 0, 0);
-
- if (!(today - comparedDate))
- return true;
+ scrollToLine(lineFk) {
+ const hashFk = this.lineFk || lineFk;
+ const hash = `vnItemDiary-${hashFk}`;
+ this.$location.hash(hash);
+ this.$anchorScroll();
}
}
+Controller.$inject = ['$element', '$scope', '$anchorScroll', '$location'];
+
ngModule.component('vnItemDiary', {
template: require('./index.html'),
controller: Controller,
diff --git a/modules/item/front/diary/index.spec.js b/modules/item/front/diary/index.spec.js
index 94458a569..ccf7ac1a1 100644
--- a/modules/item/front/diary/index.spec.js
+++ b/modules/item/front/diary/index.spec.js
@@ -16,56 +16,6 @@ describe('Item', () => {
controller.$params = {id: 1};
}));
- describe('isToday()', () => {
- it(`should call isToday() an return true if an specified date is the current date`, () => {
- let date = new Date();
-
- let result = controller.isToday(date);
-
- expect(result).toBeTruthy();
- });
-
- it(`should call isToday() an return false if an specified date is the current date`, () => {
- let date = '2018-07-03';
-
- let result = controller.isToday(date);
-
- expect(result).toBeFalsy();
- });
- });
-
- describe('freeLineIndex()', () => {
- it(`should call freeLineIndex() and return an index from line with alertLevel 0 and current date`, () => {
- let currentDate = new Date();
- currentDate.setDate(currentDate.getDate() + 1);
-
- controller.$.model = {data: [
- {name: 'My item 1', alertLevel: 3, date: '2018-05-02'},
- {name: 'My item 2', alertLevel: 1, date: '2018-05-03'},
- {name: 'My item 3', alertLevel: 0, date: currentDate}]
- };
- let result = controller.freeLineIndex;
-
- expect(result).toEqual(2);
- });
- });
-
- describe('onPreparationLineIndex()', () => {
- it(`should call onPreparationLineIndex() and return an index from line with alertLevel 1 and isPicked true`, () => {
- let currentDate = new Date();
- currentDate.setDate(currentDate.getDate() + 1);
- controller.$.model = {data: [
- {name: 'My item 1', alertLevel: 3, isPicked: true, date: currentDate},
- {name: 'My item 3', alertLevel: 1, isPicked: true, date: currentDate},
- {name: 'My item 4', alertLevel: 1, isPicked: false, date: currentDate},
- {name: 'My item 5', alertLevel: 0, isPicked: false, date: currentDate}]
- };
- let result = controller.onPreparationLineIndex;
-
- expect(result).toEqual(1);
- });
- });
-
describe('set item()', () => {
it('should set warehouseFk property based on itemType warehouseFk', () => {
jest.spyOn(controller.$, '$applyAsync');
@@ -90,21 +40,6 @@ describe('Item', () => {
expect(controller.item.id).toEqual(1);
});
});
-
- describe('givenTicketIndex() setter', () => {
- it(`should return the index position of the line of a given ticket fk`, () => {
- controller.$.model = {data: [
- {name: 'My item 1', origin: 1, alertLevel: 3, isPicked: true, date: '2018-05-02'},
- {name: 'My item 3', origin: 2, alertLevel: 1, isPicked: true, date: '2018-05-03'},
- {name: 'My item 4', origin: 3, alertLevel: 1, isPicked: false, date: '2018-05-03'}]
- };
- controller.ticketFk = 2;
-
- let index = controller.givenTicketIndex;
-
- expect(controller.$.model.data[index].origin).toEqual(2);
- });
- });
});
});
diff --git a/modules/item/front/routes.json b/modules/item/front/routes.json
index a3cf0bee6..2aab4301e 100644
--- a/modules/item/front/routes.json
+++ b/modules/item/front/routes.json
@@ -107,7 +107,7 @@
"item": "$ctrl.item"
}
}, {
- "url" : "/diary?warehouseFk&ticketFk",
+ "url" : "/diary?warehouseFk&lineFk",
"state": "item.card.diary",
"component": "vn-item-diary",
"description": "Diary",
diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js
index 938efa7e5..fe08794f1 100644
--- a/modules/ticket/back/methods/ticket-request/confirm.js
+++ b/modules/ticket/back/methods/ticket-request/confirm.js
@@ -57,7 +57,6 @@ module.exports = Self => {
if (stock.available < 0)
throw new UserError(`This item is not available`);
-
if (request.saleFk) {
sale = await models.Sale.findById(request.saleFk, null, options);
await sale.updateAttributes({
@@ -79,7 +78,7 @@ module.exports = Self => {
}, options);
}
- query = `CALL vn.ticketCalculateSale(?)`;
+ query = `CALL vn.sale_calculateComponent(?, NULL)`;
await Self.rawSql(query, [sale.id], options);
const origin = ctx.req.headers.origin;
diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js
index bb833709e..c1081c4be 100644
--- a/modules/ticket/back/methods/ticket/addSale.js
+++ b/modules/ticket/back/methods/ticket/addSale.js
@@ -60,7 +60,7 @@ module.exports = Self => {
quantity: quantity
});
- await Self.rawSql('CALL vn.ticketCalculateSale(?)', [newSale.id]);
+ await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id]);
return models.Sale.findById(newSale.id, {
include: {
diff --git a/modules/ticket/back/methods/ticket/recalculateComponents.js b/modules/ticket/back/methods/ticket/recalculateComponents.js
index 81fee4d70..0648983c5 100644
--- a/modules/ticket/back/methods/ticket/recalculateComponents.js
+++ b/modules/ticket/back/methods/ticket/recalculateComponents.js
@@ -26,6 +26,6 @@ module.exports = Self => {
if (!isEditable)
throw new UserError(`The current ticket can't be modified`);
- return Self.rawSql('CALL vn.ticket_recalcComponents(?)', [id]);
+ return Self.rawSql('CALL vn.ticket_recalcComponents(?, NULL)', [id]);
};
};
diff --git a/modules/ticket/front/component/index.html b/modules/ticket/front/component/index.html
index 8e5f74173..20ee592c1 100644
--- a/modules/ticket/front/component/index.html
+++ b/modules/ticket/front/component/index.html
@@ -27,7 +27,7 @@
{{sale.itemFk | zeroFill:6}}
@@ -66,6 +66,5 @@
+ warehouse-fk="$ctrl.ticket.warehouseFk">
\ No newline at end of file
diff --git a/modules/ticket/front/locale/es.yml b/modules/ticket/front/locale/es.yml
index b26a6d6fa..5cc2e115e 100644
--- a/modules/ticket/front/locale/es.yml
+++ b/modules/ticket/front/locale/es.yml
@@ -76,5 +76,5 @@ Tracking: Estados
Sale checked: Control clientes
Components: Componentes
Sale tracking: Líneas preparadas
-Photos: Fotos
+Pictures: Fotos
Log: Historial
\ No newline at end of file
diff --git a/modules/ticket/front/request/index/index.html b/modules/ticket/front/request/index/index.html
index 063e48ddd..3335a8a06 100644
--- a/modules/ticket/front/request/index/index.html
+++ b/modules/ticket/front/request/index/index.html
@@ -73,7 +73,7 @@
{{::request.saleFk | zeroFill:6}}
@@ -101,8 +101,7 @@
+ vn-id="itemDescriptor">
diff --git a/modules/ticket/front/routes.json b/modules/ticket/front/routes.json
index d95788036..6f54a8efd 100644
--- a/modules/ticket/front/routes.json
+++ b/modules/ticket/front/routes.json
@@ -12,18 +12,18 @@
"card": [
{"state": "ticket.card.basicData.stepOne", "icon": "settings"},
{"state": "ticket.card.sale", "icon": "icon-lines"},
+ {"state": "ticket.card.request.index", "icon": "icon-100"},
+ {"state": "ticket.card.tracking.index", "icon": "remove_red_eye"},
+ {"state": "ticket.card.log", "icon": "history"},
{"state": "ticket.card.observation", "icon": "insert_drive_file"},
+ {"state": "ticket.card.picture", "icon": "image"},
{"state": "ticket.card.volume", "icon": "icon-volume"},
{"state": "ticket.card.expedition", "icon": "icon-package"},
{"state": "ticket.card.service", "icon": "icon-services"},
{"state": "ticket.card.package", "icon": "icon-bucket"},
- {"state": "ticket.card.tracking.index", "icon": "remove_red_eye"},
{"state": "ticket.card.saleChecked", "icon": "assignment"},
{"state": "ticket.card.components", "icon": "icon-components"},
{"state": "ticket.card.saleTracking", "icon": "assignment"},
- {"state": "ticket.card.picture", "icon": "image"},
- {"state": "ticket.card.log", "icon": "history"},
- {"state": "ticket.card.request.index", "icon": "icon-100"},
{"state": "ticket.card.dms.index", "icon": "cloud_download"}
]
},
diff --git a/modules/ticket/front/sale-checked/index.html b/modules/ticket/front/sale-checked/index.html
index 659d1b990..78ed6dfdc 100644
--- a/modules/ticket/front/sale-checked/index.html
+++ b/modules/ticket/front/sale-checked/index.html
@@ -29,7 +29,7 @@
{{::sale.itemFk | zeroFill:6}}
diff --git a/modules/ticket/front/sale-tracking/index.html b/modules/ticket/front/sale-tracking/index.html
index 2faa13881..cf8f31d8e 100644
--- a/modules/ticket/front/sale-tracking/index.html
+++ b/modules/ticket/front/sale-tracking/index.html
@@ -34,7 +34,7 @@
{{sale.itemFk | zeroFill:6}}
@@ -65,8 +65,7 @@
+ warehouse-fk="$ctrl.ticket.warehouseFk">
diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html
index 214aebc9f..29294fd97 100644
--- a/modules/ticket/front/sale/index.html
+++ b/modules/ticket/front/sale/index.html
@@ -83,18 +83,18 @@
+ vn-tooltip="{{::$ctrl.$t('Claim')}}: {{::sale.claim.claimFk}}">
+ vn-tooltip="Visible: {{::sale.visible || 0}} {{::$ctrl.$t('Available')}}: {{::sale.available || 0}}">
+ icon="icon-reserve"
+ vn-tooltip="{{::$ctrl.$t('Reserved')}}">
@@ -105,7 +105,7 @@
+ ng-click="descriptor.show($event, sale.itemFk, sale.id)">
{{sale.itemFk}}
{{sale.itemFk | zeroFill:6}}
@@ -208,7 +208,7 @@
{{request.sale.itemFk | zeroFill:6}}
diff --git a/modules/ticket/front/volume/index.html b/modules/ticket/front/volume/index.html
index 84abb67c1..23f179fc4 100644
--- a/modules/ticket/front/volume/index.html
+++ b/modules/ticket/front/volume/index.html
@@ -37,7 +37,7 @@
{{sale.itemFk | zeroFill:6}}
@@ -60,7 +60,6 @@
+ warehouse-fk="$ctrl.ticket.warehouseFk">
diff --git a/modules/zone/front/create/index.html b/modules/zone/front/create/index.html
index 332e8a9b8..07ac38477 100644
--- a/modules/zone/front/create/index.html
+++ b/modules/zone/front/create/index.html
@@ -50,7 +50,7 @@
diff --git a/modules/zone/front/create/locale/es.yml b/modules/zone/front/create/locale/es.yml
index 7c1317ca7..4827ced37 100644
--- a/modules/zone/front/create/locale/es.yml
+++ b/modules/zone/front/create/locale/es.yml
@@ -1,3 +1,3 @@
Traveling days: Días de viaje
-Closing hour (ETD): Hora de cierre (ETD)
+Closing hour: Hora de cierre
Bonus: Bonificación
\ No newline at end of file
diff --git a/modules/zone/front/descriptor/index.html b/modules/zone/front/descriptor/index.html
index 3fb243a62..e1fa1c0ea 100644
--- a/modules/zone/front/descriptor/index.html
+++ b/modules/zone/front/descriptor/index.html
@@ -19,7 +19,7 @@
value="{{$ctrl.zone.agencyMode.name}}">
-
\ No newline at end of file
+
diff --git a/modules/zone/front/index/index.html b/modules/zone/front/index/index.html
index 790dd276b..55760d770 100644
--- a/modules/zone/front/index/index.html
+++ b/modules/zone/front/index/index.html
@@ -23,7 +23,7 @@
class="clickable search-result">
{{::zone.id}}
{{::zone.name}}
- {{::zone.agencyMode.name}}
+ {{::zone.agencyMode.name}}
{{::zone.hour | date: 'HH:mm'}}
{{::zone.price | currency: 'EUR':2}}
diff --git a/modules/zone/front/summary/index.html b/modules/zone/front/summary/index.html
index c2694da45..20f74916e 100644
--- a/modules/zone/front/summary/index.html
+++ b/modules/zone/front/summary/index.html
@@ -13,7 +13,7 @@
-
|