From 78eba23d1233e9d240b4ccef6dcb64d66c4db91b Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 24 Aug 2023 13:44:15 +0200 Subject: [PATCH 001/123] refs #6156 new field --- .../00-ModifyProc_ticket_canAdvance.sql | 128 ++++++++++++++++++ .../back/methods/ticket/getTicketsAdvance.js | 11 +- modules/ticket/front/advance/index.html | 12 +- modules/ticket/front/future/locale/es.yml | 1 + 4 files changed, 140 insertions(+), 12 deletions(-) create mode 100644 db/changes/233601/00-ModifyProc_ticket_canAdvance.sql diff --git a/db/changes/233601/00-ModifyProc_ticket_canAdvance.sql b/db/changes/233601/00-ModifyProc_ticket_canAdvance.sql new file mode 100644 index 000000000..b0426711f --- /dev/null +++ b/db/changes/233601/00-ModifyProc_ticket_canAdvance.sql @@ -0,0 +1,128 @@ +CREATE TABLE IF NOT EXISTS `vn`.`ticketCanAdvanceConfig` ( + `id` INT auto_increment NULL, + `destinationOrder` INT NULL, + CONSTRAINT `ticketCanAdvanceConfig_PK` PRIMARY KEY (id) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; + +INSERT INTO `vn`.`ticketCanAdvanceConfig` + SET `destinationOrder` = 5; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) +BEGIN +/** + * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. + * + * @param vDateFuture Fecha de los tickets que se quieren adelantar. + * @param vDateToAdvance Fecha a cuando se quiere adelantar. + * @param vWarehouseFk Almacén + */ + DECLARE vDateInventory DATE; + + SELECT inventoried INTO vDateInventory FROM config; + + CREATE OR REPLACE TEMPORARY TABLE tStock + (itemFk INT PRIMARY KEY, amount INT) + ENGINE = MEMORY; + + INSERT INTO tStock(itemFk, amount) + SELECT itemFk, SUM(quantity) amount FROM + ( + SELECT itemFk, quantity + FROM itemTicketOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE landed >= vDateInventory + AND landed < vDateFuture + AND isVirtualStock = FALSE + AND warehouseInFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseOutFk = vWarehouseFk + ) t + GROUP BY itemFk HAVING amount != 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.filter + (INDEX (id)) + SELECT dest.*, + origin.* + FROM ( + SELECT s.ticketFk futureId, + t.workerFk, + t.shipped futureShipped, + t.totalWithVat futureTotalWithVat, + st.name futureState, + t.addressFk futureAddressFk, + am.name futureAgency, + count(s.id) futureLines, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, + CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, + SUM((s.quantity <= IFNULL(tst.amount,0))) hasStock, + st.classColor futureClassColor, + ( + count(s.id) - + SUM((s.quantity <= IFNULL(tst.amount,0))) + ) notMovableLines, + ( + count(s.id) = + SUM((s.quantity <= IFNULL(tst.amount,0))) + ) isFullMovable + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + LEFT JOIN tStock tst ON tst.itemFk = i.id + WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) + AND t.warehouseFk = vWarehouseFk + GROUP BY t.id + ) origin + JOIN ( + SELECT t.id, + t.addressFk, + st.name state, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt, + t.shipped, + t.totalWithVat, + am.name agency, + CAST(SUM(litros) AS DECIMAL(10,0)) liters, + CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, + st.classColor, + IF(HOUR(t.shipped), + HOUR(t.shipped), + COALESCE(HOUR(zc.hour),HOUR(z.hour)) + ) preparation + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + JOIN ticketCanAdvanceConfig + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + LEFT JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk + WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance) + AND t.warehouseFk = vWarehouseFk + AND st.order <= destinationOrder + GROUP BY t.id + ) dest ON dest.addressFk = origin.futureAddressFk + WHERE origin.hasStock != 0; + + DROP TEMPORARY TABLE tStock; +END$$ +DELIMITER ; diff --git a/modules/ticket/back/methods/ticket/getTicketsAdvance.js b/modules/ticket/back/methods/ticket/getTicketsAdvance.js index ec9314db2..5ad5152b9 100644 --- a/modules/ticket/back/methods/ticket/getTicketsAdvance.js +++ b/modules/ticket/back/methods/ticket/getTicketsAdvance.js @@ -110,13 +110,12 @@ module.exports = Self => { stmt = new ParameterizedSQL( `CALL vn.ticket_canAdvance(?,?,?)`, - [args.dateFuture, args.dateToAdvance, args.warehouseFk]); + [args.dateFuture, args.dateToAdvance, args.warehouseFk] + ); stmts.push(stmt); - stmt = new ParameterizedSQL(` - SELECT f.* - FROM tmp.filter f`); + stmt = new ParameterizedSQL(`SELECT f.* FROM tmp.filter f`); stmt.merge(conn.makeWhere(filter.where)); @@ -124,9 +123,7 @@ module.exports = Self => { stmt.merge(conn.makeLimit(filter)); const ticketsIndex = stmts.push(stmt) - 1; - stmts.push( - `DROP TEMPORARY TABLE - tmp.filter`); + stmts.push(`DROP TEMPORARY TABLE tmp.filter`); const sql = ParameterizedSQL.join(stmts, ';'); const result = await conn.executeStmt(sql, myOptions); diff --git a/modules/ticket/front/advance/index.html b/modules/ticket/front/advance/index.html index e6f16c965..8c50325fa 100644 --- a/modules/ticket/front/advance/index.html +++ b/modules/ticket/front/advance/index.html @@ -32,8 +32,8 @@ - Destination - Origin + Destination + Origin @@ -43,8 +43,7 @@ check-field="checked"> - - + ID @@ -54,6 +53,9 @@ IPT + + Preparation + State @@ -120,6 +122,7 @@ {{::ticket.ipt | dashIfEmpty}} + {{::ticket.preparation | dashIfEmpty}} @@ -164,7 +167,6 @@ {{::(ticket.futureTotalWithVat ? ticket.futureTotalWithVat : 0) | currency: 'EUR': 2}} - diff --git a/modules/ticket/front/future/locale/es.yml b/modules/ticket/front/future/locale/es.yml index 9fceea111..3645ad8ac 100644 --- a/modules/ticket/front/future/locale/es.yml +++ b/modules/ticket/front/future/locale/es.yml @@ -14,3 +14,4 @@ Success: Tickets movidos correctamente IPT: Encajado Origin Date: Fecha origen Destination Date: Fecha destino +Preparation: Preparación From d1214a998abd7636d862f0813634412f944ef184 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 6 Jun 2024 07:01:55 +0200 Subject: [PATCH 002/123] feat: login refs #6868 --- .../account/back/methods/account/login-app.js | 88 +++++++++++++++++++ modules/account/back/models/account.js | 1 + 2 files changed, 89 insertions(+) create mode 100644 modules/account/back/methods/account/login-app.js diff --git a/modules/account/back/methods/account/login-app.js b/modules/account/back/methods/account/login-app.js new file mode 100644 index 000000000..18543f90e --- /dev/null +++ b/modules/account/back/methods/account/login-app.js @@ -0,0 +1,88 @@ +const {setDefaultHighWaterMark} = require('form-data'); +const {setLocale} = require('i18n'); + +module.exports = Self => { + Self.remoteMethodCtx('loginApp', { + description: 'Login a user with username/email and password', + accepts: [ + { + arg: 'user', + type: 'String', + description: 'The user name or email', + required: true + }, { + arg: 'password', + type: 'String', + description: 'The password' + }, { + arg: 'deviceId', + type: 'String', + description: 'Device id' + }, { + arg: 'android_id', + type: 'String', + description: 'Android id' + }, { + arg: 'versionApp', + type: 'String', + description: 'Version app' + }, { + arg: 'nameApp', + type: 'String', + description: 'Version app' + }, { + arg: 'serialNumber', + type: 'String', + description: 'Serial number' + } + + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/loginApp`, + verb: 'POST' + } + }); + + Self.loginApp = async(ctx, user, password, deviceId, android_id, versionApp, nameApp, options) => { + const models = Self.app.models; + + const login = await Self.app.models.VnUser.signIn(ctx, user, password, options); + + const userId = login.user; + + const query = + `INSERT IGNORE INTO operator (workerFk) + VALUES (?);`; + + const insertOperator = await Self.rawSql(query, [userId], options); + + const [serialNumber] = await models.DeviceProductionUser.findOne({ + where: {id: '100'} + }); + + const insertDeviceLog = await models.DeviceLog.create( + { + 'android_id': android_id, + 'userFk': userId, + 'versionApp': versionApp, + 'nameApp': nameApp, + 'serialNumber': [serialNumber] + }, + options + ); + + const queryDeviceCheck = + `CALL device_checkLogin(?, ?)`; + + const [queryDeviceCheckLogin] = await Self.rawSql(queryDeviceCheck, [userId, android_id], options); + + if (!queryDeviceCheckLogin.vIsAuthorized) + throw new UserError('User not authorized'); + + return insertDeviceLog; + }; +}; diff --git a/modules/account/back/models/account.js b/modules/account/back/models/account.js index ceb26053c..f89d3079e 100644 --- a/modules/account/back/models/account.js +++ b/modules/account/back/models/account.js @@ -10,6 +10,7 @@ module.exports = Self => { require('../methods/account/logout')(Self); require('../methods/account/change-password')(Self); require('../methods/account/set-password')(Self); + require('../methods/account/login-app')(Self); Self.setUnverifiedPassword = async(id, pass, options) => { const {emailVerified} = await models.VnUser.findById(id, {fields: ['emailVerified']}, options); From 5c3ce40bbdfba57fa06f7b86f0cf4eebf23484bb Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 11 Jun 2024 07:12:47 +0200 Subject: [PATCH 003/123] feat login-app refs #6868 --- .../account/back/methods/account/login-app.js | 54 ++++++++++--------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/modules/account/back/methods/account/login-app.js b/modules/account/back/methods/account/login-app.js index 18543f90e..3ade88fb8 100644 --- a/modules/account/back/methods/account/login-app.js +++ b/modules/account/back/methods/account/login-app.js @@ -49,40 +49,44 @@ module.exports = Self => { Self.loginApp = async(ctx, user, password, deviceId, android_id, versionApp, nameApp, options) => { const models = Self.app.models; + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); - const login = await Self.app.models.VnUser.signIn(ctx, user, password, options); + await models.Account.login(ctx, user, password, myOptions); - const userId = login.user; + const userId = ctx.req.accessToken.userId; - const query = - `INSERT IGNORE INTO operator (workerFk) - VALUES (?);`; + const isUserInOperator = await models.Operator.findById(userId); + if (!isUserInOperator) + await models.Operator.create({'workerFk': userId}); - const insertOperator = await Self.rawSql(query, [userId], options); + const device = await models.DeviceProduction.findById(deviceId); - const [serialNumber] = await models.DeviceProductionUser.findOne({ - where: {id: '100'} - }); + // const [serialNumber] = await models.DeviceProductionUser.findOne({ + // where: {id: '100'} + // }); - const insertDeviceLog = await models.DeviceLog.create( - { - 'android_id': android_id, - 'userFk': userId, - 'versionApp': versionApp, - 'nameApp': nameApp, - 'serialNumber': [serialNumber] - }, - options - ); + // const insertDeviceLog = await models.DeviceLog.create( + // { + // 'android_id': android_id, + // 'userFk': userId, + // 'versionApp': versionApp, + // 'nameApp': nameApp, + // 'serialNumber': [serialNumber] + // }, + // options + // ); - const queryDeviceCheck = - `CALL device_checkLogin(?, ?)`; + // const queryDeviceCheck = + // `CALL device_checkLogin(?, ?)`; - const [queryDeviceCheckLogin] = await Self.rawSql(queryDeviceCheck, [userId, android_id], options); + // const [queryDeviceCheckLogin] = await Self.rawSql(queryDeviceCheck, [userId, android_id], options); - if (!queryDeviceCheckLogin.vIsAuthorized) - throw new UserError('User not authorized'); + // if (!queryDeviceCheckLogin.vIsAuthorized) + // throw new UserError('User not authorized'); - return insertDeviceLog; + // return insertDeviceLog; + return []; }; }; From 52b82603d22d4214282eaa216945423d6274ca86 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 13 Jun 2024 10:40:37 +0200 Subject: [PATCH 004/123] feat login-app refs #6868 --- .../account/back/methods/account/login-app.js | 54 +++++++++++++++---- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/modules/account/back/methods/account/login-app.js b/modules/account/back/methods/account/login-app.js index 3ade88fb8..5392f8eb2 100644 --- a/modules/account/back/methods/account/login-app.js +++ b/modules/account/back/methods/account/login-app.js @@ -1,5 +1,4 @@ -const {setDefaultHighWaterMark} = require('form-data'); -const {setLocale} = require('i18n'); +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('loginApp', { @@ -53,20 +52,55 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - await models.Account.login(ctx, user, password, myOptions); + const login = await models.Account.login(ctx, user, password, myOptions); const userId = ctx.req.accessToken.userId; - const isUserInOperator = await models.Operator.findById(userId); - if (!isUserInOperator) - await models.Operator.create({'workerFk': userId}); + const resultCheckLogin = + await Self.rawSql('CALL vn.device_checkLogin(?, ?);', + [userId, android_id], myOptions); - const device = await models.DeviceProduction.findById(deviceId); + const [{vIsAuthorized, vMessage}] = resultCheckLogin[0]; - // const [serialNumber] = await models.DeviceProductionUser.findOne({ - // where: {id: '100'} - // }); + if (!vIsAuthorized) + throw new UserError('Not authorized'); + const isUserInOperator = await models.Operator.findOne({ + where: { + workerFk: userId + } + }); + + if (!isUserInOperator){ + await models.Operator.create({ 'workerFk': userId }); + + const getDataUser = await models.Operator.findOne({ + where: { + workerFk: userId + } + }); + + const resultDevice = await models.DeviceProduction.findOne({ + where: { + android_id: android_id + } + }); + + if (resultDevice) + serialNumber = resultDevice.serialNumber ?? ''; + + await models.DeviceLog.create({ + 'android_id': android_id, + 'userFk': userId, + 'nameApp': nameApp, + 'versionApp': versionApp, + 'serialNumber': serialNumber + }); + + + + console.log(vIsAuthorized); + console.log(vMessage); // const insertDeviceLog = await models.DeviceLog.create( // { // 'android_id': android_id, From 9d5d62afafd846b2f64989a24fb10f1d594964ed Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 17 Jun 2024 13:56:58 +0200 Subject: [PATCH 005/123] feat newLogin refs #6868 --- .../account/back/methods/account/login-app.js | 111 +++++++++--------- .../methods/account/specs/login-app.spec.js | 20 ++++ modules/account/back/models/account.json | 9 +- 3 files changed, 82 insertions(+), 58 deletions(-) create mode 100644 modules/account/back/methods/account/specs/login-app.spec.js diff --git a/modules/account/back/methods/account/login-app.js b/modules/account/back/methods/account/login-app.js index 5392f8eb2..b18226bd2 100644 --- a/modules/account/back/methods/account/login-app.js +++ b/modules/account/back/methods/account/login-app.js @@ -2,23 +2,20 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('loginApp', { - description: 'Login a user with username/email and password', + description: 'Login a user with username and password for app', accepts: [ { arg: 'user', type: 'String', - description: 'The user name or email', + description: 'The user name', required: true }, { arg: 'password', type: 'String', + required: true, description: 'The password' }, { - arg: 'deviceId', - type: 'String', - description: 'Device id' - }, { - arg: 'android_id', + arg: 'androidId', type: 'String', description: 'Android id' }, { @@ -29,11 +26,7 @@ module.exports = Self => { arg: 'nameApp', type: 'String', description: 'Version app' - }, { - arg: 'serialNumber', - type: 'String', - description: 'Serial number' - } + }, ], returns: { @@ -46,7 +39,7 @@ module.exports = Self => { } }); - Self.loginApp = async(ctx, user, password, deviceId, android_id, versionApp, nameApp, options) => { + Self.loginApp = async(ctx, user, password, android_id, versionApp, nameApp, options) => { const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') @@ -54,14 +47,16 @@ module.exports = Self => { const login = await models.Account.login(ctx, user, password, myOptions); - const userId = ctx.req.accessToken.userId; + const {id: userId} = await models.VnUser.findOne({ + where: { + name: user + } + }); - const resultCheckLogin = + const [[{vIsAuthorized, vMessage}]] = await Self.rawSql('CALL vn.device_checkLogin(?, ?);', [userId, android_id], myOptions); - const [{vIsAuthorized, vMessage}] = resultCheckLogin[0]; - if (!vIsAuthorized) throw new UserError('Not authorized'); @@ -69,25 +64,14 @@ module.exports = Self => { where: { workerFk: userId } - }); + }, myOptions); - if (!isUserInOperator){ - await models.Operator.create({ 'workerFk': userId }); - - const getDataUser = await models.Operator.findOne({ - where: { - workerFk: userId - } - }); + if (!isUserInOperator) + await models.Operator.create({'workerFk': userId}); - const resultDevice = await models.DeviceProduction.findOne({ - where: { - android_id: android_id - } - }); - - if (resultDevice) - serialNumber = resultDevice.serialNumber ?? ''; + const serialNumber = (await models.DeviceProduction.findOne({ + where: {android_id: android_id} + }, myOptions))?.serialNumber ?? ''; await models.DeviceLog.create({ 'android_id': android_id, @@ -95,32 +79,45 @@ module.exports = Self => { 'nameApp': nameApp, 'versionApp': versionApp, 'serialNumber': serialNumber - }); + }, myOptions); + ctx.req.accessToken = {userId}; + const getDataUser = await models.VnUser.getCurrentUserData(ctx); - + const getDataOperator = await models.Operator.findOne({ + where: {workerFk: userId}, + fields: ['numberOfWagons', 'warehouseFk', 'itemPackingTypeFk', 'sectorFk', 'sector', + 'trainFk', 'train', 'labelerFk', 'printer'], + include: [ + { + relation: 'sector', + scope: { + fields: ['warehouseFk', 'description'], + } + }, { + relation: 'printer', + scope: { + fields: ['name'], + } + }, { + relation: 'train', + scope: { + fields: ['name'], + } + } - console.log(vIsAuthorized); - console.log(vMessage); - // const insertDeviceLog = await models.DeviceLog.create( - // { - // 'android_id': android_id, - // 'userFk': userId, - // 'versionApp': versionApp, - // 'nameApp': nameApp, - // 'serialNumber': [serialNumber] - // }, - // options - // ); + ] + }, myOptions); - // const queryDeviceCheck = - // `CALL device_checkLogin(?, ?)`; + const getVersion = await models.MobileAppVersionControl.getVersion(ctx, nameApp); - // const [queryDeviceCheckLogin] = await Self.rawSql(queryDeviceCheck, [userId, android_id], options); - - // if (!queryDeviceCheckLogin.vIsAuthorized) - // throw new UserError('User not authorized'); - - // return insertDeviceLog; - return []; + const combinedResult = { + ...login, + ...getDataOperator.__data, + ...getDataUser.__data, + ...getVersion, + message: vMessage, + serialNumber, + }; + return combinedResult; }; }; diff --git a/modules/account/back/methods/account/specs/login-app.spec.js b/modules/account/back/methods/account/specs/login-app.spec.js new file mode 100644 index 000000000..527429435 --- /dev/null +++ b/modules/account/back/methods/account/specs/login-app.spec.js @@ -0,0 +1,20 @@ +const {models} = require('vn-loopback/server/server'); + +describe('Account loginApp()', () => { + fit('should throw an error when user/password is wrong', async() => { + let req = models.Account.loginApp('user', 'pass'); + + await expectAsync(req).toBeRejected(); + }); + + fit('should return data from user', async() => { + let user = 'employee'; + let password = 'nightmare'; + let androidId = 'androidid11234567890'; + let nameApp = 'warehouse'; + let versionApp = '10'; + + let req = models.Account.loginApp(user, password, androidId, nameApp, versionApp); + await expectAsync(req).toBeResolved(); + }); +}); diff --git a/modules/account/back/models/account.json b/modules/account/back/models/account.json index 6c2784696..466b2bc04 100644 --- a/modules/account/back/models/account.json +++ b/modules/account/back/models/account.json @@ -31,6 +31,13 @@ "principalId": "$everyone", "permission": "ALLOW" }, + { + "property": "loginApp", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }, { "property": "logout", "accessType": "EXECUTE", @@ -46,4 +53,4 @@ "permission": "ALLOW" } ] -} +} \ No newline at end of file From 0ab620b4854006a36882dcbc683fd759a94a2860 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 17 Jun 2024 16:50:00 +0200 Subject: [PATCH 006/123] feat newLogin refs #6868 --- modules/account/back/methods/account/login-app.js | 1 + modules/account/back/methods/account/specs/login-app.spec.js | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/account/back/methods/account/login-app.js b/modules/account/back/methods/account/login-app.js index b18226bd2..dc2708cbf 100644 --- a/modules/account/back/methods/account/login-app.js +++ b/modules/account/back/methods/account/login-app.js @@ -1,3 +1,4 @@ +const {ConsoleMessage} = require('puppeteer'); const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { diff --git a/modules/account/back/methods/account/specs/login-app.spec.js b/modules/account/back/methods/account/specs/login-app.spec.js index 527429435..90ce39f68 100644 --- a/modules/account/back/methods/account/specs/login-app.spec.js +++ b/modules/account/back/methods/account/specs/login-app.spec.js @@ -1,8 +1,9 @@ const {models} = require('vn-loopback/server/server'); describe('Account loginApp()', () => { + const ctx = {req: {accessToken: {}}}; fit('should throw an error when user/password is wrong', async() => { - let req = models.Account.loginApp('user', 'pass'); + let req = models.Account.loginApp(ctx, 'user', 'pass', 'androidid11234567890', 'warehouse', '10'); await expectAsync(req).toBeRejected(); }); @@ -14,7 +15,7 @@ describe('Account loginApp()', () => { let nameApp = 'warehouse'; let versionApp = '10'; - let req = models.Account.loginApp(user, password, androidId, nameApp, versionApp); + let req = models.Account.loginApp(ctx, user, password, androidId, nameApp, versionApp); await expectAsync(req).toBeResolved(); }); }); From c6da9e72e022c4101247b019887414b44c902693 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 17 Jun 2024 16:53:06 +0200 Subject: [PATCH 007/123] feat newLogin refs #6868 --- modules/account/back/methods/account/login-app.js | 2 +- .../back/methods/account/specs/login-app.spec.js | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/account/back/methods/account/login-app.js b/modules/account/back/methods/account/login-app.js index dc2708cbf..83c727f1a 100644 --- a/modules/account/back/methods/account/login-app.js +++ b/modules/account/back/methods/account/login-app.js @@ -1,4 +1,4 @@ -const {ConsoleMessage} = require('puppeteer'); + const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { diff --git a/modules/account/back/methods/account/specs/login-app.spec.js b/modules/account/back/methods/account/specs/login-app.spec.js index 90ce39f68..fc05cd726 100644 --- a/modules/account/back/methods/account/specs/login-app.spec.js +++ b/modules/account/back/methods/account/specs/login-app.spec.js @@ -3,19 +3,19 @@ const {models} = require('vn-loopback/server/server'); describe('Account loginApp()', () => { const ctx = {req: {accessToken: {}}}; fit('should throw an error when user/password is wrong', async() => { - let req = models.Account.loginApp(ctx, 'user', 'pass', 'androidid11234567890', 'warehouse', '10'); + const req = models.Account.loginApp(ctx, 'user', 'pass', 'androidid11234567890', 'warehouse', '10'); await expectAsync(req).toBeRejected(); }); fit('should return data from user', async() => { - let user = 'employee'; - let password = 'nightmare'; - let androidId = 'androidid11234567890'; - let nameApp = 'warehouse'; - let versionApp = '10'; + const user = 'employee'; + const password = 'nightmare'; + const androidId = 'androidid11234567890'; + const nameApp = 'warehouse'; + const versionApp = '10'; - let req = models.Account.loginApp(ctx, user, password, androidId, nameApp, versionApp); + const req = models.Account.loginApp(ctx, user, password, androidId, nameApp, versionApp); await expectAsync(req).toBeResolved(); }); }); From 4880d1497fe807721f094ac53fba1dbc29556ff5 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 18 Jun 2024 08:40:33 +0200 Subject: [PATCH 008/123] feat: refs #6727 Added util logClean --- db/routines/util/events/log_clean.sql | 8 ++++ db/routines/util/procedures/log_clean.sql | 41 +++++++++++++++++++ .../11107-pinkAspidistra/00-firstScript.sql | 30 ++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 db/routines/util/events/log_clean.sql create mode 100644 db/routines/util/procedures/log_clean.sql create mode 100644 db/versions/11107-pinkAspidistra/00-firstScript.sql diff --git a/db/routines/util/events/log_clean.sql b/db/routines/util/events/log_clean.sql new file mode 100644 index 000000000..8447069e6 --- /dev/null +++ b/db/routines/util/events/log_clean.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `util`.`log_clean` + ON SCHEDULE EVERY 1 DAY + STARTS '2024-07-09 00:30:00.000' + ON COMPLETION PRESERVE + ENABLE +DO CALL util.log_clean$$ +DELIMITER ; diff --git a/db/routines/util/procedures/log_clean.sql b/db/routines/util/procedures/log_clean.sql new file mode 100644 index 000000000..1401b5dd8 --- /dev/null +++ b/db/routines/util/procedures/log_clean.sql @@ -0,0 +1,41 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`log_clean`() +BEGIN +/** + * Hace limpieza de los datos de las tablas log, + * dejando únicamente los días de retención configurados. + */ + DECLARE vSchemaName VARCHAR(65); + DECLARE vTableName VARCHAR(65); + DECLARE vRetentionDays INT; + DECLARE vDated DATE; + DECLARE vDone BOOL; + + DECLARE vQueue CURSOR FOR + SELECT schemaName, tableName, retentionDays + FROM logClean + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vQueue; + l: LOOP + SET vDone = FALSE; + FETCH vQueue INTO vSchemaName, vTableName, vRetentionDays; + + SET vSchemaName = util.quoteIdentifier(vSchemaName); + SET vTableName = util.quoteIdentifier(vTableName); + SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY; + + IF vDone THEN + LEAVE l; + END IF; + + CALL util.exec(CONCAT( + 'DELETE FROM ', vSchemaName , '.', vTableName, + " WHERE creationDate < '", vDated, "'" + )); + END LOOP; + CLOSE vQueue; +END$$ +DELIMITER ; diff --git a/db/versions/11107-pinkAspidistra/00-firstScript.sql b/db/versions/11107-pinkAspidistra/00-firstScript.sql new file mode 100644 index 000000000..e702da21e --- /dev/null +++ b/db/versions/11107-pinkAspidistra/00-firstScript.sql @@ -0,0 +1,30 @@ +CREATE OR REPLACE TABLE `util`.`logClean` ( + `schemaName` varchar(64) NOT NULL, + `tableName` varchar(64) NOT NULL, + `retentionDays` int(11) NOT NULL, + `order` int(11) DEFAULT NULL, + PRIMARY KEY (`schemaName`,`tableName`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT INTO `util`.`logClean` (`schemaName`, `tableName`, `retentionDays`, `order`) + VALUES + ('account', 'roleLog', 'xxx', NULL), + ('account', 'userLog', 'xxx', NULL), + ('vn', 'entryLog', 'xxx', NULL), + ('vn', 'clientLog', 'xxx', NULL), + ('vn', 'itemLog', 'xxx', NULL), + ('vn', 'shelvingLog', 'xxx', NULL), + ('vn', 'workerLog', 'xxx', NULL), + ('vn', 'deviceProductionLog', 'xxx', NULL), + ('vn', 'zoneLog', 'xxx', NULL), + ('vn', 'rateLog', 'xxx', NULL), + ('vn', 'ticketLog', 'xxx', NULL), + ('vn', 'agencyLog', 'xxx', NULL), + ('vn', 'userLog', 'xxx', NULL), + ('vn', 'routeLog', 'xxx', NULL), + ('vn', 'claimLog', 'xxx', NULL), + ('vn', 'supplierLog', 'xxx', NULL), + ('vn', 'invoiceInLog', 'xxx', NULL), + ('vn', 'travelLog', 'xxx', NULL), + ('vn', 'packingSiteDeviceLog', 'xxx', NULL), + ('vn', 'parkingLog', 'xxx', NULL); From d61e32917a525d49ba556cbb8107821b9947a54a Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 21 Jun 2024 13:22:59 +0200 Subject: [PATCH 009/123] feat: refs #7562 Created deleteDeprecatedObjects --- db/dump/fixtures.after.sql | 4 +- .../util/events/deleteDeprecatedObjects.sql | 8 ++ .../procedures/deleteDeprecatedObjects.sql | 88 +++++++++++++++++++ .../11113-bronzeDendro/00-firstScript.sql | 22 +++++ 4 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 db/routines/util/events/deleteDeprecatedObjects.sql create mode 100644 db/routines/util/procedures/deleteDeprecatedObjects.sql create mode 100644 db/versions/11113-bronzeDendro/00-firstScript.sql diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index 562ea02d8..a276422e3 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -7,8 +7,8 @@ SET foreign_key_checks = 0; -- XXX: vn-database -INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled) - VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE); +INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled, daysKeepDeprecatedObjects) + VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE, 60); INSERT INTO util.binlogQueue (code,logName, `position`) VALUES ('mylogger', 'bin.000001', 4); diff --git a/db/routines/util/events/deleteDeprecatedObjects.sql b/db/routines/util/events/deleteDeprecatedObjects.sql new file mode 100644 index 000000000..0d7878a28 --- /dev/null +++ b/db/routines/util/events/deleteDeprecatedObjects.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `util`.`deleteDeprecatedObjects` + ON SCHEDULE EVERY 1 DAY + STARTS '2024-06-09 00:01:00.000' + ON COMPLETION PRESERVE + ENABLE +DO CALL deleteDeprecatedObjects$$ +DELIMITER ; diff --git a/db/routines/util/procedures/deleteDeprecatedObjects.sql b/db/routines/util/procedures/deleteDeprecatedObjects.sql new file mode 100644 index 000000000..a46d806d7 --- /dev/null +++ b/db/routines/util/procedures/deleteDeprecatedObjects.sql @@ -0,0 +1,88 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`deleteDeprecatedObjects`() + MODIFIES SQL DATA +BEGIN +/** + * Elimina objetos deprecados de la base de datos + */ + DECLARE vQuery TEXT; + DECLARE vDated DATE + DEFAULT ( + SELECT CURDATE() - INTERVAL daysKeepDeprecatedObjects DAY + FROM config + ); + DECLARE vDone BOOL; + + DECLARE vObjects CURSOR FOR + SELECT CONCAT('ALTER TABLE ', c.TABLE_SCHEMA, '.', c.TABLE_NAME, ' DROP PRIMARY KEY;') + FROM information_schema.`COLUMNS` c + LEFT JOIN information_schema.`VIEWS` v ON v.TABLE_SCHEMA = c.TABLE_SCHEMA + AND v.TABLE_NAME = c.TABLE_NAME + JOIN information_schema.STATISTICS s ON s.TABLE_SCHEMA = c.TABLE_SCHEMA + AND s.TABLE_NAME = c.TABLE_NAME + AND s.COLUMN_NAME = c.COLUMN_NAME + WHERE c.COLUMN_NAME LIKE '%\_\_' + AND REGEXP_SUBSTR(c.COLUMN_COMMENT, '[0-9]{4}-[0-9]{2}-[0-9]{2}') < vDated + AND v.TABLE_NAME IS NULL + AND s.INDEX_NAME = 'PRIMARY' + UNION ALL + SELECT CONCAT('ALTER TABLE ', c.TABLE_SCHEMA, '.', c.TABLE_NAME, ' DROP FOREIGN KEY ', kcu.CONSTRAINT_NAME, ';') + FROM information_schema.`COLUMNS` c + LEFT JOIN information_schema.`VIEWS` v ON v.TABLE_SCHEMA = c.TABLE_SCHEMA + AND v.TABLE_NAME = c.TABLE_NAME + JOIN information_schema.KEY_COLUMN_USAGE kcu ON kcu.TABLE_SCHEMA = c.TABLE_SCHEMA + AND kcu.TABLE_NAME = c.TABLE_NAME + AND kcu.COLUMN_NAME = c.COLUMN_NAME + WHERE c.COLUMN_NAME LIKE '%\_\_' + AND REGEXP_SUBSTR(c.COLUMN_COMMENT, '[0-9]{4}-[0-9]{2}-[0-9]{2}') < vDated + AND v.TABLE_NAME IS NULL + AND kcu.REFERENCED_COLUMN_NAME IS NOT NULL + UNION ALL + SELECT CONCAT('ALTER TABLE ', c.TABLE_SCHEMA, '.', c.TABLE_NAME, ' DROP COLUMN ', c.COLUMN_NAME, ';') + FROM information_schema.`COLUMNS` c + LEFT JOIN information_schema.`VIEWS` v ON v.TABLE_SCHEMA = c.TABLE_SCHEMA + AND v.TABLE_NAME = c.TABLE_NAME + LEFT JOIN information_schema.KEY_COLUMN_USAGE kcu ON kcu.TABLE_SCHEMA = c.TABLE_SCHEMA + AND kcu.TABLE_NAME = c.TABLE_NAME + AND kcu.COLUMN_NAME = c.COLUMN_NAME + WHERE c.COLUMN_NAME LIKE '%\_\_' + AND REGEXP_SUBSTR(c.COLUMN_COMMENT, '[0-9]{4}-[0-9]{2}-[0-9]{2}') < vDated + AND v.TABLE_NAME IS NULL + UNION ALL + SELECT CONCAT('DROP TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') + FROM information_schema.TABLES + WHERE TABLE_NAME LIKE '%\_\_' + AND REGEXP_SUBSTR(TABLE_COMMENT, '[0-9]{4}-[0-9]{2}-[0-9]{2}') < vDated; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL mail_insert( + 'cau@verdnatura.es', + NULL, + 'Error en la eliminación automática de objetos deprecados', + CONCAT('
', vQuery, '
', + '

Revisa la tabla util.eventLog para más detalles.

') + ); + RESIGNAL; + END; + + IF vDated IS NULL THEN + CALL throw('Variable config not set'); + END IF; + + OPEN vObjects; + l: LOOP + SET vDone = FALSE; + FETCH vObjects INTO vQuery; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `exec`(vQuery); + END LOOP; + CLOSE vObjects; +END$$ +DELIMITER ; diff --git a/db/versions/11113-bronzeDendro/00-firstScript.sql b/db/versions/11113-bronzeDendro/00-firstScript.sql new file mode 100644 index 000000000..b9a324c5e --- /dev/null +++ b/db/versions/11113-bronzeDendro/00-firstScript.sql @@ -0,0 +1,22 @@ +ALTER TABLE util.config + ADD daysKeepDeprecatedObjects int(11) unsigned NULL COMMENT 'Número de días que se mantendrán los objetos deprecados.'; + +UPDATE IGNORE util.config + SET daysKeepDeprecatedObjects = 60; + +ALTER TABLE IF EXISTS `vn`.`payrollWorker` + MODIFY COLUMN IF EXISTS `nss__` varchar(23) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `codpuesto__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `codcontrato__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `FAntiguedad__` date NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `grupotarifa__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `codcategoria__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `ContratoTemporal__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-03-15 refs #6738'; + +ALTER TABLE IF EXISTS `vn`.`payrollWorkCenter` + MODIFY COLUMN IF EXISTS `Centro__` varchar(255) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `nss_cotizacion__` varchar(15) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `domicilio__` varchar(255) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `poblacion__` varchar(45) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `cp__` varchar(5) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', + MODIFY COLUMN IF EXISTS `empresa_id__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738'; From c330e8c7156a55b9b99c4f7fa1e66aadcf894af0 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 21 Jun 2024 13:24:20 +0200 Subject: [PATCH 010/123] feat: refs #7562 Minor change --- db/routines/util/procedures/deleteDeprecatedObjects.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/util/procedures/deleteDeprecatedObjects.sql b/db/routines/util/procedures/deleteDeprecatedObjects.sql index a46d806d7..5911e0ab0 100644 --- a/db/routines/util/procedures/deleteDeprecatedObjects.sql +++ b/db/routines/util/procedures/deleteDeprecatedObjects.sql @@ -8,7 +8,7 @@ BEGIN DECLARE vQuery TEXT; DECLARE vDated DATE DEFAULT ( - SELECT CURDATE() - INTERVAL daysKeepDeprecatedObjects DAY + SELECT VN_CURDATE() - INTERVAL daysKeepDeprecatedObjects DAY FROM config ); DECLARE vDone BOOL; From c0668d054f86894f8e3f6ff6a4f7b3e02519266d Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 21 Jun 2024 13:51:33 +0200 Subject: [PATCH 011/123] feat: refs #7562 Changes --- db/dump/fixtures.after.sql | 4 +- .../procedures/deleteDeprecatedObjects.sql | 38 +++++++++++-------- .../11113-bronzeDendro/00-firstScript.sql | 6 ++- 3 files changed, 29 insertions(+), 19 deletions(-) diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index a276422e3..1353e481b 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -7,8 +7,8 @@ SET foreign_key_checks = 0; -- XXX: vn-database -INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled, daysKeepDeprecatedObjects) - VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE, 60); +INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled, dateRegex, deprecatedMarkRegex, daysKeepDeprecatedObjects) + VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE, '[0-9]{4}-[0-9]{2}-[0-9]{2}', '__$', 60); INSERT INTO util.binlogQueue (code,logName, `position`) VALUES ('mylogger', 'bin.000001', 4); diff --git a/db/routines/util/procedures/deleteDeprecatedObjects.sql b/db/routines/util/procedures/deleteDeprecatedObjects.sql index 5911e0ab0..729f3faf1 100644 --- a/db/routines/util/procedures/deleteDeprecatedObjects.sql +++ b/db/routines/util/procedures/deleteDeprecatedObjects.sql @@ -6,11 +6,9 @@ BEGIN * Elimina objetos deprecados de la base de datos */ DECLARE vQuery TEXT; - DECLARE vDated DATE - DEFAULT ( - SELECT VN_CURDATE() - INTERVAL daysKeepDeprecatedObjects DAY - FROM config - ); + DECLARE vDated DATE; + DECLARE vDateRegex VARCHAR(255); + DECLARE vMarkRegex VARCHAR(255); DECLARE vDone BOOL; DECLARE vObjects CURSOR FOR @@ -21,8 +19,8 @@ BEGIN JOIN information_schema.STATISTICS s ON s.TABLE_SCHEMA = c.TABLE_SCHEMA AND s.TABLE_NAME = c.TABLE_NAME AND s.COLUMN_NAME = c.COLUMN_NAME - WHERE c.COLUMN_NAME LIKE '%\_\_' - AND REGEXP_SUBSTR(c.COLUMN_COMMENT, '[0-9]{4}-[0-9]{2}-[0-9]{2}') < vDated + WHERE c.COLUMN_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci + AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated AND v.TABLE_NAME IS NULL AND s.INDEX_NAME = 'PRIMARY' UNION ALL @@ -33,8 +31,8 @@ BEGIN JOIN information_schema.KEY_COLUMN_USAGE kcu ON kcu.TABLE_SCHEMA = c.TABLE_SCHEMA AND kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME = c.COLUMN_NAME - WHERE c.COLUMN_NAME LIKE '%\_\_' - AND REGEXP_SUBSTR(c.COLUMN_COMMENT, '[0-9]{4}-[0-9]{2}-[0-9]{2}') < vDated + WHERE c.COLUMN_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci + AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated AND v.TABLE_NAME IS NULL AND kcu.REFERENCED_COLUMN_NAME IS NOT NULL UNION ALL @@ -45,20 +43,20 @@ BEGIN LEFT JOIN information_schema.KEY_COLUMN_USAGE kcu ON kcu.TABLE_SCHEMA = c.TABLE_SCHEMA AND kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME = c.COLUMN_NAME - WHERE c.COLUMN_NAME LIKE '%\_\_' - AND REGEXP_SUBSTR(c.COLUMN_COMMENT, '[0-9]{4}-[0-9]{2}-[0-9]{2}') < vDated + WHERE c.COLUMN_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci + AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated AND v.TABLE_NAME IS NULL UNION ALL SELECT CONCAT('DROP TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') FROM information_schema.TABLES - WHERE TABLE_NAME LIKE '%\_\_' - AND REGEXP_SUBSTR(TABLE_COMMENT, '[0-9]{4}-[0-9]{2}-[0-9]{2}') < vDated; + WHERE TABLE_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci + AND REGEXP_SUBSTR(TABLE_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - CALL mail_insert( + CALL vn.mail_insert( 'cau@verdnatura.es', NULL, 'Error en la eliminación automática de objetos deprecados', @@ -68,8 +66,16 @@ BEGIN RESIGNAL; END; - IF vDated IS NULL THEN - CALL throw('Variable config not set'); + SELECT dateRegex, + deprecatedMarkRegex, + VN_CURDATE() - INTERVAL daysKeepDeprecatedObjects DAY + INTO vDateRegex, + vMarkRegex, + vDated + FROM config; + + IF vDateRegex IS NULL OR vMarkRegex IS NULL OR vDated IS NULL THEN + CALL throw('Some config parameters are not set'); END IF; OPEN vObjects; diff --git a/db/versions/11113-bronzeDendro/00-firstScript.sql b/db/versions/11113-bronzeDendro/00-firstScript.sql index b9a324c5e..98ac69966 100644 --- a/db/versions/11113-bronzeDendro/00-firstScript.sql +++ b/db/versions/11113-bronzeDendro/00-firstScript.sql @@ -1,8 +1,12 @@ ALTER TABLE util.config + ADD COLUMN dateRegex varchar(255) NULL COMMENT 'Expresión regular para obtener las fechas.', + ADD deprecatedMarkRegex varchar(255) NULL COMMENT 'Expresión regular para obtener los objetos deprecados.', ADD daysKeepDeprecatedObjects int(11) unsigned NULL COMMENT 'Número de días que se mantendrán los objetos deprecados.'; UPDATE IGNORE util.config - SET daysKeepDeprecatedObjects = 60; + SET dateRegex = '[0-9]{4}-[0-9]{2}-[0-9]{2}', + deprecatedMarkRegex = '__$', + daysKeepDeprecatedObjects = 60; ALTER TABLE IF EXISTS `vn`.`payrollWorker` MODIFY COLUMN IF EXISTS `nss__` varchar(23) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', From aedc8071e1e8175a98c33add6b1c60ff9ffe7a97 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 21 Jun 2024 14:27:22 +0200 Subject: [PATCH 012/123] feat: refs #7562 Changes --- db/routines/util/procedures/deleteDeprecatedObjects.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/util/procedures/deleteDeprecatedObjects.sql b/db/routines/util/procedures/deleteDeprecatedObjects.sql index 729f3faf1..a251c3d98 100644 --- a/db/routines/util/procedures/deleteDeprecatedObjects.sql +++ b/db/routines/util/procedures/deleteDeprecatedObjects.sql @@ -23,7 +23,7 @@ BEGIN AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated AND v.TABLE_NAME IS NULL AND s.INDEX_NAME = 'PRIMARY' - UNION ALL + UNION SELECT CONCAT('ALTER TABLE ', c.TABLE_SCHEMA, '.', c.TABLE_NAME, ' DROP FOREIGN KEY ', kcu.CONSTRAINT_NAME, ';') FROM information_schema.`COLUMNS` c LEFT JOIN information_schema.`VIEWS` v ON v.TABLE_SCHEMA = c.TABLE_SCHEMA @@ -35,7 +35,7 @@ BEGIN AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated AND v.TABLE_NAME IS NULL AND kcu.REFERENCED_COLUMN_NAME IS NOT NULL - UNION ALL + UNION SELECT CONCAT('ALTER TABLE ', c.TABLE_SCHEMA, '.', c.TABLE_NAME, ' DROP COLUMN ', c.COLUMN_NAME, ';') FROM information_schema.`COLUMNS` c LEFT JOIN information_schema.`VIEWS` v ON v.TABLE_SCHEMA = c.TABLE_SCHEMA @@ -46,7 +46,7 @@ BEGIN WHERE c.COLUMN_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated AND v.TABLE_NAME IS NULL - UNION ALL + UNION SELECT CONCAT('DROP TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') FROM information_schema.TABLES WHERE TABLE_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci From ac0c3b79b4647a51c576cd88b288a03f9975f11e Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 15 Jul 2024 15:51:52 +0200 Subject: [PATCH 013/123] feat createLogin refs #6868 --- .../back/methods/account/handle-user.js | 111 ++++++++++++++++++ modules/account/back/models/account.js | 1 + 2 files changed, 112 insertions(+) create mode 100644 modules/account/back/methods/account/handle-user.js diff --git a/modules/account/back/methods/account/handle-user.js b/modules/account/back/methods/account/handle-user.js new file mode 100644 index 000000000..18beb1796 --- /dev/null +++ b/modules/account/back/methods/account/handle-user.js @@ -0,0 +1,111 @@ + +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('handleUser', { + description: 'Manage various aspects related to a user with the app', + accepts: [ + { + arg: 'androidId', + type: 'String', + description: 'Android id' + }, { + arg: 'versionApp', + type: 'String', + description: 'Version app' + }, { + arg: 'nameApp', + type: 'String', + description: 'Version app' + }, + + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/handleUser`, + verb: 'POST' + } + }); + + Self.loginApp = async(ctx, android_id, versionApp, nameApp, options) => { + const models = Self.app.models; + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + // const login = await models.Account.login(ctx, user, password, myOptions); + + const accessToken = ctx.req.accessToken; + let user = await models.VnUser.findById(accessToken.userId); + console.log(user.id); + + const [[{vIsAuthorized, vMessage}]] = + await Self.rawSql('CALL vn.device_checkLogin(?, ?);', + [user.id, android_id], myOptions); + + if (!vIsAuthorized) + throw new UserError('Not authorized'); + + const isUserInOperator = await models.Operator.findOne({ + where: { + workerFk: user.id + } + }, myOptions); + + if (!isUserInOperator) + await models.Operator.create({'workerFk': user.id}); + + const serialNumber = (await models.DeviceProduction.findOne({ + where: {android_id: android_id} + }, myOptions))?.serialNumber ?? ''; + + await models.DeviceLog.create({ + 'android_id': android_id, + 'userFk': user.id, + 'nameApp': nameApp, + 'versionApp': versionApp, + 'serialNumber': serialNumber + }, myOptions); + // ctx.req.accessToken = {userId}; + const getDataUser = await models.VnUser.getCurrentUserData(ctx); + + const getDataOperator = await models.Operator.findOne({ + where: {workerFk: user.id}, + fields: ['numberOfWagons', 'warehouseFk', 'itemPackingTypeFk', 'sectorFk', 'sector', + 'trainFk', 'train', 'labelerFk', 'printer'], + include: [ + { + relation: 'sector', + scope: { + fields: ['warehouseFk', 'description'], + } + }, { + relation: 'printer', + scope: { + fields: ['name'], + } + }, { + relation: 'train', + scope: { + fields: ['name'], + } + } + + ] + }, myOptions); + + const getVersion = await models.MobileAppVersionControl.getVersion(ctx, nameApp); + + const combinedResult = { + ...getDataOperator.__data, + ...getDataUser.__data, + ...getVersion, + message: vMessage, + serialNumber, + }; + return combinedResult; + }; +}; diff --git a/modules/account/back/models/account.js b/modules/account/back/models/account.js index f89d3079e..4dd1987d5 100644 --- a/modules/account/back/models/account.js +++ b/modules/account/back/models/account.js @@ -11,6 +11,7 @@ module.exports = Self => { require('../methods/account/change-password')(Self); require('../methods/account/set-password')(Self); require('../methods/account/login-app')(Self); + require('../methods/account/handle-user')(Self); Self.setUnverifiedPassword = async(id, pass, options) => { const {emailVerified} = await models.VnUser.findById(id, {fields: ['emailVerified']}, options); From ae6963c26d9f0d3a5ef4e15661f942b304d34e79 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 16 Jul 2024 08:19:13 +0200 Subject: [PATCH 014/123] feat handleUser refs #6868 --- modules/account/back/methods/account/handle-user.js | 5 +---- modules/account/back/models/account.js | 1 - 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/modules/account/back/methods/account/handle-user.js b/modules/account/back/methods/account/handle-user.js index 18beb1796..136ce4800 100644 --- a/modules/account/back/methods/account/handle-user.js +++ b/modules/account/back/methods/account/handle-user.js @@ -30,17 +30,14 @@ module.exports = Self => { } }); - Self.loginApp = async(ctx, android_id, versionApp, nameApp, options) => { + Self.handleUser = async(ctx, android_id, versionApp, nameApp, options) => { const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - // const login = await models.Account.login(ctx, user, password, myOptions); - const accessToken = ctx.req.accessToken; let user = await models.VnUser.findById(accessToken.userId); - console.log(user.id); const [[{vIsAuthorized, vMessage}]] = await Self.rawSql('CALL vn.device_checkLogin(?, ?);', diff --git a/modules/account/back/models/account.js b/modules/account/back/models/account.js index 4dd1987d5..08a5e0811 100644 --- a/modules/account/back/models/account.js +++ b/modules/account/back/models/account.js @@ -10,7 +10,6 @@ module.exports = Self => { require('../methods/account/logout')(Self); require('../methods/account/change-password')(Self); require('../methods/account/set-password')(Self); - require('../methods/account/login-app')(Self); require('../methods/account/handle-user')(Self); Self.setUnverifiedPassword = async(id, pass, options) => { From 144cf20e7148d67d6b3c40da6b6f7ad0615d2e42 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 16 Jul 2024 10:14:19 +0200 Subject: [PATCH 015/123] feat handleUser refs #6868 --- .../account/back/methods/account/login-app.js | 124 ------------------ ...{login-app.spec.js => handle-user.spec.js} | 4 +- 2 files changed, 2 insertions(+), 126 deletions(-) delete mode 100644 modules/account/back/methods/account/login-app.js rename modules/account/back/methods/account/specs/{login-app.spec.js => handle-user.spec.js} (80%) diff --git a/modules/account/back/methods/account/login-app.js b/modules/account/back/methods/account/login-app.js deleted file mode 100644 index 83c727f1a..000000000 --- a/modules/account/back/methods/account/login-app.js +++ /dev/null @@ -1,124 +0,0 @@ - -const UserError = require('vn-loopback/util/user-error'); - -module.exports = Self => { - Self.remoteMethodCtx('loginApp', { - description: 'Login a user with username and password for app', - accepts: [ - { - arg: 'user', - type: 'String', - description: 'The user name', - required: true - }, { - arg: 'password', - type: 'String', - required: true, - description: 'The password' - }, { - arg: 'androidId', - type: 'String', - description: 'Android id' - }, { - arg: 'versionApp', - type: 'String', - description: 'Version app' - }, { - arg: 'nameApp', - type: 'String', - description: 'Version app' - }, - - ], - returns: { - type: 'object', - root: true - }, - http: { - path: `/loginApp`, - verb: 'POST' - } - }); - - Self.loginApp = async(ctx, user, password, android_id, versionApp, nameApp, options) => { - const models = Self.app.models; - const myOptions = {}; - if (typeof options == 'object') - Object.assign(myOptions, options); - - const login = await models.Account.login(ctx, user, password, myOptions); - - const {id: userId} = await models.VnUser.findOne({ - where: { - name: user - } - }); - - const [[{vIsAuthorized, vMessage}]] = - await Self.rawSql('CALL vn.device_checkLogin(?, ?);', - [userId, android_id], myOptions); - - if (!vIsAuthorized) - throw new UserError('Not authorized'); - - const isUserInOperator = await models.Operator.findOne({ - where: { - workerFk: userId - } - }, myOptions); - - if (!isUserInOperator) - await models.Operator.create({'workerFk': userId}); - - const serialNumber = (await models.DeviceProduction.findOne({ - where: {android_id: android_id} - }, myOptions))?.serialNumber ?? ''; - - await models.DeviceLog.create({ - 'android_id': android_id, - 'userFk': userId, - 'nameApp': nameApp, - 'versionApp': versionApp, - 'serialNumber': serialNumber - }, myOptions); - ctx.req.accessToken = {userId}; - const getDataUser = await models.VnUser.getCurrentUserData(ctx); - - const getDataOperator = await models.Operator.findOne({ - where: {workerFk: userId}, - fields: ['numberOfWagons', 'warehouseFk', 'itemPackingTypeFk', 'sectorFk', 'sector', - 'trainFk', 'train', 'labelerFk', 'printer'], - include: [ - { - relation: 'sector', - scope: { - fields: ['warehouseFk', 'description'], - } - }, { - relation: 'printer', - scope: { - fields: ['name'], - } - }, { - relation: 'train', - scope: { - fields: ['name'], - } - } - - ] - }, myOptions); - - const getVersion = await models.MobileAppVersionControl.getVersion(ctx, nameApp); - - const combinedResult = { - ...login, - ...getDataOperator.__data, - ...getDataUser.__data, - ...getVersion, - message: vMessage, - serialNumber, - }; - return combinedResult; - }; -}; diff --git a/modules/account/back/methods/account/specs/login-app.spec.js b/modules/account/back/methods/account/specs/handle-user.spec.js similarity index 80% rename from modules/account/back/methods/account/specs/login-app.spec.js rename to modules/account/back/methods/account/specs/handle-user.spec.js index fc05cd726..621ff28ae 100644 --- a/modules/account/back/methods/account/specs/login-app.spec.js +++ b/modules/account/back/methods/account/specs/handle-user.spec.js @@ -1,9 +1,9 @@ const {models} = require('vn-loopback/server/server'); -describe('Account loginApp()', () => { +describe('Account handleUser()', () => { const ctx = {req: {accessToken: {}}}; fit('should throw an error when user/password is wrong', async() => { - const req = models.Account.loginApp(ctx, 'user', 'pass', 'androidid11234567890', 'warehouse', '10'); + const req = models.Account.handleUser(ctx, 'user', 'pass', 'androidid11234567890', 'warehouse', '10'); await expectAsync(req).toBeRejected(); }); From 7870416860504662b3a332adf90676ac69e257fb Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 16 Jul 2024 17:08:38 +0200 Subject: [PATCH 016/123] feat handleUser refs #6868 --- .../back/methods/account/handle-user.js | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/modules/account/back/methods/account/handle-user.js b/modules/account/back/methods/account/handle-user.js index 136ce4800..02b505e39 100644 --- a/modules/account/back/methods/account/handle-user.js +++ b/modules/account/back/methods/account/handle-user.js @@ -9,7 +9,13 @@ module.exports = Self => { arg: 'androidId', type: 'String', description: 'Android id' - }, { + }, + { + arg: 'deviceId', + type: 'String', + description: 'Device id' + }, + { arg: 'versionApp', type: 'String', description: 'Version app' @@ -30,9 +36,10 @@ module.exports = Self => { } }); - Self.handleUser = async(ctx, android_id, versionApp, nameApp, options) => { + Self.handleUser = async(ctx, androidId, deviceId, versionApp, nameApp, options) => { const models = Self.app.models; const myOptions = {}; + if (typeof options == 'object') Object.assign(myOptions, options); @@ -41,7 +48,7 @@ module.exports = Self => { const [[{vIsAuthorized, vMessage}]] = await Self.rawSql('CALL vn.device_checkLogin(?, ?);', - [user.id, android_id], myOptions); + [user.id, androidId], myOptions); if (!vIsAuthorized) throw new UserError('Not authorized'); @@ -55,18 +62,17 @@ module.exports = Self => { if (!isUserInOperator) await models.Operator.create({'workerFk': user.id}); - const serialNumber = (await models.DeviceProduction.findOne({ - where: {android_id: android_id} - }, myOptions))?.serialNumber ?? ''; + const whereCondition = deviceId ? {id: deviceId} : {android_id: androidId}; + const serialNumber = + (await models.DeviceProduction.findOne({where: whereCondition}, myOptions))?.serialNumber ?? ''; await models.DeviceLog.create({ - 'android_id': android_id, + 'android_id': androidId, 'userFk': user.id, 'nameApp': nameApp, 'versionApp': versionApp, 'serialNumber': serialNumber }, myOptions); - // ctx.req.accessToken = {userId}; const getDataUser = await models.VnUser.getCurrentUserData(ctx); const getDataOperator = await models.Operator.findOne({ From a82df8e2a278711b563f87be024d700d5c232149 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 16 Jul 2024 17:20:35 +0200 Subject: [PATCH 017/123] feat handleUser refs #6868 --- .../methods/account/specs/handle-user.spec.js | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/modules/account/back/methods/account/specs/handle-user.spec.js b/modules/account/back/methods/account/specs/handle-user.spec.js index 621ff28ae..486d9dc7a 100644 --- a/modules/account/back/methods/account/specs/handle-user.spec.js +++ b/modules/account/back/methods/account/specs/handle-user.spec.js @@ -1,21 +1,16 @@ const {models} = require('vn-loopback/server/server'); describe('Account handleUser()', () => { - const ctx = {req: {accessToken: {}}}; - fit('should throw an error when user/password is wrong', async() => { - const req = models.Account.handleUser(ctx, 'user', 'pass', 'androidid11234567890', 'warehouse', '10'); + const ctx = {req: {accessToken: {userId: 9}}}; - await expectAsync(req).toBeRejected(); - }); - - fit('should return data from user', async() => { - const user = 'employee'; - const password = 'nightmare'; + it('should return data from user', async() => { const androidId = 'androidid11234567890'; + const deviceId = 1; const nameApp = 'warehouse'; const versionApp = '10'; - const req = models.Account.loginApp(ctx, user, password, androidId, nameApp, versionApp); - await expectAsync(req).toBeResolved(); + const data = await models.Account.handleUser(ctx, androidId, deviceId, versionApp, nameApp); + + expect(data.numberOfWagons).toBe(2); }); }); From 930e2951b74da376cba76dba7fdab9e326bcd0ff Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 19 Jul 2024 08:27:39 +0200 Subject: [PATCH 018/123] feat: refs #6727 Added started and finished --- db/routines/util/procedures/log_clean.sql | 35 +++++++++++++------ .../11107-pinkAspidistra/00-firstScript.sql | 8 +++-- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/db/routines/util/procedures/log_clean.sql b/db/routines/util/procedures/log_clean.sql index 1401b5dd8..850b26612 100644 --- a/db/routines/util/procedures/log_clean.sql +++ b/db/routines/util/procedures/log_clean.sql @@ -13,7 +13,7 @@ BEGIN DECLARE vQueue CURSOR FOR SELECT schemaName, tableName, retentionDays - FROM logClean + FROM logCleanMultiConfig ORDER BY `order`; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -23,18 +23,31 @@ BEGIN SET vDone = FALSE; FETCH vQueue INTO vSchemaName, vTableName, vRetentionDays; - SET vSchemaName = util.quoteIdentifier(vSchemaName); - SET vTableName = util.quoteIdentifier(vTableName); - SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY; + IF vRetentionDays THEN - IF vDone THEN - LEAVE l; + UPDATE logCleanMultiConfig + SET `started` = util.VN_NOW() + WHERE schemaName = vSchemaName + AND tableName = vTableName; + + SET vSchemaName = util.quoteIdentifier(vSchemaName); + SET vTableName = util.quoteIdentifier(vTableName); + SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY; + + IF vDone THEN + LEAVE l; + END IF; + + CALL util.exec(CONCAT( + 'DELETE FROM ', vSchemaName , '.', vTableName, + " WHERE creationDate < '", vDated, "'" + )); + + UPDATE logCleanMultiConfig + SET `finished` = util.VN_NOW() + WHERE schemaName = vSchemaName + AND tableName = vTableName; END IF; - - CALL util.exec(CONCAT( - 'DELETE FROM ', vSchemaName , '.', vTableName, - " WHERE creationDate < '", vDated, "'" - )); END LOOP; CLOSE vQueue; END$$ diff --git a/db/versions/11107-pinkAspidistra/00-firstScript.sql b/db/versions/11107-pinkAspidistra/00-firstScript.sql index e702da21e..a1c4bb82f 100644 --- a/db/versions/11107-pinkAspidistra/00-firstScript.sql +++ b/db/versions/11107-pinkAspidistra/00-firstScript.sql @@ -1,12 +1,14 @@ -CREATE OR REPLACE TABLE `util`.`logClean` ( +CREATE OR REPLACE TABLE `util`.`logCleanMultiConfig` ( `schemaName` varchar(64) NOT NULL, `tableName` varchar(64) NOT NULL, - `retentionDays` int(11) NOT NULL, + `retentionDays` int(11) DEFAULT NULL, `order` int(11) DEFAULT NULL, + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, PRIMARY KEY (`schemaName`,`tableName`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -INSERT INTO `util`.`logClean` (`schemaName`, `tableName`, `retentionDays`, `order`) +INSERT INTO `util`.`logCleanMultiConfig` (`schemaName`, `tableName`, `retentionDays`, `order`) VALUES ('account', 'roleLog', 'xxx', NULL), ('account', 'userLog', 'xxx', NULL), From 3cf55556120df016e1f6980b2ffebc089b548aae Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 19 Jul 2024 08:58:51 +0200 Subject: [PATCH 019/123] feat: refs #6727 Fixes --- db/routines/util/procedures/log_clean.sql | 24 +++++------ .../11107-pinkAspidistra/00-firstScript.sql | 42 +++++++++---------- 2 files changed, 31 insertions(+), 35 deletions(-) diff --git a/db/routines/util/procedures/log_clean.sql b/db/routines/util/procedures/log_clean.sql index 850b26612..765d5dcbc 100644 --- a/db/routines/util/procedures/log_clean.sql +++ b/db/routines/util/procedures/log_clean.sql @@ -8,6 +8,7 @@ BEGIN DECLARE vSchemaName VARCHAR(65); DECLARE vTableName VARCHAR(65); DECLARE vRetentionDays INT; + DECLARE vStarted DATETIME; DECLARE vDated DATE; DECLARE vDone BOOL; @@ -23,28 +24,23 @@ BEGIN SET vDone = FALSE; FETCH vQueue INTO vSchemaName, vTableName, vRetentionDays; + IF vDone THEN + LEAVE l; + END IF; + IF vRetentionDays THEN - - UPDATE logCleanMultiConfig - SET `started` = util.VN_NOW() - WHERE schemaName = vSchemaName - AND tableName = vTableName; - - SET vSchemaName = util.quoteIdentifier(vSchemaName); - SET vTableName = util.quoteIdentifier(vTableName); + SET vStarted = util.VN_NOW(); SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY; - IF vDone THEN - LEAVE l; - END IF; - CALL util.exec(CONCAT( - 'DELETE FROM ', vSchemaName , '.', vTableName, + 'DELETE FROM ', util.quoteIdentifier(vSchemaName), + '.', util.quoteIdentifier(vTableName), " WHERE creationDate < '", vDated, "'" )); UPDATE logCleanMultiConfig - SET `finished` = util.VN_NOW() + SET `started` = vStarted, + `finished` = VN_NOW() WHERE schemaName = vSchemaName AND tableName = vTableName; END IF; diff --git a/db/versions/11107-pinkAspidistra/00-firstScript.sql b/db/versions/11107-pinkAspidistra/00-firstScript.sql index a1c4bb82f..3ed3df526 100644 --- a/db/versions/11107-pinkAspidistra/00-firstScript.sql +++ b/db/versions/11107-pinkAspidistra/00-firstScript.sql @@ -8,25 +8,25 @@ CREATE OR REPLACE TABLE `util`.`logCleanMultiConfig` ( PRIMARY KEY (`schemaName`,`tableName`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -INSERT INTO `util`.`logCleanMultiConfig` (`schemaName`, `tableName`, `retentionDays`, `order`) +INSERT INTO `util`.`logCleanMultiConfig` (`schemaName`, `tableName`) VALUES - ('account', 'roleLog', 'xxx', NULL), - ('account', 'userLog', 'xxx', NULL), - ('vn', 'entryLog', 'xxx', NULL), - ('vn', 'clientLog', 'xxx', NULL), - ('vn', 'itemLog', 'xxx', NULL), - ('vn', 'shelvingLog', 'xxx', NULL), - ('vn', 'workerLog', 'xxx', NULL), - ('vn', 'deviceProductionLog', 'xxx', NULL), - ('vn', 'zoneLog', 'xxx', NULL), - ('vn', 'rateLog', 'xxx', NULL), - ('vn', 'ticketLog', 'xxx', NULL), - ('vn', 'agencyLog', 'xxx', NULL), - ('vn', 'userLog', 'xxx', NULL), - ('vn', 'routeLog', 'xxx', NULL), - ('vn', 'claimLog', 'xxx', NULL), - ('vn', 'supplierLog', 'xxx', NULL), - ('vn', 'invoiceInLog', 'xxx', NULL), - ('vn', 'travelLog', 'xxx', NULL), - ('vn', 'packingSiteDeviceLog', 'xxx', NULL), - ('vn', 'parkingLog', 'xxx', NULL); + ('account', 'roleLog' ), + ('account', 'userLog' ), + ('vn', 'entryLog' ), + ('vn', 'clientLog' ), + ('vn', 'itemLog' ), + ('vn', 'shelvingLog' ), + ('vn', 'workerLog' ), + ('vn', 'deviceProductionLog' ), + ('vn', 'zoneLog' ), + ('vn', 'rateLog' ), + ('vn', 'ticketLog' ), + ('vn', 'agencyLog' ), + ('vn', 'userLog' ), + ('vn', 'routeLog' ), + ('vn', 'claimLog' ), + ('vn', 'supplierLog' ), + ('vn', 'invoiceInLog' ), + ('vn', 'travelLog' ), + ('vn', 'packingSiteDeviceLog' ), + ('vn', 'parkingLog' ); From 11337506298dbd92f92b452ecc0d78e6a6e9bab7 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 19 Jul 2024 09:29:15 +0200 Subject: [PATCH 020/123] feat: #6727 Requested changes --- db/routines/util/procedures/log_clean.sql | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/db/routines/util/procedures/log_clean.sql b/db/routines/util/procedures/log_clean.sql index 765d5dcbc..d490165a4 100644 --- a/db/routines/util/procedures/log_clean.sql +++ b/db/routines/util/procedures/log_clean.sql @@ -6,7 +6,9 @@ BEGIN * dejando únicamente los días de retención configurados. */ DECLARE vSchemaName VARCHAR(65); + DECLARE vSchemaNameQuoted VARCHAR(65); DECLARE vTableName VARCHAR(65); + DECLARE vTableNameQuoted VARCHAR(65); DECLARE vRetentionDays INT; DECLARE vStarted DATETIME; DECLARE vDated DATE; @@ -30,13 +32,15 @@ BEGIN IF vRetentionDays THEN SET vStarted = util.VN_NOW(); + SET vSchemaNameQuoted = util.quoteIdentifier(vSchemaName); + SET vTableNameQuoted = util.quoteIdentifier(vTableName); SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY; - CALL util.exec(CONCAT( - 'DELETE FROM ', util.quoteIdentifier(vSchemaName), - '.', util.quoteIdentifier(vTableName), + EXECUTE IMMEDIATE CONCAT( + 'DELETE FROM ', vSchemaNameQuoted, + '.', vTableNameQuoted, " WHERE creationDate < '", vDated, "'" - )); + ); UPDATE logCleanMultiConfig SET `started` = vStarted, From c94ca96226efc19101d07625ec9bf00cb2697125 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 19 Jul 2024 09:29:42 +0200 Subject: [PATCH 021/123] feat: #6727 Minor changes --- db/routines/util/procedures/log_clean.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/util/procedures/log_clean.sql b/db/routines/util/procedures/log_clean.sql index d490165a4..aeed9dc44 100644 --- a/db/routines/util/procedures/log_clean.sql +++ b/db/routines/util/procedures/log_clean.sql @@ -31,9 +31,9 @@ BEGIN END IF; IF vRetentionDays THEN - SET vStarted = util.VN_NOW(); - SET vSchemaNameQuoted = util.quoteIdentifier(vSchemaName); - SET vTableNameQuoted = util.quoteIdentifier(vTableName); + SET vStarted = VN_NOW(); + SET vSchemaNameQuoted = quoteIdentifier(vSchemaName); + SET vTableNameQuoted = quoteIdentifier(vTableName); SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY; EXECUTE IMMEDIATE CONCAT( From 2568ac4e923c0e33be1db57d53a6684323ce7188 Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 23 Jul 2024 13:24:43 +0200 Subject: [PATCH 022/123] feat: refs #6346 new wagon type section --- db/dump/fixtures.before.sql | 13 ++-- .../11088-bronzeAspidistra/00-firstScript.sql | 26 ++++++++ .../back/methods/wagonType/createWagonType.js | 57 ----------------- .../back/methods/wagonType/deleteWagonType.js | 43 ------------- .../back/methods/wagonType/editWagonType.js | 64 ------------------- .../wagonType/specs/crudWagonType.spec.js | 48 +------------- modules/wagon/back/models/wagon-config.json | 13 ++++ modules/wagon/back/models/wagon-type-tray.js | 16 +++++ .../wagon/back/models/wagon-type-tray.json | 8 +-- modules/wagon/back/models/wagon-type.js | 15 ++++- 10 files changed, 81 insertions(+), 222 deletions(-) create mode 100644 db/versions/11088-bronzeAspidistra/00-firstScript.sql delete mode 100644 modules/wagon/back/methods/wagonType/createWagonType.js delete mode 100644 modules/wagon/back/methods/wagonType/deleteWagonType.js delete mode 100644 modules/wagon/back/methods/wagonType/editWagonType.js create mode 100644 modules/wagon/back/models/wagon-type-tray.js diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 30f1ceb5e..3b799a610 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3024,9 +3024,6 @@ INSERT INTO `vn`.`workerTimeControlMail` (`id`, `workerFk`, `year`, `week`, `sta (3, 9, 2000, 51, 'CONFIRMED', util.VN_NOW(), 1, NULL), (4, 9, 2001, 1, 'SENDED', util.VN_NOW(), 1, NULL); -INSERT INTO `vn`.`wagonConfig` (`id`, `width`, `height`, `maxWagonHeight`, `minHeightBetweenTrays`, `maxTrays`) - VALUES - (1, 1350, 1900, 200, 50, 6); INSERT INTO `vn`.`wagonTypeColor` (`id`, `name`, `rgb`) VALUES @@ -3035,15 +3032,19 @@ INSERT INTO `vn`.`wagonTypeColor` (`id`, `name`, `rgb`) (3, 'green', '#00ff00'), (4, 'blue', '#0000ff'); +INSERT INTO `vn`.`wagonConfig` (`id`, `width`, `height`, `maxWagonHeight`, `minHeightBetweenTrays`, `maxTrays`, `defaultTrayColorFk`) + VALUES + (1, 1350, 1900, 200, 50, 6, 1); + INSERT INTO `vn`.`wagonType` (`id`, `name`, `divisible`) VALUES (1, 'Wagon Type #1', 1); -INSERT INTO `vn`.`wagonTypeTray` (`id`, `typeFk`, `height`, `colorFk`) +INSERT INTO `vn`.`wagonTypeTray` (`id`, `wagonTypeFk`, `height`, `wagonTypeColorFk`) VALUES - (1, 1, 100, 1), + (1, 1, 0, 1), (2, 1, 50, 2), - (3, 1, 0, 3); + (3, 1, 100, 3); INSERT INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `courtesyTime`, `renewInterval`) VALUES diff --git a/db/versions/11088-bronzeAspidistra/00-firstScript.sql b/db/versions/11088-bronzeAspidistra/00-firstScript.sql new file mode 100644 index 000000000..2cc4e715e --- /dev/null +++ b/db/versions/11088-bronzeAspidistra/00-firstScript.sql @@ -0,0 +1,26 @@ +-- Place your SQL code here +DROP TABLE IF EXISTS vn.wagonTypeTray; + +CREATE TABLE vn.wagonTypeTray ( + id INT UNSIGNED auto_increment NULL, + wagonTypeFk int(11) unsigned NULL, + height INT UNSIGNED NULL, + wagonTypeColorFk int(11) unsigned NULL, + CONSTRAINT wagonTypeTray_pk PRIMARY KEY (id), + CONSTRAINT wagonTypeTray_wagonType_FK FOREIGN KEY (wagonTypeFk) REFERENCES vn.wagonType(id), + CONSTRAINT wagonTypeTray_wagonTypeColor_FK FOREIGN KEY (wagonTypeColorFk) REFERENCES vn.wagonTypeColor(id) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; + +ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultHeight INT UNSIGNED DEFAULT 0 NULL COMMENT 'Default height in cm for a base tray'; +ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultTrayColorFk int(11) unsigned NULL COMMENT 'Default color for a base tray'; +ALTER TABLE vn.wagonConfig ADD CONSTRAINT wagonConfig_wagonTypeColor_FK FOREIGN KEY (defaultTrayColorFk) REFERENCES vn.wagonTypeColor(id); + +ALTER TABLE vn.wagonTypeTray DROP FOREIGN KEY wagonTypeTray_wagonType_FK; +ALTER TABLE vn.wagonTypeTray ADD CONSTRAINT wagonTypeTray_wagonType_FK FOREIGN KEY (wagonTypeFk) REFERENCES vn.wagonType(id) ON DELETE CASCADE ON UPDATE RESTRICT; + + + +-- insertar datos por defecto \ No newline at end of file diff --git a/modules/wagon/back/methods/wagonType/createWagonType.js b/modules/wagon/back/methods/wagonType/createWagonType.js deleted file mode 100644 index fed915b28..000000000 --- a/modules/wagon/back/methods/wagonType/createWagonType.js +++ /dev/null @@ -1,57 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('createWagonType', { - description: 'Creates a new wagon type', - accessType: 'WRITE', - accepts: [ - { - arg: 'name', - type: 'String', - required: true - }, - { - arg: 'divisible', - type: 'boolean', - required: true - }, { - arg: 'trays', - type: 'any', - required: true - } - ], - http: { - path: `/createWagonType`, - verb: 'PATCH' - } - }); - - Self.createWagonType = async(ctx, options) => { - const args = ctx.args; - const models = Self.app.models; - const myOptions = {}; - let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const newWagonType = await models.WagonType.create({name: args.name, divisible: args.divisible}, myOptions); - args.trays.forEach(async tray => { - await models.WagonTypeTray.create({ - typeFk: newWagonType.id, - height: tray.position, - colorFk: tray.color.id - }, myOptions); - }); - - if (tx) await tx.commit(); - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/wagon/back/methods/wagonType/deleteWagonType.js b/modules/wagon/back/methods/wagonType/deleteWagonType.js deleted file mode 100644 index 46b65e32f..000000000 --- a/modules/wagon/back/methods/wagonType/deleteWagonType.js +++ /dev/null @@ -1,43 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('deleteWagonType', { - description: 'Deletes a wagon type', - accessType: 'WRITE', - accepts: [ - { - arg: 'id', - type: 'Number', - required: true - } - ], - http: { - path: `/deleteWagonType`, - verb: 'DELETE' - } - }); - - Self.deleteWagonType = async(ctx, options) => { - const args = ctx.args; - const models = Self.app.models; - const myOptions = {}; - let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - await models.Wagon.destroyAll({typeFk: args.id}, myOptions); - await models.WagonTypeTray.destroyAll({typeFk: args.id}, myOptions); - await models.WagonType.destroyAll({id: args.id}, myOptions); - - if (tx) await tx.commit(); - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/wagon/back/methods/wagonType/editWagonType.js b/modules/wagon/back/methods/wagonType/editWagonType.js deleted file mode 100644 index bd5ad1f16..000000000 --- a/modules/wagon/back/methods/wagonType/editWagonType.js +++ /dev/null @@ -1,64 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('editWagonType', { - description: 'Edits a new wagon type', - accessType: 'WRITE', - accepts: [ - { - arg: 'id', - type: 'String', - required: true - }, - { - arg: 'name', - type: 'String', - required: true - }, - { - arg: 'divisible', - type: 'boolean', - required: true - }, { - arg: 'trays', - type: 'any', - required: true - } - ], - http: { - path: `/editWagonType`, - verb: 'PATCH' - } - }); - - Self.editWagonType = async(ctx, options) => { - const args = ctx.args; - const models = Self.app.models; - const myOptions = {}; - let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const wagonType = await models.WagonType.findById(args.id, null, myOptions); - wagonType.updateAttributes({name: args.name, divisible: args.divisible}, myOptions); - models.WagonTypeTray.destroyAll({typeFk: args.id}, myOptions); - args.trays.forEach(async tray => { - await models.WagonTypeTray.create({ - typeFk: args.id, - height: tray.position, - colorFk: tray.color.id - }, myOptions); - }); - - if (tx) await tx.commit(); - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/wagon/back/methods/wagonType/specs/crudWagonType.spec.js b/modules/wagon/back/methods/wagonType/specs/crudWagonType.spec.js index 92ac61060..96f0980f9 100644 --- a/modules/wagon/back/methods/wagonType/specs/crudWagonType.spec.js +++ b/modules/wagon/back/methods/wagonType/specs/crudWagonType.spec.js @@ -1,58 +1,16 @@ const models = require('vn-loopback/server/server').models; describe('WagonType crudWagonType()', () => { - const ctx = { - args: { - name: 'Mock wagon type', - divisible: true, - trays: [{position: 0, color: {id: 1}}, - {position: 50, color: {id: 2}}, - {position: 100, color: {id: 3}}] - } - }; - it(`should create, edit and delete a new wagon type and its trays`, async() => { const tx = await models.WagonType.beginTransaction({}); try { const options = {transaction: tx}; - // create - await models.WagonType.createWagonType(ctx, options); + const wagonType = await models.WagonType.create({name: 'Mock wagon type'}, options); + const newWagonTrays = await models.WagonTypeTray.findOne({where: {typeFk: wagonType.id}}, options); - const newWagonType = await models.WagonType.findOne({where: {name: ctx.args.name}}, options); - const newWagonTrays = await models.WagonTypeTray.find({where: {typeFk: newWagonType.id}}, options); - - expect(newWagonType).not.toEqual(null); - expect(newWagonType.name).toEqual(ctx.args.name); - expect(newWagonType.divisible).toEqual(ctx.args.divisible); - expect(newWagonTrays.length).toEqual(ctx.args.trays.length); - - ctx.args = { - id: newWagonType.id, - name: 'Edited wagon type', - divisible: false, - trays: [{position: 0, color: {id: 1}}] - }; - - // edit - await models.WagonType.editWagonType(ctx, options); - - const editedWagonType = await models.WagonType.findById(newWagonType.id, null, options); - const editedWagonTrays = await models.WagonTypeTray.find({where: {typeFk: newWagonType.id}}, options); - - expect(editedWagonType.name).toEqual(ctx.args.name); - expect(editedWagonType.divisible).toEqual(ctx.args.divisible); - expect(editedWagonTrays.length).toEqual(ctx.args.trays.length); - - // delete - await models.WagonType.deleteWagonType(ctx, options); - - const deletedWagonType = await models.WagonType.findById(newWagonType.id, null, options); - const deletedWagonTrays = await models.WagonTypeTray.find({where: {typeFk: newWagonType.id}}, options); - - expect(deletedWagonType).toEqual(null); - expect(deletedWagonTrays).toEqual([]); + expect(newWagonTrays).toBeDefined(); await tx.rollback(); } catch (e) { diff --git a/modules/wagon/back/models/wagon-config.json b/modules/wagon/back/models/wagon-config.json index 3d96e2864..d76558564 100644 --- a/modules/wagon/back/models/wagon-config.json +++ b/modules/wagon/back/models/wagon-config.json @@ -25,6 +25,19 @@ }, "maxTrays": { "type": "number" + }, + "defaultHeight": { + "type": "number" + }, + "defaultTrayColorFk": { + "type": "number" } + }, + "relations": { + "WagonTypeColor": { + "type": "belongsTo", + "model": "WagonTypeColor", + "foreignKey": "defaultTrayColorFk" + } } } diff --git a/modules/wagon/back/models/wagon-type-tray.js b/modules/wagon/back/models/wagon-type-tray.js new file mode 100644 index 000000000..e32938743 --- /dev/null +++ b/modules/wagon/back/models/wagon-type-tray.js @@ -0,0 +1,16 @@ +// module.exports = Self => { +// Self.observe('before save', async ctx => { +// if (ctx.isNewInstance) { +// const models = Self.app.models; +// const config = await models.WagonConfig.findOne(); + +// await models.WagonTypeTray.create({ +// wagonTypeFk: config.wagonTypeFk, +// height: config.height, +// wagonTypeColorFk: config.wagonTypeColorFk +// }, ctx.options); +// } +// if (ctx.instance < config.minHeightBetweenTrays) +// throw new Error('Height must be greater than ' + config.minHeightBetweenTrays); +// }); +// }; diff --git a/modules/wagon/back/models/wagon-type-tray.json b/modules/wagon/back/models/wagon-type-tray.json index b61510bcf..61b32694d 100644 --- a/modules/wagon/back/models/wagon-type-tray.json +++ b/modules/wagon/back/models/wagon-type-tray.json @@ -11,13 +11,13 @@ "id": true, "type": "number" }, - "typeFk": { + "wagonTypeFk": { "type": "number" }, "height": { "type": "number" }, - "colorFk": { + "wagonTypeColorFk": { "type": "number" } }, @@ -25,12 +25,12 @@ "type": { "type": "belongsTo", "model": "WagonType", - "foreignKey": "typeFk" + "foreignKey": "wagonTypeFk" }, "color": { "type": "belongsTo", "model": "WagonTypeColor", - "foreignKey": "colorFk" + "foreignKey": "wagonTypeColorFk" } } } diff --git a/modules/wagon/back/models/wagon-type.js b/modules/wagon/back/models/wagon-type.js index bebf7a9d9..0610adcb4 100644 --- a/modules/wagon/back/models/wagon-type.js +++ b/modules/wagon/back/models/wagon-type.js @@ -1,5 +1,14 @@ module.exports = Self => { - require('../methods/wagonType/createWagonType')(Self); - require('../methods/wagonType/editWagonType')(Self); - require('../methods/wagonType/deleteWagonType')(Self); + Self.observe('after save', async ctx => { + if (ctx.isNewInstance) { + const models = Self.app.models; + const config = await models.WagonConfig.findOne(); + + await models.WagonTypeTray.create({ + wagonTypeFk: ctx.instance.id, + height: config.defaultHeight, + wagonTypeColorFk: config.defaultTrayColorFk + }, ctx.options); + } + }); }; From 57f6c6d9a1b4f5214c3bb1b3d5f612f335d137e2 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 31 Jul 2024 10:43:55 +0200 Subject: [PATCH 023/123] chore: refs #7663 WIP setWeight --- .../11178-yellowCamellia/00-aclSetWeight.sql | 9 +++ loopback/locale/es.json | 3 +- .../ticket/back/methods/ticket/setWeight.js | 75 +++++++++++++++++++ modules/ticket/back/models/ticket-methods.js | 1 + modules/ticket/front/summary/locale/es.yml | 3 +- 5 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 db/versions/11178-yellowCamellia/00-aclSetWeight.sql create mode 100644 modules/ticket/back/methods/ticket/setWeight.js diff --git a/db/versions/11178-yellowCamellia/00-aclSetWeight.sql b/db/versions/11178-yellowCamellia/00-aclSetWeight.sql new file mode 100644 index 000000000..d70287738 --- /dev/null +++ b/db/versions/11178-yellowCamellia/00-aclSetWeight.sql @@ -0,0 +1,9 @@ +-- Place your SQL code here +INSERT INTO salix.ACL + SET model = 'Ticket', + property = 'setWeight', + accessType = 'WRITE', + permission = 'ALLOW', + principalType = 'ROLE', + principalId = 'salesPerson'; + \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index acc3d69f6..eb7a2aaf2 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -368,5 +368,6 @@ "Payment method is required": "El método de pago es obligatorio", "Cannot send mail": "Não é possível enviar o email", "CONSTRAINT `supplierAccountTooShort` failed for `vn`.`supplier`": "La cuenta debe tener exactamente 10 dígitos", - "The sale not exists in the item shelving": "La venta no existe en la estantería del artículo" + "The sale not exists in the item shelving": "La venta no existe en la estantería del artículo", + "Weight already set": "El peso ya está establecido" } \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/setWeight.js b/modules/ticket/back/methods/ticket/setWeight.js new file mode 100644 index 000000000..f2a65b1d6 --- /dev/null +++ b/modules/ticket/back/methods/ticket/setWeight.js @@ -0,0 +1,75 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('setWeight', { + description: 'Sets weight of a ticket', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The ticket id', + http: {source: 'path'} + }, { + arg: 'weight', + type: 'number', + required: true, + description: 'The weight value', + }], + http: { + path: `/:id/setWeight`, + verb: 'POST' + } + }); + + Self.setWeight = async(ctx, ticketId, weight, invoiceable, options) => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + const myOptions = {userId}; + let tx; + + if (typeof options == 'object') Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + if (ticket.weight) throw new UserError('Weight already set'); + + const canEdit = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'updateAttributes'); + const ticket = await Self.findById(ticketId, null, myOptions); + const client = await models.Client.findById(ticket.clientFk, { + include: {relation: 'salesPersonUser'}}, + myOptions); + + if (!canEdit) { + const salesPersonUser = client.salesPersonUser(); + const workerDepartments = await models.WorkerDepartment.find({ + include: {relation: 'department'}, + where: {workerFk: {inq: [userId, salesPersonUser.id]}} + }, myOptions); + + if (workerDepartments[0].departmentFk != workerDepartments[1].departmentFk) + throw new UserError('You don\'t have enough privileges'); + } + + await ticket.updateAttribute('weight', weight, myOptions); + + const packedState = await models.State.findOne({where: {code: 'PACKED'}}, myOptions); + const ticketState = await models.TicketState.findOne({where: {ticketFk: ticketId}}, myOptions); + + const [{taxArea}] = await Self.rawSql('SELECT clientTaxArea(?,?) taxArea', + [ticket.clientFk, ticket.warehouseFk], myOptions); + + if (ticketState.alertLevel >= packedState.alertLevel && taxArea == 'WORLD' && client.hasDailyInvoice) + await Self.invoiceTicketsAndPdf(ctx, [ticketId], null, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/ticket/back/models/ticket-methods.js b/modules/ticket/back/models/ticket-methods.js index 5582dde5c..457454627 100644 --- a/modules/ticket/back/models/ticket-methods.js +++ b/modules/ticket/back/models/ticket-methods.js @@ -47,4 +47,5 @@ module.exports = function(Self) { require('../methods/ticket/docuwareDownload')(Self); require('../methods/ticket/myLastModified')(Self); require('../methods/ticket/clone')(Self); + require('../methods/ticket/setWeight')(Self); }; diff --git a/modules/ticket/front/summary/locale/es.yml b/modules/ticket/front/summary/locale/es.yml index d1e6dba58..9de7ccbf4 100644 --- a/modules/ticket/front/summary/locale/es.yml +++ b/modules/ticket/front/summary/locale/es.yml @@ -3,4 +3,5 @@ Address mobile: Móv. consignatario Client phone: Tel. cliente Client mobile: Móv. cliente Go to the ticket: Ir al ticket -Change state: Cambiar estado \ No newline at end of file +Change state: Cambiar estado +Weight: Peso \ No newline at end of file From 961fafb33e4c3e204e8e5a43ceebf8a0ccf41ec8 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 5 Aug 2024 15:32:36 +0200 Subject: [PATCH 024/123] feat: refs #7404 stockBought add and calculate --- back/models/buyer.json | 3 + db/dump/fixtures.before.sql | 17 ++++++ .../vn/procedures/stockBought_calculate.sql | 54 ++++++++++++++++++ db/routines/vn/views/buyer.sql | 4 +- .../11115-turquoiseRose/00-firstScript.sql | 30 ++++++++++ loopback/locale/en.json | 8 ++- loopback/locale/es.json | 5 +- .../account/back/models/mail-alias-account.js | 1 + modules/entry/back/methods/entry/filter.js | 1 - .../methods/stock-bought/getStockBought.js | 52 +++++++++++++++++ .../stock-bought/getStockBoughtDetail.js | 56 +++++++++++++++++++ modules/entry/back/model-config.json | 3 + modules/entry/back/models/stock-bought.js | 10 ++++ modules/entry/back/models/stock-bought.json | 34 +++++++++++ 14 files changed, 272 insertions(+), 6 deletions(-) create mode 100644 db/routines/vn/procedures/stockBought_calculate.sql create mode 100644 db/versions/11115-turquoiseRose/00-firstScript.sql create mode 100644 modules/entry/back/methods/stock-bought/getStockBought.js create mode 100644 modules/entry/back/methods/stock-bought/getStockBoughtDetail.js create mode 100644 modules/entry/back/models/stock-bought.js create mode 100644 modules/entry/back/models/stock-bought.json diff --git a/back/models/buyer.json b/back/models/buyer.json index a17d3b538..a1297eda3 100644 --- a/back/models/buyer.json +++ b/back/models/buyer.json @@ -15,6 +15,9 @@ "nickname": { "type": "string", "required": true + }, + "display": { + "type": "boolean" } }, "acls": [ diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index f800a1da1..7f3ede501 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3882,3 +3882,20 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli (1, '2001-05-17', 1, 5), (1, '2001-05-18', 1, 5); +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.warehouse (id,name,isFeedStock,delay,hasAvailable,isForTicket,countryFk,labelZone,hasComission,isInventory,isComparative,valuatedInventory,isManaged,hasConfectionTeam,hasStowaway,hasDms,isBuyerToBeEmailed,hasUbications,hasProduction,hasMachine,isLogiflora,isBionic,isHalt,isOrigin,isDestiny) + VALUES (6,'Warehouse six',0,0.004,1,0,1,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,0,0); + +INSERT INTO vn.travel (id,shipped,landed,warehouseInFk,warehouseOutFk,agencyFk__,`ref`,isDelivered,isReceived,m3,kg,cargoSupplierFk,totalEntries,agencyModeFk,editorFk,awbFk) + VALUES (11,'2001-01-01','2001-01-02',6,3,0,'eleventh travel',0,0,50.00,500,2,0,1,100,4); + +INSERT INTO vn.entry (id,supplierFk,invoiceNumber,isBooked,isExcludedFromAvailable,isConfirmed,isOrdered,isRaid,commission,created,evaNotes,travelFk,currencyFk,companyFk,isBlocked__,reference,editorFk,locked) + VALUES (9,69,'IN2009',0,1,0,0,1,0.0,'2000-12-01 00:00:00.000','',11,1,442,0,'Movement 9',100,'2024-07-30 08:13:49.000'); + +INSERT INTO vn.buy (entryFk,itemFk,quantity,dispatched,buyingValue,freightValue,isIgnored,stickers,packing,`grouping`,groupingMode,comissionValue,packageValue,packagingFk,price1,price2,price3,minPrice,printedStickers,workerFk,isChecked,isPickedOff,created,`__cm2`,weight,itemOriginalFk,editorFk,buyerFk) + VALUES (9,1,5000,0,50.0000,1.500,0,1,1,1,'packing',0.000,1.500,'4',0.00,99.60,99.40,0.00,0,0,1,0,'2024-07-30 08:13:51.000',0,1.00,1,100,35); diff --git a/db/routines/vn/procedures/stockBought_calculate.sql b/db/routines/vn/procedures/stockBought_calculate.sql new file mode 100644 index 000000000..54ac78d8e --- /dev/null +++ b/db/routines/vn/procedures/stockBought_calculate.sql @@ -0,0 +1,54 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBought_calculate`() +BEGIN +/** + * Inserts the purchase volume per buyer + * into stockBought according to the date. + * + * @param vDated Purchase date + */ + DECLARE vDated DATE; + SET vDated = util.VN_CURDATE(); + + CREATE OR REPLACE TEMPORARY TABLE tStockBought + SELECT workerFk, reserve + FROM stockBought + WHERE dated = vDated + AND reserve; + + DELETE FROM stockBought WHERE dated = vDated; + + INSERT INTO stockBought (workerFk, bought, dated) + SELECT it.workerFk, + ROUND(SUM( + (ac.conversionCoefficient * + (b.quantity / b.packing) * + buy_getVolume(b.id) + ) / (vc.trolleyM3 * 1000000) + ), 1), + vDated + FROM entry e + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + JOIN buy b ON b.entryFk = e.id + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN auctionConfig ac + JOIN volumeConfig vc + WHERE t.shipped = vDated + AND t.warehouseInFk = ac.warehouseFk + GROUP BY it.workerFk; + + UPDATE stockBought s + JOIN tStockBought 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 + WHERE ts.workerFk NOT IN (SELECT workerFk FROM stockBought WHERE dated = vDated); + + DROP TEMPORARY TABLE tStockBought; +END$$ +DELIMITER ; diff --git a/db/routines/vn/views/buyer.sql b/db/routines/vn/views/buyer.sql index 7114c50bc..455c68770 100644 --- a/db/routines/vn/views/buyer.sql +++ b/db/routines/vn/views/buyer.sql @@ -2,10 +2,12 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn`.`buyer` AS SELECT DISTINCT `u`.`id` AS `userFk`, - `u`.`nickname` AS `nickname` + `u`.`nickname` AS `nickname`, + `ic`.`display` AS `display` FROM ( `account`.`user` `u` JOIN `vn`.`itemType` `it` ON(`it`.`workerFk` = `u`.`id`) + JOIN `vn`.`itemCategory` `ic` ON(`ic`.`id` = `it`.`categoryFk`) ) WHERE `u`.`active` <> 0 ORDER BY `u`.`nickname` diff --git a/db/versions/11115-turquoiseRose/00-firstScript.sql b/db/versions/11115-turquoiseRose/00-firstScript.sql new file mode 100644 index 000000000..3982936fc --- /dev/null +++ b/db/versions/11115-turquoiseRose/00-firstScript.sql @@ -0,0 +1,30 @@ +-- Place your SQL code here +-- vn.stockBought definition + +CREATE TABLE IF NOT EXISTS vn.stockBought ( + id INT UNSIGNED auto_increment NOT NULL, + workerFk int(10) unsigned NOT NULL, + bought decimal(10,2) NOT NULL COMMENT 'purchase volume in m3 for the day', + reserve decimal(10,2) NULL COMMENT 'reserved volume in m3 for the day', + dated DATE NOT NULL DEFAULT current_timestamp(), + CONSTRAINT stockBought_pk PRIMARY KEY (id), + CONSTRAINT stockBought_unique UNIQUE KEY (workerFk,dated), + CONSTRAINT stockBought_worker_FK FOREIGN KEY (workerFk) REFERENCES vn.worker(id) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; + + +INSERT IGNORE vn.stockBought (workerFk, bought, reserve, dated) + SELECT userFk, SUM(buyed), SUM(IFNULL(reserved,0)), dated + FROM vn.stockBuyed + WHERE userFk IS NOT NULL + AND buyed IS NOT NULL + GROUP BY userFk, dated; + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('StockBought','*','READ','ALLOW','ROLE','buyer'), + ('StockBought','*','WRITE','ALLOW','ROLE','buyer'), + ('Buyer','*','READ','ALLOW','ROLE','buyer'); + diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 1e5733442..79f7eecc5 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -233,5 +233,9 @@ "It has been invoiced but the PDF could not be generated": "It has been invoiced but the PDF could not be generated", "It has been invoiced but the PDF of refund not be generated": "It has been invoiced but the PDF of refund not be generated", "Cannot add holidays on this day": "Cannot add holidays on this day", - "Cannot send mail": "Cannot send mail" -} + "Cannot send mail": "Cannot send mail", + "Payment method is required": "Payment method is required", + "This worker already exists": "This worker already exists", + "This personal mail already exists": "This personal mail already exists", + "This buyer has already made a reservation for this date": "This buyer has already made a reservation for this date" +} \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 5b5928993..a11fb6f7c 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -366,5 +366,6 @@ "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", "Payment method is required": "El método de pago es obligatorio", - "Cannot send mail": "Não é possível enviar o email" -} + "Cannot send mail": "Não é possível enviar o email", + "This buyer has already made a reservation for this date": "This buyer has already made a reservation for this date" +} \ No newline at end of file diff --git a/modules/account/back/models/mail-alias-account.js b/modules/account/back/models/mail-alias-account.js index 61ca344e9..0eee6a123 100644 --- a/modules/account/back/models/mail-alias-account.js +++ b/modules/account/back/models/mail-alias-account.js @@ -1,5 +1,6 @@ const ForbiddenError = require('vn-loopback/util/forbiddenError'); +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.rewriteDbError(function(err) { diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 1cd12b737..a8a9d4de1 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/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/entry/back/methods/stock-bought/getStockBought.js b/modules/entry/back/methods/stock-bought/getStockBought.js new file mode 100644 index 000000000..da194ed80 --- /dev/null +++ b/modules/entry/back/methods/stock-bought/getStockBought.js @@ -0,0 +1,52 @@ +module.exports = Self => { + Self.remoteMethod('getStockBought', { + description: 'Returns the stock bought for a given date', + accessType: 'READ', + accepts: [{ + arg: 'dated', + type: 'date', + description: 'The date to filter', + } + ], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getStockBought`, + verb: 'GET' + } + }); + + Self.getStockBought = async(dated = Date.vnNew()) => { + const models = Self.app.models; + const today = Date.vnNew(); + dated.setHours(0, 0, 0, 0); + today.setHours(0, 0, 0, 0); + + if (dated.getTime() === today.getTime()) + await models.StockBought.rawSql(`CALL vn.stockBought_calculate()`); + + return models.StockBought.find( + { + where: { + dated: dated + }, + include: [ + { + relation: 'worker', + scope: { + include: [ + { + relation: 'user', + scope: { + fields: ['id', 'name'] + } + } + ] + } + } + ] + }); + }; +}; diff --git a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js new file mode 100644 index 000000000..471d5c9c4 --- /dev/null +++ b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js @@ -0,0 +1,56 @@ +module.exports = Self => { + Self.remoteMethod('getStockBoughtDetail', { + description: 'Returns the detail of stock bought for a given date and a worker', + accessType: 'READ', + accepts: [{ + arg: 'workerFk', + type: 'number', + description: 'The worker to filter', + required: true, + }, { + arg: 'dated', + type: 'string', + description: 'The date to filter', + } + ], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getStockBoughtDetail`, + verb: 'GET' + } + }); + + Self.getStockBoughtDetail = async(workerFk, dated = Date.vnNew()) => { + console.log('dated: ', new Date(dated)); + console.log('new Date(dated).setHours(0, 0, 0, 0): ', new Date(dated).setHours(0, 0, 0, 0)); + return Self.rawSql( + `SELECT e.id entryFk, + i.id itemFk, + i.longName itemName, + b.quantity, + ROUND((ac.conversionCoefficient * + (b.quantity / b.packing) * + buy_getVolume(b.id) + ) / (vc.trolleyM3 * 1000000), + 2 + ) volume, + b.packagingFk, + b.packing + FROM entry e + JOIN travel t ON t.id = e.travelFk + JOIN buy b ON b.entryFk = e.id + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN worker w ON w.id = it.workerFk + JOIN auctionConfig ac + JOIN volumeConfig vc + WHERE t.warehouseInFk = ac.warehouseFk + AND it.workerFk = ? + AND t.shipped = ?`, + [workerFk, new Date(dated)] + ); + }; +}; diff --git a/modules/entry/back/model-config.json b/modules/entry/back/model-config.json index dc7fd86be..85f5e8285 100644 --- a/modules/entry/back/model-config.json +++ b/modules/entry/back/model-config.json @@ -25,5 +25,8 @@ }, "EntryType": { "dataSource": "vn" + }, + "StockBought": { + "dataSource": "vn" } } \ No newline at end of file diff --git a/modules/entry/back/models/stock-bought.js b/modules/entry/back/models/stock-bought.js new file mode 100644 index 000000000..ae52e7654 --- /dev/null +++ b/modules/entry/back/models/stock-bought.js @@ -0,0 +1,10 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + require('../methods/stock-bought/getStockBought')(Self); + require('../methods/stock-bought/getStockBoughtDetail')(Self); + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`This buyer has already made a reservation for this date`); + return err; + }); +}; diff --git a/modules/entry/back/models/stock-bought.json b/modules/entry/back/models/stock-bought.json new file mode 100644 index 000000000..18c9f0347 --- /dev/null +++ b/modules/entry/back/models/stock-bought.json @@ -0,0 +1,34 @@ +{ + "name": "StockBought", + "base": "VnModel", + "options": { + "mysql": { + "table": "stockBought" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "workerFk": { + "type": "number" + }, + "bought": { + "type": "number" + }, + "reserve": { + "type": "number" + }, + "dated": { + "type": "date" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + } + } +} From 47543d5760cdfcb848eaaacb5b4f094b687d8c2e Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 5 Aug 2024 15:34:01 +0200 Subject: [PATCH 025/123] refactor: refs #7404 remove console.log --- modules/entry/back/methods/stock-bought/getStockBoughtDetail.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js index 471d5c9c4..0657fcb9a 100644 --- a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js +++ b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js @@ -24,8 +24,6 @@ module.exports = Self => { }); Self.getStockBoughtDetail = async(workerFk, dated = Date.vnNew()) => { - console.log('dated: ', new Date(dated)); - console.log('new Date(dated).setHours(0, 0, 0, 0): ', new Date(dated).setHours(0, 0, 0, 0)); return Self.rawSql( `SELECT e.id entryFk, i.id itemFk, From 6d25cb3c8c1e4a89ecbe133759519f67578cdda7 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 5 Aug 2024 15:35:48 +0200 Subject: [PATCH 026/123] fix: refs #7404 fix translation --- loopback/locale/es.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index a11fb6f7c..4c7df3e0c 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -366,6 +366,6 @@ "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", "Payment method is required": "El método de pago es obligatorio", - "Cannot send mail": "Não é possível enviar o email", + "Cannot send mail": "No se ha podido enviar el correo", "This buyer has already made a reservation for this date": "This buyer has already made a reservation for this date" } \ No newline at end of file From 0e7272f911d2c2214ae16e0a8d852f95092eb336 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 5 Aug 2024 15:42:21 +0200 Subject: [PATCH 027/123] fix: refs #7404 fix error message --- modules/entry/back/methods/entry/print.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/print.js b/modules/entry/back/methods/entry/print.js index c155c3d8b..626e212b7 100644 --- a/modules/entry/back/methods/entry/print.js +++ b/modules/entry/back/methods/entry/print.js @@ -52,7 +52,7 @@ module.exports = Self => { await merger.add(new Uint8Array(pdfBuffer[0])); } - if (!merger._doc) throw new UserError('The entry not have stickers'); + if (!merger._doc) throw new UserError('The entry does not have stickers'); return [await merger.saveAsBuffer(), 'application/pdf', `filename="entry-${id}.pdf"`]; }; }; From 323ab638d79abbc5228d9c152305bf8fe6043af8 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 5 Aug 2024 15:55:44 +0200 Subject: [PATCH 028/123] fix: refs #7404 fix fixtures and back test --- db/dump/fixtures.before.sql | 51 ++++++++----------- .../back/methods/entry/specs/filter.spec.js | 4 +- .../travel/specs/extraCommunityFilter.spec.js | 4 +- .../back/methods/travel/specs/filter.spec.js | 4 +- 4 files changed, 26 insertions(+), 37 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index a0f2537d1..69d838998 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3929,44 +3929,33 @@ INSERT INTO vn.travel (id,shipped,landed,warehouseInFk,warehouseOutFk,agencyFk__ VALUES (11,'2001-01-01','2001-01-02',6,3,0,'eleventh travel',0,0,50.00,500,2,0,1,100,4); INSERT INTO vn.entry (id,supplierFk,invoiceNumber,isBooked,isExcludedFromAvailable,isConfirmed,isOrdered,isRaid,commission,created,evaNotes,travelFk,currencyFk,companyFk,isBlocked__,reference,editorFk,locked) - VALUES (9,69,'IN2009',0,1,0,0,1,0.0,'2000-12-01 00:00:00.000','',11,1,442,0,'Movement 9',100,'2024-07-30 08:13:49.000'); + VALUES (99,69,'IN2009',0,1,0,0,1,0.0,'2000-12-01 00:00:00.000','',11,1,442,0,'Movement 9',100,'2024-07-30 08:13:49.000'); INSERT INTO vn.buy (entryFk,itemFk,quantity,dispatched,buyingValue,freightValue,isIgnored,stickers,packing,`grouping`,groupingMode,comissionValue,packageValue,packagingFk,price1,price2,price3,minPrice,printedStickers,workerFk,isChecked,isPickedOff,created,`__cm2`,weight,itemOriginalFk,editorFk,buyerFk) - VALUES (9,1,5000,0,50.0000,1.500,0,1,1,1,'packing',0.000,1.500,'4',0.00,99.60,99.40,0.00,0,0,1,0,'2024-07-30 08:13:51.000',0,1.00,1,100,35); -INSERT INTO vn.payrollComponent -(id, name, isSalaryAgreed, isVariable, isException) - VALUES - (1, 'Salario1', 1, 0, 0), + VALUES (99,1,5000,0,50.0000,1.500,0,1,1,1,'packing',0.000,1.500,'4',0.00,99.60,99.40,0.00,0,0,1,0,'2024-07-30 08:13:51.000',0,1.00,1,100,35); + +INSERT INTO vn.payrollComponent (id, name, isSalaryAgreed, isVariable, isException) + VALUES (1, 'Salario1', 1, 0, 0), (2, 'Salario2', 1, 1, 0), (3, 'Salario3', 1, 0, 1); - -INSERT INTO vn.workerIncome -(debit, credit, incomeTypeFk, paymentDate, workerFk, concept) - VALUES - (1000.00, 900.00, 2, '2000-01-01', 1106, NULL), +INSERT INTO vn.workerIncome (debit, credit, incomeTypeFk, paymentDate, workerFk, concept) + VALUES (1000.00, 900.00, 2, '2000-01-01', 1106, NULL), (1001.00, 800.00, 2, '2000-01-01', 1106, NULL); +INSERT INTO dipole.printer (id, description) VALUES(1, ''); -INSERT INTO dipole.printer (id, description) -VALUES(1, ''); +INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode, truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments) + VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL); -INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode, -truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments) -VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL); +INSERT INTO vn.accountDetail (id, value, accountDetailTypeFk, supplierAccountFk) + VALUES (21, 'ES12345B12345678', 3, 241), + (35, 'ES12346B12345679', 3, 241); -INSERT INTO vn.accountDetail -(id, value, accountDetailTypeFk, supplierAccountFk) -VALUES - (21, 'ES12345B12345678', 3, 241), - (35, 'ES12346B12345679', 3, 241); - -INSERT INTO vn.accountDetailType -(id, description) -VALUES - (1, 'IBAN'), - (2, 'SWIFT'), - (3, 'Referencia Remesas'), - (4, 'Referencia Transferencias'), - (5, 'Referencia Nominas'), - (6, 'ABA'); +INSERT INTO vn.accountDetailType (id, description) + VALUES (1, 'IBAN'), + (2, 'SWIFT'), + (3, 'Referencia Remesas'), + (4, 'Referencia Transferencias'), + (5, 'Referencia Nominas'), + (6, 'ABA'); diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index c7156062a..145da170a 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) { @@ -131,7 +131,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/travel/back/methods/travel/specs/extraCommunityFilter.spec.js b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js index 7e90c7681..97e1e5e77 100644 --- a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js +++ b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js @@ -79,7 +79,7 @@ describe('Travel extraCommunityFilter()', () => { const result = await app.models.Travel.extraCommunityFilter(ctx, filter); - expect(result.length).toEqual(9); + expect(result.length).toEqual(10); }); it('should return the travel matching "cargoSupplierFk"', async() => { @@ -110,6 +110,6 @@ describe('Travel extraCommunityFilter()', () => { const result = await app.models.Travel.extraCommunityFilter(ctx, filter); - expect(result.length).toEqual(2); + expect(result.length).toEqual(3); }); }); diff --git a/modules/travel/back/methods/travel/specs/filter.spec.js b/modules/travel/back/methods/travel/specs/filter.spec.js index a608a980e..2b6885cae 100644 --- a/modules/travel/back/methods/travel/specs/filter.spec.js +++ b/modules/travel/back/methods/travel/specs/filter.spec.js @@ -68,7 +68,7 @@ describe('Travel filter()', () => { const result = await app.models.Travel.filter(ctx); - expect(result.length).toEqual(1); + expect(result.length).toEqual(2); }); it('should return the travel matching "continent"', async() => { @@ -80,6 +80,6 @@ describe('Travel filter()', () => { const result = await app.models.Travel.filter(ctx); - expect(result.length).toEqual(6); + expect(result.length).toEqual(7); }); }); From b636b5429aa0d892c73cffa88551d1fb29b9982a Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 9 Aug 2024 08:20:42 +0200 Subject: [PATCH 029/123] fix: refs #7404 refactor fixtures --- db/dump/fixtures.before.sql | 44 ++++++++++++++----------------------- 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 69d838998..63be254d3 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -178,12 +178,12 @@ INSERT INTO `vn`.`country`(`id`, `name`, `isUeeMember`, `code`, `currencyFk`, `i (30,'Canarias', 1, 'IC', 1, 24, 4, 1, 2); INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory`, `hasAvailable`, `isManaged`, `hasDms`, `hasComission`, `countryFk`, `hasProduction`, `isOrigin`, `isDestiny`) - VALUES - (1, 'Warehouse One', 'ALG', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), + VALUES (1, 'Warehouse One', 'ALG', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 'Warehouse Two', NULL, 1, 1, 1, 1, 0, 1, 13, 1, 1, 0), (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', NULL, 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); @@ -1492,16 +1492,16 @@ 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() , 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 @@ -1514,7 +1514,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', 1, 1, ''); INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleQuantity`, `saleInternalWaste`, `saleExternalWaste`) VALUES @@ -1534,7 +1535,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'), ('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'); -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), @@ -1550,7 +1551,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 @@ -3922,18 +3924,6 @@ INSERT INTO vn.stockBought (workerFk, bought, reserve, dated) INSERT INTO vn.auctionConfig (id,conversionCoefficient,warehouseFk) VALUES (1,0.6,6); -INSERT INTO vn.warehouse (id,name,isFeedStock,delay,hasAvailable,isForTicket,countryFk,labelZone,hasComission,isInventory,isComparative,valuatedInventory,isManaged,hasConfectionTeam,hasStowaway,hasDms,isBuyerToBeEmailed,hasUbications,hasProduction,hasMachine,isLogiflora,isBionic,isHalt,isOrigin,isDestiny) - VALUES (6,'Warehouse six',0,0.004,1,0,1,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,0,0); - -INSERT INTO vn.travel (id,shipped,landed,warehouseInFk,warehouseOutFk,agencyFk__,`ref`,isDelivered,isReceived,m3,kg,cargoSupplierFk,totalEntries,agencyModeFk,editorFk,awbFk) - VALUES (11,'2001-01-01','2001-01-02',6,3,0,'eleventh travel',0,0,50.00,500,2,0,1,100,4); - -INSERT INTO vn.entry (id,supplierFk,invoiceNumber,isBooked,isExcludedFromAvailable,isConfirmed,isOrdered,isRaid,commission,created,evaNotes,travelFk,currencyFk,companyFk,isBlocked__,reference,editorFk,locked) - VALUES (99,69,'IN2009',0,1,0,0,1,0.0,'2000-12-01 00:00:00.000','',11,1,442,0,'Movement 9',100,'2024-07-30 08:13:49.000'); - -INSERT INTO vn.buy (entryFk,itemFk,quantity,dispatched,buyingValue,freightValue,isIgnored,stickers,packing,`grouping`,groupingMode,comissionValue,packageValue,packagingFk,price1,price2,price3,minPrice,printedStickers,workerFk,isChecked,isPickedOff,created,`__cm2`,weight,itemOriginalFk,editorFk,buyerFk) - VALUES (99,1,5000,0,50.0000,1.500,0,1,1,1,'packing',0.000,1.500,'4',0.00,99.60,99.40,0.00,0,0,1,0,'2024-07-30 08:13:51.000',0,1.00,1,100,35); - INSERT INTO vn.payrollComponent (id, name, isSalaryAgreed, isVariable, isException) VALUES (1, 'Salario1', 1, 0, 0), (2, 'Salario2', 1, 1, 0), From 52d62710e6347cc2b8e8d6ab8fb49effaf663757 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 13 Aug 2024 13:49:00 +0200 Subject: [PATCH 030/123] chore: refs #7663 fix logic --- .../ticket/back/methods/ticket/setWeight.js | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/ticket/setWeight.js b/modules/ticket/back/methods/ticket/setWeight.js index f2a65b1d6..4f9e1883e 100644 --- a/modules/ticket/back/methods/ticket/setWeight.js +++ b/modules/ticket/back/methods/ticket/setWeight.js @@ -16,13 +16,17 @@ module.exports = Self => { required: true, description: 'The weight value', }], + returns: { + type: 'boolean', + root: true + }, http: { path: `/:id/setWeight`, verb: 'POST' } }); - Self.setWeight = async(ctx, ticketId, weight, invoiceable, options) => { + Self.setWeight = async(ctx, ticketId, weight, options) => { const models = Self.app.models; const userId = ctx.req.accessToken.userId; const myOptions = {userId}; @@ -36,10 +40,10 @@ module.exports = Self => { } try { + const ticket = await Self.findById(ticketId, null, myOptions); if (ticket.weight) throw new UserError('Weight already set'); const canEdit = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'updateAttributes'); - const ticket = await Self.findById(ticketId, null, myOptions); const client = await models.Client.findById(ticket.clientFk, { include: {relation: 'salesPersonUser'}}, myOptions); @@ -51,7 +55,10 @@ module.exports = Self => { where: {workerFk: {inq: [userId, salesPersonUser.id]}} }, myOptions); - if (workerDepartments[0].departmentFk != workerDepartments[1].departmentFk) + if ( + workerDepartments.length == 2 && + workerDepartments[0].departmentFk != workerDepartments[1].departmentFk + ) throw new UserError('You don\'t have enough privileges'); } @@ -63,10 +70,12 @@ module.exports = Self => { const [{taxArea}] = await Self.rawSql('SELECT clientTaxArea(?,?) taxArea', [ticket.clientFk, ticket.warehouseFk], myOptions); - if (ticketState.alertLevel >= packedState.alertLevel && taxArea == 'WORLD' && client.hasDailyInvoice) + if (ticketState.alertLevel >= packedState.alertLevel && taxArea == 'WORLD' && client.hasDailyInvoice) { await Self.invoiceTicketsAndPdf(ctx, [ticketId], null, myOptions); - + return true; + } if (tx) await tx.commit(); + return false; } catch (e) { if (tx) await tx.rollback(); throw e; From 6c9676ce9c90f145b638d3ec293e6d44d274d2db Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 13 Aug 2024 14:52:26 +0200 Subject: [PATCH 031/123] chore: refs #7663 fix logic --- modules/ticket/back/methods/ticket/setWeight.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/ticket/setWeight.js b/modules/ticket/back/methods/ticket/setWeight.js index 4f9e1883e..91ecef634 100644 --- a/modules/ticket/back/methods/ticket/setWeight.js +++ b/modules/ticket/back/methods/ticket/setWeight.js @@ -70,12 +70,13 @@ module.exports = Self => { const [{taxArea}] = await Self.rawSql('SELECT clientTaxArea(?,?) taxArea', [ticket.clientFk, ticket.warehouseFk], myOptions); - if (ticketState.alertLevel >= packedState.alertLevel && taxArea == 'WORLD' && client.hasDailyInvoice) { - await Self.invoiceTicketsAndPdf(ctx, [ticketId], null, myOptions); - return true; - } + const isInvoiceable = ticketState.alertLevel >= packedState.alertLevel && + taxArea == 'WORLD' && client.hasDailyInvoice; + if (tx) await tx.commit(); - return false; + if (isInvoiceable) await Self.invoiceTicketsAndPdf(ctx, [ticketId]); + + return isInvoiceable; } catch (e) { if (tx) await tx.rollback(); throw e; From 8fad522a3e78da01b1afd659c584662d54c2ed0e Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 19 Aug 2024 12:45:06 +0200 Subject: [PATCH 032/123] feat(salix): refs #7677 #7677 return more postcode fields --- modules/client/back/models/address.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/modules/client/back/models/address.js b/modules/client/back/models/address.js index 4a93b5d5c..7011008a4 100644 --- a/modules/client/back/models/address.js +++ b/modules/client/back/models/address.js @@ -43,8 +43,14 @@ module.exports = Self => { include: [{ relation: 'province', scope: { - fields: ['id', 'name'] - } + fields: ['id', 'name', 'countryFk'], + include: [ + { + relation: 'country', + scope: {fields: ['id', 'name']}, + }, + ], + }, }, { relation: 'agencyMode', scope: { From b5940114331cf5fe3aa07ea8b0624cd4c31a29d1 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 20 Aug 2024 07:01:13 +0200 Subject: [PATCH 033/123] feat(salix): refs #7677 #7677 return more postcode fields --- back/methods/postcode/filter.js | 2 ++ db/dump/fixtures.after.sql | 4 ++-- db/dump/fixtures.before.sql | 1 + db/routines/vn/procedures/client_userDisable.sql | 6 +++--- loopback/locale/es.json | 3 ++- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/back/methods/postcode/filter.js b/back/methods/postcode/filter.js index f350b1ea9..8f47b4a93 100644 --- a/back/methods/postcode/filter.js +++ b/back/methods/postcode/filter.js @@ -47,6 +47,8 @@ module.exports = Self => { let stmt; stmt = new ParameterizedSQL(` SELECT + CONCAT_WS('_', pc.code, pc.townFk, t.provinceFk, + p.countryFk) id, pc.townFk, t.provinceFk, p.countryFk, diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index 59730d592..5489d2dd2 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -255,7 +255,7 @@ INSERT INTO vn.operator (workerFk, numberOfWagons, trainFk, itemPackingTypeFk, w (9, 1, 1, 'V', 1); */ -- XXX: web -/* #5483 + INSERT INTO `hedera`.`config` (`cookieLife`, `defaultForm`) VALUES (15,'cms/home'); @@ -274,7 +274,7 @@ UPDATE `vn`.`agencyMode` SET `description` = `name`; INSERT INTO `hedera`.`tpvConfig` (currency, terminal, transactionType, maxAmount, employeeFk, `url`, testMode, testUrl, testKey, merchantUrl) VALUES (978, 1, 0, 2000, 9, 'https://sis.redsys.es/sis/realizarPago', 0, 'https://sis-t.redsys.es:25443/sis/realizarPago', 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', NULL); -*/ + INSERT INTO hedera.tpvMerchantEnable (merchantFk, companyFk) VALUES (1, 442); diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 6563292dd..ca2468d5e 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -364,6 +364,7 @@ INSERT INTO `vn`.`postCode`(`code`, `townFk`, `geoFk`) ('46460', 2, 6), ('46680', 3, 6), ('46600', 4, 7), + ('46600',1, 6), ('EC170150', 5, 8); INSERT INTO `vn`.`clientType`(`code`, `type`) diff --git a/db/routines/vn/procedures/client_userDisable.sql b/db/routines/vn/procedures/client_userDisable.sql index 779ffd688..c0977bc62 100644 --- a/db/routines/vn/procedures/client_userDisable.sql +++ b/db/routines/vn/procedures/client_userDisable.sql @@ -20,15 +20,15 @@ BEGIN WHERE c.typeFk = 'normal' AND a.id IS NULL AND u.active - AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH + AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH AND NOT u.role = (SELECT id FROM `role` WHERE name = 'supplier') AND u.id NOT IN ( SELECT DISTINCT c.id FROM client c LEFT JOIN ticket t ON t.clientFk = c.id WHERE c.salesPersonFk IS NOT NULL - OR t.created > util.VN_CURDATE() - INTERVAL vMonths MONTH - OR shipped > util.VN_CURDATE() - INTERVAL vMonths MONTH + OR t.created > util.VN_CURDATE() - INTERVAL vMonths MONTH + OR shipped > util.VN_CURDATE() - INTERVAL vMonths MONTH ); END$$ DELIMITER ; diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 377691ae6..5d9963833 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -370,5 +370,6 @@ "CONSTRAINT `supplierAccountTooShort` failed for `vn`.`supplier`": "La cuenta debe tener exactamente 10 dígitos", "The sale not exists in the item shelving": "La venta no existe en la estantería del artículo", "The entry not have stickers": "La entrada no tiene etiquetas", - "Too many records": "Demasiados registros" + "Too many records": "Demasiados registros", + "CONSTRAINT `zone.price` failed for `vn`.`zone`": "CONSTRAINT `zone.price` failed for `vn`.`zone`" } \ No newline at end of file From 2ba391fc85bacc338914002bdab00c449339e188 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 2 Sep 2024 07:57:00 +0200 Subject: [PATCH 034/123] feat: refs #7562 Deleted deleteDeprecatedObjects objects --- .../util/events/deleteDeprecatedObjects.sql | 8 -- .../procedures/deleteDeprecatedObjects.sql | 94 ------------------- 2 files changed, 102 deletions(-) delete mode 100644 db/routines/util/events/deleteDeprecatedObjects.sql delete mode 100644 db/routines/util/procedures/deleteDeprecatedObjects.sql diff --git a/db/routines/util/events/deleteDeprecatedObjects.sql b/db/routines/util/events/deleteDeprecatedObjects.sql deleted file mode 100644 index 0d7878a28..000000000 --- a/db/routines/util/events/deleteDeprecatedObjects.sql +++ /dev/null @@ -1,8 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `util`.`deleteDeprecatedObjects` - ON SCHEDULE EVERY 1 DAY - STARTS '2024-06-09 00:01:00.000' - ON COMPLETION PRESERVE - ENABLE -DO CALL deleteDeprecatedObjects$$ -DELIMITER ; diff --git a/db/routines/util/procedures/deleteDeprecatedObjects.sql b/db/routines/util/procedures/deleteDeprecatedObjects.sql deleted file mode 100644 index a251c3d98..000000000 --- a/db/routines/util/procedures/deleteDeprecatedObjects.sql +++ /dev/null @@ -1,94 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`deleteDeprecatedObjects`() - MODIFIES SQL DATA -BEGIN -/** - * Elimina objetos deprecados de la base de datos - */ - DECLARE vQuery TEXT; - DECLARE vDated DATE; - DECLARE vDateRegex VARCHAR(255); - DECLARE vMarkRegex VARCHAR(255); - DECLARE vDone BOOL; - - DECLARE vObjects CURSOR FOR - SELECT CONCAT('ALTER TABLE ', c.TABLE_SCHEMA, '.', c.TABLE_NAME, ' DROP PRIMARY KEY;') - FROM information_schema.`COLUMNS` c - LEFT JOIN information_schema.`VIEWS` v ON v.TABLE_SCHEMA = c.TABLE_SCHEMA - AND v.TABLE_NAME = c.TABLE_NAME - JOIN information_schema.STATISTICS s ON s.TABLE_SCHEMA = c.TABLE_SCHEMA - AND s.TABLE_NAME = c.TABLE_NAME - AND s.COLUMN_NAME = c.COLUMN_NAME - WHERE c.COLUMN_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci - AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated - AND v.TABLE_NAME IS NULL - AND s.INDEX_NAME = 'PRIMARY' - UNION - SELECT CONCAT('ALTER TABLE ', c.TABLE_SCHEMA, '.', c.TABLE_NAME, ' DROP FOREIGN KEY ', kcu.CONSTRAINT_NAME, ';') - FROM information_schema.`COLUMNS` c - LEFT JOIN information_schema.`VIEWS` v ON v.TABLE_SCHEMA = c.TABLE_SCHEMA - AND v.TABLE_NAME = c.TABLE_NAME - JOIN information_schema.KEY_COLUMN_USAGE kcu ON kcu.TABLE_SCHEMA = c.TABLE_SCHEMA - AND kcu.TABLE_NAME = c.TABLE_NAME - AND kcu.COLUMN_NAME = c.COLUMN_NAME - WHERE c.COLUMN_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci - AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated - AND v.TABLE_NAME IS NULL - AND kcu.REFERENCED_COLUMN_NAME IS NOT NULL - UNION - SELECT CONCAT('ALTER TABLE ', c.TABLE_SCHEMA, '.', c.TABLE_NAME, ' DROP COLUMN ', c.COLUMN_NAME, ';') - FROM information_schema.`COLUMNS` c - LEFT JOIN information_schema.`VIEWS` v ON v.TABLE_SCHEMA = c.TABLE_SCHEMA - AND v.TABLE_NAME = c.TABLE_NAME - LEFT JOIN information_schema.KEY_COLUMN_USAGE kcu ON kcu.TABLE_SCHEMA = c.TABLE_SCHEMA - AND kcu.TABLE_NAME = c.TABLE_NAME - AND kcu.COLUMN_NAME = c.COLUMN_NAME - WHERE c.COLUMN_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci - AND REGEXP_SUBSTR(c.COLUMN_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated - AND v.TABLE_NAME IS NULL - UNION - SELECT CONCAT('DROP TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') - FROM information_schema.TABLES - WHERE TABLE_NAME REGEXP vMarkRegex COLLATE utf8mb3_unicode_ci - AND REGEXP_SUBSTR(TABLE_COMMENT, vDateRegex COLLATE utf8mb3_unicode_ci) < vDated; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - CALL vn.mail_insert( - 'cau@verdnatura.es', - NULL, - 'Error en la eliminación automática de objetos deprecados', - CONCAT('
', vQuery, '
', - '

Revisa la tabla util.eventLog para más detalles.

') - ); - RESIGNAL; - END; - - SELECT dateRegex, - deprecatedMarkRegex, - VN_CURDATE() - INTERVAL daysKeepDeprecatedObjects DAY - INTO vDateRegex, - vMarkRegex, - vDated - FROM config; - - IF vDateRegex IS NULL OR vMarkRegex IS NULL OR vDated IS NULL THEN - CALL throw('Some config parameters are not set'); - END IF; - - OPEN vObjects; - l: LOOP - SET vDone = FALSE; - FETCH vObjects INTO vQuery; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `exec`(vQuery); - END LOOP; - CLOSE vObjects; -END$$ -DELIMITER ; From 4c5f5c8324c8424d3bbb001fae7c7c4538694ca3 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 2 Sep 2024 17:08:23 +0200 Subject: [PATCH 035/123] fix: refs #7663 conflicts --- modules/ticket/back/models/ticket-methods.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/ticket/back/models/ticket-methods.js b/modules/ticket/back/models/ticket-methods.js index cb2baf01f..12161d5f5 100644 --- a/modules/ticket/back/models/ticket-methods.js +++ b/modules/ticket/back/models/ticket-methods.js @@ -46,6 +46,5 @@ module.exports = function(Self) { require('../methods/ticket/invoiceTicketsAndPdf')(Self); require('../methods/ticket/docuwareDownload')(Self); require('../methods/ticket/myLastModified')(Self); - require('../methods/ticket/clone')(Self); require('../methods/ticket/setWeight')(Self); }; From d330529bf2d828557d6d83d92b51336417a62170 Mon Sep 17 00:00:00 2001 From: ivanm Date: Tue, 3 Sep 2024 12:33:26 +0200 Subject: [PATCH 036/123] feat: refs #7819 Delete obsolete objects --- db/dump/fixtures.before.sql | 22 +-- .../11210-greenDendro/00-firstScript.sql | 8 ++ .../11210-greenDendro/01-firstScript.sql | 1 + .../11210-greenDendro/02-firstScript.sql | 21 +++ .../11210-greenDendro/03-firstScript.sql | 135 ++++++++++++++++++ 5 files changed, 176 insertions(+), 11 deletions(-) create mode 100644 db/versions/11210-greenDendro/00-firstScript.sql create mode 100644 db/versions/11210-greenDendro/01-firstScript.sql create mode 100644 db/versions/11210-greenDendro/02-firstScript.sql create mode 100644 db/versions/11210-greenDendro/03-firstScript.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 703c67443..e32dab52e 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -2572,18 +2572,18 @@ INSERT INTO `vn`.`rate`(`dated`, `warehouseFk`, `rate0`, `rate1`, `rate2`, `rate (DATE_ADD(util.VN_CURDATE(), INTERVAL -1 YEAR), 1, 10, 15, 20, 25), (util.VN_CURDATE(), 1, 12, 17, 22, 27); -INSERT INTO `vn`.`dua` (id, code, awbFk__, issued, operated, booked, bookEntried, gestdocFk, customsValue, companyFk) +INSERT INTO `vn`.`dua` (id, code, issued, operated, booked, bookEntried, gestdocFk, customsValue, companyFk) VALUES - (1, '19ES0028013A481523', 1, util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 1, 11276.95, 442), - (2, '21ES00280136115760', 2, util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 1376.20, 442), - (3, '19ES00280131956004', 3, util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 3, 14268.50, 442), - (4, '19ES00280131955995', 4, util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 1, 8242.50, 442), - (5, '19ES00280132022070', 5, util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 10012.49, 442), - (6, '19ES00280132032308', 6, util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 19914.25, 442), - (7, '19ES00280132025489', 7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 1934.06, 442), - (8, '19ES00280132025490', 8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 3618.52, 442), - (9, '19ES00280132025491', 9, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 7126.23, 442), - (10, '19ES00280132025492', 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 4631.45, 442); + (1, '19ES0028013A481523', util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 1, 11276.95, 442), + (2, '21ES00280136115760', util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 1376.20, 442), + (3, '19ES00280131956004', util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 3, 14268.50, 442), + (4, '19ES00280131955995', util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 1, 8242.50, 442), + (5, '19ES00280132022070', util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 10012.49, 442), + (6, '19ES00280132032308', util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 19914.25, 442), + (7, '19ES00280132025489', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 1934.06, 442), + (8, '19ES00280132025490', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 3618.52, 442), + (9, '19ES00280132025491', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 7126.23, 442), + (10, '19ES00280132025492', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), util.VN_CURDATE(), util.VN_CURDATE(), util.VN_CURDATE(), 2, 4631.45, 442); INSERT INTO `vn`.`duaEntry` (`duaFk`, `entryFk`, `value`, `customsValue`, `euroValue`) VALUES diff --git a/db/versions/11210-greenDendro/00-firstScript.sql b/db/versions/11210-greenDendro/00-firstScript.sql new file mode 100644 index 000000000..58e6450d6 --- /dev/null +++ b/db/versions/11210-greenDendro/00-firstScript.sql @@ -0,0 +1,8 @@ +ALTER TABLE util.config + CHANGE dbVersion dbVersion__ char(11) DEFAULT NULL COMMENT '@deprecated 2024-09-02 refs #7819'; + +ALTER TABLE util.config + CHANGE hasTriggersDisabled hasTriggersDisabled__ tinyint(1) DEFAULT 0 NOT NULL COMMENT '@deprecated 2024-09-02 refs #7819'; + +RENAME TABLE account.accountLog TO account.accountLog__; + ALTER TABLE account.accountLog__ COMMENT='@deprecated 2024-09-02 refs #7819'; diff --git a/db/versions/11210-greenDendro/01-firstScript.sql b/db/versions/11210-greenDendro/01-firstScript.sql new file mode 100644 index 000000000..787011343 --- /dev/null +++ b/db/versions/11210-greenDendro/01-firstScript.sql @@ -0,0 +1 @@ +DROP DATABASE IF EXISTS `.mysqlworkbench`; \ No newline at end of file diff --git a/db/versions/11210-greenDendro/02-firstScript.sql b/db/versions/11210-greenDendro/02-firstScript.sql new file mode 100644 index 000000000..4cb6bbb02 --- /dev/null +++ b/db/versions/11210-greenDendro/02-firstScript.sql @@ -0,0 +1,21 @@ +DROP TABLE IF EXISTS account.mailClientAccess__; +DROP TABLE IF EXISTS account.mailSenderAccess__; +DROP TABLE IF EXISTS bi.analisis_ventas_familia_evolution__; +DROP TABLE IF EXISTS bi.live_counter__; +DROP TABLE IF EXISTS bi.partitioning_information__; +DROP TABLE IF EXISTS bi.primer_pedido__; +DROP TABLE IF EXISTS bi.tarifa_premisas__; +DROP TABLE IF EXISTS bi.tarifa_warehouse__; +DROP TABLE IF EXISTS bs.compradores__; +DROP TABLE IF EXISTS bs.salesMonthlySnapshot___; +DROP TABLE IF EXISTS bs.salesPerson__; +DROP TABLE IF EXISTS bs.vendedores_evolution__; +DROP TABLE IF EXISTS vn.botanicExport__; +DROP TABLE IF EXISTS vn.claimRma__; +DROP TABLE IF EXISTS vn.coolerPathDetail__; +DROP TABLE IF EXISTS vn.forecastedBalance__; +DROP TABLE IF EXISTS vn.routeLoadWorker__; +DROP TABLE IF EXISTS vn.routeUserPercentage__; +DROP TABLE IF EXISTS vn.ticketSms__; +DROP TABLE IF EXISTS vn.ticketTrackingState__; +DROP TABLE IF EXISTS vn.warehouseAlias__; \ No newline at end of file diff --git a/db/versions/11210-greenDendro/03-firstScript.sql b/db/versions/11210-greenDendro/03-firstScript.sql new file mode 100644 index 000000000..b069d0982 --- /dev/null +++ b/db/versions/11210-greenDendro/03-firstScript.sql @@ -0,0 +1,135 @@ +ALTER TABLE bi.rutasBoard DROP COLUMN coste_bulto__; +ALTER TABLE bi.rutasBoard DROP COLUMN Dia__; +ALTER TABLE bi.rutasBoard DROP COLUMN km__; +ALTER TABLE bi.rutasBoard DROP COLUMN m3__; +ALTER TABLE bi.rutasBoard DROP COLUMN Matricula__; +ALTER TABLE bi.rutasBoard DROP COLUMN month__; +ALTER TABLE bi.rutasBoard DROP COLUMN Terceros__; +ALTER TABLE bi.rutasBoard DROP COLUMN Tipo__; +ALTER TABLE bi.rutasBoard DROP COLUMN warehouse_id__; +ALTER TABLE bi.rutasBoard DROP COLUMN year__; + +ALTER TABLE bs.clientDied DROP COLUMN Boss__; +ALTER TABLE bs.clientDied DROP COLUMN clientName__; +ALTER TABLE bs.clientDied DROP COLUMN workerCode__; + +ALTER TABLE bs.salesByItemTypeDay DROP COLUMN netSale__; + +ALTER TABLE vn.agency DROP FOREIGN KEY agency_FK; +ALTER TABLE vn.agency DROP COLUMN warehouseAliasFk__; + +ALTER TABLE vn.awbComponent DROP COLUMN dated__; + +ALTER TABLE vn.buy DROP COLUMN containerFk__; + +ALTER TABLE vn.chat DROP COLUMN status__; + +ALTER TABLE vn.claim DROP COLUMN rma__; + +ALTER TABLE vn.client DROP COLUMN clientTypeFk__; +ALTER TABLE vn.client DROP COLUMN hasIncoterms__; + +ALTER TABLE vn.clientType DROP COLUMN id__; + +ALTER TABLE vn.cmr DROP FOREIGN KEY cmr_fk1; +ALTER TABLE vn.cmr DROP COLUMN ticketFk__; + +ALTER TABLE vn.company DROP COLUMN sage200Company__; + +ALTER TABLE vn.country DROP FOREIGN KEY country_FK; +ALTER TABLE vn.country DROP COLUMN politicalCountryFk__; + +ALTER TABLE vn.deliveryNote DROP FOREIGN KEY albaran_FK; +ALTER TABLE vn.deliveryNote DROP COLUMN farmingFk__; + +ALTER TABLE vn.dmsType DROP COLUMN path__; + +ALTER TABLE vn.dua DROP COLUMN awbFk__; + +ALTER TABLE vn.entry DROP COLUMN isBlocked__; + +ALTER TABLE vn.expedition DROP COLUMN itemFk__; + +ALTER TABLE vn.item DROP COLUMN minQuantity__; +ALTER TABLE vn.item DROP COLUMN packingShelve__; + +ALTER TABLE vn.itemType DROP COLUMN compression__; +ALTER TABLE vn.itemType DROP COLUMN density__; +ALTER TABLE vn.itemType DROP COLUMN hasComponents__; +ALTER TABLE vn.itemType DROP COLUMN location__; +ALTER TABLE vn.itemType DROP COLUMN maneuver__; +ALTER TABLE vn.itemType DROP COLUMN profit__; +ALTER TABLE vn.itemType DROP COLUMN target__; +ALTER TABLE vn.itemType DROP COLUMN topMargin__; +ALTER TABLE vn.itemType DROP COLUMN transaction__; +ALTER TABLE vn.itemType DROP FOREIGN KEY warehouseFk5; +ALTER TABLE vn.itemType DROP COLUMN warehouseFk__; + +ALTER TABLE vn.ledgerConfig DROP COLUMN lastBookEntry__; + +ALTER TABLE vn.saleTracking DROP FOREIGN KEY saleTracking_FK_1; +ALTER TABLE vn.saleTracking DROP COLUMN actionFk__; + +ALTER TABLE vn.supplier DROP COLUMN isFarmer__; + +ALTER TABLE vn.supplierAccount DROP COLUMN description__; + +ALTER TABLE vn.ticketRequest DROP COLUMN buyerCode__; + +ALTER TABLE vn.travel DROP COLUMN agencyFk__; + +ALTER TABLE vn.warehouse DROP FOREIGN KEY warehouse_ibfk_2; +ALTER TABLE vn.warehouse DROP COLUMN aliasFk__; + +ALTER TABLE vn.worker DROP COLUMN labelerFk__; + +CREATE OR REPLACE +ALGORITHM = UNDEFINED VIEW `vn2008`.`Articles` AS +SELECT `i`.`id` AS `Id_Article`, + `i`.`name` AS `Article`, + `i`.`typeFk` AS `tipo_id`, + `i`.`size` AS `Medida`, + `i`.`inkFk` AS `Color`, + `i`.`category` AS `Categoria`, + `i`.`stems` AS `Tallos`, + `i`.`originFk` AS `id_origen`, + `i`.`description` AS `description`, + `i`.`producerFk` AS `producer_id`, + `i`.`intrastatFk` AS `Codintrastat`, + `i`.`box` AS `caja`, + `i`.`expenseFk` AS `expenseFk`, + `i`.`comment` AS `comments`, + `i`.`relevancy` AS `relevancy`, + `i`.`image` AS `Foto`, + `i`.`generic` AS `generic`, + `i`.`density` AS `density`, + `i`.`minPrice` AS `PVP`, + `i`.`hasMinPrice` AS `Min`, + `i`.`isActive` AS `isActive`, + `i`.`longName` AS `longName`, + `i`.`subName` AS `subName`, + `i`.`tag5` AS `tag5`, + `i`.`value5` AS `value5`, + `i`.`tag6` AS `tag6`, + `i`.`value6` AS `value6`, + `i`.`tag7` AS `tag7`, + `i`.`value7` AS `value7`, + `i`.`tag8` AS `tag8`, + `i`.`value8` AS `value8`, + `i`.`tag9` AS `tag9`, + `i`.`value9` AS `value9`, + `i`.`tag10` AS `tag10`, + `i`.`value10` AS `value10`, + `i`.`minimum` AS `minimum`, + `i`.`upToDown` AS `upToDown`, + `i`.`hasKgPrice` AS `hasKgPrice`, + `i`.`equivalent` AS `Equivalente`, + `i`.`isToPrint` AS `Imprimir`, + `i`.`doPhoto` AS `do_photo`, + `i`.`created` AS `odbc_date`, + `i`.`isFloramondo` AS `isFloramondo`, + `i`.`supplyResponseFk` AS `supplyResponseFk`, + `i`.`stemMultiplier` AS `stemMultiplier`, + `i`.`itemPackingTypeFk` AS `itemPackingTypeFk`, + `i`.`packingOut` AS `packingOut` +FROM `vn`.`item` `i`; \ No newline at end of file From 29b0851741b20d5641d283cebd3125bebd50017c Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 3 Sep 2024 14:35:05 +0200 Subject: [PATCH 037/123] refactor: refs #6346 hook added in wagon-type-tray model --- .../11088-bronzeAspidistra/00-firstScript.sql | 5 --- loopback/locale/es.json | 8 +++- modules/wagon/back/models/wagon-type-tray.js | 42 ++++++++++++------- 3 files changed, 33 insertions(+), 22 deletions(-) diff --git a/db/versions/11088-bronzeAspidistra/00-firstScript.sql b/db/versions/11088-bronzeAspidistra/00-firstScript.sql index 2cc4e715e..98203c9d1 100644 --- a/db/versions/11088-bronzeAspidistra/00-firstScript.sql +++ b/db/versions/11088-bronzeAspidistra/00-firstScript.sql @@ -1,4 +1,3 @@ --- Place your SQL code here DROP TABLE IF EXISTS vn.wagonTypeTray; CREATE TABLE vn.wagonTypeTray ( @@ -20,7 +19,3 @@ ALTER TABLE vn.wagonConfig ADD CONSTRAINT wagonConfig_wagonTypeColor_FK FOREIGN ALTER TABLE vn.wagonTypeTray DROP FOREIGN KEY wagonTypeTray_wagonType_FK; ALTER TABLE vn.wagonTypeTray ADD CONSTRAINT wagonTypeTray_wagonType_FK FOREIGN KEY (wagonTypeFk) REFERENCES vn.wagonType(id) ON DELETE CASCADE ON UPDATE RESTRICT; - - - --- insertar datos por defecto \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index e2be5d013..47601ae41 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -367,5 +367,9 @@ "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", "Payment method is required": "El método de pago es obligatorio", "Cannot send mail": "Não é possível enviar o email", - "CONSTRAINT `supplierAccountTooShort` failed for `vn`.`supplier`": "La cuenta debe tener exactamente 10 dígitos" -} + "CONSTRAINT `supplierAccountTooShort` failed for `vn`.`supplier`": "La cuenta debe tener exactamente 10 dígitos", + "There is already a tray with the same height": "Ya existe una bandeja con la misma altura", + "You must define wagon and height": "Debes definir un tipo de vagón y la altura", + "The maximum height of the wagon is": "La altura máxima es %d", + "The height must be greater than": "The height must be greater than %d" +} \ No newline at end of file diff --git a/modules/wagon/back/models/wagon-type-tray.js b/modules/wagon/back/models/wagon-type-tray.js index e32938743..5bcb1d3c7 100644 --- a/modules/wagon/back/models/wagon-type-tray.js +++ b/modules/wagon/back/models/wagon-type-tray.js @@ -1,16 +1,28 @@ -// module.exports = Self => { -// Self.observe('before save', async ctx => { -// if (ctx.isNewInstance) { -// const models = Self.app.models; -// const config = await models.WagonConfig.findOne(); +const UserError = require('vn-loopback/util/user-error'); -// await models.WagonTypeTray.create({ -// wagonTypeFk: config.wagonTypeFk, -// height: config.height, -// wagonTypeColorFk: config.wagonTypeColorFk -// }, ctx.options); -// } -// if (ctx.instance < config.minHeightBetweenTrays) -// throw new Error('Height must be greater than ' + config.minHeightBetweenTrays); -// }); -// }; +module.exports = Self => { + Self.observe('before save', async ctx => { + if (ctx.isNewInstance) { + const models = Self.app.models; + const {wagonTypeFk, height} = ctx.instance; + const trays = await models.WagonTypeTray.find({where: {wagonTypeFk}}); + + const config = await models.WagonConfig.findOne(); + const tray = await models.WagonTypeTray.find({where: {wagonTypeFk, height}}); + + if (!trays.length) return; + + if (tray.length) + throw new UserError('There is already a tray with the same height'); + + if (!wagonTypeFk && !height) + throw new UserError('You must define wagon and height'); + + if (height < config.minHeightBetweenTrays) + throw new UserError('The height must be greater than', 'HEIGHT_GREATER_THAN', config.minHeightBetweenTrays); + + if (height > config.maxWagonHeight) + throw new UserError('The maximum height of the wagon is', 'MAX_WAGON_HEIGHT', config.maxWagonHeight); + } + }); +}; From 36cf6b1aeee927320e58e19917405d88d26f533a Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 3 Sep 2024 16:50:55 +0200 Subject: [PATCH 038/123] feat: refs #6868 refs# 6868 handleUser --- modules/account/back/models/account.js | 1 - .../account => worker/back/methods/device}/handle-user.js | 0 .../back/methods/device}/specs/handle-user.spec.js | 4 ++-- modules/worker/back/models/device.js | 1 + 4 files changed, 3 insertions(+), 3 deletions(-) rename modules/{account/back/methods/account => worker/back/methods/device}/handle-user.js (100%) rename modules/{account/back/methods/account => worker/back/methods/device}/specs/handle-user.spec.js (72%) diff --git a/modules/account/back/models/account.js b/modules/account/back/models/account.js index 08a5e0811..ceb26053c 100644 --- a/modules/account/back/models/account.js +++ b/modules/account/back/models/account.js @@ -10,7 +10,6 @@ module.exports = Self => { require('../methods/account/logout')(Self); require('../methods/account/change-password')(Self); require('../methods/account/set-password')(Self); - require('../methods/account/handle-user')(Self); Self.setUnverifiedPassword = async(id, pass, options) => { const {emailVerified} = await models.VnUser.findById(id, {fields: ['emailVerified']}, options); diff --git a/modules/account/back/methods/account/handle-user.js b/modules/worker/back/methods/device/handle-user.js similarity index 100% rename from modules/account/back/methods/account/handle-user.js rename to modules/worker/back/methods/device/handle-user.js diff --git a/modules/account/back/methods/account/specs/handle-user.spec.js b/modules/worker/back/methods/device/specs/handle-user.spec.js similarity index 72% rename from modules/account/back/methods/account/specs/handle-user.spec.js rename to modules/worker/back/methods/device/specs/handle-user.spec.js index 486d9dc7a..c4cd37e33 100644 --- a/modules/account/back/methods/account/specs/handle-user.spec.js +++ b/modules/worker/back/methods/device/specs/handle-user.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -describe('Account handleUser()', () => { +describe('Device handleUser()', () => { const ctx = {req: {accessToken: {userId: 9}}}; it('should return data from user', async() => { @@ -9,7 +9,7 @@ describe('Account handleUser()', () => { const nameApp = 'warehouse'; const versionApp = '10'; - const data = await models.Account.handleUser(ctx, androidId, deviceId, versionApp, nameApp); + const data = await models.Device.handleUser(ctx, androidId, deviceId, versionApp, nameApp); expect(data.numberOfWagons).toBe(2); }); diff --git a/modules/worker/back/models/device.js b/modules/worker/back/models/device.js index cda7a958f..6a7d5dba5 100644 --- a/modules/worker/back/models/device.js +++ b/modules/worker/back/models/device.js @@ -1,6 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { + require('../methods/device/handle-user')(Self); Self.rewriteDbError(function(err) { if (err.code === 'ER_DUP_ENTRY') return new UserError(``); From 9797d5e219b1c3d1a1a9a57f50163f1b7ded9087 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 3 Sep 2024 17:33:44 +0200 Subject: [PATCH 039/123] feat: refs #7663 return created invoice ids --- modules/ticket/back/methods/ticket/setWeight.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/setWeight.js b/modules/ticket/back/methods/ticket/setWeight.js index 91ecef634..d71f2c0e5 100644 --- a/modules/ticket/back/methods/ticket/setWeight.js +++ b/modules/ticket/back/methods/ticket/setWeight.js @@ -74,9 +74,10 @@ module.exports = Self => { taxArea == 'WORLD' && client.hasDailyInvoice; if (tx) await tx.commit(); - if (isInvoiceable) await Self.invoiceTicketsAndPdf(ctx, [ticketId]); + let invoiceIds = []; + if (isInvoiceable) invoiceIds = [...await Self.invoiceTicketsAndPdf(ctx, [ticketId])]; - return isInvoiceable; + return invoiceIds; } catch (e) { if (tx) await tx.rollback(); throw e; From df5961a2a2bb196ca9e794c15fd73d80f5ce2973 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 4 Sep 2024 11:41:47 +0200 Subject: [PATCH 040/123] feat: refs #7663 wip test --- .../methods/ticket/specs/setWeight.spec.js | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 modules/ticket/back/methods/ticket/specs/setWeight.spec.js diff --git a/modules/ticket/back/methods/ticket/specs/setWeight.spec.js b/modules/ticket/back/methods/ticket/specs/setWeight.spec.js new file mode 100644 index 000000000..0d48d4adf --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/setWeight.spec.js @@ -0,0 +1,82 @@ +const {models} = require('vn-loopback/server/server'); + +fdescribe('ticket setWeight()', () => { + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); + let opts; + let tx; + const administrativeId = 5; + + beforeEach(async() => { + opts = {transaction: tx}; + tx = await models.Ticket.beginTransaction({}); + opts.transaction = tx; + }); + + afterEach(async() => await tx.rollback()); + + xit('should throw an error if the weight is already set', async() => { + try { + const ticketId = 1; + const weight = 10; + + await models.Ticket.setWeight(ctx, ticketId, weight, opts); + } catch (e) { + expect(e.message).toEqual('Weight already set'); + } + }); + + xit('should set the weight of a ticket', async() => { + const ticketId = 31; + const weight = 15; + + await models.Ticket.setWeight(ctx, ticketId, weight, opts); + + const ticket = await models.Ticket.findById(ticketId, null, opts); + + expect(ticket.weight).toEqual(weight); + }); + + it('should throw an error if the user does not have enough privileges', async() => { + ctx.req.accessToken.userId = administrativeId; + try { + const ticketId = 10; + const weight = 20; + + await models.Ticket.setWeight(ctx, ticketId, weight, opts); + } catch (e) { + expect(e.message).toEqual('You don\'t have enough privilegs'); + } + }); + + // it('should commit the transaction and return invoice ids if the ticket is invoiceable', async() => { + // const tx = await models.Ticket.beginTransaction({}); + + // try { + // const opts = {transaction: tx}; + + // const ticketId = 4; + // const weight = 25; + + // // Mock the necessary methods and data + // jest.spyOn(models.ACL, 'checkAccessAcl').mockResolvedValue(true); + // jest.spyOn(models.Client, 'findById').mockResolvedValue({ + // hasDailyInvoice: true, + // salesPersonUser: () => ({id: 1}) + // }); + // jest.spyOn(models.State, 'findOne').mockResolvedValue({alertLevel: 2}); + // jest.spyOn(models.TicketState, 'findOne').mockResolvedValue({alertLevel: 3}); + // jest.spyOn(models.Ticket, 'rawSql').mockResolvedValue([{taxArea: 'WORLD'}]); + // jest.spyOn(models.Ticket, 'invoiceTicketsAndPdf').mockResolvedValue([1001]); + + // const invoiceIds = await models.Ticket.setWeight(ctx, ticketId, weight, opts); + + // expect(invoiceIds).toEqual([1001]); + + // await tx.rollback(); + // } catch (e) { + // await tx.rollback(); + // throw e; + // } + // }); +}); From 998d3865a357be22c63c3c9759c65fc45133048e Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 5 Sep 2024 08:56:15 +0200 Subject: [PATCH 041/123] chore: refs #7663 fix test --- .../methods/ticket/specs/setWeight.spec.js | 52 +++++++------------ 1 file changed, 20 insertions(+), 32 deletions(-) diff --git a/modules/ticket/back/methods/ticket/specs/setWeight.spec.js b/modules/ticket/back/methods/ticket/specs/setWeight.spec.js index 0d48d4adf..c26ae7aaf 100644 --- a/modules/ticket/back/methods/ticket/specs/setWeight.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setWeight.spec.js @@ -1,21 +1,23 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('ticket setWeight()', () => { +describe('ticket setWeight()', () => { const ctx = beforeAll.getCtx(); beforeAll.mockLoopBackContext(); let opts; let tx; + const employeeId = 1; const administrativeId = 5; beforeEach(async() => { opts = {transaction: tx}; tx = await models.Ticket.beginTransaction({}); opts.transaction = tx; + ctx.req.accessToken.userId = administrativeId; }); afterEach(async() => await tx.rollback()); - xit('should throw an error if the weight is already set', async() => { + it('should throw an error if the weight is already set', async() => { try { const ticketId = 1; const weight = 10; @@ -26,7 +28,7 @@ fdescribe('ticket setWeight()', () => { } }); - xit('should set the weight of a ticket', async() => { + it('should set the weight of a ticket', async() => { const ticketId = 31; const weight = 15; @@ -38,45 +40,31 @@ fdescribe('ticket setWeight()', () => { }); it('should throw an error if the user does not have enough privileges', async() => { - ctx.req.accessToken.userId = administrativeId; + ctx.req.accessToken.userId = employeeId; try { const ticketId = 10; const weight = 20; await models.Ticket.setWeight(ctx, ticketId, weight, opts); } catch (e) { - expect(e.message).toEqual('You don\'t have enough privilegs'); + expect(e.message).toEqual('You don\'t have enough privileges'); } }); - // it('should commit the transaction and return invoice ids if the ticket is invoiceable', async() => { - // const tx = await models.Ticket.beginTransaction({}); + it('should call invoiceTicketsAndPdf if the ticket is invoiceable', async() => { + const ticketId = 10; + const weight = 25; - // try { - // const opts = {transaction: tx}; + spyOn(models.Client, 'findById').and.returnValue({ + hasDailyInvoice: true, + salesPersonUser: () => ({id: 1}) + }); + spyOn(models.TicketState, 'findOne').and.returnValue({alertLevel: 3}); + spyOn(models.Ticket, 'rawSql').and.returnValue([{taxArea: 'WORLD'}]); + spyOn(models.Ticket, 'invoiceTicketsAndPdf').and.returnValue([10]); - // const ticketId = 4; - // const weight = 25; + const invoiceIds = await models.Ticket.setWeight(ctx, ticketId, weight, opts); - // // Mock the necessary methods and data - // jest.spyOn(models.ACL, 'checkAccessAcl').mockResolvedValue(true); - // jest.spyOn(models.Client, 'findById').mockResolvedValue({ - // hasDailyInvoice: true, - // salesPersonUser: () => ({id: 1}) - // }); - // jest.spyOn(models.State, 'findOne').mockResolvedValue({alertLevel: 2}); - // jest.spyOn(models.TicketState, 'findOne').mockResolvedValue({alertLevel: 3}); - // jest.spyOn(models.Ticket, 'rawSql').mockResolvedValue([{taxArea: 'WORLD'}]); - // jest.spyOn(models.Ticket, 'invoiceTicketsAndPdf').mockResolvedValue([1001]); - - // const invoiceIds = await models.Ticket.setWeight(ctx, ticketId, weight, opts); - - // expect(invoiceIds).toEqual([1001]); - - // await tx.rollback(); - // } catch (e) { - // await tx.rollback(); - // throw e; - // } - // }); + expect(invoiceIds.length).toBeGreaterThan(0); + }); }); From 7486c4a3c6d5eefc8046f5997f88d8e0216d7532 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 6 Sep 2024 07:48:53 +0200 Subject: [PATCH 042/123] feat: refs #7562 refs #7532 Requested changes --- db/dump/fixtures.after.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index b3fcad6af..59730d592 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -7,8 +7,8 @@ SET foreign_key_checks = 0; -- XXX: vn-database -INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled, dateRegex, deprecatedMarkRegex, daysKeepDeprecatedObjects) - VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE, '[0-9]{4}-[0-9]{2}-[0-9]{2}', '__$', 60); +INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled) + VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE); /* #5483 INSERT INTO vn.entryConfig (defaultEntry, mailToNotify, inventorySupplierFk, maxLockTime, defaultSupplierFk) From 4daea90b1b6ecc05b43aa1b4411ebe044db5108e Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 6 Sep 2024 08:25:21 +0200 Subject: [PATCH 043/123] feat: refs #7562 refs #7759 Requested changes --- myt.config.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/myt.config.yml b/myt.config.yml index ffa4188b2..683090ecc 100755 --- a/myt.config.yml +++ b/myt.config.yml @@ -2,6 +2,7 @@ code: vn-database versionSchema: util replace: true sumViews: false +defaultDefiner: vn@localhost mockDate: '2001-01-01 12:00:00' subdir: db schemas: From 99ce15863291525340c4c35677776906c033d933 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 6 Sep 2024 11:33:15 +0200 Subject: [PATCH 044/123] chore: refs #7663 return correct type --- modules/ticket/back/methods/ticket/setWeight.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/setWeight.js b/modules/ticket/back/methods/ticket/setWeight.js index d71f2c0e5..47087d384 100644 --- a/modules/ticket/back/methods/ticket/setWeight.js +++ b/modules/ticket/back/methods/ticket/setWeight.js @@ -17,7 +17,7 @@ module.exports = Self => { description: 'The weight value', }], returns: { - type: 'boolean', + type: 'Array', root: true }, http: { From 901cdc7117b1ac701447762c23f1a5846c93400d Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 6 Sep 2024 14:18:15 +0200 Subject: [PATCH 045/123] feat: refs #4074 modify acls --- .../11216-salmonPaniculata/00-firstScript.sql | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 db/versions/11216-salmonPaniculata/00-firstScript.sql diff --git a/db/versions/11216-salmonPaniculata/00-firstScript.sql b/db/versions/11216-salmonPaniculata/00-firstScript.sql new file mode 100644 index 000000000..956dcc25b --- /dev/null +++ b/db/versions/11216-salmonPaniculata/00-firstScript.sql @@ -0,0 +1,12 @@ +-- Place your SQL code here +DELETE FROM salix.ACL WHERE model = 'Province' LIMIT 1; +DELETE FROM salix.ACL WHERE model = 'Town' LIMIT 1; + +UPDATE salix.ACL SET accessType = 'READ' WHERE model = 'BankEntity'; +INSERT INTO salix.ACL + SET model = 'BankEntity', + property = '*', + accessType = 'WRITE', + permission = 'ALLOW', + principalType = 'ROLE', + principalId = 'financial'; From 56eb3e093d8058b5e71eb31d54ba51ee61023709 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 9 Sep 2024 09:39:10 +0200 Subject: [PATCH 046/123] feat: refs #6727 Added indexes in creationDate --- .../11107-pinkAspidistra/00-firstScript.sql | 23 ++----------------- .../11107-pinkAspidistra/01-firstScript.sql | 1 + .../11107-pinkAspidistra/02-firstScript.sql | 1 + .../11107-pinkAspidistra/03-firstScript.sql | 1 + .../11107-pinkAspidistra/04-firstScript.sql | 1 + .../11107-pinkAspidistra/05-firstScript.sql | 1 + .../11107-pinkAspidistra/06-firstScript.sql | 1 + .../11107-pinkAspidistra/07-firstScript.sql | 1 + .../11107-pinkAspidistra/08-firstScript.sql | 1 + .../11107-pinkAspidistra/09-firstScript.sql | 1 + .../11107-pinkAspidistra/10-firstScript.sql | 1 + .../11107-pinkAspidistra/11-firstScript.sql | 1 + .../11107-pinkAspidistra/12-firstScript.sql | 1 + .../11107-pinkAspidistra/13-firstScript.sql | 1 + .../11107-pinkAspidistra/14-firstScript.sql | 1 + .../11107-pinkAspidistra/15-firstScript.sql | 1 + .../11107-pinkAspidistra/16-firstScript.sql | 1 + .../11107-pinkAspidistra/17-firstScript.sql | 1 + .../11107-pinkAspidistra/18-firstScript.sql | 1 + .../11107-pinkAspidistra/19-firstScript.sql | 1 + .../11107-pinkAspidistra/20-firstScript.sql | 1 + .../11107-pinkAspidistra/21-firstScript.sql | 1 + .../11107-pinkAspidistra/22-firstScript.sql | 1 + .../11107-pinkAspidistra/23-firstScript.sql | 1 + .../11107-pinkAspidistra/24-firstScript.sql | 1 + 25 files changed, 26 insertions(+), 21 deletions(-) create mode 100644 db/versions/11107-pinkAspidistra/01-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/02-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/03-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/04-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/05-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/06-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/07-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/08-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/09-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/10-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/11-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/12-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/13-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/14-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/15-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/16-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/17-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/18-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/19-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/20-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/21-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/22-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/23-firstScript.sql create mode 100644 db/versions/11107-pinkAspidistra/24-firstScript.sql diff --git a/db/versions/11107-pinkAspidistra/00-firstScript.sql b/db/versions/11107-pinkAspidistra/00-firstScript.sql index 3ed3df526..62af9c306 100644 --- a/db/versions/11107-pinkAspidistra/00-firstScript.sql +++ b/db/versions/11107-pinkAspidistra/00-firstScript.sql @@ -9,24 +9,5 @@ CREATE OR REPLACE TABLE `util`.`logCleanMultiConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; INSERT INTO `util`.`logCleanMultiConfig` (`schemaName`, `tableName`) - VALUES - ('account', 'roleLog' ), - ('account', 'userLog' ), - ('vn', 'entryLog' ), - ('vn', 'clientLog' ), - ('vn', 'itemLog' ), - ('vn', 'shelvingLog' ), - ('vn', 'workerLog' ), - ('vn', 'deviceProductionLog' ), - ('vn', 'zoneLog' ), - ('vn', 'rateLog' ), - ('vn', 'ticketLog' ), - ('vn', 'agencyLog' ), - ('vn', 'userLog' ), - ('vn', 'routeLog' ), - ('vn', 'claimLog' ), - ('vn', 'supplierLog' ), - ('vn', 'invoiceInLog' ), - ('vn', 'travelLog' ), - ('vn', 'packingSiteDeviceLog' ), - ('vn', 'parkingLog' ); + SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.`COLUMNS` + WHERE COLUMN_NAME IN ('newInstance', 'newInstance'); diff --git a/db/versions/11107-pinkAspidistra/01-firstScript.sql b/db/versions/11107-pinkAspidistra/01-firstScript.sql new file mode 100644 index 000000000..426fcc5b8 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/01-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX userLog_creationDate_IDX USING BTREE ON account.userLog (creationDate DESC); diff --git a/db/versions/11107-pinkAspidistra/02-firstScript.sql b/db/versions/11107-pinkAspidistra/02-firstScript.sql new file mode 100644 index 000000000..e916754e3 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/02-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX roleLog_creationDate_IDX USING BTREE ON account.roleLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/03-firstScript.sql b/db/versions/11107-pinkAspidistra/03-firstScript.sql new file mode 100644 index 000000000..f7400c866 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/03-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX ACLLog_creationDate_IDX USING BTREE ON salix.ACLLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/04-firstScript.sql b/db/versions/11107-pinkAspidistra/04-firstScript.sql new file mode 100644 index 000000000..0c118284e --- /dev/null +++ b/db/versions/11107-pinkAspidistra/04-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX supplierLog_creationDate_IDX USING BTREE ON vn.supplierLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/05-firstScript.sql b/db/versions/11107-pinkAspidistra/05-firstScript.sql new file mode 100644 index 000000000..5cb4070bb --- /dev/null +++ b/db/versions/11107-pinkAspidistra/05-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX deviceProductionLog_creationDate_IDX USING BTREE ON vn.deviceProductionLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/06-firstScript.sql b/db/versions/11107-pinkAspidistra/06-firstScript.sql new file mode 100644 index 000000000..332b8a60a --- /dev/null +++ b/db/versions/11107-pinkAspidistra/06-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX routeLog_creationDate_IDX USING BTREE ON vn.routeLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/07-firstScript.sql b/db/versions/11107-pinkAspidistra/07-firstScript.sql new file mode 100644 index 000000000..b80f8b75f --- /dev/null +++ b/db/versions/11107-pinkAspidistra/07-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX itemLog_creationDate_IDX USING BTREE ON vn.itemLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/08-firstScript.sql b/db/versions/11107-pinkAspidistra/08-firstScript.sql new file mode 100644 index 000000000..315f9b256 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/08-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX userLog_creationDate_IDX USING BTREE ON vn.userLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/09-firstScript.sql b/db/versions/11107-pinkAspidistra/09-firstScript.sql new file mode 100644 index 000000000..7bb604915 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/09-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX invoiceInLog_creationDate_IDX USING BTREE ON vn.invoiceInLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/10-firstScript.sql b/db/versions/11107-pinkAspidistra/10-firstScript.sql new file mode 100644 index 000000000..06e186e0e --- /dev/null +++ b/db/versions/11107-pinkAspidistra/10-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX zoneLog_creationDate_IDX USING BTREE ON vn.zoneLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/11-firstScript.sql b/db/versions/11107-pinkAspidistra/11-firstScript.sql new file mode 100644 index 000000000..be539e7b0 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/11-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX clientLog_creationDate_IDX USING BTREE ON vn.clientLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/12-firstScript.sql b/db/versions/11107-pinkAspidistra/12-firstScript.sql new file mode 100644 index 000000000..4abc284b6 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/12-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX workerLog_creationDate_IDX USING BTREE ON vn.workerLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/13-firstScript.sql b/db/versions/11107-pinkAspidistra/13-firstScript.sql new file mode 100644 index 000000000..cc901e13c --- /dev/null +++ b/db/versions/11107-pinkAspidistra/13-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX ticketLog_creationDate_IDX USING BTREE ON vn.ticketLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/14-firstScript.sql b/db/versions/11107-pinkAspidistra/14-firstScript.sql new file mode 100644 index 000000000..02d2a37b0 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/14-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX rateLog_creationDate_IDX USING BTREE ON vn.rateLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/15-firstScript.sql b/db/versions/11107-pinkAspidistra/15-firstScript.sql new file mode 100644 index 000000000..ad75ff6d0 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/15-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX claimLog_creationDate_IDX USING BTREE ON vn.claimLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/16-firstScript.sql b/db/versions/11107-pinkAspidistra/16-firstScript.sql new file mode 100644 index 000000000..50c7b61a8 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/16-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX saleGroupLog_creationDate_IDX USING BTREE ON vn.saleGroupLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/17-firstScript.sql b/db/versions/11107-pinkAspidistra/17-firstScript.sql new file mode 100644 index 000000000..3de084bcf --- /dev/null +++ b/db/versions/11107-pinkAspidistra/17-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX packingSiteDeviceLog_creationDate_IDX USING BTREE ON vn.packingSiteDeviceLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/18-firstScript.sql b/db/versions/11107-pinkAspidistra/18-firstScript.sql new file mode 100644 index 000000000..1181f8263 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/18-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX travelLog_creationDate_IDX USING BTREE ON vn.travelLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/19-firstScript.sql b/db/versions/11107-pinkAspidistra/19-firstScript.sql new file mode 100644 index 000000000..e95f93031 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/19-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX shelvingLog_creationDate_IDX USING BTREE ON vn.shelvingLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/20-firstScript.sql b/db/versions/11107-pinkAspidistra/20-firstScript.sql new file mode 100644 index 000000000..d3598466d --- /dev/null +++ b/db/versions/11107-pinkAspidistra/20-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX productionConfigLog_creationDate_IDX USING BTREE ON vn.productionConfigLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/21-firstScript.sql b/db/versions/11107-pinkAspidistra/21-firstScript.sql new file mode 100644 index 000000000..5db8d3c63 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/21-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX entryLog_creationDate_IDX USING BTREE ON vn.entryLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/22-firstScript.sql b/db/versions/11107-pinkAspidistra/22-firstScript.sql new file mode 100644 index 000000000..91e68c43b --- /dev/null +++ b/db/versions/11107-pinkAspidistra/22-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX agencyLog_creationDate_IDX USING BTREE ON vn.agencyLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/23-firstScript.sql b/db/versions/11107-pinkAspidistra/23-firstScript.sql new file mode 100644 index 000000000..edd79473e --- /dev/null +++ b/db/versions/11107-pinkAspidistra/23-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX parkingLog_creationDate_IDX USING BTREE ON vn.parkingLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/24-firstScript.sql b/db/versions/11107-pinkAspidistra/24-firstScript.sql new file mode 100644 index 000000000..81e84c405 --- /dev/null +++ b/db/versions/11107-pinkAspidistra/24-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX bufferLog_creationDate_IDX USING BTREE ON srt.bufferLog (creationDate DESC); \ No newline at end of file From 261bebbc3bad07ed317bccbf457d80764efe61d3 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 9 Sep 2024 09:41:40 +0200 Subject: [PATCH 047/123] feat: refs #6727 Deleted duplicated indexes --- db/versions/11107-pinkAspidistra/13-firstScript.sql | 1 - .../00-firstScript.sql} | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) delete mode 100644 db/versions/11107-pinkAspidistra/13-firstScript.sql rename db/versions/{11107-pinkAspidistra/16-firstScript.sql => 11219-goldenCataractarum/00-firstScript.sql} (67%) diff --git a/db/versions/11107-pinkAspidistra/13-firstScript.sql b/db/versions/11107-pinkAspidistra/13-firstScript.sql deleted file mode 100644 index cc901e13c..000000000 --- a/db/versions/11107-pinkAspidistra/13-firstScript.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE INDEX ticketLog_creationDate_IDX USING BTREE ON vn.ticketLog (creationDate DESC); \ No newline at end of file diff --git a/db/versions/11107-pinkAspidistra/16-firstScript.sql b/db/versions/11219-goldenCataractarum/00-firstScript.sql similarity index 67% rename from db/versions/11107-pinkAspidistra/16-firstScript.sql rename to db/versions/11219-goldenCataractarum/00-firstScript.sql index 50c7b61a8..4c4b9eac5 100644 --- a/db/versions/11107-pinkAspidistra/16-firstScript.sql +++ b/db/versions/11219-goldenCataractarum/00-firstScript.sql @@ -1 +1 @@ -CREATE INDEX saleGroupLog_creationDate_IDX USING BTREE ON vn.saleGroupLog (creationDate DESC); \ No newline at end of file +CREATE INDEX saleGroupLog_creationDate_IDX USING BTREE ON vn.saleGroupLog (creationDate DESC); From 71eb44d0833b1d37b8c72e51f23cc9ec2a35c0b0 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 9 Sep 2024 09:58:20 +0200 Subject: [PATCH 048/123] refactor(vnUser): refs #7792 use twoFactorFk and add foreignKey --- back/methods/vn-user/sign-in.js | 8 +++--- back/methods/vn-user/specs/sign-in.spec.js | 2 +- back/methods/vn-user/update-user.js | 8 +++--- back/methods/vn-user/validate-auth.js | 2 +- back/models/vn-user.json | 11 +++++--- db/.pullinfo.json | 2 +- .../vn/triggers/department_afterUpdate.sql | 4 +-- .../11218-pinkRaphis/00-firstScript.sql | 27 +++++++++++++++++++ .../components/change-password/index.html | 2 +- .../back/methods/account/change-password.js | 4 +-- .../account/specs/change-password.spec.js | 2 +- modules/account/back/model-config.json | 5 +++- .../account/back/models/two-factor-type.json | 26 ++++++++++++++++++ myt.config.yml | 3 ++- 14 files changed, 83 insertions(+), 23 deletions(-) create mode 100644 db/versions/11218-pinkRaphis/00-firstScript.sql create mode 100644 modules/account/back/models/two-factor-type.json diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index 775970d55..d74c486c3 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -33,7 +33,7 @@ module.exports = Self => { const where = Self.userUses(user); const vnUser = await Self.findOne({ - fields: ['id', 'name', 'password', 'active', 'email', 'passExpired', 'twoFactor'], + fields: ['id', 'name', 'password', 'active', 'email', 'passExpired', 'twoFactorFk'], where }, myOptions); @@ -46,7 +46,7 @@ module.exports = Self => { await Self.sendTwoFactor(ctx, vnUser, myOptions); await Self.passExpired(vnUser, myOptions); - if (vnUser.twoFactor) + if (vnUser.twoFactorFk) throw new ForbiddenError(null, 'REQUIRES_2FA'); } return Self.validateLogin(user, password, ctx); @@ -58,13 +58,13 @@ module.exports = Self => { if (vnUser.passExpired && vnUser.passExpired.getTime() <= today.getTime()) { const err = new UserError('Pass expired', 'passExpired'); - err.details = {userId: vnUser.id, twoFactor: vnUser.twoFactor ? true : false}; + err.details = {userId: vnUser.id, twoFactorFk: vnUser.twoFactorFk ? true : false}; throw err; } }; Self.sendTwoFactor = async(ctx, vnUser, myOptions) => { - if (vnUser.twoFactor === 'email') { + if (vnUser.twoFactorFk === 'email') { const $ = Self.app.models; const min = 100000; diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index a14dd301e..331173d38 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -70,7 +70,7 @@ describe('VnUser Sign-in()', () => { let error; try { const options = {transaction: tx}; - await employee.updateAttribute('twoFactor', 'email', options); + await employee.updateAttribute('twoFactorFk', 'email', options); await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options); await tx.rollback(); diff --git a/back/methods/vn-user/update-user.js b/back/methods/vn-user/update-user.js index 202b01c65..b0ac40192 100644 --- a/back/methods/vn-user/update-user.js +++ b/back/methods/vn-user/update-user.js @@ -25,8 +25,8 @@ module.exports = Self => { type: 'string', description: 'The user lang' }, { - arg: 'twoFactor', - type: 'string', + arg: 'twoFactorFk', + type: 'any', description: 'The user twoFactor' } ], @@ -36,8 +36,8 @@ module.exports = Self => { } }); - Self.updateUser = async(ctx, id, name, nickname, email, lang, twoFactor) => { + Self.updateUser = async(ctx, id, name, nickname, email, lang, twoFactorFk) => { await Self.userSecurity(ctx, id); - await Self.upsertWithWhere({id}, {name, nickname, email, lang, twoFactor}); + await Self.upsertWithWhere({id}, {name, nickname, email, lang, twoFactorFk}); }; }; diff --git a/back/methods/vn-user/validate-auth.js b/back/methods/vn-user/validate-auth.js index 8fb8b4923..56f0f9c5f 100644 --- a/back/methods/vn-user/validate-auth.js +++ b/back/methods/vn-user/validate-auth.js @@ -55,7 +55,7 @@ module.exports = Self => { throw new UserError('Invalid or expired verification code'); const user = await Self.findById(authCode.userFk, { - fields: ['name', 'twoFactor'] + fields: ['name', 'twoFactorFk'] }, myOptions); if (user.name.toLowerCase() !== username.toLowerCase()) diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 415aa6810..b107a8e52 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -58,9 +58,6 @@ }, "passExpired": { "type": "date" - }, - "twoFactor": { - "type": "string" } }, "relations": { @@ -89,6 +86,11 @@ "type": "hasOne", "model": "UserConfig", "foreignKey": "userFk" + }, + "twoFactor": { + "type": "belongsTo", + "model": "TwoFactorType", + "foreignKey": "twoFactorFk" } }, "acls": [ @@ -165,7 +167,8 @@ "hasGrant", "realm", "email", - "emailVerified" + "emailVerified", + "twoFactorFk" ] } } diff --git a/db/.pullinfo.json b/db/.pullinfo.json index 27d2c7535..5b75584d1 100644 --- a/db/.pullinfo.json +++ b/db/.pullinfo.json @@ -9,7 +9,7 @@ }, "vn": { "view": { - "expeditionPallet_Print": "ced2b84a114fcb99fce05f0c34f4fc03f3fa387bef92621be1bc306608a84345" + "expeditionPallet_Print": "99f75145ac2e7b612a6d71e74b6e55f194a465780fd9875a15eb01e6596b447e" } } } diff --git a/db/routines/vn/triggers/department_afterUpdate.sql b/db/routines/vn/triggers/department_afterUpdate.sql index 559fad9a3..216af0e68 100644 --- a/db/routines/vn/triggers/department_afterUpdate.sql +++ b/db/routines/vn/triggers/department_afterUpdate.sql @@ -7,10 +7,10 @@ BEGIN UPDATE vn.department_recalc SET isChanged = TRUE; END IF; - IF !(OLD.twoFactor <=> NEW.twoFactor) THEN + IF !(OLD.twoFactorFk <=> NEW.twoFactorFk) THEN UPDATE account.user u JOIN vn.workerDepartment wd ON wd.workerFk = u.id - SET u.twoFactor = NEW.twoFactor + SET u.twoFactorFk = NEW.twoFactorFk WHERE wd.departmentFk = NEW.id; END IF; END$$ diff --git a/db/versions/11218-pinkRaphis/00-firstScript.sql b/db/versions/11218-pinkRaphis/00-firstScript.sql new file mode 100644 index 000000000..21bbe3bfc --- /dev/null +++ b/db/versions/11218-pinkRaphis/00-firstScript.sql @@ -0,0 +1,27 @@ +CREATE OR REPLACE TABLE account.twoFactorType ( + `code` varchar(20) NOT NULL, + `description` varchar(255) NOT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +ALTER TABLE account.user ADD twoFactorFk varchar(20) NULL; +ALTER TABLE account.user ADD CONSTRAINT user_twoFactor_fk FOREIGN KEY (twoFactorFk) REFERENCES account.twoFactorType(code) ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE vn.department ADD twoFactorFk varchar(20) NULL; +ALTER TABLE vn.department ADD CONSTRAINT department_twoFactor_fk FOREIGN KEY (twoFactorFk) REFERENCES account.twoFactorType(code) ON DELETE CASCADE ON UPDATE CASCADE; + +INSERT INTO account.twoFactorType (code, description) + VALUES('email', 'Envia un código por email'); + +UPDATE account.`user` u + JOIN account.`user` u2 ON u.id = u2.id + SET u.twoFactorFk = u.twoFactor + WHERE u2.twoFactor IS NOT NULL; + +UPDATE vn.`department` d + JOIN vn.`department` d2 ON d.id = d2.id + SET d.twoFactorFk = d.twoFactor + WHERE d2.twoFactor IS NOT NULL; + +ALTER TABLE account.user CHANGE twoFactor twoFactor__ enum('email') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL COMMENT 'Deprecated 2024-09-09'; +ALTER TABLE vn.department CHANGE twoFactor twoFactor__ enum('email') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL COMMENT 'Deprecated 2024-09-09'; diff --git a/front/salix/components/change-password/index.html b/front/salix/components/change-password/index.html index 04f66976e..9021c51b2 100644 --- a/front/salix/components/change-password/index.html +++ b/front/salix/components/change-password/index.html @@ -22,7 +22,7 @@ autocomplete="false"> { Object.assign(myOptions, options); const {VnUser} = Self.app.models; - const user = await VnUser.findById(userId, {fields: ['name', 'twoFactor']}, myOptions); + const user = await VnUser.findById(userId, {fields: ['name', 'twoFactorFk']}, myOptions); await user.hasPassword(oldPassword); if (oldPassword == newPassword) throw new UserError(`You can not use the same password`); - if (user.twoFactor) + if (user.twoFactorFk) await VnUser.validateCode(user.name, code, myOptions); await VnUser.changePassword(userId, oldPassword, newPassword, myOptions); diff --git a/modules/account/back/methods/account/specs/change-password.spec.js b/modules/account/back/methods/account/specs/change-password.spec.js index c79960212..f3573f41c 100644 --- a/modules/account/back/methods/account/specs/change-password.spec.js +++ b/modules/account/back/methods/account/specs/change-password.spec.js @@ -75,7 +75,7 @@ describe('account changePassword()', () => { await models.VnUser.updateAll( {id: 70}, { - twoFactor: 'email', + twoFactorFk: 'email', passExpired: yesterday } , options); diff --git a/modules/account/back/model-config.json b/modules/account/back/model-config.json index 0cd43d0ce..d79d5de45 100644 --- a/modules/account/back/model-config.json +++ b/modules/account/back/model-config.json @@ -1,4 +1,7 @@ { + "Account": { + "dataSource": "vn" + }, "AccountConfig": { "dataSource": "vn" }, @@ -47,7 +50,7 @@ "SipConfig": { "dataSource": "vn" }, - "Account": { + "TwoFactorType": { "dataSource": "vn" }, "UserLog": { diff --git a/modules/account/back/models/two-factor-type.json b/modules/account/back/models/two-factor-type.json new file mode 100644 index 000000000..ce4a99858 --- /dev/null +++ b/modules/account/back/models/two-factor-type.json @@ -0,0 +1,26 @@ +{ + "name": "TwoFactorType", + "base": "VnModel", + "options": { + "mysql": { + "table": "account.twoFactorType" + } + }, + "properties": { + "code": { + "type": "string", + "id": true + }, + "description": { + "type": "string" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/myt.config.yml b/myt.config.yml index ffa4188b2..87407bac3 100755 --- a/myt.config.yml +++ b/myt.config.yml @@ -38,6 +38,7 @@ fixtures: - userPassword - accountConfig - mailConfig + - twoFactorType salix: - ACL - fieldAcl @@ -393,4 +394,4 @@ localFixtures: - zoneExclusionGeo - zoneGeo - zoneIncluded - - zoneWarehouse \ No newline at end of file + - zoneWarehouse From 31b04cba75e57d98cb0914acec72249a4017f498 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 12:08:12 +0200 Subject: [PATCH 049/123] feat(salix): refs #6156 #6156 Move to myt version --- .../00-ModifyProc_ticket_canAdvance.sql | 128 ------------- .../vn/procedures/ticket_canAdvance.sql | 181 +++++++++--------- .../11221-chocolateSalal/00-firstScript.sql | 12 ++ 3 files changed, 98 insertions(+), 223 deletions(-) delete mode 100644 db/changes/233601/00-ModifyProc_ticket_canAdvance.sql create mode 100644 db/versions/11221-chocolateSalal/00-firstScript.sql diff --git a/db/changes/233601/00-ModifyProc_ticket_canAdvance.sql b/db/changes/233601/00-ModifyProc_ticket_canAdvance.sql deleted file mode 100644 index b0426711f..000000000 --- a/db/changes/233601/00-ModifyProc_ticket_canAdvance.sql +++ /dev/null @@ -1,128 +0,0 @@ -CREATE TABLE IF NOT EXISTS `vn`.`ticketCanAdvanceConfig` ( - `id` INT auto_increment NULL, - `destinationOrder` INT NULL, - CONSTRAINT `ticketCanAdvanceConfig_PK` PRIMARY KEY (id) -) -ENGINE=InnoDB -DEFAULT CHARSET=utf8mb3 -COLLATE=utf8mb3_unicode_ci; - -INSERT INTO `vn`.`ticketCanAdvanceConfig` - SET `destinationOrder` = 5; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) -BEGIN -/** - * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. - * - * @param vDateFuture Fecha de los tickets que se quieren adelantar. - * @param vDateToAdvance Fecha a cuando se quiere adelantar. - * @param vWarehouseFk Almacén - */ - DECLARE vDateInventory DATE; - - SELECT inventoried INTO vDateInventory FROM config; - - CREATE OR REPLACE TEMPORARY TABLE tStock - (itemFk INT PRIMARY KEY, amount INT) - ENGINE = MEMORY; - - INSERT INTO tStock(itemFk, amount) - SELECT itemFk, SUM(quantity) amount FROM - ( - SELECT itemFk, quantity - FROM itemTicketOut - WHERE shipped >= vDateInventory - AND shipped < vDateFuture - AND warehouseFk = vWarehouseFk - UNION ALL - SELECT itemFk, quantity - FROM itemEntryIn - WHERE landed >= vDateInventory - AND landed < vDateFuture - AND isVirtualStock = FALSE - AND warehouseInFk = vWarehouseFk - UNION ALL - SELECT itemFk, quantity - FROM itemEntryOut - WHERE shipped >= vDateInventory - AND shipped < vDateFuture - AND warehouseOutFk = vWarehouseFk - ) t - GROUP BY itemFk HAVING amount != 0; - - CREATE OR REPLACE TEMPORARY TABLE tmp.filter - (INDEX (id)) - SELECT dest.*, - origin.* - FROM ( - SELECT s.ticketFk futureId, - t.workerFk, - t.shipped futureShipped, - t.totalWithVat futureTotalWithVat, - st.name futureState, - t.addressFk futureAddressFk, - am.name futureAgency, - count(s.id) futureLines, - GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, - CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, - SUM((s.quantity <= IFNULL(tst.amount,0))) hasStock, - st.classColor futureClassColor, - ( - count(s.id) - - SUM((s.quantity <= IFNULL(tst.amount,0))) - ) notMovableLines, - ( - count(s.id) = - SUM((s.quantity <= IFNULL(tst.amount,0))) - ) isFullMovable - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN saleVolume sv ON sv.saleFk = s.id - JOIN item i ON i.id = s.itemFk - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` st ON st.id = ts.stateFk - JOIN agencyMode am ON t.agencyModeFk = am.id - LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk - LEFT JOIN tStock tst ON tst.itemFk = i.id - WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) - AND t.warehouseFk = vWarehouseFk - GROUP BY t.id - ) origin - JOIN ( - SELECT t.id, - t.addressFk, - st.name state, - GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt, - t.shipped, - t.totalWithVat, - am.name agency, - CAST(SUM(litros) AS DECIMAL(10,0)) liters, - CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, - st.classColor, - IF(HOUR(t.shipped), - HOUR(t.shipped), - COALESCE(HOUR(zc.hour),HOUR(z.hour)) - ) preparation - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN saleVolume sv ON sv.saleFk = s.id - JOIN item i ON i.id = s.itemFk - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` st ON st.id = ts.stateFk - JOIN agencyMode am ON t.agencyModeFk = am.id - JOIN ticketCanAdvanceConfig - LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk - LEFT JOIN `zone` z ON z.id = t.zoneFk - LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk - WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance) - AND t.warehouseFk = vWarehouseFk - AND st.order <= destinationOrder - GROUP BY t.id - ) dest ON dest.addressFk = origin.futureAddressFk - WHERE origin.hasStock != 0; - - DROP TEMPORARY TABLE tStock; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index 44149126a..58b09e404 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -1,5 +1,7 @@ + + DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) BEGIN /** * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. @@ -8,91 +10,79 @@ BEGIN * @param vDateToAdvance Fecha a cuando se quiere adelantar. * @param vWarehouseFk Almacén */ + DECLARE vDateInventory DATE; - CALL item_getStock(vWarehouseFk, vDateToAdvance, NULL); - CALL item_getMinacum( - vWarehouseFk, - vDateToAdvance, - DATEDIFF(DATE_SUB(vDateFuture, INTERVAL 1 DAY), vDateToAdvance), - NULL - ); + SELECT inventoried INTO vDateInventory FROM config; + + CREATE OR REPLACE TEMPORARY TABLE tStock + (itemFk INT PRIMARY KEY, amount INT) + ENGINE = MEMORY; + + INSERT INTO tStock(itemFk, amount) + SELECT itemFk, SUM(quantity) amount FROM + ( + SELECT itemFk, quantity + FROM itemTicketOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE landed >= vDateInventory + AND landed < vDateFuture + AND isVirtualStock = FALSE + AND warehouseInFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseOutFk = vWarehouseFk + ) t + GROUP BY itemFk HAVING amount != 0; CREATE OR REPLACE TEMPORARY TABLE tmp.filter (INDEX (id)) - SELECT - origin.ticketFk futureId, - dest.ticketFk id, - dest.state, - origin.futureState, - origin.futureIpt, - dest.ipt, - origin.workerFk, - origin.futureLiters, - origin.futureLines, - dest.shipped, - origin.shipped futureShipped, - dest.totalWithVat, - origin.totalWithVat futureTotalWithVat, - dest.agency, - dest.agencyModeFk, - origin.futureAgency, - origin.agencyModeFk futureAgencyModeFk, - dest.lines, - dest.liters, - origin.futureLines - origin.hasStock AS notMovableLines, - (origin.futureLines = origin.hasStock) AS isFullMovable, - dest.zoneFk, - origin.futureZoneFk, - origin.futureZoneName, - origin.classColor futureClassColor, - dest.classColor, - origin.clientFk futureClientFk, - origin.addressFk futureAddressFk, - origin.warehouseFk futureWarehouseFk, - origin.companyFk futureCompanyFk, - IFNULL(dest.nickname, origin.nickname) nickname, - dest.landed + SELECT dest.*, + origin.* FROM ( - SELECT - s.ticketFk, - c.salesPersonFk workerFk, - t.shipped, - t.totalWithVat, - st.name futureState, - am.name futureAgency, - count(s.id) futureLines, - GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, - CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, - SUM(s.quantity <= (IFNULL(il.stock,0) + IFNULL(im.amount, 0))) hasStock, - z.id futureZoneFk, - z.name futureZoneName, - st.classColor, - t.clientFk, - t.nickname, + SELECT s.ticketFk futureId, + t.workerFk, + t.shipped futureShipped, + t.totalWithVat futureTotalWithVat, + st.name futureState, + t.addressFk futureAddressFk, + am.name futureAgency, + count(s.id) futureLines, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, + CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, + SUM((s.quantity <= IFNULL(tst.amount,0))) hasStock, + st.classColor futureClassColor, + ( + count(s.id) - + SUM((s.quantity <= IFNULL(tst.amount,0))) + ) notMovableLines, + ( + count(s.id) = + SUM((s.quantity <= IFNULL(tst.amount,0))) + ) isFullMovable + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + LEFT JOIN tStock tst ON tst.itemFk = i.id + WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) + AND t.warehouseFk = vWarehouseFk + GROUP BY t.id + ) origin + JOIN ( + SELECT t.id, t.addressFk, - t.warehouseFk, - t.companyFk, - t.agencyModeFk - FROM ticket t - JOIN client c ON c.id = t.clientFk - JOIN sale s ON s.ticketFk = t.id - JOIN saleVolume sv ON sv.saleFk = s.id - JOIN item i ON i.id = s.itemFk - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN state st ON st.id = ts.stateFk - JOIN agencyMode am ON t.agencyModeFk = am.id - JOIN zone z ON t.zoneFk = z.id - LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk - LEFT JOIN tmp.itemMinacum im ON im.itemFk = i.id - AND im.warehouseFk = vWarehouseFk - LEFT JOIN tmp.itemList il ON il.itemFk = i.id - WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) - AND t.warehouseFk = vWarehouseFk - GROUP BY t.id - ) origin - LEFT JOIN ( - SELECT - t.id ticketFk, st.name state, GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt, t.shipped, @@ -101,31 +91,32 @@ BEGIN CAST(SUM(litros) AS DECIMAL(10,0)) liters, CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, st.classColor, - t.clientFk, - t.nickname, - t.addressFk, - t.zoneFk, - t.warehouseFk, - t.companyFk, - t.landed, - t.agencyModeFk + CONCAT_WS(':', + IF(HOUR(t.shipped), + HOUR(t.shipped), + COALESCE(HOUR(zc.hour),HOUR(z.hour))), + IF(MINUTE(t.shipped), + MINUTE(t.shipped), + COALESCE(MINUTE(zc.hour),MINUTE(z.hour))) + ) preparation FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id JOIN item i ON i.id = s.itemFk JOIN ticketState ts ON ts.ticketFk = t.id - JOIN state st ON st.id = ts.stateFk + JOIN `state` st ON st.id = ts.stateFk JOIN agencyMode am ON t.agencyModeFk = am.id + JOIN ticketCanAdvanceConfig LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + LEFT JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance) AND t.warehouseFk = vWarehouseFk - AND st.order <= 5 + AND st.order <= destinationOrder GROUP BY t.id - ) dest ON dest.addressFk = origin.addressFk - WHERE origin.hasStock; + ) dest ON dest.addressFk = origin.futureAddressFk + WHERE origin.hasStock != 0; - DROP TEMPORARY TABLE IF EXISTS - tmp.itemList, - tmp.itemMinacum; + DROP TEMPORARY TABLE tStock; END$$ DELIMITER ; diff --git a/db/versions/11221-chocolateSalal/00-firstScript.sql b/db/versions/11221-chocolateSalal/00-firstScript.sql new file mode 100644 index 000000000..8dba40cb3 --- /dev/null +++ b/db/versions/11221-chocolateSalal/00-firstScript.sql @@ -0,0 +1,12 @@ +-- Place your SQL code here +CREATE TABLE IF NOT EXISTS `vn`.`ticketCanAdvanceConfig` ( + `id` INT auto_increment NULL, + `destinationOrder` INT NULL, + CONSTRAINT `ticketCanAdvanceConfig_PK` PRIMARY KEY (id) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; + +INSERT INTO `vn`.`ticketCanAdvanceConfig` + SET `destinationOrder` = 5; From f15b33778cd337fd850732697aae9fd14482ec32 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 14:21:42 +0200 Subject: [PATCH 050/123] feat(salix): refs #5938 #5938 replace variables --- e2e/helpers/selectors.js | 2 +- e2e/paths/05-ticket/21_future.spec.js | 4 +- .../back/methods/ticket/getTicketsFuture.js | 12 ++--- .../ticket/specs/getTicketsFuture.spec.js | 48 +++++++++---------- .../front/future-search-panel/index.html | 8 ++-- modules/ticket/front/future/index.js | 4 +- 6 files changed, 39 insertions(+), 39 deletions(-) diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 097c6e1ab..cfc641a5d 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -688,7 +688,7 @@ export default { searchResult: 'vn-ticket-future tbody tr', openAdvancedSearchButton: 'vn-searchbar .append vn-icon[icon="arrow_drop_down"]', originDated: 'vn-date-picker[label="Origin date"]', - futureDated: 'vn-date-picker[label="Destination date"]', + futureScopeDays: 'vn-date-picker[label="Destination date"]', linesMax: 'vn-textfield[label="Max Lines"]', litersMax: 'vn-textfield[label="Max Liters"]', ipt: 'vn-autocomplete[label="Origin IPT"]', diff --git a/e2e/paths/05-ticket/21_future.spec.js b/e2e/paths/05-ticket/21_future.spec.js index 7b7d478f7..294d79cda 100644 --- a/e2e/paths/05-ticket/21_future.spec.js +++ b/e2e/paths/05-ticket/21_future.spec.js @@ -30,11 +30,11 @@ describe('Ticket Future path', () => { expect(message.text).toContain('warehouseFk is a required argument'); await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - await page.clearInput(selectors.ticketFuture.futureDated); + await page.clearInput(selectors.ticketFuture.futureScopeDays); await page.waitToClick(selectors.ticketFuture.submit); message = await page.waitForSnackbar(); - expect(message.text).toContain('futureDated is a required argument'); + expect(message.text).toContain('futureScopeDays is a required argument'); await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); await page.clearInput(selectors.ticketFuture.originDated); diff --git a/modules/ticket/back/methods/ticket/getTicketsFuture.js b/modules/ticket/back/methods/ticket/getTicketsFuture.js index abd269e5e..247924591 100644 --- a/modules/ticket/back/methods/ticket/getTicketsFuture.js +++ b/modules/ticket/back/methods/ticket/getTicketsFuture.js @@ -9,13 +9,13 @@ module.exports = Self => { accessType: 'READ', accepts: [ { - arg: 'originDated', + arg: 'originScopeDays', type: 'date', description: 'The date in question', required: true }, { - arg: 'futureDated', + arg: 'futureScopeDays', type: 'date', description: 'The date to probe', required: true @@ -129,9 +129,9 @@ module.exports = Self => { ] }; case 'state': - return {'f.stateCode': {like: `%${value}%`}}; + return {'f.alertLevel': value}; case 'futureState': - return {'f.futureStateCode': {like: `%${value}%`}}; + return {'f.futureAlertLevel': value}; } }); @@ -141,7 +141,7 @@ module.exports = Self => { stmt = new ParameterizedSQL( `CALL vn.ticket_canbePostponed(?,?,?)`, - [args.originDated, args.futureDated, args.warehouseFk]); + [args.originScopeDays, args.futureScopeDays, args.warehouseFk]); stmts.push(stmt); @@ -170,7 +170,7 @@ module.exports = Self => { LEFT JOIN tmp.ticket_problems tp ON tp.ticketFk = f.id `); - if (args.problems != undefined && (!args.originDated && !args.futureDated)) + if (args.problems != undefined && (!args.originScopeDays && !args.futureScopeDays)) throw new UserError('Choose a date range or days forward'); let condition; diff --git a/modules/ticket/back/methods/ticket/specs/getTicketsFuture.spec.js b/modules/ticket/back/methods/ticket/specs/getTicketsFuture.spec.js index 4b28f34ea..e1e9a0ed2 100644 --- a/modules/ticket/back/methods/ticket/specs/getTicketsFuture.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getTicketsFuture.spec.js @@ -12,8 +12,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, }; @@ -35,8 +35,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, problems: true }; @@ -60,8 +60,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, problems: false }; @@ -85,8 +85,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, problems: null }; @@ -110,8 +110,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, state: 'OK' }; @@ -135,8 +135,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, futureState: 'OK' }; @@ -160,8 +160,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, ipt: null }; @@ -185,8 +185,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, ipt: 'H' }; @@ -210,8 +210,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, futureIpt: null }; @@ -235,8 +235,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, futureIpt: 'H' }; @@ -260,8 +260,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, id: 13 }; @@ -285,8 +285,8 @@ describe('ticket getTicketsFuture()', () => { const options = {transaction: tx}; const args = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: 1, futureId: 12 }; diff --git a/modules/ticket/front/future-search-panel/index.html b/modules/ticket/front/future-search-panel/index.html index d873fbc37..d74a0f2a0 100644 --- a/modules/ticket/front/future-search-panel/index.html +++ b/modules/ticket/front/future-search-panel/index.html @@ -1,7 +1,7 @@
@@ -9,13 +9,13 @@ diff --git a/modules/ticket/front/future/index.js b/modules/ticket/front/future/index.js index f18dfa17e..a7d579681 100644 --- a/modules/ticket/front/future/index.js +++ b/modules/ticket/front/future/index.js @@ -65,8 +65,8 @@ export default class Controller extends Section { this.$http.get(`UserConfigs/getUserConfig`) .then(res => { this.filterParams = { - originDated: today, - futureDated: today, + originScopeDays: today, + futureScopeDays: today, warehouseFk: res.data.warehouseFk }; this.$.model.applyFilter(null, this.filterParams); From 89c2d2705c7dfed5be92f4f5409e3873f07b7e27 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 14:21:59 +0200 Subject: [PATCH 051/123] feat(salix): refs #5938 #5938 change value-field --- modules/ticket/front/future-search-panel/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/front/future-search-panel/index.html b/modules/ticket/front/future-search-panel/index.html index d74a0f2a0..bcf6e5fe3 100644 --- a/modules/ticket/front/future-search-panel/index.html +++ b/modules/ticket/front/future-search-panel/index.html @@ -59,7 +59,7 @@ @@ -69,7 +69,7 @@ From bf1a43a23ec43d1a129e2b02ef03f301cd1ecd71 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 9 Sep 2024 14:43:16 +0200 Subject: [PATCH 052/123] refactor: refs #7900 Deleted sectorProdPriority column --- db/routines/vn/procedures/productionSectorList.sql | 1 - db/routines/vn/views/itemShelvingAvailable.sql | 1 - db/routines/vn2008/views/state.sql | 1 - db/versions/11222-azureCordyline/00-firstScript.sql | 1 + 4 files changed, 1 insertion(+), 3 deletions(-) create mode 100644 db/versions/11222-azureCordyline/00-firstScript.sql diff --git a/db/routines/vn/procedures/productionSectorList.sql b/db/routines/vn/procedures/productionSectorList.sql index f61ec7ec9..ed6eff147 100644 --- a/db/routines/vn/procedures/productionSectorList.sql +++ b/db/routines/vn/procedures/productionSectorList.sql @@ -55,7 +55,6 @@ BEGIN i.itemPackingTypeFk, isa.`size`, isa.Estado, - isa.sectorProdPriority, isa.available, isa.sectorFk, isa.matricula, diff --git a/db/routines/vn/views/itemShelvingAvailable.sql b/db/routines/vn/views/itemShelvingAvailable.sql index 561569285..15083e6cc 100644 --- a/db/routines/vn/views/itemShelvingAvailable.sql +++ b/db/routines/vn/views/itemShelvingAvailable.sql @@ -10,7 +10,6 @@ AS SELECT `s`.`id` AS `saleFk`, `s`.`concept` AS `concept`, `i`.`size` AS `size`, `st`.`name` AS `Estado`, - `st`.`sectorProdPriority` AS `sectorProdPriority`, `stock`.`visible` AS `available`, `stock`.`sectorFk` AS `sectorFk`, `stock`.`shelvingFk` AS `matricula`, diff --git a/db/routines/vn2008/views/state.sql b/db/routines/vn2008/views/state.sql index 63f6589af..9f7fcccd8 100644 --- a/db/routines/vn2008/views/state.sql +++ b/db/routines/vn2008/views/state.sql @@ -6,7 +6,6 @@ AS SELECT `s`.`id` AS `id`, `s`.`order` AS `order`, `s`.`alertLevel` AS `alert_level`, `s`.`code` AS `code`, - `s`.`sectorProdPriority` AS `sectorProdPriority`, `s`.`nextStateFk` AS `nextStateFk`, `s`.`isPreviousPreparable` AS `isPreviousPreparable`, `s`.`isPicked` AS `isPicked` diff --git a/db/versions/11222-azureCordyline/00-firstScript.sql b/db/versions/11222-azureCordyline/00-firstScript.sql new file mode 100644 index 000000000..c63228911 --- /dev/null +++ b/db/versions/11222-azureCordyline/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.state DROP COLUMN sectorProdPriority; From a5f6fe95ea5b874504142ce4cb9d48b278f1ec80 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 14:58:02 +0200 Subject: [PATCH 053/123] feat(salix): refs #5938 #5938 add futureAlertLevel --- db/routines/vn/procedures/ticket_canbePostponed.sql | 2 ++ e2e/helpers/selectors.js | 2 +- e2e/paths/05-ticket/21_future.spec.js | 8 ++++---- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/ticket_canbePostponed.sql b/db/routines/vn/procedures/ticket_canbePostponed.sql index 871cafddc..1f3c43057 100644 --- a/db/routines/vn/procedures/ticket_canbePostponed.sql +++ b/db/routines/vn/procedures/ticket_canbePostponed.sql @@ -21,6 +21,7 @@ BEGIN t.clientFk, t.warehouseFk, ts.alertLevel, + sub2.alertLevel futureAlertLevel, t.shipped, t.totalWithVat, sub2.shipped futureShipped, @@ -47,6 +48,7 @@ BEGIN t.addressFk, t.id, t.shipped, + ts.alertLevel, st.name state, st.code, st.classColor, diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index cfc641a5d..0a3892c86 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -687,7 +687,7 @@ export default { ticketFuture: { searchResult: 'vn-ticket-future tbody tr', openAdvancedSearchButton: 'vn-searchbar .append vn-icon[icon="arrow_drop_down"]', - originDated: 'vn-date-picker[label="Origin date"]', + originScopeDays: 'vn-date-picker[label="Origin date"]', futureScopeDays: 'vn-date-picker[label="Destination date"]', linesMax: 'vn-textfield[label="Max Lines"]', litersMax: 'vn-textfield[label="Max Liters"]', diff --git a/e2e/paths/05-ticket/21_future.spec.js b/e2e/paths/05-ticket/21_future.spec.js index 294d79cda..60bb9c38d 100644 --- a/e2e/paths/05-ticket/21_future.spec.js +++ b/e2e/paths/05-ticket/21_future.spec.js @@ -37,11 +37,11 @@ describe('Ticket Future path', () => { expect(message.text).toContain('futureScopeDays is a required argument'); await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - await page.clearInput(selectors.ticketFuture.originDated); + await page.clearInput(selectors.ticketFuture.originScopeDays); await page.waitToClick(selectors.ticketFuture.submit); message = await page.waitForSnackbar(); - expect(message.text).toContain('originDated is a required argument'); + expect(message.text).toContain('originScopeDays is a required argument'); await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); await page.waitToClick(selectors.ticketFuture.submit); @@ -71,7 +71,7 @@ describe('Ticket Future path', () => { await page.autocompleteSearch(selectors.ticketFuture.state, 'Free'); await page.waitToClick(selectors.ticketFuture.submit); - expect(httpRequest).toContain('state=FREE'); + expect(httpRequest).toContain('state=0'); await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); @@ -80,7 +80,7 @@ describe('Ticket Future path', () => { await page.autocompleteSearch(selectors.ticketFuture.futureState, 'Free'); await page.waitToClick(selectors.ticketFuture.submit); - expect(httpRequest).toContain('futureState=FREE'); + expect(httpRequest).toContain('futureState=0'); await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); await page.clearInput(selectors.ticketFuture.state); From 1aa888b1a30f20adac3372a9428281710be8d113 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 9 Sep 2024 15:11:09 +0200 Subject: [PATCH 054/123] feat(WorkerDms_filter): refs #7182 split code. fix: filter --- .../back/methods/worker-dms/docuwareFilter.js | 74 +++++++++++++++ .../worker/back/methods/worker-dms/filter.js | 90 ++++++------------- 2 files changed, 99 insertions(+), 65 deletions(-) create mode 100644 modules/worker/back/methods/worker-dms/docuwareFilter.js diff --git a/modules/worker/back/methods/worker-dms/docuwareFilter.js b/modules/worker/back/methods/worker-dms/docuwareFilter.js new file mode 100644 index 000000000..0311153b0 --- /dev/null +++ b/modules/worker/back/methods/worker-dms/docuwareFilter.js @@ -0,0 +1,74 @@ +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find docuware documents', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'number', + description: 'The worker id', + http: {source: 'path'} + } + ], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/:id/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, id) => { + const models = Self.app.models; + + const {dmsTypeFk} = await models.Docuware.findOne({ + fields: ['dmsTypeFk'], + where: {code: 'hr', action: 'find'} + }); + + if (!await models.DmsType.hasReadRole(ctx, dmsTypeFk)) return []; + + let workerDocuware = []; + const worker = await models.Worker.findById(id, {fields: ['fi', 'firstName', 'lastName']}); + const docuwareParse = { + 'Filename': 'dmsFk', + 'Tipo Documento': 'description', + 'Stored on': 'created', + 'Document ID': 'id', + 'URL': 'download', + 'Stored by': 'name', + 'Estado': 'state' + }; + + workerDocuware = + await models.Docuware.getById('hr', worker.lastName + ' ' + worker.firstName, docuwareParse) ?? []; + const url = (await Self.app.models.Url.getUrl('docuware')) + 'WebClient'; + for (document of workerDocuware) { + const docuwareId = document.id; + const defaultData = { + id: docuwareId, + workerFk: id, + dmsFk: docuwareId, + dms: { + id: docuwareId, + file: docuwareId + '.pdf', + isDocuware: true, + hasFile: false, + reference: worker.fi, + dmsFk: docuwareId, + url, + description: document.description + ' - ' + document.state, + download: document.download, + created: document.created, + dmsType: {name: 'Docuware'}, + worker: {id: null, user: {name: document.name}}, + } + }; + Object.assign(document, defaultData); + } + }; + + return workerDocuware; +}; diff --git a/modules/worker/back/methods/worker-dms/filter.js b/modules/worker/back/methods/worker-dms/filter.js index b7802a689..b92ba139b 100644 --- a/modules/worker/back/methods/worker-dms/filter.js +++ b/modules/worker/back/methods/worker-dms/filter.js @@ -8,19 +8,19 @@ module.exports = Self => { accepts: [ { arg: 'id', - type: 'Number', + type: 'number', description: 'The worker id', http: {source: 'path'} }, { arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', http: {source: 'query'} } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -36,6 +36,7 @@ module.exports = Self => { // Get ids alloweds const account = await models.VnUser.findById(userId); + const stmt = new ParameterizedSQL( `SELECT d.id, d.id dmsFk FROM workerDocument wd @@ -44,68 +45,27 @@ module.exports = Self => { LEFT JOIN account.roleRole rr ON rr.inheritsFrom = dt.readRoleFk AND rr.role = ? `, [account.roleFk] ); - const yourOwnDms = {and: [{isReadableByWorker: true}, {worker: userId}]}; - const where = { - or: [yourOwnDms, { - role: { - neq: null - } - }] - }; - stmt.merge(conn.makeSuffix(mergeWhere(filter.where, where))); - - // Get workerDms alloweds - const dmsIds = await conn.executeStmt(stmt); - const allowedIds = dmsIds.map(dms => dms.id); - const allowedFilter = mergeFilters(filter, {where: {dmsFk: {inq: allowedIds}, workerFk: id}}); - let workerDms = await models.WorkerDms.find(allowedFilter); - - // Get docuware info - const docuware = await models.Docuware.findOne({ - fields: ['dmsTypeFk'], - where: {code: 'hr', action: 'find'} - }); - const docuwareDmsType = docuware.dmsTypeFk; - let workerDocuware = []; - if (!filter.skip && (!docuwareDmsType || (docuwareDmsType && await models.DmsType.hasReadRole(ctx, docuwareDmsType)))) { - const worker = await models.Worker.findById(id, {fields: ['fi', 'firstName', 'lastName']}); - const docuwareParse = { - 'Filename': 'dmsFk', - 'Tipo Documento': 'description', - 'Stored on': 'created', - 'Document ID': 'id', - 'URL': 'download', - 'Stored by': 'name', - 'Estado': 'state' - }; - - workerDocuware = - await models.Docuware.getById('hr', worker.lastName + ' ' + worker.firstName, docuwareParse) ?? []; - const url = (await Self.app.models.Url.getUrl('docuware')) + 'WebClient'; - for (document of workerDocuware) { - const docuwareId = document.id; - const defaultData = { - id: docuwareId, - workerFk: id, - dmsFk: docuwareId, - dms: { - id: docuwareId, - file: docuwareId + '.pdf', - isDocuware: true, - hasFile: false, - reference: worker.fi, - dmsFk: docuwareId, - url, - description: document.description + ' - ' + document.state, - download: document.download, - created: document.created, - dmsType: {name: 'Docuware'}, - worker: {id: null, user: {name: document.name}}, + const yourOwnDms = { + or: [ + {and: [ + {isReadableByWorker: true}, + {worker: userId} + ]}, + { + role: { + neq: null } - }; - Object.assign(document, defaultData); - } - } - return workerDms.concat(workerDocuware); + }] + }; + const where = mergeWhere(filter.where, yourOwnDms); + stmt.merge(conn.makeSuffix({where})); + const dmsIds = await conn.executeStmt(stmt); + + const allowedIds = dmsIds.map(dms => dms.id); + const allowedFilter = mergeFilters(filter, {where: {dmsFk: {inq: allowedIds}}}); + + const find = await models.WorkerDms.find(allowedFilter); + + return find; }; }; From 773933ca3c32bec8745457afd9e23fb80d96c0fe Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 15:11:55 +0200 Subject: [PATCH 055/123] feat(salix): refs #6156 #6156 change config sql --- db/versions/11221-chocolateSalal/00-firstScript.sql | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/db/versions/11221-chocolateSalal/00-firstScript.sql b/db/versions/11221-chocolateSalal/00-firstScript.sql index 8dba40cb3..680f0ee0e 100644 --- a/db/versions/11221-chocolateSalal/00-firstScript.sql +++ b/db/versions/11221-chocolateSalal/00-firstScript.sql @@ -1,12 +1,12 @@ -- Place your SQL code here -CREATE TABLE IF NOT EXISTS `vn`.`ticketCanAdvanceConfig` ( - `id` INT auto_increment NULL, - `destinationOrder` INT NULL, - CONSTRAINT `ticketCanAdvanceConfig_PK` PRIMARY KEY (id) +CREATE TABLE IF NOT EXISTS vn.ticketCanAdvanceConfig ( + id INT NOT NULL unsigned PRIMARY KEY, + destinationOrder INT NULL, + CONSTRAINT ticketCanAdvanceConfig_PK PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -INSERT INTO `vn`.`ticketCanAdvanceConfig` - SET `destinationOrder` = 5; +INSERT INTO vn.ticketCanAdvanceConfig + SET destinationOrder = 5; From f70f475223313874abe7e9ea787a4f9e12667db8 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 15:12:44 +0200 Subject: [PATCH 056/123] feat(salix): refs #6156 #6156 change user definer --- db/routines/vn/procedures/ticket_canAdvance.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index 58b09e404..b9e27784d 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -1,7 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) BEGIN /** * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. From f9a25617f0eed7ab6e5c6e0a0eba104dd2263e47 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 15:13:08 +0200 Subject: [PATCH 057/123] feat(salix): refs #6156 #6156 add missing values --- db/routines/vn/procedures/ticket_canAdvance.sql | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index b9e27784d..b1f135e5f 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -45,7 +45,10 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.filter (INDEX (id)) SELECT dest.*, - origin.* + origin.*, + IFNULL(dest.nickname, origin.nickname) nickname, + (origin.futureLines = origin.hasStock) AS isFullMovable, + origin.futureLines - origin.hasStock AS notMovableLines FROM ( SELECT s.ticketFk futureId, t.workerFk, From 615f57b2e6d5fd2951bee7f5cd9822f61af87ee5 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 15:13:32 +0200 Subject: [PATCH 058/123] feat(salix): refs #6156 #6156 simplify CONCAT_WS --- db/routines/vn/procedures/ticket_canAdvance.sql | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index b1f135e5f..5be8d7d7f 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -95,13 +95,9 @@ BEGIN CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, st.classColor, CONCAT_WS(':', - IF(HOUR(t.shipped), - HOUR(t.shipped), - COALESCE(HOUR(zc.hour),HOUR(z.hour))), - IF(MINUTE(t.shipped), - MINUTE(t.shipped), - COALESCE(MINUTE(zc.hour),MINUTE(z.hour))) - ) preparation + COALESCE(HOUR(t.shipped), HOUR(zc.hour), HOUR(z.hour)), + COALESCE(MINUTE(t.shipped), MINUTE(zc.hour), MINUTE(z.hour)) + ) preparation FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id From c407dde7a021c3defe5ca8003758dbf163995159 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 9 Sep 2024 15:14:01 +0200 Subject: [PATCH 059/123] feat(salix): refs #6156 #6156 remove redundant condition --- db/routines/vn/procedures/ticket_canAdvance.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index 5be8d7d7f..c5b918def 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -114,7 +114,7 @@ BEGIN AND st.order <= destinationOrder GROUP BY t.id ) dest ON dest.addressFk = origin.futureAddressFk - WHERE origin.hasStock != 0; + WHERE origin.hasStock; DROP TEMPORARY TABLE tStock; END$$ From 45649359be0b2c788d93f1847a9c9b18159cad1d Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 9 Sep 2024 15:59:17 +0200 Subject: [PATCH 060/123] chore: refs #4074 fix test --- .../02-client/04_edit_billing_data.spec.js | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/e2e/paths/02-client/04_edit_billing_data.spec.js b/e2e/paths/02-client/04_edit_billing_data.spec.js index 10eb85406..12a2e7b74 100644 --- a/e2e/paths/02-client/04_edit_billing_data.spec.js +++ b/e2e/paths/02-client/04_edit_billing_data.spec.js @@ -18,7 +18,7 @@ const $ = { watcher: 'vn-client-billing-data vn-watcher' }; -describe('Client Edit billing data path', () => { +fdescribe('Client Edit billing data path', () => { let browser; let page; beforeAll(async() => { @@ -35,6 +35,14 @@ describe('Client Edit billing data path', () => { it(`should attempt to edit the billing data without an IBAN but fail`, async() => { await page.autocompleteSearch($.payMethod, 'PayMethod with IBAN'); + await page.waitToClick($.saveButton); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('That payment method requires an IBAN'); + }); + + it(`should edit the billing data and save the form`, async() => { + await page.autocompleteSearch($.payMethod, 'PayMethod five'); await page.autocompleteSearch($.swiftBic, 'BBKKESMMMMM'); await page.clearInput($.dueDay); await page.write($.dueDay, '60'); @@ -45,10 +53,13 @@ describe('Client Edit billing data path', () => { await page.waitToClick($.saveButton); const message = await page.waitForSnackbar(); - expect(message.text).toContain('That payment method requires an IBAN'); + expect(message.text).toContain('Notification sent!'); }); it(`should create a new BIC code`, async() => { + await page.loginAndModule('financial', 'client'); + await page.accessToSearchResult('Bruce Banner'); + await page.accessToSection('client.card.billingData'); await page.waitToClick($.newBankEntityButton); await page.write($.newBankEntityName, 'Gotham City Bank'); await page.write($.newBankEntityBIC, 'GTHMCT'); @@ -66,7 +77,7 @@ describe('Client Edit billing data path', () => { it(`should confirm the IBAN pay method was sucessfully saved`, async() => { const payMethod = await page.waitToGetProperty($.payMethod, 'value'); - expect(payMethod).toEqual('PayMethod with IBAN'); + expect(payMethod).toEqual('PayMethod five'); }); it(`should clear the BIC code field, update the IBAN to see how he BIC code autocompletes`, async() => { @@ -79,14 +90,6 @@ describe('Client Edit billing data path', () => { expect(automaticCode).toEqual('CAIXESBB'); }); - it(`should save the form with all its new data`, async() => { - await page.waitForWatcherData($.watcher); - await page.waitToClick($.saveButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Notification sent!'); - }); - it('should confirm the billing data have been edited', async() => { const dueDate = await page.waitToGetProperty($.dueDay, 'value'); const IBAN = await page.waitToGetProperty($.IBAN, 'value'); @@ -94,7 +97,9 @@ describe('Client Edit billing data path', () => { const receivedCoreLCR = await page.checkboxState($.receivedCoreLCRCheckbox); const receivedCoreVNL = await page.checkboxState($.receivedCoreVNLCheckbox); const receivedB2BVNL = await page.checkboxState($.receivedB2BVNLCheckbox); + const payMethod = await page.waitToGetProperty($.payMethod, 'value'); + expect(payMethod).toEqual('PayMethod five'); expect(dueDate).toEqual('60'); expect(IBAN).toEqual('ES9121000418450200051332'); expect(swiftBic).toEqual('CAIXESBB'); From eadff638f90d9472f96c4a0dc061457b85cb6e86 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 9 Sep 2024 15:59:40 +0200 Subject: [PATCH 061/123] chore: refs #4074 drop focus --- e2e/paths/02-client/04_edit_billing_data.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/paths/02-client/04_edit_billing_data.spec.js b/e2e/paths/02-client/04_edit_billing_data.spec.js index 12a2e7b74..ca2c3b953 100644 --- a/e2e/paths/02-client/04_edit_billing_data.spec.js +++ b/e2e/paths/02-client/04_edit_billing_data.spec.js @@ -18,7 +18,7 @@ const $ = { watcher: 'vn-client-billing-data vn-watcher' }; -fdescribe('Client Edit billing data path', () => { +describe('Client Edit billing data path', () => { let browser; let page; beforeAll(async() => { From 125c0c9b3b64fdc538ff8becfba50b45ac3c6675 Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 10 Sep 2024 07:50:40 +0200 Subject: [PATCH 062/123] refactor: refs #6346 requested changes --- .../11088-bronzeAspidistra/00-firstScript.sql | 2 +- loopback/locale/en.json | 6 +- loopback/locale/es.json | 5 +- .../methods/wagonType/specs/wagonTray.spec.js | 58 +++++++++++++++++++ modules/wagon/back/models/wagon-type-tray.js | 7 +-- 5 files changed, 67 insertions(+), 11 deletions(-) create mode 100644 modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js diff --git a/db/versions/11088-bronzeAspidistra/00-firstScript.sql b/db/versions/11088-bronzeAspidistra/00-firstScript.sql index 98203c9d1..11effc5d2 100644 --- a/db/versions/11088-bronzeAspidistra/00-firstScript.sql +++ b/db/versions/11088-bronzeAspidistra/00-firstScript.sql @@ -1,6 +1,6 @@ DROP TABLE IF EXISTS vn.wagonTypeTray; -CREATE TABLE vn.wagonTypeTray ( +CREATE OR REPLACE TABLE vn.wagonTypeTray ( id INT UNSIGNED auto_increment NULL, wagonTypeFk int(11) unsigned NULL, height INT UNSIGNED NULL, diff --git a/loopback/locale/en.json b/loopback/locale/en.json index d9d9c8511..1753d1d07 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -236,6 +236,8 @@ "Cannot send mail": "Cannot send mail", "CONSTRAINT `chkParkingCodeFormat` failed for `vn`.`parking`": "CONSTRAINT `chkParkingCodeFormat` failed for `vn`.`parking`", "This postcode already exists": "This postcode already exists", - "Original invoice not found": "Original invoice not found" - + "Original invoice not found": "Original invoice not found", + "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" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index d7c2d31a0..a14262c49 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -374,7 +374,6 @@ "Original invoice not found": "Factura original no encontrada", "The entry has no lines or does not exist": "La entrada no tiene lineas o no existe", "There is already a tray with the same height": "Ya existe una bandeja con la misma altura", - "You must define wagon and height": "Debes definir un tipo de vagón y la altura", - "The maximum height of the wagon is": "La altura máxima es %d", - "The height must be greater than": "The height must be greater than %d" + "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" } \ No newline at end of file diff --git a/modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js b/modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js new file mode 100644 index 000000000..9e4ae0907 --- /dev/null +++ b/modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js @@ -0,0 +1,58 @@ +const models = require('vn-loopback/server/server').models; + +fdescribe('WagonTray max height()', () => { + it(`should throw an error if the tray's height is above the maximum of the wagon`, async() => { + const tx = await models.WagonTypeTray.beginTransaction({}); + + let error; + try { + const options = {transaction: tx}; + + await models.WagonTypeTray.create({height: 210, wagonTypeFk: 1, wagonTypeColorFk: 4}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe('The maximum height of the wagon is 200cm'); + }); + + it(`should throw an error if the tray's height is already in the wagon`, async() => { + const tx = await models.WagonTypeTray.beginTransaction({}); + + let error; + try { + const options = {transaction: tx}; + + await models.WagonTypeTray.create({height: 50, wagonTypeFk: 1, wagonTypeColorFk: 2}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe('There is already a tray with the same height'); + }); + + it(`should throw an error if the tray's height is below the minimum between the trays`, async() => { + const tx = await models.WagonTypeTray.beginTransaction({}); + + let error; + try { + const options = {transaction: tx}; + + await models.WagonTypeTray.create({height: 40, wagonTypeFk: 1, wagonTypeColorFk: 4}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe('The height must be greater than 50cm'); + }); +}); + diff --git a/modules/wagon/back/models/wagon-type-tray.js b/modules/wagon/back/models/wagon-type-tray.js index 5bcb1d3c7..219f20bfb 100644 --- a/modules/wagon/back/models/wagon-type-tray.js +++ b/modules/wagon/back/models/wagon-type-tray.js @@ -15,14 +15,11 @@ module.exports = Self => { if (tray.length) throw new UserError('There is already a tray with the same height'); - if (!wagonTypeFk && !height) - throw new UserError('You must define wagon and height'); - if (height < config.minHeightBetweenTrays) - throw new UserError('The height must be greater than', 'HEIGHT_GREATER_THAN', config.minHeightBetweenTrays); + throw new UserError('The height must be greater than 50cm'); if (height > config.maxWagonHeight) - throw new UserError('The maximum height of the wagon is', 'MAX_WAGON_HEIGHT', config.maxWagonHeight); + throw new UserError('The maximum height of the wagon is 200cm'); } }); }; From 97597156091e18cdea6529f941c5fc87eb77e199 Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 10 Sep 2024 07:52:09 +0200 Subject: [PATCH 063/123] fix: refs #6346 created test --- db/.pullinfo.json | 2 +- modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/db/.pullinfo.json b/db/.pullinfo.json index 27d2c7535..5b75584d1 100644 --- a/db/.pullinfo.json +++ b/db/.pullinfo.json @@ -9,7 +9,7 @@ }, "vn": { "view": { - "expeditionPallet_Print": "ced2b84a114fcb99fce05f0c34f4fc03f3fa387bef92621be1bc306608a84345" + "expeditionPallet_Print": "99f75145ac2e7b612a6d71e74b6e55f194a465780fd9875a15eb01e6596b447e" } } } diff --git a/modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js b/modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js index 9e4ae0907..783c1a621 100644 --- a/modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js +++ b/modules/wagon/back/methods/wagonType/specs/wagonTray.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -fdescribe('WagonTray max height()', () => { +describe('WagonTray max height()', () => { it(`should throw an error if the tray's height is above the maximum of the wagon`, async() => { const tx = await models.WagonTypeTray.beginTransaction({}); From 1c0e148233f066993713b92355fc4b00fc52c7f0 Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 10 Sep 2024 09:08:43 +0200 Subject: [PATCH 064/123] fix: cau #217599 --- modules/client/back/models/client.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 0a8ebcae5..dc19c5d81 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -320,7 +320,8 @@ module.exports = Self => { // Credit management changes - if (changes?.rating >= 0 || changes?.recommendedCredit >= 0) + if ((changes?.rating != null && changes.rating >= 0) + || (changes?.recommendedCredit != null && changes.recommendedCredit >= 0)) await Self.changeCreditManagement(ctx, finalState, changes); const oldInstance = {}; From 91abf2eefe7a68473b19fbf16794200fe37a03ea Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 10 Sep 2024 09:50:02 +0200 Subject: [PATCH 065/123] refactor: refs #7663 accurate error --- loopback/locale/es.json | 3 ++- modules/ticket/back/methods/ticket/setWeight.js | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index e9e9cd212..064ea4a95 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -373,5 +373,6 @@ "Too many records": "Demasiados registros", "Original invoice not found": "Factura original no encontrada", "The entry has no lines or does not exist": "La entrada no tiene lineas o no existe", - "Weight already set": "El peso ya está establecido" + "Weight already set": "El peso ya está establecido", + "This ticket is not allocated to your department": "Este ticket no está asignado a tu departamento" } \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/setWeight.js b/modules/ticket/back/methods/ticket/setWeight.js index 47087d384..b3b505832 100644 --- a/modules/ticket/back/methods/ticket/setWeight.js +++ b/modules/ticket/back/methods/ticket/setWeight.js @@ -59,7 +59,7 @@ module.exports = Self => { workerDepartments.length == 2 && workerDepartments[0].departmentFk != workerDepartments[1].departmentFk ) - throw new UserError('You don\'t have enough privileges'); + throw new UserError('This ticket is not allocated to your department'); } await ticket.updateAttribute('weight', weight, myOptions); From bb27f0f1f531b958f49910b83a3559d60022c82b Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 10 Sep 2024 10:34:28 +0200 Subject: [PATCH 066/123] build: init version 2440 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bbb83c4b0..1d3b9d253 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.36.0", + "version": "24.40.0", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From 8607a60ca7c57267ef3a86f3002fbf997a7a82af Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 11 Sep 2024 07:56:08 +0200 Subject: [PATCH 067/123] feat: refs #7404 format date before select --- db/routines/vn/procedures/stockBought_calculate.sql | 4 +--- .../back/methods/stock-bought/getStockBoughtDetail.js | 10 +++++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/stockBought_calculate.sql b/db/routines/vn/procedures/stockBought_calculate.sql index 54ac78d8e..6eabe015c 100644 --- a/db/routines/vn/procedures/stockBought_calculate.sql +++ b/db/routines/vn/procedures/stockBought_calculate.sql @@ -3,9 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBought_calcula BEGIN /** * Inserts the purchase volume per buyer - * into stockBought according to the date. - * - * @param vDated Purchase date + * into stockBought according to the current date. */ DECLARE vDated DATE; SET vDated = util.VN_CURDATE(); diff --git a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js index 0657fcb9a..6f09f1f67 100644 --- a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js +++ b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js @@ -23,7 +23,11 @@ module.exports = Self => { } }); - Self.getStockBoughtDetail = async(workerFk, dated = Date.vnNew()) => { + Self.getStockBoughtDetail = async(workerFk, dated) => { + if (!dated) { + dated = Date.vnNew(); + dated.setHours(0, 0, 0, 0); + } return Self.rawSql( `SELECT e.id entryFk, i.id itemFk, @@ -47,8 +51,8 @@ module.exports = Self => { JOIN volumeConfig vc WHERE t.warehouseInFk = ac.warehouseFk AND it.workerFk = ? - AND t.shipped = ?`, - [workerFk, new Date(dated)] + AND t.shipped = util.VN_CURDATE()`, + [workerFk] ); }; }; From b492a1e6a8858f39f118bc0a356b14ff5f1b7860 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 11 Sep 2024 08:05:26 +0200 Subject: [PATCH 068/123] feat: refs #6868 refs# 6868 handleUser --- db/versions/11223-turquoiseLilium/00-firstScript.sql | 2 ++ modules/account/back/models/account.json | 7 ------- 2 files changed, 2 insertions(+), 7 deletions(-) create mode 100644 db/versions/11223-turquoiseLilium/00-firstScript.sql diff --git a/db/versions/11223-turquoiseLilium/00-firstScript.sql b/db/versions/11223-turquoiseLilium/00-firstScript.sql new file mode 100644 index 000000000..9003451c4 --- /dev/null +++ b/db/versions/11223-turquoiseLilium/00-firstScript.sql @@ -0,0 +1,2 @@ +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES( 'Device', 'handleUser', '*', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file diff --git a/modules/account/back/models/account.json b/modules/account/back/models/account.json index 466b2bc04..fc1bbeb3d 100644 --- a/modules/account/back/models/account.json +++ b/modules/account/back/models/account.json @@ -31,13 +31,6 @@ "principalId": "$everyone", "permission": "ALLOW" }, - { - "property": "loginApp", - "accessType": "EXECUTE", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - }, { "property": "logout", "accessType": "EXECUTE", From 56e6a7e6aa794b2ce7c6ddf58b789622abee4ded Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 11 Sep 2024 08:10:21 +0200 Subject: [PATCH 069/123] feat: refs #7956 parametro daysInForward --- db/routines/vn/procedures/item_getSimilar.sql | 186 ++++++++++-------- 1 file changed, 102 insertions(+), 84 deletions(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 823625b97..5c1cfe0e3 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -1,99 +1,117 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_getSimilar`( - vSelf INT, - vWarehouseFk INT, - vDated DATE, - vShowType BOOL +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getSimilar`( + vSelf INT, + vWarehouseFk INT, + vDated DATE, + vShowType BOOL, + vDaysInForward INT ) BEGIN /** -* Propone articulos disponibles ordenados, con la cantidad +* 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 */ - DECLARE vAvailableCalcFk INT; - DECLARE vVisibleCalcFk INT; - DECLARE vTypeFk INT; - DECLARE vPriority INT DEFAULT 1; + DECLARE vAvailableCalcFk INT; + DECLARE vPriority INT DEFAULT 1; - CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); - CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); + CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); - WITH itemTags AS ( - SELECT i.id, - typeFk, - tag5, - value5, - tag6, - value6, - tag7, - value7, - tag8, - value8, - t.name, - it.value - FROM vn.item i - LEFT JOIN vn.itemTag it ON it.itemFk = i.id - AND it.priority = vPriority - LEFT JOIN vn.tag t ON t.id = it.tagFk - WHERE i.id = vSelf - ) - SELECT i.id itemFk, - i.longName, - i.subName, - i.tag5, - i.value5, - (i.value5 <=> its.value5) match5, - i.tag6, - i.value6, - (i.value6 <=> its.value6) match6, - i.tag7, - i.value7, - (i.value7 <=> its.value7) match7, - i.tag8, - i.value8, - (i.value8 <=> its.value8) match8, - a.available, - IFNULL(ip.counter, 0) `counter`, - CASE - WHEN b.groupingMode = 'grouping' THEN b.grouping - WHEN b.groupingMode = 'packing' THEN b.packing - ELSE 1 - END minQuantity, - v.visible located, - b.price2 - FROM vn.item i - JOIN cache.available a ON a.item_id = i.id - 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 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 - JOIN itemTags its - WHERE a.available > 0 - AND (i.typeFk = its.typeFk OR NOT vShowType) - AND i.id <> vSelf - 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; + WITH itemTags AS ( + SELECT i.id, + typeFk, + tag5, + value5, + tag6, + value6, + tag7, + value7, + tag8, + value8, + t.name, + it.value + FROM vn.item i + LEFT JOIN vn.itemTag it ON it.itemFk = i.id + 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) AS 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 BETWEEN CURDATE() AND CURDATE() + INTERVAL vDaysInForward DAY + AND iss.saleFk IS NULL + AND t.warehouseFk = vWarehouseFk + GROUP BY s.itemFk + ) + SELECT i.id itemFk, + CAST(sd.quantity AS INT) advanceable, + i.longName, + i.subName, + i.tag5, + i.value5, + (i.value5 <=> its.value5) match5, + i.tag6, + i.value6, + (i.value6 <=> its.value6) match6, + i.tag7, + i.value7, + (i.value7 <=> its.value7) match7, + i.tag8, + i.value8, + (i.value8 <=> its.value8) match8, + a.available, + IFNULL(ip.counter, 0) `counter`, + CASE + WHEN b.groupingMode = 'grouping' THEN b.grouping + WHEN b.groupingMode = 'packing' THEN b.packing + ELSE 1 + END minQuantity, + sk.stock 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 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 + JOIN itemTags its + WHERE (a.available > 0 OR sd.quantity < sk.stock) + 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 + LIMIT 100; END$$ DELIMITER ; From 6ae15a8e649fbcfbec4c04b98e10dabc0db6847f Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 11 Sep 2024 08:13:28 +0200 Subject: [PATCH 070/123] feat: refs #7956 definer --- db/routines/vn/procedures/item_getSimilar.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 5c1cfe0e3..bc7c6fa87 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getSimilar`( +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_getSimilar`( vSelf INT, vWarehouseFk INT, vDated DATE, From ed8cf628a5ee758af4e4d70bcc193eb8805f462e Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 11 Sep 2024 08:15:32 +0200 Subject: [PATCH 071/123] feat: refs #7956 tabulaciones --- db/routines/vn/procedures/item_getSimilar.sql | 141 +++++++++--------- 1 file changed, 70 insertions(+), 71 deletions(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index bc7c6fa87..77a21eb83 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -35,83 +35,82 @@ BEGIN value8, t.name, it.value - FROM vn.item i - LEFT JOIN vn.itemTag it ON it.itemFk = i.id - AND it.priority = vPriority - LEFT JOIN vn.tag t ON t.id = it.tagFk - WHERE i.id = vSelf + FROM vn.item i + LEFT JOIN vn.itemTag it ON it.itemFk = i.id + 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 + FROM vn.itemShelvingStock + WHERE warehouseFk = vWarehouseFk + GROUP BY itemFk ), sold AS ( - SELECT SUM(s.quantity) AS 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 BETWEEN CURDATE() AND CURDATE() + INTERVAL vDaysInForward DAY - AND iss.saleFk IS NULL - AND t.warehouseFk = vWarehouseFk - GROUP BY s.itemFk + SELECT SUM(s.quantity) AS 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 BETWEEN CURDATE() AND CURDATE() + INTERVAL vDaysInForward DAY + AND iss.saleFk IS NULL + AND t.warehouseFk = vWarehouseFk + GROUP BY s.itemFk ) SELECT i.id itemFk, - CAST(sd.quantity AS INT) advanceable, - i.longName, - i.subName, - i.tag5, - i.value5, - (i.value5 <=> its.value5) match5, - i.tag6, - i.value6, - (i.value6 <=> its.value6) match6, - i.tag7, - i.value7, - (i.value7 <=> its.value7) match7, - i.tag8, - i.value8, - (i.value8 <=> its.value8) match8, - a.available, - IFNULL(ip.counter, 0) `counter`, - CASE - WHEN b.groupingMode = 'grouping' THEN b.grouping - WHEN b.groupingMode = 'packing' THEN b.packing - ELSE 1 - END minQuantity, - sk.stock 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 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 - JOIN itemTags its - WHERE (a.available > 0 OR sd.quantity < sk.stock) - 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 - LIMIT 100; + CAST(sd.quantity AS INT) advanceable, + i.longName, + i.subName, + i.tag5, + i.value5, + (i.value5 <=> its.value5) match5, + i.tag6, + i.value6, + (i.value6 <=> its.value6) match6, + i.tag7, + i.value7, + (i.value7 <=> its.value7) match7, + i.tag8, + i.value8, + (i.value8 <=> its.value8) match8, + a.available, + IFNULL(ip.counter, 0) `counter`, + CASE + WHEN b.groupingMode = 'grouping' THEN b.grouping + WHEN b.groupingMode = 'packing' THEN b.packing + ELSE 1 + END minQuantity, + sk.stock 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 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 + JOIN itemTags its + WHERE (a.available > 0 OR sd.quantity < sk.stock) + 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 + LIMIT 100; END$$ DELIMITER ; From 8dc83e244473b172cac65892ceef5b6de2183d3e Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 11 Sep 2024 08:16:21 +0200 Subject: [PATCH 072/123] feat: refs #7182 optimize workerDms filter --- .../worker/back/methods/worker-dms/filter.js | 57 ++++++++++++++++++- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/modules/worker/back/methods/worker-dms/filter.js b/modules/worker/back/methods/worker-dms/filter.js index b92ba139b..ed0490f54 100644 --- a/modules/worker/back/methods/worker-dms/filter.js +++ b/modules/worker/back/methods/worker-dms/filter.js @@ -57,15 +57,66 @@ module.exports = Self => { } }] }; + const where = mergeWhere(filter.where, yourOwnDms); stmt.merge(conn.makeSuffix({where})); const dmsIds = await conn.executeStmt(stmt); const allowedIds = dmsIds.map(dms => dms.id); - const allowedFilter = mergeFilters(filter, {where: {dmsFk: {inq: allowedIds}}}); + const allowedFilter = mergeFilters(filter, {where: {dmsFk: {inq: allowedIds}, workerFk: id}}); - const find = await models.WorkerDms.find(allowedFilter); + const workerDms = await models.WorkerDms.find(allowedFilter); - return find; + const workerDocuware = filter.skip ? [] : await getDocuwareasync(ctx, id); + return workerDms.concat(workerDocuware); + + async function getDocuwareasync(ctx, id) { + const {dmsTypeFk} = await models.Docuware.findOne({ + fields: ['dmsTypeFk'], + where: {code: 'hr', action: 'find'} + }); + + if (!await models.DmsType.hasReadRole(ctx, dmsTypeFk)) return []; + + let workerDocuware = []; + const worker = await models.Worker.findById(id, {fields: ['fi', 'firstName', 'lastName']}); + const docuwareParse = { + 'Filename': 'dmsFk', + 'Tipo Documento': 'description', + 'Stored on': 'created', + 'Document ID': 'id', + 'URL': 'download', + 'Stored by': 'name', + 'Estado': 'state' + }; + + workerDocuware = + await models.Docuware.getById('hr', worker.lastName + ' ' + worker.firstName, docuwareParse) ?? []; + const url = (await Self.app.models.Url.getUrl('docuware')) + 'WebClient'; + for (document of workerDocuware) { + const docuwareId = document.id; + const defaultData = { + id: docuwareId, + workerFk: id, + dmsFk: docuwareId, + dms: { + id: docuwareId, + file: docuwareId + '.pdf', + isDocuware: true, + hasFile: false, + reference: worker.fi, + dmsFk: docuwareId, + url, + description: document.description + ' - ' + document.state, + download: document.download, + created: document.created, + dmsType: {name: 'Docuware'}, + worker: {id: null, user: {name: document.name}}, + } + }; + Object.assign(document, defaultData); + } + return workerDocuware; + } }; }; From fbfbf21e06f044ee929820e19d79279e8dd9433f Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 11 Sep 2024 08:17:18 +0200 Subject: [PATCH 073/123] fix: refs #7182 unnesesary file --- .../back/methods/worker-dms/docuwareFilter.js | 74 ------------------- 1 file changed, 74 deletions(-) delete mode 100644 modules/worker/back/methods/worker-dms/docuwareFilter.js diff --git a/modules/worker/back/methods/worker-dms/docuwareFilter.js b/modules/worker/back/methods/worker-dms/docuwareFilter.js deleted file mode 100644 index 0311153b0..000000000 --- a/modules/worker/back/methods/worker-dms/docuwareFilter.js +++ /dev/null @@ -1,74 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('filter', { - description: 'Find docuware documents', - accessType: 'READ', - accepts: [ - { - arg: 'id', - type: 'number', - description: 'The worker id', - http: {source: 'path'} - } - ], - returns: { - type: ['object'], - root: true - }, - http: { - path: `/:id/filter`, - verb: 'GET' - } - }); - - Self.filter = async(ctx, id) => { - const models = Self.app.models; - - const {dmsTypeFk} = await models.Docuware.findOne({ - fields: ['dmsTypeFk'], - where: {code: 'hr', action: 'find'} - }); - - if (!await models.DmsType.hasReadRole(ctx, dmsTypeFk)) return []; - - let workerDocuware = []; - const worker = await models.Worker.findById(id, {fields: ['fi', 'firstName', 'lastName']}); - const docuwareParse = { - 'Filename': 'dmsFk', - 'Tipo Documento': 'description', - 'Stored on': 'created', - 'Document ID': 'id', - 'URL': 'download', - 'Stored by': 'name', - 'Estado': 'state' - }; - - workerDocuware = - await models.Docuware.getById('hr', worker.lastName + ' ' + worker.firstName, docuwareParse) ?? []; - const url = (await Self.app.models.Url.getUrl('docuware')) + 'WebClient'; - for (document of workerDocuware) { - const docuwareId = document.id; - const defaultData = { - id: docuwareId, - workerFk: id, - dmsFk: docuwareId, - dms: { - id: docuwareId, - file: docuwareId + '.pdf', - isDocuware: true, - hasFile: false, - reference: worker.fi, - dmsFk: docuwareId, - url, - description: document.description + ' - ' + document.state, - download: document.download, - created: document.created, - dmsType: {name: 'Docuware'}, - worker: {id: null, user: {name: document.name}}, - } - }; - Object.assign(document, defaultData); - } - }; - - return workerDocuware; -}; From 2ee0c93e246335e157141af1bb49f38a3ecfbe2d Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 11 Sep 2024 09:35:26 +0200 Subject: [PATCH 074/123] chore: refs #7663 fix test --- modules/ticket/back/methods/ticket/specs/setWeight.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/specs/setWeight.spec.js b/modules/ticket/back/methods/ticket/specs/setWeight.spec.js index c26ae7aaf..f6ef1f8e7 100644 --- a/modules/ticket/back/methods/ticket/specs/setWeight.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setWeight.spec.js @@ -39,7 +39,7 @@ describe('ticket setWeight()', () => { expect(ticket.weight).toEqual(weight); }); - it('should throw an error if the user does not have enough privileges', async() => { + it('should throw an error if the user is not allocated to the same department', async() => { ctx.req.accessToken.userId = employeeId; try { const ticketId = 10; @@ -47,7 +47,7 @@ describe('ticket setWeight()', () => { await models.Ticket.setWeight(ctx, ticketId, weight, opts); } catch (e) { - expect(e.message).toEqual('You don\'t have enough privileges'); + expect(e.message).toEqual('This ticket is not allocated to your department'); } }); From 92f305b9fd5458f13291e8f8ff5b86bdb6e864f5 Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 11 Sep 2024 10:19:55 +0200 Subject: [PATCH 075/123] fix: refs #6156 proc and version --- .../vn/procedures/ticket_canAdvance.sql | 142 ++++++++++-------- .../11221-chocolateSalal/00-firstScript.sql | 15 +- 2 files changed, 85 insertions(+), 72 deletions(-) diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql index c5b918def..57c3f4235 100644 --- a/db/routines/vn/procedures/ticket_canAdvance.sql +++ b/db/routines/vn/procedures/ticket_canAdvance.sql @@ -1,5 +1,3 @@ - - DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) BEGIN @@ -10,82 +8,90 @@ BEGIN * @param vDateToAdvance Fecha a cuando se quiere adelantar. * @param vWarehouseFk Almacén */ - DECLARE vDateInventory DATE; - SELECT inventoried INTO vDateInventory FROM config; - - CREATE OR REPLACE TEMPORARY TABLE tStock - (itemFk INT PRIMARY KEY, amount INT) - ENGINE = MEMORY; - - INSERT INTO tStock(itemFk, amount) - SELECT itemFk, SUM(quantity) amount FROM - ( - SELECT itemFk, quantity - FROM itemTicketOut - WHERE shipped >= vDateInventory - AND shipped < vDateFuture - AND warehouseFk = vWarehouseFk - UNION ALL - SELECT itemFk, quantity - FROM itemEntryIn - WHERE landed >= vDateInventory - AND landed < vDateFuture - AND isVirtualStock = FALSE - AND warehouseInFk = vWarehouseFk - UNION ALL - SELECT itemFk, quantity - FROM itemEntryOut - WHERE shipped >= vDateInventory - AND shipped < vDateFuture - AND warehouseOutFk = vWarehouseFk - ) t - GROUP BY itemFk HAVING amount != 0; + CALL item_getStock(vWarehouseFk, vDateToAdvance, NULL); + CALL item_getMinacum( + vWarehouseFk, + vDateToAdvance, + DATEDIFF(DATE_SUB(vDateFuture, INTERVAL 1 DAY), vDateToAdvance), + NULL + ); CREATE OR REPLACE TEMPORARY TABLE tmp.filter (INDEX (id)) - SELECT dest.*, - origin.*, - IFNULL(dest.nickname, origin.nickname) nickname, + SELECT origin.ticketFk futureId, + dest.ticketFk id, + dest.state, + origin.futureState, + origin.futureIpt, + dest.ipt, + origin.workerFk, + origin.futureLiters, + origin.futureLines, + dest.shipped, + origin.shipped futureShipped, + dest.totalWithVat, + origin.totalWithVat futureTotalWithVat, + dest.agency, + dest.agencyModeFk, + origin.futureAgency, + origin.agencyModeFk futureAgencyModeFk, + dest.lines, + dest.liters, + origin.futureLines - origin.hasStock AS notMovableLines, (origin.futureLines = origin.hasStock) AS isFullMovable, - origin.futureLines - origin.hasStock AS notMovableLines + dest.zoneFk, + origin.futureZoneFk, + origin.futureZoneName, + origin.classColor futureClassColor, + dest.classColor, + origin.clientFk futureClientFk, + origin.addressFk futureAddressFk, + origin.warehouseFk futureWarehouseFk, + origin.companyFk futureCompanyFk, + IFNULL(dest.nickname, origin.nickname) nickname, + dest.landed, + dest.preparation FROM ( - SELECT s.ticketFk futureId, - t.workerFk, - t.shipped futureShipped, - t.totalWithVat futureTotalWithVat, + SELECT s.ticketFk, + c.salesPersonFk workerFk, + t.shipped, + t.totalWithVat, st.name futureState, - t.addressFk futureAddressFk, am.name futureAgency, count(s.id) futureLines, GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, - SUM((s.quantity <= IFNULL(tst.amount,0))) hasStock, - st.classColor futureClassColor, - ( - count(s.id) - - SUM((s.quantity <= IFNULL(tst.amount,0))) - ) notMovableLines, - ( - count(s.id) = - SUM((s.quantity <= IFNULL(tst.amount,0))) - ) isFullMovable + SUM(s.quantity <= (IFNULL(il.stock,0) + IFNULL(im.amount, 0))) hasStock, + z.id futureZoneFk, + z.name futureZoneName, + st.classColor, + t.clientFk, + t.nickname, + t.addressFk, + t.warehouseFk, + t.companyFk, + t.agencyModeFk FROM ticket t + JOIN client c ON c.id = t.clientFk JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id JOIN item i ON i.id = s.itemFk JOIN ticketState ts ON ts.ticketFk = t.id JOIN `state` st ON st.id = ts.stateFk JOIN agencyMode am ON t.agencyModeFk = am.id + JOIN `zone` z ON t.zoneFk = z.id + LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk - LEFT JOIN tStock tst ON tst.itemFk = i.id + LEFT JOIN tmp.itemMinacum im ON im.itemFk = i.id + AND im.warehouseFk = vWarehouseFk + LEFT JOIN tmp.itemList il ON il.itemFk = i.id WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) AND t.warehouseFk = vWarehouseFk GROUP BY t.id - ) origin - JOIN ( - SELECT t.id, - t.addressFk, + ) origin + LEFT JOIN ( + SELECT t.id ticketFk, st.name state, GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt, t.shipped, @@ -94,9 +100,17 @@ BEGIN CAST(SUM(litros) AS DECIMAL(10,0)) liters, CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, st.classColor, - CONCAT_WS(':', - COALESCE(HOUR(t.shipped), HOUR(zc.hour), HOUR(z.hour)), - COALESCE(MINUTE(t.shipped), MINUTE(zc.hour), MINUTE(z.hour)) + t.clientFk, + t.nickname, + t.addressFk, + t.zoneFk, + t.warehouseFk, + t.companyFk, + t.landed, + t.agencyModeFk, + SEC_TO_TIME( + COALESCE(HOUR(t.shipped), HOUR(zc.hour), HOUR(z.hour)) * 3600 + + COALESCE(MINUTE(t.shipped), MINUTE(zc.hour), MINUTE(z.hour)) * 60 ) preparation FROM ticket t JOIN sale s ON s.ticketFk = t.id @@ -105,17 +119,19 @@ BEGIN JOIN ticketState ts ON ts.ticketFk = t.id JOIN `state` st ON st.id = ts.stateFk JOIN agencyMode am ON t.agencyModeFk = am.id - JOIN ticketCanAdvanceConfig LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk LEFT JOIN `zone` z ON z.id = t.zoneFk LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk + JOIN ticketCanAdvanceConfig tc WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance) AND t.warehouseFk = vWarehouseFk - AND st.order <= destinationOrder + AND st.order <= tc.destinationOrder GROUP BY t.id - ) dest ON dest.addressFk = origin.futureAddressFk + ) dest ON dest.addressFk = origin.addressFk WHERE origin.hasStock; - DROP TEMPORARY TABLE tStock; + DROP TEMPORARY TABLE IF EXISTS + tmp.itemList, + tmp.itemMinacum; END$$ DELIMITER ; diff --git a/db/versions/11221-chocolateSalal/00-firstScript.sql b/db/versions/11221-chocolateSalal/00-firstScript.sql index 680f0ee0e..bca742585 100644 --- a/db/versions/11221-chocolateSalal/00-firstScript.sql +++ b/db/versions/11221-chocolateSalal/00-firstScript.sql @@ -1,12 +1,9 @@ -- Place your SQL code here CREATE TABLE IF NOT EXISTS vn.ticketCanAdvanceConfig ( - id INT NOT NULL unsigned PRIMARY KEY, - destinationOrder INT NULL, - CONSTRAINT ticketCanAdvanceConfig_PK PRIMARY KEY (id) -) -ENGINE=InnoDB -DEFAULT CHARSET=utf8mb3 -COLLATE=utf8mb3_unicode_ci; + id int(10) unsigned NOT NULL, + destinationOrder INT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `ticketCanAdvanceConfig_check` CHECK (`id` = 1) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -INSERT INTO vn.ticketCanAdvanceConfig - SET destinationOrder = 5; +INSERT INTO vn.ticketCanAdvanceConfig SET id =1, destinationOrder = 5; \ No newline at end of file From c21da8d258196466544549fadad1c7cd7b54c823 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 11 Sep 2024 10:31:43 +0200 Subject: [PATCH 076/123] fix: refs #7182 function name --- modules/worker/back/methods/worker-dms/filter.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/worker/back/methods/worker-dms/filter.js b/modules/worker/back/methods/worker-dms/filter.js index ed0490f54..394988f9e 100644 --- a/modules/worker/back/methods/worker-dms/filter.js +++ b/modules/worker/back/methods/worker-dms/filter.js @@ -67,10 +67,10 @@ module.exports = Self => { const workerDms = await models.WorkerDms.find(allowedFilter); - const workerDocuware = filter.skip ? [] : await getDocuwareasync(ctx, id); + const workerDocuware = filter.skip ? [] : await getDocuware(ctx, id); return workerDms.concat(workerDocuware); - async function getDocuwareasync(ctx, id) { + async function getDocuware(ctx, id) { const {dmsTypeFk} = await models.Docuware.findOne({ fields: ['dmsTypeFk'], where: {code: 'hr', action: 'find'} From 10f75835871dd02b999baa1fa4b1265fa66a2a94 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 11 Sep 2024 11:22:22 +0200 Subject: [PATCH 077/123] feat: refs #7956 sin AS --- db/routines/vn/procedures/item_getSimilar.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 77a21eb83..b524e30a7 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -48,7 +48,7 @@ BEGIN GROUP BY itemFk ), sold AS ( - SELECT SUM(s.quantity) AS quantity, s.itemFk + 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 From d15be5100d8b58cfad3ee673f0008b30196582e6 Mon Sep 17 00:00:00 2001 From: ivanm Date: Wed, 11 Sep 2024 13:42:04 +0200 Subject: [PATCH 078/123] refactor: refs #7952 Deprecate creditInsurance.creditClassification --- db/routines/vn/procedures/creditInsurance_getRisk.sql | 2 +- .../vn/triggers/creditInsurance_afterInsert.sql | 2 +- .../vn/triggers/creditInsurance_beforeInsert.sql | 10 ---------- db/routines/vn/triggers/solunionCAP_afterInsert.sql | 2 +- db/routines/vn/triggers/solunionCAP_afterUpdate.sql | 4 ++-- db/routines/vn/triggers/solunionCAP_beforeDelete.sql | 2 +- db/versions/11224-whiteMastic/00-firstScript.sql | 2 ++ 7 files changed, 8 insertions(+), 16 deletions(-) delete mode 100644 db/routines/vn/triggers/creditInsurance_beforeInsert.sql create mode 100644 db/versions/11224-whiteMastic/00-firstScript.sql diff --git a/db/routines/vn/procedures/creditInsurance_getRisk.sql b/db/routines/vn/procedures/creditInsurance_getRisk.sql index ea19f8aef..5562c91d4 100644 --- a/db/routines/vn/procedures/creditInsurance_getRisk.sql +++ b/db/routines/vn/procedures/creditInsurance_getRisk.sql @@ -10,7 +10,7 @@ BEGIN SELECT * FROM ( SELECT cc.client clientFk, ci.grade FROM creditClassification cc - JOIN creditInsurance ci ON cc.id = ci.creditClassification + JOIN creditInsurance ci ON cc.id = ci.creditClassificationFk WHERE dateEnd IS NULL ORDER BY ci.creationDate DESC LIMIT 10000000000000000000) t1 diff --git a/db/routines/vn/triggers/creditInsurance_afterInsert.sql b/db/routines/vn/triggers/creditInsurance_afterInsert.sql index c865f31a4..f4857a730 100644 --- a/db/routines/vn/triggers/creditInsurance_afterInsert.sql +++ b/db/routines/vn/triggers/creditInsurance_afterInsert.sql @@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`creditInsurance_afterIn BEGIN UPDATE `client` c JOIN vn.creditClassification cc ON cc.client = c.id - SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; + SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassificationFk; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/creditInsurance_beforeInsert.sql b/db/routines/vn/triggers/creditInsurance_beforeInsert.sql deleted file mode 100644 index 8e036d373..000000000 --- a/db/routines/vn/triggers/creditInsurance_beforeInsert.sql +++ /dev/null @@ -1,10 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`creditInsurance_beforeInsert` - BEFORE INSERT ON `creditInsurance` - FOR EACH ROW -BEGIN - IF NEW.creditClassificationFk THEN - SET NEW.creditClassification = NEW.creditClassificationFk; - END IF; -END$$ -DELIMITER ; diff --git a/db/routines/vn/triggers/solunionCAP_afterInsert.sql b/db/routines/vn/triggers/solunionCAP_afterInsert.sql index b4df7dc61..d09cadd95 100644 --- a/db/routines/vn/triggers/solunionCAP_afterInsert.sql +++ b/db/routines/vn/triggers/solunionCAP_afterInsert.sql @@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`solunionCAP_afterInsert BEGIN UPDATE client c JOIN creditClassification cc ON cc.client = c.id - JOIN creditInsurance ci ON ci.creditClassification = cc.id + JOIN creditInsurance ci ON ci.creditClassificationFk = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/solunionCAP_afterUpdate.sql b/db/routines/vn/triggers/solunionCAP_afterUpdate.sql index ccfba96f2..1199067bb 100644 --- a/db/routines/vn/triggers/solunionCAP_afterUpdate.sql +++ b/db/routines/vn/triggers/solunionCAP_afterUpdate.sql @@ -6,12 +6,12 @@ BEGIN IF NEW.dateLeaving IS NOT NULL THEN UPDATE client c JOIN creditClassification cc ON cc.client = c.id - JOIN creditInsurance ci ON ci.creditClassification = cc.id + JOIN creditInsurance ci ON ci.creditClassificationFk = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; ELSE UPDATE client c JOIN creditClassification cc ON cc.client = c.id - JOIN creditInsurance ci ON ci.creditClassification = cc.id + JOIN creditInsurance ci ON ci.creditClassificationFk = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance; END IF; END$$ diff --git a/db/routines/vn/triggers/solunionCAP_beforeDelete.sql b/db/routines/vn/triggers/solunionCAP_beforeDelete.sql index a8b6732c1..7913a0d78 100644 --- a/db/routines/vn/triggers/solunionCAP_beforeDelete.sql +++ b/db/routines/vn/triggers/solunionCAP_beforeDelete.sql @@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`solunionCAP_beforeDelet BEGIN UPDATE client c JOIN creditClassification cc ON cc.client = c.id - JOIN creditInsurance ci ON ci.creditClassification = cc.id + JOIN creditInsurance ci ON ci.creditClassificationFk = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; END$$ DELIMITER ; diff --git a/db/versions/11224-whiteMastic/00-firstScript.sql b/db/versions/11224-whiteMastic/00-firstScript.sql new file mode 100644 index 000000000..52267cd91 --- /dev/null +++ b/db/versions/11224-whiteMastic/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.creditInsurance + CHANGE creditClassification creditClassification__ int(11) DEFAULT NULL COMMENT '@deprecated 2024-09-11'; From 728c40916c4dc759afe2a0e56bb8ffb5e1acb7fd Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 11 Sep 2024 14:38:58 +0200 Subject: [PATCH 079/123] refactor: refs #7895 workerDocument to workerDms --- db/dump/fixtures.before.sql | 2 +- ...ent_afterDelete.sql => workerDms_afterDelete.sql} | 6 +++--- ...t_beforeInsert.sql => workerDms_beforeInsert.sql} | 4 ++-- ...t_beforeUpdate.sql => workerDms_beforeUpdate.sql} | 4 ++-- db/versions/11225-goldenLaurel/00-firstScript.sql | 1 + db/versions/11225-goldenLaurel/01-firstScript.sql | 1 + db/versions/11225-goldenLaurel/02-firstScript.sql | 1 + modules/worker/back/methods/worker-dms/filter.js | 7 ++++--- modules/worker/back/models/worker-dms.json | 12 +++--------- myt.config.yml | 2 +- 10 files changed, 19 insertions(+), 21 deletions(-) rename db/routines/vn/triggers/{workerDocument_afterDelete.sql => workerDms_afterDelete.sql} (71%) rename db/routines/vn/triggers/{workerDocument_beforeInsert.sql => workerDms_beforeInsert.sql} (73%) rename db/routines/vn/triggers/{workerDocument_beforeUpdate.sql => workerDms_beforeUpdate.sql} (73%) create mode 100644 db/versions/11225-goldenLaurel/00-firstScript.sql create mode 100644 db/versions/11225-goldenLaurel/01-firstScript.sql create mode 100644 db/versions/11225-goldenLaurel/02-firstScript.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index ea689c609..0a797f7ec 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -2488,7 +2488,7 @@ INSERT INTO `vn`.`clientDms`(`clientFk`, `dmsFk`) (1104, 2), (1104, 3); -INSERT INTO `vn`.`workerDocument`(`id`, `worker`, `document`,`isReadableByWorker`) +INSERT INTO `vn`.`workerDms`(`id`, `workerFk`, `dmsFk`,`isReadableByWorker`) VALUES (1, 1106, 4, TRUE), (2, 1107, 3, FALSE); diff --git a/db/routines/vn/triggers/workerDocument_afterDelete.sql b/db/routines/vn/triggers/workerDms_afterDelete.sql similarity index 71% rename from db/routines/vn/triggers/workerDocument_afterDelete.sql rename to db/routines/vn/triggers/workerDms_afterDelete.sql index 8d4878248..bfb7d481e 100644 --- a/db/routines/vn/triggers/workerDocument_afterDelete.sql +++ b/db/routines/vn/triggers/workerDms_afterDelete.sql @@ -1,11 +1,11 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDocument_afterDelete` - AFTER DELETE ON `workerDocument` +CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDms_afterDelete` + AFTER DELETE ON `workerDms` FOR EACH ROW BEGIN INSERT INTO workerLog SET `action` = 'delete', - `changedModel` = 'WorkerDocument', + `changedModel` = 'WorkerDms', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); END$$ diff --git a/db/routines/vn/triggers/workerDocument_beforeInsert.sql b/db/routines/vn/triggers/workerDms_beforeInsert.sql similarity index 73% rename from db/routines/vn/triggers/workerDocument_beforeInsert.sql rename to db/routines/vn/triggers/workerDms_beforeInsert.sql index f0675e68f..a52c60961 100644 --- a/db/routines/vn/triggers/workerDocument_beforeInsert.sql +++ b/db/routines/vn/triggers/workerDms_beforeInsert.sql @@ -1,6 +1,6 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDocument_beforeInsert` - BEFORE INSERT ON `workerDocument` +CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDms_beforeInsert` + BEFORE INSERT ON `workerDms` FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); diff --git a/db/routines/vn/triggers/workerDocument_beforeUpdate.sql b/db/routines/vn/triggers/workerDms_beforeUpdate.sql similarity index 73% rename from db/routines/vn/triggers/workerDocument_beforeUpdate.sql rename to db/routines/vn/triggers/workerDms_beforeUpdate.sql index ffb6efd74..564064444 100644 --- a/db/routines/vn/triggers/workerDocument_beforeUpdate.sql +++ b/db/routines/vn/triggers/workerDms_beforeUpdate.sql @@ -1,6 +1,6 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDocument_beforeUpdate` - BEFORE UPDATE ON `workerDocument` +CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDms_beforeUpdate` + BEFORE UPDATE ON `workerDms` FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); diff --git a/db/versions/11225-goldenLaurel/00-firstScript.sql b/db/versions/11225-goldenLaurel/00-firstScript.sql new file mode 100644 index 000000000..87f521a03 --- /dev/null +++ b/db/versions/11225-goldenLaurel/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.workerDocument CHANGE worker workerFk int(10) unsigned DEFAULT NULL NULL; diff --git a/db/versions/11225-goldenLaurel/01-firstScript.sql b/db/versions/11225-goldenLaurel/01-firstScript.sql new file mode 100644 index 000000000..3aa3a1876 --- /dev/null +++ b/db/versions/11225-goldenLaurel/01-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.workerDocument CHANGE document dmsFk int(11) DEFAULT NULL NULL; diff --git a/db/versions/11225-goldenLaurel/02-firstScript.sql b/db/versions/11225-goldenLaurel/02-firstScript.sql new file mode 100644 index 000000000..d0e789534 --- /dev/null +++ b/db/versions/11225-goldenLaurel/02-firstScript.sql @@ -0,0 +1 @@ +RENAME TABLE vn.workerDocument TO vn.workerDms; diff --git a/modules/worker/back/methods/worker-dms/filter.js b/modules/worker/back/methods/worker-dms/filter.js index b7802a689..8feac3658 100644 --- a/modules/worker/back/methods/worker-dms/filter.js +++ b/modules/worker/back/methods/worker-dms/filter.js @@ -38,10 +38,11 @@ module.exports = Self => { const account = await models.VnUser.findById(userId); const stmt = new ParameterizedSQL( `SELECT d.id, d.id dmsFk - FROM workerDocument wd - JOIN dms d ON d.id = wd.document + FROM workerDms wd + JOIN dms d ON d.id = wd.dmsFk JOIN dmsType dt ON dt.id = d.dmsTypeFk - LEFT JOIN account.roleRole rr ON rr.inheritsFrom = dt.readRoleFk AND rr.role = ? + LEFT JOIN account.roleRole rr ON rr.inheritsFrom = dt.readRoleFk + AND rr.role = ? `, [account.roleFk] ); const yourOwnDms = {and: [{isReadableByWorker: true}, {worker: userId}]}; diff --git a/modules/worker/back/models/worker-dms.json b/modules/worker/back/models/worker-dms.json index a5c0f30b2..ef5684025 100644 --- a/modules/worker/back/models/worker-dms.json +++ b/modules/worker/back/models/worker-dms.json @@ -6,7 +6,7 @@ }, "options": { "mysql": { - "table": "workerDocument" + "table": "workerDms" } }, "properties": { @@ -16,17 +16,11 @@ }, "dmsFk": { "type": "number", - "required": true, - "mysql": { - "columnName": "document" - } + "required": true }, "workerFk": { "type": "number", - "required": true, - "mysql": { - "columnName": "worker" - } + "required": true }, "isReadableByWorker": { "type": "boolean" diff --git a/myt.config.yml b/myt.config.yml index ffa4188b2..1a0a138f0 100755 --- a/myt.config.yml +++ b/myt.config.yml @@ -375,7 +375,7 @@ localFixtures: - workerBosses - workerBusinessType - workerConfig - - workerDocument + - workerDms - workerLog - workerMana - workerManaExcluded From 0feb44e404307638223a753e442dd7cd13e3110e Mon Sep 17 00:00:00 2001 From: ivanm Date: Wed, 11 Sep 2024 15:07:37 +0200 Subject: [PATCH 080/123] refactor: refs #7923 Delete Logiflora functions --- db/routines/edi/events/floramondo.sql | 8 - .../procedures/floramondo_offerRefresh.sql | 522 ------------------ .../vn/functions/entry_getForLogiflora.sql | 64 --- .../vn/functions/travel_getForLogiflora.sql | 52 -- 4 files changed, 646 deletions(-) delete mode 100644 db/routines/edi/events/floramondo.sql delete mode 100644 db/routines/edi/procedures/floramondo_offerRefresh.sql delete mode 100644 db/routines/vn/functions/entry_getForLogiflora.sql delete mode 100644 db/routines/vn/functions/travel_getForLogiflora.sql diff --git a/db/routines/edi/events/floramondo.sql b/db/routines/edi/events/floramondo.sql deleted file mode 100644 index 0a38f3537..000000000 --- a/db/routines/edi/events/floramondo.sql +++ /dev/null @@ -1,8 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `edi`.`floramondo` - ON SCHEDULE EVERY 6 MINUTE - STARTS '2022-01-28 09:52:45.000' - ON COMPLETION NOT PRESERVE - DISABLE -DO CALL edi.floramondo_offerRefresh()$$ -DELIMITER ; diff --git a/db/routines/edi/procedures/floramondo_offerRefresh.sql b/db/routines/edi/procedures/floramondo_offerRefresh.sql deleted file mode 100644 index 18d3f8b7e..000000000 --- a/db/routines/edi/procedures/floramondo_offerRefresh.sql +++ /dev/null @@ -1,522 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenseFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packagingFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 'packing', - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); -END$$ -DELIMITER ; diff --git a/db/routines/vn/functions/entry_getForLogiflora.sql b/db/routines/vn/functions/entry_getForLogiflora.sql deleted file mode 100644 index 57e787afa..000000000 --- a/db/routines/vn/functions/entry_getForLogiflora.sql +++ /dev/null @@ -1,64 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) - RETURNS int(11) - NOT DETERMINISTIC - READS SQL DATA -BEGIN - - /** - * Devuelve una entrada para Logiflora. Si no existe la crea. - * - * @param vLanded Fecha de llegada al almacén - * @param vWarehouseFk Identificador de vn.warehouse - */ - - DECLARE vTravelFk INT; - DECLARE vEntryFk INT; - DECLARE previousEntryFk INT; - - SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk); - - IF vLanded THEN - - SELECT IFNULL(MAX(id),0) INTO vEntryFk - FROM vn.entry - WHERE travelFk = vTravelFk - AND isRaid; - - IF NOT vEntryFk THEN - - INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid) - SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE - FROM vn.supplier s - JOIN vn.company c ON c.code = 'VNL' - JOIN vn.currency cu ON cu.code = 'EUR' - WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk - FROM vn.entry - WHERE travelFk = vTravelFk; - - END IF; - - END IF; - - SELECT entryFk INTO previousEntryFk - FROM edi.warehouseFloramondo wf - WHERE wf.warehouseFk = vWarehouseFk; - - IF IFNULL(previousEntryFk,0) != vEntryFk THEN - - UPDATE buy b - SET b.printedStickers = 0 - WHERE entryFk = previousEntryFk; - - DELETE FROM buy WHERE entryFk = previousEntryFk; - - DELETE FROM entry WHERE id = previousEntryFk; - - END IF; - - RETURN vEntryFk; - -END$$ -DELIMITER ; diff --git a/db/routines/vn/functions/travel_getForLogiflora.sql b/db/routines/vn/functions/travel_getForLogiflora.sql deleted file mode 100644 index 39c3086b7..000000000 --- a/db/routines/vn/functions/travel_getForLogiflora.sql +++ /dev/null @@ -1,52 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) - RETURNS int(11) - NOT DETERMINISTIC - READS SQL DATA -BEGIN - - /** - * Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén. - * Si no existe lo genera. - * - * @param vLanded Fecha de llegada al almacén - * @param vWarehouseFk Identificador de vn.warehouse - */ - - DECLARE vTravelFk INT; - - IF vLanded THEN - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk - FROM vn.travel tr - JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - WHERE wIn.id = vWarehouseFk - AND wOut.name = 'Holanda' - AND am.name = 'LOGIFLORA' - AND landed = vLanded; - - IF NOT vTravelFk THEN - - INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) - SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id - FROM vn.warehouse wOut - JOIN vn.agencyMode am ON am.name = 'LOGIFLORA' - WHERE wOut.name = 'Holanda'; - - SELECT MAX(tr.id) INTO vTravelFk - FROM vn.travel tr - JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk - WHERE wIn.id = vWarehouseFk - AND wOut.name = 'Holanda' - AND landed = vLanded; - END IF; - - END IF; - - RETURN vTravelFk; - -END$$ -DELIMITER ; From 6075ec6518d919ab7f31075b975d9431a94dac95 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 12 Sep 2024 09:06:03 +0200 Subject: [PATCH 081/123] feat: refs #7562 Requested changes --- .../11113-bronzeDendro/00-firstScript.sql | 36 +++++++------------ 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/db/versions/11113-bronzeDendro/00-firstScript.sql b/db/versions/11113-bronzeDendro/00-firstScript.sql index 98ac69966..63db65378 100644 --- a/db/versions/11113-bronzeDendro/00-firstScript.sql +++ b/db/versions/11113-bronzeDendro/00-firstScript.sql @@ -1,26 +1,16 @@ -ALTER TABLE util.config - ADD COLUMN dateRegex varchar(255) NULL COMMENT 'Expresión regular para obtener las fechas.', - ADD deprecatedMarkRegex varchar(255) NULL COMMENT 'Expresión regular para obtener los objetos deprecados.', - ADD daysKeepDeprecatedObjects int(11) unsigned NULL COMMENT 'Número de días que se mantendrán los objetos deprecados.'; - -UPDATE IGNORE util.config - SET dateRegex = '[0-9]{4}-[0-9]{2}-[0-9]{2}', - deprecatedMarkRegex = '__$', - daysKeepDeprecatedObjects = 60; - ALTER TABLE IF EXISTS `vn`.`payrollWorker` - MODIFY COLUMN IF EXISTS `nss__` varchar(23) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `codpuesto__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `codcontrato__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `FAntiguedad__` date NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `grupotarifa__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `codcategoria__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `ContratoTemporal__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-03-15 refs #6738'; + MODIFY COLUMN IF EXISTS `nss__` varchar(23) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `codpuesto__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `codcontrato__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `FAntiguedad__` date NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `grupotarifa__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `codcategoria__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `ContratoTemporal__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-03-15'; ALTER TABLE IF EXISTS `vn`.`payrollWorkCenter` - MODIFY COLUMN IF EXISTS `Centro__` varchar(255) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `nss_cotizacion__` varchar(15) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `domicilio__` varchar(255) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `poblacion__` varchar(45) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `cp__` varchar(5) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738', - MODIFY COLUMN IF EXISTS `empresa_id__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15 refs #6738'; + MODIFY COLUMN IF EXISTS `Centro__` varchar(255) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `nss_cotizacion__` varchar(15) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `domicilio__` varchar(255) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `poblacion__` varchar(45) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `cp__` varchar(5) NOT NULL COMMENT '@deprecated 2024-03-15', + MODIFY COLUMN IF EXISTS `empresa_id__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15'; From f1f10d1367b79c62709ca7ee1ec3d9d521f7f6e2 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 12 Sep 2024 09:15:07 +0200 Subject: [PATCH 082/123] refactor: refs #7828 wip --- .../11227-maroonEucalyptus/00-firstScript.sql | 3 ++ .../worker-time-control-mail/getWeeklyMail.js | 34 +++++++++++++++++++ .../back/models/worker-time-control-mail.js | 1 + .../back/models/worker-time-control-mail.json | 18 +++++----- 4 files changed, 47 insertions(+), 9 deletions(-) create mode 100644 db/versions/11227-maroonEucalyptus/00-firstScript.sql create mode 100644 modules/worker/back/methods/worker-time-control-mail/getWeeklyMail.js diff --git a/db/versions/11227-maroonEucalyptus/00-firstScript.sql b/db/versions/11227-maroonEucalyptus/00-firstScript.sql new file mode 100644 index 000000000..bd4a0b681 --- /dev/null +++ b/db/versions/11227-maroonEucalyptus/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) + VALUES ('WorkerTimeControlMail', 'getWeeklyMail', 'READ', 'ALLOW', 'ROLE', '$owner'); diff --git a/modules/worker/back/methods/worker-time-control-mail/getWeeklyMail.js b/modules/worker/back/methods/worker-time-control-mail/getWeeklyMail.js new file mode 100644 index 000000000..e2253889f --- /dev/null +++ b/modules/worker/back/methods/worker-time-control-mail/getWeeklyMail.js @@ -0,0 +1,34 @@ +module.exports = Self => { + Self.remoteMethod('getWeeklyMail', { + description: 'Check an email inbox and process it', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + description: 'workerFk', + required: true, + http: {source: 'path'} + }, { + arg: 'week', + type: 'number', + required: true + }, { + arg: 'year', + type: 'number', + required: true + }], + returns: + { + type: 'Object', + root: true + }, + http: { + path: `/:id/getWeeklyMail`, + verb: 'GET' + } + }); + + Self.getWeeklyMail = async(workerFk, week, year) => { + return Self.findOne({where: {workerFk, week, year}}); + }; +}; diff --git a/modules/worker/back/models/worker-time-control-mail.js b/modules/worker/back/models/worker-time-control-mail.js index 36f3851b6..e0d385fd0 100644 --- a/modules/worker/back/models/worker-time-control-mail.js +++ b/modules/worker/back/models/worker-time-control-mail.js @@ -1,3 +1,4 @@ module.exports = Self => { require('../methods/worker-time-control-mail/checkInbox')(Self); + require('../methods/worker-time-control-mail/getWeeklyMail')(Self); }; diff --git a/modules/worker/back/models/worker-time-control-mail.json b/modules/worker/back/models/worker-time-control-mail.json index 87eae9217..285c0a7e5 100644 --- a/modules/worker/back/models/worker-time-control-mail.json +++ b/modules/worker/back/models/worker-time-control-mail.json @@ -33,12 +33,12 @@ "type": "number" } }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "employee", - "permission": "ALLOW" - } - ] -} + "relations": { + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "workerFk" + } + }, + "acls": [] +} \ No newline at end of file From 74fafdf330af4ef25e5db58008a528841160f251 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 12 Sep 2024 10:27:18 +0200 Subject: [PATCH 083/123] fix: refs #7828 filter mail access --- .../00-addWorkerTimeControlMailAcl.sql | 4 + .../11227-maroonEucalyptus/00-firstScript.sql | 3 - .../worker-time-control-mail/getWeeklyMail.js | 34 --------- .../back/models/worker-time-control-mail.js | 1 - .../back/models/worker-time-control-mail.json | 10 +-- modules/worker/back/models/worker.json | 73 ++++--------------- 6 files changed, 18 insertions(+), 107 deletions(-) create mode 100644 db/versions/11227-maroonEucalyptus/00-addWorkerTimeControlMailAcl.sql delete mode 100644 db/versions/11227-maroonEucalyptus/00-firstScript.sql delete mode 100644 modules/worker/back/methods/worker-time-control-mail/getWeeklyMail.js diff --git a/db/versions/11227-maroonEucalyptus/00-addWorkerTimeControlMailAcl.sql b/db/versions/11227-maroonEucalyptus/00-addWorkerTimeControlMailAcl.sql new file mode 100644 index 000000000..330dcb839 --- /dev/null +++ b/db/versions/11227-maroonEucalyptus/00-addWorkerTimeControlMailAcl.sql @@ -0,0 +1,4 @@ +-- Place your SQL code here +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) + VALUES ('WorkerTimeControlMail', 'count', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Worker', '__get__mail', 'READ', 'ALLOW', 'ROLE', 'hr'); diff --git a/db/versions/11227-maroonEucalyptus/00-firstScript.sql b/db/versions/11227-maroonEucalyptus/00-firstScript.sql deleted file mode 100644 index bd4a0b681..000000000 --- a/db/versions/11227-maroonEucalyptus/00-firstScript.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Place your SQL code here -INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) - VALUES ('WorkerTimeControlMail', 'getWeeklyMail', 'READ', 'ALLOW', 'ROLE', '$owner'); diff --git a/modules/worker/back/methods/worker-time-control-mail/getWeeklyMail.js b/modules/worker/back/methods/worker-time-control-mail/getWeeklyMail.js deleted file mode 100644 index e2253889f..000000000 --- a/modules/worker/back/methods/worker-time-control-mail/getWeeklyMail.js +++ /dev/null @@ -1,34 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('getWeeklyMail', { - description: 'Check an email inbox and process it', - accessType: 'READ', - accepts: [{ - arg: 'id', - type: 'number', - description: 'workerFk', - required: true, - http: {source: 'path'} - }, { - arg: 'week', - type: 'number', - required: true - }, { - arg: 'year', - type: 'number', - required: true - }], - returns: - { - type: 'Object', - root: true - }, - http: { - path: `/:id/getWeeklyMail`, - verb: 'GET' - } - }); - - Self.getWeeklyMail = async(workerFk, week, year) => { - return Self.findOne({where: {workerFk, week, year}}); - }; -}; diff --git a/modules/worker/back/models/worker-time-control-mail.js b/modules/worker/back/models/worker-time-control-mail.js index e0d385fd0..36f3851b6 100644 --- a/modules/worker/back/models/worker-time-control-mail.js +++ b/modules/worker/back/models/worker-time-control-mail.js @@ -1,4 +1,3 @@ module.exports = Self => { require('../methods/worker-time-control-mail/checkInbox')(Self); - require('../methods/worker-time-control-mail/getWeeklyMail')(Self); }; diff --git a/modules/worker/back/models/worker-time-control-mail.json b/modules/worker/back/models/worker-time-control-mail.json index 285c0a7e5..192178c2d 100644 --- a/modules/worker/back/models/worker-time-control-mail.json +++ b/modules/worker/back/models/worker-time-control-mail.json @@ -32,13 +32,5 @@ "sendedCounter": { "type": "number" } - }, - "relations": { - "user": { - "type": "belongsTo", - "model": "VnUser", - "foreignKey": "workerFk" - } - }, - "acls": [] + } } \ No newline at end of file diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 82cd1cc2d..502c192c6 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -116,11 +116,6 @@ "model": "Locker", "foreignKey": "workerFk" }, - "medicalReview": { - "type": "hasMany", - "model": "MedicalReview", - "foreignKey": "workerFk" - }, "incomes": { "type": "hasMany", "model": "WorkerIncome", @@ -130,6 +125,11 @@ "type": "hasMany", "model": "TrainingCourse", "foreignKey": "workerFk" + }, + "mail": { + "type": "hasMany", + "model": "WorkerTimeControlMail", + "foreignKey": "workerFk" } }, "acls": [ @@ -139,60 +139,13 @@ "permission": "ALLOW", "principalType": "ROLE", "principalId": "$owner" + }, + { + "property": "__get__mail", + "accessType": "READ", + "permission": "ALLOW", + "principalType": "ROLE", + "principalId": "$owner" } - ], - "scopes": { - "descriptor": { - "fields": [ - "id", - "phone" - ], - "include": [ - { - "relation": "user", - "scope": { - "fields": [ - "name", - "nickname" - ], - "include": { - "relation": "emailUser", - "scope": { - "fields": [ - "email" - ] - } - } - } - }, - { - "relation": "department", - "scope": { - "fields": [ - "departmentFk" - ], - "include": [ - { - "relation": "department", - "scope": { - "fields": [ - "id", - "name" - ] - } - } - ] - } - }, - { - "relation": "sip", - "scope": { - "fields": [ - "extension" - ] - } - } - ] - } - } + ] } \ No newline at end of file From b2bc095caa10a288896e60b4838c51a54723ce14 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 12 Sep 2024 10:28:29 +0200 Subject: [PATCH 084/123] fix: refs #7828 rollback --- modules/worker/back/models/worker.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 502c192c6..67eb5cab8 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -116,6 +116,11 @@ "model": "Locker", "foreignKey": "workerFk" }, + "medicalReview": { + "type": "hasMany", + "model": "MedicalReview", + "foreignKey": "workerFk" + }, "incomes": { "type": "hasMany", "model": "WorkerIncome", From edccd95fa1121ee9ffd264d3599e3514040e264d Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 12 Sep 2024 10:29:03 +0200 Subject: [PATCH 085/123] fix: refs #7828 rollback --- modules/worker/back/models/worker.json | 56 +++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 67eb5cab8..21c5bd10f 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -152,5 +152,59 @@ "principalType": "ROLE", "principalId": "$owner" } - ] + ], + "scopes": { + "descriptor": { + "fields": [ + "id", + "phone" + ], + "include": [ + { + "relation": "user", + "scope": { + "fields": [ + "name", + "nickname" + ], + "include": { + "relation": "emailUser", + "scope": { + "fields": [ + "email" + ] + } + } + } + }, + { + "relation": "department", + "scope": { + "fields": [ + "departmentFk" + ], + "include": [ + { + "relation": "department", + "scope": { + "fields": [ + "id", + "name" + ] + } + } + ] + } + }, + { + "relation": "sip", + "scope": { + "fields": [ + "extension" + ] + } + } + ] + } + } } \ No newline at end of file From b6cba2325aeefa88e5c50fd271c0beecfae43950 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 12 Sep 2024 11:02:41 +0200 Subject: [PATCH 086/123] feat: refs #7562 myt version increased to 1.6.10 --- package.json | 2 +- pnpm-lock.yaml | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 1d3b9d253..d50631eb7 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ "@babel/register": "^7.7.7", "@commitlint/cli": "^19.2.1", "@commitlint/config-conventional": "^19.1.0", - "@verdnatura/myt": "^1.6.9", + "@verdnatura/myt": "^1.6.10", "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 b4030d779..458ce647c 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.9 - version: 1.6.9 + specifier: ^1.6.10 + version: 1.6.10 angular-mocks: specifier: ^1.7.9 version: 1.8.3 @@ -2846,8 +2846,8 @@ packages: dev: false optional: true - /@verdnatura/myt@1.6.9: - resolution: {integrity: sha512-29IauYra9igfdPWwV4+pVV/tBXvIg0fkVHEpSz8Zz3G3lRtzm286FN2Kv6hZkxmD/F1n52O37jN9WLiLHDTW1Q==} + /@verdnatura/myt@1.6.10: + resolution: {integrity: sha512-fih/TFll5Sn/SxxafUmYh6CW0Qwpck8PpQ63/CKm4ya8rz8gYPq0THM2B5N8yEJ3PiolMg0wrWWas9j+taAh6w==} hasBin: true dependencies: '@sqltools/formatter': 1.2.5 @@ -3306,6 +3306,7 @@ packages: /are-we-there-yet@1.1.7: resolution: {integrity: sha512-nxwy40TuMiUGqMyRHgCSWZ9FM4VAoRP4xUYSTv5ImRog+h9yISPbVH7H8fASCIzYn9wlEv4zvFL7uKDMCFQm3g==} + deprecated: This package is no longer supported. dependencies: delegates: 1.0.0 readable-stream: 2.3.8 @@ -6593,6 +6594,7 @@ packages: /gauge@2.7.4: resolution: {integrity: sha512-14x4kjc6lkD3ltw589k0NrPD6cCNTD6CWoVUNpB85+DrtONoZn+Rug6xZU5RvSC4+TZPxA5AnBibQYAvZn41Hg==} + deprecated: This package is no longer supported. dependencies: aproba: 1.2.0 console-control-strings: 1.1.0 @@ -10814,6 +10816,7 @@ packages: /npmlog@4.1.2: resolution: {integrity: sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==} + deprecated: This package is no longer supported. dependencies: are-we-there-yet: 1.1.7 console-control-strings: 1.1.0 @@ -11055,6 +11058,7 @@ packages: /osenv@0.1.5: resolution: {integrity: sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==} + deprecated: This package is no longer supported. dependencies: os-homedir: 1.0.2 os-tmpdir: 1.0.2 From 6b6eea78dadcc1d94d4ba3725ee5ba243d4ca599 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 12 Sep 2024 13:21:01 +0200 Subject: [PATCH 087/123] feat: refs #7562 myt version increased to 1.6.11 --- package.json | 2 +- pnpm-lock.yaml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index d50631eb7..2ae7c3764 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ "@babel/register": "^7.7.7", "@commitlint/cli": "^19.2.1", "@commitlint/config-conventional": "^19.1.0", - "@verdnatura/myt": "^1.6.10", + "@verdnatura/myt": "^1.6.11", "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 458ce647c..e2480cf4a 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.10 - version: 1.6.10 + specifier: ^1.6.11 + version: 1.6.11 angular-mocks: specifier: ^1.7.9 version: 1.8.3 @@ -2846,8 +2846,8 @@ packages: dev: false optional: true - /@verdnatura/myt@1.6.10: - resolution: {integrity: sha512-fih/TFll5Sn/SxxafUmYh6CW0Qwpck8PpQ63/CKm4ya8rz8gYPq0THM2B5N8yEJ3PiolMg0wrWWas9j+taAh6w==} + /@verdnatura/myt@1.6.11: + resolution: {integrity: sha512-uqdbSJSznBBzAoRkvBt600nUMEPL1PJ2v73eWMZbaoGUMiZiNAehYjs4gIrObP1cxC85JOx97XoLpG0BzPsaig==} hasBin: true dependencies: '@sqltools/formatter': 1.2.5 From 1abf6a14f95be25297e3b52e1610cf916cf81eb9 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 12 Sep 2024 13:26:09 +0200 Subject: [PATCH 088/123] fix: workerDms filter workerFk --- modules/worker/back/methods/worker-dms/filter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker-dms/filter.js b/modules/worker/back/methods/worker-dms/filter.js index 0d13276b1..597084e60 100644 --- a/modules/worker/back/methods/worker-dms/filter.js +++ b/modules/worker/back/methods/worker-dms/filter.js @@ -50,7 +50,7 @@ module.exports = Self => { or: [ {and: [ {isReadableByWorker: true}, - {worker: userId} + {'wd.workerFk': userId} ]}, { role: { From b1027f454b3f056892f4111441be6ab2807acafa Mon Sep 17 00:00:00 2001 From: Pako Date: Thu, 12 Sep 2024 14:13:17 +0200 Subject: [PATCH 089/123] locallyTested --- db/routines/vn/procedures/collection_new.sql | 3 ++- .../vn/procedures/productionControl.sql | 21 +++++++++++++++---- .../11229-salmonAsparagus/00-firstScript.sql | 3 +++ 3 files changed, 22 insertions(+), 5 deletions(-) create mode 100644 db/versions/11229-salmonAsparagus/00-firstScript.sql diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index a5a9a61c7..53f5500a0 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -167,7 +167,8 @@ BEGIN OR LENGTH(pb.problem) OR pb.lines > vLinesLimit OR pb.m3 > vVolumeLimit - OR sub.maxSize > vSizeLimit; + OR sub.maxSize > vSizeLimit + OR pb.hasPlantTray; END IF; -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index e5323e84e..101a0f058 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -211,8 +211,6 @@ proc: BEGIN salesInParkingCount INT DEFAULT 0) ENGINE = MEMORY; - -- Insertamos todos los tickets que tienen productos parkineados - -- en sectores de previa, segun el sector CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock (PRIMARY KEY(itemFk, sectorFk)) ENGINE = MEMORY @@ -245,7 +243,6 @@ proc: BEGIN AND s.quantity > 0 GROUP BY pb.ticketFk; - -- Se calcula la cantidad de productos que estan ya preparados porque su saleGroup está aparcado UPDATE tmp.ticketWithPrevia twp JOIN ( SELECT pb.ticketFk, COUNT(DISTINCT s.id) salesInParkingCount @@ -259,12 +256,28 @@ proc: BEGIN ) sub ON twp.ticketFk = sub.ticketFk SET twp.salesInParkingCount = sub.salesInParkingCount; - -- Marcamos como pendientes aquellos que no coinciden las cantidades UPDATE tmp.productionBuffer pb JOIN tmp.ticketWithPrevia twp ON twp.ticketFk = pb.ticketFk SET pb.previousWithoutParking = TRUE WHERE twp.salesCount > twp.salesInParkingCount; + -- hasPlantTray + ALTER TABLE tmp.productionBuffer + ADD hasPlantTray BOOL DEFAULT FALSE; + + UPDATE tmp.productionBuffer pb + JOIN sale s ON s.ticketFk = pb.ticketFk + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN 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 hasPlantTray = TRUE + WHERE ic.code = 'plant' + AND p.`depth` >= pc.minPlantTrayLength; + DROP TEMPORARY TABLE tmp.productionTicket, tmp.ticket, diff --git a/db/versions/11229-salmonAsparagus/00-firstScript.sql b/db/versions/11229-salmonAsparagus/00-firstScript.sql new file mode 100644 index 000000000..d590ed958 --- /dev/null +++ b/db/versions/11229-salmonAsparagus/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE vn.productionConfig ADD minPlantTrayLength INT DEFAULT 53 NOT NULL +COMMENT 'minimum length for plant tray restriction. Avoid to make collection of the ticket with this kind of item'; From a0bfc2059530cee109a52d5a7e512af722b44ea8 Mon Sep 17 00:00:00 2001 From: Pako Date: Thu, 12 Sep 2024 14:34:19 +0200 Subject: [PATCH 090/123] revision --- db/routines/vn/procedures/productionControl.sql | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 101a0f058..842a306b4 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -266,14 +266,14 @@ proc: BEGIN ADD hasPlantTray BOOL DEFAULT FALSE; UPDATE tmp.productionBuffer pb - JOIN sale s ON s.ticketFk = pb.ticketFk - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN 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 + JOIN sale s ON s.ticketFk = pb.ticketFk + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN 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 hasPlantTray = TRUE WHERE ic.code = 'plant' AND p.`depth` >= pc.minPlantTrayLength; From 3d598a4ec4afcc57d5edd309f7479aa88e884f99 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 12 Sep 2024 14:57:19 +0200 Subject: [PATCH 091/123] fix: refs #7952 Version --- db/versions/11224-whiteMastic/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db/versions/11224-whiteMastic/00-firstScript.sql b/db/versions/11224-whiteMastic/00-firstScript.sql index 52267cd91..de74dfc55 100644 --- a/db/versions/11224-whiteMastic/00-firstScript.sql +++ b/db/versions/11224-whiteMastic/00-firstScript.sql @@ -1,2 +1,3 @@ +ALTER TABLE vn.creditInsurance DROP FOREIGN KEY CreditInsurance_Fk1; ALTER TABLE vn.creditInsurance CHANGE creditClassification creditClassification__ int(11) DEFAULT NULL COMMENT '@deprecated 2024-09-11'; From 93e71638581a6d9067f09b36057e551d7b621b87 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 12 Sep 2024 17:09:27 +0200 Subject: [PATCH 092/123] feat: refs #6868 refs# 6868 handleUser --- .../worker/back/methods/device/handle-user.js | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/modules/worker/back/methods/device/handle-user.js b/modules/worker/back/methods/device/handle-user.js index 02b505e39..87aec378e 100644 --- a/modules/worker/back/methods/device/handle-user.js +++ b/modules/worker/back/methods/device/handle-user.js @@ -59,8 +59,12 @@ module.exports = Self => { } }, myOptions); - if (!isUserInOperator) - await models.Operator.create({'workerFk': user.id}); + if (!isUserInOperator) { + await models.Operator.create({ + 'workerFk': user.id, + 'isOnReservationMode': false + }); + } const whereCondition = deviceId ? {id: deviceId} : {android_id: androidId}; const serialNumber = @@ -103,12 +107,21 @@ module.exports = Self => { const getVersion = await models.MobileAppVersionControl.getVersion(ctx, nameApp); const combinedResult = { + ...getDataOperator.toObject(), + ...getDataUser.toObject(), + ...getVersion, + message: vMessage, + serialNumber, + }; + + const combinedResult2 = { ...getDataOperator.__data, ...getDataUser.__data, ...getVersion, message: vMessage, serialNumber, }; + console.log('conbinedResult2', combinedResult2); return combinedResult; }; }; From 2d4e6670099ef4f2ab8a38dd09923edf9e22385b Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 13 Sep 2024 07:02:30 +0200 Subject: [PATCH 093/123] feat: refs #6868 refs# 6868 handleUser --- modules/worker/back/methods/device/handle-user.js | 9 --------- .../worker/back/methods/device/specs/handle-user.spec.js | 2 +- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/modules/worker/back/methods/device/handle-user.js b/modules/worker/back/methods/device/handle-user.js index 87aec378e..ac4ff2704 100644 --- a/modules/worker/back/methods/device/handle-user.js +++ b/modules/worker/back/methods/device/handle-user.js @@ -113,15 +113,6 @@ module.exports = Self => { message: vMessage, serialNumber, }; - - const combinedResult2 = { - ...getDataOperator.__data, - ...getDataUser.__data, - ...getVersion, - message: vMessage, - serialNumber, - }; - console.log('conbinedResult2', combinedResult2); return combinedResult; }; }; diff --git a/modules/worker/back/methods/device/specs/handle-user.spec.js b/modules/worker/back/methods/device/specs/handle-user.spec.js index c4cd37e33..37f76b765 100644 --- a/modules/worker/back/methods/device/specs/handle-user.spec.js +++ b/modules/worker/back/methods/device/specs/handle-user.spec.js @@ -3,7 +3,7 @@ const {models} = require('vn-loopback/server/server'); describe('Device handleUser()', () => { const ctx = {req: {accessToken: {userId: 9}}}; - it('should return data from user', async() => { + fit('should return data from user', async() => { const androidId = 'androidid11234567890'; const deviceId = 1; const nameApp = 'warehouse'; From e80fe1d0dc8a5189652a1c44ec0985e0c1afd2da Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 13 Sep 2024 07:10:47 +0200 Subject: [PATCH 094/123] feat: refs #6868 refs# 6868 handleUser --- modules/worker/back/methods/device/specs/handle-user.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/device/specs/handle-user.spec.js b/modules/worker/back/methods/device/specs/handle-user.spec.js index 37f76b765..c4cd37e33 100644 --- a/modules/worker/back/methods/device/specs/handle-user.spec.js +++ b/modules/worker/back/methods/device/specs/handle-user.spec.js @@ -3,7 +3,7 @@ const {models} = require('vn-loopback/server/server'); describe('Device handleUser()', () => { const ctx = {req: {accessToken: {userId: 9}}}; - fit('should return data from user', async() => { + it('should return data from user', async() => { const androidId = 'androidid11234567890'; const deviceId = 1; const nameApp = 'warehouse'; From ebbc1431522cd2675915f835c7e2ea74a4d357f1 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 13 Sep 2024 08:29:41 +0200 Subject: [PATCH 095/123] fix: sql wagonTypeTray --- db/versions/11088-bronzeAspidistra/00-firstScript.sql | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/db/versions/11088-bronzeAspidistra/00-firstScript.sql b/db/versions/11088-bronzeAspidistra/00-firstScript.sql index 11effc5d2..5de386df1 100644 --- a/db/versions/11088-bronzeAspidistra/00-firstScript.sql +++ b/db/versions/11088-bronzeAspidistra/00-firstScript.sql @@ -1,12 +1,10 @@ -DROP TABLE IF EXISTS vn.wagonTypeTray; - CREATE OR REPLACE TABLE vn.wagonTypeTray ( id INT UNSIGNED auto_increment NULL, wagonTypeFk int(11) unsigned NULL, height INT UNSIGNED NULL, wagonTypeColorFk int(11) unsigned NULL, CONSTRAINT wagonTypeTray_pk PRIMARY KEY (id), - CONSTRAINT wagonTypeTray_wagonType_FK FOREIGN KEY (wagonTypeFk) REFERENCES vn.wagonType(id), + CONSTRAINT wagonTypeTray_wagonType_FK FOREIGN KEY (wagonTypeFk) REFERENCES vn.wagonType(id) ON DELETE CASCADE ON UPDATE RESTRICT, CONSTRAINT wagonTypeTray_wagonTypeColor_FK FOREIGN KEY (wagonTypeColorFk) REFERENCES vn.wagonTypeColor(id) ) ENGINE=InnoDB @@ -17,5 +15,3 @@ ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultHeight INT UNSIGNED DEFAULT ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultTrayColorFk int(11) unsigned NULL COMMENT 'Default color for a base tray'; ALTER TABLE vn.wagonConfig ADD CONSTRAINT wagonConfig_wagonTypeColor_FK FOREIGN KEY (defaultTrayColorFk) REFERENCES vn.wagonTypeColor(id); -ALTER TABLE vn.wagonTypeTray DROP FOREIGN KEY wagonTypeTray_wagonType_FK; -ALTER TABLE vn.wagonTypeTray ADD CONSTRAINT wagonTypeTray_wagonType_FK FOREIGN KEY (wagonTypeFk) REFERENCES vn.wagonType(id) ON DELETE CASCADE ON UPDATE RESTRICT; From bbb3889154253962b6e59f102190812fb748df08 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 13 Sep 2024 08:54:03 +0200 Subject: [PATCH 096/123] fix: sql wagonTypeTray --- db/versions/11088-bronzeAspidistra/00-firstScript.sql | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/db/versions/11088-bronzeAspidistra/00-firstScript.sql b/db/versions/11088-bronzeAspidistra/00-firstScript.sql index 5de386df1..751bbf7e3 100644 --- a/db/versions/11088-bronzeAspidistra/00-firstScript.sql +++ b/db/versions/11088-bronzeAspidistra/00-firstScript.sql @@ -1,7 +1,9 @@ +ALTER TABLE vn.collectionWagonTicket DROP FOREIGN KEY IF EXISTS collectionWagonTicket_tray; +ALTER TABLE vn.wagonConfig DROP FOREIGN KEY IF EXISTS wagonConfig_wagonTypeColor_FK; CREATE OR REPLACE TABLE vn.wagonTypeTray ( - id INT UNSIGNED auto_increment NULL, - wagonTypeFk int(11) unsigned NULL, - height INT UNSIGNED NULL, + id INT(11) UNSIGNED, + wagonTypeFk INT(11) unsigned NULL, + height INT(11) UNSIGNED NULL, wagonTypeColorFk int(11) unsigned NULL, CONSTRAINT wagonTypeTray_pk PRIMARY KEY (id), CONSTRAINT wagonTypeTray_wagonType_FK FOREIGN KEY (wagonTypeFk) REFERENCES vn.wagonType(id) ON DELETE CASCADE ON UPDATE RESTRICT, @@ -14,4 +16,4 @@ COLLATE=utf8mb3_unicode_ci; ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultHeight INT UNSIGNED DEFAULT 0 NULL COMMENT 'Default height in cm for a base tray'; ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultTrayColorFk int(11) unsigned NULL COMMENT 'Default color for a base tray'; ALTER TABLE vn.wagonConfig ADD CONSTRAINT wagonConfig_wagonTypeColor_FK FOREIGN KEY (defaultTrayColorFk) REFERENCES vn.wagonTypeColor(id); - +ALTER TABLE vn.collectionWagonTicket ADD CONSTRAINT collectionWagonTicket_tray FOREIGN KEY (trayFk) REFERENCES vn.wagonTypeTray(id); From f1f0f5920cdd39318e8ca13d93a81729b1401c8c Mon Sep 17 00:00:00 2001 From: Jon Date: Fri, 13 Sep 2024 11:29:05 +0200 Subject: [PATCH 097/123] fix: refs #6346 fixed SQL --- db/versions/11088-bronzeAspidistra/00-firstScript.sql | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/db/versions/11088-bronzeAspidistra/00-firstScript.sql b/db/versions/11088-bronzeAspidistra/00-firstScript.sql index 751bbf7e3..5c56993fd 100644 --- a/db/versions/11088-bronzeAspidistra/00-firstScript.sql +++ b/db/versions/11088-bronzeAspidistra/00-firstScript.sql @@ -1,10 +1,10 @@ ALTER TABLE vn.collectionWagonTicket DROP FOREIGN KEY IF EXISTS collectionWagonTicket_tray; ALTER TABLE vn.wagonConfig DROP FOREIGN KEY IF EXISTS wagonConfig_wagonTypeColor_FK; CREATE OR REPLACE TABLE vn.wagonTypeTray ( - id INT(11) UNSIGNED, - wagonTypeFk INT(11) unsigned NULL, + id INT(11) UNSIGNED auto_increment, + wagonTypeFk INT(11) UNSIGNED NULL, height INT(11) UNSIGNED NULL, - wagonTypeColorFk int(11) unsigned NULL, + wagonTypeColorFk int(11) UNSIGNED NULL, CONSTRAINT wagonTypeTray_pk PRIMARY KEY (id), CONSTRAINT wagonTypeTray_wagonType_FK FOREIGN KEY (wagonTypeFk) REFERENCES vn.wagonType(id) ON DELETE CASCADE ON UPDATE RESTRICT, CONSTRAINT wagonTypeTray_wagonTypeColor_FK FOREIGN KEY (wagonTypeColorFk) REFERENCES vn.wagonTypeColor(id) @@ -14,6 +14,6 @@ DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultHeight INT UNSIGNED DEFAULT 0 NULL COMMENT 'Default height in cm for a base tray'; -ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultTrayColorFk int(11) unsigned NULL COMMENT 'Default color for a base tray'; +ALTER TABLE vn.wagonConfig ADD IF NOT EXISTS defaultTrayColorFk int(11) UNSIGNED NULL COMMENT 'Default color for a base tray'; ALTER TABLE vn.wagonConfig ADD CONSTRAINT wagonConfig_wagonTypeColor_FK FOREIGN KEY (defaultTrayColorFk) REFERENCES vn.wagonTypeColor(id); ALTER TABLE vn.collectionWagonTicket ADD CONSTRAINT collectionWagonTicket_tray FOREIGN KEY (trayFk) REFERENCES vn.wagonTypeTray(id); From 63dde3dd786b4f60c7638c33f4268cbcfd5646a4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 13 Sep 2024 14:13:14 +0200 Subject: [PATCH 098/123] fix: refs #7819 Version --- db/routines/vn2008/views/Articles.sql | 1 - .../11210-greenDendro/02-firstScript.sql | 105 +++++++++--- .../11210-greenDendro/03-firstScript.sql | 156 +++--------------- 3 files changed, 105 insertions(+), 157 deletions(-) diff --git a/db/routines/vn2008/views/Articles.sql b/db/routines/vn2008/views/Articles.sql index 385bf310b..87f1b6d5e 100644 --- a/db/routines/vn2008/views/Articles.sql +++ b/db/routines/vn2008/views/Articles.sql @@ -41,7 +41,6 @@ AS SELECT `i`.`id` AS `Id_Article`, `i`.`hasKgPrice` AS `hasKgPrice`, `i`.`equivalent` AS `Equivalente`, `i`.`isToPrint` AS `Imprimir`, - `i`.`family` AS `Familia__`, `i`.`doPhoto` AS `do_photo`, `i`.`created` AS `odbc_date`, `i`.`isFloramondo` AS `isFloramondo`, diff --git a/db/versions/11210-greenDendro/02-firstScript.sql b/db/versions/11210-greenDendro/02-firstScript.sql index 4cb6bbb02..2603c5df5 100644 --- a/db/versions/11210-greenDendro/02-firstScript.sql +++ b/db/versions/11210-greenDendro/02-firstScript.sql @@ -1,21 +1,84 @@ -DROP TABLE IF EXISTS account.mailClientAccess__; -DROP TABLE IF EXISTS account.mailSenderAccess__; -DROP TABLE IF EXISTS bi.analisis_ventas_familia_evolution__; -DROP TABLE IF EXISTS bi.live_counter__; -DROP TABLE IF EXISTS bi.partitioning_information__; -DROP TABLE IF EXISTS bi.primer_pedido__; -DROP TABLE IF EXISTS bi.tarifa_premisas__; -DROP TABLE IF EXISTS bi.tarifa_warehouse__; -DROP TABLE IF EXISTS bs.compradores__; -DROP TABLE IF EXISTS bs.salesMonthlySnapshot___; -DROP TABLE IF EXISTS bs.salesPerson__; -DROP TABLE IF EXISTS bs.vendedores_evolution__; -DROP TABLE IF EXISTS vn.botanicExport__; -DROP TABLE IF EXISTS vn.claimRma__; -DROP TABLE IF EXISTS vn.coolerPathDetail__; -DROP TABLE IF EXISTS vn.forecastedBalance__; -DROP TABLE IF EXISTS vn.routeLoadWorker__; -DROP TABLE IF EXISTS vn.routeUserPercentage__; -DROP TABLE IF EXISTS vn.ticketSms__; -DROP TABLE IF EXISTS vn.ticketTrackingState__; -DROP TABLE IF EXISTS vn.warehouseAlias__; \ No newline at end of file +ALTER TABLE bi.rutasBoard DROP COLUMN coste_bulto__; +ALTER TABLE bi.rutasBoard DROP COLUMN Dia__; +ALTER TABLE bi.rutasBoard DROP COLUMN km__; +ALTER TABLE bi.rutasBoard DROP COLUMN m3__; +ALTER TABLE bi.rutasBoard DROP COLUMN Matricula__; +ALTER TABLE bi.rutasBoard DROP COLUMN month__; +ALTER TABLE bi.rutasBoard DROP COLUMN Terceros__; +ALTER TABLE bi.rutasBoard DROP COLUMN Tipo__; +ALTER TABLE bi.rutasBoard DROP COLUMN warehouse_id__; +ALTER TABLE bi.rutasBoard DROP COLUMN year__; + +ALTER TABLE bs.clientDied DROP COLUMN Boss__; +ALTER TABLE bs.clientDied DROP COLUMN clientName__; +ALTER TABLE bs.clientDied DROP COLUMN workerCode__; + +ALTER TABLE bs.salesByItemTypeDay DROP COLUMN netSale__; + +ALTER TABLE vn.agency DROP FOREIGN KEY agency_FK; +ALTER TABLE vn.agency DROP COLUMN warehouseAliasFk__; + +ALTER TABLE vn.awbComponent DROP COLUMN dated__; + +ALTER TABLE vn.buy DROP COLUMN containerFk__; + +ALTER TABLE vn.chat DROP COLUMN status__; + +ALTER TABLE vn.claim DROP COLUMN rma__; + +ALTER TABLE vn.client DROP COLUMN clientTypeFk__; +ALTER TABLE vn.client DROP COLUMN hasIncoterms__; + +ALTER TABLE vn.clientType DROP COLUMN id__; + +ALTER TABLE vn.cmr DROP FOREIGN KEY cmr_fk1; +ALTER TABLE vn.cmr DROP COLUMN ticketFk__; + +ALTER TABLE vn.company DROP COLUMN sage200Company__; + +ALTER TABLE vn.country DROP FOREIGN KEY country_FK; +ALTER TABLE vn.country DROP COLUMN politicalCountryFk__; + +ALTER TABLE vn.deliveryNote DROP FOREIGN KEY albaran_FK; +ALTER TABLE vn.deliveryNote DROP COLUMN farmingFk__; + +ALTER TABLE vn.dmsType DROP COLUMN path__; + +ALTER TABLE vn.dua DROP COLUMN awbFk__; + +ALTER TABLE vn.entry DROP COLUMN isBlocked__; + +ALTER TABLE vn.expedition DROP COLUMN itemFk__; + +ALTER TABLE vn.item DROP COLUMN minQuantity__; +ALTER TABLE vn.item DROP COLUMN packingShelve__; + +ALTER TABLE vn.itemType DROP COLUMN compression__; +ALTER TABLE vn.itemType DROP COLUMN density__; +ALTER TABLE vn.itemType DROP COLUMN hasComponents__; +ALTER TABLE vn.itemType DROP COLUMN location__; +ALTER TABLE vn.itemType DROP COLUMN maneuver__; +ALTER TABLE vn.itemType DROP COLUMN profit__; +ALTER TABLE vn.itemType DROP COLUMN target__; +ALTER TABLE vn.itemType DROP COLUMN topMargin__; +ALTER TABLE vn.itemType DROP COLUMN transaction__; +ALTER TABLE vn.itemType DROP FOREIGN KEY warehouseFk5; +ALTER TABLE vn.itemType DROP COLUMN warehouseFk__; + +ALTER TABLE vn.ledgerConfig DROP COLUMN lastBookEntry__; + +ALTER TABLE vn.saleTracking DROP FOREIGN KEY saleTracking_FK_1; +ALTER TABLE vn.saleTracking DROP COLUMN actionFk__; + +ALTER TABLE vn.supplier DROP COLUMN isFarmer__; + +ALTER TABLE vn.supplierAccount DROP COLUMN description__; + +ALTER TABLE vn.ticketRequest DROP COLUMN buyerCode__; + +ALTER TABLE vn.travel DROP COLUMN agencyFk__; + +ALTER TABLE vn.warehouse DROP FOREIGN KEY warehouse_ibfk_2; +ALTER TABLE vn.warehouse DROP COLUMN aliasFk__; + +ALTER TABLE vn.worker DROP COLUMN labelerFk__; diff --git a/db/versions/11210-greenDendro/03-firstScript.sql b/db/versions/11210-greenDendro/03-firstScript.sql index b069d0982..f8157b756 100644 --- a/db/versions/11210-greenDendro/03-firstScript.sql +++ b/db/versions/11210-greenDendro/03-firstScript.sql @@ -1,135 +1,21 @@ -ALTER TABLE bi.rutasBoard DROP COLUMN coste_bulto__; -ALTER TABLE bi.rutasBoard DROP COLUMN Dia__; -ALTER TABLE bi.rutasBoard DROP COLUMN km__; -ALTER TABLE bi.rutasBoard DROP COLUMN m3__; -ALTER TABLE bi.rutasBoard DROP COLUMN Matricula__; -ALTER TABLE bi.rutasBoard DROP COLUMN month__; -ALTER TABLE bi.rutasBoard DROP COLUMN Terceros__; -ALTER TABLE bi.rutasBoard DROP COLUMN Tipo__; -ALTER TABLE bi.rutasBoard DROP COLUMN warehouse_id__; -ALTER TABLE bi.rutasBoard DROP COLUMN year__; - -ALTER TABLE bs.clientDied DROP COLUMN Boss__; -ALTER TABLE bs.clientDied DROP COLUMN clientName__; -ALTER TABLE bs.clientDied DROP COLUMN workerCode__; - -ALTER TABLE bs.salesByItemTypeDay DROP COLUMN netSale__; - -ALTER TABLE vn.agency DROP FOREIGN KEY agency_FK; -ALTER TABLE vn.agency DROP COLUMN warehouseAliasFk__; - -ALTER TABLE vn.awbComponent DROP COLUMN dated__; - -ALTER TABLE vn.buy DROP COLUMN containerFk__; - -ALTER TABLE vn.chat DROP COLUMN status__; - -ALTER TABLE vn.claim DROP COLUMN rma__; - -ALTER TABLE vn.client DROP COLUMN clientTypeFk__; -ALTER TABLE vn.client DROP COLUMN hasIncoterms__; - -ALTER TABLE vn.clientType DROP COLUMN id__; - -ALTER TABLE vn.cmr DROP FOREIGN KEY cmr_fk1; -ALTER TABLE vn.cmr DROP COLUMN ticketFk__; - -ALTER TABLE vn.company DROP COLUMN sage200Company__; - -ALTER TABLE vn.country DROP FOREIGN KEY country_FK; -ALTER TABLE vn.country DROP COLUMN politicalCountryFk__; - -ALTER TABLE vn.deliveryNote DROP FOREIGN KEY albaran_FK; -ALTER TABLE vn.deliveryNote DROP COLUMN farmingFk__; - -ALTER TABLE vn.dmsType DROP COLUMN path__; - -ALTER TABLE vn.dua DROP COLUMN awbFk__; - -ALTER TABLE vn.entry DROP COLUMN isBlocked__; - -ALTER TABLE vn.expedition DROP COLUMN itemFk__; - -ALTER TABLE vn.item DROP COLUMN minQuantity__; -ALTER TABLE vn.item DROP COLUMN packingShelve__; - -ALTER TABLE vn.itemType DROP COLUMN compression__; -ALTER TABLE vn.itemType DROP COLUMN density__; -ALTER TABLE vn.itemType DROP COLUMN hasComponents__; -ALTER TABLE vn.itemType DROP COLUMN location__; -ALTER TABLE vn.itemType DROP COLUMN maneuver__; -ALTER TABLE vn.itemType DROP COLUMN profit__; -ALTER TABLE vn.itemType DROP COLUMN target__; -ALTER TABLE vn.itemType DROP COLUMN topMargin__; -ALTER TABLE vn.itemType DROP COLUMN transaction__; -ALTER TABLE vn.itemType DROP FOREIGN KEY warehouseFk5; -ALTER TABLE vn.itemType DROP COLUMN warehouseFk__; - -ALTER TABLE vn.ledgerConfig DROP COLUMN lastBookEntry__; - -ALTER TABLE vn.saleTracking DROP FOREIGN KEY saleTracking_FK_1; -ALTER TABLE vn.saleTracking DROP COLUMN actionFk__; - -ALTER TABLE vn.supplier DROP COLUMN isFarmer__; - -ALTER TABLE vn.supplierAccount DROP COLUMN description__; - -ALTER TABLE vn.ticketRequest DROP COLUMN buyerCode__; - -ALTER TABLE vn.travel DROP COLUMN agencyFk__; - -ALTER TABLE vn.warehouse DROP FOREIGN KEY warehouse_ibfk_2; -ALTER TABLE vn.warehouse DROP COLUMN aliasFk__; - -ALTER TABLE vn.worker DROP COLUMN labelerFk__; - -CREATE OR REPLACE -ALGORITHM = UNDEFINED VIEW `vn2008`.`Articles` AS -SELECT `i`.`id` AS `Id_Article`, - `i`.`name` AS `Article`, - `i`.`typeFk` AS `tipo_id`, - `i`.`size` AS `Medida`, - `i`.`inkFk` AS `Color`, - `i`.`category` AS `Categoria`, - `i`.`stems` AS `Tallos`, - `i`.`originFk` AS `id_origen`, - `i`.`description` AS `description`, - `i`.`producerFk` AS `producer_id`, - `i`.`intrastatFk` AS `Codintrastat`, - `i`.`box` AS `caja`, - `i`.`expenseFk` AS `expenseFk`, - `i`.`comment` AS `comments`, - `i`.`relevancy` AS `relevancy`, - `i`.`image` AS `Foto`, - `i`.`generic` AS `generic`, - `i`.`density` AS `density`, - `i`.`minPrice` AS `PVP`, - `i`.`hasMinPrice` AS `Min`, - `i`.`isActive` AS `isActive`, - `i`.`longName` AS `longName`, - `i`.`subName` AS `subName`, - `i`.`tag5` AS `tag5`, - `i`.`value5` AS `value5`, - `i`.`tag6` AS `tag6`, - `i`.`value6` AS `value6`, - `i`.`tag7` AS `tag7`, - `i`.`value7` AS `value7`, - `i`.`tag8` AS `tag8`, - `i`.`value8` AS `value8`, - `i`.`tag9` AS `tag9`, - `i`.`value9` AS `value9`, - `i`.`tag10` AS `tag10`, - `i`.`value10` AS `value10`, - `i`.`minimum` AS `minimum`, - `i`.`upToDown` AS `upToDown`, - `i`.`hasKgPrice` AS `hasKgPrice`, - `i`.`equivalent` AS `Equivalente`, - `i`.`isToPrint` AS `Imprimir`, - `i`.`doPhoto` AS `do_photo`, - `i`.`created` AS `odbc_date`, - `i`.`isFloramondo` AS `isFloramondo`, - `i`.`supplyResponseFk` AS `supplyResponseFk`, - `i`.`stemMultiplier` AS `stemMultiplier`, - `i`.`itemPackingTypeFk` AS `itemPackingTypeFk`, - `i`.`packingOut` AS `packingOut` -FROM `vn`.`item` `i`; \ No newline at end of file +DROP TABLE IF EXISTS account.mailClientAccess__; +DROP TABLE IF EXISTS account.mailSenderAccess__; +DROP TABLE IF EXISTS bi.analisis_ventas_familia_evolution__; +DROP TABLE IF EXISTS bi.live_counter__; +DROP TABLE IF EXISTS bi.partitioning_information__; +DROP TABLE IF EXISTS bi.primer_pedido__; +DROP TABLE IF EXISTS bi.tarifa_premisas__; +DROP TABLE IF EXISTS bi.tarifa_warehouse__; +DROP TABLE IF EXISTS bs.compradores__; +DROP TABLE IF EXISTS bs.salesMonthlySnapshot___; +DROP TABLE IF EXISTS bs.salesPerson__; +DROP TABLE IF EXISTS bs.vendedores_evolution__; +DROP TABLE IF EXISTS vn.botanicExport__; +DROP TABLE IF EXISTS vn.claimRma__; +DROP TABLE IF EXISTS vn.coolerPathDetail__; +DROP TABLE IF EXISTS vn.forecastedBalance__; +DROP TABLE IF EXISTS vn.routeLoadWorker__; +DROP TABLE IF EXISTS vn.routeUserPercentage__; +DROP TABLE IF EXISTS vn.ticketSms__; +DROP TABLE IF EXISTS vn.ticketTrackingState__; +DROP TABLE IF EXISTS vn.warehouseAlias__; From cc1cd0563fe1b8cee7bbedf3b827fe881d908d54 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 16 Sep 2024 09:00:46 +0200 Subject: [PATCH 099/123] feat: refs #7404 fixtures and translates --- db/dump/fixtures.before.sql | 2 +- loopback/locale/en.json | 3 +- .../methods/stock-bought/getStockBought.js | 49 +++++++++++-------- 3 files changed, 32 insertions(+), 22 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index ce33b4e48..cd1a470ff 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -183,7 +183,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', 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); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 06538a524..b8835f5f3 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -235,5 +235,6 @@ "Cannot add holidays on this day": "Cannot add holidays on this day", "Cannot send mail": "Cannot send mail", "CONSTRAINT `chkParkingCodeFormat` failed for `vn`.`parking`": "CONSTRAINT `chkParkingCodeFormat` failed for `vn`.`parking`", - "This postcode already exists": "This postcode already exists" + "This postcode already exists": "This postcode already exists", + "This buyer has already made a reservation for this date": "This buyer has already made a reservation for this date" } \ No newline at end of file diff --git a/modules/entry/back/methods/stock-bought/getStockBought.js b/modules/entry/back/methods/stock-bought/getStockBought.js index da194ed80..0f67d878d 100644 --- a/modules/entry/back/methods/stock-bought/getStockBought.js +++ b/modules/entry/back/methods/stock-bought/getStockBought.js @@ -3,6 +3,11 @@ module.exports = Self => { description: 'Returns the stock bought for a given date', accessType: 'READ', accepts: [{ + arg: 'workerFk', + type: 'number', + description: 'The id for a buyer', + }, + { arg: 'dated', type: 'date', description: 'The date to filter', @@ -18,7 +23,7 @@ module.exports = Self => { } }); - Self.getStockBought = async(dated = Date.vnNew()) => { + Self.getStockBought = async(workerFk, dated = Date.vnNew()) => { const models = Self.app.models; const today = Date.vnNew(); dated.setHours(0, 0, 0, 0); @@ -27,26 +32,30 @@ module.exports = Self => { if (dated.getTime() === today.getTime()) await models.StockBought.rawSql(`CALL vn.stockBought_calculate()`); - return models.StockBought.find( - { - where: { - dated: dated - }, - include: [ - { - relation: 'worker', - scope: { - include: [ - { - relation: 'user', - scope: { - fields: ['id', 'name'] - } + const filter = { + where: { + dated: dated + }, + include: [ + { + relation: 'worker', + scope: { + include: [ + { + relation: 'user', + scope: { + fields: ['id', 'name'] } - ] - } + } + ] } - ] - }); + } + ] + }; + + if (workerFk) filter.where.workerFk = workerFk; + console.log('workerFk: ', workerFk); + + return models.StockBought.find(filter); }; }; From d7679fcb500a7c09e9c5ec5d9695bf8570b4b976 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 16 Sep 2024 09:01:47 +0200 Subject: [PATCH 100/123] feat: refs #7977 muestra las facturas sin vencimientos tambien --- .../procedures/supplier_statementWithEntries.sql | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/db/routines/vn/procedures/supplier_statementWithEntries.sql b/db/routines/vn/procedures/supplier_statementWithEntries.sql index df3b918a7..55b271296 100644 --- a/db/routines/vn/procedures/supplier_statementWithEntries.sql +++ b/db/routines/vn/procedures/supplier_statementWithEntries.sql @@ -17,14 +17,14 @@ BEGIN * @param vOrderBy Order by criteria * @param vIsConciliated Indicates whether it is reconciled or not * @param vHasEntries Indicates if future entries must be shown -* @return tmp.supplierStatement +* @return tmp.supplierStatement */ DECLARE vBalanceStartingDate DATETIME; SET @euroBalance:= 0; SET @currencyBalance:= 0; - SELECT balanceStartingDate + SELECT balanceStartingDate INTO vBalanceStartingDate FROM invoiceInConfig; @@ -64,14 +64,14 @@ BEGIN c.code, 'invoiceIn' statementType FROM invoiceIn ii - JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id + LEFT JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id JOIN currency c ON c.id = ii.currencyFk WHERE ii.issued >= vBalanceStartingDate - AND ii.supplierFk = vSupplierFk + AND ii.supplierFk = vSupplierFk AND vCurrencyFk IN (ii.currencyFk, 0) AND vCompanyFk IN (ii.companyFk, 0) AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated) - GROUP BY iid.id + GROUP BY iid.id, ii.id UNION ALL SELECT p.bankFk, p.companyFk, @@ -107,7 +107,7 @@ BEGIN AND vCurrencyFk IN (p.currencyFk, 0) AND vCompanyFk IN (p.companyFk, 0) AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated) - UNION ALL + UNION ALL SELECT NULL, companyFk, NULL, @@ -134,7 +134,7 @@ BEGIN AND vCurrencyFk IN (se.currencyFk,0) AND vCompanyFk IN (se.companyFk,0) AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated) - UNION ALL + UNION ALL SELECT NULL bankFk, e.companyFk, 'E' serial, @@ -150,7 +150,7 @@ BEGIN FALSE isBooked, c.code, 'order' - FROM entry e + FROM entry e JOIN travel tr ON tr.id = e.travelFk JOIN currency c ON c.id = e.currencyFk WHERE e.supplierFk = vSupplierFk From 51cabd06a4486b619498250b136e89b0f1950fd1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 16 Sep 2024 10:44:04 +0200 Subject: [PATCH 101/123] refactor: refs #7562 Deleted deprecated objects --- db/versions/11234-yellowRuscus/00-firstScript.sql | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 db/versions/11234-yellowRuscus/00-firstScript.sql diff --git a/db/versions/11234-yellowRuscus/00-firstScript.sql b/db/versions/11234-yellowRuscus/00-firstScript.sql new file mode 100644 index 000000000..2cbac598b --- /dev/null +++ b/db/versions/11234-yellowRuscus/00-firstScript.sql @@ -0,0 +1,13 @@ +ALTER TABLE `vn`.`payrollWorkCenter` DROP PRIMARY KEY; +ALTER TABLE `vn`.`payrollWorkCenter` DROP COLUMN `empresa_id__`; +ALTER TABLE `vn`.`payrollWorkCenter` DROP COLUMN `Centro__`; +ALTER TABLE `vn`.`payrollWorkCenter` DROP COLUMN `nss_cotizacion__`; +ALTER TABLE `vn`.`payrollWorkCenter` DROP COLUMN `domicilio__`; +ALTER TABLE `vn`.`payrollWorkCenter` DROP COLUMN `poblacion__`; +ALTER TABLE `vn`.`payrollWorkCenter` DROP COLUMN `cp__`; +ALTER TABLE `vn`.`payrollWorker` DROP COLUMN `nss__`; +ALTER TABLE `vn`.`payrollWorker` DROP COLUMN `codpuesto__`; +ALTER TABLE `vn`.`payrollWorker` DROP COLUMN `codcontrato__`; +ALTER TABLE `vn`.`payrollWorker` DROP COLUMN `FAntiguedad__`; +ALTER TABLE `vn`.`payrollWorker` DROP COLUMN `codcategoria__`; +ALTER TABLE `vn`.`payrollWorker` DROP COLUMN `ContratoTemporal__`; From 138640f9910cfc63efd08db06f0a8650207a6d36 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 16 Sep 2024 12:05:36 +0200 Subject: [PATCH 102/123] fix: refs #7404 update test to match new fixtures for travel by continent --- .../back/methods/travel/specs/extraCommunityFilter.spec.js | 4 ++-- modules/travel/back/methods/travel/specs/filter.spec.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js index 97e1e5e77..7e90c7681 100644 --- a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js +++ b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js @@ -79,7 +79,7 @@ describe('Travel extraCommunityFilter()', () => { const result = await app.models.Travel.extraCommunityFilter(ctx, filter); - expect(result.length).toEqual(10); + expect(result.length).toEqual(9); }); it('should return the travel matching "cargoSupplierFk"', async() => { @@ -110,6 +110,6 @@ describe('Travel extraCommunityFilter()', () => { const result = await app.models.Travel.extraCommunityFilter(ctx, filter); - expect(result.length).toEqual(3); + expect(result.length).toEqual(2); }); }); diff --git a/modules/travel/back/methods/travel/specs/filter.spec.js b/modules/travel/back/methods/travel/specs/filter.spec.js index 2b6885cae..a608a980e 100644 --- a/modules/travel/back/methods/travel/specs/filter.spec.js +++ b/modules/travel/back/methods/travel/specs/filter.spec.js @@ -68,7 +68,7 @@ describe('Travel filter()', () => { const result = await app.models.Travel.filter(ctx); - expect(result.length).toEqual(2); + expect(result.length).toEqual(1); }); it('should return the travel matching "continent"', async() => { @@ -80,6 +80,6 @@ describe('Travel filter()', () => { const result = await app.models.Travel.filter(ctx); - expect(result.length).toEqual(7); + expect(result.length).toEqual(6); }); }); From 1f1da689d4bcec0072e2281d9ed564af610b6c8c Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 16 Sep 2024 12:17:51 +0200 Subject: [PATCH 103/123] fix: refs #7404 remove console log --- modules/entry/back/methods/stock-bought/getStockBought.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/entry/back/methods/stock-bought/getStockBought.js b/modules/entry/back/methods/stock-bought/getStockBought.js index 0f67d878d..94e206ece 100644 --- a/modules/entry/back/methods/stock-bought/getStockBought.js +++ b/modules/entry/back/methods/stock-bought/getStockBought.js @@ -54,7 +54,6 @@ module.exports = Self => { }; if (workerFk) filter.where.workerFk = workerFk; - console.log('workerFk: ', workerFk); return models.StockBought.find(filter); }; From 7540526b9b0e1cc57247dd9e49ca4063a5f74894 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 16 Sep 2024 12:26:29 +0200 Subject: [PATCH 104/123] feat: refs #7964 entry_beforeUpdate --- db/routines/vn/triggers/entry_beforeUpdate.sql | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index ee2178024..e57ba08a9 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -71,7 +71,10 @@ BEGIN SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); END IF; - IF NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN + IF NOT (NEW.travelFk <=> OLD.travelFk) + OR NOT (NEW.currencyFk <=> OLD.currencyFk) + OR (NEW.supplierFk <=> OLD.supplierFk) THEN + SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk, NEW.supplierFk); END IF; END$$ From 5c7a537275e47e8382c803602c7c3648dbc132b7 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 16 Sep 2024 12:32:52 +0200 Subject: [PATCH 105/123] feat: refs #7912 Added new waste types --- db/dump/fixtures.before.sql | 32 +++++++++---------- db/routines/bs/procedures/waste_addSales.sql | 32 ++++++++++++++----- .../11236-blackMedeola/00-firstScript.sql | 19 +++++++++++ .../11236-blackMedeola/01-firstScript.sql | 6 ++++ .../item/back/methods/item/getWasteByItem.js | 8 ++++- .../back/methods/item/getWasteByWorker.js | 16 ++++++++-- .../buyer-week-waste/sql/wasteWeekly.sql | 10 ++++-- 7 files changed, 94 insertions(+), 29 deletions(-) create mode 100644 db/versions/11236-blackMedeola/00-firstScript.sql create mode 100644 db/versions/11236-blackMedeola/01-firstScript.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index fdd6d6d65..6fbd34274 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1521,23 +1521,23 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed INSERT INTO `vn`.`entryConfig` (`defaultEntry`, `inventorySupplierFk`, `defaultSupplierFk`) VALUES (2, 4, 1); -INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWasteQuantity`, `saleInternalWaste`, `saleExternalWaste`) +INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWasteQuantity`, `saleExternalWaste`, `saleFaultWaste`, `saleContainerWaste`, `saleBreakWaste`, `saleOtherWaste`) VALUES - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 1, 1, '1062', '51', '56.20', '56.20'), - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '35074', '687', '53.12', '89.69'), - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 3, 1, '1777', '13', '12.02', '53.12'), - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 4, 1, '3182', '59', '51', '56.20'), - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 5, 1, '1747', '13', '53.12', '53.12'), - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 6, 1, '7182', '59', '51', '53.12'), - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 7, 1, '1777', '13', '89.69', '89.69'), - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 8, 1, '4181', '59', '53.12', '53.12'), - ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 9, 1, '7268', '59', '12.02', '56.20'), - ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '-74', '0', '51', '89.69'), - ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 3, 1, '-7', '0', '12.02', '53.12'), - ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 4, 1, '1100', '0', '51', '56.20'), - ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 5, 1, '848', '-187', '12.02', '89.69'), - ('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'), - ('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'); + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 1, 1, '1062', '51', '56.20', '56.20', '56.20', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '35074', '687', '53.12', '89.69', '56.20', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 3, 1, '1777', '13', '12.02', '53.12', '56.20', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 4, 1, '3182', '59', '51', '56.20', '56.20', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 5, 1, '1747', '13', '53.12', '53.12', '56.20', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 6, 1, '7182', '59', '51', '53.12', '56.20', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 7, 1, '1777', '13', '89.69', '89.69', '56.20', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 8, 1, '4181', '59', '53.12', '53.12', '56.20', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 9, 1, '7268', '59', '12.02', '56.20', '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), 2, 1, '-74', '0', '51', '89.69', '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), 3, 1, '-7', '0', '12.02', '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), 4, 1, '1100', '0', '51', '56.20', '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), 5, 1, '848', '-187', '12.02', '89.69', '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), 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`) VALUES diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index 20eee5d49..f23c1b360 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -1,7 +1,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`() BEGIN - DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY; + DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY; DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY; CALL cache.last_buy_refresh(FALSE); @@ -14,16 +14,32 @@ BEGIN s.itemFk, SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity), SUM(IF(aw.`type`, s.quantity, 0)), - SUM( - IF( - aw.`type` = 'internal', + SUM(IF( + aw.`type` = 'external', (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, 0 ) - ), - SUM( - IF( - aw.`type` = 'external', + ), + SUM(IF( + aw.`type` = 'fault', + (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, + 0 + ) + ), + SUM(IF( + aw.`type` = 'container', + (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, + 0 + ) + ), + SUM(IF( + aw.`type` = 'break', + (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, + 0 + ) + ), + SUM(IF( + aw.`type` = 'other', (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, 0 ) diff --git a/db/versions/11236-blackMedeola/00-firstScript.sql b/db/versions/11236-blackMedeola/00-firstScript.sql new file mode 100644 index 000000000..8729e40e1 --- /dev/null +++ b/db/versions/11236-blackMedeola/00-firstScript.sql @@ -0,0 +1,19 @@ +ALTER TABLE vn.addressWaste + MODIFY COLUMN `type` enum('external', 'fault', 'container', 'break', 'other') + CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL; + +UPDATE vn.addressWaste + SET `type`='container' + WHERE addressFk=77; + +UPDATE vn.addressWaste + SET `type`='fault' + WHERE addressFk=317; + +UPDATE vn.addressWaste + SET `type`='break' + WHERE addressFk=57702; + +UPDATE vn.addressWaste + SET `type`='other' + WHERE addressFk=43432; diff --git a/db/versions/11236-blackMedeola/01-firstScript.sql b/db/versions/11236-blackMedeola/01-firstScript.sql new file mode 100644 index 000000000..87262115b --- /dev/null +++ b/db/versions/11236-blackMedeola/01-firstScript.sql @@ -0,0 +1,6 @@ +ALTER TABLE bs.waste + DROP COLUMN saleInternalWaste, + ADD saleFaultWaste decimal(10,2) DEFAULT NULL NULL, + ADD saleContainerWaste decimal(10,2) DEFAULT NULL NULL, + ADD saleBreakWaste decimal(10,2) DEFAULT NULL NULL, + ADD saleOtherWaste decimal(10,2) DEFAULT NULL NULL; diff --git a/modules/item/back/methods/item/getWasteByItem.js b/modules/item/back/methods/item/getWasteByItem.js index 548f28008..b4cc566ae 100644 --- a/modules/item/back/methods/item/getWasteByItem.js +++ b/modules/item/back/methods/item/getWasteByItem.js @@ -52,7 +52,13 @@ module.exports = Self => { it.name family, w.itemFk, SUM(w.saleTotal) total, - SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle + SUM( + w.saleExternalWaste + + w.saleFaultWaste + + w.saleContainerWaste + + w.saleBreakWaste + + w.saleOtherWaste + ) dwindle FROM bs.waste w JOIN account.user u ON u.id = w.buyerFk JOIN vn.itemType it ON it.id = w.itemTypeFk diff --git a/modules/item/back/methods/item/getWasteByWorker.js b/modules/item/back/methods/item/getWasteByWorker.js index 9af49478f..d2c2f7f59 100644 --- a/modules/item/back/methods/item/getWasteByWorker.js +++ b/modules/item/back/methods/item/getWasteByWorker.js @@ -28,7 +28,13 @@ module.exports = Self => { it.name family, w.itemFk, SUM(w.saleTotal) total, - SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle + SUM( + w.saleExternalWaste + + w.saleFaultWaste + + w.saleContainerWaste + + w.saleBreakWaste + + w.saleOtherWaste + ) dwindle FROM bs.waste w JOIN account.user u ON u.id = w.buyerFk JOIN vn.itemType it ON it.id = w.itemTypeFk @@ -44,7 +50,13 @@ module.exports = Self => { FROM ( SELECT u.name buyer, SUM(w.saleTotal) total, - SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle + SUM( + w.saleExternalWaste + + w.saleFaultWaste + + w.saleContainerWaste + + w.saleBreakWaste + + w.saleOtherWaste + ) dwindle FROM bs.waste w JOIN account.user u ON u.id = w.buyerFk WHERE w.year = YEAR(TIMESTAMPADD(WEEK, -1, ?)) diff --git a/print/templates/email/buyer-week-waste/sql/wasteWeekly.sql b/print/templates/email/buyer-week-waste/sql/wasteWeekly.sql index 1b486a004..e5dbdfcb6 100644 --- a/print/templates/email/buyer-week-waste/sql/wasteWeekly.sql +++ b/print/templates/email/buyer-week-waste/sql/wasteWeekly.sql @@ -1,8 +1,14 @@ SELECT *, 100 * dwindle / total `percentage` FROM ( SELECT u.name buyer, - SUM(saleTotal) total, - SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle + SUM(w.saleTotal) total, + SUM( + w.saleExternalWaste + + w.saleFaultWaste + + w.saleContainerWaste + + w.saleBreakWaste + + w.saleOtherWaste + ) dwindle FROM bs.waste w JOIN account.user u ON u.id = w.buyerFk JOIN vn.itemType it ON it.id = w.itemTypeFk From 9aff118b6eba56abe3540119f1b1c92315b99f18 Mon Sep 17 00:00:00 2001 From: Jon Date: Mon, 16 Sep 2024 13:00:11 +0200 Subject: [PATCH 106/123] feat: refs #6346 added script for wagons --- db/versions/11235-purpleCordyline/00-firstScript.sql | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 db/versions/11235-purpleCordyline/00-firstScript.sql diff --git a/db/versions/11235-purpleCordyline/00-firstScript.sql b/db/versions/11235-purpleCordyline/00-firstScript.sql new file mode 100644 index 000000000..f3bb6ddab --- /dev/null +++ b/db/versions/11235-purpleCordyline/00-firstScript.sql @@ -0,0 +1,12 @@ +ALTER TABLE vn.collectionWagon DROP FOREIGN KEY IF EXISTS collectionWagon_FK_1; +ALTER TABLE vn.collectionWagonTicket DROP FOREIGN KEY IF EXISTS collectionWagonTicket_FK_1; +ALTER TABLE vn.wagonVolumetry DROP FOREIGN KEY IF EXISTS wagonVolumetry_FK_1; + +ALTER TABLE vn.wagon MODIFY COLUMN id int(11) unsigned auto_increment NOT NULL COMMENT '26 letras de alfabeto inglés'; +ALTER TABLE vn.collectionWagon MODIFY COLUMN wagonFk int(11) unsigned NOT NULL; +ALTER TABLE vn.collectionWagonTicket MODIFY COLUMN wagonFk int(11) unsigned NOT NULL; +ALTER TABLE vn.wagonVolumetry MODIFY COLUMN wagonFk int(11) unsigned NOT NULL; + +ALTER TABLE vn.collectionWagon ADD CONSTRAINT collectionWagon_FK_1 FOREIGN KEY (wagonFk) REFERENCES vn.wagon(id) ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE vn.collectionWagonTicket ADD CONSTRAINT collectionWagonTicket_FK_1 FOREIGN KEY (wagonFk) REFERENCES vn.wagon(id) ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE vn.wagonVolumetry ADD CONSTRAINT wagonVolumetry_FK_1 FOREIGN KEY (wagonFk) REFERENCES vn.wagon(id) ON DELETE RESTRICT ON UPDATE CASCADE; From e4a74ba0e9ea9632bc0c6ecf9b0f44de613f07b6 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 16 Sep 2024 13:24:33 +0200 Subject: [PATCH 107/123] feat: refs #3505 testBack closure --- .../mrw-config/specs/createShipment.spec.js | 17 ++- db/dump/fixtures.before.sql | 68 +++++----- modules/invoiceOut/back/models/invoice-out.js | 6 +- .../sales-monitor/specs/salesFilter.spec.js | 15 ++- .../back/methods/ticket-weekly/filter.js | 17 +-- .../ticket-weekly/specs/filter.spec.js | 4 +- .../back/methods/ticket/closeByAgency.js | 79 ------------ .../back/methods/ticket/closeByRoute.js | 75 ----------- .../back/methods/ticket/closeByTicket.js | 30 ++++- modules/ticket/back/methods/ticket/closure.js | 41 ++++-- modules/ticket/back/methods/ticket/saveCmr.js | 2 +- .../back/methods/ticket/specs/closure.spec.js | 119 ++++++++++++++++++ .../back/methods/ticket/specs/filter.spec.js | 20 ++- .../ticket/specs/isEditableOrThrow.spec.js | 2 +- modules/ticket/back/models/ticket-methods.js | 2 - print/core/email.js | 2 +- 16 files changed, 262 insertions(+), 237 deletions(-) delete mode 100644 modules/ticket/back/methods/ticket/closeByAgency.js delete mode 100644 modules/ticket/back/methods/ticket/closeByRoute.js create mode 100644 modules/ticket/back/methods/ticket/specs/closure.spec.js diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js index 1ab77f608..c8a5295f7 100644 --- a/back/methods/mrw-config/specs/createShipment.spec.js +++ b/back/methods/mrw-config/specs/createShipment.spec.js @@ -12,9 +12,8 @@ const ticket1 = { 'addressFk': 1, 'agencyModeFk': 999 }; - +let expedition; const expedition1 = { - 'id': 17, 'agencyModeFk': 999, 'ticketFk': 44, 'freightItemFk': 71, @@ -47,7 +46,7 @@ describe('MRWConfig createShipment()', () => { await createMrwConfig(); await models.Ticket.create(ticket1); - await models.Expedition.create(expedition1); + expedition = await models.Expedition.create(expedition1); }); afterAll(async() => { @@ -93,7 +92,7 @@ describe('MRWConfig createShipment()', () => { } it('should create a shipment and return a base64Binary label', async() => { - const {file} = await models.MrwConfig.createShipment(expedition1.id); + const {file} = await models.MrwConfig.createShipment(expedition.id); expect(file).toEqual(mockBase64Binary); }); @@ -101,7 +100,7 @@ describe('MRWConfig createShipment()', () => { it('should fail if mrwConfig has no data', async() => { let error; await models.MrwConfig.destroyAll(); - await models.MrwConfig.createShipment(expedition1.id).catch(e => { + await models.MrwConfig.createShipment(expedition.id).catch(e => { error = e; }).finally(async() => { expect(error.message).toEqual(`MRW service is not configured`); @@ -126,7 +125,7 @@ describe('MRWConfig createShipment()', () => { yesterday.setDate(yesterday.getDate() - 1); await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday}); - await models.MrwConfig.createShipment(expedition1.id).catch(e => { + await models.MrwConfig.createShipment(expedition.id).catch(e => { error = e; }).finally(async() => { expect(error.message).toEqual(`This ticket has a shipped date earlier than today`); @@ -136,7 +135,7 @@ describe('MRWConfig createShipment()', () => { it('should send mail if you are past the dead line and is not notified today', async() => { await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: null}); - await models.MrwConfig.createShipment(expedition1.id); + await models.MrwConfig.createShipment(expedition.id); const notification = await getLastNotification(); expect(notification.notificationFk).toEqual(filter.notificationFk); @@ -144,7 +143,7 @@ describe('MRWConfig createShipment()', () => { it('should send mail if you are past the dead line and it is notified from another day', async() => { await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: new Date()}); - await models.MrwConfig.createShipment(expedition1.id); + await models.MrwConfig.createShipment(expedition.id); const notification = await getLastNotification(); expect(notification.notificationFk).toEqual(filter.notificationFk); @@ -152,7 +151,7 @@ describe('MRWConfig createShipment()', () => { it('should not send mail if you are past the dead line and it is notified', async() => { await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: Date.vnNew()}); - await models.MrwConfig.createShipment(expedition1.id); + await models.MrwConfig.createShipment(expedition.id); const notification = await getLastNotification(); expect(notification).toEqual(null); diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index fdd6d6d65..a28212270 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -335,21 +335,21 @@ INSERT INTO `vn`.`payDem`(`id`, `payDem`) (2, 20), (7, 0); -INSERT INTO `vn`.`autonomy`(`id`, `name`, `countryFk`) +INSERT INTO `vn`.`autonomy`(`id`, `name`, `countryFk`, `hasDailyInvoice`) VALUES - (1, 'Autonomy one', 1), - (2, 'Autonomy two', 1), - (3, 'Autonomy three', 2), - (4, 'Autonomy four', 13); + (1, 'Autonomy one', 1, 1), + (2, 'Autonomy two', 1, 0), + (3, 'Autonomy three', 2, 0), + (4, 'Autonomy four', 13, 0); INSERT INTO `vn`.`province`(`id`, `name`, `countryFk`, `autonomyFk`, `warehouseFk`) VALUES - (1, 'Province one', 1, 1, NULL), - (2, 'Province two', 1, 1, NULL), - (3, 'Province three', 30, 2, NULL), - (4, 'Province four', 2, 3, NULL), - (5, 'Province five', 13, 4, NULL); + (1, 'Province one', 1, 1, NULL), + (2, 'Province two', 1, 1, NULL), + (3, 'Province three', 30, 2, NULL), + (4, 'Province four', 2, 3, NULL), + (5, 'Province five', 13, 4, NULL); INSERT INTO `vn`.`town`(`id`, `name`, `provinceFk`) VALUES @@ -361,11 +361,11 @@ INSERT INTO `vn`.`town`(`id`, `name`, `provinceFk`) INSERT INTO `vn`.`postCode`(`code`, `townFk`, `geoFk`) VALUES - ('46000', 1, 6), - ('46460', 2, 6), - ('46680', 3, 6), - ('46600', 4, 7), - ('EC170150', 5, 8); + ('46000', 1, 6), + ('46460', 2, 6), + ('46680', 3, 6), + ('46600', 4, 7), + ('EC170150', 5, 8); INSERT INTO `vn`.`clientType`(`code`, `type`) VALUES @@ -397,7 +397,7 @@ INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city (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, 0, 0, NULL, 0, 0, NULL, 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'); @@ -821,10 +821,10 @@ INSERT INTO `vn`.`ticketTracking`(`ticketFk`, `stateFk`, `userFk`, `created`) (12, 3, 19, util.VN_NOW()), (13, 3, 19, util.VN_NOW()), (14, 3, 19, util.VN_NOW()), - (15, 2, 19, util.VN_NOW()), + (15, 10, 19, util.VN_NOW()), (16, 3, 19, util.VN_NOW()), (17, 2, 19, util.VN_NOW()), - (18, 2, 19, util.VN_NOW()), + (37, 10, 19, util.VN_NOW()), (19, 2, 19, util.VN_NOW()), (20, 1, 19, DATE_ADD(util.VN_NOW(), INTERVAL +1 MONTH)), (21, 1, 19, DATE_ADD(util.VN_NOW(), INTERVAL +1 MONTH)), @@ -1031,19 +1031,20 @@ INSERT INTO `vn`.`expeditionStateType`(`id`, `description`, `code`) INSERT INTO `vn`.`expedition`(`id`, `agencyModeFk`, `ticketFk`, `freightItemFk`, `created`, `counter`, `workerFk`, `externalId`, `packagingFk`, `stateTypeFk`, `hostFk`) VALUES - (1, 1, 1, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 18, 'UR9000006041', 94, 1, 'pc1'), - (2, 1, 1, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 18, 'UR9000006041', 94, 1, NULL), - (3, 1, 1, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 18, 'UR9000006041', 94, 2, NULL), - (4, 1, 1, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 18, 'UR9000006041', 94, 2, NULL), - (5, 1, 2, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 18, NULL, 94, 3, NULL), - (6, 7, 3, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 18, NULL, 94, 3, NULL), - (7, 2, 4, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), 1, 18, NULL, 94, NULL,NULL), - (8, 3, 5, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), 1, 18, NULL, 94, 1, NULL), - (9, 3, 6, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 18, NULL, 94, 2, NULL), - (10, 7, 7, 71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL), - (11, 7, 8, 71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL), - (12, 7, 9, 71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL), - (13, 1, 10,71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL); + (1, 1, 1, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 18, 'UR9000006041', 94, 1, 'pc1'), + (2, 1, 1, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 18, 'UR9000006041', 94, 1, NULL), + (3, 1, 1, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 18, 'UR9000006041', 94, 2, NULL), + (4, 1, 1, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 18, 'UR9000006041', 94, 2, NULL), + (5, 1, 2, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 18, NULL, 94, 3, NULL), + (6, 7, 3, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 18, NULL, 94, 3, NULL), + (7, 2, 4, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), 1, 18, NULL, 94, NULL,NULL), + (8, 3, 5, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), 1, 18, NULL, 94, 1, NULL), + (9, 3, 6, 71, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 18, NULL, 94, 2, NULL), + (10, 7, 7, 71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL), + (11, 7, 8, 71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL), + (12, 7, 9, 71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL), + (13, 1, 10, 71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL), + (14, 1, 37, 71, util.VN_NOW(), 1, 18, NULL, 94, 3, NULL); INSERT INTO `vn`.`expeditionState`(`id`, `created`, `expeditionFk`, `typeFk`, `userFk`) @@ -1478,7 +1479,8 @@ INSERT INTO `vn`.`ticketWeekly`(`ticketFk`, `weekDay`) (2, 1), (3, 2), (5, 6), - (15, 6); + (15, 6), + (17, 6); INSERT INTO `vn`.`awb` (id, code, package, weight, created, amount, transitoryFk, taxFk) VALUES @@ -3970,6 +3972,6 @@ VALUES (5, 'Referencia Nominas', 'payRef'), (6, 'ABA', 'aba'); -INSERT IGNORE INTO ormConfig +INSERT IGNORE INTO ormConfig SET id =1, selectLimit = 1000; diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index 47dbcbea4..bab1fa375 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -83,8 +83,10 @@ module.exports = Self => { const invoiceOutSerial = await Self.app.models.InvoiceOutSerial.findById(serial); if (invoiceOutSerial?.taxAreaFk == 'WORLD') { const address = await Self.app.models.Address.findById(addressId); - if (!address || !address.customsAgentFk || !address.incotermsFk) - throw new UserError('The address of the customer must have information about Incoterms and Customs Agent'); + if (!address?.customsAgentFk || !address.incotermsFk) { + throw new UserError( + 'The address of the customer must have information about Incoterms and Customs Agent'); + } } return serial; diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index 9460addfa..738af5219 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -39,7 +39,7 @@ describe('SalesMonitor salesFilter()', () => { const filter = {}; const result = await models.SalesMonitor.salesFilter(ctx, filter, options); - expect(result.length).toBeGreaterThan(10); + expect(result.length).toBeGreaterThan(9); await tx.rollback(); } catch (e) { @@ -146,13 +146,20 @@ describe('SalesMonitor salesFilter()', () => { try { const options = {transaction: tx}; + const alertLevel = await models.AlertLevel.findOne({ + where: {code: 'FREE'}, + options + }); + + const alertLevelFree = alertLevel.id; + const ctx = {req: {accessToken: {userId: 9}}, args: {pending: false}}; const filter = {order: 'alertLevel ASC'}; const result = await models.SalesMonitor.salesFilter(ctx, filter, options); - const firstRow = result[0]; - expect(result.length).toEqual(15); - expect(firstRow.alertLevel).not.toEqual(0); + result.forEach(row => { + expect(row.alertLevel).toBeGreaterThan(alertLevelFree); + }); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket-weekly/filter.js b/modules/ticket/back/methods/ticket-weekly/filter.js index a43b5e270..21f31518e 100644 --- a/modules/ticket/back/methods/ticket-weekly/filter.js +++ b/modules/ticket/back/methods/ticket-weekly/filter.js @@ -38,14 +38,17 @@ module.exports = Self => { Object.assign(myOptions, options); const where = buildFilter(ctx.args, (param, value) => { - switch (param) { - case 'search': - return {or: [ - {'t.id': value}, - {'c.id': value}, - {'c.name': {like: `%${value}%`}} - ]}; + if (param === 'search') { + return { + or: [ + {'t.id': value}, + {'c.id': value}, + {'c.name': {like: `%${value}%`}} + ] + }; } + + return {}; }); filter = mergeFilters(ctx.args.filter, {where}); diff --git a/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js b/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js index 453b7924f..9b1ad5209 100644 --- a/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js @@ -13,11 +13,11 @@ describe('ticket-weekly filter()', () => { const ctx = {req: {accessToken: {userId: authUserId}}, args: {filter: filter}}; const result = await models.TicketWeekly.filter(ctx, null, options); - + const totalRecords = await models.TicketWeekly.count(); const firstRow = result[0]; expect(firstRow.ticketFk).toEqual(2); - expect(result.length).toEqual(4); + expect(result.length).toEqual(totalRecords); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/closeByAgency.js b/modules/ticket/back/methods/ticket/closeByAgency.js deleted file mode 100644 index eb1aee349..000000000 --- a/modules/ticket/back/methods/ticket/closeByAgency.js +++ /dev/null @@ -1,79 +0,0 @@ -const closure = require('./closure'); - -module.exports = Self => { - Self.remoteMethodCtx('closeByAgency', { - description: 'Makes the closure process by agency mode', - accessType: 'WRITE', - accepts: [ - { - arg: 'agencyModeFk', - type: ['number'], - required: true, - description: 'The agencies mode ids', - }, - { - arg: 'warehouseFk', - type: 'number', - description: 'The ticket warehouse id', - required: true - }, - { - arg: 'to', - type: 'date', - description: 'Max closure date', - required: true - } - ], - returns: { - type: 'object', - root: true - }, - http: { - path: `/close-by-agency`, - verb: 'POST' - } - }); - - Self.closeByAgency = async ctx => { - const args = ctx.args; - - const tickets = await Self.rawSql(` - SELECT - t.id, - t.clientFk, - t.companyFk, - c.name clientName, - c.email recipient, - c.salesPersonFk, - c.isToBeMailed, - c.hasToInvoice, - co.hasDailyInvoice, - eu.email salesPersonEmail - FROM expedition e - JOIN ticket t ON t.id = e.ticketFk - 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.agencyModeFk IN(?) - AND t.warehouseFk = ? - AND DATE(t.shipped) BETWEEN DATE_ADD(?, INTERVAL -2 DAY) - AND util.dayEnd(?) - AND t.refFk IS NULL - GROUP BY e.ticketFk`, [ - args.agencyModeFk, - args.warehouseFk, - args.to, - args.to - ]); - - await closure(Self, tickets); - - return { - message: 'Success' - }; - }; -}; diff --git a/modules/ticket/back/methods/ticket/closeByRoute.js b/modules/ticket/back/methods/ticket/closeByRoute.js deleted file mode 100644 index 58e130b8e..000000000 --- a/modules/ticket/back/methods/ticket/closeByRoute.js +++ /dev/null @@ -1,75 +0,0 @@ -const closure = require('./closure'); -const {Email} = require('vn-print'); - -module.exports = Self => { - Self.remoteMethodCtx('closeByRoute', { - description: 'Makes the closure process by route', - accessType: 'WRITE', - accepts: [ - { - arg: 'routeFk', - type: 'number', - required: true, - description: 'The routes ids', - }, - ], - returns: { - type: 'object', - root: true - }, - http: { - path: `/close-by-route`, - verb: 'POST' - } - }); - - Self.closeByRoute = async ctx => { - const args = ctx.args; - - const tickets = await Self.rawSql(` - SELECT - t.id, - t.clientFk, - t.companyFk, - c.name clientName, - c.email recipient, - c.salesPersonFk, - c.isToBeMailed, - c.hasToInvoice, - co.hasDailyInvoice, - eu.email salesPersonEmail - FROM expedition e - JOIN ticket t ON t.id = e.ticketFk - 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.routeFk = ? - AND t.refFk IS NULL - GROUP BY e.ticketFk`, [args.routeFk]); - - await closure(Self, tickets); - - // Send route report to the agency - const [agencyMail] = await Self.rawSql(` - SELECT am.reportMail - FROM route r - JOIN agencyMode am ON am.id = r.agencyModeFk - WHERE r.id = ?`, [args.routeFk]); - - if (agencyMail) { - const email = new Email('driver-route', { - id: args.routeFk, - recipient: agencyMail - }); - await email.send(); - } - - return { - message: 'Success' - }; - }; -}; diff --git a/modules/ticket/back/methods/ticket/closeByTicket.js b/modules/ticket/back/methods/ticket/closeByTicket.js index 8884897c2..40fe048a5 100644 --- a/modules/ticket/back/methods/ticket/closeByTicket.js +++ b/modules/ticket/back/methods/ticket/closeByTicket.js @@ -23,11 +23,25 @@ module.exports = Self => { } }); - Self.closeByTicket = async ctx => { + Self.closeByTicket = async(ctx, options) => { + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const userId = ctx.req.accessToken.userId; + myOptions.userId = userId; + const args = ctx.args; const tickets = await Self.rawSql(` - SELECT + SELECT t.id, t.clientFk, t.companyFk, @@ -37,7 +51,8 @@ module.exports = Self => { c.isToBeMailed, c.hasToInvoice, co.hasDailyInvoice, - eu.email salesPersonEmail + eu.email salesPersonEmail, + t.addressFk FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = t.id @@ -49,9 +64,14 @@ module.exports = Self => { WHERE al.code = 'PACKED' AND t.id = ? AND t.refFk IS NULL - GROUP BY e.ticketFk`, [args.id]); + GROUP BY e.ticketFk`, + [args.id], + myOptions); - await closure(Self, tickets); + await closure(ctx, Self, tickets, myOptions); + + if (tx) + await tx.commit(); return { message: 'Success' diff --git a/modules/ticket/back/methods/ticket/closure.js b/modules/ticket/back/methods/ticket/closure.js index 4622ba271..a75596bac 100644 --- a/modules/ticket/back/methods/ticket/closure.js +++ b/modules/ticket/back/methods/ticket/closure.js @@ -1,13 +1,22 @@ -/* eslint max-len: ["error", { "code": 150 }]*/ - const Report = require('vn-print/core/report'); const Email = require('vn-print/core/email'); const smtp = require('vn-print/core/smtp'); const config = require('vn-print/core/config'); const storage = require('vn-print/core/storage'); -module.exports = async function(ctx, Self, tickets, reqArgs = {}) { +module.exports = async function(ctx, Self, tickets, options) { const userId = ctx.req.accessToken.userId; + const myOptions = {userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + let tx; + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + if (tickets.length == 0) return; const failedtickets = []; @@ -17,7 +26,7 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { await Self.rawSql( `CALL vn.ticket_closeByTicket(?)`, [ticket.id], - {userId} + myOptions ); const [invoiceOut] = await Self.rawSql(` @@ -26,7 +35,7 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { JOIN invoiceOut io ON io.ref = t.refFk JOIN company cny ON cny.id = io.companyFk WHERE t.id = ? - `, [ticket.id]); + `, [ticket.id], myOptions); const mailOptions = { overrideAttachments: true, @@ -63,7 +72,7 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { await Self.rawSql( 'UPDATE invoiceOut SET hasPdf = true WHERE id = ?', [invoiceOut.id], - {userId}, + myOptions ); if (isToBeMailed) { @@ -108,7 +117,9 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { WHERE t.clientFk = ? AND NOT t.isDeleted AND c.isVies - `, [ticket.clientFk]); + `, + [ticket.clientFk], + myOptions); if (firstOrder == 1) { const args = { @@ -127,20 +138,22 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { SELECT id FROM sample WHERE code = 'incoterms-authorization' - `); + `, + null, + myOptions); await Self.rawSql(` INSERT INTO clientSample (clientFk, typeFk, companyFk) VALUES(?, ?, ?) - `, [ticket.clientFk, sample.id, ticket.companyFk], {userId}); + `, + [ticket.clientFk, sample.id, ticket.companyFk], + myOptions); } } catch (error) { - // Domain not found if (error.responseCode == 450) { await invalidEmail(ticket); continue; } - // Save tickets on a list of failed ids failedtickets.push({ id: ticket.id, stacktrace: error, @@ -148,7 +161,6 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { } } - // Send email with failed tickets if (failedtickets.length > 0) { let body = 'This following tickets have failed:

'; @@ -164,11 +176,14 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { }).catch(err => console.error(err)); } + if (tx) + await tx.commit(); + async function invalidEmail(ticket) { await Self.rawSql( `UPDATE client SET email = NULL WHERE id = ?`, [ticket.clientFk], - {userId}, + myOptions ); const body = `No se ha podido enviar el albarán ${ticket.id} diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index f8d0af8ef..339ac1e38 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -39,7 +39,7 @@ module.exports = Self => { }, myOptions); for (const ticketId of tickets) { - const ticket = await models.Ticket.findById(ticketId, myOptions); + const ticket = await models.Ticket.findById(ticketId, null, myOptions); if (ticket.cmrFk) { const hasDmsCmr = await Self.rawSql(` diff --git a/modules/ticket/back/methods/ticket/specs/closure.spec.js b/modules/ticket/back/methods/ticket/specs/closure.spec.js new file mode 100644 index 000000000..a184bb7af --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/closure.spec.js @@ -0,0 +1,119 @@ +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); +const smtp = require('vn-print/core/smtp'); +const Email = require('vn-print/core/email'); +const config = require('vn-print/core/config'); +const closure = require('../closure'); + +fdescribe('Ticket closure functionality', () => { + const userId = 19; + const companyFk = 442; + const activeCtx = { + getLocale: () => 'es', + accessToken: {userId: userId}, + headers: {origin: 'http://localhost:5000'}, + }; + let ctx = {req: activeCtx}; + let tx; + let options; + + beforeEach(async() => { + LoopBackContext.getCurrentContext = () => ({ + active: activeCtx, + }); + + tx = await models.Sale.beginTransaction({}); + options = {transaction: tx}; + }); + + afterEach(async() => { + await tx.rollback(); + }); + + it('should successfully close a ticket and not invoiced', async() => { + const ticketId = 15; + const tickets = [{ + id: ticketId, + clientFk: 1101, + companyFk, + addressFk: 1, + isToBeMailed: true, + recipient: 'some@email.com', + salesPersonFk: userId + }]; + + const ticketStateBefore = await models.TicketState.findById(ticketId, null, options); + + await closure(ctx, models.Ticket, tickets, options); + + const ticketStateAfter = await models.TicketState.findById(ticketId, null, options); + + expect(ticketStateBefore.code).not.toBe(ticketStateAfter.code); + + const ticketAfter = await models.TicketState.findById(ticketId, null, options); + + expect(ticketAfter.refFk).toBeUndefined(); + }); + + fit('should send Incoterms authorization email on first order', async() => { + const ticketId = 37; + ctx.args = { + id: ticketId, + }; + + const ticket = await models.Ticket.findById(ticketId, null, options); + spyOn(Email.prototype, 'send').and.returnValue(Promise.resolve()); + + await models.Ticket.closeByTicket(ctx, options); + + const sample = await models.Sample.findOne({ + where: {code: 'incoterms-authorization'}, + fields: ['id'] + }, + options); + + const insertedSample = await models.ClientSample.findOne({ + where: { + clientFk: ticket.clientFk, + typeFk: sample.id, + companyFk: companyFk + } + }, options); + + expect(insertedSample.clientFk).toEqual(ticket.clientFk); + }); + + it('should report failed tickets and set client email to null', async() => { + const ticketId = 37; + const clientId = 1110; + const tickets = [{ + id: ticketId, + clientFk: clientId, + companyFk, + addressFk: 1, + isToBeMailed: true, + recipient: 'invalid@example.com', + salesPersonFk: userId + }]; + + spyOn(Email.prototype, 'send').and.callFake(() => { + const error = new Error('Invalid email'); + error.responseCode = 450; + return Promise.reject(error); + }); + + await closure(ctx, models.Ticket, tickets, options); + + const client = await models.Client.findById(clientId, null, options); + + expect(client.email).toBeNull(); + + const reportEmail = await smtp.send({ + to: config.app.reportEmail, + subject: '[API] Nightly ticket closure report', + html: `This following tickets have failed:` + }); + + expect(reportEmail).not.toBeNull(); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index 72249fe5d..d0edb24e3 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -21,7 +21,7 @@ describe('ticket filter()', () => { } }); - it('should return the tickets matching the problems on true', async() => { + it('should return at least one ticket matching the problems on true', async() => { const tx = await models.Ticket.beginTransaction({}); try { @@ -41,7 +41,15 @@ describe('ticket filter()', () => { const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); - expect(result.length).toBeGreaterThan(3); + const hasProblemTicket = result.some(ticket => + ticket.isFreezed === true || + ticket.hasRisk === true || + ticket.hasTicketRequest === true || + (typeof ticket.hasRounding === 'string' && ticket.hasRounding.trim().length > 0) || + (typeof ticket.itemShortage === 'string' && ticket.itemShortage.trim().length > 0) + ); + + expect(hasProblemTicket).toBe(true); await tx.rollback(); } catch (e) { @@ -71,7 +79,13 @@ describe('ticket filter()', () => { const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); - expect(result.length).toEqual(11); + result.forEach(ticket => { + expect(ticket.isFreezed).toEqual(null); + expect(ticket.hasRisk).toEqual(null); + expect(ticket.hasTicketRequest).toEqual(null); + expect(ticket.itemShortage).toEqual(null); + expect(ticket.hasRounding).toEqual(null); + }); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js b/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js index 883b0de2e..1a8025f09 100644 --- a/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js @@ -65,7 +65,7 @@ describe('ticket isEditableOrThrow()', () => { const options = {transaction: tx}; const ctx = {req: {accessToken: {userId: 1}}}; - await models.Ticket.isEditableOrThrow(ctx, 15, options); + await models.Ticket.isEditableOrThrow(ctx, 17, options); await tx.rollback(); } catch (e) { error = e; diff --git a/modules/ticket/back/models/ticket-methods.js b/modules/ticket/back/models/ticket-methods.js index 12161d5f5..7fe968b26 100644 --- a/modules/ticket/back/models/ticket-methods.js +++ b/modules/ticket/back/models/ticket-methods.js @@ -33,8 +33,6 @@ module.exports = function(Self) { require('../methods/ticket/deliveryNoteCsvEmail')(Self); require('../methods/ticket/closeAll')(Self); require('../methods/ticket/closeByTicket')(Self); - require('../methods/ticket/closeByAgency')(Self); - require('../methods/ticket/closeByRoute')(Self); require('../methods/ticket/getTicketsFuture')(Self); require('../methods/ticket/merge')(Self); require('../methods/ticket/getTicketsAdvance')(Self); diff --git a/print/core/email.js b/print/core/email.js index a0bcf9122..a673685bb 100644 --- a/print/core/email.js +++ b/print/core/email.js @@ -33,7 +33,7 @@ class Email extends Component { const attachments = []; const getAttachments = async(componentPath, files) => { for (const file of files) { - const fileCopy = Object.assign({}, file); + const fileCopy = {...file}; const fileName = fileCopy.filename; if (options.overrideAttachments && !fileName.includes('.png')) continue; From f43fa32d364d1beb8f6d1c6520dff70e77594851 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 16 Sep 2024 13:26:53 +0200 Subject: [PATCH 108/123] feat: refs #3505 fdescribe --- modules/ticket/back/methods/ticket/specs/closure.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/specs/closure.spec.js b/modules/ticket/back/methods/ticket/specs/closure.spec.js index a184bb7af..303c38233 100644 --- a/modules/ticket/back/methods/ticket/specs/closure.spec.js +++ b/modules/ticket/back/methods/ticket/specs/closure.spec.js @@ -5,7 +5,7 @@ const Email = require('vn-print/core/email'); const config = require('vn-print/core/config'); const closure = require('../closure'); -fdescribe('Ticket closure functionality', () => { +describe('Ticket closure functionality', () => { const userId = 19; const companyFk = 442; const activeCtx = { @@ -55,7 +55,7 @@ fdescribe('Ticket closure functionality', () => { expect(ticketAfter.refFk).toBeUndefined(); }); - fit('should send Incoterms authorization email on first order', async() => { + it('should send Incoterms authorization email on first order', async() => { const ticketId = 37; ctx.args = { id: ticketId, From 51da7ae063385148090226a8e5ffbbd30ee8316c Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 16 Sep 2024 13:33:53 +0200 Subject: [PATCH 109/123] feat: refs #7893 Created waste_addSalesLauncher --- db/routines/bs/procedures/waste_addSales.sql | 16 ++++++++++++---- .../bs/procedures/waste_addSalesLauncher.sql | 6 ++++++ .../11237-goldenBamboo/00-firstScript.sql | 3 +++ 3 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 db/routines/bs/procedures/waste_addSalesLauncher.sql create mode 100644 db/versions/11237-goldenBamboo/00-firstScript.sql diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index f23c1b360..128c4f2db 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -1,8 +1,16 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`( + vDateFrom DATE, + vDateTo DATE +) BEGIN - DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY; - DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY; + IF vDateFrom IS NULL THEN + SET vDateFrom = util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY; + END IF; + + IF vDateTo IS NULL THEN + SET vDateTo = vDateFrom + INTERVAL 6 DAY; + END IF; CALL cache.last_buy_refresh(FALSE); @@ -56,6 +64,6 @@ BEGIN JOIN vn.buy b ON b.id = lb.buy_id WHERE t.shipped BETWEEN vDateFrom AND vDateTo AND w.isManaged - GROUP BY i.id; + GROUP BY YEAR(t.shipped), WEEK(t.shipped, 4), i.id; END$$ DELIMITER ; diff --git a/db/routines/bs/procedures/waste_addSalesLauncher.sql b/db/routines/bs/procedures/waste_addSalesLauncher.sql new file mode 100644 index 000000000..5eaea9be4 --- /dev/null +++ b/db/routines/bs/procedures/waste_addSalesLauncher.sql @@ -0,0 +1,6 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSalesLauncher`() +BEGIN + CALL waste_addSales(NULL, NULL); +END$$ +DELIMITER ; diff --git a/db/versions/11237-goldenBamboo/00-firstScript.sql b/db/versions/11237-goldenBamboo/00-firstScript.sql new file mode 100644 index 000000000..3e387eba8 --- /dev/null +++ b/db/versions/11237-goldenBamboo/00-firstScript.sql @@ -0,0 +1,3 @@ +UPDATE bs.nightTask + SET `procedure` = 'waste_addSalesLauncher' + WHERE `procedure` = 'waste_addSales'; From 10fcbffd376d81e55b4622f8543fc0334f129f58 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 16 Sep 2024 13:37:35 +0200 Subject: [PATCH 110/123] feat: refs #7964 entry_beforeUpdate not --- db/routines/vn/triggers/entry_beforeUpdate.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index e57ba08a9..8e5a326a0 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -73,7 +73,7 @@ BEGIN IF NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.currencyFk <=> OLD.currencyFk) - OR (NEW.supplierFk <=> OLD.supplierFk) THEN + OR NOT (NEW.supplierFk <=> OLD.supplierFk) THEN SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk, NEW.supplierFk); END IF; From e5e14878b874faf8b7e9b1f6b097092c94b919b8 Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 17 Sep 2024 07:57:00 +0200 Subject: [PATCH 111/123] feat: refs #3505 remove return --- e2e/paths/05-ticket/09_weekly.spec.js | 4 ++-- modules/ticket/back/methods/ticket-weekly/filter.js | 2 -- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/e2e/paths/05-ticket/09_weekly.spec.js b/e2e/paths/05-ticket/09_weekly.spec.js index 1caf91f9c..370d422e6 100644 --- a/e2e/paths/05-ticket/09_weekly.spec.js +++ b/e2e/paths/05-ticket/09_weekly.spec.js @@ -19,7 +19,7 @@ describe('Ticket descriptor path', () => { it('should count the amount of tickets in the turns section', async() => { const result = await page.countElement(selectors.ticketsIndex.weeklyTicket); - expect(result).toEqual(5); + expect(result).toEqual(6); }); it('should go back to the ticket index then search and access a ticket summary', async() => { @@ -106,7 +106,7 @@ describe('Ticket descriptor path', () => { await page.doSearch(); const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); - expect(nResults).toEqual(5); + expect(nResults).toEqual(6); }); it('should update the agency then remove it afterwards', async() => { diff --git a/modules/ticket/back/methods/ticket-weekly/filter.js b/modules/ticket/back/methods/ticket-weekly/filter.js index 21f31518e..6c9ed4f8b 100644 --- a/modules/ticket/back/methods/ticket-weekly/filter.js +++ b/modules/ticket/back/methods/ticket-weekly/filter.js @@ -47,8 +47,6 @@ module.exports = Self => { ] }; } - - return {}; }); filter = mergeFilters(ctx.args.filter, {where}); From 0c259b7a81f7e0d90ceca94d99ed1737548e1fc1 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 17 Sep 2024 10:32:26 +0200 Subject: [PATCH 112/123] fix: refs #7404 remove duplicate translate --- loopback/locale/en.json | 1 - 1 file changed, 1 deletion(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 875f06e3b..352e08826 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -235,7 +235,6 @@ "Cannot add holidays on this day": "Cannot add holidays on this day", "Cannot send mail": "Cannot send mail", "CONSTRAINT `chkParkingCodeFormat` failed for `vn`.`parking`": "CONSTRAINT `chkParkingCodeFormat` failed for `vn`.`parking`", - "This postcode already exists": "This postcode already exists", "Original invoice not found": "Original invoice not found", "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", From 2e32dfddc413156f88a97738f7e91dbf63862d46 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 17 Sep 2024 11:43:28 +0200 Subject: [PATCH 113/123] perf(salix): refs #7677 #7677 restore files --- db/dump/fixtures.after.sql | 4 ++-- db/routines/vn/procedures/client_userDisable.sql | 6 +++--- loopback/locale/es.json | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index 5489d2dd2..59730d592 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -255,7 +255,7 @@ INSERT INTO vn.operator (workerFk, numberOfWagons, trainFk, itemPackingTypeFk, w (9, 1, 1, 'V', 1); */ -- XXX: web - +/* #5483 INSERT INTO `hedera`.`config` (`cookieLife`, `defaultForm`) VALUES (15,'cms/home'); @@ -274,7 +274,7 @@ UPDATE `vn`.`agencyMode` SET `description` = `name`; INSERT INTO `hedera`.`tpvConfig` (currency, terminal, transactionType, maxAmount, employeeFk, `url`, testMode, testUrl, testKey, merchantUrl) VALUES (978, 1, 0, 2000, 9, 'https://sis.redsys.es/sis/realizarPago', 0, 'https://sis-t.redsys.es:25443/sis/realizarPago', 'sq7HjrUOBfKmC576ILgskD5srU870gJ7', NULL); - +*/ INSERT INTO hedera.tpvMerchantEnable (merchantFk, companyFk) VALUES (1, 442); diff --git a/db/routines/vn/procedures/client_userDisable.sql b/db/routines/vn/procedures/client_userDisable.sql index e769114fb..1a7c9846b 100644 --- a/db/routines/vn/procedures/client_userDisable.sql +++ b/db/routines/vn/procedures/client_userDisable.sql @@ -20,15 +20,15 @@ BEGIN WHERE c.typeFk = 'normal' AND a.id IS NULL AND u.active - AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH + AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH AND NOT u.role = (SELECT id FROM `role` WHERE name = 'supplier') AND u.id NOT IN ( SELECT DISTINCT c.id FROM client c LEFT JOIN ticket t ON t.clientFk = c.id WHERE c.salesPersonFk IS NOT NULL - OR t.created > util.VN_CURDATE() - INTERVAL vMonths MONTH - OR shipped > util.VN_CURDATE() - INTERVAL vMonths MONTH + OR t.created > util.VN_CURDATE() - INTERVAL vMonths MONTH + OR shipped > util.VN_CURDATE() - INTERVAL vMonths MONTH ); END$$ DELIMITER ; diff --git a/loopback/locale/es.json b/loopback/locale/es.json index eb48b0646..1093fe326 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -378,4 +378,4 @@ "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" -} +} \ No newline at end of file From f962b2e38b0e365f6dba24b396d684ae68f36899 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 17 Sep 2024 11:44:34 +0200 Subject: [PATCH 114/123] perf(salix): refs #7677 #7677 restore files because unnecessary change --- back/methods/postcode/filter.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/back/methods/postcode/filter.js b/back/methods/postcode/filter.js index 8f47b4a93..f350b1ea9 100644 --- a/back/methods/postcode/filter.js +++ b/back/methods/postcode/filter.js @@ -47,8 +47,6 @@ module.exports = Self => { let stmt; stmt = new ParameterizedSQL(` SELECT - CONCAT_WS('_', pc.code, pc.townFk, t.provinceFk, - p.countryFk) id, pc.townFk, t.provinceFk, p.countryFk, From fa5ace677cec91a359bfb875370139505efdea10 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 17 Sep 2024 12:35:08 +0200 Subject: [PATCH 115/123] refactor: refs #7893 Requested changes --- db/routines/bs/procedures/waste_addSales.sql | 6 ++++++ db/versions/11240-aquaCyca/00-firstScript.sql | 1 + 2 files changed, 7 insertions(+) create mode 100644 db/versions/11240-aquaCyca/00-firstScript.sql diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index 128c4f2db..ea4adbc27 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -4,6 +4,12 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`( vDateTo DATE ) BEGIN +/** + * Recalcula las mermas de un periodo. + * + * @param vDateFrom Fecha desde + * @param vDateTo Fecha hasta + */ IF vDateFrom IS NULL THEN SET vDateFrom = util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY; END IF; diff --git a/db/versions/11240-aquaCyca/00-firstScript.sql b/db/versions/11240-aquaCyca/00-firstScript.sql new file mode 100644 index 000000000..97ad39ef1 --- /dev/null +++ b/db/versions/11240-aquaCyca/00-firstScript.sql @@ -0,0 +1 @@ +GRANT EXECUTE ON PROCEDURE bs.waste_addSales TO buyerBoss; From 7cd8e535f0fc85deedb6ff66e28f182fa848564a Mon Sep 17 00:00:00 2001 From: ivanm Date: Tue, 17 Sep 2024 16:19:09 +0200 Subject: [PATCH 116/123] refactor: refs #7934 Delete vn.MIDNIGHT function --- db/routines/vn/functions/MIDNIGHT.sql | 8 ----- db/routines/vn/functions/routeProposal_.sql | 30 ------------------- .../vn/procedures/itemShelvingProblem.sql | 2 +- db/routines/vn/views/ticketStateToday.sql | 2 +- 4 files changed, 2 insertions(+), 40 deletions(-) delete mode 100644 db/routines/vn/functions/MIDNIGHT.sql delete mode 100644 db/routines/vn/functions/routeProposal_.sql diff --git a/db/routines/vn/functions/MIDNIGHT.sql b/db/routines/vn/functions/MIDNIGHT.sql deleted file mode 100644 index d40734fcf..000000000 --- a/db/routines/vn/functions/MIDNIGHT.sql +++ /dev/null @@ -1,8 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`MIDNIGHT`(vDate DATE) - RETURNS datetime - DETERMINISTIC -BEGIN - RETURN TIMESTAMP(vDate,'23:59:59'); -END$$ -DELIMITER ; diff --git a/db/routines/vn/functions/routeProposal_.sql b/db/routines/vn/functions/routeProposal_.sql deleted file mode 100644 index a307d8fc0..000000000 --- a/db/routines/vn/functions/routeProposal_.sql +++ /dev/null @@ -1,30 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`routeProposal_`(vTicketFk INT) - RETURNS int(11) - NOT DETERMINISTIC - READS SQL DATA -BEGIN - - DECLARE vRouteFk INT; - DECLARE vAddressFk INT; - DECLARE vShipped DATETIME; - - SELECT addressFk, date(shipped) INTO vAddressFk, vShipped - FROM vn.ticket - WHERE id = vTicketFk; - - SELECT routeFk INTO vRouteFk - FROM - (SELECT t.routeFk, sum(af.friendship) friendshipSum - FROM vn.ticket t - JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk - WHERE t.shipped BETWEEN vShipped and MIDNIGHT(vShipped) - AND t.routeFk - GROUP BY routeFk - ORDER BY friendshipSum DESC - ) sub - LIMIT 1; - - RETURN vRouteFk; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingProblem.sql b/db/routines/vn/procedures/itemShelvingProblem.sql index bb4725434..06c7a376c 100644 --- a/db/routines/vn/procedures/itemShelvingProblem.sql +++ b/db/routines/vn/procedures/itemShelvingProblem.sql @@ -38,7 +38,7 @@ BEGIN AND IFNULL(sub3.transit,0) < s.quantity AND s.isPicked = FALSE AND s.reserved = FALSE - AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) + AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() AND tst.isPreviousPreparable = TRUE AND t.warehouseFk = vWarehouseFk AND iss.sectorFk = vSectorFk diff --git a/db/routines/vn/views/ticketStateToday.sql b/db/routines/vn/views/ticketStateToday.sql index 0c9e01188..8c11fcc87 100644 --- a/db/routines/vn/views/ticketStateToday.sql +++ b/db/routines/vn/views/ticketStateToday.sql @@ -13,4 +13,4 @@ FROM ( `vn`.`ticketState` `ts` JOIN `vn`.`ticket` `t` ON(`t`.`id` = `ts`.`ticketFk`) ) -WHERE `t`.`shipped` BETWEEN `util`.`VN_CURDATE`() AND `MIDNIGHT`(`util`.`VN_CURDATE`()) +WHERE `t`.`shipped` BETWEEN `util`.`VN_CURDATE`() AND `util`.`midnight`() From 829ecba2ef57050e54369a4bce6e4c123c3a15a1 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Sep 2024 08:30:05 +0200 Subject: [PATCH 117/123] refactor: refs #7792 revert TwoFactorType --- back/methods/vn-user/sign-in.js | 8 +++--- back/methods/vn-user/specs/sign-in.spec.js | 2 +- back/methods/vn-user/update-user.js | 8 +++--- back/methods/vn-user/validate-auth.js | 2 +- back/models/vn-user.json | 10 +++---- .../vn/triggers/department_afterUpdate.sql | 4 +-- .../11218-pinkRaphis/00-firstScript.sql | 12 ++++----- .../components/change-password/index.html | 2 +- .../back/methods/account/change-password.js | 4 +-- .../account/specs/change-password.spec.js | 2 +- modules/account/back/model-config.json | 3 --- .../account/back/models/two-factor-type.json | 26 ------------------- myt.config.yml | 1 - 13 files changed, 26 insertions(+), 58 deletions(-) delete mode 100644 modules/account/back/models/two-factor-type.json diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index d74c486c3..775970d55 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -33,7 +33,7 @@ module.exports = Self => { const where = Self.userUses(user); const vnUser = await Self.findOne({ - fields: ['id', 'name', 'password', 'active', 'email', 'passExpired', 'twoFactorFk'], + fields: ['id', 'name', 'password', 'active', 'email', 'passExpired', 'twoFactor'], where }, myOptions); @@ -46,7 +46,7 @@ module.exports = Self => { await Self.sendTwoFactor(ctx, vnUser, myOptions); await Self.passExpired(vnUser, myOptions); - if (vnUser.twoFactorFk) + if (vnUser.twoFactor) throw new ForbiddenError(null, 'REQUIRES_2FA'); } return Self.validateLogin(user, password, ctx); @@ -58,13 +58,13 @@ module.exports = Self => { if (vnUser.passExpired && vnUser.passExpired.getTime() <= today.getTime()) { const err = new UserError('Pass expired', 'passExpired'); - err.details = {userId: vnUser.id, twoFactorFk: vnUser.twoFactorFk ? true : false}; + err.details = {userId: vnUser.id, twoFactor: vnUser.twoFactor ? true : false}; throw err; } }; Self.sendTwoFactor = async(ctx, vnUser, myOptions) => { - if (vnUser.twoFactorFk === 'email') { + if (vnUser.twoFactor === 'email') { const $ = Self.app.models; const min = 100000; diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index 331173d38..a14dd301e 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -70,7 +70,7 @@ describe('VnUser Sign-in()', () => { let error; try { const options = {transaction: tx}; - await employee.updateAttribute('twoFactorFk', 'email', options); + await employee.updateAttribute('twoFactor', 'email', options); await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options); await tx.rollback(); diff --git a/back/methods/vn-user/update-user.js b/back/methods/vn-user/update-user.js index b0ac40192..202b01c65 100644 --- a/back/methods/vn-user/update-user.js +++ b/back/methods/vn-user/update-user.js @@ -25,8 +25,8 @@ module.exports = Self => { type: 'string', description: 'The user lang' }, { - arg: 'twoFactorFk', - type: 'any', + arg: 'twoFactor', + type: 'string', description: 'The user twoFactor' } ], @@ -36,8 +36,8 @@ module.exports = Self => { } }); - Self.updateUser = async(ctx, id, name, nickname, email, lang, twoFactorFk) => { + Self.updateUser = async(ctx, id, name, nickname, email, lang, twoFactor) => { await Self.userSecurity(ctx, id); - await Self.upsertWithWhere({id}, {name, nickname, email, lang, twoFactorFk}); + await Self.upsertWithWhere({id}, {name, nickname, email, lang, twoFactor}); }; }; diff --git a/back/methods/vn-user/validate-auth.js b/back/methods/vn-user/validate-auth.js index 56f0f9c5f..8fb8b4923 100644 --- a/back/methods/vn-user/validate-auth.js +++ b/back/methods/vn-user/validate-auth.js @@ -55,7 +55,7 @@ module.exports = Self => { throw new UserError('Invalid or expired verification code'); const user = await Self.findById(authCode.userFk, { - fields: ['name', 'twoFactorFk'] + fields: ['name', 'twoFactor'] }, myOptions); if (user.name.toLowerCase() !== username.toLowerCase()) diff --git a/back/models/vn-user.json b/back/models/vn-user.json index b107a8e52..8c49c8db9 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -58,6 +58,9 @@ }, "passExpired": { "type": "date" + }, + "twoFactor": { + "type": "string" } }, "relations": { @@ -86,11 +89,6 @@ "type": "hasOne", "model": "UserConfig", "foreignKey": "userFk" - }, - "twoFactor": { - "type": "belongsTo", - "model": "TwoFactorType", - "foreignKey": "twoFactorFk" } }, "acls": [ @@ -168,7 +166,7 @@ "realm", "email", "emailVerified", - "twoFactorFk" + "twoFactor" ] } } diff --git a/db/routines/vn/triggers/department_afterUpdate.sql b/db/routines/vn/triggers/department_afterUpdate.sql index 216af0e68..559fad9a3 100644 --- a/db/routines/vn/triggers/department_afterUpdate.sql +++ b/db/routines/vn/triggers/department_afterUpdate.sql @@ -7,10 +7,10 @@ BEGIN UPDATE vn.department_recalc SET isChanged = TRUE; END IF; - IF !(OLD.twoFactorFk <=> NEW.twoFactorFk) THEN + IF !(OLD.twoFactor <=> NEW.twoFactor) THEN UPDATE account.user u JOIN vn.workerDepartment wd ON wd.workerFk = u.id - SET u.twoFactorFk = NEW.twoFactorFk + SET u.twoFactor = NEW.twoFactor WHERE wd.departmentFk = NEW.id; END IF; END$$ diff --git a/db/versions/11218-pinkRaphis/00-firstScript.sql b/db/versions/11218-pinkRaphis/00-firstScript.sql index 21bbe3bfc..8efa18cd0 100644 --- a/db/versions/11218-pinkRaphis/00-firstScript.sql +++ b/db/versions/11218-pinkRaphis/00-firstScript.sql @@ -4,23 +4,23 @@ CREATE OR REPLACE TABLE account.twoFactorType ( PRIMARY KEY (`code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -ALTER TABLE account.user ADD twoFactorFk varchar(20) NULL; -ALTER TABLE account.user ADD CONSTRAINT user_twoFactor_fk FOREIGN KEY (twoFactorFk) REFERENCES account.twoFactorType(code) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE account.user ADD twoFactor varchar(20) NULL; +ALTER TABLE account.user ADD CONSTRAINT user_twoFactor_fk FOREIGN KEY (twoFactor) REFERENCES account.twoFactorType(code) ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE vn.department ADD twoFactorFk varchar(20) NULL; -ALTER TABLE vn.department ADD CONSTRAINT department_twoFactor_fk FOREIGN KEY (twoFactorFk) REFERENCES account.twoFactorType(code) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE vn.department ADD twoFactor varchar(20) NULL; +ALTER TABLE vn.department ADD CONSTRAINT department_twoFactor_fk FOREIGN KEY (twoFactor) REFERENCES account.twoFactorType(code) ON DELETE CASCADE ON UPDATE CASCADE; INSERT INTO account.twoFactorType (code, description) VALUES('email', 'Envia un código por email'); UPDATE account.`user` u JOIN account.`user` u2 ON u.id = u2.id - SET u.twoFactorFk = u.twoFactor + SET u.twoFactor = u.twoFactor WHERE u2.twoFactor IS NOT NULL; UPDATE vn.`department` d JOIN vn.`department` d2 ON d.id = d2.id - SET d.twoFactorFk = d.twoFactor + SET d.twoFactor = d.twoFactor WHERE d2.twoFactor IS NOT NULL; ALTER TABLE account.user CHANGE twoFactor twoFactor__ enum('email') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL COMMENT 'Deprecated 2024-09-09'; diff --git a/front/salix/components/change-password/index.html b/front/salix/components/change-password/index.html index 9021c51b2..04f66976e 100644 --- a/front/salix/components/change-password/index.html +++ b/front/salix/components/change-password/index.html @@ -22,7 +22,7 @@ autocomplete="false"> { Object.assign(myOptions, options); const {VnUser} = Self.app.models; - const user = await VnUser.findById(userId, {fields: ['name', 'twoFactorFk']}, myOptions); + const user = await VnUser.findById(userId, {fields: ['name', 'twoFactor']}, myOptions); await user.hasPassword(oldPassword); if (oldPassword == newPassword) throw new UserError(`You can not use the same password`); - if (user.twoFactorFk) + if (user.twoFactor) await VnUser.validateCode(user.name, code, myOptions); await VnUser.changePassword(userId, oldPassword, newPassword, myOptions); diff --git a/modules/account/back/methods/account/specs/change-password.spec.js b/modules/account/back/methods/account/specs/change-password.spec.js index f3573f41c..c79960212 100644 --- a/modules/account/back/methods/account/specs/change-password.spec.js +++ b/modules/account/back/methods/account/specs/change-password.spec.js @@ -75,7 +75,7 @@ describe('account changePassword()', () => { await models.VnUser.updateAll( {id: 70}, { - twoFactorFk: 'email', + twoFactor: 'email', passExpired: yesterday } , options); diff --git a/modules/account/back/model-config.json b/modules/account/back/model-config.json index d79d5de45..cfec1fbe4 100644 --- a/modules/account/back/model-config.json +++ b/modules/account/back/model-config.json @@ -50,9 +50,6 @@ "SipConfig": { "dataSource": "vn" }, - "TwoFactorType": { - "dataSource": "vn" - }, "UserLog": { "dataSource": "vn" }, diff --git a/modules/account/back/models/two-factor-type.json b/modules/account/back/models/two-factor-type.json deleted file mode 100644 index ce4a99858..000000000 --- a/modules/account/back/models/two-factor-type.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "TwoFactorType", - "base": "VnModel", - "options": { - "mysql": { - "table": "account.twoFactorType" - } - }, - "properties": { - "code": { - "type": "string", - "id": true - }, - "description": { - "type": "string" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] -} diff --git a/myt.config.yml b/myt.config.yml index 87407bac3..dcda2d04b 100755 --- a/myt.config.yml +++ b/myt.config.yml @@ -38,7 +38,6 @@ fixtures: - userPassword - accountConfig - mailConfig - - twoFactorType salix: - ACL - fieldAcl From c75cc87129039f54f1969fdb3cbfc76b76c6ac7c Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Sep 2024 08:31:26 +0200 Subject: [PATCH 118/123] refactor: refs #7792 revert TwoFactorType --- .../11218-pinkRaphis/00-firstScript.sql | 27 ------------------- 1 file changed, 27 deletions(-) delete mode 100644 db/versions/11218-pinkRaphis/00-firstScript.sql diff --git a/db/versions/11218-pinkRaphis/00-firstScript.sql b/db/versions/11218-pinkRaphis/00-firstScript.sql deleted file mode 100644 index 8efa18cd0..000000000 --- a/db/versions/11218-pinkRaphis/00-firstScript.sql +++ /dev/null @@ -1,27 +0,0 @@ -CREATE OR REPLACE TABLE account.twoFactorType ( - `code` varchar(20) NOT NULL, - `description` varchar(255) NOT NULL, - PRIMARY KEY (`code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; - -ALTER TABLE account.user ADD twoFactor varchar(20) NULL; -ALTER TABLE account.user ADD CONSTRAINT user_twoFactor_fk FOREIGN KEY (twoFactor) REFERENCES account.twoFactorType(code) ON DELETE CASCADE ON UPDATE CASCADE; - -ALTER TABLE vn.department ADD twoFactor varchar(20) NULL; -ALTER TABLE vn.department ADD CONSTRAINT department_twoFactor_fk FOREIGN KEY (twoFactor) REFERENCES account.twoFactorType(code) ON DELETE CASCADE ON UPDATE CASCADE; - -INSERT INTO account.twoFactorType (code, description) - VALUES('email', 'Envia un código por email'); - -UPDATE account.`user` u - JOIN account.`user` u2 ON u.id = u2.id - SET u.twoFactor = u.twoFactor - WHERE u2.twoFactor IS NOT NULL; - -UPDATE vn.`department` d - JOIN vn.`department` d2 ON d.id = d2.id - SET d.twoFactor = d.twoFactor - WHERE d2.twoFactor IS NOT NULL; - -ALTER TABLE account.user CHANGE twoFactor twoFactor__ enum('email') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL COMMENT 'Deprecated 2024-09-09'; -ALTER TABLE vn.department CHANGE twoFactor twoFactor__ enum('email') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL COMMENT 'Deprecated 2024-09-09'; From e523b12536527d2b1ebfa71c473d2a217c676d67 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Sep 2024 09:50:55 +0200 Subject: [PATCH 119/123] fix: refs #7792 enable null --- back/methods/vn-user/update-user.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/vn-user/update-user.js b/back/methods/vn-user/update-user.js index 202b01c65..2bb390cf9 100644 --- a/back/methods/vn-user/update-user.js +++ b/back/methods/vn-user/update-user.js @@ -26,7 +26,7 @@ module.exports = Self => { description: 'The user lang' }, { arg: 'twoFactor', - type: 'string', + type: 'any', description: 'The user twoFactor' } ], From c30ecd3760c873a3df9eb6616cc4a330570e4b1f Mon Sep 17 00:00:00 2001 From: ivanm Date: Thu, 19 Sep 2024 12:26:06 +0200 Subject: [PATCH 120/123] feat: refs #7343 Modify driverRouteEmail.js --- .../back/methods/route/driverRouteEmail.js | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/modules/route/back/methods/route/driverRouteEmail.js b/modules/route/back/methods/route/driverRouteEmail.js index bbac2b0e8..467528989 100644 --- a/modules/route/back/methods/route/driverRouteEmail.js +++ b/modules/route/back/methods/route/driverRouteEmail.js @@ -39,6 +39,8 @@ module.exports = Self => { const {reportMail} = agencyMode(); let user; let account; + let userEmail = null; + let reportEmails = reportMail ? reportMail.split(',').map(email => email.trim()) : []; if (workerFk) { user = await models.VnUser.findById(workerFk, { @@ -48,10 +50,22 @@ module.exports = Self => { account = await models.Account.findById(workerFk); } - if (user?.active && account) ctx.args.recipient = user.emailUser().email; - else ctx.args.recipient = reportMail; + if (user?.active && account) { + userEmail = user.emailUser().email; + } - if (!ctx.args.recipient) throw new UserError('An email is necessary'); + let recipients = reportEmails; + if (userEmail) { + recipients.push(userEmail); + } + + recipients = [...new Set(recipients)]; + + if (recipients.length === 0) { + throw new UserError('An email is necessary'); + } + + ctx.args.recipients = recipients; return Self.sendTemplate(ctx, 'driver-route'); }; }; From c82c9395a4e9d0ab883dd7830804db3402c4fe82 Mon Sep 17 00:00:00 2001 From: ivanm Date: Thu, 19 Sep 2024 12:49:45 +0200 Subject: [PATCH 121/123] feat: refs #7343 Requested changes --- .../back/methods/route/driverRouteEmail.js | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/modules/route/back/methods/route/driverRouteEmail.js b/modules/route/back/methods/route/driverRouteEmail.js index 467528989..62147db87 100644 --- a/modules/route/back/methods/route/driverRouteEmail.js +++ b/modules/route/back/methods/route/driverRouteEmail.js @@ -39,8 +39,8 @@ module.exports = Self => { const {reportMail} = agencyMode(); let user; let account; - let userEmail = null; - let reportEmails = reportMail ? reportMail.split(',').map(email => email.trim()) : []; + let userEmail; + ctx.args.recipients = reportMail ? reportMail.split(',').map(email => email.trim()) : []; if (workerFk) { user = await models.VnUser.findById(workerFk, { @@ -50,22 +50,17 @@ module.exports = Self => { account = await models.Account.findById(workerFk); } - if (user?.active && account) { + if (user?.active && account) userEmail = user.emailUser().email; - } - let recipients = reportEmails; - if (userEmail) { - recipients.push(userEmail); - } + if (userEmail) + ctx.args.recipients.push(userEmail); - recipients = [...new Set(recipients)]; + ctx.args.recipients = [...new Set(ctx.args.recipients)]; - if (recipients.length === 0) { + if (!ctx.args.recipients.length) throw new UserError('An email is necessary'); - } - ctx.args.recipients = recipients; return Self.sendTemplate(ctx, 'driver-route'); }; }; From e8add6e61490129cc165f83b00e69c5edf6255c6 Mon Sep 17 00:00:00 2001 From: Pako Date: Fri, 20 Sep 2024 10:12:24 +0200 Subject: [PATCH 122/123] feat(TPV): refs #7999 new frmLongTermStorage Parking table foreign key updated Old proc removed Refs: #7999 --- .../vn/procedures/itemFuentesBalance.sql | 79 ------------------- .../11249-crimsonPhormium/00-firstScript.sql | 3 + 2 files changed, 3 insertions(+), 79 deletions(-) delete mode 100644 db/routines/vn/procedures/itemFuentesBalance.sql create mode 100644 db/versions/11249-crimsonPhormium/00-firstScript.sql diff --git a/db/routines/vn/procedures/itemFuentesBalance.sql b/db/routines/vn/procedures/itemFuentesBalance.sql deleted file mode 100644 index d6961a05f..000000000 --- a/db/routines/vn/procedures/itemFuentesBalance.sql +++ /dev/null @@ -1,79 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemFuentesBalance`(vDaysInFuture INT) -BEGIN - - /* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro - * - * @param vDaysInFuture Rango de dias para calcular entradas y salidas - * - */ - - DECLARE vWarehouseFk INT; - - SELECT s.warehouseFk INTO vWarehouseFk - FROM vn.sector s - WHERE s.code = 'FUENTES_PICASSE'; - - CALL cache.stock_refresh(FALSE); - - SELECT i.id itemFk, - i.longName, - i.size, - i.subName, - v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, - fue.Fuentes, - alb.Albenfruit, - sale.venta, - IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, - IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN ( - SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes - FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk - WHERE s.code = 'FUENTES_PICASSE' - GROUP BY ish.itemFk - ) fue ON fue.itemFk = i.id - LEFT JOIN ( - SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit - FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk - WHERE s.code = 'ALBENFRUIT' - GROUP BY ish.itemFk - ) alb ON alb.itemFk = i.id - LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk - LEFT JOIN ( - SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta - FROM itemTicketOut - WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) - AND warehouseFk = vWarehouseFk - GROUP BY itemFk - ) sale ON sale.item_id = i.id - LEFT JOIN ( - SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra - FROM itemEntryIn - WHERE landed BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) - AND warehouseInFk = vWarehouseFk - AND isVirtualStock = FALSE - GROUP BY itemFk - ) buy ON buy.item_id = i.id - LEFT JOIN ( - SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado - FROM itemEntryOut - WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) - AND warehouseOutFk = vWarehouseFk - GROUP BY itemFk - ) mov ON mov.item_id = i.id - WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) - AND i.itemPackingTypeFk = 'H' - AND ic.shortLife; - -END$$ -DELIMITER ; diff --git a/db/versions/11249-crimsonPhormium/00-firstScript.sql b/db/versions/11249-crimsonPhormium/00-firstScript.sql new file mode 100644 index 000000000..32410c561 --- /dev/null +++ b/db/versions/11249-crimsonPhormium/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE vn.parking DROP FOREIGN KEY IF EXISTS parking_fk1; +ALTER TABLE vn.parking ADD CONSTRAINT parking_fk1 FOREIGN KEY (sectorFk) REFERENCES vn.sector(id) ON DELETE RESTRICT ON UPDATE CASCADE; From 06f8f8e95e09739be81ee2915d6a5cc95f75f271 Mon Sep 17 00:00:00 2001 From: ivanm Date: Sun, 22 Sep 2024 08:39:19 +0200 Subject: [PATCH 123/123] refactor: refs #7725 deprecate worker.isF11Allowed --- db/versions/11255-maroonRaphis/00-firstScript.sql | 2 ++ modules/worker/back/locale/worker/en.yml | 1 - modules/worker/back/locale/worker/es.yml | 1 - modules/worker/back/models/worker.json | 3 --- 4 files changed, 2 insertions(+), 5 deletions(-) create mode 100644 db/versions/11255-maroonRaphis/00-firstScript.sql diff --git a/db/versions/11255-maroonRaphis/00-firstScript.sql b/db/versions/11255-maroonRaphis/00-firstScript.sql new file mode 100644 index 000000000..7febf0e6c --- /dev/null +++ b/db/versions/11255-maroonRaphis/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.worker + CHANGE isF11Allowed isF11Allowed__ TINYINT(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-09-22'; \ No newline at end of file diff --git a/modules/worker/back/locale/worker/en.yml b/modules/worker/back/locale/worker/en.yml index 8438c15cf..ae3053af1 100644 --- a/modules/worker/back/locale/worker/en.yml +++ b/modules/worker/back/locale/worker/en.yml @@ -14,7 +14,6 @@ columns: hasMachineryAuthorized: machinery authorized seniority: seniority isTodayRelative: today relative - isF11Allowed: F11 allowed sectorFk: sector maritalStatus: marital status labelerFk: labeler diff --git a/modules/worker/back/locale/worker/es.yml b/modules/worker/back/locale/worker/es.yml index 96616d7d2..330d266c8 100644 --- a/modules/worker/back/locale/worker/es.yml +++ b/modules/worker/back/locale/worker/es.yml @@ -14,7 +14,6 @@ columns: hasMachineryAuthorized: maquinaria autorizada seniority: antigüedad isTodayRelative: relativo hoy - isF11Allowed: F11 autorizado sectorFk: sector maritalStatus: estado civil labelerFk: etiquetadora diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index a700f4c78..b896e775b 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -55,9 +55,6 @@ "birth": { "type": "date" }, - "isF11Allowed": { - "type": "boolean" - }, "sex": { "type": "string" },