Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix into 5688-worker.calendar_workCenter
gitea/salix/pipeline/head There was a failure building this commit Details

This commit is contained in:
Vicent Llopis 2023-06-22 08:04:17 +02:00
commit 473b218da1
107 changed files with 721 additions and 294 deletions

View File

@ -8,13 +8,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [2326.01] - 2023-06-29 ## [2326.01] - 2023-06-29
### Added ### Added
- (Entradas -> Correo) Al cambiar el tipo de cambio enviará un correo a las personas designadas
### Changed ### Changed
### Fixed ### Fixed
- -
## [2324.01] - 2023-06-08 ## [2324.01] - 2023-06-15
### Added ### Added
- (Tickets -> Abono) Al abonar permite crear el ticket abono con almacén o sin almmacén - (Tickets -> Abono) Al abonar permite crear el ticket abono con almacén o sin almmacén

View File

@ -8,7 +8,7 @@ Salix is also the scientific name of a beautifull tree! :)
Required applications. Required applications.
* Node.js = 14.x LTS * Node.js >= 16.x LTS
* Docker * Docker
* Git * Git
@ -71,7 +71,7 @@ $ npm run test:e2e
Open Visual Studio Code, press Ctrl+P and paste the following commands. Open Visual Studio Code, press Ctrl+P and paste the following commands.
In Visual Studio Code we use the ESLint extension. In Visual Studio Code we use the ESLint extension.
``` ```
ext install dbaeumer.vscode-eslint ext install dbaeumer.vscode-eslint
``` ```

View File

@ -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};
};
};

View File

@ -62,10 +62,9 @@ module.exports = Self => {
scopes: ['change-password'], scopes: ['change-password'],
userId: vnUser.id userId: vnUser.id
}); });
throw new UserError('Pass expired', 'passExpired', { const err = new UserError('Pass expired', 'passExpired');
id: vnUser.id, err.details = {token: changePasswordToken};
token: changePasswordToken.id throw err;
});
} }
try { try {
@ -77,6 +76,6 @@ module.exports = Self => {
let loginInfo = Object.assign({password}, userInfo); let loginInfo = Object.assign({password}, userInfo);
token = await Self.login(loginInfo, 'user'); token = await Self.login(loginInfo, 'user');
return {token: token.id}; return {token: token.id, created: token.created};
}; };
}; };

View File

@ -9,7 +9,7 @@ describe('VnUser signIn()', () => {
expect(login.token).toBeDefined(); 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() => { 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(); expect(login.token).toBeDefined();
await models.VnUser.signOut(ctx); await models.VnUser.logout(ctx.req.accessToken.id);
}); });
}); });

View File

@ -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();
});
});

View File

@ -2,6 +2,14 @@
"AccountingType": { "AccountingType": {
"dataSource": "vn" "dataSource": "vn"
}, },
"AccessTokenConfig": {
"dataSource": "vn",
"options": {
"mysql": {
"table": "salix.accessTokenConfig"
}
}
},
"Bank": { "Bank": {
"dataSource": "vn" "dataSource": "vn"
}, },

View File

@ -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"
}]
}

View File

@ -10,6 +10,9 @@ module.exports = function(Self) {
require('../methods/vn-user/recover-password')(Self); require('../methods/vn-user/recover-password')(Self);
require('../methods/vn-user/validate-token')(Self); require('../methods/vn-user/validate-token')(Self);
require('../methods/vn-user/privileges')(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 // Validations

View File

@ -118,5 +118,24 @@
"principalId": "$authenticated", "principalId": "$authenticated",
"permission": "ALLOW" "permission": "ALLOW"
} }
] ],
"scopes": {
"preview": {
"fields": [
"id",
"name",
"username",
"roleFk",
"nickname",
"lang",
"active",
"created",
"updated",
"image",
"hasGrant",
"realm",
"email"
]
}
}
} }

View File

@ -4,4 +4,4 @@ apps:
instances: 1 instances: 1
max_restarts: 3 max_restarts: 3
restart_delay: 15000 restart_delay: 15000
node_args: --tls-min-v1.0 node_args: --tls-min-v1.0 --openssl-legacy-provider

View File

@ -1,6 +1,5 @@
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
VALUES VALUES
('VnUser', '*', '*', 'ALLOW', 'ROLE', 'employee'),
('VnUser','acl','READ','ALLOW','ROLE','account'), ('VnUser','acl','READ','ALLOW','ROLE','account'),
('VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'), ('VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),
('VnUser','changePassword', 'WRITE', 'ALLOW', 'ROLE', 'account'), ('VnUser','changePassword', 'WRITE', 'ALLOW', 'ROLE', 'account'),

View File

@ -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');

View File

@ -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');

View File

@ -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');

View File

@ -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');

View File

@ -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');

View File

@ -0,0 +1,3 @@
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
VALUES
('VnUser', 'renewToken', 'WRITE', 'ALLOW', 'ROLE', 'employee')

View File

@ -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 ;

View File

@ -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);

View File

@ -2736,7 +2736,8 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`)
(1, 'print-email', 'notification fixture one'), (1, 'print-email', 'notification fixture one'),
(2, 'invoice-electronic', 'A electronic invoice has been generated'), (2, 'invoice-electronic', 'A electronic invoice has been generated'),
(3, 'not-main-printer-configured', 'A printer distinct than main has been configured'), (3, 'not-main-printer-configured', 'A printer distinct than main has been configured'),
(4, 'supplier-pay-method-update', 'A supplier pay method has been updated'); (4, 'supplier-pay-method-update', 'A supplier pay method has been updated'),
(5, 'modified-entry', 'An entry has been modified');
INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`)
VALUES VALUES
@ -2894,6 +2895,10 @@ INSERT INTO `vn`.`wagonTypeTray` (`id`, `typeFk`, `height`, `colorFk`)
(2, 1, 50, 2), (2, 1, 50, 2),
(3, 1, 0, 3); (3, 1, 0, 3);
INSERT INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `renewInterval`)
VALUES
(1, 21600, 300);
INSERT INTO `vn`.`travelConfig` (`id`, `warehouseInFk`, `warehouseOutFk`, `agencyFk`, `companyFk`) INSERT INTO `vn`.`travelConfig` (`id`, `warehouseInFk`, `warehouseOutFk`, `agencyFk`, `companyFk`)
VALUES VALUES
(1, 1, 1, 1, 442); (1, 1, 1, 1, 442);

View File

