diff --git a/back/Dockerfile b/back/Dockerfile index 363192a0b..0f75f6949 100644 --- a/back/Dockerfile +++ b/back/Dockerfile @@ -32,8 +32,7 @@ RUN apt-get update \ RUN apt-get update \ && apt-get install -y --no-install-recommends \ samba-common-bin samba-dsdb-modules\ - && rm -rf /var/lib/apt/lists/* \ - && npm -g install pm2 + && rm -rf /var/lib/apt/lists/* # Salix @@ -55,7 +54,4 @@ COPY \ README.md \ ./ -CMD ["pm2-runtime", "./back/process.yml"] - -HEALTHCHECK --interval=15s --timeout=10s \ - CMD curl -f http://localhost:3000/api/Applications/status || exit 1 +CMD ["node", "--tls-min-v1.0", "--openssl-legacy-provider", "./loopback/server/server.js"] \ No newline at end of file diff --git a/back/methods/dms/updateFile.js b/back/methods/dms/updateFile.js index cfc4c322f..68149ef62 100644 --- a/back/methods/dms/updateFile.js +++ b/back/methods/dms/updateFile.js @@ -38,7 +38,7 @@ module.exports = Self => { { arg: 'hasFile', type: 'Boolean', - description: 'True if has an attached file' + description: 'True if has the original in paper' }, { arg: 'hasFileAttached', diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js index 56d206529..98aa8be39 100644 --- a/back/methods/mrw-config/cancelShipment.js +++ b/back/methods/mrw-config/cancelShipment.js @@ -39,6 +39,9 @@ module.exports = Self => { const xmlString = response.data; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); + + await Self.rawSql('CALL util.debugAdd(?,?);', ['cancelShipment', xmlDoc]); + const result = xmlDoc.getElementsByTagName('Mensaje')[0].textContent; return result.toLowerCase().includes('se ha cancelado correctamente'); }; diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js index 8f1bb54c1..8941916ec 100644 --- a/back/methods/vn-user/specs/renew-token.spec.js +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -72,9 +72,9 @@ describe('Renew Token', () => { } expect(error).toBeDefined(); - const query = 'SELECT * FROM util.debug'; - const debugLog = await models.Application.rawSql(query, null); + const query = 'SELECT * FROM util.debug WHERE variable = "renewToken"'; + const debugLog = await models.Application.rawSql(query); expect(debugLog.length).toEqual(1); }); diff --git a/back/model-config.json b/back/model-config.json index 20bfb06bd..b6d304675 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -175,6 +175,9 @@ "PrintConfig": { "dataSource": "vn" }, + "QueueMember": { + "dataSource": "vn" + }, "ViaexpressConfig": { "dataSource": "vn" }, diff --git a/back/models/autonomy.json b/back/models/autonomy.json index 8c9d82936..214061cf5 100644 --- a/back/models/autonomy.json +++ b/back/models/autonomy.json @@ -16,6 +16,10 @@ "name": { "type": "string", "required": true + }, + "hasDailyInvoice": { + "type": "boolean", + "description": "Indicates if the autonomy has daily invoice enabled" } }, "relations": { @@ -40,4 +44,4 @@ "permission": "ALLOW" } ] -} \ No newline at end of file +} diff --git a/back/models/country.json b/back/models/country.json index 5b9d842a8..80d456702 100644 --- a/back/models/country.json +++ b/back/models/country.json @@ -28,6 +28,10 @@ }, "continentFk": { "type": "number" + }, + "hasDailyInvoice": { + "type": "boolean", + "description": "Indicates if the autonomy has daily invoice enabled" } }, "relations": { diff --git a/back/models/province.json b/back/models/province.json index 77e0b24a6..61a1574d7 100644 --- a/back/models/province.json +++ b/back/models/province.json @@ -16,6 +16,9 @@ "name": { "type": "string", "required": true + }, + "autonomyFk": { + "type": "number" } }, "relations": { @@ -55,4 +58,4 @@ "permission": "ALLOW" } ] -} \ No newline at end of file +} diff --git a/back/models/queue-member.json b/back/models/queue-member.json new file mode 100644 index 000000000..93ca2ebd7 --- /dev/null +++ b/back/models/queue-member.json @@ -0,0 +1,38 @@ +{ + "name": "QueueMember", + "base": "VnModel", + "options": { + "mysql": { + "table": "pbx.queueMember" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "queue": { + "type": "string" + }, + "extension": { + "type": "string" + } + }, + "relations": { + "queueRelation": { + "type": "belongsTo", + "model": "Queue", + "foreignKey": "queue", + "primaryKey": "name" + } + }, + "acls": [ + { + "property": "*", + "accessType": "READ", + "principalType": "ROLE", + "principalId": "employee", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/back/process.yml b/back/process.yml deleted file mode 100644 index 94072b57d..000000000 --- a/back/process.yml +++ /dev/null @@ -1,7 +0,0 @@ -apps: - - script: ./loopback/server/server.js - name: salix-back - instances: 1 - max_restarts: 0 - autorestart: false - node_args: --tls-min-v1.0 --openssl-legacy-provider diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index ca254055b..d0824e392 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -4,7 +4,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','11278','fe10f03459a153fc213bf64e352804c043f94590','2024-10-03 07:47:47','11281'); +INSERT INTO `version` VALUES ('vn-database','11311','315864403260623fede9f0471ef3d9036faf23b1','2024-11-12 08:00:59','11336'); 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); @@ -988,6 +988,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','11194','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11195','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11196','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-18 07:28:14',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11197','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11198','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:49',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11201','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-27 13:04:26',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11204','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11205','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-04 13:54:55',NULL,NULL); @@ -1013,6 +1014,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','11225','01-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11225','02-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11227','00-addWorkerTimeControlMailAcl.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11229','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-16 08:24:17',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11230','00-addClientObservationType.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:52',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11234','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:42',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11235','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11236','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); @@ -1021,18 +1023,53 @@ INSERT INTO `versionLog` VALUES ('vn-database','11237','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11239','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 12:57:06',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11240','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11241','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-20 09:08:25',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11242','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:52',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11246','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-18 12:39:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11247','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-19 12:10:08',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11248','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-23 11:12:17',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11249','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11251','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:43:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11251','01-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:57:30',NULL,'Connection lost: The server closed the connection.'); INSERT INTO `versionLog` VALUES ('vn-database','11253','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-20 14:41:27',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11254','00-thermographTemperature.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11254','01-thermographFk.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11255','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11256','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-23 12:18:24',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11258','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11260','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11261','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11262','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11263','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-27 12:05:32',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11264','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11271','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11272','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11273','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 10:50:51',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:16',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript2.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:29',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript3.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:30',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript5.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:35',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript6.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:35',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript7.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11277','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11278','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11279','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-10-02 08:05:24',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11280','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-02 08:46:50',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11281','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11283','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11284','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11285','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11287','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11288','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-10 08:26:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11289','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-15 07:01:33',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11290','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11291','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-17 09:10:30',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11294','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11295','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-10 08:45:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11298','00-closure.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11300','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-18 08:27:05',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11302','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:57',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11308','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-23 12:41:55',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11311','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:57',NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -1407,6 +1444,8 @@ INSERT INTO `roleInherit` VALUES (376,124,21,19336); INSERT INTO `roleInherit` VALUES (377,47,49,19295); INSERT INTO `roleInherit` VALUES (378,101,15,19294); INSERT INTO `roleInherit` VALUES (379,103,121,19294); +INSERT INTO `roleInherit` VALUES (381,119,123,19295); +INSERT INTO `roleInherit` VALUES (382,48,72,783); INSERT INTO `userPassword` VALUES (1,7,1,0,2,1); @@ -2175,7 +2214,6 @@ INSERT INTO `ACL` VALUES (892,'WorkerIncome','*','*','ALLOW','ROLE','hr',NULL); INSERT INTO `ACL` VALUES (893,'PayrollComponent','*','*','ALLOW','ROLE','hr',NULL); INSERT INTO `ACL` VALUES (894,'Worker','__get__incomes','*','ALLOW','ROLE','hr',NULL); INSERT INTO `ACL` VALUES (895,'ItemShelvingLog','*','READ','ALLOW','ROLE','production',NULL); -INSERT INTO `ACL` VALUES (897,'WorkerLog','*','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (901,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','system',NULL); INSERT INTO `ACL` VALUES (902,'Entry','filter','READ','ALLOW','ROLE','supplier',NULL); INSERT INTO `ACL` VALUES (903,'Entry','getBuys','READ','ALLOW','ROLE','supplier',NULL); @@ -2191,7 +2229,6 @@ INSERT INTO `ACL` VALUES (912,'Worker','__get__medicalReview','*','ALLOW','ROLE' INSERT INTO `ACL` VALUES (913,'VnToken','*','READ','ALLOW','ROLE','developer',10578); INSERT INTO `ACL` VALUES (914,'VnToken','killSession','*','ALLOW','ROLE','developer',10578); INSERT INTO `ACL` VALUES (915,'ACL','*','WRITE','ALLOW','ROLE','developerBoss',10578); -INSERT INTO `ACL` VALUES (916,'Entry','getBuysCsv','READ','ALLOW','ROLE','supplier',10578); INSERT INTO `ACL` VALUES (917,'InvoiceOut','refundAndInvoice','WRITE','ALLOW','ROLE','administrative',10578); INSERT INTO `ACL` VALUES (918,'Worker','__get__descriptor','READ','ALLOW','ROLE','employee',10578); INSERT INTO `ACL` VALUES (919,'Worker','findById','READ','ALLOW','ROLE','employee',10578); @@ -2213,6 +2250,7 @@ INSERT INTO `ACL` VALUES (935,'BankEntity','*','WRITE','ALLOW','ROLE','financial INSERT INTO `ACL` VALUES (936,'Device','handleUser','*','ALLOW','ROLE','employee',10578); INSERT INTO `ACL` VALUES (937,'WorkerTimeControlMail','count','READ','ALLOW','ROLE','employee',10578); INSERT INTO `ACL` VALUES (938,'Worker','__get__mail','READ','ALLOW','ROLE','hr',10578); +INSERT INTO `ACL` VALUES (939,'Machine','*','*','ALLOW','ROLE','productionBoss',10578); INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'); INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee'); @@ -2408,6 +2446,8 @@ INSERT INTO `claimResponsible` VALUES (22,'Paletizadores',0,'pal'); INSERT INTO `claimResponsible` VALUES (23,'Preparación Previa',0,'pre'); INSERT INTO `claimResponsible` VALUES (24,'Almacén PCA',0,'war'); INSERT INTO `claimResponsible` VALUES (25,'Huelga',0,'str'); +INSERT INTO `claimResponsible` VALUES (27,'Prep. por caja',0,''); +INSERT INTO `claimResponsible` VALUES (45,'Negativo',0,'neg'); INSERT INTO `claimReason` VALUES (1,'Prisas',0); INSERT INTO `claimReason` VALUES (2,'Novato',0); @@ -2450,6 +2490,9 @@ INSERT INTO `claimReason` VALUES (52,'Mala gestión comercial',0); INSERT INTO `claimReason` VALUES (53,'Mala gestión comprador',0); INSERT INTO `claimReason` VALUES (54,'A2',0); INSERT INTO `claimReason` VALUES (55,'Entrega 48h o más',0); +INSERT INTO `claimReason` VALUES (56,'Error cliente',0); +INSERT INTO `claimReason` VALUES (57,'A2/B1',0); +INSERT INTO `claimReason` VALUES (58,'Seguro',0); INSERT INTO `claimRedelivery` VALUES (1,'Cliente'); INSERT INTO `claimRedelivery` VALUES (2,'No dev./No especif.'); @@ -2457,6 +2500,7 @@ INSERT INTO `claimRedelivery` VALUES (3,'Reparto'); INSERT INTO `claimRedelivery` VALUES (4,'Agencia'); INSERT INTO `claimRedelivery` VALUES (5,'Tour'); INSERT INTO `claimRedelivery` VALUES (6,'Fuera Peninsula'); +INSERT INTO `claimRedelivery` VALUES (7,'Francia'); INSERT INTO `claimResult` VALUES (1,'Otros daños'); INSERT INTO `claimResult` VALUES (2,'Roces'); @@ -2534,39 +2578,39 @@ INSERT INTO `continent` VALUES (3,'África','AF'); INSERT INTO `continent` VALUES (4,'Europa','EU'); INSERT INTO `continent` VALUES (5,'Oceanía','OC'); -INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,114,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,116,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (22,'shopping','COMPRAS',2,5,NULL,72,0,0,1,1,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (23,'CMA','CAMARA',15,16,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,'PREVIOUS'); -INSERT INTO `department` VALUES (31,'it','INFORMATICA',6,7,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (34,'accounting','CONTABILIDAD',8,9,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (35,'finance','FINANZAS',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (36,'labor','LABORAL',12,13,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (31,'it','INFORMATICA',6,7,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (34,'accounting','CONTABILIDAD',8,9,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (35,'finance','FINANZAS',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (36,'labor','LABORAL',12,13,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',14,37,NULL,72,1,1,1,11,1,'/1/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,NULL); -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,'ON_PREPARATION'); +INSERT INTO `department` VALUES (38,'picking','SACADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,1,NULL,NULL,NULL,'ON_PREPARATION'); 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,'PACKING'); -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,73,NULL,0,0,0,1,16,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (44,'management','GERENCIA',74,75,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',76,77,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',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'DELIVERY'); -INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',80,81,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'STORAGE'); -INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',86,87,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',38,39,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (43,'VT','VENTAS',40,75,NULL,0,0,0,1,17,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (44,'management','GERENCIA',76,77,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',78,79,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',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'DELIVERY'); +INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',82,83,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'STORAGE'); +INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',86,87,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',88,89,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (55,NULL,'TALLER NATURAL',21,22,14548,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1118,NULL,NULL,NULL); INSERT INTO `department` VALUES (56,NULL,'TALLER ARTIFICIAL',23,24,8470,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1927,NULL,NULL,NULL); -INSERT INTO `department` VALUES (58,'CMP','CAMPOS',88,91,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'FIELD'); -INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',92,93,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',43,44,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,1,1,0,0,NULL,NULL,NULL,'CLAIM'); -INSERT INTO `department` VALUES (61,NULL,'VNH',94,97,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (58,'CMP','CAMPOS',90,93,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'FIELD'); +INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',94,95,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',43,44,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'CLAIM'); +INSERT INTO `department` VALUES (61,NULL,'VNH',96,99,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',100,101,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (68,NULL,'COMPLEMENTOS',25,26,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',100,101,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',102,103,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (80,'spainTeam5','EQUIPO ESPAÑA 5',45,46,4250,0,0,0,2,0,43,'/1/43/','es5_equipo',1,'es5@verdnatura.es',0,0,0,0,NULL,NULL,'5300',NULL); -INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',102,103,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (89,NULL,'COORDINACION',104,105,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (90,NULL,'TRAILER',95,96,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',104,105,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (89,NULL,'COORDINACION',106,107,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (90,NULL,'TRAILER',97,98,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (91,'artificial','ARTIFICIAL',27,28,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'PREVIOUS'); INSERT INTO `department` VALUES (92,NULL,'EQUIPO SILVERIO',47,48,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',49,50,3797,0,0,0,2,0,43,'/1/43/','es2_equipo',1,'es2@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL); @@ -2574,23 +2618,24 @@ INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',51,52,24065, INSERT INTO `department` VALUES (96,NULL,'EQUIPO C LOPEZ',53,54,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (115,NULL,'EQUIPO CLAUDI',55,56,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (123,NULL,'EQUIPO ELENA BASCUÑANA',57,58,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',106,107,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',108,109,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',59,60,1118,0,0,0,2,0,43,'/1/43/','es3_equipo',1,'es3@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL); INSERT INTO `department` VALUES (126,NULL,'PRESERVADO',29,30,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (128,NULL,'PALETIZADO',31,32,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'PALLETIZING'); INSERT INTO `department` VALUES (130,NULL,'REVISION',33,34,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'ON_CHECKING'); -INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',89,90,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',91,92,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',61,62,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',63,64,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL); INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',65,66,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL); -INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',108,109,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',110,111,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (137,'sorter','SORTER',112,113,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',110,111,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',112,113,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (137,'sorter','SORTER',114,115,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',67,68,3803,0,0,0,2,0,43,'/1/43/','es4_equipo',1,'es4@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL); -INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',69,70,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (140,'internationalTeam','EQUIPO INTERNACIONAL',69,70,33320,0,0,0,2,0,43,'/1/43/','int_equipo',1,'international@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (141,NULL,'PREVIA',35,36,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'PREVIOUS'); INSERT INTO `department` VALUES (146,NULL,'VERDNACOLOMBIA',3,4,NULL,72,0,0,2,0,22,'/1/22/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (147,'spainTeamAsia','EQUIPO ESPAÑA ASIA',71,72,40214,0,0,0,2,0,43,'/1/43/','esA_equipo',0,'esA@verdnatura.es',0,0,0,0,NULL,NULL,'5500',NULL); +INSERT INTO `department` VALUES (148,NULL,'CAPTATION FRANCIA',73,74,NULL,0,0,0,2,0,43,'/1/43/',NULL,0,NULL,0,0,0,0,NULL,NULL,'6000',NULL); INSERT INTO `docuware` VALUES (1,'deliveryNote','Albaranes cliente','find','find','N__ALBAR_N',NULL); INSERT INTO `docuware` VALUES (2,'deliveryNote','Albaranes cliente','store','Archivar','N__ALBAR_N',NULL); diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index 66e553763..486bec661 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -502,7 +502,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','receipt','alexm@%','0000- INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visitUser','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','referenceRate','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','report','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','cache','productionBoss','available','guillermo@10.5.1.2','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerAssistant','producer','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','time','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','role','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','config__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -605,7 +605,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','project','jua INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','productionConfig','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','productionConfig','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','creditInsurance','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','cache','productionBoss','visible','guillermo@10.5.1.2','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','errorProduction__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','invoiceOut','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','coolerAssist','Tickets','alexm@%','0000-00-00 00:00:00','Update',''); @@ -792,7 +791,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','Movimientos','alexm@% INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','buy','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','itemMinimumQuantity','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','receipt','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','producer','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','link','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','link','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','delivery','vehicle','alexm@%','0000-00-00 00:00:00','Select',''); @@ -971,7 +969,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','officeBoss','ticketPackagingSt INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerRelatives','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierPackaging','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerDocument','alexm@%','0000-00-00 00:00:00','Select,Insert',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierContact','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceCorrection','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ink','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','zone','alexm@%','0000-00-00 00:00:00','Select',''); @@ -1471,9 +1469,31 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','tillSerial',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','stockBuyed','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','alertLevel','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerActivityType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','priceDelta','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','priceDelta','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','parkingLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','travelLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','supplierContact','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerDms','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','itemLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','account','developer','user','juan@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimReason','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimResponsible','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimResult','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimRedelivery','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','producer','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemStateTag','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','material','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','saleUnit','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','origin','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','itemType','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','delivery','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemFarmingTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemWrappingTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemLanguageTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemStemTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemBaseTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemBreederTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemShelvingLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; @@ -1853,7 +1873,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_getVolumeByE INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_getVolumeByEntry','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entry_moveNotPrinted','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getVolume','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockbuyedbyworker','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getsplit','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','subordinategetlist','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_afterUpsert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); @@ -2001,7 +2020,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','logshow','PROCEDURE','alex INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyerBoss','supplierpackaging_reportsource','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financialBoss','supplierexpenses','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana','firstdayofweek','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockbuyed_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','mail_insert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaParcialMake','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','palletizerBoss','packingsite_startcollection','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2211,7 +2229,10 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','guest','ticketCalculatePurge',' INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','cooler','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','bs','buyerBoss','waste_addSales','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','bs','grafana','waste_addSales','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','saletracking_sectorcollectionaddprevok','PROCEDURE','alexm@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','saleSplit','PROCEDURE','carlosap@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemShelvingSale_deleteAdded','PROCEDURE','guillermo@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); /*!40000 ALTER TABLE `procs_priv` ENABLE KEYS */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 0bd03ac32..e4e59a6bf 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -416,7 +416,7 @@ CREATE TABLE `user` ( `role` int(10) unsigned NOT NULL DEFAULT 2, `active` tinyint(1) NOT NULL DEFAULT 1, `email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, - `emailVerified` tinyint(1) DEFAULT NULL, + `emailVerified` tinyint(1) NOT NULL DEFAULT 0, `verificationToken` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, `lang` char(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, `lastPassChange` datetime DEFAULT NULL, @@ -3815,7 +3815,7 @@ CREATE TABLE `defaulter` ( `created` date NOT NULL, `amount` double NOT NULL DEFAULT 0, `defaulterSinced` date DEFAULT NULL, - `hasChanged` tinyint(1) DEFAULT NULL, + `hasChanged` tinyint(1) NOT NULL DEFAULT 0, `frozened` date DEFAULT NULL, PRIMARY KEY (`clientFk`,`created`), KEY `client` (`clientFk`), @@ -4685,25 +4685,27 @@ BLOCK1: BEGIN DECLARE vShipped DATE; DECLARE vPreviousShipped DATE; DECLARE vDone boolean; - DECLARE cur cursor for - - SELECT clientFk, firstShipped - FROM bs.clientNewBorn; + + DECLARE cur CURSOR FOR + SELECT clientFk, firstShipped + FROM bs.clientNewBorn; DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; SET vDone := FALSE; DELETE FROM bs.clientNewBorn WHERE isModified = FALSE; - INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped) - SELECT c.id, MAX(t.shipped), MAX(t.shipped) - FROM vn.client c - JOIN vn.ticket t on t.clientFk = c.id - LEFT JOIN clientNewBorn cb on cb.clientFk = c.id - WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null - GROUP BY c.id; + INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped) + SELECT c.id, DATE(MAX(t.shipped)), DATE(MAX(t.shipped)) + FROM vn.client c + JOIN vn.ticket t ON t.clientFk = c.id + LEFT JOIN clientNewBorn cb ON cb.clientFk = c.id + WHERE t.shipped BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR + AND util.VN_CURDATE() + AND cb.isModified IS NULL + GROUP BY c.id; + OPEN cur; - LOOP1: LOOP SET vDone := FALSE; FETCH cur INTO vClientFk, vShipped; @@ -7835,7 +7837,6 @@ 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 @@ -11396,6 +11397,7 @@ CREATE TABLE `order` ( `tax` decimal(10,2) NOT NULL, `total` decimal(10,2) NOT NULL, `configured` datetime DEFAULT NULL, + `rowUpdated` datetime DEFAULT NULL COMMENT 'Timestamp for last updated record in orderRow table', PRIMARY KEY (`id`), KEY `address` (`address_id`), KEY `delivery_method` (`delivery_method_id`), @@ -13184,6 +13186,70 @@ 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 `orderRow_updateOverstocking` */; +/*!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=`vn`@`localhost` PROCEDURE `orderRow_updateOverstocking`(vOrderFk INT) +BEGIN +/** +* Set amount = 0 to avoid overbooking sales +* +* @param vOrderFk hedera.order.id +*/ + DECLARE vCalcFk INT; + DECLARE vDone BOOL; + DECLARE vWarehouseFk INT; + + DECLARE cWarehouses CURSOR FOR + SELECT DISTINCT warehouseFk + FROM orderRow + WHERE orderFk = vOrderFk + AND shipment = util.VN_CURDATE(); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + OPEN cWarehouses; + checking: LOOP + SET vDone = FALSE; + + FETCH cWarehouses INTO vWarehouseFk; + + IF vDone THEN + LEAVE checking; + END IF; + + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, util.VN_CURDATE()); + + UPDATE orderRow r + JOIN `order` o ON o.id = r.orderFk + JOIN orderConfig oc + JOIN cache.available a ON a.calc_id = vCalcFk AND a.item_id = r.itemFk + SET r.amount = 0 + WHERE ADDTIME(o.rowUpdated, oc.reserveTime) < util.VN_NOW() + AND a.available <= 0 + AND r.warehouseFk = vWarehouseFk + AND r.orderFk = vOrderFk; + END LOOP; + CLOSE cWarehouses; +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 `order_addItem` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -13689,6 +13755,7 @@ BEGIN * @param vUser The user identifier */ DECLARE vHasRows BOOL; + DECLARE vHas0Amount BOOL; DECLARE vDone BOOL; DECLARE vWarehouseFk INT; DECLARE vShipment DATE; @@ -13698,7 +13765,6 @@ BEGIN DECLARE vItemFk INT; DECLARE vConcept VARCHAR(30); DECLARE vAmount INT; - DECLARE vAvailable INT; DECLARE vPrice DECIMAL(10,2); DECLARE vSaleFk INT; DECLARE vRowFk INT; @@ -13708,7 +13774,6 @@ BEGIN DECLARE vClientFk INT; DECLARE vCompanyFk INT; DECLARE vAgencyModeFk INT; - DECLARE vCalcFk INT; DECLARE vIsTaxDataChecked BOOL; DECLARE vDates CURSOR FOR @@ -13774,6 +13839,20 @@ BEGIN SELECT employeeFk INTO vUserFk FROM orderConfig; END IF; + CALL orderRow_updateOverstocking(vSelf); + + -- Check if any product has a quantity of 0 + SELECT EXISTS ( + SELECT id + FROM orderRow + WHERE orderFk = vSelf + AND amount = 0 + ) INTO vHas0Amount; + + IF vHas0Amount THEN + CALL util.throw('Hay líneas vacías. Por favor, elimínelas'); + END IF; + START TRANSACTION; CALL order_checkEditable(vSelf); @@ -25827,7 +25906,7 @@ CREATE TABLE `address` ( `isActive` tinyint(4) NOT NULL DEFAULT 1, `longitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última longitud proporcionada por tabla delivery', `latitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última latitud proporcionada por tabla delivery', - `isEqualizated` tinyint(1) DEFAULT NULL, + `isEqualizated` tinyint(1) NOT NULL DEFAULT 0, `customsAgentFk` int(11) DEFAULT NULL, `incotermsFk` varchar(3) DEFAULT NULL, `isLogifloraAllowed` tinyint(4) NOT NULL DEFAULT 0, @@ -26035,7 +26114,7 @@ CREATE TABLE `agencyMode` ( `inflation` decimal(5,2) NOT NULL DEFAULT 0.00 COMMENT 'Este valor se utiliza para aumentar el valor del componente porte.', `isVolumetric` tinyint(1) NOT NULL DEFAULT 0, `reportMail` varchar(100) DEFAULT NULL, - `showAgencyName` tinyint(1) DEFAULT 1 COMMENT 'obsoleta', + `showAgencyName__` tinyint(1) DEFAULT 1 COMMENT '@deprecated 2024-09-24', `isActive` tinyint(1) NOT NULL DEFAULT 1, `isExternalAgency` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'obsoleta', `flag` blob DEFAULT NULL COMMENT 'obsoleta', @@ -27058,23 +27137,6 @@ CREATE TABLE `buyConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `buyMark` --- - -DROP TABLE IF EXISTS `buyMark`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `buyMark` ( - `id` int(11) NOT NULL, - `comment` varchar(255) DEFAULT NULL, - `mark` tinyint(1) DEFAULT NULL, - `odbcDate` timestamp NULL DEFAULT current_timestamp(), - PRIMARY KEY (`id`), - CONSTRAINT `Compres_mark_ibfk_1` FOREIGN KEY (`id`) REFERENCES `buy` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `buyer` -- @@ -27208,9 +27270,10 @@ DROP TABLE IF EXISTS `campaign`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `campaign` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `code` enum('mothersDay','allSaints','valentinesDay') NOT NULL, + `code` enum('mothersDay','allSaints','valentinesDay','frenchMothersDay') NOT NULL, `dated` datetime NOT NULL DEFAULT current_timestamp(), `scopeDays` int(11) NOT NULL DEFAULT 15, + `previousDays` int(10) unsigned NOT NULL DEFAULT 30 COMMENT 'Días previos para calcular e insertar en la tabla itemCampaign', PRIMARY KEY (`id`), UNIQUE KEY `campaign_dated_uindex` (`dated`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -27262,7 +27325,7 @@ CREATE TABLE `chat` ( `senderFk` int(10) unsigned DEFAULT NULL, `recipient` varchar(50) DEFAULT NULL, `dated` datetime DEFAULT NULL, - `checkUserStatus` tinyint(1) DEFAULT NULL, + `checkUserStatus` tinyint(1) NOT NULL DEFAULT 0, `message` text DEFAULT NULL, `attempts` int(1) DEFAULT NULL, `error` text DEFAULT NULL, @@ -27656,7 +27719,7 @@ CREATE TABLE `client` ( `credit` decimal(10,2) unsigned NOT NULL DEFAULT 0.00, `countryFk` mediumint(8) unsigned NOT NULL DEFAULT 1, `isActive` tinyint(1) NOT NULL DEFAULT 1, - `gestdocFk` int(11) DEFAULT NULL, + `gestdocFk__` int(11) DEFAULT NULL COMMENT '@deprecated 2024-10-17', `quality` int(2) DEFAULT 11, `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT 5, `created` timestamp NULL DEFAULT current_timestamp(), @@ -27969,11 +28032,14 @@ CREATE TABLE `clientObservation` ( `text` text NOT NULL, `created` timestamp NOT NULL DEFAULT current_timestamp(), `editorFk` int(10) unsigned DEFAULT NULL, + `observationTypeFk` tinyint(3) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `Id_Trabajador` (`workerFk`), KEY `Id_Cliente` (`clientFk`), KEY `clientObservation_created_IDX` (`created`) USING BTREE, KEY `clientObservation_fk_editor` (`editorFk`), + KEY `clientObservationTypeFk` (`observationTypeFk`), + CONSTRAINT `clientObservationTypeFk` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`), CONSTRAINT `clientObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `clientObservation_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `clientObservation_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE @@ -29619,6 +29685,10 @@ CREATE TABLE `docuwareConfig` ( `id` int(10) unsigned NOT NULL, `url` varchar(75) DEFAULT NULL, `cookie` varchar(1000) DEFAULT NULL, + `username` varchar(100) DEFAULT NULL, + `password` varchar(100) DEFAULT NULL, + `token` text DEFAULT NULL, + `expired` int(11) DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `docuwareConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -31985,6 +32055,21 @@ CREATE TABLE `itemBarcode` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemBaseTag` +-- + +DROP TABLE IF EXISTS `itemBaseTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemBaseTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemBotanical` -- @@ -32021,6 +32106,42 @@ SET character_set_client = utf8; 1 AS `ediBotanic` */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `itemBreederTag` +-- + +DROP TABLE IF EXISTS `itemBreederTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemBreederTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemCampaign` +-- + +DROP TABLE IF EXISTS `itemCampaign`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemCampaign` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `itemFk` int(11) NOT NULL, + `quantity` decimal(10,2) NOT NULL, + `total` decimal(10,2) NOT NULL, + `campaign` varchar(100) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `itemCampaign_UNIQUE` (`dated`,`itemFk`), + KEY `itemCampaign_item_FK` (`itemFk`), + CONSTRAINT `itemCampaign_item_FK` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tallos confirmados por día en los días de más producción de una campaña. La tabla está pensada para que sea una foto.'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemCategory` -- @@ -32205,6 +32326,21 @@ CREATE TABLE `itemFamily` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemFarmingTag` +-- + +DROP TABLE IF EXISTS `itemFarmingTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemFarmingTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemImageQueue` -- @@ -32256,6 +32392,21 @@ CREATE TABLE `itemLabel` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemLanguageTag` +-- + +DROP TABLE IF EXISTS `itemLanguageTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemLanguageTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemLog` -- @@ -32470,6 +32621,7 @@ CREATE TABLE `itemShelving` ( `editorFk` int(10) unsigned DEFAULT NULL, `available` int(11) DEFAULT NULL, `isSplit` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda', + `movingState` enum('selected','printed') DEFAULT NULL, PRIMARY KEY (`id`), KEY `itemShelving_fk1_idx` (`itemFk`), KEY `itemShelving_fk2_idx` (`shelvingFk`), @@ -32478,7 +32630,7 @@ CREATE TABLE `itemShelving` ( KEY `itemShelvingBuy_FK` (`buyFk`), CONSTRAINT `itemShelvingBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`), CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON UPDATE CASCADE, CONSTRAINT `itemShelving_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla utilizada para localizar los artículos dentro de los carros. Usado para la gestión del almacén en el altillo '; /*!40101 SET character_set_client = @saved_cs_client */; @@ -32737,6 +32889,36 @@ SET character_set_client = utf8; 1 AS `removed` */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `itemStateTag` +-- + +DROP TABLE IF EXISTS `itemStateTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemStateTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemStemTag` +-- + +DROP TABLE IF EXISTS `itemStemTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemStemTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemTag` -- @@ -32957,6 +33139,36 @@ CREATE TABLE `itemTypeTag` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemVatRateTag` +-- + +DROP TABLE IF EXISTS `itemVatRateTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemVatRateTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemWrappingTag` +-- + +DROP TABLE IF EXISTS `itemWrappingTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemWrappingTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `item_Free_Id` -- @@ -33809,6 +34021,7 @@ CREATE TABLE `operator` ( `volumeLimit` decimal(10,6) DEFAULT 0.500000 COMMENT 'Límite de volumen en una colección para la asignación de pedidos', `sizeLimit` int(10) unsigned DEFAULT NULL COMMENT 'Límite de altura en una colección para la asignación de pedidos', `isOnReservationMode` tinyint(1) NOT NULL DEFAULT 0, + `machineFk` int(11) DEFAULT NULL, PRIMARY KEY (`workerFk`), KEY `operator_FK` (`workerFk`), KEY `operator_FK_1` (`trainFk`), @@ -33816,11 +34029,13 @@ CREATE TABLE `operator` ( KEY `operator_FK_3` (`warehouseFk`), KEY `operator_FK_5` (`labelerFk`), KEY `operator_FK_4` (`sectorFk`), + KEY `operator_machine_FK` (`machineFk`), CONSTRAINT `operator_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `operator_FK_1` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE, CONSTRAINT `operator_FK_2` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `operator_FK_3` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `operator_FK_4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE + CONSTRAINT `operator_FK_4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE, + CONSTRAINT `operator_machine_FK` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -34916,7 +35131,7 @@ CREATE TABLE `priceDelta` ( `warehouseFk` smallint(6) unsigned NOT NULL, `created` timestamp NOT NULL DEFAULT current_timestamp(), `editorFk` int(10) unsigned DEFAULT NULL, - `zoneGeoFk` int(11) DEFAULT NULL, + `zoneGeoFk` int(11) DEFAULT NULL COMMENT 'Application area for the bonus component', PRIMARY KEY (`id`), KEY `priceDelta_itemType_FK` (`itemTypeFk`), KEY `priceDelta_ink_FK` (`inkFk`), @@ -36929,6 +37144,7 @@ CREATE TABLE `sector` ( `isReserve` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Sectores de reserva, como Albenfruit o Fuentes', `backupPrinterFk` int(10) unsigned DEFAULT NULL, `typeFk` int(10) unsigned NOT NULL DEFAULT 1, + `isOnReservationMode` tinyint(1) DEFAULT 0, PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), @@ -37651,13 +37867,13 @@ CREATE TABLE `stockBought` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `stockBuyed` +-- Table structure for table `stockBuyed__` -- -DROP TABLE IF EXISTS `stockBuyed`; +DROP TABLE IF EXISTS `stockBuyed__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `stockBuyed` ( +CREATE TABLE `stockBuyed__` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `userFk` int(10) unsigned DEFAULT NULL, `buyed` decimal(10,2) DEFAULT NULL, @@ -37669,7 +37885,7 @@ CREATE TABLE `stockBuyed` ( PRIMARY KEY (`id`), KEY `stockBuyed_user_idx` (`userFk`), CONSTRAINT `stockBuyedUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-10-01 rename and refactor to stockBought'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -38374,10 +38590,12 @@ CREATE TABLE `ticketConfig` ( `packingDelay` int(11) DEFAULT 1 COMMENT 'Horas que marcará el retraso respecto hora de cierre web del ticket', `daysForWarningClaim` int(11) NOT NULL DEFAULT 2 COMMENT 'dias restantes hasta que salte el aviso de reclamación fuera de plazo', `defaultAttenderFk` int(10) unsigned DEFAULT NULL, + `closureDaysAgo` int(11) NOT NULL DEFAULT 2 COMMENT 'Number of days to look back for ticket closure', PRIMARY KEY (`id`), KEY `ticketConfig_worker_FK` (`defaultAttenderFk`), CONSTRAINT `ticketConfig_worker_FK` FOREIGN KEY (`defaultAttenderFk`) REFERENCES `worker` (`id`), - CONSTRAINT `ticketConfig_check` CHECK (`id` = 1) + CONSTRAINT `ticketConfig_check` CHECK (`id` = 1), + CONSTRAINT `closureDaysAgo_check` CHECK (`closureDaysAgo` > 0) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39414,6 +39632,8 @@ CREATE TABLE `travelThermograph` ( `result` varchar(45) DEFAULT NULL, `dmsFk` int(11) DEFAULT NULL, `temperatureFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 'cool' COMMENT 'En la versión de Agosto de Salix se empezará a usar este campo y se actualizaran los anteriores mirando temperature.', + `maxTemperature` decimal(5,2) DEFAULT NULL, + `minTemperature` decimal(5,2) DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `thermograph_fk_idx` (`thermographFk`), @@ -39422,7 +39642,7 @@ CREATE TABLE `travelThermograph` ( KEY `warehouse_id` (`warehouseFk`), KEY `travelThermographTemperatureFgn` (`temperatureFk`), KEY `travelThermograph_fk_editor` (`editorFk`), - CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE, + CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `travelThermographTemperatureFgn` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`), CONSTRAINT `travelThermographThermographFgn` FOREIGN KEY (`thermographFk`) REFERENCES `thermograph` (`id`) ON UPDATE CASCADE, CONSTRAINT `travelThermographTravelFgn` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`), @@ -39938,8 +40158,8 @@ CREATE TABLE `warehouse` ( `isLogiflora` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Este almacén acepta productos de Logiflora', `isBionic` tinyint(1) NOT NULL DEFAULT 1, `isHalt` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Almacén en el que descargan nuestros troncales', - `isOrigin` tinyint(1) DEFAULT NULL, - `isDestiny` tinyint(1) DEFAULT NULL, + `isOrigin` tinyint(1) NOT NULL DEFAULT 0, + `isDestiny` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`), KEY `Id_Paises` (`countryFk`), @@ -41174,7 +41394,7 @@ CREATE TABLE `zoneIncluded` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `zoneFk` int(11) NOT NULL, `geoFk` int(11) NOT NULL, - `isIncluded` tinyint(1) DEFAULT NULL, + `isIncluded` tinyint(1) NOT NULL DEFAULT 0, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `unique_zone_geo` (`zoneFk`,`geoFk`), @@ -41428,6 +41648,24 @@ 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 `itemCampaig_add` */;; +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=`vn`@`localhost`*/ /*!50106 EVENT `itemCampaig_add` ON SCHEDULE EVERY 1 DAY STARTS '2024-10-18 03:00:00' ON COMPLETION PRESERVE ENABLE DO CALL itemCampaign_add() */ ;; +/*!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 `itemImageQueue_check` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -48028,39 +48266,6 @@ 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 `buy_getVolumeByAgency` */; -/*!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=`vn`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS tmp.buy; - CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - - INSERT INTO tmp.buy - SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed = vDated - AND t.agencyModeFk IN (0, vAgencyFk); - - CALL buy_getVolume(); - DROP TEMPORARY TABLE tmp.buy; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!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_getVolumeByEntry` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -49309,6 +49514,13 @@ BEGIN DELETE FROM messageInbox WHERE sendDate < v2Months; DELETE FROM messageInbox WHERE sendDate < v2Months; DELETE FROM workerTimeControl WHERE timed < v4Years; + DELETE FROM itemShelvingSale + WHERE itemShelvingFk IN ( + SELECT id + FROM itemShelving + WHERE created < util.VN_CURDATE() + AND visible = 0 + ); DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0; DELETE FROM ticketDown WHERE created < util.yesterday(); DELETE IGNORE FROM expedition WHERE created < v26Months; @@ -49336,16 +49548,10 @@ BEGIN DELETE FROM claim WHERE ticketCreated < v4Years; -- Robert ubicacion anterior de travelLog comentario para debug DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months; - DELETE bm - FROM buyMark bm - JOIN buy b ON b.id = bm.id - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed <= v2Months; DELETE b FROM buy b JOIN entryConfig e ON e.defaultEntry = b.entryFk WHERE b.created < v2Months; - DELETE FROM stockBuyed WHERE creationDate < v2Months; + DELETE FROM stockBought WHERE dated < v2Months; DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months; -- Equipos duplicados DELETE w.* @@ -50287,22 +50493,19 @@ BEGIN DECLARE vIsTaxDataChecked TINYINT(1); DECLARE vHasCoreVnl BOOLEAN; DECLARE vMandateTypeFk INT; - DECLARE vHasDailyInvoice BOOLEAN; SELECT cc.defaultPayMethodFk, cc.defaultDueDay, cc.defaultCredit, cc.defaultIsTaxDataChecked, cc.defaultHasCoreVnl, - cc.defaultMandateTypeFk, - c.hasDailyInvoice + cc.defaultMandateTypeFk INTO vPayMethodFk, vDueDay, vDefaultCredit, vIsTaxDataChecked, vHasCoreVnl, - vMandateTypeFk, - vHasDailyInvoice + vMandateTypeFk FROM clientConfig cc LEFT JOIN province p ON p.id = vProvinceFk LEFT JOIN country c ON c.id = p.countryFk; @@ -50323,8 +50526,7 @@ BEGIN credit = vDefaultCredit, isTaxDataChecked = vIsTaxDataChecked, hasCoreVnl = vHasCoreVnl, - isEqualizated = FALSE, - hasDailyInvoice = vHasDailyInvoice + isEqualizated = FALSE ON duplicate KEY UPDATE payMethodFk = vPayMethodFk, dueDay = vDueDay, @@ -51057,23 +51259,23 @@ BEGIN WHERE t.id = vTicketFk; CALL cache.available_refresh( - vCacheAvailableFk, + vCacheAvailableFk, FALSE, - vWarehouseFk, + vWarehouseFk, util.VN_CURDATE()); SELECT available INTO vAvailable FROM cache.available - WHERE calc_id = vCacheAvailableFk + WHERE calc_id = vCacheAvailableFk AND item_id = vItemFk; - + IF vAvailable < vQuantity THEN SET vHasThrow = TRUE; ELSE SELECT `name`, - CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) + CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) INTO vItemName, vConcept - FROM item + FROM item WHERE id = vItemFk; START TRANSACTION; @@ -51089,7 +51291,7 @@ BEGIN CALL sale_calculateComponent(vSaleFk, NULL); CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk); - + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN SET vHasThrow = TRUE; END IF; @@ -51098,13 +51300,13 @@ BEGIN IF vHasThrow THEN CALL util.throw("There is no available for the selected item"); END IF; - + IF vSaleGroupFk THEN INSERT INTO saleGroupDetail SET saleFk = vSaleFk, saleGroupFk = vSaleGroupFk; END IF; - + COMMIT; END ;; DELIMITER ; @@ -51126,7 +51328,7 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_assign`( vUserFk INT, OUT vCollectionFk INT ) -BEGIN +BEGIN /** * Comprueba si existen colecciones libres que se ajustan * al perfil del usuario y le asigna la más antigua. @@ -51168,6 +51370,12 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; -- Si hay colecciones sin terminar, sale del proceso + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + CALL collection_get(vUserFk); SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime @@ -51241,9 +51449,19 @@ BEGIN IF vCollectionFk IS NULL THEN CALL collection_new(vUserFk, vCollectionFk); - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + END IF; + + COMMIT; END IF; END ;; DELIMITER ; @@ -51318,101 +51536,140 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_getAssigned`( ) BEGIN /** - * Comprueba si existen colecciones libres que se ajustan al perfil del usuario - * y le asigna la más antigua. - * Añade un registro al semillero de colecciones y hace la reserva para la colección - * + * Comprueba si existen colecciones libres que se ajustan + * al perfil del usuario y le asigna la más antigua. + * Añade un registro al semillero de colecciones. + * * @param vUserFk Id de usuario * @param vCollectionFk Id de colección */ DECLARE vHasTooMuchCollections BOOL; - DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vWarehouseFk INT; - DECLARE vLockName VARCHAR(215); - DECLARE vLockTime INT DEFAULT 30; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCollectionWorker INT; + DECLARE vMaxNotAssignedCollectionLifeTime TIME; + + DECLARE vCollections CURSOR FOR + WITH collections AS ( + SELECT tc.collectionFk, + SUM(sv.volume) volume, + c.saleTotalCount, + c.itemPackingTypeFk, + c.trainFk, + c.warehouseFk, + c.wagons + FROM vn.ticketCollection tc + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE c.workerFk IS NULL + AND sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) SELECT c.collectionFk + FROM collections c + JOIN vn.operator o + WHERE o.workerFk = vUserFk + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + -- Si hay colecciones sin terminar, sale del proceso DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - IF vLockName IS NOT NULL THEN - DO RELEASE_LOCK(vLockName); - END IF; - + ROLLBACK; RESIGNAL; END; - -- Si hay colecciones sin terminar, sale del proceso CALL collection_get(vUserFk); - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, - pc.collection_assign_lockname - INTO vHasTooMuchCollections, - vLockName - FROM tmp.collection c - JOIN productionConfig pc; + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime + INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime + FROM productionConfig pc + LEFT JOIN tmp.collection ON TRUE; DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN - CALL util.throw('There are pending collections'); - END IF; - - SELECT warehouseFk, itemPackingTypeFk - INTO vWarehouseFk, vItemPackingTypeFk - FROM operator - WHERE workerFk = vUserFk; - - SET vLockName = CONCAT_WS('/', - vLockName, - vWarehouseFk, - vItemPackingTypeFk - ); - - IF NOT GET_LOCK(vLockName, vLockTime) THEN - CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + CALL util.throw('Hay colecciones pendientes'); END IF; -- Se eliminan las colecciones sin asignar que estan obsoletas - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN state s ON s.code = 'PRINTED_AUTO' - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - DELETE c - FROM collection c - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM `collection` c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN `state` s ON s.code = 'PRINTED_AUTO' + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime; + + DELETE FROM `collection` + WHERE workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime; -- Se añade registro al semillero - INSERT INTO collectionHotbed - SET userFk = vUserFk; + + INSERT INTO collectionHotbed(userFk) VALUES(vUserFk); -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) INTO vCollectionFk - FROM collection c - JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk - OR c.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk - AND c.workerFk IS NULL - WHERE o.workerFk = vUserFk; + + OPEN vCollections; + l: LOOP + SET vDone = FALSE; + FETCH vCollections INTO vCollectionFk; + + IF vDone THEN + LEAVE l; + END IF; + + BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + SET vCollectionFk = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + COMMIT; + LEAVE l; + END IF; + + ROLLBACK; + END; + END LOOP; + CLOSE vCollections; IF vCollectionFk IS NULL THEN CALL collection_new(vUserFk, vCollectionFk); + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + END IF; + + COMMIT; END IF; - - UPDATE collection - SET workerFk = vUserFk - WHERE id = vCollectionFk; - CALL itemShelvingSale_addByCollection(vCollectionFk); - - DO RELEASE_LOCK(vLockName); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51451,9 +51708,8 @@ BEGIN SELECT tob.ticketFk, tob.description FROM vn.ticketObservation tob JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk - LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk - WHERE ot.`code` = 'itemPicker' - AND tc.collectionFk = vParamFk OR tc.ticketFk = vParamFk + JOIN vn.observationType ot ON ot.id = tob.observationTypeFk AND ot.`code` = 'itemPicker' + WHERE tc.collectionFk = vParamFk OR tc.ticketFk = vParamFk ) SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, @@ -51476,7 +51732,7 @@ BEGIN LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE t.id = vParamFk AND t.shipped >= vYesterday - UNION ALL + UNION SELECT t.id ticketFk, IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, @@ -51497,7 +51753,7 @@ BEGIN LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE tc.collectionFk = vParamFk - UNION ALL + UNION SELECT sg.ticketFk, NULL `level`, am.name agencyName, @@ -51514,7 +51770,8 @@ BEGIN LEFT JOIN observation ob ON ob.ticketFk = t.id LEFT JOIN vn.client c ON c.id = t.clientFk WHERE sc.id = vParamFk - AND t.shipped >= vYesterday; + AND t.shipped >= vYesterday + GROUP BY ticketFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51683,7 +51940,10 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_new`(vUserFk INT, OUT vCollectionFk INT) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_new`( + vUserFk INT, + OUT vCollectionFk INT +) BEGIN /** * Genera colecciones de tickets sin asignar trabajador. @@ -51696,30 +51956,29 @@ BEGIN DECLARE vLinesLimit INT; DECLARE vTicketLines INT; DECLARE vVolumeLimit DECIMAL; - DECLARE vTicketVolume DECIMAL; DECLARE vSizeLimit INT; + DECLARE vTicketVolume DECIMAL; DECLARE vMaxTickets INT; - DECLARE vStateFk VARCHAR(45); + DECLARE vStateCode VARCHAR(45); DECLARE vFirstTicketFk INT; - DECLARE vHour INT; - DECLARE vMinute INT; DECLARE vWorkerCode VARCHAR(3); - DECLARE vWagonCounter INT DEFAULT 0; + DECLARE vWagonCounter INT DEFAULT 1; DECLARE vTicketFk INT; DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vHasAssignedTickets BOOLEAN; + DECLARE vHasAssignedTickets BOOL; DECLARE vHasUniqueCollectionTime BOOL; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vLockName VARCHAR(215); - DECLARE vLockTime INT DEFAULT 30; + DECLARE vHeight INT; + DECLARE vVolume INT; + DECLARE vLiters INT; + DECLARE vLines INT; + DECLARE vTotalLines INT DEFAULT 0; + DECLARE vTotalVolume INT DEFAULT 0; DECLARE vFreeWagonFk INT; - DECLARE vErrorNumber INT; - DECLARE vErrorMsg TEXT; + DECLARE vDone INT DEFAULT FALSE; - DECLARE c1 CURSOR FOR + DECLARE vTickets CURSOR FOR SELECT ticketFk, `lines`, m3 FROM tmp.productionBuffer - WHERE ticketFk <> vFirstTicketFk ORDER BY HH, mm, productionOrder DESC, @@ -51732,26 +51991,6 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - GET DIAGNOSTICS CONDITION 1 - vErrorNumber = MYSQL_ERRNO, - vErrorMsg = MESSAGE_TEXT; - - CALL util.debugAdd('collection_new', JSON_OBJECT( - 'errorNumber', vErrorNumber, - 'errorMsg', vErrorMsg, - 'lockName', vLockName, - 'userFk', vUserFk, - 'ticketFk', vTicketFk - )); -- Tmp - - IF vLockName IS NOT NULL THEN - DO RELEASE_LOCK(vLockName); - END IF; - RESIGNAL; - END; - SELECT pc.ticketTrolleyMax * o.numberOfWagons, pc.hasUniqueCollectionTime, w.code, @@ -51762,36 +52001,26 @@ BEGIN o.trainFk, o.linesLimit, o.volumeLimit, - o.sizeLimit, - pc.collection_new_lockname + o.sizeLimit INTO vMaxTickets, - vHasUniqueCollectionTime, - vWorkerCode, - vWarehouseFk, - vItemPackingTypeFk, - vStateFk, - vWagons, - vTrainFk, - vLinesLimit, - vVolumeLimit, - vSizeLimit, - vLockName - FROM productionConfig pc - JOIN worker w ON w.id = vUserFk + vHasUniqueCollectionTime, + vWorkerCode, + vWarehouseFk, + vItemPackingTypeFk, + vStateCode, + vWagons, + vTrainFk, + vLinesLimit, + vVolumeLimit, + vSizeLimit + FROM worker w + JOIN operator o ON o.workerFk = w.id JOIN state st ON st.`code` = 'ON_PREPARATION' - JOIN operator o ON o.workerFk = vUserFk; - - SET vLockName = CONCAT_WS('/', - vLockName, - vWarehouseFk, - vItemPackingTypeFk - ); - - IF NOT GET_LOCK(vLockName, vLockTime) THEN - CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); - END IF; + JOIN productionConfig pc + WHERE w.id = vUserFk; -- Se prepara el tren, con tantos vagones como sea necesario. + CREATE OR REPLACE TEMPORARY TABLE tTrain (wagon INT, shelve INT, @@ -51802,63 +52031,62 @@ BEGIN PRIMARY KEY(wagon, shelve)) ENGINE = MEMORY; - WHILE vWagons > vWagonCounter DO - SET vWagonCounter = vWagonCounter + 1; - - INSERT INTO tTrain(wagon, shelve, liters, `lines`, height) - SELECT vWagonCounter, cv.`level` , cv.liters , cv.`lines` , cv.height - FROM collectionVolumetry cv - WHERE cv.trainFk = vTrainFk + INSERT INTO tTrain (wagon, shelve, liters, `lines`, height) + WITH RECURSIVE wagonSequence AS ( + SELECT vWagonCounter wagon + UNION ALL + SELECT wagon + 1 wagon + FROM wagonSequence + WHERE wagon < vWagonCounter + vWagons -1 + ) + SELECT ws.wagon, cv.`level`, cv.liters, cv.`lines`, cv.height + FROM wagonSequence ws + JOIN vn.collectionVolumetry cv ON cv.trainFk = vTrainFk AND cv.itemPackingTypeFk = vItemPackingTypeFk; - END WHILE; -- Esto desaparecerá cuando tengamos la table cache.ticket + CALL productionControl(vWarehouseFk, 0); ALTER TABLE tmp.productionBuffer ADD COLUMN liters INT, ADD COLUMN height INT; - -- Se obtiene nº de colección. - INSERT INTO collection - SET itemPackingTypeFk = vItemPackingTypeFk, - trainFk = vTrainFk, - wagons = vWagons, - warehouseFk = vWarehouseFk; - - SELECT LAST_INSERT_ID() INTO vCollectionFk; - -- Los tickets de recogida en Algemesí sólo se sacan si están asignados. -- Los pedidos con riesgo no se sacan aunque se asignen. - DELETE pb.* + + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state WHERE (pb.agency = 'REC_ALGEMESI' AND s.code <> 'PICKER_DESIGNED') OR pb.problem LIKE '%RIESGO%'; - -- Comprobamos si hay tickets asignados. En ese caso, nos centramos - -- exclusivamente en esos tickets y los sacamos independientemente - -- de problemas o tamaños - SELECT COUNT(*) INTO vHasAssignedTickets - FROM tmp.productionBuffer pb - JOIN state s ON s.id = pb.state - WHERE s.code = 'PICKER_DESIGNED' - AND pb.workerCode = vWorkerCode; + -- Si hay tickets asignados, nos centramos exclusivamente en esos tickets + -- y los sacamos independientemente de problemas o tamaños + + SELECT EXISTS ( + SELECT TRUE + FROM tmp.productionBuffer pb + JOIN state s ON s.id = pb.state + WHERE (s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode) + OR s.code = 'LAST_CALL' + ) INTO vHasAssignedTickets; -- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados + IF vHasAssignedTickets THEN - DELETE pb.* + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state - WHERE s.code <> 'PICKER_DESIGNED' - OR pb.workerCode <> vWorkerCode; + WHERE (s.code <> 'PICKER_DESIGNED' + OR pb.workerCode <> vWorkerCode) + AND s.code <> 'LAST_CALL'; ELSE - DELETE pb.* + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state - JOIN agencyMode am ON am.id = pb.agencyModeFk - JOIN agency a ON a.id = am.agencyFk LEFT JOIN ( SELECT pb.ticketFk, MAX(i.`size`) maxSize FROM tmp.productionBuffer pb @@ -51869,7 +52097,7 @@ BEGIN ) sub ON sub.ticketFk = pb.ticketFk JOIN productionConfig pc WHERE pb.shipped <> util.VN_CURDATE() - OR (pb.ubicacion IS NULL AND a.isOwn) + OR pb.ubicacion IS NULL OR (NOT s.isPreparable AND NOT s.isPrintable) OR pb.collectionH IS NOT NULL OR pb.collectionV IS NOT NULL @@ -51877,26 +52105,25 @@ BEGIN OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H') OR (NOT pb.V AND vItemPackingTypeFk = 'V') OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking) - OR LENGTH(pb.problem) > 0 + OR LENGTH(pb.problem) OR pb.lines > vLinesLimit OR pb.m3 > vVolumeLimit OR sub.maxSize > vSizeLimit OR pb.hasPlantTray; END IF; - -- Es importante que el primer ticket se coja en todos los casos - SELECT ticketFk, - HH, - mm, - `lines`, - m3 - INTO vFirstTicketFk, - vHour, - vMinute, - vTicketLines, - vTicketVolume + -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede + + IF vHasUniqueCollectionTime THEN + DELETE pb + FROM tmp.productionBuffer pb + JOIN tmp.productionBuffer pb2 ON pb2.ticketFk = vFirstTicketFk + AND (pb.HH <> pb2.HH OR pb.mm <> pb2.mm); + END IF; + + SELECT ticketFk INTO vFirstTicketFk FROM tmp.productionBuffer - ORDER BY HH, + ORDER BY HH, mm, productionOrder DESC, m3 DESC, @@ -51906,44 +52133,37 @@ BEGIN ticketFk LIMIT 1; - -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede - IF vHasUniqueCollectionTime THEN - DELETE FROM tmp.productionBuffer - WHERE HH <> vHour - OR mm <> vMinute; - END IF; - - SET vTicketFk = vFirstTicketFk; - SET @lines = 0; - SET @volume = 0; - - OPEN c1; - read_loop: LOOP + OPEN vTickets; + l: LOOP SET vDone = FALSE; + FETCH vTickets INTO vTicketFk, vTicketLines, vTicketVolume; + + IF vDone THEN + LEAVE l; + END IF; -- Buscamos un ticket que cumpla con los requisitos en el listado - IF ((vTicketLines + @lines) <= vLinesLimit OR vLinesLimit IS NULL) - AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN + + IF (vLinesLimit IS NULL OR (vTotalLines + vTicketLines) <= vLinesLimit) + AND (vVolumeLimit IS NULL OR (vTotalVolume + vTicketVolume) <= vVolumeLimit) THEN CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk); DROP TEMPORARY TABLE tmp.ticketIPT; + SELECT COUNT(*), SUM(litros), MAX(i.`size`), SUM(sv.volume) + INTO vLines, vLiters, vHeight, vVolume + FROM saleVolume sv + JOIN sale s ON s.id = sv.saleFk + JOIN item i ON i.id = s.itemFk + WHERE sv.ticketFk = vTicketFk; + + SET vTotalVolume = vTotalVolume + vVolume, + vTotalLines = vTotalLines + vLines; + UPDATE tmp.productionBuffer pb - JOIN ( - SELECT SUM(litros) liters, - @lines:= COUNT(*) + @lines, - COUNT(*) `lines`, - MAX(i.`size`) height, - @volume := SUM(sv.volume) + @volume, - SUM(sv.volume) volume - FROM saleVolume sv - JOIN sale s ON s.id = sv.saleFk - JOIN item i ON i.id = s.itemFk - WHERE sv.ticketFk = vTicketFk - ) sub - SET pb.liters = sub.liters, - pb.`lines` = sub.`lines`, - pb.height = sub.height + SET pb.liters = vLiters, + pb.`lines` = vLines, + pb.height = vHeight WHERE pb.ticketFk = vTicketFk; UPDATE tTrain tt @@ -51960,17 +52180,13 @@ BEGIN tt.height LIMIT 1; - -- Si no le encuentra una balda adecuada, intentamos darle un carro entero si queda alguno libre + -- Si no le encuentra una balda, intentamos darle un carro entero libre + IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN - SELECT tt.wagon - INTO vFreeWagonFk - FROM tTrain tt - LEFT JOIN ( - SELECT DISTINCT wagon - FROM tTrain - WHERE ticketFk IS NOT NULL - ) nn ON nn.wagon = tt.wagon - WHERE nn.wagon IS NULL + SELECT wagon INTO vFreeWagonFk + FROM tTrain + GROUP BY wagon + HAVING COUNT(ticketFk) = 0 ORDER BY wagon LIMIT 1; @@ -51979,38 +52195,35 @@ BEGIN SET ticketFk = vFirstTicketFk WHERE wagon = vFreeWagonFk; - -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo - DELETE tt.* - FROM tTrain tt - LEFT JOIN ( - SELECT DISTINCT wagon - FROM tTrain - WHERE ticketFk IS NOT NULL - ) nn ON nn.wagon = tt.wagon - WHERE nn.wagon IS NULL; - END IF; - END IF; + -- Se anulan el resto de carros libres, + -- máximo un carro con pedido excesivo - FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume; - IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN - LEAVE read_loop; - END IF; - ELSE - FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume; - IF vDone THEN - LEAVE read_loop; - END IF; + DELETE tt + FROM tTrain tt + JOIN (SELECT wagon + FROM tTrain + GROUP BY wagon + HAVING COUNT(ticketFk) = 0 + ) sub ON sub.wagon = tt.wagon; + END IF; + END IF; END IF; END LOOP; - CLOSE c1; + CLOSE vTickets; IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN - UPDATE collection c - JOIN state st ON st.code = 'ON_PREPARATION' - SET c.stateFk = st.id - WHERE c.id = vCollectionFk; + -- Se obtiene nº de colección + + INSERT INTO collection + SET itemPackingTypeFk = vItemPackingTypeFk, + trainFk = vTrainFk, + wagons = vWagons, + warehouseFk = vWarehouseFk; + + SELECT LAST_INSERT_ID() INTO vCollectionFk; -- Asigna las bandejas + INSERT IGNORE INTO ticketCollection(ticketFk, collectionFk, `level`, wagon, liters) SELECT tt.ticketFk, vCollectionFk, tt.shelve, tt.wagon, tt.liters FROM tTrain tt @@ -52018,37 +52231,34 @@ BEGIN ORDER BY tt.wagon, tt.shelve; -- Actualiza el estado de los tickets - CALL collection_setState(vCollectionFk, vStateFk); + + CALL collection_setState(vCollectionFk, vStateCode); -- Aviso para la preparacion previa + INSERT INTO ticketDown(ticketFk, collectionFk) SELECT tc.ticketFk, tc.collectionFk FROM ticketCollection tc WHERE tc.collectionFk = vCollectionFk; - CALL sales_mergeByCollection(vCollectionFk); + CALL collection_mergeSales(vCollectionFk); UPDATE `collection` c - JOIN ( + JOIN( SELECT COUNT(*) saleTotalCount, SUM(s.isPicked <> 0) salePickedCount FROM ticketCollection tc JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND s.quantity > 0 - ) sub + WHERE tc.collectionFk = vCollectionFk + AND s.quantity > 0 + )sub SET c.saleTotalCount = sub.saleTotalCount, c.salePickedCount = sub.salePickedCount WHERE c.id = vCollectionFk; - ELSE - DELETE FROM `collection` - WHERE id = vCollectionFk; - SET vCollectionFk = NULL; + SET vCollectionFk = NULL; END IF; - DO RELEASE_LOCK(vLockName); - DROP TEMPORARY TABLE tTrain, tmp.productionBuffer; @@ -55362,22 +55572,26 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `expeditionPallet_build`( vWorkerFk INT, OUT vPalletFk INT ) -BEGIN -/** Construye un pallet de expediciones. +proc: BEGIN +/** + * Builds an expedition pallet. * - * Primero comprueba si esas expediciones ya pertenecen a otro pallet, - * en cuyo caso actualiza ese pallet. + * First, it checks if these expeditions already belong to another pallet, + * in which case it returns an error. * - * @param vExpeditions JSON_ARRAY con esta estructura [exp1, exp2, exp3, ...] - * @param vArcId INT Identificador de arcRead - * @param vWorkerFk INT Identificador de worker - * @param out vPalletFk Identificador de expeditionPallet + * @param vExpeditions JSON_ARRAY with this structure [exp1, exp2, exp3, ...] + * @param vArcId INT Identifier of arcRead + * @param vWorkerFk INT Identifier of worker + * @param out vPalletFk Identifier of expeditionPallet */ + DECLARE vCounter INT; DECLARE vExpeditionFk INT; DECLARE vTruckFk INT; DECLARE vPrinterFk INT; DECLARE vExpeditionStateTypeFk INT; + DECLARE vFreeExpeditionCount INT; + DECLARE vExpeditionWithPallet INT; CREATE OR REPLACE TEMPORARY TABLE tExpedition ( expeditionFk INT, @@ -55401,48 +55615,63 @@ BEGIN WHERE e.id = vExpeditionFk; END WHILE; - SELECT palletFk INTO vPalletFk - FROM ( - SELECT palletFk, count(*) n - FROM tExpedition - WHERE palletFk > 0 - GROUP BY palletFk - ORDER BY n DESC - LIMIT 100 - ) sub - LIMIT 1; + SELECT COUNT(expeditionFk) INTO vFreeExpeditionCount + FROM tExpedition + WHERE palletFk IS NULL; - IF vPalletFk IS NULL THEN - SELECT roadmapStopFk INTO vTruckFk - FROM ( - SELECT rm.roadmapStopFk, count(*) n - FROM routesMonitor rm - JOIN tExpedition e ON e.routeFk = rm.routeFk - GROUP BY roadmapStopFk - ORDER BY n DESC - LIMIT 1 - ) sub; + SELECT COUNT(expeditionFk) INTO vExpeditionWithPallet + FROM tExpedition + WHERE palletFk; - IF vTruckFk IS NULL THEN - CALL util.throw ('TRUCK_NOT_AVAILABLE'); - END IF; - - INSERT INTO expeditionPallet SET truckFk = vTruckFk; - - SET vPalletFk = LAST_INSERT_ID(); + IF vExpeditionWithPallet THEN + UPDATE arcRead + SET error = ( + SELECT GROUP_CONCAT(expeditionFk SEPARATOR ', ') + FROM tExpedition + WHERE palletFk + ) + WHERE id = vArcId; + LEAVE proc; END IF; + IF NOT vFreeExpeditionCount THEN + CALL util.throw ('NO_FREE_EXPEDITIONS'); + END IF; + + SELECT roadmapStopFk INTO vTruckFk + FROM ( + SELECT rm.roadmapStopFk, count(*) n + FROM routesMonitor rm + JOIN tExpedition e ON e.routeFk = rm.routeFk + WHERE e.palletFk IS NULL + GROUP BY roadmapStopFk + ORDER BY n DESC + LIMIT 1 + ) sub; + + IF vTruckFk IS NULL THEN + CALL util.throw ('TRUCK_NOT_AVAILABLE'); + END IF; + + INSERT INTO expeditionPallet SET truckFk = vTruckFk; + + SET vPalletFk = LAST_INSERT_ID(); + INSERT INTO expeditionScan(expeditionFk, palletFk, workerFk) SELECT expeditionFk, vPalletFk, vWorkerFk FROM tExpedition - ON DUPLICATE KEY UPDATE palletFk = vPalletFk, workerFk = vWorkerFk; + WHERE palletFk IS NULL; SELECT id INTO vExpeditionStateTypeFk FROM expeditionStateType WHERE code = 'PALLETIZED'; - + INSERT INTO expeditionState(expeditionFk, typeFk) - SELECT expeditionFk, vExpeditionStateTypeFk FROM tExpedition; + SELECT expeditionFk, vExpeditionStateTypeFk + FROM tExpedition + WHERE palletFk IS NULL; + + UPDATE arcRead SET error = NULL WHERE id = vArcId; SELECT printerFk INTO vPrinterFk FROM arcRead WHERE id = vArcId; @@ -58550,6 +58779,75 @@ 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 `invoiceOut_newFromAddress` */; +/*!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=`vn`@`localhost` PROCEDURE `invoiceOut_newFromAddress`( + IN vAddressFk INT, + IN vSerial CHAR(2), + IN vMaxShipped DATE, + IN vCompanyFk INT, + IN vTaxArea VARCHAR(25), + IN vRef VARCHAR(25), + OUT vInvoiceId INT) +BEGIN +/** + * Factura los tickets de un consignatario hasta una fecha dada + * @param vAddressFk Id del consignatario a facturar + * @param vSerial Serie de factura + * @param vMaxShipped Fecha hasta la cual cogerá tickets para facturar + * @param vCompanyFk Id de la empresa desde la que se factura + * @param vTaxArea Tipo de iva en relacion a la empresa y al cliente, NULL por defecto + * @param vRef Referencia de la factura en caso que se quiera forzar, NULL por defecto + * @return vInvoiceId factura + */ + DECLARE vIsRefEditable BOOLEAN; + + IF vRef IS NOT NULL AND vSerial IS NOT NULL THEN + SELECT isRefEditable INTO vIsRefEditable + FROM invoiceOutSerial + WHERE code = vSerial; + + IF NOT vIsRefEditable THEN + CALL util.throw('serial non editable'); + END IF; + END IF; + + DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`; + CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice` + (PRIMARY KEY (`id`)) + ENGINE = MEMORY + SELECT id FROM ticket t + WHERE t.addressFk = vAddressFk + AND t.refFk IS NULL + AND t.companyFk = vCompanyFk + AND t.shipped BETWEEN + util.firstDayOfYear(vMaxShipped - INTERVAL 1 YEAR) + AND util.dayend(vMaxShipped); + + CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId); + + UPDATE invoiceOut + SET `ref` = vRef + WHERE id = vInvoiceId + AND vRef IS NOT NULL; + + IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN + CALL invoiceOutBooking(vInvoiceId); + 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 `invoiceOut_newFromClient` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -58739,6 +59037,73 @@ ELSE INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode); 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 `itemCampaign_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemCampaign_add`() +proc: BEGIN +/** + * Añade registros a tabla itemCampaign. + * + * @param vDateFrom Fecha desde + * @param vDateTo Fecha hasta + * @param vCampaign Código de la campaña + */ + DECLARE vYesterday DATE; + DECLARE vCampaign VARCHAR(100); + DECLARE vScopeDays INT; + DECLARE vPreviousDays INT; + DECLARE vDateSumFrom DATE; + DECLARE vDateSumTo DATE; + + SET vYesterday = util.yesterday(); + + SELECT dated, code, scopeDays, previousDays + INTO vDateSumTo, vCampaign, vScopeDays, vPreviousDays + FROM campaign + WHERE dated >= vYesterday + ORDER BY dated + LIMIT 1; + + IF vCampaign IS NULL THEN + CALL util.throw('Missing data in campaign table'); + END IF; + + IF NOT vYesterday BETWEEN vDateSumTo - INTERVAL vPreviousDays DAY + AND vDateSumTo THEN + LEAVE proc; + END IF; + + SET vDateSumFrom = vDateSumTo - INTERVAL vScopeDays DAY; + SET vDateSumTo = vDateSumTo - INTERVAL 1 DAY; + + INSERT INTO itemCampaign(dated, itemFk, quantity, total, campaign) + SELECT vYesterday, + s.itemFk, + SUM(s.quantity) quantity, + SUM((s.quantity * s.price) * (100 - s.discount) / 100) total, + vCampaign + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN client c ON c.id = t.clientFk + WHERE t.shipped BETWEEN vDateSumFrom AND util.dayEnd(vDateSumTo) + AND c.typeFk = 'normal' + AND NOT t.isDeleted + GROUP BY s.itemFk + HAVING quantity; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59767,8 +60132,9 @@ proc: BEGIN DECLARE vReservedQuantity INT; DECLARE vOutStanding INT; DECLARE vUserFk INT; - DECLARE vTotalReservedQuantity INT; + DECLARE vTotalReservedQuantity INT; DECLARE vSaleQuantity INT; + DECLARE vIsRequiredTx BOOL DEFAULT NOT @@in_transaction; DECLARE vItemShelvingAvailable CURSOR FOR SELECT ish.id itemShelvingFk, @@ -59778,7 +60144,7 @@ proc: BEGIN JOIN shelving sh ON sh.code = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk - JOIN productionConfig pc + JOIN productionConfig pc WHERE s.id = vSaleFk AND NOT sc.isHideForPickers AND (sc.id = vSectorFk OR vSectorFk IS NULL) @@ -59793,15 +60159,15 @@ proc: BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - ROLLBACK; + CALL util.tx_rollback(vIsRequiredTx); RESIGNAL; END; - - START TRANSACTION; - + + CALL util.tx_start(vIsRequiredTx); + SELECT id INTO vSaleFk FROM sale - WHERE id = vSaleFk + WHERE id = vSaleFk FOR UPDATE; SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)), s.quantity @@ -59814,7 +60180,7 @@ proc: BEGIN WHERE s.id = vSaleFk; IF vOutStanding <= 0 THEN - COMMIT; + CALL util.tx_commit(vIsRequiredTx); LEAVE proc; END IF; @@ -59834,7 +60200,7 @@ proc: BEGIN IF vTotalReservedQuantity <> vSaleQuantity THEN CALL util.debugAdd('itemShelvingSale_addBySale', CONCAT(vSaleFk, ' - ', vSaleQuantity,' - ', vTotalReservedQuantity,'-', vOutStanding,'-', account.myUser_getId())); - + UPDATE sale SET quantity = vTotalReservedQuantity WHERE id = vSaleFk; @@ -59842,7 +60208,7 @@ proc: BEGIN LEAVE l; END IF; - SELECT id INTO vItemShelvingFk + SELECT id INTO vItemShelvingFk FROM itemShelving WHERE id = vItemShelvingFk FOR UPDATE; @@ -59851,19 +60217,19 @@ proc: BEGIN SET vOutStanding = vOutStanding - vReservedQuantity; IF vReservedQuantity > 0 THEN - CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity', - CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId())); - INSERT INTO itemShelvingSale( - itemShelvingFk, - saleFk, - quantity, - userFk, - isPicked) - SELECT vItemShelvingFk, - vSaleFk, - vReservedQuantity, - vUserFk, - FALSE; + CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity', + CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId())); + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk, + isPicked) + SELECT vItemShelvingFk, + vSaleFk, + vReservedQuantity, + vUserFk, + FALSE; UPDATE itemShelving SET available = available - vReservedQuantity @@ -59872,7 +60238,7 @@ proc: BEGIN END IF; END LOOP; CLOSE vItemShelvingAvailable; - COMMIT; + CALL util.tx_commit(vIsRequiredTx); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60000,6 +60366,68 @@ 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_deleteAdded` */; +/*!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=`vn`@`localhost` PROCEDURE `itemShelvingSale_deleteAdded`( + vSelf INT(11) +) +proc: BEGIN +/** + * Borra una reservea devolviendo la cantidad al itemShelving + * + * @param vSelf Identificador del itemShelvingSale + */ + DECLARE vSaleFk INT; + DECLARE vHasSalesPicked BOOL; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT iss.saleFk INTO vSaleFk + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vSelf AND s.isAdded + FOR UPDATE; + + IF vSaleFk IS NULL THEN + CALL util.throw('The sale can not be deleted'); + END IF; + + SELECT COUNT(*) INTO vHasSalesPicked + FROM itemShelvingSale + WHERE saleFk = vSaleFk AND isPicked; + + IF vHasSalesPicked THEN + CALL util.throw('A sale with picked sales cannot be deleted'); + END IF; + + UPDATE itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + SET ish.available = ish.available + iss.quantity + WHERE iss.saleFk = vSaleFk; + + DELETE FROM sale WHERE id = vSaleFk; + + COMMIT; +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_doReserve` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -60517,18 +60945,24 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_addList`(vShelvingFk VARCHAR(3), vList TEXT, vIsChecking BOOL, vWarehouseFk INT) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_addList`( + vShelvingFk VARCHAR(3), + vList TEXT, + vIsChecking BOOL, + vWarehouseFk INT +) BEGIN -/* Recorre cada elemento en la colección vList. +/** + * Recorre cada elemento en la colección vList. * Si el parámetro isChecking = FALSE, llama a itemShelving_add. * * Cuando es TRUE sólo inserta los elementos de la colección que no están ya en - * ese shelving, actualizando los valores del campo vn.itemShelving.isChecked + * ese shelving, actualizando los valores del campo itemShelving.isChecked * - * param vShelvingFk Identificador de vn.shelving - * param vList JSON array con esta estructura: '[value1, value2, ...]' - * param vIsChecking Define si hay que añadir o comprobar los items - * param vWarehouseFk Identificador de vn.warehouse + * @param vShelvingFk Identificador de shelving + * @param vList JSON array con esta estructura: '[value1, value2, ...]' + * @param vIsChecking Define si hay que añadir o comprobar los items + * @param vWarehouseFk Identificador de warehouse */ DECLARE vListLength INT DEFAULT JSON_LENGTH(vList); DECLARE vCounter INT DEFAULT 0; @@ -60538,26 +60972,27 @@ BEGIN DECLARE vIsChecked BOOL; WHILE vCounter < vListLength DO - SET vPath = CONCAT('$[',vCounter,']'); - SET vBarcode = JSON_EXTRACT(vList,vPath); + SET vPath = CONCAT('$[', vCounter, ']'); + SET vBarcode = JSON_EXTRACT(vList, vPath); SET vIsChecked = NULL; IF vIsChecking THEN SELECT barcodeToItem(vBarcode) INTO vItemFk; - SELECT COUNT(*) INTO vIsChecked - FROM vn.itemShelving + SELECT IF(COUNT(*), TRUE, FALSE) INTO vIsChecked + FROM itemShelving WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk; END IF; - IF NOT (vIsChecking AND vIsChecked) THEN - CALL vn.itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); + IF NOT vIsChecking OR NOT vIsChecked THEN + CALL itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); END IF; - UPDATE vn.itemShelving + UPDATE itemShelving SET isChecked = vIsChecked WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk AND isChecked IS NULL; + AND itemFk = vItemFk + AND isChecked IS NULL; SET vCounter = vCounter + 1; END WHILE; @@ -61625,6 +62060,58 @@ SET tag8 = t.name, value8 = it.value WHERE it.priority = 4 AND (vItem IS NULL OR vItem = it.itemFk); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_calculateStock` */; +/*!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=`vn`@`localhost` PROCEDURE `item_calculateStock`( + vDated DATE +) +BEGIN +/** + * Calculate the stock of the auction warehouse from the inventory date to vDated + * + * @param vDated Date to calculate the stock. + * @return tmp.item, tmp.buyUltimate + */ + DECLARE vAuctionWarehouseFk INT; + + SELECT warehouseFk INTO vAuctionWarehouseFk + FROM auctionConfig; + + CREATE OR REPLACE TEMPORARY TABLE tmp.item + (UNIQUE INDEX i USING HASH (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) quantity + FROM itemEntryIn + WHERE landed = vDated + AND vDated >= util.VN_CURDATE() + AND warehouseInFk = vAuctionWarehouseFk + AND NOT isVirtualStock + GROUP BY itemFk + HAVING quantity; + + CALL `cache`.stock_refresh(FALSE); + + INSERT INTO tmp.item (itemFk, quantity) + SELECT item_id, amount + FROM `cache`.stock + WHERE warehouse_id = vAuctionWarehouseFk + ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity); + + CALL buy_getUltimate(NULL, vAuctionWarehouseFk, vDated); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63380,19 +63867,23 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `item_getSimilar`( ) BEGIN /** -* Propone articulos ordenados, con la cantidad -* de veces usado y segun sus caracteristicas. -* -* @param vSelf Id de artículo -* @param vWarehouseFk Id de almacen -* @param vDated Fecha -* @param vShowType Mostrar tipos -* @param vDaysInForward Días de alcance para las ventas -*/ + * Propone articulos ordenados, con la cantidad + * de veces usado y segun sus caracteristicas. + * + * @param vSelf Id de artículo + * @param vWarehouseFk Id de almacen + * @param vDated Fecha + * @param vShowType Mostrar tipos + * @param vDaysInForward Días de alcance para las ventas (https://redmine.verdnatura.es/issues/7956#note-4) + */ DECLARE vAvailableCalcFk INT; + DECLARE vVisibleCalcFk INT; + DECLARE vTypeFk INT; DECLARE vPriority INT DEFAULT 1; CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); + CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); + CALL buy_getUltimate(NULL, vWarehouseFk, vDated); WITH itemTags AS ( SELECT i.id, @@ -63412,25 +63903,9 @@ BEGIN AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk WHERE i.id = vSelf - ), - stock AS ( - SELECT itemFk, SUM(visible) stock - FROM vn.itemShelvingStock - WHERE warehouseFk = vWarehouseFk - GROUP BY itemFk - ), - sold AS ( - SELECT SUM(s.quantity) quantity, s.itemFk - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id - WHERE t.shipped >= CURDATE() + INTERVAL vDaysInForward DAY - AND iss.saleFk IS NULL - AND t.warehouseFk = vWarehouseFk - GROUP BY s.itemFk ) SELECT i.id itemFk, - LEAST(CAST(sd.quantity AS INT), sk.stock) advanceable, + NULL advanceable, -- https://redmine.verdnatura.es/issues/7956#note-4 i.longName, i.subName, i.tag5, @@ -63452,38 +63927,38 @@ BEGIN WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 END minQuantity, - sk.stock located, + v.visible located, b.price2 FROM vn.item i - LEFT JOIN sold sd ON sd.itemFk = i.id JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vAvailableCalcFk - LEFT JOIN stock sk ON sk.itemFk = i.id - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - AND lb.warehouse_id = vWarehouseFk + LEFT JOIN cache.visible v ON v.item_id = i.id + AND v.calc_id = vVisibleCalcFk + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.id LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.buy b ON b.id = bu.buyFk JOIN itemTags its - WHERE (a.available > 0 OR sd.quantity < sk.stock) + WHERE a.available > 0 AND (i.typeFk = its.typeFk OR NOT vShowType) AND i.id <> vSelf - ORDER BY (a.available > 0) DESC, - `counter` DESC, - (t.name = its.name) DESC, - (it.value = its.value) DESC, - (i.tag5 = its.tag5) DESC, - match5 DESC, - (i.tag6 = its.tag6) DESC, - match6 DESC, - (i.tag7 = its.tag7) DESC, - match7 DESC, - (i.tag8 = its.tag8) DESC, - match8 DESC + ORDER BY `counter` DESC, + (t.name = its.name) DESC, + (it.value = its.value) DESC, + (i.tag5 = its.tag5) DESC, + match5 DESC, + (i.tag6 = its.tag6) DESC, + match6 DESC, + (i.tag7 = its.tag7) DESC, + match7 DESC, + (i.tag8 = its.tag8) DESC, + match8 DESC LIMIT 100; + + DROP TEMPORARY TABLE tmp.buyUltimate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66055,13 +66530,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; - SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY - INTO vEndingDate - FROM productionConfig; - - SELECT isTodayRelative INTO vIsTodayRelative - FROM worker - WHERE id = getUser(); -- Cambiar por account.myUser_getId(), falta dar permisos + SELECT w.isTodayRelative, util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, pc.maxProductionScopeDays) DAY + INTO vIsTodayRelative,vEndingDate + FROM worker w + JOIN productionConfig pc + WHERE w.id = account.myUser_getId(); CALL prepareTicketList(util.yesterday(), vEndingDate); @@ -66308,15 +66781,14 @@ proc: BEGIN UPDATE tmp.productionBuffer pb JOIN sale s ON s.ticketFk = pb.ticketFk JOIN item i ON i.id = s.itemFk - JOIN cache.last_buy lb ON lb.warehouse_id = vWarehouseFk + JOIN cache.last_buy lb ON lb.warehouse_id = vWarehouseFk AND lb.item_id = s.itemFk JOIN buy b ON b.id = lb.buy_id JOIN packaging p ON p.id = b.packagingFk - JOIN productionConfig pc SET pb.hasPlantTray = TRUE WHERE p.isPlantTray AND s.quantity >= b.packing - AND pb.isOwn; + AND pb.isOwn; DROP TEMPORARY TABLE tmp.productionTicket, @@ -66691,6 +67163,47 @@ 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 `queueMember_updateQueue` */; +/*!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=`vn`@`localhost` PROCEDURE `queueMember_updateQueue`( + vBusinessFk INT +) +BEGIN + /** + * Elimina la entrada de la cola anterior y luego inserta la nueva para un trabajador. + * + * @param vBusinessFk ID del negocio + */ + DECLARE vNewQueue VARCHAR(10); + DECLARE vExtension VARCHAR(10); + DECLARE exit handler FOR SQLEXCEPTION + + SELECT d.pbxQueue, s.extension + INTO vNewQueue, vExtension + FROM business b + JOIN department d ON d.id = b.departmentFk + JOIN pbx.sip s ON s.user_id = b.workerFk + WHERE b.id = vBusinessFk; + + DELETE FROM pbx.queueMember + WHERE extension = vExtension COLLATE utf8_general_ci; + + INSERT IGNORE INTO pbx.queueMember (queue, extension) + VALUES (vNewQueue, vExtension); +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 `raidUpdate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -68192,6 +68705,39 @@ 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 `saleTracking_sectorCollectionAddPrevOK` */; +/*!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=`vn`@`localhost` PROCEDURE `saleTracking_sectorCollectionAddPrevOK`( + vSectorCollectionFk INT +) +BEGIN +/** + * Inserta los registros de sectorCollection con el estado PREVIA OK si la reserva está picked + * + * @param vSectorCollectionFk Identificador de vn.sectorCollection + */ + REPLACE saleTracking(saleFk, isChecked, workerFk, stateFk) + SELECT sgd.saleFk, TRUE, sc.userFk, s.id + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + JOIN saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + JOIN state s ON s.code = 'OK PREVIOUS' + JOIN itemShelvingSale iss ON iss.saleFk = sgd.saleFk + WHERE sc.id = vSectorCollectionFk AND iss.isPicked; +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 `saleTracking_updateIsChecked` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -68834,7 +69380,7 @@ BEGIN isTooLittle BOOL DEFAULT FALSE, isVip BOOL DEFAULT FALSE, PRIMARY KEY (ticketFk, saleFk) - ) ENGINE = MEMORY; + ); -- No memory INSERT INTO tmp.sale_problems(ticketFk, saleFk, @@ -70238,13 +70784,13 @@ proc: BEGIN * Calculate the stock of the auction warehouse from the inventory date to vDated * without taking into account the outputs of the same day vDated * - * @param vDated Date to calculate the stock. + * @param vDated Date to calculate the stock */ IF vDated < util.VN_CURDATE() THEN LEAVE proc; END IF; - CREATE OR REPLACE TEMPORARY TABLE tStockBought + CREATE OR REPLACE TEMPORARY TABLE tCurrentData SELECT workerFk, reserve FROM stockBought WHERE dated = vDated @@ -70252,15 +70798,28 @@ proc: BEGIN DELETE FROM stockBought WHERE dated = vDated; + CREATE OR REPLACE TEMPORARY TABLE tStockSold + SELECT it.workerFk, + SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000) sold + FROM itemTicketOut ito + JOIN item i ON i.id = ito.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN ticket t ON t.id = ito.ticketFk + JOIN warehouse wh ON wh.id = t.warehouseFk + JOIN itemCost ic ON ic.itemFk = ito.itemFk + AND ic.warehouseFk = t.warehouseFk + JOIN volumeConfig vc + WHERE ito.shipped BETWEEN vDated AND util.dayEnd(vDated) + AND wh.code = 'VNH' + GROUP BY it.workerFk; + CALL item_calculateStock(vDated); - INSERT INTO stockBought(workerFk, bought, dated) + CREATE OR REPLACE TEMPORARY TABLE tStockBought SELECT it.workerFk, - ROUND(SUM( - (ti.quantity / b.packing) * - buy_getVolume(b.id) - ) / vc.palletM3 / 1000000, 1) bought, - vDated + SUM((ti.quantity / b.packing) * + buy_getVolume(b.id) + ) / vc.palletM3 / 1000000 bought FROM itemType it JOIN item i ON i.typeFk = it.id LEFT JOIN tmp.item ti ON ti.itemFk = i.id @@ -70274,245 +70833,34 @@ proc: BEGIN GROUP BY it.workerFk HAVING bought; + + INSERT INTO stockBought(workerFk, bought, dated) + SELECT tb.workerFk, + ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 1), + vDated + FROM tStockBought tb + LEFT JOIN tStockSold ts ON ts.workerFk = tb.workerFk; + UPDATE stockBought s - JOIN tStockBought ts ON ts.workerFk = s.workerFk + JOIN tCurrentData ts ON ts.workerFk = s.workerFk SET s.reserve = ts.reserve WHERE s.dated = vDated; INSERT INTO stockBought (workerFk, reserve, dated) SELECT ts.workerFk, ts.reserve, vDated - FROM tStockBought ts + FROM tCurrentData ts WHERE ts.workerFk NOT IN ( SELECT workerFk FROM stockBought WHERE dated = vDated ); - DROP TEMPORARY TABLE tStockBought, tmp.item, tmp.buyUltimate; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorker` */; -/*!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=`vn`@`localhost` PROCEDURE `stockBuyedByWorker`( - vDated DATE, - vWorker INT -) -BEGIN -/** - * Inserta el volumen de compra de un comprador - * en stockBuyed de acuerdo con la fecha. - * - * @param vDated Fecha de compra - * @param vWorker Id de trabajador - */ - CREATE OR REPLACE TEMPORARY TABLE tStockBuyed - (INDEX (userFk)) - ENGINE = MEMORY - SELECT requested, reserved, userFk - FROM stockBuyed - WHERE dated = vDated - AND userFk = vWorker; - - DELETE FROM stockBuyed - WHERE dated = vDated - AND userFk = vWorker; - - CALL stockTraslation(vDated); - - INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description) - SELECT it.workerFk, - SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, - vDated, - sb.reserved, - sb.requested, - u.name - FROM itemType it - JOIN item i ON i.typeFk = it.id - LEFT JOIN tmp.item ti ON ti.itemFk = i.id - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN warehouse wh ON wh.code = 'VNH' - JOIN tmp.buyUltimate bu ON bu.itemFk = i.id - AND bu.warehouseFk = wh.id - JOIN buy b ON b.id = bu.buyFk - JOIN volumeConfig vc - JOIN account.`user` u ON u.id = it.workerFk - LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk - WHERE ic.display - AND it.workerFk = vWorker; - - SELECT b.entryFk Id_Entrada, - i.id Id_Article, - i.name Article, - ti.quantity Cantidad, - (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) - / (vc.trolleyM3 * 1000000) buyed, - b.packagingFk id_cubo, - b.packing - FROM tmp.item ti - JOIN item i ON i.id = ti.itemFk - JOIN itemType it ON i.typeFk = it.id - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN worker w ON w.id = it.workerFk - JOIN auctionConfig ac - JOIN tmp.buyUltimate bu ON bu.itemFk = i.id - AND bu.warehouseFk = ac.warehouseFk - JOIN buy b ON b.id = bu.buyFk - JOIN volumeConfig vc - WHERE ic.display - AND w.id = vWorker; - - DROP TEMPORARY TABLE tmp.buyUltimate, - tmp.item, - tStockBuyed; -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 `stockBuyed_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `stockBuyed_add`( - vDated DATE -) -BEGIN -/** - * Inserta el volumen de compra por comprador - * en stockBuyed de acuerdo con la fecha. - * - * @param vDated Fecha de compra - */ - CREATE OR REPLACE TEMPORARY TABLE tStockBuyed - (INDEX (userFk)) - ENGINE = MEMORY - SELECT requested, reserved, userFk - FROM stockBuyed - WHERE dated = vDated; - - DELETE FROM stockBuyed WHERE dated = vDated; - - CALL stockTraslation(vDated); - - INSERT INTO stockBuyed(userFk, buyed, `dated`, description) - SELECT it.workerFk, - SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, - vDated, - u.name - FROM itemType it - JOIN item i ON i.typeFk = it.id - LEFT JOIN tmp.item ti ON ti.itemFk = i.id - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN warehouse wh ON wh.code = 'VNH' - JOIN tmp.buyUltimate bu ON bu.itemFk = i.id AND bu.warehouseFk = wh.id - JOIN buy b ON b.id = bu.buyFk - JOIN volumeConfig vc - JOIN account.`user` u ON u.id = it.workerFk - JOIN workerDepartment wd ON wd.workerFk = u.id - JOIN department d ON d.id = wd.departmentFk - WHERE ic.display - AND d.code IN ('shopping', 'logistic', 'franceTeam') - GROUP BY it.workerFk; - - INSERT INTO stockBuyed(buyed, dated, description) - SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000), - vDated, - IF(c.code = 'ES', p.name, c.name) destiny - FROM itemTicketOut ito - JOIN ticket t ON t.id = ito.ticketFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country c ON c.id = p.countryFk - JOIN warehouse wh ON wh.id = t.warehouseFk - JOIN itemCost ic ON ic.itemFk = ito.itemFk - AND ic.warehouseFk = t.warehouseFk - JOIN volumeConfig vc - WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated) - AND wh.code = 'VNH' - GROUP BY destiny; - - UPDATE stockBuyed s - JOIN tStockBuyed ts ON ts.userFk = s.userFk - SET s.requested = ts.requested, - s.reserved = ts.reserved + UPDATE stockBought s + JOIN tStockSold ts ON ts.workerFk = s.workerFk + SET s.bought = IF(s.bought < ts.sold, ROUND(s.bought - ts.sold, 1), 0) WHERE s.dated = vDated; - DROP TEMPORARY TABLE tmp.buyUltimate, - tmp.item, - tStockBuyed; -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 `stockTraslation` */; -/*!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=`vn`@`localhost` PROCEDURE `stockTraslation`( - vDated DATE -) -BEGIN -/** - * Calcula el stock del almacén de subasta desde FechaInventario hasta vDated - * sin tener en cuenta las salidas del mismo dia vDated - * para ver el transporte a reservar - * - * @param vDated Fecha hasta la cual calcula el stock - * @return tmp.item - */ - DECLARE vAuctionWarehouseFk INT; - - SELECT warehouseFk INTO vAuctionWarehouseFk - FROM auctionConfig; - - CREATE OR REPLACE TEMPORARY TABLE tmp.item - (UNIQUE INDEX i USING HASH (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(quantity) quantity - FROM itemEntryIn - WHERE landed = vDated - AND vDated >= util.VN_CURDATE() - AND warehouseInFk = vAuctionWarehouseFk - AND NOT isVirtualStock - GROUP BY itemFk - HAVING quantity; - - CALL `cache`.stock_refresh(FALSE); - - INSERT INTO tmp.item (itemFk, quantity) - SELECT item_id, amount - FROM `cache`.stock - WHERE warehouse_id = vAuctionWarehouseFk - ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity); - - CALL buy_getUltimate(NULL, vAuctionWarehouseFk, vDated); + DROP TEMPORARY TABLE tCurrentData, tmp.item, tmp.buyUltimate, tStockSold; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72250,6 +72598,44 @@ 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 `ticketRefund_upsert` */; +/*!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=`vn`@`localhost` PROCEDURE `ticketRefund_upsert`( + vRefundTicketFk INT, + vOriginalTicketFk INT +) + READS SQL DATA +BEGIN +/** + * Common code for ticketRefund triggers + * + * @param vRefundTicketFk + * @param vOriginalTicketFk + */ + DECLARE vIsDeleted BOOL; + + SELECT COUNT(*) INTO vIsDeleted + FROM ticket + WHERE id IN (vRefundTicketFk, vOriginalTicketFk) + AND isDeleted; + + IF vIsDeleted THEN + CALL util.throw('The refund ticket cannot be deleted tickets'); + 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 `ticketStateToday_setState` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -72655,7 +73041,8 @@ BEGIN origin.companyFk futureCompanyFk, IFNULL(dest.nickname, origin.nickname) nickname, dest.landed, - dest.preparation + dest.preparation, + origin.departmentFk FROM ( SELECT s.ticketFk, c.salesPersonFk workerFk, @@ -72675,9 +73062,11 @@ BEGIN t.addressFk, t.warehouseFk, t.companyFk, - t.agencyModeFk + t.agencyModeFk, + wd.departmentFk FROM ticket t JOIN client c ON c.id = t.clientFk + JOIN workerDepartment wd ON wd.workerFk = c.salesPersonFk JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id JOIN item i ON i.id = s.itemFk @@ -73394,7 +73783,7 @@ BEGIN c.isTaxDataChecked, t.companyFk, t.shipped, - IFNULL(a.hasDailyInvoice, co.hasDailyInvoice), + c.hasDailyInvoice, w.isManaged, c.hasToInvoice INTO vClientFk, @@ -73406,9 +73795,6 @@ BEGIN vHasToInvoice FROM ticket t JOIN `client` c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - LEFT JOIN autonomy a ON a.id = p.autonomyFk - JOIN country co ON co.id = p.countryFk JOIN warehouse w ON w.id = t.warehouseFk WHERE t.id = vCurTicketFk; @@ -73436,7 +73822,7 @@ BEGIN IF(vHasDailyInvoice) AND vHasToInvoice THEN SELECT invoiceSerial(vClientFk, vCompanyFk, 'quick') INTO vSerial; - IF vSerial IS NULL THEN + IF vSerial IS NULL THEN CALL util.throw('Cannot booking without a serial'); END IF; @@ -74401,7 +74787,9 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_getTax`(IN vTaxArea VARCHAR(25)) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_getTax`( + vTaxArea VARCHAR(25) +) BEGIN /** * Calcula la base imponible, el IVA y el recargo de equivalencia para @@ -74435,30 +74823,39 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.ticketTax (PRIMARY KEY (ticketFk, code, rate)) ENGINE = MEMORY - SELECT * FROM ( - SELECT tmpTicket.ticketFk, - bp.pgcFk, - SUM(s.quantity * s.price * (100 - s.discount) / 100 ) taxableBase, - pgc.rate, - tc.code, - bp.priority - FROM tmp.ticket tmpTicket - JOIN sale s ON s.ticketFk = tmpTicket.ticketFk - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = tmpTicket.ticketFk - JOIN supplier su ON su.id = t.companyFk + WITH sales AS ( + SELECT s.ticketFk, + s.itemFk, + s.quantity * s.price * (100 - s.discount) / 100 total, + t.companyFk, + t.addressFk, + su.countryFk, + ata.areaFk, + itc.taxClassFk + FROM vn.sale s + JOIN tmp.ticket tmp ON tmp.ticketFk = s.ticketFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.supplier su ON su.id = t.companyFk JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc ON itc.itemFk = i.id + JOIN vn.itemTaxCountry itc ON itc.itemFk = s.itemFk AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp ON bp.countryFk = su.countryFk - AND bp.taxAreaFk = ata.areaFk - AND bp.taxClassFk = itc.taxClassFk - JOIN pgc ON pgc.code = bp.pgcFk - JOIN taxClass tc ON tc.id = bp.taxClassFk - GROUP BY tmpTicket.ticketFk, pgc.code, pgc.rate - HAVING taxableBase - ) t3 + HAVING total + ) + SELECT s.ticketFk, + bp.pgcFk, + SUM(s.total) taxableBase, + pgc.rate, + tc.code, + bp.priority + FROM sales s + JOIN vn.bookingPlanner bp ON bp.countryFk = s.countryFk + AND bp.taxAreaFk = s.areaFk + AND bp.taxClassFk = s.taxClassFk + JOIN vn.pgc ON pgc.code = bp.pgcFk + JOIN vn.taxClass tc ON tc.id = bp.taxClassFk + GROUP BY s.ticketFk, pgc.code, pgc.rate + HAVING taxableBase ORDER BY priority; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketServiceTax @@ -74681,12 +75078,25 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_mergeSales`( vSelf INT ) BEGIN +/** + * Para un ticket se agrupa las diferentes líneas de venta de un mismo artículo en una sola + * siempre y cuando tengan el mismo precio y dto. + * + * @param vSelf Id de ticket + */ + DECLARE vHasSalesToMerge BOOL; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; + START TRANSACTION; + + SELECT id INTO vSelf + FROM ticket + WHERE id = vSelf FOR UPDATE; + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve (PRIMARY KEY (id)) ENGINE = MEMORY @@ -74696,26 +75106,24 @@ BEGIN JOIN itemType it ON it.id = i.typeFk WHERE s.ticketFk = vSelf AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; + GROUP BY s.itemFk, s.price, s.discount + HAVING COUNT(*) > 1; - START TRANSACTION; + SELECT COUNT(*) INTO vHasSalesToMerge FROM tSalesToPreserve; - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET s.quantity = newQuantity - WHERE s.ticketFk = vSelf; + IF vHasSalesToMerge THEN + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET s.quantity = newQuantity; - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vSelf - AND stp.id IS NULL - AND it.isMergeable; + DELETE s + FROM sale s + JOIN tSalesToPreserve stp ON stp.itemFk = s.itemFk + WHERE s.ticketFk = vSelf + AND s.id <> stp.id; + END IF; COMMIT; - DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; @@ -75856,125 +76264,88 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_splitItemPackingType`( vSelf INT, vOriginalItemPackingTypeFk VARCHAR(1) ) -BEGIN +proc:BEGIN /** - * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. - * Respeta el id inicial para el tipo propuesto. + * Clona y reparte las líneas de ventas de un ticket en funcion del tipo de empaquetado. + * Respeta el id de ticket original para el tipo de empaquetado propuesto. * * @param vSelf Id ticket - * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original + * @param vOriginalItemPackingTypeFk Tipo empaquetado que se mantiene el ticket original * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ - DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; - DECLARE vNewTicketFk INT; - DECLARE vPackingTypesToSplit INT; DECLARE vDone INT DEFAULT FALSE; + DECLARE vHasItemPackingType BOOL; + DECLARE vItemPackingTypeFk INT; + DECLARE vNewTicketFk INT; - DECLARE vSaleGroup CURSOR FOR - SELECT itemPackingTypeFk - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL - ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC; + DECLARE vItemPackingTypes CURSOR FOR + SELECT DISTINCT itemPackingTypeFk + FROM tSalesToMove; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - START TRANSACTION; - - SELECT id - FROM sale - WHERE ticketFk = vSelf - AND NOT quantity - FOR UPDATE; - - DELETE FROM sale - WHERE NOT quantity - AND ticketFk = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tSale - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT s.id, i.itemPackingTypeFk, IFNULL(sv.litros, 0) litros - FROM sale s - JOIN item i ON i.id = s.itemFk - LEFT JOIN saleVolume sv ON sv.saleFk = s.id - WHERE s.ticketFk = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tSaleGroup - ENGINE = MEMORY - SELECT itemPackingTypeFk, SUM(litros) totalLitros - FROM tSale - GROUP BY itemPackingTypeFk; - - SELECT COUNT(*) INTO vPackingTypesToSplit - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL; + SELECT COUNT(*) INTO vHasItemPackingType + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE t.id = vSelf + AND i.itemPackingTypeFk = vOriginalItemPackingTypeFk; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) - ) ENGINE = MEMORY; + ) ENGINE=MEMORY + SELECT vSelf ticketFk, vOriginalItemPackingTypeFk itemPackingTypeFk; - CASE vPackingTypesToSplit - WHEN 0 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vSelf, vItemPackingTypeFk); - WHEN 1 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - SELECT vSelf, itemPackingTypeFk - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL; - ELSE - OPEN vSaleGroup; - FETCH vSaleGroup INTO vItemPackingTypeFk; + IF NOT vHasItemPackingType THEN + LEAVE proc; + END IF; - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vSelf, vItemPackingTypeFk); + CREATE OR REPLACE TEMPORARY TABLE tSalesToMove ( + ticketFk INT, + saleFk INT, + itemPackingTypeFk INT + ) ENGINE=MEMORY; - l: LOOP - SET vDone = FALSE; - FETCH vSaleGroup INTO vItemPackingTypeFk; + INSERT INTO tSalesToMove (saleFk, itemPackingTypeFk) + SELECT s.id, i.itemPackingTypeFk + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE t.id = vSelf + AND i.itemPackingTypeFk <> vOriginalItemPackingTypeFk; - IF vDone THEN - LEAVE l; - END IF; + OPEN vItemPackingTypes; - CALL ticket_Clone(vSelf, vNewTicketFk); + l: LOOP + SET vDone = FALSE; + FETCH vItemPackingTypes INTO vItemPackingTypeFk; - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vNewTicketFk, vItemPackingTypeFk); - END LOOP; + IF vDone THEN + LEAVE l; + END IF; - CLOSE vSaleGroup; + CALL ticket_Clone(vSelf, vNewTicketFk); - SELECT s.id - FROM sale s - JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk - FOR UPDATE; + UPDATE tSalesToMove + SET ticketFk = vNewTicketFk + WHERE itemPackingTypeFk = vItemPackingTypeFk; - UPDATE sale s - JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk - SET s.ticketFk = t.ticketFk; + END LOOP; - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM tSaleGroup sg - WHERE sg.itemPackingTypeFk IS NOT NULL - ORDER BY sg.itemPackingTypeFk - LIMIT 1; + CLOSE vItemPackingTypes; - UPDATE sale s - JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk - SET s.ticketFk = t.ticketFk - WHERE ts.itemPackingTypeFk IS NULL; - END CASE; + UPDATE sale s + JOIN tSalesToMove stm ON stm.saleFk = s.id + SET s.ticketFk = stm.ticketFk + WHERE stm.ticketFk; - COMMIT; + INSERT INTO tmp.ticketIPT (ticketFk, itemPackingTypeFk) + SELECT ticketFk, itemPackingTypeFk + FROM tSalesToMove + GROUP BY ticketFk; - DROP TEMPORARY TABLE - tSale, - tSaleGroup; + DROP TEMPORARY TABLE tSalesToMove; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80405,6 +80776,8 @@ BEGIN SET businessFk = vNewBusinessFk WHERE id = vSelf; + CALL queueMember_updateQueue(vNewBusinessFk); + IF vOldBusinessFk IS NULL THEN CALL account.account_enable(vSelf); @@ -82245,7 +82618,6 @@ SET character_set_client = utf8; 1 AS `send_mail`, 1 AS `tpv`, 1 AS `code`, - 1 AS `show_AgencyName`, 1 AS `isRiskFree` */; SET character_set_client = @saved_cs_client; @@ -82416,7 +82788,6 @@ SET character_set_client = utf8; 1 AS `credito`, 1 AS `Id_Pais`, 1 AS `activo`, - 1 AS `gestdoc_id`, 1 AS `calidad`, 1 AS `pay_met_id`, 1 AS `created`, @@ -82496,21 +82867,6 @@ SET character_set_client = utf8; 1 AS `itemOriginalFk` */; SET character_set_client = @saved_cs_client; --- --- Temporary table structure for view `Compres_mark` --- - -DROP TABLE IF EXISTS `Compres_mark`; -/*!50001 DROP VIEW IF EXISTS `Compres_mark`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Compres_mark` AS SELECT - 1 AS `Id_Compra`, - 1 AS `comment`, - 1 AS `mark`, - 1 AS `odbc_date` */; -SET character_set_client = @saved_cs_client; - -- -- Temporary table structure for view `Consignatarios` -- @@ -88082,7 +88438,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Agencias` AS select `am`.`id` AS `Id_Agencia`,`am`.`name` AS `Agencia`,`am`.`description` AS `description`,`am`.`deliveryMethodFk` AS `Vista`,`am`.`m3` AS `m3`,`am`.`web` AS `web`,`am`.`agencyFk` AS `agency_id`,`am`.`inflation` AS `inflacion`,`am`.`isVolumetric` AS `is_volumetric`,`am`.`reportMail` AS `send_mail`,`am`.`isActive` AS `tpv`,`am`.`code` AS `code`,`am`.`showAgencyName` AS `show_AgencyName`,`am`.`isRiskFree` AS `isRiskFree` from `vn`.`agencyMode` `am` */; +/*!50001 VIEW `Agencias` AS select `am`.`id` AS `Id_Agencia`,`am`.`name` AS `Agencia`,`am`.`description` AS `description`,`am`.`deliveryMethodFk` AS `Vista`,`am`.`m3` AS `m3`,`am`.`web` AS `web`,`am`.`agencyFk` AS `agency_id`,`am`.`inflation` AS `inflacion`,`am`.`isVolumetric` AS `is_volumetric`,`am`.`reportMail` AS `send_mail`,`am`.`isActive` AS `tpv`,`am`.`code` AS `code`,`am`.`isRiskFree` AS `isRiskFree` from `vn`.`agencyMode` `am` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88172,7 +88528,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Clientes` AS select `c`.`id` AS `id_cliente`,`c`.`name` AS `cliente`,`c`.`fi` AS `if`,`c`.`socialName` AS `razonSocial`,`c`.`contact` AS `contacto`,`c`.`street` AS `domicilio`,`c`.`city` AS `poblacion`,`c`.`postcode` AS `codPostal`,`c`.`phone` AS `telefono`,`c`.`mobile` AS `movil`,`c`.`isRelevant` AS `real`,`c`.`email` AS `e-mail`,`c`.`iban` AS `iban`,`c`.`dueDay` AS `vencimiento`,`c`.`accountingAccount` AS `Cuenta`,`c`.`isEqualizated` AS `RE`,`c`.`provinceFk` AS `province_id`,`c`.`hasToInvoice` AS `invoice`,`c`.`credit` AS `credito`,`c`.`countryFk` AS `Id_Pais`,`c`.`isActive` AS `activo`,`c`.`gestdocFk` AS `gestdoc_id`,`c`.`quality` AS `calidad`,`c`.`payMethodFk` AS `pay_met_id`,`c`.`created` AS `created`,`c`.`isToBeMailed` AS `mail`,`c`.`contactChannelFk` AS `chanel_id`,`c`.`hasSepaVnl` AS `sepaVnl`,`c`.`hasCoreVnl` AS `coreVnl`,`c`.`hasCoreVnh` AS `coreVnh`,`c`.`hasLcr` AS `hasLcr`,`c`.`defaultAddressFk` AS `default_address`,`c`.`riskCalculated` AS `risk_calculated`,`c`.`hasToInvoiceByAddress` AS `invoiceByAddress`,`c`.`isTaxDataChecked` AS `contabilizado`,`c`.`isFreezed` AS `congelado`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`salesPersonFk` AS `Id_Trabajador`,`c`.`isVies` AS `vies`,`c`.`bankEntityFk` AS `bankEntityFk`,`c`.`typeFk` AS `typeFk` from `vn`.`client` `c` */; +/*!50001 VIEW `Clientes` AS select `c`.`id` AS `id_cliente`,`c`.`name` AS `cliente`,`c`.`fi` AS `if`,`c`.`socialName` AS `razonSocial`,`c`.`contact` AS `contacto`,`c`.`street` AS `domicilio`,`c`.`city` AS `poblacion`,`c`.`postcode` AS `codPostal`,`c`.`phone` AS `telefono`,`c`.`mobile` AS `movil`,`c`.`isRelevant` AS `real`,`c`.`email` AS `e-mail`,`c`.`iban` AS `iban`,`c`.`dueDay` AS `vencimiento`,`c`.`accountingAccount` AS `Cuenta`,`c`.`isEqualizated` AS `RE`,`c`.`provinceFk` AS `province_id`,`c`.`hasToInvoice` AS `invoice`,`c`.`credit` AS `credito`,`c`.`countryFk` AS `Id_Pais`,`c`.`isActive` AS `activo`,`c`.`quality` AS `calidad`,`c`.`payMethodFk` AS `pay_met_id`,`c`.`created` AS `created`,`c`.`isToBeMailed` AS `mail`,`c`.`contactChannelFk` AS `chanel_id`,`c`.`hasSepaVnl` AS `sepaVnl`,`c`.`hasCoreVnl` AS `coreVnl`,`c`.`hasCoreVnh` AS `coreVnh`,`c`.`hasLcr` AS `hasLcr`,`c`.`defaultAddressFk` AS `default_address`,`c`.`riskCalculated` AS `risk_calculated`,`c`.`hasToInvoiceByAddress` AS `invoiceByAddress`,`c`.`isTaxDataChecked` AS `contabilizado`,`c`.`isFreezed` AS `congelado`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`salesPersonFk` AS `Id_Trabajador`,`c`.`isVies` AS `vies`,`c`.`bankEntityFk` AS `bankEntityFk`,`c`.`typeFk` AS `typeFk` from `vn`.`client` `c` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88213,24 +88569,6 @@ USE `vn2008`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Final view structure for view `Compres_mark` --- - -/*!50001 DROP VIEW IF EXISTS `Compres_mark`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Compres_mark` AS select `bm`.`id` AS `Id_Compra`,`bm`.`comment` AS `comment`,`bm`.`mark` AS `mark`,`bm`.`odbcDate` AS `odbc_date` from `vn`.`buyMark` `bm` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Final view structure for view `Consignatarios` -- @@ -90472,4 +90810,4 @@ USE `vn2008`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-10-03 7:42:53 +-- Dump completed on 2024-11-12 7:06:20 diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index 74190df36..7152187bb 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -1128,6 +1128,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 */ ; +/*!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' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterInsert` + AFTER INSERT ON `orderRow` + FOR EACH ROW +BEGIN + UPDATE `order` + SET rowUpdated = util.VN_NOW() + WHERE id = NEW.orderFk; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Current Database: `pbx` @@ -2432,11 +2454,21 @@ DELIMITER ;; AFTER UPDATE ON `business` FOR EACH ROW BEGIN + DECLARE vIsActive BOOL; + DECLARE vExtension VARCHAR(10); + CALL worker_updateBusiness(NEW.workerFk); IF NOT (OLD.workerFk <=> NEW.workerFk) THEN CALL worker_updateBusiness(OLD.workerFk); END IF; + + IF NOT (OLD.departmentFk <=> NEW.departmentFk) THEN + SELECT COUNT(*) INTO vIsActive FROM worker WHERE businessFk = NEW.id; + IF vIsActive THEN + CALL queueMember_updateQueue(NEW.id); + END IF; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6554,6 +6586,9 @@ BEGIN SET NEW.userFk = account.myUser_getId(); END IF; + IF NEW.shelvingFk <> OLD.shelvingFk THEN + SET NEW.movingState = NULL; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6654,11 +6689,11 @@ DELIMITER ;; AFTER INSERT ON `itemShelvingSale` FOR EACH ROW BEGIN - UPDATE sale s JOIN operator o ON o.workerFk = account.myUser_getId() - SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE) - WHERE id = NEW.saleFk; + JOIN sector se ON se.id = o.sectorFk + SET s.isPicked = IF(IFNULL(se.isOnReservationMode, o.isOnReservationMode), s.isPicked, TRUE) + WHERE s.id = NEW.saleFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9988,6 +10023,8 @@ DELIMITER ;; BEFORE INSERT ON `ticketRefund` FOR EACH ROW BEGIN + CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk); + SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; @@ -10008,6 +10045,8 @@ DELIMITER ;; BEFORE UPDATE ON `ticketRefund` FOR EACH ROW BEGIN + CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk); + SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; @@ -10678,6 +10717,15 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + + IF NEW.travelFk IS NULL AND + (SELECT COUNT(*) FROM travelThermograph + WHERE thermographFk = NEW.thermographFk + AND travelFk IS NULL + AND id <> NEW.id) > 0 + THEN + CALL util.throw('Duplicate thermographFk without travelFk not allowed.'); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10698,6 +10746,15 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + + IF NEW.travelFk IS NULL AND + (SELECT COUNT(*) FROM travelThermograph + WHERE thermographFk = NEW.thermographFk + AND travelFk IS NULL + AND id <> NEW.id) > 0 + THEN + CALL util.throw('Duplicate thermographFk without travelFk not allowed.'); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11469,4 +11526,4 @@ USE `vn2008`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-10-03 7:43:14 +-- Dump completed on 2024-11-12 7:06:44 diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 5076f9330..e93bb3b8e 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -185,6 +185,7 @@ INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory (3, 'Warehouse Three', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0), (4, 'Warehouse Four', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1), (5, 'Warehouse Five', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0), + (6, 'Warehouse six', 'vnh', 1, 1, 1, 1, 0, 0, 1, 1, 0, 0), (13, 'Inventory', 'inv', 1, 1, 1, 0, 0, 0, 1, 0, 0, 0), (60, 'Algemesi', NULL, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0); @@ -387,23 +388,23 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`) (4, 'GCN Channel'), (5, 'The Newspaper'); -INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`businessTypeFk`,`typeFk`) +INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`businessTypeFk`,`typeFk`) VALUES - (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), - (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), - (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), - (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), - (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 18, 0, 'florist','normal'), - (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 19, 0, 'florist','normal'), - (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 19, 0, 'florist','normal'), - (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 19, 0, 'florist','normal'), - (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 9, 0, 'florist','normal'), - (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, NULL, 1, 'florist','normal'), - (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'), - (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'); + (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), + (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), + (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), + (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'), + (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 18, 0, 'florist','normal'), + (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 19, 0, 'florist','normal'), + (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 19, 0, 'florist','normal'), + (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 19, 0, 'florist','normal'), + (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 9, 0, 'florist','normal'), + (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, NULL, 1, 'florist','normal'), + (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'), + (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'); -INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) - SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), UPPER(CONCAT(name, 'Social')), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1 +INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) + SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), UPPER(CONCAT(name, 'Social')), CONCAT(name, 'Contact'), UPPER(CONCAT(name, 'Street')), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1 FROM `account`.`role` `r` WHERE `r`.`hasLogin` = 1; @@ -545,7 +546,8 @@ INSERT INTO `vn`.`observationType`(`id`,`description`, `code`) (6, 'Weight', 'weight'), (7, 'InvoiceOut', 'invoiceOut'), (8, 'DropOff', 'dropOff'), - (9, 'Sustitución', 'substitution'); + (9, 'Sustitución', 'substitution'), + (10, 'Finance', 'finance'); INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) VALUES @@ -630,14 +632,21 @@ INSERT INTO vn.invoiceOutConfig SET id = 1, parallelism = 8; -INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaFk`, `isCEE`, `type`) +INSERT INTO `vn`.`invoiceOutSerial` + (`code`,`description`, `isTaxed`, `taxAreaFk`, `isCEE`, `type`) VALUES - ('A', 'Global nacional', 1, 'NATIONAL', 0, 'global'), - ('T', 'Española rapida', 1, 'NATIONAL', 0, 'quick'), - ('V', 'Intracomunitaria global', 0, 'CEE', 1, 'global'), - ('M', 'Múltiple nacional', 1, 'NATIONAL', 0, 'multiple'), - ('R', 'Rectificativa', 1, 'NATIONAL', 0, NULL), - ('E', 'Exportación rápida', 0, 'WORLD', 0, 'quick'); + ('A', 'Global nacional', 1, 'NATIONAL', 0, 'global'), + ('T', 'Española rapida', 1, 'NATIONAL', 0, 'quick'), + ('V', 'Intracomunitaria global', 0, 'CEE', 1, 'global'), + ('M', 'Múltiple nacional', 1, 'NATIONAL', 0, 'multiple'), + ('R', 'Rectificativa', 1, 'NATIONAL', 0, NULL), + ('E', 'Exportación rápida', 0, 'WORLD', 0, 'quick'), + ('H', 'Intracomunitaria rápida', 0, 'CEE', 1, 'quick'), + ('P', 'Factura simplificada', 1, 'NATIONAL', 0, NULL), + ('PE', 'COOPERATIE FLORAHOLLAND UA', 0, 'CEE', 1, NULL), + ('S', 'Simplificada', 1, 'NATIONAL', 0, NULL), + ('X', 'Exportación global', 0, 'WORLD', 0, 'global'), + ('N', 'Múltiple Intracomunitaria', 0, 'CEE', 1, 'multiple'); INSERT INTO `vn`.`invoiceOut`(`id`, `serial`, `amount`, `issued`,`clientFk`, `created`, `companyFk`, `dued`, `booked`, `bankFk`, `hasPdf`) VALUES @@ -1497,16 +1506,17 @@ INSERT INTO `vn`.`awb` (id, code, package, weight, created, amount, transitoryFk (10, '07546500856', 185, 2364, util.VN_CURDATE(), 5321, 442, 1); INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseOutFk`, `agencyModeFk`, `m3`, `kg`,`ref`, `totalEntries`, `cargoSupplierFk`, `awbFK`) - VALUES - (1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1, 1, 1), - (2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150, 2000, 'second travel', 2, 2, 2), - (3, util.VN_CURDATE(), util.VN_CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1, 1, 3), - (4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 3, 1, 50.00, 500, 'fourth travel', 0, 2, 4), - (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5), - (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6), - (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7), - (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10), - (10, DATE_ADD(util.VN_CURDATE(), INTERVAL + 5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10); + VALUES (1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1, 1, 1), + (2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150.00, 2000, 'second travel', 2, 2, 2), + (3, util.VN_CURDATE(), util.VN_CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1, 1, 3), + (4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 3, 1, 50.00, 500, 'fourth travel', 0, 2, 4), + (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5), + (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6), + (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7), + (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10), + (10, DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10), + (11, util.VN_CURDATE() - INTERVAL 1 DAY , util.VN_CURDATE(), 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4), + (12, util.VN_CURDATE() , util.VN_CURDATE() + INTERVAL 1 DAY, 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4); INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `isRaid`, `evaNotes`) VALUES @@ -1519,7 +1529,8 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 0, 'observation seven'), (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''), (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, ''); + (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 10', 1, 1, ''), + (99, 69, '2000-12-01 00:00:00.000', 11, 0, 442, 'IN2009', 'Movement 99', 0, 0, ''); INSERT INTO `vn`.`entryConfig` (`defaultEntry`, `inventorySupplierFk`, `defaultSupplierFk`) VALUES (2, 4, 1); @@ -1542,7 +1553,7 @@ INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `sal ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 6, 1, '186', '0', '51', '53.12', '56.20', '56.20', '56.20'), ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 7, 1, '277', '0', '53.12', '56.20', '56.20', '56.20', '56.20'); -INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagingFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) + INSERT INTO vn.buy(id,entryFk,itemFk,buyingValue,quantity,packagingFk,stickers,freightValue,packageValue,comissionValue,packing,grouping,groupingMode,location,price1,price2,price3,printedStickers,isChecked,isIgnored,weight,created) VALUES (1, 1, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 'packing', NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, util.VN_CURDATE() - INTERVAL 2 MONTH), (2, 2, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 'packing', NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, util.VN_CURDATE() - INTERVAL 1 MONTH), @@ -1558,7 +1569,8 @@ INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagi (12, 6, 4, 1.25, 0, 3, 1, 2.500, 2.500, 0.000, 10, 10, 'grouping', NULL, 0.00, 1.75, 1.67, 0, 1, 0, 4, util.VN_CURDATE()), (13, 7, 1, 50, 0, 3, 1, 2.000, 2.000, 0.000, 1, 1, 'packing', NULL, 0.00, 99.6, 99.4, 0, 1, 0, 4, util.VN_CURDATE()), (14, 7, 2, 5, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 'grouping', NULL, 0.00, 7.30, 7.00, 0, 1, 0, 4, util.VN_CURDATE()), - (15, 7, 4, 1.25, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 'grouping', NULL, 0.00, 1.75, 1.67, 0, 1, 0, 4, util.VN_CURDATE()); + (15, 7, 4, 1.25, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 'grouping', NULL, 0.00, 1.75, 1.67, 0, 1, 0, 4, util.VN_CURDATE()), + (16, 99,1,50.0000, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 'packing', NULL, 0.00, 99.60, 99.40, 0, 1, 0, 1.00, '2024-07-30 08:13:51.000'); INSERT INTO `hedera`.`order`(`id`, `date_send`, `customer_id`, `delivery_method_id`, `agency_id`, `address_id`, `company_id`, `note`, `source_app`, `confirmed`,`total`, `date_make`, `first_row_stamp`, `confirm_date`) VALUES @@ -2439,30 +2451,32 @@ INSERT INTO `vn`.`workerTimeControl`(`userFk`, `timed`, `manual`, `direction`, ` (1107, CONCAT(util.VN_CURDATE(), ' 10:20'), TRUE, 'middle', 1), (1107, CONCAT(util.VN_CURDATE(), ' 14:50'), TRUE, 'out', 1); -INSERT INTO `vn`.`dmsType`(`id`, `name`, `readRoleFk`, `writeRoleFk`, `code`) +INSERT INTO `vn`.`dmsType` + (`id`, `name`, `readRoleFk`, `writeRoleFk`, `code`) VALUES - (1, 'Facturas Recibidas', NULL, NULL, 'invoiceIn'), - (2, 'Doc oficial', NULL, NULL, 'officialDoc'), - (3, 'Laboral', 37, 37, 'hhrrData'), - (4, 'Albaranes recibidos', NULL, NULL, 'deliveryNote'), - (5, 'Otros', 1, 1, 'miscellaneous'), - (6, 'Pruebas', NULL, NULL, 'tests'), - (7, 'IAE Clientes', 1, 1, 'economicActivitiesTax'), - (8, 'Fiscal', NULL, NULL, 'fiscal'), - (9, 'Vehiculos', NULL, NULL, 'vehicles'), - (10, 'Plantillas', NULL, NULL, 'templates'), - (11, 'Contratos', NULL, NULL, 'contracts'), - (12, 'ley de pagos', 1, 1, 'paymentsLaw'), - (13, 'Basura', 1, 1, 'trash'), - (14, 'Ticket', 1, 1, 'ticket'), - (15, 'Presupuestos', NULL, NULL, 'budgets'), - (16, 'Logistica', NULL, NULL, 'logistics'), - (17, 'cmr', 1, 1, 'cmr'), - (18, 'dua', NULL, NULL, 'dua'), - (19, 'inmovilizado', NULL, NULL, 'fixedAssets'), - (20, 'Reclamación', 1, 1, 'claim'), - (21, 'Entrada', 1, 1, 'entry'), - (22, 'Proveedor', 1, 1, 'supplier'); + (1, 'Facturas Recibidas', NULL, NULL, 'invoiceIn'), + (2, 'Doc oficial', NULL, NULL, 'officialDoc'), + (3, 'Laboral', 37, 37, 'hhrrData'), + (4, 'Albaranes recibidos', NULL, NULL, 'deliveryNote'), + (5, 'Otros', 1, 1, 'miscellaneous'), + (6, 'Pruebas', NULL, NULL, 'tests'), + (7, 'IAE Clientes', 1, 1, 'economicActivitiesTax'), + (8, 'Fiscal', NULL, NULL, 'fiscal'), + (9, 'Vehiculos', NULL, NULL, 'vehicles'), + (10, 'Plantillas', NULL, NULL, 'templates'), + (11, 'Contratos', NULL, NULL, 'contracts'), + (12, 'ley de pagos', 1, 1, 'paymentsLaw'), + (13, 'Basura', 1, 1, 'trash'), + (14, 'Ticket', 1, 1, 'ticket'), + (15, 'Presupuestos', NULL, NULL, 'budgets'), + (16, 'Logistica', NULL, NULL, 'logistics'), + (17, 'cmr', 1, 1, 'cmr'), + (18, 'dua', NULL, NULL, 'dua'), + (19, 'inmovilizado', NULL, NULL, 'fixedAssets'), + (20, 'Reclamación', 1, 1, 'claim'), + (21, 'Entrada', 1, 1, 'entry'), + (22, 'Proveedor', 1, 1, 'supplier'), + (23, 'Termografos', 35, 35, 'thermograph'); INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `warehouseFk`, `companyFk`, `hardCopyNumber`, `hasFile`, `reference`, `description`, `created`) VALUES @@ -2470,7 +2484,7 @@ INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `wa (2, 5, '2.txt', 'text/plain', 5, 1, 442, 1, TRUE, 'Client:104', 'Client:104 dms for the client', util.VN_CURDATE()), (3, 5, '3.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'Client: 104', 'Client:104 readme', util.VN_CURDATE()), (4, 3, '4.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'Worker: 106', 'Worker:106 readme', util.VN_CURDATE()), - (5, 5, '5.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'travel: 1', 'dmsForThermograph', util.VN_CURDATE()), + (5, 23, '5.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'travel: 1', 'dmsForThermograph', util.VN_CURDATE()), (6, 5, '6.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'NotExists', 'DoesNotExists', util.VN_CURDATE()), (7, 20, '7.jpg', 'image/jpeg', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()), (8, 20, '8.mp4', 'video/mp4', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()), @@ -2520,14 +2534,15 @@ INSERT INTO `vn`.`thermograph`(`id`, `model`) ('138350-0', 'DISPOSABLE'); -INSERT INTO `vn`.`travelThermograph`(`thermographFk`, `created`, `warehouseFk`, `travelFk`, `temperatureFk`, `result`, `dmsFk`) +INSERT INTO `vn`.`travelThermograph` + (`thermographFk`, `created`, `warehouseFk`, `travelFk`, `temperatureFk`, `minTemperature`, `maxTemperature`, `result`, `dmsFk`) VALUES - ('TMM190901395', util.VN_CURDATE(), 1, 1, 'WARM', 'Ok', NULL), - ('TL.BBA85422', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 2, 'COOL', 'Ok', NULL), - ('TL.BBA85422', util.VN_CURDATE(), 2, 1, 'COOL', 'can not read the temperature', NULL), - ('TZ1905012010', util.VN_CURDATE(), 1, 1, 'WARM', 'Temperature in range', 5), - ('138350-0', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 'WARM', NULL, 5), - ('138350-0', util.VN_CURDATE(), 1, NULL, 'COOL', NULL, NULL); + ('TMM190901395', util.VN_CURDATE(), 1, 1, 'WARM', NULL, NULL, 'Ok', NULL), + ('TL.BBA85422', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 2, 'COOL', NULL, NULL, 'Ok', NULL), + ('TL.BBA85422', util.VN_CURDATE(), 2, 1, 'COOL', NULL, NULL, 'can not read the temperature', NULL), + ('TZ1905012010', util.VN_CURDATE(), 1, 1, 'WARM', NULL, NULL, 'Temperature in range', 5), + ('138350-0', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 'WARM', 2, 12, NULL, 5), + ('138350-0', util.VN_CURDATE(), 1, NULL, 'COOL', NULL, NULL, NULL, NULL); REPLACE INTO `vn`.`incoterms`(`code`, `name`) VALUES @@ -2903,7 +2918,8 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`) (6, 'book-entry-deleted', 'accounting entries deleted'), (7, 'zone-included','An email to notify zoneCollisions'), (8, 'backup-printer-selected','A backup printer has been selected'), - (9, 'mrw-deadline','The MRW deadline has passed'); + (9, 'mrw-deadline','The MRW deadline has passed'), + (10,'invoice-ticket-closure','Tickets not invoiced during the nightly closure ticket process'); TRUNCATE `util`.`notificationAcl`; INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) @@ -3935,6 +3951,11 @@ INSERT INTO vn.medicalReview (id, workerFk, centerFk, `date`, `time`, isFit, amount, invoice, remark) VALUES(3, 9, 2, '2000-01-01', '8:00', 1, 150.0, NULL, NULL); +INSERT INTO vn.stockBought (workerFk, bought, reserve, dated) + VALUES(35, 1.00, 1.00, '2001-01-01'); +INSERT INTO vn.auctionConfig (id,conversionCoefficient,warehouseFk) + VALUES (1,0.6,6); + INSERT INTO vn.payrollComponent (id, name, isSalaryAgreed, isVariable, isException) VALUES @@ -3976,3 +3997,25 @@ VALUES INSERT IGNORE INTO ormConfig SET id =1, selectLimit = 1000; + +INSERT INTO pbx.queueMultiConfig + SET id = 'ring', + strategy = 20, + timeout = 2, + retry = 0, + weight = 0, + maxLen = 0, + ringInUse = 0; + +INSERT INTO pbx.queue (description, name, config) + VALUES ('X-men', '1000', 1), + ('Avengers', '2000', 1); + +INSERT IGNORE INTO pbx.queueMember + SET queue = '1000', + extension = '1010'; + +UPDATE vn.department SET pbxQueue = '1000' WHERE name = "CAMARA"; +UPDATE vn.department SET pbxQueue = '2000' WHERE name = "VENTAS"; + + diff --git a/db/routines/bs/procedures/clientNewBorn_recalc.sql b/db/routines/bs/procedures/clientNewBorn_recalc.sql index 1c89b5745..bb6b02aa7 100644 --- a/db/routines/bs/procedures/clientNewBorn_recalc.sql +++ b/db/routines/bs/procedures/clientNewBorn_recalc.sql @@ -6,25 +6,27 @@ BLOCK1: BEGIN DECLARE vShipped DATE; DECLARE vPreviousShipped DATE; DECLARE vDone boolean; - DECLARE cur cursor for - - SELECT clientFk, firstShipped - FROM bs.clientNewBorn; + + DECLARE cur CURSOR FOR + SELECT clientFk, firstShipped + FROM bs.clientNewBorn; DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; SET vDone := FALSE; DELETE FROM bs.clientNewBorn WHERE isModified = FALSE; - INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped) - SELECT c.id, MAX(t.shipped), MAX(t.shipped) - FROM vn.client c - JOIN vn.ticket t on t.clientFk = c.id - LEFT JOIN clientNewBorn cb on cb.clientFk = c.id - WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null - GROUP BY c.id; + INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped) + SELECT c.id, DATE(MAX(t.shipped)), DATE(MAX(t.shipped)) + FROM vn.client c + JOIN vn.ticket t ON t.clientFk = c.id + LEFT JOIN clientNewBorn cb ON cb.clientFk = c.id + WHERE t.shipped BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR + AND util.VN_CURDATE() + AND cb.isModified IS NULL + GROUP BY c.id; + OPEN cur; - LOOP1: LOOP SET vDone := FALSE; FETCH cur INTO vClientFk, vShipped; diff --git a/db/routines/hedera/procedures/orderRow_updateOverstocking.sql b/db/routines/hedera/procedures/orderRow_updateOverstocking.sql index e919ff922..bbfa9432a 100644 --- a/db/routines/hedera/procedures/orderRow_updateOverstocking.sql +++ b/db/routines/hedera/procedures/orderRow_updateOverstocking.sql @@ -1,10 +1,10 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `hedera`.`orderRow_updateOverstocking`(vOrderFk INT) BEGIN /** * Set amount = 0 to avoid overbooking sales -* +* * @param vOrderFk hedera.order.id */ DECLARE vCalcFk INT; @@ -49,4 +49,4 @@ BEGIN END LOOP; CLOSE cWarehouses; END$$ -DELIMITER ; \ No newline at end of file +DELIMITER ; diff --git a/db/routines/hedera/procedures/order_confirmWithUser.sql b/db/routines/hedera/procedures/order_confirmWithUser.sql index 44da9d071..644d68a87 100644 --- a/db/routines/hedera/procedures/order_confirmWithUser.sql +++ b/db/routines/hedera/procedures/order_confirmWithUser.sql @@ -12,8 +12,8 @@ BEGIN * @param vUser The user identifier */ DECLARE vHasRows BOOL; - DECLARE vDone BOOL; DECLARE vHas0Amount BOOL; + DECLARE vDone BOOL; DECLARE vWarehouseFk INT; DECLARE vShipment DATE; DECLARE vShipmentDayEnd DATETIME; @@ -108,7 +108,7 @@ BEGIN IF vHas0Amount THEN CALL util.throw('Hay líneas vacías. Por favor, elimínelas'); - END IF; + END IF; START TRANSACTION; diff --git a/db/routines/hedera/triggers/orderRow_afterInsert.sql b/db/routines/hedera/triggers/orderRow_afterInsert.sql index d0da043e7..7196dce10 100644 --- a/db/routines/hedera/triggers/orderRow_afterInsert.sql +++ b/db/routines/hedera/triggers/orderRow_afterInsert.sql @@ -3,8 +3,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `hedera`.`orderRow_afterIns AFTER INSERT ON `orderRow` FOR EACH ROW BEGIN - UPDATE `order` - SET rowUpdated = util.VN_NOW() + UPDATE `order` + SET rowUpdated = util.VN_NOW() WHERE id = NEW.orderFk; END$$ -DELIMITER ; \ No newline at end of file +DELIMITER ; diff --git a/db/routines/vn/events/itemCampaign_add.sql b/db/routines/vn/events/itemCampaign_add.sql new file mode 100644 index 000000000..efb2aeb11 --- /dev/null +++ b/db/routines/vn/events/itemCampaign_add.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` EVENT `vn`.`itemCampaig_add` + ON SCHEDULE EVERY 1 DAY + STARTS '2024-10-18 03:00:00.000' + ON COMPLETION PRESERVE + ENABLE +DO CALL itemCampaign_add()$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/buy_getVolumeByAgency.sql b/db/routines/vn/procedures/buy_getVolumeByAgency.sql deleted file mode 100644 index 7393d12d8..000000000 --- a/db/routines/vn/procedures/buy_getVolumeByAgency.sql +++ /dev/null @@ -1,20 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS tmp.buy; - CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - - INSERT INTO tmp.buy - SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed = vDated - AND t.agencyModeFk IN (0, vAgencyFk); - - CALL buy_getVolume(); - DROP TEMPORARY TABLE tmp.buy; - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/clean.sql b/db/routines/vn/procedures/clean.sql index a8ca68e5f..d3fed0242 100644 --- a/db/routines/vn/procedures/clean.sql +++ b/db/routines/vn/procedures/clean.sql @@ -23,6 +23,13 @@ BEGIN DELETE FROM messageInbox WHERE sendDate < v2Months; DELETE FROM messageInbox WHERE sendDate < v2Months; DELETE FROM workerTimeControl WHERE timed < v4Years; + DELETE FROM itemShelvingSale + WHERE itemShelvingFk IN ( + SELECT id + FROM itemShelving + WHERE created < util.VN_CURDATE() + AND visible = 0 + ); DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0; DELETE FROM ticketDown WHERE created < util.yesterday(); DELETE IGNORE FROM expedition WHERE created < v26Months; @@ -50,16 +57,10 @@ BEGIN DELETE FROM claim WHERE ticketCreated < v4Years; -- Robert ubicacion anterior de travelLog comentario para debug DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months; - DELETE bm - FROM buyMark bm - JOIN buy b ON b.id = bm.id - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed <= v2Months; DELETE b FROM buy b JOIN entryConfig e ON e.defaultEntry = b.entryFk WHERE b.created < v2Months; - DELETE FROM stockBuyed WHERE creationDate < v2Months; + DELETE FROM stockBought WHERE dated < v2Months; DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months; -- Equipos duplicados DELETE w.* diff --git a/db/routines/vn/procedures/client_create.sql b/db/routines/vn/procedures/client_create.sql index 3df3df905..fad01c107 100644 --- a/db/routines/vn/procedures/client_create.sql +++ b/db/routines/vn/procedures/client_create.sql @@ -34,22 +34,19 @@ BEGIN DECLARE vIsTaxDataChecked TINYINT(1); DECLARE vHasCoreVnl BOOLEAN; DECLARE vMandateTypeFk INT; - DECLARE vHasDailyInvoice BOOLEAN; SELECT cc.defaultPayMethodFk, cc.defaultDueDay, cc.defaultCredit, cc.defaultIsTaxDataChecked, cc.defaultHasCoreVnl, - cc.defaultMandateTypeFk, - c.hasDailyInvoice + cc.defaultMandateTypeFk INTO vPayMethodFk, vDueDay, vDefaultCredit, vIsTaxDataChecked, vHasCoreVnl, - vMandateTypeFk, - vHasDailyInvoice + vMandateTypeFk FROM clientConfig cc LEFT JOIN province p ON p.id = vProvinceFk LEFT JOIN country c ON c.id = p.countryFk; @@ -70,8 +67,7 @@ BEGIN credit = vDefaultCredit, isTaxDataChecked = vIsTaxDataChecked, hasCoreVnl = vHasCoreVnl, - isEqualizated = FALSE, - hasDailyInvoice = vHasDailyInvoice + isEqualizated = FALSE ON duplicate KEY UPDATE payMethodFk = vPayMethodFk, dueDay = vDueDay, diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql index cc0b7fd9b..bb6e94a63 100644 --- a/db/routines/vn/procedures/collection_addWithReservation.sql +++ b/db/routines/vn/procedures/collection_addWithReservation.sql @@ -37,23 +37,23 @@ BEGIN WHERE t.id = vTicketFk; CALL cache.available_refresh( - vCacheAvailableFk, + vCacheAvailableFk, FALSE, - vWarehouseFk, + vWarehouseFk, util.VN_CURDATE()); SELECT available INTO vAvailable FROM cache.available - WHERE calc_id = vCacheAvailableFk + WHERE calc_id = vCacheAvailableFk AND item_id = vItemFk; - + IF vAvailable < vQuantity THEN SET vHasThrow = TRUE; ELSE SELECT `name`, - CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) + CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) INTO vItemName, vConcept - FROM item + FROM item WHERE id = vItemFk; START TRANSACTION; @@ -69,7 +69,7 @@ BEGIN CALL sale_calculateComponent(vSaleFk, NULL); CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk); - + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN SET vHasThrow = TRUE; END IF; @@ -78,13 +78,13 @@ BEGIN IF vHasThrow THEN CALL util.throw("There is no available for the selected item"); END IF; - + IF vSaleGroupFk THEN INSERT INTO saleGroupDetail SET saleFk = vSaleFk, saleGroupFk = vSaleGroupFk; END IF; - + COMMIT; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index f04d5241e..84133d36e 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`collection_new`(vUserFk INT, OUT vCollectionFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`collection_new`( + vUserFk INT, + OUT vCollectionFk INT +) BEGIN /** * Genera colecciones de tickets sin asignar trabajador. @@ -12,30 +15,29 @@ BEGIN DECLARE vLinesLimit INT; DECLARE vTicketLines INT; DECLARE vVolumeLimit DECIMAL; - DECLARE vTicketVolume DECIMAL; DECLARE vSizeLimit INT; + DECLARE vTicketVolume DECIMAL; DECLARE vMaxTickets INT; - DECLARE vStateFk VARCHAR(45); + DECLARE vStateCode VARCHAR(45); DECLARE vFirstTicketFk INT; - DECLARE vHour INT; - DECLARE vMinute INT; DECLARE vWorkerCode VARCHAR(3); - DECLARE vWagonCounter INT DEFAULT 0; + DECLARE vWagonCounter INT DEFAULT 1; DECLARE vTicketFk INT; DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vHasAssignedTickets BOOLEAN; + DECLARE vHasAssignedTickets BOOL; DECLARE vHasUniqueCollectionTime BOOL; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vLockName VARCHAR(215); - DECLARE vLockTime INT DEFAULT 30; + DECLARE vHeight INT; + DECLARE vVolume INT; + DECLARE vLiters INT; + DECLARE vLines INT; + DECLARE vTotalLines INT DEFAULT 0; + DECLARE vTotalVolume INT DEFAULT 0; DECLARE vFreeWagonFk INT; - DECLARE vErrorNumber INT; - DECLARE vErrorMsg TEXT; + DECLARE vDone INT DEFAULT FALSE; - DECLARE c1 CURSOR FOR + DECLARE vTickets CURSOR FOR SELECT ticketFk, `lines`, m3 FROM tmp.productionBuffer - WHERE ticketFk <> vFirstTicketFk ORDER BY HH, mm, productionOrder DESC, @@ -48,26 +50,6 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - GET DIAGNOSTICS CONDITION 1 - vErrorNumber = MYSQL_ERRNO, - vErrorMsg = MESSAGE_TEXT; - - CALL util.debugAdd('collection_new', JSON_OBJECT( - 'errorNumber', vErrorNumber, - 'errorMsg', vErrorMsg, - 'lockName', vLockName, - 'userFk', vUserFk, - 'ticketFk', vTicketFk - )); -- Tmp - - IF vLockName IS NOT NULL THEN - DO RELEASE_LOCK(vLockName); - END IF; - RESIGNAL; - END; - SELECT pc.ticketTrolleyMax * o.numberOfWagons, pc.hasUniqueCollectionTime, w.code, @@ -78,36 +60,26 @@ BEGIN o.trainFk, o.linesLimit, o.volumeLimit, - o.sizeLimit, - pc.collection_new_lockname + o.sizeLimit INTO vMaxTickets, - vHasUniqueCollectionTime, - vWorkerCode, - vWarehouseFk, - vItemPackingTypeFk, - vStateFk, - vWagons, - vTrainFk, - vLinesLimit, - vVolumeLimit, - vSizeLimit, - vLockName - FROM productionConfig pc - JOIN worker w ON w.id = vUserFk + vHasUniqueCollectionTime, + vWorkerCode, + vWarehouseFk, + vItemPackingTypeFk, + vStateCode, + vWagons, + vTrainFk, + vLinesLimit, + vVolumeLimit, + vSizeLimit + FROM worker w + JOIN operator o ON o.workerFk = w.id JOIN state st ON st.`code` = 'ON_PREPARATION' - JOIN operator o ON o.workerFk = vUserFk; - - SET vLockName = CONCAT_WS('/', - vLockName, - vWarehouseFk, - vItemPackingTypeFk - ); - - IF NOT GET_LOCK(vLockName, vLockTime) THEN - CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); - END IF; + JOIN productionConfig pc + WHERE w.id = vUserFk; -- Se prepara el tren, con tantos vagones como sea necesario. + CREATE OR REPLACE TEMPORARY TABLE tTrain (wagon INT, shelve INT, @@ -118,63 +90,62 @@ BEGIN PRIMARY KEY(wagon, shelve)) ENGINE = MEMORY; - WHILE vWagons > vWagonCounter DO - SET vWagonCounter = vWagonCounter + 1; - - INSERT INTO tTrain(wagon, shelve, liters, `lines`, height) - SELECT vWagonCounter, cv.`level` , cv.liters , cv.`lines` , cv.height - FROM collectionVolumetry cv - WHERE cv.trainFk = vTrainFk + INSERT INTO tTrain (wagon, shelve, liters, `lines`, height) + WITH RECURSIVE wagonSequence AS ( + SELECT vWagonCounter wagon + UNION ALL + SELECT wagon + 1 wagon + FROM wagonSequence + WHERE wagon < vWagonCounter + vWagons -1 + ) + SELECT ws.wagon, cv.`level`, cv.liters, cv.`lines`, cv.height + FROM wagonSequence ws + JOIN vn.collectionVolumetry cv ON cv.trainFk = vTrainFk AND cv.itemPackingTypeFk = vItemPackingTypeFk; - END WHILE; -- Esto desaparecerá cuando tengamos la table cache.ticket + CALL productionControl(vWarehouseFk, 0); ALTER TABLE tmp.productionBuffer ADD COLUMN liters INT, ADD COLUMN height INT; - -- Se obtiene nº de colección. - INSERT INTO collection - SET itemPackingTypeFk = vItemPackingTypeFk, - trainFk = vTrainFk, - wagons = vWagons, - warehouseFk = vWarehouseFk; - - SELECT LAST_INSERT_ID() INTO vCollectionFk; - -- Los tickets de recogida en Algemesí sólo se sacan si están asignados. -- Los pedidos con riesgo no se sacan aunque se asignen. - DELETE pb.* + + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state WHERE (pb.agency = 'REC_ALGEMESI' AND s.code <> 'PICKER_DESIGNED') OR pb.problem LIKE '%RIESGO%'; - -- Comprobamos si hay tickets asignados. En ese caso, nos centramos - -- exclusivamente en esos tickets y los sacamos independientemente - -- de problemas o tamaños - SELECT COUNT(*) INTO vHasAssignedTickets - FROM tmp.productionBuffer pb - JOIN state s ON s.id = pb.state - WHERE s.code = 'PICKER_DESIGNED' - AND pb.workerCode = vWorkerCode; + -- Si hay tickets asignados, nos centramos exclusivamente en esos tickets + -- y los sacamos independientemente de problemas o tamaños + + SELECT EXISTS ( + SELECT TRUE + FROM tmp.productionBuffer pb + JOIN state s ON s.id = pb.state + WHERE (s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode) + OR s.code = 'LAST_CALL' + ) INTO vHasAssignedTickets; -- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados + IF vHasAssignedTickets THEN - DELETE pb.* + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state - WHERE s.code <> 'PICKER_DESIGNED' - OR pb.workerCode <> vWorkerCode; + WHERE (s.code <> 'PICKER_DESIGNED' + OR pb.workerCode <> vWorkerCode) + AND s.code <> 'LAST_CALL'; ELSE - DELETE pb.* + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state - JOIN agencyMode am ON am.id = pb.agencyModeFk - JOIN agency a ON a.id = am.agencyFk LEFT JOIN ( SELECT pb.ticketFk, MAX(i.`size`) maxSize FROM tmp.productionBuffer pb @@ -185,7 +156,7 @@ BEGIN ) sub ON sub.ticketFk = pb.ticketFk JOIN productionConfig pc WHERE pb.shipped <> util.VN_CURDATE() - OR (pb.ubicacion IS NULL AND a.isOwn) + OR pb.ubicacion IS NULL OR (NOT s.isPreparable AND NOT s.isPrintable) OR pb.collectionH IS NOT NULL OR pb.collectionV IS NOT NULL @@ -193,26 +164,25 @@ BEGIN OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H') OR (NOT pb.V AND vItemPackingTypeFk = 'V') OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking) - OR LENGTH(pb.problem) > 0 + OR LENGTH(pb.problem) OR pb.lines > vLinesLimit OR pb.m3 > vVolumeLimit OR sub.maxSize > vSizeLimit OR pb.hasPlantTray; END IF; - -- Es importante que el primer ticket se coja en todos los casos - SELECT ticketFk, - HH, - mm, - `lines`, - m3 - INTO vFirstTicketFk, - vHour, - vMinute, - vTicketLines, - vTicketVolume + -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede + + IF vHasUniqueCollectionTime THEN + DELETE pb + FROM tmp.productionBuffer pb + JOIN tmp.productionBuffer pb2 ON pb2.ticketFk = vFirstTicketFk + AND (pb.HH <> pb2.HH OR pb.mm <> pb2.mm); + END IF; + + SELECT ticketFk INTO vFirstTicketFk FROM tmp.productionBuffer - ORDER BY HH, + ORDER BY HH, mm, productionOrder DESC, m3 DESC, @@ -222,44 +192,37 @@ BEGIN ticketFk LIMIT 1; - -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede - IF vHasUniqueCollectionTime THEN - DELETE FROM tmp.productionBuffer - WHERE HH <> vHour - OR mm <> vMinute; - END IF; - - SET vTicketFk = vFirstTicketFk; - SET @lines = 0; - SET @volume = 0; - - OPEN c1; - read_loop: LOOP + OPEN vTickets; + l: LOOP SET vDone = FALSE; + FETCH vTickets INTO vTicketFk, vTicketLines, vTicketVolume; + + IF vDone THEN + LEAVE l; + END IF; -- Buscamos un ticket que cumpla con los requisitos en el listado - IF ((vTicketLines + @lines) <= vLinesLimit OR vLinesLimit IS NULL) - AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN + + IF (vLinesLimit IS NULL OR (vTotalLines + vTicketLines) <= vLinesLimit) + AND (vVolumeLimit IS NULL OR (vTotalVolume + vTicketVolume) <= vVolumeLimit) THEN CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk); DROP TEMPORARY TABLE tmp.ticketIPT; + SELECT COUNT(*), SUM(litros), MAX(i.`size`), SUM(sv.volume) + INTO vLines, vLiters, vHeight, vVolume + FROM saleVolume sv + JOIN sale s ON s.id = sv.saleFk + JOIN item i ON i.id = s.itemFk + WHERE sv.ticketFk = vTicketFk; + + SET vTotalVolume = vTotalVolume + vVolume, + vTotalLines = vTotalLines + vLines; + UPDATE tmp.productionBuffer pb - JOIN ( - SELECT SUM(litros) liters, - @lines:= COUNT(*) + @lines, - COUNT(*) `lines`, - MAX(i.`size`) height, - @volume := SUM(sv.volume) + @volume, - SUM(sv.volume) volume - FROM saleVolume sv - JOIN sale s ON s.id = sv.saleFk - JOIN item i ON i.id = s.itemFk - WHERE sv.ticketFk = vTicketFk - ) sub - SET pb.liters = sub.liters, - pb.`lines` = sub.`lines`, - pb.height = sub.height + SET pb.liters = vLiters, + pb.`lines` = vLines, + pb.height = vHeight WHERE pb.ticketFk = vTicketFk; UPDATE tTrain tt @@ -276,17 +239,13 @@ BEGIN tt.height LIMIT 1; - -- Si no le encuentra una balda adecuada, intentamos darle un carro entero si queda alguno libre + -- Si no le encuentra una balda, intentamos darle un carro entero libre + IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN - SELECT tt.wagon - INTO vFreeWagonFk - FROM tTrain tt - LEFT JOIN ( - SELECT DISTINCT wagon - FROM tTrain - WHERE ticketFk IS NOT NULL - ) nn ON nn.wagon = tt.wagon - WHERE nn.wagon IS NULL + SELECT wagon INTO vFreeWagonFk + FROM tTrain + GROUP BY wagon + HAVING COUNT(ticketFk) = 0 ORDER BY wagon LIMIT 1; @@ -295,38 +254,35 @@ BEGIN SET ticketFk = vFirstTicketFk WHERE wagon = vFreeWagonFk; - -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo - DELETE tt.* - FROM tTrain tt - LEFT JOIN ( - SELECT DISTINCT wagon - FROM tTrain - WHERE ticketFk IS NOT NULL - ) nn ON nn.wagon = tt.wagon - WHERE nn.wagon IS NULL; - END IF; - END IF; + -- Se anulan el resto de carros libres, + -- máximo un carro con pedido excesivo - FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume; - IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN - LEAVE read_loop; - END IF; - ELSE - FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume; - IF vDone THEN - LEAVE read_loop; - END IF; + DELETE tt + FROM tTrain tt + JOIN (SELECT wagon + FROM tTrain + GROUP BY wagon + HAVING COUNT(ticketFk) = 0 + ) sub ON sub.wagon = tt.wagon; + END IF; + END IF; END IF; END LOOP; - CLOSE c1; + CLOSE vTickets; IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN - UPDATE collection c - JOIN state st ON st.code = 'ON_PREPARATION' - SET c.stateFk = st.id - WHERE c.id = vCollectionFk; + -- Se obtiene nº de colección + + INSERT INTO collection + SET itemPackingTypeFk = vItemPackingTypeFk, + trainFk = vTrainFk, + wagons = vWagons, + warehouseFk = vWarehouseFk; + + SELECT LAST_INSERT_ID() INTO vCollectionFk; -- Asigna las bandejas + INSERT IGNORE INTO ticketCollection(ticketFk, collectionFk, `level`, wagon, liters) SELECT tt.ticketFk, vCollectionFk, tt.shelve, tt.wagon, tt.liters FROM tTrain tt @@ -334,39 +290,36 @@ BEGIN ORDER BY tt.wagon, tt.shelve; -- Actualiza el estado de los tickets - CALL collection_setState(vCollectionFk, vStateFk); + + CALL collection_setState(vCollectionFk, vStateCode); -- Aviso para la preparacion previa + INSERT INTO ticketDown(ticketFk, collectionFk) SELECT tc.ticketFk, tc.collectionFk FROM ticketCollection tc WHERE tc.collectionFk = vCollectionFk; - CALL sales_mergeByCollection(vCollectionFk); + CALL collection_mergeSales(vCollectionFk); UPDATE `collection` c - JOIN ( + JOIN( SELECT COUNT(*) saleTotalCount, SUM(s.isPicked <> 0) salePickedCount FROM ticketCollection tc JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND s.quantity > 0 - ) sub + WHERE tc.collectionFk = vCollectionFk + AND s.quantity > 0 + )sub SET c.saleTotalCount = sub.saleTotalCount, c.salePickedCount = sub.salePickedCount WHERE c.id = vCollectionFk; - ELSE - DELETE FROM `collection` - WHERE id = vCollectionFk; - SET vCollectionFk = NULL; + SET vCollectionFk = NULL; END IF; - DO RELEASE_LOCK(vLockName); - DROP TEMPORARY TABLE tTrain, tmp.productionBuffer; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/invoiceOut_newFromAddress.sql b/db/routines/vn/procedures/invoiceOut_newFromAddress.sql new file mode 100644 index 000000000..495ace608 --- /dev/null +++ b/db/routines/vn/procedures/invoiceOut_newFromAddress.sql @@ -0,0 +1,56 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`invoiceOut_newFromAddress`( + IN vAddressFk INT, + IN vSerial CHAR(2), + IN vMaxShipped DATE, + IN vCompanyFk INT, + IN vTaxArea VARCHAR(25), + IN vRef VARCHAR(25), + OUT vInvoiceId INT) +BEGIN +/** + * Factura los tickets de un consignatario hasta una fecha dada + * @param vAddressFk Id del consignatario a facturar + * @param vSerial Serie de factura + * @param vMaxShipped Fecha hasta la cual cogerá tickets para facturar + * @param vCompanyFk Id de la empresa desde la que se factura + * @param vTaxArea Tipo de iva en relacion a la empresa y al cliente, NULL por defecto + * @param vRef Referencia de la factura en caso que se quiera forzar, NULL por defecto + * @return vInvoiceId factura + */ + DECLARE vIsRefEditable BOOLEAN; + + IF vRef IS NOT NULL AND vSerial IS NOT NULL THEN + SELECT isRefEditable INTO vIsRefEditable + FROM invoiceOutSerial + WHERE code = vSerial; + + IF NOT vIsRefEditable THEN + CALL util.throw('serial non editable'); + END IF; + END IF; + + DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`; + CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice` + (PRIMARY KEY (`id`)) + ENGINE = MEMORY + SELECT id FROM ticket t + WHERE t.addressFk = vAddressFk + AND t.refFk IS NULL + AND t.companyFk = vCompanyFk + AND t.shipped BETWEEN + util.firstDayOfYear(vMaxShipped - INTERVAL 1 YEAR) + AND util.dayend(vMaxShipped); + + CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId); + + UPDATE invoiceOut + SET `ref` = vRef + WHERE id = vInvoiceId + AND vRef IS NOT NULL; + + IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN + CALL invoiceOutBooking(vInvoiceId); + END IF; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/itemCampaign_add.sql b/db/routines/vn/procedures/itemCampaign_add.sql new file mode 100644 index 000000000..8fb40df67 --- /dev/null +++ b/db/routines/vn/procedures/itemCampaign_add.sql @@ -0,0 +1,54 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemCampaign_add`() +proc: BEGIN +/** + * Añade registros a tabla itemCampaign. + * + * @param vDateFrom Fecha desde + * @param vDateTo Fecha hasta + * @param vCampaign Código de la campaña + */ + DECLARE vYesterday DATE; + DECLARE vCampaign VARCHAR(100); + DECLARE vScopeDays INT; + DECLARE vPreviousDays INT; + DECLARE vDateSumFrom DATE; + DECLARE vDateSumTo DATE; + + SET vYesterday = util.yesterday(); + + SELECT dated, code, scopeDays, previousDays + INTO vDateSumTo, vCampaign, vScopeDays, vPreviousDays + FROM campaign + WHERE dated >= vYesterday + ORDER BY dated + LIMIT 1; + + IF vCampaign IS NULL THEN + CALL util.throw('Missing data in campaign table'); + END IF; + + IF NOT vYesterday BETWEEN vDateSumTo - INTERVAL vPreviousDays DAY + AND vDateSumTo THEN + LEAVE proc; + END IF; + + SET vDateSumFrom = vDateSumTo - INTERVAL vScopeDays DAY; + SET vDateSumTo = vDateSumTo - INTERVAL 1 DAY; + + INSERT INTO itemCampaign(dated, itemFk, quantity, total, campaign) + SELECT vYesterday, + s.itemFk, + SUM(s.quantity) quantity, + SUM((s.quantity * s.price) * (100 - s.discount) / 100) total, + vCampaign + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN client c ON c.id = t.clientFk + WHERE t.shipped BETWEEN vDateSumFrom AND util.dayEnd(vDateSumTo) + AND c.typeFk = 'normal' + AND NOT t.isDeleted + GROUP BY s.itemFk + HAVING quantity; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql index 6625e89b8..06736732a 100644 --- a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql +++ b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql @@ -18,8 +18,9 @@ proc: BEGIN DECLARE vReservedQuantity INT; DECLARE vOutStanding INT; DECLARE vUserFk INT; - DECLARE vTotalReservedQuantity INT; + DECLARE vTotalReservedQuantity INT; DECLARE vSaleQuantity INT; + DECLARE vIsRequiredTx BOOL DEFAULT NOT @@in_transaction; DECLARE vItemShelvingAvailable CURSOR FOR SELECT ish.id itemShelvingFk, @@ -29,7 +30,7 @@ proc: BEGIN JOIN shelving sh ON sh.code = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk - JOIN productionConfig pc + JOIN productionConfig pc WHERE s.id = vSaleFk AND NOT sc.isHideForPickers AND (sc.id = vSectorFk OR vSectorFk IS NULL) @@ -44,15 +45,15 @@ proc: BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - ROLLBACK; + CALL util.tx_rollback(vIsRequiredTx); RESIGNAL; END; - - START TRANSACTION; - + + CALL util.tx_start(vIsRequiredTx); + SELECT id INTO vSaleFk FROM sale - WHERE id = vSaleFk + WHERE id = vSaleFk FOR UPDATE; SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)), s.quantity @@ -65,7 +66,7 @@ proc: BEGIN WHERE s.id = vSaleFk; IF vOutStanding <= 0 THEN - COMMIT; + CALL util.tx_commit(vIsRequiredTx); LEAVE proc; END IF; @@ -85,7 +86,7 @@ proc: BEGIN IF vTotalReservedQuantity <> vSaleQuantity THEN CALL util.debugAdd('itemShelvingSale_addBySale', CONCAT(vSaleFk, ' - ', vSaleQuantity,' - ', vTotalReservedQuantity,'-', vOutStanding,'-', account.myUser_getId())); - + UPDATE sale SET quantity = vTotalReservedQuantity WHERE id = vSaleFk; @@ -93,7 +94,7 @@ proc: BEGIN LEAVE l; END IF; - SELECT id INTO vItemShelvingFk + SELECT id INTO vItemShelvingFk FROM itemShelving WHERE id = vItemShelvingFk FOR UPDATE; @@ -102,19 +103,19 @@ proc: BEGIN SET vOutStanding = vOutStanding - vReservedQuantity; IF vReservedQuantity > 0 THEN - CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity', - CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId())); - INSERT INTO itemShelvingSale( - itemShelvingFk, - saleFk, - quantity, - userFk, - isPicked) - SELECT vItemShelvingFk, - vSaleFk, - vReservedQuantity, - vUserFk, - FALSE; + CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity', + CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId())); + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk, + isPicked) + SELECT vItemShelvingFk, + vSaleFk, + vReservedQuantity, + vUserFk, + FALSE; UPDATE itemShelving SET available = available - vReservedQuantity @@ -123,6 +124,6 @@ proc: BEGIN END IF; END LOOP; CLOSE vItemShelvingAvailable; - COMMIT; + CALL util.tx_commit(vIsRequiredTx); END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelving_addList.sql b/db/routines/vn/procedures/itemShelving_addList.sql index 05b392485..ade92b9fd 100644 --- a/db/routines/vn/procedures/itemShelving_addList.sql +++ b/db/routines/vn/procedures/itemShelving_addList.sql @@ -1,16 +1,22 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addList`(vShelvingFk VARCHAR(3), vList TEXT, vIsChecking BOOL, vWarehouseFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addList`( + vShelvingFk VARCHAR(3), + vList TEXT, + vIsChecking BOOL, + vWarehouseFk INT +) BEGIN -/* Recorre cada elemento en la colección vList. +/** + * Recorre cada elemento en la colección vList. * Si el parámetro isChecking = FALSE, llama a itemShelving_add. * * Cuando es TRUE sólo inserta los elementos de la colección que no están ya en - * ese shelving, actualizando los valores del campo vn.itemShelving.isChecked + * ese shelving, actualizando los valores del campo itemShelving.isChecked * - * param vShelvingFk Identificador de vn.shelving - * param vList JSON array con esta estructura: '[value1, value2, ...]' - * param vIsChecking Define si hay que añadir o comprobar los items - * param vWarehouseFk Identificador de vn.warehouse + * @param vShelvingFk Identificador de shelving + * @param vList JSON array con esta estructura: '[value1, value2, ...]' + * @param vIsChecking Define si hay que añadir o comprobar los items + * @param vWarehouseFk Identificador de warehouse */ DECLARE vListLength INT DEFAULT JSON_LENGTH(vList); DECLARE vCounter INT DEFAULT 0; @@ -20,26 +26,27 @@ BEGIN DECLARE vIsChecked BOOL; WHILE vCounter < vListLength DO - SET vPath = CONCAT('$[',vCounter,']'); - SET vBarcode = JSON_EXTRACT(vList,vPath); + SET vPath = CONCAT('$[', vCounter, ']'); + SET vBarcode = JSON_EXTRACT(vList, vPath); SET vIsChecked = NULL; IF vIsChecking THEN SELECT barcodeToItem(vBarcode) INTO vItemFk; - SELECT COUNT(*) INTO vIsChecked - FROM vn.itemShelving + SELECT IF(COUNT(*), TRUE, FALSE) INTO vIsChecked + FROM itemShelving WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk; END IF; - IF NOT (vIsChecking AND vIsChecked) THEN - CALL vn.itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); + IF NOT vIsChecking OR NOT vIsChecked THEN + CALL itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); END IF; - UPDATE vn.itemShelving + UPDATE itemShelving SET isChecked = vIsChecked WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk AND isChecked IS NULL; + AND itemFk = vItemFk + AND isChecked IS NULL; SET vCounter = vCounter + 1; END WHILE; diff --git a/db/routines/vn/procedures/stockTraslation.sql b/db/routines/vn/procedures/item_calculateStock.sql similarity index 71% rename from db/routines/vn/procedures/stockTraslation.sql rename to db/routines/vn/procedures/item_calculateStock.sql index 4cc64fe3b..976ac10e4 100644 --- a/db/routines/vn/procedures/stockTraslation.sql +++ b/db/routines/vn/procedures/item_calculateStock.sql @@ -1,15 +1,13 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`stockTraslation`( +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_calculateStock`( vDated DATE ) BEGIN /** - * Calcula el stock del almacén de subasta desde FechaInventario hasta vDated - * sin tener en cuenta las salidas del mismo dia vDated - * para ver el transporte a reservar + * Calculate the stock of the auction warehouse from the inventory date to vDated * - * @param vDated Fecha hasta la cual calcula el stock - * @return tmp.item + * @param vDated Date to calculate the stock. + * @return tmp.item, tmp.buyUltimate */ DECLARE vAuctionWarehouseFk INT; diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 537f53848..336f3521e 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -24,6 +24,7 @@ BEGIN CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); + CALL buy_getUltimate(NULL, vWarehouseFk, vDated); WITH itemTags AS ( SELECT i.id, @@ -74,14 +75,13 @@ BEGIN AND a.calc_id = vAvailableCalcFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCalcFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - AND lb.warehouse_id = vWarehouseFk + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.id LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.buy b ON b.id = bu.buyFk JOIN itemTags its WHERE a.available > 0 AND (i.typeFk = its.typeFk OR NOT vShowType) @@ -98,5 +98,7 @@ BEGIN (i.tag8 = its.tag8) DESC, match8 DESC LIMIT 100; + + DROP TEMPORARY TABLE tmp.buyUltimate; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 0560cdd7e..1d206e20d 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -15,13 +15,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; - SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY - INTO vEndingDate - FROM productionConfig; - - SELECT isTodayRelative INTO vIsTodayRelative - FROM worker - WHERE id = getUser(); -- Cambiar por account.myUser_getId(), falta dar permisos + SELECT w.isTodayRelative, util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, pc.maxProductionScopeDays) DAY + INTO vIsTodayRelative,vEndingDate + FROM worker w + JOIN productionConfig pc + WHERE w.id = account.myUser_getId(); CALL prepareTicketList(util.yesterday(), vEndingDate); @@ -268,15 +266,14 @@ proc: BEGIN UPDATE tmp.productionBuffer pb JOIN sale s ON s.ticketFk = pb.ticketFk JOIN item i ON i.id = s.itemFk - JOIN cache.last_buy lb ON lb.warehouse_id = vWarehouseFk + JOIN cache.last_buy lb ON lb.warehouse_id = vWarehouseFk AND lb.item_id = s.itemFk JOIN buy b ON b.id = lb.buy_id JOIN packaging p ON p.id = b.packagingFk - JOIN productionConfig pc SET pb.hasPlantTray = TRUE WHERE p.isPlantTray AND s.quantity >= b.packing - AND pb.isOwn; + AND pb.isOwn; DROP TEMPORARY TABLE tmp.productionTicket, diff --git a/db/routines/vn/procedures/queueMember_updateQueue.sql b/db/routines/vn/procedures/queueMember_updateQueue.sql new file mode 100644 index 000000000..5af44da4f --- /dev/null +++ b/db/routines/vn/procedures/queueMember_updateQueue.sql @@ -0,0 +1,29 @@ +DELIMITER $$ + +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`queueMember_updateQueue`( + vBusinessFk INT +) +BEGIN + /** + * Elimina la entrada de la cola anterior y luego inserta la nueva para un trabajador. + * + * @param vBusinessFk ID del negocio + */ + DECLARE vNewQueue VARCHAR(10); + DECLARE vExtension VARCHAR(10); + DECLARE exit handler FOR SQLEXCEPTION + + SELECT d.pbxQueue, s.extension + INTO vNewQueue, vExtension + FROM business b + JOIN department d ON d.id = b.departmentFk + JOIN pbx.sip s ON s.user_id = b.workerFk + WHERE b.id = vBusinessFk; + + DELETE FROM pbx.queueMember + WHERE extension = vExtension COLLATE utf8_general_ci; + + INSERT IGNORE INTO pbx.queueMember (queue, extension) + VALUES (vNewQueue, vExtension); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/saleTracking_sectorCollectionAddPrevOK.sql b/db/routines/vn/procedures/saleTracking_sectorCollectionAddPrevOK.sql new file mode 100644 index 000000000..003168ec8 --- /dev/null +++ b/db/routines/vn/procedures/saleTracking_sectorCollectionAddPrevOK.sql @@ -0,0 +1,20 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`saleTracking_sectorCollectionAddPrevOK`( + vSectorCollectionFk INT +) +BEGIN +/** + * Inserta los registros de sectorCollection con el estado PREVIA OK si la reserva está picked + * + * @param vSectorCollectionFk Identificador de vn.sectorCollection + */ + REPLACE saleTracking(saleFk, isChecked, workerFk, stateFk) + SELECT sgd.saleFk, TRUE, sc.userFk, s.id + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + JOIN saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + JOIN state s ON s.code = 'OK PREVIOUS' + JOIN itemShelvingSale iss ON iss.saleFk = sgd.saleFk + WHERE sc.id = vSectorCollectionFk AND iss.isPicked; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index b50b4784d..cd65bb81c 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -127,7 +127,7 @@ BEGIN LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible, 0) < s.quantity - AND IFNULL(av.available, 0) < s.quantity + AND IFNULL(av.available, 0) < 0 AND IFNULL(issw.visible, 0) < s.quantity AND NOT s.isPicked AND NOT s.reserved @@ -190,7 +190,7 @@ BEGIN LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible, 0) < s.quantity - AND IFNULL(av.available, 0) >= s.quantity + AND IFNULL(av.available, 0) >= 0 AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 AND NOT s.isPicked diff --git a/db/routines/vn/procedures/stockBought_calculate.sql b/db/routines/vn/procedures/stockBought_calculate.sql index 8b2a32e5d..c3b5a0dc6 100644 --- a/db/routines/vn/procedures/stockBought_calculate.sql +++ b/db/routines/vn/procedures/stockBought_calculate.sql @@ -7,13 +7,13 @@ proc: BEGIN * Calculate the stock of the auction warehouse from the inventory date to vDated * without taking into account the outputs of the same day vDated * - * @param vDated Date to calculate the stock. + * @param vDated Date to calculate the stock */ IF vDated < util.VN_CURDATE() THEN LEAVE proc; END IF; - CREATE OR REPLACE TEMPORARY TABLE tStockBought + CREATE OR REPLACE TEMPORARY TABLE tCurrentData SELECT workerFk, reserve FROM stockBought WHERE dated = vDated @@ -21,15 +21,28 @@ proc: BEGIN DELETE FROM stockBought WHERE dated = vDated; + CREATE OR REPLACE TEMPORARY TABLE tStockSold + SELECT it.workerFk, + SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000) sold + FROM itemTicketOut ito + JOIN item i ON i.id = ito.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN ticket t ON t.id = ito.ticketFk + JOIN warehouse wh ON wh.id = t.warehouseFk + JOIN itemCost ic ON ic.itemFk = ito.itemFk + AND ic.warehouseFk = t.warehouseFk + JOIN volumeConfig vc + WHERE ito.shipped BETWEEN vDated AND util.dayEnd(vDated) + AND wh.code = 'VNH' + GROUP BY it.workerFk; + CALL item_calculateStock(vDated); - INSERT INTO stockBought(workerFk, bought, dated) + CREATE OR REPLACE TEMPORARY TABLE tStockBought SELECT it.workerFk, - ROUND(SUM( - (ti.quantity / b.packing) * - buy_getVolume(b.id) - ) / vc.palletM3 / 1000000, 1) bought, - vDated + SUM((ti.quantity / b.packing) * + buy_getVolume(b.id) + ) / vc.palletM3 / 1000000 bought FROM itemType it JOIN item i ON i.typeFk = it.id LEFT JOIN tmp.item ti ON ti.itemFk = i.id @@ -43,20 +56,33 @@ proc: BEGIN GROUP BY it.workerFk HAVING bought; + + INSERT INTO stockBought(workerFk, bought, dated) + SELECT tb.workerFk, + ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 2), + vDated + FROM tStockBought tb + LEFT JOIN tStockSold ts ON ts.workerFk = tb.workerFk; + UPDATE stockBought s - JOIN tStockBought ts ON ts.workerFk = s.workerFk + JOIN tCurrentData ts ON ts.workerFk = s.workerFk SET s.reserve = ts.reserve WHERE s.dated = vDated; INSERT INTO stockBought (workerFk, reserve, dated) SELECT ts.workerFk, ts.reserve, vDated - FROM tStockBought ts + FROM tCurrentData ts WHERE ts.workerFk NOT IN ( SELECT workerFk FROM stockBought WHERE dated = vDated ); - DROP TEMPORARY TABLE tStockBought, tmp.item, tmp.buyUltimate; + UPDATE stockBought s + JOIN tStockSold ts ON ts.workerFk = s.workerFk + SET s.bought = IF(s.bought < ts.sold, ROUND(s.bought - ts.sold, 1), 0) + WHERE s.dated = vDated; + + DROP TEMPORARY TABLE tCurrentData, tmp.item, tmp.buyUltimate, tStockSold; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/stockBuyedByWorker.sql b/db/routines/vn/procedures/stockBuyedByWorker.sql index a0bad78d4..536638770 100644 --- a/db/routines/vn/procedures/stockBuyedByWorker.sql +++ b/db/routines/vn/procedures/stockBuyedByWorker.sql @@ -23,7 +23,7 @@ BEGIN WHERE dated = vDated AND userFk = vWorker; - CALL stockTraslation(vDated); + CALL item_calculateStock(vDated); INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description) SELECT it.workerFk, @@ -71,4 +71,4 @@ BEGIN tmp.item, tStockBuyed; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/stockBuyed_add.sql b/db/routines/vn/procedures/stockBuyed_add.sql index 104a2d34d..0491c2424 100644 --- a/db/routines/vn/procedures/stockBuyed_add.sql +++ b/db/routines/vn/procedures/stockBuyed_add.sql @@ -18,7 +18,7 @@ BEGIN DELETE FROM stockBuyed WHERE dated = vDated; - CALL stockTraslation(vDated); + CALL item_calculateStock(vDated); INSERT INTO stockBuyed(userFk, buyed, `dated`, description) SELECT it.workerFk, @@ -67,4 +67,4 @@ BEGIN tmp.item, tStockBuyed; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ticketRefund_upsert.sql b/db/routines/vn/procedures/ticketRefund_upsert.sql new file mode 100644 index 000000000..fb22e6e8c --- /dev/null +++ b/db/routines/vn/procedures/ticketRefund_upsert.sql @@ -0,0 +1,25 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticketRefund_upsert`( + vRefundTicketFk INT, + vOriginalTicketFk INT +) + READS SQL DATA +BEGIN +/** + * Common code for ticketRefund triggers + * + * @param vRefundTicketFk + * @param vOriginalTicketFk + */ + DECLARE vIsDeleted BOOL; + + SELECT COUNT(*) INTO vIsDeleted + FROM ticket + WHERE id IN (vRefundTicketFk, vOriginalTicketFk) + AND isDeleted; + + IF vIsDeleted THEN + CALL util.throw('The refund ticket cannot be deleted tickets'); + END IF; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index 57c3f4235..e8fc70bba 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -51,7 +51,8 @@ BEGIN origin.companyFk futureCompanyFk, IFNULL(dest.nickname, origin.nickname) nickname, dest.landed, - dest.preparation + dest.preparation, + origin.departmentFk FROM ( SELECT s.ticketFk, c.salesPersonFk workerFk, @@ -71,9 +72,11 @@ BEGIN t.addressFk, t.warehouseFk, t.companyFk, - t.agencyModeFk + t.agencyModeFk, + wd.departmentFk FROM ticket t JOIN client c ON c.id = t.clientFk + JOIN workerDepartment wd ON wd.workerFk = c.salesPersonFk JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id JOIN item i ON i.id = s.itemFk diff --git a/db/routines/vn/procedures/ticket_close.sql b/db/routines/vn/procedures/ticket_close.sql index 0da001ffa..e2dcef9a5 100644 --- a/db/routines/vn/procedures/ticket_close.sql +++ b/db/routines/vn/procedures/ticket_close.sql @@ -43,7 +43,7 @@ BEGIN c.isTaxDataChecked, t.companyFk, t.shipped, - IFNULL(a.hasDailyInvoice, co.hasDailyInvoice), + c.hasDailyInvoice, w.isManaged, c.hasToInvoice INTO vClientFk, @@ -55,9 +55,6 @@ BEGIN vHasToInvoice FROM ticket t JOIN `client` c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - LEFT JOIN autonomy a ON a.id = p.autonomyFk - JOIN country co ON co.id = p.countryFk JOIN warehouse w ON w.id = t.warehouseFk WHERE t.id = vCurTicketFk; @@ -85,7 +82,7 @@ BEGIN IF(vHasDailyInvoice) AND vHasToInvoice THEN SELECT invoiceSerial(vClientFk, vCompanyFk, 'quick') INTO vSerial; - IF vSerial IS NULL THEN + IF vSerial IS NULL THEN CALL util.throw('Cannot booking without a serial'); END IF; diff --git a/db/routines/vn/procedures/ticket_getTax.sql b/db/routines/vn/procedures/ticket_getTax.sql index 947c45806..cb9dc09d9 100644 --- a/db/routines/vn/procedures/ticket_getTax.sql +++ b/db/routines/vn/procedures/ticket_getTax.sql @@ -1,5 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_getTax`(IN vTaxArea VARCHAR(25)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_getTax`( + vTaxArea VARCHAR(25) +) BEGIN /** * Calcula la base imponible, el IVA y el recargo de equivalencia para @@ -33,30 +35,39 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.ticketTax (PRIMARY KEY (ticketFk, code, rate)) ENGINE = MEMORY - SELECT * FROM ( - SELECT tmpTicket.ticketFk, - bp.pgcFk, - SUM(s.quantity * s.price * (100 - s.discount) / 100 ) taxableBase, - pgc.rate, - tc.code, - bp.priority - FROM tmp.ticket tmpTicket - JOIN sale s ON s.ticketFk = tmpTicket.ticketFk - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = tmpTicket.ticketFk - JOIN supplier su ON su.id = t.companyFk + WITH sales AS ( + SELECT s.ticketFk, + s.itemFk, + s.quantity * s.price * (100 - s.discount) / 100 total, + t.companyFk, + t.addressFk, + su.countryFk, + ata.areaFk, + itc.taxClassFk + FROM vn.sale s + JOIN tmp.ticket tmp ON tmp.ticketFk = s.ticketFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.supplier su ON su.id = t.companyFk JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc ON itc.itemFk = i.id + JOIN vn.itemTaxCountry itc ON itc.itemFk = s.itemFk AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp ON bp.countryFk = su.countryFk - AND bp.taxAreaFk = ata.areaFk - AND bp.taxClassFk = itc.taxClassFk - JOIN pgc ON pgc.code = bp.pgcFk - JOIN taxClass tc ON tc.id = bp.taxClassFk - GROUP BY tmpTicket.ticketFk, pgc.code, pgc.rate - HAVING taxableBase - ) t3 + HAVING total + ) + SELECT s.ticketFk, + bp.pgcFk, + SUM(s.total) taxableBase, + pgc.rate, + tc.code, + bp.priority + FROM sales s + JOIN vn.bookingPlanner bp ON bp.countryFk = s.countryFk + AND bp.taxAreaFk = s.areaFk + AND bp.taxClassFk = s.taxClassFk + JOIN vn.pgc ON pgc.code = bp.pgcFk + JOIN vn.taxClass tc ON tc.id = bp.taxClassFk + GROUP BY s.ticketFk, pgc.code, pgc.rate + HAVING taxableBase ORDER BY priority; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketServiceTax diff --git a/db/routines/vn/procedures/ticket_mergeSales.sql b/db/routines/vn/procedures/ticket_mergeSales.sql index 0bde200b0..8ef5f6d90 100644 --- a/db/routines/vn/procedures/ticket_mergeSales.sql +++ b/db/routines/vn/procedures/ticket_mergeSales.sql @@ -3,12 +3,25 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_mergeSales`( vSelf INT ) BEGIN +/** + * Para un ticket se agrupa las diferentes líneas de venta de un mismo artículo en una sola + * siempre y cuando tengan el mismo precio y dto. + * + * @param vSelf Id de ticket + */ + DECLARE vHasSalesToMerge BOOL; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; + START TRANSACTION; + + SELECT id INTO vSelf + FROM ticket + WHERE id = vSelf FOR UPDATE; + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve (PRIMARY KEY (id)) ENGINE = MEMORY @@ -18,26 +31,24 @@ BEGIN JOIN itemType it ON it.id = i.typeFk WHERE s.ticketFk = vSelf AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; + GROUP BY s.itemFk, s.price, s.discount + HAVING COUNT(*) > 1; - START TRANSACTION; + SELECT COUNT(*) INTO vHasSalesToMerge FROM tSalesToPreserve; - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET s.quantity = newQuantity - WHERE s.ticketFk = vSelf; + IF vHasSalesToMerge THEN + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET s.quantity = newQuantity; - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vSelf - AND stp.id IS NULL - AND it.isMergeable; + DELETE s + FROM sale s + JOIN tSalesToPreserve stp ON stp.itemFk = s.itemFk + WHERE s.ticketFk = vSelf + AND s.id <> stp.id; + END IF; COMMIT; - DROP TEMPORARY TABLE tSalesToPreserve; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/worker_updateBusiness.sql b/db/routines/vn/procedures/worker_updateBusiness.sql index a160c417a..43edb0416 100644 --- a/db/routines/vn/procedures/worker_updateBusiness.sql +++ b/db/routines/vn/procedures/worker_updateBusiness.sql @@ -21,6 +21,8 @@ BEGIN SET businessFk = vNewBusinessFk WHERE id = vSelf; + CALL queueMember_updateQueue(vNewBusinessFk); + IF vOldBusinessFk IS NULL THEN CALL account.account_enable(vSelf); diff --git a/db/routines/vn/triggers/business_afterUpdate.sql b/db/routines/vn/triggers/business_afterUpdate.sql index 888308b9a..11aeb88b6 100644 --- a/db/routines/vn/triggers/business_afterUpdate.sql +++ b/db/routines/vn/triggers/business_afterUpdate.sql @@ -3,10 +3,20 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`business_afterUpdate` AFTER UPDATE ON `business` FOR EACH ROW BEGIN + DECLARE vIsActive BOOL; + DECLARE vExtension VARCHAR(10); + CALL worker_updateBusiness(NEW.workerFk); IF NOT (OLD.workerFk <=> NEW.workerFk) THEN CALL worker_updateBusiness(OLD.workerFk); END IF; + + IF NOT (OLD.departmentFk <=> NEW.departmentFk) THEN + SELECT COUNT(*) INTO vIsActive FROM worker WHERE businessFk = NEW.id; + IF vIsActive THEN + CALL queueMember_updateQueue(NEW.id); + END IF; + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/ticketRefund_beforeInsert.sql b/db/routines/vn/triggers/ticketRefund_beforeInsert.sql index 61d9fe7a2..dd1da6650 100644 --- a/db/routines/vn/triggers/ticketRefund_beforeInsert.sql +++ b/db/routines/vn/triggers/ticketRefund_beforeInsert.sql @@ -3,6 +3,8 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`ticketRefund_beforeInse BEFORE INSERT ON `ticketRefund` FOR EACH ROW BEGIN + CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk); + SET NEW.editorFk = account.myUser_getId(); END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql b/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql index 807695de6..f27e3f092 100644 --- a/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql +++ b/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql @@ -3,6 +3,8 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`ticketRefund_beforeUpda BEFORE UPDATE ON `ticketRefund` FOR EACH ROW BEGIN + CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk); + SET NEW.editorFk = account.myUser_getId(); END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/travelThermograph_beforeInsert.sql b/db/routines/vn/triggers/travelThermograph_beforeInsert.sql index f56109fba..256ee12a6 100644 --- a/db/routines/vn/triggers/travelThermograph_beforeInsert.sql +++ b/db/routines/vn/triggers/travelThermograph_beforeInsert.sql @@ -4,5 +4,14 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`travelThermograph_befor FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + + IF NEW.travelFk IS NULL AND + (SELECT COUNT(*) FROM travelThermograph + WHERE thermographFk = NEW.thermographFk + AND travelFk IS NULL + AND id <> NEW.id) > 0 + THEN + CALL util.throw('Duplicate thermographFk without travelFk not allowed.'); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/travelThermograph_beforeUpdate.sql b/db/routines/vn/triggers/travelThermograph_beforeUpdate.sql index 49f52f181..ffe81b38d 100644 --- a/db/routines/vn/triggers/travelThermograph_beforeUpdate.sql +++ b/db/routines/vn/triggers/travelThermograph_beforeUpdate.sql @@ -4,5 +4,14 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`travelThermograph_befor FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + + IF NEW.travelFk IS NULL AND + (SELECT COUNT(*) FROM travelThermograph + WHERE thermographFk = NEW.thermographFk + AND travelFk IS NULL + AND id <> NEW.id) > 0 + THEN + CALL util.throw('Duplicate thermographFk without travelFk not allowed.'); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn2008/views/Agencias.sql b/db/routines/vn2008/views/Agencias.sql index d70ec73f4..1176d02c4 100644 --- a/db/routines/vn2008/views/Agencias.sql +++ b/db/routines/vn2008/views/Agencias.sql @@ -13,6 +13,5 @@ AS SELECT `am`.`id` AS `Id_Agencia`, `am`.`reportMail` AS `send_mail`, `am`.`isActive` AS `tpv`, `am`.`code` AS `code`, - `am`.`showAgencyName` AS `show_AgencyName`, `am`.`isRiskFree` AS `isRiskFree` FROM `vn`.`agencyMode` `am` diff --git a/db/routines/vn2008/views/Clientes.sql b/db/routines/vn2008/views/Clientes.sql index 153d875bc..9f8ef712e 100644 --- a/db/routines/vn2008/views/Clientes.sql +++ b/db/routines/vn2008/views/Clientes.sql @@ -22,7 +22,6 @@ AS SELECT `c`.`id` AS `id_cliente`, `c`.`credit` AS `credito`, `c`.`countryFk` AS `Id_Pais`, `c`.`isActive` AS `activo`, - `c`.`gestdocFk` AS `gestdoc_id`, `c`.`quality` AS `calidad`, `c`.`payMethodFk` AS `pay_met_id`, `c`.`created` AS `created`, diff --git a/db/routines/vn2008/views/Compres_mark.sql b/db/routines/vn2008/views/Compres_mark.sql deleted file mode 100644 index 7138c4e4c..000000000 --- a/db/routines/vn2008/views/Compres_mark.sql +++ /dev/null @@ -1,8 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Compres_mark` -AS SELECT `bm`.`id` AS `Id_Compra`, - `bm`.`comment` AS `comment`, - `bm`.`mark` AS `mark`, - `bm`.`odbcDate` AS `odbc_date` -FROM `vn`.`buyMark` `bm` diff --git a/db/versions/11198-blackPhormium/00-firstScript.sql b/db/versions/11198-blackPhormium/00-firstScript.sql new file mode 100644 index 000000000..6c181ed21 --- /dev/null +++ b/db/versions/11198-blackPhormium/00-firstScript.sql @@ -0,0 +1,7 @@ +UPDATE vn.itemShelving + SET isChecked = TRUE + WHERE isChecked; + +UPDATE vn.itemShelving + SET isChecked = FALSE + WHERE NOT isChecked; diff --git a/db/versions/11230-brownEucalyptus/00-addClientObservationType.sql b/db/versions/11230-brownEucalyptus/00-addClientObservationType.sql new file mode 100644 index 000000000..f69e20611 --- /dev/null +++ b/db/versions/11230-brownEucalyptus/00-addClientObservationType.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.clientObservation DROP COLUMN IF EXISTS observationTypeFk; +ALTER TABLE vn.clientObservation ADD COLUMN IF NOT EXISTS observationTypeFk TINYINT(3) UNSIGNED NULL; +ALTER TABLE vn.clientObservation ADD CONSTRAINT clientObservationTypeFk FOREIGN KEY IF NOT EXISTS (observationTypeFk) REFERENCES vn.observationType(id); diff --git a/db/versions/11230-brownEucalyptus/01-addNewObservation.vn.sql b/db/versions/11230-brownEucalyptus/01-addNewObservation.vn.sql new file mode 100644 index 000000000..983419111 --- /dev/null +++ b/db/versions/11230-brownEucalyptus/01-addNewObservation.vn.sql @@ -0,0 +1,3 @@ +INSERT IGNORE INTO vn.observationType + SET description = 'Finance', + code = 'finance'; \ No newline at end of file diff --git a/db/versions/11242-whiteAnthurium/00-firstScript.sql b/db/versions/11242-whiteAnthurium/00-firstScript.sql new file mode 100644 index 000000000..43dccf374 --- /dev/null +++ b/db/versions/11242-whiteAnthurium/00-firstScript.sql @@ -0,0 +1,3 @@ +DELETE FROM salix.ACL + WHERE model = 'WorkerLog' + AND property = '*'; \ No newline at end of file diff --git a/db/versions/11251-navyChrysanthemum/00-firstScript.sql b/db/versions/11251-navyChrysanthemum/00-firstScript.sql new file mode 100644 index 000000000..7c2c69839 --- /dev/null +++ b/db/versions/11251-navyChrysanthemum/00-firstScript.sql @@ -0,0 +1,2 @@ +-- Debido a que tardaba mucho en la subida a master, se ha creado una nueva versión para que el proceso no se vea afectado y se ejecute por la noche. +-- Se crea de nuevo en la versión 11344-grayBamboo diff --git a/db/versions/11254-tealCarnation/00-thermographTemperature.sql b/db/versions/11254-tealCarnation/00-thermographTemperature.sql new file mode 100644 index 000000000..123e6c665 --- /dev/null +++ b/db/versions/11254-tealCarnation/00-thermographTemperature.sql @@ -0,0 +1,3 @@ +ALTER TABLE `vn`.`travelThermograph` +ADD COLUMN `maxTemperature` DECIMAL(5,2) NULL AFTER `temperatureFk`, +ADD COLUMN `minTemperature` DECIMAL(5,2) NULL AFTER `maxTemperature`; diff --git a/db/versions/11254-tealCarnation/01-thermographFk.sql b/db/versions/11254-tealCarnation/01-thermographFk.sql new file mode 100644 index 000000000..2baf99a45 --- /dev/null +++ b/db/versions/11254-tealCarnation/01-thermographFk.sql @@ -0,0 +1,2 @@ +ALTER TABLE `vn`.`travelThermograph` DROP FOREIGN KEY travelThermographDmsFgn; +ALTER TABLE `vn`.`travelThermograph` ADD CONSTRAINT travelThermographDmsFgn FOREIGN KEY (dmsFk) REFERENCES vn.dms(id) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/db/versions/11258-silverTulip/00-firstScript.sql b/db/versions/11258-silverTulip/00-firstScript.sql new file mode 100644 index 000000000..79910fa76 --- /dev/null +++ b/db/versions/11258-silverTulip/00-firstScript.sql @@ -0,0 +1,31 @@ +-- vn.priceDelta definition + +CREATE OR REPLACE TABLE vn.priceDelta ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `itemTypeFk` smallint(5) unsigned NOT NULL, + `minSize` int(10) unsigned DEFAULT NULL COMMENT 'Minimum item.size', + `maxSize` int(10) unsigned DEFAULT NULL COMMENT 'Maximum item.size', + `inkFk` varchar(3) DEFAULT NULL, + `originFk` tinyint(2) unsigned DEFAULT NULL, + `producerFk` mediumint(3) unsigned DEFAULT NULL, + `fromDated` date DEFAULT NULL, + `toDated` date DEFAULT NULL, + `absIncreasing` decimal(10,3) DEFAULT NULL COMMENT 'Absolute increasing of final price', + `ratIncreasing` int(11) DEFAULT NULL COMMENT 'Increasing ratio for the cost price', + `warehouseFk` smallint(6) unsigned NOT NULL, + `created` timestamp NOT NULL DEFAULT current_timestamp(), + `editorFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `priceDelta_itemType_FK` (`itemTypeFk`), + KEY `priceDelta_ink_FK` (`inkFk`), + KEY `priceDelta_producer_FK` (`producerFk`), + KEY `priceDelta_warehouse_FK` (`warehouseFk`), + KEY `priceDelta_worker_FK` (`editorFk`), + CONSTRAINT `priceDelta_ink_FK` FOREIGN KEY (`inkFk`) REFERENCES `ink` (`id`) ON UPDATE CASCADE, + CONSTRAINT `priceDelta_itemType_FK` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `priceDelta_producer_FK` FOREIGN KEY (`producerFk`) REFERENCES `producer` (`id`) ON UPDATE CASCADE, + CONSTRAINT `priceDelta_warehouse_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `priceDelta_worker_FK` FOREIGN KEY (`editorFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Defines the increasing o decreasing for ranges of items'; + +GRANT INSERT, SELECT, UPDATE, DELETE ON TABLE vn.priceDelta TO buyer; \ No newline at end of file diff --git a/db/versions/11260-navyCyca/00-firstScript.sql b/db/versions/11260-navyCyca/00-firstScript.sql new file mode 100644 index 000000000..0824ea5f7 --- /dev/null +++ b/db/versions/11260-navyCyca/00-firstScript.sql @@ -0,0 +1,32 @@ +-- Place your SQL code here +-- vn.priceDelta definition + +CREATE OR REPLACE TABLE vn.priceDelta ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `itemTypeFk` smallint(5) unsigned NOT NULL, + `minSize` int(10) unsigned DEFAULT NULL COMMENT 'Minimum item.size', + `maxSize` int(10) unsigned DEFAULT NULL COMMENT 'Maximum item.size', + `inkFk` varchar(3) DEFAULT NULL, + `originFk` tinyint(2) unsigned DEFAULT NULL, + `producerFk` mediumint(3) unsigned DEFAULT NULL, + `fromDated` date DEFAULT NULL, + `toDated` date DEFAULT NULL, + `absIncreasing` decimal(10,3) DEFAULT NULL COMMENT 'Absolute increasing of final price', + `ratIncreasing` int(11) DEFAULT NULL COMMENT 'Increasing ratio for the cost price', + `warehouseFk` smallint(6) unsigned NOT NULL, + `created` timestamp NOT NULL DEFAULT current_timestamp(), + `editorFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `priceDelta_itemType_FK` (`itemTypeFk`), + KEY `priceDelta_ink_FK` (`inkFk`), + KEY `priceDelta_producer_FK` (`producerFk`), + KEY `priceDelta_warehouse_FK` (`warehouseFk`), + KEY `priceDelta_worker_FK` (`editorFk`), + CONSTRAINT `priceDelta_ink_FK` FOREIGN KEY (`inkFk`) REFERENCES `ink` (`id`) ON UPDATE CASCADE, + CONSTRAINT `priceDelta_itemType_FK` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `priceDelta_producer_FK` FOREIGN KEY (`producerFk`) REFERENCES `producer` (`id`) ON UPDATE CASCADE, + CONSTRAINT `priceDelta_warehouse_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `priceDelta_worker_FK` FOREIGN KEY (`editorFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Defines the increasing o decreasing for ranges of items'; + +GRANT INSERT, SELECT, UPDATE, DELETE ON TABLE vn.priceDelta TO buyer; \ No newline at end of file diff --git a/db/versions/11261-bronzeDracena/00-firstScript.sql b/db/versions/11261-bronzeDracena/00-firstScript.sql new file mode 100644 index 000000000..1ef944db2 --- /dev/null +++ b/db/versions/11261-bronzeDracena/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.agencyMode + CHANGE IF EXISTS showAgencyName showAgencyName__ tinyint(1) DEFAULT 1 COMMENT '@deprecated 2024-09-24'; \ No newline at end of file diff --git a/db/versions/11264-turquoisePaniculata/00-firstScript.sql b/db/versions/11264-turquoisePaniculata/00-firstScript.sql new file mode 100644 index 000000000..8ca3df265 --- /dev/null +++ b/db/versions/11264-turquoisePaniculata/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE dipole.expedition_PrintOut DROP COLUMN IF EXISTS isChecked; diff --git a/db/versions/11271-blackMastic/00-firstScript.sql b/db/versions/11271-blackMastic/00-firstScript.sql new file mode 100644 index 000000000..dcc8349a5 --- /dev/null +++ b/db/versions/11271-blackMastic/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE vn.priceDelta ADD IF NOT EXISTS zoneGeoFk int(11) NULL COMMENT 'Application area for the bonus component'; +ALTER TABLE vn.priceDelta ADD CONSTRAINT priceDelta_zoneGeo_FK FOREIGN KEY IF NOT EXISTS (zoneGeoFk) REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/versions/11272-azureLilium/00-firstScript.sql b/db/versions/11272-azureLilium/00-firstScript.sql new file mode 100644 index 000000000..0194ece18 --- /dev/null +++ b/db/versions/11272-azureLilium/00-firstScript.sql @@ -0,0 +1,4 @@ +-- Place your SQL code here +RENAME TABLE vn.stockBuyed TO vn.stockBuyed__; +ALTER TABLE vn.stockBuyed__ +COMMENT='@deprecated 2024-10-01 rename and refactor to stockBought'; diff --git a/db/versions/11274-redGerbera/00-firstScript.sql b/db/versions/11274-redGerbera/00-firstScript.sql new file mode 100644 index 000000000..8bcf7e027 --- /dev/null +++ b/db/versions/11274-redGerbera/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE account.user MODIFY COLUMN emailVerified tinyint(1) DEFAULT FALSE NOT NULL; diff --git a/db/versions/11274-redGerbera/00-firstScript2.sql b/db/versions/11274-redGerbera/00-firstScript2.sql new file mode 100644 index 000000000..f14ff371d --- /dev/null +++ b/db/versions/11274-redGerbera/00-firstScript2.sql @@ -0,0 +1 @@ +ALTER TABLE bs.defaulter MODIFY COLUMN hasChanged tinyint(1) DEFAULT FALSE NOT NULL; diff --git a/db/versions/11274-redGerbera/00-firstScript3.sql b/db/versions/11274-redGerbera/00-firstScript3.sql new file mode 100644 index 000000000..452accf2e --- /dev/null +++ b/db/versions/11274-redGerbera/00-firstScript3.sql @@ -0,0 +1 @@ +ALTER TABLE vn.address MODIFY COLUMN isEqualizated tinyint(1) DEFAULT FALSE NOT NULL; diff --git a/db/versions/11274-redGerbera/00-firstScript5.sql b/db/versions/11274-redGerbera/00-firstScript5.sql new file mode 100644 index 000000000..18a4d3314 --- /dev/null +++ b/db/versions/11274-redGerbera/00-firstScript5.sql @@ -0,0 +1 @@ +ALTER TABLE vn.chat MODIFY COLUMN checkUserStatus tinyint(1) DEFAULT FALSE NOT NULL; diff --git a/db/versions/11274-redGerbera/00-firstScript6.sql b/db/versions/11274-redGerbera/00-firstScript6.sql new file mode 100644 index 000000000..c75965735 --- /dev/null +++ b/db/versions/11274-redGerbera/00-firstScript6.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.warehouse + MODIFY COLUMN isOrigin tinyint(1) DEFAULT FALSE NOT NULL, + MODIFY COLUMN isDestiny tinyint(1) DEFAULT FALSE NOT NULL; \ No newline at end of file diff --git a/db/versions/11274-redGerbera/00-firstScript7.sql b/db/versions/11274-redGerbera/00-firstScript7.sql new file mode 100644 index 000000000..63b942e9d --- /dev/null +++ b/db/versions/11274-redGerbera/00-firstScript7.sql @@ -0,0 +1 @@ +ALTER TABLE vn.zoneIncluded MODIFY COLUMN isIncluded tinyint(1) DEFAULT FALSE NOT NULL; diff --git a/db/versions/11277-wheatChico/00-firstScript.sql b/db/versions/11277-wheatChico/00-firstScript.sql new file mode 100644 index 000000000..c2b5963a4 --- /dev/null +++ b/db/versions/11277-wheatChico/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE hedera.`order` ADD IF NOT EXISTS rowUpdated DATETIME NULL + COMMENT 'Timestamp for last updated record in orderRow table'; diff --git a/db/versions/11281-purpleCyca/00-firstScript.sql b/db/versions/11281-purpleCyca/00-firstScript.sql new file mode 100644 index 000000000..eadba5ae1 --- /dev/null +++ b/db/versions/11281-purpleCyca/00-firstScript.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS vn.buyMark; diff --git a/db/versions/11283-redAspidistra/00-firstScript.sql b/db/versions/11283-redAspidistra/00-firstScript.sql new file mode 100644 index 000000000..a88091297 --- /dev/null +++ b/db/versions/11283-redAspidistra/00-firstScript.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.itemShelving DROP FOREIGN KEY itemShelving_fk2; +ALTER TABLE vn.itemShelving ADD CONSTRAINT itemShelving_fk2 + FOREIGN KEY (shelvingFk) REFERENCES vn.shelving(code) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/versions/11284-turquoiseLaurel/00-firstScript.sql b/db/versions/11284-turquoiseLaurel/00-firstScript.sql new file mode 100644 index 000000000..34762faf6 --- /dev/null +++ b/db/versions/11284-turquoiseLaurel/00-firstScript.sql @@ -0,0 +1,2 @@ +-- Place your SQL code here +ALTER TABLE vn.itemShelving ADD IF NOT EXISTS isMoving BOOL DEFAULT FALSE NOT NULL COMMENT 'Indica que se ha marcado este registro para transferirlo a otro sector'; diff --git a/db/versions/11285-orangeErica/00-firstScript.sql b/db/versions/11285-orangeErica/00-firstScript.sql new file mode 100644 index 000000000..c13571f3a --- /dev/null +++ b/db/versions/11285-orangeErica/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE vn.itemShelving DROP COLUMN IF EXISTS isMoving; +ALTER TABLE vn.itemShelving ADD IF NOT EXISTS movingState ENUM('selected','printed') NULL; diff --git a/db/versions/11287-azureRaphis/00-firstScript.sql b/db/versions/11287-azureRaphis/00-firstScript.sql new file mode 100644 index 000000000..77d60eb40 --- /dev/null +++ b/db/versions/11287-azureRaphis/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE hedera.`order` ADD IF NOT EXISTS rowUpdated DATETIME NULL + COMMENT 'Timestamp for last updated record in orderRow table'; \ No newline at end of file diff --git a/db/versions/11290-blackOrchid/00-firstScript.sql b/db/versions/11290-blackOrchid/00-firstScript.sql new file mode 100644 index 000000000..fe568ed6e --- /dev/null +++ b/db/versions/11290-blackOrchid/00-firstScript.sql @@ -0,0 +1,6 @@ +ALTER TABLE `vn`.`operator` +ADD COLUMN `machineFk` int(11) DEFAULT NULL, +ADD CONSTRAINT `operator_machine_FK` FOREIGN KEY (`machineFk`) REFERENCES `vn`.`machine` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Machine','*','*','ALLOW','ROLE','productionBoss'); diff --git a/db/versions/11294-azureFern/00-firstScript.sql b/db/versions/11294-azureFern/00-firstScript.sql new file mode 100644 index 000000000..2d6ed3a5b --- /dev/null +++ b/db/versions/11294-azureFern/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE vn.itemShelving DROP COLUMN IF EXISTS isMoving; +ALTER TABLE vn.itemShelving ADD IF NOT EXISTS movingState ENUM('selected','printed') NULL; \ No newline at end of file diff --git a/db/versions/11298-wheatIvy/00-closure.sql b/db/versions/11298-wheatIvy/00-closure.sql new file mode 100644 index 000000000..7b33939cf --- /dev/null +++ b/db/versions/11298-wheatIvy/00-closure.sql @@ -0,0 +1,3 @@ +ALTER TABLE `vn`.`ticketConfig` +ADD COLUMN `closureDaysAgo` int(11) NOT NULL DEFAULT 2 COMMENT 'Number of days to look back for ticket closure', +ADD CONSTRAINT `closureDaysAgo_check` CHECK (`closureDaysAgo` > 0); diff --git a/db/versions/11300-limeMedeola/00-firstScript.sql b/db/versions/11300-limeMedeola/00-firstScript.sql new file mode 100644 index 000000000..28b033b4a --- /dev/null +++ b/db/versions/11300-limeMedeola/00-firstScript.sql @@ -0,0 +1,137 @@ +CREATE TABLE IF NOT EXISTS `vn`.`itemFarmingTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemFarmingTag` (`name`) VALUES ('Enraizado'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemFarmingTag' + WHERE name= 'cultivo'; + +CREATE TABLE IF NOT EXISTS `vn`.`itemWrappingTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Bolsa'); +INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Caja cartón'); +INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Caja decorativa'); +INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Celofán'); +INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Papel kraft'); +INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Plástico'); +INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Variable'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemWrappingTag' + WHERE name= 'Envoltorio'; + +CREATE TABLE IF NOT EXISTS `vn`.`itemLanguageTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Castellano'); +INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Catalán'); +INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Euskera'); +INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Francés'); +INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Gallego'); +INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Inglés'); +INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Portugués'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemLanguageTag' + WHERE name= 'Idioma'; + +CREATE TABLE IF NOT EXISTS `vn`.`itemStemTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemStemTag` (`name`) VALUES ('Natural'); +INSERT IGNORE INTO `vn`.`itemStemTag` (`name`) VALUES ('Seminatural'); +INSERT IGNORE INTO `vn`.`itemStemTag` (`name`) VALUES ('Sintético'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemStemTag' + WHERE name= 'Tronco'; + + +CREATE TABLE IF NOT EXISTS `vn`.`itemBreederTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemBreederTag` (`name`) VALUES ('David Austin'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemBreederTag' + WHERE name= 'Obtentor'; + +CREATE TABLE IF NOT EXISTS `vn`.`itemBaseTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Biodegradable'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Caballete'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Cerámica'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Cristal'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Plástico por inyección'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Madera'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Plástico'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Rígido'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Ruedas'); +INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Sin soporte rígido'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemBaseTag' + WHERE name= 'Soporte'; + +CREATE TABLE IF NOT EXISTS `vn`.`itemVatRateTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemVatRateTag` (`name`) VALUES ('General'); +INSERT IGNORE INTO `vn`.`itemVatRateTag` (`name`) VALUES ('Reducido'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemVatRateTag' + WHERE name= 'Tipo de IVA'; + +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemFarmingTag TO logisticAssist; +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemWrappingTag TO logisticAssist; +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemLanguageTag TO logisticAssist; +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemStemTag TO logisticAssist; +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemWrappingTag TO logisticAssist; +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemBaseTag TO logisticAssist; +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemBreederTag TO logisticAssist; \ No newline at end of file diff --git a/db/versions/11302-limeTulip/00-firstScript.sql b/db/versions/11302-limeTulip/00-firstScript.sql new file mode 100644 index 000000000..7bda31b64 --- /dev/null +++ b/db/versions/11302-limeTulip/00-firstScript.sql @@ -0,0 +1,13 @@ + +UPDATE `vn`.`client` c + JOIN `vn`.`country` co ON co.id=c.countryFk +SET c.hasDailyInvoice = co.hasDailyInvoice +WHERE co.hasDailyInvoice IS NOT NULL + AND c.hasDailyInvoice = FALSE; + +UPDATE `vn`.`client` c + JOIN `vn`.`province` p ON p.id=c.provinceFk + JOIN `vn`.`autonomy` a ON a.id = p.autonomyFk +SET c.hasDailyInvoice = a.hasDailyInvoice +WHERE a.hasDailyInvoice IS NOT NULL + AND c.hasDailyInvoice = FALSE; diff --git a/db/versions/11308-redCymbidium/00-firstScript.sql b/db/versions/11308-redCymbidium/00-firstScript.sql new file mode 100644 index 000000000..fe76cb600 --- /dev/null +++ b/db/versions/11308-redCymbidium/00-firstScript.sql @@ -0,0 +1,25 @@ +CREATE TABLE IF NOT EXISTS `vn`.`itemCampaign` ( + `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, + dated date NOT NULL, + itemFk int(11) NOT NULL, + quantity decimal(10,2) NOT NULL, + total decimal(10,2) NOT NULL, + campaign varchar(100) NOT NULL, + UNIQUE KEY `itemCampaign_UNIQUE` (`dated`,`itemFk`), + CONSTRAINT itemCampaign_item_FK FOREIGN KEY (itemFk) REFERENCES vn.item(id) ON DELETE RESTRICT ON UPDATE CASCADE +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci +COMMENT='Tallos confirmados por día en los días de más producción de una campaña. La tabla está pensada para que sea una foto.'; + +ALTER TABLE vn.campaign + ADD previousDays int(10) unsigned DEFAULT 30 NOT NULL COMMENT 'Días previos para calcular e insertar en la tabla itemCampaign'; + +UPDATE vn.campaign + SET previousDays = 90 + WHERE code = 'allSaints'; + +UPDATE vn.campaign + SET previousDays = 60 + WHERE code IN ('valentinesDay', 'mothersDay'); diff --git a/db/versions/11311-tealFern/00-firstScript.sql b/db/versions/11311-tealFern/00-firstScript.sql new file mode 100644 index 000000000..909747f3c --- /dev/null +++ b/db/versions/11311-tealFern/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.client CHANGE gestdocFk gestdocFk__ int(11) DEFAULT NULL NULL COMMENT '@deprecated 2024-10-17'; \ No newline at end of file diff --git a/db/versions/11324-salmonCataractarum/00-firstScript.sql b/db/versions/11324-salmonCataractarum/00-firstScript.sql new file mode 100644 index 000000000..5c17ed549 --- /dev/null +++ b/db/versions/11324-salmonCataractarum/00-firstScript.sql @@ -0,0 +1,71 @@ +CREATE TABLE IF NOT EXISTS `vn`.`itemTextureTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y encerado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y esponjoso'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y foam'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y látex'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Arenosa'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Aterciopelado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Flocado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Foam'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Gasa'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Goma'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Látex'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Latón'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Mate'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Metálico'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado y engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado y rugoso'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Pluma'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plástico'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plástico engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Poliéster'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Poliéster texturizado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Rugoso'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Rígido'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Seminatural'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Silicona'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Suave'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela con brillo'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela con texturas'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela dura'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela engomada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela escarchada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela flocada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela flocada engomada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela foam'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela micro peach'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela plastificada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela plástico engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela poliéster'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela PVC'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela ratan'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rigida'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rugosa'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rústica'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela sintética'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y cristal'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y foam'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y goma'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y látex'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y madera'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y plástico'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y seco'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemTextureTag' + WHERE name= 'Textura'; + +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemTextureTag TO logisticAssist; diff --git a/db/versions/11338-brownMonstera/00-firstScript.sql b/db/versions/11338-brownMonstera/00-firstScript.sql new file mode 100644 index 000000000..9752bb90d --- /dev/null +++ b/db/versions/11338-brownMonstera/00-firstScript.sql @@ -0,0 +1,2 @@ +-- Place your SQL code here +RENAME TABLE vn.stockBuyed__ TO vn.stockBuyed; diff --git a/db/versions/11344-grayBamboo/00-firstScript.sql b/db/versions/11344-grayBamboo/00-firstScript.sql new file mode 100644 index 000000000..1fbd2a0d8 --- /dev/null +++ b/db/versions/11344-grayBamboo/00-firstScript.sql @@ -0,0 +1,3 @@ +UPDATE vn.sale + SET originalQuantity = quantity + WHERE originalQuantity IS NULL \ No newline at end of file diff --git a/db/versions/11344-grayBamboo/01-firstScript.sql b/db/versions/11344-grayBamboo/01-firstScript.sql new file mode 100644 index 000000000..e3e08e0aa --- /dev/null +++ b/db/versions/11344-grayBamboo/01-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.sale MODIFY COLUMN originalQuantity decimal(10,2) DEFAULT 0.00 NOT NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity'; \ No newline at end of file diff --git a/e2e/paths/01-salix/03_smartTable_searchBar_integrations.spec.js b/e2e/paths/01-salix/03_smartTable_searchBar_integrations.spec.js deleted file mode 100644 index 9c37ce9ba..000000000 --- a/e2e/paths/01-salix/03_smartTable_searchBar_integrations.spec.js +++ /dev/null @@ -1,68 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('SmartTable SearchBar integration', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('salesPerson', 'item'); - await page.waitToClick(selectors.globalItems.searchButton); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should search by type in searchBar, reload page and have same results', async() => { - await page.waitToClick(selectors.itemsIndex.openAdvancedSearchButton); - await page.autocompleteSearch(selectors.itemsIndex.advancedSearchItemType, 'Anthurium'); - await page.waitToClick(selectors.itemsIndex.advancedSearchButton); - await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 4); - - await page.reload({ - waitUntil: 'networkidle2' - }); - - await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 4); - - await page.write(selectors.itemsIndex.advancedSmartTableGrouping, '1'); - await page.keyboard.press('Enter'); - await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 2); - - await page.reload({ - waitUntil: 'networkidle2' - }); - - await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 1); - }); - - it('should filter in section without smart-table and search in searchBar go to zone section', async() => { - await page.loginAndModule('salesPerson', 'zone'); - await page.waitToClick(selectors.globalItems.searchButton); - - await page.doSearch('A'); - const firstCount = await page.countElement(selectors.zoneIndex.searchResult); - - await page.doSearch('A'); - const secondCount = await page.countElement(selectors.zoneIndex.searchResult); - - expect(firstCount).toEqual(7); - expect(secondCount).toEqual(7); - }); - - it('should order orders by first id and order by last id, reload page and have same order', async() => { - await page.loginAndModule('developer', 'item'); - await page.accessToSection('item.fixedPrice'); - await page.keyboard.press('Enter'); - - await page.waitForTextInField(selectors.itemFixedPrice.firstItemID, '1'); - - await page.waitToClick(selectors.itemFixedPrice.orderColumnId); - await page.reload({ - waitUntil: 'networkidle2' - }); - await page.waitForTextInField(selectors.itemFixedPrice.firstItemID, '3'); - }); -}); diff --git a/e2e/paths/02-client/08_add_notes.spec.js b/e2e/paths/02-client/08_add_notes.spec.js deleted file mode 100644 index d0c483a11..000000000 --- a/e2e/paths/02-client/08_add_notes.spec.js +++ /dev/null @@ -1,42 +0,0 @@ -import selectors from '../../helpers/selectors'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Client Add notes path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'client'); - await page.accessToSearchResult('Bruce Banner'); - await page.accessToSection('client.card.note.index'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should reach the notes index`, async() => { - await page.waitForState('client.card.note.index'); - }); - - it(`should click on the add note button`, async() => { - await page.waitToClick(selectors.clientNotes.addNoteFloatButton); - await page.waitForState('client.card.note.create'); - }); - - it(`should create a note`, async() => { - await page.waitForSelector(selectors.clientNotes.note); - await page.type(`${selectors.clientNotes.note} textarea`, 'Meeting with Black Widow 21st 9am'); - await page.waitToClick(selectors.clientNotes.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.clientNotes.firstNoteText, 'innerText'); - - expect(result).toEqual('Meeting with Black Widow 21st 9am'); - }); -}); diff --git a/e2e/paths/02-client/21_defaulter.spec.js b/e2e/paths/02-client/21_defaulter.spec.js index 2bb3d6254..01f394bc8 100644 --- a/e2e/paths/02-client/21_defaulter.spec.js +++ b/e2e/paths/02-client/21_defaulter.spec.js @@ -28,12 +28,12 @@ describe('Client defaulter path', () => { const salesPersonName = await page.waitToGetProperty(selectors.clientDefaulter.firstSalesPersonName, 'innerText'); - expect(clientName).toEqual('Bruce Banner'); - expect(salesPersonName).toEqual('developer'); + expect(clientName).toEqual('Ororo Munroe'); + expect(salesPersonName).toEqual('salesperson'); }); it('should first observation not changed', async() => { - const expectedObservation = 'Meeting with Black Widow 21st 9am'; + const expectedObservation = 'Madness, as you know, is like gravity, all it takes is a little push'; const result = await page.waitToGetProperty(selectors.clientDefaulter.firstObservation, 'value'); expect(result).toContain(expectedObservation); @@ -62,13 +62,4 @@ describe('Client defaulter path', () => { await page.write(selectors.clientDefaulter.observation, 'My new observation'); await page.waitToClick(selectors.clientDefaulter.saveButton); }); - - it('should first observation changed', async() => { - const message = await page.waitForSnackbar(); - await page.waitForSelector(selectors.clientDefaulter.firstObservation); - const result = await page.waitToGetProperty(selectors.clientDefaulter.firstObservation, 'value'); - - expect(message.text).toContain('Observation saved!'); - expect(result).toContain('My new observation'); - }); }); diff --git a/e2e/paths/07-order/01_summary.spec.js b/e2e/paths/07-order/01_summary.spec.js deleted file mode 100644 index 9df481ef6..000000000 --- a/e2e/paths/07-order/01_summary.spec.js +++ /dev/null @@ -1,46 +0,0 @@ -import getBrowser from '../../helpers/puppeteer'; - -const $ = { - id: 'vn-order-summary vn-one:nth-child(1) > vn-label-value:nth-child(1) span', - alias: 'vn-order-summary vn-one:nth-child(1) > vn-label-value:nth-child(2) span', - consignee: 'vn-order-summary vn-one:nth-child(2) > vn-label-value:nth-child(6) span', - subtotal: 'vn-order-summary vn-one.taxes > p:nth-child(1)', - vat: 'vn-order-summary vn-one.taxes > p:nth-child(2)', - total: 'vn-order-summary vn-one.taxes > p:nth-child(3)', - sale: 'vn-order-summary vn-tbody > vn-tr', -}; - -describe('Order summary path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'order'); - await page.accessToSearchResult('16'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should reach the order summary section and check data', async() => { - await page.waitForState('order.card.summary'); - - const id = await page.innerText($.id); - const alias = await page.innerText($.alias); - const consignee = await page.innerText($.consignee); - const subtotal = await page.innerText($.subtotal); - const vat = await page.innerText($.vat); - const total = await page.innerText($.total); - const sale = await page.countElement($.sale); - - expect(id).toEqual('16'); - expect(alias).toEqual('Many places'); - expect(consignee).toEqual('address 26 - Gotham (Province one)'); - expect(subtotal.length).toBeGreaterThan(1); - expect(vat.length).toBeGreaterThan(1); - expect(total.length).toBeGreaterThan(1); - expect(sale).toBeGreaterThan(0); - }); -}); diff --git a/e2e/paths/07-order/02_basic_data.spec.js b/e2e/paths/07-order/02_basic_data.spec.js deleted file mode 100644 index b2c21b071..000000000 --- a/e2e/paths/07-order/02_basic_data.spec.js +++ /dev/null @@ -1,69 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -const $ = { - form: 'vn-order-basic-data form', - observation: 'vn-order-basic-data form [vn-name="note"]', - saveButton: `vn-order-basic-data form button[type=submit]`, - acceptButton: '.vn-confirm.shown button[response="accept"]' -}; - -describe('Order edit basic data path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - - await page.loginAndModule('employee', 'order'); - await page.accessToSearchResult('1'); - await page.accessToSection('order.card.basicData'); - }); - - afterAll(async() => { - await browser.close(); - }); - - describe('when confirmed order', () => { - it('should not be able to change the client', async() => { - const message = await page.sendForm($.form, { - client: 'Tony Stark', - address: 'Tony Stark', - }); - - expect(message.text).toContain(`You can't make changes on the basic data`); - }); - }); - - describe('when new order', () => { - it('should create an order and edit its basic data', async() => { - await page.waitToClick(selectors.globalItems.returnToModuleIndexButton); - await page.waitToClick($.acceptButton); - await page.waitForContentLoaded(); - await page.waitToClick(selectors.ordersIndex.createOrderButton); - await page.waitForState('order.create'); - - await page.autocompleteSearch(selectors.createOrderView.client, 'Jessica Jones'); - await page.pickDate(selectors.createOrderView.landedDatePicker); - await page.autocompleteSearch(selectors.createOrderView.agency, 'Other agency'); - await page.waitToClick(selectors.createOrderView.createButton); - await page.waitForState('order.card.catalog'); - - await page.accessToSection('order.card.basicData'); - - const values = { - client: 'Tony Stark', - address: 'Tony Stark', - agencyMode: 'Other agency' - }; - - const message = await page.sendForm($.form, values); - await page.reloadSection('order.card.basicData'); - const formValues = await page.fetchForm($.form, Object.keys(values)); - - expect(message.isSuccess).toBeTrue(); - expect(formValues).toEqual(values); - }); - }); -}); diff --git a/e2e/paths/07-order/03_lines.spec.js b/e2e/paths/07-order/03_lines.spec.js deleted file mode 100644 index 718ea5ce5..000000000 --- a/e2e/paths/07-order/03_lines.spec.js +++ /dev/null @@ -1,48 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Order lines', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'order'); - await page.accessToSearchResult('8'); - await page.accessToSection('order.card.line'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should check the order subtotal', async() => { - const result = await page - .waitToGetProperty(selectors.orderLine.orderSubtotal, 'innerText'); - - expect(result).toContain('112.30'); - }); - - it('should delete the first line in the order', async() => { - await page.waitToClick(selectors.orderLine.firstLineDeleteButton); - await page.waitToClick(selectors.orderLine.confirmButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the order subtotal has changed', async() => { - await page.waitForTextInElement(selectors.orderLine.orderSubtotal, '92.80'); - const result = await page - .waitToGetProperty(selectors.orderLine.orderSubtotal, 'innerText'); - - expect(result).toContain('92.80'); - }); - - it('should confirm the whole order and redirect to ticket index filtered by clientFk', async() => { - await page.waitToClick(selectors.orderLine.confirmOrder); - - await page.expectURL('ticket/index'); - await page.expectURL('clientFk'); - }); -}); diff --git a/e2e/paths/07-order/04_catalog.spec.js b/e2e/paths/07-order/04_catalog.spec.js deleted file mode 100644 index b8a20e938..000000000 --- a/e2e/paths/07-order/04_catalog.spec.js +++ /dev/null @@ -1,97 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Order catalog', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'order'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should open the create new order form', async() => { - await page.waitToClick(selectors.ordersIndex.createOrderButton); - await page.waitForState('order.create'); - }); - - it('should create a new order', async() => { - await page.autocompleteSearch(selectors.createOrderView.client, 'Tony Stark'); - await page.pickDate(selectors.createOrderView.landedDatePicker); - await page.autocompleteSearch(selectors.createOrderView.agency, 'Other agency'); - await page.waitToClick(selectors.createOrderView.createButton); - await page.waitForState('order.card.catalog'); - }); - - it('should add the realm and type filters and obtain results', async() => { - await page.waitToClick(selectors.orderCatalog.plantRealmButton); - await page.autocompleteSearch(selectors.orderCatalog.type, 'Anthurium'); - await page.waitForNumberOfElements('section.product', 4); - const result = await page.countElement('section.product'); - - expect(result).toEqual(4); - }); - - it('should perfom an "OR" search for the item tag colors silver and brown', async() => { - await page.waitToClick(selectors.orderCatalog.openTagSearch); - await page.autocompleteSearch(selectors.orderCatalog.tag, 'Color'); - await page.autocompleteSearch(selectors.orderCatalog.firstTagAutocomplete, 'silver'); - await page.waitToClick(selectors.orderCatalog.addTagButton); - await page.autocompleteSearch(selectors.orderCatalog.secondTagAutocomplete, 'brown'); - await page.waitToClick(selectors.orderCatalog.searchTagButton); - await page.waitForNumberOfElements('section.product', 4); - }); - - it('should perfom an "OR" search for the item tag tallos 2 and 9', async() => { - await page.waitToClick(selectors.orderCatalog.openTagSearch); - await page.autocompleteSearch(selectors.orderCatalog.tag, 'Tallos'); - await page.write(selectors.orderCatalog.firstTagValue, '2'); - await page.waitToClick(selectors.orderCatalog.addTagButton); - await page.write(selectors.orderCatalog.secondTagValue, '9'); - await page.waitToClick(selectors.orderCatalog.searchTagButton); - await page.waitForNumberOfElements('section.product', 2); - }); - - it('should perform a general search for category', async() => { - await page.write(selectors.orderCatalog.itemTagValue, 'concussion'); - await page.keyboard.press('Enter'); - await page.waitForNumberOfElements('section.product', 2); - }); - - it('should perfom an "AND" search for the item tag tallos 2', async() => { - await page.waitToClick(selectors.orderCatalog.openTagSearch); - await page.autocompleteSearch(selectors.orderCatalog.tag, 'Tallos'); - await page.write(selectors.orderCatalog.firstTagValue, '2'); - await page.waitToClick(selectors.orderCatalog.searchTagButton); - await page.waitForNumberOfElements('section.product', 1); - }); - - it('should remove the tag filters and have 4 results', async() => { - await page.waitForContentLoaded(); - await page.waitToClick(selectors.orderCatalog.sixthFilterRemoveButton); - await page.waitForContentLoaded(); - await page.waitToClick(selectors.orderCatalog.fifthFilterRemoveButton); - await page.waitForContentLoaded(); - await page.waitToClick(selectors.orderCatalog.fourthFilterRemoveButton); - await page.waitForContentLoaded(); - await page.waitToClick(selectors.orderCatalog.thirdFilterRemoveButton); - - await page.waitForNumberOfElements('.product', 4); - const result = await page.countElement('section.product'); - - expect(result).toEqual(4); - }); - - it('should search for an item by id', async() => { - await page.accessToSearchResult('2'); - await page.waitForNumberOfElements('section.product', 1); - const result = await page.countElement('section.product'); - - expect(result).toEqual(1); - }); -}); diff --git a/e2e/paths/07-order/05_index.spec.js b/e2e/paths/07-order/05_index.spec.js deleted file mode 100644 index 23769766c..000000000 --- a/e2e/paths/07-order/05_index.spec.js +++ /dev/null @@ -1,34 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Order Index', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'order'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should check the second search result doesn't contain a total of 0€`, async() => { - await page.waitToClick(selectors.globalItems.searchButton); - const result = await page.waitToGetProperty(selectors.ordersIndex.secondSearchResultTotal, 'innerText'); - - expect(result).not.toContain('0.00'); - }); - - it('should search including empty orders', async() => { - await page.waitToClick(selectors.ordersIndex.openAdvancedSearch); - await page.waitToClick(selectors.ordersIndex.advancedSearchShowEmptyCheckbox); - await page.waitToClick(selectors.ordersIndex.advancedSearchButton); - await page.waitForTextInElement(selectors.ordersIndex.secondSearchResultTotal, '0.00'); - const result = await page.waitToGetProperty(selectors.ordersIndex.secondSearchResultTotal, 'innerText'); - - expect(result).toContain('0.00'); - }); -}); diff --git a/e2e/paths/10-travel/01_create.spec.js b/e2e/paths/10-travel/01_create.spec.js deleted file mode 100644 index 98ade4852..000000000 --- a/e2e/paths/10-travel/01_create.spec.js +++ /dev/null @@ -1,42 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Travel create path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'travel'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should create a new travel and check it was created with the correct data', async() => { - const date = Date.vnNew(); - date.setDate(15); - date.setUTCHours(0, 0, 0, 0); - - await page.waitToClick(selectors.travelIndex.newTravelButton); - await page.waitForState('travel.create'); - - const values = { - reference: 'Testing reference', - agencyMode: 'inhouse pickup', - shipped: date, - landed: date, - warehouseOut: 'Warehouse One', - warehouseIn: 'Warehouse Five' - }; - - const message = await page.sendForm('vn-travel-create form', values); - await page.waitForState('travel.card.basicData'); - const formValues = await page.fetchForm('vn-travel-basic-data form', Object.keys(values)); - - expect(message.isSuccess).toBeTrue(); - expect(formValues).toEqual(values); - }); -}); diff --git a/e2e/paths/10-travel/02_basic_data_and_log.spec.js b/e2e/paths/10-travel/02_basic_data_and_log.spec.js deleted file mode 100644 index 701e6b1b4..000000000 --- a/e2e/paths/10-travel/02_basic_data_and_log.spec.js +++ /dev/null @@ -1,97 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Travel basic data path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'travel'); - await page.write(selectors.travelIndex.generalSearchFilter, '3'); - await page.keyboard.press('Enter'); - await page.accessToSection('travel.card.basicData'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should reach the thermograph section', async() => { - await page.waitForState('travel.card.basicData'); - }); - - it('should set a wrong delivery date then receive an error on submit', async() => { - await page.loginAndModule('buyer', 'travel'); - await page.write(selectors.travelIndex.generalSearchFilter, '4'); - await page.keyboard.press('Enter'); - await page.accessToSection('travel.card.basicData'); - await page.waitForState('travel.card.basicData'); - - const lastMonth = Date.vnNew(); - lastMonth.setMonth(lastMonth.getMonth() - 2); - - await page.pickDate(selectors.travelBasicData.deliveryDate, lastMonth); - await page.waitToClick(selectors.travelBasicData.save); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Landing cannot be lesser than shipment'); - }); - - it('should undo the changes', async() => { - await page.clearInput(selectors.travelBasicData.reference); - await page.write(selectors.travelBasicData.reference, 'totally pointless ref'); - await page.waitToClick(selectors.travelBasicData.undoChanges); - const result = await page.waitToGetProperty(selectors.travelBasicData.reference, 'value'); - - expect(result).toEqual('fourth travel'); - }); - - it('should now edit the whole form then save', async() => { - await page.clearInput(selectors.travelBasicData.reference); - await page.write(selectors.travelBasicData.reference, 'new reference!'); - await page.autocompleteSearch(selectors.travelBasicData.agency, 'Entanglement'); - await page.autocompleteSearch(selectors.travelBasicData.outputWarehouse, 'Warehouse Three'); - await page.autocompleteSearch(selectors.travelBasicData.inputWarehouse, 'Warehouse Four'); - await page.waitToClick(selectors.travelBasicData.delivered); - await page.waitToClick(selectors.travelBasicData.received); - await page.waitToClick(selectors.travelBasicData.save); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should reload the section and check the reference was saved', async() => { - await page.reloadSection('travel.card.basicData'); - const result = await page.waitToGetProperty(selectors.travelBasicData.reference, 'value'); - - expect(result).toEqual('new reference!'); - }); - - it('should check the agency was saved', async() => { - const result = await page.waitToGetProperty(selectors.travelBasicData.agency, 'value'); - - expect(result).toEqual('Entanglement'); - }); - - it('should check the output warehouse date was saved', async() => { - const result = await page.waitToGetProperty(selectors.travelBasicData.outputWarehouse, 'value'); - - expect(result).toEqual('Warehouse Three'); - }); - - it('should check the input warehouse date was saved', async() => { - const result = await page.waitToGetProperty(selectors.travelBasicData.inputWarehouse, 'value'); - - expect(result).toEqual('Warehouse Four'); - }); - - it(`should check the delivered checkbox was saved even tho it doesn't make sense`, async() => { - await page.waitForClassPresent(selectors.travelBasicData.delivered, 'checked'); - }); - - it(`should check the received checkbox was saved even tho it doesn't make sense`, async() => { - await page.waitForClassPresent(selectors.travelBasicData.received, 'checked'); - }); -}); diff --git a/e2e/paths/10-travel/03_descriptor.spec.js b/e2e/paths/10-travel/03_descriptor.spec.js deleted file mode 100644 index f066a74ca..000000000 --- a/e2e/paths/10-travel/03_descriptor.spec.js +++ /dev/null @@ -1,36 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Travel descriptor path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'travel'); - await page.write(selectors.travelIndex.generalSearchFilter, '3'); - await page.keyboard.press('Enter'); - await page.waitForState('travel.card.summary'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should click the descriptor button to navigate to the travel index showing all travels with current agency', async() => { - await page.waitToClick(selectors.travelDescriptor.filterByAgencyButton); - await page.waitForState('travel.index'); - const result = await page.countElement(selectors.travelIndex.anySearchResult); - - expect(result).toBeGreaterThanOrEqual(1); - }); - - it('should navigate to the first search result', async() => { - await page.waitToClick(selectors.travelIndex.firstSearchResult); - await page.waitForState('travel.card.summary'); - const state = await page.getState(); - - expect(state).toBe('travel.card.summary'); - }); -}); diff --git a/e2e/paths/10-travel/04_extra_community.spec.js b/e2e/paths/10-travel/04_extra_community.spec.js deleted file mode 100644 index c5975c958..000000000 --- a/e2e/paths/10-travel/04_extra_community.spec.js +++ /dev/null @@ -1,42 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Travel extra community path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'travel'); - await page.accessToSection('travel.extraCommunity'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should edit the travel reference and the locked kilograms', async() => { - await page.waitToClick(selectors.travelExtraCommunity.removeContinentFilter); - await page.waitForSpinnerLoad(); - await page.writeOnEditableTD(selectors.travelExtraCommunity.firstTravelReference, 'edited reference'); - await page.waitForSpinnerLoad(); - await page.writeOnEditableTD(selectors.travelExtraCommunity.firstTravelLockedKg, '1500'); - - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should reload the index and confirm the reference and locked kg were edited', async() => { - await page.accessToSection('travel.index'); - await page.accessToSection('travel.extraCommunity'); - await page.waitToClick(selectors.travelExtraCommunity.removeContinentFilter); - await page.waitForTextInElement(selectors.travelExtraCommunity.firstTravelReference, 'edited reference'); - const reference = await page.getProperty(selectors.travelExtraCommunity.firstTravelReference, 'innerText'); - const lockedKg = await page.getProperty(selectors.travelExtraCommunity.firstTravelLockedKg, 'innerText'); - - expect(reference).toContain('edited reference'); - expect(lockedKg).toContain(1500); - }); -}); diff --git a/e2e/paths/10-travel/05_thermograph.spec.js b/e2e/paths/10-travel/05_thermograph.spec.js deleted file mode 100644 index c9709f2f5..000000000 --- a/e2e/paths/10-travel/05_thermograph.spec.js +++ /dev/null @@ -1,64 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Travel thermograph path', () => { - const thermographName = '7H3-37H3RN4L-FL4M3'; - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'travel'); - await page.write(selectors.travelIndex.generalSearchFilter, '3'); - await page.keyboard.press('Enter'); - await page.accessToSection('travel.card.thermograph.index'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should reach the thermograph section', async() => { - await page.waitForState('travel.card.thermograph.index'); - }); - - it('should click the add thermograph floating button', async() => { - await page.waitToClick(selectors.travelThermograph.add); - await page.waitForState('travel.card.thermograph.create'); - }); - - it('should click on the add thermograph icon of the thermograph autocomplete', async() => { - await page.waitToClick(selectors.travelThermograph.addThermographIcon); - await page.write(selectors.travelThermograph.newThermographId, thermographName); - await page.autocompleteSearch(selectors.travelThermograph.newThermographModel, 'TEMPMATE'); - await page.autocompleteSearch(selectors.travelThermograph.newThermographWarehouse, 'Warehouse Two'); - await page.autocompleteSearch(selectors.travelThermograph.newThermographTemperature, 'Warm'); - await page.waitToClick(selectors.travelThermograph.createThermographButton); - }); - - it('should select the file to upload', async() => { - let currentDir = process.cwd(); - let filePath = `${currentDir}/e2e/assets/thermograph.jpeg`; - - const [fileChooser] = await Promise.all([ - page.waitForFileChooser(), - page.waitToClick(selectors.travelThermograph.uploadIcon) - ]); - await fileChooser.accept([filePath]); - - await page.waitToClick(selectors.travelThermograph.upload); - - const message = await page.waitForSnackbar(); - const state = await page.getState(); - - expect(message.text).toContain('Data saved!'); - expect(state).toBe('travel.card.thermograph.index'); - }); - - it('should check everything was saved correctly', async() => { - const result = await page.waitToGetProperty(selectors.travelThermograph.createdThermograph, 'innerText'); - - expect(result).toContain(thermographName); - }); -}); diff --git a/e2e/paths/10-travel/06_search_panel.spec.js b/e2e/paths/10-travel/06_search_panel.spec.js deleted file mode 100644 index 420ceaf48..000000000 --- a/e2e/paths/10-travel/06_search_panel.spec.js +++ /dev/null @@ -1,62 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Travel search panel path', () => { - let browser; - let page; - let httpRequest; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'travel'); - page.on('request', req => { - if (req.url().includes(`Travels/filter`)) - httpRequest = req.url(); - }); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should filter using all the fields', async() => { - await page.click(selectors.travelIndex.chip); - await page.write(selectors.travelIndex.generalSearchFilter, 'travel'); - await page.keyboard.press('Enter'); - - expect(httpRequest).toContain('search=travel'); - - await page.click(selectors.travelIndex.chip); - await page.autocompleteSearch(selectors.travelIndex.agencyFilter, 'Entanglement'); - - expect(httpRequest).toContain('agencyModeFk'); - - await page.click(selectors.travelIndex.chip); - await page.autocompleteSearch(selectors.travelIndex.warehouseOutFilter, 'Warehouse One'); - - expect(httpRequest).toContain('warehouseOutFk'); - - await page.click(selectors.travelIndex.chip); - await page.autocompleteSearch(selectors.travelIndex.warehouseInFilter, 'Warehouse Two'); - - expect(httpRequest).toContain('warehouseInFk'); - - await page.click(selectors.travelIndex.chip); - await page.overwrite(selectors.travelIndex.scopeDaysFilter, '15'); - await page.keyboard.press('Enter'); - - expect(httpRequest).toContain('scopeDays=15'); - - await page.click(selectors.travelIndex.chip); - await page.autocompleteSearch(selectors.travelIndex.continentFilter, 'Asia'); - - expect(httpRequest).toContain('continent'); - - await page.click(selectors.travelIndex.chip); - await page.write(selectors.travelIndex.totalEntriesFilter, '1'); - await page.keyboard.press('Enter'); - - expect(httpRequest).toContain('totalEntries=1'); - }); -}); diff --git a/e2e/paths/11-zone/01_basic-data.spec.js b/e2e/paths/11-zone/01_basic-data.spec.js deleted file mode 100644 index 34d08c57f..000000000 --- a/e2e/paths/11-zone/01_basic-data.spec.js +++ /dev/null @@ -1,104 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Zone basic data path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - - await page.loginAndModule('deliveryAssistant', - 'zone'); // turns up the zone module name and route aint the same lol - await page.accessToSearchResult('10'); - await page.accessToSection('zone.card.basicData'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should reach the basic data section', async() => { - await page.waitForState('zone.card.basicData'); - }); - - it('should edit de form and then save', async() => { - await page.clearInput(selectors.zoneBasicData.name); - await page.write(selectors.zoneBasicData.name, 'Brimstone teleportation'); - await page.autocompleteSearch(selectors.zoneBasicData.agency, 'Quantum break device'); - await page.clearInput(selectors.zoneBasicData.maxVolume); - await page.write(selectors.zoneBasicData.maxVolume, '10'); - await page.clearInput(selectors.zoneBasicData.travelingDays); - await page.write(selectors.zoneBasicData.travelingDays, '1'); - await page.clearInput(selectors.zoneBasicData.closing); - await page.pickTime(selectors.zoneBasicData.closing, '21:00'); - await page.clearInput(selectors.zoneBasicData.price); - await page.write(selectors.zoneBasicData.price, '999'); - await page.clearInput(selectors.zoneBasicData.bonus); - await page.write(selectors.zoneBasicData.bonus, '100'); - await page.clearInput(selectors.zoneBasicData.inflation); - await page.write(selectors.zoneBasicData.inflation, '200'); - await page.waitToClick(selectors.zoneBasicData.volumetric); - await page.waitToClick(selectors.zoneBasicData.saveButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should now reload the section', async() => { - await page.reloadSection('zone.card.basicData'); - }); - - it('should confirm the name was updated', async() => { - const result = await page.waitToGetProperty(selectors.zoneBasicData.name, 'value'); - - expect(result).toEqual('Brimstone teleportation'); - }); - - it('should confirm the agency was updated', async() => { - const result = await page.waitToGetProperty(selectors.zoneBasicData.agency, 'value'); - - expect(result).toEqual('Quantum break device'); - }); - - it('should confirm the max volume was updated', async() => { - const result = await page.waitToGetProperty(selectors.zoneBasicData.maxVolume, 'value'); - - expect(result).toEqual('10'); - }); - - it('should confirm the traveling days were updated', async() => { - const result = await page.waitToGetProperty(selectors.zoneBasicData.travelingDays, 'value'); - - expect(result).toEqual('1'); - }); - - it('should confirm the closing hour was updated', async() => { - const result = await page.waitToGetProperty(selectors.zoneBasicData.closing, 'value'); - - expect(result).toEqual('21:00'); - }); - - it('should confirm the price was updated', async() => { - const result = await page.waitToGetProperty(selectors.zoneBasicData.price, 'value'); - - expect(result).toEqual('999'); - }); - - it('should confirm the bonus was updated', async() => { - const result = await page.waitToGetProperty(selectors.zoneBasicData.bonus, 'value'); - - expect(result).toEqual('100'); - }); - - it('should confirm the inflation was updated', async() => { - const result = await page.waitToGetProperty(selectors.zoneBasicData.inflation, 'value'); - - expect(result).toEqual('200'); - }); - - it('should confirm the volumetric checkbox was checked', async() => { - await page.waitForClassPresent(selectors.zoneBasicData.volumetric, 'checked'); - }); -}); diff --git a/e2e/paths/11-zone/02_descriptor.spec.js b/e2e/paths/11-zone/02_descriptor.spec.js deleted file mode 100644 index baccc910f..000000000 --- a/e2e/paths/11-zone/02_descriptor.spec.js +++ /dev/null @@ -1,32 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Zone descriptor path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('deliveryAssistant', 'zone'); - await page.accessToSearchResult('13'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should eliminate the zone using the descriptor option', async() => { - await page.waitToClick(selectors.zoneDescriptor.menu); - await page.waitToClick(selectors.zoneDescriptor.deleteZone); - await page.respondToDialog('accept'); - await page.waitForState('zone.index'); - }); - - it('should search for the deleted zone to find no results', async() => { - await page.doSearch('13'); - const count = await page.countElement(selectors.zoneIndex.searchResult); - - expect(count).toEqual(0); - }); -}); diff --git a/front/core/services/app.js b/front/core/services/app.js index dba6e70bf..816167835 100644 --- a/front/core/services/app.js +++ b/front/core/services/app.js @@ -70,10 +70,18 @@ export default class App { if (this.logger.$params.q) { let tableValue = this.logger.$params.q; - const q = JSON.parse(tableValue); - if (typeof q === 'number') - tableValue = JSON.stringify({id: tableValue}); - newRoute = newRoute.concat(`?table=${tableValue}`); + if (Array.isArray(tableValue)) { + const [key, param1, param2] = tableValue; + const payload = key === 'createForm' + ? {[param1]: param2} + : {[key]: param1}; + newRoute += `?${key}=${JSON.stringify(payload)}`; + } else { + const q = JSON.parse(tableValue); + if (typeof q === 'number') + tableValue = JSON.stringify({id: tableValue}); + newRoute = newRoute.concat(`?table=${tableValue}`); + } } else if (!hasId && this.logger.$params.id && newRoute.indexOf(this.logger.$params.id) < 0) newRoute = newRoute.concat(`${this.logger.$params.id}`); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index ea84cb6eb..a7e21960b 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -240,5 +240,6 @@ "There is already a tray with the same height": "There is already a tray with the same height", "The height must be greater than 50cm": "The height must be greater than 50cm", "The maximum height of the wagon is 200cm": "The maximum height of the wagon is 200cm", - "The quantity claimed cannot be greater than the quantity of the line": "The quantity claimed cannot be greater than the quantity of the line" + "The quantity claimed cannot be greater than the quantity of the line": "The quantity claimed cannot be greater than the quantity of the line", + "There are tickets for this area, delete them first": "There are tickets for this area, delete them first" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 4345517fe..a97da3194 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -350,6 +350,7 @@ "Cmr file does not exist": "El archivo del cmr no existe", "You are not allowed to modify the alias": "No estás autorizado a modificar el alias", "The address of the customer must have information about Incoterms and Customs Agent": "El consignatario del cliente debe tener informado Incoterms y Agente de aduanas", + "No invoice series found for these parameters": "No se encontró una serie para estos parámetros", "The line could not be marked": "La linea no puede ser marcada", "Through this procedure, it is not possible to modify the password of users with verified email": "Mediante este procedimiento, no es posible modificar la contraseña de usuarios con correo verificado", "They're not your subordinate": "No es tu subordinado/a.", @@ -378,5 +379,10 @@ "There is already a tray with the same height": "Ya existe una bandeja con la misma altura", "The height must be greater than 50cm": "La altura debe ser superior a 50cm", "The maximum height of the wagon is 200cm": "La altura máxima es 200cm", - "The quantity claimed cannot be greater than the quantity of the line": "La cantidad reclamada no puede ser mayor que la cantidad de la línea" + "The entry does not have stickers": "La entrada no tiene etiquetas", + "This buyer has already made a reservation for this date": "Este comprador ya ha hecho una reserva para esta fecha", + "No valid travel thermograph found": "No se encontró un termógrafo válido", + "The quantity claimed cannot be greater than the quantity of the line": "La cantidad reclamada no puede ser mayor que la cantidad de la línea", + "type cannot be blank": "Se debe rellenar el tipo", + "There are tickets for this area, delete them first": "Hay tickets para esta sección, borralos primero" } diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json index a6648b186..23bd5cc04 100644 --- a/loopback/locale/fr.json +++ b/loopback/locale/fr.json @@ -350,6 +350,7 @@ "Cmr file does not exist": "Le fichier cmr n'existe pas", "You are not allowed to modify the alias": "Vous n'êtes pas autorisé à modifier l'alias", "The address of the customer must have information about Incoterms and Customs Agent": "L'adresse du client doit contenir des informations sur les Incoterms et l'agent des douanes", + "No invoice series found for these parameters": "Aucune série de facture trouvée pour ces paramètres", "The line could not be marked": "La ligne ne peut pas être marquée", "This password can only be changed by the user themselves": "Ce mot de passe ne peut être modifié que par l'utilisateur lui-même", "They're not your subordinate": "Ce n'est pas votre subordonné.", diff --git a/loopback/locale/pt.json b/loopback/locale/pt.json index a43f0e780..f85afd607 100644 --- a/loopback/locale/pt.json +++ b/loopback/locale/pt.json @@ -350,6 +350,7 @@ "Cmr file does not exist": "O arquivo CMR não existe", "You are not allowed to modify the alias": "Você não tem permissão para modificar o alias", "The address of the customer must have information about Incoterms and Customs Agent": "O endereço do cliente deve ter informações sobre Incoterms e Agente Aduaneiro", + "No invoice series found for these parameters": "Nenhuma série de fatura encontrada para esses parâmetros", "The line could not be marked": "A linha não pôde ser marcada", "This password can only be changed by the user themselves": "Esta senha só pode ser alterada pelo próprio usuário", "They're not your subordinate": "Eles não são seus subordinados.", diff --git a/modules/account/back/models/sip.json b/modules/account/back/models/sip.json index f2e2221b5..dbcef3b9e 100644 --- a/modules/account/back/models/sip.json +++ b/modules/account/back/models/sip.json @@ -25,7 +25,12 @@ "type": "belongsTo", "model": "VnUser", "foreignKey": "user_id" + }, + "queueMember": { + "type": "belongsTo", + "model": "QueueMember", + "foreignKey": "extension", + "primaryKey": "extension" } } -} - \ No newline at end of file +} \ No newline at end of file diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index 326192385..563b5b53d 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -85,16 +85,11 @@ module.exports = Self => { const updatedClaim = await claim.updateAttributes(args, myOptions); const salesPerson = claim.client().salesPersonUser(); - if (salesPerson) { - if (changedPickup && updatedClaim.pickup) - await notifyPickUp(ctx, salesPerson.id, claim); - - if (args.claimStateFk) { - const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); - await notifyStateChange(ctx, salesPerson.id, claim, newState.description); - if (newState.code == 'canceled') - await notifyStateChange(ctx, claim.workerFk, claim, newState.description); - } + if (salesPerson && args.claimStateFk) { + const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); + await notifyStateChange(ctx, salesPerson.id, claim, newState.description); + if (newState.code == 'canceled') + await notifyStateChange(ctx, claim.workerFk, claim, newState.description); } if (tx) await tx.commit(); @@ -119,18 +114,4 @@ module.exports = Self => { }); await models.Chat.sendCheckingPresence(ctx, workerId, message); } - - async function notifyPickUp(ctx, workerId, claim) { - const models = Self.app.models; - const url = await models.Url.getUrl(); - const $t = ctx.req.__; // $translate - - const message = $t('Claim will be picked', { - claimId: claim.id, - clientName: claim.client().name, - claimUrl: `${url}claim/${claim.id}/summary`, - claimPickup: $t(claim.pickup) - }); - await models.Chat.sendCheckingPresence(ctx, workerId, message); - } }; diff --git a/modules/client/back/methods/client/createWithUser.js b/modules/client/back/methods/client/createWithUser.js index 06b885ab8..c8cd282e1 100644 --- a/modules/client/back/methods/client/createWithUser.js +++ b/modules/client/back/methods/client/createWithUser.js @@ -43,6 +43,23 @@ module.exports = function(Self) { }; try { + const province = await models.Province.findOne({ + where: {id: data.provinceFk}, + fields: ['autonomyFk'] + }); + + const autonomy = province ? await models.Autonomy.findOne({ + where: {id: province.autonomyFk}, + fields: ['hasDailyInvoice'] + }) : null; + + const country = await models.Country.findOne({ + where: {id: data.countryFk}, + fields: ['hasDailyInvoice'] + }); + + const hasDailyInvoice = (autonomy?.hasDailyInvoice ?? country?.hasDailyInvoice) || false; + const account = await models.VnUser.create(user, myOptions); const client = await Self.create({ id: account.id, @@ -57,7 +74,8 @@ module.exports = function(Self) { provinceFk: data.provinceFk, countryFk: data.countryFk, isEqualizated: data.isEqualizated, - businessTypeFk: data.businessTypeFk + businessTypeFk: data.businessTypeFk, + hasDailyInvoice: hasDailyInvoice }, myOptions); const address = await models.Address.create({ diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index f805c4be9..7df973f19 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -1,4 +1,3 @@ - const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 5b1ff5da9..8cff96ac5 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -1,67 +1,78 @@ const models = require('vn-loopback/server/server').models; + describe('Client Create', () => { - const newAccount = { - userName: 'deadpool', - email: 'deadpool@marvel.com', - fi: '16195279J', - name: 'Wade', - socialName: 'DEADPOOL MARVEL', - street: 'WALL STREET', - city: 'New York', - businessTypeFk: 'florist', - provinceFk: 1 - }; - const newAccountWithoutEmail = JSON.parse(JSON.stringify(newAccount)); - delete newAccountWithoutEmail.email; + let options; + let tx; beforeAll.mockLoopBackContext(); - it(`should not find deadpool as he's not created yet`, async() => { - const tx = await models.Client.beginTransaction({}); + beforeEach(async() => { + tx = await models.Client.beginTransaction({}); + options = {transaction: tx}; + }); + afterEach(async() => await tx.rollback()); + + it('should not find deadpool as he is not created yet', async() => { try { - const options = {transaction: tx}; + const account = await models.VnUser.findOne({where: {name: 'deadpool'}}, options); + const client = await models.Client.findOne({where: {name: 'Wade'}}, options); - const account = await models.VnUser.findOne({where: {name: newAccount.userName}}, options); - const client = await models.Client.findOne({where: {name: newAccount.name}}, options); - - expect(account).toEqual(null); - expect(client).toEqual(null); - - await tx.rollback(); + expect(account).toBeNull(); + expect(client).toBeNull(); } catch (e) { await tx.rollback(); throw e; } }); - it('should not create a new account', async() => { - const tx = await models.Client.beginTransaction({}); - + it('should throw an error when creating a new account without email', async() => { let error; + const newAccountWithoutEmail = { + userName: 'deadpool', + fi: '16195279J', + name: 'Wade', + socialName: 'DEADPOOL MARVEL', + street: 'WALL STREET', + city: 'New York', + businessTypeFk: 'florist', + provinceFk: 1 + }; + try { - const options = {transaction: tx}; await models.Client.createWithUser(newAccountWithoutEmail, options); - - await tx.rollback(); } catch (e) { - error = e.message; - - await tx.rollback(); + error = e; } - expect(error).toEqual(`An email is necessary`); + expect(error.message).toEqual('An email is necessary'); }); - it('should create a new account', async() => { - const tx = await models.Client.beginTransaction({}); + it('should create a new account with dailyInvoice', async() => { + const newAccount = { + userName: 'deadpool', + email: 'deadpool@marvel.com', + fi: '16195279J', + name: 'Wade', + socialName: 'DEADPOOL MARVEL', + street: 'WALL STREET', + city: 'New York', + businessTypeFk: 'florist', + provinceFk: 1 + }; try { - const options = {transaction: tx}; + const province = await models.Province.findById(newAccount.provinceFk, { + fields: ['id', 'name', 'autonomyFk'], + include: { + relation: 'autonomy' + } + }, options); const client = await models.Client.createWithUser(newAccount, options); const account = await models.VnUser.findOne({where: {name: newAccount.userName}}, options); + expect(province.autonomy().hasDailyInvoice).toBeTruthy(); expect(account.name).toEqual(newAccount.userName); expect(client.id).toEqual(account.id); expect(client.name).toEqual(newAccount.name); @@ -69,8 +80,38 @@ describe('Client Create', () => { expect(client.fi).toEqual(newAccount.fi); expect(client.socialName).toEqual(newAccount.socialName); expect(client.businessTypeFk).toEqual(newAccount.businessTypeFk); - + expect(client.hasDailyInvoice).toBeTruthy(); + } catch (e) { await tx.rollback(); + throw e; + } + }); + + it('should create a new account without dailyInvoice', async() => { + const newAccount = { + userName: 'deadpool', + email: 'deadpool@marvel.com', + fi: '16195279J', + name: 'Wade', + socialName: 'DEADPOOL MARVEL', + street: 'WALL STREET', + city: 'New York', + businessTypeFk: 'florist', + provinceFk: 3 + }; + + try { + const province = await models.Province.findById(newAccount.provinceFk, { + fields: ['id', 'name', 'autonomyFk'], + include: { + relation: 'autonomy' + } + }, options); + + const client = await models.Client.createWithUser(newAccount, options); + + expect(province.autonomy.hasDailyInvoice).toBeFalsy(); + expect(client.hasDailyInvoice).toBeFalsy(); } catch (e) { await tx.rollback(); throw e; @@ -78,26 +119,25 @@ describe('Client Create', () => { }); it('should not be able to create a user if exists', async() => { - const tx = await models.Client.beginTransaction({}); - let error; - + const newAccount = { + userName: 'deadpool', + email: 'deadpool@marvel.com', + fi: '16195279J', + name: 'Wade', + socialName: 'DEADPOOL MARVEL', + street: 'WALL STREET', + city: 'New York', + businessTypeFk: 'florist', + provinceFk: 1 + }; try { - const options = {transaction: tx}; - await models.Client.createWithUser(newAccount, options); - const client = await models.Client.createWithUser(newAccount, options); - - expect(client).toBeNull(); - - await tx.rollback(); + await models.Client.createWithUser(newAccount, options); } catch (e) { - await tx.rollback(); error = e; } - const errorName = error.details.codes.name[0]; - - expect(errorName).toEqual('uniqueness'); + expect(error.message).toContain('already exists'); }); }); diff --git a/modules/client/back/methods/defaulter/filter.js b/modules/client/back/methods/defaulter/filter.js index 9f19dee0a..5359ce4a7 100644 --- a/modules/client/back/methods/defaulter/filter.js +++ b/modules/client/back/methods/defaulter/filter.js @@ -74,7 +74,8 @@ module.exports = Self => { pm.name payMethod, r.finished IS NULL hasRecovery, dp.id departmentFk, - dp.name departmentName + dp.name departmentName, + dp.notificationEmail departmentEmail FROM defaulter d JOIN client c ON c.id = d.clientFk JOIN country cn ON cn.id = c.countryFk diff --git a/modules/client/back/methods/defaulter/observationEmail.js b/modules/client/back/methods/defaulter/observationEmail.js index c06d1d3d0..797e88f74 100644 --- a/modules/client/back/methods/defaulter/observationEmail.js +++ b/modules/client/back/methods/defaulter/observationEmail.js @@ -47,7 +47,7 @@ module.exports = Self => { await models.Mail.create({ subject: $t('Comment added to client', {clientFk: defaulter.clientFk}), body: body, - receiver: `${defaulter.salesPersonName}@verdnatura.es`, + receiver: `${defaulter.departmentEmail}`, replyTo: `${user.name}@verdnatura.es` }, myOptions); } diff --git a/modules/client/back/models/client-observation.js b/modules/client/back/models/client-observation.js index e34eedca9..d022a440a 100644 --- a/modules/client/back/models/client-observation.js +++ b/modules/client/back/models/client-observation.js @@ -1,8 +1,11 @@ module.exports = function(Self) { - Self.validate('text', isEnabled, {message: 'Description cannot be blank'}); - function isEnabled(err) { + Self.validate('text', function(err) { if (!this.text) err(); - } + }, {message: 'Description cannot be blank'}); + + Self.validate('observationTypeFk', function(err) { + if (!this.observationTypeFk) err(); + }, {message: 'type cannot be blank'}); Self.observe('before save', function(ctx, next) { ctx.instance.created = Date(); diff --git a/modules/client/back/models/client-observation.json b/modules/client/back/models/client-observation.json index b204ebeb4..86351862d 100644 --- a/modules/client/back/models/client-observation.json +++ b/modules/client/back/models/client-observation.json @@ -1,10 +1,10 @@ { - "name": "ClientObservation", + "name": "ClientObservation", "description": "Client notes", "base": "VnModel", - "mixins": { - "Loggable": true - }, + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "clientObservation" @@ -26,6 +26,10 @@ "created": { "type": "date", "description": "Creation date and time" + }, + "observationTypeFk": { + "type": "number", + "description": "Type of observation" } }, "relations": { @@ -44,14 +48,18 @@ "include": { "relation": "worker", "scope": { - "fields": ["id"], + "fields": [ + "id" + ], "include": { "relation": "user", "scope": { - "fields": ["nickname"] + "fields": [ + "nickname" + ] } } } } } -} +} \ No newline at end of file diff --git a/modules/client/front/descriptor/index.html b/modules/client/front/descriptor/index.html index f2dbd64b6..cecd7ee62 100644 --- a/modules/client/front/descriptor/index.html +++ b/modules/client/front/descriptor/index.html @@ -99,7 +99,7 @@
diff --git a/modules/client/front/note/index/index.html b/modules/client/front/note/index/index.html index 634a9c3ce..e69de29bb 100644 --- a/modules/client/front/note/index/index.html +++ b/modules/client/front/note/index/index.html @@ -1,31 +0,0 @@ - - - - -
- - {{::note.worker.user.nickname}} - {{::note.created | date:'dd/MM/yyyy HH:mm'}} - - - {{::note.text}} - -
-
-
- - - diff --git a/modules/client/front/note/index/index.js b/modules/client/front/note/index/index.js index ed15db671..1610bdaab 100644 --- a/modules/client/front/note/index/index.js +++ b/modules/client/front/note/index/index.js @@ -5,9 +5,10 @@ import './style.scss'; export default class Controller extends Section { constructor($element, $) { super($element, $); - this.filter = { - order: 'created DESC', - }; + } + async $onInit() { + this.$state.go('home'); + window.location.href = await this.vnApp.getUrl(`customer/${this.$params.id}/notes`); } } diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 776544bc6..f4703245c 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -106,10 +106,15 @@ module.exports = Self => { description: `The to shipped date filter` }, { - arg: 'days', + arg: 'daysOnward', type: 'number', description: `N days interval` }, + { + arg: 'daysAgo', + type: 'number', + description: `N days ago interval` + }, { arg: 'invoiceAmount', type: 'number', @@ -216,16 +221,29 @@ module.exports = Self => { JOIN vn.currency cu ON cu.id = e.currencyFk` ); - if (ctx.args.days) { - stmt.merge({ - sql: ` - AND t.shipped <= util.VN_CURDATE() + INTERVAL ? DAY - AND t.shipped >= util.VN_CURDATE() - `, - params: [ctx.args.days] - }); + stmt.merge(conn.makeWhere(filter.where)); + + const {daysAgo, daysOnward} = ctx.args; + if (daysOnward || daysAgo) { + const params = []; + let today = 'util.VN_CURDATE()'; + let from = today; + let to = today; + + if (daysAgo) { + from += ' - INTERVAL ? DAY'; + params.push(daysAgo); + } + if (daysOnward) { + to += ' + INTERVAL ? DAY'; + params.push(daysOnward); + } + + const whereDays = (filter.where ? 'AND' : 'WHERE') + ` t.shipped BETWEEN ${from} AND ${to}`; + stmt.merge({sql: whereDays, params}); } - stmt.merge(conn.makeSuffix(filter)); + + stmt.merge(conn.makePagination(filter)); const itemsIndex = stmts.push(stmt) - 1; const sql = ParameterizedSQL.join(stmts, ';'); diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index c7156062a..4bf5127b0 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -39,7 +39,7 @@ describe('Entry filter()', () => { const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(11); + expect(result.length).toEqual(12); await tx.rollback(); } catch (e) { @@ -49,13 +49,13 @@ describe('Entry filter()', () => { }); describe('should return the entry matching the supplier', () => { - it('when userId is supplier ', async() => { + it('when userId is supplier and searching days onward', async() => { const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; try { const ctx = { - args: {days: 6}, + args: {daysOnward: 6}, req: {accessToken: {userId: 1102}} }; @@ -70,6 +70,27 @@ describe('Entry filter()', () => { } }); + it('when userId is supplier and searching days ago', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: {daysAgo: 31}, + req: {accessToken: {userId: 1102}} + }; + + const result = await models.Entry.filter(ctx, options); + + expect(result.length).toEqual(6); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + it('when userId is supplier fetching other supplier', async() => { const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; @@ -131,7 +152,7 @@ describe('Entry filter()', () => { const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(10); + expect(result.length).toEqual(11); await tx.rollback(); } catch (e) { diff --git a/modules/entry/back/methods/stock-bought/getStockBought.js b/modules/entry/back/methods/stock-bought/getStockBought.js index c1f99c496..9768b58e7 100644 --- a/modules/entry/back/methods/stock-bought/getStockBought.js +++ b/modules/entry/back/methods/stock-bought/getStockBought.js @@ -6,6 +6,9 @@ module.exports = Self => { arg: 'workerFk', type: 'number', description: 'The id for a buyer', + }, { + arg: 'filter', + type: 'object', }, { arg: 'dated', @@ -23,7 +26,7 @@ module.exports = Self => { } }); - Self.getStockBought = async(workerFk, dated = Date.vnNew()) => { + Self.getStockBought = async(workerFk, filter, dated = Date.vnNew()) => { const models = Self.app.models; const today = Date.vnNew(); dated.setHours(0, 0, 0, 0); @@ -31,7 +34,7 @@ module.exports = Self => { await models.StockBought.rawSql(`CALL vn.stockBought_calculate(?)`, [dated]); - const filter = { + const defaultFilter = { where: {dated}, include: [ { @@ -53,6 +56,6 @@ module.exports = Self => { if (workerFk) filter.where.workerFk = workerFk; - return models.StockBought.find(filter); + return models.StockBought.find({...filter, ...defaultFilter}); }; }; diff --git a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js index 3e040d0d3..60b099682 100644 --- a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js +++ b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js @@ -1,3 +1,4 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('getStockBoughtDetail', { description: 'Returns the detail of stock bought for a given date and a worker', @@ -12,6 +13,9 @@ module.exports = Self => { type: 'string', description: 'The date to filter', required: true, + }, { + arg: 'filter', + type: 'object', } ], returns: { @@ -24,11 +28,10 @@ module.exports = Self => { } }); - Self.getStockBoughtDetail = async(workerFk, dated) => { - const models = Self.app.models; + Self.getStockBoughtDetail = async(workerFk, dated, filter, options) => { + const conn = Self.dataSource.connector; const myOptions = {}; let tx; - let result; if (typeof options == 'object') Object.assign(myOptions, options); @@ -39,14 +42,16 @@ module.exports = Self => { } try { - await models.StockBought.rawSql(`CALL vn.item_calculateStock(?)`, [dated], myOptions); - result = await Self.rawSql( + const stmts = []; + stmts.push(new ParameterizedSQL(`CALL vn.item_calculateStock(?)`, [dated])); + + const query = new ParameterizedSQL( `SELECT b.entryFk entryFk, i.id itemFk, i.name itemName, ti.quantity, - (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) - / (vc.trolleyM3 * 1000000) volume, + ROUND((ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) + / (vc.trolleyM3 * 1000000),1) volume, b.packagingFk packagingFk, b.packing FROM tmp.item ti @@ -61,11 +66,17 @@ module.exports = Self => { JOIN volumeConfig vc WHERE ic.display AND w.id = ?`, - [workerFk], myOptions + [workerFk] ); - await Self.rawSql(`DROP TEMPORARY TABLE tmp.item, tmp.buyUltimate;`, [], myOptions); + + stmts.push(query.merge(conn.makeSuffix(filter))); + + stmts.push(new ParameterizedSQL(`DROP TEMPORARY TABLE tmp.item, tmp.buyUltimate`)); + + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql, myOptions); if (tx) await tx.commit(); - return result; + return result[1]; } catch (e) { await tx.rollback(); throw e; diff --git a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js index c46da0ba5..a06128848 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js @@ -10,6 +10,11 @@ module.exports = Self => { type: 'any', description: 'The invoiceable client id' }, + { + arg: 'addressFk', + type: 'any', + description: 'The address id' + }, { arg: 'ticketFk', type: 'any', @@ -23,7 +28,8 @@ module.exports = Self => { { arg: 'serial', type: 'string', - description: 'The invoice serial' + description: 'The invoice serial', + required: true }, { arg: 'taxArea', @@ -46,108 +52,126 @@ module.exports = Self => { } }); - Self.createManualInvoice = async(ctx, clientFk, ticketFk, maxShipped, serial, taxArea, reference, options) => { - if (!clientFk && !ticketFk) throw new UserError(`Select ticket or client`); - const models = Self.app.models; - const myOptions = {userId: ctx.req.accessToken.userId}; - let tx; + Self.createManualInvoice = + async(ctx, clientFk, addressFk, ticketFk, maxShipped, serial, taxArea, reference, options) => { + if (!clientFk && !ticketFk) throw new UserError(`Select ticket or client`); + const models = Self.app.models; + const myOptions = {userId: ctx.req.accessToken.userId}; + let tx; - if (typeof options == 'object') - Object.assign(myOptions, options); + if (typeof options == 'object') + Object.assign(myOptions, options); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } - let companyId; - let newInvoice; - let query; - try { - if (ticketFk) { - const ticket = await models.Ticket.findById(ticketFk, null, myOptions); - const company = await models.Company.findById(ticket.companyFk, null, myOptions); + let companyFk; + let newInvoice; + let query; + try { + if (ticketFk) { + const ticket = await models.Ticket.findById(ticketFk, { + fields: ['clientFk', 'companyFk', 'shipped', 'refFk', 'totalWithVat'] + }, myOptions); + const company = await models.Company.findById(ticket.companyFk, { + fields: ['code'] + }, myOptions); - clientFk = ticket.clientFk; - maxShipped = ticket.shipped; - companyId = ticket.companyFk; + clientFk = ticket.clientFk; + maxShipped = ticket.shipped; + companyFk = ticket.companyFk; - // Validates invoiced ticket - if (ticket.refFk) - throw new UserError('This ticket is already invoiced'); + if (ticket.refFk) + throw new UserError('This ticket is already invoiced'); - // Validates ticket amount - if (ticket.totalWithVat == 0) - throw new UserError(`A ticket with an amount of zero can't be invoiced`); + if (ticket.totalWithVat == 0) + throw new UserError(`A ticket with an amount of zero can't be invoiced`); - // Validates ticket nagative base - const hasNegativeBase = await getNegativeBase(maxShipped, clientFk, companyId, myOptions); - if (hasNegativeBase && company.code == 'VNL') - throw new UserError(`A ticket with a negative base can't be invoiced`); - } else { - if (!maxShipped) - throw new UserError(`Max shipped required`); + const hasNegativeBase = await getNegativeBase(maxShipped, clientFk, companyFk, myOptions); + if (hasNegativeBase && company.code == 'VNL') + throw new UserError(`A ticket with a negative base can't be invoiced`); + } else { + if (!maxShipped) + throw new UserError(`Max shipped required`); - const company = await models.Ticket.findOne({ - fields: ['companyFk'], - where: { - clientFk: clientFk, - shipped: {lte: maxShipped} + if (addressFk) { + const address = await models.Address.findById(addressFk, { + fields: ['clientFk'] + }, myOptions); + + if (clientFk && clientFk !== address.clientFk) + throw new UserError('The provided clientFk does not match'); } - }, myOptions); - companyId = company.companyFk; + const company = await models.Ticket.findOne({ + fields: ['companyFk'], + where: { + clientFk: clientFk, + shipped: {lte: maxShipped} + } + }, myOptions); + companyFk = company.companyFk; + } + + const isClientInvoiceable = await isInvoiceable(clientFk, myOptions); + if (!isClientInvoiceable) + throw new UserError(`This client is not invoiceable`); + + const tomorrow = Date.vnNew(); + tomorrow.setDate(tomorrow.getDate() + 1); + + if (maxShipped >= tomorrow) + throw new UserError(`Can't invoice to future`); + + const maxInvoiceDate = await getMaxIssued(serial, companyFk, myOptions); + if (Date.vnNew() < maxInvoiceDate) + throw new UserError(`Can't invoice to past`); + + if (ticketFk) { + query = `CALL invoiceOut_newFromTicket(?, ?, ?, ?, @newInvoiceId)`; + await Self.rawSql(query, [ + ticketFk, + serial, + taxArea, + reference + ], myOptions); + } else if (addressFk) { + query = `CALL invoiceOut_newFromAddress(?, ?, ?, ?, ?, ?, @newInvoiceId)`; + await Self.rawSql(query, [ + addressFk, + serial, + maxShipped, + companyFk, + taxArea, + reference + ], myOptions); + } else { + query = `CALL invoiceOut_newFromClient(?, ?, ?, ?, ?, ?, @newInvoiceId)`; + await Self.rawSql(query, [ + clientFk, + serial, + maxShipped, + companyFk, + taxArea, + reference + ], myOptions); + } + + [newInvoice] = await Self.rawSql(`SELECT @newInvoiceId id`, null, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; } - // Validate invoiceable client - const isClientInvoiceable = await isInvoiceable(clientFk, myOptions); - if (!isClientInvoiceable) - throw new UserError(`This client is not invoiceable`); + if (!newInvoice.id) throw new UserError('It was not able to create the invoice'); - // Can't invoice tickets into future - const tomorrow = Date.vnNew(); - tomorrow.setDate(tomorrow.getDate() + 1); + await Self.createPdf(ctx, newInvoice.id); - if (maxShipped >= tomorrow) - throw new UserError(`Can't invoice to future`); - - const maxInvoiceDate = await getMaxIssued(serial, companyId, myOptions); - if (Date.vnNew() < maxInvoiceDate) - throw new UserError(`Can't invoice to past`); - - if (ticketFk) { - query = `CALL invoiceOut_newFromTicket(?, ?, ?, ?, @newInvoiceId)`; - await Self.rawSql(query, [ - ticketFk, - serial, - taxArea, - reference - ], myOptions); - } else { - query = `CALL invoiceOut_newFromClient(?, ?, ?, ?, ?, ?, @newInvoiceId)`; - await Self.rawSql(query, [ - clientFk, - serial, - maxShipped, - companyId, - taxArea, - reference - ], myOptions); - } - - [newInvoice] = await Self.rawSql(`SELECT @newInvoiceId id`, null, myOptions); - - if (tx) await tx.commit(); - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - - if (!newInvoice.id) throw new UserError('It was not able to create the invoice'); - - await Self.createPdf(ctx, newInvoice.id); - - return newInvoice; - }; + return newInvoice; + }; async function isInvoiceable(clientFk, options) { const models = Self.app.models; @@ -159,10 +183,10 @@ module.exports = Self => { return result.invoiceable; } - async function getNegativeBase(maxShipped, clientFk, companyId, options) { + async function getNegativeBase(maxShipped, clientFk, companyFk, options) { const models = Self.app.models; await models.InvoiceOut.rawSql('CALL invoiceOut_exportationFromClient(?,?,?)', - [maxShipped, clientFk, companyId], options + [maxShipped, clientFk, companyFk], options ); const query = 'SELECT vn.hasAnyNegativeBase() AS base'; const [result] = await models.InvoiceOut.rawSql(query, [], options); @@ -170,14 +194,14 @@ module.exports = Self => { return result.base; } - async function getMaxIssued(serial, companyId, options) { + async function getMaxIssued(serial, companyFk, options) { const models = Self.app.models; const query = `SELECT MAX(issued) AS issued FROM invoiceOut WHERE serial = ? AND companyFk = ?`; const [maxIssued] = await models.InvoiceOut.rawSql(query, - [serial, companyId], options); - const maxInvoiceDate = maxIssued && maxIssued.issued || Date.vnNew(); + [serial, companyFk], options); + const maxInvoiceDate = maxIssued?.issued || Date.vnNew(); return maxInvoiceDate; } diff --git a/modules/invoiceOut/back/methods/invoiceOut/delete.js b/modules/invoiceOut/back/methods/invoiceOut/delete.js index d6efd9961..1ab9a582b 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/delete.js +++ b/modules/invoiceOut/back/methods/invoiceOut/delete.js @@ -37,7 +37,7 @@ module.exports = Self => { const tickets = await models.Ticket.find({ where: {refFk: invoiceOut.ref} }, myOptions); - + const [bookEntry] = await models.Xdiario.find({ where: { SERIE: invoiceOut.ref[0], @@ -55,13 +55,13 @@ module.exports = Self => { if (bookEntry) { if (bookEntry.enlazadoSage) { const params = { - bookEntry: bookEntry.ASIEN, + bookEntry: bookEntry.ASIEN, invoiceOutRef: invoiceOut.ref - } + }; await Self.rawSql(`SELECT util.notification_send('book-entry-deleted', ?, NULL)`, [JSON.stringify(params)], myOptions); - }; + } await models.Xdiario.destroyAll({ ASIEN: bookEntry.ASIEN diff --git a/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js b/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js index 76ef29604..9e491b35c 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js +++ b/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js @@ -48,13 +48,13 @@ module.exports = Self => { let stmt; stmts.push(new ParameterizedSQL( `CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (KEY (ticketFk)) + (INDEX (ticketFk)) ENGINE = MEMORY SELECT id ticketFk - FROM ticket t + FROM ticket WHERE shipped BETWEEN ? AND util.dayEnd(?) AND refFk IS NULL`, [args.from, args.to])); - stmts.push(`CALL vn.ticket_getTax(NULL)`); + stmts.push(`CALL ticket_getTax(NULL)`); stmts.push(new ParameterizedSQL( `CREATE OR REPLACE TEMPORARY TABLE tmp.filter ENGINE = MEMORY @@ -71,12 +71,12 @@ module.exports = Self => { c.isTaxDataChecked, w.id comercialId, u.name workerName - FROM vn.ticket t - JOIN vn.company co ON co.id = t.companyFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.country cou ON cou.id = c.countryFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + FROM ticket t + JOIN company co ON co.id = t.companyFk + JOIN sale s ON s.ticketFk = t.id + JOIN client c ON c.id = t.clientFk + JOIN country cou ON cou.id = c.countryFk + LEFT JOIN worker w ON w.id = c.salesPersonFk JOIN account.user u ON u.id = w.id LEFT JOIN ( SELECT ticketFk, taxableBase diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js index 55739e570..58c18b730 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js @@ -6,110 +6,90 @@ describe('InvoiceOut createManualInvoice()', () => { const clientId = 1106; const activeCtx = {accessToken: {userId: 1}}; const ctx = {req: activeCtx}; + let tx; let options; + + beforeEach(async() => { + spyOn(models.InvoiceOut, 'createPdf').and.returnValue(Promise.resolve(true)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + + tx = await models.InvoiceOut.beginTransaction({}); + options = {transaction: tx}; + }); + + afterEach(async() => { + await tx.rollback(); + }); it('should throw an error trying to invoice again', async() => { - spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); - - const tx = await models.InvoiceOut.beginTransaction({}); - const options = {transaction: tx}; - let error; try { - await createInvoice(ctx, options, undefined, ticketId); - await createInvoice(ctx, options, undefined, ticketId); - - await tx.rollback(); + await createInvoice(ctx, options, undefined, undefined, ticketId); + await createInvoice(ctx, options, undefined, undefined, ticketId); } catch (e) { error = e; - await tx.rollback(); } expect(error.message).toContain('This ticket is already invoiced'); }); it('should throw an error for a ticket with an amount of zero', async() => { - spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - - const tx = await models.InvoiceOut.beginTransaction({}); - const options = {transaction: tx}; - let error; try { const ticket = await models.Ticket.findById(ticketId, null, options); await ticket.updateAttributes({totalWithVat: 0}, options); - await createInvoice(ctx, options, undefined, ticketId); - await tx.rollback(); + await createInvoice(ctx, options, undefined, undefined, ticketId); } catch (e) { error = e; - await tx.rollback(); } expect(error.message).toContain(`A ticket with an amount of zero can't be invoiced`); }); it('should throw an error when the clientFk property is set without the max shipped date', async() => { - spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); - - const tx = await models.InvoiceOut.beginTransaction({}); - const options = {transaction: tx}; - let error; try { await createInvoice(ctx, options, clientId); - await tx.rollback(); } catch (e) { error = e; - await tx.rollback(); } expect(error.message).toContain(`Max shipped required`); }); it('should throw an error for a non-invoiceable client', async() => { - spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - - const tx = await models.InvoiceOut.beginTransaction({}); - const options = {transaction: tx}; - let error; try { const client = await models.Client.findById(clientId, null, options); await client.updateAttributes({isTaxDataChecked: false}, options); - await createInvoice(ctx, options, undefined, ticketId); - - await tx.rollback(); + await createInvoice(ctx, options, undefined, undefined, ticketId); } catch (e) { error = e; - await tx.rollback(); } expect(error.message).toContain(`This client is not invoiceable`); }); - it('should create a manual invoice', async() => { - spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); + it('should create a manual invoice with ticket', async() => { + const result = await createInvoice(ctx, options, undefined, undefined, ticketId); - const tx = await models.InvoiceOut.beginTransaction({}); - const options = {transaction: tx}; + expect(result.id).toEqual(jasmine.any(Number)); + }); - try { - const result = await createInvoice(ctx, options, undefined, ticketId); + it('should create a manual invoice with client', async() => { + const result = await createInvoice(ctx, options, clientId, undefined, undefined, Date.vnNew()); - expect(result.id).toEqual(jasmine.any(Number)); + expect(result.id).toEqual(jasmine.any(Number)); + }); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + it('should create a manual invoice with address', async() => { + const addressFk = 126; + const result = await createInvoice(ctx, options, clientId, addressFk, undefined, Date.vnNew()); + + expect(result.id).toEqual(jasmine.any(Number)); }); }); @@ -117,6 +97,7 @@ function createInvoice( ctx, options, clientFk = undefined, + addressFk = undefined, ticketFk = undefined, maxShipped = undefined, serial = 'T', @@ -124,6 +105,6 @@ function createInvoice( reference = undefined ) { return models.InvoiceOut.createManualInvoice( - ctx, clientFk, ticketFk, maxShipped, serial, taxArea, reference, options + ctx, clientFk, addressFk, ticketFk, maxShipped, serial, taxArea, reference, options ); } diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index bab1fa375..f8fc8cdbf 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -79,6 +79,8 @@ module.exports = Self => { type ], myOptions); + if (!serial) + throw new UserError('No invoice series found for these parameters'); const invoiceOutSerial = await Self.app.models.InvoiceOutSerial.findById(serial); if (invoiceOutSerial?.taxAreaFk == 'WORLD') { diff --git a/modules/invoiceOut/front/index.js b/modules/invoiceOut/front/index.js index a5e51d439..6d58a0a45 100644 --- a/modules/invoiceOut/front/index.js +++ b/modules/invoiceOut/front/index.js @@ -1,7 +1,7 @@ export * from './module'; import './main'; -import './summary'; import './descriptor'; import './descriptor-popover'; import './descriptor-menu'; +import './summary'; diff --git a/modules/invoiceOut/front/routes.json b/modules/invoiceOut/front/routes.json index 7c7495cb9..908df3972 100644 --- a/modules/invoiceOut/front/routes.json +++ b/modules/invoiceOut/front/routes.json @@ -34,6 +34,12 @@ "params": { "invoice-out": "$ctrl.invoiceOut" } + }, + { + "url": "/:id", + "state": "invoiceOut.card", + "abstract": true, + "component": "vn-invoice-out-card" } ] } diff --git a/modules/item/back/methods/item-shelving/deleteItemShelvings.js b/modules/item/back/methods/item-shelving/deleteItemShelvings.js index f534b4e9a..fbc354cce 100644 --- a/modules/item/back/methods/item-shelving/deleteItemShelvings.js +++ b/modules/item/back/methods/item-shelving/deleteItemShelvings.js @@ -34,6 +34,11 @@ module.exports = Self => { try { const promises = []; for (let itemShelvingId of itemShelvingIds) { + const itemShelvingSaleToDelete = models.ItemShelvingSale.destroyAll({ + itemShelvingFk: itemShelvingId + }, myOptions); + promises.push(itemShelvingSaleToDelete); + const itemShelvingToDelete = models.ItemShelving.destroyById(itemShelvingId, myOptions); promises.push(itemShelvingToDelete); } diff --git a/modules/item/back/methods/item-shelving/specs/deleteItemShelvings.spec.js b/modules/item/back/methods/item-shelving/specs/deleteItemShelvings.spec.js index b4113d7cf..541a529cb 100644 --- a/modules/item/back/methods/item-shelving/specs/deleteItemShelvings.spec.js +++ b/modules/item/back/methods/item-shelving/specs/deleteItemShelvings.spec.js @@ -10,7 +10,7 @@ describe('ItemShelving deleteItemShelvings()', () => { const itemShelvingIds = [1, 2]; const result = await models.ItemShelving.deleteItemShelvings(itemShelvingIds, options); - expect(result.length).toEqual(2); + expect(result.length).toEqual(4); await tx.rollback(); } catch (e) { diff --git a/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js b/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js index 00488e534..2fd30c2ca 100644 --- a/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js +++ b/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); describe('item lastEntriesFilter()', () => { - it('should return one entry for the given item', async() => { + it('should return two entry for the given item', async() => { const minDate = Date.vnNew(); minDate.setHours(0, 0, 0, 0); const maxDate = Date.vnNew(); @@ -13,7 +13,7 @@ describe('item lastEntriesFilter()', () => { const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; const result = await models.Item.lastEntriesFilter(filter, options); - expect(result.length).toEqual(1); + expect(result.length).toEqual(2); await tx.rollback(); } catch (e) { @@ -22,7 +22,7 @@ describe('item lastEntriesFilter()', () => { } }); - it('should return five entries for the given item', async() => { + it('should return six entries for the given item', async() => { const minDate = Date.vnNew(); minDate.setHours(0, 0, 0, 0); minDate.setMonth(minDate.getMonth() - 2, 1); @@ -37,7 +37,7 @@ describe('item lastEntriesFilter()', () => { const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; const result = await models.Item.lastEntriesFilter(filter, options); - expect(result.length).toEqual(5); + expect(result.length).toEqual(6); await tx.rollback(); } catch (e) { diff --git a/modules/monitor/front/index.js b/modules/monitor/front/index.js index 19ea06b5a..a7209a0bd 100644 --- a/modules/monitor/front/index.js +++ b/modules/monitor/front/index.js @@ -1,8 +1,3 @@ export * from './module'; import './main'; -import './index/'; -import './index/tickets'; -import './index/clients'; -import './index/orders'; -import './index/search-panel'; diff --git a/modules/monitor/front/index/clients/index.html b/modules/monitor/front/index/clients/index.html deleted file mode 100644 index c0e3d1b14..000000000 --- a/modules/monitor/front/index/clients/index.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - - Clients on website - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Date - - Hour - - Salesperson - - Client -
- - {{::visit.dated | date:'dd/MM/yy'}} - - - - {{::visit.hour | date: 'HH:mm'}} - - - - {{::visit.salesPerson | dashIfEmpty}} - - - - {{::visit.clientName}} - -
-
- - - - -
-
- - - - diff --git a/modules/monitor/front/index/clients/index.js b/modules/monitor/front/index/clients/index.js deleted file mode 100644 index ac3ce9140..000000000 --- a/modules/monitor/front/index/clients/index.js +++ /dev/null @@ -1,96 +0,0 @@ -import ngModule from '../../module'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - constructor($element, $) { - super($element, $); - - const date = Date.vnNew(); - this.dateFrom = date; - this.dateTo = date; - this.filter = { - where: { - 'v.stamp': { - between: this.dateRange() - } - } - }; - - this.smartTableOptions = { - activeButtons: { - search: true - }, - columns: [ - { - field: 'clientFk', - autocomplete: { - url: 'Clients', - showField: 'name', - valueField: 'id' - } - }, - { - field: 'salesPersonFk', - autocomplete: { - url: 'Workers/activeWithInheritedRole', - where: `{role: 'salesPerson'}`, - searchFunction: '{firstName: $search}', - showField: 'nickname', - valueField: 'id', - } - }, - { - field: 'dated', - searchable: false - }, - { - field: 'hour', - searchable: false - } - ] - }; - } - - exprBuilder(param, value) { - switch (param) { - case 'clientFk': - return {[`c.id`]: value}; - case 'salesPersonFk': - return {[`c.${param}`]: value}; - } - } - - dateRange() { - let from = this.dateFrom; - let to = this.dateTo; - if (!from) - from = Date.vnNew(); - if (!to) - to = Date.vnNew(); - const minHour = new Date(from); - minHour.setHours(0, 0, 0, 0); - const maxHour = new Date(to); - maxHour.setHours(23, 59, 59, 59); - - return [minHour, maxHour]; - } - - addFilterDate() { - this.$.model.filter = { - where: { - 'v.stamp': { - between: this.dateRange() - } - } - }; - this.$.model.refresh(); - } -} - -ngModule.vnComponent('vnMonitorSalesClients', { - template: require('./index.html'), - controller: Controller, - require: { - main: '^vnMonitorIndex' - } -}); diff --git a/modules/monitor/front/index/index.html b/modules/monitor/front/index/index.html deleted file mode 100644 index 85987ac20..000000000 --- a/modules/monitor/front/index/index.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/modules/monitor/front/index/index.js b/modules/monitor/front/index/index.js deleted file mode 100644 index 72ca9dae9..000000000 --- a/modules/monitor/front/index/index.js +++ /dev/null @@ -1,34 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -export default class Controller extends Section { - constructor($element, $) { - super($element, $); - - const isTopPanelHidden = localStorage.getItem('ticketTopPanelHidden'); - if (isTopPanelHidden === 'true') - this.isTopPanelHidden = true; - } - - toggle() { - const monitor = this.element.querySelector('vn-horizontal'); - const isHidden = monitor.classList.contains('hidden'); - - if (!isHidden) { - monitor.classList.add('hidden'); - localStorage.setItem('ticketTopPanelHidden', true); - } else { - monitor.classList.remove('hidden'); - localStorage.setItem('ticketTopPanelHidden', false); - } - } -} - -ngModule.vnComponent('vnMonitorIndex', { - template: require('./index.html'), - controller: Controller, - require: { - main: '^vnMonitorIndex' - } -}); diff --git a/modules/monitor/front/index/index.spec.js b/modules/monitor/front/index/index.spec.js deleted file mode 100644 index 506e75720..000000000 --- a/modules/monitor/front/index/index.spec.js +++ /dev/null @@ -1,38 +0,0 @@ -import './index.js'; -describe('Component vnMonitorIndex', () => { - let controller; - let $element; - - beforeEach(ngModule('monitor')); - - beforeEach(inject(($compile, $rootScope) => { - $element = $compile('')($rootScope); - controller = $element.controller('vnMonitorIndex'); - })); - - describe('toggle()', () => { - it('should add the hidden class to the horizontal contaning the panel to hide', () => { - controller.toggle(); - - const targetElement = $element[0].querySelector('vn-horizontal'); - const firstClass = targetElement.classList[0]; - - const isTopPanelHidden = localStorage.getItem('ticketTopPanelHidden'); - - expect(firstClass).toEqual('hidden'); - expect(isTopPanelHidden).toEqual('true'); - }); - - it('should remove the hidden class to the horizontal contaning the panel to hide', () => { - const targetElement = $element[0].querySelector('vn-horizontal'); - targetElement.classList.add('hidden'); - controller.toggle(); - const firstClass = targetElement.classList[0]; - - const isTopPanelHidden = localStorage.getItem('ticketTopPanelHidden'); - - expect(firstClass).toBeUndefined(); - expect(isTopPanelHidden).toEqual('false'); - }); - }); -}); diff --git a/modules/monitor/front/index/locale/es.yml b/modules/monitor/front/index/locale/es.yml deleted file mode 100644 index f114a2259..000000000 --- a/modules/monitor/front/index/locale/es.yml +++ /dev/null @@ -1,16 +0,0 @@ -Tickets monitor: Monitor de tickets -Clients on website: Clientes activos en la web -Recent order actions: Acciones recientes en pedidos -Search tickets: Buscar tickets -Delete selected elements: Eliminar los elementos seleccionados -All the selected elements will be deleted. Are you sure you want to continue?: Todos los elementos seleccionados serán eliminados. ¿Seguro que quieres continuar? -Component lack: Faltan componentes -Ticket too little: Ticket demasiado pequeño -Minimize/Maximize: Minimizar/Maximizar -Problems: Problemas -Theoretical: Teórica -Practical: Práctica -Preparation: Preparación -Auto-refresh: Auto-refresco -Toggle auto-refresh every 2 minutes: Conmuta el refresco automático cada 2 minutos -Is fragile: Es frágil diff --git a/modules/monitor/front/index/orders/index.html b/modules/monitor/front/index/orders/index.html deleted file mode 100644 index 4d1171185..000000000 --- a/modules/monitor/front/index/orders/index.html +++ /dev/null @@ -1,141 +0,0 @@ - - - - - Recent order actions - - - - - - - - - - - - - - - - - - - Date - Client - SalesPerson - - - - - - - - - - - {{::order.date_send | date: 'dd/MM/yyyy'}} - - - - - {{::order.clientName}} - - - - - {{::order.salesPerson | dashIfEmpty}} - - - - - - - - {{::order.date_make | date: 'dd/MM/yyyy HH:mm'}} - - - - - {{::order.agencyName | dashIfEmpty}} - - - - {{::order.import | currency: 'EUR':2}} - - - - - - - - - - - - - - - Filter by selection - - - Exclude selection - - - Remove filter - - - Remove all filters - - - Copy value - - - - - diff --git a/modules/monitor/front/index/orders/index.js b/modules/monitor/front/index/orders/index.js deleted file mode 100644 index 40100b79f..000000000 --- a/modules/monitor/front/index/orders/index.js +++ /dev/null @@ -1,74 +0,0 @@ -import ngModule from '../../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -export default class Controller extends Section { - get checked() { - const rows = this.$.model.data || []; - const checkedRows = []; - for (let row of rows) { - if (row.checked) - checkedRows.push(row.id); - } - - return checkedRows; - } - - get totalChecked() { - return this.checked.length; - } - - onDelete() { - const params = {deletes: this.checked}; - const query = `SalesMonitors/deleteOrders`; - this.$http.post(query, params).then( - () => this.$.model.refresh()); - } - - chipColor(date) { - const today = Date.vnNew(); - today.setHours(0, 0, 0, 0); - - const orderLanded = new Date(date); - orderLanded.setHours(0, 0, 0, 0); - - const difference = today - orderLanded; - - if (difference == 0) - return 'warning'; - if (difference < 0) - return 'success'; - if (difference > 0) - return 'alert'; - } - - exprBuilder(param, value) { - switch (param) { - case 'date_send': - return {[`o.date_send`]: { - between: this.dateRange(value)} - }; - case 'clientFk': - return {[`c.id`]: value}; - case 'salesPersonFk': - return {[`c.${param}`]: value}; - } - } - - dateRange(value) { - const minHour = new Date(value); - minHour.setHours(0, 0, 0, 0); - const maxHour = new Date(value); - maxHour.setHours(23, 59, 59, 59); - - return [minHour, maxHour]; - } -} - -ngModule.vnComponent('vnMonitorSalesOrders', { - template: require('./index.html'), - controller: Controller, - require: { - main: '^vnMonitorIndex' - } -}); diff --git a/modules/monitor/front/index/orders/index.spec.js b/modules/monitor/front/index/orders/index.spec.js deleted file mode 100644 index 109925358..000000000 --- a/modules/monitor/front/index/orders/index.spec.js +++ /dev/null @@ -1,50 +0,0 @@ -import './index.js'; -import crudModel from 'core/mocks/crud-model'; - -describe('Component vnMonitorSalesOrders', () => { - let controller; - let $httpBackend; - - beforeEach(ngModule('monitor')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - const $element = angular.element(''); - controller = $componentController('vnMonitorSalesOrders', {$element}); - controller.$.model = crudModel; - controller.$.model.data = [ - {id: 1, name: 'My item 1'}, - {id: 2, name: 'My item 2'}, - {id: 3, name: 'My item 3'} - ]; - })); - - describe('checked() getter', () => { - it('should return a the selected rows', () => { - const modelData = controller.$.model.data; - modelData[0].checked = true; - modelData[1].checked = true; - - const result = controller.checked; - - expect(result).toEqual(expect.arrayContaining([1, 2])); - }); - }); - - describe('onDelete()', () => { - it('should make a query and then call to the model refresh() method', () => { - jest.spyOn(controller.$.model, 'refresh'); - - const modelData = controller.$.model.data; - modelData[0].checked = true; - modelData[1].checked = true; - - const expectedParams = {deletes: [1, 2]}; - $httpBackend.expect('POST', 'SalesMonitors/deleteOrders', expectedParams).respond(200); - controller.onDelete(); - $httpBackend.flush(); - - expect(controller.$.model.refresh).toHaveBeenCalledWith(); - }); - }); -}); diff --git a/modules/monitor/front/index/orders/style.scss b/modules/monitor/front/index/orders/style.scss deleted file mode 100644 index 64d6497c9..000000000 --- a/modules/monitor/front/index/orders/style.scss +++ /dev/null @@ -1,19 +0,0 @@ -@import "variables"; - -vn-monitor-sales-orders { - vn-table.scrollable { - max-height: 350px; - overflow-x: hidden - } - - vn-table a.vn-tbody { - & > vn-tr:nth-child(2) { - color: gray; - - & > vn-td { - border-bottom: $border; - font-size: 13px; - } - } - } -} \ No newline at end of file diff --git a/modules/monitor/front/index/search-panel/index.html b/modules/monitor/front/index/search-panel/index.html deleted file mode 100644 index 25a3510ab..000000000 --- a/modules/monitor/front/index/search-panel/index.html +++ /dev/null @@ -1,120 +0,0 @@ -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {{name}} - - - - - - - - - - - - - - - - - - - - -
-
diff --git a/modules/monitor/front/index/search-panel/index.js b/modules/monitor/front/index/search-panel/index.js deleted file mode 100644 index ef6625e8a..000000000 --- a/modules/monitor/front/index/search-panel/index.js +++ /dev/null @@ -1,59 +0,0 @@ -import ngModule from '../../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; - -class Controller extends SearchPanel { - constructor($, $element) { - super($, $element); - this.filter = this.$.filter; - - this.getGroupedStates(); - } - - getGroupedStates() { - let groupedStates = []; - this.$http.get('AlertLevels').then(res => { - for (let state of res.data) { - groupedStates.push({ - id: state.id, - code: state.code, - name: this.$t(state.code) - }); - } - this.groupedStates = groupedStates; - }); - } - - get from() { - return this._from; - } - - set from(value) { - this._from = value; - this.filter.scopeDays = null; - } - - get to() { - return this._to; - } - - set to(value) { - this._to = value; - this.filter.scopeDays = null; - } - - get scopeDays() { - return this._scopeDays; - } - - set scopeDays(value) { - this._scopeDays = value; - - this.filter.from = null; - this.filter.to = null; - } -} - -ngModule.vnComponent('vnMonitorSalesSearchPanel', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/monitor/front/index/search-panel/index.spec.js b/modules/monitor/front/index/search-panel/index.spec.js deleted file mode 100644 index 18cf1abfc..000000000 --- a/modules/monitor/front/index/search-panel/index.spec.js +++ /dev/null @@ -1,71 +0,0 @@ -import './index'; - -describe('Monitor Component vnMonitorSalesSearchPanel', () => { - let $httpBackend; - let controller; - - beforeEach(ngModule('monitor')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - controller = $componentController('vnMonitorSalesSearchPanel', {$element: null}); - controller.$t = () => {}; - controller.filter = {}; - })); - - describe('getGroupedStates()', () => { - it('should set an array of groupedStates with the adition of a name translation', () => { - jest.spyOn(controller, '$t').mockReturnValue('miCodigo'); - const data = [ - { - id: 9999, - code: 'myCode' - } - ]; - $httpBackend.whenGET('AlertLevels').respond(data); - controller.getGroupedStates(); - $httpBackend.flush(); - - expect(controller.groupedStates).toEqual([{ - id: 9999, - code: 'myCode', - name: 'miCodigo' - }]); - }); - }); - - describe('from() setter', () => { - it('should clear the scope days when setting the from property', () => { - controller.filter.scopeDays = 1; - - controller.from = Date.vnNew(); - - expect(controller.filter.scopeDays).toBeNull(); - expect(controller.from).toBeDefined(); - }); - }); - - describe('to() setter', () => { - it('should clear the scope days when setting the to property', () => { - controller.filter.scopeDays = 1; - - controller.to = Date.vnNew(); - - expect(controller.filter.scopeDays).toBeNull(); - expect(controller.to).toBeDefined(); - }); - }); - - describe('scopeDays() setter', () => { - it('should clear the date range when setting the scopeDays property', () => { - controller.filter.from = Date.vnNew(); - controller.filter.to = Date.vnNew(); - - controller.scopeDays = 1; - - expect(controller.filter.from).toBeNull(); - expect(controller.filter.to).toBeNull(); - expect(controller.scopeDays).toBeDefined(); - }); - }); -}); diff --git a/modules/monitor/front/index/style.scss b/modules/monitor/front/index/style.scss deleted file mode 100644 index 2b193ac88..000000000 --- a/modules/monitor/front/index/style.scss +++ /dev/null @@ -1,85 +0,0 @@ -@import "variables"; -@import "effects"; - -vn-monitor-index { - .header { - padding: 12px 0 5px 0; - color: gray; - font-size: 1.2rem; - border-bottom: $border; - margin-bottom: 10px; - - & > vn-none > vn-icon { - @extend %clickable-light; - color: $color-button; - font-size: 1.4rem; - } - - vn-none > .arrow { - transition: transform 200ms; - } - } - - vn-monitor-sales-clients { - vn-card { - margin-right: 15px; - } - - .header { - padding-right: 15px; - - & > vn-none > .arrow { - display: none - } - } - } - - vn-table.scrollable { - height: 300px - } - - vn-horizontal { - flex-wrap: wrap - } - - .hidden { - vn-card { - display: none - } - - .header > vn-none > .arrow { - transform: rotate(180deg); - } - } -} - -@media (max-width:1150px) { - vn-monitor-index { - & > vn-horizontal { - flex-direction: column; - - vn-monitor-sales-clients, - vn-monitor-sales-orders { - width: 100% - } - - vn-monitor-sales-clients { - margin-bottom: 15px - } - } - - vn-monitor-sales-clients { - vn-card { - margin-right: 0 - } - - .header { - padding-right: 0; - - & > vn-none > .arrow { - display: inline-block - } - } - } - } -} \ No newline at end of file diff --git a/modules/monitor/front/index/tickets/index.html b/modules/monitor/front/index/tickets/index.html deleted file mode 100644 index 94a950baf..000000000 --- a/modules/monitor/front/index/tickets/index.html +++ /dev/null @@ -1,270 +0,0 @@ - - - - - - - - - Tickets monitor - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Problems - - Identifier - - Client - - Salesperson - - Date - - Theoretical - - Practical - - Preparation - - Province - - State - - Fragile - - Zone - - Total -
- - - - - - - - - - - - - - - - - {{ticket.id}} - - - - {{ticket.nickname}} - - - - {{ticket.userName | dashIfEmpty}} - - - - {{ticket.shippedDate | date: 'dd/MM/yyyy'}} - - {{ticket.zoneLanding | date: 'HH:mm'}}{{ticket.practicalHour | date: 'HH:mm'}}{{ticket.shipped | date: 'HH:mm'}}{{ticket.province}} - - {{ticket.refFk}} - - - {{ticket.state}} - - - - - - - {{ticket.zoneName | dashIfEmpty}} - - - - {{(ticket.totalWithVat ? ticket.totalWithVat : 0) | currency: 'EUR': 2}} - - - - - - -
-
-
-
- - - - - - - - - - - - - - - - Filter by selection - - - Exclude selection - - - Remove filter - - - Remove all filters - - - Copy value - - - diff --git a/modules/monitor/front/index/tickets/index.js b/modules/monitor/front/index/tickets/index.js deleted file mode 100644 index 2f2dead05..000000000 --- a/modules/monitor/front/index/tickets/index.js +++ /dev/null @@ -1,178 +0,0 @@ -import ngModule from '../../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -export default class Controller extends Section { - constructor($element, $) { - super($element, $); - - this.filterParams = this.fetchParams(); - this.smartTableOptions = { - activeButtons: { - search: true, - shownColumns: true, - }, - columns: [ - { - field: 'totalProblems', - searchable: false - }, - { - field: 'salesPersonFk', - autocomplete: { - url: 'Workers/activeWithInheritedRole', - where: `{role: 'salesPerson'}`, - searchFunction: '{firstName: $search}', - showField: 'nickname', - valueField: 'id', - } - }, - { - field: 'provinceFk', - autocomplete: { - url: 'Provinces', - } - }, - { - field: 'stateFk', - autocomplete: { - url: 'States', - } - }, - { - field: 'zoneFk', - autocomplete: { - url: 'Zones', - } - }, - { - field: 'warehouseFk', - autocomplete: { - url: 'Warehouses', - } - }, - { - field: 'shippedDate', - datepicker: true - }, - { - field: 'theoreticalHour', - searchable: false - }, - { - field: 'preparationHour', - searchable: false - } - ] - }; - } - - $onInit() { - if (!this.$params.q) { - this.$.$applyAsync( - () => this.$.model.applyFilter(null, this.filterParams)); - } - } - - fetchParams($params = {}) { - const excludedParams = [ - 'search', - 'clientFk', - 'orderFk', - 'refFk', - 'scopeDays' - ]; - - const hasExcludedParams = excludedParams.some(param => { - return $params && $params[param] != undefined; - }); - const hasParams = Object.entries($params).length; - if (!hasParams || !hasExcludedParams) - $params.scopeDays = 1; - - if (typeof $params.scopeDays === 'number') { - const from = Date.vnNew(); - from.setHours(0, 0, 0, 0); - - const to = new Date(from.getTime()); - to.setDate(to.getDate() + $params.scopeDays); - to.setHours(23, 59, 59, 999); - - Object.assign($params, {from, to}); - } - - return $params; - } - - compareDate(date) { - let today = Date.vnNew(); - today.setHours(0, 0, 0, 0); - let timeTicket = new Date(date); - timeTicket.setHours(0, 0, 0, 0); - - let comparation = today - timeTicket; - - if (comparation == 0) - return 'warning'; - if (comparation < 0) - return 'success'; - } - - totalPriceColor(ticket) { - const total = parseInt(ticket.totalWithVat); - if (total > 0 && total < 50) - return 'warning'; - } - - exprBuilder(param, value) { - switch (param) { - case 'stateFk': - return {'ts.stateFk': value}; - case 'salesPersonFk': - return {'c.salesPersonFk': value}; - case 'provinceFk': - return {'a.provinceFk': value}; - case 'theoreticalHour': - return {'z.hour': value}; - case 'practicalHour': - return {'zed.etc': value}; - case 'shippedDate': - return {'t.shipped': { - between: this.dateRange(value)} - }; - case 'nickname': - return {[`t.nickname`]: {like: `%${value}%`}}; - case 'zoneFk': - case 'totalWithVat': - return {[`t.${param}`]: value}; - } - } - - dateRange(value) { - const minHour = new Date(value); - minHour.setHours(0, 0, 0, 0); - const maxHour = new Date(value); - maxHour.setHours(23, 59, 59, 59); - - return [minHour, maxHour]; - } - - preview(ticket) { - this.selectedTicket = ticket; - this.$.summary.show(); - } - - autoRefresh(value) { - if (value) - this.refreshTimer = setInterval(() => this.$.model.refresh(), 120000); - else { - clearInterval(this.refreshTimer); - this.refreshTimer = null; - } - } -} - -ngModule.vnComponent('vnMonitorSalesTickets', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/monitor/front/index/tickets/index.spec.js b/modules/monitor/front/index/tickets/index.spec.js deleted file mode 100644 index c12ea6844..000000000 --- a/modules/monitor/front/index/tickets/index.spec.js +++ /dev/null @@ -1,133 +0,0 @@ -import './index.js'; -describe('Component vnMonitorSalesTickets', () => { - let controller; - let $window; - let tickets = [{ - id: 1, - clientFk: 1, - checked: false, - totalWithVat: 10.5 - }, { - id: 2, - clientFk: 1, - checked: true, - totalWithVat: 20.5 - }, { - id: 3, - clientFk: 1, - checked: true, - totalWithVat: 30 - }]; - - beforeEach(ngModule('monitor')); - - beforeEach(inject(($componentController, _$window_) => { - $window = _$window_; - const $element = angular.element(''); - controller = $componentController('vnMonitorSalesTickets', {$element}); - })); - - describe('fetchParams()', () => { - it('should return a range of dates with passed scope days', () => { - let params = controller.fetchParams({ - scopeDays: 2 - }); - const from = Date.vnNew(); - from.setHours(0, 0, 0, 0); - const to = new Date(from.getTime()); - to.setDate(to.getDate() + params.scopeDays); - to.setHours(23, 59, 59, 999); - - const expectedParams = { - from, - scopeDays: params.scopeDays, - to - }; - - expect(params).toEqual(expectedParams); - }); - - it('should return default value for scope days', () => { - let params = controller.fetchParams({ - scopeDays: 1 - }); - - expect(params.scopeDays).toEqual(1); - }); - - it('should return the given scope days', () => { - let params = controller.fetchParams({ - scopeDays: 2 - }); - - expect(params.scopeDays).toEqual(2); - }); - }); - - describe('compareDate()', () => { - it('should return warning when the date is the present', () => { - let today = Date.vnNew(); - let result = controller.compareDate(today); - - expect(result).toEqual('warning'); - }); - - it('should return sucess when the date is in the future', () => { - let futureDate = Date.vnNew(); - futureDate = futureDate.setDate(futureDate.getDate() + 10); - let result = controller.compareDate(futureDate); - - expect(result).toEqual('success'); - }); - - it('should return undefined when the date is in the past', () => { - let pastDate = Date.vnNew(); - pastDate = pastDate.setDate(pastDate.getDate() - 10); - let result = controller.compareDate(pastDate); - - expect(result).toEqual(undefined); - }); - }); - - describe('totalPriceColor()', () => { - it('should return "warning" when the ticket amount is less than 50€', () => { - const result = controller.totalPriceColor({totalWithVat: '8.50'}); - - expect(result).toEqual('warning'); - }); - }); - - describe('dateRange()', () => { - it('should return two dates with the hours at the start and end of the given date', () => { - const now = Date.vnNew(); - - const today = now.getDate(); - - const dateRange = controller.dateRange(now); - const start = dateRange[0].toString(); - const end = dateRange[1].toString(); - - expect(start).toContain(today); - expect(start).toContain('00:00:00'); - - expect(end).toContain(today); - expect(end).toContain('23:59:59'); - }); - }); - - describe('preview()', () => { - it('should show the dialog summary', () => { - controller.$.summary = {show: () => {}}; - jest.spyOn(controller.$.summary, 'show'); - - let event = new MouseEvent('click', { - view: $window, - bubbles: true, - cancelable: true - }); - controller.preview(event, tickets[0]); - - expect(controller.$.summary.show).toHaveBeenCalledWith(); - }); - }); -}); diff --git a/modules/monitor/front/index/tickets/style.scss b/modules/monitor/front/index/tickets/style.scss deleted file mode 100644 index 102c92a8a..000000000 --- a/modules/monitor/front/index/tickets/style.scss +++ /dev/null @@ -1,47 +0,0 @@ -@import "variables"; - -vn-monitor-sales-tickets { - @media screen and (max-width: 1440px) { - .expendable { - display: none; - } - } - - vn-th.icon-field, - vn-th.icon-field *, - vn-td.icon-field, - vn-td.icon-field * { - padding: 0; - max-width: 50px - } - - vn-th[field="nickname"], - vn-td[name="nickname"] { - min-width: 250px - } - - vn-td.icon-field > vn-icon { - margin-left: 3px; - margin-right: 3px; - } - - vn-table.scrollable.lg { - height: 736px - } - - tbody tr[ng-repeat]:focus { - background-color: $color-primary-light - } - - .highRisk i { - color: $color-alert - } - - td[name="nickname"] { - max-width: 200px - } - - td[name="zone"] { - max-width: 150px - } -} \ No newline at end of file diff --git a/modules/monitor/front/locale/es.yml b/modules/monitor/front/locale/es.yml index 7d7e72f6b..01b26b70c 100644 --- a/modules/monitor/front/locale/es.yml +++ b/modules/monitor/front/locale/es.yml @@ -1 +1,16 @@ -Sales monitor: Monitor de ventas \ No newline at end of file +Tickets monitor: Monitor de tickets +Clients on website: Clientes activos en la web +Recent order actions: Acciones recientes en pedidos +Search tickets: Buscar tickets +Delete selected elements: Eliminar los elementos seleccionados +All the selected elements will be deleted. Are you sure you want to continue?: Todos los elementos seleccionados serán eliminados. ¿Seguro que quieres continuar? +Component lack: Faltan componentes +Ticket too little: Ticket demasiado pequeño +Minimize/Maximize: Minimizar/Maximizar +Problems: Problemas +Theoretical: Teórica +Practical: Práctica +Preparation: Preparación +Auto-refresh: Auto-refresco +Toggle auto-refresh every 2 minutes: Conmuta el refresco automático cada 2 minutos +Is fragile: Es frágil \ No newline at end of file diff --git a/modules/monitor/front/main/index.html b/modules/monitor/front/main/index.html index 6e04f06d0..e69de29bb 100644 --- a/modules/monitor/front/main/index.html +++ b/modules/monitor/front/main/index.html @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/modules/monitor/front/main/index.js b/modules/monitor/front/main/index.js index 42fc159d5..3af5292cb 100644 --- a/modules/monitor/front/main/index.js +++ b/modules/monitor/front/main/index.js @@ -1,7 +1,16 @@ import ngModule from '../module'; import ModuleMain from 'salix/components/module-main'; -export default class Monitor extends ModuleMain {} +export default class Monitor extends ModuleMain { + constructor($element, $) { + super($element, $); + } + + async $onInit() { + this.$state.go('home'); + window.location.href = await this.vnApp.getUrl(`monitor/`); + } +} ngModule.vnComponent('vnMonitor', { controller: Monitor, diff --git a/modules/monitor/front/routes.json b/modules/monitor/front/routes.json index acad3ecbc..30da8bcac 100644 --- a/modules/monitor/front/routes.json +++ b/modules/monitor/front/routes.json @@ -1,13 +1,9 @@ { "module": "monitor", "name": "Monitors", - "icon" : "grid_view", - "dependencies": ["ticket", "worker", "client"], - "validations" : true, + "icon": "grid_view", "menus": { - "main": [ - {"state": "monitor.index", "icon": "grid_view"} - ], + "main": [], "card": [] }, "keybindings": [ @@ -23,7 +19,7 @@ "abstract": true, "component": "vn-monitor", "description": "Monitors" - }, + }, { "url": "/index?q", "state": "monitor.index", diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 758e8065c..f8df6e10e 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -76,6 +76,7 @@ module.exports = Self => { }); Self.filter = async(ctx, filter, options) => { + const models = Self.app.models; const conn = Self.dataSource.connector; const myOptions = {}; diff --git a/modules/order/front/basic-data/index.html b/modules/order/front/basic-data/index.html deleted file mode 100644 index 019153b0d..000000000 --- a/modules/order/front/basic-data/index.html +++ /dev/null @@ -1,88 +0,0 @@ - - - - - -
- - - - -
{{::name}}
-
#{{::id}}
-
-
- - {{::nickname}} - -
- - - - - - - - - - -
- - - - - - -
diff --git a/modules/order/front/basic-data/index.js b/modules/order/front/basic-data/index.js deleted file mode 100644 index 16a3cea5e..000000000 --- a/modules/order/front/basic-data/index.js +++ /dev/null @@ -1,57 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $) { - super($element, $); - let isDirty = false; - this.$.$watch('$ctrl.selection', newValue => { - if (newValue) { - this.$.addressModel.where = {clientFk: newValue.id}; - this.$.addressModel.refresh(); - if (isDirty) - this.order.addressFk = newValue.defaultAddressFk; - isDirty = true; - } else { - this.$.addressModel.clear(); - if (isDirty) - this.order.addressFk = null; - } - }); - } - - set order(value = {}) { - this._order = value; - - const agencyModeFk = value.agencyModeFk; - this.getAvailableAgencies(); - this._order.agencyModeFk = agencyModeFk; - } - - get order() { - return this._order; - } - - getAvailableAgencies() { - const order = this.order; - order.agencyModeFk = null; - - const params = { - addressFk: order.addressFk, - landed: order.landed - }; - if (params.landed && params.addressFk) { - this.$http.get(`Agencies/landsThatDay`, {params}) - .then(res => this._availableAgencies = res.data); - } - } -} - -ngModule.vnComponent('vnOrderBasicData', { - controller: Controller, - template: require('./index.html'), - bindings: { - order: '<' - } -}); diff --git a/modules/order/front/basic-data/index.spec.js b/modules/order/front/basic-data/index.spec.js deleted file mode 100644 index 21dee0765..000000000 --- a/modules/order/front/basic-data/index.spec.js +++ /dev/null @@ -1,67 +0,0 @@ -import './index.js'; - -describe('Order', () => { - describe('Component vnOrderBasicData', () => { - let $httpBackend; - let $httpParamSerializer; - let controller; - let $scope; - - beforeEach(ngModule('order')); - - beforeEach(inject(($compile, _$httpBackend_, $rootScope, _$httpParamSerializer_) => { - $httpBackend = _$httpBackend_; - $httpParamSerializer = _$httpParamSerializer_; - $scope = $rootScope.$new(); - - $httpBackend.whenRoute('GET', 'Addresses') - .respond([{id: 2, nickname: 'address 2'}]); - $httpBackend.whenRoute('GET', 'Clients') - .respond([{id: 1, defaultAddressFk: 1}]); - $scope.order = {clientFk: 1, addressFk: 1}; - - let $element = $compile('')($scope); - $httpBackend.flush(); - controller = $element.controller('vnOrderBasicData'); - })); - - afterAll(() => { - $scope.$destroy(); - $element.remove(); - }); - - describe('constructor()', () => { - it('should update the address after the client changes', async() => { - const addressId = 999; - const id = 444; - - controller.selection = {id: id, defaultAddressFk: addressId}; - $scope.$digest(); - - expect(controller.order.addressFk).toEqual(addressId); - }); - }); - - describe('getAvailableAgencies()', () => { - it('should set agencyModeFk to null and get the available agencies if the order has landed and client', async() => { - controller.order.agencyModeFk = 999; - controller.order.addressFk = 999; - controller.order.landed = Date.vnNew(); - - const expectedAgencies = [{id: 1}, {id: 2}]; - - const paramsObj = { - addressFk: controller.order.addressFk, - landed: controller.order.landed - }; - const serializedParams = $httpParamSerializer(paramsObj); - $httpBackend.expect('GET', `Agencies/landsThatDay?${serializedParams}`).respond(expectedAgencies); - controller.getAvailableAgencies(); - $httpBackend.flush(); - - expect(controller.order.agencyModeFk).toBeDefined(); - expect(controller._availableAgencies).toEqual(expectedAgencies); - }); - }); - }); -}); diff --git a/modules/order/front/basic-data/locale/es.yml b/modules/order/front/basic-data/locale/es.yml deleted file mode 100644 index 5c6014c9c..000000000 --- a/modules/order/front/basic-data/locale/es.yml +++ /dev/null @@ -1 +0,0 @@ -This form has been disabled because there are lines in this order or it's confirmed: Este formulario ha sido deshabilitado por que esta orden contiene líneas o está confirmada \ No newline at end of file diff --git a/modules/order/front/basic-data/style.scss b/modules/order/front/basic-data/style.scss deleted file mode 100644 index 34d6c2931..000000000 --- a/modules/order/front/basic-data/style.scss +++ /dev/null @@ -1,9 +0,0 @@ -vn-order-basic-data { - .disabledForm { - text-align: center; - color: red; - span { - margin: 0 auto; - } - } -} \ No newline at end of file diff --git a/modules/order/front/card/index.html b/modules/order/front/card/index.html deleted file mode 100644 index 4f10c1728..000000000 --- a/modules/order/front/card/index.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/modules/order/front/card/index.js b/modules/order/front/card/index.js deleted file mode 100644 index a7e5eeb5d..000000000 --- a/modules/order/front/card/index.js +++ /dev/null @@ -1,58 +0,0 @@ -import ngModule from '../module'; -import ModuleCard from 'salix/components/module-card'; - -class Controller extends ModuleCard { - reload() { - let filter = { - include: [ - { - relation: 'agencyMode', - scope: { - fields: ['name'] - } - }, { - relation: 'address', - scope: { - fields: ['nickname'] - } - }, { - relation: 'rows', - scope: { - fields: ['id'] - } - }, { - relation: 'client', - scope: { - fields: [ - 'salesPersonFk', - 'name', - 'isActive', - 'isFreezed', - 'isTaxDataChecked' - ], - include: { - relation: 'salesPersonUser', - scope: { - fields: ['id', 'name'] - } - } - } - } - ] - }; - - return this.$q.all([ - this.$http.get(`Orders/${this.$params.id}`, {filter}) - .then(res => this.order = res.data), - this.$http.get(`Orders/${this.$params.id}/getTotal`) - .then(res => ({total: res.data})) - ]).then(res => { - this.order = Object.assign.apply(null, res); - }); - } -} - -ngModule.vnComponent('vnOrderCard', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/order/front/card/index.spec.js b/modules/order/front/card/index.spec.js deleted file mode 100644 index f0de26b72..000000000 --- a/modules/order/front/card/index.spec.js +++ /dev/null @@ -1,31 +0,0 @@ -import './index.js'; - -describe('Order', () => { - describe('Component vnOrderCard', () => { - let controller; - let $httpBackend; - let data = {id: 1, name: 'fooName'}; - let total = 10.5; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, _$httpBackend_, $stateParams) => { - $httpBackend = _$httpBackend_; - - let $element = angular.element('
'); - controller = $componentController('vnOrderCard', {$element}); - - $stateParams.id = data.id; - $httpBackend.whenRoute('GET', 'Orders/:id').respond(data); - $httpBackend.whenRoute('GET', 'Orders/:id/getTotal').respond(200, total); - })); - - it('should request data and total, merge them, and set it on the controller', () => { - controller.reload(); - $httpBackend.flush(); - - expect(controller.order).toEqual(Object.assign({}, data, {total})); - }); - }); -}); - diff --git a/modules/order/front/catalog-search-panel/index.html b/modules/order/front/catalog-search-panel/index.html deleted file mode 100644 index 42f2e0f50..000000000 --- a/modules/order/front/catalog-search-panel/index.html +++ /dev/null @@ -1,54 +0,0 @@ -
-
- - - - - - - - - - - - - - - - - - - -
-
diff --git a/modules/order/front/catalog-search-panel/index.js b/modules/order/front/catalog-search-panel/index.js deleted file mode 100644 index b84243ca7..000000000 --- a/modules/order/front/catalog-search-panel/index.js +++ /dev/null @@ -1,38 +0,0 @@ -import ngModule from '../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; - -class Controller extends SearchPanel { - constructor($element, $) { - super($element, $); - - this.filter = {}; - } - - get filter() { - return this.$.filter; - } - - set filter(value) { - if (!value) - value = {}; - if (!value.values) - value.values = [{}]; - - this.$.filter = value; - } - - addValue() { - this.filter.values.push({}); - setTimeout(() => this.parentPopover.relocate()); - } -} - -ngModule.vnComponent('vnOrderCatalogSearchPanel', { - template: require('./index.html'), - controller: Controller, - bindings: { - onSubmit: '&?', - parentPopover: ' - -
- -
-
-
-
- -
-
- -

- {{::item.subName}} -

-
- - - - - - -
- - - - - - {{::item.minQuantity}} - - -
-
-
-
- - - - - diff --git a/modules/order/front/catalog-view/index.js b/modules/order/front/catalog-view/index.js deleted file mode 100644 index 6f2cead8f..000000000 --- a/modules/order/front/catalog-view/index.js +++ /dev/null @@ -1,12 +0,0 @@ -import ngModule from '../module'; -import Component from 'core/lib/component'; -import './style.scss'; - -ngModule.vnComponent('vnOrderCatalogView', { - template: require('./index.html'), - controller: Component, - bindings: { - order: '<', - model: '<' - } -}); diff --git a/modules/order/front/catalog-view/locale/es.yml b/modules/order/front/catalog-view/locale/es.yml deleted file mode 100644 index 187dbbc83..000000000 --- a/modules/order/front/catalog-view/locale/es.yml +++ /dev/null @@ -1 +0,0 @@ -Order created: Orden creada \ No newline at end of file diff --git a/modules/order/front/catalog-view/style.scss b/modules/order/front/catalog-view/style.scss deleted file mode 100644 index 1e48745ca..000000000 --- a/modules/order/front/catalog-view/style.scss +++ /dev/null @@ -1,50 +0,0 @@ -@import "variables"; - -vn-order-catalog { - .catalog-header { - border-bottom: $border-thin; - padding: $spacing-md; - align-items: center; - - & > vn-one { - display: flex; - flex: 1; - - span { - color: $color-font-secondary - } - } - & > vn-auto { - width: 448px; - display: flex; - overflow: hidden; - - & > * { - padding-left: $spacing-md; - } - } - } - .catalog-list { - padding-top: $spacing-sm; - } - .item-color-background { - background: linear-gradient($color-bg-panel, $color-main); - border-radius: 50%; - margin-left: 140px; - margin-top: 140px; - width: 40px; - height: 40px; - position: absolute; - } - .item-color { - margin: auto; - margin-top: 5px; - border-radius: 50%; - width: 30px; - height: 30px; - position: relative; - } - .alert { - color: $color-alert; - } -} diff --git a/modules/order/front/catalog/index.html b/modules/order/front/catalog/index.html deleted file mode 100644 index 0f7928c8b..000000000 --- a/modules/order/front/catalog/index.html +++ /dev/null @@ -1,166 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -
{{name}}
-
- {{categoryName}} -
-
-
-
- - - - - -
- More than {{model.limit}} results -
-
- - - - - - - - - - - - - - - -
- - Id: {{$ctrl.itemId}} - - -
- - Name: - - {{$ctrl.itemName}} -
-
- - {{category.selection.name}} - - - {{type.selection.name}} - - -
- - {{::tagGroup.tagSelection.name}}: - - - , - "{{::tagValue.value}}" - -
-
-
-
diff --git a/modules/order/front/catalog/index.js b/modules/order/front/catalog/index.js deleted file mode 100644 index c0777ebc9..000000000 --- a/modules/order/front/catalog/index.js +++ /dev/null @@ -1,377 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $) { - super($element, $); - this.itemTypes = []; - this._tagGroups = []; - - // Static autocomplete data - this.orderWays = [ - {way: 'ASC', name: 'Ascendant'}, - {way: 'DESC', name: 'Descendant'}, - ]; - this.defaultOrderFields = [ - {field: 'relevancy DESC, name', name: 'Relevancy', priority: 999}, - {field: 'showOrder, price', name: 'Color and price', priority: 999}, - {field: 'name', name: 'Name', priority: 999}, - {field: 'price', name: 'Price', priority: 999} - ]; - this.orderFields = [].concat(this.defaultOrderFields); - this._orderWay = this.orderWays[0].way; - this.orderField = this.orderFields[0].field; - } - - $onChanges() { - this.getData().then(() => { - if (this.order && this.order.isConfirmed) - this.$state.go('order.card.line'); - }); - } - - getData() { - return this.$http.get(`Orders/${this.$params.id}`) - .then(res => this.order = res.data); - } - - /** - * Fills order autocomplete with tags - * obtained from last filtered - */ - get order() { - return this._order; - } - - /** - * Sets filter values from state params - * - * @param {Object} value - Order data - */ - set order(value) { - this._order = value; - - if (!value) return; - - this.$.$applyAsync(() => { - if (this.$params.categoryId) - this.categoryId = parseInt(this.$params.categoryId); - - if (this.$params.typeId) - this.typeId = parseInt(this.$params.typeId); - - if (this.$params.tagGroups) - this.tagGroups = JSON.parse(this.$params.tagGroups); - }); - } - - get items() { - return this._items; - } - - set items(value) { - this._items = value; - - if (!value) return; - - this.fetchResultTags(value); - this.buildOrderFilter(); - } - - get categoryId() { - return this._categoryId; - } - - set categoryId(value = null) { - this._categoryId = value; - this.itemTypes = []; - this.typeId = null; - - this.updateStateParams(); - - if (this.tagGroups.length > 0) - this.applyFilters(); - - if (value) - this.updateItemTypes(); - } - - changeCategory(id) { - if (this._categoryId == id) id = null; - this.categoryId = id; - } - - get typeId() { - return this._typeId; - } - - set typeId(value) { - this._typeId = value; - - this.updateStateParams(); - - if (value || this.tagGroups.length > 0) - this.applyFilters(); - } - - get tagGroups() { - return this._tagGroups; - } - - set tagGroups(value) { - this._tagGroups = value; - - this.updateStateParams(); - - if (value.length) - this.applyFilters(); - } - - /** - * Get order way ASC/DESC - */ - get orderWay() { - return this._orderWay; - } - - set orderWay(value) { - this._orderWay = value; - if (value) this.applyOrder(); - } - - /** - * Returns the order way selection - */ - get orderSelection() { - return this._orderSelection; - } - - set orderSelection(value) { - this._orderSelection = value; - - if (value) this.applyOrder(); - } - - /** - * Apply order to model - */ - applyOrder() { - if (this.typeId || this.tagGroups.length > 0 || this.itemName) - this.$.model.addFilter(null, {orderBy: this.getOrderBy()}); - } - - /** - * Returns order param - * - * @return {Object} - Order param - */ - getOrderBy() { - const isTag = !!(this.orderSelection && this.orderSelection.isTag); - return { - field: this.orderField, - way: this.orderWay, - isTag: isTag - }; - } - - /** - * Refreshes item type dropdown data - */ - updateItemTypes() { - let params = { - itemCategoryId: this.categoryId - }; - - const query = `Orders/${this.order.id}/getItemTypeAvailable`; - this.$http.get(query, {params}).then(res => - this.itemTypes = res.data); - } - - /** - * Search by tag value - * @param {object} event - */ - onSearchByTag(event) { - const value = this.$.search.value; - if (event.key !== 'Enter' || !value) return; - this.tagGroups.push({values: [{value: value}]}); - this.$.search.value = null; - this.updateStateParams(); - this.applyFilters(); - } - - remove(index) { - this.tagGroups.splice(index, 1); - this.updateStateParams(); - - if (this.tagGroups.length >= 0 || this.itemId || this.typeId) - this.applyFilters(); - } - - removeItemId() { - this.itemId = null; - this.$.searchbar.doSearch({}, 'bar'); - } - - removeItemName() { - this.itemName = null; - this.$.searchbar.doSearch({}, 'bar'); - } - - applyFilters(filter = {}) { - let newParams = {}; - let newFilter = Object.assign({}, filter); - const model = this.$.model; - - if (this.categoryId) - newFilter.categoryFk = this.categoryId; - - if (this.typeId) - newFilter.typeFk = this.typeId; - - newParams = { - orderFk: this.$params.id, - orderBy: this.getOrderBy(), - tagGroups: this.tagGroups, - }; - - return model.applyFilter({where: newFilter}, newParams); - } - - openPanel(event) { - if (event.defaultPrevented) return; - event.preventDefault(); - - this.panelFilter = {}; - this.$.popover.show(this.$.search.element); - } - - onPanelSubmit(filter) { - this.$.popover.hide(); - const values = filter.values; - const nonEmptyValues = values.filter(tagValue => { - return tagValue.value; - }); - - filter.values = nonEmptyValues; - - if (filter.tagFk && nonEmptyValues.length) { - this.tagGroups.push(filter); - this.updateStateParams(); - this.applyFilters(); - } - } - - /** - * Updates url state params from filter values - */ - updateStateParams() { - const params = {}; - - params.categoryId = undefined; - if (this.categoryId) - params.categoryId = this.categoryId; - - params.typeId = undefined; - if (this.typeId) - params.typeId = this.typeId; - - params.tagGroups = undefined; - if (this.tagGroups && this.tagGroups.length) - params.tagGroups = JSON.stringify(this.sanitizedTagGroupParam()); - - this.$state.go(this.$state.current.name, params); - } - - sanitizedTagGroupParam() { - const tagGroups = []; - for (let tagGroup of this.tagGroups) { - const tagParam = {values: []}; - - for (let tagValue of tagGroup.values) - tagParam.values.push({value: tagValue.value}); - - if (tagGroup.tagFk) - tagParam.tagFk = tagGroup.tagFk; - - if (tagGroup.tagSelection) { - tagParam.tagSelection = { - name: tagGroup.tagSelection.name - }; - } - - tagGroups.push(tagParam); - } - - return tagGroups; - } - - fetchResultTags(items) { - const resultTags = []; - for (let item of items) { - for (let itemTag of item.tags) { - const alreadyAdded = resultTags.findIndex(tag => { - return tag.tagFk == itemTag.tagFk; - }); - - if (alreadyAdded == -1) - resultTags.push({...itemTag, priority: 1}); - else - resultTags[alreadyAdded].priority += 1; - } - } - this.resultTags = resultTags; - } - - buildOrderFilter() { - const filter = [].concat(this.defaultOrderFields); - for (let tag of this.resultTags) - filter.push({...tag, field: tag.id, isTag: true}); - - this.orderFields = filter; - } - - onSearch(params) { - if (!params) return; - - this.itemId = null; - this.itemName = null; - - if (params.search) { - if (/^\d+$/.test(params.search)) { - this.itemId = params.search; - return this.applyFilters({ - 'i.id': params.search - }); - } else { - this.itemName = params.search; - return this.applyFilters({ - 'i.name': {like: `%${params.search}%`} - }); - } - } else return this.applyFilters(); - } - - formatTooltip(tagGroup) { - const tagValues = tagGroup.values; - - let title = ''; - if (tagGroup.tagFk) { - const tagName = tagGroup.tagSelection.name; - title += `${tagName}: `; - } - - for (let [i, tagValue] of tagValues.entries()) { - if (i > 0) title += ', '; - title += `"${tagValue.value}"`; - } - - return `${title}`; - } -} - -ngModule.vnComponent('vnOrderCatalog', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/order/front/catalog/index.spec.js b/modules/order/front/catalog/index.spec.js deleted file mode 100644 index 03d7c41ba..000000000 --- a/modules/order/front/catalog/index.spec.js +++ /dev/null @@ -1,386 +0,0 @@ -import './index.js'; -import crudModel from 'core/mocks/crud-model'; - -describe('Order', () => { - describe('Component vnOrderCatalog', () => { - let $scope; - let $state; - let controller; - let $httpBackend; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, _$state_, _$httpBackend_, $rootScope) => { - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - $scope.model = crudModel; - $scope.search = {}; - $scope.itemId = {}; - $state = _$state_; - $state.current.name = 'my.current.state'; - const $element = angular.element(''); - controller = $componentController('vnOrderCatalog', {$element, $scope}); - controller._order = {id: 4}; - controller.$params = { - categoryId: 1, - typeId: 2, - id: 4 - }; - })); - - describe('getData()', () => { - it(`should make a query an fetch the order data`, () => { - controller._order = null; - - $httpBackend.expect('GET', `Orders/4`).respond(200, {id: 4, isConfirmed: true}); - $httpBackend.expect('GET', `Orders/4/getItemTypeAvailable?itemCategoryId=1`).respond(); - controller.getData(); - $httpBackend.flush(); - - const order = controller.order; - - expect(order.id).toEqual(4); - expect(order.isConfirmed).toBeTruthy(); - }); - }); - - describe('order() setter', () => { - it(`should call scope $applyAsync() method and apply filters from state params`, () => { - $httpBackend.expect('GET', `Orders/4/getItemTypeAvailable?itemCategoryId=1`).respond(); - controller.order = {id: 4}; - - $scope.$apply(); - - expect(controller.categoryId).toEqual(1); - expect(controller.typeId).toEqual(2); - }); - }); - - describe('items() setter', () => { - it(`should return an object with order params`, () => { - jest.spyOn(controller, 'fetchResultTags'); - jest.spyOn(controller, 'buildOrderFilter'); - - const expectedResult = [{field: 'showOrder, price', name: 'Color and price', priority: 999}]; - const items = [{id: 1, name: 'My Item', tags: [ - {tagFk: 4, name: 'Length'}, - {tagFk: 5, name: 'Color'} - ]}]; - controller.items = items; - - expect(controller.orderFields.length).toEqual(6); - expect(controller.orderFields).toEqual(jasmine.arrayContaining(expectedResult)); - expect(controller.fetchResultTags).toHaveBeenCalledWith(items); - expect(controller.buildOrderFilter).toHaveBeenCalledWith(); - }); - }); - - describe('categoryId() setter', () => { - it(`should set category property to null, call updateStateParams() method and not call applyFilters()`, () => { - jest.spyOn(controller, 'updateStateParams'); - - controller.categoryId = null; - - expect(controller.updateStateParams).toHaveBeenCalledWith(); - }); - - it(`should set category property and then call updateStateParams() and applyFilters() methods`, () => { - jest.spyOn(controller, 'updateStateParams'); - - controller.categoryId = 2; - - expect(controller.updateStateParams).toHaveBeenCalledWith(); - }); - }); - - describe('changeCategory()', () => { - it(`should set categoryId property to null if the new value equals to the old one`, () => { - controller.categoryId = 2; - controller.changeCategory(2); - - expect(controller.categoryId).toBeNull(); - }); - - it(`should set categoryId property`, () => { - controller.categoryId = 2; - controller.changeCategory(1); - - expect(controller.categoryId).toEqual(1); - }); - }); - - describe('typeId() setter', () => { - it(`should set type property to null, call updateStateParams() method and not call applyFilters()`, () => { - jest.spyOn(controller, 'updateStateParams'); - jest.spyOn(controller, 'applyFilters'); - - controller.typeId = null; - - expect(controller.updateStateParams).toHaveBeenCalledWith(); - expect(controller.applyFilters).not.toHaveBeenCalledWith(); - }); - - it(`should set category property and then call updateStateParams() and applyFilters() methods`, () => { - jest.spyOn(controller, 'updateStateParams'); - jest.spyOn(controller, 'applyFilters'); - - controller.typeId = 2; - - expect(controller.updateStateParams).toHaveBeenCalledWith(); - expect(controller.applyFilters).toHaveBeenCalledWith(); - }); - }); - - describe('tagGroups() setter', () => { - it(`should set tagGroups property and then call updateStateParams() and applyFilters() methods`, () => { - jest.spyOn(controller, 'updateStateParams'); - jest.spyOn(controller, 'applyFilters'); - - controller.tagGroups = [{tagFk: 11, values: [{value: 'Brown'}]}]; - - expect(controller.updateStateParams).toHaveBeenCalledWith(); - expect(controller.applyFilters).toHaveBeenCalledWith(); - }); - }); - - describe('onSearchByTag()', () => { - it(`should not add a new tag if the event key code doesn't equals to 'Enter'`, () => { - jest.spyOn(controller, 'applyFilters'); - - controller.order = {id: 4}; - controller.$.search.value = 'Brown'; - controller.onSearchByTag({key: 'Tab'}); - - expect(controller.applyFilters).not.toHaveBeenCalledWith(); - }); - - it(`should add a new tag if the event key code equals to 'Enter' an then call applyFilters()`, () => { - jest.spyOn(controller, 'applyFilters'); - - controller.order = {id: 4}; - controller.$.search.value = 'Brown'; - controller.onSearchByTag({key: 'Enter'}); - - expect(controller.applyFilters).toHaveBeenCalledWith(); - }); - }); - - describe('onSearch()', () => { - it(`should apply a filter by item id an then call the applyFilters method`, () => { - jest.spyOn(controller, 'applyFilters'); - - const itemId = 1; - controller.onSearch({search: itemId}); - - expect(controller.applyFilters).toHaveBeenCalledWith({ - 'i.id': itemId - }); - }); - - it(`should apply a filter by item name an then call the applyFilters method`, () => { - jest.spyOn(controller, 'applyFilters'); - - const itemName = 'Bow'; - controller.onSearch({search: itemName}); - - expect(controller.applyFilters).toHaveBeenCalledWith({ - 'i.name': {like: `%${itemName}%`} - }); - }); - }); - - describe('applyFilters()', () => { - it(`should call model applyFilter() method with a new filter`, () => { - jest.spyOn(controller.$.model, 'applyFilter'); - - controller._categoryId = 2; - controller._typeId = 4; - - controller.applyFilters(); - - expect(controller.$.model.applyFilter).toHaveBeenCalledWith( - {where: {categoryFk: 2, typeFk: 4}}, - {orderFk: 4, orderBy: controller.getOrderBy(), tagGroups: []}); - }); - }); - - describe('remove()', () => { - it(`should remove a tag from tags property`, () => { - jest.spyOn(controller, 'applyFilters'); - - controller.tagGroups = [ - {tagFk: 1, values: [{value: 'Brown'}]}, - {tagFk: 67, values: [{value: 'Concussion'}]} - ]; - controller.remove(0); - - const firstTag = controller.tagGroups[0]; - - expect(controller.tagGroups.length).toEqual(1); - expect(firstTag.tagFk).toEqual(67); - expect(controller.applyFilters).toHaveBeenCalledWith(); - }); - - it(`should remove a tag from tags property and call applyFilters() if there's no more tags`, () => { - jest.spyOn(controller, 'applyFilters'); - - controller._categoryId = 1; - controller._typeId = 1; - controller.tagGroups = [{tagFk: 1, values: [{value: 'Blue'}]}]; - controller.remove(0); - - expect(controller.tagGroups.length).toEqual(0); - expect(controller.applyFilters).toHaveBeenCalledWith(); - }); - }); - - describe('updateStateParams()', () => { - it(`should call state go() method passing category and type state params`, () => { - jest.spyOn(controller.$state, 'go'); - - controller._categoryId = 2; - controller._typeId = 4; - controller._tagGroups = [ - {tagFk: 67, values: [{value: 'Concussion'}], tagSelection: {name: 'Category'}} - ]; - const tagGroups = JSON.stringify([ - {values: [{value: 'Concussion'}], tagFk: 67, tagSelection: {name: 'Category'}} - ]); - const expectedResult = {categoryId: 2, typeId: 4, tagGroups: tagGroups}; - controller.updateStateParams(); - - expect(controller.$state.go).toHaveBeenCalledWith('my.current.state', expectedResult); - }); - }); - - describe('getOrderBy()', () => { - it(`should return an object with order params`, () => { - controller.orderField = 'relevancy DESC, name'; - controller.orderWay = 'DESC'; - let expectedResult = { - field: 'relevancy DESC, name', - way: 'DESC', - isTag: false - }; - let result = controller.getOrderBy(); - - expect(result).toEqual(expectedResult); - }); - }); - - describe('applyOrder()', () => { - it(`should apply order param to model calling getOrderBy()`, () => { - jest.spyOn(controller, 'getOrderBy'); - jest.spyOn(controller.$.model, 'addFilter'); - - controller.field = 'relevancy DESC, name'; - controller.way = 'ASC'; - controller._categoryId = 1; - controller._typeId = 1; - let expectedOrder = {orderBy: controller.getOrderBy()}; - - controller.applyOrder(); - - expect(controller.getOrderBy).toHaveBeenCalledWith(); - expect(controller.$.model.addFilter).toHaveBeenCalledWith(null, expectedOrder); - }); - }); - - describe('fetchResultTags()', () => { - it(`should create an array of non repeated tags then set the resultTags property`, () => { - const items = [ - { - id: 1, name: 'My Item 1', tags: [ - {tagFk: 4, name: 'Length', value: 1}, - {tagFk: 5, name: 'Color', value: 'red'} - ] - }, - { - id: 2, name: 'My Item 2', tags: [ - {tagFk: 4, name: 'Length', value: 1}, - {tagFk: 5, name: 'Color', value: 'blue'} - ] - }]; - controller.fetchResultTags(items); - - expect(controller.resultTags.length).toEqual(2); - }); - }); - - describe('buildOrderFilter()', () => { - it(`should create an array of non repeated tags plus default filters and then set the orderFields property`, () => { - const items = [ - { - id: 1, name: 'My Item 1', tags: [ - {tagFk: 4, name: 'Length'}, - {tagFk: 5, name: 'Color'} - ] - }, - { - id: 2, name: 'My Item 2', tags: [ - {tagFk: 5, name: 'Color'}, - {tagFk: 6, name: 'Relevancy'} - ] - }]; - - controller.fetchResultTags(items); - controller.buildOrderFilter(); - - expect(controller.orderFields.length).toEqual(7); - }); - }); - - describe('formatTooltip()', () => { - it(`should return a formatted text with the tag name and values`, () => { - const tagGroup = { - values: [{value: 'Silver'}, {value: 'Brown'}], - tagFk: 1, - tagSelection: { - name: 'Color' - } - }; - - const result = controller.formatTooltip(tagGroup); - - expect(result).toEqual(`Color: "Silver", "Brown"`); - }); - - it(`should return a formatted text with the tag value`, () => { - const tagGroup = { - values: [{value: 'Silver'}] - }; - - const result = controller.formatTooltip(tagGroup); - - expect(result).toEqual(`"Silver"`); - }); - }); - - describe('sanitizedTagGroupParam()', () => { - it(`should return an array of tags`, () => { - const dirtyTagGroups = [{ - values: [{value: 'Silver'}, {value: 'Brown'}], - tagFk: 1, - tagSelection: { - name: 'Color', - $orgRow: {name: 'Color'} - }, - $orgIndex: 1 - }]; - controller.tagGroups = dirtyTagGroups; - - const expectedResult = [{ - values: [{value: 'Silver'}, {value: 'Brown'}], - tagFk: 1, - tagSelection: { - name: 'Color' - } - }]; - const result = controller.sanitizedTagGroupParam(); - - expect(result).toEqual(expect.objectContaining(expectedResult)); - }); - }); - }); -}); - diff --git a/modules/order/front/catalog/locale/es.yml b/modules/order/front/catalog/locale/es.yml deleted file mode 100644 index fc78755ae..000000000 --- a/modules/order/front/catalog/locale/es.yml +++ /dev/null @@ -1,3 +0,0 @@ -Name: Nombre -Search by item id or name: Buscar por id de artículo o nombre -OR: O \ No newline at end of file diff --git a/modules/order/front/catalog/style.scss b/modules/order/front/catalog/style.scss deleted file mode 100644 index 9ffe81dfb..000000000 --- a/modules/order/front/catalog/style.scss +++ /dev/null @@ -1,54 +0,0 @@ -@import "variables"; - -vn-order-catalog vn-side-menu div { - & > .input { - padding-left: $spacing-md; - padding-right: $spacing-md; - border-color: $color-spacer; - border-bottom: $border-thin; - } - .item-category { - padding: $spacing-sm; - justify-content: flex-start; - align-items: flex-start; - flex-wrap: wrap; - - vn-autocomplete[vn-id="category"] { - display: none - } - - & > vn-one { - padding: $spacing-sm; - min-width: 33.33%; - text-align: center; - box-sizing: border-box; - - & > vn-icon { - padding: $spacing-sm; - background-color: $color-font-secondary; - border-radius: 50%; - cursor: pointer; - - &.active { - background-color: $color-main; - color: #FFF - } - & > i:before { - font-size: 2.6rem; - width: 16px; - height: 16px; - } - } - } - } - .chips { - display: flex; - flex-wrap: wrap; - padding: $spacing-md; - overflow: hidden; - max-width: 100%; - } - vn-autocomplete[vn-id="type"] .list { - max-height: 320px - } -} \ No newline at end of file diff --git a/modules/order/front/create/card.html b/modules/order/front/create/card.html deleted file mode 100644 index ed6f752d3..000000000 --- a/modules/order/front/create/card.html +++ /dev/null @@ -1,38 +0,0 @@ - - {{id}}: {{name}} - - - {{nickname}}: {{street}}, {{city}} - - - - - diff --git a/modules/order/front/create/card.js b/modules/order/front/create/card.js deleted file mode 100644 index 315cc8255..000000000 --- a/modules/order/front/create/card.js +++ /dev/null @@ -1,114 +0,0 @@ -import ngModule from '../module'; -import Component from 'core/lib/component'; - -class Controller extends Component { - constructor($element, $) { - super($element, $); - this.order = {}; - this.clientFk = this.$params.clientFk; - } - - $onInit() { - if (this.$params && this.$params.clientFk) - this.clientFk = this.$params.clientFk; - } - - set order(value) { - if (value) - this._order = value; - } - - get order() { - return this._order; - } - - set clientFk(value) { - this.order.clientFk = value; - - if (value) { - let filter = { - include: { - relation: 'defaultAddress', - scope: { - fields: 'id' - } - }, - where: {id: value} - }; - filter = encodeURIComponent(JSON.stringify(filter)); - let query = `Clients?filter=${filter}`; - this.$http.get(query).then(res => { - if (res.data) { - let client = res.data[0]; - let defaultAddress = client.defaultAddress; - this.addressFk = defaultAddress.id; - } - }); - } else - this.addressFk = null; - } - - get clientFk() { - return this.order.clientFk; - } - - set addressFk(value) { - this.order.addressFk = value; - this.getAvailableAgencies(); - } - - get addressFk() { - return this.order.addressFk; - } - - set landed(value) { - this.order.landed = value; - this.getAvailableAgencies(); - } - - get landed() { - return this.order.landed; - } - - get warehouseFk() { - return this.order.warehouseFk; - } - - getAvailableAgencies() { - let order = this.order; - order.agencyModeFk = null; - - let params = { - addressFk: order.addressFk, - landed: order.landed - }; - if (params.landed && params.addressFk) { - this.$http.get(`Agencies/landsThatDay`, {params}) - .then(res => this._availableAgencies = res.data); - } - } - - onSubmit() { - this.createOrder(); - } - - createOrder() { - let params = { - landed: this.order.landed, - addressId: this.order.addressFk, - agencyModeId: this.order.agencyModeFk - }; - this.$http.post(`Orders/new`, params).then(res => { - this.vnApp.showSuccess(this.$t('Data saved!')); - this.$state.go('order.card.catalog', {id: res.data}); - }); - } -} - -ngModule.vnComponent('vnOrderCreateCard', { - template: require('./card.html'), - controller: Controller, - bindings: { - order: ' { - describe('Component vnOrderCreateCard', () => { - let controller; - let $httpBackend; - let $scope; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, _$httpBackend_, _vnApp_, $rootScope) => { - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - const $element = angular.element(''); - controller = $componentController('vnOrderCreateCard', {$element, $scope}); - controller.item = {id: 3}; - })); - - describe('set order', () => { - it(`should set order if the value given is not null`, () => { - controller.order = 1; - - expect(controller.order).toEqual(1); - }); - }); - - describe('set clientFk', () => { - it(`should set addressFk to null and clientFk to a value and set addressFk to a value given`, () => { - let filter = { - include: { - relation: 'defaultAddress', - scope: { - fields: 'id' - } - }, - where: {id: 2} - }; - filter = encodeURIComponent(JSON.stringify(filter)); - let response = [ - { - defaultAddress: {id: 1} - } - ]; - $httpBackend.whenGET(`Clients?filter=${filter}`).respond(response); - $httpBackend.expectGET(`Clients?filter=${filter}`); - - controller.clientFk = 2; - $httpBackend.flush(); - - expect(controller.clientFk).toEqual(2); - expect(controller.order.addressFk).toBe(1); - }); - }); - - describe('set addressFk', () => { - it(`should set agencyModeFk property to null and addressFk to a value`, () => { - controller.addressFk = 1101; - - expect(controller.addressFk).toEqual(1101); - expect(controller.order.agencyModeFk).toBe(null); - }); - }); - - describe('getAvailableAgencies()', () => { - it(`should make a query if landed and addressFk exists`, () => { - controller.order.addressFk = 1101; - controller.order.landed = 1101; - - $httpBackend.whenRoute('GET', 'Agencies/landsThatDay') - .respond({data: 1}); - - controller.getAvailableAgencies(); - $httpBackend.flush(); - }); - }); - - describe('onSubmit()', () => { - it(`should call createOrder()`, () => { - jest.spyOn(controller, 'createOrder'); - controller.onSubmit(); - - expect(controller.createOrder).toHaveBeenCalledWith(); - }); - }); - - describe('createOrder()', () => { - it(`should make a query, call vnApp.showSuccess and $state.go if the response is defined`, () => { - controller.order.landed = 1101; - controller.order.addressFk = 1101; - controller.order.agencyModeFk = 1101; - - jest.spyOn(controller.vnApp, 'showSuccess'); - jest.spyOn(controller.$state, 'go'); - $httpBackend.expect('POST', 'Orders/new', {landed: 1101, addressId: 1101, agencyModeId: 1101}).respond(200, 1); - controller.createOrder(); - $httpBackend.flush(); - - expect(controller.vnApp.showSuccess).toHaveBeenCalled(); - expect(controller.$state.go).toHaveBeenCalledWith('order.card.catalog', {id: 1}); - }); - }); - }); -}); - diff --git a/modules/order/front/create/index.html b/modules/order/front/create/index.html deleted file mode 100644 index 86df579a6..000000000 --- a/modules/order/front/create/index.html +++ /dev/null @@ -1,16 +0,0 @@ -
- - - - - - - - - -
\ No newline at end of file diff --git a/modules/order/front/create/index.js b/modules/order/front/create/index.js deleted file mode 100644 index 317c4e27e..000000000 --- a/modules/order/front/create/index.js +++ /dev/null @@ -1,14 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -class Controller extends Section { - async onSubmit() { - let newOrderID = await this.$.card.createOrder(); - this.$state.go('order.card.summary', {id: newOrderID}); - } -} - -ngModule.vnComponent('vnOrderCreate', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/order/front/create/index.spec.js b/modules/order/front/create/index.spec.js deleted file mode 100644 index af8c8f974..000000000 --- a/modules/order/front/create/index.spec.js +++ /dev/null @@ -1,34 +0,0 @@ -import './index.js'; - -describe('Order', () => { - describe('Component vnOrderCreate', () => { - let $scope; - let controller; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, $rootScope) => { - $scope = $rootScope.$new(); - $scope.card = {createOrder: () => {}}; - const $element = angular.element(''); - controller = $componentController('vnOrderCreate', {$element, $scope}); - })); - - describe('onSubmit()', () => { - it(`should call createOrder()`, () => { - jest.spyOn(controller.$.card, 'createOrder'); - controller.onSubmit(); - - expect(controller.$.card.createOrder).toHaveBeenCalledWith(); - }); - - it(`should call go()`, async() => { - jest.spyOn(controller.$state, 'go'); - await controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('order.card.summary', {id: undefined}); - }); - }); - }); -}); - diff --git a/modules/order/front/create/locale/es.yml b/modules/order/front/create/locale/es.yml deleted file mode 100644 index 49cd64c4a..000000000 --- a/modules/order/front/create/locale/es.yml +++ /dev/null @@ -1,6 +0,0 @@ -You can't create an order for a frozen client: No puedes crear una orden a un cliente congelado -You can't create an order for an inactive client: No puedes crear una orden a un cliente inactivo -You can't create an order for a client that doesn't has tax data verified: - No puedes crear una orden a un cliente cuyos datos fiscales no han sido verificados -You can't create an order for a client that has a debt: No puedes crear una orden a un cliente que tiene deuda -New order: Nueva orden \ No newline at end of file diff --git a/modules/order/front/descriptor/index.html b/modules/order/front/descriptor/index.html deleted file mode 100644 index 538789027..000000000 --- a/modules/order/front/descriptor/index.html +++ /dev/null @@ -1,78 +0,0 @@ - - - - Delete order - - - -
- - - - - {{$ctrl.order.client.salesPersonUser.name}} - - - - - - - - - - - - -
- -
-
- - - - - - - \ No newline at end of file diff --git a/modules/order/front/descriptor/index.js b/modules/order/front/descriptor/index.js deleted file mode 100644 index 5d22dd721..000000000 --- a/modules/order/front/descriptor/index.js +++ /dev/null @@ -1,32 +0,0 @@ -import ngModule from '../module'; -import Descriptor from 'salix/components/descriptor'; - -class Controller extends Descriptor { - get order() { - return this.entity; - } - - set order(value) { - this.entity = value; - } - - get ticketFilter() { - return JSON.stringify({orderFk: this.id}); - } - - deleteOrder() { - return this.$http.delete(`Orders/${this.id}`) - .then(() => { - this.$state.go('order.index'); - this.vnApp.showSuccess(this.$t('Order deleted')); - }); - } -} - -ngModule.vnComponent('vnOrderDescriptor', { - template: require('./index.html'), - controller: Controller, - bindings: { - order: '<' - } -}); diff --git a/modules/order/front/descriptor/index.spec.js b/modules/order/front/descriptor/index.spec.js deleted file mode 100644 index e6147faee..000000000 --- a/modules/order/front/descriptor/index.spec.js +++ /dev/null @@ -1,29 +0,0 @@ -import './index.js'; - -describe('Order Component vnOrderDescriptor', () => { - let $httpBackend; - let controller; - const order = {id: 1}; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - controller = $componentController('vnOrderDescriptor', {$element: null}, {order}); - })); - - describe('deleteOrder()', () => { - it(`should perform a DELETE query`, () => { - jest.spyOn(controller.vnApp, 'showSuccess'); - jest.spyOn(controller.$state, 'go'); - - $httpBackend.expectDELETE(`Orders/${order.id}`).respond(); - controller.deleteOrder(); - $httpBackend.flush(); - - expect(controller.vnApp.showSuccess).toHaveBeenCalled(); - expect(controller.$state.go).toHaveBeenCalledWith('order.index'); - }); - }); -}); - diff --git a/modules/order/front/descriptor/locale/es.yml b/modules/order/front/descriptor/locale/es.yml deleted file mode 100644 index 0734d7638..000000000 --- a/modules/order/front/descriptor/locale/es.yml +++ /dev/null @@ -1,12 +0,0 @@ -Client: Cliente -Confirmed: Confirmado -Not confirmed: Sin confirmar -State: Estado -Landed: F. entrega -Items: Articulos -Agency: Agencia -Sales person: Comercial -Order ticket list: Ticket del pedido -Delete order: Eliminar pedido -You are going to delete this order: El pedido se eliminará -continue anyway?: ¿Continuar de todos modos? \ No newline at end of file diff --git a/modules/order/front/index.js b/modules/order/front/index.js index 4d5b5615e..a7209a0bd 100644 --- a/modules/order/front/index.js +++ b/modules/order/front/index.js @@ -1,17 +1,3 @@ export * from './module'; import './main'; -import './index/'; -import './card'; -import './descriptor'; -import './search-panel'; -import './catalog-search-panel'; -import './catalog-view'; -import './catalog'; -import './summary'; -import './line'; -import './prices-popover'; -import './volume'; -import './create'; -import './create/card'; -import './basic-data'; diff --git a/modules/order/front/index/index.html b/modules/order/front/index/index.html deleted file mode 100644 index c4bed7307..000000000 --- a/modules/order/front/index/index.html +++ /dev/null @@ -1,90 +0,0 @@ - - - - - - - - - Id - Sales person - Client - Confirmed - Created - Landed - Hour - Agency - Total - - - - - {{::order.id}} - - - {{::order.name | dashIfEmpty}} - - - - - {{::order.clientName}} - - - - - - - {{::order.created | date: 'dd/MM/yyyy HH:mm'}} - - - {{::order.landed | date:'dd/MM/yyyy'}} - - - {{::(order.hourTheoretical - ? order.hourTheoretical - : order.hourEffective) | dashIfEmpty - }} - {{::order.agencyName}} - {{::order.total | currency: 'EUR': 2 | dashIfEmpty}} - - - - - - - - - - - - - - - - - - - - diff --git a/modules/order/front/index/index.js b/modules/order/front/index/index.js deleted file mode 100644 index 750f2e226..000000000 --- a/modules/order/front/index/index.js +++ /dev/null @@ -1,26 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - preview(order) { - this.selectedOrder = order; - this.$.summary.show(); - } - - compareDate(date) { - let today = Date.vnNew(); - today.setHours(0, 0, 0, 0); - - date = new Date(date); - date.setHours(0, 0, 0, 0); - - const timeDifference = today - date; - if (timeDifference == 0) return 'warning'; - if (timeDifference < 0) return 'success'; - } -} - -ngModule.vnComponent('vnOrderIndex', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/order/front/index/index.spec.js b/modules/order/front/index/index.spec.js deleted file mode 100644 index abe336478..000000000 --- a/modules/order/front/index/index.spec.js +++ /dev/null @@ -1,67 +0,0 @@ -import './index.js'; -describe('Component vnOrderIndex', () => { - let controller; - let $window; - let orders = [{ - id: 1, - clientFk: 1, - isConfirmed: false - }, { - id: 2, - clientFk: 1, - isConfirmed: false - }, { - id: 3, - clientFk: 1, - isConfirmed: true - }]; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, _$window_) => { - $window = _$window_; - const $element = angular.element(''); - controller = $componentController('vnOrderIndex', {$element}); - })); - - describe('compareDate()', () => { - it('should return warning when the date is the present', () => { - let curDate = Date.vnNew(); - let result = controller.compareDate(curDate); - - expect(result).toEqual('warning'); - }); - - it('should return sucess when the date is in the future', () => { - let futureDate = Date.vnNew(); - futureDate = futureDate.setDate(futureDate.getDate() + 10); - let result = controller.compareDate(futureDate); - - expect(result).toEqual('success'); - }); - - it('should return undefined when the date is in the past', () => { - let pastDate = Date.vnNew(); - pastDate = pastDate.setDate(pastDate.getDate() - 10); - let result = controller.compareDate(pastDate); - - expect(result).toEqual(undefined); - }); - }); - - describe('preview()', () => { - it('should show the dialog summary', () => { - controller.$.summary = {show: () => {}}; - jest.spyOn(controller.$.summary, 'show'); - - let event = new MouseEvent('click', { - view: $window, - bubbles: true, - cancelable: true - }); - controller.preview(event, orders[0]); - - expect(controller.$.summary.show).toHaveBeenCalledWith(); - }); - }); -}); diff --git a/modules/order/front/line/index.html b/modules/order/front/line/index.html deleted file mode 100644 index 7be5a00af..000000000 --- a/modules/order/front/line/index.html +++ /dev/null @@ -1,96 +0,0 @@ - - -
- Subtotal - {{$ctrl.subtotal | currency: 'EUR':2}} -
-
- VAT - {{$ctrl.VAT | currency: 'EUR':2}} -
-
- Total - {{$ctrl.order.total | currency: 'EUR':2}} -
-
- - - - - - Id - Description - Warehouse - Shipped - Quantity - Price - Amount - - - - - - - - - - - {{::row.itemFk}} - - - -
- {{::row.item.name}} - -

{{::row.item.subName}}

-
-
- - -
- {{::row.warehouse.name}} - {{::row.shipped | date: 'dd/MM/yyyy'}} - {{::row.quantity}} - - {{::row.price | currency: 'EUR':2}} - - - {{::row.price * row.quantity | currency: 'EUR':2}} - - - - - -
-
-
-
-
- - - - - - \ No newline at end of file diff --git a/modules/order/front/line/index.js b/modules/order/front/line/index.js deleted file mode 100644 index 94d1fbfbf..000000000 --- a/modules/order/front/line/index.js +++ /dev/null @@ -1,70 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - $onInit() { - this.getRows(); - } - - set order(value) { - this._order = value; - this.getVAT(); - } - - get order() { - return this._order; - } - - get subtotal() { - return this.order ? this.order.total - this.VAT : 0; - } - - getRows() { - let filter = { - where: {orderFk: this.$params.id}, - include: [ - {relation: 'item'}, - {relation: 'warehouse'} - ] - }; - this.$http.get(`OrderRows`, {filter}) - .then(res => this.rows = res.data); - } - - getVAT() { - this.$http.get(`Orders/${this.$params.id}/getVAT`) - .then(res => this.VAT = res.data); - } - - deleteRow(index) { - let [row] = this.rows.splice(index, 1); - let params = { - rows: [row.id], - actualOrderId: this.$params.id - }; - return this.$http.post(`OrderRows/removes`, params) - .then(() => this.card.reload()) - .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))); - } - - save() { - this.$http.post(`Orders/${this.$params.id}/confirm`).then(() => { - this.vnApp.showSuccess(this.$t('Order confirmed')); - this.$state.go(`ticket.index`, { - q: JSON.stringify({clientFk: this.order.clientFk}) - }); - }); - } -} - -ngModule.vnComponent('vnOrderLine', { - template: require('./index.html'), - controller: Controller, - bindings: { - order: '<' - }, - require: { - card: '^vnOrderCard' - } -}); diff --git a/modules/order/front/line/index.spec.js b/modules/order/front/line/index.spec.js deleted file mode 100644 index ad0e1edbc..000000000 --- a/modules/order/front/line/index.spec.js +++ /dev/null @@ -1,66 +0,0 @@ -import './index.js'; - -describe('Order', () => { - describe('Component vnOrderLine', () => { - let $state; - let controller; - let $httpBackend; - - const vat = 10.5; - const rows = [ - { - quantity: 4, - price: 10.5 - }, { - quantity: 3, - price: 2.4 - } - ]; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, _$state_, _$httpBackend_) => { - $state = _$state_; - $httpBackend = _$httpBackend_; - - $state.params.id = 1; - $httpBackend.whenGET(`OrderRows`).respond(rows); - $httpBackend.whenRoute('GET', `Orders/:id/getVAT`).respond(200, vat); - - controller = $componentController('vnOrderLine', {$element: null}); - })); - - describe('getRows()', () => { - it('should make a query to get the rows of a given order', () => { - controller.getRows(); - $httpBackend.flush(); - - expect(controller.rows).toEqual(rows); - }); - }); - - describe('getVAT()', () => { - it('should make a query to get the VAT of a given order', () => { - controller.getVAT(); - $httpBackend.flush(); - - expect(controller.VAT).toBe(vat); - }); - }); - - describe('deleteRow()', () => { - it('should remove a row from rows and add save the data if the response is accept', () => { - controller.getRows(); - $httpBackend.flush(); - - controller.card = {reload: jasmine.createSpy('reload')}; - $httpBackend.expectPOST(`OrderRows/removes`).respond(); - controller.deleteRow(0); - $httpBackend.flush(); - - expect(controller.rows.length).toBe(1); - expect(controller.card.reload).toHaveBeenCalled(); - }); - }); - }); -}); diff --git a/modules/order/front/line/locale/es.yml b/modules/order/front/line/locale/es.yml deleted file mode 100644 index d1368d369..000000000 --- a/modules/order/front/line/locale/es.yml +++ /dev/null @@ -1,3 +0,0 @@ -Delete row: Eliminar linea -Order confirmed: Pedido confirmado -Are you sure you want to delete this row?: ¿Estas seguro de que quieres eliminar esta línea? \ No newline at end of file diff --git a/modules/order/front/line/style.scss b/modules/order/front/line/style.scss deleted file mode 100644 index 4da941a2c..000000000 --- a/modules/order/front/line/style.scss +++ /dev/null @@ -1,18 +0,0 @@ -@import "./variables"; - -vn-order-line { - vn-table { - img { - border-radius: 50%; - width: 50px; - height: 50px; - } - } - .header { - text-align: right; - - & > div { - margin-bottom: $spacing-xs; - } - } -} \ No newline at end of file diff --git a/modules/order/front/main/index.js b/modules/order/front/main/index.js index caf819c9d..61b0201fd 100644 --- a/modules/order/front/main/index.js +++ b/modules/order/front/main/index.js @@ -2,8 +2,12 @@ import ngModule from '../module'; import ModuleMain from 'salix/components/module-main'; export default class Order extends ModuleMain { - $postLink() { - this.filter = {showEmpty: false}; + constructor($element, $) { + super($element, $); + } + async $onInit() { + this.$state.go('home'); + window.location.href = await this.vnApp.getUrl(`order/`); } } diff --git a/modules/order/front/prices-popover/index.html b/modules/order/front/prices-popover/index.html deleted file mode 100644 index 2551853e6..000000000 --- a/modules/order/front/prices-popover/index.html +++ /dev/null @@ -1,52 +0,0 @@ - -
- - - - - - {{::price.warehouse}} - - - -
- {{::price.grouping}} - x {{::price.price | currency: 'EUR': 2}} -
-
- {{::price.priceKg | currency: 'EUR'}}/Kg -
-
- - - - - - - -
-
-
- -
-
diff --git a/modules/order/front/prices-popover/index.js b/modules/order/front/prices-popover/index.js deleted file mode 100644 index aa5570f59..000000000 --- a/modules/order/front/prices-popover/index.js +++ /dev/null @@ -1,115 +0,0 @@ -import ngModule from '../module'; -import Popover from 'core/components/popover'; -import './style.scss'; - -class Controller extends Popover { - constructor(...args) { - super(...args); - this.totalBasquet = 0; - } - - set prices(value) { - this._prices = value; - if (value && value[0].grouping) - this.getTotalQuantity(); - } - - get prices() { - return this._prices; - } - - show(parent, item) { - this.id = item.id; - this.item = JSON.parse(JSON.stringify(item)); - this.maxQuantity = this.item.available; - this.prices = this.item.prices; - - super.show(parent); - } - - onClose() { - this.id = null; - this.item = {}; - this.tags = {}; - this._prices = {}; - this.totalQuantity = 0; - super.onClose(); - } - - getTotalQuantity() { - let total = 0; - for (let price of this.prices) { - if (!price.quantity) price.quantity = 0; - total += price.quantity; - } - - this.totalQuantity = total; - } - - addQuantity(price) { - this.getTotalQuantity(); - const quantity = this.totalQuantity + price.grouping; - if (quantity <= this.maxQuantity) - price.quantity += price.grouping; - } - - getGroupings() { - const filledRows = []; - for (let priceOption of this.prices) { - if (priceOption.quantity && priceOption.quantity > 0) { - const priceMatch = filledRows.find(row => { - return row.warehouseFk == priceOption.warehouseFk - && row.price == priceOption.price; - }); - - if (!priceMatch) - filledRows.push(Object.assign({}, priceOption)); - else priceMatch.quantity += priceOption.quantity; - } - } - - return filledRows; - } - - submit() { - const filledRows = this.getGroupings(); - - try { - const hasInvalidGropings = filledRows.some(row => - row.quantity % row.grouping != 0 - ); - - if (filledRows.length <= 0) - throw new Error('First you must add some quantity'); - - if (hasInvalidGropings) - throw new Error(`The amounts doesn't match with the grouping`); - - const params = { - orderFk: this.order.id, - items: filledRows - }; - this.$http.post(`OrderRows/addToOrder`, params) - .then(() => { - this.vnApp.showSuccess(this.$t('Data saved!')); - this.hide(); - if (this.card) this.card.reload(); - }); - } catch (e) { - this.vnApp.showError(this.$t(e.message)); - return false; - } - return true; - } -} - -ngModule.vnComponent('vnOrderPricesPopover', { - slotTemplate: require('./index.html'), - controller: Controller, - bindings: { - order: '<' - }, - require: { - card: '?^vnOrderCard' - } -}); diff --git a/modules/order/front/prices-popover/index.spec.js b/modules/order/front/prices-popover/index.spec.js deleted file mode 100644 index 734a9e254..000000000 --- a/modules/order/front/prices-popover/index.spec.js +++ /dev/null @@ -1,171 +0,0 @@ -import './index.js'; - -describe('Order', () => { - describe('Component vnOrderPricesPopover', () => { - let controller; - let $httpBackend; - let orderId = 16; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - const $scope = $rootScope.$new(); - const $element = angular.element(''); - const $transclude = { - $$boundTransclude: { - $$slots: [] - } - }; - controller = $componentController('vnOrderPricesPopover', {$element, $scope, $transclude}); - controller._prices = [ - {warehouseFk: 1, grouping: 10, quantity: 0}, - {warehouseFk: 1, grouping: 100, quantity: 100} - ]; - controller.item = {available: 1000}; - controller.maxQuantity = 1000; - controller.order = {id: orderId}; - })); - - describe('prices() setter', () => { - it('should call to the getTotalQuantity() method', () => { - controller.getTotalQuantity = jest.fn(); - - controller.prices = [ - {grouping: 10, quantity: 0}, - {grouping: 100, quantity: 0}, - {grouping: 1000, quantity: 0}, - ]; - - expect(controller.getTotalQuantity).toHaveBeenCalledWith(); - }); - }); - - describe('getTotalQuantity()', () => { - it('should set the totalQuantity property', () => { - controller.getTotalQuantity(); - - expect(controller.totalQuantity).toEqual(100); - }); - }); - - describe('addQuantity()', () => { - it('should call to the getTotalQuantity() method and NOT set the quantity property', () => { - jest.spyOn(controller, 'getTotalQuantity'); - - controller.prices = [ - {grouping: 10, quantity: 0}, - {grouping: 100, quantity: 0}, - {grouping: 1000, quantity: 1000}, - ]; - - const oneThousandGrouping = controller.prices[2]; - - expect(oneThousandGrouping.quantity).toEqual(1000); - - controller.addQuantity(oneThousandGrouping); - - expect(controller.getTotalQuantity).toHaveBeenCalledWith(); - expect(oneThousandGrouping.quantity).toEqual(1000); - }); - - it('should call to the getTotalQuantity() method and then set the quantity property', () => { - jest.spyOn(controller, 'getTotalQuantity'); - - const oneHandredGrouping = controller.prices[1]; - controller.addQuantity(oneHandredGrouping); - - expect(controller.getTotalQuantity).toHaveBeenCalledWith(); - expect(oneHandredGrouping.quantity).toEqual(200); - }); - }); - - describe('getGroupings()', () => { - it('should return a row with the total filled quantity', () => { - jest.spyOn(controller, 'getTotalQuantity'); - - controller.prices = [ - {warehouseFk: 1, grouping: 10, quantity: 10}, - {warehouseFk: 1, grouping: 100, quantity: 100}, - {warehouseFk: 1, grouping: 1000, quantity: 1000}, - ]; - - const rows = controller.getGroupings(); - const firstRow = rows[0]; - - expect(rows.length).toEqual(1); - expect(firstRow.quantity).toEqual(1110); - }); - - it('should return two filled rows with a quantity', () => { - jest.spyOn(controller, 'getTotalQuantity'); - - controller.prices = [ - {warehouseFk: 1, grouping: 10, quantity: 10}, - {warehouseFk: 2, grouping: 10, quantity: 10}, - {warehouseFk: 1, grouping: 100, quantity: 0}, - {warehouseFk: 1, grouping: 1000, quantity: 1000}, - ]; - - const rows = controller.getGroupings(); - const firstRow = rows[0]; - const secondRow = rows[1]; - - expect(rows.length).toEqual(2); - expect(firstRow.quantity).toEqual(1010); - expect(secondRow.quantity).toEqual(10); - }); - }); - - describe('submit()', () => { - it('should throw an error if none of the rows contains a quantity', () => { - jest.spyOn(controller, 'getTotalQuantity'); - jest.spyOn(controller.vnApp, 'showError'); - - controller.prices = [ - {warehouseFk: 1, grouping: 10, quantity: 0}, - {warehouseFk: 1, grouping: 100, quantity: 0} - ]; - - controller.submit(); - - expect(controller.vnApp.showError).toHaveBeenCalledWith(`First you must add some quantity`); - }); - - it(`should throw an error if the quantity doesn't match the grouping value`, () => { - jest.spyOn(controller, 'getTotalQuantity'); - jest.spyOn(controller.vnApp, 'showError'); - - controller.prices = [ - {warehouseFk: 1, grouping: 10, quantity: 0}, - {warehouseFk: 1, grouping: 100, quantity: 1101} - ]; - - controller.submit(); - - expect(controller.vnApp.showError).toHaveBeenCalledWith(`The amounts doesn't match with the grouping`); - }); - - it('should should make an http query and then show a success message', () => { - jest.spyOn(controller, 'getTotalQuantity'); - jest.spyOn(controller.vnApp, 'showSuccess'); - - controller.prices = [ - {warehouseFk: 1, grouping: 10, quantity: 0}, - {warehouseFk: 1, grouping: 100, quantity: 100} - ]; - - const params = { - orderFk: orderId, - items: [{warehouseFk: 1, grouping: 100, quantity: 100}] - }; - - $httpBackend.expectPOST('OrderRows/addToOrder', params).respond(200); - controller.submit(); - $httpBackend.flush(); - - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith(`Data saved!`); - }); - }); - }); -}); diff --git a/modules/order/front/prices-popover/locale/es.yml b/modules/order/front/prices-popover/locale/es.yml deleted file mode 100644 index 27eac802d..000000000 --- a/modules/order/front/prices-popover/locale/es.yml +++ /dev/null @@ -1,3 +0,0 @@ -Qty.: Cant. -First you must add some quantity: Primero debes agregar alguna cantidad -The amounts doesn't match with the grouping: Las cantidades no coinciden con el grouping \ No newline at end of file diff --git a/modules/order/front/prices-popover/style.scss b/modules/order/front/prices-popover/style.scss deleted file mode 100644 index deaeab044..000000000 --- a/modules/order/front/prices-popover/style.scss +++ /dev/null @@ -1,18 +0,0 @@ -@import "variables"; - -.vn-order-prices-popover .content { - .prices { - vn-table { - .price-kg { - color: $color-font-secondary; - font-size: .75rem - } - .vn-input-number { - width: 80px; - } - } - .footer { - text-align: center; - } - } -} \ No newline at end of file diff --git a/modules/order/front/routes.json b/modules/order/front/routes.json index 2eeb60553..25c68300f 100644 --- a/modules/order/front/routes.json +++ b/modules/order/front/routes.json @@ -28,19 +28,19 @@ "abstract": true, "component": "vn-order", "description": "Orders" - }, + }, { "url": "/index?q", "state": "order.index", "component": "vn-order-index", "description": "Orders" - }, + }, { "url": "/:id", "state": "order.card", "abstract": true, "component": "vn-order-card" - }, + }, { "url": "/summary", "state": "order.card.summary", @@ -49,48 +49,6 @@ "params": { "order": "$ctrl.order" } - }, - { - "url": "/catalog?q&categoryId&typeId&tagGroups", - "state": "order.card.catalog", - "component": "vn-order-catalog", - "description": "Catalog", - "params": { - "order": "$ctrl.order" - } - }, - { - "url": "/volume", - "state": "order.card.volume", - "component": "vn-order-volume", - "description": "Volume", - "params": { - "order": "$ctrl.order" - } - }, - { - "url": "/line", - "state": "order.card.line", - "component": "vn-order-line", - "description": "Lines", - "params": { - "order": "$ctrl.order" - } - }, - { - "url": "/create?clientFk", - "state": "order.create", - "component": "vn-order-create", - "description": "New order" - }, - { - "url": "/basic-data", - "state": "order.card.basicData", - "component": "vn-order-basic-data", - "description": "Basic data", - "params": { - "order": "$ctrl.order" - } } ] -} \ No newline at end of file +} diff --git a/modules/order/front/search-panel/index.html b/modules/order/front/search-panel/index.html deleted file mode 100644 index 001fc0bcb..000000000 --- a/modules/order/front/search-panel/index.html +++ /dev/null @@ -1,86 +0,0 @@ -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
diff --git a/modules/order/front/search-panel/index.js b/modules/order/front/search-panel/index.js deleted file mode 100644 index 07be9ca24..000000000 --- a/modules/order/front/search-panel/index.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; - -ngModule.vnComponent('vnOrderSearchPanel', { - template: require('./index.html'), - controller: SearchPanel -}); diff --git a/modules/order/front/search-panel/locale/es.yml b/modules/order/front/search-panel/locale/es.yml deleted file mode 100644 index 9801e151f..000000000 --- a/modules/order/front/search-panel/locale/es.yml +++ /dev/null @@ -1,11 +0,0 @@ -Order id: Id cesta -Client id: Id cliente -From landed: Desde f. entrega -To landed: Hasta f. entrega -To: Hasta -Agency: Agencia -Application: Aplicación -SalesPerson: Comercial -Order confirmed: Pedido confirmado -Show empty: Mostrar vacías -Search orders by ticket id: Buscar pedido por id ticket \ No newline at end of file diff --git a/modules/order/front/summary/index.html b/modules/order/front/summary/index.html deleted file mode 100644 index 218359992..000000000 --- a/modules/order/front/summary/index.html +++ /dev/null @@ -1,131 +0,0 @@ - -
- - - - - Basket #{{$ctrl.summary.id}} - {{$ctrl.summary.client.name}} - ({{$ctrl.summary.client.id}}) - - - -
- - - - - - - {{$ctrl.summary.address.nickname}} - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Subtotal {{$ctrl.summary.subTotal | currency: 'EUR':2}}

-

VAT {{$ctrl.summary.VAT | currency: 'EUR':2}}

-

Total {{$ctrl.summary.total | currency: 'EUR':2}}

-
- - - - - - Item - Description - Quantity - Price - Amount - - - - - - - - - - - - {{::row.itemFk}} - - - -
- {{::row.item.name}} - -

{{::row.item.subName}}

-
-
- - -
- {{::row.quantity}} - {{::row.price | currency: 'EUR':2}} - {{::row.quantity * row.price | currency: 'EUR':2}} -
-
- -
-
-
- - - - diff --git a/modules/order/front/summary/index.js b/modules/order/front/summary/index.js deleted file mode 100644 index cc1df8f5d..000000000 --- a/modules/order/front/summary/index.js +++ /dev/null @@ -1,41 +0,0 @@ -import ngModule from '../module'; -import Summary from 'salix/components/summary'; -import './style.scss'; - -class Controller extends Summary { - setSummary() { - this.$http.get(`Orders/${this.order.id}/summary`) - .then(res => this.summary = res.data); - } - - get formattedAddress() { - if (!this.summary) return null; - - let address = this.summary.address; - let province = address.province ? `(${address.province.name})` : ''; - - return `${address.street} - ${address.city} ${province}`; - } - - $onChanges() { - if (this.order && this.order.id) - this.setSummary(); - } - - save() { - this.$http.post(`Orders/${this.order.id}/confirm`).then(() => { - this.vnApp.showSuccess(this.$t('Order confirmed')); - this.$state.go(`ticket.index`, { - q: JSON.stringify({clientFk: this.order.clientFk}) - }); - }); - } -} - -ngModule.vnComponent('vnOrderSummary', { - template: require('./index.html'), - controller: Controller, - bindings: { - order: '<' - } -}); diff --git a/modules/order/front/summary/index.spec.js b/modules/order/front/summary/index.spec.js deleted file mode 100644 index 0c04593e1..000000000 --- a/modules/order/front/summary/index.spec.js +++ /dev/null @@ -1,47 +0,0 @@ -import './index'; - -describe('Order', () => { - describe('Component vnOrderSummary', () => { - let controller; - let $httpBackend; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - const $element = angular.element(''); - controller = $componentController('vnOrderSummary', {$element}); - controller.order = {id: 1}; - })); - - describe('getSummary()', () => { - it('should now perform a GET query and define the summary property', () => { - let res = { - id: 1, - nickname: 'Batman' - }; - $httpBackend.expectGET(`Orders/1/summary`).respond(res); - controller.setSummary(); - $httpBackend.flush(); - - expect(controller.summary).toEqual(res); - }); - }); - - describe('formattedAddress()', () => { - it('should return a full fromatted address with city and province', () => { - controller.summary = { - address: { - province: { - name: 'Gotham' - }, - street: '1007 Mountain Drive', - city: 'Gotham' - } - }; - - expect(controller.formattedAddress).toEqual('1007 Mountain Drive - Gotham (Gotham)'); - }); - }); - }); -}); diff --git a/modules/order/front/summary/style.scss b/modules/order/front/summary/style.scss deleted file mode 100644 index a2537c58f..000000000 --- a/modules/order/front/summary/style.scss +++ /dev/null @@ -1,20 +0,0 @@ -@import "./variables"; - -vn-order-summary .summary{ - max-width: $width-lg; - - & > vn-horizontal > vn-one { - min-width: 160px; - - &.taxes { - border: $border-thin-light; - text-align: right; - padding: 8px; - - & > p { - font-size: 1.2rem; - margin: 3px; - } - } - } -} \ No newline at end of file diff --git a/modules/order/front/volume/index.html b/modules/order/front/volume/index.html deleted file mode 100644 index e0053f9ed..000000000 --- a/modules/order/front/volume/index.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - - Item - Description - Quantity - m³ per quantity - - - - - - - {{::row.itemFk}} - - - -
- {{::row.item.name}} - -

{{::row.item.subName}}

-
-
- - -
- {{::row.quantity}} - {{::row.volume | number:3}} -
-
-
-
-
- - - diff --git a/modules/order/front/volume/index.js b/modules/order/front/volume/index.js deleted file mode 100644 index c1bc5ec7d..000000000 --- a/modules/order/front/volume/index.js +++ /dev/null @@ -1,37 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $) { - super($element, $); - this.filter = { - include: { - relation: 'item' - }, - order: 'itemFk' - }; - this.order = {}; - this.ticketVolumes = []; - } - - onDataChange() { - this.$http.get(`Orders/${this.$params.id}/getVolumes`) - .then(res => { - this.$.model.data.forEach(order => { - res.data.volumes.forEach(volume => { - if (order.itemFk === volume.itemFk) - order.volume = volume.volume; - }); - }); - }); - } -} - -ngModule.vnComponent('vnOrderVolume', { - template: require('./index.html'), - controller: Controller, - bindings: { - order: '<' - } -}); diff --git a/modules/order/front/volume/index.spec.js b/modules/order/front/volume/index.spec.js deleted file mode 100644 index 6d7b18865..000000000 --- a/modules/order/front/volume/index.spec.js +++ /dev/null @@ -1,42 +0,0 @@ -import './index'; - -describe('Order', () => { - describe('Component vnOrderVolume', () => { - let controller; - let $httpBackend; - let $scope; - - beforeEach(ngModule('order')); - - beforeEach(inject(($componentController, $state, _$httpBackend_, $rootScope) => { - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - $scope.model = { - data: [ - {itemFk: 1}, - {itemFk: 2} - ] - }; - - $state.params.id = 1; - const $element = angular.element(''); - controller = $componentController('vnOrderVolume', {$element, $scope}); - })); - - it('should join the sale volumes to its respective sale', () => { - let response = { - volumes: [ - {itemFk: 1, volume: 0.008}, - {itemFk: 2, volume: 0.003} - ] - }; - - $httpBackend.expectGET(`Orders/1/getVolumes`).respond(response); - controller.onDataChange(); - $httpBackend.flush(); - - expect(controller.$.model.data[0].volume).toBe(0.008); - expect(controller.$.model.data[1].volume).toBe(0.003); - }); - }); -}); diff --git a/modules/order/front/volume/style.scss b/modules/order/front/volume/style.scss deleted file mode 100644 index da13eca0d..000000000 --- a/modules/order/front/volume/style.scss +++ /dev/null @@ -1,12 +0,0 @@ - -@import "./variables"; - -vn-order-volume { - .header { - text-align: right; - - & > div { - margin-bottom: $spacing-xs; - } - } -} diff --git a/modules/ticket/back/methods/expedition-state/filter.js b/modules/ticket/back/methods/expedition-state/filter.js index 1483780f7..3a4e7a87c 100644 --- a/modules/ticket/back/methods/expedition-state/filter.js +++ b/modules/ticket/back/methods/expedition-state/filter.js @@ -29,7 +29,7 @@ module.exports = Self => { Object.assign(myOptions, options); const stmt = new ParameterizedSQL( - `SELECT es.created, u.name, u.id workerFk, est.description state + `SELECT es.created, u.name, u.id workerFk, est.description state, es.isScanned FROM vn.expeditionState es JOIN vn.expeditionStateType est ON est.id = es.typeFk JOIN account.user u ON u.id = es.userFk diff --git a/modules/ticket/back/methods/sale/recalculatePrice.js b/modules/ticket/back/methods/sale/recalculatePrice.js index fd3d6aa9b..ea71032d0 100644 --- a/modules/ticket/back/methods/sale/recalculatePrice.js +++ b/modules/ticket/back/methods/sale/recalculatePrice.js @@ -48,7 +48,7 @@ module.exports = Self => { CALL vn.sale_recalcComponent(null); DROP TEMPORARY TABLE tmp.recalculateSales;`; - const recalculation = await Self.rawSql(query, salesIds, myOptions); + const recalculation = await Self.rawSql(query, [salesIds], myOptions); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js index 9d1403df0..100f74bf0 100644 --- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -85,6 +85,25 @@ describe('sale updatePrice()', () => { } }); + it('should check if priceFixed has changed', async() => { + const tx = await models.Sale.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const price = 3; + const beforeUpdate = await models.Sale.findById(saleId, null, options); + await models.Sale.updatePrice(ctx, saleId, price, options); + const afterUpdate = await models.Sale.findById(saleId, null, options); + + expect(beforeUpdate.priceFixed).not.toEqual(afterUpdate.priceFixed); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + it('should set price as a decimal number and check the sale has the mana component changing the salesPersonMana', async() => { const tx = await models.Sale.beginTransaction({}); diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 191fd09e3..d4f128082 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -91,7 +91,21 @@ module.exports = Self => { value: componentValue }, myOptions); } - await sale.updateAttributes({price: newPrice}, myOptions); + + const [priceFixed] = await Self.rawSql(` + SELECT SUM(value) value + FROM sale s + JOIN saleComponent sc ON sc.saleFk = s.id + JOIN component c ON c.id = sc.componentFk + JOIN componentType ct ON ct.id = c.typeFk + WHERE ct.isBase + AND s.id = ? + `, [id], myOptions); + + await sale.updateAttributes({ + price: newPrice, + priceFixed: priceFixed.value + }, myOptions); await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions); await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [sale.ticketFk], myOptions); diff --git a/modules/ticket/back/methods/sale/usesMana.js b/modules/ticket/back/methods/sale/usesMana.js index 31beb3a4c..b4768d80a 100644 --- a/modules/ticket/back/methods/sale/usesMana.js +++ b/modules/ticket/back/methods/sale/usesMana.js @@ -31,6 +31,6 @@ module.exports = Self => { const usesMana = departments.find(department => department.id == workerDepartment.departmentFk); - return usesMana ? true : false; + return !!usesMana; }; }; diff --git a/modules/ticket/back/methods/ticket-request/filter.js b/modules/ticket/back/methods/ticket-request/filter.js index 5364cef9a..53f90b98f 100644 --- a/modules/ticket/back/methods/ticket-request/filter.js +++ b/modules/ticket/back/methods/ticket-request/filter.js @@ -59,6 +59,11 @@ module.exports = Self => { arg: 'state', type: 'string', description: `Search request by request state` + }, + { + arg: 'myTeam', + type: 'boolean', + description: `Team partners` } ], returns: { @@ -75,6 +80,8 @@ module.exports = Self => { const conn = Self.dataSource.connector; const userId = ctx.req.accessToken.userId; const myOptions = {}; + const models = Self.app.models; + const args = ctx.args; if (typeof options == 'object') Object.assign(myOptions, options); @@ -82,6 +89,21 @@ module.exports = Self => { if (ctx.args.mine) ctx.args.attenderFk = userId; + const teamMembersId = []; + if (args.myTeam != null) { + const worker = await models.Worker.findById(userId, { + include: { + relation: 'collegues' + } + }, myOptions); + const collegues = worker.collegues() || []; + for (let collegue of collegues) + teamMembersId.push(collegue.collegueFk); + + if (teamMembersId.length == 0) + teamMembersId.push(userId); + } + let where = buildFilter(ctx.args, (param, value) => { switch (param) { case 'search': @@ -113,6 +135,11 @@ module.exports = Self => { return {'w.id': value}; case 'salesPersonFk': return {'c.salesPersonFk': value}; + case 'myTeam': + if (value) + return {'tr.requesterFk': {inq: teamMembersId}}; + else + return {'tr.requesterFk': {nin: teamMembersId}}; } }); diff --git a/modules/ticket/back/methods/ticket-weekly/filter.js b/modules/ticket/back/methods/ticket-weekly/filter.js index 6c9ed4f8b..512faa4cf 100644 --- a/modules/ticket/back/methods/ticket-weekly/filter.js +++ b/modules/ticket/back/methods/ticket-weekly/filter.js @@ -67,7 +67,7 @@ module.exports = Self => { FROM ticketWeekly tw JOIN ticket t ON t.id = tw.ticketFk JOIN client c ON c.id = t.clientFk - JOIN account.user u ON u.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = c.salesPersonFk JOIN warehouse wh ON wh.id = t.warehouseFk LEFT JOIN agencyMode am ON am.id = tw.agencyModeFk` ); diff --git a/modules/ticket/back/methods/ticket/closeAll.js b/modules/ticket/back/methods/ticket/closeAll.js index 8869f9464..71122808c 100644 --- a/modules/ticket/back/methods/ticket/closeAll.js +++ b/modules/ticket/back/methods/ticket/closeAll.js @@ -1,11 +1,17 @@ -const UserError = require('vn-loopback/util/user-error'); const closure = require('./closure'); module.exports = Self => { Self.remoteMethodCtx('closeAll', { description: 'Makes the closure process from all warehouses', accessType: 'WRITE', - accepts: [], + accepts: [ + { + arg: 'options', + type: 'object', + http: {source: 'body'}, + description: 'Optional parameters, including transaction.' + } + ], returns: { type: 'object', root: true @@ -16,21 +22,20 @@ module.exports = Self => { } }); - Self.closeAll = async ctx => { + Self.closeAll = async(ctx, options) => { + const userId = ctx.req.accessToken.userId; + const myOptions = {userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + let tx; + // IMPORTANT: Due to its high cost in production, wrapping this process in a transaction may cause timeouts. + const toDate = Date.vnNew(); toDate.setHours(0, 0, 0, 0); toDate.setDate(toDate.getDate() - 1); - const todayMinDate = Date.vnNew(); - todayMinDate.setHours(0, 0, 0, 0); - - const todayMaxDate = Date.vnNew(); - todayMaxDate.setHours(23, 59, 59, 59); - - // Prevent closure for current day - if (toDate >= todayMinDate && toDate <= todayMaxDate) - throw new UserError('You cannot close tickets for today'); - const tickets = await Self.rawSql(` SELECT t.id, t.clientFk, @@ -41,7 +46,7 @@ module.exports = Self => { c.salesPersonFk, c.isToBeMailed, c.hasToInvoice, - co.hasDailyInvoice, + c.hasDailyInvoice, eu.email salesPersonEmail, t.addressFk FROM ticket t @@ -53,16 +58,17 @@ module.exports = Self => { JOIN province p ON p.id = c.provinceFk JOIN country co ON co.id = p.countryFk LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk + JOIN ticketConfig tc ON TRUE WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code <> 'delivered')) - AND DATE(t.shipped) BETWEEN ? - INTERVAL 7 DAY AND util.dayEnd(?) + AND t.shipped BETWEEN ? - INTERVAL tc.closureDaysAgo DAY AND util.dayEnd(?) AND t.refFk IS NULL GROUP BY t.id - `, [toDate, toDate]); + `, [toDate, toDate], myOptions); const ticketIds = tickets.map(ticket => ticket.id); await Self.rawSql(` INSERT INTO util.debug (variable, value) VALUES ('nightInvoicing', ?) - `, [ticketIds.join(',')]); + `, [ticketIds.join(',')], myOptions); await Self.rawSql(` WITH ticketNotInvoiceable AS( @@ -108,6 +114,7 @@ module.exports = Self => { JOIN alertLevel al ON al.id = ts.alertLevel JOIN client c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk + JOIN ticketConfig tc ON TRUE LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk @@ -116,9 +123,9 @@ module.exports = Self => { LEFT JOIN vn.invoiceOutSerial ios ON ios.taxAreaFk = 'WORLD' AND ios.code = invoiceSerial(t.clientFk, t.companyFk, 'multiple') WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code <> 'delivered')) - AND DATE(t.shipped) BETWEEN ? - INTERVAL 2 DAY AND util.dayEnd(?) + AND t.shipped BETWEEN ? - INTERVAL tc.closureDaysAgo DAY AND util.dayEnd(?) AND t.refFk IS NULL - AND IFNULL(a.hasDailyInvoice, co.hasDailyInvoice) + AND c.hasDailyInvoice GROUP BY ticketFk HAVING hasErrorToInvoice OR hasErrorTaxDataChecked @@ -131,9 +138,9 @@ module.exports = Self => { ) SELECT IF(errors = '{"tickets": null}', 'No errors', util.notification_send('invoice-ticket-closure', errors, NULL)) - FROM ticketNotInvoiceable`, [toDate, toDate]); + FROM ticketNotInvoiceable`, [toDate, toDate], myOptions); - await closure(ctx, Self, tickets); + await closure(ctx, Self, tickets, myOptions); await Self.rawSql(` UPDATE ticket t @@ -141,13 +148,17 @@ module.exports = Self => { JOIN alertLevel al ON al.id = ts.alertLevel JOIN agencyMode am ON am.id = t.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN ticketConfig tc ON TRUE LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id SET t.routeFk = NULL - WHERE DATE(t.shipped) BETWEEN ? - INTERVAL 2 DAY AND util.dayEnd(?) + WHERE t.shipped BETWEEN ? - INTERVAL tc.closureDaysAgo DAY AND util.dayEnd(?) AND al.code NOT IN ('DELIVERED', 'PACKED') AND NOT t.packages AND tob.id IS NULL - AND t.routeFk`, [toDate, toDate], {userId: ctx.req.accessToken.userId}); + AND t.routeFk`, [toDate, toDate], myOptions); + + if (tx) + await tx.commit(); return { message: 'Success' diff --git a/modules/ticket/back/methods/ticket/closeByTicket.js b/modules/ticket/back/methods/ticket/closeByTicket.js index 40fe048a5..8a21267b6 100644 --- a/modules/ticket/back/methods/ticket/closeByTicket.js +++ b/modules/ticket/back/methods/ticket/closeByTicket.js @@ -50,7 +50,7 @@ module.exports = Self => { c.salesPersonFk, c.isToBeMailed, c.hasToInvoice, - co.hasDailyInvoice, + c.hasDailyInvoice, eu.email salesPersonEmail, t.addressFk FROM expedition e @@ -58,8 +58,6 @@ module.exports = Self => { JOIN ticketState ts ON ts.ticketFk = t.id JOIN alertLevel al ON al.id = ts.alertLevel JOIN client c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - JOIN country co ON co.id = p.countryFk LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk WHERE al.code = 'PACKED' AND t.id = ? diff --git a/modules/ticket/back/methods/ticket/closure.js b/modules/ticket/back/methods/ticket/closure.js index 892c1ddc6..e4cb49007 100644 --- a/modules/ticket/back/methods/ticket/closure.js +++ b/modules/ticket/back/methods/ticket/closure.js @@ -12,19 +12,21 @@ module.exports = async function(ctx, Self, tickets, options) { Object.assign(myOptions, options); let tx; - // if (!myOptions.transaction) { - // tx = await Self.beginTransaction({}); - // myOptions.transaction = tx; - // } + // IMPORTANT: Due to its high cost in production, wrapping this process in a transaction may cause timeouts. if (tickets.length == 0) return; const failedtickets = []; for (const ticket of tickets) { try { - await Self.rawSql(`CALL util.debugAdd('invoicingTicket', ?)`, [ticket.id], {userId}); + await Self.rawSql(`CALL util.debugAdd('invoicingTicket', ?)`, [ticket.id], myOptions); - await Self.app.models.InvoiceOut.getSerial(ticket.clientFk, ticket.companyFk, ticket.addressFk, 'quick'); + await Self.app.models.InvoiceOut.getSerial( + ticket.clientFk, + ticket.companyFk, + ticket.addressFk, + 'quick', + myOptions); await Self.rawSql( `CALL vn.ticket_closeByTicket(?)`, [ticket.id], @@ -155,6 +157,7 @@ module.exports = async function(ctx, Self, tickets, options) { INSERT INTO util.debug (variable, value) VALUES ('invoicingTicketError', ?) `, [ticket.id + ' - ' + error]); + if (error.responseCode == 450) { await invalidEmail(ticket); continue; diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js index c98ddaab6..d3e53c702 100644 --- a/modules/ticket/back/methods/ticket/filter.js +++ b/modules/ticket/back/methods/ticket/filter.js @@ -76,7 +76,8 @@ module.exports = Self => { { arg: 'myTeam', type: 'boolean', - description: `Whether to show only tickets for the current logged user team (For now it shows only the current user tickets)` + description: `Whether to show only tickets for the current logged user team + (For now it shows only the current user tickets)` }, { arg: 'problems', @@ -227,51 +228,57 @@ module.exports = Self => { stmt = new ParameterizedSQL(` CREATE OR REPLACE TEMPORARY TABLE tmp.filter (INDEX (id)) - ENGINE = MEMORY + ENGINE = InnoDB SELECT t.id, - t.shipped, - CAST(DATE(t.shipped) AS CHAR) shippedDate, - HOUR(t.shipped) shippedHour, - t.nickname, - t.refFk, - t.routeFk, - t.warehouseFk, - t.clientFk, - t.totalWithoutVat, - t.totalWithVat, - io.id invoiceOutId, - a.provinceFk, - p.name province, - w.name warehouse, - am.name agencyMode, - am.id agencyModeFk, - st.name state, - st.classColor, - wk.lastName salesPerson, - ts.stateFk stateFk, - ts.alertLevel alertLevel, - ts.code alertLevelCode, - u.name userName, - c.salesPersonFk, - z.hour zoneLanding, - HOUR(z.hour) zoneHour, - MINUTE(z.hour) zoneMinute, - z.name zoneName, - z.id zoneFk, - CAST(z.hour AS CHAR) hour - FROM ticket t - LEFT JOIN invoiceOut io ON t.refFk = io.ref - LEFT JOIN zone z ON z.id = t.zoneFk - LEFT JOIN address a ON a.id = t.addressFk - LEFT JOIN province p ON p.id = a.provinceFk - LEFT JOIN warehouse w ON w.id = t.warehouseFk - LEFT JOIN agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - LEFT JOIN state st ON st.id = ts.stateFk - LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id - LEFT JOIN route r ON r.id = t.routeFk + t.shipped, + CAST(DATE(t.shipped) AS CHAR) shippedDate, + HOUR(t.shipped) shippedHour, + t.nickname, + t.refFk, + t.routeFk, + t.warehouseFk, + t.clientFk, + t.totalWithoutVat, + t.totalWithVat, + io.id invoiceOutId, + a.provinceFk, + p.name province, + w.name warehouse, + am.name agencyMode, + am.id agencyModeFk, + st.name state, + st.classColor, + wk.lastName salesPerson, + ts.stateFk stateFk, + ts.alertLevel alertLevel, + ts.code alertLevelCode, + u.name userName, + c.salesPersonFk, + z.hour zoneLanding, + HOUR(z.hour) zoneHour, + MINUTE(z.hour) zoneMinute, + z.name zoneName, + z.id zoneFk, + CAST(z.hour AS CHAR) hour, + a.nickname addressNickname, + (SELECT GROUP_CONCAT(DISTINCT i2.itemPackingTypeFk ORDER BY i2.itemPackingTypeFk SEPARATOR ',') + FROM sale s2 + JOIN item i2 ON i2.id = s2.itemFk + WHERE s2.ticketFk = t.id + ) AS packing + FROM ticket t + LEFT JOIN invoiceOut io ON t.refFk = io.ref + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN address a ON a.id = t.addressFk + LEFT JOIN province p ON p.id = a.provinceFk + LEFT JOIN warehouse w ON w.id = t.warehouseFk + LEFT JOIN agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + LEFT JOIN state st ON st.id = ts.stateFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.id + LEFT JOIN route r ON r.id = t.routeFk `); if (args.orderFk) { @@ -290,6 +297,7 @@ module.exports = Self => { } stmt.merge(conn.makeWhere(filter.where)); + stmts.push(stmt); stmt = new ParameterizedSQL(` diff --git a/modules/ticket/back/methods/ticket/getSales.js b/modules/ticket/back/methods/ticket/getSales.js index e721d90ae..5b2288d31 100644 --- a/modules/ticket/back/methods/ticket/getSales.js +++ b/modules/ticket/back/methods/ticket/getSales.js @@ -37,6 +37,7 @@ module.exports = Self => { 'name', 'subName', 'itemPackingTypeFk', + 'size', 'tag5', 'value5', 'tag6', diff --git a/modules/ticket/back/methods/ticket/getTicketsAdvance.js b/modules/ticket/back/methods/ticket/getTicketsAdvance.js index 1bd5f83de..41f3ee79a 100644 --- a/modules/ticket/back/methods/ticket/getTicketsAdvance.js +++ b/modules/ticket/back/methods/ticket/getTicketsAdvance.js @@ -50,6 +50,11 @@ module.exports = Self => { type: 'boolean', description: 'True when lines and stock of origin are equal' }, + { + arg: 'departmentFk', + type: 'number', + description: 'Department identifier' + }, { arg: 'filter', type: 'object', @@ -96,6 +101,8 @@ module.exports = Self => { }; case 'isFullMovable': return {'f.isFullMovable': value}; + case 'departmentFk': + return {'f.departmentFk': value}; } }); diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index a684e1cbc..fcab95ee2 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -49,9 +49,12 @@ module.exports = Self => { where: {originalTicketFk: id} }, myOptions); + const hasRefund = !!ticketRefunds?.length; + const allDeleted = ticketRefunds.every(refund => refund.refundTicket().isDeleted); - if (ticketRefunds?.length && !allDeleted) { + if (!hasRefund) await models.TicketRefund.destroyAll({refundTicketFk: id}, myOptions); + if (hasRefund && !allDeleted) { const notDeleted = []; for (const refund of ticketRefunds) if (!refund.refundTicket().isDeleted) notDeleted.push(refund.refundTicket().id); diff --git a/modules/ticket/back/methods/ticket/specs/closeAll.spec.js b/modules/ticket/back/methods/ticket/specs/closeAll.spec.js new file mode 100644 index 000000000..f01541eec --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/closeAll.spec.js @@ -0,0 +1,54 @@ +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('Ticket Closure - closeAll function', () => { + let ctx = { + req: { + getLocale: () => 'es', + accessToken: {userId: 1106}, + headers: {origin: 'http://localhost'}, + __: value => value, + }, + args: {} + }; + let options; + let tx; + let originalVnNew; + + beforeEach(async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: ctx.req}); + + tx = await models.Ticket.beginTransaction({}); + options = {transaction: tx}; + originalVnNew = Date.vnNew; + spyOn(Date, 'vnNew').and.callFake(() => { + const mockDate = originalVnNew(); + mockDate.setDate(mockDate.getDate() + 1); + return mockDate; + }); + }); + + afterEach(async() => { + if (tx) + await tx.rollback(); + }); + + it('should set routeFk to NULL when conditions are met', async() => { + const ticketsBefore = await models.Ticket.find({ + where: { + routeFk: {neq: null} + } + }, options); + + await models.Ticket.closeAll(ctx, options); + + const ticketsAfter = await models.Ticket.find({ + where: { + id: {inq: ticketsBefore.map(ticket => ticket.id)}, + routeFk: {neq: null} + } + }, options); + + expect(ticketsBefore.length).toBeGreaterThan(ticketsAfter.length); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/closure.spec.js b/modules/ticket/back/methods/ticket/specs/closure.spec.js index 303c38233..cafe178cb 100644 --- a/modules/ticket/back/methods/ticket/specs/closure.spec.js +++ b/modules/ticket/back/methods/ticket/specs/closure.spec.js @@ -50,9 +50,9 @@ describe('Ticket closure functionality', () => { expect(ticketStateBefore.code).not.toBe(ticketStateAfter.code); - const ticketAfter = await models.TicketState.findById(ticketId, null, options); + const ticketAfter = await models.Ticket.findById(ticketId, null, options); - expect(ticketAfter.refFk).toBeUndefined(); + expect(ticketAfter.refFk).toBeNull(); }); it('should send Incoterms authorization email on first order', async() => { diff --git a/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js b/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js index 488cd1fc2..a941013cd 100644 --- a/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js @@ -6,6 +6,9 @@ describe('TicketFuture getTicketsAdvance()', () => { today.setHours(0, 0, 0, 0); let tomorrow = Date.vnNew(); tomorrow.setDate(today.getDate() + 1); + const salesDeptId = 43; + const spain1DeptId = 95; + beforeAll.mockLoopBackContext(); it('should return the tickets passing the required data', async() => { const tx = await models.Ticket.beginTransaction({}); @@ -129,4 +132,39 @@ describe('TicketFuture getTicketsAdvance()', () => { throw e; } }); + + it('should return the tickets matching the right department', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + ctx.args = { + dateFuture: tomorrow, + dateToAdvance: today, + warehouseFk: 1, + }; + + await models.Ticket.updateAll({id: {inq: [12, 31]}}, {clientFk: 1}, options); + const client = await models.Client.findById(1, null, options); + await client.updateAttribute('salesPersonFk', 1, options); + const business = await models.Business.findById(1, null, options); + await business.updateAttributes({departmentFk: spain1DeptId}, options); + + const saleTickets = await models.Ticket.getTicketsAdvance(ctx, options); + const filteredSaleTickets = await models.Ticket.getTicketsAdvance( + {args: {...ctx.args, departmentFk: spain1DeptId}}, + options); + + expect(saleTickets.length).toBeGreaterThan(filteredSaleTickets.length); + expect(saleTickets.some(ticket => ticket.departmentFk === salesDeptId)).toBeTrue(); + expect(saleTickets.some(ticket => ticket.departmentFk === spain1DeptId)).toBeTrue(); + + expect(filteredSaleTickets.some(ticket => ticket.departmentFk === salesDeptId)).toBeFalse(); + expect(filteredSaleTickets.some(ticket => ticket.departmentFk === spain1DeptId)).toBeTrue(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js index 782c31c02..b70c94cee 100644 --- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -113,5 +113,27 @@ describe('ticket setDeleted()', () => { expect(error.message).not.toContain('Tickets with associated refunds'); }); + + it('should delete the refund - original ticket relation', async() => { + const tx = await models.Ticket.beginTransaction({}); + try { + const options = {transaction: tx}; + + const ticketId = 24; + const refundTicket = await models.TicketRefund.findOne({where: {refundTicketFk: ticketId}}, options); + + expect(refundTicket).toBeTruthy(); + + await models.Ticket.setDeleted(ctx, ticketId, options); + const removedRefundTicket = await models.TicketRefund.findOne({ + where: {refundTicketFk: ticketId}}, + options); + + expect(removedRefundTicket).toBeNull(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } + }); }); }); diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json index 2dcca1e87..f3f912ec3 100644 --- a/modules/ticket/back/models/expedition.json +++ b/modules/ticket/back/models/expedition.json @@ -1,63 +1,66 @@ { - "name": "Expedition", - "base": "VnModel", - "mixins": { - "Loggable": true + "name": "Expedition", + "base": "VnModel", + "mixins": { + "Loggable": true + }, + "options": { + "mysql": { + "table": "expedition" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" }, - "options": { - "mysql": { - "table": "expedition" - } + "freightItemFk": { + "type": "number" }, - "properties": { - "id": { - "id": true, - "type": "number", - "description": "Identifier" - }, - "freightItemFk": { - "type": "number" - }, - "created": { - "type": "date" - }, - "counter": { - "type": "number" - }, - "externalId": { - "type": "string" - } + "created": { + "type": "date" }, - "relations": { - "ticket": { - "type": "belongsTo", - "model": "Ticket", - "foreignKey": "ticketFk" - }, - "agencyMode": { - "type": "belongsTo", - "model": "AgencyMode", - "foreignKey": "agencyModeFk" - }, - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" - }, - "packages": { - "type": "hasMany", - "model": "TicketPackaging", - "foreignKey": "ticketFk" - }, - "freightItem": { - "type": "belongsTo", - "model": "Item", - "foreignKey": "freightItemFk" - }, - "packaging": { - "type": "belongsTo", - "model": "Package", - "foreignKey": "packagingFk" - } + "counter": { + "type": "number" + }, + "externalId": { + "type": "string" + }, + "stateTypeFk": { + "type": "number" + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "agencyMode": { + "type": "belongsTo", + "model": "AgencyMode", + "foreignKey": "agencyModeFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "packages": { + "type": "hasMany", + "model": "TicketPackaging", + "foreignKey": "ticketFk" + }, + "freightItem": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "freightItemFk" + }, + "packaging": { + "type": "belongsTo", + "model": "Package", + "foreignKey": "packagingFk" } } +} \ No newline at end of file diff --git a/modules/ticket/back/models/sale.json b/modules/ticket/back/models/sale.json index 96a36bbc9..947115f5c 100644 --- a/modules/ticket/back/models/sale.json +++ b/modules/ticket/back/models/sale.json @@ -28,6 +28,9 @@ "discount": { "type": "number" }, + "priceFixed": { + "type": "number" + }, "reserved": { "type": "boolean" }, diff --git a/modules/travel/back/methods/thermograph/createThermograph.js b/modules/travel/back/methods/thermograph/createThermograph.js index 243e2129f..2c47bbf0e 100644 --- a/modules/travel/back/methods/thermograph/createThermograph.js +++ b/modules/travel/back/methods/thermograph/createThermograph.js @@ -56,14 +56,16 @@ module.exports = Self => { model: model }, myOptions); - await Self.rawSql(` - INSERT INTO travelThermograph(thermographFk, warehouseFk, temperatureFk, created) - VALUES (?, ?, ?, ?) - `, [thermograph.id, warehouseId, temperatureFk, date], myOptions); + const travelThermograph = await models.TravelThermograph.create({ + thermographFk: thermograph.id, + warehouseFk: warehouseId, + temperatureFk: temperatureFk, + created: date + }, myOptions); if (tx) await tx.commit(); - return thermograph; + return travelThermograph; } catch (err) { if (tx) await tx.rollback(); throw err; diff --git a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js index 71b9fcccb..f9b2a19f9 100644 --- a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js @@ -6,47 +6,42 @@ describe('Termograph createThermograph()', () => { const temperatureFk = 'COOL'; const warehouseId = 1; const ctx = beforeAll.getCtx(); + let tx; + + beforeEach(async() => { + tx = await models.Thermograph.beginTransaction({}); + }); + + afterEach(async() => { + await tx.rollback(); + }); it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => { - const tx = await models.Thermograph.beginTransaction({}); + const options = {transaction: tx}; - try { - const options = {transaction: tx}; + const createdThermograph = await models.Thermograph.createThermograph( + ctx, thermographId, model, temperatureFk, warehouseId, options); - const createdThermograph = await models.Thermograph.createThermograph(ctx, thermographId, model, temperatureFk, warehouseId, options); + expect(createdThermograph.thermographFk).toEqual(thermographId); - expect(createdThermograph.id).toEqual(thermographId); - expect(createdThermograph.model).toEqual(model); + const createdTravelThermograph = + await models.TravelThermograph.findOne({where: {thermographFk: thermographId}}, options); - const createdTravelThermograpth = await models.TravelThermograph.findOne({where: {thermographFk: thermographId}}, options); - - expect(createdTravelThermograpth.warehouseFk).toEqual(warehouseId); - expect(createdTravelThermograpth.temperatureFk).toEqual(temperatureFk); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(createdTravelThermograph.warehouseFk).toEqual(warehouseId); + expect(createdTravelThermograph.temperatureFk).toEqual(temperatureFk); }); - it(`should throw an error when trying to created repeated thermograph`, async() => { - const tx = await models.Thermograph.beginTransaction({}); - - let error; - + it(`should throw an error when trying to create a repeated thermograph`, async() => { try { const options = {transaction: tx}; - await models.Thermograph.createThermograph(ctx, thermographId, model, temperatureFk, warehouseId, options); - await models.Thermograph.createThermograph(ctx, thermographId, model, temperatureFk, warehouseId, options); - - await tx.rollback(); + await models.Thermograph.createThermograph( + ctx, thermographId, model, temperatureFk, warehouseId, options); + await models.Thermograph.createThermograph( + ctx, thermographId, model, temperatureFk, warehouseId, options); + fail('Expected an error to be thrown when trying to create a repeated thermograph'); } catch (e) { - await tx.rollback(); - error = e; + expect(e.message).toBe('This thermograph id already exists'); } - - expect(error.message).toBe('This thermograph id already exists'); }); }); diff --git a/modules/travel/back/methods/travel/createThermograph.js b/modules/travel/back/methods/travel/createThermograph.js deleted file mode 100644 index aac3a22b9..000000000 --- a/modules/travel/back/methods/travel/createThermograph.js +++ /dev/null @@ -1,103 +0,0 @@ -const UserError = require('vn-loopback/util/user-error'); - -module.exports = Self => { - Self.remoteMethodCtx('createThermograph', { - description: 'Creates a new travel thermograph', - accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'number', - description: 'The travel id', - http: {source: 'path'} - }, - { - arg: 'thermographId', - type: 'string', - description: 'The thermograph id', - required: true - }, - { - arg: 'state', - type: 'string', - required: true - }, - { - arg: 'warehouseId', - type: 'number', - description: 'The warehouse id', - required: true - }, - { - arg: 'companyId', - type: 'number', - description: 'The company id', - required: true - }, - { - arg: 'dmsTypeId', - type: 'number', - description: 'The dms type id', - required: true - }, - { - arg: 'reference', - type: 'string', - required: true - }, - { - arg: 'description', - type: 'string', - required: true - }], - returns: { - type: 'object', - root: true - }, - http: { - path: `/:id/createThermograph`, - verb: 'POST' - } - }); - - Self.createThermograph = async(ctx, id, thermographId, state, options) => { - const models = Self.app.models; - let tx; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const travelThermograph = await models.TravelThermograph.findOne({ - where: { - thermographFk: thermographId, - travelFk: null - } - }, myOptions); - - if (!travelThermograph) - throw new UserError('No valid travel thermograph found'); - - const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); - const firstDms = uploadedFiles[0]; - - await travelThermograph.updateAttributes({ - dmsFk: firstDms.id, - travelFk: id, - result: state - }, myOptions); - - if (tx) await tx.commit(); - - return travelThermograph; - } catch (err) { - if (tx) await tx.rollback(); - throw err; - } - }; -}; diff --git a/modules/travel/back/methods/travel/filter.js b/modules/travel/back/methods/travel/filter.js index e24a7659c..30c10f191 100644 --- a/modules/travel/back/methods/travel/filter.js +++ b/modules/travel/back/methods/travel/filter.js @@ -117,7 +117,6 @@ module.exports = Self => { case 'landedTo': return {'t.landed': {lte: value}}; case 'daysOnward': - today.setHours(0, 0, 0, 0); future.setDate(today.getDate() + value); future.setHours(23, 59, 59, 999); diff --git a/modules/travel/back/methods/travel/saveThermograph.js b/modules/travel/back/methods/travel/saveThermograph.js new file mode 100644 index 000000000..6f7e1c8bf --- /dev/null +++ b/modules/travel/back/methods/travel/saveThermograph.js @@ -0,0 +1,132 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('saveThermograph', { + description: 'Creates or updates a travel thermograph', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + description: 'The travel id', + http: {source: 'path'} + }, + { + arg: 'travelThermographFk', + type: 'number', + description: 'The travel thermograph id', + required: true + }, + { + arg: 'state', + type: 'string', + required: true + }, + { + arg: 'maxTemperature', + type: 'number', + description: 'The maximum temperature' + }, + { + arg: 'minTemperature', + type: 'number', + description: 'The minimum temperature' + }, + { + arg: 'temperatureFk', + type: 'string', + description: 'Range of temperature' + }, { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id' + }, { + arg: 'companyId', + type: 'Number', + description: 'The company id' + }, { + arg: 'dmsTypeId', + type: 'Number', + description: 'The dms type id' + }, { + arg: 'reference', + type: 'String' + }, { + arg: 'description', + type: 'String' + }, { + arg: 'hasFileAttached', + type: 'Boolean', + description: 'True if has an attached file' + }], + returns: {type: 'object', root: true}, + http: {path: `/:id/saveThermograph`, verb: 'POST'} + }); + + Self.saveThermograph = async( + ctx, + id, + travelThermographFk, + state, + maxTemperature, + minTemperature, + temperatureFk, + warehouseId, + companyId, + dmsTypeId, + reference, + description, + hasFileAttached, + options + ) => { + const models = Self.app.models; + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + let dmsFk; + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const travelThermograph = await models.TravelThermograph.findById( + travelThermographFk, + {fields: ['id', 'dmsFk', 'warehouseFk']}, + myOptions + ); + + if (!travelThermograph) + throw new UserError('No valid travel thermograph found'); + + if (travelThermograph.dmsFk) { + await models.Dms.updateFile(ctx, travelThermograph.dmsFk, myOptions); + dmsFk = travelThermograph.dmsFk; + } else { + const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); + const firstDms = uploadedFiles[0]; + dmsFk = firstDms.id; + } + + await travelThermograph.updateAttributes({ + dmsFk, + travelFk: id, + result: state, + maxTemperature, + minTemperature, + temperatureFk, + warehouseFk: warehouseId, + }, myOptions); + + if (tx) await tx.commit(); + + return travelThermograph; + } catch (err) { + if (tx) await tx.rollback(); + throw err; + } + }; +}; diff --git a/modules/travel/back/methods/travel/specs/createThermograph.spec.js b/modules/travel/back/methods/travel/specs/createThermograph.spec.js deleted file mode 100644 index f70e27368..000000000 --- a/modules/travel/back/methods/travel/specs/createThermograph.spec.js +++ /dev/null @@ -1,51 +0,0 @@ -const models = require('vn-loopback/server/server').models; - -describe('Travel createThermograph()', () => { - beforeAll.mockLoopBackContext(); - const travelId = 3; - const currentUserId = 1102; - const thermographId = '138350-0'; - const ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: 1}}; - - it(`should set the travelFk and dmsFk properties to the travel thermograph`, async() => { - const tx = await models.Travel.beginTransaction({}); - - try { - const options = {transaction: tx}; - - spyOn(models.Dms, 'uploadFile').and.returnValue([{id: 5}]); - - travelThermographBefore = await models.TravelThermograph.findOne({ - where: { - thermographFk: thermographId, - travelFk: null - } - }, options); - - await models.Travel.createThermograph(ctx, travelId, thermographId, options); - - const travelThermographAfter = await models.TravelThermograph.findOne({ - where: { - thermographFk: thermographId, - travelFk: travelId - } - }, options); - - expect(models.Dms.uploadFile).toHaveBeenCalledWith(ctx, jasmine.any(Object)); - - expect(travelThermographBefore).toBeDefined(); - expect(travelThermographBefore.thermographFk).toEqual(thermographId); - expect(travelThermographBefore.travelFk).toBeNull(); - expect(travelThermographAfter).toBeDefined(); - - expect(travelThermographAfter.thermographFk).toEqual(thermographId); - expect(travelThermographAfter.travelFk).toEqual(travelId); - expect(travelThermographAfter.dmsFk).toEqual(5); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/travel/back/methods/travel/specs/saveThermograph.spec.js b/modules/travel/back/methods/travel/specs/saveThermograph.spec.js new file mode 100644 index 000000000..c2da4234e --- /dev/null +++ b/modules/travel/back/methods/travel/specs/saveThermograph.spec.js @@ -0,0 +1,69 @@ +const models = require('vn-loopback/server/server').models; + +describe('Thermograph saveThermograph()', () => { + const ctx = beforeAll.getCtx(); + const travelFk = 1; + const thermographId = '138350-0'; + const warehouseFk = 1; + const state = 'COMPLETED'; + const maxTemperature = 30; + const minTemperature = 10; + const temperatureFk = 'COOL'; + let tx; + let options; + + beforeEach(async() => { + options = {transaction: tx}; + tx = await models.Sale.beginTransaction({}); + options.transaction = tx; + }); + + afterEach(async() => { + await tx.rollback(); + }); + + it('should update an existing travel thermograph', async() => { + const dmsFk = 5; + spyOn(models.Dms, 'uploadFile').and.returnValue([{id: dmsFk}]); + + const travelThermograph = await models.TravelThermograph.create({ + travelFk, + thermographFk: thermographId, + temperatureFk, + warehouseFk, + }, options); + + const updatedThermograph = await models.Travel.saveThermograph( + ctx, + travelFk, + travelThermograph.id, + state, + maxTemperature, + minTemperature, + temperatureFk, + warehouseFk, + null, + null, + null, + null, + null, options + ); + + expect(updatedThermograph.result).toEqual(state); + expect(updatedThermograph.maxTemperature).toEqual(maxTemperature); + expect(updatedThermograph.minTemperature).toEqual(minTemperature); + expect(updatedThermograph.temperatureFk).toEqual(temperatureFk); + expect(updatedThermograph.dmsFk).toEqual(dmsFk); + }); + + it('should throw an error if no valid travel thermograph is found', async() => { + try { + await models.Travel.saveThermograph( + ctx, null, 'notExists', state, maxTemperature, minTemperature, temperatureFk, options + ); + fail('Expected an error to be thrown when no valid travel thermograph is found'); + } catch (e) { + expect(e.message).toBe('No valid travel thermograph found'); + } + }); +}); diff --git a/modules/travel/back/methods/travel/updateThermograph.js b/modules/travel/back/methods/travel/updateThermograph.js deleted file mode 100644 index d89725920..000000000 --- a/modules/travel/back/methods/travel/updateThermograph.js +++ /dev/null @@ -1,83 +0,0 @@ -const UserError = require('vn-loopback/util/user-error'); - -module.exports = Self => { - Self.remoteMethodCtx('updateThermograph', { - description: 'Updates a travel thermograph', - accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'Number', - description: 'The travel id', - http: {source: 'path'} - }, { - arg: 'thermographId', - type: 'String', - description: 'The thermograph id', - required: true - }, { - arg: 'state', - type: 'String', - required: true - }, { - arg: 'warehouseId', - type: 'Number', - description: 'The warehouse id' - }, { - arg: 'companyId', - type: 'Number', - description: 'The company id' - }, { - arg: 'dmsTypeId', - type: 'Number', - description: 'The dms type id' - }, { - arg: 'reference', - type: 'String' - }, { - arg: 'description', - type: 'String' - }, { - arg: 'hasFileAttached', - type: 'Boolean', - description: 'True if has an attached file' - }], - returns: { - type: 'Object', - root: true - }, - http: { - path: `/:id/updateThermograph`, - verb: 'POST' - } - }); - - Self.updateThermograph = async(ctx, id, thermographId, state) => { - const models = Self.app.models; - const tx = await Self.beginTransaction({}); - - try { - const options = {transaction: tx}; - const travelThermograph = await models.TravelThermograph.findOne({ - where: { - thermographFk: thermographId, - travelFk: id - } - }, options); - - if (!travelThermograph) - throw new UserError('No valid travel thermograph found'); - - const dmsFk = travelThermograph.dmsFk; - await models.Dms.updateFile(ctx, dmsFk, options); - await travelThermograph.updateAttributes({ - result: state - }, options); - - await tx.commit(); - return travelThermograph; - } catch (e) { - await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/travel/back/models/travel-thermograph.json b/modules/travel/back/models/travel-thermograph.json index cc8e60aaf..cb0a9b4f8 100644 --- a/modules/travel/back/models/travel-thermograph.json +++ b/modules/travel/back/models/travel-thermograph.json @@ -28,6 +28,14 @@ "warehouseFk": { "type": "number", "required": true + }, + "maxTemperature": { + "type": "number", + "description": "Maximum temperature" + }, + "minTemperature": { + "type": "number", + "description": "Minimum temperature" } }, "relations": { diff --git a/modules/travel/back/models/travel.js b/modules/travel/back/models/travel.js index 4bcf7b31d..369be7919 100644 --- a/modules/travel/back/models/travel.js +++ b/modules/travel/back/models/travel.js @@ -4,9 +4,8 @@ module.exports = Self => { require('../methods/travel/getTravel')(Self); require('../methods/travel/getEntries')(Self); require('../methods/travel/filter')(Self); - require('../methods/travel/createThermograph')(Self); require('../methods/travel/deleteThermograph')(Self); - require('../methods/travel/updateThermograph')(Self); + require('../methods/travel/saveThermograph')(Self); require('../methods/travel/extraCommunityFilter')(Self); require('../methods/travel/getAverageDays')(Self); require('../methods/travel/cloneWithEntries')(Self); diff --git a/modules/travel/front/basic-data/index.html b/modules/travel/front/basic-data/index.html deleted file mode 100644 index 783208d9a..000000000 --- a/modules/travel/front/basic-data/index.html +++ /dev/null @@ -1,92 +0,0 @@ - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/modules/travel/front/basic-data/index.js b/modules/travel/front/basic-data/index.js deleted file mode 100644 index 581fd71e5..000000000 --- a/modules/travel/front/basic-data/index.js +++ /dev/null @@ -1,21 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -class Controller extends Section { - onSubmit() { - return this.$.watcher.submit().then(() => - this.card.reload() - ); - } -} - -ngModule.vnComponent('vnTravelBasicData', { - template: require('./index.html'), - controller: Controller, - bindings: { - travel: '<' - }, - require: { - card: '^vnTravelCard' - } -}); diff --git a/modules/travel/front/basic-data/index.spec.js b/modules/travel/front/basic-data/index.spec.js deleted file mode 100644 index 11894d6e0..000000000 --- a/modules/travel/front/basic-data/index.spec.js +++ /dev/null @@ -1,28 +0,0 @@ -import './index.js'; - -describe('Travel Component vnTravelBasicData', () => { - let controller; - - beforeEach(angular.mock.module('travel', $translateProvider => { - $translateProvider.translations('en', {}); - })); - - beforeEach(inject($componentController => { - const $element = angular.element(''); - controller = $componentController('vnTravelBasicData', {$element}); - controller.card = {reload: () => {}}; - controller.$.watcher = {submit: () => {}}; - })); - - describe('onSubmit()', () => { - it('should call the card reload method after the watcher submits', done => { - jest.spyOn(controller.card, 'reload'); - jest.spyOn(controller.$.watcher, 'submit').mockReturnValue(Promise.resolve()); - - controller.onSubmit().then(() => { - expect(controller.card.reload).toHaveBeenCalledWith(); - done(); - }).catch(done.fail); - }); - }); -}); diff --git a/modules/travel/front/basic-data/locale/es.yml b/modules/travel/front/basic-data/locale/es.yml deleted file mode 100644 index d95675612..000000000 --- a/modules/travel/front/basic-data/locale/es.yml +++ /dev/null @@ -1 +0,0 @@ -Undo changes: Deshacer cambios diff --git a/modules/travel/front/card/index.html b/modules/travel/front/card/index.html deleted file mode 100644 index 91964be21..000000000 --- a/modules/travel/front/card/index.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/modules/travel/front/card/index.js b/modules/travel/front/card/index.js deleted file mode 100644 index d46244cb5..000000000 --- a/modules/travel/front/card/index.js +++ /dev/null @@ -1,31 +0,0 @@ -import ngModule from '../module'; -import ModuleCard from 'salix/components/module-card'; - -class Controller extends ModuleCard { - reload() { - let filter = { - include: [ - { - relation: 'warehouseIn', - scope: { - fields: ['id', 'name'] - } - }, { - relation: 'warehouseOut', - scope: { - fields: ['id', 'name'] - } - } - ] - }; - - this.$http.get(`Travels/${this.$params.id}`, {filter}) - .then(response => this.travel = response.data); - } -} - -ngModule.vnComponent('vnTravelCard', { - template: require('./index.html'), - controller: Controller -}); - diff --git a/modules/travel/front/create/index.html b/modules/travel/front/create/index.html deleted file mode 100644 index 593887a22..000000000 --- a/modules/travel/front/create/index.html +++ /dev/null @@ -1,61 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/modules/travel/front/create/index.js b/modules/travel/front/create/index.js deleted file mode 100644 index a85917ca8..000000000 --- a/modules/travel/front/create/index.js +++ /dev/null @@ -1,48 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -class Controller extends Section { - $onChanges() { - if (this.$params && this.$params.q) - this.travel = JSON.parse(this.$params.q); - } - - onShippedChange(value) { - let hasFilledProperties; - let hasAgencyMode; - if (this.travel) { - hasAgencyMode = Boolean(this.travel.agencyModeFk); - hasFilledProperties = this.travel.landed || this.travel.warehouseInFk || this.travel.warehouseOutFk; - } - if (!hasAgencyMode || hasFilledProperties) - return; - - const query = `travels/getAverageDays`; - const params = { - agencyModeFk: this.travel.agencyModeFk - }; - this.$http.get(query, {params}).then(res => { - if (!res.data) - return; - - const landed = new Date(value); - const futureDate = landed.getDate() + res.data.dayDuration; - landed.setDate(futureDate); - - this.travel.landed = landed; - this.travel.warehouseInFk = res.data.warehouseInFk; - this.travel.warehouseOutFk = res.data.warehouseOutFk; - }); - } - - onSubmit() { - return this.$.watcher.submit().then( - res => this.$state.go('travel.card.basicData', {id: res.data.id}) - ); - } -} - -ngModule.vnComponent('vnTravelCreate', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/travel/front/create/index.spec.js b/modules/travel/front/create/index.spec.js deleted file mode 100644 index cdff8cfb9..000000000 --- a/modules/travel/front/create/index.spec.js +++ /dev/null @@ -1,88 +0,0 @@ -import './index'; -import watcher from 'core/mocks/watcher'; - -describe('Travel Component vnTravelCreate', () => { - let $scope; - let $state; - let controller; - let $httpBackend; - - beforeEach(ngModule('travel')); - - beforeEach(inject(($componentController, $rootScope, _$state_, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - $state = _$state_; - $scope.watcher = watcher; - const $element = angular.element(''); - controller = $componentController('vnTravelCreate', {$element, $scope}); - })); - - describe('onSubmit()', () => { - it(`should call submit() on the watcher then expect a callback`, () => { - jest.spyOn($state, 'go'); - - controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('travel.card.basicData', {id: 1234}); - }); - }); - - describe('$onChanges()', () => { - it('should update the travel data when $params.q is defined', () => { - controller.$params = {q: '{"ref": 1,"agencyModeFk": 1}'}; - - const params = {q: '{"ref": 1, "agencyModeFk": 1}'}; - const json = JSON.parse(params.q); - - controller.$onChanges(); - - expect(controller.travel).toEqual(json); - }); - }); - - describe('onShippedChange()', () => { - it(`should do nothing if there's no agencyModeFk in the travel.`, () => { - controller.travel = {}; - controller.onShippedChange(); - - expect(controller.travel.landed).toBeUndefined(); - expect(controller.travel.warehouseInFk).toBeUndefined(); - expect(controller.travel.warehouseOutFk).toBeUndefined(); - }); - - it(`should do nothing if there's no response data.`, () => { - controller.travel = {agencyModeFk: 4}; - const tomorrow = Date.vnNew(); - - const query = `travels/getAverageDays?agencyModeFk=${controller.travel.agencyModeFk}`; - $httpBackend.expectGET(query).respond(undefined); - controller.onShippedChange(tomorrow); - $httpBackend.flush(); - - expect(controller.travel.warehouseInFk).toBeUndefined(); - expect(controller.travel.warehouseOutFk).toBeUndefined(); - expect(controller.travel.dayDuration).toBeUndefined(); - }); - - it(`should fill the fields when it's selected a date and agency.`, () => { - controller.travel = {agencyModeFk: 1}; - const tomorrow = Date.vnNew(); - tomorrow.setDate(tomorrow.getDate() + 9); - const expectedResponse = { - id: 8, - dayDuration: 9, - warehouseInFk: 5, - warehouseOutFk: 1 - }; - - const query = `travels/getAverageDays?agencyModeFk=${controller.travel.agencyModeFk}`; - $httpBackend.expectGET(query).respond(expectedResponse); - controller.onShippedChange(tomorrow); - $httpBackend.flush(); - - expect(controller.travel.warehouseInFk).toEqual(expectedResponse.warehouseInFk); - expect(controller.travel.warehouseOutFk).toEqual(expectedResponse.warehouseOutFk); - }); - }); -}); diff --git a/modules/travel/front/descriptor-menu/index.html b/modules/travel/front/descriptor-menu/index.html deleted file mode 100644 index 19831860b..000000000 --- a/modules/travel/front/descriptor-menu/index.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - Clone travel - - - Clone travel and his entries - - - Delete travel - - - Add entry - - - - - - - - - - - - - - - diff --git a/modules/travel/front/descriptor-menu/index.js b/modules/travel/front/descriptor-menu/index.js deleted file mode 100644 index f68502ec3..000000000 --- a/modules/travel/front/descriptor-menu/index.js +++ /dev/null @@ -1,95 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $) { - super($element, $); - } - - get travelId() { - return this._travelId; - } - - set travelId(value) { - this._travelId = value; - - if (value) this.loadData(); - } - - loadData() { - const filter = { - fields: [ - 'id', - 'ref', - 'shipped', - 'landed', - 'totalEntries', - 'agencyModeFk', - 'warehouseInFk', - 'warehouseOutFk', - 'cargoSupplierFk' - ], - include: [ - { - relation: 'warehouseIn', - scope: { - fields: ['name'] - } - }, { - relation: 'warehouseOut', - scope: { - fields: ['name'] - } - } - ] - }; - this.$http.get(`Travels/${this.travelId}`, {filter}) - .then(res => this.travel = res.data); - - this.$http.get(`Travels/${this.travelId}/getEntries`) - .then(res => this.entries = res.data); - } - - get isBuyer() { - return this.aclService.hasAny(['buyer']); - } - - onDeleteAccept() { - this.$http.delete(`Travels/${this.travelId}`) - .then(() => this.$state.go('travel.index')) - .then(() => this.vnApp.showSuccess(this.$t('Travel deleted'))); - } - - onCloneAccept() { - const params = JSON.stringify({ - ref: this.travel.ref, - agencyModeFk: this.travel.agencyModeFk, - shipped: this.travel.shipped, - landed: this.travel.landed, - warehouseInFk: this.travel.warehouseInFk, - warehouseOutFk: this.travel.warehouseOutFk - }); - this.$state.go('travel.create', {q: params}); - } - - async redirectToCreateEntry() { - this.$state.go('home'); - window.location.href = await this.vnApp.getUrl(`entry/create?travelFk=${this.travelId}`); - } - - onCloneWithEntriesAccept() { - this.$http.post(`Travels/${this.travelId}/cloneWithEntries`) - .then(res => this.$state.go('travel.card.basicData', {id: res.data})); - } -} - -Controller.$inject = ['$element', '$scope']; - -ngModule.vnComponent('vnTravelDescriptorMenu', { - template: require('./index.html'), - controller: Controller, - bindings: { - travelId: '<', - } -}); diff --git a/modules/travel/front/descriptor-menu/index.spec.js b/modules/travel/front/descriptor-menu/index.spec.js deleted file mode 100644 index 40319e8e2..000000000 --- a/modules/travel/front/descriptor-menu/index.spec.js +++ /dev/null @@ -1,71 +0,0 @@ -import './index.js'; - -describe('Travel Component vnTravelDescriptorMenu', () => { - let controller; - let $httpBackend; - beforeEach(ngModule('travel')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - const $element = angular.element(''); - controller = $componentController('vnTravelDescriptorMenu', {$element}); - controller._travelId = 5; - })); - - describe('onCloneAccept()', () => { - it('should call state.go with the travel data', () => { - jest.spyOn(controller.$state, 'go').mockReturnValue('ok'); - - controller.travel = { - ref: 'the ref', - agencyModeFk: 'the agency', - shipped: 'the shipped date', - landed: 'the landing date', - warehouseInFk: 'the receiver warehouse', - warehouseOutFk: 'the sender warehouse' - }; - - controller.onCloneAccept(); - - const params = JSON.stringify({ - ref: controller.travel.ref, - agencyModeFk: controller.travel.agencyModeFk, - shipped: controller.travel.shipped, - landed: controller.travel.landed, - warehouseInFk: controller.travel.warehouseInFk, - warehouseOutFk: controller.travel.warehouseOutFk - }); - - expect(controller.$state.go).toHaveBeenCalledWith('travel.create', {'q': params}); - }); - }); - - describe('onDeleteAccept()', () => { - it('should perform a delete query', () => { - jest.spyOn(controller.$state, 'go').mockReturnValue('ok'); - controller.travelId = 1; - - $httpBackend.when('GET', `Travels/${controller.travelId}`).respond(200); - $httpBackend.when('GET', `Travels/${controller.travelId}/getEntries`).respond(200); - $httpBackend.expect('DELETE', `Travels/${controller.travelId}`).respond(200); - controller.onDeleteAccept(); - $httpBackend.flush(); - - expect(controller.$state.go).toHaveBeenCalledWith('travel.index'); - }); - }); - - describe('onCloneWithEntriesAccept()', () => { - it('should make an HTTP query and then call to the $state.go method with the returned id', () => { - jest.spyOn(controller.$state, 'go').mockReturnValue('ok'); - - $httpBackend.expect('POST', `Travels/${controller.travelId}/cloneWithEntries`).respond(200, 9); - controller.onCloneWithEntriesAccept(); - $httpBackend.flush(); - - expect(controller.$state.go).toHaveBeenCalledWith('travel.card.basicData', { - id: jasmine.any(Number) - }); - }); - }); -}); diff --git a/modules/travel/front/descriptor-menu/locale/es.yml b/modules/travel/front/descriptor-menu/locale/es.yml deleted file mode 100644 index e019d1769..000000000 --- a/modules/travel/front/descriptor-menu/locale/es.yml +++ /dev/null @@ -1,8 +0,0 @@ -Clone travel: Clonar envío -Add entry: Añadir entrada -Clone travel and his entries: Clonar travel y sus entradas -Do you want to clone this travel and all containing entries?: ¿Quieres clonar este travel y todas las entradas que contiene? -Delete travel: Eliminar envío -The travel will be deleted: El envío será eliminado -Do you want to delete this travel?: ¿Quieres eliminar este envío? -Travel deleted: Envío eliminado \ No newline at end of file diff --git a/modules/travel/front/descriptor-menu/style.scss b/modules/travel/front/descriptor-menu/style.scss deleted file mode 100644 index beab9335e..000000000 --- a/modules/travel/front/descriptor-menu/style.scss +++ /dev/null @@ -1,24 +0,0 @@ -@import "./effects"; -@import "variables"; - -vn-travel-descriptor-menu { - & > vn-icon-button[icon="more_vert"] { - display: flex; - min-width: 45px; - height: 45px; - box-sizing: border-box; - align-items: center; - justify-content: center; - } - & > vn-icon-button[icon="more_vert"] { - @extend %clickable; - color: inherit; - - & > vn-icon { - padding: 10px; - } - vn-icon { - font-size: 1.75rem; - } - } -} \ No newline at end of file diff --git a/modules/travel/front/descriptor-popover/index.html b/modules/travel/front/descriptor-popover/index.html deleted file mode 100644 index 376423bbc..000000000 --- a/modules/travel/front/descriptor-popover/index.html +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/modules/travel/front/descriptor-popover/index.js b/modules/travel/front/descriptor-popover/index.js deleted file mode 100644 index 12c5908ca..000000000 --- a/modules/travel/front/descriptor-popover/index.js +++ /dev/null @@ -1,9 +0,0 @@ -import ngModule from '../module'; -import DescriptorPopover from 'salix/components/descriptor-popover'; - -class Controller extends DescriptorPopover {} - -ngModule.vnComponent('vnTravelDescriptorPopover', { - slotTemplate: require('./index.html'), - controller: Controller -}); diff --git a/modules/travel/front/descriptor/index.html b/modules/travel/front/descriptor/index.html deleted file mode 100644 index bbf5721fd..000000000 --- a/modules/travel/front/descriptor/index.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - -
- - - - - - - - - - -
- -
-
- - - \ No newline at end of file diff --git a/modules/travel/front/descriptor/index.js b/modules/travel/front/descriptor/index.js deleted file mode 100644 index b1f2f53be..000000000 --- a/modules/travel/front/descriptor/index.js +++ /dev/null @@ -1,63 +0,0 @@ -import ngModule from '../module'; -import Descriptor from 'salix/components/descriptor'; - -class Controller extends Descriptor { - get travel() { - return this.entity; - } - - set travel(value) { - this.entity = value; - } - - get travelFilter() { - let travelFilter; - const travel = this.travel; - - if (travel && travel.agencyModeFk) { - travelFilter = this.travel && JSON.stringify({ - agencyModeFk: this.travel.agencyModeFk - }); - } - return travelFilter; - } - - loadData() { - const filter = { - fields: [ - 'id', - 'ref', - 'shipped', - 'landed', - 'totalEntries', - 'warehouseInFk', - 'warehouseOutFk', - 'cargoSupplierFk' - ], - include: [ - { - relation: 'warehouseIn', - scope: { - fields: ['name'] - } - }, { - relation: 'warehouseOut', - scope: { - fields: ['name'] - } - } - ] - }; - - return this.getData(`Travels/${this.id}`, {filter}) - .then(res => this.entity = res.data); - } -} - -ngModule.vnComponent('vnTravelDescriptor', { - template: require('./index.html'), - controller: Controller, - bindings: { - travel: '<' - } -}); diff --git a/modules/travel/front/descriptor/index.spec.js b/modules/travel/front/descriptor/index.spec.js deleted file mode 100644 index 0a88c8607..000000000 --- a/modules/travel/front/descriptor/index.spec.js +++ /dev/null @@ -1,26 +0,0 @@ -import './index.js'; - -describe('vnTravelDescriptor', () => { - let controller; - let $httpBackend; - - beforeEach(ngModule('travel')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - controller = $componentController('vnTravelDescriptor', {$element: null}); - })); - - describe('loadData()', () => { - it(`should perform a get query to store the worker data into the controller`, () => { - const id = 1; - const response = 'foo'; - - $httpBackend.expectRoute('GET', `Travels/${id}`).respond(response); - controller.id = id; - $httpBackend.flush(); - - expect(controller.travel).toEqual(response); - }); - }); -}); diff --git a/modules/travel/front/descriptor/locale/es.yml b/modules/travel/front/descriptor/locale/es.yml deleted file mode 100644 index 3e6d62735..000000000 --- a/modules/travel/front/descriptor/locale/es.yml +++ /dev/null @@ -1,6 +0,0 @@ -Reference: Referencia -Wh. In: Alm. entrada -Wh. Out: Alm. salida -Shipped: F. envío -Landed: F. entrega -Total entries: Entradas totales \ No newline at end of file diff --git a/modules/travel/front/extra-community-search-panel/index.html b/modules/travel/front/extra-community-search-panel/index.html deleted file mode 100644 index c0d726718..000000000 --- a/modules/travel/front/extra-community-search-panel/index.html +++ /dev/null @@ -1,92 +0,0 @@ -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
diff --git a/modules/travel/front/extra-community-search-panel/index.js b/modules/travel/front/extra-community-search-panel/index.js deleted file mode 100644 index 1add11dce..000000000 --- a/modules/travel/front/extra-community-search-panel/index.js +++ /dev/null @@ -1,31 +0,0 @@ -import ngModule from '../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; - -class Controller extends SearchPanel { - constructor($, $element) { - super($, $element); - - this.filter = this.$.filter; - } - - get shippedFrom() { - return this.filter.shippedFrom; - } - - set shippedFrom(value) { - this.filter.shippedFrom = value; - } - - get landedTo() { - return this.filter.landedTo; - } - - set landedTo(value) { - this.filter.landedTo = value; - } -} - -ngModule.vnComponent('vnExtraCommunitySearchPanel', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/travel/front/extra-community/index.html b/modules/travel/front/extra-community/index.html deleted file mode 100644 index 8132bddb1..000000000 --- a/modules/travel/front/extra-community/index.html +++ /dev/null @@ -1,189 +0,0 @@ - - - - - - - - - -
- - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Id - - Supplier - - Agency - - Amount - - Reference - - Packages - - Bl. KG - - Phy. KG - - Vol. KG - - Wh. Out - - W. Shipped - - Wh. In - - W. Landed -
- - {{::travel.id}} - - - - {{::travel.cargoSupplierNickname}} - - {{::travel.agencyModeName}} - - {{travel.ref}} - - - - - - {{::travel.stickers}} - - {{travel.kg}} - - - - - - {{::travel.loadedKg}}{{::travel.volumeKg}}{{::travel.warehouseOutName}}{{::travel.shipped | date: 'dd/MM/yyyy'}}{{::travel.warehouseInName}}{{::travel.landed | date: 'dd/MM/yyyy'}}
- - {{::entry.id}} - - - - {{::entry.supplierName}} - - {{::entry.invoiceAmount | currency: 'EUR': 2}}{{::entry.reference}}{{::entry.stickers}}{{::entry.loadedkg}}{{::entry.volumeKg}}
-
-
-
- - - - - - diff --git a/modules/travel/front/extra-community/index.js b/modules/travel/front/extra-community/index.js deleted file mode 100644 index 6e9c39f43..000000000 --- a/modules/travel/front/extra-community/index.js +++ /dev/null @@ -1,162 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $, vnReport) { - super($element, $); - - this.vnReport = vnReport; - - const draggable = this.element.querySelector('.travel-list'); - draggable.addEventListener('dragstart', - event => this.dragStart(event)); - draggable.addEventListener('dragend', - event => this.dragEnd(event)); - - draggable.addEventListener('dragover', - event => this.dragOver(event)); - draggable.addEventListener('dragenter', - event => this.dragEnter(event)); - draggable.addEventListener('dragleave', - event => this.dragLeave(event)); - - this.draggableElement = 'tr[draggable]'; - this.droppableElement = 'tbody[vn-droppable]'; - - const twoDays = 2; - const shippedFrom = Date.vnNew(); - shippedFrom.setDate(shippedFrom.getDate() - twoDays); - shippedFrom.setHours(0, 0, 0, 0); - - const sevenDays = 7; - const landedTo = Date.vnNew(); - landedTo.setDate(landedTo.getDate() + sevenDays); - landedTo.setHours(23, 59, 59, 59); - - this.defaultFilter = { - shippedFrom: shippedFrom, - landedTo: landedTo, - continent: 'AM' - }; - - this.smartTableOptions = {}; - } - - onDragInterval() { - if (this.dragClientY > 0 && this.dragClientY < 75) - this.$window.scrollTo(0, this.$window.scrollY - 10); - - const maxHeight = window.screen.availHeight - (window.outerHeight - window.innerHeight); - if (this.dragClientY > maxHeight - 75 && this.dragClientY < maxHeight) - this.$window.scrollTo(0, this.$window.scrollY + 10); - } - - findDraggable($event) { - const target = $event.target; - const draggable = target.closest(this.draggableElement); - - return draggable; - } - - findDroppable($event) { - const target = $event.target; - const droppable = target.closest(this.droppableElement); - - return droppable; - } - - dragStart($event) { - const draggable = this.findDraggable($event); - draggable.classList.add('dragging'); - - const id = parseInt(draggable.id); - this.entryId = id; - this.entry = draggable; - this.interval = setInterval(() => this.onDragInterval(), 50); - } - - dragEnd($event) { - const draggable = this.findDraggable($event); - draggable.classList.remove('dragging'); - this.entryId = null; - this.entry = null; - - clearInterval(this.interval); - } - - onDrop($event) { - const model = this.$.model; - const droppable = this.findDroppable($event); - const travelId = parseInt(droppable.id); - - const currentDroppable = this.entry.closest(this.droppableElement); - - if (currentDroppable == droppable) return; - - if (this.entryId && travelId) { - const path = `Entries/${this.entryId}`; - this.$http.patch(path, {travelFk: travelId}) - .then(() => model.refresh()) - .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))); - } - } - - undrop() { - if (!this.dropping) return; - this.dropping.classList.remove('dropping'); - this.dropping = null; - } - - dragOver($event) { - this.dragClientY = $event.clientY; - $event.preventDefault(); - } - - dragEnter($event) { - let element = this.findDroppable($event); - if (element) this.dropCount++; - - if (element != this.dropping) { - this.undrop(); - if (element) element.classList.add('dropping'); - this.dropping = element; - } - } - - dragLeave($event) { - let element = this.findDroppable($event); - - if (element) { - this.dropCount--; - if (this.dropCount == 0) this.undrop(); - } - } - - save(id, data) { - const endpoint = `Travels/${id}`; - this.$http.patch(endpoint, data) - .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))); - } - - get reportParams() { - const userParams = this.$.model.userParams; - const currentFilter = this.$.model.currentFilter; - - return Object.assign({ - authorization: this.vnToken.tokenMultimedia, - filter: currentFilter - }, userParams); - } - - showReport() { - this.vnReport.show(`Travels/extra-community-pdf`, this.reportParams); - } -} - -Controller.$inject = ['$element', '$scope', 'vnReport']; - -ngModule.vnComponent('vnTravelExtraCommunity', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/travel/front/extra-community/index.spec.js b/modules/travel/front/extra-community/index.spec.js deleted file mode 100644 index 18ddee665..000000000 --- a/modules/travel/front/extra-community/index.spec.js +++ /dev/null @@ -1,128 +0,0 @@ -import './index.js'; - -describe('Travel Component vnTravelExtraCommunity', () => { - let controller; - let $httpBackend; - - beforeEach(ngModule('travel')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - const $element = angular.element('
'); - controller = $componentController('vnTravelExtraCommunity', {$element}); - controller.$.model = {}; - controller.$.model.refresh = jest.fn(); - })); - - describe('findDraggable()', () => { - it('should find the draggable element', () => { - const draggable = document.createElement('tr'); - draggable.setAttribute('draggable', true); - - const $event = new Event('dragstart'); - const target = document.createElement('div'); - draggable.appendChild(target); - target.dispatchEvent($event); - - const result = controller.findDraggable($event); - - expect(result).toEqual(draggable); - }); - }); - - describe('findDroppable()', () => { - it('should find the droppable element', () => { - const droppable = document.createElement('tbody'); - droppable.setAttribute('vn-droppable', true); - - const $event = new Event('drop'); - const target = document.createElement('div'); - droppable.appendChild(target); - target.dispatchEvent($event); - - const result = controller.findDroppable($event); - - expect(result).toEqual(droppable); - }); - }); - - describe('dragStart()', () => { - it(`should add the class "dragging" to the draggable element - and then set the entryId controller property`, () => { - const draggable = document.createElement('tr'); - draggable.setAttribute('draggable', true); - draggable.setAttribute('id', 3); - - jest.spyOn(controller, 'findDraggable').mockReturnValue(draggable); - - const $event = new Event('dragStart'); - controller.dragStart($event); - - const firstClass = draggable.classList[0]; - - expect(firstClass).toEqual('dragging'); - expect(controller.entryId).toEqual(3); - expect(controller.entry).toEqual(draggable); - }); - }); - - describe('dragEnd()', () => { - it(`should remove the class "dragging" from the draggable element - and then set the entryId controller property to null`, () => { - const draggable = document.createElement('tr'); - draggable.setAttribute('draggable', true); - draggable.setAttribute('id', 3); - draggable.classList.add('dragging'); - - jest.spyOn(controller, 'findDraggable').mockReturnValue(draggable); - - const $event = new Event('dragStart'); - controller.dragEnd($event); - - const classList = draggable.classList; - - expect(classList.length).toEqual(0); - expect(controller.entryId).toBeNull(); - expect(controller.entry).toBeNull(); - }); - }); - - describe('onDrop()', () => { - it('should make an HTTP patch query', () => { - const droppable = document.createElement('tbody'); - droppable.setAttribute('vn-droppable', true); - droppable.setAttribute('id', 1); - - jest.spyOn(controller, 'findDroppable').mockReturnValue(droppable); - - const oldDroppable = document.createElement('tbody'); - oldDroppable.setAttribute('vn-droppable', true); - const entry = document.createElement('div'); - oldDroppable.appendChild(entry); - - controller.entryId = 3; - controller.entry = entry; - - const $event = new Event('drop'); - const expectedData = {travelFk: 1}; - $httpBackend.expect('PATCH', `Entries/3`, expectedData).respond(200); - controller.onDrop($event); - $httpBackend.flush(); - }); - }); - - describe('save()', () => { - it('should make an HTTP query', () => { - jest.spyOn(controller.vnApp, 'showSuccess'); - - const travelId = 1; - const data = {ref: 'New reference'}; - const expectedData = {ref: 'New reference'}; - $httpBackend.expect('PATCH', `Travels/${travelId}`, expectedData).respond(200); - controller.save(travelId, data); - $httpBackend.flush(); - - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); - }); - }); -}); diff --git a/modules/travel/front/extra-community/locale/es.yml b/modules/travel/front/extra-community/locale/es.yml deleted file mode 100644 index ed6179c91..000000000 --- a/modules/travel/front/extra-community/locale/es.yml +++ /dev/null @@ -1,11 +0,0 @@ -Family: Familia -Extra community: Extra comunitarios -Freighter: Transitario -Bl. KG: KG Bloq. -Phy. KG: KG físico -Vol. KG: KG Vol. -Search by travel id or reference: Buscar por id de travel o referencia -Search by extra community travel: Buscar por envío extra comunitario -Continent Out: Cont. salida -W. Shipped: F. envío -W. Landed: F. llegada diff --git a/modules/travel/front/extra-community/style.scss b/modules/travel/front/extra-community/style.scss deleted file mode 100644 index fb64822f9..000000000 --- a/modules/travel/front/extra-community/style.scss +++ /dev/null @@ -1,67 +0,0 @@ -@import "variables"; - -vn-travel-extra-community { - .header { - margin-bottom: 16px; - line-height: 1; - padding: 7px; - padding-bottom: 7px; - padding-bottom: 4px; - font-weight: lighter; - background-color: $color-bg; - color: white; - border-bottom: 1px solid #f7931e; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - cursor: pointer; - .multi-line{ - padding-top: 15px; - padding-bottom: 15px; - } - } - - table[vn-droppable] { - border-radius: 0; - } - - tr[draggable] { - transition: all .5s; - cursor: move; - overflow: auto; - outline: 0; - height: 65px; - pointer-events: fill; - user-select: all; - } - - tr[draggable] *::selection { - background-color: transparent; - } - - tr[draggable]:hover { - background-color: $color-hover-cd; - } - - tr[draggable].dragging { - background-color: $color-primary-light; - color: $color-font-light; - font-weight: bold; - } - - - .multi-line{ - max-width: 200px; - word-wrap: normal; - white-space: normal; - } - - vn-td-editable text { - background-color: transparent; - padding: 0; - border: 0; - border-bottom: 1px dashed $color-active; - border-radius: 0; - color: $color-active - } -} diff --git a/modules/travel/front/index.js b/modules/travel/front/index.js index e4375c59d..a7209a0bd 100644 --- a/modules/travel/front/index.js +++ b/modules/travel/front/index.js @@ -1,18 +1,3 @@ export * from './module'; import './main'; -import './index/'; -import './search-panel'; -import './descriptor'; -import './card'; -import './summary'; -import './basic-data'; -import './log'; -import './create'; -import './thermograph/index/'; -import './thermograph/create/'; -import './thermograph/edit/'; -import './descriptor-popover'; -import './descriptor-menu'; -import './extra-community'; -import './extra-community-search-panel'; diff --git a/modules/travel/front/index/index.html b/modules/travel/front/index/index.html deleted file mode 100644 index a768e4a29..000000000 --- a/modules/travel/front/index/index.html +++ /dev/null @@ -1,107 +0,0 @@ - - - - - - - - - - - - - Reference - Agency - Warehouse Out - Shipped - - Warehouse In - Landed - - Total entries - - - - - - {{::travel.ref}} - {{::travel.agencyModeName}} - {{::travel.warehouseOutName}} - - - {{::travel.shipped | date:'dd/MM/yyyy'}} - - - - - - - {{::travel.warehouseInName}} - - - {{::travel.landed | date:'dd/MM/yyyy'}} - - - - - - - {{::travel.totalEntries}} - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/modules/travel/front/index/index.js b/modules/travel/front/index/index.js deleted file mode 100644 index a570146fe..000000000 --- a/modules/travel/front/index/index.js +++ /dev/null @@ -1,39 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -export default class Controller extends Section { - preview(travel) { - this.travelSelected = travel; - this.$.summary.show(); - } - - onCloneAccept(travel) { - const params = JSON.stringify({ - ref: travel.ref, - agencyModeFk: travel.agencyModeFk, - shipped: travel.shipped, - landed: travel.landed, - warehouseInFk: travel.warehouseInFk, - warehouseOutFk: travel.warehouseOutFk - }); - this.$state.go('travel.create', {q: params}); - } - - compareDate(date) { - let today = Date.vnNew(); - today.setHours(0, 0, 0, 0); - - date = new Date(date); - date.setHours(0, 0, 0, 0); - - const timeDifference = today - date; - if (timeDifference == 0) return 'warning'; - if (timeDifference < 0) return 'success'; - } -} - -ngModule.vnComponent('vnTravelIndex', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/travel/front/index/index.spec.js b/modules/travel/front/index/index.spec.js deleted file mode 100644 index 9083c4519..000000000 --- a/modules/travel/front/index/index.spec.js +++ /dev/null @@ -1,78 +0,0 @@ -import './index.js'; - -describe('Travel Component vnTravelIndex', () => { - let controller; - let travel = { - id: 1, - warehouseInFk: 1, - totalEntries: 3, - isDelivered: false - }; - - beforeEach(ngModule('travel')); - - beforeEach(inject($componentController => { - const $element = angular.element(''); - controller = $componentController('vnTravelIndex', {$element}); - controller.$.summary = {show: jasmine.createSpy('show')}; - })); - - describe('preview()', () => { - it('should show the dialog summary', () => { - let event = new MouseEvent('click', { - bubbles: true, - cancelable: true - }); - controller.preview(event, travel); - - expect(controller.$.summary.show).toHaveBeenCalledWith(); - }); - }); - - describe('onCloneAccept()', () => { - it('should call go() then update travelSelected in the controller', () => { - jest.spyOn(controller.$state, 'go'); - - const travel = { - ref: 1, - agencyModeFk: 1 - }; - const travelParams = { - ref: travel.ref, - agencyModeFk: travel.agencyModeFk - }; - const queryParams = JSON.stringify(travelParams); - controller.onCloneAccept(travel); - - expect(controller.$state.go).toHaveBeenCalledWith('travel.create', {q: queryParams}); - }); - }); - - describe('compareDate()', () => { - it('should return warning if the date passed to compareDate() is todays', () => { - const today = Date.vnNew(); - - const result = controller.compareDate(today); - - expect(result).toEqual('warning'); - }); - - it('should return success if the date passed to compareDate() is in the future', () => { - const tomorrow = Date.vnNew(); - tomorrow.setDate(tomorrow.getDate() + 1); - - const result = controller.compareDate(tomorrow); - - expect(result).toEqual('success'); - }); - - it('should return undefined if the date passed to compareDate() is in the past', () => { - const yesterday = Date.vnNew(); - yesterday.setDate(yesterday.getDate() - 1); - - const result = controller.compareDate(yesterday); - - expect(result).toBeUndefined(); - }); - }); -}); diff --git a/modules/travel/front/index/locale/es.yml b/modules/travel/front/index/locale/es.yml deleted file mode 100644 index 5ce4c502f..000000000 --- a/modules/travel/front/index/locale/es.yml +++ /dev/null @@ -1,3 +0,0 @@ -Do you want to clone this travel?: ¿Desea clonar este envio? -All it's properties will be copied: Todas sus propiedades serán copiadas -Clone: Clonar \ No newline at end of file diff --git a/modules/travel/front/index/style.scss b/modules/travel/front/index/style.scss deleted file mode 100644 index ca1cf538b..000000000 --- a/modules/travel/front/index/style.scss +++ /dev/null @@ -1,11 +0,0 @@ -@import "variables"; - -vn-travel-index { - vn-icon { - color: $color-font-secondary - } - - vn-icon.active { - color: $color-success - } -} diff --git a/modules/travel/front/log/index.html b/modules/travel/front/log/index.html deleted file mode 100644 index fc4622e5a..000000000 --- a/modules/travel/front/log/index.html +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/modules/travel/front/log/index.js b/modules/travel/front/log/index.js deleted file mode 100644 index 7af601b5c..000000000 --- a/modules/travel/front/log/index.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -ngModule.vnComponent('vnTravelLog', { - template: require('./index.html'), - controller: Section, -}); diff --git a/modules/travel/front/main/index.html b/modules/travel/front/main/index.html index 131d9409e..e69de29bb 100644 --- a/modules/travel/front/main/index.html +++ b/modules/travel/front/main/index.html @@ -1,6 +0,0 @@ - - - - - - diff --git a/modules/travel/front/main/index.js b/modules/travel/front/main/index.js index 6a153f21a..37dcbb0dc 100644 --- a/modules/travel/front/main/index.js +++ b/modules/travel/front/main/index.js @@ -5,6 +5,10 @@ export default class Travel extends ModuleMain { constructor() { super(); } + async $onInit() { + this.$state.go('home'); + window.location.href = await this.vnApp.getUrl(`travel/`); + } } ngModule.vnComponent('vnTravel', { diff --git a/modules/travel/front/routes.json b/modules/travel/front/routes.json index ccdc657d9..6891a46cf 100644 --- a/modules/travel/front/routes.json +++ b/modules/travel/front/routes.json @@ -27,80 +27,6 @@ "state": "travel.index", "component": "vn-travel-index", "description": "Travels" - }, { - "url": "/:id", - "state": "travel.card", - "abstract": true, - "component": "vn-travel-card" - }, { - "url": "/summary", - "state": "travel.card.summary", - "component": "vn-travel-summary", - "description": "Summary", - "params": { - "travel": "$ctrl.travel" - } - }, { - "url": "/basic-data", - "state": "travel.card.basicData", - "component": "vn-travel-basic-data", - "description": "Basic data", - "acl": ["buyer","logistic"], - "params": { - "travel": "$ctrl.travel" - } - }, { - "url" : "/log", - "state": "travel.card.log", - "component": "vn-travel-log", - "description": "Log" - }, { - "url": "/create?q", - "state": "travel.create", - "component": "vn-travel-create", - "description": "New travel" - }, { - "url": "/thermograph", - "state": "travel.card.thermograph", - "abstract": true, - "component": "ui-view" - }, { - "url" : "/index", - "state": "travel.card.thermograph.index", - "component": "vn-travel-thermograph-index", - "description": "Thermographs", - "params": { - "travel": "$ctrl.travel" - }, - "acl": ["buyer"] - }, { - "url" : "/create", - "state": "travel.card.thermograph.create", - "component": "vn-travel-thermograph-create", - "description": "Add thermograph", - "params": { - "travel": "$ctrl.travel" - }, - "acl": ["buyer"] - }, { - "url" : "/:thermographId/edit", - "state": "travel.card.thermograph.edit", - "component": "vn-travel-thermograph-edit", - "description": "Edit thermograph", - "params": { - "travel": "$ctrl.travel" - }, - "acl": ["buyer"] - }, - { - "url": "/extra-community?q", - "state": "travel.extraCommunity", - "component": "vn-travel-extra-community", - "description": "Extra community", - "acl": ["buyer"], - "params": { - "travel": "$ctrl.travel" - } } ] } diff --git a/modules/travel/front/search-panel/index.html b/modules/travel/front/search-panel/index.html deleted file mode 100644 index dd8d98af1..000000000 --- a/modules/travel/front/search-panel/index.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - Id/{{$ctrl.$t('Reference')}}: {{$ctrl.filter.search}} - - - {{$ctrl.$t('Agency')}}: {{agency.selection.name}} - - - {{$ctrl.$t('Warehouse Out')}}: {{warehouseOut.selection.name}} - - - {{$ctrl.$t('Warehouse In')}}: {{warehouseIn.selection.name}} - - - {{$ctrl.$t('Days onward')}}: {{$ctrl.filter.scopeDays}} - - - {{$ctrl.$t('Landed from')}}: {{$ctrl.filter.landedFrom | date:'dd/MM/yyyy'}} - - - {{$ctrl.$t('Landed to')}}: {{$ctrl.filter.landedTo | date:'dd/MM/yyyy'}} - - - {{$ctrl.$t('Continent Out')}}: {{continent.selection.name}} - - - {{$ctrl.$t('Total entries')}}: {{$ctrl.filter.totalEntries}} - -
-
diff --git a/modules/travel/front/search-panel/index.js b/modules/travel/front/search-panel/index.js deleted file mode 100644 index 5969a8c3f..000000000 --- a/modules/travel/front/search-panel/index.js +++ /dev/null @@ -1,72 +0,0 @@ -import ngModule from '../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; -import './style.scss'; - -class Controller extends SearchPanel { - constructor($, $element) { - super($, $element); - this.initFilter(); - this.fetchData(); - } - - $onChanges() { - if (this.model) - this.applyFilters(); - } - - fetchData() { - this.$http.get('AgencyModes').then(res => { - this.agencyModes = res.data; - }); - this.$http.get('Warehouses').then(res => { - this.warehouses = res.data; - }); - this.$http.get('Continents').then(res => { - this.continents = res.data; - }); - } - - initFilter() { - this.filter = {}; - if (this.$params.q) { - this.filter = JSON.parse(this.$params.q); - this.search = this.filter.search; - this.totalEntries = this.filter.totalEntries; - } - if (!this.filter.scopeDays) this.filter.scopeDays = 7; - } - - applyFilters(param) { - if (this.filter?.search) - delete this.filter.scopeDays; - - this.model.applyFilter({}, this.filter) - .then(() => { - if (param && this.model._orgData.length === 1) - this.$state.go('travel.card.summary', {id: this.model._orgData[0].id}); - else - this.$state.go(this.$state.current.name, {q: JSON.stringify(this.filter)}, {location: 'replace'}); - }); - } - - removeParamFilter(param) { - if (this[param]) delete this[param]; - delete this.filter[param]; - this.applyFilters(); - } - - onKeyPress($event, param) { - if ($event.key === 'Enter') { - this.filter[param] = this[param]; - this.applyFilters(param === 'search'); - } - } -} - -ngModule.vnComponent('vnTravelSearchPanel', { - template: require('./index.html'), - controller: Controller, - bindings: { - model: '<' - } -}); diff --git a/modules/travel/front/search-panel/index.spec.js b/modules/travel/front/search-panel/index.spec.js deleted file mode 100644 index 488143e80..000000000 --- a/modules/travel/front/search-panel/index.spec.js +++ /dev/null @@ -1,38 +0,0 @@ -import './index'; - -describe('Travel Component vnTravelSearchPanel', () => { - let controller; - - beforeEach(ngModule('travel')); - - beforeEach(inject($componentController => { - controller = $componentController('vnTravelSearchPanel', {$element: null}); - controller.$t = () => {}; - })); - - describe('applyFilters()', () => { - it('should apply filters', async() => { - controller.filter = {foo: 'bar'}; - controller.model = { - applyFilter: jest.fn().mockResolvedValue(), - _orgData: [{id: 1}] - }; - controller.$state = { - current: { - name: 'foo' - }, - go: jest.fn() - }; - - await controller.applyFilters(true); - - expect(controller.model.applyFilter).toHaveBeenCalledWith({}, controller.filter); - expect(controller.$state.go).toHaveBeenCalledWith('travel.card.summary', {id: 1}); - - await controller.applyFilters(false); - - expect(controller.$state.go).toHaveBeenCalledWith(controller.$state.current.name, - {q: JSON.stringify(controller.filter)}, {location: 'replace'}); - }); - }); -}); diff --git a/modules/travel/front/search-panel/locale/es.yml b/modules/travel/front/search-panel/locale/es.yml deleted file mode 100644 index 1f892a742..000000000 --- a/modules/travel/front/search-panel/locale/es.yml +++ /dev/null @@ -1,7 +0,0 @@ -Ticket id: Id ticket -Client id: Id cliente -Nickname: Alias -From: Desde -To: Hasta -Agency: Agencia -Warehouse: Almacén \ No newline at end of file diff --git a/modules/travel/front/search-panel/style.scss b/modules/travel/front/search-panel/style.scss deleted file mode 100644 index 0da52408a..000000000 --- a/modules/travel/front/search-panel/style.scss +++ /dev/null @@ -1,37 +0,0 @@ -@import "variables"; - -vn-travel-search-panel vn-side-menu { - .menu { - min-width: $menu-width; - } - & > div { - .input { - padding-left: $spacing-md; - padding-right: $spacing-md; - border-color: $color-spacer; - border-bottom: $border-thin; - } - .horizontal { - padding-left: $spacing-md; - padding-right: $spacing-md; - grid-auto-flow: column; - grid-column-gap: $spacing-sm; - align-items: center; - } - .chips { - display: flex; - flex-wrap: wrap; - padding: $spacing-md; - overflow: hidden; - max-width: 100%; - border-color: $color-spacer; - } - - .or { - align-self: center; - font-weight: bold; - font-size: 26px; - color: $color-font-secondary; - } - } -} diff --git a/modules/travel/front/summary/index.html b/modules/travel/front/summary/index.html deleted file mode 100644 index d9dbb0f90..000000000 --- a/modules/travel/front/summary/index.html +++ /dev/null @@ -1,167 +0,0 @@ - -
- - - - {{$ctrl.travelData.id}} - {{$ctrl.travelData.ref}} - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Entries

- - - - Confirmed - Entry Id - Supplier - Reference - HB - Freight - Package - CC - Pallet - - - - - - - - - - - - - {{entry.id}} - - - {{entry.supplierName}} - {{entry.reference}} - {{entry.hb}} - {{entry.freightValue | currency: 'EUR': 2}} - {{entry.packageValue | currency: 'EUR': 2}} - {{entry.cc}} - {{entry.pallet}} - {{entry.m3}} - - - - - - - - - - - - - {{$ctrl.total('hb')}} - {{$ctrl.total('freightValue') | currency: 'EUR': 2}} - {{$ctrl.total('packageValue') | currency: 'EUR': 2}} - {{$ctrl.total('cc') | number:2}} - {{$ctrl.total('pallet') | number:2}} - {{$ctrl.total('m3') | number:2}} - - - - -
- -

- - Thermograph - -

-

- Thermograph -

- - - - Code - Temperature - State - Destination - Created - - - - - {{thermograph.thermographFk}} - {{thermograph.temperatureFk}} - {{thermograph.result}} - {{thermograph.warehouse.name}} - {{thermograph.created | date: 'dd/MM/yyyy'}} - - - -
-
-
- - diff --git a/modules/travel/front/summary/index.js b/modules/travel/front/summary/index.js deleted file mode 100644 index 5144a0bb5..000000000 --- a/modules/travel/front/summary/index.js +++ /dev/null @@ -1,71 +0,0 @@ -import ngModule from '../module'; -import Summary from 'salix/components/summary'; -import './style.scss'; - -class Controller extends Summary { - $onInit() { - this.entries = []; - } - - get travel() { - return this._travel; - } - - set travel(value) { - this._travel = value; - - if (value && value.id) { - this.getTravel(); - this.getEntries(); - this.getThermographs(); - } - } - - getTravel() { - return this.$http.get(`Travels/${this.travel.id}/getTravel`) - .then(res => this.travelData = res.data); - } - - getEntries() { - return this.$http.get(`Travels/${this.travel.id}/getEntries`) - .then(res => this.entries = res.data); - } - - getThermographs() { - const filter = { - include: { - relation: 'warehouse', - scope: { - fields: ['id', 'name'] - } - }, - where: { - travelFk: this.travel.id - } - }; - - return this.$http.get(`TravelThermographs`, {filter}) - .then(res => this.travelThermographs = res.data); - } - - total(field) { - let total = 0; - - for (let entry of this.entries) - total += entry[field]; - - return total; - } - - get isBuyer() { - return this.aclService.hasAny(['buyer']); - } -} - -ngModule.vnComponent('vnTravelSummary', { - template: require('./index.html'), - controller: Controller, - bindings: { - travel: '<' - } -}); diff --git a/modules/travel/front/summary/index.spec.js b/modules/travel/front/summary/index.spec.js deleted file mode 100644 index b1b750689..000000000 --- a/modules/travel/front/summary/index.spec.js +++ /dev/null @@ -1,86 +0,0 @@ -import './index'; - -describe('component vnTravelSummary', () => { - let controller; - let $httpBackend; - let $scope; - let $httpParamSerializer; - - beforeEach(angular.mock.module('travel', $translateProvider => { - $translateProvider.translations('en', {}); - })); - - beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { - $httpBackend = _$httpBackend_; - $httpParamSerializer = _$httpParamSerializer_; - $scope = $rootScope.$new(); - const $element = angular.element(``); - controller = $componentController('vnTravelSummary', {$element, $scope}); - })); - - describe('travel setter/getter', () => { - it('should return the travel and then call both getTravel() and getEntries()', () => { - jest.spyOn(controller, 'getTravel'); - jest.spyOn(controller, 'getEntries'); - jest.spyOn(controller, 'getThermographs'); - controller.travel = {id: 99}; - - expect(controller._travel.id).toEqual(99); - expect(controller.getTravel).toHaveBeenCalledWith(); - expect(controller.getEntries).toHaveBeenCalledWith(); - expect(controller.getThermographs).toHaveBeenCalledWith(); - }); - }); - - describe('getTravel()', () => { - it('should perform a get and then store data on the controller', () => { - controller._travel = {id: 999}; - - const query = `Travels/${controller._travel.id}/getTravel`; - $httpBackend.expectGET(query).respond('I am the travelData'); - controller.getTravel(); - $httpBackend.flush(); - - expect(controller.travelData).toEqual('I am the travelData'); - }); - }); - - describe('getEntries()', () => { - it('should call the getEntries method to get the entries data', () => { - controller._travel = {id: 999}; - - const query = `Travels/${controller._travel.id}/getEntries`; - $httpBackend.expectGET(query).respond('I am the entries'); - controller.getEntries(); - $httpBackend.flush(); - - expect(controller.entries).toEqual('I am the entries'); - }); - }); - - describe('getThermographs()', () => { - it('should call the getThermographs method to get the thermographs', () => { - controller._travel = {id: 2}; - - $httpBackend.expectGET(`TravelThermographs`).respond('I am the thermographs'); - controller.getThermographs(); - $httpBackend.flush(); - - expect(controller.travelThermographs).toEqual('I am the thermographs'); - }); - }); - - describe('total()', () => { - it('should calculate the total amount of a given property for every row', () => { - controller.entries = [ - {id: 1, freightValue: 1, packageValue: 2, cc: 0.01}, - {id: 2, freightValue: 1, packageValue: 2, cc: 0.01}, - {id: 3, freightValue: 1, packageValue: 2, cc: 0.01} - ]; - - expect(controller.total('freightValue')).toEqual(3); - expect(controller.total('packageValue')).toEqual(6); - expect(controller.total('cc')).toEqual(0.03); - }); - }); -}); diff --git a/modules/travel/front/summary/locale/es.yml b/modules/travel/front/summary/locale/es.yml deleted file mode 100644 index aa6adc938..000000000 --- a/modules/travel/front/summary/locale/es.yml +++ /dev/null @@ -1,18 +0,0 @@ -Reference: Referencia -Warehouse In: Alm. entrada -Warehouse Out: Alm. salida -Shipped: F. envío -Landed: F. entrega -Total entries: Ent. totales -Delivered: Enviada -Received: Recibida -Agency: Agencia -Entries: Entradas -Confirmed: Confirmada -Entry Id: Id entrada -Supplier: Proveedor -Pallet: Pallet -Freight: Porte -Package: Embalaje -Half box: Media caja -Go to the travel: Ir al envío diff --git a/modules/travel/front/summary/style.scss b/modules/travel/front/summary/style.scss deleted file mode 100644 index dd4cfa72d..000000000 --- a/modules/travel/front/summary/style.scss +++ /dev/null @@ -1,6 +0,0 @@ -@import "variables"; - - -vn-travel-summary .summary { - max-width: $width-lg; -} \ No newline at end of file diff --git a/modules/travel/front/thermograph/create/index.html b/modules/travel/front/thermograph/create/index.html deleted file mode 100644 index 41709e1fb..000000000 --- a/modules/travel/front/thermograph/create/index.html +++ /dev/null @@ -1,177 +0,0 @@ - - - - - - - - -
-
- - - - - {{thermographFk}} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/modules/travel/front/thermograph/create/index.js b/modules/travel/front/thermograph/create/index.js deleted file mode 100644 index fa2c1261a..000000000 --- a/modules/travel/front/thermograph/create/index.js +++ /dev/null @@ -1,122 +0,0 @@ -import ngModule from '../../module'; -import Section from 'salix/components/section'; -import UserError from 'core/lib/user-error'; - -class Controller extends Section { - constructor($element, $) { - super($element, $); - this.dms = {files: [], state: 'Ok'}; - } - - get travel() { - return this._travel; - } - - set travel(value) { - this._travel = value; - - if (value) { - this.setDefaultParams(); - this.getAllowedContentTypes(); - } - } - - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - - get contentTypesInfo() { - return this.$t('ContentTypesInfo', { - allowedContentTypes: this.allowedContentTypes - }); - } - - setDefaultParams() { - const params = {filter: { - where: {code: 'miscellaneous'} - }}; - this.$http.get('DmsTypes/findOne', {params}).then(res => { - const dmsTypeId = res.data && res.data.id; - const companyId = this.vnConfig.companyFk; - const warehouseId = this.vnConfig.warehouseFk; - const defaultParams = { - reference: this.travel.id, - warehouseId: warehouseId, - companyId: companyId, - dmsTypeId: dmsTypeId, - description: this.$t('TravelFileDescription', { - travelId: this.travel.id - }).toUpperCase() - }; - - this.dms = Object.assign(this.dms, defaultParams); - }); - } - - onAddThermographClick(event) { - const defaultTemperature = 'cool'; - const defaultModel = 'DISPOSABLE'; - - event.preventDefault(); - this.newThermograph = { - thermographId: this.thermographId, - warehouseId: this.warehouseId, - temperatureFk: defaultTemperature, - model: defaultModel - }; - - this.$.modelsModel.refresh(); - this.$.newThermographDialog.show(); - } - - onNewThermographAccept() { - const hasMissingField = - !this.newThermograph.thermographId || - !this.newThermograph.warehouseId || - !this.newThermograph.temperatureFk || - !this.newThermograph.model; - - if (hasMissingField) - throw new UserError(`Some fields are invalid`); - - return this.$http.post(`Thermographs/createThermograph`, this.newThermograph) - .then(res => this.dms.thermographId = res.data.id); - } - - onSubmit() { - const query = `Travels/${this.travel.id}/createThermograph`; - const options = { - method: 'POST', - url: query, - params: this.dms, - headers: { - 'Content-Type': undefined - }, - transformRequest: files => { - const formData = new FormData(); - - for (let i = 0; i < files.length; i++) - formData.append(files[i].name, files[i]); - - return formData; - }, - data: this.dms.files - }; - this.$http(options).then(res => { - this.vnApp.showSuccess(this.$t('Data saved!')); - this.$.watcher.updateOriginalData(); - this.$state.go('travel.card.thermograph.index'); - }); - } -} - -ngModule.vnComponent('vnTravelThermographCreate', { - template: require('./index.html'), - controller: Controller, - bindings: { - travel: '<' - } -}); diff --git a/modules/travel/front/thermograph/create/index.spec.js b/modules/travel/front/thermograph/create/index.spec.js deleted file mode 100644 index 1ad263d31..000000000 --- a/modules/travel/front/thermograph/create/index.spec.js +++ /dev/null @@ -1,108 +0,0 @@ -import './index'; - -describe('Ticket', () => { - describe('Component vnTravelThermographCreate', () => { - let controller; - let $httpBackend; - let $httpParamSerializer; - const travelId = 3; - const dmsTypeId = 5; - - beforeEach(ngModule('travel')); - - beforeEach(inject(($componentController, _$httpBackend_, _$httpParamSerializer_) => { - $httpBackend = _$httpBackend_; - $httpParamSerializer = _$httpParamSerializer_; - const $element = angular.element(''); - controller = $componentController('vnTravelThermographCreate', {$element}); - controller._travel = { - id: travelId - }; - })); - - describe('travel() setter', () => { - it('should set the travel data and then call setDefaultParams() and getAllowedContentTypes()', () => { - jest.spyOn(controller, 'setDefaultParams'); - jest.spyOn(controller, 'getAllowedContentTypes'); - controller.travel = { - id: travelId - }; - - expect(controller.travel).toBeDefined(); - expect(controller.setDefaultParams).toHaveBeenCalledWith(); - expect(controller.getAllowedContentTypes).toHaveBeenCalledWith(); - }); - }); - - describe('setDefaultParams()', () => { - it('should perform a GET query and define the dms property on controller', () => { - const params = {filter: { - where: {code: 'miscellaneous'} - }}; - let serializedParams = $httpParamSerializer(params); - $httpBackend.expect('GET', `DmsTypes/findOne?${serializedParams}`).respond({id: dmsTypeId, code: 'miscellaneous'}); - controller.setDefaultParams(); - $httpBackend.flush(); - - expect(controller.dms).toBeDefined(); - expect(controller.dms.reference).toEqual(travelId); - expect(controller.dms.dmsTypeId).toEqual(dmsTypeId); - }); - }); - - describe('getAllowedContentTypes()', () => { - it('should make an HTTP GET request to get the allowed content types', () => { - const expectedResponse = ['application/pdf', 'image/png', 'image/jpg']; - $httpBackend.expect('GET', `DmsContainers/allowedContentTypes`).respond(expectedResponse); - controller.getAllowedContentTypes(); - $httpBackend.flush(); - - expect(controller.allowedContentTypes).toBeDefined(); - expect(controller.allowedContentTypes).toEqual('application/pdf, image/png, image/jpg'); - }); - }); - - describe('onAddThermographClick()', () => { - it('should call the show() function of the create thermograph dialog', () => { - controller.$.newThermographDialog = {show: jest.fn()}; - controller.$.modelsModel = {refresh: jest.fn()}; - controller.$.temperaturesModel = {refresh: jest.fn()}; - - const event = new Event('click'); - jest.spyOn(event, 'preventDefault'); - - controller.onAddThermographClick(event); - - expect(event.preventDefault).toHaveBeenCalledTimes(1); - expect(controller.$.newThermographDialog.show).toHaveBeenCalledTimes(1); - }); - }); - - describe('onNewThermographAccept()', () => { - it('should set the created thermograph data on to the controller for the autocomplete to use it', () => { - const id = 'the created id'; - const warehouseId = 1; - const temperatureId = 'cool'; - const model = 'my model'; - - controller.newThermograph = { - thermographId: id, - warehouseId: warehouseId, - temperatureFk: temperatureId, - model: model - }; - const response = { - id: id, - warehouseId: warehouseId, - temperatureFk: temperatureId, - model: model - }; - $httpBackend.when('POST', `Thermographs/createThermograph`).respond(response); - controller.onNewThermographAccept(); - $httpBackend.flush(); - - expect(controller.dms.thermographId).toEqual(response.id); - }); - }); - }); -}); diff --git a/modules/travel/front/thermograph/edit/index.html b/modules/travel/front/thermograph/edit/index.html deleted file mode 100644 index 3fe448b56..000000000 --- a/modules/travel/front/thermograph/edit/index.html +++ /dev/null @@ -1,87 +0,0 @@ - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
diff --git a/modules/travel/front/thermograph/edit/index.js b/modules/travel/front/thermograph/edit/index.js deleted file mode 100644 index a8df3142d..000000000 --- a/modules/travel/front/thermograph/edit/index.js +++ /dev/null @@ -1,98 +0,0 @@ -import ngModule from '../../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - get travel() { - return this._travel; - } - - set travel(value) { - this._travel = value; - - if (value) { - this.setDefaultParams(); - this.getAllowedContentTypes(); - } - } - - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - - get contentTypesInfo() { - return this.$t('ContentTypesInfo', { - allowedContentTypes: this.allowedContentTypes - }); - } - - setDefaultParams() { - const filterObj = {include: {relation: 'dms'}}; - const filter = encodeURIComponent(JSON.stringify(filterObj)); - const path = `TravelThermographs/${this.$params.thermographId}?filter=${filter}`; - this.$http.get(path).then(res => { - const thermograph = res.data && res.data; - this.thermograph = { - thermographId: thermograph.thermographFk, - state: thermograph.result, - reference: thermograph.dms.reference, - warehouseId: thermograph.dms.warehouseFk, - companyId: thermograph.dms.companyFk, - dmsTypeId: thermograph.dms.dmsTypeFk, - description: thermograph.dms.description, - hasFile: thermograph.dms.hasFile, - hasFileAttached: false, - files: [] - }; - }); - } - - onSubmit() { - const query = `travels/${this.$params.id}/updateThermograph`; - const options = { - method: 'POST', - url: query, - params: this.thermograph, - headers: { - 'Content-Type': undefined - }, - transformRequest: files => { - const formData = new FormData(); - - for (let i = 0; i < files.length; i++) - formData.append(files[i].name, files[i]); - - return formData; - }, - data: this.thermograph.files - }; - this.$http(options).then(res => { - if (res) { - this.vnApp.showSuccess(this.$t('Data saved!')); - this.$.watcher.updateOriginalData(); - this.$state.go('travel.card.thermograph.index'); - } - }); - } - - onFileChange(files) { - let hasFileAttached = false; - if (files.length > 0) - hasFileAttached = true; - - this.$.$applyAsync(() => { - this.thermograph.hasFileAttached = hasFileAttached; - }); - } -} - -ngModule.vnComponent('vnTravelThermographEdit', { - template: require('./index.html'), - controller: Controller, - bindings: { - travel: '<' - } -}); diff --git a/modules/travel/front/thermograph/edit/index.spec.js b/modules/travel/front/thermograph/edit/index.spec.js deleted file mode 100644 index c0b044a8d..000000000 --- a/modules/travel/front/thermograph/edit/index.spec.js +++ /dev/null @@ -1,120 +0,0 @@ -import './index'; -import watcher from 'core/mocks/watcher.js'; - -describe('Worker', () => { - describe('Component vnTravelThermographEdit', () => { - let controller; - let $scope; - let $httpBackend; - let $httpParamSerializer; - - beforeEach(ngModule('travel')); - - beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { - $scope = $rootScope.$new(); - $httpBackend = _$httpBackend_; - $httpParamSerializer = _$httpParamSerializer_; - const $element = angular.element(` { - it('should set the travel data and then call setDefaultParams() and getAllowedContentTypes()', () => { - jest.spyOn(controller, 'setDefaultParams'); - jest.spyOn(controller, 'getAllowedContentTypes'); - controller._travel = undefined; - controller.travel = { - id: 3 - }; - - expect(controller.setDefaultParams).toHaveBeenCalledWith(); - expect(controller.travel).toBeDefined(); - expect(controller.getAllowedContentTypes).toHaveBeenCalledWith(); - }); - }); - - describe('setDefaultParams()', () => { - it('should perform a GET query and define the dms property on controller', () => { - const thermographId = 6; - const expectedResponse = { - thermographFk: 6, - result: 'Ok', - dms: { - reference: '123456-01', - warehouseFk: 1, - companyFk: 442, - dmsTypeFk: 3, - description: 'Test' - } - }; - - const filterObj = {include: {relation: 'dms'}}; - const filter = encodeURIComponent(JSON.stringify(filterObj)); - const query = `TravelThermographs/${thermographId}?filter=${filter}`; - $httpBackend.expect('GET', query).respond(expectedResponse); - controller.setDefaultParams(); - $httpBackend.flush(); - - expect(controller.thermograph).toBeDefined(); - expect(controller.thermograph.reference).toEqual('123456-01'); - expect(controller.thermograph.dmsTypeId).toEqual(3); - expect(controller.thermograph.state).toEqual('Ok'); - }); - }); - - describe('onFileChange()', () => { - it('should set dms hasFileAttached property to true if has any files', () => { - const files = [{id: 1, name: 'MyFile'}]; - controller.thermograph = {hasFileAttached: false}; - controller.onFileChange(files); - $scope.$apply(); - - expect(controller.thermograph.hasFileAttached).toBeTruthy(); - }); - }); - - describe('getAllowedContentTypes()', () => { - it('should make an HTTP GET request to get the allowed content types', () => { - const expectedResponse = ['image/png', 'image/jpg']; - $httpBackend.expect('GET', `DmsContainers/allowedContentTypes`).respond(expectedResponse); - controller.getAllowedContentTypes(); - $httpBackend.flush(); - - expect(controller.allowedContentTypes).toBeDefined(); - expect(controller.allowedContentTypes).toEqual('image/png, image/jpg'); - }); - }); - - describe('contentTypesInfo()', () => { - it('should return a description with a list of allowed content types', () => { - controller.allowedContentTypes = ['image/png', 'image/jpg']; - const expectedTypes = controller.allowedContentTypes.join(', '); - - const expectedResult = `Allowed content types: ${expectedTypes}`; - jest.spyOn(controller.$translate, 'instant').mockReturnValue(expectedResult); - - const result = controller.contentTypesInfo; - - expect(result).toEqual(expectedResult); - }); - }); - - describe('onSubmit()', () => { - it('should make an HTTP POST request to save the form data', () => { - jest.spyOn(controller.$.watcher, 'updateOriginalData'); - - const files = [{id: 1, name: 'MyFile'}]; - controller.thermograph = {files}; - const serializedParams = $httpParamSerializer(controller.thermograph); - const query = `travels/${controller.$params.id}/updateThermograph?${serializedParams}`; - - $httpBackend.expect('POST', query).respond({}); - controller.onSubmit(); - $httpBackend.flush(); - }); - }); - }); -}); diff --git a/modules/travel/front/thermograph/edit/style.scss b/modules/travel/front/thermograph/edit/style.scss deleted file mode 100644 index 73f136fc1..000000000 --- a/modules/travel/front/thermograph/edit/style.scss +++ /dev/null @@ -1,7 +0,0 @@ -vn-ticket-request { - .vn-textfield { - margin: 0!important; - max-width: 100px; - } -} - diff --git a/modules/travel/front/thermograph/index/index.html b/modules/travel/front/thermograph/index/index.html deleted file mode 100644 index 4d711613d..000000000 --- a/modules/travel/front/thermograph/index/index.html +++ /dev/null @@ -1,70 +0,0 @@ - - - -
- - - - - Code - Temperature - State - Destination - Created - - - - - - {{::thermograph.thermographFk}} - {{::thermograph.temperatureFk}} - {{::thermograph.result}} - {{::thermograph.warehouse.name}} - {{::thermograph.created | date: 'dd/MM/yyyy'}} - - - - - - - - - - - - - - - - -
-
- - - - - - - \ No newline at end of file diff --git a/modules/travel/front/thermograph/index/index.js b/modules/travel/front/thermograph/index/index.js deleted file mode 100644 index f8b239cfe..000000000 --- a/modules/travel/front/thermograph/index/index.js +++ /dev/null @@ -1,51 +0,0 @@ -import ngModule from '../../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $, vnFile) { - super($element, $); - this.vnFile = vnFile; - this.filter = { - include: - {relation: 'warehouse', - scope: { - fields: ['id', 'name'] - } - } - }; - } - - showDeleteConfirm(index) { - this.thermographIndex = index; - this.$.confirm.show(); - } - - deleteThermograph() { - const data = this.travelThermographs; - const thermographId = data[this.thermographIndex].id; - const query = `Travels/deleteThermograph?id=${thermographId}`; - this.$http.delete(query).then(() => { - this.vnApp.showSuccess(this.$t('Thermograph deleted')); - this.$.model.remove(this.thermographIndex); - this.thermographIndex = null; - }); - } - - downloadFile(dmsId) { - this.vnFile.download(`api/dms/${dmsId}/downloadFile`); - } -} - -Controller.$inject = ['$element', '$scope', 'vnFile']; - -ngModule.vnComponent('vnTravelThermographIndex', { - template: require('./index.html'), - controller: Controller, - require: { - card: '^vnTravelCard' - }, - bindings: { - travel: '<' - } -}); diff --git a/modules/travel/front/thermograph/index/style.scss b/modules/travel/front/thermograph/index/style.scss deleted file mode 100644 index 2c287ed9d..000000000 --- a/modules/travel/front/thermograph/index/style.scss +++ /dev/null @@ -1,6 +0,0 @@ -@import "variables"; - -vn-route-tickets form{ - margin: 0 auto; - max-width: $width-lg; -} \ No newline at end of file diff --git a/modules/travel/front/thermograph/locale/es.yml b/modules/travel/front/thermograph/locale/es.yml deleted file mode 100644 index 1fdb98c8e..000000000 --- a/modules/travel/front/thermograph/locale/es.yml +++ /dev/null @@ -1,20 +0,0 @@ -Code: Código -Temperature: Temperatura -State: Estado -Destination: Destino -Created: Creado -Remove thermograph: Eliminar termógrafo -Upload file: Subir fichero -Edit file: Editar fichero -Upload: Subir -File: Fichero -TravelFileDescription: Travel id {{travelId}} -ContentTypesInfo: 'Tipos de archivo permitidos: {{allowedContentTypes}}' -Are you sure you want to continue?: ¿Seguro que quieres continuar? -Add thermograph: Añadir termógrafo -Edit thermograph: Editar termógrafo -Thermograph deleted: Termógrafo eliminado -Thermograph: Termógrafo -New thermograph: Nuevo termógrafo -Are you sure you want to remove the thermograph?: ¿Seguro que quieres quitar el termógrafo? -Identifier: Identificador \ No newline at end of file diff --git a/modules/worker/back/methods/worker/filter.js b/modules/worker/back/methods/worker/filter.js index 2f328d28f..52c60572a 100644 --- a/modules/worker/back/methods/worker/filter.js +++ b/modules/worker/back/methods/worker/filter.js @@ -67,6 +67,12 @@ module.exports = Self => { type: 'String', description: 'The worker user name', http: {source: 'query'} + }, + { + arg: 'email', + type: 'String', + description: 'The user email', + http: {source: 'query'} } ], returns: { @@ -99,6 +105,8 @@ module.exports = Self => { return {'w.firstName': {like: `%${value}%`}}; case 'lastName': return {'w.lastName': {like: `%${value}%`}}; + case 'nickname': + return {'u.nickname': {like: `%${value}%`}}; case 'extension': return {'p.extension': value}; case 'fi': @@ -107,6 +115,8 @@ module.exports = Self => { return {'d.id': value}; case 'userName': return {'u.name': {like: `%${value}%`}}; + case 'email': + return {'eu.email': {like: `%${value}%`}}; } }); @@ -116,15 +126,23 @@ module.exports = Self => { let stmt; stmt = new ParameterizedSQL( - `SELECT w.id, u.email, p.extension, u.name as userName, - d.name AS department, w.lastName, u.nickname, mu.email + `SELECT w.id, + w.lastName, + w.firstName, + u.email, + u.nickname, + p.extension, + u.name as userName, + d.name AS department, + eu.email, + c.fi FROM worker w LEFT JOIN workerDepartment wd ON wd.workerFk = w.id LEFT JOIN department d ON d.id = wd.departmentFk LEFT JOIN client c ON c.id = w.id LEFT JOIN account.user u ON u.id = w.id LEFT JOIN pbx.sip p ON p.user_id = u.id - LEFT JOIN account.emailUser mu ON mu.userFk = u.id` + LEFT JOIN account.emailUser eu ON eu.userFk = u.id` ); stmt.merge(conn.makeSuffix(filter)); diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index bb43fba99..7da8a8da2 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -217,6 +217,7 @@ module.exports = Self => { const code = e.code; const message = e.sqlMessage; + if (e.message && e.message.includes('Invalid email')) throw new UserError('Invalid email'); if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`); if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`); if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`); diff --git a/modules/worker/back/models/operator.json b/modules/worker/back/models/operator.json index d4832bccf..b75bf6732 100644 --- a/modules/worker/back/models/operator.json +++ b/modules/worker/back/models/operator.json @@ -24,13 +24,28 @@ "warehouseFk": { "type": "number" }, + "sectorFk": { + "type": "number" + }, "labelerFk": { "type": "number" }, "isOnReservationMode": { "type": "boolean", "required": true - } + }, + "machineFk": { + "type": "number" + }, + "linesLimit": { + "type": "number" + }, + "volumeLimit": { + "type": "number" + }, + "sizeLimit": { + "type": "number" + } }, "relations": { "sector": { @@ -53,6 +68,11 @@ "model": "ItemPackingType", "foreignKey": "itemPackingTypeFk", "primaryKey": "code" - } + }, + "machine": { + "type": "belongsTo", + "model": "Machine", + "foreignKey": "machineFk" + } } -} \ No newline at end of file +} diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index b896e775b..c334c0d05 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -253,7 +253,18 @@ "relation": "client" }, { - "relation": "sip" + "relation": "sip", + "scope": { + "include": { + "relation": "queueMember", + "scope": { + "fields": [ + "queue", + "extension" + ] + } + } + } } ] }, diff --git a/modules/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js index a75302703..ffe23c9b9 100644 --- a/modules/zone/back/methods/zone/deleteZone.js +++ b/modules/zone/back/methods/zone/deleteZone.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('deleteZone', { description: 'Delete a zone', @@ -49,26 +50,12 @@ module.exports = Self => { } } }; - const promises = []; const ticketList = await models.Ticket.find(filter, myOptions); - const fixingState = await models.State.findOne({where: {code: 'FIXING'}}, myOptions); - const worker = await models.Worker.findOne({ - where: {id: userId} - }, myOptions); - await models.Ticket.rawSql('UPDATE ticket SET zoneFk = NULL WHERE zoneFk = ?', [id], myOptions); + if (ticketList.length > 0) + throw new UserError('There are tickets for this area, delete them first'); - for (ticket of ticketList) { - if (ticket.ticketState().alertLevel == 0) { - promises.push(models.Ticket.state(ctx, { - ticketFk: ticket.id, - stateFk: fixingState.id, - userFk: worker.id - }, myOptions)); - } - } - await Promise.all(promises); await models.Zone.destroyById(id, myOptions); if (tx) await tx.commit(); diff --git a/modules/zone/back/methods/zone/specs/deleteZone.spec.js b/modules/zone/back/methods/zone/specs/deleteZone.spec.js index 08dafd181..aef7fd290 100644 --- a/modules/zone/back/methods/zone/specs/deleteZone.spec.js +++ b/modules/zone/back/methods/zone/specs/deleteZone.spec.js @@ -8,9 +8,9 @@ describe('zone deletezone()', () => { __: value => value }; const ctx = {req: activeCtx}; - const zoneId = 9; + const zoneId = 4; + const zoneId2 = 3; let ticketIDs; - let originalTicketStates; beforeAll(async() => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ @@ -35,18 +35,8 @@ describe('zone deletezone()', () => { await models.Zone.deleteZone(ctx, zoneId, options); const updatedZone = await models.Zone.findById(zoneId, null, options); - const anUpdatedTicket = await models.Ticket.findById(ticketIDs[0], null, options); - - const updatedTicketStates = await models.TicketState.find({ - where: { - ticketFk: {inq: ticketIDs}, - code: 'FIXING' - } - }, options); expect(updatedZone).toBeNull(); - expect(anUpdatedTicket.zoneFk).toBeNull(); - expect(updatedTicketStates.length).toBeGreaterThan(originalTicketStates.length); await tx.rollback(); } catch (e) { @@ -54,4 +44,20 @@ describe('zone deletezone()', () => { throw e; } }); + + it('should not delete the zone if it has tickets', async() => { + const tx = await models.Zone.beginTransaction({}); + + let error; + try { + const options = {transaction: tx}; + await models.Zone.deleteZone(ctx, zoneId2, options); + await tx.rollback(); + } catch (e) { + error = e.message; + await tx.rollback(); + } + + expect(error).toEqual('There are tickets for this area, delete them first'); + }); }); diff --git a/modules/zone/front/basic-data/index.html b/modules/zone/front/basic-data/index.html deleted file mode 100644 index 5070a3aea..000000000 --- a/modules/zone/front/basic-data/index.html +++ /dev/null @@ -1,114 +0,0 @@ - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/modules/zone/front/basic-data/index.js b/modules/zone/front/basic-data/index.js deleted file mode 100644 index 402b471fc..000000000 --- a/modules/zone/front/basic-data/index.js +++ /dev/null @@ -1,21 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -class Controller extends Section { - onSubmit() { - this.$.watcher.submit().then(() => - this.card.reload() - ); - } -} - -ngModule.vnComponent('vnZoneBasicData', { - template: require('./index.html'), - controller: Controller, - bindings: { - zone: '<' - }, - require: { - card: '^vnZoneCard' - } -}); diff --git a/modules/zone/front/calendar/index.html b/modules/zone/front/calendar/index.html deleted file mode 100644 index cfcebf359..000000000 --- a/modules/zone/front/calendar/index.html +++ /dev/null @@ -1,33 +0,0 @@ - -
- - -
- {{$ctrl.firstDay | date:'MMMM'}} - {{$ctrl.firstDay | date:'yyyy'}} - - {{$ctrl.lastDay | date:'MMMM'}} - {{$ctrl.lastDay | date:'yyyy'}} -
- - -
-
- - -
-
\ No newline at end of file diff --git a/modules/zone/front/calendar/index.js b/modules/zone/front/calendar/index.js deleted file mode 100644 index 288a8f328..000000000 --- a/modules/zone/front/calendar/index.js +++ /dev/null @@ -1,191 +0,0 @@ -import ngModule from '../module'; -import Component from 'core/lib/component'; -import './style.scss'; - -class Controller extends Component { - constructor($element, $, vnWeekDays) { - super($element, $); - this.vnWeekDays = vnWeekDays; - this.nMonths = 4; - - let date = Date.vnNew(); - date.setDate(1); - date.setHours(0, 0, 0, 0); - this.date = date; - } - - get date() { - return this._date; - } - - set date(value) { - this._date = value; - let stamp = value.getTime(); - - let firstDay = new Date(stamp); - firstDay.setDate(1); - this.firstDay = firstDay; - - let lastDay = new Date(stamp); - lastDay.setMonth(lastDay.getMonth() + this.nMonths); - lastDay.setDate(0); - this.lastDay = lastDay; - - this.months = []; - for (let i = 0; i < this.nMonths; i++) { - let monthDate = new Date(stamp); - monthDate.setMonth(value.getMonth() + i); - this.months.push(monthDate); - } - - this.refreshEvents(); - } - - step(direction) { - let date = new Date(this.date.getTime()); - date.setMonth(date.getMonth() + (this.nMonths * direction)); - this.date = date; - - this.emit('step'); - } - - get data() { - return this._data; - } - - set data(value) { - this._data = value; - - value = value || {}; - - this.events = value.events; - - function toStamp(date) { - return date && new Date(date).setHours(0, 0, 0, 0); - } - - this.exclusions = {}; - let exclusions = value.exclusions; - - if (exclusions) { - for (let exclusion of exclusions) { - let stamp = toStamp(exclusion.dated); - if (!this.exclusions[stamp]) this.exclusions[stamp] = []; - this.exclusions[stamp].push(exclusion); - } - } - - this.geoExclusions = {}; - let geoExclusions = value.geoExclusions; - - if (geoExclusions) { - for (let geoExclusion of geoExclusions) { - let stamp = toStamp(geoExclusion.dated); - if (!this.geoExclusions[stamp]) this.geoExclusions[stamp] = []; - this.geoExclusions[stamp].push(geoExclusion); - } - } - - let events = value.events; - - if (events) { - for (let event of events) { - event.dated = toStamp(event.dated); - event.ended = toStamp(event.ended); - event.started = toStamp(event.started); - event.wdays = this.vnWeekDays.fromSet(event.weekDays); - } - } - - this.refreshEvents(); - - let calendars = this.element.querySelectorAll('vn-calendar'); - for (let calendar of calendars) - calendar.$ctrl.repaint(); - } - - refreshEvents() { - this.days = {}; - if (!this.data) return; - - let day = new Date(this.firstDay.getTime()); - - while (day <= this.lastDay) { - let stamp = day.getTime(); - let wday = day.getDay(); - let dayEvents = []; - let exclusions = this.exclusions[stamp] || []; - - if (this.events) { - for (let event of this.events) { - let match; - - switch (event.type) { - case 'day': - match = event.dated == stamp; - break; - default: - match = event.wdays[wday] - && (!event.started || stamp >= event.started) - && (!event.ended || stamp <= event.ended); - break; - } - - if (match && !exclusions.find(e => e.zoneFk == event.zoneFk)) - dayEvents.push(event); - } - } - - if (dayEvents.length) - this.days[stamp] = dayEvents; - - day.setDate(day.getDate() + 1); - } - } - - onSelection($event, $days, $type, $weekday) { - let $events = []; - let $exclusions = []; - let $geoExclusions = []; - - for (let day of $days) { - let stamp = day.getTime(); - $events = $events.concat(this.days[stamp] || []); - $exclusions = $exclusions.concat(this.exclusions[stamp] || []); - $geoExclusions = $geoExclusions.concat(this.geoExclusions[stamp] || []); - } - - this.emit('selection', { - $event, - $days, - $type, - $weekday, - $events, - $exclusions, - $geoExclusions - }); - } - - hasEvents(day) { - let stamp = day.getTime(); - return this.days[stamp] || this.exclusions[stamp] || this.geoExclusions[stamp]; - } - - getClass(day) { - let stamp = day.getTime(); - if (this.geoExclusions[stamp]) - return 'geoExcluded'; - else if (this.exclusions[stamp]) - return 'excluded'; - else return ''; - } -} -Controller.$inject = ['$element', '$scope', 'vnWeekDays']; - -ngModule.vnComponent('vnZoneCalendar', { - template: require('./index.html'), - controller: Controller, - bindings: { - data: ' { - let $scope; - let controller; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, $rootScope) => { - $scope = $rootScope.$new(); - const $element = angular.element(``); - controller = $componentController('vnZoneCalendar', {$element, $scope}); - controller.$.model = crudModel; - controller.zone = {id: 1}; - controller.days = []; - controller.exclusions = []; - controller.geoExclusions = []; - })); - - describe('date() setter', () => { - it('should set the month property and then call the refreshEvents() method', () => { - jest.spyOn(controller, 'refreshEvents').mockReturnThis(); - - controller.date = Date.vnNew(); - - expect(controller.refreshEvents).toHaveBeenCalledWith(); - expect(controller.months.length).toEqual(4); - }); - }); - - describe('step()', () => { - it('should set the date month to 4 months backwards', () => { - const now = Date.vnNew(); - now.setDate(15); - now.setMonth(now.getMonth() - 4); - - controller.step(-1); - - const expectedMonth = now.getMonth(); - const currentMonth = controller.date.getMonth(); - - expect(currentMonth).toEqual(expectedMonth); - }); - - it('should set the date month to 4 months forwards', () => { - const now = Date.vnNew(); - now.setDate(15); - now.setMonth(now.getMonth() + 4); - - controller.step(1); - - const expectedMonth = now.getMonth(); - const currentMonth = controller.date.getMonth(); - - expect(currentMonth).toEqual(expectedMonth); - }); - }); - - describe('data() setter', () => { - it('should set the events, exclusions and geoExclusions and then call the refreshEvents() method', () => { - jest.spyOn(controller, 'refreshEvents').mockReturnThis(); - - controller.data = { - exclusions: [{ - dated: Date.vnNew() - }], - events: [{ - dated: Date.vnNew() - }], - geoExclusions: [{ - dated: Date.vnNew() - }], - }; - - expect(controller.refreshEvents).toHaveBeenCalledWith(); - expect(controller.events).toBeDefined(); - expect(controller.events.length).toEqual(1); - expect(controller.exclusions).toBeDefined(); - expect(controller.geoExclusions).toBeDefined(); - expect(Object.keys(controller.exclusions).length).toEqual(1); - }); - }); - - describe('refreshEvents()', () => { - it('should fill the days property with the events.', () => { - controller.data = []; - controller.firstDay = Date.vnNew(); - - const lastDay = Date.vnNew(); - lastDay.setDate(lastDay.getDate() + 10); - controller.lastDay = lastDay; - - const firstEventStamp = controller.firstDay.getTime(); - const lastEventStamp = controller.lastDay.getTime(); - controller.events = [{ - type: 'day', - dated: firstEventStamp - }, - { - type: 'day', - dated: lastEventStamp - }]; - - controller.refreshEvents(); - const expectedDays = Object.keys(controller.days); - - expect(expectedDays.length).toEqual(2); - }); - }); - - describe('onSelection()', () => { - it('should call the emit() method', () => { - jest.spyOn(controller, 'emit'); - - const $event = {}; - const $days = [Date.vnNew()]; - const $type = 'day'; - const $weekday = 1; - - controller.onSelection($event, $days, $type, $weekday); - - expect(controller.emit).toHaveBeenCalledWith('selection', - { - $days: $days, - $event: {}, - $events: [], - $exclusions: [], - $type: 'day', - $weekday: 1, - $geoExclusions: [], - } - ); - }); - }); - - describe('hasEvents()', () => { - it('should return true for an existing event on a date', () => { - const dated = Date.vnNew(); - - controller.days[dated.getTime()] = true; - - const result = controller.hasEvents(dated); - - expect(result).toBeTruthy(); - }); - }); - - describe('getClass()', () => { - it('should return the className "excluded" for an excluded date', () => { - const dated = Date.vnNew(); - - controller.exclusions = []; - controller.exclusions[dated.getTime()] = true; - - const result = controller.getClass(dated); - - expect(result).toEqual('excluded'); - }); - - it('should return the className "geoExcluded" for a date with geo excluded', () => { - const dated = Date.vnNew(); - - controller.geoExclusions = []; - controller.geoExclusions[dated.getTime()] = true; - - const result = controller.getClass(dated); - - expect(result).toEqual('geoExcluded'); - }); - }); -}); diff --git a/modules/zone/front/calendar/style.scss b/modules/zone/front/calendar/style.scss deleted file mode 100644 index 38491af58..000000000 --- a/modules/zone/front/calendar/style.scss +++ /dev/null @@ -1,43 +0,0 @@ -@import "variables"; - -vn-zone-calendar { - display: block; - - & > vn-card { - & > .header { - display: flex; - align-items: center; - justify-content: space-between; - background-color: $color-main; - color: white; - font-weight: bold; - height: 45px; - - & > .vn-button { - color: inherit; - height: 100%; - } - } - & > .calendars { - display: flex; - flex-wrap: wrap; - justify-content: space-evenly; - - & > .vn-calendar { - max-width: 288px; - - #days-container .day { - &.event .day-number { - background-color: $color-success; - } - &.excluded .day-number { - background-color: $color-alert; - } - &.geoExcluded .day-number { - background-color: $color-main; - } - } - } - } - } -} \ No newline at end of file diff --git a/modules/zone/front/card/index.html b/modules/zone/front/card/index.html deleted file mode 100644 index ae6a7f10a..000000000 --- a/modules/zone/front/card/index.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/modules/zone/front/card/index.js b/modules/zone/front/card/index.js deleted file mode 100644 index 4e8ac7e8c..000000000 --- a/modules/zone/front/card/index.js +++ /dev/null @@ -1,21 +0,0 @@ -import ngModule from '../module'; -import ModuleCard from 'salix/components/module-card'; - -class Controller extends ModuleCard { - reload() { - let filter = { - include: { - relation: 'agencyMode', - scope: {fields: ['name']} - } - }; - - this.$http.get(`Zones/${this.$params.id}`, {filter}) - .then(res => this.zone = res.data); - } -} - -ngModule.vnComponent('vnZoneCard', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/zone/front/card/index.spec.js b/modules/zone/front/card/index.spec.js deleted file mode 100644 index 64127990f..000000000 --- a/modules/zone/front/card/index.spec.js +++ /dev/null @@ -1,26 +0,0 @@ -import './index.js'; - -describe('Zone Component vnZoneCard', () => { - let controller; - let $httpBackend; - let data = {id: 1, name: 'fooName'}; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, _$httpBackend_, $stateParams) => { - $httpBackend = _$httpBackend_; - - let $element = angular.element('
'); - controller = $componentController('vnZoneCard', {$element}); - - $stateParams.id = data.id; - $httpBackend.whenRoute('GET', 'Zones/:id').respond(data); - })); - - it('should request data and set it on the controller', () => { - controller.reload(); - $httpBackend.flush(); - - expect(controller.zone).toEqual(data); - }); -}); diff --git a/modules/zone/front/create/index.html b/modules/zone/front/create/index.html deleted file mode 100644 index f8c7df391..000000000 --- a/modules/zone/front/create/index.html +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/modules/zone/front/create/index.js b/modules/zone/front/create/index.js deleted file mode 100644 index db337a9a3..000000000 --- a/modules/zone/front/create/index.js +++ /dev/null @@ -1,24 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - $onInit() { - this.zone = { - travelingDays: 0, - price: 0.20, - bonus: 0.20, - hour: Date.vnNew() - }; - } - - onSubmit() { - return this.$.watcher.submit().then(res => - this.$state.go('zone.card.location', {id: res.data.id}) - ); - } -} - -ngModule.vnComponent('vnZoneCreate', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/zone/front/create/index.spec.js b/modules/zone/front/create/index.spec.js deleted file mode 100644 index fe0088225..000000000 --- a/modules/zone/front/create/index.spec.js +++ /dev/null @@ -1,40 +0,0 @@ -import './index'; -import watcher from 'core/mocks/watcher'; - -describe('Zone Component vnZoneCreate', () => { - let $scope; - let $state; - let controller; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, $rootScope, _$state_) => { - $scope = $rootScope.$new(); - $state = _$state_; - $scope.watcher = watcher; - $scope.watcher.submit = () => { - return { - then: callback => { - callback({data: {id: 1234}}); - } - }; - }; - const $element = angular.element(''); - controller = $componentController('vnZoneCreate', {$element, $scope}); - })); - - describe('onSubmit()', () => { - it(`should call submit() on the watcher then expect a callback`, () => { - jest.spyOn($state, 'go'); - - controller.zone = { - name: 'Zone One' - }; - - controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('zone.card.location', Object({id: 1234})); - }); - }); -}); - diff --git a/modules/zone/front/create/locale/es.yml b/modules/zone/front/create/locale/es.yml deleted file mode 100644 index 4827ced37..000000000 --- a/modules/zone/front/create/locale/es.yml +++ /dev/null @@ -1,3 +0,0 @@ -Traveling days: Días de viaje -Closing hour: Hora de cierre -Bonus: Bonificación \ No newline at end of file diff --git a/modules/zone/front/delivery-days/index.html b/modules/zone/front/delivery-days/index.html deleted file mode 100644 index c47d89982..000000000 --- a/modules/zone/front/delivery-days/index.html +++ /dev/null @@ -1,102 +0,0 @@ -
- - -
- -
- - - - - - -
- {{code}} {{town.name}} -
-
- {{town.province.name}}, {{town.province.country.name}} -
-
-
- - - -
-
- - - -
-
Zones
- - - - - - Id - Name - Agency - Closing - Price - - - - - - {{::zone.id}} - {{::zone.name}} - {{::zone.agencyModeName}} - {{::zone.hour | date: 'HH:mm'}} - {{::zone.price | currency: 'EUR':2}} - - - - - - - - - - - -
-
- - - \ No newline at end of file diff --git a/modules/zone/front/delivery-days/index.js b/modules/zone/front/delivery-days/index.js deleted file mode 100644 index 71e8c8ab7..000000000 --- a/modules/zone/front/delivery-days/index.js +++ /dev/null @@ -1,95 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - $onInit() { - this.setParams(); - } - - $postLink() { - this.deliveryMethodFk = 'delivery'; - } - - setParams() { - const hasParams = this.$params.deliveryMethodFk || this.$params.geoFk || this.$params.agencyModeFk; - if (hasParams) { - if (this.$params.deliveryMethodFk) - this.deliveryMethodFk = this.$params.deliveryMethodFk; - - if (this.$params.geoFk) - this.geoFk = this.$params.geoFk; - - if (this.$params.agencyModeFk) - this.agencyModeFk = this.$params.agencyModeFk; - - this.fetchData(); - } - } - - fetchData() { - const params = { - deliveryMethodFk: this.deliveryMethodFk, - geoFk: this.geoFk, - agencyModeFk: this.agencyModeFk - }; - this.$.data = null; - this.$http.get(`Zones/getEvents`, {params}) - .then(res => { - let data = res.data; - this.$.data = data; - if (!data.events.length) - this.vnApp.showMessage(this.$t('No service for the specified zone')); - - this.$state.go(this.$state.current.name, params); - }); - } - - get deliveryMethodFk() { - return this._deliveryMethodFk; - } - - set deliveryMethodFk(value) { - this._deliveryMethodFk = value; - - let filter; - - if (value === 'pickUp') - filter = {where: {code: 'PICKUP'}}; - else - filter = {where: {code: {inq: ['DELIVERY', 'AGENCY']}}}; - - this.$http.get(`DeliveryMethods`, {filter}).then(res => { - const deliveryMethods = res.data.map(deliveryMethod => deliveryMethod.id); - this.agencyFilter = {deliveryMethodFk: {inq: deliveryMethods}}; - }); - } - - onSelection($event, $events, $days) { - if (!$events.length) return; - - const day = $days[0]; - const zoneIds = []; - for (let event of $events) - zoneIds.push(event.zoneFk); - - const params = { - zoneIds: zoneIds, - date: day - }; - - this.$http.post(`Zones/getZoneClosing`, params) - .then(res => this.zoneClosing = res.data) - .then(() => this.$.zoneEvents.show($event.target)); - } - - preview(zone) { - this.selectedZone = zone; - this.$.summary.show(); - } -} - -ngModule.vnComponent('vnZoneDeliveryDays', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/zone/front/delivery-days/index.spec.js b/modules/zone/front/delivery-days/index.spec.js deleted file mode 100644 index 28705880c..000000000 --- a/modules/zone/front/delivery-days/index.spec.js +++ /dev/null @@ -1,126 +0,0 @@ -import './index.js'; -import popover from 'core/mocks/popover'; -import crudModel from 'core/mocks/crud-model'; - -describe('Zone Component vnZoneDeliveryDays', () => { - let $httpBackend; - let controller; - let $element; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - $element = angular.element(' { - it('should set the deliveryMethodFk property as pickup and then perform a query that sets the filter', () => { - $httpBackend.expect('GET', 'DeliveryMethods').respond([{id: 999}]); - controller.deliveryMethodFk = 'pickUp'; - $httpBackend.flush(); - - expect(controller.agencyFilter).toEqual({deliveryMethodFk: {inq: [999]}}); - }); - }); - - describe('setParams()', () => { - it('should do nothing when no params are received', () => { - controller.setParams(); - - expect(controller.deliveryMethodFk).toBeUndefined(); - expect(controller.geoFk).toBeUndefined(); - expect(controller.agencyModeFk).toBeUndefined(); - }); - - it('should set the controller properties when the params are provided', () => { - controller.$params = { - deliveryMethodFk: 3, - geoFk: 2, - agencyModeFk: 1 - }; - controller.setParams(); - - expect(controller.deliveryMethodFk).toEqual(controller.$params.deliveryMethodFk); - expect(controller.geoFk).toEqual(controller.$params.geoFk); - expect(controller.agencyModeFk).toEqual(controller.$params.agencyModeFk); - }); - }); - - describe('fetchData()', () => { - it('should make an HTTP GET query and then call the showMessage() method', () => { - jest.spyOn(controller.vnApp, 'showMessage'); - jest.spyOn(controller.$state, 'go'); - - controller.agencyModeFk = 1; - controller.deliveryMethodFk = 2; - controller.geoFk = 3; - controller.$state.current.name = 'myState'; - - const expectedData = {events: []}; - - const url = 'Zones/getEvents?agencyModeFk=1&deliveryMethodFk=2&geoFk=3'; - - $httpBackend.when('GET', 'DeliveryMethods').respond([]); - $httpBackend.expect('GET', url).respond({events: []}); - controller.fetchData(); - $httpBackend.flush(); - - expect(controller.$.data).toEqual(expectedData); - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('No service for the specified zone'); - expect(controller.$state.go).toHaveBeenCalledWith( - controller.$state.current.name, - { - agencyModeFk: 1, - deliveryMethodFk: 2, - geoFk: 3 - } - ); - }); - }); - - describe('onSelection()', () => { - it('should not call the show popover method if events array is empty', () => { - jest.spyOn(controller.$.zoneEvents, 'show'); - - const event = new Event('click'); - const target = document.createElement('div'); - target.dispatchEvent(event); - const events = []; - controller.onSelection(event, events); - - expect(controller.$.zoneEvents.show).not.toHaveBeenCalled(); - }); - - it('should call the show() method and call getZoneClosing() with the expected ids', () => { - jest.spyOn(controller.$.zoneEvents, 'show'); - - const event = new Event('click'); - const target = document.createElement('div'); - target.dispatchEvent(event); - - const day = Date.vnNew(); - const events = [ - {zoneFk: 1}, - {zoneFk: 2}, - {zoneFk: 8} - ]; - const params = { - zoneIds: [1, 2, 8], - date: [day][0] - }; - const response = [{id: 1, hour: ''}]; - - $httpBackend.when('POST', 'Zones/getZoneClosing', params).respond({response}); - controller.onSelection(event, events, [day]); - $httpBackend.flush(); - - expect(controller.$.zoneEvents.show).toHaveBeenCalledWith(target); - expect(controller.zoneClosing.id).toEqual(response.id); - }); - }); -}); diff --git a/modules/zone/front/delivery-days/style.scss b/modules/zone/front/delivery-days/style.scss deleted file mode 100644 index 3dd4abb7c..000000000 --- a/modules/zone/front/delivery-days/style.scss +++ /dev/null @@ -1,36 +0,0 @@ -@import "variables"; - -vn-zone-delivery-days { - vn-zone-calendar { - display: flex; - justify-content: center; - flex-wrap: wrap; - - & > vn-calendar { - min-width: 264px; - } - } - form { - display: flex; - flex-direction: column; - } -} - -.zoneEvents { - width: 700px; - max-height: 450px; - - vn-data-viewer { - margin-bottom: 0; - vn-pagination { - padding: 0 - } - } - - & > .header { - background-color: $color-main; - color: white; - font-weight: bold; - text-align: center - } -} \ No newline at end of file diff --git a/modules/zone/front/descriptor-popover/index.html b/modules/zone/front/descriptor-popover/index.html deleted file mode 100644 index 7e4e8f5d8..000000000 --- a/modules/zone/front/descriptor-popover/index.html +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/modules/zone/front/descriptor-popover/index.js b/modules/zone/front/descriptor-popover/index.js deleted file mode 100644 index a21232e41..000000000 --- a/modules/zone/front/descriptor-popover/index.js +++ /dev/null @@ -1,9 +0,0 @@ -import ngModule from '../module'; -import DescriptorPopover from 'salix/components/descriptor-popover'; - -class Controller extends DescriptorPopover {} - -ngModule.vnComponent('vnZoneDescriptorPopover', { - slotTemplate: require('./index.html'), - controller: Controller -}); diff --git a/modules/zone/front/descriptor/index.html b/modules/zone/front/descriptor/index.html deleted file mode 100644 index a3432a99d..000000000 --- a/modules/zone/front/descriptor/index.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - Delete - - - Clone - - - -
- - - - - - - - - - -
-
-
- - - - - - - - \ No newline at end of file diff --git a/modules/zone/front/descriptor/index.js b/modules/zone/front/descriptor/index.js deleted file mode 100644 index 3f4863a60..000000000 --- a/modules/zone/front/descriptor/index.js +++ /dev/null @@ -1,65 +0,0 @@ -import ngModule from '../module'; -import Descriptor from 'salix/components/descriptor'; - -class Controller extends Descriptor { - get zone() { - return this.entity; - } - - set zone(value) { - this.entity = value; - } - - loadData() { - const filter = { - include: [ - { - relation: 'agencyMode', - scope: { - fields: ['name'], - } - } - ] - }; - - return this.getData(`Zones/${this.id}`, {filter}) - .then(res => this.entity = res.data); - } - - onDelete() { - const $t = this.$translate.instant; - const today = Date.vnNew(); - today.setHours(0, 0, 0, 0); - const filter = {where: {zoneFk: this.id, shipped: {gte: today}}}; - this.$http.get(`Tickets`, {filter}).then(res => { - const ticketsAmount = res.data.length; - if (ticketsAmount) { - const params = {ticketsAmount}; - const question = $t('This zone contains tickets', params, null, null, 'sanitizeParameters'); - this.$.deleteZone.question = question; - this.$.deleteZone.show(); - } else - this.deleteZone(); - }); - } - - deleteZone() { - return this.$http.post(`Zones/${this.id}/deleteZone`).then(() => { - this.$state.go('zone.index'); - this.vnApp.showSuccess(this.$t('Zone deleted')); - }); - } - - onCloneAccept() { - return this.$http.post(`Zones/${this.id}/clone`). - then(res => this.$state.go('zone.card.basicData', {id: res.data.id})); - } -} - -ngModule.vnComponent('vnZoneDescriptor', { - template: require('./index.html'), - controller: Controller, - bindings: { - zone: '<' - } -}); diff --git a/modules/zone/front/descriptor/index.spec.js b/modules/zone/front/descriptor/index.spec.js deleted file mode 100644 index 435a1d00f..000000000 --- a/modules/zone/front/descriptor/index.spec.js +++ /dev/null @@ -1,74 +0,0 @@ -import './index.js'; - -describe('Zone descriptor', () => { - let $httpBackend; - let controller; - let $element; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - $element = angular.element(' {}, - show: () => {} - }; - })); - - describe('onDelete()', () => { - it('should make an HTTP POST query and then call the deleteZone show() method', () => { - jest.spyOn(controller.$.deleteZone, 'show'); - - const expectedData = [{id: 16}]; - $httpBackend.when('GET', 'Tickets').respond(expectedData); - controller.onDelete(); - $httpBackend.flush(); - - expect(controller.$.deleteZone.show).toHaveBeenCalledWith(); - }); - - it('should make an HTTP POST query and then call the deleteZone() method', () => { - jest.spyOn(controller, 'deleteZone').mockReturnThis(); - - const expectedData = []; - $httpBackend.when('GET', 'Tickets').respond(expectedData); - controller.onDelete(); - $httpBackend.flush(); - - expect(controller.deleteZone).toHaveBeenCalledWith(); - }); - }); - - describe('deleteZone()', () => { - it('should make an HTTP POST query and then call the showMessage() method', () => { - jest.spyOn(controller.$state, 'go').mockReturnThis(); - jest.spyOn(controller.vnApp, 'showSuccess'); - - const stateName = 'zone.index'; - $httpBackend.when('POST', 'Zones/1/deleteZone').respond(200); - controller.deleteZone(); - $httpBackend.flush(); - - expect(controller.$state.go).toHaveBeenCalledWith(stateName); - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Zone deleted'); - }); - }); - - describe('onCloneAccept()', () => { - it('should make an HTTP POST query and then call the state go() method', () => { - jest.spyOn(controller.$state, 'go').mockReturnThis(); - - const stateName = 'zone.card.basicData'; - const expectedData = {id: 1}; - $httpBackend.when('POST', 'Zones/1/clone').respond(expectedData); - controller.onCloneAccept(); - $httpBackend.flush(); - - expect(controller.$state.go).toHaveBeenCalledWith(stateName, expectedData); - }); - }); -}); diff --git a/modules/zone/front/descriptor/locale/es.yml b/modules/zone/front/descriptor/locale/es.yml deleted file mode 100644 index 0581ee93a..000000000 --- a/modules/zone/front/descriptor/locale/es.yml +++ /dev/null @@ -1,4 +0,0 @@ -This zone contains tickets: Esta zona contiene {{ticketsAmount}} tickets por servir. ¿Seguro que quieres eliminar esta zona? -Do you want to clone this zone?: ¿Quieres clonar esta zona? -All it's properties will be copied: Todas sus propiedades serán copiadas -Zone deleted: Zona eliminada \ No newline at end of file diff --git a/modules/zone/front/events/index.html b/modules/zone/front/events/index.html deleted file mode 100644 index 157b2a669..000000000 --- a/modules/zone/front/events/index.html +++ /dev/null @@ -1,277 +0,0 @@ - - - -
-
- Edit mode -
- - - - - - -
-
- Events -
- - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - -
- - - - -
-
-
-
- - - - - - - -
diff --git a/modules/zone/front/events/index.js b/modules/zone/front/events/index.js deleted file mode 100644 index b86330126..000000000 --- a/modules/zone/front/events/index.js +++ /dev/null @@ -1,316 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $, vnWeekDays) { - super($element, $); - this.vnWeekDays = vnWeekDays; - this.editMode = 'include'; - } - - $onInit() { - this.refresh(); - } - - get path() { - return `Zones/${this.$params.id}/events`; - } - - get exclusionsPath() { - return `Zones/${this.$params.id}/exclusions`; - } - - get checked() { - const geos = this.$.model.data || []; - const checkedLines = []; - for (let geo of geos) { - if (geo.checked) - checkedLines.push(geo); - } - return checkedLines; - } - - refresh() { - this.$.data = null; - this.$.$applyAsync(() => { - const params = { - zoneFk: this.$params.id, - started: this.$.calendar.firstDay, - ended: this.$.calendar.lastDay - }; - - this.$http.get(`Zones/getEventsFiltered`, {params}).then(res => { - const data = res.data; - this.$.data = data; - }); - }); - } - - formatWdays(weekDays) { - if (!weekDays) return; - - let abrWdays = weekDays - .split(',') - .map(wday => this.vnWeekDays.map[wday].localeAbr); - - return abrWdays.length < 7 - ? abrWdays.join(', ') - : this.$t('Everyday'); - } - - onSelection(days, type, weekday, events, exclusions, exclusionGeos) { - if (this.editMode == 'include') { - if (events.length) - return this.editInclusion(events[0]); - return this.createInclusion(type, days, weekday); - } else if (this.editMode == 'exclude') { - if (exclusions.length || exclusionGeos.length) - return this.editExclusion(exclusions[0] || {}, exclusionGeos); - return this.createExclusion(days); - } - } - - editExclusion(exclusion, exclusionGeos) { - this.isNew = false; - this.excludeSelected = angular.copy(exclusion); - this.excludeSelected.type = exclusionGeos.length ? - 'specificLocations' : 'all'; - - this.exclusionGeos = new Set(); - if (exclusionGeos.length) { - this.excludeSelected.id = exclusionGeos[0].zoneExclusionFk; - exclusionGeos.forEach(x => this.exclusionGeos.add(x.geoFk)); - } - - this.$.excludeDialog.show(); - } - - createExclusion(days) { - this.isNew = true; - this.excludeSelected = { - type: 'all', - dated: days[0] - }; - this.exclusionGeos = new Set(); - this.$.excludeDialog.show(); - } - - onEditClick(row, event) { - if (event.defaultPrevented) return; - this.editInclusion(row); - } - - editInclusion(row) { - this.isNew = false; - this.selected = angular.copy(row); - this.selected.wdays = this.vnWeekDays.fromSet(row.weekDays); - this.$.includeDialog.show(); - } - - createInclusion(type, days, weekday) { - this.isNew = true; - - if (type == 'weekday') { - let wdays = []; - if (weekday) wdays[weekday] = true; - - this.selected = { - type: 'indefinitely', - wdays - }; - } else { - this.selected = { - type: 'day', - dated: days[0] - }; - } - - this.$.includeDialog.show(); - } - - onIncludeResponse(response) { - switch (response) { - case 'accept': { - let selected = this.selected; - let type = selected.type; - - selected.weekDays = this.vnWeekDays.toSet(selected.wdays); - - if (type == 'day') - selected.weekDays = ''; - else - selected.dated = null; - - if (type != 'range') { - selected.started = null; - selected.ended = null; - } - - let req; - - if (this.isNew) - req = this.$http.post(this.path, selected); - else - req = this.$http.put(`${this.path}/${selected.id}`, selected); - - return req.then(() => { - this.selected = null; - this.isNew = null; - this.refresh(); - }); - } - case 'delete': - return this.onDelete(this.selected.id) - .then(response => response == 'accept'); - } - } - - onExcludeResponse(response) { - const type = this.excludeSelected.type; - switch (response) { - case 'accept': { - if (type == 'all') - return this.exclusionCreate(); - return this.exclusionGeoCreate(); - } - case 'delete': - return this.exclusionDelete(this.excludeSelected); - } - } - - onDeleteClick(id, event) { - if (event.defaultPrevented) return; - event.preventDefault(); - this.onDelete(id); - } - - onDelete(id) { - return this.$.confirm.show( - response => this.onDeleteResponse(response, id)); - } - - onDeleteResponse(response, id) { - if (response != 'accept' || !id) return; - return this.$http.delete(`${this.path}/${id}`) - .then(() => this.refresh()); - } - - exclusionCreate() { - const excludeSelected = this.excludeSelected; - const dated = excludeSelected.dated; - let req; - - if (this.isNew) - req = this.$http.post(this.exclusionsPath, [{dated}]); - if (!this.isNew) - req = this.$http.put(`${this.exclusionsPath}/${excludeSelected.id}`, {dated}); - - return req.then(() => { - this.refresh(); - }); - } - - exclusionGeoCreate() { - const excludeSelected = this.excludeSelected; - let req; - const geoIds = []; - this.exclusionGeos.forEach(id => geoIds.push(id)); - - if (this.isNew) { - const params = { - zoneFk: parseInt(this.$params.id), - date: excludeSelected.dated, - geoIds - }; - req = this.$http.post(`Zones/exclusionGeo`, params); - } else { - const params = { - zoneExclusionFk: this.excludeSelected.id, - geoIds - }; - req = this.$http.post(`Zones/updateExclusionGeo`, params); - } - return req.then(() => this.refresh()); - } - - exclusionDelete(exclusion) { - const path = `${this.exclusionsPath}/${exclusion.id}`; - return this.$http.delete(path) - .then(() => this.refresh()); - } - - set excludeSearch(value) { - this._excludeSearch = value; - if (!value) this.onSearch(); - } - - get excludeSearch() { - return this._excludeSearch; - } - - onKeyDown(event) { - if (event.key == 'Enter') { - event.preventDefault(); - this.onSearch(); - } - } - - onSearch() { - const params = {search: this._excludeSearch}; - if (this.excludeSelected.type == 'specificLocations') { - this.$.model.applyFilter({}, params).then(() => { - const data = this.$.model.data; - this.getChecked(data); - this.$.treeview.data = data; - }); - } - } - - onFetch(item) { - const params = item ? {parentId: item.id} : null; - return this.$.model.applyFilter({}, params).then(() => { - const data = this.$.model.data; - this.getChecked(data); - return data; - }); - } - - onSort(a, b) { - if (b.selected !== a.selected) { - if (a.selected == null) - return 1; - if (b.selected == null) - return -1; - return b.selected - a.selected; - } - - return a.name.localeCompare(b.name); - } - - getChecked(data) { - for (let geo of data) { - geo.checked = this.exclusionGeos.has(geo.id); - if (geo.childs) this.getChecked(geo.childs); - } - } - - onItemCheck(geoId, checked) { - if (checked) - this.exclusionGeos.add(geoId); - else - this.exclusionGeos.delete(geoId); - } -} -Controller.$inject = ['$element', '$scope', 'vnWeekDays']; - -ngModule.vnComponent('vnZoneEvents', { - template: require('./index.html'), - controller: Controller, - bindings: { - zone: '<' - }, - require: { - card: '^vnZoneCard' - } -}); diff --git a/modules/zone/front/events/index.spec.js b/modules/zone/front/events/index.spec.js deleted file mode 100644 index 558d97b6f..000000000 --- a/modules/zone/front/events/index.spec.js +++ /dev/null @@ -1,340 +0,0 @@ -import './index'; -import crudModel from 'core/mocks/crud-model'; - -describe('component vnZoneEvents', () => { - let $scope; - let controller; - let $httpBackend; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - const $element = angular.element(``); - controller = $componentController('vnZoneEvents', {$element, $scope}); - controller.$params = {id: 1}; - })); - - describe('refresh()', () => { - it('should set the zone and then call both getSummary() and getWarehouses()', () => { - const date = '2021-10-01'; - - controller.$params.id = 999; - controller.$.calendar = { - firstDay: date, - lastDay: date - }; - - const params = { - zoneFk: controller.$params.id, - started: date, - ended: date - }; - - const query = `Zones/getEventsFiltered?ended=${date}&started=${date}&zoneFk=${params.zoneFk}`; - const response = { - events: 'myEvents', - exclusions: 'myExclusions', - geoExclusions: 'myGeoExclusions', - }; - $httpBackend.whenGET(query).respond(response); - controller.refresh(); - $httpBackend.flush(); - - const data = controller.$.data; - - expect(data.events).toBeDefined(); - expect(data.exclusions).toBeDefined(); - }); - }); - - describe('onSelection()', () => { - it('should call the editInclusion() method', () => { - jest.spyOn(controller, 'editInclusion').mockReturnThis(); - - const weekday = {}; - const days = []; - const type = 'EventType'; - const events = [{name: 'Event'}]; - const exclusions = []; - const exclusionsGeo = []; - controller.editMode = 'include'; - controller.onSelection(days, type, weekday, events, exclusions, exclusionsGeo); - - expect(controller.editInclusion).toHaveBeenCalledWith({name: 'Event'}); - }); - - it('should call the createInclusion() method', () => { - jest.spyOn(controller, 'createInclusion').mockReturnThis(); - - const weekday = {dated: Date.vnNew()}; - const days = [weekday]; - const type = 'EventType'; - const events = []; - const exclusions = []; - const exclusionsGeo = []; - controller.editMode = 'include'; - controller.onSelection(days, type, weekday, events, exclusions, exclusionsGeo); - - expect(controller.createInclusion).toHaveBeenCalledWith(type, days, weekday); - }); - - it('should call the editExclusion() method with exclusions', () => { - jest.spyOn(controller, 'editExclusion').mockReturnThis(); - - const weekday = {}; - const days = []; - const type = 'EventType'; - const events = []; - const exclusions = [{name: 'Exclusion'}]; - const exclusionsGeo = []; - controller.editMode = 'exclude'; - controller.onSelection(days, type, weekday, events, exclusions, exclusionsGeo); - - expect(controller.editExclusion).toHaveBeenCalled(); - }); - - it('should call the editExclusion() method with exclusionsGeo', () => { - jest.spyOn(controller, 'editExclusion').mockReturnThis(); - - const weekday = {}; - const days = []; - const type = 'EventType'; - const events = []; - const exclusions = []; - const exclusionsGeo = [{name: 'GeoExclusion'}]; - controller.editMode = 'exclude'; - controller.onSelection(days, type, weekday, events, exclusions, exclusionsGeo); - - expect(controller.editExclusion).toHaveBeenCalled(); - }); - - it('should call the createExclusion() method', () => { - jest.spyOn(controller, 'createExclusion').mockReturnThis(); - - const weekday = {}; - const days = [{dated: Date.vnNew()}]; - const type = 'EventType'; - const events = []; - const exclusions = []; - const exclusionsGeo = []; - controller.editMode = 'exclude'; - controller.onSelection(days, type, weekday, events, exclusions, exclusionsGeo); - - expect(controller.createExclusion).toHaveBeenCalledWith(days); - }); - }); - - describe('editExclusion()', () => { - it('shoud set the excludeSelected.type = "specificLocations" and then call the excludeDialog show() method', () => { - controller.$.excludeDialog = {show: jest.fn()}; - - const exclusionGeos = [{id: 1}]; - const exclusions = []; - - controller.editExclusion(exclusions, exclusionGeos); - - expect(controller.excludeSelected.type).toEqual('specificLocations'); - expect(controller.$.excludeDialog.show).toHaveBeenCalledWith(); - }); - - it('shoud set the excludeSelected.type = "all" and then call the excludeDialog show() method', () => { - controller.$.excludeDialog = {show: jest.fn()}; - - const exclusionGeos = []; - const exclusions = [{id: 1}]; - - controller.editExclusion(exclusions, exclusionGeos); - - expect(controller.excludeSelected.type).toEqual('all'); - expect(controller.$.excludeDialog.show).toHaveBeenCalledWith(); - }); - }); - - describe('createExclusion()', () => { - it('shoud set the excludeSelected property and then call the excludeDialog show() method', () => { - controller.$.excludeDialog = {show: jest.fn()}; - - const days = [Date.vnNew()]; - controller.createExclusion(days); - - expect(controller.excludeSelected).toBeDefined(); - expect(controller.isNew).toBeTruthy(); - expect(controller.$.excludeDialog.show).toHaveBeenCalledWith(); - }); - }); - - describe('createInclusion()', () => { - it('shoud set the selected property and then call the includeDialog show() method', () => { - controller.$.includeDialog = {show: jest.fn()}; - - const type = 'weekday'; - const days = [Date.vnNew()]; - const weekday = 1; - controller.createInclusion(type, days, weekday); - - const selection = controller.selected; - const firstWeekday = selection.wdays[weekday]; - - expect(selection.type).toEqual('indefinitely'); - expect(firstWeekday).toBeTruthy(); - expect(controller.isNew).toBeTruthy(); - expect(controller.$.includeDialog.show).toHaveBeenCalledWith(); - }); - - it('shoud set the selected property with the first day and then call the includeDialog show() method', () => { - controller.$.includeDialog = {show: jest.fn()}; - - const type = 'nonListedType'; - const days = [Date.vnNew()]; - const weekday = 1; - controller.createInclusion(type, days, weekday); - - const selection = controller.selected; - - expect(selection.type).toEqual('day'); - expect(selection.dated).toEqual(days[0]); - expect(controller.isNew).toBeTruthy(); - expect(controller.$.includeDialog.show).toHaveBeenCalledWith(); - }); - }); - - describe('onIncludeResponse()', () => { - it('shoud call the onDelete() method', () => { - jest.spyOn(controller, 'onDelete').mockReturnValue( - new Promise(accept => accept()) - ); - - controller.selected = {id: 1}; - controller.onIncludeResponse('delete'); - - expect(controller.onDelete).toHaveBeenCalledWith(1); - }); - - it('shoud make an HTTP POST query to create a new one and then call the refresh() method', () => { - jest.spyOn(controller, 'refresh').mockReturnThis(); - - controller.selected = {id: 1}; - controller.isNew = true; - - $httpBackend.when('POST', `Zones/1/events`).respond(200); - controller.onIncludeResponse('accept'); - $httpBackend.flush(); - - expect(controller.refresh).toHaveBeenCalledWith(); - }); - - it('shoud make an HTTP PUT query and then call the refresh() method', () => { - jest.spyOn(controller, 'refresh').mockReturnThis(); - - controller.selected = {id: 1}; - controller.isNew = false; - - const eventId = 1; - $httpBackend.when('PUT', `Zones/1/events/${eventId}`).respond(200); - controller.onIncludeResponse('accept'); - $httpBackend.flush(); - - expect(controller.refresh).toHaveBeenCalledWith(); - }); - }); - - describe('onExcludeResponse()', () => { - it('should call the exclusionCreate() method', () => { - jest.spyOn(controller, 'exclusionCreate').mockReturnThis(); - - controller.excludeSelected = {type: 'all'}; - controller.onExcludeResponse('accept'); - - expect(controller.exclusionCreate).toHaveBeenCalledWith(); - }); - - it('should call the exclusionGeoCreate() method', () => { - jest.spyOn(controller, 'exclusionGeoCreate').mockReturnThis(); - - controller.excludeSelected = {type: 'specificLocations'}; - controller.onExcludeResponse('accept'); - - expect(controller.exclusionGeoCreate).toHaveBeenCalledWith(); - }); - - it('should call the exclusionDelete() method', () => { - jest.spyOn(controller, 'exclusionDelete').mockReturnThis(); - - controller.excludeSelected = {id: 1, type: 'all'}; - controller.onExcludeResponse('delete'); - - expect(controller.exclusionDelete).toHaveBeenCalledWith(controller.excludeSelected); - }); - }); - - describe('onDeleteResponse()', () => { - it('shoud make an HTTP DELETE query and then call the refresh() method', () => { - jest.spyOn(controller, 'refresh').mockReturnThis(); - - const eventId = 1; - $httpBackend.expect('DELETE', `Zones/1/events/1`).respond({id: 1}); - controller.onDeleteResponse('accept', eventId); - $httpBackend.flush(); - - expect(controller.refresh).toHaveBeenCalledWith(); - }); - }); - - describe('exclusionCreate()', () => { - it('shoud make an HTTP POST query and then call the refresh() method', () => { - jest.spyOn(controller, 'refresh').mockReturnThis(); - - controller.excludeSelected = {}; - controller.isNew = true; - $httpBackend.expect('POST', `Zones/1/exclusions`).respond({id: 1}); - controller.exclusionCreate(); - $httpBackend.flush(); - - expect(controller.refresh).toHaveBeenCalledWith(); - }); - }); - - describe('exclusionDelete()', () => { - it('shoud make an HTTP DELETE query once and then call the refresh() method', () => { - jest.spyOn(controller, 'refresh').mockReturnThis(); - - const exclusions = {id: 1}; - const firstExclusionId = 1; - $httpBackend.expectDELETE(`Zones/1/exclusions/${firstExclusionId}`).respond(200); - controller.exclusionDelete(exclusions); - $httpBackend.flush(); - - expect(controller.refresh).toHaveBeenCalledWith(); - }); - }); - - describe('onSearch()', () => { - it('should call the applyFilter() method and then set the data', () => { - jest.spyOn(controller, 'getChecked').mockReturnValue([1, 2, 3]); - - controller.$.treeview = {}; - controller.$.model = crudModel; - controller.excludeSelected = {type: 'specificLocations'}; - controller._excludeSearch = 'es'; - - controller.onSearch(); - const treeviewData = controller.$.treeview.data; - - expect(treeviewData).toBeDefined(); - expect(treeviewData.length).toEqual(3); - }); - }); - - describe('onFetch()', () => { - it('should call the applyFilter() method and then return the model data', () => { - jest.spyOn(controller, 'getChecked').mockReturnValue([1, 2, 3]); - - controller.$.model = crudModel; - const result = controller.onFetch(); - - expect(result.length).toEqual(3); - }); - }); -}); diff --git a/modules/zone/front/events/locale/es.yml b/modules/zone/front/events/locale/es.yml deleted file mode 100644 index d6eee9f67..000000000 --- a/modules/zone/front/events/locale/es.yml +++ /dev/null @@ -1,12 +0,0 @@ -Edit mode: Modo de edición -Include: Incluir -Exclude: Excluir -Events: Eventos -Add event: Añadir evento -Edit event: Editar evento -All: Todo -Specific locations: Localizaciones concretas -Locations where it is not distributed: Localizaciones en las que no se reparte -You must select a location: Debes seleccionar una localización -Add exclusion: Añadir exclusión -Edit exclusion: Editar exclusión diff --git a/modules/zone/front/events/style.scss b/modules/zone/front/events/style.scss deleted file mode 100644 index 49a6e87a6..000000000 --- a/modules/zone/front/events/style.scss +++ /dev/null @@ -1,11 +0,0 @@ -@import "variables"; - - .width{ - width: 600px - } - - .treeview{ - max-height: 300px; - overflow: auto; - } - diff --git a/modules/zone/front/index.js b/modules/zone/front/index.js index dc20eea47..a7209a0bd 100644 --- a/modules/zone/front/index.js +++ b/modules/zone/front/index.js @@ -1,19 +1,3 @@ export * from './module'; import './main'; -import './index/'; -import './delivery-days'; -import './summary'; -import './card'; -import './descriptor'; -import './descriptor-popover'; -import './search-panel'; -import './create'; -import './basic-data'; -import './warehouses'; -import './events'; -import './calendar'; -import './location'; -import './calendar'; -import './upcoming-deliveries'; -import './log'; diff --git a/modules/zone/front/index/index.html b/modules/zone/front/index/index.html deleted file mode 100644 index 78e3f2cd8..000000000 --- a/modules/zone/front/index/index.html +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - Id - Name - Agency - Closing - Price - - - - - - {{::zone.id}} - {{::zone.name}} - {{::zone.agencyMode.name}} - {{::zone.hour | date: 'HH:mm'}} - {{::zone.price | currency: 'EUR':2}} - - - - - - - - - - - - - - - - - - - - - - diff --git a/modules/zone/front/index/index.js b/modules/zone/front/index/index.js deleted file mode 100644 index ad54f7df4..000000000 --- a/modules/zone/front/index/index.js +++ /dev/null @@ -1,21 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - preview(zone) { - this.selectedZone = zone; - this.$.summary.show(); - } - - onCloneAccept(zone) { - return this.$http.post(`Zones/${zone.id}/clone`) - .then(res => { - this.$state.go('zone.card.basicData', {id: res.data.id}); - }); - } -} - -ngModule.vnComponent('vnZoneIndex', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/zone/front/index/locale/es.yml b/modules/zone/front/index/locale/es.yml deleted file mode 100644 index 14195e869..000000000 --- a/modules/zone/front/index/locale/es.yml +++ /dev/null @@ -1,2 +0,0 @@ -Do you want to clone this zone?: ¿Seguro que quieres clonar esta zona? -All it's properties will be copied: Todas sus propiedades serán copiadas \ No newline at end of file diff --git a/modules/zone/front/locale/es.yml b/modules/zone/front/locale/es.yml index 7c9e783ab..4d528f37a 100644 --- a/modules/zone/front/locale/es.yml +++ b/modules/zone/front/locale/es.yml @@ -13,7 +13,7 @@ Indefinitely: Indefinido Inflation: Inflación Locations: Localizaciones Maximum m³: M³ máximo -Max m³: Medida máxima +Max m³: Medida máxima New zone: Nueva zona One day: Un día Pick up: Recogida @@ -32,4 +32,4 @@ Warehouses: Almacenes Week days: Días de la semana Zones: Zonas zone: zona -Go to the zone: Ir a la zona \ No newline at end of file +Go to the zone: Ir a la zona diff --git a/modules/zone/front/location/index.html b/modules/zone/front/location/index.html deleted file mode 100644 index b86c618b7..000000000 --- a/modules/zone/front/location/index.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - -
- - - - - - -
diff --git a/modules/zone/front/location/index.js b/modules/zone/front/location/index.js deleted file mode 100644 index 0f92f37de..000000000 --- a/modules/zone/front/location/index.js +++ /dev/null @@ -1,56 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - onSearch(params) { - this.$.model.applyFilter({}, params).then(() => { - const data = this.$.model.data; - this.$.treeview.data = data; - }); - } - - onFetch(item) { - const params = item ? {parentId: item.id} : null; - return this.$.model.applyFilter({}, params) - .then(() => this.$.model.data); - } - - onSort(a, b) { - if (b.selected !== a.selected) { - if (a.selected == null) - return 1; - if (b.selected == null) - return -1; - return b.selected - a.selected; - } - - return a.name.localeCompare(b.name); - } - - exprBuilder(param, value) { - switch (param) { - case 'search': - return {name: {like: `%${value}%`}}; - } - } - - onSelection(value, item) { - if (value == null) - value = undefined; - const params = {geoId: item.id, isIncluded: value}; - const path = `zones/${this.zone.id}/toggleIsIncluded`; - this.$http.post(path, params); - } -} - -ngModule.vnComponent('vnZoneLocation', { - template: require('./index.html'), - controller: Controller, - bindings: { - zone: '<' - }, - require: { - card: '^vnZoneCard' - } -}); diff --git a/modules/zone/front/location/index.spec.js b/modules/zone/front/location/index.spec.js deleted file mode 100644 index 30968209c..000000000 --- a/modules/zone/front/location/index.spec.js +++ /dev/null @@ -1,50 +0,0 @@ -import './index'; -import crudModel from 'core/mocks/crud-model'; - -describe('component vnZoneLocation', () => { - let $scope; - let controller; - let $httpBackend; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - const $element = angular.element(``); - controller = $componentController('vnZoneLocation', {$element, $scope}); - controller.$.model = crudModel; - controller.zone = {id: 1}; - })); - - describe('onSearch()', () => { - it('should call the applyFilter() method and then set the data', () => { - controller.$.treeview = {}; - controller.onSearch({}); - - const treeviewData = controller.$.treeview.data; - - expect(treeviewData).toBeDefined(); - expect(treeviewData.length).toEqual(3); - }); - }); - - describe('onFetch()', () => { - it('should call the applyFilter() method and then return the model data', () => { - const result = controller.onFetch(); - - expect(result.length).toEqual(3); - }); - }); - - describe('onSelection()', () => { - it('should make an HTTP POST query', () => { - const item = {id: 123}; - - const expectedParams = {geoId: 123, isIncluded: true}; - $httpBackend.expect('POST', `zones/1/toggleIsIncluded`, expectedParams).respond(200); - controller.onSelection(true, item); - $httpBackend.flush(); - }); - }); -}); diff --git a/modules/zone/front/location/style.scss b/modules/zone/front/location/style.scss deleted file mode 100644 index 24d685a51..000000000 --- a/modules/zone/front/location/style.scss +++ /dev/null @@ -1,21 +0,0 @@ -@import "variables"; - -vn-zone-location { - vn-treeview-child { - .content > .vn-check:not(.indeterminate):not(.checked) { - color: $color-alert; - - & > .btn { - border-color: $color-alert; - } - } - .content > .vn-check.checked { - color: $color-notice; - - & > .btn { - background-color: $color-notice; - border-color: $color-notice - } - } - } -} diff --git a/modules/zone/front/log/index.html b/modules/zone/front/log/index.html deleted file mode 100644 index 539afda82..000000000 --- a/modules/zone/front/log/index.html +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/modules/zone/front/log/index.js b/modules/zone/front/log/index.js deleted file mode 100644 index 8c3be2423..000000000 --- a/modules/zone/front/log/index.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -ngModule.vnComponent('vnZoneLog', { - template: require('./index.html'), - controller: Section, -}); diff --git a/modules/zone/front/main/index.html b/modules/zone/front/main/index.html index 8dd6cdf78..e69de29bb 100644 --- a/modules/zone/front/main/index.html +++ b/modules/zone/front/main/index.html @@ -1,19 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/modules/zone/front/main/index.js b/modules/zone/front/main/index.js index 3be60c5a1..38896d418 100644 --- a/modules/zone/front/main/index.js +++ b/modules/zone/front/main/index.js @@ -4,25 +4,10 @@ import ModuleMain from 'salix/components/module-main'; export default class Zone extends ModuleMain { constructor($element, $) { super($element, $); - this.filter = { - include: { - relation: 'agencyMode', - scope: {fields: ['name']} - } - }; } - - exprBuilder(param, value) { - switch (param) { - case 'search': - return /^\d+$/.test(value) - ? {id: value} - : {name: {like: `%${value}%`}}; - case 'name': - return {[param]: {like: `%${value}%`}}; - case 'agencyModeFk': - return {[param]: value}; - } + async $onInit() { + this.$state.go('home'); + window.location.href = await this.vnApp.getUrl(`zone/`); } } diff --git a/modules/zone/front/main/index.spec.js b/modules/zone/front/main/index.spec.js deleted file mode 100644 index 1e50cee80..000000000 --- a/modules/zone/front/main/index.spec.js +++ /dev/null @@ -1,30 +0,0 @@ -import './index.js'; - -describe('Zone Component vnZone', () => { - let controller; - - beforeEach(ngModule('zone')); - - beforeEach(inject($componentController => { - const $element = angular.element(''); - controller = $componentController('vnZone', {$element}); - })); - - describe('exprBuilder()', () => { - it('should return a formated object with the id in case of search', () => { - let param = 'search'; - let value = 1; - let result = controller.exprBuilder(param, value); - - expect(result).toEqual({id: 1}); - }); - - it('should return a formated object with the agencyModeFk in case of agencyModeFk', () => { - let param = 'agencyModeFk'; - let value = 'My Delivery'; - let result = controller.exprBuilder(param, value); - - expect(result).toEqual({agencyModeFk: 'My Delivery'}); - }); - }); -}); diff --git a/modules/zone/front/routes.json b/modules/zone/front/routes.json index 7f67260da..a4993007d 100644 --- a/modules/zone/front/routes.json +++ b/modules/zone/front/routes.json @@ -7,15 +7,6 @@ "menus": { "main": [ {"state": "zone.index", "icon": "icon-zone"}, - {"state": "zone.deliveryDays", "icon": "today"}, - {"state": "zone.upcomingDeliveries", "icon": "today"} - ], - "card": [ - {"state": "zone.card.basicData", "icon": "settings"}, - {"state": "zone.card.location", "icon": "my_location"}, - {"state": "zone.card.warehouses", "icon": "home"}, - {"state": "zone.card.log", "icon": "history"}, - {"state": "zone.card.events", "icon": "today"} ] }, "keybindings": [ @@ -34,79 +25,6 @@ "state": "zone.index", "component": "vn-zone-index", "description": "Zones" - }, - { - "url": "/delivery-days?q&deliveryMethodFk&geoFk&agencyModeFk", - "state": "zone.deliveryDays", - "component": "vn-zone-delivery-days", - "description": "Delivery days" - }, - { - "url": "/upcoming-deliveries", - "state": "zone.upcomingDeliveries", - "component": "vn-upcoming-deliveries", - "description": "Upcoming deliveries" - }, - { - "url": "/create", - "state": "zone.create", - "component": "vn-zone-create", - "description": "New zone" - }, - { - "url": "/:id", - "state": "zone.card", - "component": "vn-zone-card", - "abstract": true, - "description": "Detail" - }, - { - "url": "/summary", - "state": "zone.card.summary", - "component": "vn-zone-summary", - "description": "Summary", - "params": { - "zone": "$ctrl.zone" - } - }, - { - "url": "/basic-data", - "state": "zone.card.basicData", - "component": "vn-zone-basic-data", - "description": "Basic data", - "params": { - "zone": "$ctrl.zone" - } - }, - { - "url": "/warehouses", - "state": "zone.card.warehouses", - "component": "vn-zone-warehouses", - "description": "Warehouses" - }, - { - "url": "/events?q", - "state": "zone.card.events", - "component": "vn-zone-events", - "description": "Calendar", - "params": { - "zone": "$ctrl.zone" - } - }, - { - "url": "/location?q", - "state": "zone.card.location", - "component": "vn-zone-location", - "description": "Locations", - "params": { - "zone": "$ctrl.zone" - } - }, - { - "url" : "/log", - "state": "zone.card.log", - "component": "vn-zone-log", - "description": "Log" } ] -} \ No newline at end of file +} diff --git a/modules/zone/front/search-panel/index.html b/modules/zone/front/search-panel/index.html deleted file mode 100644 index bda8a946e..000000000 --- a/modules/zone/front/search-panel/index.html +++ /dev/null @@ -1,34 +0,0 @@ -
-
- - - - - - - - - - - - - - - -
-
\ No newline at end of file diff --git a/modules/zone/front/search-panel/index.js b/modules/zone/front/search-panel/index.js deleted file mode 100644 index 598af02b2..000000000 --- a/modules/zone/front/search-panel/index.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; - -ngModule.vnComponent('vnZoneSearchPanel', { - template: require('./index.html'), - controller: SearchPanel -}); diff --git a/modules/zone/front/summary/index.html b/modules/zone/front/summary/index.html deleted file mode 100644 index 2fe94388f..000000000 --- a/modules/zone/front/summary/index.html +++ /dev/null @@ -1,59 +0,0 @@ - -
- - - - #{{$ctrl.summary.id}} - {{$ctrl.summary.name}} -
- - - - - - - - - - - - - - - - - - - - - - -

- - Warehouse - -

- - - - Name - - - - - {{zoneWarehouse.warehouse.name}} - - - -
-
-
\ No newline at end of file diff --git a/modules/zone/front/summary/index.js b/modules/zone/front/summary/index.js deleted file mode 100644 index ad33f28be..000000000 --- a/modules/zone/front/summary/index.js +++ /dev/null @@ -1,56 +0,0 @@ -import ngModule from '../module'; -import Summary from 'salix/components/summary'; - -class Controller extends Summary { - get zone() { - return this._zone; - } - - set zone(value) { - this._zone = value; - - if (!value) return; - - this.getSummary(); - this.getWarehouses(); - } - - getSummary() { - const params = { - filter: { - include: { - relation: 'agencyMode', - fields: ['name'] - }, - where: { - id: this.zone.id - } - } - }; - this.$http.get(`Zones/findOne`, {params}).then(res => { - this.summary = res.data; - }); - } - - getWarehouses() { - const params = { - filter: { - include: { - relation: 'warehouse', - fields: ['name'] - } - } - }; - this.$http.get(`Zones/${this.zone.id}/warehouses`, {params}).then(res => { - this.zoneWarehouses = res.data; - }); - } -} - -ngModule.vnComponent('vnZoneSummary', { - template: require('./index.html'), - controller: Controller, - bindings: { - zone: '<' - } -}); diff --git a/modules/zone/front/summary/index.spec.js b/modules/zone/front/summary/index.spec.js deleted file mode 100644 index 7541ee795..000000000 --- a/modules/zone/front/summary/index.spec.js +++ /dev/null @@ -1,76 +0,0 @@ -import './index'; - -describe('component vnZoneSummary', () => { - let $scope; - let controller; - let $httpBackend; - let $httpParamSerializer; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { - $httpBackend = _$httpBackend_; - $httpParamSerializer = _$httpParamSerializer_; - $scope = $rootScope.$new(); - const $element = angular.element(``); - controller = $componentController('vnZoneSummary', {$element, $scope}); - })); - - describe('zone setter', () => { - it('should set the zone and then call both getSummary() and getWarehouses()', () => { - jest.spyOn(controller, 'getSummary'); - jest.spyOn(controller, 'getWarehouses'); - - controller.zone = {id: 1}; - - expect(controller.getSummary).toHaveBeenCalledWith(); - expect(controller.getWarehouses).toHaveBeenCalledWith(); - }); - }); - - describe('getSummary()', () => { - it('should perform a get and then store data on the controller', () => { - controller._zone = {id: 1}; - let params = { - filter: { - include: { - relation: 'agencyMode', - fields: ['name'] - }, - where: { - id: controller._zone.id - } - } - }; - const serializedParams = $httpParamSerializer(params); - const query = `Zones/findOne?${serializedParams}`; - $httpBackend.expectGET(query).respond({id: 1}); - controller.getSummary(); - $httpBackend.flush(); - - expect(controller.summary).toBeDefined(); - }); - }); - - describe('getWarehouses()', () => { - it('should make an HTTP get query and then store data on the controller', () => { - controller._zone = {id: 1}; - const params = { - filter: { - include: { - relation: 'warehouse', - fields: ['name'] - } - } - }; - - const serializedParams = $httpParamSerializer(params); - const query = `Zones/1/warehouses?${serializedParams}`; - $httpBackend.expect('GET', query).respond([{id: 1}]); - controller.getWarehouses(); - $httpBackend.flush(); - - expect(controller.zoneWarehouses.length).toEqual(1); - }); - }); -}); diff --git a/modules/zone/front/upcoming-deliveries/index.html b/modules/zone/front/upcoming-deliveries/index.html deleted file mode 100644 index afcd0bbc6..000000000 --- a/modules/zone/front/upcoming-deliveries/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - -
- -
{{$ctrl.getWeekDay(detail.shipped)}} - {{detail.shipped | date: 'dd/MM/yyyy'}}
-
- - - - Province - Closing - Id - - - - - {{::zone.name}} - {{::zone.hour}} - {{::zone.zoneFk}} - - - -
-
-
diff --git a/modules/zone/front/upcoming-deliveries/index.js b/modules/zone/front/upcoming-deliveries/index.js deleted file mode 100644 index 371321711..000000000 --- a/modules/zone/front/upcoming-deliveries/index.js +++ /dev/null @@ -1,23 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $, vnWeekDays) { - super($element, $); - this.days = vnWeekDays.days; - } - - getWeekDay(jsonDate) { - const weekDay = new Date(jsonDate).getDay(); - - return this.days[weekDay].locale; - } -} - -Controller.$inject = ['$element', '$scope', 'vnWeekDays']; - -ngModule.vnComponent('vnUpcomingDeliveries', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/zone/front/upcoming-deliveries/index.spec.js b/modules/zone/front/upcoming-deliveries/index.spec.js deleted file mode 100644 index 95eb999f9..000000000 --- a/modules/zone/front/upcoming-deliveries/index.spec.js +++ /dev/null @@ -1,22 +0,0 @@ -import './index'; - -describe('component vnUpcomingDeliveries', () => { - let $scope; - let controller; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, $rootScope) => { - $scope = $rootScope.$new(); - const $element = angular.element(``); - controller = $componentController('vnUpcomingDeliveries', {$element, $scope}); - })); - - describe('getWeekDay()', () => { - it('should retrieve a weekday for a json passed', () => { - let jsonDate = '1970-01-01T22:00:00.000Z'; - - expect(controller.getWeekDay(jsonDate)).toEqual('Thursday'); - }); - }); -}); diff --git a/modules/zone/front/upcoming-deliveries/locale/es.yml b/modules/zone/front/upcoming-deliveries/locale/es.yml deleted file mode 100644 index 9f08e3a72..000000000 --- a/modules/zone/front/upcoming-deliveries/locale/es.yml +++ /dev/null @@ -1,3 +0,0 @@ -Family: Familia -Percentage: Porcentaje -Dwindle: Mermas \ No newline at end of file diff --git a/modules/zone/front/upcoming-deliveries/style.scss b/modules/zone/front/upcoming-deliveries/style.scss deleted file mode 100644 index b52231a09..000000000 --- a/modules/zone/front/upcoming-deliveries/style.scss +++ /dev/null @@ -1,26 +0,0 @@ -@import "variables"; - -vn-upcoming-deliveries { - .header { - margin-bottom: 16px; - text-transform: uppercase; - font-size: 1.25rem; - line-height: 1; - padding: 7px; - padding-bottom: 7px; - padding-bottom: 4px; - font-weight: lighter; - background-color: $color-main-light; - border-bottom: 1px solid $color-primary; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - background-color: $color-bg; - } - - vn-table vn-th.waste-family, - vn-table vn-td.waste-family { - max-width: 64px; - width: 64px - } -} \ No newline at end of file diff --git a/modules/zone/front/warehouses/index.html b/modules/zone/front/warehouses/index.html deleted file mode 100644 index acd85f182..000000000 --- a/modules/zone/front/warehouses/index.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - {{::row.warehouse.name}} - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/modules/zone/front/warehouses/index.js b/modules/zone/front/warehouses/index.js deleted file mode 100644 index 85b398658..000000000 --- a/modules/zone/front/warehouses/index.js +++ /dev/null @@ -1,56 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -class Controller extends Section { - $onInit() { - this.refresh(); - } - - get path() { - return `Zones/${this.$params.id}/warehouses`; - } - - refresh() { - let filter = {include: 'warehouse'}; - this.$http.get(this.path, {params: {filter}}) - .then(res => this.$.data = res.data); - } - - onCreate() { - this.selected = {}; - this.$.dialog.show(); - } - - onSave() { - this.$http.post(this.path, this.selected) - .then(() => { - this.selected = null; - this.isNew = null; - this.$.dialog.hide(); - this.refresh(); - }); - - return false; - } - - onDelete(row) { - this.$.confirm.show(); - this.deleteRow = row; - } - - delete() { - let row = this.deleteRow; - if (!row) return; - return this.$http.delete(`${this.path}/${row.id}`) - .then(() => { - let index = this.$.data.indexOf(row); - if (index !== -1) this.$.data.splice(index, 1); - this.deleteRow = null; - }); - } -} - -ngModule.vnComponent('vnZoneWarehouses', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/zone/front/warehouses/index.spec.js b/modules/zone/front/warehouses/index.spec.js deleted file mode 100644 index 0e71d541c..000000000 --- a/modules/zone/front/warehouses/index.spec.js +++ /dev/null @@ -1,60 +0,0 @@ -import './index.js'; - -describe('Zone warehouses', () => { - let $httpBackend; - let $httpParamSerializer; - let controller; - let $element; - - beforeEach(ngModule('zone')); - - beforeEach(inject(($componentController, _$httpBackend_, _$httpParamSerializer_) => { - $httpBackend = _$httpBackend_; - $httpParamSerializer = _$httpParamSerializer_; - $element = angular.element(' { - it('should make an HTTP GET query and then set the data', () => { - const params = {filter: {include: 'warehouse'}}; - const serializedParams = $httpParamSerializer(params); - const path = `Zones/1/warehouses?${serializedParams}`; - $httpBackend.expect('GET', path).respond([{id: 1, name: 'Warehouse one'}]); - controller.refresh(); - $httpBackend.flush(); - - expect(controller.$.data).toBeDefined(); - }); - }); - - describe('onSave()', () => { - it('should make an HTTP POST query and then call the refresh() method', () => { - jest.spyOn(controller, 'refresh').mockReturnThis(); - - $httpBackend.expect('POST', `Zones/1/warehouses`).respond(200); - controller.onSave(); - $httpBackend.flush(); - - expect(controller.selected).toBeNull(); - expect(controller.isNew).toBeNull(); - expect(controller.$.dialog.hide).toHaveBeenCalledWith(); - expect(controller.refresh).toHaveBeenCalledWith(); - }); - }); - - describe('delete()', () => { - it('should make an HTTP DELETE query and then set deleteRow property to null value', () => { - controller.deleteRow = {id: 1}; - controller.$.data = [{id: 1}]; - $httpBackend.expect('DELETE', `Zones/1/warehouses/1`).respond(200); - controller.delete(); - $httpBackend.flush(); - - expect(controller.deleteRow).toBeNull(); - }); - }); -}); diff --git a/package.json b/package.json index 2ae7c3764..767ec231e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.40.0", + "version": "24.44.0", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", @@ -60,7 +60,7 @@ "@babel/register": "^7.7.7", "@commitlint/cli": "^19.2.1", "@commitlint/config-conventional": "^19.1.0", - "@verdnatura/myt": "^1.6.11", + "@verdnatura/myt": "^1.6.12", "angular-mocks": "^1.7.9", "babel-jest": "^26.0.1", "babel-loader": "^8.2.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e2480cf4a..042b91fe0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -143,8 +143,8 @@ devDependencies: specifier: ^19.1.0 version: 19.1.0 '@verdnatura/myt': - specifier: ^1.6.11 - version: 1.6.11 + specifier: ^1.6.12 + version: 1.6.12 angular-mocks: specifier: ^1.7.9 version: 1.8.3 @@ -2846,8 +2846,8 @@ packages: dev: false optional: true - /@verdnatura/myt@1.6.11: - resolution: {integrity: sha512-uqdbSJSznBBzAoRkvBt600nUMEPL1PJ2v73eWMZbaoGUMiZiNAehYjs4gIrObP1cxC85JOx97XoLpG0BzPsaig==} + /@verdnatura/myt@1.6.12: + resolution: {integrity: sha512-t/SiDuQW9KJkcjhwQ9AkrcoTwghxQ7IyQ56e+88eYdoMi24l6bQGF0wHzMaIPRfQAoR8hqgfMOief4OAqW4Iqw==} hasBin: true dependencies: '@sqltools/formatter': 1.2.5 @@ -6548,7 +6548,7 @@ packages: resolution: {integrity: sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==} engines: {node: '>= 4.0'} os: [darwin] - deprecated: The v1 package contains DANGEROUS / INSECURE binaries. Upgrade to safe fsevents v2 + deprecated: Upgrade to fsevents v2 to mitigate potential security issues requiresBuild: true dependencies: bindings: 1.5.0 @@ -10485,7 +10485,7 @@ packages: engines: {node: '>=10'} requiresBuild: true dependencies: - semver: 7.5.4 + semver: 7.6.0 dev: false optional: true @@ -12501,6 +12501,7 @@ packages: hasBin: true dependencies: lru-cache: 6.0.0 + dev: true /semver@7.6.0: resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==} @@ -12508,7 +12509,6 @@ packages: hasBin: true dependencies: lru-cache: 6.0.0 - dev: true /send@0.18.0(supports-color@6.1.0): resolution: {integrity: sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==} diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index c1701e084..89bc07488 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -58,6 +58,7 @@ {{$t('reference')}} {{$t('quantity')}} {{$t('concept')}} + {{$t('producer')}} {{$t('price')}} {{$t('discount')}} {{$t('vat')}} @@ -69,6 +70,7 @@ {{sale.itemFk}} {{sale.quantity}} {{sale.concept}} + {{sale.subName}} {{sale.price | currency('EUR', $i18n.locale)}} {{(sale.discount / 100) | percentage}} {{sale.vatType}} @@ -81,7 +83,6 @@ {{sale.tag5}} {{sale.value5}} {{sale.tag6}} {{sale.value6}} {{sale.tag7}} {{sale.value7}} - {{$t('producer')}} {{ sale.subName }}