diff --git a/CHANGELOG.md b/CHANGELOG.md
index f59a3d4c6..6db79a40a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,61 @@
+# Version 24.32 - 2024-08-06
+
+### Added 🆕
+
+- chore: refs #7197 add supplierActivityFk filter by:jorgep
+- feat checkExpeditionPrintOut refs #7751 by:sergiodt
+- feat(defaulter_filter): add department by:alexm
+- feat: redirect to lilium page not found by:alexm
+- feat: refactor buyUltimate refs #7736 by:Carlos Andrés
+- feat: refs #6403 add delete by:pablone
+- feat: refs #7126 Added manaClaim calc by:guillermo
+- feat: refs #7126 Refactor and added columns in bs.waste table & proc by:guillermo
+- feat: refs #7197 filter by correcting by:jorgep
+- feat: refs #7297 add new columns by:pablone
+- feat: refs #7356 new parameters in sql for Weekly tickets front by:Jon
+- feat: refs #7401 redirect lilium by:pablone
+- feat: refs #7511 Fix tests by:guillermo
+- feat: refs #7511 Rename to multiConfig tables by:guillermo
+- feat: refs #7589 Added display (item_valuateInventory) by:guillermo
+- feat: refs #7589 Added vItemTypeFk & vItemCategoryFk (item_valuateInventory) by:guillermo
+- feat: refs #7681 Changes by:guillermo
+- feat: refs #7681 Optimization and refactor by:guillermo
+- feat: refs #7683 drop temporary table by:robert
+- feat: refs #7683 productionControl by:robert
+- feat: refs #7728 Added throw due date by:guillermo
+- feat: refs #7740 Ticket before update added restriction by:guillermo
+- feat(salix): #7648 Add field for endpoint as buyLabel report by:Javier Segarra
+- feat(salix): #7648 remove white line by:Javier Segarra
+- feat: tabla config dias margen vctos. refs #7728 by:Carlos Andrés
+
+### Changed 📦
+
+- eat: refactor buyUltimate refs #7736 by:Carlos Andrés
+- feat: refactor buyUltimate refs #7736 by:Carlos Andrés
+- feat: refs #7681 Optimization and refactor by:guillermo
+- refactor: refs #7126 Requested changes by:guillermo
+- refactor: refs #7511 Minor change by:guillermo
+- refactor: refs #7640 Multipleinventory available by:guillermo
+- refactor: refs #7681 Changes by:guillermo
+- refactor: refs #7681 Requested changes by:guillermo
+
+### Fixed 🛠️
+
+- add prefix (hotFix_liliumRedirection) by:alexm
+- fix(client_filter): add recovery by:alexm
+- fix: defaulter filter correct sql (6943-fix_defaulter_filter) by:alexm
+- fix(deletExpeditions): merge test → dev by:guillermo
+- fix: refs #6403 fix mrw cancel shipment return type by:pablone
+- fix: refs #7126 Added addressWaste type by:guillermo
+- fix: refs #7126 Fix by:guillermo
+- fix: refs #7126 Minor change by:guillermo
+- fix: refs #7126 Primary key no unique data by:guillermo
+- fix: refs #7126 Slow update by:guillermo
+- fix: refs #7511 Minor change by:guillermo
+- fix: refs #7546 Deleted insert util.binlogQueue by:guillermo
+- fix: refs #7811 Variables pm2 by:guillermo
+- fix: without path by:alexm
+
# Version 24.28 - 2024-07-09
### Added 🆕
diff --git a/back/methods/collection/assign.js b/back/methods/collection/assign.js
index 718cd48c5..f246043b8 100644
--- a/back/methods/collection/assign.js
+++ b/back/methods/collection/assign.js
@@ -20,13 +20,14 @@ module.exports = Self => {
if (typeof options == 'object')
Object.assign(myOptions, options);
+ const randStr = Math.random().toString(36).substring(3);
const result = await Self.rawSql(`
CALL vn.collection_assign(?, @vCollectionFk);
- SELECT @vCollectionFk collectionFk
- `, [userId], myOptions);
+ SELECT @vCollectionFk ?
+ `, [userId, randStr], myOptions);
- // Por si entra en el SELECT FOR UPDATE y retorna un array más
- const collectionFk = result[2]?.[0]?.collectionFk || result[3]?.[0]?.collectionFk;
+ // Por si entra en SELECT FOR UPDATE una o varias veces
+ const collectionFk = result.find(item => item[0]?.[randStr] !== undefined)?.[0]?.[randStr];
if (!collectionFk) throw new UserError('There are not picking tickets');
await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions);
diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js
index b79dbc93a..2a2b67524 100644
--- a/back/methods/collection/getTickets.js
+++ b/back/methods/collection/getTickets.js
@@ -57,8 +57,10 @@ module.exports = Self => {
ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving,
COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving,
sh.code,
- IFNULL(p2.code, p.code) parkingCode,
- IFNULL(p2.pickingOrder, p.pickingOrder) pickingOrder,
+ p2.code parkingCode,
+ p2.pickingOrder pickingOrder,
+ p.code parkingCodePrevia,
+ p.pickingOrder pickingOrderPrevia,
iss.id itemShelvingSaleFk,
iss.isPicked
FROM ticketCollection tc
@@ -95,8 +97,10 @@ module.exports = Self => {
ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY p.pickingOrder),
COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) ,
sh.code,
- IFNULL(p2.code, p.code),
- IFNULL(p2.pickingOrder, p.pickingOrder),
+ p2.code,
+ p2.pickingOrder,
+ p.code,
+ p.pickingOrder,
iss.id itemShelvingSaleFk,
iss.isPicked
FROM sectorCollection sc
diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js
index 0efd00874..56d206529 100644
--- a/back/methods/mrw-config/cancelShipment.js
+++ b/back/methods/mrw-config/cancelShipment.js
@@ -37,7 +37,6 @@ module.exports = Self => {
});
const xmlString = response.data;
- console.log('xmlString: ', xmlString);
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
const result = xmlDoc.getElementsByTagName('Mensaje')[0].textContent;
diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js
index 3b91f4486..2ebb80774 100644
--- a/back/methods/mrw-config/createShipment.js
+++ b/back/methods/mrw-config/createShipment.js
@@ -47,7 +47,7 @@ module.exports = Self => {
co.code countryCode,
c.fi,
c.name clientName,
- a.mobile,
+ IFNULL(a.mobile, c.mobile) mobile,
DATE_FORMAT(t.shipped, '%d/%m/%Y') created,
t.shipped,
CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference,
diff --git a/back/methods/postcode/filter.js b/back/methods/postcode/filter.js
index 8b0f64d97..f350b1ea9 100644
--- a/back/methods/postcode/filter.js
+++ b/back/methods/postcode/filter.js
@@ -11,13 +11,6 @@ module.exports = Self => {
arg: 'filter',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
- http: {source: 'query'}
- },
- {
- arg: 'search',
- type: 'string',
- description: 'Value to filter',
- http: {source: 'query'}
},
],
returns: {
@@ -29,13 +22,11 @@ module.exports = Self => {
verb: 'GET',
},
});
- Self.filter = async(ctx, filter, options) => {
+ Self.filter = async(filter = {}, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
- filter = ctx?.filter ?? {};
-
const conn = Self.dataSource.connector;
const where = buildFilter(filter?.where, (param, value) => {
switch (param) {
@@ -50,31 +41,33 @@ module.exports = Self => {
};
}
}) ?? {};
- delete ctx.filter.where;
+ delete filter.where;
const stmts = [];
let stmt;
stmt = new ParameterizedSQL(`
- SELECT
- pc.townFk,
- t.provinceFk,
- p.countryFk,
- pc.code,
- t.name as town,
- p.name as province,
- c.name country
- FROM
- postCode pc
- JOIN town t on t.id = pc.townFk
- JOIN province p on p.id = t.provinceFk
- JOIN country c on c.id = p.countryFk
+ SELECT
+ pc.townFk,
+ t.provinceFk,
+ p.countryFk,
+ pc.code,
+ t.name as town,
+ p.name as province,
+ c.name country
+ FROM
+ postCode pc
+ JOIN town t on t.id = pc.townFk
+ JOIN province p on p.id = t.provinceFk
+ JOIN country c on c.id = p.countryFk
`);
- stmt.merge(conn.makeSuffix({where, ...ctx}));
+ stmt.merge(conn.makeSuffix({where}));
+ stmt.merge(conn.makeLimit(filter));
const itemsIndex = stmts.push(stmt) - 1;
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions);
+
return itemsIndex === 0 ? result : result[itemsIndex];
};
};
diff --git a/back/methods/postcode/specs/filter.spec.js b/back/methods/postcode/specs/filter.spec.js
index 60ac24809..abf450a19 100644
--- a/back/methods/postcode/specs/filter.spec.js
+++ b/back/methods/postcode/specs/filter.spec.js
@@ -6,12 +6,9 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
- const ctx = {
- filter: {
- },
+ const results = await models.Postcode.filter({
limit: 1
- };
- const results = await models.Postcode.filter(ctx, options);
+ }, options);
expect(results.length).toEqual(1);
await tx.rollback();
@@ -26,14 +23,11 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
- const ctx = {
- filter: {
- where: {
- search: 46,
- }
- },
- };
- const results = await models.Postcode.filter(ctx, options);
+ const results = await models.Postcode.filter({
+ where: {
+ search: 46,
+ }
+ }, options);
expect(results.length).toEqual(4);
await tx.rollback();
@@ -48,14 +42,9 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
- const ctx = {
- filter: {
- where: {
- search: 'Alz',
- }
- },
- };
- const results = await models.Postcode.filter(ctx, options);
+ const results = await models.Postcode.filter({where: {
+ search: 'Alz',
+ }}, options);
expect(results.length).toEqual(1);
await tx.rollback();
@@ -70,14 +59,9 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
- const ctx = {
- filter: {
- where: {
- search: 'one',
- }
- },
- };
- const results = await models.Postcode.filter(ctx, options);
+ const results = await models.Postcode.filter({where: {
+ search: 'one',
+ }}, options);
expect(results.length).toEqual(4);
await tx.rollback();
@@ -92,14 +76,11 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
- const ctx = {
- filter: {
- where: {
- search: 'Ec',
- }
- },
- };
- const results = await models.Postcode.filter(ctx, options);
+ const results = await models.Postcode.filter({
+ where: {
+ search: 'Ec',
+ }
+ }, options);
expect(results.length).toEqual(1);
await tx.rollback();
diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js
index 782046641..775970d55 100644
--- a/back/methods/vn-user/sign-in.js
+++ b/back/methods/vn-user/sign-in.js
@@ -67,7 +67,9 @@ module.exports = Self => {
if (vnUser.twoFactor === 'email') {
const $ = Self.app.models;
- const code = String(Math.floor(Math.random() * 999999));
+ const min = 100000;
+ const max = 999999;
+ const code = String(Math.floor(Math.random() * (max - min + 1)) + min);
const maxTTL = ((60 * 1000) * 5); // 5 min
await $.AuthCode.upsertWithWhere({userFk: vnUser.id}, {
userFk: vnUser.id,
diff --git a/back/methods/vn-user/validate-auth.js b/back/methods/vn-user/validate-auth.js
index beab43417..8fb8b4923 100644
--- a/back/methods/vn-user/validate-auth.js
+++ b/back/methods/vn-user/validate-auth.js
@@ -58,7 +58,7 @@ module.exports = Self => {
fields: ['name', 'twoFactor']
}, myOptions);
- if (user.name !== username)
+ if (user.name.toLowerCase() !== username.toLowerCase())
throw new UserError('Authentication failed');
await authCode.destroy(myOptions);
diff --git a/back/methods/workerActivity/add.js b/back/methods/workerActivity/add.js
new file mode 100644
index 000000000..4592a0797
--- /dev/null
+++ b/back/methods/workerActivity/add.js
@@ -0,0 +1,50 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('add', {
+ description: 'Add activity if the activity is different or is the same but have exceed time for break',
+ accessType: 'WRITE',
+ accepts: [
+ {
+ arg: 'code',
+ type: 'string',
+ description: 'Code for activity'
+ },
+ {
+ arg: 'model',
+ type: 'string',
+ description: 'Origin model from insert'
+ },
+
+ ],
+ http: {
+ path: `/add`,
+ verb: 'POST'
+ }
+ });
+
+ Self.add = async(ctx, code, model, options) => {
+ const userId = ctx.req.accessToken.userId;
+ const myOptions = {};
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ return await Self.rawSql(`
+ INSERT INTO workerActivity (workerFk, workerActivityTypeFk, model)
+ SELECT ?, ?, ?
+ FROM workerTimeControlParams wtcp
+ LEFT JOIN (
+ SELECT wa.workerFk,
+ wa.created,
+ wat.code
+ FROM workerActivity wa
+ LEFT JOIN workerActivityType wat ON wat.code = wa.workerActivityTypeFk
+ WHERE wa.workerFk = ?
+ ORDER BY wa.created DESC
+ LIMIT 1
+ ) sub ON TRUE
+ WHERE sub.workerFk IS NULL
+ OR sub.code <> ?
+ OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcp.dayBreak;`
+ , [userId, code, model, userId, code], myOptions);
+ };
+};
diff --git a/back/methods/workerActivity/specs/add.spec.js b/back/methods/workerActivity/specs/add.spec.js
new file mode 100644
index 000000000..352d67723
--- /dev/null
+++ b/back/methods/workerActivity/specs/add.spec.js
@@ -0,0 +1,30 @@
+const {models} = require('vn-loopback');
+
+describe('workerActivity insert()', () => {
+ const ctx = beforeAll.getCtx(1106);
+
+ it('should insert in workerActivity', async() => {
+ const tx = await models.WorkerActivity.beginTransaction({});
+ let count = 0;
+ const options = {transaction: tx};
+
+ try {
+ await models.WorkerActivityType.create(
+ {'code': 'STOP', 'description': 'STOP'}, options
+ );
+
+ await models.WorkerActivity.add(ctx, 'STOP', 'APP', options);
+
+ count = await models.WorkerActivity.count(
+ {'workerFK': 1106}, options
+ );
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+
+ expect(count).toEqual(1);
+ });
+});
diff --git a/back/model-config.json b/back/model-config.json
index a16fe4e8a..13c06ef54 100644
--- a/back/model-config.json
+++ b/back/model-config.json
@@ -28,6 +28,9 @@
"Company": {
"dataSource": "vn"
},
+ "Config": {
+ "dataSource": "vn"
+ },
"Continent": {
"dataSource": "vn"
},
diff --git a/back/models/config.json b/back/models/config.json
new file mode 100644
index 000000000..e5ba1f134
--- /dev/null
+++ b/back/models/config.json
@@ -0,0 +1,22 @@
+{
+ "name": "Config",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "config"
+ }
+ },
+ "properties": {
+ "inventoried": {
+ "type": "date"
+ }
+ },
+ "acls": [
+ {
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/back/models/postcode.json b/back/models/postcode.json
index eadc2c86c..bad6be5d7 100644
--- a/back/models/postcode.json
+++ b/back/models/postcode.json
@@ -9,7 +9,8 @@
"properties": {
"code": {
"id": true,
- "type": "string"
+ "type": "string",
+ "required": true
}
},
"relations": {
@@ -47,4 +48,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/back/models/town.json b/back/models/town.json
index 4ad729791..e5d39314b 100644
--- a/back/models/town.json
+++ b/back/models/town.json
@@ -12,7 +12,8 @@
"type": "number"
},
"name": {
- "type": "string"
+ "type": "string",
+ "required": true
}
},
"relations": {
@@ -54,4 +55,4 @@
"fields": ["id", "name", "provinceFk"]
}
}
-}
\ No newline at end of file
+}
diff --git a/back/models/workerActivity.js b/back/models/workerActivity.js
new file mode 100644
index 000000000..b3bb2c160
--- /dev/null
+++ b/back/models/workerActivity.js
@@ -0,0 +1,3 @@
+module.exports = Self => {
+ require('../methods/workerActivity/add')(Self);
+};
diff --git a/back/models/workerActivity.json b/back/models/workerActivity.json
index e3b994f77..ecd92bbce 100644
--- a/back/models/workerActivity.json
+++ b/back/models/workerActivity.json
@@ -22,18 +22,18 @@
},
"description": {
"type": "string"
+ }
+ },
+ "relations": {
+ "workerFk": {
+ "type": "belongsTo",
+ "model": "Worker",
+ "foreignKey": "workerFk"
},
- "relations": {
- "workerFk": {
- "type": "belongsTo",
- "model": "Worker",
- "foreignKey": "workerFk"
- },
- "workerActivityTypeFk": {
- "type": "belongsTo",
- "model": "WorkerActivityType",
- "foreignKey": "workerActivityTypeFk"
- }
+ "workerActivityTypeFk": {
+ "type": "belongsTo",
+ "model": "WorkerActivityType",
+ "foreignKey": "workerActivityTypeFk"
}
}
}
\ No newline at end of file
diff --git a/back/process.yml b/back/process.yml
index a29323240..08fee7a93 100644
--- a/back/process.yml
+++ b/back/process.yml
@@ -2,6 +2,5 @@ apps:
- script: ./loopback/server/server.js
name: salix-back
instances: 1
- max_restarts: 3
- restart_delay: 15000
+ max_restarts: 0
node_args: --tls-min-v1.0 --openssl-legacy-provider
diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql
index 711524e4c..f6bc84db7 100644
--- a/db/dump/.dump/data.sql
+++ b/db/dump/.dump/data.sql
@@ -3,7 +3,7 @@ USE `util`;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-INSERT INTO `version` VALUES ('vn-database','11154','04ff3e0cc79b00272d1ebbde7196292eab651c1d','2024-07-23 09:24:55','11163');
+INSERT INTO `version` VALUES ('vn-database','11161','36dee872d62ba2421c05503f374f6b208c40ecfa','2024-08-06 07:53:56','11180');
INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL);
@@ -822,6 +822,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','11034','00-firstScript.sql','jen
INSERT INTO `versionLog` VALUES ('vn-database','11037','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11038','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11040','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11042','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-06 07:53:54',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11044','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:31',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11045','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-10 14:53:29',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11046','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:46',NULL,NULL);
@@ -896,14 +897,22 @@ INSERT INTO `versionLog` VALUES ('vn-database','11138','00-firstScript.sql','jen
INSERT INTO `versionLog` VALUES ('vn-database','11139','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-08 10:58:01',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11140','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-23 08:23:34',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11145','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 13:55:46',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11146','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-06 07:53:54',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11149','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-23 08:23:35',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11150','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-23 08:23:35',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11152','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-16 09:06:11',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11154','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-23 08:23:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11155','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-06 07:53:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11156','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-06 07:53:54',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11157','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-16 13:11:00',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11158','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-17 17:06:30',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11159','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-18 17:23:32',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11160','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-18 13:46:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11161','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-06 07:53:54',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11164','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-23 11:03:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11168','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-25 08:58:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11169','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-25 12:38:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11177','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-30 12:42:28',NULL,NULL);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
@@ -2046,13 +2055,14 @@ INSERT INTO `ACL` VALUES (892,'WorkerIncome','*','*','ALLOW','ROLE','hr');
INSERT INTO `ACL` VALUES (893,'PayrollComponent','*','*','ALLOW','ROLE','hr');
INSERT INTO `ACL` VALUES (894,'Worker','__get__incomes','*','ALLOW','ROLE','hr');
INSERT INTO `ACL` VALUES (895,'ItemShelvingLog','*','READ','ALLOW','ROLE','production');
-INSERT INTO `ACL` VALUES (896,'Expedition_PrintOut','*','READ','ALLOW','ROLE','production');
INSERT INTO `ACL` VALUES (897,'WorkerLog','*','READ','ALLOW','ROLE','employee');
INSERT INTO `ACL` VALUES (901,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','system');
INSERT INTO `ACL` VALUES (902,'Entry','filter','READ','ALLOW','ROLE','supplier');
INSERT INTO `ACL` VALUES (903,'Entry','getBuys','READ','ALLOW','ROLE','supplier');
INSERT INTO `ACL` VALUES (904,'Entry','buyLabel','READ','ALLOW','ROLE','supplier');
INSERT INTO `ACL` VALUES (905,'AddressWaste','*','READ','ALLOW','ROLE','production');
+INSERT INTO `ACL` VALUES (906,'Entry','print','READ','ALLOW','ROLE','supplier');
+INSERT INTO `ACL` VALUES (907,'Expedition_PrintOut','*','*','ALLOW','ROLE','production');
INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee');
INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee');
@@ -2137,11 +2147,11 @@ INSERT INTO `module` VALUES ('wagon');
INSERT INTO `module` VALUES ('worker');
INSERT INTO `module` VALUES ('zone');
-INSERT INTO `defaultViewConfig` VALUES ('itemsIndex','{\"intrastat\":false,\"stemMultiplier\":false,\"landed\":false,\"producer\":false}');
-INSERT INTO `defaultViewConfig` VALUES ('latestBuys','{\"intrastat\":false,\"description\":false,\"density\":false,\"isActive\":false,\n \"freightValue\":false,\"packageValue\":false,\"isIgnored\":false,\"price2\":false,\"ektFk\":false,\"weight\":false,\n \"size\":false,\"comissionValue\":false,\"landing\":false}');
-INSERT INTO `defaultViewConfig` VALUES ('ticketsMonitor','{\"id\":false}');
-INSERT INTO `defaultViewConfig` VALUES ('clientsDetail','{\"id\":true,\"phone\":true,\"city\":true,\"socialName\":true,\"salesPersonFk\":true,\"email\":true,\"name\":false,\"fi\":false,\"credit\":false,\"creditInsurance\":false,\"mobile\":false,\"street\":false,\"countryFk\":false,\"provinceFk\":false,\"postcode\":false,\"created\":false,\"businessTypeFk\":false,\"payMethodFk\":false,\"sageTaxTypeFk\":false,\"sageTransactionTypeFk\":false,\"isActive\":false,\"isVies\":false,\"isTaxDataChecked\":false,\"isEqualizated\":false,\"isFreezed\":false,\"hasToInvoice\":false,\"hasToInvoiceByAddress\":false,\"isToBeMailed\":false,\"hasLcr\":false,\"hasCoreVnl\":false,\"hasSepaVnl\":false}');
-INSERT INTO `defaultViewConfig` VALUES ('routesList','{\"ID\":true,\"worker\":true,\"agency\":true,\"vehicle\":true,\"date\":true,\"volume\":true,\"description\":true,\"started\":true,\"finished\":true,\"actions\":true}');
+INSERT INTO `defaultViewMultiConfig` VALUES ('itemsIndex','{\"intrastat\":false,\"stemMultiplier\":false,\"landed\":false,\"producer\":false}');
+INSERT INTO `defaultViewMultiConfig` VALUES ('latestBuys','{\"intrastat\":false,\"description\":false,\"density\":false,\"isActive\":false,\n \"freightValue\":false,\"packageValue\":false,\"isIgnored\":false,\"price2\":false,\"ektFk\":false,\"weight\":false,\n \"size\":false,\"comissionValue\":false,\"landing\":false}');
+INSERT INTO `defaultViewMultiConfig` VALUES ('ticketsMonitor','{\"id\":false}');
+INSERT INTO `defaultViewMultiConfig` VALUES ('clientsDetail','{\"id\":true,\"phone\":true,\"city\":true,\"socialName\":true,\"salesPersonFk\":true,\"email\":true,\"name\":false,\"fi\":false,\"credit\":false,\"creditInsurance\":false,\"mobile\":false,\"street\":false,\"countryFk\":false,\"provinceFk\":false,\"postcode\":false,\"created\":false,\"businessTypeFk\":false,\"payMethodFk\":false,\"sageTaxTypeFk\":false,\"sageTransactionTypeFk\":false,\"isActive\":false,\"isVies\":false,\"isTaxDataChecked\":false,\"isEqualizated\":false,\"isFreezed\":false,\"hasToInvoice\":false,\"hasToInvoiceByAddress\":false,\"isToBeMailed\":false,\"hasLcr\":false,\"hasCoreVnl\":false,\"hasSepaVnl\":false}');
+INSERT INTO `defaultViewMultiConfig` VALUES ('routesList','{\"ID\":true,\"worker\":true,\"agency\":true,\"vehicle\":true,\"date\":true,\"volume\":true,\"description\":true,\"started\":true,\"finished\":true,\"actions\":true}');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
@@ -2153,6 +2163,7 @@ USE `vn`;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
INSERT INTO `alertLevel` VALUES ('FREE',0,1);
+INSERT INTO `alertLevel` VALUES ('ON_PREVIOUS',1,1);
INSERT INTO `alertLevel` VALUES ('ON_PREPARATION',2,1);
INSERT INTO `alertLevel` VALUES ('PACKED',3,0);
INSERT INTO `alertLevel` VALUES ('DELIVERED',4,0);
@@ -2384,7 +2395,7 @@ INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',14,37,NULL,72,1,1,1,11,1
INSERT INTO `department` VALUES (38,'picking','SACADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (39,'packing','ENCAJADO',19,20,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',38,39,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (43,'VT','VENTAS',40,71,NULL,0,0,0,1,15,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (43,'VT','VENTAS',40,71,NULL,0,0,0,1,15,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (44,'management','GERENCIA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (46,'delivery','REPARTO',76,77,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
@@ -2722,6 +2733,7 @@ INSERT INTO `state` VALUES (36,'Previa Revisando',3,0,'PREVIOUS_CONTROL',2,37,1,
INSERT INTO `state` VALUES (37,'Previa Revisado',3,0,'PREVIOUS_CONTROLLED',2,29,1,0,1,0,0,1,2,0,'warning');
INSERT INTO `state` VALUES (38,'Prep Cámara',6,2,'COOLER_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning');
INSERT INTO `state` VALUES (41,'Prep Parcial',6,2,'PARTIAL_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning');
+INSERT INTO `state` VALUES (42,'Entregado en parte',13,3,'PARTIAL_DELIVERED',NULL,16,0,1,0,0,0,0,0,0,NULL);
INSERT INTO `ticketUpdateAction` VALUES (1,'Cambiar los precios en el ticket','renewPrices');
INSERT INTO `ticketUpdateAction` VALUES (2,'Convertir en maná','mana');
diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql
index dc0549de4..7776e6d5a 100644
--- a/db/dump/.dump/privileges.sql
+++ b/db/dump/.dump/privileges.sql
@@ -1292,6 +1292,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','buffer','juan@db-p
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greuge','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','item','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select,Update');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemShelving','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','agencyIncoming','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','addressObservation','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','negativeOrigin','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','Vehiculos_consumo','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','entryOrder','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
@@ -1357,6 +1359,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','accounting',
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accounting','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketRequest','guillermo@10.5.1.3','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','Vehiculos_consumo','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','vehicleState','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','expeditionState','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','specialPrice','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
@@ -1379,6 +1383,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','professionalCategor
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','ticketObservation','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNoteState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','inventoryConfig','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','comparative','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceOutExpense','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','delivery','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
@@ -1404,6 +1409,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','teamBoss','business','guiller
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketServiceType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierAgencyTerm','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemMinimumQuantity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientRate','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert','Update');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientInforma','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
@@ -1428,6 +1434,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','businessReasonEnd','guil
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','claims_ratio','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','employee','shelfMultiConfig','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientConfig','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_gestdoc','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_state','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql
index 174471895..4790e156c 100644
--- a/db/dump/.dump/structure.sql
+++ b/db/dump/.dump/structure.sql
@@ -4499,20 +4499,22 @@ DROP TABLE IF EXISTS `waste`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `waste` (
- `buyer` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`year` int(4) NOT NULL,
`week` int(2) NOT NULL,
- `family` varchar(30) NOT NULL,
+ `buyerFk` int(10) unsigned NOT NULL,
+ `itemTypeFk` smallint(5) unsigned NOT NULL,
`itemFk` int(11) NOT NULL DEFAULT 0,
- `itemTypeFk` smallint(5) unsigned DEFAULT NULL,
- `saleTotal` decimal(16,0) DEFAULT NULL,
- `saleWaste` decimal(16,0) DEFAULT NULL,
- `rate` decimal(5,1) DEFAULT NULL,
- PRIMARY KEY (`buyer`,`year`,`week`,`family`,`itemFk`),
+ `saleQuantity` decimal(10,2) DEFAULT NULL,
+ `saleTotal` decimal(10,2) DEFAULT NULL,
+ `saleInternalWaste` decimal(10,2) DEFAULT NULL,
+ `saleExternalWaste` decimal(10,2) DEFAULT NULL,
+ PRIMARY KEY (`year`,`week`,`buyerFk`,`itemTypeFk`,`itemFk`),
KEY `waste_itemType_id` (`itemTypeFk`),
KEY `waste_item_id` (`itemFk`),
+ KEY `waste_user_FK` (`buyerFk`),
CONSTRAINT `waste_itemType_id` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn`.`itemType` (`id`),
- CONSTRAINT `waste_item_id` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE
+ CONSTRAINT `waste_item_id` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `waste_user_FK` FOREIGN KEY (`buyerFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -6525,32 +6527,51 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `waste_addSales`()
BEGIN
- DECLARE vWeek INT;
- DECLARE vYear INT;
+ DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY;
+ DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY;
+
+ CALL cache.last_buy_refresh(FALSE);
- SELECT week, year
- INTO vWeek, vYear
- FROM vn.time
- WHERE dated = util.VN_CURDATE();
-
REPLACE bs.waste
- SELECT *, 100 * mermas / total as porcentaje
- FROM (
- SELECT buyer,
- year,
- week,
- family,
- itemFk,
- itemTypeFk,
- floor(sum(value)) as total,
- floor(sum(IF(typeFk = 'loses', value, 0))) as mermas
- FROM vn.saleValue
- where year = vYear and week = vWeek
-
- GROUP BY family, itemFk
-
- ) sub
- ORDER BY mermas DESC;
+ SELECT YEAR(t.shipped),
+ WEEK(t.shipped, 4),
+ it.workerFk,
+ it.id,
+ s.itemFk,
+ SUM(s.quantity),
+ SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) `value`,
+ SUM (
+ IF(
+ aw.`type` = 'internal',
+ (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
+ 0
+ )
+ ) internalWaste,
+ SUM (
+ IF(
+ aw.`type` = 'external',
+ (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
+ IF(c.code = 'manaClaim',
+ sc.value * s.quantity,
+ 0
+ )
+ )
+ ) externalWaste
+ FROM vn.sale s
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.address a FORCE INDEX (PRIMARY) ON a.id = t.addressFk
+ LEFT JOIN vn.addressWaste aw ON aw.addressFk = a.id
+ JOIN vn.warehouse w ON w.id = t.warehouseFk
+ JOIN cache.last_buy lb ON lb.item_id = i.id
+ AND lb.warehouse_id = w.id
+ JOIN vn.buy b ON b.id = lb.buy_id
+ LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id
+ LEFT JOIN vn.component c ON c.id = sc.componentFk
+ WHERE t.shipped BETWEEN vDateFrom AND vDateTo
+ AND w.isManaged
+ GROUP BY it.id, i.id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -7745,7 +7766,7 @@ proc: BEGIN
SELECT inventoried INTO started FROM vn.config LIMIT 1;
SET ended = util.VN_CURDATE(); -- TIMESTAMPADD(DAY, -1, util.VN_CURDATE());
- CALL vn.buyUltimateFromInterval(NULL, started, ended);
+ CALL vn.buy_getUltimateFromInterval(NULL, NULL, started, ended);
DELETE FROM last_buy;
@@ -7889,9 +7910,12 @@ proc:BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible
(PRIMARY KEY (item_id))
ENGINE = MEMORY
- SELECT item_id, amount stock, amount visible
- FROM cache.stock
- WHERE warehouse_id = v_warehouse;
+ SELECT s.item_id, SUM(s.amount) stock, SUM(s.amount) visible
+ FROM stock s
+ JOIN vn.warehouse w ON w.id = s.warehouse_id
+ WHERE (v_warehouse IS NULL OR s.warehouse_id = v_warehouse)
+ AND w.isComparative
+ GROUP BY s.item_id;
-- Calculamos los movimientos confirmados de hoy
CALL vn.item_calcVisible(NULL, v_warehouse);
@@ -7964,6 +7988,7 @@ CREATE TABLE `expedition_PrintOut` (
`longName` varchar(30) DEFAULT NULL,
`shelvingFk` varchar(5) DEFAULT NULL,
`comments` varchar(100) DEFAULT NULL,
+ `isChecked` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si la expedición ha sido revisada por un revisor',
PRIMARY KEY (`expeditionFk`),
KEY `expedition_PrintOut_FK` (`printerFk`),
CONSTRAINT `expedition_PrintOut_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
@@ -8608,13 +8633,13 @@ CREATE TABLE `feature` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `fileConfig`
+-- Table structure for table `fileMultiConfig`
--
-DROP TABLE IF EXISTS `fileConfig`;
+DROP TABLE IF EXISTS `fileMultiConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `fileConfig` (
+CREATE TABLE `fileMultiConfig` (
`name` varchar(25) NOT NULL,
`checksum` text DEFAULT NULL,
`keyValue` tinyint(1) NOT NULL DEFAULT 1,
@@ -8687,13 +8712,13 @@ CREATE TABLE `goodCharacteristic` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `imapConfig`
+-- Table structure for table `imapMultiConfig`
--
-DROP TABLE IF EXISTS `imapConfig`;
+DROP TABLE IF EXISTS `imapMultiConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `imapConfig` (
+CREATE TABLE `imapMultiConfig` (
`id` tinyint(3) unsigned NOT NULL,
`environment` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`host` varchar(150) NOT NULL DEFAULT 'localhost',
@@ -9219,13 +9244,13 @@ CREATE TABLE `supplyResponseLog` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `tableConfig`
+-- Table structure for table `tableMultiConfig`
--
-DROP TABLE IF EXISTS `tableConfig`;
+DROP TABLE IF EXISTS `tableMultiConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `tableConfig` (
+CREATE TABLE `tableMultiConfig` (
`fileName` varchar(2) NOT NULL,
`toTable` varchar(15) NOT NULL,
`file` varchar(30) NOT NULL,
@@ -12256,13 +12281,13 @@ CREATE TABLE `shelf` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `shelfConfig`
+-- Table structure for table `shelfMultiConfig`
--
-DROP TABLE IF EXISTS `shelfConfig`;
+DROP TABLE IF EXISTS `shelfMultiConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `shelfConfig` (
+CREATE TABLE `shelfMultiConfig` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL,
`namePrefix` varchar(50) DEFAULT NULL,
@@ -12276,9 +12301,9 @@ CREATE TABLE `shelfConfig` (
KEY `shelf_id` (`shelf`),
KEY `family_id` (`family`),
KEY `warehouse_id` (`warehouse`),
- CONSTRAINT `shelfConfig_ibfk_1` FOREIGN KEY (`family`) REFERENCES `vn`.`itemType` (`id`),
- CONSTRAINT `shelfConfig_ibfk_2` FOREIGN KEY (`shelf`) REFERENCES `shelf` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `shelfConfig_ibfk_3` FOREIGN KEY (`warehouse`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+ CONSTRAINT `shelfMultiConfig_ibfk_1` FOREIGN KEY (`family`) REFERENCES `vn`.`itemType` (`id`),
+ CONSTRAINT `shelfMultiConfig_ibfk_2` FOREIGN KEY (`shelf`) REFERENCES `shelf` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `shelfMultiConfig_ibfk_3` FOREIGN KEY (`warehouse`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -15834,7 +15859,7 @@ CREATE TABLE `queue` (
UNIQUE KEY `name` (`name`),
UNIQUE KEY `description` (`description`),
KEY `config` (`config`),
- CONSTRAINT `queue_ibfk_1` FOREIGN KEY (`config`) REFERENCES `queueConfig` (`id`) ON UPDATE CASCADE
+ CONSTRAINT `queue_ibfk_1` FOREIGN KEY (`config`) REFERENCES `queueMultiConfig` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queues';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -15856,25 +15881,6 @@ SET character_set_client = utf8;
1 AS `ringinuse` */;
SET character_set_client = @saved_cs_client;
---
--- Table structure for table `queueConfig`
---
-
-DROP TABLE IF EXISTS `queueConfig`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `queueConfig` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `strategy` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- `timeout` int(10) unsigned NOT NULL,
- `retry` int(10) unsigned NOT NULL,
- `weight` int(10) unsigned NOT NULL,
- `maxLen` int(10) unsigned NOT NULL,
- `ringInUse` tinyint(4) NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Default values for queues configuration';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `queueMember`
--
@@ -15909,6 +15915,25 @@ SET character_set_client = utf8;
1 AS `paused` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `queueMultiConfig`
+--
+
+DROP TABLE IF EXISTS `queueMultiConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `queueMultiConfig` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `strategy` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `timeout` int(10) unsigned NOT NULL,
+ `retry` int(10) unsigned NOT NULL,
+ `weight` int(10) unsigned NOT NULL,
+ `maxLen` int(10) unsigned NOT NULL,
+ `ringInUse` tinyint(4) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Default values for queues configuration';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `queuePhone`
--
@@ -19090,13 +19115,13 @@ CREATE TABLE `authCode` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `defaultViewConfig`
+-- Table structure for table `defaultViewMultiConfig`
--
-DROP TABLE IF EXISTS `defaultViewConfig`;
+DROP TABLE IF EXISTS `defaultViewMultiConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `defaultViewConfig` (
+CREATE TABLE `defaultViewMultiConfig` (
`tableCode` varchar(25) NOT NULL,
`columns` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='The default configuration of columns for views';
@@ -26523,6 +26548,7 @@ CREATE TABLE `agencyLog` (
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
+ `summaryId` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `logAgencyUserFk` (`userFk`),
KEY `agencyLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
@@ -27664,8 +27690,10 @@ CREATE TABLE `calendar` (
KEY `calendar_employee_business_labour_id_idx` (`businessFk`),
KEY `calendar_employee_calendar_state_calendar_state_id_idx` (`dayOffTypeFk`),
KEY `id_index` (`id`),
+ KEY `calendar_user_FK` (`editorFk`),
CONSTRAINT `calendar_FK` FOREIGN KEY (`dayOffTypeFk`) REFERENCES `absenceType` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `calendar_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+ CONSTRAINT `calendar_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `calendar_user_FK` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -29332,24 +29360,6 @@ CREATE TABLE `conveyorBuildingClass` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de caja para el montaje de pallets';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `conveyorConfig`
---
-
-DROP TABLE IF EXISTS `conveyorConfig`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `conveyorConfig` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `itemName` varchar(45) NOT NULL,
- `length` int(11) DEFAULT NULL,
- `width` int(11) DEFAULT NULL,
- `height` int(11) DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `itemName_UNIQUE` (`itemName`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `conveyorExpedition`
--
@@ -29398,6 +29408,24 @@ CREATE TABLE `conveyorMode` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `conveyorMultiConfig`
+--
+
+DROP TABLE IF EXISTS `conveyorMultiConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `conveyorMultiConfig` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `itemName` varchar(45) NOT NULL,
+ `length` int(11) DEFAULT NULL,
+ `width` int(11) DEFAULT NULL,
+ `height` int(11) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `itemName_UNIQUE` (`itemName`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `conveyorType`
--
@@ -32085,6 +32113,7 @@ CREATE TABLE `invoiceInConfig` (
`sageFarmerWithholdingFk` smallint(6) NOT NULL,
`daysAgo` int(10) unsigned DEFAULT 45 COMMENT 'Días en el pasado para mostrar facturas en invoiceIn series en salix',
`taxRowLimit` int(11) DEFAULT 4 COMMENT 'Número máximo de líneas de IVA que puede tener una factura',
+ `dueDateMarginDays` int(10) unsigned DEFAULT 2,
PRIMARY KEY (`id`),
KEY `invoiceInConfig_sageWithholdingFk` (`sageFarmerWithholdingFk`),
CONSTRAINT `invoiceInConfig_sageWithholdingFk` FOREIGN KEY (`sageFarmerWithholdingFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON DELETE CASCADE ON UPDATE CASCADE,
@@ -32438,13 +32467,13 @@ CREATE TABLE `invoiceOutTax` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `invoiceOutTaxConfig`
+-- Table structure for table `invoiceOutTaxMultiConfig`
--
-DROP TABLE IF EXISTS `invoiceOutTaxConfig`;
+DROP TABLE IF EXISTS `invoiceOutTaxMultiConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `invoiceOutTaxConfig` (
+CREATE TABLE `invoiceOutTaxMultiConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taxClassCodeFk` varchar(1) DEFAULT NULL,
`taxTypeSageFk` smallint(6) DEFAULT NULL,
@@ -32534,6 +32563,12 @@ CREATE TABLE `item` (
`minQuantity__` int(10) unsigned DEFAULT NULL COMMENT '@deprecated 2024-07-11 refs #7704 Cantidad mínima para una línea de venta',
`isBoxPickingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'FALSE: using item.packingOut TRUE: boxPicking using itemShelving.packing',
`photoMotivation` varchar(255) DEFAULT NULL,
+ `tag11` varchar(20) DEFAULT NULL,
+ `value11` varchar(50) DEFAULT NULL,
+ `tag12` varchar(20) DEFAULT NULL,
+ `value12` varchar(50) DEFAULT NULL,
+ `tag13` varchar(20) DEFAULT NULL,
+ `value13` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `item_supplyResponseFk_idx` (`supplyResponseFk`),
KEY `Color` (`inkFk`),
@@ -33070,7 +33105,7 @@ CREATE TABLE `itemShelving` (
`buyFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
`available` int(11) DEFAULT NULL,
- `isSplit` tinyint(1) DEFAULT NULL COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda',
+ `isSplit` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda',
PRIMARY KEY (`id`),
KEY `itemShelving_fk1_idx` (`itemFk`),
KEY `itemShelving_fk2_idx` (`shelvingFk`),
@@ -33253,7 +33288,8 @@ CREATE TABLE `itemShelvingSaleReserve` (
`sectorFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `itemShelvingSaleReserve_ibfk_1` (`saleFk`),
- CONSTRAINT `itemShelvingSaleReserve_sector_FK` FOREIGN KEY (`id`) REFERENCES `sector` (`id`) ON UPDATE CASCADE
+ KEY `itemShelvingSaleReserve_sector_FK` (`sectorFk`),
+ CONSTRAINT `itemShelvingSaleReserve_sector_FK` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed itemShelvingSale to reserve';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -35741,6 +35777,7 @@ CREATE TABLE `productionConfigLog` (
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
+ `summaryId` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `productionConfigLog_userFk` (`userFk`),
KEY `productionConfigLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
@@ -39958,27 +39995,6 @@ CREATE TABLE `trolley` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `userConfig`
---
-
-DROP TABLE IF EXISTS `userConfig`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `userConfig` (
- `userFk` int(10) unsigned NOT NULL,
- `warehouseFk` smallint(6) DEFAULT NULL,
- `companyFk` smallint(5) unsigned DEFAULT NULL,
- `created` timestamp NULL DEFAULT current_timestamp(),
- `updated` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
- `darkMode` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Salix interface dark mode',
- `tabletFk` varchar(100) DEFAULT NULL,
- PRIMARY KEY (`userFk`),
- KEY `tabletFk` (`tabletFk`),
- CONSTRAINT `userConfig_ibfk_1` FOREIGN KEY (`tabletFk`) REFERENCES `docuwareTablet` (`tablet`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de usuario en Salix';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `userLog`
--
@@ -40006,6 +40022,27 @@ CREATE TABLE `userLog` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `userMultiConfig`
+--
+
+DROP TABLE IF EXISTS `userMultiConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `userMultiConfig` (
+ `userFk` int(10) unsigned NOT NULL,
+ `warehouseFk` smallint(6) DEFAULT NULL,
+ `companyFk` smallint(5) unsigned DEFAULT NULL,
+ `created` timestamp NULL DEFAULT current_timestamp(),
+ `updated` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
+ `darkMode` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Salix interface dark mode',
+ `tabletFk` varchar(100) DEFAULT NULL,
+ PRIMARY KEY (`userFk`),
+ KEY `tabletFk` (`tabletFk`),
+ CONSTRAINT `userMultiConfig_ibfk_1` FOREIGN KEY (`tabletFk`) REFERENCES `docuwareTablet` (`tablet`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de usuario en Salix';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `userPhone`
--
@@ -42152,6 +42189,28 @@ DELIMITER ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection = @saved_col_connection */ ;;
+/*!50106 DROP EVENT IF EXISTS `travel_setDelivered` */;;
+DELIMITER ;;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
+/*!50003 SET character_set_client = utf8mb4 */ ;;
+/*!50003 SET character_set_results = utf8mb4 */ ;;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
+/*!50003 SET @saved_time_zone = @@time_zone */ ;;
+/*!50003 SET time_zone = 'SYSTEM' */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `travel_setDelivered` ON SCHEDULE EVERY 1 DAY STARTS '2024-07-12 00:10:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
+ UPDATE travel t
+ SET t.isDelivered = TRUE
+ WHERE t.shipped < util.VN_CURDATE();
+END */ ;;
+/*!50003 SET time_zone = @saved_time_zone */ ;;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;;
+/*!50003 SET character_set_client = @saved_cs_client */ ;;
+/*!50003 SET character_set_results = @saved_cs_results */ ;;
+/*!50003 SET collation_connection = @saved_col_connection */ ;;
/*!50106 DROP EVENT IF EXISTS `vehicle_notify` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
@@ -47452,7 +47511,7 @@ proc: BEGIN
-- Tabla con el ultimo dia de last_buy para cada producto
-- que hace un replace de la anterior.
- CALL buyUltimate(vWarehouseShipment, util.VN_CURDATE());
+ CALL buy_getUltimate (NULL, vWarehouseShipment, util.VN_CURDATE());
INSERT INTO tItemRange
SELECT t.itemFk, tr.landed
@@ -48118,40 +48177,15 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `buyUltimate`(
)
BEGIN
/**
- * Calcula las últimas compras realizadas hasta una fecha
+ * @deprecated Usar buy_getUltimate
+ * Calcula las últimas compras realizadas hasta una fecha.
*
+ * @param vItemFk Id del artículo
* @param vWarehouseFk Id del almacén
* @param vDated Compras hasta fecha
* @return tmp.buyUltimate
*/
- CALL cache.last_buy_refresh (FALSE);
-
- DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
- CREATE TEMPORARY TABLE tmp.buyUltimate
- (PRIMARY KEY (itemFk, warehouseFk),
- INDEX(itemFk))
- ENGINE = MEMORY
- SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing
- FROM cache.last_buy
- WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL;
-
- IF vDated >= util.VN_CURDATE() THEN
- CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated);
-
- REPLACE INTO tmp.buyUltimate
- SELECT itemFk, buyFk, warehouseFk, landed landing
- FROM tmp.buyUltimateFromInterval
- WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
- AND landed <= vDated
- AND NOT isIgnored;
-
- INSERT IGNORE INTO tmp.buyUltimate
- SELECT itemFk, buyFk, warehouseFk, landed landing
- FROM tmp.buyUltimateFromInterval
- WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
- AND landed > vDated
- ORDER BY isIgnored = FALSE DESC;
- END IF;
+ CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48175,6 +48209,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `buyUltimateFromInterval`(
)
BEGIN
/**
+ * @deprecated Usar buy_getUltimateFromInterval
* Calcula las últimas compras realizadas
* desde un rango de fechas.
*
@@ -48183,154 +48218,7 @@ BEGIN
* @param vEnded Fecha fin
* @return tmp.buyUltimateFromInterval
*/
- IF vEnded IS NULL THEN
- SET vEnded = vStarted;
- END IF;
-
- IF vEnded < vStarted THEN
- SET vStarted = TIMESTAMPADD(MONTH, -1, vEnded);
- END IF;
-
- -- Item
- DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval;
- CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval
- (PRIMARY KEY (itemFk, warehouseFk),
- INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
- ENGINE = MEMORY
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vStarted AND vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.price2 > 0
- ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
-
-
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed > vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.price2 > 0
- AND NOT b.isIgnored
- ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
-
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vStarted AND vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.quantity = 0
- ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
-
- -- ItemOriginal
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- itemOriginalFk,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vStarted AND vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.price2 > 0
- AND NOT b.isIgnored
- AND b.quantity > 0
- AND itemOriginalFk
- ORDER BY t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed > vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.price2 > 0
- AND NOT b.isIgnored
- AND itemOriginalFk
- ORDER BY t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
-
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM
- (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vStarted AND vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.quantity = 0
- AND itemOriginalFk
- ORDER BY t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
+ CALL vn.buy_getUltimateFromInterval(NULL, vWarehouseFk, vStarted, vEnded);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -48716,6 +48604,254 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buy_getUltimate` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getUltimate`(
+ vItemFk INT,
+ vWarehouseFk SMALLINT,
+ vDated DATE
+)
+BEGIN
+/**
+ * Calcula las últimas compras realizadas hasta una fecha.
+ *
+ * @param vItemFk Id del artículo
+ * @param vWarehouseFk Id del almacén
+ * @param vDated Compras hasta fecha
+ * @return tmp.buyUltimate
+ */
+ CALL cache.last_buy_refresh(FALSE);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.buyUltimate
+ (PRIMARY KEY (itemFk, warehouseFk),
+ INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing
+ FROM cache.last_buy
+ WHERE (warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL)
+ AND (item_id = vItemFk OR vItemFk IS NULL);
+
+ IF vDated >= util.VN_CURDATE() THEN
+ CALL buy_getUltimateFromInterval(vItemFk, vWarehouseFk, util.VN_CURDATE(), vDated);
+
+ REPLACE INTO tmp.buyUltimate
+ SELECT itemFk, buyFk, warehouseFk, landed landing
+ FROM tmp.buyUltimateFromInterval
+ WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
+ AND (itemFk = vItemFk OR vItemFk IS NULL)
+ AND landed <= vDated
+ AND NOT isIgnored;
+
+ INSERT IGNORE INTO tmp.buyUltimate
+ SELECT itemFk, buyFk, warehouseFk, landed landing
+ FROM tmp.buyUltimateFromInterval
+ WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
+ AND (itemFk = vItemFk OR vItemFk IS NULL)
+ AND landed > vDated
+ ORDER BY isIgnored = FALSE DESC;
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `buy_getUltimateFromInterval` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getUltimateFromInterval`(
+ vItemFk INT,
+ vWarehouseFk SMALLINT,
+ vStarted DATE,
+ vEnded DATE
+)
+BEGIN
+/**
+ * Calcula las últimas compras realizadas
+ * desde un rango de fechas.
+ *
+ * @param vItemFk Id del artículo
+ * @param vWarehouseFk Id del almacén si es NULL se actualizan todos
+ * @param vStarted Fecha inicial
+ * @param vEnded Fecha fin
+ * @return tmp.buyUltimateFromInterval
+ */
+ IF vEnded IS NULL THEN
+ SET vEnded = vStarted;
+ END IF;
+
+ IF vEnded < vStarted THEN
+ SET vStarted = vEnded - INTERVAL 1 MONTH;
+ END IF;
+
+ -- Item
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.buyUltimateFromInterval
+ (PRIMARY KEY (itemFk, warehouseFk),
+ INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.price2 > 0
+ ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed > vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.quantity = 0
+ ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+ -- ItemOriginal
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ itemOriginalFk,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ AND b.quantity > 0
+ AND itemOriginalFk
+ ORDER BY t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed > vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ AND itemOriginalFk
+ ORDER BY t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM
+ (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.quantity = 0
+ AND itemOriginalFk
+ ORDER BY t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_getVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
@@ -49044,7 +49180,11 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updateGrouping`(vWarehouseFk INT, vItemFk INT, vGrouping INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updateGrouping`(
+ vWarehouseFk INT,
+ vItemFk INT,
+ vGrouping INT
+)
BEGIN
/**
* Actualiza el grouping de las últimas compras de un artículo
@@ -49053,9 +49193,9 @@ BEGIN
* @param vItemFk Id del Artículo
* @param vGrouping Cantidad de grouping
*/
- CALL vn.buyUltimate(vWarehouseFk, util.VN_CURDATE());
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, util.VN_CURDATE());
- UPDATE vn.buy b
+ UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
SET b.`grouping` = vGrouping
WHERE bu.warehouseFk = vWarehouseFk
@@ -49087,7 +49227,7 @@ BEGIN
* @param vItemFk id del item
* @param vPacking packing a actualizar
*/
- CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, util.VN_CURDATE());
UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
@@ -49182,7 +49322,7 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, vShowExpiredZones);
+ CALL zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, vShowExpiredZones);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot(
@@ -49225,9 +49365,9 @@ BEGIN
LEAVE l;
END IF;
- CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped);
- CALL `cache`.availableNoRaids_refresh (vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped);
- CALL vn.buyUltimate(vWarehouseFk, vShipped);
+ CALL `cache`.available_refresh(vAvailableCalc, FALSE, vWarehouseFk, vShipped);
+ CALL `cache`.availableNoRaids_refresh(vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk)
SELECT vWarehouseFk,
@@ -49239,17 +49379,17 @@ BEGIN
LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
AND anr.calc_id = vAvailableNoRaidsCalc
JOIN tmp.item i ON i.itemFk = a.item_id
- JOIN vn.item it ON it.id = i.itemFk
- JOIN vn.`zone` z ON z.id = vZoneFk
+ JOIN item it ON it.id = i.itemFk
+ JOIN `zone` z ON z.id = vZoneFk
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed
- FROM vn.addressFilter af
+ FROM addressFilter af
JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
- FROM vn.address ad
- JOIN vn.province p ON p.id = ad.provinceFk
+ FROM address ad
+ JOIN province p ON p.id = ad.provinceFk
WHERE ad.id = vAddressFk
) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk)
AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk)
@@ -49261,18 +49401,18 @@ BEGIN
OR ISNULL(af.afterDated))
) sub ON sub.isVNHSupplier = v.isVNHSupplier
AND (sub.isEarlyBird = mp.isEarlyBird OR ISNULL(sub.isEarlyBird))
- JOIN vn.agencyMode am ON am.id = vAgencyModeFk
- JOIN vn.agency ag ON ag.id = am.agencyFk
- JOIN vn.itemType itt ON itt.id = it.typeFk
- JOIN vn.itemCategory itc on itc.id = itt.categoryFk
- JOIN vn.address ad ON ad.id = vAddressFk
- LEFT JOIN vn.clientItemType cit
+ JOIN agencyMode am ON am.id = vAgencyModeFk
+ JOIN agency ag ON ag.id = am.agencyFk
+ JOIN itemType itt ON itt.id = it.typeFk
+ JOIN itemCategory itc on itc.id = itt.categoryFk
+ JOIN address ad ON ad.id = vAddressFk
+ LEFT JOIN clientItemType cit
ON cit.clientFk = ad.clientFk
AND cit.itemTypeFk = itt.id
- LEFT JOIN vn.zoneItemType zit
+ LEFT JOIN zoneItemType zit
ON zit.zoneFk = vZoneFk
AND zit.itemTypeFk = itt.id
- LEFT JOIN vn.agencyModeItemType ait
+ LEFT JOIN agencyModeItemType ait
ON ait.agencyModeFk = vAgencyModeFk
AND ait.itemTypeFk = itt.id
WHERE a.calc_id = vAvailableCalc
@@ -49286,7 +49426,7 @@ BEGIN
DROP TEMPORARY TABLE tmp.buyUltimate;
- CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
+ CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
INSERT INTO tmp.ticketCalculateItem(
itemFk,
@@ -52853,7 +52993,7 @@ DECLARE vCompanyFk INT;
SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk)
INTO vCompanyFk
FROM vn.routeConfig rc
- LEFT JOIN userConfig uc ON uc.userFk = workerFk;
+ LEFT JOIN userMultiConfig uc ON uc.userFk = workerFk;
SELECT
@@ -54183,6 +54323,7 @@ BEGIN
DECLARE vInvoiceFk INT;
DECLARE vBookEntry INT;
DECLARE vFiscalYear INT;
+ DECLARE vIncorrectInvoiceInDueDay INT;
DECLARE vInvoicesIn CURSOR FOR
SELECT DISTINCT e.invoiceInFk
@@ -54195,6 +54336,19 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ SELECT GROUP_CONCAT(ii.id) INTO vIncorrectInvoiceInDueDay
+ FROM invoiceInDueDay iidd
+ JOIN invoiceIn ii ON iidd.invoiceInFk = ii.id
+ JOIN `entry` e ON e.invoiceInFk = ii.id
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN invoiceInConfig iic
+ WHERE de.duaFk = vDuaFk
+ AND iidd.dueDated <= util.VN_CURDATE() + INTERVAL iic.dueDateMarginDays DAY;
+
+ IF vIncorrectInvoiceInDueDay THEN
+ CALL util.throw(CONCAT('Incorrect due date, invoice: ', vIncorrectInvoiceInDueDay));
+ END IF;
+
UPDATE invoiceIn ii
JOIN entry e ON e.invoiceInFk = ii.id
JOIN duaEntry de ON de.entryFk = e.id
@@ -55212,7 +55366,7 @@ BEGIN
FROM tmp.itemList;
END IF;
- CALL buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded);
+ CALL buy_getUltimateFromInterval(NULL, vWarehouseIn,vInventoryDate, vDateLanded);
CREATE OR REPLACE TEMPORARY TABLE tTransfer
ENGINE = MEMORY
@@ -55785,7 +55939,7 @@ BEGIN
UPDATE itemShelving
SET isSplit = TRUE
- WHERE shelvingFk = vShelvingFk;
+ WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci;
END LOOP;
CLOSE cur;
END ;;
@@ -57642,7 +57796,9 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(vInvoiceInFk INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(
+vInvoiceInFk INT
+)
BEGIN
/**
* Calcula los vctos. de una factura recibida
@@ -57699,12 +57855,13 @@ BEGIN
COUNT(DISTINCT(pdd.detail)) cont,
s.payDay,
ii.issued,
- DATE(ii.created) + INTERVAL 2 DAY created
+ DATE(ii.created) + INTERVAL iic.dueDateMarginDays DAY created
FROM invoiceIn ii
JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk
JOIN supplier s ON s.id = ii.supplierFk
- JOIN payDemDetail pdd ON pdd.id = s.payDemFk
+ JOIN payDemDetail pdd ON pdd.id = s.payDemFk
+ JOIN invoiceInConfig iic
WHERE ii.id = vInvoiceInFk
GROUP BY ii.id
)sub
@@ -58038,9 +58195,11 @@ BEGIN
DECLARE vHasRepeatedTransactions BOOL;
SELECT TRUE INTO vHasRepeatedTransactions
- FROM invoiceInTax
- WHERE invoiceInFk = vSelf
- HAVING COUNT(DISTINCT transactionTypeSageFk) > 1
+ FROM invoiceInTax iit
+ JOIN invoiceIn ii ON ii.id = iit.invoiceInFk
+ WHERE ii.id = vSelf
+ AND ii.serial = 'E'
+ HAVING COUNT(DISTINCT iit.transactionTypeSageFk) > 1
LIMIT 1;
IF vHasRepeatedTransactions THEN
@@ -59101,7 +59260,7 @@ BEGIN
i.transactionTypeSageFk,
@vTaxCodeGeneral := i.taxClassCodeFk
FROM tmp.ticketServiceTax tst
- JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code
+ JOIN invoiceOutTaxMultiConfig i ON i.taxClassCodeFk = tst.code
WHERE i.isService
HAVING taxableBase
) sub;
@@ -59114,7 +59273,7 @@ BEGIN
i.taxTypeSageFk ,
i.transactionTypeSageFk
FROM tmp.ticketTax tt
- JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code
+ JOIN invoiceOutTaxMultiConfig i ON i.taxClassCodeFk = tt.code
WHERE !i.isService
GROUP BY tt.pgcFk
HAVING taxableBase
@@ -60660,6 +60819,7 @@ proc: BEGIN
itemShelvingFk,
saleFk,
quantity,
+ userFk,
isPicked)
SELECT vItemShelvingFk,
vSaleFk,
@@ -60684,6 +60844,65 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addBySaleGroup` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addBySaleGroup`(
+ vSaleGroupFk INT(11)
+)
+BEGIN
+/**
+ * Reserva cantidades con ubicaciones para el contenido de una preparación previa
+ * a través del saleGroup
+ *
+ * @param vSaleGroupFk Identificador de saleGroup
+ */
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vSaleFk INT;
+ DECLARE vSectorFk INT;
+ DECLARE vSales CURSOR FOR
+ SELECT s.id
+ FROM saleGroupDetail sgd
+ JOIN sale s ON sgd.saleFk = s.id
+ JOIN saleTracking str ON str.saleFk = s.id
+ JOIN `state` st ON st.id = str.stateFk
+ AND st.code = 'PREVIOUS_PREPARATION'
+ LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
+ WHERE sgd.saleGroupFk = vSaleGroupFk
+ AND str.workerFk = account.myUser_getId()
+ AND iss.id IS NULL;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SELECT sectorFk INTO vSectorFk
+ FROM operator
+ WHERE workerFk = account.myUser_getId();
+
+ OPEN vSales;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vSales INTO vSaleFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk);
+ END LOOP;
+ CLOSE vSales;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addBySectorCollection` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -60817,58 +61036,58 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reallocate`(
- vItemShelvingFk INT(10),
- vItemFk INT(10),
- vSectorFk INT
+CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reallocate`(
+ vItemShelvingFk INT(10),
+ vItemFk INT(10),
+ vSectorFk INT
)
-BEGIN
-/**
- * Elimina reservas de un itemShelving e intenta reservar en otra ubicación
- *
- * @param vItemShelvingFk Id itemShelving
- * @param vItemFk Id del artículo
- * @param vSectorFk Id del sector
- */
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
- START TRANSACTION;
-
- UPDATE itemShelving
- SET visible = 0,
- available = 0
- WHERE id = vItemShelvingFk
- AND itemFk = vItemFk;
-
- SELECT iss.id
- FROM itemShelvingSale iss
- JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- WHERE iss.itemShelvingFk = vItemShelvingFk
- AND iss.itemFk = vItemFk
- AND NOT iss.isPicked
- FOR UPDATE;
-
- INSERT INTO itemShelvingSaleReserve (saleFk, vSectorFk)
- SELECT DISTINCT iss.saleFk
- FROM itemShelvingSale iss
- JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- WHERE iss.itemShelvingFk = vItemShelvingFk
- AND ish.itemFk = vItemFk
- AND NOT iss.isPicked;
-
- DELETE iss
- FROM itemShelvingSale iss
- JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- WHERE iss.itemShelvingFk = vItemShelvingFk
- AND ish.itemFk = vItemFk
- AND NOT iss.isPicked;
- COMMIT;
-
- CALL itemShelvingSale_doReserve();
+BEGIN
+/**
+ * Elimina reservas de un itemShelving e intenta reservar en otra ubicación
+ *
+ * @param vItemShelvingFk Id itemShelving
+ * @param vItemFk Id del artículo
+ * @param vSectorFk Id del sector
+ */
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ UPDATE itemShelving
+ SET visible = 0,
+ available = 0
+ WHERE id = vItemShelvingFk
+ AND itemFk = vItemFk;
+
+ SELECT iss.id
+ FROM itemShelvingSale iss
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ WHERE iss.itemShelvingFk = vItemShelvingFk
+ AND ish.itemFk = vItemFk
+ AND NOT iss.isPicked
+ FOR UPDATE;
+
+ INSERT INTO itemShelvingSaleReserve (saleFk, sectorFk)
+ SELECT DISTINCT iss.saleFk, vSectorFk
+ FROM itemShelvingSale iss
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ WHERE iss.itemShelvingFk = vItemShelvingFk
+ AND ish.itemFk = vItemFk
+ AND NOT iss.isPicked;
+
+ DELETE iss
+ FROM itemShelvingSale iss
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ WHERE iss.itemShelvingFk = vItemShelvingFk
+ AND ish.itemFk = vItemFk
+ AND NOT iss.isPicked;
+ COMMIT;
+
+ CALL itemShelvingSale_doReserve();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -61036,7 +61255,7 @@ BEGIN
COMMIT;
IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN
- INSERT INTO itemShelvingSaleReserve (saleFk, vSectorFk)
+ INSERT INTO itemShelvingSaleReserve (saleFk, sectorFk)
SELECT vSaleFk, vSectorFk;
CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk, vSectorFk);
END IF;
@@ -61231,7 +61450,7 @@ BEGIN
JOIN ticket t ON t.id = c.ticketFk
WHERE c.id = vClaimFk;
- CALL buyUltimate (vWarehouseFk, util.VN_CURDATE());
+ CALL buy_getUltimate(NULL, vWarehouseFk, util.VN_CURDATE());
INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible)
SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible
@@ -61434,7 +61653,8 @@ BEGIN
ish.id,
s.priority,
ish.isChecked,
- ic.url
+ ic.url,
+ ish.available
FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk
JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci
@@ -61553,7 +61773,7 @@ BEGIN
FROM operator
WHERE workerFk = account.myUser_getId();
- CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
+ CALL buy_getUltimate(vBarcodeItem, vWarehouseFk, util.VN_CURDATE());
SELECT buyFk INTO vBuyFk
FROM tmp.buyUltimate
@@ -62397,6 +62617,7 @@ BEGIN
FROM itemTicketOut i
LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk
JOIN `state` s ON s.id = ts.stateFk
+ JOIN warehouse w ON w.id = i.warehouseFk
LEFT JOIN (
SELECT DISTINCT st.saleFk
FROM saleTracking st
@@ -62404,26 +62625,31 @@ BEGIN
WHERE st.created > vDated
AND (s.isPicked OR st.isChecked)
) stPrevious ON `stPrevious`.`saleFk` = i.saleFk
- WHERE IFNULL(vWarehouseFk, i.warehouseFk) = i.warehouseFk
+ WHERE (vWarehouseFk IS NULL OR i.warehouseFk = vWarehouseFk)
AND (vSelf IS NULL OR i.itemFk = vSelf)
AND (s.isPicked OR i.reserved OR stPrevious.saleFk)
AND i.shipped >= vDated AND i.shipped < vTomorrow
+ AND w.isComparative
UNION ALL
- SELECT itemFk, quantity
- FROM itemEntryIn
- WHERE isReceived
- AND landed >= vDated AND landed < vTomorrow
- AND IFNULL(vWarehouseFk, warehouseInFk) = warehouseInFk
- AND (vSelf IS NULL OR itemFk = vSelf)
- AND NOT isVirtualStock
+ SELECT iei.itemFk, iei.quantity
+ FROM itemEntryIn iei
+ JOIN warehouse w ON w.id = iei.warehouseInFk
+ WHERE iei.isReceived
+ AND iei.landed >= vDated AND iei.landed < vTomorrow
+ AND (vWarehouseFk IS NULL OR iei.warehouseInFk = vWarehouseFk)
+ AND (vSelf IS NULL OR iei.itemFk = vSelf)
+ AND NOT iei.isVirtualStock
+ AND w.isComparative
UNION ALL
- SELECT itemFk, quantity
- FROM itemEntryOut
- WHERE isDelivered
- AND shipped >= vDated
- AND shipped < vTomorrow
- AND IFNULL(vWarehouseFk, warehouseOutFk) = warehouseOutFk
- AND (vSelf IS NULL OR itemFk = vSelf)
+ SELECT ieo.itemFk, ieo.quantity
+ FROM itemEntryOut ieo
+ JOIN warehouse w ON w.id = ieo.warehouseOutFk
+ WHERE ieo.isDelivered
+ AND ieo.shipped >= vDated
+ AND ieo.shipped < vTomorrow
+ AND (vWarehouseFk IS NULL OR ieo.warehouseOutFk = vWarehouseFk)
+ AND (vSelf IS NULL OR ieo.itemFk = vSelf)
+ AND w.isComparative
) t
GROUP BY itemFk
ON DUPLICATE KEY UPDATE
@@ -62668,19 +62894,20 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_comparative`(
)
proc: BEGIN
/**
- * Genera una tabla de comparativa de artículos por itemType/comprador/fecha.
- * Los datos se calculan en función de los parámetros proporcionados.
+ * Generates a comparison table of items by itemType/buyer/date.
+ * The data is calculated based on the provided parameters.
*
- * @param vDate La fecha para la cual se generará la comparativa.
- * @param vDayRange El rango de días a considerar para la comparativa.
- * @param vWarehouseFk El identificador del almacén para filtrar los artículos.
- * @param vAvailableSince La fecha de disponibilidad desde la cual se consideran los artículos disponibles.
- * @param vBuyerFk El identificador del comprador para filtrar los artículos.
- * @param vIsFloramondo Indica si se deben incluir solo los artículos de Floramondo (opcional).
- * @param vCountryFk El identificador del país.
- * @param tmp.comparativeFilterType(filterFk INT ,itemTypeFk INT)
+ * @param vDate The date for which the comparison will be generated.
+ * @param vDayRange The range of days to consider for the comparison.
+ * @param vWarehouseFk The warehouse identifier to filter the items.
+ * @param vAvailableSince The availability date from which the items are considered available.
+ * @param vBuyerFk The buyer identifier to filter the items.
+ * @param vIsFloramondo Indicates whether only Floramondo items should be included (optional).
+ * @param vCountryFk The country identifier.
+ * @param tmp.comparativeFilterType(filterFk INT, itemTypeFk INT)
* @return tmp.comparative
*/
+
DECLARE vDayRangeStart DATE;
DECLARE vDayRangeEnd DATE;
DECLARE w1, w2, w3, w4, w5, w6, w7 INT;
@@ -63053,7 +63280,7 @@ BEGIN
END IF;
SELECT warehouseFk INTO vWarehouseFk
- FROM userConfig
+ FROM userMultiConfig
WHERE userFk = account.myUser_getId();
IF NOT vWarehouseFk OR vWarehouseFk IS NULL THEN
@@ -63104,7 +63331,7 @@ BEGIN
ORDER BY created DESC
LIMIT 1;
- CALL buyUltimate(vWarehouseFk, vCurdate);
+ CALL buy_getUltimate(vSelf, vWarehouseFk, vCurdate);
SELECT b.entryFk, bu.buyFk,IFNULL(b.buyingValue, 0) INTO vLastEntryFk, vLastBuyFk, vBuyingValueOriginal
FROM tmp.buyUltimate bu
@@ -63785,7 +64012,10 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getInfo`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getInfo`(
+ `vBarcode` VARCHAR(22),
+ `vWarehouseFk` INT
+)
BEGIN
/**
* Devuelve información relativa al item correspondiente del vBarcode pasado
@@ -63797,12 +64027,14 @@ BEGIN
DECLARE vCacheAvailableFk INT;
DECLARE vVisibleItemShelving INT;
DECLARE vItemFk INT;
+ DECLARE vDated DATE;
+
+ SELECT barcodeToItem(vBarcode), util.VN_CURDATE() INTO vItemFk, vDated;
CALL cache.visible_refresh(vCacheVisibleFk, FALSE, vWarehouseFk);
- CALL cache.available_refresh(vCacheAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
- CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
-
- SELECT barcodeToItem(vBarcode) INTO vItemFk;
+ CALL cache.available_refresh(vCacheAvailableFk, FALSE, vWarehouseFk, vDated);
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, vDated);
+
SELECT SUM(visible) INTO vVisibleItemShelving
FROM itemShelvingStock
WHERE itemFk = vItemFk
@@ -63940,39 +64172,42 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinacum`(IN vWarehouseFk TINYINT, IN vDatedFrom DATETIME, IN vRange INT, IN vItemFk INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinacum`(
+ vWarehouseFk TINYINT,
+ vDated DATE,
+ vRange INT,
+ vItemFk INT
+)
BEGIN
/**
- * Cálculo del mínimo acumulado, para un item/almacén especificado, en caso de
- * NULL para todo.
+ * Cálculo del mínimo acumulado, para un item/almacén
+ * especificado, en caso de NULL para todos.
*
- * @param vWarehouseFk -> warehouseFk
- * @param vDatedFrom -> fecha inicio
- * @param vRange -> número de días a considerar
- * @param vItemFk -> Identificador de item
+ * @param vWarehouseFk Id warehouse
+ * @param vDated Fecha inicio
+ * @param vRange Número de días a considerar
+ * @param vItemFk Id de artículo
* @return tmp.itemMinacum
*/
- DECLARE vDatedTo DATETIME;
+ DECLARE vDatedTo DATETIME DEFAULT util.dayEnd(vDated + INTERVAL vRange DAY);
- SET vDatedFrom = TIMESTAMP(DATE(vDatedFrom), '00:00:00');
- SET vDatedTo = TIMESTAMP(TIMESTAMPADD(DAY, vRange, vDatedFrom), '23:59:59');
-
- DROP TEMPORARY TABLE IF EXISTS tmp.itemCalc;
- CREATE TEMPORARY TABLE tmp.itemCalc
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
SELECT sub.itemFk,
sub.dated,
CAST(SUM(sub.quantity) AS SIGNED) quantity,
sub.warehouseFk
- FROM (SELECT s.itemFk,
+ FROM (
+ SELECT s.itemFk,
DATE(t.shipped) dated,
-s.quantity quantity,
t.warehouseFk
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
- WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ WHERE t.shipped BETWEEN vDated AND vDatedTo
AND t.warehouseFk
- AND s.quantity != 0
+ AND s.quantity <> 0
AND (vItemFk IS NULL OR s.itemFk = vItemFk)
AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk)
UNION ALL
@@ -63983,10 +64218,10 @@ BEGIN
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vDatedFrom AND vDatedTo
+ WHERE t.landed BETWEEN vDated AND vDatedTo
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND !e.isExcludedFromAvailable
- AND b.quantity != 0
+ AND NOT e.isExcludedFromAvailable
+ AND b.quantity <> 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk)
UNION ALL
SELECT b.itemFk,
@@ -63996,29 +64231,46 @@ BEGIN
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
- WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ WHERE t.shipped BETWEEN vDated AND vDatedTo
AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk)
- AND !e.isExcludedFromAvailable
- AND b.quantity != 0
+ AND NOT e.isExcludedFromAvailable
+ AND b.quantity <> 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk)
- AND !e.isRaid
+ AND NOT e.isRaid
+ UNION ALL
+ SELECT r.itemFk,
+ r.shipment,
+ -r.amount,
+ r.warehouseFk
+ FROM hedera.orderRow r
+ JOIN hedera.`order` o ON o.id = r.orderFk
+ JOIN client c ON c.id = o.customer_id
+ WHERE r.shipment BETWEEN vDated AND vDatedTo
+ AND (vWarehouseFk IS NULL OR r.warehouseFk = vWarehouseFk)
+ AND r.created >= (
+ SELECT util.VN_NOW() - INTERVAL TIME_TO_SEC(reserveTime) SECOND
+ FROM hedera.orderConfig
+ )
+ AND NOT o.confirmed
+ AND (vItemFk IS NULL OR r.itemFk = vItemFk)
+ AND r.amount <> 0
) sub
GROUP BY sub.itemFk, sub.warehouseFk, sub.dated;
- CALL item_getAtp(vDatedFrom);
- DROP TEMPORARY TABLE tmp.itemCalc;
+ CALL item_getAtp(vDated);
- DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum;
- CREATE TEMPORARY TABLE tmp.itemMinacum
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemMinacum
(INDEX(itemFk))
ENGINE = MEMORY
- SELECT i.itemFk,
- i.warehouseFk,
- i.quantity amount
- FROM tmp.itemAtp i
- HAVING amount != 0;
+ SELECT itemFk,
+ warehouseFk,
+ quantity amount
+ FROM tmp.itemAtp
+ WHERE quantity <> 0;
- DROP TEMPORARY TABLE tmp.itemAtp;
+ DROP TEMPORARY TABLE
+ tmp.itemAtp,
+ tmp.itemCalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64283,7 +64535,7 @@ BEGIN
*/
ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT;
- CALL buyUltimate(vWarehouseFk, vDate);
+ CALL buy_getUltimate (NULL, vWarehouseFk, vDate);
CREATE OR REPLACE TEMPORARY TABLE tmp
(KEY (itemFk))
@@ -64418,12 +64670,18 @@ BEGIN
i.tag8 = JSON_VALUE(vTags, '$.8'),
i.tag9 = JSON_VALUE(vTags, '$.9'),
i.tag10 = JSON_VALUE(vTags, '$.10'),
+ i.tag11 = JSON_VALUE(vTags, '$.11'),
+ i.tag12 = JSON_VALUE(vTags, '$.12'),
+ i.tag13 = JSON_VALUE(vTags, '$.13'),
i.value5 = JSON_VALUE(vValues, '$.5'),
i.value6 = JSON_VALUE(vValues, '$.6'),
i.value7 = JSON_VALUE(vValues, '$.7'),
i.value8 = JSON_VALUE(vValues, '$.8'),
i.value9 = JSON_VALUE(vValues, '$.9'),
i.value10 = JSON_VALUE(vValues, '$.10'),
+ i.value11 = JSON_VALUE(vValues, '$.11'),
+ i.value12 = JSON_VALUE(vValues, '$.12'),
+ i.value13 = JSON_VALUE(vValues, '$.13'),
i.producerFk = p.id,
i.inkFk = k.id,
i.originFk = IFNULL(o.id, i.originFk)
@@ -64699,232 +64957,256 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_valuateInventory` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_valuateInventory`(
-vDated DATE
+ vDated DATE,
+ vItemTypeFk INT,
+ vItemCategoryFk INT
)
BEGIN
-DECLARE vInventoried DATE;
-DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE;
-DECLARE vInventoryClone DATE;
-DECLARE vDateDayEnd DATETIME;
-DECLARE vInventorySupplierFk INT;
+ DECLARE vInventoried DATE;
+ DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE;
+ DECLARE vInventoryClone DATE;
+ DECLARE vDateDayEnd DATETIME;
+ DECLARE vInventorySupplierFk INT;
-SELECT inventorySupplierFk INTO vInventorySupplierFk
-FROM entryConfig;
+ SELECT inventorySupplierFk INTO vInventorySupplierFk
+ FROM entryConfig;
-SET vDateDayEnd = util.dayEnd(vDated);
+ SET vDateDayEnd = util.dayEnd(vDated);
-SELECT tr.landed INTO vInventoried
-FROM travel tr
-JOIN `entry` e ON e.travelFk = tr.id
-WHERE tr.landed <= vDateDayEnd
-AND e.supplierFk = vInventorySupplierFk
-ORDER BY tr.landed DESC
-LIMIT 1;
+ SELECT tr.landed INTO vInventoried
+ FROM travel tr
+ JOIN `entry` e ON e.travelFk = tr.id
+ WHERE tr.landed <= vDateDayEnd
+ AND e.supplierFk = vInventorySupplierFk
+ ORDER BY tr.landed DESC
+ LIMIT 1;
-SET vHasNotInventory = (vInventoried IS NULL);
+ SET vHasNotInventory = (vInventoried IS NULL);
+
+ IF vHasNotInventory THEN
+ SELECT landed INTO vInventoryClone
+ FROM travel tr
+ JOIN `entry` e ON e.travelFk = tr.id
+ WHERE tr.landed >= vDated
+ AND e.supplierFk = vInventorySupplierFk
+ ORDER BY landed ASC
+ LIMIT 1;
-IF vHasNotInventory THEN
-SELECT landed INTO vInventoryClone
-FROM travel tr
-JOIN `entry` e ON e.travelFk = tr.id
-WHERE tr.landed >= vDated
-AND e.supplierFk = vInventorySupplierFk
-ORDER BY landed ASC
-LIMIT 1;
+ SET vInventoried = vDated + INTERVAL 1 DAY;
+ SET vDateDayEnd = vInventoryClone;
+ END IF;
-SET vInventoried = vDated + INTERVAL 1 DAY;
-SET vDateDayEnd = vInventoryClone;
-END IF;
+ CREATE OR REPLACE TEMPORARY TABLE tInventory(
+ warehouseFk SMALLINT,
+ itemFk BIGINT,
+ quantity INT,
+ volume DECIMAL(10,2),
+ cost DOUBLE DEFAULT 0,
+ total DOUBLE DEFAULT 0,
+ warehouseInventory VARCHAR(20),
+ PRIMARY KEY (warehouseInventory, itemFk) USING HASH
+ )
+ ENGINE = MEMORY;
+
+ -- Inventario inicial
+ IF vHasNotInventory THEN
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ SUM(b.quantity),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = t.categoryFk
+ JOIN warehouse w ON w.id = tr.warehouseInFk
+ WHERE tr.landed = vDateDayEnd
+ AND e.supplierFk = vInventorySupplierFk
+ AND w.valuatedInventory
+ AND t.isInventory
+ AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
+ AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
+ GROUP BY tr.warehouseInFk, b.itemFk;
+ ELSE
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ SUM(b.quantity),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = t.categoryFk
+ JOIN warehouse w ON w.id = tr.warehouseInFk
+ WHERE tr.landed = vInventoried
+ AND e.supplierFk = vInventorySupplierFk
+ AND w.valuatedInventory
+ AND t.isInventory
+ AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
+ AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
+ GROUP BY tr.warehouseInFk, b.itemFk;
+ END IF;
-CREATE OR REPLACE TEMPORARY TABLE tInventory(
-warehouseFk SMALLINT,
-itemFk BIGINT,
-quantity INT,
-volume DECIMAL(10,2),
-cost DOUBLE DEFAULT 0,
-total DOUBLE DEFAULT 0,
-warehouseInventory VARCHAR(20),
-PRIMARY KEY (warehouseInventory, itemFk) USING HASH
-)
-ENGINE = MEMORY;
+ -- Añadimos las entradas
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ b.quantity * IF(vHasNotInventory, -1, 1),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = t.categoryFk
+ JOIN warehouse w ON w.id = tr.warehouseInFk
+ WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
+ AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE)
+ AND NOT e.isRaid
+ AND w.valuatedInventory
+ AND t.isInventory
+ AND e.supplierFk <> vInventorySupplierFk
+ AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
+ AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory, -1, 1));
+ -- Descontamos las salidas
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseOutFk,
+ b.itemFk,
+ b.quantity * IF(vHasNotInventory, 1, -1),
+ w.name
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = t.categoryFk
+ JOIN warehouse w ON w.id = tr.warehouseOutFk
+ WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd
+ AND NOT e.isRaid
+ AND w.valuatedInventory
+ AND t.isInventory
+ AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
+ AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory,1,-1));
-IF vHasNotInventory THEN
-INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
-SELECT tr.warehouseInFk,
-b.itemFk,
-SUM(b.quantity),
-w.name
-FROM buy b
-JOIN item i ON i.id = b.itemFk
-JOIN `entry` e ON e.id = b.entryFk
-JOIN travel tr ON tr.id = e.travelFk
-JOIN itemType t ON t.id = i.typeFk
-JOIN warehouse w ON w.id = tr.warehouseInFk
-WHERE tr.landed = vDateDayEnd
-AND e.supplierFk = vInventorySupplierFk
-AND w.valuatedInventory
-AND t.isInventory
-GROUP BY tr.warehouseInFk, b.itemFk;
-ELSE
-INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
-SELECT tr.warehouseInFk,
-b.itemFk,
-SUM(b.quantity),
-w.name
-FROM buy b
-JOIN item i ON i.id = b.itemFk
-JOIN `entry` e ON e.id = b.entryFk
-JOIN travel tr ON tr.id = e.travelFk
-JOIN itemType t ON t.id = i.typeFk
-JOIN warehouse w ON w.id = tr.warehouseInFk
-WHERE tr.landed = vInventoried
-AND e.supplierFk = vInventorySupplierFk
-AND w.valuatedInventory
-AND t.isInventory
-GROUP BY tr.warehouseInFk, b.itemFk;
-END IF;
+ -- Descontamos las lineas de venta
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT w.id,
+ s.itemFk,
+ s.quantity * IF(vHasNotInventory, 1, -1),
+ w.name
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN `client` c ON c.id = t.clientFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd
+ AND w.valuatedInventory
+ AND it.isInventory
+ AND (it.id = vItemTypeFk OR vItemTypeFk IS NULL)
+ AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1);
+ -- Volver a poner lo que esta aun en las estanterias
+ IF vDated = util.VN_CURDATE() THEN
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT w.id,
+ s.itemFk,
+ s.quantity * IF(vHasNotInventory, 0, 1),
+ w.name
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN `client` c ON c.id = t.clientFk
+ JOIN item i ON i.id = s.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDated AND vDateDayEnd
+ AND NOT (s.isPicked OR t.isLabeled)
+ AND w.valuatedInventory
+ AND it.isInventory
+ AND (it.id = vItemTypeFk OR vItemTypeFk IS NULL)
+ AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 0, 1);
+ END IF;
-INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
-SELECT tr.warehouseInFk,
-b.itemFk,
-b.quantity * IF(vHasNotInventory, -1, 1),
-w.name
-FROM buy b
-JOIN item i ON i.id = b.itemFk
-JOIN `entry` e ON e.id = b.entryFk
-JOIN travel tr ON tr.id = e.travelFk
-JOIN itemType t ON t.id = i.typeFk
-JOIN warehouse w ON w.id = tr.warehouseInFk
-WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
-AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE)
-AND NOT e.isRaid
-AND w.valuatedInventory
-AND t.isInventory
-AND e.supplierFk <> vInventorySupplierFk
-ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory, -1, 1));
+ -- Mercancia en transito
+ INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
+ SELECT tr.warehouseInFk,
+ b.itemFk,
+ b.quantity,
+ CONCAT(wOut.`name`, ' - ', wIn.`name`)
+ FROM buy b
+ JOIN item i ON i.id = b.itemFk
+ JOIN `entry` e ON e.id = b.entryFk
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN itemType t ON t.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = t.categoryFk
+ JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
+ JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
+ WHERE vDated >= tr.shipped AND vDated < tr.landed
+ AND NOT isRaid
+ AND wIn.valuatedInventory
+ AND t.isInventory
+ AND e.isConfirmed
+ AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
+ AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
+ ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity);
+
+ CALL buy_getUltimate (NULL, NULL, vDateDayEnd);
+ DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity;
-INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
-SELECT tr.warehouseOutFk,
-b.itemFk,
-b.quantity * IF(vHasNotInventory, 1, -1),
-w.name
-FROM buy b
-JOIN item i ON i.id = b.itemFk
-JOIN `entry` e ON e.id = b.entryFk
-JOIN travel tr ON tr.id = e.travelFk
-JOIN itemType t ON t.id = i.typeFk
-JOIN warehouse w ON w.id = tr.warehouseOutFk
-WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd
-AND NOT e.isRaid
-AND w.valuatedInventory
-AND t.isInventory
-ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory,1,-1));
+ UPDATE tInventory i
+ JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk
+ JOIN buy b ON b.id = bu.buyFk
+ LEFT JOIN itemCost ic ON ic.itemFk = i.itemFk
+ AND ic.warehouseFk = i.warehouseFk
+ SET i.total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)),
+ i.cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0),
+ i.volume = i.quantity * ic.cm3delivery / 1000000;
+ SELECT ti.warehouseFk,
+ i.id,
+ i.longName,
+ i.size,
+ ti.quantity,
+ ti.volume,
+ tp.name itemTypeName,
+ ic.name itemCategoryName,
+ ti.cost,
+ ti.total,
+ ti.warehouseInventory,
+ ic.display
+ FROM tInventory ti
+ JOIN warehouse w ON w.id = warehouseFk
+ JOIN item i ON i.id = ti.itemFk
+ JOIN itemType tp ON tp.id = i.typeFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
+ WHERE w.valuatedInventory
+ AND ti.total > 0;
-INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
-SELECT w.id,
-s.itemFk,
-s.quantity * IF(vHasNotInventory, 1, -1),
-w.name
-FROM sale s
-JOIN ticket t ON t.id = s.ticketFk
-JOIN `client` c ON c.id = t.clientFk
-JOIN item i ON i.id = s.itemFk
-JOIN itemType it ON it.id = i.typeFk
-JOIN warehouse w ON w.id = t.warehouseFk
-WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd
-AND w.valuatedInventory
-AND it.isInventory
-ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1);
-
-
-IF vDated = util.VN_CURDATE() THEN
-INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
-SELECT w.id,
-s.itemFk,
-s.quantity * IF(vHasNotInventory, 0, 1),
-w.name
-FROM sale s
-JOIN ticket t ON t.id = s.ticketFk
-JOIN `client` c ON c.id = t.clientFk
-JOIN item i ON i.id = s.itemFk
-JOIN itemType it ON it.id = i.typeFk
-JOIN warehouse w ON w.id = t.warehouseFk
-WHERE t.shipped BETWEEN vDated AND vDateDayEnd
-AND NOT (s.isPicked OR t.isLabeled)
-AND w.valuatedInventory
-AND it.isInventory
-ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 0, 1);
-END IF;
-
-
-INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
-SELECT tr.warehouseInFk,
-b.itemFk,
-b.quantity,
-CONCAT(wOut.`name`, ' - ', wIn.`name`)
-FROM buy b
-JOIN item i ON i.id = b.itemFk
-JOIN `entry` e ON e.id = b.entryFk
-JOIN travel tr ON tr.id = e.travelFk
-JOIN itemType t ON t.id = i.typeFk
-JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
-JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
-WHERE vDated >= tr.shipped AND vDated < tr.landed
-AND NOT isRaid
-AND wIn.valuatedInventory
-AND t.isInventory
-AND e.isConfirmed
-ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity);
-
-CALL buyUltimate(NULL, vDateDayEnd);
-
-DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity;
-
-UPDATE tInventory i
-JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk
-JOIN buy b ON b.id = bu.buyFk
-LEFT JOIN itemCost ic ON ic.itemFk = i.itemFk
-AND ic.warehouseFk = i.warehouseFk
-SET i.total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)),
-i.cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0),
-i.volume = i.quantity * ic.cm3delivery / 1000000;
-
-SELECT ti.warehouseFk,
-i.id,
-i.longName,
-i.size,
-ti.quantity,
-ti.volume,
-tp.name itemTypeName,
-ic.name itemCategoryName,
-ti.cost,
-ti.total,
-ti.warehouseInventory
-FROM tInventory ti
-JOIN warehouse w ON w.id = warehouseFk
-JOIN item i ON i.id = ti.itemFk
-JOIN itemType tp ON tp.id = i.typeFk
-JOIN itemCategory ic ON ic.id = tp.categoryFk
-WHERE w.valuatedInventory
-AND ti.total > 0;
-
-DROP TEMPORARY TABLE
-tmp.buyUltimate,
-tInventory;
+ DROP TEMPORARY TABLE
+ tmp.buyUltimate,
+ tInventory;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -65679,13 +65961,6 @@ proc: BEGIN
) sub
GROUP BY itemFk;
- UPDATE tmp.itemInventory ai
- JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id
- SET ai.inventory = iic.quantity,
- ai.visible = iic.quantity,
- ai.avalaible = iic.quantity,
- ai.sd = iic.quantity;
-
-- Cálculo del visible
CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
@@ -65697,8 +65972,12 @@ proc: BEGIN
WHERE calc_id = vCalcFk;
UPDATE tmp.itemInventory it
- JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id
- SET it.visible = it.visible + ivc.visible;
+ LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id
+ LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id
+ SET it.inventory = iic.quantity,
+ it.visible = ivc.visible,
+ it.avalaible = iic.quantity,
+ it.sd = iic.quantity;
-- Calculo del disponible
CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
@@ -65746,32 +66025,36 @@ proc: BEGIN
CALL item_getAtp(vDate);
CALL travel_upcomingArrivals(vWarehouseFk, vDate);
- UPDATE tmp.itemInventory ai
- JOIN (
- SELECT it.itemFk,
- SUM(it.quantity) quantity,
- im.quantity minQuantity
- FROM tmp.itemCalc it
- JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
- JOIN item i ON i.id = it.itemFk
- LEFT JOIN origin o ON o.id = i.originFk
- LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
- WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
- t.landing,
- vDateToTomorrow)
- GROUP BY it.itemFk
- ) sub ON sub.itemFk = ai.id
- SET ai.avalaible = IF(sub.minQuantity > 0,
- ai.avalaible,
- ai.avalaible + sub.minQuantity),
- ai.sd = ai.inventory + sub.quantity;
+ CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT it.itemFk,
+ SUM(it.quantity) quantity,
+ im.quantity minQuantity
+ FROM tmp.itemCalc it
+ JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
+ JOIN item i ON i.id = it.itemFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
+ WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
+ t.landing,
+ vDateToTomorrow)
+ GROUP BY it.itemFk;
+
+ UPDATE tmp.itemInventory it
+ JOIN tItemAvailableCalc iac ON iac.itemFk = it.id
+ SET it.avalaible = IF(iac.minQuantity > 0,
+ it.avalaible,
+ it.avalaible + iac.minQuantity),
+ it.sd = it.inventory + iac.quantity;
DROP TEMPORARY TABLE
tmp.itemTravel,
tmp.itemCalc,
tmp.itemAtp,
tItemInventoryCalc,
- tItemVisibleCalc;
+ tItemVisibleCalc,
+ tItemAvailableCalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -66861,27 +67144,30 @@ proc: BEGIN
WHERE NOT `lines`;
-- Lineas por linea de encajado
+ CREATE OR REPLACE TEMPORARY TABLE tItemPackingType
+ (PRIMARY KEY(ticketFk))
+ ENGINE = MEMORY
+ SELECT ticketFk,
+ SUM(sub.H) H,
+ SUM(sub.V) V,
+ SUM(sub.N) N
+ FROM (
+ SELECT t.ticketFk,
+ SUM(i.itemPackingTypeFk = 'H') H,
+ SUM(i.itemPackingTypeFk = 'V') V,
+ SUM(i.itemPackingTypeFk IS NULL) N
+ FROM tmp.productionTicket t
+ JOIN sale s ON s.ticketFk = t.ticketFk
+ JOIN item i ON i.id = s.itemFk
+ GROUP BY t.ticketFk, i.itemPackingTypeFk
+ ) sub
+ GROUP BY ticketFk;
+
UPDATE tmp.productionBuffer pb
- JOIN (
- SELECT ticketFk,
- SUM(sub.H) H,
- SUM(sub.V) V,
- SUM(sub.N) N
- FROM (
- SELECT t.ticketFk,
- SUM(i.itemPackingTypeFk = 'H') H,
- SUM(i.itemPackingTypeFk = 'V') V,
- SUM(i.itemPackingTypeFk IS NULL) N
- FROM tmp.productionTicket t
- JOIN sale s ON s.ticketFk = t.ticketFk
- JOIN item i ON i.id = s.itemFk
- GROUP BY t.ticketFk, i.itemPackingTypeFk
- ) sub
- GROUP BY ticketFk
- ) sub2 ON sub2.ticketFk = pb.ticketFk
- SET pb.H = sub2.H,
- pb.V = sub2.V,
- pb.N = sub2.N;
+ JOIN tItemPackingType ti ON ti.ticketFk = pb.ticketFk
+ SET pb.H = ti.H,
+ pb.V = ti.V,
+ pb.N = ti.N;
-- Colecciones segun tipo de encajado
UPDATE tmp.productionBuffer pb
@@ -66960,7 +67246,8 @@ proc: BEGIN
tmp.risk,
tmp.ticket_problems,
tmp.ticketWithPrevia,
- tItemShelvingStock;
+ tItemShelvingStock,
+ tItemPackingType;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68339,17 +68626,21 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `route_updateM3`(vRoute INT)
+CREATE DEFINER=`root`@`localhost` PROCEDURE `route_updateM3`(
+ vSelf INT
+)
BEGIN
+/**
+ * Actualiza el volumen de la ruta.
+ *
+ * @param vSelf Id ruta
+ */
+ DECLARE vVolume DECIMAL(10,1)
+ DEFAULT (SELECT SUM(volume) FROM saleVolume WHERE routeFk = vSelf);
- UPDATE vn.route r
- LEFT JOIN (
- SELECT routeFk, SUM(volume) AS m3
- FROM saleVolume
- WHERE routeFk = vRoute
- ) v ON v.routeFk = r.id
- SET r.m3 = IFNULL(v.m3,0)
- WHERE r.id =vRoute;
+ UPDATE `route`
+ SET m3 = IFNULL(vVolume, 0)
+ WHERE id = vSelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68445,15 +68736,10 @@ BEGIN
* @param vSaleGroupFk id de la preparación previa
* @param vParkingFk id del parking
*/
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- RESIGNAL;
- END;
-
UPDATE saleGroup sg
SET sg.parkingFk = vParkingFk
- WHERE sg.id = vSaleGroupFk
- AND sg.created >= util.VN_CURDATE() - INTERVAL 1 WEEK;
+ WHERE sg.id = vSaleGroupFk
+ AND sg.created >= util.VN_CURDATE() - INTERVAL 1 WEEK;
CALL ticket_setNextState(ticket_get(vSaleGroupFk));
END ;;
@@ -69496,7 +69782,7 @@ BEGIN
DECLARE vAvailableCache INT;
DECLARE vVisibleCache INT;
DECLARE vDone BOOL;
- DECLARE vComponentCount INT;
+ DECLARE vRequiredComponent INT;
DECLARE vCursor CURSOR FOR
SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), DATE(tt.shipped))
@@ -69537,7 +69823,7 @@ BEGIN
SELECT ticketFk, clientFk
FROM tmp.sale_getProblems;
- SELECT COUNT(*) INTO vComponentCount
+ SELECT COUNT(*) INTO vRequiredComponent
FROM component
WHERE isRequired;
@@ -69579,20 +69865,18 @@ BEGIN
-- Faltan componentes
INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk)
- SELECT ticketFk, (vComponentCount > nComp) hasComponentLack, saleFk
- FROM (
- SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk
- FROM tmp.ticket_list tl
- JOIN sale s ON s.ticketFk = tl.ticketFk
- LEFT JOIN saleComponent sc ON sc.saleFk = s.id
- LEFT JOIN component c ON c.id = sc.componentFk AND c.isRequired
- JOIN ticket t ON t.id = tl.ticketFk
- JOIN agencyMode am ON am.id = t.agencyModeFk
- JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
- WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
- AND s.quantity > 0
- GROUP BY s.id
- ) sub
+ SELECT t.id, COUNT(c.id) < vRequiredComponent hasComponentLack, s.id
+ FROM tmp.ticket_list tl
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ LEFT JOIN component c ON c.id = sc.componentFk
+ AND c.isRequired
+ WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
+ AND s.quantity > 0
+ GROUP BY s.id
HAVING hasComponentLack;
-- Cliente congelado
@@ -69759,7 +70043,7 @@ BEGIN
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
-- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra
- CALL buyUltimate(vWarehouseFk, vDate);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vDate);
INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT ticketFk, problem ,saleFk
FROM (
@@ -69872,14 +70156,14 @@ DELIMITER ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_recalcComponent` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb3 */ ;
-/*!50003 SET character_set_results = utf8mb3 */ ;
-/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_recalcComponent`(vOption VARCHAR(25))
proc: BEGIN
@@ -69960,7 +70244,7 @@ proc: BEGIN
DROP TEMPORARY TABLE tmp.zoneGetLanded;
-- rellena la tabla buyUltimate con la ultima compra
- CALL buyUltimate (vWarehouseFk, vShipped);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY
@@ -70063,7 +70347,7 @@ BEGIN
JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSaleFk;
- CALL buyUltimate(vWarehouseFk, vDate);
+ CALL buy_getUltimate(vNewItemFk, vWarehouseFk, vDate);
SELECT `grouping`, groupingMode, packing
INTO vGrouping,vGroupingMode,vPacking
@@ -70071,6 +70355,8 @@ BEGIN
JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk
WHERE tmp.itemFk = vNewItemFk AND tmp.WarehouseFk = vWarehouseFk;
+ DROP TEMPORARY TABLE tmp.buyUltimate;
+
IF vGroupingMode = 'packing' AND vPacking > 0 THEN
SET vRoundQuantity = vPacking;
END IF;
@@ -70166,24 +70452,29 @@ BEGIN
*/
DECLARE vSaleFk INT;
DECLARE vHasProblem INT;
+ DECLARE vIsProblemCalcNeeded BOOL;
DECLARE vDone BOOL;
- DECLARE vSaleList CURSOR FOR SELECT saleFk, hasProblem FROM tmp.sale;
+ DECLARE vSaleList CURSOR FOR
+ SELECT saleFk, hasProblem, isProblemCalcNeeded
+ FROM tmp.sale;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vSaleList;
l: LOOP
SET vDone = FALSE;
- FETCH vSaleList INTO vSaleFk, vHasProblem;
+ FETCH vSaleList INTO vSaleFk, vHasProblem, vIsProblemCalcNeeded;
IF vDone THEN
LEAVE l;
END IF;
UPDATE sale
- SET problem = CONCAT(
- IF(vHasProblem,
- CONCAT(problem, ',', vProblemCode),
- REPLACE(problem, vProblemCode , '')))
+ SET problem = IF (vIsProblemCalcNeeded,
+ CONCAT(
+ IF(vHasProblem,
+ CONCAT(problem, ',', vProblemCode),
+ REPLACE(problem, vProblemCode , ''))),
+ NULL)
WHERE id = vSaleFk;
END LOOP;
CLOSE vSaleList;
@@ -70218,7 +70509,7 @@ BEGIN
ENGINE = MEMORY
SELECT vSelf saleFk,
sale_hasComponentLack(vSelf) hasProblem,
- ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded
+ (ticket_isProblemCalcNeeded(ticketFk) AND quantity > 0) isProblemCalcNeeded
FROM sale
WHERE id = vSelf;
@@ -70256,9 +70547,9 @@ BEGIN
ENGINE = MEMORY
SELECT saleFk,
sale_hasComponentLack(saleFk) hasProblem,
- ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded
+ (ticket_isProblemCalcNeeded(ticketFk) AND quantity > 0) isProblemCalcNeeded
FROM (
- SELECT s.id saleFk, s.ticketFk
+ SELECT s.id saleFk, s.ticketFk, s.quantity
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
LEFT JOIN saleComponent sc ON sc.saleFk = s.id
@@ -70305,7 +70596,7 @@ BEGIN
JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSelf;
- CALL buyUltimate(vWarehouseFk, vShipped);
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
SELECT vSelf saleFk,
@@ -70681,12 +70972,6 @@ BEGIN
DECLARE vParkingFk INT;
DECLARE vLastWeek DATE;
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
SET vParkingCode = REPLACE(vParkingCode, ' ', '');
SELECT id INTO vParkingFk
@@ -70697,8 +70982,6 @@ BEGIN
CALL util.throw('parkingNotExist');
END IF;
- START TRANSACTION;
-
SET vLastWeek = util.VN_CURDATE() - INTERVAL 1 WEEK;
-- Comprobamos si es una prep. previa, ticket, colección o shelving
@@ -70713,8 +70996,6 @@ BEGIN
ELSE
CALL util.throw('paramNotExist');
END IF;
-
- COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -70991,21 +71272,21 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelving_setParking`(IN `vShelvingCode` VARCHAR(8), IN `vParkingFk` INT)
-proc: BEGIN
+BEGIN
/**
* Aparca una matrícula en un parking
*
* @param vShelvingCode code de la matrícula
* @param vParkingFk id del parking
*/
- INSERT INTO vn.shelvingLog (originFk, userFk, action , description,changedModel,changedModelId)
+ INSERT INTO shelvingLog (originFk, userFk, action , description,changedModel,changedModelId)
SELECT s.id, account.myUser_getId(), 'update', CONCAT("Cambio parking ",vShelvingCode," de ", p.code," a ", pNew.code),'Shelving',s.id
FROM parking p
JOIN shelving s ON s.parkingFk = p.id
JOIN parking pNew ON pNew.id = vParkingFk
WHERE s.code = vShelvingCode COLLATE utf8_unicode_ci;
- UPDATE vn.shelving
+ UPDATE shelving
SET parkingFk = vParkingFk,
parked = util.VN_NOW(),
isPrinted = TRUE
@@ -71255,7 +71536,7 @@ BEGIN
WHERE warehouse_id = vAuctionWarehouseFk
ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity);
- CALL buyUltimate(vAuctionWarehouseFk, vDated);
+ CALL buy_getUltimate(NULL, vAuctionWarehouseFk, vDated);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -74392,13 +74673,12 @@ BEGIN
FROM zone
WHERE id = vZoneFk;
- CALL buyUltimate(vWarehouseFk, vShipped);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY (
- SELECT
- vWarehouseFk AS warehouseFk,
- NULL AS available,
+ SELECT vWarehouseFk warehouseFk,
+ NULL available,
s.itemFk,
bu.buyFk,
vZoneFk zoneFk
@@ -75694,11 +75974,6 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- RESIGNAL;
- END;
-
INSERT INTO vn.ticketParking(ticketFk, parkingFk)
SELECT IFNULL(tc2.ticketFk, t.id), vParkingFk
FROM ticket t
@@ -75793,24 +76068,28 @@ BEGIN
*/
DECLARE vTicketFk INT;
DECLARE vHasProblem INT;
+ DECLARE vIsProblemCalcNeeded BOOL;
DECLARE vDone BOOL;
- DECLARE vTicketList CURSOR FOR SELECT ticketFk, hasProblem FROM tmp.ticket;
+ DECLARE vTicketList CURSOR FOR
+ SELECT ticketFk, hasProblem, isProblemCalcNeeded
+ FROM tmp.ticket;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vTicketList;
l: LOOP
SET vDone = FALSE;
- FETCH vTicketList INTO vTicketFk, vHasProblem;
+ FETCH vTicketList INTO vTicketFk, vHasProblem, vIsProblemCalcNeeded;
IF vDone THEN
LEAVE l;
END IF;
UPDATE ticket
- SET problem = CONCAT(
- IF(vHasProblem,
+ SET problem = IF(vIsProblemCalcNeeded,
+ CONCAT(IF(vHasProblem,
CONCAT(problem, ',', vProblemCode),
- REPLACE(problem, vProblemCode , '')))
+ REPLACE(problem, vProblemCode , ''))),
+ NULL)
WHERE id = vTicketFk;
END LOOP;
CLOSE vTicketList;
@@ -75964,6 +76243,54 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemRiskByClient` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemRiskByClient`(
+ vClientFk INT
+)
+BEGIN
+/**
+ * Updates future ticket risk for a client.
+ *
+ * @param vClientFk Id client
+ */
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE vTicketFk INT;
+ DECLARE vTickets CURSOR FOR
+ SELECT id
+ FROM ticket
+ WHERE clientFk = vClientFk
+ AND shipped >= util.VN_CURDATE()
+ AND refFk IS NULL;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vTickets;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vTickets INTO vTicketFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL vn.ticket_setProblemRisk(vTicketFk);
+ END LOOP;
+ CLOSE vTickets;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemRounding` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -75989,7 +76316,7 @@ BEGIN
FROM ticket
WHERE id = vSelf;
- CALL buyUltimate(vWarehouseFk, vDated);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk, isProblemCalcNeeded))
@@ -76142,96 +76469,85 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setRisk`(
- vClientFk INT)
+ vClientFk INT
+)
BEGIN
/**
- * Update the risk for a client with pending tickets
+ * Update the risk for a client with pending tickets.
*
* @param vClientFk Id cliente
*/
- DECLARE vHasDebt BOOL;
- DECLARE vStarted DATETIME;
-
- SELECT COUNT(*) INTO vHasDebt
- FROM `client`
- WHERE id = vClientFk
- AND typeFk = 'normal';
-
- IF vHasDebt THEN
-
- SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted
- FROM clientConfig;
-
+ IF (SELECT COUNT(*) FROM client WHERE id = vClientFk AND typeFk = 'normal') THEN
CREATE OR REPLACE TEMPORARY TABLE tTicketRisk
- (KEY (ticketFk))
+ (PRIMARY KEY (ticketFk))
ENGINE = MEMORY
- WITH ticket AS(
- SELECT id ticketFk,
- companyFk,
- DATE(shipped) dated,
- totalWithVat,
- ticket_isProblemCalcNeeded(id) isProblemCalcNeeded
- FROM vn.ticket
- WHERE clientFk = vClientFk
- AND refFk IS NULL
- AND NOT isDeleted
- AND IFNULL(totalWithVat, 0) <> 0
- AND shipped > vStarted
- ), balance AS(
- SELECT SUM(amount)amount, companyFk
- FROM (
- SELECT amount, companyFk
- FROM vn.clientRisk
- WHERE clientFk = vClientFk
- UNION ALL
- SELECT -(SUM(amount) / 100) amount, tm.companyFk
- FROM hedera.tpvTransaction t
- JOIN hedera.tpvMerchant tm ON t.id = t.merchantFk
- WHERE clientFk = vClientFk
- AND receiptFk IS NULL
- AND status = 'ok'
- ) sub
- WHERE companyFk
- GROUP BY companyFk
- ), uninvoiced AS(
+ WITH ticket AS (
+ SELECT t.id ticketFk,
+ t.companyFk,
+ DATE(t.shipped) dated,
+ t.totalWithVat,
+ ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
+ FROM vn.ticket t
+ JOIN vn.clientConfig cc
+ WHERE t.clientFk = vClientFk
+ AND t.refFk IS NULL
+ AND NOT t.isDeleted
+ AND IFNULL(t.totalWithVat, 0) <> 0
+ AND t.shipped > (util.VN_CURDATE() - INTERVAL cc.riskScope MONTH)
+ ), uninvoiced AS (
SELECT companyFk, dated, SUM(totalWithVat) amount
FROM ticket
- GROUP BY companyFk, dated
- ), receipt AS(
- SELECT companyFk, DATE(payed) dated, SUM(amountPaid) amount
- FROM vn.receipt
- WHERE clientFk = vClientFk
- AND payed > util.VN_CURDATE()
- GROUP BY companyFk, DATE(payed)
- ), risk AS(
+ GROUP BY companyFk, dated
+ ), companies AS (
+ SELECT DISTINCT companyFk FROM uninvoiced
+ ), balance AS (
+ SELECT SUM(IFNULL(amount, 0))amount, companyFk
+ FROM (
+ SELECT cr.amount, c.companyFk
+ FROM companies c
+ LEFT JOIN vn.clientRisk cr ON cr.companyFk = c.companyFk
+ AND cr.clientFk = vClientFk
+ UNION ALL
+ SELECT -(SUM(t.amount) / 100) amount, c.companyFk
+ FROM companies c
+ LEFT JOIN hedera.tpvMerchant tm ON tm.companyFk = c.companyFk
+ LEFT JOIN hedera.tpvTransaction t ON t.merchantFk = tm.id
+ AND t.clientFk = vClientFk
+ AND t.receiptFk IS NULL
+ AND t.`status` = 'ok'
+ ) sub
+ WHERE companyFk
+ GROUP BY companyFk
+ ), receipt AS (
+ SELECT r.companyFk, DATE(r.payed) dated, SUM(r.amountPaid) amount
+ FROM vn.receipt r
+ JOIN companies c ON c.companyFk = r.companyFk
+ WHERE r.clientFk = vClientFk
+ AND r.payed > util.VN_CURDATE()
+ GROUP BY r.companyFk, DATE(r.payed)
+ ), risk AS (
SELECT b.companyFk,
- ui.dated,
- SUM(ui.amount) OVER (PARTITION BY b.companyFk ORDER BY ui.dated ) +
+ ui.dated,
+ SUM(ui.amount) OVER (PARTITION BY b.companyFk ORDER BY ui.dated) +
b.amount +
SUM(IFNULL(r.amount, 0)) amount
FROM balance b
JOIN uninvoiced ui ON ui.companyFk = b.companyFk
- LEFT JOIN receipt r ON r.dated > ui.dated AND r.companyFk = ui.companyFk
+ LEFT JOIN receipt r ON r.dated > ui.dated
+ AND r.companyFk = ui.companyFk
GROUP BY b.companyFk, ui.dated
- )
- SELECT ti.ticketFk, r.amount, ti.isProblemCalcNeeded
- FROM ticket ti
- JOIN risk r ON r.dated = ti.dated AND r.companyFk = ti.companyFk;
+ )
+ SELECT ti.ticketFk, r.amount, ti.isProblemCalcNeeded
+ FROM ticket ti
+ JOIN risk r ON r.dated = ti.dated
+ AND r.companyFk = ti.companyFk;
UPDATE ticket t
JOIN tTicketRisk tr ON tr.ticketFk = t.id
- SET t.risk = tr.amount
- WHERE tr.isProblemCalcNeeded
- ORDER BY t.id;
-
- UPDATE ticket t
- JOIN tTicketRisk tr ON tr.ticketFk = t.id
- SET t.risk = NULL
- WHERE tr.isProblemCalcNeeded
- ORDER BY t.id;
+ SET t.risk = IF(tr.isProblemCalcNeeded, tr.amount, NULL);
DROP TEMPORARY TABLE tTicketRisk;
- END IF;
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -76408,7 +76724,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitItemPackingType`(
vSelf INT,
- vItemPackingTypeFk VARCHAR(1)
+ vOriginalItemPackingTypeFk VARCHAR(1)
)
BEGIN
/**
@@ -76416,7 +76732,7 @@ BEGIN
* Respeta el id inicial para el tipo propuesto.
*
* @param vSelf Id ticket
- * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original
+ * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original
* @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk)
*/
DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H';
@@ -76430,7 +76746,7 @@ BEGIN
SELECT itemPackingTypeFk
FROM tSaleGroup
WHERE itemPackingTypeFk IS NOT NULL
- ORDER BY (itemPackingTypeFk = vItemPackingTypeFk) DESC;
+ ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
@@ -86309,7 +86625,7 @@ USE `pbx`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `queueConf` AS select `q`.`name` AS `name`,`c`.`strategy` AS `strategy`,`c`.`timeout` AS `timeout`,`c`.`retry` AS `retry`,`c`.`weight` AS `weight`,`c`.`maxLen` AS `maxlen`,`c`.`ringInUse` AS `ringinuse` from (`queue` `q` join `queueConfig` `c` on(`q`.`config` = `c`.`id`)) */;
+/*!50001 VIEW `queueConf` AS select `q`.`name` AS `name`,`c`.`strategy` AS `strategy`,`c`.`timeout` AS `timeout`,`c`.`retry` AS `retry`,`c`.`weight` AS `weight`,`c`.`maxLen` AS `maxlen`,`c`.`ringInUse` AS `ringinuse` from (`queue` `q` join `queueMultiConfig` `c` on(`q`.`config` = `c`.`id`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -91039,4 +91355,4 @@ USE `vn2008`;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
--- Dump completed on 2024-07-23 8:19:18
+-- Dump completed on 2024-08-06 6:02:57
diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql
index 1b92f0d43..014bce729 100644
--- a/db/dump/.dump/triggers.sql
+++ b/db/dump/.dump/triggers.sql
@@ -6325,10 +6325,6 @@ BEGIN
SET NEW.userFk = account.myUser_getId();
END IF;
- IF (NEW.visible <> OLD.visible) THEN
- SET NEW.available = GREATEST(NEW.available + NEW.visible - OLD.visible, 0);
- END IF;
-
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -9224,13 +9220,16 @@ BEGIN
SET NEW.editorFk = account.myUser_getId();
IF NOT (NEW.routeFk <=> OLD.routeFk) THEN
- INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
- SELECT r.id
- FROM vn.route r
- WHERE r.isOk = FALSE
- AND r.id IN (OLD.routeFk,NEW.routeFk)
- AND r.created >= util.VN_CURDATE()
- GROUP BY r.id;
+ IF NEW.isSigned THEN
+ CALL util.throw('A signed ticket cannot be rerouted');
+ END IF;
+ INSERT IGNORE INTO routeRecalc(routeFk)
+ SELECT id
+ FROM `route`
+ WHERE NOT isOk
+ AND id IN (OLD.routeFk, NEW.routeFk)
+ AND created >= util.VN_CURDATE()
+ GROUP BY id;
END IF;
IF NOT (DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN
@@ -11143,4 +11142,4 @@ USE `vn2008`;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
--- Dump completed on 2024-07-23 8:19:41
+-- Dump completed on 2024-08-06 6:03:19
diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql
index 60c96abb4..6563292dd 100644
--- a/db/dump/fixtures.before.sql
+++ b/db/dump/fixtures.before.sql
@@ -1516,7 +1516,7 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed
(9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, ''),
(10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, '');
-INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleQuantity`, `saleInternalWaste`, `saleExternalWaste`)
+INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWasteQuantity`, `saleInternalWaste`, `saleExternalWaste`)
VALUES
('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 1, 1, '1062', '51', '56.20', '56.20'),
('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '35074', '687', '53.12', '89.69'),
diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql
index 3e189d2e6..20eee5d49 100644
--- a/db/routines/bs/procedures/waste_addSales.sql
+++ b/db/routines/bs/procedures/waste_addSales.sql
@@ -1,7 +1,7 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`()
BEGIN
- DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY;
+ DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY;
DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY;
CALL cache.last_buy_refresh(FALSE);
@@ -12,25 +12,22 @@ BEGIN
it.workerFk,
it.id,
s.itemFk,
- SUM(s.quantity),
- SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) `value`,
- SUM (
+ SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity),
+ SUM(IF(aw.`type`, s.quantity, 0)),
+ SUM(
IF(
aw.`type` = 'internal',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
0
)
- ) internalWaste,
- SUM (
+ ),
+ SUM(
IF(
aw.`type` = 'external',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
- IF(c.code = 'manaClaim',
- sc.value * s.quantity,
- 0
- )
+ 0
)
- ) externalWaste
+ )
FROM vn.sale s
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
@@ -41,10 +38,8 @@ BEGIN
JOIN cache.last_buy lb ON lb.item_id = i.id
AND lb.warehouse_id = w.id
JOIN vn.buy b ON b.id = lb.buy_id
- LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id
- LEFT JOIN vn.component c ON c.id = sc.componentFk
WHERE t.shipped BETWEEN vDateFrom AND vDateTo
AND w.isManaged
- GROUP BY it.id, i.id;
+ GROUP BY i.id;
END$$
DELIMITER ;
diff --git a/db/routines/cache/procedures/last_buy_refresh.sql b/db/routines/cache/procedures/last_buy_refresh.sql
index 49ef4ee5e..555ae0b8d 100644
--- a/db/routines/cache/procedures/last_buy_refresh.sql
+++ b/db/routines/cache/procedures/last_buy_refresh.sql
@@ -30,7 +30,7 @@ proc: BEGIN
SELECT inventoried INTO started FROM vn.config LIMIT 1;
SET ended = util.VN_CURDATE(); -- TIMESTAMPADD(DAY, -1, util.VN_CURDATE());
- CALL vn.buyUltimateFromInterval(NULL, started, ended);
+ CALL vn.buy_getUltimateFromInterval(NULL, NULL, started, ended);
DELETE FROM last_buy;
diff --git a/db/routines/hedera/procedures/order_confirmWithUser.sql b/db/routines/hedera/procedures/order_confirmWithUser.sql
index 9c932aaa1..2b033b704 100644
--- a/db/routines/hedera/procedures/order_confirmWithUser.sql
+++ b/db/routines/hedera/procedures/order_confirmWithUser.sql
@@ -1,59 +1,62 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_confirmWithUser`(vSelf INT, vUserId INT)
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_confirmWithUser`(
+ vSelf INT,
+ vUserFk INT
+)
BEGIN
/**
- * Confirms an order, creating each of its tickets on the corresponding
- * date, store and user.
+ * Confirms an order, creating each of its tickets
+ * on the corresponding date, store and user.
*
* @param vSelf The order identifier
* @param vUser The user identifier
*/
- DECLARE vOk BOOL;
- DECLARE vDone BOOL DEFAULT FALSE;
- DECLARE vWarehouse INT;
+ DECLARE vHasRows BOOL;
+ DECLARE vDone BOOL;
+ DECLARE vWarehouseFk INT;
DECLARE vShipment DATE;
- DECLARE vTicket INT;
+ DECLARE vShipmentDayEnd DATETIME;
+ DECLARE vTicketFk INT;
DECLARE vNotes VARCHAR(255);
- DECLARE vItem INT;
+ DECLARE vItemFk INT;
DECLARE vConcept VARCHAR(30);
DECLARE vAmount INT;
+ DECLARE vAvailable INT;
DECLARE vPrice DECIMAL(10,2);
- DECLARE vSale INT;
- DECLARE vRate INT;
- DECLARE vRowId INT;
+ DECLARE vSaleFk INT;
+ DECLARE vRowFk INT;
DECLARE vPriceFixed DECIMAL(10,2);
- 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 vCalc INT;
- DECLARE vIsLogifloraItem BOOL;
- DECLARE vOldQuantity INT;
- DECLARE vNewQuantity INT;
+ DECLARE vLanded DATE;
+ DECLARE vAddressFk INT;
+ DECLARE vClientFk INT;
+ DECLARE vCompanyFk INT;
+ DECLARE vAgencyModeFk INT;
+ DECLARE vCalcFk INT;
DECLARE vIsTaxDataChecked BOOL;
- DECLARE cDates CURSOR FOR
- SELECT zgs.shipped, r.warehouse_id
+ DECLARE vDates CURSOR FOR
+ SELECT zgs.shipped, r.warehouseFk
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 = vSelf AND r.amount != 0
- GROUP BY r.warehouse_id;
+ JOIN orderRow r ON r.orderFk = o.id
+ LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouseFk
+ WHERE o.id = vSelf
+ AND r.amount
+ GROUP BY r.warehouseFk;
- DECLARE cRows CURSOR FOR
- SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate, i.isFloramondo
- 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 = vSelf
+ DECLARE vRows CURSOR FOR
+ SELECT r.id,
+ r.itemFk,
+ i.name,
+ r.amount,
+ r.price
+ FROM orderRow r
+ JOIN vn.item i ON i.id = r.itemFk
+ WHERE r.amount
+ AND r.warehouseFk = vWarehouseFk
+ AND r.orderFk = vSelf
ORDER BY r.rate DESC;
- DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
@@ -62,26 +65,36 @@ BEGIN
END;
-- Carga los datos del pedido
- SELECT o.date_send, o.address_id, o.note, a.clientFk,
- o.company_id, o.agency_id, c.isTaxDataChecked
- INTO vDelivery, vAddress, vNotes, vClientId,
- vCompanyId, vAgencyModeId, vIsTaxDataChecked
- FROM hedera.`order` o
+ SELECT o.date_send,
+ o.address_id,
+ o.note,
+ a.clientFk,
+ o.company_id,
+ o.agency_id,
+ c.isTaxDataChecked
+ INTO vLanded,
+ vAddressFk,
+ vNotes,
+ vClientFk,
+ vCompanyFk,
+ vAgencyModeFk,
+ vIsTaxDataChecked
+ FROM `order` o
JOIN vn.address a ON a.id = o.address_id
JOIN vn.client c ON c.id = a.clientFk
WHERE o.id = vSelf;
-- Verifica si el cliente tiene los datos comprobados
IF NOT vIsTaxDataChecked THEN
- CALL util.throw ('clientNotVerified');
+ CALL util.throw('clientNotVerified');
END IF;
-- Carga las fechas de salida de cada almacen
- CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE);
+ CALL vn.zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, FALSE);
-- Trabajador que realiza la accion
- IF vUserId IS NULL THEN
- SELECT employeeFk INTO vUserId FROM orderConfig;
+ IF vUserFk IS NULL THEN
+ SELECT employeeFk INTO vUserFk FROM orderConfig;
END IF;
START TRANSACTION;
@@ -89,207 +102,188 @@ BEGIN
CALL order_checkEditable(vSelf);
-- Check order is not empty
+ SELECT COUNT(*) > 0 INTO vHasRows
+ FROM orderRow
+ WHERE orderFk = vSelf
+ AND amount > 0;
- SELECT COUNT(*) > 0 INTO vOk
- FROM order_row WHERE order_id = vSelf AND amount > 0;
-
- IF NOT vOk THEN
- CALL util.throw ('ORDER_EMPTY');
+ IF NOT vHasRows THEN
+ CALL util.throw('ORDER_EMPTY');
END IF;
-- Crea los tickets del pedido
-
- OPEN cDates;
-
- lDates:
- LOOP
- SET vTicket = NULL;
+ OPEN vDates;
+ lDates: LOOP
+ SET vTicketFk = NULL;
SET vDone = FALSE;
- FETCH cDates INTO vShipment, vWarehouse;
+ FETCH vDates INTO vShipment, vWarehouseFk;
IF vDone THEN
LEAVE lDates;
END IF;
- -- Busca un ticket existente que coincida con los parametros
- WITH tPrevia AS
- (SELECT DISTINCT s.ticketFk
+ SET vShipmentDayEnd = util.dayEnd(vShipment);
+
+ -- Busca un ticket libre disponible
+ WITH tPrevia AS (
+ SELECT DISTINCT s.ticketFk
FROM vn.sale s
JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN vn.ticket t ON t.id = s.ticketFk
- WHERE t.shipped BETWEEN vShipment AND util.dayend(vShipment)
- )
- SELECT t.id INTO vTicket
+ WHERE t.shipped BETWEEN vShipment AND vShipmentDayEnd
+ )
+ SELECT t.id INTO vTicketFk
FROM vn.ticket t
JOIN vn.alertLevel al ON al.code = 'FREE'
LEFT JOIN tPrevia tp ON tp.ticketFk = t.id
- LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id
- JOIN hedera.`order` o
- ON o.address_id = t.addressFk
- AND vWarehouse = t.warehouseFk
- AND o.date_send = t.landed
- AND DATE(t.shipped) = vShipment
+ LEFT JOIN vn.ticketState tls ON tls.ticketFk = t.id
+ JOIN hedera.`order` o ON o.address_id = t.addressFk
+ AND t.shipped BETWEEN vShipment AND vShipmentDayEnd
+ AND t.warehouseFk = vWarehouseFk
+ AND o.date_send = t.landed
WHERE o.id = vSelf
AND t.refFk IS NULL
AND tp.ticketFk IS NULL
AND (tls.alertLevel IS NULL OR tls.alertLevel = al.id)
LIMIT 1;
+ -- Comprobamos si hay un ticket de previa disponible
+ IF vTicketFk IS NULL THEN
+ WITH tItemPackingTypeOrder AS (
+ SELECT GROUP_CONCAT(
+ DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk
+ ) distinctItemPackingTypes,
+ o.address_id
+ FROM vn.item i
+ JOIN hedera.orderRow oro ON oro.itemFk = i.id
+ JOIN hedera.`order` o ON o.id = oro.orderFk
+ WHERE oro.orderFk = vSelf
+ ),
+ tItemPackingTypeTicket AS (
+ SELECT t.id,
+ GROUP_CONCAT(
+ DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk
+ ) distinctItemPackingTypes
+ FROM vn.ticket t
+ JOIN vn.ticketState tls ON tls.ticketFk = t.id
+ JOIN vn.alertLevel al ON al.id = tls.alertLevel
+ JOIN vn.sale s ON s.ticketFk = t.id
+ JOIN vn.item i ON i.id = s.itemFk
+ JOIN tItemPackingTypeOrder ipto
+ WHERE t.shipped BETWEEN vShipment AND vShipmentDayEnd
+ AND t.refFk IS NULL
+ AND t.warehouseFk = vWarehouseFk
+ AND t.addressFk = ipto.address_id
+ AND al.code = 'ON_PREVIOUS'
+ GROUP BY t.id
+ )
+ SELECT iptt.id INTO vTicketFk
+ FROM tItemPackingTypeTicket iptt
+ JOIN tItemPackingTypeOrder ipto
+ WHERE INSTR(iptt.distinctItemPackingTypes, ipto.distinctItemPackingTypes)
+ LIMIT 1;
+ END IF;
+
-- Crea el ticket en el caso de no existir uno adecuado
- IF vTicket IS NULL
- THEN
-
+ IF vTicketFk IS NULL THEN
SET vShipment = IFNULL(vShipment, util.VN_CURDATE());
-
CALL vn.ticket_add(
- vClientId,
+ vClientFk,
vShipment,
- vWarehouse,
- vCompanyId,
- vAddress,
- vAgencyModeId,
+ vWarehouseFk,
+ vCompanyFk,
+ vAddressFk,
+ vAgencyModeFk,
NULL,
- vDelivery,
- vUserId,
+ vLanded,
+ vUserFk,
TRUE,
- vTicket
+ vTicketFk
);
ELSE
INSERT INTO vn.ticketTracking
- SET ticketFk = vTicket,
- userFk = vUserId,
- stateFk = TICKET_FREE;
+ SET ticketFk = vTicketFk,
+ userFk = vUserFk,
+ stateFk = (SELECT id FROM vn.state WHERE code = 'FREE');
END IF;
INSERT IGNORE INTO vn.orderTicket
SET orderFk = vSelf,
- ticketFk = vTicket;
+ ticketFk = vTicketFk;
-- Añade las notas
-
- IF vNotes IS NOT NULL AND vNotes != ''
- THEN
- INSERT INTO vn.ticketObservation SET
- ticketFk = vTicket,
- observationTypeFk = 4 /* salesperson */ ,
+ IF vNotes IS NOT NULL AND vNotes <> '' THEN
+ INSERT INTO vn.ticketObservation
+ SET ticketFk = vTicketFk,
+ observationTypeFk = (SELECT id FROM vn.observationType WHERE code = 'salesPerson'),
`description` = vNotes
ON DUPLICATE KEY UPDATE
`description` = CONCAT(VALUES(`description`),'. ', `description`);
END IF;
-- Añade los movimientos y sus componentes
-
- OPEN cRows;
-
+ OPEN vRows;
lRows: LOOP
+ SET vSaleFk = NULL;
SET vDone = FALSE;
- FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate, vIsLogifloraItem;
+ FETCH vRows INTO vRowFk, vItemFk, vConcept, vAmount, vPrice;
IF vDone THEN
LEAVE lRows;
END IF;
- SET vSale = NULL;
-
- SELECT s.id, s.quantity INTO vSale, vOldQuantity
+ SELECT s.id INTO vSaleFk
FROM vn.sale s
- WHERE ticketFk = vTicket
+ WHERE ticketFk = vTicketFk
AND price = vPrice
- AND itemFk = vItem
+ AND itemFk = vItemFk
AND discount = 0
LIMIT 1;
- IF vSale THEN
+ IF vSaleFk THEN
UPDATE vn.sale
SET quantity = quantity + vAmount,
originalQuantity = quantity
- WHERE id = vSale;
-
- SELECT s.quantity INTO vNewQuantity
- FROM vn.sale s
- WHERE id = vSale;
+ WHERE id = vSaleFk;
ELSE
-- Obtiene el coste
SELECT SUM(rc.`price`) valueSum INTO vPriceFixed
FROM orderRowComponent rc
JOIN vn.component c ON c.id = rc.componentFk
- JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.isBase
- WHERE rc.rowFk = vRowId;
+ JOIN vn.componentType ct ON ct.id = c.typeFk
+ AND ct.isBase
+ WHERE rc.rowFk = vRowFk;
INSERT INTO vn.sale
- SET itemFk = vItem,
- ticketFk = vTicket,
+ SET itemFk = vItemFk,
+ ticketFk = vTicketFk,
concept = vConcept,
quantity = vAmount,
price = vPrice,
priceFixed = vPriceFixed,
isPriceFixed = TRUE;
- SET vSale = LAST_INSERT_ID();
+ SET vSaleFk = LAST_INSERT_ID();
- INSERT INTO vn.saleComponent
- (saleFk, componentFk, `value`)
- SELECT vSale, rc.componentFk, rc.price
+ INSERT INTO vn.saleComponent (saleFk, componentFk, `value`)
+ SELECT vSaleFk, rc.componentFk, rc.price
FROM orderRowComponent rc
JOIN vn.component c ON c.id = rc.componentFk
- WHERE rc.rowFk = vRowId
- GROUP BY vSale, rc.componentFk;
+ WHERE rc.rowFk = vRowFk
+ GROUP BY vSaleFk, rc.componentFk;
END IF;
- UPDATE order_row SET Id_Movimiento = vSale
- WHERE id = vRowId;
-
- -- Inserta en putOrder si la compra es de Floramondo
- IF vIsLogifloraItem THEN
- CALL cache.availableNoRaids_refresh(vCalc,FALSE,vWarehouse,vShipment);
-
- SET @available := 0;
-
- SELECT GREATEST(0,available) INTO @available
- FROM cache.availableNoRaids
- WHERE calc_id = vCalc
- AND item_id = vItem;
-
- UPDATE cache.availableNoRaids
- SET available = GREATEST(0,available - vAmount)
- WHERE item_id = vItem
- AND calc_id = vCalc;
-
- INSERT INTO edi.putOrder (
- deliveryInformationID,
- supplyResponseId,
- quantity ,
- EndUserPartyId,
- EndUserPartyGLN,
- FHAdminNumber,
- saleFk
- )
- SELECT di.ID,
- i.supplyResponseFk,
- CEIL((vAmount - @available)/ sr.NumberOfItemsPerCask),
- o.address_id ,
- vClientId,
- IFNULL(ca.fhAdminNumber, fhc.defaultAdminNumber),
- vSale
- FROM edi.deliveryInformation di
- JOIN vn.item i ON i.supplyResponseFk = di.supplyResponseID
- JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
- LEFT JOIN edi.clientFHAdminNumber ca ON ca.clientFk = vClientId
- JOIN edi.floraHollandConfig fhc
- JOIN hedera.`order` o ON o.id = vSelf
- WHERE i.id = vItem
- AND di.LatestOrderDateTime > util.VN_NOW()
- AND vAmount > @available
- LIMIT 1;
- END IF;
+ UPDATE orderRow
+ SET saleFk = vSaleFk
+ WHERE id = vRowFk;
END LOOP;
-
- CLOSE cRows;
+ CLOSE vRows;
END LOOP;
+ CLOSE vDates;
- CLOSE cDates;
-
- UPDATE `order` SET confirmed = TRUE, confirm_date = util.VN_NOW()
+ UPDATE `order`
+ SET confirmed = TRUE,
+ confirm_date = util.VN_NOW()
WHERE id = vSelf;
COMMIT;
diff --git a/db/routines/salix/triggers/ACL_afterDelete.sql b/db/routines/salix/triggers/ACL_afterDelete.sql
new file mode 100644
index 000000000..18689dfb0
--- /dev/null
+++ b/db/routines/salix/triggers/ACL_afterDelete.sql
@@ -0,0 +1,12 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `salix`.`ACL_afterDelete`
+ AFTER DELETE ON `ACL`
+ FOR EACH ROW
+BEGIN
+ INSERT INTO ACL
+ SET `action` = 'delete',
+ `changedModel` = 'Acl',
+ `changedModelId` = OLD.id,
+ `userFk` = account.myUser_getId();
+END$$
+DELIMITER ;
diff --git a/db/routines/salix/triggers/ACL_beforeInsert.sql b/db/routines/salix/triggers/ACL_beforeInsert.sql
new file mode 100644
index 000000000..94fb51ada
--- /dev/null
+++ b/db/routines/salix/triggers/ACL_beforeInsert.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `salix`.`ACL_beforeInsert`
+ BEFORE INSERT ON `ACL`
+ FOR EACH ROW
+BEGIN
+ SET NEW.editorFk = account.myUser_getId();
+END$$
+DELIMITER ;
diff --git a/db/routines/salix/triggers/ACL_beforeUpdate.sql b/db/routines/salix/triggers/ACL_beforeUpdate.sql
new file mode 100644
index 000000000..b214fc9f6
--- /dev/null
+++ b/db/routines/salix/triggers/ACL_beforeUpdate.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `salix`.`ACL_beforeUpdate`
+ BEFORE UPDATE ON `ACL`
+ FOR EACH ROW
+BEGIN
+ SET NEW.editorFk = account.myUser_getId();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/events/travel_setDelivered.sql b/db/routines/vn/events/travel_setDelivered.sql
new file mode 100644
index 000000000..769ee9d24
--- /dev/null
+++ b/db/routines/vn/events/travel_setDelivered.sql
@@ -0,0 +1,12 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`travel_setDelivered`
+ ON SCHEDULE EVERY 1 DAY
+ STARTS '2024-07-12 00:10:00.000'
+ ON COMPLETION PRESERVE
+ ENABLE
+DO BEGIN
+ UPDATE travel t
+ SET t.isDelivered = TRUE
+ WHERE t.shipped < util.VN_CURDATE();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/address_updateCoordinates.sql b/db/routines/vn/procedures/address_updateCoordinates.sql
index bdeb886df..9d3ec963a 100644
--- a/db/routines/vn/procedures/address_updateCoordinates.sql
+++ b/db/routines/vn/procedures/address_updateCoordinates.sql
@@ -1,8 +1,8 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_updateCoordinates`(
vTicketFk INT,
- vLongitude INT,
- vLatitude INT)
+ vLongitude DECIMAL(11,7),
+ vLatitude DECIMAL(11,7))
BEGIN
/**
* Actualiza las coordenadas de una dirección.
diff --git a/db/routines/vn/procedures/available_traslate.sql b/db/routines/vn/procedures/available_traslate.sql
index d33a8e10e..e4ba13d79 100644
--- a/db/routines/vn/procedures/available_traslate.sql
+++ b/db/routines/vn/procedures/available_traslate.sql
@@ -47,7 +47,7 @@ proc: BEGIN
-- Tabla con el ultimo dia de last_buy para cada producto
-- que hace un replace de la anterior.
- CALL buyUltimate(vWarehouseShipment, util.VN_CURDATE());
+ CALL buy_getUltimate (NULL, vWarehouseShipment, util.VN_CURDATE());
INSERT INTO tItemRange
SELECT t.itemFk, tr.landed
diff --git a/db/routines/vn/procedures/buyUltimate.sql b/db/routines/vn/procedures/buyUltimate.sql
index 98b16cbc0..e743b8c90 100644
--- a/db/routines/vn/procedures/buyUltimate.sql
+++ b/db/routines/vn/procedures/buyUltimate.sql
@@ -5,39 +5,14 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(
)
BEGIN
/**
- * Calcula las últimas compras realizadas hasta una fecha
+ * @deprecated Usar buy_getUltimate
+ * Calcula las últimas compras realizadas hasta una fecha.
*
+ * @param vItemFk Id del artículo
* @param vWarehouseFk Id del almacén
* @param vDated Compras hasta fecha
* @return tmp.buyUltimate
*/
- CALL cache.last_buy_refresh (FALSE);
-
- DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
- CREATE TEMPORARY TABLE tmp.buyUltimate
- (PRIMARY KEY (itemFk, warehouseFk),
- INDEX(itemFk))
- ENGINE = MEMORY
- SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing
- FROM cache.last_buy
- WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL;
-
- IF vDated >= util.VN_CURDATE() THEN
- CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated);
-
- REPLACE INTO tmp.buyUltimate
- SELECT itemFk, buyFk, warehouseFk, landed landing
- FROM tmp.buyUltimateFromInterval
- WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
- AND landed <= vDated
- AND NOT isIgnored;
-
- INSERT IGNORE INTO tmp.buyUltimate
- SELECT itemFk, buyFk, warehouseFk, landed landing
- FROM tmp.buyUltimateFromInterval
- WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
- AND landed > vDated
- ORDER BY isIgnored = FALSE DESC;
- END IF;
+ CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/buyUltimateFromInterval.sql b/db/routines/vn/procedures/buyUltimateFromInterval.sql
index 5879b58e1..acb6282de 100644
--- a/db/routines/vn/procedures/buyUltimateFromInterval.sql
+++ b/db/routines/vn/procedures/buyUltimateFromInterval.sql
@@ -6,6 +6,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInte
)
BEGIN
/**
+ * @deprecated Usar buy_getUltimateFromInterval
* Calcula las últimas compras realizadas
* desde un rango de fechas.
*
@@ -14,153 +15,6 @@ BEGIN
* @param vEnded Fecha fin
* @return tmp.buyUltimateFromInterval
*/
- IF vEnded IS NULL THEN
- SET vEnded = vStarted;
- END IF;
-
- IF vEnded < vStarted THEN
- SET vStarted = TIMESTAMPADD(MONTH, -1, vEnded);
- END IF;
-
- -- Item
- DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval;
- CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval
- (PRIMARY KEY (itemFk, warehouseFk),
- INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
- ENGINE = MEMORY
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vStarted AND vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.price2 > 0
- ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
-
-
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed > vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.price2 > 0
- AND NOT b.isIgnored
- ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
-
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vStarted AND vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.quantity = 0
- ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
-
- -- ItemOriginal
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- itemOriginalFk,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vStarted AND vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.price2 > 0
- AND NOT b.isIgnored
- AND b.quantity > 0
- AND itemOriginalFk
- ORDER BY t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed > vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.price2 > 0
- AND NOT b.isIgnored
- AND itemOriginalFk
- ORDER BY t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
-
- INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
- SELECT itemFk,
- warehouseFk,
- buyFk,
- landed,
- isIgnored
- FROM
- (SELECT b.itemFk,
- t.warehouseInFk warehouseFk,
- b.id buyFk,
- t.landed,
- b.isIgnored
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vStarted AND vEnded
- AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND b.quantity = 0
- AND itemOriginalFk
- ORDER BY t.landed DESC, b.id DESC
- LIMIT 10000000000000000000) sub
- GROUP BY itemFk, warehouseFk;
+ CALL vn.buy_getUltimateFromInterval(NULL, vWarehouseFk, vStarted, vEnded);
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_getUltimate.sql b/db/routines/vn/procedures/buy_getUltimate.sql
new file mode 100644
index 000000000..023e81774
--- /dev/null
+++ b/db/routines/vn/procedures/buy_getUltimate.sql
@@ -0,0 +1,47 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getUltimate`(
+ vItemFk INT,
+ vWarehouseFk SMALLINT,
+ vDated DATE
+)
+BEGIN
+/**
+ * Calcula las últimas compras realizadas hasta una fecha.
+ *
+ * @param vItemFk Id del artículo
+ * @param vWarehouseFk Id del almacén
+ * @param vDated Compras hasta fecha
+ * @return tmp.buyUltimate
+ */
+ CALL cache.last_buy_refresh(FALSE);
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.buyUltimate
+ (PRIMARY KEY (itemFk, warehouseFk),
+ INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing
+ FROM cache.last_buy
+ WHERE (warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL)
+ AND (item_id = vItemFk OR vItemFk IS NULL);
+
+ IF vDated >= util.VN_CURDATE() THEN
+ CALL buy_getUltimateFromInterval(vItemFk, vWarehouseFk, util.VN_CURDATE(), vDated);
+
+ REPLACE INTO tmp.buyUltimate
+ SELECT itemFk, buyFk, warehouseFk, landed landing
+ FROM tmp.buyUltimateFromInterval
+ WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
+ AND (itemFk = vItemFk OR vItemFk IS NULL)
+ AND landed <= vDated
+ AND NOT isIgnored;
+
+ INSERT IGNORE INTO tmp.buyUltimate
+ SELECT itemFk, buyFk, warehouseFk, landed landing
+ FROM tmp.buyUltimateFromInterval
+ WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
+ AND (itemFk = vItemFk OR vItemFk IS NULL)
+ AND landed > vDated
+ ORDER BY isIgnored = FALSE DESC;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_getUltimateFromInterval.sql b/db/routines/vn/procedures/buy_getUltimateFromInterval.sql
new file mode 100644
index 000000000..2115beb95
--- /dev/null
+++ b/db/routines/vn/procedures/buy_getUltimateFromInterval.sql
@@ -0,0 +1,175 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getUltimateFromInterval`(
+ vItemFk INT,
+ vWarehouseFk SMALLINT,
+ vStarted DATE,
+ vEnded DATE
+)
+BEGIN
+/**
+ * Calcula las últimas compras realizadas
+ * desde un rango de fechas.
+ *
+ * @param vItemFk Id del artículo
+ * @param vWarehouseFk Id del almacén si es NULL se actualizan todos
+ * @param vStarted Fecha inicial
+ * @param vEnded Fecha fin
+ * @return tmp.buyUltimateFromInterval
+ */
+ IF vEnded IS NULL THEN
+ SET vEnded = vStarted;
+ END IF;
+
+ IF vEnded < vStarted THEN
+ SET vStarted = vEnded - INTERVAL 1 MONTH;
+ END IF;
+
+ -- Item
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.buyUltimateFromInterval
+ (PRIMARY KEY (itemFk, warehouseFk),
+ INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.price2 > 0
+ ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed > vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.quantity = 0
+ ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+ -- ItemOriginal
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ itemOriginalFk,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ AND b.quantity > 0
+ AND itemOriginalFk
+ ORDER BY t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed > vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.price2 > 0
+ AND NOT b.isIgnored
+ AND itemOriginalFk
+ ORDER BY t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+
+ INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
+ SELECT itemFk,
+ warehouseFk,
+ buyFk,
+ landed,
+ isIgnored
+ FROM
+ (SELECT b.itemFk,
+ t.warehouseInFk warehouseFk,
+ b.id buyFk,
+ t.landed,
+ b.isIgnored
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE t.landed BETWEEN vStarted AND vEnded
+ AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
+ AND (b.itemFk = vItemFk OR vItemFk IS NULL)
+ AND b.quantity = 0
+ AND itemOriginalFk
+ ORDER BY t.landed DESC, b.id DESC
+ LIMIT 10000000000000000000) sub
+ GROUP BY itemFk, warehouseFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_updateGrouping.sql b/db/routines/vn/procedures/buy_updateGrouping.sql
index fb7adc0a3..e589fbd2a 100644
--- a/db/routines/vn/procedures/buy_updateGrouping.sql
+++ b/db/routines/vn/procedures/buy_updateGrouping.sql
@@ -1,5 +1,9 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_updateGrouping`(vWarehouseFk INT, vItemFk INT, vGrouping INT)
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_updateGrouping`(
+ vWarehouseFk INT,
+ vItemFk INT,
+ vGrouping INT
+)
BEGIN
/**
* Actualiza el grouping de las últimas compras de un artículo
@@ -8,9 +12,9 @@ BEGIN
* @param vItemFk Id del Artículo
* @param vGrouping Cantidad de grouping
*/
- CALL vn.buyUltimate(vWarehouseFk, util.VN_CURDATE());
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, util.VN_CURDATE());
- UPDATE vn.buy b
+ UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
SET b.`grouping` = vGrouping
WHERE bu.warehouseFk = vWarehouseFk
diff --git a/db/routines/vn/procedures/buy_updatePacking.sql b/db/routines/vn/procedures/buy_updatePacking.sql
index d86edc98f..0ee9d4c80 100644
--- a/db/routines/vn/procedures/buy_updatePacking.sql
+++ b/db/routines/vn/procedures/buy_updatePacking.sql
@@ -8,7 +8,7 @@ BEGIN
* @param vItemFk id del item
* @param vPacking packing a actualizar
*/
- CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, util.VN_CURDATE());
UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
diff --git a/db/routines/vn/procedures/catalog_calculate.sql b/db/routines/vn/procedures/catalog_calculate.sql
index 963e33507..2a0157881 100644
--- a/db/routines/vn/procedures/catalog_calculate.sql
+++ b/db/routines/vn/procedures/catalog_calculate.sql
@@ -29,7 +29,7 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, vShowExpiredZones);
+ CALL zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, vShowExpiredZones);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot(
@@ -72,9 +72,9 @@ BEGIN
LEAVE l;
END IF;
- CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped);
- CALL `cache`.availableNoRaids_refresh (vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped);
- CALL vn.buyUltimate(vWarehouseFk, vShipped);
+ CALL `cache`.available_refresh(vAvailableCalc, FALSE, vWarehouseFk, vShipped);
+ CALL `cache`.availableNoRaids_refresh(vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk)
SELECT vWarehouseFk,
@@ -86,17 +86,17 @@ BEGIN
LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
AND anr.calc_id = vAvailableNoRaidsCalc
JOIN tmp.item i ON i.itemFk = a.item_id
- JOIN vn.item it ON it.id = i.itemFk
- JOIN vn.`zone` z ON z.id = vZoneFk
+ JOIN item it ON it.id = i.itemFk
+ JOIN `zone` z ON z.id = vZoneFk
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed
- FROM vn.addressFilter af
+ FROM addressFilter af
JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
- FROM vn.address ad
- JOIN vn.province p ON p.id = ad.provinceFk
+ FROM address ad
+ JOIN province p ON p.id = ad.provinceFk
WHERE ad.id = vAddressFk
) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk)
AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk)
@@ -108,18 +108,18 @@ BEGIN
OR ISNULL(af.afterDated))
) sub ON sub.isVNHSupplier = v.isVNHSupplier
AND (sub.isEarlyBird = mp.isEarlyBird OR ISNULL(sub.isEarlyBird))
- JOIN vn.agencyMode am ON am.id = vAgencyModeFk
- JOIN vn.agency ag ON ag.id = am.agencyFk
- JOIN vn.itemType itt ON itt.id = it.typeFk
- JOIN vn.itemCategory itc on itc.id = itt.categoryFk
- JOIN vn.address ad ON ad.id = vAddressFk
- LEFT JOIN vn.clientItemType cit
+ JOIN agencyMode am ON am.id = vAgencyModeFk
+ JOIN agency ag ON ag.id = am.agencyFk
+ JOIN itemType itt ON itt.id = it.typeFk
+ JOIN itemCategory itc on itc.id = itt.categoryFk
+ JOIN address ad ON ad.id = vAddressFk
+ LEFT JOIN clientItemType cit
ON cit.clientFk = ad.clientFk
AND cit.itemTypeFk = itt.id
- LEFT JOIN vn.zoneItemType zit
+ LEFT JOIN zoneItemType zit
ON zit.zoneFk = vZoneFk
AND zit.itemTypeFk = itt.id
- LEFT JOIN vn.agencyModeItemType ait
+ LEFT JOIN agencyModeItemType ait
ON ait.agencyModeFk = vAgencyModeFk
AND ait.itemTypeFk = itt.id
WHERE a.calc_id = vAvailableCalc
@@ -133,7 +133,7 @@ BEGIN
DROP TEMPORARY TABLE tmp.buyUltimate;
- CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
+ CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
INSERT INTO tmp.ticketCalculateItem(
itemFk,
diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql
index 10c0714e5..4570de332 100644
--- a/db/routines/vn/procedures/duaInvoiceInBooking.sql
+++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql
@@ -12,6 +12,7 @@ BEGIN
DECLARE vInvoiceFk INT;
DECLARE vBookEntry INT;
DECLARE vFiscalYear INT;
+ DECLARE vIncorrectInvoiceInDueDay INT;
DECLARE vInvoicesIn CURSOR FOR
SELECT DISTINCT e.invoiceInFk
@@ -24,6 +25,19 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ SELECT GROUP_CONCAT(ii.id) INTO vIncorrectInvoiceInDueDay
+ FROM invoiceInDueDay iidd
+ JOIN invoiceIn ii ON iidd.invoiceInFk = ii.id
+ JOIN `entry` e ON e.invoiceInFk = ii.id
+ JOIN duaEntry de ON de.entryFk = e.id
+ JOIN invoiceInConfig iic
+ WHERE de.duaFk = vDuaFk
+ AND iidd.dueDated < util.VN_CURDATE() + INTERVAL iic.dueDateMarginDays DAY;
+
+ IF vIncorrectInvoiceInDueDay THEN
+ CALL util.throw(CONCAT('Incorrect due date, invoice: ', vIncorrectInvoiceInDueDay));
+ END IF;
+
UPDATE invoiceIn ii
JOIN entry e ON e.invoiceInFk = ii.id
JOIN duaEntry de ON de.entryFk = e.id
diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql
index 165c87dc7..5bf049b6e 100644
--- a/db/routines/vn/procedures/entry_getTransfer.sql
+++ b/db/routines/vn/procedures/entry_getTransfer.sql
@@ -97,7 +97,7 @@ BEGIN
FROM tmp.itemList;
END IF;
- CALL buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded);
+ CALL buy_getUltimateFromInterval(NULL, vWarehouseIn,vInventoryDate, vDateLanded);
CREATE OR REPLACE TEMPORARY TABLE tTransfer
ENGINE = MEMORY
diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql
index eb07c12b7..9f09ed5be 100644
--- a/db/routines/vn/procedures/entry_splitByShelving.sql
+++ b/db/routines/vn/procedures/entry_splitByShelving.sql
@@ -15,7 +15,7 @@ BEGIN
DECLARE cur CURSOR FOR
SELECT bb.id buyFk,
- FLOOR(ish.visible / ish.packing) ishStickers,
+ LEAST(bb.stickers, FLOOR(ish.visible / ish.packing)) ishStickers,
bb.stickers buyStickers
FROM itemShelving ish
JOIN (SELECT b.id, b.itemFk, b.stickers
@@ -23,7 +23,6 @@ BEGIN
WHERE b.entryFk = vFromEntryFk
ORDER BY b.stickers DESC
LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
- AND bb.stickers >= FLOOR(ish.visible / ish.packing)
WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
AND NOT ish.isSplit
GROUP BY ish.id;
@@ -110,7 +109,7 @@ BEGIN
UPDATE itemShelving
SET isSplit = TRUE
- WHERE shelvingFk = vShelvingFk;
+ WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci;
END LOOP;
CLOSE cur;
END$$
diff --git a/db/routines/vn/procedures/expeditionScan_Put.sql b/db/routines/vn/procedures/expeditionScan_Put.sql
index 9744a7cd7..cbc76d317 100644
--- a/db/routines/vn/procedures/expeditionScan_Put.sql
+++ b/db/routines/vn/procedures/expeditionScan_Put.sql
@@ -1,11 +1,18 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT)
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionScan_Put`(
+ vPalletFk INT,
+ vExpeditionFk INT
+)
BEGIN
-
- REPLACE vn.expeditionScan(expeditionFk, palletFk)
- VALUES(vExpeditionFk, vPalletFk);
-
- SELECT LAST_INSERT_ID() INTO vPalletFk;
-
+ IF NOT (SELECT TRUE FROM expedition WHERE id = vExpeditionFk LIMIT 1) THEN
+ CALL util.throw('Expedition not exists');
+ END IF;
+
+ IF NOT (SELECT TRUE FROM expeditionPallet WHERE id = vPalletFk LIMIT 1) THEN
+ CALL util.throw('Pallet not exists');
+ END IF;
+
+ REPLACE expeditionScan(expeditionFk, palletFk)
+ VALUES(vExpeditionFk, vPalletFk);
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/invoiceInDueDay_calculate.sql b/db/routines/vn/procedures/invoiceInDueDay_calculate.sql
index e51b5f64d..7929bee6f 100644
--- a/db/routines/vn/procedures/invoiceInDueDay_calculate.sql
+++ b/db/routines/vn/procedures/invoiceInDueDay_calculate.sql
@@ -1,5 +1,7 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInDueDay_calculate`(vInvoiceInFk INT)
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceInDueDay_calculate`(
+vInvoiceInFk INT
+)
BEGIN
/**
* Calcula los vctos. de una factura recibida
@@ -56,12 +58,13 @@ BEGIN
COUNT(DISTINCT(pdd.detail)) cont,
s.payDay,
ii.issued,
- DATE(ii.created) + INTERVAL 2 DAY created
+ DATE(ii.created) + INTERVAL iic.dueDateMarginDays DAY created
FROM invoiceIn ii
JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk
JOIN supplier s ON s.id = ii.supplierFk
- JOIN payDemDetail pdd ON pdd.id = s.payDemFk
+ JOIN payDemDetail pdd ON pdd.id = s.payDemFk
+ JOIN invoiceInConfig iic
WHERE ii.id = vInvoiceInFk
GROUP BY ii.id
)sub
diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql
index c728085b8..a5dd3a5f1 100644
--- a/db/routines/vn/procedures/invoiceIn_booking.sql
+++ b/db/routines/vn/procedures/invoiceIn_booking.sql
@@ -16,9 +16,11 @@ BEGIN
DECLARE vHasRepeatedTransactions BOOL;
SELECT TRUE INTO vHasRepeatedTransactions
- FROM invoiceInTax
- WHERE invoiceInFk = vSelf
- HAVING COUNT(DISTINCT transactionTypeSageFk) > 1
+ FROM invoiceInTax iit
+ JOIN invoiceIn ii ON ii.id = iit.invoiceInFk
+ WHERE ii.id = vSelf
+ AND ii.serial = 'E'
+ HAVING COUNT(DISTINCT iit.transactionTypeSageFk) > 1
LIMIT 1;
IF vHasRepeatedTransactions THEN
diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql
index 757f880f9..454ea877f 100644
--- a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql
+++ b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql
@@ -98,6 +98,7 @@ proc: BEGIN
itemShelvingFk,
saleFk,
quantity,
+ userFk,
isPicked)
SELECT vItemShelvingFk,
vSaleFk,
diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySaleGroup.sql b/db/routines/vn/procedures/itemShelvingSale_addBySaleGroup.sql
new file mode 100644
index 000000000..285b9f93f
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingSale_addBySaleGroup.sql
@@ -0,0 +1,46 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addBySaleGroup`(
+ vSaleGroupFk INT(11)
+)
+BEGIN
+/**
+ * Reserva cantidades con ubicaciones para el contenido de una preparación previa
+ * a través del saleGroup
+ *
+ * @param vSaleGroupFk Identificador de saleGroup
+ */
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vSaleFk INT;
+ DECLARE vSectorFk INT;
+ DECLARE vSales CURSOR FOR
+ SELECT s.id
+ FROM saleGroupDetail sgd
+ JOIN sale s ON sgd.saleFk = s.id
+ JOIN saleTracking str ON str.saleFk = s.id
+ JOIN `state` st ON st.id = str.stateFk
+ AND st.code = 'PREVIOUS_PREPARATION'
+ LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
+ WHERE sgd.saleGroupFk = vSaleGroupFk
+ AND str.workerFk = account.myUser_getId()
+ AND iss.id IS NULL;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ SELECT sectorFk INTO vSectorFk
+ FROM operator
+ WHERE workerFk = account.myUser_getId();
+
+ OPEN vSales;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vSales INTO vSaleFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk);
+ END LOOP;
+ CLOSE vSales;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/itemShelvingSale_reallocate.sql b/db/routines/vn/procedures/itemShelvingSale_reallocate.sql
index a60287caa..d5b89c373 100644
--- a/db/routines/vn/procedures/itemShelvingSale_reallocate.sql
+++ b/db/routines/vn/procedures/itemShelvingSale_reallocate.sql
@@ -1,55 +1,55 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reallocate`(
- vItemShelvingFk INT(10),
- vItemFk INT(10),
- vSectorFk INT
-)
-BEGIN
-/**
- * Elimina reservas de un itemShelving e intenta reservar en otra ubicación
- *
- * @param vItemShelvingFk Id itemShelving
- * @param vItemFk Id del artículo
- * @param vSectorFk Id del sector
- */
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
- START TRANSACTION;
-
- UPDATE itemShelving
- SET visible = 0,
- available = 0
- WHERE id = vItemShelvingFk
- AND itemFk = vItemFk;
-
- SELECT iss.id
- FROM itemShelvingSale iss
- JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- WHERE iss.itemShelvingFk = vItemShelvingFk
- AND iss.itemFk = vItemFk
- AND NOT iss.isPicked
- FOR UPDATE;
-
- INSERT INTO itemShelvingSaleReserve (saleFk, vSectorFk)
- SELECT DISTINCT iss.saleFk
- FROM itemShelvingSale iss
- JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- WHERE iss.itemShelvingFk = vItemShelvingFk
- AND ish.itemFk = vItemFk
- AND NOT iss.isPicked;
-
- DELETE iss
- FROM itemShelvingSale iss
- JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- WHERE iss.itemShelvingFk = vItemShelvingFk
- AND ish.itemFk = vItemFk
- AND NOT iss.isPicked;
- COMMIT;
-
- CALL itemShelvingSale_doReserve();
-END$$
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reallocate`(
+ vItemShelvingFk INT(10),
+ vItemFk INT(10),
+ vSectorFk INT
+)
+BEGIN
+/**
+ * Elimina reservas de un itemShelving e intenta reservar en otra ubicación
+ *
+ * @param vItemShelvingFk Id itemShelving
+ * @param vItemFk Id del artículo
+ * @param vSectorFk Id del sector
+ */
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ UPDATE itemShelving
+ SET visible = 0,
+ available = 0
+ WHERE id = vItemShelvingFk
+ AND itemFk = vItemFk;
+
+ SELECT iss.id
+ FROM itemShelvingSale iss
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ WHERE iss.itemShelvingFk = vItemShelvingFk
+ AND ish.itemFk = vItemFk
+ AND NOT iss.isPicked
+ FOR UPDATE;
+
+ INSERT INTO itemShelvingSaleReserve (saleFk, sectorFk)
+ SELECT DISTINCT iss.saleFk, vSectorFk
+ FROM itemShelvingSale iss
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ WHERE iss.itemShelvingFk = vItemShelvingFk
+ AND ish.itemFk = vItemFk
+ AND NOT iss.isPicked;
+
+ DELETE iss
+ FROM itemShelvingSale iss
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ WHERE iss.itemShelvingFk = vItemShelvingFk
+ AND ish.itemFk = vItemFk
+ AND NOT iss.isPicked;
+ COMMIT;
+
+ CALL itemShelvingSale_doReserve();
+END$$
DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql
index 30abefec8..9d21e6a6f 100644
--- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql
+++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql
@@ -103,7 +103,7 @@ BEGIN
COMMIT;
IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN
- INSERT INTO itemShelvingSaleReserve (saleFk, vSectorFk)
+ INSERT INTO itemShelvingSaleReserve (saleFk, sectorFk)
SELECT vSaleFk, vSectorFk;
CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk, vSectorFk);
END IF;
diff --git a/db/routines/vn/procedures/itemShelving_addByClaim.sql b/db/routines/vn/procedures/itemShelving_addByClaim.sql
index 851162952..4ff2955c7 100644
--- a/db/routines/vn/procedures/itemShelving_addByClaim.sql
+++ b/db/routines/vn/procedures/itemShelving_addByClaim.sql
@@ -15,7 +15,7 @@ BEGIN
JOIN ticket t ON t.id = c.ticketFk
WHERE c.id = vClaimFk;
- CALL buyUltimate (vWarehouseFk, util.VN_CURDATE());
+ CALL buy_getUltimate(NULL, vWarehouseFk, util.VN_CURDATE());
INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible)
SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible
diff --git a/db/routines/vn/procedures/itemShelving_get.sql b/db/routines/vn/procedures/itemShelving_get.sql
index 1be762f09..d42446b06 100644
--- a/db/routines/vn/procedures/itemShelving_get.sql
+++ b/db/routines/vn/procedures/itemShelving_get.sql
@@ -16,7 +16,8 @@ BEGIN
ish.id,
s.priority,
ish.isChecked,
- ic.url
+ ic.url,
+ ish.available
FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk
JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci
diff --git a/db/routines/vn/procedures/itemShelving_getItemDetails.sql b/db/routines/vn/procedures/itemShelving_getItemDetails.sql
index c01bc348c..b097c2d17 100644
--- a/db/routines/vn/procedures/itemShelving_getItemDetails.sql
+++ b/db/routines/vn/procedures/itemShelving_getItemDetails.sql
@@ -23,7 +23,7 @@ BEGIN
FROM operator
WHERE workerFk = account.myUser_getId();
- CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
+ CALL buy_getUltimate(vBarcodeItem, vWarehouseFk, util.VN_CURDATE());
SELECT buyFk INTO vBuyFk
FROM tmp.buyUltimate
diff --git a/db/routines/vn/procedures/item_devalueA2.sql b/db/routines/vn/procedures/item_devalueA2.sql
index 5b03fc872..5b19b1522 100644
--- a/db/routines/vn/procedures/item_devalueA2.sql
+++ b/db/routines/vn/procedures/item_devalueA2.sql
@@ -93,7 +93,7 @@ BEGIN
ORDER BY created DESC
LIMIT 1;
- CALL buyUltimate(vWarehouseFk, vCurdate);
+ CALL buy_getUltimate(vSelf, vWarehouseFk, vCurdate);
SELECT b.entryFk, bu.buyFk,IFNULL(b.buyingValue, 0) INTO vLastEntryFk, vLastBuyFk, vBuyingValueOriginal
FROM tmp.buyUltimate bu
diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql
index 0de59b478..3a594c81c 100644
--- a/db/routines/vn/procedures/item_getBalance.sql
+++ b/db/routines/vn/procedures/item_getBalance.sql
@@ -240,7 +240,7 @@ BEGIN
NULL reference,
NULL entityType,
NULL entityId,
- 'Inventario calculado',
+ 'Inventario calculado' entityName,
@a invalue,
NULL `out`,
@a balance,
diff --git a/db/routines/vn/procedures/item_getInfo.sql b/db/routines/vn/procedures/item_getInfo.sql
index 50ab880a0..5cd4fb31e 100644
--- a/db/routines/vn/procedures/item_getInfo.sql
+++ b/db/routines/vn/procedures/item_getInfo.sql
@@ -1,5 +1,8 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getInfo`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT)
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getInfo`(
+ `vBarcode` VARCHAR(22),
+ `vWarehouseFk` INT
+)
BEGIN
/**
* Devuelve información relativa al item correspondiente del vBarcode pasado
@@ -11,12 +14,14 @@ BEGIN
DECLARE vCacheAvailableFk INT;
DECLARE vVisibleItemShelving INT;
DECLARE vItemFk INT;
+ DECLARE vDated DATE;
+
+ SELECT barcodeToItem(vBarcode), util.VN_CURDATE() INTO vItemFk, vDated;
CALL cache.visible_refresh(vCacheVisibleFk, FALSE, vWarehouseFk);
- CALL cache.available_refresh(vCacheAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
- CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
-
- SELECT barcodeToItem(vBarcode) INTO vItemFk;
+ CALL cache.available_refresh(vCacheAvailableFk, FALSE, vWarehouseFk, vDated);
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, vDated);
+
SELECT SUM(visible) INTO vVisibleItemShelving
FROM itemShelvingStock
WHERE itemFk = vItemFk
diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql
index a3ebedb12..1decf881d 100644
--- a/db/routines/vn/procedures/item_getMinacum.sql
+++ b/db/routines/vn/procedures/item_getMinacum.sql
@@ -1,37 +1,40 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getMinacum`(IN vWarehouseFk TINYINT, IN vDatedFrom DATETIME, IN vRange INT, IN vItemFk INT)
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getMinacum`(
+ vWarehouseFk TINYINT,
+ vDated DATE,
+ vRange INT,
+ vItemFk INT
+)
BEGIN
/**
- * Cálculo del mínimo acumulado, para un item/almacén especificado, en caso de
- * NULL para todo.
+ * Cálculo del mínimo acumulado, para un item/almacén
+ * especificado, en caso de NULL para todos.
*
- * @param vWarehouseFk -> warehouseFk
- * @param vDatedFrom -> fecha inicio
- * @param vRange -> número de días a considerar
- * @param vItemFk -> Identificador de item
+ * @param vWarehouseFk Id warehouse
+ * @param vDated Fecha inicio
+ * @param vRange Número de días a considerar
+ * @param vItemFk Id de artículo
* @return tmp.itemMinacum
*/
- DECLARE vDatedTo DATETIME;
+ DECLARE vDatedTo DATETIME DEFAULT util.dayEnd(vDated + INTERVAL vRange DAY);
- SET vDatedFrom = TIMESTAMP(DATE(vDatedFrom), '00:00:00');
- SET vDatedTo = TIMESTAMP(TIMESTAMPADD(DAY, vRange, vDatedFrom), '23:59:59');
-
- DROP TEMPORARY TABLE IF EXISTS tmp.itemCalc;
- CREATE TEMPORARY TABLE tmp.itemCalc
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
SELECT sub.itemFk,
sub.dated,
CAST(SUM(sub.quantity) AS SIGNED) quantity,
sub.warehouseFk
- FROM (SELECT s.itemFk,
+ FROM (
+ SELECT s.itemFk,
DATE(t.shipped) dated,
-s.quantity quantity,
t.warehouseFk
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
- WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ WHERE t.shipped BETWEEN vDated AND vDatedTo
AND t.warehouseFk
- AND s.quantity != 0
+ AND s.quantity <> 0
AND (vItemFk IS NULL OR s.itemFk = vItemFk)
AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk)
UNION ALL
@@ -42,10 +45,10 @@ BEGIN
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
- WHERE t.landed BETWEEN vDatedFrom AND vDatedTo
+ WHERE t.landed BETWEEN vDated AND vDatedTo
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
- AND !e.isExcludedFromAvailable
- AND b.quantity != 0
+ AND NOT e.isExcludedFromAvailable
+ AND b.quantity <> 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk)
UNION ALL
SELECT b.itemFk,
@@ -55,28 +58,45 @@ BEGIN
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
- WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
+ WHERE t.shipped BETWEEN vDated AND vDatedTo
AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk)
- AND !e.isExcludedFromAvailable
- AND b.quantity != 0
+ AND NOT e.isExcludedFromAvailable
+ AND b.quantity <> 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk)
- AND !e.isRaid
+ AND NOT e.isRaid
+ UNION ALL
+ SELECT r.itemFk,
+ r.shipment,
+ -r.amount,
+ r.warehouseFk
+ FROM hedera.orderRow r
+ JOIN hedera.`order` o ON o.id = r.orderFk
+ JOIN client c ON c.id = o.customer_id
+ WHERE r.shipment BETWEEN vDated AND vDatedTo
+ AND (vWarehouseFk IS NULL OR r.warehouseFk = vWarehouseFk)
+ AND r.created >= (
+ SELECT util.VN_NOW() - INTERVAL TIME_TO_SEC(reserveTime) SECOND
+ FROM hedera.orderConfig
+ )
+ AND NOT o.confirmed
+ AND (vItemFk IS NULL OR r.itemFk = vItemFk)
+ AND r.amount <> 0
) sub
GROUP BY sub.itemFk, sub.warehouseFk, sub.dated;
- CALL item_getAtp(vDatedFrom);
- DROP TEMPORARY TABLE tmp.itemCalc;
+ CALL item_getAtp(vDated);
- DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum;
- CREATE TEMPORARY TABLE tmp.itemMinacum
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemMinacum
(INDEX(itemFk))
ENGINE = MEMORY
- SELECT i.itemFk,
- i.warehouseFk,
- i.quantity amount
- FROM tmp.itemAtp i
- HAVING amount != 0;
+ SELECT itemFk,
+ warehouseFk,
+ quantity amount
+ FROM tmp.itemAtp
+ WHERE quantity <> 0;
- DROP TEMPORARY TABLE tmp.itemAtp;
+ DROP TEMPORARY TABLE
+ tmp.itemAtp,
+ tmp.itemCalc;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/item_multipleBuy.sql b/db/routines/vn/procedures/item_multipleBuy.sql
index ba49f8d36..0a08f5015 100644
--- a/db/routines/vn/procedures/item_multipleBuy.sql
+++ b/db/routines/vn/procedures/item_multipleBuy.sql
@@ -13,7 +13,7 @@ BEGIN
*/
ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT;
- CALL buyUltimate(vWarehouseFk, vDate);
+ CALL buy_getUltimate (NULL, vWarehouseFk, vDate);
CREATE OR REPLACE TEMPORARY TABLE tmp
(KEY (itemFk))
diff --git a/db/routines/vn/procedures/item_valuateInventory.sql b/db/routines/vn/procedures/item_valuateInventory.sql
index d1d0573a3..5f3131c9f 100644
--- a/db/routines/vn/procedures/item_valuateInventory.sql
+++ b/db/routines/vn/procedures/item_valuateInventory.sql
@@ -204,7 +204,7 @@ BEGIN
AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity);
- CALL buyUltimate(NULL, vDateDayEnd);
+ CALL buy_getUltimate (NULL, NULL, vDateDayEnd);
DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity;
diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql
index 6cd584c6e..99fb92cc8 100644
--- a/db/routines/vn/procedures/multipleInventory.sql
+++ b/db/routines/vn/procedures/multipleInventory.sql
@@ -75,13 +75,6 @@ proc: BEGIN
) sub
GROUP BY itemFk;
- UPDATE tmp.itemInventory ai
- JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id
- SET ai.inventory = iic.quantity,
- ai.visible = iic.quantity,
- ai.avalaible = iic.quantity,
- ai.sd = iic.quantity;
-
-- Cálculo del visible
CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
@@ -93,8 +86,12 @@ proc: BEGIN
WHERE calc_id = vCalcFk;
UPDATE tmp.itemInventory it
- JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id
- SET it.visible = it.visible + ivc.visible;
+ LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id
+ LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id
+ SET it.inventory = iic.quantity,
+ it.visible = ivc.visible,
+ it.avalaible = iic.quantity,
+ it.sd = iic.quantity;
-- Calculo del disponible
CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
@@ -142,31 +139,35 @@ proc: BEGIN
CALL item_getAtp(vDate);
CALL travel_upcomingArrivals(vWarehouseFk, vDate);
- UPDATE tmp.itemInventory ai
- JOIN (
- SELECT it.itemFk,
- SUM(it.quantity) quantity,
- im.quantity minQuantity
- FROM tmp.itemCalc it
- JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
- JOIN item i ON i.id = it.itemFk
- LEFT JOIN origin o ON o.id = i.originFk
- LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
- WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
- t.landing,
- vDateToTomorrow)
- GROUP BY it.itemFk
- ) sub ON sub.itemFk = ai.id
- SET ai.avalaible = IF(sub.minQuantity > 0,
- ai.avalaible,
- ai.avalaible + sub.minQuantity),
- ai.sd = ai.inventory + sub.quantity;
+ CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT it.itemFk,
+ SUM(it.quantity) quantity,
+ im.quantity minQuantity
+ FROM tmp.itemCalc it
+ JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
+ JOIN item i ON i.id = it.itemFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
+ WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
+ t.landing,
+ vDateToTomorrow)
+ GROUP BY it.itemFk;
+
+ UPDATE tmp.itemInventory it
+ JOIN tItemAvailableCalc iac ON iac.itemFk = it.id
+ SET it.avalaible = IF(iac.minQuantity > 0,
+ it.avalaible,
+ it.avalaible + iac.minQuantity),
+ it.sd = it.inventory + iac.quantity;
DROP TEMPORARY TABLE
tmp.itemTravel,
tmp.itemCalc,
tmp.itemAtp,
tItemInventoryCalc,
- tItemVisibleCalc;
+ tItemVisibleCalc,
+ tItemAvailableCalc;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql
index dad46393d..af6d929d7 100644
--- a/db/routines/vn/procedures/productionControl.sql
+++ b/db/routines/vn/procedures/productionControl.sql
@@ -174,27 +174,30 @@ proc: BEGIN
WHERE NOT `lines`;
-- Lineas por linea de encajado
+ CREATE OR REPLACE TEMPORARY TABLE tItemPackingType
+ (PRIMARY KEY(ticketFk))
+ ENGINE = MEMORY
+ SELECT ticketFk,
+ SUM(sub.H) H,
+ SUM(sub.V) V,
+ SUM(sub.N) N
+ FROM (
+ SELECT t.ticketFk,
+ SUM(i.itemPackingTypeFk = 'H') H,
+ SUM(i.itemPackingTypeFk = 'V') V,
+ SUM(i.itemPackingTypeFk IS NULL) N
+ FROM tmp.productionTicket t
+ JOIN sale s ON s.ticketFk = t.ticketFk
+ JOIN item i ON i.id = s.itemFk
+ GROUP BY t.ticketFk, i.itemPackingTypeFk
+ ) sub
+ GROUP BY ticketFk;
+
UPDATE tmp.productionBuffer pb
- JOIN (
- SELECT ticketFk,
- SUM(sub.H) H,
- SUM(sub.V) V,
- SUM(sub.N) N
- FROM (
- SELECT t.ticketFk,
- SUM(i.itemPackingTypeFk = 'H') H,
- SUM(i.itemPackingTypeFk = 'V') V,
- SUM(i.itemPackingTypeFk IS NULL) N
- FROM tmp.productionTicket t
- JOIN sale s ON s.ticketFk = t.ticketFk
- JOIN item i ON i.id = s.itemFk
- GROUP BY t.ticketFk, i.itemPackingTypeFk
- ) sub
- GROUP BY ticketFk
- ) sub2 ON sub2.ticketFk = pb.ticketFk
- SET pb.H = sub2.H,
- pb.V = sub2.V,
- pb.N = sub2.N;
+ JOIN tItemPackingType ti ON ti.ticketFk = pb.ticketFk
+ SET pb.H = ti.H,
+ pb.V = ti.V,
+ pb.N = ti.N;
-- Colecciones segun tipo de encajado
UPDATE tmp.productionBuffer pb
@@ -273,6 +276,7 @@ proc: BEGIN
tmp.risk,
tmp.ticket_problems,
tmp.ticketWithPrevia,
- tItemShelvingStock;
+ tItemShelvingStock,
+ tItemPackingType;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/saleGroup_setParking.sql b/db/routines/vn/procedures/saleGroup_setParking.sql
index 551ca6386..fffe5e154 100644
--- a/db/routines/vn/procedures/saleGroup_setParking.sql
+++ b/db/routines/vn/procedures/saleGroup_setParking.sql
@@ -10,15 +10,10 @@ BEGIN
* @param vSaleGroupFk id de la preparación previa
* @param vParkingFk id del parking
*/
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- RESIGNAL;
- END;
-
UPDATE saleGroup sg
SET sg.parkingFk = vParkingFk
- WHERE sg.id = vSaleGroupFk
- AND sg.created >= util.VN_CURDATE() - INTERVAL 1 WEEK;
+ WHERE sg.id = vSaleGroupFk
+ AND sg.created >= util.VN_CURDATE() - INTERVAL 1 WEEK;
CALL ticket_setNextState(ticket_get(vSaleGroupFk));
END$$
diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql
index ba4ff5857..c881bcf92 100644
--- a/db/routines/vn/procedures/sale_getProblems.sql
+++ b/db/routines/vn/procedures/sale_getProblems.sql
@@ -13,7 +13,7 @@ BEGIN
DECLARE vAvailableCache INT;
DECLARE vVisibleCache INT;
DECLARE vDone BOOL;
- DECLARE vComponentCount INT;
+ DECLARE vRequiredComponent INT;
DECLARE vCursor CURSOR FOR
SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), DATE(tt.shipped))
@@ -54,7 +54,7 @@ BEGIN
SELECT ticketFk, clientFk
FROM tmp.sale_getProblems;
- SELECT COUNT(*) INTO vComponentCount
+ SELECT COUNT(*) INTO vRequiredComponent
FROM component
WHERE isRequired;
@@ -96,20 +96,18 @@ BEGIN
-- Faltan componentes
INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk)
- SELECT ticketFk, (vComponentCount > nComp) hasComponentLack, saleFk
- FROM (
- SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk
- FROM tmp.ticket_list tl
- JOIN sale s ON s.ticketFk = tl.ticketFk
- LEFT JOIN saleComponent sc ON sc.saleFk = s.id
- LEFT JOIN component c ON c.id = sc.componentFk AND c.isRequired
- JOIN ticket t ON t.id = tl.ticketFk
- JOIN agencyMode am ON am.id = t.agencyModeFk
- JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
- WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
- AND s.quantity > 0
- GROUP BY s.id
- ) sub
+ SELECT t.id, COUNT(c.id) < vRequiredComponent hasComponentLack, s.id
+ FROM tmp.ticket_list tl
+ JOIN ticket t ON t.id = tl.ticketFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN agencyMode am ON am.id = t.agencyModeFk
+ JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ LEFT JOIN saleComponent sc ON sc.saleFk = s.id
+ LEFT JOIN component c ON c.id = sc.componentFk
+ AND c.isRequired
+ WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
+ AND s.quantity > 0
+ GROUP BY s.id
HAVING hasComponentLack;
-- Cliente congelado
@@ -276,7 +274,7 @@ BEGIN
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
-- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra
- CALL buyUltimate(vWarehouseFk, vDate);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vDate);
INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT ticketFk, problem ,saleFk
FROM (
diff --git a/db/routines/vn/procedures/sale_recalcComponent.sql b/db/routines/vn/procedures/sale_recalcComponent.sql
index 54297571a..f3c188404 100644
--- a/db/routines/vn/procedures/sale_recalcComponent.sql
+++ b/db/routines/vn/procedures/sale_recalcComponent.sql
@@ -78,7 +78,7 @@ proc: BEGIN
DROP TEMPORARY TABLE tmp.zoneGetLanded;
-- rellena la tabla buyUltimate con la ultima compra
- CALL buyUltimate (vWarehouseFk, vShipped);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY
diff --git a/db/routines/vn/procedures/sale_replaceItem.sql b/db/routines/vn/procedures/sale_replaceItem.sql
index a4aefc088..573d5b488 100644
--- a/db/routines/vn/procedures/sale_replaceItem.sql
+++ b/db/routines/vn/procedures/sale_replaceItem.sql
@@ -53,7 +53,7 @@ BEGIN
JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSaleFk;
- CALL buyUltimate(vWarehouseFk, vDate);
+ CALL buy_getUltimate(vNewItemFk, vWarehouseFk, vDate);
SELECT `grouping`, groupingMode, packing
INTO vGrouping,vGroupingMode,vPacking
@@ -61,6 +61,8 @@ BEGIN
JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk
WHERE tmp.itemFk = vNewItemFk AND tmp.WarehouseFk = vWarehouseFk;
+ DROP TEMPORARY TABLE tmp.buyUltimate;
+
IF vGroupingMode = 'packing' AND vPacking > 0 THEN
SET vRoundQuantity = vPacking;
END IF;
diff --git a/db/routines/vn/procedures/sale_setProblem.sql b/db/routines/vn/procedures/sale_setProblem.sql
index b0870089f..b343c0b8c 100644
--- a/db/routines/vn/procedures/sale_setProblem.sql
+++ b/db/routines/vn/procedures/sale_setProblem.sql
@@ -11,24 +11,29 @@ BEGIN
*/
DECLARE vSaleFk INT;
DECLARE vHasProblem INT;
+ DECLARE vIsProblemCalcNeeded BOOL;
DECLARE vDone BOOL;
- DECLARE vSaleList CURSOR FOR SELECT saleFk, hasProblem FROM tmp.sale;
+ DECLARE vSaleList CURSOR FOR
+ SELECT saleFk, hasProblem, isProblemCalcNeeded
+ FROM tmp.sale;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vSaleList;
l: LOOP
SET vDone = FALSE;
- FETCH vSaleList INTO vSaleFk, vHasProblem;
+ FETCH vSaleList INTO vSaleFk, vHasProblem, vIsProblemCalcNeeded;
IF vDone THEN
LEAVE l;
END IF;
UPDATE sale
- SET problem = CONCAT(
- IF(vHasProblem,
- CONCAT(problem, ',', vProblemCode),
- REPLACE(problem, vProblemCode , '')))
+ SET problem = IF (vIsProblemCalcNeeded,
+ CONCAT(
+ IF(vHasProblem,
+ CONCAT(problem, ',', vProblemCode),
+ REPLACE(problem, vProblemCode , ''))),
+ NULL)
WHERE id = vSaleFk;
END LOOP;
CLOSE vSaleList;
diff --git a/db/routines/vn/procedures/sale_setProblemComponentLack.sql b/db/routines/vn/procedures/sale_setProblemComponentLack.sql
index aa5f5f1be..23eb77c2e 100644
--- a/db/routines/vn/procedures/sale_setProblemComponentLack.sql
+++ b/db/routines/vn/procedures/sale_setProblemComponentLack.sql
@@ -14,7 +14,7 @@ BEGIN
ENGINE = MEMORY
SELECT vSelf saleFk,
sale_hasComponentLack(vSelf) hasProblem,
- ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded
+ (ticket_isProblemCalcNeeded(ticketFk) AND quantity > 0) isProblemCalcNeeded
FROM sale
WHERE id = vSelf;
diff --git a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql
index 2ee49b656..cdf28ac09 100644
--- a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql
+++ b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql
@@ -14,9 +14,9 @@ BEGIN
ENGINE = MEMORY
SELECT saleFk,
sale_hasComponentLack(saleFk) hasProblem,
- ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded
+ (ticket_isProblemCalcNeeded(ticketFk) AND quantity > 0) isProblemCalcNeeded
FROM (
- SELECT s.id saleFk, s.ticketFk
+ SELECT s.id saleFk, s.ticketFk, s.quantity
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
LEFT JOIN saleComponent sc ON sc.saleFk = s.id
diff --git a/db/routines/vn/procedures/sale_setProblemRounding.sql b/db/routines/vn/procedures/sale_setProblemRounding.sql
index f58d00799..894749c7b 100644
--- a/db/routines/vn/procedures/sale_setProblemRounding.sql
+++ b/db/routines/vn/procedures/sale_setProblemRounding.sql
@@ -19,7 +19,7 @@ BEGIN
JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSelf;
- CALL buyUltimate(vWarehouseFk, vShipped);
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
SELECT vSelf saleFk,
diff --git a/db/routines/vn/procedures/setParking.sql b/db/routines/vn/procedures/setParking.sql
index 1aa4f920a..b3edf350d 100644
--- a/db/routines/vn/procedures/setParking.sql
+++ b/db/routines/vn/procedures/setParking.sql
@@ -13,12 +13,6 @@ BEGIN
DECLARE vParkingFk INT;
DECLARE vLastWeek DATE;
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
SET vParkingCode = REPLACE(vParkingCode, ' ', '');
SELECT id INTO vParkingFk
@@ -29,8 +23,6 @@ BEGIN
CALL util.throw('parkingNotExist');
END IF;
- START TRANSACTION;
-
SET vLastWeek = util.VN_CURDATE() - INTERVAL 1 WEEK;
-- Comprobamos si es una prep. previa, ticket, colección o shelving
@@ -45,7 +37,5 @@ BEGIN
ELSE
CALL util.throw('paramNotExist');
END IF;
-
- COMMIT;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/shelving_setParking.sql b/db/routines/vn/procedures/shelving_setParking.sql
index 0ff07ef5d..3e8717197 100644
--- a/db/routines/vn/procedures/shelving_setParking.sql
+++ b/db/routines/vn/procedures/shelving_setParking.sql
@@ -1,20 +1,20 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelving_setParking`(IN `vShelvingCode` VARCHAR(8), IN `vParkingFk` INT)
-proc: BEGIN
+BEGIN
/**
* Aparca una matrícula en un parking
*
* @param vShelvingCode code de la matrícula
* @param vParkingFk id del parking
*/
- INSERT INTO vn.shelvingLog (originFk, userFk, action , description,changedModel,changedModelId)
+ INSERT INTO shelvingLog (originFk, userFk, action , description,changedModel,changedModelId)
SELECT s.id, account.myUser_getId(), 'update', CONCAT("Cambio parking ",vShelvingCode," de ", p.code," a ", pNew.code),'Shelving',s.id
FROM parking p
JOIN shelving s ON s.parkingFk = p.id
JOIN parking pNew ON pNew.id = vParkingFk
WHERE s.code = vShelvingCode COLLATE utf8_unicode_ci;
- UPDATE vn.shelving
+ UPDATE shelving
SET parkingFk = vParkingFk,
parked = util.VN_NOW(),
isPrinted = TRUE
diff --git a/db/routines/vn/procedures/stockTraslation.sql b/db/routines/vn/procedures/stockTraslation.sql
index c681112f1..f9175dc2a 100644
--- a/db/routines/vn/procedures/stockTraslation.sql
+++ b/db/routines/vn/procedures/stockTraslation.sql
@@ -36,6 +36,6 @@ BEGIN
WHERE warehouse_id = vAuctionWarehouseFk
ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity);
- CALL buyUltimate(vAuctionWarehouseFk, vDated);
+ CALL buy_getUltimate(NULL, vAuctionWarehouseFk, vDated);
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/supplier_statement.sql b/db/routines/vn/procedures/supplier_statement.sql
deleted file mode 100644
index a03a7770c..000000000
--- a/db/routines/vn/procedures/supplier_statement.sql
+++ /dev/null
@@ -1,139 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_statement`(
- vSupplierFk INT,
- vCurrencyFk INT,
- vCompanyFk INT,
- vOrderBy VARCHAR(15),
- vIsConciliated BOOL
-)
-BEGIN
-/**
- * Crea un estado de cuenta de proveedores calculando
- * los saldos en euros y en la moneda especificada.
- *
- * @param vSupplierFk Id del proveedor
- * @param vCurrencyFk Id de la moneda
- * @param vCompanyFk Id de la empresa
- * @param vOrderBy Criterio de ordenación
- * @param vIsConciliated Indica si está conciliado o no
- * @return tmp.supplierStatement
- */
- SET @euroBalance:= 0;
- SET @currencyBalance:= 0;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement
- ENGINE = MEMORY
- SELECT *,
- @euroBalance:= ROUND(
- @euroBalance + IFNULL(paymentEuros, 0) -
- IFNULL(invoiceEuros, 0), 2
- ) euroBalance,
- @currencyBalance:= ROUND(
- @currencyBalance + IFNULL(paymentCurrency, 0) -
- IFNULL(invoiceCurrency, 0), 2
- ) currencyBalance
- FROM (
- SELECT * FROM
- (
- SELECT NULL bankFk,
- ii.companyFk,
- ii.serial,
- ii.id,
- CASE
- WHEN vOrderBy = 'issued' THEN ii.issued
- WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried
- WHEN vOrderBy = 'booked' THEN ii.booked
- WHEN vOrderBy = 'dueDate' THEN iid.dueDated
- END dated,
- CONCAT('S/Fra ', ii.supplierRef) sref,
- IF(ii.currencyFk > 1,
- ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3),
- NULL
- ) changeValue,
- CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros,
- CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency,
- NULL paymentEuros,
- NULL paymentCurrency,
- ii.currencyFk,
- ii.isBooked,
- c.code,
- 'invoiceIn' statementType
- FROM invoiceIn ii
- JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
- JOIN currency c ON c.id = ii.currencyFk
- WHERE ii.issued > '2014-12-31'
- AND ii.supplierFk = vSupplierFk
- AND vCurrencyFk IN (ii.currencyFk, 0)
- AND vCompanyFk IN (ii.companyFk, 0)
- AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
- GROUP BY iid.id
- UNION ALL
- SELECT p.bankFk,
- p.companyFk,
- NULL,
- p.id,
- CASE
- WHEN vOrderBy = 'issued' THEN p.received
- WHEN vOrderBy = 'bookEntried' THEN p.received
- WHEN vOrderBy = 'booked' THEN p.received
- WHEN vOrderBy = 'dueDate' THEN p.dueDated
- END,
- CONCAT(IFNULL(pm.name, ''),
- IF(pn.concept <> '',
- CONCAT(' : ', pn.concept),
- '')
- ),
- IF(p.currencyFk > 1, p.divisa / p.amount, NULL),
- NULL,
- NULL,
- p.amount,
- p.divisa,
- p.currencyFk,
- p.isConciliated,
- c.code,
- 'payment'
- FROM payment p
- LEFT JOIN currency c ON c.id = p.currencyFk
- LEFT JOIN accounting a ON a.id = p.bankFk
- LEFT JOIN payMethod pm ON pm.id = p.payMethodFk
- LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id
- WHERE p.received > '2014-12-31'
- AND p.supplierFk = vSupplierFk
- AND vCurrencyFk IN (p.currencyFk, 0)
- AND vCompanyFk IN (p.companyFk, 0)
- AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
- UNION ALL
- SELECT NULL,
- companyFk,
- NULL,
- se.id,
- CASE
- WHEN vOrderBy = 'issued' THEN se.dated
- WHEN vOrderBy = 'bookEntried' THEN se.dated
- WHEN vOrderBy = 'booked' THEN se.dated
- WHEN vOrderBy = 'dueDate' THEN se.dueDated
- END,
- se.description,
- 1,
- amount,
- NULL,
- NULL,
- NULL,
- currencyFk,
- isConciliated,
- c.`code`,
- 'expense'
- FROM supplierExpense se
- JOIN currency c ON c.id = se.currencyFk
- WHERE se.supplierFk = vSupplierFk
- AND vCurrencyFk IN (se.currencyFk,0)
- AND vCompanyFk IN (se.companyFk,0)
- AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
- ) sub
- ORDER BY (dated IS NULL AND NOT isBooked),
- dated,
- IF(vOrderBy = 'dueDate', id, NULL)
- LIMIT 10000000000000000000
- ) t;
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/supplier_statementWithEntries.sql b/db/routines/vn/procedures/supplier_statementWithEntries.sql
new file mode 100644
index 000000000..df3b918a7
--- /dev/null
+++ b/db/routines/vn/procedures/supplier_statementWithEntries.sql
@@ -0,0 +1,166 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE vn.supplier_statementWithEntries(
+ vSupplierFk INT,
+ vCurrencyFk INT,
+ vCompanyFk INT,
+ vOrderBy VARCHAR(15),
+ vIsConciliated BOOL,
+ vHasEntries BOOL
+)
+BEGIN
+/**
+* Creates a supplier statement, calculating balances in euros and the specified currency.
+*
+* @param vSupplierFk Supplier ID
+* @param vCurrencyFk Currency ID
+* @param vCompanyFk Company ID
+* @param vOrderBy Order by criteria
+* @param vIsConciliated Indicates whether it is reconciled or not
+* @param vHasEntries Indicates if future entries must be shown
+* @return tmp.supplierStatement
+*/
+ DECLARE vBalanceStartingDate DATETIME;
+
+ SET @euroBalance:= 0;
+ SET @currencyBalance:= 0;
+
+ SELECT balanceStartingDate
+ INTO vBalanceStartingDate
+ FROM invoiceInConfig;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement
+ ENGINE = MEMORY
+ SELECT *,
+ @euroBalance:= ROUND(
+ @euroBalance + IFNULL(paymentEuros, 0) -
+ IFNULL(invoiceEuros, 0), 2
+ ) euroBalance,
+ @currencyBalance:= ROUND(
+ @currencyBalance + IFNULL(paymentCurrency, 0) -
+ IFNULL(invoiceCurrency, 0), 2
+ ) currencyBalance
+ FROM (
+ SELECT NULL bankFk,
+ ii.companyFk,
+ ii.serial,
+ ii.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN ii.issued
+ WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried
+ WHEN vOrderBy = 'booked' THEN ii.booked
+ WHEN vOrderBy = 'dueDate' THEN iid.dueDated
+ END dated,
+ CONCAT('S/Fra ', ii.supplierRef) sref,
+ IF(ii.currencyFk > 1,
+ ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3),
+ NULL
+ ) changeValue,
+ CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros,
+ CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency,
+ NULL paymentEuros,
+ NULL paymentCurrency,
+ ii.currencyFk,
+ ii.isBooked,
+ c.code,
+ 'invoiceIn' statementType
+ FROM invoiceIn ii
+ JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
+ JOIN currency c ON c.id = ii.currencyFk
+ WHERE ii.issued >= vBalanceStartingDate
+ AND ii.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (ii.currencyFk, 0)
+ AND vCompanyFk IN (ii.companyFk, 0)
+ AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
+ GROUP BY iid.id
+ UNION ALL
+ SELECT p.bankFk,
+ p.companyFk,
+ NULL,
+ p.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN p.received
+ WHEN vOrderBy = 'bookEntried' THEN p.received
+ WHEN vOrderBy = 'booked' THEN p.received
+ WHEN vOrderBy = 'dueDate' THEN p.dueDated
+ END,
+ CONCAT(IFNULL(pm.name, ''),
+ IF(pn.concept <> '',
+ CONCAT(' : ', pn.concept),
+ '')
+ ),
+ IF(p.currencyFk > 1, p.divisa / p.amount, NULL),
+ NULL,
+ NULL,
+ p.amount,
+ p.divisa,
+ p.currencyFk,
+ p.isConciliated,
+ c.code,
+ 'payment'
+ FROM payment p
+ LEFT JOIN currency c ON c.id = p.currencyFk
+ LEFT JOIN accounting a ON a.id = p.bankFk
+ LEFT JOIN payMethod pm ON pm.id = p.payMethodFk
+ LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id
+ WHERE p.received >= vBalanceStartingDate
+ AND p.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (p.currencyFk, 0)
+ AND vCompanyFk IN (p.companyFk, 0)
+ AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
+ UNION ALL
+ SELECT NULL,
+ companyFk,
+ NULL,
+ se.id,
+ CASE
+ WHEN vOrderBy = 'issued' THEN se.dated
+ WHEN vOrderBy = 'bookEntried' THEN se.dated
+ WHEN vOrderBy = 'booked' THEN se.dated
+ WHEN vOrderBy = 'dueDate' THEN se.dueDated
+ END,
+ se.description,
+ 1,
+ amount,
+ NULL,
+ NULL,
+ NULL,
+ currencyFk,
+ isConciliated,
+ c.`code`,
+ 'expense'
+ FROM supplierExpense se
+ JOIN currency c ON c.id = se.currencyFk
+ WHERE se.supplierFk = vSupplierFk
+ AND vCurrencyFk IN (se.currencyFk,0)
+ AND vCompanyFk IN (se.companyFk,0)
+ AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
+ UNION ALL
+ SELECT NULL bankFk,
+ e.companyFk,
+ 'E' serial,
+ e.invoiceNumber id,
+ tr.landed dated,
+ CONCAT('Ent. ',e.id) sref,
+ 1 / ((e.commission/100)+1) changeValue,
+ e.invoiceAmount * (1 + (e.commission/100)),
+ e.invoiceAmount,
+ NULL,
+ NULL,
+ e.currencyFk,
+ FALSE isBooked,
+ c.code,
+ 'order'
+ FROM entry e
+ JOIN travel tr ON tr.id = e.travelFk
+ JOIN currency c ON c.id = e.currencyFk
+ WHERE e.supplierFk = vSupplierFk
+ AND tr.landed >= CURDATE()
+ AND e.invoiceInFk IS NULL
+ AND vHasEntries
+ ORDER BY (dated IS NULL AND NOT isBooked),
+ dated,
+ IF(vOrderBy = 'dueDate', id, NULL)
+ LIMIT 10000000000000000000
+ ) t;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_componentPreview.sql b/db/routines/vn/procedures/ticket_componentPreview.sql
index 729e3a743..4bcd8c8ec 100644
--- a/db/routines/vn/procedures/ticket_componentPreview.sql
+++ b/db/routines/vn/procedures/ticket_componentPreview.sql
@@ -56,13 +56,12 @@ BEGIN
FROM zone
WHERE id = vZoneFk;
- CALL buyUltimate(vWarehouseFk, vShipped);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vShipped);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY (
- SELECT
- vWarehouseFk AS warehouseFk,
- NULL AS available,
+ SELECT vWarehouseFk warehouseFk,
+ NULL available,
s.itemFk,
bu.buyFk,
vZoneFk zoneFk
diff --git a/db/routines/vn/procedures/ticket_setParking.sql b/db/routines/vn/procedures/ticket_setParking.sql
index 7935e0d60..bd2a5370a 100644
--- a/db/routines/vn/procedures/ticket_setParking.sql
+++ b/db/routines/vn/procedures/ticket_setParking.sql
@@ -21,11 +21,6 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- RESIGNAL;
- END;
-
INSERT INTO vn.ticketParking(ticketFk, parkingFk)
SELECT IFNULL(tc2.ticketFk, t.id), vParkingFk
FROM ticket t
diff --git a/db/routines/vn/procedures/ticket_setProblem.sql b/db/routines/vn/procedures/ticket_setProblem.sql
index 66d244d5a..fea6d9b7d 100644
--- a/db/routines/vn/procedures/ticket_setProblem.sql
+++ b/db/routines/vn/procedures/ticket_setProblem.sql
@@ -12,24 +12,28 @@ BEGIN
*/
DECLARE vTicketFk INT;
DECLARE vHasProblem INT;
+ DECLARE vIsProblemCalcNeeded BOOL;
DECLARE vDone BOOL;
- DECLARE vTicketList CURSOR FOR SELECT ticketFk, hasProblem FROM tmp.ticket;
+ DECLARE vTicketList CURSOR FOR
+ SELECT ticketFk, hasProblem, isProblemCalcNeeded
+ FROM tmp.ticket;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vTicketList;
l: LOOP
SET vDone = FALSE;
- FETCH vTicketList INTO vTicketFk, vHasProblem;
+ FETCH vTicketList INTO vTicketFk, vHasProblem, vIsProblemCalcNeeded;
IF vDone THEN
LEAVE l;
END IF;
UPDATE ticket
- SET problem = CONCAT(
- IF(vHasProblem,
+ SET problem = IF(vIsProblemCalcNeeded,
+ CONCAT(IF(vHasProblem,
CONCAT(problem, ',', vProblemCode),
- REPLACE(problem, vProblemCode , '')))
+ REPLACE(problem, vProblemCode , ''))),
+ NULL)
WHERE id = vTicketFk;
END LOOP;
CLOSE vTicketList;
diff --git a/db/routines/vn/procedures/ticket_setProblemRiskByClient.sql b/db/routines/vn/procedures/ticket_setProblemRiskByClient.sql
new file mode 100644
index 000000000..8479550de
--- /dev/null
+++ b/db/routines/vn/procedures/ticket_setProblemRiskByClient.sql
@@ -0,0 +1,35 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setProblemRiskByClient`(
+ vClientFk INT
+)
+BEGIN
+/**
+ * Updates future ticket risk for a client.
+ *
+ * @param vClientFk Id client
+ */
+ DECLARE vDone INT DEFAULT FALSE;
+ DECLARE vTicketFk INT;
+ DECLARE vTickets CURSOR FOR
+ SELECT id
+ FROM ticket
+ WHERE clientFk = vClientFk
+ AND shipped >= util.VN_CURDATE()
+ AND refFk IS NULL;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vTickets;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vTickets INTO vTicketFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ CALL vn.ticket_setProblemRisk(vTicketFk);
+ END LOOP;
+ CLOSE vTickets;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/ticket_setProblemRounding.sql b/db/routines/vn/procedures/ticket_setProblemRounding.sql
index fb580eacf..551cf67d1 100644
--- a/db/routines/vn/procedures/ticket_setProblemRounding.sql
+++ b/db/routines/vn/procedures/ticket_setProblemRounding.sql
@@ -16,7 +16,7 @@ BEGIN
FROM ticket
WHERE id = vSelf;
- CALL buyUltimate(vWarehouseFk, vDated);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk, isProblemCalcNeeded))
diff --git a/db/routines/vn/procedures/ticket_setRisk.sql b/db/routines/vn/procedures/ticket_setRisk.sql
index bd5d1e9f9..e3cbaf231 100644
--- a/db/routines/vn/procedures/ticket_setRisk.sql
+++ b/db/routines/vn/procedures/ticket_setRisk.sql
@@ -1,94 +1,83 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setRisk`(
- vClientFk INT)
+ vClientFk INT
+)
BEGIN
/**
- * Update the risk for a client with pending tickets
+ * Update the risk for a client with pending tickets.
*
* @param vClientFk Id cliente
*/
- DECLARE vHasDebt BOOL;
- DECLARE vStarted DATETIME;
-
- SELECT COUNT(*) INTO vHasDebt
- FROM `client`
- WHERE id = vClientFk
- AND typeFk = 'normal';
-
- IF vHasDebt THEN
-
- SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted
- FROM clientConfig;
-
+ IF (SELECT COUNT(*) FROM client WHERE id = vClientFk AND typeFk = 'normal') THEN
CREATE OR REPLACE TEMPORARY TABLE tTicketRisk
- (KEY (ticketFk))
+ (PRIMARY KEY (ticketFk))
ENGINE = MEMORY
- WITH ticket AS(
- SELECT id ticketFk,
- companyFk,
- DATE(shipped) dated,
- totalWithVat,
- ticket_isProblemCalcNeeded(id) isProblemCalcNeeded
- FROM vn.ticket
- WHERE clientFk = vClientFk
- AND refFk IS NULL
- AND NOT isDeleted
- AND IFNULL(totalWithVat, 0) <> 0
- AND shipped > vStarted
- ), balance AS(
- SELECT SUM(amount)amount, companyFk
- FROM (
- SELECT amount, companyFk
- FROM vn.clientRisk
- WHERE clientFk = vClientFk
- UNION ALL
- SELECT -(SUM(amount) / 100) amount, tm.companyFk
- FROM hedera.tpvTransaction t
- JOIN hedera.tpvMerchant tm ON t.id = t.merchantFk
- WHERE clientFk = vClientFk
- AND receiptFk IS NULL
- AND status = 'ok'
- ) sub
- WHERE companyFk
- GROUP BY companyFk
- ), uninvoiced AS(
+ WITH ticket AS (
+ SELECT t.id ticketFk,
+ t.companyFk,
+ DATE(t.shipped) dated,
+ t.totalWithVat,
+ ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
+ FROM vn.ticket t
+ JOIN vn.clientConfig cc
+ WHERE t.clientFk = vClientFk
+ AND t.refFk IS NULL
+ AND NOT t.isDeleted
+ AND IFNULL(t.totalWithVat, 0) <> 0
+ AND t.shipped > (util.VN_CURDATE() - INTERVAL cc.riskScope MONTH)
+ ), uninvoiced AS (
SELECT companyFk, dated, SUM(totalWithVat) amount
FROM ticket
- GROUP BY companyFk, dated
- ), receipt AS(
- SELECT companyFk, DATE(payed) dated, SUM(amountPaid) amount
- FROM vn.receipt
- WHERE clientFk = vClientFk
- AND payed > util.VN_CURDATE()
- GROUP BY companyFk, DATE(payed)
- ), risk AS(
+ GROUP BY companyFk, dated
+ ), companies AS (
+ SELECT DISTINCT companyFk FROM uninvoiced
+ ), balance AS (
+ SELECT SUM(IFNULL(amount, 0))amount, companyFk
+ FROM (
+ SELECT cr.amount, c.companyFk
+ FROM companies c
+ LEFT JOIN vn.clientRisk cr ON cr.companyFk = c.companyFk
+ AND cr.clientFk = vClientFk
+ UNION ALL
+ SELECT -(SUM(t.amount) / 100) amount, c.companyFk
+ FROM companies c
+ LEFT JOIN hedera.tpvMerchant tm ON tm.companyFk = c.companyFk
+ LEFT JOIN hedera.tpvTransaction t ON t.merchantFk = tm.id
+ AND t.clientFk = vClientFk
+ AND t.receiptFk IS NULL
+ AND t.`status` = 'ok'
+ ) sub
+ WHERE companyFk
+ GROUP BY companyFk
+ ), receipt AS (
+ SELECT r.companyFk, DATE(r.payed) dated, SUM(r.amountPaid) amount
+ FROM vn.receipt r
+ JOIN companies c ON c.companyFk = r.companyFk
+ WHERE r.clientFk = vClientFk
+ AND r.payed > util.VN_CURDATE()
+ GROUP BY r.companyFk, DATE(r.payed)
+ ), risk AS (
SELECT b.companyFk,
- ui.dated,
- SUM(ui.amount) OVER (PARTITION BY b.companyFk ORDER BY ui.dated ) +
+ ui.dated,
+ SUM(ui.amount) OVER (PARTITION BY b.companyFk ORDER BY ui.dated) +
b.amount +
SUM(IFNULL(r.amount, 0)) amount
FROM balance b
JOIN uninvoiced ui ON ui.companyFk = b.companyFk
- LEFT JOIN receipt r ON r.dated > ui.dated AND r.companyFk = ui.companyFk
+ LEFT JOIN receipt r ON r.dated > ui.dated
+ AND r.companyFk = ui.companyFk
GROUP BY b.companyFk, ui.dated
- )
- SELECT ti.ticketFk, r.amount, ti.isProblemCalcNeeded
- FROM ticket ti
- JOIN risk r ON r.dated = ti.dated AND r.companyFk = ti.companyFk;
+ )
+ SELECT ti.ticketFk, r.amount, ti.isProblemCalcNeeded
+ FROM ticket ti
+ JOIN risk r ON r.dated = ti.dated
+ AND r.companyFk = ti.companyFk;
UPDATE ticket t
JOIN tTicketRisk tr ON tr.ticketFk = t.id
- SET t.risk = tr.amount
- WHERE tr.isProblemCalcNeeded
- ORDER BY t.id;
-
- UPDATE ticket t
- JOIN tTicketRisk tr ON tr.ticketFk = t.id
- SET t.risk = NULL
- WHERE tr.isProblemCalcNeeded
- ORDER BY t.id;
+ SET t.risk = IF(tr.isProblemCalcNeeded, tr.amount, NULL);
DROP TEMPORARY TABLE tTicketRisk;
- END IF;
+ END IF;
END$$
DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql
index c2ec50fd9..5ae9fb9bc 100644
--- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql
+++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql
@@ -1,7 +1,7 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`(
vSelf INT,
- vItemPackingTypeFk VARCHAR(1)
+ vOriginalItemPackingTypeFk VARCHAR(1)
)
BEGIN
/**
@@ -9,7 +9,7 @@ BEGIN
* Respeta el id inicial para el tipo propuesto.
*
* @param vSelf Id ticket
- * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original
+ * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original
* @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk)
*/
DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H';
@@ -23,7 +23,7 @@ BEGIN
SELECT itemPackingTypeFk
FROM tSaleGroup
WHERE itemPackingTypeFk IS NOT NULL
- ORDER BY (itemPackingTypeFk = vItemPackingTypeFk) DESC;
+ ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
diff --git a/db/routines/vn/procedures/zone_getAddresses.sql b/db/routines/vn/procedures/zone_getAddresses.sql
index ce7b0204e..0622ece1b 100644
--- a/db/routines/vn/procedures/zone_getAddresses.sql
+++ b/db/routines/vn/procedures/zone_getAddresses.sql
@@ -1,55 +1,57 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getAddresses`(
vSelf INT,
- vLanded DATE
+ vShipped DATE,
+ vDepartmentFk INT
)
BEGIN
/**
* Devuelve un listado de todos los clientes activos
* con consignatarios a los que se les puede
- * vender producto para esa zona y no tiene un ticket
- * para ese día.
+ * vender producto para esa zona.
*
* @param vSelf Id de zona
- * @param vDated Fecha de entrega
+ * @param vShipped Fecha de envio
+ * @param vDepartmentFk Id de departamento
* @return Un select
*/
CALL zone_getPostalCode(vSelf);
- WITH notHasTicket AS (
- SELECT id
- FROM vn.client
- WHERE id NOT IN (
- SELECT clientFk
- FROM vn.ticket
- WHERE landed BETWEEN vLanded AND util.dayEnd(vLanded)
- )
+ WITH clientWithTicket AS (
+ SELECT clientFk
+ FROM vn.ticket
+ WHERE shipped BETWEEN vShipped AND util.dayEnd(vShipped)
)
- SELECT c.id clientFk,
- c.name,
- c.phone,
- bt.description,
- c.salesPersonFk,
- u.name username,
- aai.invoiced,
- cnb.lastShipped
- FROM vn.client c
- JOIN notHasTicket ON notHasTicket.id = c.id
- LEFT JOIN account.`user` u ON u.id = c.salesPersonFk
- JOIN vn.`address` a ON a.clientFk = c.id
- JOIN vn.postCode pc ON pc.code = a.postalCode
- JOIN vn.town t ON t.id = pc.townFk AND t.provinceFk = a.provinceFk
- JOIN vn.zoneGeo zg ON zg.name = a.postalCode
- JOIN tmp.zoneNodes zn ON zn.geoFk = pc.geoFk
- LEFT JOIN bs.clientNewBorn cnb ON cnb.clientFk = c.id
- LEFT JOIN vn.annualAverageInvoiced aai ON aai.clientFk = c.id
- JOIN vn.clientType ct ON ct.code = c.typeFk
- JOIN vn.businessType bt ON bt.code = c.businessTypeFk
- WHERE a.isActive
- AND c.isActive
- AND ct.code = 'normal'
- AND bt.code <> 'worker'
- GROUP BY c.id;
+ SELECT c.id,
+ c.name,
+ c.phone,
+ bt.description,
+ c.salesPersonFk,
+ u.name username,
+ aai.invoiced,
+ cnb.lastShipped,
+ cwt.clientFk
+ FROM vn.client c
+ JOIN vn.worker w ON w.id = c.salesPersonFk
+ JOIN vn.workerDepartment wd ON wd.workerFk = w.id
+ JOIN vn.department d ON d.id = wd.departmentFk
+ LEFT JOIN clientWithTicket cwt ON cwt.clientFk = c.id
+ LEFT JOIN account.`user` u ON u.id = c.salesPersonFk
+ JOIN vn.`address` a ON a.clientFk = c.id
+ JOIN vn.postCode pc ON pc.code = a.postalCode
+ JOIN vn.town t ON t.id = pc.townFk AND t.provinceFk = a.provinceFk
+ JOIN vn.zoneGeo zg ON zg.name = a.postalCode
+ JOIN tmp.zoneNodes zn ON zn.geoFk = pc.geoFk
+ LEFT JOIN bs.clientNewBorn cnb ON cnb.clientFk = c.id
+ LEFT JOIN vn.annualAverageInvoiced aai ON aai.clientFk = c.id
+ JOIN vn.clientType ct ON ct.code = c.typeFk
+ JOIN vn.businessType bt ON bt.code = c.businessTypeFk
+ WHERE a.isActive
+ AND c.isActive
+ AND ct.code = 'normal'
+ AND bt.code <> 'worker'
+ AND (d.id = vDepartmentFk OR NOT vDepartmentFk)
+ GROUP BY c.id;
DROP TEMPORARY TABLE tmp.zoneNodes;
END$$
diff --git a/db/routines/vn/triggers/itemShelving_beforeUpdate.sql b/db/routines/vn/triggers/itemShelving_beforeUpdate.sql
index 214c64b45..961d89f65 100644
--- a/db/routines/vn/triggers/itemShelving_beforeUpdate.sql
+++ b/db/routines/vn/triggers/itemShelving_beforeUpdate.sql
@@ -9,9 +9,5 @@ BEGIN
SET NEW.userFk = account.myUser_getId();
END IF;
- IF (NEW.visible <> OLD.visible) THEN
- SET NEW.available = GREATEST(NEW.available + NEW.visible - OLD.visible, 0);
- END IF;
-
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/ticket_beforeUpdate.sql b/db/routines/vn/triggers/ticket_beforeUpdate.sql
index 34b6711ff..6d5d7f908 100644
--- a/db/routines/vn/triggers/ticket_beforeUpdate.sql
+++ b/db/routines/vn/triggers/ticket_beforeUpdate.sql
@@ -8,7 +8,13 @@ BEGIN
SET NEW.editorFk = account.myUser_getId();
IF NOT (NEW.routeFk <=> OLD.routeFk) THEN
- IF NEW.isSigned THEN
+ IF NEW.isSigned AND NOT (
+ SELECT (COUNT(s.id) = COUNT(cb.saleFk)
+ AND SUM(s.quantity) = SUM(cb.quantity))
+ FROM sale s
+ LEFT JOIN claimBeginning cb ON cb.saleFk = s.id
+ WHERE s.ticketFk = NEW.id
+ ) THEN
CALL util.throw('A signed ticket cannot be rerouted');
END IF;
INSERT IGNORE INTO routeRecalc(routeFk)
diff --git a/db/versions/11155-purpleMoss/00-firstScript.sql b/db/versions/11155-purpleMoss/00-firstScript.sql
new file mode 100644
index 000000000..fec63b193
--- /dev/null
+++ b/db/versions/11155-purpleMoss/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.invoiceInConfig
+ ADD dueDateMarginDays INT UNSIGNED DEFAULT 2 NULL;
diff --git a/db/versions/11165-grayAralia/00-firstScript.sql b/db/versions/11165-grayAralia/00-firstScript.sql
new file mode 100644
index 000000000..652b2343a
--- /dev/null
+++ b/db/versions/11165-grayAralia/00-firstScript.sql
@@ -0,0 +1,3 @@
+ALTER TABLE vn.productionConfig
+ DROP COLUMN scannableCodeType,
+ DROP COLUMN scannablePreviusCodeType;
diff --git a/db/versions/11166-azureDracena/00-firstScript.sql b/db/versions/11166-azureDracena/00-firstScript.sql
new file mode 100644
index 000000000..ba087b5a8
--- /dev/null
+++ b/db/versions/11166-azureDracena/00-firstScript.sql
@@ -0,0 +1,25 @@
+CREATE OR REPLACE TABLE `salix`.`ACLLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `originFk` int(11) DEFAULT NULL,
+ `userFk` int(10) unsigned DEFAULT NULL,
+ `action` set('insert','update','delete','select') NOT NULL,
+ `creationDate` timestamp NULL DEFAULT current_timestamp(),
+ `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `changedModel` enum('Acl') NOT NULL DEFAULT 'Acl',
+ `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
+ `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
+ `changedModelId` int(11) NOT NULL,
+ `changedModelValue` varchar(45) DEFAULT NULL,
+ `summaryId` varchar(30) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `logRateuserFk` (`userFk`),
+ KEY `ACLLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
+ KEY `ACLLog_originFk` (`originFk`,`creationDate`),
+ CONSTRAINT `aclUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+ALTER TABLE salix.ACL
+ ADD editorFk int(10) unsigned DEFAULT NULL NULL;
+
+ALTER TABLE vn.ticket
+ CHANGE editorFk editorFk int(10) unsigned DEFAULT NULL NULL AFTER risk;
diff --git a/db/versions/11168-redFern/00-firstScript.sql b/db/versions/11168-redFern/00-firstScript.sql
new file mode 100644
index 000000000..f91780e37
--- /dev/null
+++ b/db/versions/11168-redFern/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.calendar
+ ADD CONSTRAINT calendar_user_FK FOREIGN KEY (editorFk) REFERENCES account.`user`(id);
diff --git a/db/versions/11169-azureCyca/00-firstScript.sql b/db/versions/11169-azureCyca/00-firstScript.sql
new file mode 100644
index 000000000..49adcfc05
--- /dev/null
+++ b/db/versions/11169-azureCyca/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE IF EXISTS vn.itemShelving
+MODIFY COLUMN IF EXISTS isSplit tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda';
diff --git a/db/versions/11170-redPaniculata/00-firstScript.sql b/db/versions/11170-redPaniculata/00-firstScript.sql
new file mode 100644
index 000000000..b5d34c082
--- /dev/null
+++ b/db/versions/11170-redPaniculata/00-firstScript.sql
@@ -0,0 +1,6 @@
+-- Place your SQL code here
+
+ALTER TABLE vn.packingSite DROP COLUMN IF EXISTS hasNewLabelMrwMethod;
+
+ALTER TABLE vn.productionConfig ADD IF NOT EXISTS hasNewLabelMrwMethod BOOL DEFAULT TRUE NOT NULL
+ COMMENT 'column to activate the new mrw integration';
diff --git a/db/versions/11177-crimsonPaniculata/00-firstScript.sql b/db/versions/11177-crimsonPaniculata/00-firstScript.sql
new file mode 100644
index 000000000..79bcf1291
--- /dev/null
+++ b/db/versions/11177-crimsonPaniculata/00-firstScript.sql
@@ -0,0 +1,6 @@
+-- Place your SQL code here
+
+ALTER TABLE vn.itemShelvingSaleReserve DROP FOREIGN KEY IF EXISTS itemShelvingSaleReserve_sector_FK;
+
+ALTER TABLE vn.itemShelvingSaleReserve ADD CONSTRAINT itemShelvingSaleReserve_sector_FK
+ FOREIGN KEY IF NOT EXISTS (sectorFk) REFERENCES vn.sector(id) ON DELETE RESTRICT ON UPDATE CASCADE;
\ No newline at end of file
diff --git a/db/versions/11179-whiteLaurel/00-firstScript.sql b/db/versions/11179-whiteLaurel/00-firstScript.sql
new file mode 100644
index 000000000..4a4e32c9d
--- /dev/null
+++ b/db/versions/11179-whiteLaurel/00-firstScript.sql
@@ -0,0 +1,2 @@
+RENAME TABLE vn.silexACL TO vn.silexACL__;
+ALTER TABLE vn.silexACL__ COMMENT='@deprecated 2024-08-05 refs #7820';
diff --git a/db/versions/11180-navyGerbera/00-firstScript.sql b/db/versions/11180-navyGerbera/00-firstScript.sql
new file mode 100644
index 000000000..8c5d79ce8
--- /dev/null
+++ b/db/versions/11180-navyGerbera/00-firstScript.sql
@@ -0,0 +1,2 @@
+-- Place your SQL code here
+ALTER TABLE vn.invoiceInConfig ADD balanceStartingDate DATE DEFAULT '2015-01-01' NOT NULL;
diff --git a/db/versions/11182-redAralia/00-firstScript.sql b/db/versions/11182-redAralia/00-firstScript.sql
new file mode 100644
index 000000000..72c06de65
--- /dev/null
+++ b/db/versions/11182-redAralia/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE bs.waste CHANGE saleQuantity saleWasteQuantity decimal(10,2) DEFAULT NULL NULL AFTER saleTotal;
+ALTER TABLE bs.waste MODIFY COLUMN saleTotal decimal(10,2) DEFAULT NULL NULL COMMENT 'Coste';
diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js
index 685345273..097c6e1ab 100644
--- a/e2e/helpers/selectors.js
+++ b/e2e/helpers/selectors.js
@@ -738,69 +738,6 @@ export default {
worker: 'vn-worker-autocomplete[ng-model="$ctrl.userFk"]',
saveStateButton: `button[type=submit]`
},
- claimsIndex: {
- searchResult: 'vn-claim-index vn-card > vn-table > div > vn-tbody > a'
- },
- claimDescriptor: {
- moreMenu: 'vn-claim-descriptor vn-icon-button[icon=more_vert]',
- moreMenuDeleteClaim: '.vn-menu [name="deleteClaim"]',
- acceptDeleteClaim: '.vn-confirm.shown button[response="accept"]'
- },
- claimSummary: {
- header: 'vn-claim-summary > vn-card > h5',
- state: 'vn-claim-summary vn-label-value[label="State"] > section > span',
- observation: 'vn-claim-summary vn-horizontal.text',
- firstSaleItemId: 'vn-claim-summary vn-horizontal > vn-auto:nth-child(5) vn-table > div > vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(1) > span',
- firstSaleDescriptorImage: '.vn-popover.shown vn-item-descriptor img',
- itemDescriptorPopover: '.vn-popover.shown vn-item-descriptor',
- itemDescriptorPopoverItemDiaryButton: '.vn-popover vn-item-descriptor vn-quick-link[icon="icon-transaction"] > a',
- firstDevelopmentWorker: 'vn-claim-summary vn-horizontal > vn-auto:nth-child(4) vn-table > div > vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(4) > span',
- firstDevelopmentWorkerGoToClientButton: '.vn-popover vn-worker-descriptor vn-quick-link[icon="person"] > a',
- firstActionTicketId: 'vn-claim-summary > vn-card > vn-horizontal > vn-auto:nth-child(5) vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(2) > span',
- firstActionTicketDescriptor: '.vn-popover.shown vn-ticket-descriptor'
- },
- claimBasicData: {
- claimState: 'vn-claim-basic-data vn-autocomplete[ng-model="$ctrl.claim.claimStateFk"]',
- packages: 'vn-input-number[ng-model="$ctrl.claim.packages"]',
- saveButton: `button[type=submit]`
- },
- claimDetail: {
- secondItemDiscount: 'vn-claim-detail > vn-vertical > vn-card > vn-vertical > vn-table > div > vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(6) > span',
- discount: '.vn-popover.shown vn-input-number[ng-model="$ctrl.newDiscount"]',
- discoutPopoverMana: '.vn-popover.shown .content > div > vn-horizontal > h5',
- addItemButton: 'vn-claim-detail a vn-float-button',
- firstClaimableSaleFromTicket: '.vn-dialog.shown vn-tbody > vn-tr',
- claimDetailLine: 'vn-claim-detail > vn-vertical > vn-card > vn-vertical > vn-table > div > vn-tbody > vn-tr',
- totalClaimed: 'vn-claim-detail > vn-vertical > vn-card > vn-vertical > vn-horizontal > div > vn-label-value:nth-child(2) > section > span',
- secondItemDeleteButton: 'vn-claim-detail > vn-vertical > vn-card > vn-vertical > vn-table > div > vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(8) > vn-icon-button > button > vn-icon > i'
- },
- claimDevelopment: {
- addDevelopmentButton: 'vn-claim-development > vn-vertical > vn-card > vn-vertical > vn-one > vn-icon-button > button > vn-icon',
- firstDeleteDevelopmentButton: 'vn-claim-development > vn-vertical > vn-card > vn-vertical > form > vn-horizontal:nth-child(2) > vn-icon-button > button > vn-icon',
- firstClaimReason: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.claimReasonFk"]',
- firstClaimResult: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.claimResultFk"]',
- firstClaimResponsible: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.claimResponsibleFk"]',
- firstClaimWorker: 'vn-claim-development vn-horizontal:nth-child(1) vn-worker-autocomplete[ng-model="claimDevelopment.workerFk"]',
- firstClaimRedelivery: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.claimRedeliveryFk"]',
- secondClaimReason: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.claimReasonFk"]',
- secondClaimResult: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.claimResultFk"]',
- secondClaimResponsible: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.claimResponsibleFk"]',
- secondClaimWorker: 'vn-claim-development vn-horizontal:nth-child(2) vn-worker-autocomplete[ng-model="claimDevelopment.workerFk"]',
- secondClaimRedelivery: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.claimRedeliveryFk"]',
- saveDevelopmentButton: 'button[type=submit]'
- },
- claimNote: {
- addNoteFloatButton: 'vn-float-button',
- note: 'vn-textarea[ng-model="$ctrl.note.text"]',
- saveButton: 'button[type=submit]',
- firstNoteText: 'vn-claim-note .text'
- },
- claimAction: {
- importClaimButton: 'vn-claim-action vn-button[label="Import claim"]',
- anyLine: 'vn-claim-action vn-tbody > vn-tr',
- firstDeleteLine: 'vn-claim-action tr:nth-child(2) vn-icon-button[icon="delete"]',
- isPaidWithManaCheckbox: 'vn-claim-action vn-check[ng-model="$ctrl.claim.isChargedToMana"]'
- },
ordersIndex: {
secondSearchResultTotal: 'vn-order-index vn-card > vn-table > div > vn-tbody .vn-tr:nth-child(2) vn-td:nth-child(9)',
advancedSearchButton: 'vn-order-search-panel vn-submit[label="Search"]',
diff --git a/e2e/paths/03-worker/01-department/01_summary.spec.js b/e2e/paths/03-worker/01-department/01_summary.spec.js
deleted file mode 100644
index e4bf8fc2d..000000000
--- a/e2e/paths/03-worker/01-department/01_summary.spec.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import selectors from '../../../helpers/selectors.js';
-import getBrowser from '../../../helpers/puppeteer';
-
-describe('department summary path', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('hr', 'worker');
- await page.accessToSection('worker.department');
- await page.doSearch('INFORMATICA');
- await page.click(selectors.department.firstDepartment);
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should reach the employee summary section and check all properties', async() => {
- expect(await page.waitToGetProperty(selectors.departmentSummary.header, 'innerText')).toEqual('INFORMATICA');
- expect(await page.getProperty(selectors.departmentSummary.name, 'innerText')).toEqual('INFORMATICA');
- expect(await page.getProperty(selectors.departmentSummary.code, 'innerText')).toEqual('it');
- expect(await page.getProperty(selectors.departmentSummary.chat, 'innerText')).toEqual('informatica-cau');
- expect(await page.getProperty(selectors.departmentSummary.bossDepartment, 'innerText')).toEqual('');
- expect(await page.getProperty(selectors.departmentSummary.email, 'innerText')).toEqual('-');
- expect(await page.getProperty(selectors.departmentSummary.clientFk, 'innerText')).toEqual('-');
- });
-});
diff --git a/e2e/paths/03-worker/01-department/02-basicData.spec.js b/e2e/paths/03-worker/01-department/02-basicData.spec.js
deleted file mode 100644
index 219d1426c..000000000
--- a/e2e/paths/03-worker/01-department/02-basicData.spec.js
+++ /dev/null
@@ -1,43 +0,0 @@
-import getBrowser from '../../../helpers/puppeteer';
-import selectors from '../../../helpers/selectors.js';
-
-const $ = {
- form: 'vn-worker-department-basic-data form',
-};
-
-describe('department summary path', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('hr', 'worker');
- await page.accessToSection('worker.department');
- await page.doSearch('INFORMATICA');
- await page.click(selectors.department.firstDepartment);
- });
-
- beforeEach(async() => {
- await page.accessToSection('worker.department.card.basicData');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it(`should edit the department basic data and confirm the department data was edited`, async() => {
- const values = {
- Name: 'Informatica',
- Code: 'IT',
- Chat: 'informatica-cau',
- Email: 'it@verdnatura.es',
- };
-
- await page.fillForm($.form, values);
- const formValues = await page.fetchForm($.form, Object.keys(values));
- const message = await page.sendForm($.form, values);
-
- expect(message.isSuccess).toBeTrue();
- expect(formValues).toEqual(values);
- });
-});
diff --git a/e2e/paths/03-worker/01_summary.spec.js b/e2e/paths/03-worker/01_summary.spec.js
deleted file mode 100644
index 51992b41d..000000000
--- a/e2e/paths/03-worker/01_summary.spec.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Worker summary path', () => {
- const workerId = 3;
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('employee', 'worker');
- const httpDataResponse = page.waitForResponse(response => {
- return response.status() === 200 && response.url().includes(`Workers/${workerId}`);
- });
- await page.accessToSearchResult('agencyNick');
- await httpDataResponse;
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should reach the employee summary section and check all properties', async() => {
- expect(await page.getProperty(selectors.workerSummary.header, 'innerText')).toEqual('agency agency');
- expect(await page.getProperty(selectors.workerSummary.id, 'innerText')).toEqual('3');
- expect(await page.getProperty(selectors.workerSummary.email, 'innerText')).toEqual('agency@verdnatura.es');
- expect(await page.getProperty(selectors.workerSummary.department, 'innerText')).toEqual('CAMARA');
- expect(await page.getProperty(selectors.workerSummary.userId, 'innerText')).toEqual('3');
- expect(await page.getProperty(selectors.workerSummary.userName, 'innerText')).toEqual('agency');
- expect(await page.getProperty(selectors.workerSummary.role, 'innerText')).toEqual('agency');
- expect(await page.getProperty(selectors.workerSummary.extension, 'innerText')).toEqual('1101');
- expect(await page.getProperty(selectors.workerSummary.locker, 'innerText')).toEqual('-');
- });
-});
diff --git a/e2e/paths/03-worker/02_basicData.spec.js b/e2e/paths/03-worker/02_basicData.spec.js
deleted file mode 100644
index 66a597dd1..000000000
--- a/e2e/paths/03-worker/02_basicData.spec.js
+++ /dev/null
@@ -1,40 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Worker basic data path', () => {
- const workerId = 1106;
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('hr', 'worker');
- const httpDataResponse = page.waitForResponse(response => {
- return response.status() === 200 && response.url().includes(`Workers/${workerId}`);
- });
- await page.accessToSearchResult('David Charles Haller');
- await httpDataResponse;
- await page.accessToSection('worker.card.basicData');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should edit the form and then reload the section and check the data was edited', async() => {
- await page.overwrite(selectors.workerBasicData.name, 'David C.');
- await page.overwrite(selectors.workerBasicData.surname, 'H.');
- await page.overwrite(selectors.workerBasicData.phone, '444332211');
- await page.click(selectors.workerBasicData.saveButton);
-
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
-
- await page.reloadSection('worker.card.basicData');
-
- expect(await page.waitToGetProperty(selectors.workerBasicData.name, 'value')).toEqual('David C.');
- expect(await page.waitToGetProperty(selectors.workerBasicData.surname, 'value')).toEqual('H.');
- expect(await page.waitToGetProperty(selectors.workerBasicData.phone, 'value')).toEqual('444332211');
- });
-});
diff --git a/e2e/paths/03-worker/03_pbx.spec.js b/e2e/paths/03-worker/03_pbx.spec.js
deleted file mode 100644
index 0e8003c47..000000000
--- a/e2e/paths/03-worker/03_pbx.spec.js
+++ /dev/null
@@ -1,32 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Worker pbx path', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('hr', 'worker');
- await page.accessToSearchResult('employee');
- await page.accessToSection('worker.card.pbx');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should receive an error when the extension exceeds 4 characters and then sucessfully save the changes', async() => {
- await page.write(selectors.workerPbx.extension, '55555');
- await page.click(selectors.workerPbx.saveButton);
- let message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Extension format is invalid');
-
- await page.overwrite(selectors.workerPbx.extension, '4444');
- await page.click(selectors.workerPbx.saveButton);
- message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved! User must access web');
- });
-});
diff --git a/e2e/paths/03-worker/04_time_control.spec.js b/e2e/paths/03-worker/04_time_control.spec.js
deleted file mode 100644
index c6589d2e3..000000000
--- a/e2e/paths/03-worker/04_time_control.spec.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* eslint max-len: ["error", { "code": 150 }]*/
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Worker time control path', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('salesBoss', 'worker');
- await page.accessToSearchResult('HankPym');
- await page.accessToSection('worker.card.timeControl');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- const eightAm = '08:00';
- const fourPm = '16:00';
- const hankPymId = 1107;
-
- it('should go to the next month, go to current month and go 1 month in the past', async() => {
- let date = Date.vnNew();
- date.setDate(1);
- date.setMonth(date.getMonth() + 1);
- let month = date.toLocaleString('default', {month: 'long'});
-
- await page.waitToClick(selectors.workerTimeControl.nextMonthButton);
- let result = await page.getProperty(selectors.workerTimeControl.monthName, 'innerText');
-
- expect(result).toContain(month);
-
- date = Date.vnNew();
- date.setDate(1);
- month = date.toLocaleString('default', {month: 'long'});
-
- await page.waitToClick(selectors.workerTimeControl.previousMonthButton);
- result = await page.getProperty(selectors.workerTimeControl.monthName, 'innerText');
-
- expect(result).toContain(month);
-
- date = Date.vnNew();
- date.setDate(1);
- date.setMonth(date.getMonth() - 1);
- const timestamp = Math.round(date.getTime() / 1000);
- month = date.toLocaleString('default', {month: 'long'});
-
- await page.loginAndModule('salesBoss', 'worker');
- await page.goto(`http://localhost:5000/#!/worker/${hankPymId}/time-control?timestamp=${timestamp}`);
- await page.waitToClick(selectors.workerTimeControl.secondWeekDay);
-
- result = await page.getProperty(selectors.workerTimeControl.monthName, 'innerText');
-
- expect(result).toContain(month);
- });
-
- it('should change week of month', async() => {
- await page.click(selectors.workerTimeControl.thrirdWeekDay);
- const result = await page.getProperty(selectors.workerTimeControl.mondayWorkedHours, 'innerText');
-
- expect(result).toEqual('00:00 h.');
- });
-});
diff --git a/e2e/paths/03-worker/05_calendar.spec.js b/e2e/paths/03-worker/05_calendar.spec.js
deleted file mode 100644
index f0af0a053..000000000
--- a/e2e/paths/03-worker/05_calendar.spec.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* eslint-disable max-len */
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Worker calendar path', () => {
- const reasonableTimeBetweenClicks = 300;
- const date = Date.vnNew();
- const lastYear = (date.getFullYear() - 1).toString();
-
- let browser;
- let page;
-
- async function accessAs(user) {
- await page.loginAndModule(user, 'worker');
- await page.accessToSearchResult('Charles Xavier');
- await page.accessToSection('worker.card.calendar');
- }
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- accessAs('hr');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- describe('as hr', () => {
- it('should set two days as holidays on the calendar and check the total holidays increased by 1.5', async() => {
- await page.waitToClick(selectors.workerCalendar.holidays);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.penultimateMondayOfJanuary);
-
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.absence);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.lastMondayOfMarch);
-
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.halfHoliday);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.fistMondayOfMay);
-
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.furlough);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.secondTuesdayOfMay);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.secondWednesdayOfMay);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.secondThursdayOfMay);
-
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.halfFurlough);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.click(selectors.workerCalendar.secondFridayOfJun);
-
- expect(await page.getProperty(selectors.workerCalendar.totalHolidaysUsed, 'innerText')).toContain(' 1.5 ');
- });
- });
-
- describe(`as salesBoss`, () => {
- it(`should log in, get to Charles Xavier's calendar, undo what was done here, and check the total holidays used are back to what it was`, async() => {
- accessAs('salesBoss');
-
- await page.waitToClick(selectors.workerCalendar.holidays);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.penultimateMondayOfJanuary);
-
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.absence);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.lastMondayOfMarch);
-
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.halfHoliday);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.fistMondayOfMay);
-
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.furlough);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.secondTuesdayOfMay);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.secondWednesdayOfMay);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.secondThursdayOfMay);
-
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.halfFurlough);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
- await page.waitToClick(selectors.workerCalendar.secondFridayOfJun);
-
- expect(await page.getProperty(selectors.workerCalendar.totalHolidaysUsed, 'innerText')).toContain(' 0 ');
- });
- });
-
- describe(`as Charles Xavier`, () => {
- it('should log in and get to his calendar, make a futile attempt to add holidays, check the total holidays used are now the initial ones and use the year selector to go to the previous year', async() => {
- accessAs('CharlesXavier');
- await page.waitToClick(selectors.workerCalendar.holidays);
- await page.waitForTimeout(reasonableTimeBetweenClicks);
-
- await page.click(selectors.workerCalendar.penultimateMondayOfJanuary);
-
- expect(await page.getProperty(selectors.workerCalendar.totalHolidaysUsed, 'innerText')).toContain(' 0 ');
-
- await page.autocompleteSearch(selectors.workerCalendar.year, lastYear);
-
- expect(await page.getProperty(selectors.workerCalendar.totalHolidaysUsed, 'innerText')).toContain(' 0 ');
- });
- });
-});
diff --git a/e2e/paths/03-worker/06_create.spec.js b/e2e/paths/03-worker/06_create.spec.js
deleted file mode 100644
index 2accdfc31..000000000
--- a/e2e/paths/03-worker/06_create.spec.js
+++ /dev/null
@@ -1,73 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Worker create path', () => {
- let browser;
- let page;
- let newWorker;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('hr', 'worker');
- await page.waitToClick(selectors.workerCreate.newWorkerButton);
- await page.waitForState('worker.create');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should insert default data', async() => {
- await page.write(selectors.workerCreate.firstname, 'Victor');
- await page.write(selectors.workerCreate.lastname, 'Von Doom');
- await page.write(selectors.workerCreate.fi, '78457139E');
- await page.write(selectors.workerCreate.phone, '12356789');
- await page.write(selectors.workerCreate.postcode, '46680');
- await page.write(selectors.workerCreate.street, 'S/ DOOMSTADT');
- await page.write(selectors.workerCreate.email, 'doctorDoom@marvel.com');
- await page.write(selectors.workerCreate.iban, 'ES9121000418450200051332');
-
- // should check for autocompleted worker code and worker user name
- const workerCode = await page
- .waitToGetProperty(selectors.workerCreate.code, 'value');
-
- newWorker = await page
- .waitToGetProperty(selectors.workerCreate.user, 'value');
-
- expect(workerCode).toEqual('VVD');
- expect(newWorker).toContain('victorvd');
-
- // should fail if necessary data is void
- await page.waitToClick(selectors.workerCreate.createButton);
- let message = await page.waitForSnackbar();
-
- expect(message.text).toContain('is a required argument');
-
- // should create a new worker and go to worker basic data'
- await page.pickDate(selectors.workerCreate.birth, new Date(1962, 8, 5));
- await page.autocompleteSearch(selectors.workerCreate.boss, 'deliveryAssistant');
- await page.waitToClick(selectors.workerCreate.createButton);
- message = await page.waitForSnackbar();
- await page.waitForState('worker.card.basicData');
-
- expect(message.text).toContain('Data saved!');
-
- // 'rollback'
- await page.loginAndModule('itManagement', 'account');
- await page.accessToSearchResult(newWorker);
-
- await page.waitToClick(selectors.accountDescriptor.menuButton);
- await page.waitToClick(selectors.accountDescriptor.deactivateUser);
- await page.waitToClick(selectors.accountDescriptor.acceptButton);
- message = await page.waitForSnackbar();
-
- expect(message.text).toContain('User deactivated!');
-
- await page.waitToClick(selectors.accountDescriptor.menuButton);
- await page.waitToClick(selectors.accountDescriptor.disableAccount);
- await page.waitToClick(selectors.accountDescriptor.acceptButton);
- message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Account disabled!');
- });
-});
diff --git a/e2e/paths/03-worker/08_add_notes.spec.js b/e2e/paths/03-worker/08_add_notes.spec.js
deleted file mode 100644
index bdc475c90..000000000
--- a/e2e/paths/03-worker/08_add_notes.spec.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import selectors from '../../helpers/selectors';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Worker Add notes path', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('hr', 'worker');
- await page.accessToSearchResult('Bruce Banner');
- await page.accessToSection('worker.card.note.index');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it(`should reach the notes index`, async() => {
- await page.waitForState('worker.card.note.index');
- });
-
- it(`should click on the add note button`, async() => {
- await page.waitToClick(selectors.workerNotes.addNoteFloatButton);
- await page.waitForState('worker.card.note.create');
- });
-
- it(`should create a note`, async() => {
- await page.waitForSelector(selectors.workerNotes.note);
- await page.type(`${selectors.workerNotes.note} textarea`, 'Meeting with Black Widow 21st 9am');
- await page.waitToClick(selectors.workerNotes.saveButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should confirm the note was created', async() => {
- const result = await page.waitToGetProperty(selectors.workerNotes.firstNoteText, 'innerText');
-
- expect(result).toEqual('Meeting with Black Widow 21st 9am');
- });
-});
diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js
index e0f32fc3a..d9689e31a 100644
--- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js
+++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js
@@ -19,7 +19,9 @@ describe('Ticket Edit sale path', () => {
it(`should click on the first sale claim icon to navigate over there`, async() => {
await page.waitToClick(selectors.ticketSales.firstSaleClaimIcon);
- await page.waitForState('claim.card.basicData');
+ await page.waitForNavigation();
+ await page.goBack();
+ await page.goBack();
});
it('should navigate to the tickets index', async() => {
@@ -243,29 +245,13 @@ describe('Ticket Edit sale path', () => {
await page.waitToClick(selectors.ticketSales.moreMenu);
await page.waitToClick(selectors.ticketSales.moreMenuCreateClaim);
await page.waitToClick(selectors.globalItems.acceptButton);
- await page.waitForState('claim.card.basicData');
- });
-
- it('should click on the Claims button of the top bar menu', async() => {
- await page.waitToClick(selectors.globalItems.applicationsMenuButton);
- await page.waitForSelector(selectors.globalItems.applicationsMenuVisible);
- await page.waitToClick(selectors.globalItems.claimsButton);
- await page.waitForState('claim.index');
- });
-
- it('should search for the claim with id 4', async() => {
- await page.accessToSearchResult('4');
- await page.waitForState('claim.card.summary');
- });
-
- it('should click the Tickets button of the top bar menu', async() => {
- await page.waitToClick(selectors.globalItems.applicationsMenuButton);
- await page.waitForSelector(selectors.globalItems.applicationsMenuVisible);
- await page.waitToClick(selectors.globalItems.ticketsButton);
- await page.waitForState('ticket.index');
+ await page.waitForNavigation();
});
it('should search for a ticket then access to the sales section', async() => {
+ await page.goBack();
+ await page.goBack();
+ await page.loginAndModule('salesPerson', 'ticket');
await page.accessToSearchResult('16');
await page.accessToSection('ticket.card.sale');
});
diff --git a/e2e/paths/06-claim/01_basic_data.spec.js b/e2e/paths/06-claim/01_basic_data.spec.js
deleted file mode 100644
index 33c68183f..000000000
--- a/e2e/paths/06-claim/01_basic_data.spec.js
+++ /dev/null
@@ -1,61 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Claim edit basic data path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it(`should log in as claimManager then reach basic data of the target claim`, async() => {
- await page.loginAndModule('claimManager', 'claim');
- await page.accessToSearchResult('1');
- await page.accessToSection('claim.card.basicData');
- });
-
- it(`should edit claim state and observation fields`, async() => {
- await page.autocompleteSearch(selectors.claimBasicData.claimState, 'Resuelto');
- await page.clearInput(selectors.claimBasicData.packages);
- await page.write(selectors.claimBasicData.packages, '2');
- await page.waitToClick(selectors.claimBasicData.saveButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it(`should have been redirected to the next section of claims as the role is claimManager`, async() => {
- await page.waitForState('claim.card.detail');
- });
-
- it('should confirm the claim state was edited', async() => {
- await page.reloadSection('claim.card.basicData');
- await page.waitForSelector(selectors.claimBasicData.claimState);
- const result = await page.waitToGetProperty(selectors.claimBasicData.claimState, 'value');
-
- expect(result).toEqual('Resuelto');
- });
-
- it('should confirm the claim packages was edited', async() => {
- const result = await page
- .waitToGetProperty(selectors.claimBasicData.packages, 'value');
-
- expect(result).toEqual('2');
- });
-
- it(`should edit the claim to leave it untainted`, async() => {
- await page.autocompleteSearch(selectors.claimBasicData.claimState, 'Pendiente');
- await page.clearInput(selectors.claimBasicData.packages);
- await page.write(selectors.claimBasicData.packages, '0');
- await page.waitToClick(selectors.claimBasicData.saveButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-});
diff --git a/e2e/paths/06-claim/03_claim_action.spec.js b/e2e/paths/06-claim/03_claim_action.spec.js
deleted file mode 100644
index ac6f72e37..000000000
--- a/e2e/paths/06-claim/03_claim_action.spec.js
+++ /dev/null
@@ -1,54 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer.js';
-
-describe('Claim action path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('claimManager', 'claim');
- await page.accessToSearchResult('2');
- await page.accessToSection('claim.card.action');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should import the claim', async() => {
- await page.waitToClick(selectors.claimAction.importClaimButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should delete the first line', async() => {
- await page.waitToClick(selectors.claimAction.firstDeleteLine);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should refresh the view to check not have lines', async() => {
- await page.reloadSection('claim.card.action');
- const result = await page.countElement(selectors.claimAction.anyLine);
-
- expect(result).toEqual(0);
- });
-
- it('should check the "is paid with mana" checkbox', async() => {
- await page.waitToClick(selectors.claimAction.isPaidWithManaCheckbox);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should confirm the "is paid with mana" is checked', async() => {
- await page.reloadSection('claim.card.action');
- const isPaidWithManaCheckbox = await page.checkboxState(selectors.claimAction.isPaidWithManaCheckbox);
-
- expect(isPaidWithManaCheckbox).toBe('checked');
- });
-});
diff --git a/e2e/paths/06-claim/04_summary.spec.js b/e2e/paths/06-claim/04_summary.spec.js
deleted file mode 100644
index dda8484a6..000000000
--- a/e2e/paths/06-claim/04_summary.spec.js
+++ /dev/null
@@ -1,96 +0,0 @@
-
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer.js';
-
-describe('Claim summary path', () => {
- let browser;
- let page;
- const claimId = '4';
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should navigate to the target claim summary section', async() => {
- await page.loginAndModule('salesPerson', 'claim');
- await page.accessToSearchResult(claimId);
- await page.waitForState('claim.card.summary');
- });
-
- it(`should display details from the claim and it's client on the top of the header`, async() => {
- await page.waitForTextInElement(selectors.claimSummary.header, 'Tony Stark');
- const result = await page.waitToGetProperty(selectors.claimSummary.header, 'innerText');
-
- expect(result).toContain('4 -');
- expect(result).toContain('Tony Stark');
- });
-
- it('should display the claim state', async() => {
- const result = await page.waitToGetProperty(selectors.claimSummary.state, 'innerText');
-
- expect(result).toContain('Resuelto');
- });
-
- it('should display the observation', async() => {
- const result = await page.waitToGetProperty(selectors.claimSummary.observation, 'innerText');
-
- expect(result).toContain('Wisi forensibus mnesarchum in cum. Per id impetus abhorreant');
- });
-
- it('should display the claimed line(s)', async() => {
- const result = await page.waitToGetProperty(selectors.claimSummary.firstSaleItemId, 'innerText');
-
- expect(result).toContain('2');
- });
-
- it(`should click on the first sale ID making the item descriptor visible`, async() => {
- const firstItem = selectors.claimSummary.firstSaleItemId;
- await page.evaluate(selectors => {
- document.querySelector(selectors).scrollIntoView();
- }, firstItem);
- await page.click(firstItem);
- await page.waitImgLoad(selectors.claimSummary.firstSaleDescriptorImage);
- const visible = await page.isVisible(selectors.claimSummary.itemDescriptorPopover);
-
- expect(visible).toBeTruthy();
- });
-
- it(`should check the url for the item diary link of the descriptor is for the right item id`, async() => {
- await page.waitForSelector(selectors.claimSummary.itemDescriptorPopoverItemDiaryButton, {visible: true});
-
- await page.closePopup();
- });
-
- it('should display the claim development details', async() => {
- const result = await page.waitToGetProperty(selectors.claimSummary.firstDevelopmentWorker, 'innerText');
-
- expect(result).toContain('salesAssistantNick');
- });
-
- it(`should click on the first development worker making the worker descriptor visible`, async() => {
- await page.waitToClick(selectors.claimSummary.firstDevelopmentWorker);
-
- const visible = await page.isVisible(selectors.claimSummary.firstDevelopmentWorkerGoToClientButton);
-
- expect(visible).toBeTruthy();
- });
-
- it(`should check the url for the go to clientlink of the descriptor is for the right client id`, async() => {
- await page.waitForSelector(selectors.claimSummary.firstDevelopmentWorkerGoToClientButton, {visible: true});
-
- await page.closePopup();
- });
-
- it(`should click on the first action ticket ID making the ticket descriptor visible`, async() => {
- await page.waitToClick(selectors.claimSummary.firstActionTicketId);
- await page.waitForSelector(selectors.claimSummary.firstActionTicketDescriptor);
- const visible = await page.isVisible(selectors.claimSummary.firstActionTicketDescriptor);
-
- expect(visible).toBeTruthy();
- });
-});
diff --git a/e2e/paths/06-claim/05_descriptor.spec.js b/e2e/paths/06-claim/05_descriptor.spec.js
deleted file mode 100644
index 49912b26a..000000000
--- a/e2e/paths/06-claim/05_descriptor.spec.js
+++ /dev/null
@@ -1,58 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer.js';
-
-describe('Claim descriptor path', () => {
- let browser;
- let page;
- const claimId = '1';
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should now navigate to the target claim summary section', async() => {
- await page.loginAndModule('salesPerson', 'claim');
- await page.accessToSearchResult(claimId);
- await page.waitForState('claim.card.summary');
- });
-
- it(`should not be able to see the delete claim button of the descriptor more menu`, async() => {
- await page.waitToClick(selectors.claimDescriptor.moreMenu);
- await page.waitForSelector(selectors.claimDescriptor.moreMenuDeleteClaim, {hidden: true});
- });
-
- it(`should log in as claimManager and navigate to the target claim`, async() => {
- await page.loginAndModule('claimManager', 'claim');
- await page.accessToSearchResult(claimId);
- await page.waitForState('claim.card.summary');
- });
-
- it(`should be able to see the delete claim button of the descriptor more menu`, async() => {
- await page.waitToClick(selectors.claimDescriptor.moreMenu);
- await page.waitForSelector(selectors.claimDescriptor.moreMenuDeleteClaim, {visible: true});
- });
-
- it(`should delete the claim`, async() => {
- await page.waitToClick(selectors.claimDescriptor.moreMenuDeleteClaim);
- await page.waitToClick(selectors.claimDescriptor.acceptDeleteClaim);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Claim deleted!');
- });
-
- it(`should have been relocated to the claim index`, async() => {
- await page.waitForState('claim.index');
- });
-
- it(`should search for the deleted claim to find no results`, async() => {
- await page.doSearch(claimId);
- const nResults = await page.countElement(selectors.claimsIndex.searchResult);
-
- expect(nResults).toEqual(0);
- });
-});
diff --git a/e2e/paths/06-claim/06_note.spec.js b/e2e/paths/06-claim/06_note.spec.js
deleted file mode 100644
index 830f77cbe..000000000
--- a/e2e/paths/06-claim/06_note.spec.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import selectors from '../../helpers/selectors';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Claim Add note path', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('salesPerson', 'claim');
- await page.accessToSearchResult('2');
- await page.accessToSection('claim.card.note.index');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it(`should reach the claim note index`, async() => {
- await page.waitForState('claim.card.note.index');
- });
-
- it(`should click on the add new note button`, async() => {
- await page.waitToClick(selectors.claimNote.addNoteFloatButton);
- await page.waitForState('claim.card.note.create');
- });
-
- it(`should create a new note`, async() => {
- await page.waitForSelector(selectors.claimNote.note);
- await page.type(`${selectors.claimNote.note} textarea`, 'The delivery was unsuccessful');
- await page.waitToClick(selectors.claimNote.saveButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it(`should redirect back to the claim notes page`, async() => {
- await page.waitForState('claim.card.note.index');
- });
-
- it('should confirm the note was created', async() => {
- const result = await page.waitToGetProperty(selectors.claimNote.firstNoteText, 'innerText');
-
- expect(result).toEqual('The delivery was unsuccessful');
- });
-});
diff --git a/e2e/paths/08-route/01_summary.spec.js b/e2e/paths/08-route/01_summary.spec.js
deleted file mode 100644
index 44f66ba2d..000000000
--- a/e2e/paths/08-route/01_summary.spec.js
+++ /dev/null
@@ -1,62 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Route summary path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('employee', 'route');
- await page.waitToClick(selectors.routeIndex.previewButton);
- await page.waitToClick(selectors.routeSummary.goToRouteSummaryButton);
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should reach the first route summary section', async() => {
- await page.waitForState('route.card.summary');
- });
-
- it(`should display details from the route on the header`, async() => {
- await page.waitForTextInElement(selectors.routeSummary.header, 'first route');
- const result = await page.waitToGetProperty(selectors.routeSummary.header, 'innerText');
-
- expect(result).toContain('first route');
- });
-
- it('should display some route details like the cost', async() => {
- const result = await page.waitToGetProperty(selectors.routeSummary.cost, 'innerText');
-
- expect(result).toContain('€10.00');
- });
-
- it('should click on the first ticket ID making the descriptor popover visible', async() => {
- await page.waitForState('route.card.summary');
- await page.waitForTimeout(250);
- await page.waitToClick(selectors.routeSummary.firstTicketID);
- await page.waitForSelector(selectors.routeSummary.firstTicketDescriptor);
- const visible = await page.isVisible(selectors.routeSummary.firstTicketDescriptor);
-
- expect(visible).toBe(true);
- });
-
- it('should close the ticket descriptor', async() => {
- await page.closePopup();
- });
-
- it('should click on the first alias making the client descriptor popover visible', async() => {
- await page.waitToClick(selectors.routeSummary.firstAlias);
- await page.waitForSelector(selectors.routeSummary.firstClientDescriptor);
- const visible = await page.isVisible(selectors.routeSummary.firstClientDescriptor);
-
- expect(visible).toBe(true);
- });
-
- it('should close the client descriptor', async() => {
- await page.closePopup();
- });
-});
diff --git a/e2e/paths/08-route/02_basic_data.spec.js b/e2e/paths/08-route/02_basic_data.spec.js
deleted file mode 100644
index 7ab7dda42..000000000
--- a/e2e/paths/08-route/02_basic_data.spec.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Route basic Data path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('delivery', 'route');
- await page.accessToSearchResult('1');
- await page.accessToSection('route.card.basicData');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should edit the route basic data and confirm the route was edited', async() => {
- const nextMonth = Date.vnNew();
- nextMonth.setMonth(nextMonth.getMonth() + 1);
- nextMonth.setUTCHours(0, 0, 0, 0);
-
- const form = 'vn-route-basic-data form';
- const values = {
- worker: 'adminBossNick',
- vehicle: '1111-IMK',
- created: nextMonth,
- kmStart: 1,
- kmEnd: 2,
- started: '08:00',
- finished: '12:30',
- };
-
- const message = await page.sendForm(form, values);
- await page.reloadSection('route.card.basicData');
- const formValues = await page.fetchForm(form, Object.keys(values));
-
- expect(message.isSuccess).toBeTrue();
- expect(formValues).toEqual(values);
- });
-});
diff --git a/e2e/paths/08-route/03_create_and_clone.spec.js b/e2e/paths/08-route/03_create_and_clone.spec.js
deleted file mode 100644
index 31c0cfc18..000000000
--- a/e2e/paths/08-route/03_create_and_clone.spec.js
+++ /dev/null
@@ -1,91 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Route create path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('employee', 'route');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- describe('as employee', () => {
- it('should click on the add new route button and open the creation form', async() => {
- await page.waitToClick(selectors.routeIndex.addNewRouteButton);
- await page.waitForState('route.create');
- });
-
- it(`should attempt to create a new route but fail since employee has no access rights`, async() => {
- await page.write(selectors.createRouteView.description, 'faster faster!!');
- await page.waitToClick(selectors.createRouteView.submitButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Access Denied');
- });
- });
-
- describe('as delivery', () => {
- beforeAll(async() => {
- await page.login('delivery');
- await page.selectModule('route');
- });
-
- it('should again click on the add new route button and open the creation form', async() => {
- await page.waitToClick(selectors.routeIndex.addNewRouteButton);
- await page.waitForState('route.create');
- });
-
- it(`should create a new route`, async() => {
- await page.autocompleteSearch(selectors.createRouteView.worker, 'teamManagerNick');
- await page.pickDate(selectors.createRouteView.createdDatePicker);
- await page.autocompleteSearch(selectors.createRouteView.vehicleAuto, '4444-IMK');
- await page.autocompleteSearch(selectors.createRouteView.agency, 'Teleportation device');
- await page.write(selectors.createRouteView.description, 'faster faster!!');
- await page.waitToClick(selectors.createRouteView.submitButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it(`should confirm the redirection to the created route summary`, async() => {
- await page.waitForState('route.card.summary');
- });
-
- it(`should navigate back to the route index`, async() => {
- await page.waitToClick(selectors.globalItems.returnToModuleIndexButton);
- await page.waitForState('route.index');
- });
-
- let count;
- it(`should count the amount of routes before clonation`, async() => {
- await page.waitForFunction(selector => {
- return document.querySelectorAll(selector).length > 6;
- }, {}, selectors.routeIndex.anyResult);
- count = await page.countElement(selectors.routeIndex.anyResult);
-
- expect(count).toBeGreaterThanOrEqual(7);
- });
-
- it(`should clone the first route`, async() => {
- await page.waitToClick(selectors.routeIndex.firstRouteCheckbox);
- await page.waitToClick(selectors.routeIndex.cloneButton);
- await page.waitToClick(selectors.routeIndex.submitClonationButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it(`should reload the section and count the amount of routes after clonation`, async() => {
- await page.waitForNumberOfElements(selectors.routeIndex.anyResult, count + 1);
- const result = await page.countElement(selectors.routeIndex.anyResult);
-
- expect(result).toEqual(count + 1);
- });
- });
-});
diff --git a/e2e/paths/08-route/04_tickets.spec.js b/e2e/paths/08-route/04_tickets.spec.js
deleted file mode 100644
index c890162a1..000000000
--- a/e2e/paths/08-route/04_tickets.spec.js
+++ /dev/null
@@ -1,59 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Route tickets path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('delivery', 'route');
- await page.accessToSearchResult('2');
- await page.accessToSection('route.card.tickets');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should modify the first ticket priority', async() => {
- await page.writeOnEditableTD(selectors.routeTickets.firstTicketPriority, '9');
- await page.keyboard.press('Enter');
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should confirm the buscaman button is disabled', async() => {
- await page.waitForSelector(`${selectors.routeTickets.buscamanButton}.disabled`);
- });
-
- it('should check the first ticket checkbox and confirm the buscamanButton button is no longer disabled', async() => {
- await page.waitForSelector(`${selectors.routeTickets.buscamanButton}.disabled`, {visible: false});
- });
-
- it('should check the route volume on the descriptor', async() => {
- const result = await page.waitToGetProperty(selectors.routeDescriptor.volume, 'innerText');
-
- expect(result).toEqual('0.2 / 50 m³');
- });
-
- it('should count how many tickets are in route', async() => {
- const result = await page.countElement(selectors.routeTickets.anyTicket);
-
- expect(result).toEqual(1);
- });
-
- it('should delete the first ticket in route', async() => {
- await page.waitToClick(selectors.routeTickets.firstTicketDeleteButton);
- await page.waitToClick(selectors.routeTickets.confirmButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Ticket removed from route');
- });
-
- it('should now count how many tickets are in route to find one less', async() => {
- await page.waitForNumberOfElements(selectors.routeTickets.anyTicket, 0);
- });
-});
diff --git a/e2e/tests.js b/e2e/tests.js
index 829056f4c..a9c662dc4 100644
--- a/e2e/tests.js
+++ b/e2e/tests.js
@@ -41,7 +41,6 @@ async function test() {
`./e2e/paths/03*/*[sS]pec.js`,
`./e2e/paths/04*/*[sS]pec.js`,
`./e2e/paths/05*/*[sS]pec.js`,
- `./e2e/paths/06*/*[sS]pec.js`,
`./e2e/paths/07*/*[sS]pec.js`,
`./e2e/paths/08*/*[sS]pec.js`,
`./e2e/paths/09*/*[sS]pec.js`,
diff --git a/front/salix/routes.js b/front/salix/routes.js
index be210b749..2c6f1b848 100644
--- a/front/salix/routes.js
+++ b/front/salix/routes.js
@@ -4,7 +4,17 @@ import getMainRoute from 'core/lib/get-main-route';
config.$inject = ['$stateProvider', '$urlRouterProvider'];
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider
- .otherwise('/');
+ .otherwise(async($injector, {$location}) => {
+ const prefix = '#!';
+ if (!$location.$$path) return window.location.href = `/${prefix}/`;
+
+ const url = $location.$$absUrl
+ .replace('5000', '9000')
+ .replace('salix', 'lilium')
+ .replace(prefix, '#')
+ .replace('client', 'customer');
+ window.location.href = url;
+ });
$stateProvider
.state('layout', {
diff --git a/loopback/locale/en.json b/loopback/locale/en.json
index 382a2824c..06538a524 100644
--- a/loopback/locale/en.json
+++ b/loopback/locale/en.json
@@ -233,5 +233,7 @@
"It has been invoiced but the PDF could not be generated": "It has been invoiced but the PDF could not be generated",
"It has been invoiced but the PDF of refund not be generated": "It has been invoiced but the PDF of refund not be generated",
"Cannot add holidays on this day": "Cannot add holidays on this day",
- "Cannot send mail": "Cannot send mail"
+ "Cannot send mail": "Cannot send mail",
+ "CONSTRAINT `chkParkingCodeFormat` failed for `vn`.`parking`": "CONSTRAINT `chkParkingCodeFormat` failed for `vn`.`parking`",
+ "This postcode already exists": "This postcode already exists"
}
\ No newline at end of file
diff --git a/loopback/locale/es.json b/loopback/locale/es.json
index e2be5d013..e1f7fd655 100644
--- a/loopback/locale/es.json
+++ b/loopback/locale/es.json
@@ -367,5 +367,7 @@
"It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono",
"Payment method is required": "El método de pago es obligatorio",
"Cannot send mail": "Não é possível enviar o email",
- "CONSTRAINT `supplierAccountTooShort` failed for `vn`.`supplier`": "La cuenta debe tener exactamente 10 dígitos"
-}
+ "CONSTRAINT `supplierAccountTooShort` failed for `vn`.`supplier`": "La cuenta debe tener exactamente 10 dígitos",
+ "The sale not exists in the item shelving": "La venta no existe en la estantería del artículo",
+ "The entry not have stickers": "La entrada no tiene etiquetas"
+}
\ No newline at end of file
diff --git a/modules/claim/front/action/index.html b/modules/claim/front/action/index.html
deleted file mode 100644
index 9da51b8de..000000000
--- a/modules/claim/front/action/index.html
+++ /dev/null
@@ -1,188 +0,0 @@
-
-
-
-
-
-
-
-
-
- Id
- Ticket
-
- Destination
-
-
- Landed
-
-
- Quantity
-
-
- Description
-
-
- Price
-
-
- Disc.
-
- Total
-
-
-
-
-
-
-
-
-
-
-
- {{::saleClaimed.landed | date: 'dd/MM/yyyy'}}
- {{::saleClaimed.quantity}}
- {{::saleClaimed.concept}}
- {{::saleClaimed.price | currency: 'EUR':2}}
- {{::saleClaimed.discount}} %
- {{saleClaimed.total | currency: 'EUR':2}}
-
-
- {{$ctrl.$t('Change destination to all selected rows', {total: $ctrl.checked.length})}}
-
Total claimed price
-{{$ctrl.newPrice | currency: 'EUR':2}} -
-- Id - | -- Client - | -- Created - | -- Worker - | -- State - | -- |
---|---|---|---|---|---|
{{::claim.id}} | -- - {{::claim.clientName}} - - | -{{::claim.created | date:'dd/MM/yyyy'}} | -- - {{::claim.workerName}} - - | -- - {{::claim.stateDescription}} - - | -
- |
-
- |
- - Id - | -- Date - | -- Agency route - | -- Agency Agreement - | -- Packages - | -- M3 - | -- Km - | -- Price - | -- Received - | -- Autonomous - | -- |
---|---|---|---|---|---|---|---|---|---|---|---|
- |
- - - {{::agencyTerm.routeFk}} - - | -{{::agencyTerm.created | date:'dd/MM/yyyy'}} | -{{::agencyTerm.agencyModeName | dashIfEmpty}} | -{{::agencyTerm.agencyAgreement | dashIfEmpty}} | -{{::agencyTerm.packages | dashIfEmpty}} | -{{::agencyTerm.m3 | dashIfEmpty}} | -{{::agencyTerm.kmTotal | dashIfEmpty}} | -{{::agencyTerm.price | dashIfEmpty}} | -- - {{::agencyTerm.invoiceInFk}} - - | -- - {{::agencyTerm.supplierName}} - - | -
- |
-
- |
- - Id - | -- Worker - | -- Agency - | -- Vehicle - | -- Date - | -- m³ - | -- Description - | -- Hour started - | -- Hour finished - | -- |
---|---|---|---|---|---|---|---|---|---|---|
- |
- {{::route.id | dashIfEmpty}} | -
- {{name}} - {{nickname}}
- |
-
- |
-
- |
-
- |
- {{::route.m3 | dashIfEmpty}} | -
- |
-
- |
-
- |
-
- |
-