@ -311,9 +311,9 @@ export default {
}, },
clientDefaulter: { clientDefaulter: {
anyClient: 'vn-client-defaulter tbody > tr', anyClient: 'vn-client-defaulter tbody > tr',
firstClientName: 'vn-client-defaulter tbody > tr:nth-child(1) > td:nth-child(2) > span', firstClientName: 'vn-client-defaulter tbody > tr:nth-child(2) > td:nth-child(2) > span',
firstSalesPersonName: 'vn-client-defaulter tbody > tr:nth-child(1) > td:nth-child(3) > span', firstSalesPersonName: 'vn-client-defaulter tbody > tr:nth-child(2) > td:nth-child(3) > span',
firstObservation: 'vn-client-defaulter tbody > tr:nth-child(1) > td:nth-child(8) > vn-textarea[ng-model="defaulter.observation"]', firstObservation: 'vn-client-defaulter tbody > tr:nth-child(2) > td:nth-child(8) > vn-textarea[ng-model="defaulter.observation"]',
allDefaulterCheckbox: 'vn-client-defaulter thead vn-multi-check', allDefaulterCheckbox: 'vn-client-defaulter thead vn-multi-check',
addObservationButton: 'vn-client-defaulter vn-button[icon="icon-notes"]', addObservationButton: 'vn-client-defaulter vn-button[icon="icon-notes"]',
observation: '.vn-dialog.shown vn-textarea[ng-model="$ctrl.defaulter.observation"]', observation: '.vn-dialog.shown vn-textarea[ng-model="$ctrl.defaulter.observation"]',
@ -334,15 +334,15 @@ export default {
}, },
itemsIndex: { itemsIndex: {
createItemButton: `vn-float-button`, createItemButton: `vn-float-button`,
firstSearchResult: 'vn-item-index tbody tr:nth-child(1)', firstSearchResult: 'vn-item-index tbody tr:nth-child(2)',
searchResult: 'vn-item-index tbody tr:not(.empty-rows)', searchResult: 'vn-item-index tbody tr:not(.empty-rows)',
firstResultPreviewButton: 'vn-item-index tbody > :nth-child(1) .buttons > [icon="preview"]', firstResultPreviewButton: 'vn-item-index tbody > :nth-child(2) .buttons > [icon="preview"]',
searchResultCloneButton: 'vn-item-index .buttons > [icon="icon-clone"]', searchResultCloneButton: 'vn-item-index .buttons > [icon="icon-clone"]',
acceptClonationAlertButton: '.vn-confirm.shown [response="accept"]', acceptClonationAlertButton: '.vn-confirm.shown [response="accept"]',
closeItemSummaryPreview: '.vn-popup.shown', closeItemSummaryPreview: '.vn-popup.shown',
shownColumns: 'vn-item-index vn-button[id="shownColumns"]', shownColumns: 'vn-item-index vn-button[id="shownColumns"]',
shownColumnsList: '.vn-popover.shown .content', shownColumnsList: '.vn-popover.shown .content',
firstItemImage: 'vn-item-index tbody > tr:nth-child(1) > td:nth-child(1) > img', firstItemImage: 'vn-item-index tbody > tr:nth-child(2) > td:nth-child(1) > img',
firstItemImageTd: 'vn-item-index smart-table tr:nth-child(1) td:nth-child(1)', firstItemImageTd: 'vn-item-index smart-table tr:nth-child(1) td:nth-child(1)',
firstItemId: 'vn-item-index tbody > tr:nth-child(1) > td:nth-child(2)', firstItemId: 'vn-item-index tbody > tr:nth-child(1) > td:nth-child(2)',
idCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check[label="Identifier"]', idCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check[label="Identifier"]',
@ -523,11 +523,11 @@ export default {
searchResultDate: 'vn-ticket-summary [label=Landed] span', searchResultDate: 'vn-ticket-summary [label=Landed] span',
topbarSearch: 'vn-searchbar', topbarSearch: 'vn-searchbar',
moreMenu: 'vn-ticket-index vn-icon-button[icon=more_vert]', moreMenu: 'vn-ticket-index vn-icon-button[icon=more_vert]',
fourthWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(4)', fourthWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(5)',
fiveWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(5)', fiveWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(6)',
weeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table table tbody tr', weeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table table tbody tr',
firstWeeklyTicketDeleteIcon: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(1) vn-icon-button[icon="delete"]', firstWeeklyTicketDeleteIcon: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(2) vn-icon-button[icon="delete"]',
firstWeeklyTicketAgency: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(1) [ng-model="weekly.agencyModeFk"]', firstWeeklyTicketAgency: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(2) [ng-model="weekly.agencyModeFk"]',
acceptDeleteTurn: '.vn-confirm.shown button[response="accept"]' acceptDeleteTurn: '.vn-confirm.shown button[response="accept"]'
}, },
createTicketView: { createTicketView: {
@ -572,8 +572,8 @@ export default {
submitNotesButton: 'button[type=submit]' submitNotesButton: 'button[type=submit]'
}, },
ticketExpedition: { ticketExpedition: {
firstSaleCheckbox: 'vn-ticket-expedition tr:nth-child(1) vn-check[ng-model="expedition.checked"]', firstSaleCheckbox: 'vn-ticket-expedition tr:nth-child(2) vn-check[ng-model="expedition.checked"]',
thirdSaleCheckbox: 'vn-ticket-expedition tr:nth-child(3) vn-check[ng-model="expedition.checked"]', thirdSaleCheckbox: 'vn-ticket-expedition tr:nth-child(4) vn-check[ng-model="expedition.checked"]',
deleteExpeditionButton: 'vn-ticket-expedition slot-actions > vn-button[icon="delete"]', deleteExpeditionButton: 'vn-ticket-expedition slot-actions > vn-button[icon="delete"]',
moveExpeditionButton: 'vn-ticket-expedition slot-actions > vn-button[icon="keyboard_arrow_down"]', moveExpeditionButton: 'vn-ticket-expedition slot-actions > vn-button[icon="keyboard_arrow_down"]',
moreMenuWithoutRoute: 'vn-item[name="withoutRoute"]', moreMenuWithoutRoute: 'vn-item[name="withoutRoute"]',
@ -712,7 +712,7 @@ export default {
problems: 'vn-check[label="With problems"]', problems: 'vn-check[label="With problems"]',
tableButtonSearch: 'vn-button[vn-tooltip="Search"]', tableButtonSearch: 'vn-button[vn-tooltip="Search"]',
moveButton: 'vn-button[vn-tooltip="Future tickets"]', moveButton: 'vn-button[vn-tooltip="Future tickets"]',
firstCheck: 'tbody > tr:nth-child(1) > td > vn-check', firstCheck: 'tbody > tr:nth-child(2) > td > vn-check',
multiCheck: 'vn-multi-check', multiCheck: 'vn-multi-check',
tableId: 'vn-textfield[name="id"]', tableId: 'vn-textfield[name="id"]',
tableFutureId: 'vn-textfield[name="futureId"]', tableFutureId: 'vn-textfield[name="futureId"]',
@ -736,7 +736,7 @@ export default {
tableButtonSearch: 'vn-button[vn-tooltip="Search"]', tableButtonSearch: 'vn-button[vn-tooltip="Search"]',
moveButton: 'vn-button[vn-tooltip="Advance tickets"]', moveButton: 'vn-button[vn-tooltip="Advance tickets"]',
acceptButton: '.vn-confirm.shown button[response="accept"]', acceptButton: '.vn-confirm.shown button[response="accept"]',
firstCheck: 'tbody > tr:nth-child(1) > td > vn-check', firstCheck: 'tbody > tr:nth-child(2) > td > vn-check',
tableId: 'vn-textfield[name="id"]', tableId: 'vn-textfield[name="id"]',
tableFutureId: 'vn-textfield[name="futureId"]', tableFutureId: 'vn-textfield[name="futureId"]',
tableLiters: 'vn-textfield[name="liters"]', tableLiters: 'vn-textfield[name="liters"]',
@ -810,7 +810,7 @@ export default {
claimAction: { claimAction: {
importClaimButton: 'vn-claim-action vn-button[label="Import claim"]', importClaimButton: 'vn-claim-action vn-button[label="Import claim"]',
anyLine: 'vn-claim-action vn-tbody > vn-tr', anyLine: 'vn-claim-action vn-tbody > vn-tr',
firstDeleteLine: 'vn-claim-action tr:nth-child(1) vn-icon-button[icon="delete"]', firstDeleteLine: 'vn-claim-action tr:nth-child(2) vn-icon-button[icon="delete"]',
isPaidWithManaCheckbox: 'vn-claim-action vn-check[ng-model="$ctrl.claim.isChargedToMana"]' isPaidWithManaCheckbox: 'vn-claim-action vn-check[ng-model="$ctrl.claim.isChargedToMana"]'
}, },
ordersIndex: { ordersIndex: {
@ -1216,7 +1216,7 @@ export default {
addTagButton: 'vn-icon-button[vn-tooltip="Add tag"]', addTagButton: 'vn-icon-button[vn-tooltip="Add tag"]',
itemTagInput: 'vn-autocomplete[ng-model="itemTag.tagFk"]', itemTagInput: 'vn-autocomplete[ng-model="itemTag.tagFk"]',
itemTagValueInput: 'vn-autocomplete[ng-model="itemTag.value"]', itemTagValueInput: 'vn-autocomplete[ng-model="itemTag.value"]',
firstBuy: 'vn-entry-latest-buys tbody > tr:nth-child(1)', firstBuy: 'vn-entry-latest-buys tbody > tr:nth-child(2)',
allBuysCheckBox: 'vn-entry-latest-buys thead vn-check', allBuysCheckBox: 'vn-entry-latest-buys thead vn-check',
secondBuyCheckBox: 'vn-entry-latest-buys tbody tr:nth-child(2) vn-check[ng-model="buy.checked"]', secondBuyCheckBox: 'vn-entry-latest-buys tbody tr:nth-child(2) vn-check[ng-model="buy.checked"]',
editBuysButton: 'vn-entry-latest-buys vn-button[icon="edit"]', editBuysButton: 'vn-entry-latest-buys vn-button[icon="edit"]',

View File

@ -19,15 +19,14 @@ describe('SmartTable SearchBar integration', () => {
await page.waitToClick(selectors.itemsIndex.openAdvancedSearchButton); await page.waitToClick(selectors.itemsIndex.openAdvancedSearchButton);
await page.autocompleteSearch(selectors.itemsIndex.advancedSearchItemType, 'Anthurium'); await page.autocompleteSearch(selectors.itemsIndex.advancedSearchItemType, 'Anthurium');
await page.waitToClick(selectors.itemsIndex.advancedSearchButton); await page.waitToClick(selectors.itemsIndex.advancedSearchButton);
await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 3); await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 4);
await page.reload({ await page.reload({
waitUntil: 'networkidle2' waitUntil: 'networkidle2'
}); });
await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 3); await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 4);
await page.waitToClick(selectors.itemsIndex.advancedSmartTableButton);
await page.write(selectors.itemsIndex.advancedSmartTableGrouping, '1'); await page.write(selectors.itemsIndex.advancedSmartTableGrouping, '1');
await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 2); await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 2);
@ -36,7 +35,7 @@ describe('SmartTable SearchBar integration', () => {
waitUntil: 'networkidle2' waitUntil: 'networkidle2'
}); });
await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 2); await page.waitForNumberOfElements(selectors.itemsIndex.searchResult, 1);
}); });
it('should filter in section without smart-table and search in searchBar go to zone section', async() => { it('should filter in section without smart-table and search in searchBar go to zone section', async() => {

View File

@ -19,7 +19,7 @@ describe('Client defaulter path', () => {
it('should count the amount of clients in the turns section', async() => { it('should count the amount of clients in the turns section', async() => {
const result = await page.countElement(selectors.clientDefaulter.anyClient); const result = await page.countElement(selectors.clientDefaulter.anyClient);
expect(result).toEqual(5); expect(result).toEqual(6);
}); });
it('should check contain expected client', async() => { it('should check contain expected client', async() => {

View File

@ -53,7 +53,7 @@ describe('Worker create path', () => {
expect(message.text).toContain('Data saved!'); expect(message.text).toContain('Data saved!');
// 'rollback' // 'rollback'
await page.loginAndModule('sysadmin', 'account'); await page.loginAndModule('itManagement', 'account');
await page.accessToSearchResult(newWorker); await page.accessToSearchResult(newWorker);
await page.waitToClick(selectors.accountDescriptor.menuButton); await page.waitToClick(selectors.accountDescriptor.menuButton);

View File

@ -18,11 +18,11 @@ describe('Item summary path', () => {
await page.doSearch('Ranged weapon'); await page.doSearch('Ranged weapon');
const resultsCount = await page.countElement(selectors.itemsIndex.searchResult); const resultsCount = await page.countElement(selectors.itemsIndex.searchResult);
await page.waitForTextInElement(selectors.itemsIndex.searchResult, 'Ranged weapon'); await page.waitForTextInElement(selectors.itemsIndex.firstSearchResult, 'Ranged weapon');
await page.waitToClick(selectors.itemsIndex.firstResultPreviewButton); await page.waitToClick(selectors.itemsIndex.firstResultPreviewButton);
const isVisible = await page.isVisible(selectors.itemSummary.basicData); const isVisible = await page.isVisible(selectors.itemSummary.basicData);
expect(resultsCount).toBe(3); expect(resultsCount).toBe(4);
expect(isVisible).toBeTruthy(); expect(isVisible).toBeTruthy();
}); });
@ -66,7 +66,7 @@ describe('Item summary path', () => {
await page.waitToClick(selectors.itemsIndex.firstResultPreviewButton); await page.waitToClick(selectors.itemsIndex.firstResultPreviewButton);
await page.waitForSelector(selectors.itemSummary.basicData, {visible: true}); await page.waitForSelector(selectors.itemSummary.basicData, {visible: true});
expect(resultsCount).toBe(2); expect(resultsCount).toBe(3);
}); });
it(`should now check the item summary preview shows fields from basic data`, async() => { it(`should now check the item summary preview shows fields from basic data`, async() => {

View File

@ -18,7 +18,7 @@ describe('Item log path', () => {
await page.doSearch('Knowledge artifact'); await page.doSearch('Knowledge artifact');
const nResults = await page.countElement(selectors.itemsIndex.searchResult); const nResults = await page.countElement(selectors.itemsIndex.searchResult);
expect(nResults).toEqual(0); expect(nResults).toEqual(1);
}); });
it('should access to the create item view by clicking the create floating button', async() => { it('should access to the create item view by clicking the create floating button', async() => {

View File

@ -27,6 +27,6 @@ describe('Ticket expeditions and log path', () => {
const result = await page const result = await page
.countElement(selectors.ticketExpedition.expeditionRow); .countElement(selectors.ticketExpedition.expeditionRow);
expect(result).toEqual(3); expect(result).toEqual(4);
}); });
}); });

View File

@ -19,7 +19,7 @@ describe('Ticket descriptor path', () => {
it('should count the amount of tickets in the turns section', async() => { it('should count the amount of tickets in the turns section', async() => {
const result = await page.countElement(selectors.ticketsIndex.weeklyTicket); const result = await page.countElement(selectors.ticketsIndex.weeklyTicket);
expect(result).toEqual(6); expect(result).toEqual(7);
}); });
it('should go back to the ticket index then search and access a ticket summary', async() => { it('should go back to the ticket index then search and access a ticket summary', async() => {
@ -89,7 +89,7 @@ describe('Ticket descriptor path', () => {
await page.doSearch('11'); await page.doSearch('11');
const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult);
expect(nResults).toEqual(1); expect(nResults).toEqual(2);
}); });
it('should delete the weekly ticket 11', async() => { it('should delete the weekly ticket 11', async() => {
@ -104,7 +104,7 @@ describe('Ticket descriptor path', () => {
await page.doSearch(); await page.doSearch();
const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult);
expect(nResults).toEqual(6); expect(nResults).toEqual(7);
}); });
it('should update the agency then remove it afterwards', async() => { it('should update the agency then remove it afterwards', async() => {

View File

@ -29,7 +29,7 @@ describe('Ticket expeditions', () => {
const result = await page const result = await page
.countElement(selectors.ticketExpedition.expeditionRow); .countElement(selectors.ticketExpedition.expeditionRow);
expect(result).toEqual(1); expect(result).toEqual(2);
}); });
it(`should move one expedition to new ticket with route`, async() => { it(`should move one expedition to new ticket with route`, async() => {
@ -45,6 +45,6 @@ describe('Ticket expeditions', () => {
const result = await page const result = await page
.countElement(selectors.ticketExpedition.expeditionRow); .countElement(selectors.ticketExpedition.expeditionRow);
expect(result).toEqual(1); expect(result).toEqual(2);
}); });
}); });

View File

@ -87,7 +87,7 @@ describe('Ticket Future path', () => {
await page.clearInput(selectors.ticketFuture.futureState); await page.clearInput(selectors.ticketFuture.futureState);
await page.waitToClick(selectors.ticketFuture.submit); await page.waitToClick(selectors.ticketFuture.submit);
await page.waitForNumberOfElements(selectors.ticketFuture.searchResult, 4); await page.waitForNumberOfElements(selectors.ticketFuture.searchResult, 5);
await page.waitToClick(selectors.ticketFuture.multiCheck); await page.waitToClick(selectors.ticketFuture.multiCheck);
await page.waitToClick(selectors.ticketFuture.firstCheck); await page.waitToClick(selectors.ticketFuture.firstCheck);
await page.waitToClick(selectors.ticketFuture.moveButton); await page.waitToClick(selectors.ticketFuture.moveButton);

View File

@ -8,7 +8,7 @@ describe('Account create and basic data path', () => {
beforeAll(async() => { beforeAll(async() => {
browser = await getBrowser(); browser = await getBrowser();
page = browser.page; page = browser.page;
await page.loginAndModule('developer', 'account'); await page.loginAndModule('itManagement', 'account');
}); });
afterAll(async() => { afterAll(async() => {

View File

@ -40,6 +40,8 @@ export default class SmartTable extends Component {
this._options = options; this._options = options;
if (!options) return; if (!options) return;
options.defaultSearch = true;
if (options.defaultSearch) if (options.defaultSearch)
this.displaySearch(); this.displaySearch();

View File

@ -64,7 +64,7 @@ export default class Auth {
} }
onLoginOk(json, remember) { onLoginOk(json, remember) {
this.vnToken.set(json.data.token, remember); this.vnToken.set(json.data.token, json.data.created, remember);
return this.loadAcls().then(() => { return this.loadAcls().then(() => {
let continueHash = this.$state.params.continue; let continueHash = this.$state.params.continue;

View File

@ -11,3 +11,4 @@ import './report';
import './email'; import './email';
import './file'; import './file';
import './date'; import './date';

View File

@ -9,25 +9,33 @@ export default class Token {
constructor() { constructor() {
try { try {
this.token = sessionStorage.getItem('vnToken'); this.token = sessionStorage.getItem('vnToken');
if (!this.token) this.created = sessionStorage.getItem('vnTokenCreated');
if (!this.token) {
this.token = localStorage.getItem('vnToken'); this.token = localStorage.getItem('vnToken');
this.created = localStorage.getItem('vnTokenCreated');
}
} catch (e) {} } catch (e) {}
} }
set(value, remember) { set(token, created, remember) {
this.unset(); this.unset();
try { try {
if (remember) if (remember) {
localStorage.setItem('vnToken', value); localStorage.setItem('vnToken', token);
else localStorage.setItem('vnTokenCreated', created);
sessionStorage.setItem('vnToken', value); } else {
sessionStorage.setItem('vnToken', token);
sessionStorage.setItem('vnTokenCreated', created);
}
} catch (e) {} } catch (e) {}
this.token = value; this.token = token;
this.created = created;
} }
unset() { unset() {
localStorage.removeItem('vnToken'); localStorage.removeItem('vnToken');
sessionStorage.removeItem('vnToken'); sessionStorage.removeItem('vnToken');
this.token = null; this.token = null;
this.created = null;
} }
} }

View File

@ -15,7 +15,7 @@ export default class Controller {
} }
$onInit() { $onInit() {
if (!this.$state.params || !this.$state.params.id || !this.$state.params.token) if (!this.$state.params.id)
this.$state.go('login'); this.$state.go('login');
this.$http.get('UserPasswords/findOne') this.$http.get('UserPasswords/findOne')
@ -25,7 +25,7 @@ export default class Controller {
} }
submit() { submit() {
const id = this.$state.params.id; const userId = this.$state.params.userId;
const newPassword = this.newPassword; const newPassword = this.newPassword;
const oldPassword = this.oldPassword; const oldPassword = this.oldPassword;
@ -35,12 +35,12 @@ export default class Controller {
throw new UserError(`Passwords don't match`); throw new UserError(`Passwords don't match`);
const headers = { const headers = {
Authorization: this.$state.params.token Authorization: this.$state.params.id
}; };
this.$http.post('VnUsers/change-password', this.$http.post('VnUsers/change-password',
{ {
id, id: userId,
oldPassword, oldPassword,
newPassword newPassword
}, },

View File

@ -3,13 +3,14 @@ import Component from 'core/lib/component';
import './style.scss'; import './style.scss';
export class Layout extends Component { export class Layout extends Component {
constructor($element, $, vnModules) { constructor($element, $, vnModules, vnToken) {
super($element, $); super($element, $);
this.modules = vnModules.get(); this.modules = vnModules.get();
} }
$onInit() { $onInit() {
this.getUserData(); this.getUserData();
this.getAccessTokenConfig();
} }
getUserData() { getUserData() {
@ -30,8 +31,42 @@ export class Layout extends Component {
refresh() { refresh() {
window.location.reload(); 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', { ngModule.vnComponent('vnLayout', {
template: require('./index.html'), template: require('./index.html'),

View File

@ -37,4 +37,49 @@ describe('Component vnLayout', () => {
expect(url).not.toBeDefined(); 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);
});
});
}); });

View File

@ -27,10 +27,9 @@ export default class Controller {
this.loading = false; this.loading = false;
this.password = ''; this.password = '';
this.focusUser(); this.focusUser();
if (req?.data?.error?.code == 'passExpired') { const err = req.data?.error;
const [args] = req.data.error.translateArgs; if (err?.code == 'passExpired')
this.$state.go('change-password', args); this.$state.go('change-password', err.details.token);
}
throw req; throw req;
}); });

View File

@ -38,7 +38,7 @@ function config($stateProvider, $urlRouterProvider) {
}) })
.state('change-password', { .state('change-password', {
parent: 'outLayout', parent: 'outLayout',
url: '/change-password?id&token', url: '/change-password?id&userId',
description: 'Change password', description: 'Change password',
template: '<vn-change-password></vn-change-password>' template: '<vn-change-password></vn-change-password>'
}) })

View File

@ -200,22 +200,20 @@ module.exports = function(Self) {
const connector = this.dataSource.connector; const connector = this.dataSource.connector;
let conn; let conn;
let res; let res;
const opts = Object.assign({}, options);
try { try {
if (userId) { if (userId) {
conn = await new Promise((resolve, reject) => { if (!options.transaction) {
connector.client.getConnection(function(err, conn) { options = Object.assign({}, options);
if (err) conn = await new Promise((resolve, reject) => {
reject(err); connector.client.getConnection(function(err, conn) {
else if (err)
resolve(conn); reject(err);
else
resolve(conn);
});
}); });
}); options.transaction = {
const opts = Object.assign({}, options);
if (!opts.transaction) {
opts.transaction = {
connection: conn, connection: conn,
connector connector
}; };
@ -223,15 +221,14 @@ module.exports = function(Self) {
await connector.executeP( await connector.executeP(
'CALL account.myUser_loginWithName((SELECT name FROM account.user WHERE id = ?))', 'CALL account.myUser_loginWithName((SELECT name FROM account.user WHERE id = ?))',
[userId], opts [userId], options
); );
} }
res = await connector.executeP(query, params, opts); res = await connector.executeP(query, params, options);
if (userId) { if (userId)
await connector.executeP('CALL account.myUser_logout()', null, opts); await connector.executeP('CALL account.myUser_logout()', null, options);
}
} finally { } finally {
if (conn) conn.release(); if (conn) conn.release();
} }

View File

@ -293,5 +293,6 @@
"Pass expired": "La contraseña ha caducado, cambiela desde Salix", "Pass expired": "La contraseña ha caducado, cambiela desde Salix",
"Invalid NIF for VIES": "Invalid NIF for VIES", "Invalid NIF for VIES": "Invalid NIF for VIES",
"Ticket does not exist": "Este ticket no existe", "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",
"The renew period has not been exceeded": "El periodo de renovación no ha sido superado"
} }

View File

@ -0,0 +1,3 @@
name: account
columns:
id: id

View File

@ -0,0 +1,3 @@
name: cuenta
columns:
id: id

View File

@ -0,0 +1,5 @@
name: mail alias
columns:
id: id
mailAlias: alias
account: account

View File

@ -0,0 +1,5 @@
name: alias de correo
columns:
id: id
mailAlias: alias
account: cuenta

View File

@ -5,8 +5,7 @@ import UserError from 'core/lib/user-error';
export default class Controller extends Section { export default class Controller extends Section {
onSynchronizeAll() { onSynchronizeAll() {
this.vnApp.showSuccess(this.$t('Synchronizing in the background')); this.vnApp.showSuccess(this.$t('Synchronizing in the background'));
this.$http.patch(`Accounts/syncAll`) this.$http.patch(`Accounts/syncAll`);
.then(() => this.vnApp.showSuccess(this.$t('Users synchronized!')));
} }
onUserSync() { onUserSync() {

View File

@ -17,7 +17,9 @@
<vn-icon-button <vn-icon-button
icon="delete" icon="delete"
translate-attr="{title: 'Unsubscribe'}" translate-attr="{title: 'Unsubscribe'}"
ng-click="removeConfirm.show(row)"> ng-click="removeConfirm.show(row)"
vn-acl="itManagement"
vn-acl-action="remove">
</vn-icon-button> </vn-icon-button>
</vn-item-section> </vn-item-section>
</vn-item> </vn-item>
@ -30,9 +32,11 @@
translate-attr="{title: 'Add'}" translate-attr="{title: 'Add'}"
vn-bind="+" vn-bind="+"
ng-click="$ctrl.onAddClick()" ng-click="$ctrl.onAddClick()"
fixed-bottom-right> fixed-bottom-right
vn-acl="itManagement"
vn-acl-action="remove">
</vn-float-button> </vn-float-button>
<vn-dialog <vn-dialog
vn-id="dialog" vn-id="dialog"
on-accept="$ctrl.onAddSave()"> on-accept="$ctrl.onAddSave()">
<tpl-body> <tpl-body>
@ -49,7 +53,7 @@
<button response="accept" translate>Save</button> <button response="accept" translate>Save</button>
</tpl-buttons> </tpl-buttons>
</vn-dialog> </vn-dialog>
<vn-confirm <vn-confirm
vn-id="removeConfirm" vn-id="removeConfirm"
message="User will be removed from alias" message="User will be removed from alias"
question="Are you sure you want to continue?" question="Are you sure you want to continue?"

View File

@ -5,6 +5,7 @@ import './style.scss';
class Controller extends ModuleCard { class Controller extends ModuleCard {
reload() { reload() {
const filter = { const filter = {
where: {id: this.$params.id},
include: { include: {
relation: 'role', relation: 'role',
scope: { scope: {
@ -14,8 +15,11 @@ class Controller extends ModuleCard {
}; };
return Promise.all([ return Promise.all([
this.$http.get(`VnUsers/${this.$params.id}`, {filter}) this.$http.get(`VnUsers/preview`, {filter})
.then(res => this.user = res.data), .then(res => {
const [user] = res.data;
this.user = user;
}),
this.$http.get(`Accounts/${this.$params.id}/exists`) this.$http.get(`Accounts/${this.$params.id}/exists`)
.then(res => this.hasAccount = res.data.exists) .then(res => this.hasAccount = res.data.exists)
]); ]);

View File

@ -15,12 +15,12 @@ describe('component vnUserCard', () => {
it('should reload the controller data', () => { it('should reload the controller data', () => {
controller.$params.id = 1; controller.$params.id = 1;
$httpBackend.expectGET('VnUsers/1').respond('foo'); $httpBackend.expectGET('VnUsers/preview').respond('foo');
$httpBackend.expectGET('Accounts/1/exists').respond({exists: true}); $httpBackend.expectGET('Accounts/1/exists').respond({exists: true});
controller.reload(); controller.reload();
$httpBackend.flush(); $httpBackend.flush();
expect(controller.user).toBe('foo'); expect(controller.user).toBe('f');
expect(controller.hasAccount).toBeTruthy(); expect(controller.hasAccount).toBeTruthy();
}); });
}); });

View File

@ -12,18 +12,18 @@
<vn-card class="vn-pa-lg"> <vn-card class="vn-pa-lg">
<vn-vertical> <vn-vertical>
<vn-textfield <vn-textfield
label="Name" label="Name"
ng-model="$ctrl.user.name" ng-model="$ctrl.user.name"
rule="VnUser" rule="VnUser"
vn-focus> vn-focus>
</vn-textfield> </vn-textfield>
<vn-textfield <vn-textfield
label="Nickname" label="Nickname"
ng-model="$ctrl.user.nickname" ng-model="$ctrl.user.nickname"
rule="VnUser"> rule="VnUser">
</vn-textfield> </vn-textfield>
<vn-textfield <vn-textfield
label="Email" label="Email"
ng-model="$ctrl.user.email" ng-model="$ctrl.user.email"
rule="VnUser"> rule="VnUser">
</vn-textfield> </vn-textfield>
@ -39,7 +39,7 @@
type="password"> type="password">
</vn-textfield> </vn-textfield>
<vn-check <vn-check
label="Active" label="Active"
ng-model="$ctrl.user.active"> ng-model="$ctrl.user.active">
</vn-check> </vn-check>
</vn-vertical> </vn-vertical>

View File

@ -2,6 +2,11 @@ import ngModule from '../module';
import Section from 'salix/components/section'; import Section from 'salix/components/section';
export default class Controller extends Section { export default class Controller extends Section {
constructor($element, $) {
super($element, $);
this.user = {active: true};
}
onSubmit() { onSubmit() {
return this.$.watcher.submit().then(res => { return this.$.watcher.submit().then(res => {
this.$state.go('account.card.basicData', {id: res.data.id}); this.$state.go('account.card.basicData', {id: res.data.id});

View File

@ -6,7 +6,7 @@
<vn-item <vn-item
ng-click="deleteUser.show()" ng-click="deleteUser.show()"
name="deleteUser" name="deleteUser"
vn-acl="it" vn-acl="itManagement"
vn-acl-action="remove" vn-acl-action="remove"
translate> translate>
Delete Delete
@ -15,7 +15,7 @@
ng-if="::$root.user.id == $ctrl.id" ng-if="::$root.user.id == $ctrl.id"
ng-click="$ctrl.onChangePassClick(true)" ng-click="$ctrl.onChangePassClick(true)"
name="changePassword" name="changePassword"
vn-acl="hr" vn-acl="sysadmin"
vn-acl-action="remove" vn-acl-action="remove"
translate> translate>
Change password Change password
@ -23,7 +23,7 @@
<vn-item <vn-item
ng-click="$ctrl.onChangePassClick(false)" ng-click="$ctrl.onChangePassClick(false)"
name="setPassword" name="setPassword"
vn-acl="hr" vn-acl="sysadmin"
vn-acl-action="remove" vn-acl-action="remove"
translate> translate>
Set password Set password
@ -32,7 +32,7 @@
ng-if="!$ctrl.hasAccount" ng-if="!$ctrl.hasAccount"
ng-click="enableAccount.show()" ng-click="enableAccount.show()"
name="enableAccount" name="enableAccount"
vn-acl="it" vn-acl="sysadmin"
vn-acl-action="remove" vn-acl-action="remove"
translate> translate>
Enable account Enable account
@ -41,7 +41,7 @@
ng-if="$ctrl.hasAccount" ng-if="$ctrl.hasAccount"
ng-click="disableAccount.show()" ng-click="disableAccount.show()"
name="disableAccount" name="disableAccount"
vn-acl="it" vn-acl="sysadmin"
vn-acl-action="remove" vn-acl-action="remove"
translate> translate>
Disable account Disable account
@ -50,7 +50,7 @@
ng-if="!$ctrl.user.active" ng-if="!$ctrl.user.active"
ng-click="activateUser.show()" ng-click="activateUser.show()"
name="activateUser" name="activateUser"
vn-acl="hr" vn-acl="itManagement"
vn-acl-action="remove" vn-acl-action="remove"
translate> translate>
Activate user Activate user
@ -59,7 +59,7 @@
ng-if="$ctrl.user.active" ng-if="$ctrl.user.active"
ng-click="deactivateUser.show()" ng-click="deactivateUser.show()"
name="deactivateUser" name="deactivateUser"
vn-acl="hr" vn-acl="itManagement"
vn-acl-action="remove" vn-acl-action="remove"
translate> translate>
Deactivate user Deactivate user

View File

@ -14,11 +14,11 @@
<vn-item-section> <vn-item-section>
<h6>{{::user.nickname}}</h6> <h6>{{::user.nickname}}</h6>
<vn-label-value <vn-label-value
label="Id" label="Id"
value="{{::user.id}}"> value="{{::user.id}}">
</vn-label-value> </vn-label-value>
<vn-label-value <vn-label-value
label="User" label="User"
value="{{::user.name}}"> value="{{::user.name}}">
</vn-label-value> </vn-label-value>
</vn-item-section> </vn-item-section>
@ -36,12 +36,12 @@
<vn-popup vn-id="summary"> <vn-popup vn-id="summary">
<vn-user-summary user="$ctrl.selectedUser"></vn-user-summary> <vn-user-summary user="$ctrl.selectedUser"></vn-user-summary>
</vn-popup> </vn-popup>
<a <a
fixed-bottom-right fixed-bottom-right
ui-sref="account.create" ui-sref="account.create"
vn-tooltip="New user" vn-tooltip="New user"
vn-bind="+" vn-bind="+"
vn-acl="it" vn-acl="itManagement"
vn-acl-action="remove"> vn-acl-action="remove">
<vn-float-button icon="add"></vn-float-button> <vn-float-button icon="add"></vn-float-button>
</a> </a>

View File

@ -14,12 +14,12 @@
<vn-card class="vn-pa-lg"> <vn-card class="vn-pa-lg">
<vn-vertical> <vn-vertical>
<vn-check <vn-check
label="Enable mail forwarding" label="Enable mail forwarding"
ng-model="watcher.hasData"> ng-model="watcher.hasData">
</vn-check> </vn-check>
<vn-textfield <vn-textfield
ng-if="watcher.hasData" ng-if="watcher.hasData"
label="Forward email" label="Forward email"
ng-model="data.forwardTo" ng-model="data.forwardTo"
info="All emails will be forwarded to the specified address." info="All emails will be forwarded to the specified address."
rule="MailForward" rule="MailForward"

View File

@ -4,3 +4,4 @@ Enable mail forwarding: Habilitar redirección de correo
All emails will be forwarded to the specified address.: > All emails will be forwarded to the specified address.: >
Todos los correos serán reenviados a la dirección especificada, no se Todos los correos serán reenviados a la dirección especificada, no se
mantendrá copia de los mismos en el buzón del usuario. mantendrá copia de los mismos en el buzón del usuario.
You don't have enough privileges: No tienes suficientes permisos

View File

@ -1,6 +1,6 @@
<vn-crud-model <vn-crud-model
vn-id="model" vn-id="model"
url="VnUsers" url="VnUsers/preview"
filter="::$ctrl.filter" filter="::$ctrl.filter"
limit="20"> limit="20">
</vn-crud-model> </vn-crud-model>

View File

@ -1,9 +1,7 @@
<mg-ajax path="VnUsers/{{post.params.id}}/privileges" options="vnPost"></mg-ajax> <mg-ajax path="VnUsers/{{post.params.id}}/privileges" options="vnPost"></mg-ajax>
<vn-watcher <vn-watcher
vn-id="watcher" vn-id="watcher"
url="VnUsers"
data="$ctrl.user" data="$ctrl.user"
id-value="$ctrl.$params.id"
form="form" form="form"
save="post"> save="post">
</vn-watcher> </vn-watcher>
@ -11,15 +9,16 @@
name="form" name="form"
ng-submit="watcher.submit()" ng-submit="watcher.submit()"
class="vn-w-md"> class="vn-w-md">
<vn-card class="vn-pa-lg" vn-focus> <vn-card class="vn-pa-lg">
<vn-vertical> <vn-vertical>
<vn-check <vn-check
label="Has grant" label="Has grant"
ng-model="$ctrl.user.hasGrant"> ng-model="$ctrl.user.hasGrant">
</vn-check> </vn-check>
</vn-vertical> </vn-vertical>
<vn-vertical </vn-card>
class="vn-mt-md"> <vn-card class="vn-pa-lg vn-mt-md">
<vn-vertical>
<vn-autocomplete <vn-autocomplete
label="Role" label="Role"
ng-model="$ctrl.user.roleFk" ng-model="$ctrl.user.roleFk"

View File

@ -1,9 +1,21 @@
import ngModule from '../module'; import ngModule from '../module';
import Section from 'salix/components/section'; import Section from 'salix/components/section';
export default class Controller extends Section {} export default class Controller extends Section {
get user() {
return this._user;
}
set user(value) {
this._user = value;
if (!value) return;
}
}
ngModule.component('vnUserPrivileges', { ngModule.component('vnUserPrivileges', {
template: require('./index.html'), template: require('./index.html'),
controller: Controller controller: Controller,
bindings: {
user: '<'
}
}); });

View File

@ -49,15 +49,13 @@
"url": "/index?q", "url": "/index?q",
"state": "account.index", "state": "account.index",
"component": "vn-user-index", "component": "vn-user-index",
"description": "Users", "description": "Users"
"acl": ["marketing", "hr"]
}, },
{ {
"url": "/create", "url": "/create",
"state": "account.create", "state": "account.create",
"component": "vn-user-create", "component": "vn-user-create",
"description": "New user", "description": "New user"
"acl": ["it"]
}, },
{ {
"url": "/:id", "url": "/:id",
@ -80,7 +78,7 @@
"state": "account.card.basicData", "state": "account.card.basicData",
"component": "vn-user-basic-data", "component": "vn-user-basic-data",
"description": "Basic data", "description": "Basic data",
"acl": ["hr"] "acl": ["itManagement"]
}, },
{ {
"url" : "/log", "url" : "/log",
@ -98,8 +96,7 @@
"url": "/roles", "url": "/roles",
"state": "account.card.roles", "state": "account.card.roles",
"component": "vn-user-roles", "component": "vn-user-roles",
"description": "Inherited roles", "description": "Inherited roles"
"acl": ["it"]
}, },
{ {
"url": "/mail-forwarding", "url": "/mail-forwarding",
@ -111,15 +108,16 @@
"url": "/aliases", "url": "/aliases",
"state": "account.card.aliases", "state": "account.card.aliases",
"component": "vn-user-aliases", "component": "vn-user-aliases",
"description": "Mail aliases", "description": "Mail aliases"
"acl": ["marketing", "hr"]
}, },
{ {
"url": "/privileges", "url": "/privileges",
"state": "account.card.privileges", "state": "account.card.privileges",
"component": "vn-user-privileges", "component": "vn-user-privileges",
"description": "Privileges", "description": "Privileges",
"acl": ["hr"] "params": {
"user": "$ctrl.user"
}
}, },
{ {
"url": "/role?q", "url": "/role?q",
@ -180,8 +178,7 @@
"url": "/alias?q", "url": "/alias?q",
"state": "account.alias", "state": "account.alias",
"component": "vn-alias", "component": "vn-alias",
"description": "Mail aliases", "description": "Mail aliases"
"acl": ["marketing"]
}, },
{ {
"url": "/create", "url": "/create",

View File

@ -8,6 +8,7 @@ class Controller extends Summary {
if (!value) return; if (!value) return;
const filter = { const filter = {
where: {id: value.id},
include: { include: {
relation: 'role', relation: 'role',
scope: { scope: {
@ -15,8 +16,11 @@ class Controller extends Summary {
} }
} }
}; };
this.$http.get(`VnUsers/${value.id}`, {filter}) this.$http.get(`VnUsers/preview`, {filter})
.then(res => this.$.summary = res.data); .then(res => {
const [summary] = res.data;
this.$.summary = summary;
});
} }
get isHr() { get isHr() {
return this.aclService.hasAny(['hr']); return this.aclService.hasAny(['hr']);

View File

@ -2,7 +2,7 @@ const UserError = require('vn-loopback/util/user-error');
const base64url = require('base64url'); const base64url = require('base64url');
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx('confirm', { Self.remoteMethod('confirm', {
description: 'Confirms electronic payment transaction', description: 'Confirms electronic payment transaction',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ accepts: [
@ -30,7 +30,7 @@ module.exports = Self => {
} }
}); });
Self.confirm = async(ctx, signatureVersion, merchantParameters, signature) => { Self.confirm = async(signatureVersion, merchantParameters, signature) => {
const $ = Self.app.models; const $ = Self.app.models;
let transaction; let transaction;
@ -83,7 +83,7 @@ module.exports = Self => {
params['Ds_Currency'], params['Ds_Currency'],
params['Ds_Response'], params['Ds_Response'],
params['Ds_ErrorCode'] params['Ds_ErrorCode']
], {userId: ctx.req.accessToken.userId}); ]);
return true; return true;
} catch (err) { } catch (err) {

View File

@ -1,7 +1,5 @@
<vn-watcher <vn-watcher
vn-id="watcher" vn-id="watcher"
url="VnUsers"
id-field="id"
data="$ctrl.account" data="$ctrl.account"
form="form"> form="form">
</vn-watcher> </vn-watcher>
@ -51,9 +49,9 @@
label="Save"> label="Save">
</vn-submit> </vn-submit>
<vn-button <vn-button
ng-if="$ctrl.canChangePassword" ng-if="$ctrl.canChangePassword"
label="Change password" label="Change password"
vn-dialog="change-pass"> vn-dialog="change-pass">
</vn-button> </vn-button>
<vn-button <vn-button
class="cancel" class="cancel"

View File

@ -8,6 +8,22 @@ export default class Controller extends Section {
this.canEnableCheckBox = true; this.canEnableCheckBox = true;
} }
set client(value) {
this._client = value;
if (!value) return;
const filter = {where: {id: value.id}};
this.$http.get(`VnUsers/preview`, {filter})
.then(res => {
const [user] = res.data;
this.account = user;
});
}
get client() {
return this._client;
}
$onChanges() { $onChanges() {
if (this.client) { if (this.client) {
this.account = this.client.account; this.account = this.client.account;

View File

@ -5,12 +5,14 @@ describe('Component VnClientWebAccess', () => {
let $scope; let $scope;
let vnApp; let vnApp;
let controller; let controller;
let $httpParamSerializer;
beforeEach(ngModule('client')); beforeEach(ngModule('client'));
beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _vnApp_) => { beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_, _vnApp_) => {
$scope = $rootScope.$new(); $scope = $rootScope.$new();
$httpBackend = _$httpBackend_; $httpBackend = _$httpBackend_;
$httpParamSerializer = _$httpParamSerializer_;
vnApp = _vnApp_; vnApp = _vnApp_;
jest.spyOn(vnApp, 'showError'); jest.spyOn(vnApp, 'showError');
const $element = angular.element('<vn-client-web-access></vn-client-web-access>'); const $element = angular.element('<vn-client-web-access></vn-client-web-access>');
@ -32,7 +34,10 @@ describe('Component VnClientWebAccess', () => {
describe('isCustomer()', () => { describe('isCustomer()', () => {
it('should return true if the password can be modified', () => { it('should return true if the password can be modified', () => {
controller.client = {id: '1234'}; 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); $httpBackend.expectGET(`Clients/${controller.client.id}/hasCustomerRole`).respond(true);
controller.isCustomer(); controller.isCustomer();
$httpBackend.flush(); $httpBackend.flush();
@ -42,7 +47,10 @@ describe('Component VnClientWebAccess', () => {
it(`should return a false if the password can't be modified`, () => { it(`should return a false if the password can't be modified`, () => {
controller.client = {id: '1234'}; 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); $httpBackend.expectGET(`Clients/${controller.client.id}/hasCustomerRole`).respond(false);
controller.isCustomer(); controller.isCustomer();
$httpBackend.flush(); $httpBackend.flush();
@ -54,9 +62,12 @@ describe('Component VnClientWebAccess', () => {
describe('checkConditions()', () => { describe('checkConditions()', () => {
it('should perform a query to check if the client is valid', () => { it('should perform a query to check if the client is valid', () => {
controller.client = {id: '1234'}; controller.client = {id: '1234'};
const filter = {where: {id: controller.client.id}};
const serializedParams = $httpParamSerializer({filter});
expect(controller.canEnableCheckBox).toBeTruthy(); expect(controller.canEnableCheckBox).toBeTruthy();
$httpBackend.expectGET(`VnUsers/preview?${serializedParams}`).respond('foo');
$httpBackend.expectGET(`Clients/${controller.client.id}/isValidClient`).respond(false); $httpBackend.expectGET(`Clients/${controller.client.id}/isValidClient`).respond(false);
controller.checkConditions(); controller.checkConditions();
$httpBackend.flush(); $httpBackend.flush();
@ -82,7 +93,10 @@ describe('Component VnClientWebAccess', () => {
controller.newPassword = 'm24x8'; controller.newPassword = 'm24x8';
controller.repeatPassword = 'm24x8'; controller.repeatPassword = 'm24x8';
controller.canChangePassword = true; 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`; const query = `Clients/${controller.client.id}/setPassword`;
$httpBackend.expectPATCH(query, {newPassword: controller.newPassword}).respond('done'); $httpBackend.expectPATCH(query, {newPassword: controller.newPassword}).respond('done');
controller.onPassChange(); controller.onPassChange();

View File

@ -46,7 +46,7 @@ module.exports = Self => {
} }
try { try {
let buy = await models.Buy.findOne({where: {entryFk: args.id}}, myOptions); let buy = await models.Buy.findOne({where: {entryFk: args.id, itemFk: args.item}}, myOptions);
if (buy) if (buy)
await buy.updateAttribute('printedStickers', args.printedStickers, myOptions); await buy.updateAttribute('printedStickers', args.printedStickers, myOptions);
else { else {

View File

@ -118,7 +118,8 @@
label="Company" label="Company"
show-field="code" show-field="code"
value-field="id" value-field="id"
ng-model="$ctrl.companyFk"> ng-model="$ctrl.companyFk"
on-change="$ctrl.getInvoiceDate(value)">
</vn-autocomplete> </vn-autocomplete>
<vn-autocomplete <vn-autocomplete
url="Printers" url="Printers"

View File

@ -7,23 +7,29 @@ class Controller extends Section {
$onInit() { $onInit() {
const date = Date.vnNew(); const date = Date.vnNew();
Object.assign(this, { Object.assign(this, {
maxShipped: new Date(date.getFullYear(), date.getMonth(), 0), maxShipped: new Date(date.getFullYear(), date.getMonth(), 0),
clientsToInvoice: 'all', clientsToInvoice: 'all',
}); });
this.$http.get('UserConfigs/getUserConfig') this.$http.get('UserConfigs/getUserConfig')
.then(res => { .then(res => {
this.companyFk = res.data.companyFk; this.companyFk = res.data.companyFk;
const params = { this.getInvoiceDate(this.companyFk);
companyFk: this.companyFk });
}; }
return this.$http.get('InvoiceOuts/getInvoiceDate', {params});
}) getInvoiceDate(companyFk) {
.then(res => { const params = { companyFk: companyFk };
this.minInvoicingDate = res.data.issued ? new Date(res.data.issued) : null; this.fetchInvoiceDate(params);
this.invoiceDate = this.minInvoicingDate; }
});
} 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() { stopInvoicing() {
this.status = 'stopping'; this.status = 'stopping';
@ -42,7 +48,7 @@ class Controller extends Section {
throw new UserError('Invoice date and the max date should be filled'); throw new UserError('Invoice date and the max date should be filled');
if (this.invoiceDate < this.maxShipped) if (this.invoiceDate < this.maxShipped)
throw new UserError('Invoice date can\'t be less than max date'); throw new UserError('Invoice date can\'t be less than max date');
if (this.invoiceDate.getTime() < this.minInvoicingDate.getTime()) 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 previous date');
if (!this.companyFk) if (!this.companyFk)
throw new UserError('Choose a valid company'); throw new UserError('Choose a valid company');

View File

@ -19,7 +19,8 @@ export default class Controller extends Section {
this.smartTableOptions = { this.smartTableOptions = {
activeButtons: { activeButtons: {
search: true, search: true,
}, columns: [ },
columns: [
{ {
field: 'isActive', field: 'isActive',
searchable: false searchable: false

View File

@ -13,7 +13,6 @@ export default class Controller extends Section {
activeButtons: { activeButtons: {
search: true search: true
}, },
defaultSearch: true,
columns: [ columns: [
{ {
field: 'warehouseFk', field: 'warehouseFk',

View File

@ -50,13 +50,13 @@
<th field="salesPersonFk"> <th field="salesPersonFk">
<span translate>Salesperson</span> <span translate>Salesperson</span>
</th> </th>
<th field="shippedDate" shrink-date> <th field="shippedDate" shrink-date filter-enabled="false">
<span translate>Date</span> <span translate>Date</span>
</th> </th>
<th field="theoreticalHour"> <th field="theoreticalHour" filter-enabled="false">
<span translate>Theoretical</span> <span translate>Theoretical</span>
</th> </th>
<th field="practicalHour"> <th field="practicalHour" filter-enabled="false">
<span translate>Practical</span> <span translate>Practical</span>
</th> </th>
<th field="preparationHour" filter-enabled="false"> <th field="preparationHour" filter-enabled="false">

View File

@ -21,7 +21,6 @@ module.exports = Self => {
Self.confirm = async(ctx, orderFk) => { Self.confirm = async(ctx, orderFk) => {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const query = `CALL hedera.order_confirmWithUser(?, ?)`; const query = `CALL hedera.order_confirmWithUser(?, ?)`;
const response = await Self.rawSql(query, [orderFk, userId], {userId}); const response = await Self.rawSql(query, [orderFk, userId], {userId});

View File

@ -5,3 +5,4 @@ columns:
beneficiary: beneficiary beneficiary: beneficiary
supplierFk: supplier supplierFk: supplier
bankEntityFk: bank entity bankEntityFk: bank entity
accountingFk: ledger account

View File

@ -5,3 +5,4 @@ columns:
beneficiary: beneficiario beneficiary: beneficiario
supplierFk: proveedor supplierFk: proveedor
bankEntityFk: entidad bancaria bankEntityFk: entidad bancaria
accountingFk: cuenta contable

View File

@ -26,14 +26,14 @@ module.exports = Self => {
Self.getItemsPackaging = async(id, entry) => { Self.getItemsPackaging = async(id, entry) => {
return Self.rawSql(` return Self.rawSql(`
WITH entryTmp AS ( WITH entryTmp AS (
SELECT i.id, SUM(b.quantity) quantity SELECT i.id, SUM(b.quantity) quantity, SUM(b.printedStickers) printedStickers
FROM vn.entry e FROM vn.entry e
JOIN vn.buy b ON b.entryFk = e.id JOIN vn.buy b ON b.entryFk = e.id
JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.supplier s ON s.id = e.supplierFk
JOIN vn.item i ON i.id = b.itemFk JOIN vn.item i ON i.id = b.itemFk
WHERE e.id = ? AND e.supplierFk = ? WHERE e.id = ? AND e.supplierFk = ?
GROUP BY i.id GROUP BY i.id
) SELECT i.id, i.name, et.quantity, SUM(b.quantity) quantityTotal ) SELECT i.id, i.name, et.quantity, SUM(b.quantity) quantityTotal, et.printedStickers
FROM vn.buy b FROM vn.buy b
JOIN vn.item i ON i.id = b.itemFk JOIN vn.item i ON i.id = b.itemFk
JOIN vn.entry e ON e.id = b.entryFk JOIN vn.entry e ON e.id = b.entryFk

View File

@ -2,14 +2,17 @@ name: request
columns: columns:
id: id id: id
description: description description: description
created: created buyerCode: buyer
quantity: quantity quantity: quantity
price: price price: price
isOk: ok
response: response
saleFk: sale
ticketFk: ticket
attenderFk: attender
requesterFk: requester
itemFk: item itemFk: item
clientFk: client
response: response
total: total
buyed: buyed
saleFk: sale
created: created
isOk: ok
requesterFk: requester
attenderFk: attender
ticketFk: ticket

View File

@ -1,15 +1,18 @@
name: peticion name: petición
columns: columns:
id: id id: id
description: descripción description: descripción
created: creado buyerCode: comprador
quantity: cantidad quantity: cantidad
price: precio price: precio
isOk: ok
response: respuesta
saleFk: línea
ticketFk: ticket
attenderFk: asistente
requesterFk: solicitante
itemFk: artículo itemFk: artículo
clientFk: cliente
response: respuesta
total: total
buyed: comprado
saleFk: línea
created: creado
isOk: ok
requesterFk: solicitante
attenderFk: asistente
ticketFk: ticket

View File

@ -69,7 +69,7 @@
<vn-th ng-click="$ctrl.sortBy('price')" field="price" number>Price</vn-th> <vn-th ng-click="$ctrl.sortBy('price')" field="price" number>Price</vn-th>
<vn-th ng-click="$ctrl.sortBy('discount')" field="discount" number>Disc</vn-th> <vn-th ng-click="$ctrl.sortBy('discount')" field="discount" number>Disc</vn-th>
<vn-th ng-click="$ctrl.sortBy('amount')" field="amount" number>Amount</vn-th> <vn-th ng-click="$ctrl.sortBy('amount')" field="amount" number>Amount</vn-th>
<vn-th ng-click="$ctrl.sortBy('itemPackingTypeFk')" field="itemPackingTypeFk" shrink>Packaging</vn-th> <vn-th ng-click="$ctrl.sortBy('item.itemPackingTypeFk')" field="itemPackingTypeFk" shrink>Packaging</vn-th>
<vn-th shrink></vn-th> <vn-th shrink></vn-th>
</vn-tr> </vn-tr>
</vn-thead> </vn-thead>
@ -202,7 +202,7 @@
</span> </span>
</vn-td> </vn-td>
<vn-td number> <vn-td number>
{{$ctrl.getSaleTotal(sale) | currency: 'EUR':2}} {{sale.amount | currency: 'EUR':2}}
</vn-td> </vn-td>
<vn-td shrink> <vn-td shrink>
{{::sale.item.itemPackingTypeFk | dashIfEmpty}} {{::sale.item.itemPackingTypeFk | dashIfEmpty}}

View File

@ -34,6 +34,11 @@ class Controller extends Section {
} }
get sales() { get sales() {
if (this._sales) {
for (let sale of this._sales)
sale.amount = this.getSaleTotal(sale);
}
return this._sales; return this._sales;
} }
@ -49,6 +54,7 @@ class Controller extends Section {
return ticketState && ticketState.state.code; return ticketState && ticketState.state.code;
} }
getConfig() { getConfig() {
let filter = { let filter = {
fields: ['daysForWarningClaim'], fields: ['daysForWarningClaim'],

View File

@ -1,5 +1,5 @@
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx, ('getLeaves', { Self.remoteMethodCtx('getLeaves', {
description: 'Returns the nodes for a department', description: 'Returns the nodes for a department',
accepts: [{ accepts: [{
arg: 'parentId', arg: 'parentId',

View File

@ -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;
};
};

View File

@ -16,6 +16,7 @@ module.exports = Self => {
require('../methods/worker/new')(Self); require('../methods/worker/new')(Self);
require('../methods/worker/deallocatePDA')(Self); require('../methods/worker/deallocatePDA')(Self);
require('../methods/worker/allocatePDA')(Self); require('../methods/worker/allocatePDA')(Self);
require('../methods/worker/isAuthorized')(Self);
Self.validatesUniquenessOf('locker', { Self.validatesUniquenessOf('locker', {
message: 'This locker has already been assigned' message: 'This locker has already been assigned'

View File

@ -1,33 +0,0 @@
<mg-ajax
path="VnUsers/{{$ctrl.worker.userFk}}"
actions="user = edit.model"
options="mgEdit">
</mg-ajax>
<vn-watcher
vn-id="watcher"
url="VnUsers"
id-field="id"
data="user"
form="form">
</vn-watcher>
<form name="form" ng-submit="$ctrl.onSubmit()" class="vn-w-md">
<vn-card class="vn-pa-lg">
<vn-vertical>
<vn-horizontal>
<vn-field
vn-one
label="Nickname"
ng-model="user.nickname">
</vn-field>
</vn-horizontal>
</vn-vertical>
</vn-card>
<vn-button-bar>
<vn-submit label="Save"></vn-submit>
<vn-button
label="Undo changes"
ng-if="watcher.dataChanged()"
ng-click="watcher.loadOriginalData()">
</vn-button>
</vn-button-bar>
</form>

View File

@ -70,10 +70,6 @@ class Controller extends Section {
} }
} }
get payedHolidays() {
return this._businessId;
}
buildYearFilter() { buildYearFilter() {
const now = Date.vnNew(); const now = Date.vnNew();
now.setFullYear(now.getFullYear() + 1); now.setFullYear(now.getFullYear() + 1);
@ -94,10 +90,10 @@ class Controller extends Section {
} }
getActiveContract() { getActiveContract() {
this.$http.get(`Workers/${this.worker.id}/activeContract`).then(res => { this.$http.get(`Workers/${this.worker.id}/activeContract`)
if (res.data) .then(res => {
this.businessId = res.data.businessFk; if (res.data) this.businessId = res.data.businessFk;
}); });
} }
getContractHolidays() { getContractHolidays() {

View File

@ -1,14 +1,14 @@
name: zone event name: event
columns: columns:
id: id id: id
zoneFk: zone zoneFk: zone
type: type type: type
dated: dated dated: dated
started: started started: starts
ended: ended ended: ends
weekDays: week days weekDays: week days
hour: hour hour: hour
travelingDays: traveling days travelingDays: traveling days
price: price price: price
bonus: bonus bonus: bonus
m3Max: max m3 m3Max: max. m3

View File

@ -1,11 +1,11 @@
name: evento zona name: evento
columns: columns:
id: id id: id
zoneFk: zona zoneFk: zona
type: tipo type: tipo
dated: fecha dated: fecha
started: comenzado started: empieza
ended: terminado ended: termina
weekDays: días semana weekDays: días semana
hour: hora hour: hora
travelingDays: días de viaje travelingDays: días de viaje

View File

@ -1,5 +1,5 @@
name: zone exclusion name: exclusion
columns: columns:
id: id id: id
dated: dated dated: date
zoneFk: zone zoneFk: zone

View File

@ -1,4 +1,4 @@
name: zone exclusion name: exclusión
columns: columns:
id: id id: id
dated: fecha dated: fecha

View File

@ -1,5 +1,7 @@
name: zone included name: inclusion
columns: columns:
id: id id: id
dated: dated dated: dated
zoneFk: zone zoneFk: zone
isIncluded: incluida
geoFk: localización

View File

@ -1,5 +1,7 @@
name: zona incluida name: inclusión
columns: columns:
id: id id: id
dated: fecha dated: fecha
zoneFk: zona zoneFk: zona
isIncluded: incluida
geoFk: localización

View File

@ -1,4 +1,4 @@
name: zone warehouse name: warehouse
columns: columns:
id: id id: id
warehouseFk: warehouse warehouseFk: warehouse

View File

@ -1,4 +1,4 @@
name: almacén zona name: almacén
columns: columns:
id: id id: id
warehouseFk: almacén warehouseFk: almacén

2
package-lock.json generated
View File

@ -1,6 +1,6 @@
{ {
"name": "salix-back", "name": "salix-back",
"version": "23.24.01", "version": "23.26.01",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {

View File

@ -5,10 +5,9 @@ module.exports = {
name: 'report-footer', name: 'report-footer',
async serverPrefetch() { async serverPrefetch() {
this.company = await db.findOne(` this.company = await db.findOne(`
SELECT IFNULL(ci.footnotes, cl.footnotes) as footnotes SELECT IFNULL(ci.footnotes, c.footnotes) footnotes
FROM company c FROM company c
LEFT JOIN companyL10n cl ON c.id = cl.id LEFT JOIN companyI18n ci ON ci.companyFk = c.id
LEFT JOIN companyI18n ci ON ci.companyFk = cl.id
AND ci.lang = (SELECT lang FROM account.user where id = ?) AND ci.lang = (SELECT lang FROM account.user where id = ?)
WHERE c.code = ?`, WHERE c.code = ?`,
[this.recipientId, this.companyCode]); [this.recipientId, this.companyCode]);

View File

@ -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();

View File

@ -0,0 +1,5 @@
.external-link {
border: 2px dashed #8dba25;
border-radius: 3px;
text-align: center
}

View File

@ -0,0 +1,10 @@
<email-body v-bind="$props">
<div class="grid-row">
<div class="grid-block vn-pa-ml">
<p>
{{$t('dear')}}
</p>
<p v-html="$t('body',[currencyName,referenceCurrent])"></p>
</div>
</div>
</email-body>

View File

@ -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
}
}
};

Some files were not shown because too many files have changed in this diff Show More