diff --git a/.eslintrc.yml b/.eslintrc.yml index ee20324ff..edbc47195 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -17,7 +17,7 @@ rules: camelcase: 0 default-case: 0 no-eq-null: 0 - no-console: ["error"] + no-console: ["warn"] no-warning-comments: 0 no-empty: [error, allowEmptyCatch: true] complexity: 0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 8967a1633..cbfc6e9e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,19 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2328.01] - 2023-07-13 + +### Added + +### Changed + +### Fixed + + ## [2326.01] - 2023-06-29 ### Added +- (Entradas -> Correo) Al cambiar el tipo de cambio enviará un correo a las personas designadas ### Changed diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js new file mode 100644 index 000000000..41470dfea --- /dev/null +++ b/back/methods/vn-user/renew-token.js @@ -0,0 +1,39 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('renewToken', { + description: 'Checks if the token has more than renewPeriod seconds to live and if so, renews it', + accessType: 'WRITE', + accepts: [], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/renewToken`, + verb: 'POST' + } + }); + + Self.renewToken = async function(ctx) { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + const created = ctx.req.accessToken.created; + const tokenId = ctx.req.accessToken.id; + + const now = new Date(); + const differenceMilliseconds = now - created; + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + + const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']}); + + if (differenceSeconds <= accessTokenConfig.renewPeriod) + throw new UserError(`The renew period has not been exceeded`); + + await Self.logout(tokenId); + const user = await Self.findById(userId); + const accessToken = await user.createAccessToken(); + + return {token: accessToken.id, created: accessToken.created}; + }; +}; diff --git a/back/methods/vn-user/signIn.js b/back/methods/vn-user/signIn.js index 6615cb5f1..c98f1da54 100644 --- a/back/methods/vn-user/signIn.js +++ b/back/methods/vn-user/signIn.js @@ -76,6 +76,6 @@ module.exports = Self => { let loginInfo = Object.assign({password}, userInfo); token = await Self.login(loginInfo, 'user'); - return {token: token.id}; + return {token: token.id, created: token.created}; }; }; diff --git a/back/methods/vn-user/specs/signIn.js b/back/methods/vn-user/specs/signIn.spec.js similarity index 91% rename from back/methods/vn-user/specs/signIn.js rename to back/methods/vn-user/specs/signIn.spec.js index b46c645d6..c3f4630c6 100644 --- a/back/methods/vn-user/specs/signIn.js +++ b/back/methods/vn-user/specs/signIn.spec.js @@ -9,7 +9,7 @@ describe('VnUser signIn()', () => { expect(login.token).toBeDefined(); - await models.VnUser.signOut(ctx); + await models.VnUser.logout(ctx.req.accessToken.id); }); it('should return the token if the user doesnt exist but the client does', async() => { @@ -19,7 +19,7 @@ describe('VnUser signIn()', () => { expect(login.token).toBeDefined(); - await models.VnUser.signOut(ctx); + await models.VnUser.logout(ctx.req.accessToken.id); }); }); diff --git a/back/methods/vn-user/specs/signOut.js b/back/methods/vn-user/specs/signOut.js deleted file mode 100644 index c84e86f05..000000000 --- a/back/methods/vn-user/specs/signOut.js +++ /dev/null @@ -1,42 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('VnUser signOut()', () => { - it('should logout and remove token after valid login', async() => { - let loginResponse = await models.VnUser.signOut('buyer', 'nightmare'); - let accessToken = await models.AccessToken.findById(loginResponse.token); - let ctx = {req: {accessToken: accessToken}}; - - let logoutResponse = await models.VnUser.signOut(ctx); - let tokenAfterLogout = await models.AccessToken.findById(loginResponse.token); - - expect(logoutResponse).toBeTrue(); - expect(tokenAfterLogout).toBeNull(); - }); - - it('should throw a 401 error when token is invalid', async() => { - let error; - let ctx = {req: {accessToken: {id: 'invalidToken'}}}; - - try { - response = await models.VnUser.signOut(ctx); - } catch (e) { - error = e; - } - - expect(error).toBeDefined(); - expect(error.statusCode).toBe(401); - }); - - it('should throw an error when no token is passed', async() => { - let error; - let ctx = {req: {accessToken: null}}; - - try { - response = await models.VnUser.signOut(ctx); - } catch (e) { - error = e; - } - - expect(error).toBeDefined(); - }); -}); diff --git a/back/model-config.json b/back/model-config.json index ff2bf5850..d945f3250 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -2,6 +2,14 @@ "AccountingType": { "dataSource": "vn" }, + "AccessTokenConfig": { + "dataSource": "vn", + "options": { + "mysql": { + "table": "salix.accessTokenConfig" + } + } + }, "Bank": { "dataSource": "vn" }, diff --git a/back/models/access-token-config.json b/back/models/access-token-config.json new file mode 100644 index 000000000..6d90a0f4d --- /dev/null +++ b/back/models/access-token-config.json @@ -0,0 +1,30 @@ +{ + "name": "AccessTokenConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "accessTokenConfig" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "renewPeriod": { + "type": "number", + "required": true + }, + "renewInterval": { + "type": "number", + "required": true + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} diff --git a/back/models/vn-user.js b/back/models/vn-user.js index fb3279353..b58395acc 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -10,6 +10,9 @@ module.exports = function(Self) { require('../methods/vn-user/recover-password')(Self); require('../methods/vn-user/validate-token')(Self); require('../methods/vn-user/privileges')(Self); + require('../methods/vn-user/renew-token')(Self); + + Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create'); // Validations diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 8486e29b8..61e42f77a 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -118,5 +118,24 @@ "principalId": "$authenticated", "permission": "ALLOW" } - ] + ], + "scopes": { + "preview": { + "fields": [ + "id", + "name", + "username", + "roleFk", + "nickname", + "lang", + "active", + "created", + "updated", + "image", + "hasGrant", + "realm", + "email" + ] + } + } } diff --git a/db/changes/231801/00-userAcl.sql b/db/changes/231801/00-userAcl.sql index 64803bf18..9eb3ebf28 100644 --- a/db/changes/231801/00-userAcl.sql +++ b/db/changes/231801/00-userAcl.sql @@ -1,6 +1,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES - ('VnUser', '*', '*', 'ALLOW', 'ROLE', 'employee'), ('VnUser','acl','READ','ALLOW','ROLE','account'), ('VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'), ('VnUser','changePassword', 'WRITE', 'ALLOW', 'ROLE', 'account'), diff --git a/db/changes/232601/00-aclAccount.sql b/db/changes/232601/00-aclAccount.sql new file mode 100644 index 000000000..bf8106b98 --- /dev/null +++ b/db/changes/232601/00-aclAccount.sql @@ -0,0 +1,8 @@ +DELETE + FROM `salix`.`ACL` + WHERE model='Account' AND property='*' AND accessType='*'; + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('Account', '*', 'WRITE', 'ALLOW', 'ROLE', 'sysadmin'), + ('Account', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/232601/00-aclMailAliasAccount.sql b/db/changes/232601/00-aclMailAliasAccount.sql new file mode 100644 index 000000000..619e9bb6e --- /dev/null +++ b/db/changes/232601/00-aclMailAliasAccount.sql @@ -0,0 +1,5 @@ +DELETE FROM `salix`.`ACL` WHERE model = 'MailAliasAccount'; +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('MailAliasAccount', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('MailAliasAccount', '*', 'WRITE', 'ALLOW', 'ROLE', 'itManagement'); diff --git a/db/changes/232601/00-aclMailForward.sql b/db/changes/232601/00-aclMailForward.sql new file mode 100644 index 000000000..afe2acec8 --- /dev/null +++ b/db/changes/232601/00-aclMailForward.sql @@ -0,0 +1,5 @@ +DELETE FROM `salix`.`ACL` WHERE model = 'MailForward'; +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('MailForward', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('MailForward', '*', 'WRITE', 'ALLOW', 'ROLE', 'itManagement'); diff --git a/db/changes/232601/00-aclRole.sql b/db/changes/232601/00-aclRole.sql new file mode 100644 index 000000000..e16f052be --- /dev/null +++ b/db/changes/232601/00-aclRole.sql @@ -0,0 +1,5 @@ +DELETE FROM `salix`.`ACL` WHERE model = 'Role'; +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('Role', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Role', '*', 'WRITE', 'ALLOW', 'ROLE', 'it'); diff --git a/db/changes/232601/00-aclVnUser.sql b/db/changes/232601/00-aclVnUser.sql new file mode 100644 index 000000000..39fa2cb14 --- /dev/null +++ b/db/changes/232601/00-aclVnUser.sql @@ -0,0 +1,10 @@ +DELETE + FROM `salix`.`ACL` + WHERE model = 'VnUser' AND property = '*' AND principalId = 'employee'; + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('VnUser', '*', '*', 'ALLOW', 'ROLE', 'itManagement'), + ('VnUser', '__get__preview', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('VnUser', 'preview', '*', 'ALLOW', 'ROLE', 'employee'), + ('VnUser', 'create', '*', 'ALLOW', 'ROLE', 'itManagement'); diff --git a/db/changes/232601/00-aclVnUser_renewToken.sql b/db/changes/232601/00-aclVnUser_renewToken.sql new file mode 100644 index 000000000..aa20f7a82 --- /dev/null +++ b/db/changes/232601/00-aclVnUser_renewToken.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('VnUser', 'renewToken', 'WRITE', 'ALLOW', 'ROLE', 'employee') diff --git a/db/changes/232601/00-entry_updateComission.sql b/db/changes/232601/00-entry_updateComission.sql new file mode 100644 index 000000000..5a25d72e8 --- /dev/null +++ b/db/changes/232601/00-entry_updateComission.sql @@ -0,0 +1,40 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_updateComission`(vCurrency INT) +BEGIN +/** + * Actualiza la comision de las entradas de hoy a futuro y las recalcula + * + * @param vCurrency id del tipo de moneda(SAR,EUR,USD,GBP,JPY) + */ + DECLARE vCurrencyName VARCHAR(25); + DECLARE vComission INT; + + CREATE OR REPLACE TEMPORARY TABLE tmp.recalcEntryCommision + SELECT e.id + FROM vn.entry e + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk + WHERE t.shipped >= util.VN_CURDATE() + AND e.currencyFk = vCurrency; + + SET vComission = currency_getCommission(vCurrency); + + UPDATE vn.entry e + JOIN tmp.recalcEntryCommision tmp ON tmp.id = e.id + SET e.commission = vComission; + + SELECT `name` INTO vCurrencyName + FROM currency + WHERE id = vCurrency; + + CALL entry_recalc(); + SELECT util.notification_send( + 'entry-update-comission', + JSON_OBJECT('currencyName', vCurrencyName, 'referenceCurrent', vComission), + account.myUser_getId() + ); + + DROP TEMPORARY TABLE tmp.recalcEntryCommision; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/232601/00-salix.sql b/db/changes/232601/00-salix.sql new file mode 100644 index 000000000..dc1ed69be --- /dev/null +++ b/db/changes/232601/00-salix.sql @@ -0,0 +1,10 @@ +CREATE TABLE `salix`.`accessTokenConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `renewPeriod` int(10) unsigned DEFAULT NULL, + `renewInterval` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `renewInterval`) + VALUES + (1, 21600, 300); diff --git a/db/changes/232601/01-invoiceOutPdf.sql b/db/changes/232601/01-invoiceOutPdf.sql new file mode 100644 index 000000000..38e0b8bbb --- /dev/null +++ b/db/changes/232601/01-invoiceOutPdf.sql @@ -0,0 +1,13 @@ +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES + ('InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'), + ('InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'); + +CREATE OR REPLACE TABLE vn.invoiceOutConfig ( + id INT UNSIGNED auto_increment NOT NULL, + parallelism int UNSIGNED DEFAULT 1 NOT NULL, + PRIMARY KEY (id) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; diff --git a/db/changes/232801/.gitkeep b/db/changes/232801/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 3f4433fa1..c4338a555 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -603,6 +603,9 @@ UPDATE `vn`.`invoiceOut` SET ref = 'T3333333' WHERE id = 3; UPDATE `vn`.`invoiceOut` SET ref = 'T4444444' WHERE id = 4; UPDATE `vn`.`invoiceOut` SET ref = 'A1111111' WHERE id = 5; +INSERT INTO vn.invoiceOutConfig + SET parallelism = 8; + INSERT INTO `vn`.`invoiceOutTax` (`invoiceOutFk`, `taxableBase`, `vat`, `pgcFk`) VALUES (1, 895.76, 89.58, 4722000010), @@ -2895,6 +2898,10 @@ INSERT INTO `vn`.`wagonTypeTray` (`id`, `typeFk`, `height`, `colorFk`) (2, 1, 50, 2), (3, 1, 0, 3); +INSERT INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `renewInterval`) + VALUES + (1, 21600, 300); + INSERT INTO `vn`.`travelConfig` (`id`, `warehouseInFk`, `warehouseOutFk`, `agencyFk`, `companyFk`) VALUES (1, 1, 1, 1, 442); diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index b8eaa99a1..5c6350ba5 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -1179,8 +1179,6 @@ export default { allBuyCheckbox: 'vn-entry-buy-index thead vn-check', firstBuyCheckbox: 'vn-entry-buy-index tbody:nth-child(2) vn-check', deleteBuysButton: 'vn-entry-buy-index vn-button[icon="delete"]', - addBuyButton: 'vn-entry-buy-index vn-icon[icon="add"]', - secondBuyPackingPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.price3"]', secondBuyGroupingPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.price2"]', secondBuyPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.buyingValue"]', secondBuyGrouping: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.grouping"]', diff --git a/e2e/paths/03-worker/06_create.spec.js b/e2e/paths/03-worker/06_create.spec.js index 98e67edbf..11d36b3cf 100644 --- a/e2e/paths/03-worker/06_create.spec.js +++ b/e2e/paths/03-worker/06_create.spec.js @@ -53,7 +53,7 @@ describe('Worker create path', () => { expect(message.text).toContain('Data saved!'); // 'rollback' - await page.loginAndModule('sysadmin', 'account'); + await page.loginAndModule('itManagement', 'account'); await page.accessToSearchResult(newWorker); await page.waitToClick(selectors.accountDescriptor.menuButton); diff --git a/e2e/paths/12-entry/07_buys.spec.js b/e2e/paths/12-entry/07_buys.spec.js index e501452bc..28d39fb1d 100644 --- a/e2e/paths/12-entry/07_buys.spec.js +++ b/e2e/paths/12-entry/07_buys.spec.js @@ -66,97 +66,4 @@ describe('Entry import, create and edit buys path', () => { await page.waitToClick(selectors.globalItems.acceptButton); await page.waitForNumberOfElements(selectors.entryBuys.anyBuyLine, 1); }); - - it('should add a new buy', async() => { - await page.waitToClick(selectors.entryBuys.addBuyButton); - await page.write(selectors.entryBuys.secondBuyPackingPrice, '999'); - await page.write(selectors.entryBuys.secondBuyGroupingPrice, '999'); - await page.write(selectors.entryBuys.secondBuyPrice, '999'); - await page.write(selectors.entryBuys.secondBuyGrouping, '999'); - await page.write(selectors.entryBuys.secondBuyPacking, '999'); - await page.write(selectors.entryBuys.secondBuyWeight, '999'); - await page.write(selectors.entryBuys.secondBuyStickers, '999'); - await page.autocompleteSearch(selectors.entryBuys.secondBuyPackage, '1'); - await page.write(selectors.entryBuys.secondBuyQuantity, '999'); - await page.autocompleteSearch(selectors.entryBuys.secondBuyItem, '1'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - - await page.waitForNumberOfElements(selectors.entryBuys.anyBuyLine, 2); - }); - - it('should edit the newest buy and check data', async() => { - await page.clearInput(selectors.entryBuys.secondBuyPackingPrice); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyPackingPrice, '100'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyGroupingPrice); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyGroupingPrice, '200'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyPrice); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyPrice, '300'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyGrouping); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyGrouping, '400'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyPacking); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyPacking, '500'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyWeight); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyWeight, '600'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyStickers); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyStickers, '700'); - await page.keyboard.press('Enter'); - await page.waitForSnackbar(); - - await page.autocompleteSearch(selectors.entryBuys.secondBuyPackage, '94'); - await page.waitForSnackbar(); - - await page.clearInput(selectors.entryBuys.secondBuyQuantity); - await page.waitForTimeout(250); - await page.write(selectors.entryBuys.secondBuyQuantity, '800'); - await page.keyboard.press('Enter'); - - await page.reloadSection('entry.card.buy.index'); - - const secondBuyPackingPrice = await page.getValue(selectors.entryBuys.secondBuyPackingPrice); - const secondBuyGroupingPrice = await page.getValue(selectors.entryBuys.secondBuyGroupingPrice); - const secondBuyPrice = await page.getValue(selectors.entryBuys.secondBuyPrice); - const secondBuyGrouping = await page.getValue(selectors.entryBuys.secondBuyGrouping); - const secondBuyPacking = await page.getValue(selectors.entryBuys.secondBuyPacking); - const secondBuyWeight = await page.getValue(selectors.entryBuys.secondBuyWeight); - const secondBuyStickers = await page.getValue(selectors.entryBuys.secondBuyStickers); - const secondBuyPackage = await page.getValue(selectors.entryBuys.secondBuyPackage); - const secondBuyQuantity = await page.getValue(selectors.entryBuys.secondBuyQuantity); - - expect(secondBuyPackingPrice).toEqual('100'); - expect(secondBuyGroupingPrice).toEqual('200'); - expect(secondBuyPrice).toEqual('300'); - expect(secondBuyGrouping).toEqual('400'); - expect(secondBuyPacking).toEqual('500'); - expect(secondBuyWeight).toEqual('600'); - expect(secondBuyStickers).toEqual('700'); - expect(secondBuyPackage).toEqual('94'); - expect(secondBuyQuantity).toEqual('800'); - }); }); diff --git a/e2e/paths/14-account/01_create_and_basic_data.spec.js b/e2e/paths/14-account/01_create_and_basic_data.spec.js index 54e4d1f12..e38d1aeec 100644 --- a/e2e/paths/14-account/01_create_and_basic_data.spec.js +++ b/e2e/paths/14-account/01_create_and_basic_data.spec.js @@ -8,7 +8,7 @@ describe('Account create and basic data path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('developer', 'account'); + await page.loginAndModule('itManagement', 'account'); }); afterAll(async() => { diff --git a/front/core/services/auth.js b/front/core/services/auth.js index 41cd27f03..ef6c07637 100644 --- a/front/core/services/auth.js +++ b/front/core/services/auth.js @@ -64,7 +64,7 @@ export default class Auth { } onLoginOk(json, remember) { - this.vnToken.set(json.data.token, remember); + this.vnToken.set(json.data.token, json.data.created, remember); return this.loadAcls().then(() => { let continueHash = this.$state.params.continue; diff --git a/front/core/services/index.js b/front/core/services/index.js index 867a13df0..855f2fab1 100644 --- a/front/core/services/index.js +++ b/front/core/services/index.js @@ -11,3 +11,4 @@ import './report'; import './email'; import './file'; import './date'; + diff --git a/front/core/services/token.js b/front/core/services/token.js index 126fbb604..c1bb5a173 100644 --- a/front/core/services/token.js +++ b/front/core/services/token.js @@ -9,25 +9,33 @@ export default class Token { constructor() { try { this.token = sessionStorage.getItem('vnToken'); - if (!this.token) + this.created = sessionStorage.getItem('vnTokenCreated'); + if (!this.token) { this.token = localStorage.getItem('vnToken'); + this.created = localStorage.getItem('vnTokenCreated'); + } } catch (e) {} } - set(value, remember) { + set(token, created, remember) { this.unset(); try { - if (remember) - localStorage.setItem('vnToken', value); - else - sessionStorage.setItem('vnToken', value); + if (remember) { + localStorage.setItem('vnToken', token); + localStorage.setItem('vnTokenCreated', created); + } else { + sessionStorage.setItem('vnToken', token); + sessionStorage.setItem('vnTokenCreated', created); + } } catch (e) {} - this.token = value; + this.token = token; + this.created = created; } unset() { localStorage.removeItem('vnToken'); sessionStorage.removeItem('vnToken'); this.token = null; + this.created = null; } } diff --git a/front/salix/components/layout/index.js b/front/salix/components/layout/index.js index 48f50f404..dc2313f4f 100644 --- a/front/salix/components/layout/index.js +++ b/front/salix/components/layout/index.js @@ -3,13 +3,14 @@ import Component from 'core/lib/component'; import './style.scss'; export class Layout extends Component { - constructor($element, $, vnModules) { + constructor($element, $, vnModules, vnToken) { super($element, $); this.modules = vnModules.get(); } $onInit() { this.getUserData(); + this.getAccessTokenConfig(); } getUserData() { @@ -30,8 +31,42 @@ export class Layout extends Component { refresh() { window.location.reload(); } + + getAccessTokenConfig() { + this.$http.get('AccessTokenConfigs').then(json => { + const firtsResult = json.data[0]; + if (!firtsResult) return; + this.renewPeriod = firtsResult.renewPeriod; + this.renewInterval = firtsResult.renewInterval; + + const intervalMilliseconds = firtsResult.renewInterval * 1000; + this.inservalId = setInterval(this.checkTokenValidity.bind(this), intervalMilliseconds); + }); + } + + checkTokenValidity() { + const now = new Date(); + const differenceMilliseconds = now - new Date(this.vnToken.created); + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + + if (differenceSeconds > this.renewPeriod) { + this.$http.post('VnUsers/renewToken') + .then(json => { + if (json.data.token) { + let remember = true; + if (window.sessionStorage.vnToken) remember = false; + + this.vnToken.set(json.data.token, json.data.created, remember); + } + }); + } + } + + $onDestroy() { + clearInterval(this.inservalId); + } } -Layout.$inject = ['$element', '$scope', 'vnModules']; +Layout.$inject = ['$element', '$scope', 'vnModules', 'vnToken']; ngModule.vnComponent('vnLayout', { template: require('./index.html'), diff --git a/front/salix/components/layout/index.spec.js b/front/salix/components/layout/index.spec.js index 0d70c4806..8f65f32ce 100644 --- a/front/salix/components/layout/index.spec.js +++ b/front/salix/components/layout/index.spec.js @@ -37,4 +37,49 @@ describe('Component vnLayout', () => { expect(url).not.toBeDefined(); }); }); + + describe('getAccessTokenConfig()', () => { + it(`should set the renewPeriod and renewInterval properties in localStorage`, () => { + const response = [{ + renewPeriod: 100, + renewInterval: 5 + }]; + + $httpBackend.expect('GET', `AccessTokenConfigs`).respond(response); + controller.getAccessTokenConfig(); + $httpBackend.flush(); + + expect(controller.renewPeriod).toBe(100); + expect(controller.renewInterval).toBe(5); + expect(controller.inservalId).toBeDefined(); + }); + }); + + describe('checkTokenValidity()', () => { + it(`should not call renewToken and not set vnToken in the controller`, () => { + controller.renewPeriod = 100; + controller.vnToken.created = new Date(); + + controller.checkTokenValidity(); + + expect(controller.vnToken.token).toBeNull(); + }); + + it(`should call renewToken and set vnToken properties in the controller`, () => { + const response = { + token: 999, + created: new Date() + }; + controller.renewPeriod = 100; + const oneHourBefore = new Date(Date.now() - (60 * 60 * 1000)); + controller.vnToken.created = oneHourBefore; + + $httpBackend.expect('POST', `VnUsers/renewToken`).respond(response); + controller.checkTokenValidity(); + $httpBackend.flush(); + + expect(controller.vnToken.token).toBe(999); + expect(controller.vnToken.created).toEqual(response.created); + }); + }); }); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 43ff4b86a..40df9a712 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -115,7 +115,7 @@ "This client is not invoiceable": "This client is not invoiceable", "INACTIVE_PROVIDER": "Inactive provider", "reference duplicated": "reference duplicated", - "The PDF document does not exists": "The PDF document does not exists. Try regenerating it from 'Regenerate invoice PDF' option", + "The PDF document does not exist": "The PDF document does not exists. Try regenerating it from 'Regenerate invoice PDF' option", "This item is not available": "This item is not available", "Deny buy request": "Purchase request for ticket id [{{ticketId}}]({{{url}}}) has been rejected. Reason: {{observation}}", "The type of business must be filled in basic data": "The type of business must be filled in basic data", @@ -175,5 +175,6 @@ "Pass expired": "The password has expired, change it from Salix", "Can't transfer claimed sales": "Can't transfer claimed sales", "Invalid quantity": "Invalid quantity", - "Failed to upload delivery note": "Error to upload delivery note {{id}}" + "Failed to upload delivery note": "Error to upload delivery note {{id}}", + "Mail not sent": "There has been an error sending the invoice to the client [{{clientId}}]({{{clientUrl}}}), please check the email address" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 7e2701f95..138fa7100 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -211,7 +211,7 @@ "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas", "Amounts do not match": "Las cantidades no coinciden", - "The PDF document does not exists": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", + "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos", "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días", "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", @@ -265,7 +265,7 @@ "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas", "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.", "There is no assigned email for this client": "No hay correo asignado para este cliente", - "Exists an invoice with a previous date": "Existe una factura con fecha anterior", + "Exists an invoice with a future date": "Existe una factura con fecha posterior", "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite", "Warehouse inventory not set": "El almacén inventario no está establecido", "This locker has already been assigned": "Esta taquilla ya ha sido asignada", @@ -293,5 +293,10 @@ "Pass expired": "La contraseña ha caducado, cambiela desde Salix", "Invalid NIF for VIES": "Invalid NIF for VIES", "Ticket does not exist": "Este ticket no existe", - "Ticket is already signed": "Este ticket ya ha sido firmado" + "Ticket is already signed": "Este ticket ya ha sido firmado", + "Fecha fuera de rango": "Fecha fuera de rango", + "Error while generating PDF": "Error al generar PDF", + "Error when sending mail to client": "Error al enviar el correo al cliente", + "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", + "The renew period has not been exceeded": "El periodo de renovación no ha sido superado" } diff --git a/modules/account/front/aliases/index.html b/modules/account/front/aliases/index.html index 9f4ba857f..11d546afb 100644 --- a/modules/account/front/aliases/index.html +++ b/modules/account/front/aliases/index.html @@ -17,7 +17,9 @@ + ng-click="removeConfirm.show(row)" + vn-acl="itManagement" + vn-acl-action="remove"> @@ -30,9 +32,11 @@ translate-attr="{title: 'Add'}" vn-bind="+" ng-click="$ctrl.onAddClick()" - fixed-bottom-right> + fixed-bottom-right + vn-acl="itManagement" + vn-acl-action="remove"> - @@ -49,7 +53,7 @@ - this.user = res.data), + this.$http.get(`VnUsers/preview`, {filter}) + .then(res => { + const [user] = res.data; + this.user = user; + }), this.$http.get(`Accounts/${this.$params.id}/exists`) .then(res => this.hasAccount = res.data.exists) ]); diff --git a/modules/account/front/card/index.spec.js b/modules/account/front/card/index.spec.js index 204b897e4..712d3c1d8 100644 --- a/modules/account/front/card/index.spec.js +++ b/modules/account/front/card/index.spec.js @@ -15,12 +15,12 @@ describe('component vnUserCard', () => { it('should reload the controller data', () => { controller.$params.id = 1; - $httpBackend.expectGET('VnUsers/1').respond('foo'); + $httpBackend.expectGET('VnUsers/preview').respond('foo'); $httpBackend.expectGET('Accounts/1/exists').respond({exists: true}); controller.reload(); $httpBackend.flush(); - expect(controller.user).toBe('foo'); + expect(controller.user).toBe('f'); expect(controller.hasAccount).toBeTruthy(); }); }); diff --git a/modules/account/front/create/index.html b/modules/account/front/create/index.html index ee2de926a..acc07d346 100644 --- a/modules/account/front/create/index.html +++ b/modules/account/front/create/index.html @@ -12,18 +12,18 @@ @@ -39,7 +39,7 @@ type="password"> diff --git a/modules/account/front/create/index.js b/modules/account/front/create/index.js index 41fd718f6..01ba7905b 100644 --- a/modules/account/front/create/index.js +++ b/modules/account/front/create/index.js @@ -2,6 +2,11 @@ import ngModule from '../module'; import Section from 'salix/components/section'; export default class Controller extends Section { + constructor($element, $) { + super($element, $); + this.user = {active: true}; + } + onSubmit() { return this.$.watcher.submit().then(res => { this.$state.go('account.card.basicData', {id: res.data.id}); diff --git a/modules/account/front/descriptor/index.html b/modules/account/front/descriptor/index.html index 7a7ba43f3..381b2991c 100644 --- a/modules/account/front/descriptor/index.html +++ b/modules/account/front/descriptor/index.html @@ -6,7 +6,7 @@ Delete @@ -15,7 +15,7 @@ ng-if="::$root.user.id == $ctrl.id" ng-click="$ctrl.onChangePassClick(true)" name="changePassword" - vn-acl="hr" + vn-acl="sysadmin" vn-acl-action="remove" translate> Change password @@ -23,7 +23,7 @@ Set password @@ -32,7 +32,7 @@ ng-if="!$ctrl.hasAccount" ng-click="enableAccount.show()" name="enableAccount" - vn-acl="it" + vn-acl="sysadmin" vn-acl-action="remove" translate> Enable account @@ -41,7 +41,7 @@ ng-if="$ctrl.hasAccount" ng-click="disableAccount.show()" name="disableAccount" - vn-acl="it" + vn-acl="sysadmin" vn-acl-action="remove" translate> Disable account @@ -50,7 +50,7 @@ ng-if="!$ctrl.user.active" ng-click="activateUser.show()" name="activateUser" - vn-acl="hr" + vn-acl="itManagement" vn-acl-action="remove" translate> Activate user @@ -59,7 +59,7 @@ ng-if="$ctrl.user.active" ng-click="deactivateUser.show()" name="deactivateUser" - vn-acl="hr" + vn-acl="itManagement" vn-acl-action="remove" translate> Deactivate user diff --git a/modules/account/front/index/index.html b/modules/account/front/index/index.html index d067c8c37..7502c8b3d 100644 --- a/modules/account/front/index/index.html +++ b/modules/account/front/index/index.html @@ -14,11 +14,11 @@
{{::user.nickname}}
@@ -36,12 +36,12 @@ - - \ No newline at end of file + diff --git a/modules/account/front/mail-forwarding/index.html b/modules/account/front/mail-forwarding/index.html index 6c688f504..df5cd80bf 100644 --- a/modules/account/front/mail-forwarding/index.html +++ b/modules/account/front/mail-forwarding/index.html @@ -14,12 +14,12 @@ Todos los correos serán reenviados a la dirección especificada, no se mantendrá copia de los mismos en el buzón del usuario. +You don't have enough privileges: No tienes suficientes permisos diff --git a/modules/account/front/main/index.html b/modules/account/front/main/index.html index 5872a328d..36b493ec4 100644 --- a/modules/account/front/main/index.html +++ b/modules/account/front/main/index.html @@ -1,6 +1,6 @@ diff --git a/modules/account/front/privileges/index.html b/modules/account/front/privileges/index.html index 8e33b708e..61f2c534e 100644 --- a/modules/account/front/privileges/index.html +++ b/modules/account/front/privileges/index.html @@ -1,9 +1,7 @@ @@ -11,15 +9,16 @@ name="form" ng-submit="watcher.submit()" class="vn-w-md"> - + - + + + this.$.summary = res.data); + this.$http.get(`VnUsers/preview`, {filter}) + .then(res => { + const [summary] = res.data; + this.$.summary = summary; + }); } get isHr() { return this.aclService.hasAny(['hr']); diff --git a/modules/client/back/locale/client/en.yml b/modules/client/back/locale/client/en.yml index 74384461c..ad21a6ce6 100644 --- a/modules/client/back/locale/client/en.yml +++ b/modules/client/back/locale/client/en.yml @@ -52,4 +52,5 @@ columns: hasInvoiceSimplified: simplified invoice typeFk: type lastSalesPersonFk: last salesperson - + rating: rating + recommendedCredit: recommended credit diff --git a/modules/client/back/locale/client/es.yml b/modules/client/back/locale/client/es.yml index 47bf896d9..b17f53b1c 100644 --- a/modules/client/back/locale/client/es.yml +++ b/modules/client/back/locale/client/es.yml @@ -52,4 +52,5 @@ columns: hasInvoiceSimplified: factura simple typeFk: tipo lastSalesPersonFk: último comercial - + rating: clasificación + recommendedCredit: crédito recomendado diff --git a/modules/client/front/web-access/index.html b/modules/client/front/web-access/index.html index 15dc5ed58..74407ba5c 100644 --- a/modules/client/front/web-access/index.html +++ b/modules/client/front/web-access/index.html @@ -1,7 +1,5 @@ @@ -51,9 +49,9 @@ label="Save"> + ng-if="$ctrl.canChangePassword" + label="Change password" + vn-dialog="change-pass"> { + const [user] = res.data; + this.account = user; + }); + } + + get client() { + return this._client; + } + $onChanges() { if (this.client) { this.account = this.client.account; diff --git a/modules/client/front/web-access/index.spec.js b/modules/client/front/web-access/index.spec.js index c1bb47a8e..7325bf932 100644 --- a/modules/client/front/web-access/index.spec.js +++ b/modules/client/front/web-access/index.spec.js @@ -5,12 +5,14 @@ describe('Component VnClientWebAccess', () => { let $scope; let vnApp; let controller; + let $httpParamSerializer; beforeEach(ngModule('client')); - beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _vnApp_) => { + beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_, _vnApp_) => { $scope = $rootScope.$new(); $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; vnApp = _vnApp_; jest.spyOn(vnApp, 'showError'); const $element = angular.element(''); @@ -32,7 +34,10 @@ describe('Component VnClientWebAccess', () => { describe('isCustomer()', () => { it('should return true if the password can be modified', () => { controller.client = {id: '1234'}; + const filter = {where: {id: controller.client.id}}; + const serializedParams = $httpParamSerializer({filter}); + $httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo'); $httpBackend.expectGET(`Clients/${controller.client.id}/hasCustomerRole`).respond(true); controller.isCustomer(); $httpBackend.flush(); @@ -42,7 +47,10 @@ describe('Component VnClientWebAccess', () => { it(`should return a false if the password can't be modified`, () => { controller.client = {id: '1234'}; + const filter = {where: {id: controller.client.id}}; + const serializedParams = $httpParamSerializer({filter}); + $httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo'); $httpBackend.expectGET(`Clients/${controller.client.id}/hasCustomerRole`).respond(false); controller.isCustomer(); $httpBackend.flush(); @@ -54,9 +62,12 @@ describe('Component VnClientWebAccess', () => { describe('checkConditions()', () => { it('should perform a query to check if the client is valid', () => { controller.client = {id: '1234'}; + const filter = {where: {id: controller.client.id}}; + const serializedParams = $httpParamSerializer({filter}); expect(controller.canEnableCheckBox).toBeTruthy(); + $httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo'); $httpBackend.expectGET(`Clients/${controller.client.id}/isValidClient`).respond(false); controller.checkConditions(); $httpBackend.flush(); @@ -82,7 +93,10 @@ describe('Component VnClientWebAccess', () => { controller.newPassword = 'm24x8'; controller.repeatPassword = 'm24x8'; controller.canChangePassword = true; + const filter = {where: {id: controller.client.id}}; + const serializedParams = $httpParamSerializer({filter}); + $httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo'); const query = `Clients/${controller.client.id}/setPassword`; $httpBackend.expectPATCH(query, {newPassword: controller.newPassword}).respond('done'); controller.onPassChange(); diff --git a/modules/entry/back/methods/entry/addBuy.js b/modules/entry/back/methods/entry/addBuy.js deleted file mode 100644 index f612c1651..000000000 --- a/modules/entry/back/methods/entry/addBuy.js +++ /dev/null @@ -1,165 +0,0 @@ - -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -module.exports = Self => { - Self.remoteMethodCtx('addBuy', { - description: 'Inserts a new buy for the current entry', - accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'number', - required: true, - description: 'The entry id', - http: {source: 'path'} - }, - { - arg: 'itemFk', - type: 'number', - required: true - }, - { - arg: 'quantity', - type: 'number', - required: true - }, - { - arg: 'packageFk', - type: 'string', - required: true - }, - { - arg: 'packing', - type: 'number', - }, - { - arg: 'grouping', - type: 'number' - }, - { - arg: 'weight', - type: 'number', - }, - { - arg: 'stickers', - type: 'number', - }, - { - arg: 'price2', - type: 'number', - }, - { - arg: 'price3', - type: 'number', - }, - { - arg: 'buyingValue', - type: 'number' - }], - returns: { - type: 'object', - root: true - }, - http: { - path: `/:id/addBuy`, - verb: 'POST' - } - }); - - Self.addBuy = async(ctx, options) => { - const conn = Self.dataSource.connector; - let tx; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const models = Self.app.models; - - ctx.args.entryFk = ctx.args.id; - - // remove unwanted properties - delete ctx.args.id; - delete ctx.args.ctx; - - const newBuy = await models.Buy.create(ctx.args, myOptions); - - const filter = { - fields: [ - 'id', - 'itemFk', - 'stickers', - 'packing', - 'grouping', - 'quantity', - 'packageFk', - 'weight', - 'buyingValue', - 'price2', - 'price3' - ], - include: { - relation: 'item', - scope: { - fields: [ - 'id', - 'typeFk', - 'name', - 'size', - 'minPrice', - 'tag5', - 'value5', - 'tag6', - 'value6', - 'tag7', - 'value7', - 'tag8', - 'value8', - 'tag9', - 'value9', - 'tag10', - 'value10', - 'groupingMode' - ], - include: { - relation: 'itemType', - scope: { - fields: ['code', 'description'] - } - } - } - } - }; - - const stmts = []; - let stmt; - - stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc'); - stmt = new ParameterizedSQL( - `CREATE TEMPORARY TABLE tmp.buyRecalc - (INDEX (id)) - ENGINE = MEMORY - SELECT ? AS id`, [newBuy.id]); - - stmts.push(stmt); - stmts.push('CALL buy_recalcPrices()'); - - const sql = ParameterizedSQL.join(stmts, ';'); - await conn.executeStmt(sql, myOptions); - - const buy = await models.Buy.findById(newBuy.id, filter, myOptions); - - if (tx) await tx.commit(); - - return buy; - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/entry/back/methods/entry/editLatestBuys.js b/modules/entry/back/methods/entry/editLatestBuys.js index 2642d4f4d..0da2b1625 100644 --- a/modules/entry/back/methods/entry/editLatestBuys.js +++ b/modules/entry/back/methods/entry/editLatestBuys.js @@ -75,7 +75,7 @@ module.exports = Self => { value[field] = newValue; if (filter) { - ctx.args.filter = {where: filter, limit: null}; + ctx.args = {where: filter, limit: null}; lines = await models.Buy.latestBuysFilter(ctx, null, myOptions); } diff --git a/modules/entry/back/methods/entry/specs/addBuy.spec.js b/modules/entry/back/methods/entry/specs/addBuy.spec.js deleted file mode 100644 index ead75f2d2..000000000 --- a/modules/entry/back/methods/entry/specs/addBuy.spec.js +++ /dev/null @@ -1,42 +0,0 @@ -const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - -describe('entry addBuy()', () => { - const activeCtx = { - accessToken: {userId: 18}, - }; - - const ctx = { - req: activeCtx - }; - - const entryId = 2; - it('should create a new buy for the given entry', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - const itemId = 4; - const quantity = 10; - - ctx.args = { - id: entryId, - itemFk: itemId, - quantity: quantity, - packageFk: 3 - }; - - const tx = await models.Entry.beginTransaction({}); - const options = {transaction: tx}; - - try { - const newBuy = await models.Entry.addBuy(ctx, options); - - expect(newBuy.itemFk).toEqual(itemId); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js index 99d2df67b..a4dd185fd 100644 --- a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js @@ -53,7 +53,36 @@ describe('Buy editLatestsBuys()', () => { const options = {transaction: tx}; try { - const filter = {'i.typeFk': 1}; + const filter = {'categoryFk': 1, 'tags': []}; + const ctx = { + args: { + filter: filter + }, + req: {accessToken: {userId: 1}} + }; + + const field = 'size'; + const newValue = 88; + + await models.Buy.editLatestBuys(ctx, field, newValue, null, filter, options); + + const [result] = await models.Buy.latestBuysFilter(ctx, null, options); + + expect(result[field]).toEqual(newValue); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should change the value of a given column for filter tags', async() => { + const tx = await models.Buy.beginTransaction({}); + const options = {transaction: tx}; + + try { + const filter = {'tags': [{tagFk: 1, value: 'Brown'}]}; const ctx = { args: { filter: filter diff --git a/modules/entry/back/models/entry.js b/modules/entry/back/models/entry.js index 0eabd70ee..6148ae559 100644 --- a/modules/entry/back/models/entry.js +++ b/modules/entry/back/models/entry.js @@ -3,7 +3,6 @@ module.exports = Self => { require('../methods/entry/filter')(Self); require('../methods/entry/getEntry')(Self); require('../methods/entry/getBuys')(Self); - require('../methods/entry/addBuy')(Self); require('../methods/entry/importBuys')(Self); require('../methods/entry/importBuysPreview')(Self); require('../methods/entry/lastItemBuys')(Self); diff --git a/modules/entry/front/buy/index/index.html b/modules/entry/front/buy/index/index.html index e6d1a0b76..28fdabdb4 100644 --- a/modules/entry/front/buy/index/index.html +++ b/modules/entry/front/buy/index/index.html @@ -222,13 +222,6 @@
- - { if (!res.data) return; diff --git a/modules/entry/front/buy/index/index.spec.js b/modules/entry/front/buy/index/index.spec.js index aff52bc80..0e221302c 100644 --- a/modules/entry/front/buy/index/index.spec.js +++ b/modules/entry/front/buy/index/index.spec.js @@ -25,17 +25,6 @@ describe('Entry buy', () => { controller.saveBuy(buy); $httpBackend.flush(); }); - - it(`should call the entry addBuy post route if the received buy has no ID`, () => { - controller.entry = {id: 1}; - const buy = {itemFk: 1, quantity: 1, packageFk: 1}; - - const query = `Entries/${controller.entry.id}/addBuy`; - - $httpBackend.expectPOST(query).respond(200); - controller.saveBuy(buy); - $httpBackend.flush(); - }); }); describe('deleteBuys()', () => { diff --git a/modules/invoiceOut/back/methods/invoiceOut/createPdf.js b/modules/invoiceOut/back/methods/invoiceOut/createPdf.js index dfdb3c1a7..8cc584c94 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/createPdf.js +++ b/modules/invoiceOut/back/methods/invoiceOut/createPdf.js @@ -1,5 +1,4 @@ const UserError = require('vn-loopback/util/user-error'); -const print = require('vn-print'); module.exports = Self => { Self.remoteMethodCtx('createPdf', { @@ -26,9 +25,6 @@ module.exports = Self => { Self.createPdf = async function(ctx, id, options) { const models = Self.app.models; - if (process.env.NODE_ENV == 'test') - throw new UserError(`Action not allowed on the test environment`); - let tx; const myOptions = {}; @@ -41,40 +37,20 @@ module.exports = Self => { } try { - const invoiceOut = await Self.findById(id, null, myOptions); - const canCreatePdf = await models.ACL.checkAccessAcl(ctx, 'InvoiceOut', 'canCreatePdf', 'WRITE'); + const invoiceOut = await Self.findById(id, {fields: ['hasPdf']}, myOptions); - if (invoiceOut.hasPdf && !canCreatePdf) - throw new UserError(`You don't have enough privileges`); + if (invoiceOut.hasPdf) { + const canCreatePdf = await models.ACL.checkAccessAcl(ctx, 'InvoiceOut', 'canCreatePdf', 'WRITE'); + if (!canCreatePdf) + throw new UserError(`You don't have enough privileges`); + } - await invoiceOut.updateAttributes({ - hasPdf: true - }, myOptions); - - const invoiceReport = new print.Report('invoice', { - reference: invoiceOut.ref, - recipientId: invoiceOut.clientFk - }); - const buffer = await invoiceReport.toPdfStream(); - - const issued = invoiceOut.issued; - const year = issued.getFullYear().toString(); - const month = (issued.getMonth() + 1).toString(); - const day = issued.getDate().toString(); - - const fileName = `${year}${invoiceOut.ref}.pdf`; - - // Store invoice - await print.storage.write(buffer, { - type: 'invoice', - path: `${year}/${month}/${day}`, - fileName: fileName - }); + await Self.makePdf(id, myOptions); if (tx) await tx.commit(); - } catch (e) { + } catch (err) { if (tx) await tx.rollback(); - throw e; + throw err; } }; }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/download.js b/modules/invoiceOut/back/methods/invoiceOut/download.js index 5c787428b..49bba046b 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/download.js +++ b/modules/invoiceOut/back/methods/invoiceOut/download.js @@ -43,7 +43,9 @@ module.exports = Self => { Object.assign(myOptions, options); try { - const invoiceOut = await models.InvoiceOut.findById(id, null, myOptions); + const invoiceOut = await models.InvoiceOut.findById(id, { + fields: ['ref', 'issued'] + }, myOptions); const issued = invoiceOut.issued; const year = issued.getFullYear().toString(); @@ -73,7 +75,7 @@ module.exports = Self => { return [stream, file.contentType, `filename="${file.name}"`]; } catch (error) { if (error.code === 'ENOENT') - throw new UserError('The PDF document does not exists'); + throw new UserError('The PDF document does not exist'); throw error; } diff --git a/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js b/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js index 421cbaea1..ab076b46f 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js +++ b/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js @@ -30,15 +30,10 @@ module.exports = Self => { type: 'number', description: 'The company id to invoice', required: true - }, { - arg: 'printerFk', - type: 'number', - description: 'The printer to print', - required: true } ], returns: { - type: 'object', + type: 'number', root: true }, http: { @@ -50,26 +45,23 @@ module.exports = Self => { Self.invoiceClient = async(ctx, options) => { const args = ctx.args; const models = Self.app.models; - const myOptions = {userId: ctx.req.accessToken.userId}; + + options = typeof options == 'object' + ? Object.assign({}, options) : {}; + options.userId = ctx.req.accessToken.userId; + let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } + if (!options.transaction) + tx = options.transaction = await Self.beginTransaction({}); const minShipped = Date.vnNew(); minShipped.setFullYear(args.maxShipped.getFullYear() - 1); let invoiceId; - let invoiceOut; try { const client = await models.Client.findById(args.clientId, { fields: ['id', 'hasToInvoiceByAddress'] - }, myOptions); + }, options); if (client.hasToInvoiceByAddress) { await Self.rawSql('CALL ticketToInvoiceByAddress(?, ?, ?, ?)', [ @@ -77,49 +69,58 @@ module.exports = Self => { args.maxShipped, args.addressId, args.companyFk - ], myOptions); + ], options); } else { await Self.rawSql('CALL invoiceFromClient(?, ?, ?)', [ args.maxShipped, client.id, args.companyFk - ], myOptions); + ], options); } - // Make invoice - const isSpanishCompany = await getIsSpanishCompany(args.companyFk, myOptions); + // Check negative bases - // Validates ticket nagative base - const hasAnyNegativeBase = await getNegativeBase(myOptions); + let query = + `SELECT COUNT(*) isSpanishCompany + FROM supplier s + JOIN country c ON c.id = s.countryFk + AND c.code = 'ES' + WHERE s.id = ?`; + const [supplierCompany] = await Self.rawSql(query, [ + args.companyFk + ], options); + + const isSpanishCompany = supplierCompany?.isSpanishCompany; + + query = 'SELECT hasAnyNegativeBase() AS base'; + const [result] = await Self.rawSql(query, null, options); + + const hasAnyNegativeBase = result?.base; if (hasAnyNegativeBase && isSpanishCompany) throw new UserError('Negative basis'); + // Invoicing + query = `SELECT invoiceSerial(?, ?, ?) AS serial`; const [invoiceSerial] = await Self.rawSql(query, [ client.id, args.companyFk, 'G' - ], myOptions); + ], options); const serialLetter = invoiceSerial.serial; query = `CALL invoiceOut_new(?, ?, NULL, @invoiceId)`; await Self.rawSql(query, [ serialLetter, args.invoiceDate - ], myOptions); + ], options); - const [newInvoice] = await Self.rawSql(`SELECT @invoiceId id`, null, myOptions); - if (newInvoice.id) { - await Self.rawSql('CALL invoiceOutBooking(?)', [newInvoice.id], myOptions); + const [newInvoice] = await Self.rawSql(`SELECT @invoiceId id`, null, options); + if (!newInvoice) + throw new UserError('No tickets to invoice', 'notInvoiced'); - invoiceOut = await models.InvoiceOut.findById(newInvoice.id, { - include: { - relation: 'client' - } - }, myOptions); - - invoiceId = newInvoice.id; - } + await Self.rawSql('CALL invoiceOutBooking(?)', [newInvoice.id], options); + invoiceId = newInvoice.id; if (tx) await tx.commit(); } catch (e) { @@ -127,47 +128,6 @@ module.exports = Self => { throw e; } - if (invoiceId) { - if (!invoiceOut.client().isToBeMailed) { - const query = ` - CALL vn.report_print( - 'invoice', - ?, - account.myUser_getId(), - JSON_OBJECT('refFk', ?), - 'normal' - );`; - await models.InvoiceOut.rawSql(query, [args.printerFk, invoiceOut.ref]); - } else { - ctx.args = { - reference: invoiceOut.ref, - recipientId: invoiceOut.clientFk, - recipient: invoiceOut.client().email - }; - await models.InvoiceOut.invoiceEmail(ctx, invoiceOut.ref); - } - } return invoiceId; }; - - async function getNegativeBase(options) { - const models = Self.app.models; - const query = 'SELECT hasAnyNegativeBase() AS base'; - const [result] = await models.InvoiceOut.rawSql(query, null, options); - return result && result.base; - } - - async function getIsSpanishCompany(companyId, options) { - const models = Self.app.models; - const query = `SELECT COUNT(*) isSpanishCompany - FROM supplier s - JOIN country c ON c.id = s.countryFk - AND c.code = 'ES' - WHERE s.id = ?`; - const [supplierCompany] = await models.InvoiceOut.rawSql(query, [ - companyId - ], options); - - return supplierCompany && supplierCompany.isSpanishCompany; - } }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/invoiceEmail.js b/modules/invoiceOut/back/methods/invoiceOut/invoiceEmail.js index 83cb84881..113526484 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/invoiceEmail.js +++ b/modules/invoiceOut/back/methods/invoiceOut/invoiceEmail.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); const {Email} = require('vn-print'); module.exports = Self => { @@ -74,6 +75,10 @@ module.exports = Self => { ] }; - return email.send(mailOptions); + try { + return email.send(mailOptions); + } catch (err) { + throw new UserError('Error when sending mail to client', 'mailNotSent'); + } }; }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js new file mode 100644 index 000000000..a999437c0 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js @@ -0,0 +1,87 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('makePdfAndNotify', { + description: 'Create invoice PDF and send it to client', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'number', + description: 'The invoice id', + required: true, + http: {source: 'path'} + }, { + arg: 'printerFk', + type: 'number', + description: 'The printer to print', + required: true + } + ], + http: { + path: '/:id/makePdfAndNotify', + verb: 'POST' + } + }); + + Self.makePdfAndNotify = async function(ctx, id, printerFk) { + const models = Self.app.models; + + options = typeof options == 'object' + ? Object.assign({}, options) : {}; + options.userId = ctx.req.accessToken.userId; + + try { + await Self.makePdf(id, options); + } catch (err) { + console.error(err); + throw new UserError('Error while generating PDF', 'pdfError'); + } + + const invoiceOut = await Self.findById(id, { + fields: ['ref', 'clientFk'], + include: { + relation: 'client', + scope: { + fields: ['id', 'email', 'isToBeMailed', 'salesPersonFk'] + } + } + }, options); + + const ref = invoiceOut.ref; + const client = invoiceOut.client(); + + if (client.isToBeMailed) { + try { + ctx.args = { + reference: ref, + recipientId: client.id, + recipient: client.email + }; + await Self.invoiceEmail(ctx, ref); + } catch (err) { + const origin = ctx.req.headers.origin; + const message = ctx.req.__('Mail not sent', { + clientId: client.id, + clientUrl: `${origin}/#!/claim/${id}/summary` + }); + const salesPersonId = client.salesPersonFk; + + if (salesPersonId) + await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); + + throw new UserError('Error when sending mail to client', 'mailNotSent'); + } + } else { + const query = ` + CALL vn.report_print( + 'invoice', + ?, + account.myUser_getId(), + JSON_OBJECT('refFk', ?), + 'normal' + );`; + await Self.rawSql(query, [printerFk, ref], options); + } + }; +}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/invoiceClient.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/invoiceClient.spec.js index 9a0574dba..0faa8fe1a 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/invoiceClient.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/invoiceClient.spec.js @@ -18,12 +18,14 @@ describe('InvoiceOut invoiceClient()', () => { accessToken: {userId: userId}, __: value => { return value; - } + }, + headers: {origin: 'http://localhost'} + }; const ctx = {req: activeCtx}; it('should make a global invoicing', async() => { - spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); + spyOn(models.InvoiceOut, 'makePdf').and.returnValue(new Promise(resolve => resolve(true))); spyOn(models.InvoiceOut, 'invoiceEmail'); const tx = await models.InvoiceOut.beginTransaction({}); diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json index b190126ea..9e8b119ab 100644 --- a/modules/invoiceOut/back/model-config.json +++ b/modules/invoiceOut/back/model-config.json @@ -2,6 +2,9 @@ "InvoiceOut": { "dataSource": "vn" }, + "InvoiceOutConfig": { + "dataSource": "vn" + }, "InvoiceOutSerial": { "dataSource": "vn" }, diff --git a/modules/invoiceOut/back/models/invoice-out config.json b/modules/invoiceOut/back/models/invoice-out config.json new file mode 100644 index 000000000..d5595f687 --- /dev/null +++ b/modules/invoiceOut/back/models/invoice-out config.json @@ -0,0 +1,22 @@ +{ + "name": "InvoiceOutConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceOutConfig" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "parallelism": { + "type": "number", + "required": true + } + } +} + + diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index 5fcef7744..9baa1e7e6 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -1,3 +1,5 @@ +const print = require('vn-print'); + module.exports = Self => { require('../methods/invoiceOut/filter')(Self); require('../methods/invoiceOut/summary')(Self); @@ -10,6 +12,7 @@ module.exports = Self => { require('../methods/invoiceOut/createManualInvoice')(Self); require('../methods/invoiceOut/clientsToInvoice')(Self); require('../methods/invoiceOut/invoiceClient')(Self); + require('../methods/invoiceOut/makePdfAndNotify')(Self); require('../methods/invoiceOut/refund')(Self); require('../methods/invoiceOut/invoiceEmail')(Self); require('../methods/invoiceOut/exportationPdf')(Self); @@ -19,4 +22,34 @@ module.exports = Self => { require('../methods/invoiceOut/getInvoiceDate')(Self); require('../methods/invoiceOut/negativeBases')(Self); require('../methods/invoiceOut/negativeBasesCsv')(Self); + + Self.makePdf = async function(id, options) { + const fields = ['id', 'hasPdf', 'ref', 'issued']; + const invoiceOut = await Self.findById(id, {fields}, options); + const invoiceReport = new print.Report('invoice', { + reference: invoiceOut.ref + }); + const buffer = await invoiceReport.toPdfStream(); + + const issued = invoiceOut.issued; + const year = issued.getFullYear().toString(); + const month = (issued.getMonth() + 1).toString(); + const day = issued.getDate().toString(); + + const fileName = `${year}${invoiceOut.ref}.pdf`; + + // Store invoice + + await invoiceOut.updateAttributes({ + hasPdf: true + }, options); + + if (process.env.NODE_ENV !== 'test') { + await print.storage.write(buffer, { + type: 'invoice', + path: `${year}/${month}/${day}`, + fileName: fileName + }); + } + }; }; diff --git a/modules/invoiceOut/front/global-invoicing/index.html b/modules/invoiceOut/front/global-invoicing/index.html index 3f0a10650..3ece30862 100644 --- a/modules/invoiceOut/front/global-invoicing/index.html +++ b/modules/invoiceOut/front/global-invoicing/index.html @@ -1,7 +1,6 @@ + class="status vn-w-lg vn-pa-md"> @@ -20,8 +19,15 @@ Ended process
-
- {{$ctrl.percentage | percentage: 0}} ({{$ctrl.addressNumber}} {{'of' | translate}} {{$ctrl.nAddresses}}) +
+
+ {{$ctrl.percentage | percentage: 0}} + ({{$ctrl.addressNumber}} of {{$ctrl.nAddresses}}) +
+
+ {{$ctrl.nPdfs}} of {{$ctrl.totalPdfs}} + PDFs +
@@ -55,7 +61,11 @@ {{::error.address.nickname}} - {{::error.message}} + + {{::error.message}} + @@ -137,7 +147,7 @@ + ng-click="$ctrl.status = 'stopping'">
diff --git a/modules/invoiceOut/front/global-invoicing/index.js b/modules/invoiceOut/front/global-invoicing/index.js index 5a078dfbb..9a936611a 100644 --- a/modules/invoiceOut/front/global-invoicing/index.js +++ b/modules/invoiceOut/front/global-invoicing/index.js @@ -7,32 +7,29 @@ class Controller extends Section { $onInit() { const date = Date.vnNew(); Object.assign(this, { - maxShipped: new Date(date.getFullYear(), date.getMonth(), 0), - clientsToInvoice: 'all', + maxShipped: new Date(date.getFullYear(), date.getMonth(), 0), + clientsToInvoice: 'all', + companyFk: this.vnConfig.companyFk, + parallelism: 1 }); - this.$http.get('UserConfigs/getUserConfig') - .then(res => { - this.companyFk = res.data.companyFk; - this.getInvoiceDate(this.companyFk); - }); - } + const params = {companyFk: this.companyFk}; + this.$http.get('InvoiceOuts/getInvoiceDate', {params}) + .then(res => { + this.minInvoicingDate = res.data.issued ? new Date(res.data.issued) : null; + this.invoiceDate = this.minInvoicingDate; + }); - getInvoiceDate(companyFk) { - const params = { companyFk: companyFk }; - this.fetchInvoiceDate(params); - } - - fetchInvoiceDate(params) { - this.$http.get('InvoiceOuts/getInvoiceDate', { params }) - .then(res => { - this.minInvoicingDate = res.data.issued ? new Date(res.data.issued) : null; - this.invoiceDate = this.minInvoicingDate; - }); - } - - stopInvoicing() { - this.status = 'stopping'; + const filter = {fields: ['parallelism']}; + this.$http.get('InvoiceOutConfigs/findOne', {filter}) + .then(res => { + if (res.data.parallelism) + this.parallelism = res.data.parallelism; + }) + .catch(res => { + if (res.status == 404) return; + throw res; + }); } makeInvoice() { @@ -49,7 +46,7 @@ class Controller extends Section { if (this.invoiceDate < this.maxShipped) throw new UserError('Invoice date can\'t be less than max date'); if (this.minInvoicingDate && this.invoiceDate.getTime() < this.minInvoicingDate.getTime()) - throw new UserError('Exists an invoice with a previous date'); + throw new UserError('Exists an invoice with a future date'); if (!this.companyFk) throw new UserError('Choose a valid company'); if (!this.printerFk) @@ -70,8 +67,11 @@ class Controller extends Section { if (!this.addresses.length) throw new UserError(`There aren't tickets to invoice`); + this.nRequests = 0; + this.nPdfs = 0; + this.totalPdfs = 0; this.addressIndex = 0; - return this.invoiceOut(); + this.invoiceClient(); }) .catch(err => this.handleError(err)); } catch (err) { @@ -85,8 +85,11 @@ class Controller extends Section { throw err; } - invoiceOut() { - if (this.addressIndex == this.addresses.length || this.status == 'stopping') { + invoiceClient() { + if (this.nRequests == this.parallelism || this.isInvoicing) return; + + if (this.addressIndex >= this.addresses.length || this.status == 'stopping') { + if (this.nRequests) return; this.invoicing = false; this.status = 'done'; return; @@ -95,34 +98,59 @@ class Controller extends Section { this.status = 'invoicing'; const address = this.addresses[this.addressIndex]; this.currentAddress = address; + this.isInvoicing = true; const params = { clientId: address.clientId, addressId: address.id, invoiceDate: this.invoiceDate, maxShipped: this.maxShipped, - companyFk: this.companyFk, - printerFk: this.printerFk, + companyFk: this.companyFk }; this.$http.post(`InvoiceOuts/invoiceClient`, params) - .then(() => this.invoiceNext()) + .then(res => { + this.isInvoicing = false; + if (res.data) + this.makePdfAndNotify(res.data, address); + this.invoiceNext(); + }) .catch(res => { - const message = res.data?.error?.message || res.message; + this.isInvoicing = false; if (res.status >= 400 && res.status < 500) { - this.errors.unshift({address, message}); + this.invoiceError(address, res); this.invoiceNext(); } else { this.invoicing = false; this.status = 'done'; throw new UserError(`Critical invoicing error, proccess stopped`); } - }) + }); } invoiceNext() { this.addressIndex++; - this.invoiceOut(); + this.invoiceClient(); + } + + makePdfAndNotify(invoiceId, address) { + this.nRequests++; + this.totalPdfs++; + const params = {printerFk: this.printerFk}; + this.$http.post(`InvoiceOuts/${invoiceId}/makePdfAndNotify`, params) + .catch(res => { + this.invoiceError(address, res, true); + }) + .finally(() => { + this.nPdfs++; + this.nRequests--; + this.invoiceClient(); + }); + } + + invoiceError(address, res, isWarning) { + const message = res.data?.error?.message || res.message; + this.errors.unshift({address, message, isWarning}); } get nAddresses() { diff --git a/modules/invoiceOut/front/global-invoicing/locale/es.yml b/modules/invoiceOut/front/global-invoicing/locale/es.yml index 5b1f7e883..f1a411ba1 100644 --- a/modules/invoiceOut/front/global-invoicing/locale/es.yml +++ b/modules/invoiceOut/front/global-invoicing/locale/es.yml @@ -10,6 +10,7 @@ Build packaging tickets: Generando tickets de embalajes Address id: Id dirección Printer: Impresora of: de +PDFs: PDFs Client: Cliente Current client id: Id cliente actual Invoicing client: Facturando cliente @@ -18,4 +19,4 @@ Invoice out: Facturar One client: Un solo cliente Choose a valid client: Selecciona un cliente válido Stop: Parar -Critical invoicing error, proccess stopped: Error crítico al facturar, proceso detenido \ No newline at end of file +Critical invoicing error, proccess stopped: Error crítico al facturar, proceso detenido diff --git a/modules/invoiceOut/front/global-invoicing/style.scss b/modules/invoiceOut/front/global-invoicing/style.scss index 6fdfac0ba..3ad767aba 100644 --- a/modules/invoiceOut/front/global-invoicing/style.scss +++ b/modules/invoiceOut/front/global-invoicing/style.scss @@ -1,17 +1,21 @@ @import "variables"; -vn-invoice-out-global-invoicing{ - - h5{ +vn-invoice-out-global-invoicing { + h5 { color: $color-primary; } - + .status { + height: 80px; + display: flex; + align-items: center; + justify-content: center; + gap: 20px; + } #error { line-break: normal; overflow-wrap: break-word; white-space: normal; } - } diff --git a/modules/worker/back/methods/worker/isAuthorized.js b/modules/worker/back/methods/worker/isAuthorized.js new file mode 100644 index 000000000..519aab94f --- /dev/null +++ b/modules/worker/back/methods/worker/isAuthorized.js @@ -0,0 +1,44 @@ +module.exports = Self => { + Self.remoteMethod('isAuthorized', { + description: 'Return true if the current user is a superior of the worker that is passed by parameter', + accessType: 'READ', + accepts: [{ + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }, { + arg: 'id', + type: 'number', + required: true, + description: 'The worker id', + http: {source: 'path'} + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:id/isAuthorized`, + verb: 'GET' + } + }); + + Self.isAuthorized = async(ctx, id, options) => { + const models = Self.app.models; + const currentUserId = ctx.req.accessToken.userId; + const isHimself = currentUserId == id; + + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const isSubordinate = await models.Worker.isSubordinate(ctx, id, myOptions); + const isTeamBoss = await models.VnUser.hasRole(currentUserId, 'teamBoss', myOptions); + + if (!isSubordinate || (isSubordinate && isHimself && !isTeamBoss)) + return false; + + return true; + }; +}; diff --git a/modules/worker/back/models/worker.js b/modules/worker/back/models/worker.js index fa17640a8..b44703a88 100644 --- a/modules/worker/back/models/worker.js +++ b/modules/worker/back/models/worker.js @@ -16,6 +16,7 @@ module.exports = Self => { require('../methods/worker/new')(Self); require('../methods/worker/deallocatePDA')(Self); require('../methods/worker/allocatePDA')(Self); + require('../methods/worker/isAuthorized')(Self); Self.validatesUniquenessOf('locker', { message: 'This locker has already been assigned' diff --git a/modules/worker/front/account/index.html b/modules/worker/front/account/index.html deleted file mode 100644 index 6f6be660c..000000000 --- a/modules/worker/front/account/index.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - -
- - - - - - - - - - - - - -
diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index c9eacbd82..29540081e 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -63,6 +63,7 @@ ng-model="$ctrl.businessId" search-function="{businessFk: $search}" value-field="businessFk" + show-field="businessFk" order="businessFk DESC" limit="5"> diff --git a/modules/worker/front/calendar/index.js b/modules/worker/front/calendar/index.js index 4ca0fc929..a52ecd7da 100644 --- a/modules/worker/front/calendar/index.js +++ b/modules/worker/front/calendar/index.js @@ -71,10 +71,6 @@ class Controller extends Section { } } - get payedHolidays() { - return this._businessId; - } - buildYearFilter() { const now = Date.vnNew(); now.setFullYear(now.getFullYear() + 1); @@ -95,10 +91,10 @@ class Controller extends Section { } getActiveContract() { - this.$http.get(`Workers/${this.worker.id}/activeContract`).then(res => { - if (res.data) - this.businessId = res.data.businessFk; - }); + this.$http.get(`Workers/${this.worker.id}/activeContract`) + .then(res => { + if (res.data) this.businessId = res.data.businessFk; + }); } getContractHolidays() { diff --git a/package.json b/package.json index 4358c86a7..64c374841 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.26.01", + "version": "23.28.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", diff --git a/print/core/components/report-footer/report-footer.js b/print/core/components/report-footer/report-footer.js index 077ef0bde..ed718b8dc 100755 --- a/print/core/components/report-footer/report-footer.js +++ b/print/core/components/report-footer/report-footer.js @@ -5,10 +5,9 @@ module.exports = { name: 'report-footer', async serverPrefetch() { this.company = await db.findOne(` - SELECT IFNULL(ci.footnotes, cl.footnotes) as footnotes + SELECT IFNULL(ci.footnotes, c.footnotes) footnotes FROM company c - LEFT JOIN companyL10n cl ON c.id = cl.id - LEFT JOIN companyI18n ci ON ci.companyFk = cl.id + LEFT JOIN companyI18n ci ON ci.companyFk = c.id AND ci.lang = (SELECT lang FROM account.user where id = ?) WHERE c.code = ?`, [this.recipientId, this.companyCode]); diff --git a/print/core/smtp.js b/print/core/smtp.js index 61b115b5a..04bede5b5 100644 --- a/print/core/smtp.js +++ b/print/core/smtp.js @@ -46,14 +46,21 @@ module.exports = { const fileNames = attachments.join(',\n'); await db.rawSql(` - INSERT INTO vn.mail (receiver, replyTo, sent, subject, body, attachment, status) - VALUES (?, ?, 1, ?, ?, ?, ?)`, [ + INSERT INTO vn.mail + SET receiver = ?, + replyTo = ?, + sent = ?, + subject = ?, + body = ?, + attachment = ?, + status = ?`, [ options.to, options.replyTo, + error ? 2 : 1, options.subject, options.text || options.html, fileNames, - error && error.message || 'Sent' + error && error.message || 'OK' ]); } diff --git a/print/templates/email/entry-update-comission/assets/css/import.js b/print/templates/email/entry-update-comission/assets/css/import.js new file mode 100644 index 000000000..7360587f7 --- /dev/null +++ b/print/templates/email/entry-update-comission/assets/css/import.js @@ -0,0 +1,13 @@ +const Stylesheet = require(`vn-print/core/stylesheet`); + +const path = require('path'); +const vnPrintPath = path.resolve('print'); + +module.exports = new Stylesheet([ + `${vnPrintPath}/common/css/spacing.css`, + `${vnPrintPath}/common/css/misc.css`, + `${vnPrintPath}/common/css/layout.css`, + `${vnPrintPath}/common/css/email.css`, + `${__dirname}/style.css`]) + .mergeStyles(); + diff --git a/print/templates/email/entry-update-comission/assets/css/style.css b/print/templates/email/entry-update-comission/assets/css/style.css new file mode 100644 index 000000000..5db85befa --- /dev/null +++ b/print/templates/email/entry-update-comission/assets/css/style.css @@ -0,0 +1,5 @@ +.external-link { + border: 2px dashed #8dba25; + border-radius: 3px; + text-align: center +} \ No newline at end of file diff --git a/print/templates/email/entry-update-comission/entry-update-comission.html b/print/templates/email/entry-update-comission/entry-update-comission.html new file mode 100644 index 000000000..d3ca1202a --- /dev/null +++ b/print/templates/email/entry-update-comission/entry-update-comission.html @@ -0,0 +1,10 @@ + +
+
+

+ {{$t('dear')}} +

+

+
+
+
diff --git a/print/templates/email/entry-update-comission/entry-update-comission.js b/print/templates/email/entry-update-comission/entry-update-comission.js new file mode 100755 index 000000000..8afe10ea0 --- /dev/null +++ b/print/templates/email/entry-update-comission/entry-update-comission.js @@ -0,0 +1,19 @@ +const Component = require(`vn-print/core/component`); +const emailBody = new Component('email-body'); + +module.exports = { + name: 'entry-update-comission', + components: { + 'email-body': emailBody.build(), + }, + props: { + currencyName: { + type: String, + required: true + }, + referenceCurrent: { + type: Number, + required: true + } + } +}; diff --git a/print/templates/email/entry-update-comission/locale/es.yml b/print/templates/email/entry-update-comission/locale/es.yml new file mode 100644 index 000000000..de58be3e7 --- /dev/null +++ b/print/templates/email/entry-update-comission/locale/es.yml @@ -0,0 +1,4 @@ +subject: Actualización tipo de cambio en entradas +title: Actualización tipo de cambio en entradas +dear: Hola, +body: 'El tipo de cambio para las ENTRADAS/COMPRAS en {0} se ha actualizado a partir de hoy en: {1}' \ No newline at end of file diff --git a/print/templates/reports/invoice/assets/css/style.css b/print/templates/reports/invoice/assets/css/style.css index 9fda2a613..d4526ce56 100644 --- a/print/templates/reports/invoice/assets/css/style.css +++ b/print/templates/reports/invoice/assets/css/style.css @@ -16,6 +16,10 @@ h2 { font-size: 22px } +.column-oriented td, +.column-oriented th { + padding: 6px +} #nickname h2 { max-width: 400px; @@ -39,4 +43,4 @@ h2 { .phytosanitary-info { margin-top: 10px -} \ No newline at end of file +} diff --git a/print/templates/reports/invoice/invoice.html b/print/templates/reports/invoice/invoice.html index d74325dfd..45b6c3934 100644 --- a/print/templates/reports/invoice/invoice.html +++ b/print/templates/reports/invoice/invoice.html @@ -62,7 +62,7 @@ -
+

{{$t('deliveryNote')}}

@@ -106,13 +106,6 @@ {{sale.vatType}} {{saleImport(sale) | currency('EUR', $i18n.locale)}} - - - {{sale.tag5}} {{sale.value5}} - {{sale.tag6}} {{sale.value6}} - {{sale.tag7}} {{sale.value7}} - -