Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix into 3598-worker_calendar_absences

This commit is contained in:
Alex Moreno 2022-03-02 10:24:11 +01:00
commit 26ed4b3c30
56 changed files with 1178 additions and 355 deletions

View File

@ -0,0 +1,55 @@
const axios = require('axios');
const tokenLifespan = 10;
module.exports = Self => {
Self.remoteMethodCtx('getServiceAuth', {
description: 'Authenticates with the service and request a new token',
accessType: 'READ',
accepts: [],
returns: {
type: 'object',
root: true
},
http: {
path: `/getServiceAuth`,
verb: 'GET'
}
});
Self.getServiceAuth = async() => {
if (!this.login)
this.login = await requestToken();
if (!this.login) return;
if (Date.now() > this.login.expires)
this.login = await requestToken();
return this.login;
};
/**
* Requests a new Rocketchat token
*/
async function requestToken() {
const models = Self.app.models;
const chatConfig = await models.ChatConfig.findOne();
const {data} = await axios.post(`${chatConfig.api}/login`, {
user: chatConfig.user,
password: chatConfig.password
});
const requestData = data.data;
if (requestData) {
return {
host: chatConfig.host,
api: chatConfig.api,
auth: {
userId: requestData.userId,
token: requestData.authToken
},
expires: Date.now() + (1000 * 60 * tokenLifespan)
};
}
}
};

View File

@ -1,4 +1,4 @@
const got = require('got'); const axios = require('axios');
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx('send', { Self.remoteMethodCtx('send', {
description: 'Send a RocketChat message', description: 'Send a RocketChat message',
@ -30,122 +30,35 @@ module.exports = Self => {
const sender = await models.Account.findById(accessToken.userId); const sender = await models.Account.findById(accessToken.userId);
const recipient = to.replace('@', ''); const recipient = to.replace('@', '');
if (sender.name != recipient) { if (sender.name != recipient)
let {body} = await sendMessage(sender, to, message); return sendMessage(sender, to, message);
if (body)
body = JSON.parse(body);
else
body = false;
return body;
}
return false;
}; };
async function sendMessage(sender, channel, message) { async function sendMessage(sender, channel, message) {
const config = await getConfig();
const avatar = `${config.host}/avatar/${sender.name}`;
const uri = `${config.api}/chat.postMessage`;
return sendAuth(uri, {
'channel': channel,
'avatar': avatar,
'alias': sender.nickname,
'text': message
}).catch(async error => {
if (error.statusCode === 401) {
this.auth = null;
return sendMessage(sender, channel, message);
}
throw new Error(error.message);
});
}
/**
* Returns a rocketchat token
* @return {Object} userId and authToken
*/
async function getAuthToken() {
if (!this.auth || this.auth && !this.auth.authToken) {
const config = await getConfig();
const uri = `${config.api}/login`;
let {body} = await send(uri, {
user: config.user,
password: config.password
});
if (body) {
body = JSON.parse(body);
this.auth = body.data;
}
}
return this.auth;
}
/**
* Returns a rocketchat config
* @return {Object} Auth config
*/
async function getConfig() {
if (!this.chatConfig) {
const models = Self.app.models;
this.chatConfig = await models.ChatConfig.findOne();
}
return this.chatConfig;
}
/**
* Send unauthenticated request
* @param {*} uri - Request uri
* @param {*} params - Request params
* @param {*} options - Request options
*
* @return {Object} Request response
*/
async function send(uri, params, options = {}) {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => { return new Promise(resolve => {
return resolve({ return resolve({
body: JSON.stringify( statusCode: 200,
{statusCode: 200, message: 'Fake notification sent'} message: 'Fake notification sent'
)
}); });
}); });
} }
const defaultOptions = { const login = await Self.getServiceAuth();
form: params const avatar = `${login.host}/avatar/${sender.name}`;
};
if (options) Object.assign(defaultOptions, options);
return got.post(uri, defaultOptions);
}
/**
* Send authenticated request
* @param {*} uri - Request uri
* @param {*} body - Request params
*
* @return {Object} Request response
*/
async function sendAuth(uri, body) {
const login = await getAuthToken();
const options = { const options = {
headers: {} headers: {
'X-Auth-Token': login.auth.token,
'X-User-Id': login.auth.userId
},
}; };
if (login) { return axios.post(`${login.api}/chat.postMessage`, {
options.headers['X-Auth-Token'] = login.authToken; 'channel': channel,
options.headers['X-User-Id'] = login.userId; 'avatar': avatar,
} 'alias': sender.nickname,
'text': message
return send(uri, body, options); }, options);
} }
}; };

View File

@ -1,21 +1,23 @@
const axios = require('axios');
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx('sendCheckingPresence', { Self.remoteMethodCtx('sendCheckingPresence', {
description: 'Sends a RocketChat message to a working worker or department channel', description: 'Sends a RocketChat message to a connected user or department channel',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [{ accepts: [{
arg: 'workerId', arg: 'recipientId',
type: 'Number', type: 'number',
required: true, required: true,
description: 'The worker id of the destinatary' description: 'The recipient user id'
}, },
{ {
arg: 'message', arg: 'message',
type: 'String', type: 'string',
required: true, required: true,
description: 'The message' description: 'The message'
}], }],
returns: { returns: {
type: 'Object', type: 'object',
root: true root: true
}, },
http: { http: {
@ -33,30 +35,61 @@ module.exports = Self => {
Object.assign(myOptions, options); Object.assign(myOptions, options);
const models = Self.app.models; const models = Self.app.models;
const account = await models.Account.findById(recipientId, null, myOptions);
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const recipient = await models.Account.findById(recipientId, null, myOptions);
// Prevent sending messages to yourself
if (recipientId == userId) return false; if (recipientId == userId) return false;
if (!account) if (!recipient)
throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`); throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);
const query = `SELECT worker_isWorking(?) isWorking`; const {data} = await Self.getUserStatus(recipient.name);
const [result] = await Self.rawSql(query, [recipientId], myOptions); if (data) {
if (data.status === 'offline') {
// Send message to department room
const workerDepartment = await models.WorkerDepartment.findById(recipientId, {
include: {
relation: 'department'
}
}, myOptions);
const department = workerDepartment && workerDepartment.department();
const channelName = department && department.chatName;
if (!result.isWorking) { if (channelName)
const workerDepartment = await models.WorkerDepartment.findById(recipientId, { return Self.send(ctx, `#${channelName}`, `@${recipient.name}${message}`);
include: { } else
relation: 'department' return Self.send(ctx, `@${recipient.name}`, message);
} }
}, myOptions); };
const department = workerDepartment && workerDepartment.department();
const channelName = department && department.chatName;
if (channelName) /**
return Self.send(ctx, `#${channelName}`, `@${account.name}${message}`); * Returns the current user status on Rocketchat
*
* @param {string} username - The recipient user name
* @return {Promise} - The request promise
*/
Self.getUserStatus = async function getUserStatus(username) {
if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => {
return resolve({
data: {
status: 'online'
}
});
});
} }
return Self.send(ctx, `@${account.name}`, message); const login = await Self.getServiceAuth();
const options = {
params: {username},
headers: {
'X-Auth-Token': login.auth.token,
'X-User-Id': login.auth.userId
},
};
return axios.get(`${login.api}/users.getStatus`, options);
}; };
}; };

View File

@ -1,46 +1,62 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('Chat sendCheckingPresence()', () => { describe('Chat sendCheckingPresence()', () => {
const today = new Date(); const today = new Date();
today.setHours(6, 0); today.setHours(6, 0);
const ctx = {req: {accessToken: {userId: 1}}}; const ctx = {req: {accessToken: {userId: 1}}};
const chatModel = app.models.Chat; const chatModel = models.Chat;
const departmentId = 23; const departmentId = 23;
const workerId = 1107; const workerId = 1107;
it(`should call send() method with the worker name if he's currently working then return a response`, async() => { it(`should call to send() method with "@HankPym" as recipient argument`, async() => {
spyOn(chatModel, 'send').and.callThrough(); spyOn(chatModel, 'send').and.callThrough();
spyOn(chatModel, 'getUserStatus').and.returnValue(
const timeEntry = await app.models.WorkerTimeControl.create({ new Promise(resolve => {
userFk: workerId, return resolve({
timed: today, data: {
manual: false, status: 'online'
direction: 'in' }
}); });
})
);
const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something'); const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something');
expect(response.statusCode).toEqual(200); expect(response.statusCode).toEqual(200);
expect(response.message).toEqual('Fake notification sent'); expect(response.message).toEqual('Fake notification sent');
expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', 'I changed something'); expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', 'I changed something');
// restores
await app.models.WorkerTimeControl.destroyById(timeEntry.id);
}); });
it(`should call to send() method with the worker department channel if he's not currently working then return a response`, async() => { it(`should call to send() method with "#cooler" as recipient argument`, async() => {
spyOn(chatModel, 'send').and.callThrough(); spyOn(chatModel, 'send').and.callThrough();
spyOn(chatModel, 'getUserStatus').and.returnValue(
new Promise(resolve => {
return resolve({
data: {
status: 'offline'
}
});
})
);
const department = await app.models.Department.findById(departmentId); const tx = await models.Claim.beginTransaction({});
await department.updateAttribute('chatName', 'cooler');
const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something'); try {
const options = {transaction: tx};
expect(response.statusCode).toEqual(200); const department = await models.Department.findById(departmentId, null, options);
expect(response.message).toEqual('Fake notification sent'); await department.updateAttribute('chatName', 'cooler');
expect(chatModel.send).toHaveBeenCalledWith(ctx, '#cooler', '@HankPym ➔ I changed something');
// restores const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something');
await department.updateAttribute('chatName', null);
expect(response.statusCode).toEqual(200);
expect(response.message).toEqual('Fake notification sent');
expect(chatModel.send).toHaveBeenCalledWith(ctx, '#cooler', '@HankPym ➔ I changed something');
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -0,0 +1,93 @@
const got = require('got');
module.exports = Self => {
Self.remoteMethodCtx('checkFile', {
description: 'Check if exist docuware file',
accessType: 'READ',
accepts: [
{
arg: 'id',
type: 'number',
description: 'The id',
http: {source: 'path'}
},
{
arg: 'fileCabinet',
type: 'string',
required: true,
description: 'The fileCabinet name'
},
{
arg: 'dialog',
type: 'string',
required: true,
description: 'The dialog name'
}
],
returns: {
type: 'boolean',
root: true
},
http: {
path: `/:id/checkFile`,
verb: 'POST'
}
});
Self.checkFile = async function(ctx, id, fileCabinet, dialog) {
const myUserId = ctx.req.accessToken.userId;
if (!myUserId)
return false;
const models = Self.app.models;
const docuwareConfig = await models.DocuwareConfig.findOne();
const docuwareInfo = await models.Docuware.findOne({
where: {
code: fileCabinet,
dialogName: dialog
}
});
const docuwareUrl = docuwareConfig.url;
const cookie = docuwareConfig.token;
const fileCabinetName = docuwareInfo.fileCabinetName;
const find = docuwareInfo.find;
const options = {
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cookie': cookie
}
};
const searchFilter = {
condition: [
{
DBName: find,
Value: [id]
}
]
};
try {
// get fileCabinetId
const fileCabinetResponse = await got.get(`${docuwareUrl}/FileCabinets`, options);
const fileCabinetJson = JSON.parse(fileCabinetResponse.body).FileCabinet;
const fileCabinetId = fileCabinetJson.find(dialogs => dialogs.Name === fileCabinetName).Id;
// get dialog
const dialogResponse = await got.get(`${docuwareUrl}/FileCabinets/${fileCabinetId}/dialogs`, options);
const dialogJson = JSON.parse(dialogResponse.body).Dialog;
const dialogId = dialogJson.find(dialogs => dialogs.DisplayName === 'find').Id;
// get docuwareID
Object.assign(options, {'body': JSON.stringify(searchFilter)});
const response = await got.post(
`${docuwareUrl}/FileCabinets/${fileCabinetId}/Query/DialogExpression?dialogId=${dialogId}`, options);
JSON.parse(response.body).Items[0].Id;
return true;
} catch (error) {
return false;
}
};
};

View File

@ -0,0 +1,120 @@
/* eslint max-len: ["error", { "code": 180 }]*/
const got = require('got');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('download', {
description: 'Download an docuware PDF',
accessType: 'READ',
accepts: [
{
arg: 'id',
type: 'number',
description: 'The id',
http: {source: 'path'}
},
{
arg: 'fileCabinet',
type: 'string',
description: 'The id',
http: {source: 'path'}
},
{
arg: 'dialog',
type: 'string',
description: 'The id',
http: {source: 'path'}
}
],
returns: [
{
arg: 'body',
type: 'file',
root: true
}, {
arg: 'Content-Type',
type: 'string',
http: {target: 'header'}
}, {
arg: 'Content-Disposition',
type: 'string',
http: {target: 'header'}
}
],
http: {
path: `/:id/download/:fileCabinet/:dialog`,
verb: 'GET'
}
});
Self.download = async function(ctx, id, fileCabinet, dialog) {
const myUserId = ctx.req.accessToken.userId;
if (!myUserId)
throw new UserError(`You don't have enough privileges`);
const models = Self.app.models;
const docuwareConfig = await models.DocuwareConfig.findOne();
const docuwareInfo = await models.Docuware.findOne({
where: {
code: fileCabinet,
dialogName: dialog
}
});
const docuwareUrl = docuwareConfig.url;
const cookie = docuwareConfig.token;
const fileCabinetName = docuwareInfo.fileCabinetName;
const find = docuwareInfo.find;
const options = {
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cookie': cookie
}
};
const searchFilter = {
condition: [
{
DBName: find,
Value: [id]
}
]
};
try {
// get fileCabinetId
const fileCabinetResponse = await got.get(`${docuwareUrl}/FileCabinets`, options);
const fileCabinetJson = JSON.parse(fileCabinetResponse.body).FileCabinet;
const fileCabinetId = fileCabinetJson.find(dialogs => dialogs.Name === fileCabinetName).Id;
// get dialog
const dialogResponse = await got.get(`${docuwareUrl}/FileCabinets/${fileCabinetId}/dialogs`, options);
const dialogJson = JSON.parse(dialogResponse.body).Dialog;
const dialogId = dialogJson.find(dialogs => dialogs.DisplayName === 'find').Id;
// get docuwareID
Object.assign(options, {'body': JSON.stringify(searchFilter)});
const response = await got.post(`${docuwareUrl}/FileCabinets/${fileCabinetId}/Query/DialogExpression?dialogId=${dialogId}`, options);
const docuwareId = JSON.parse(response.body).Items[0].Id;
// download & save file
const fileName = `filename="${id}.pdf"`;
const contentType = 'application/pdf';
const downloadUri = `${docuwareUrl}/FileCabinets/${fileCabinetId}/Documents/${docuwareId}/FileDownload?targetFileType=Auto&keepAnnotations=false`;
const downloadOptions = {
'headers': {
'Cookie': cookie
}
};
const stream = got.stream(downloadUri, downloadOptions);
return [stream, contentType, fileName];
} catch (error) {
if (error.code === 'ENOENT')
throw new UserError('The DOCUWARE PDF document does not exists');
throw error;
}
};
};

View File

@ -0,0 +1,64 @@
const models = require('vn-loopback/server/server').models;
const got = require('got');
describe('docuware download()', () => {
const ticketId = 1;
const userId = 9;
const ctx = {
req: {
accessToken: {userId: userId},
headers: {origin: 'http://localhost:5000'},
}
};
const fileCabinetName = 'deliveryClientTest';
const dialogDisplayName = 'find';
const dialogName = 'findTest';
const gotGetResponse = {
body: JSON.stringify(
{
FileCabinet: [
{Id: 12, Name: fileCabinetName}
],
Dialog: [
{Id: 34, DisplayName: dialogDisplayName}
]
})
};
it('should return exist file in docuware', async() => {
const gotPostResponse = {
body: JSON.stringify(
{
Items: [
{Id: 56}
],
})
};
spyOn(got, 'get').and.returnValue(new Promise(resolve => resolve(gotGetResponse)));
spyOn(got, 'post').and.returnValue(new Promise(resolve => resolve(gotPostResponse)));
const result = await models.Docuware.checkFile(ctx, ticketId, fileCabinetName, dialogName);
expect(result).toEqual(true);
});
it('should return not exist file in docuware', async() => {
const gotPostResponse = {
body: JSON.stringify(
{
Items: [],
})
};
spyOn(got, 'get').and.returnValue(new Promise(resolve => resolve(gotGetResponse)));
spyOn(got, 'post').and.returnValue(new Promise(resolve => resolve(gotPostResponse)));
const result = await models.Docuware.checkFile(ctx, ticketId, fileCabinetName, dialogName);
expect(result).toEqual(false);
});
});

View File

@ -0,0 +1,50 @@
const models = require('vn-loopback/server/server').models;
const got = require('got');
const stream = require('stream');
describe('docuware download()', () => {
const userId = 9;
const ticketId = 1;
const ctx = {
req: {
accessToken: {userId: userId},
headers: {origin: 'http://localhost:5000'},
}
};
it('should return the downloaded file name', async() => {
const fileCabinetName = 'deliveryClientTest';
const dialogDisplayName = 'find';
const dialogName = 'findTest';
const gotGetResponse = {
body: JSON.stringify(
{
FileCabinet: [
{Id: 12, Name: fileCabinetName}
],
Dialog: [
{Id: 34, DisplayName: dialogDisplayName}
]
})
};
const gotPostResponse = {
body: JSON.stringify(
{
Items: [
{Id: 56}
],
})
};
spyOn(got, 'get').and.returnValue(new Promise(resolve => resolve(gotGetResponse)));
spyOn(got, 'post').and.returnValue(new Promise(resolve => resolve(gotPostResponse)));
spyOn(got, 'stream').and.returnValue(new stream.PassThrough({objectMode: true}));
const result = await models.Docuware.download(ctx, ticketId, fileCabinetName, dialogName);
expect(result[1]).toEqual('application/pdf');
expect(result[2]).toEqual(`filename="${ticketId}.pdf"`);
});
});

View File

@ -44,6 +44,12 @@
"DmsType": { "DmsType": {
"dataSource": "vn" "dataSource": "vn"
}, },
"Docuware": {
"dataSource": "vn"
},
"DocuwareConfig": {
"dataSource": "vn"
},
"EmailUser": { "EmailUser": {
"dataSource": "vn" "dataSource": "vn"
}, },

View File

@ -1,4 +1,5 @@
module.exports = Self => { module.exports = Self => {
require('../methods/chat/getServiceAuth')(Self);
require('../methods/chat/send')(Self); require('../methods/chat/send')(Self);
require('../methods/chat/sendCheckingPresence')(Self); require('../methods/chat/sendCheckingPresence')(Self);
require('../methods/chat/notifyIssues')(Self); require('../methods/chat/notifyIssues')(Self);

View File

@ -0,0 +1,32 @@
{
"name": "DocuwareConfig",
"description": "Docuware config",
"base": "VnModel",
"options": {
"mysql": {
"table": "docuwareConfig"
}
},
"properties": {
"id": {
"type": "number",
"id": true,
"description": "Identifier"
},
"url": {
"type": "string"
},
"token": {
"type": "string"
}
},
"acls": [
{
"property": "*",
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
]
}

4
back/models/docuware.js Normal file
View File

@ -0,0 +1,4 @@
module.exports = Self => {
require('../methods/docuware/download')(Self);
require('../methods/docuware/checkFile')(Self);
};

38
back/models/docuware.json Normal file
View File

@ -0,0 +1,38 @@
{
"name": "Docuware",
"description": "Docuware sections",
"base": "VnModel",
"options": {
"mysql": {
"table": "docuware"
}
},
"properties": {
"id": {
"type": "number",
"id": true,
"description": "Identifier"
},
"code": {
"type": "string"
},
"fileCabinetName": {
"type": "string"
},
"dialogName": {
"type": "string"
},
"find": {
"type": "string"
}
},
"acls": [
{
"property": "*",
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
]
}

View File

@ -0,0 +1,3 @@
INSERT INTO salix.ACL
(model, property, accessType, permission, principalType, principalId)
VALUES('Docuware', '*', '*', 'ALLOW', 'ROLE', 'employee');

View File

@ -0,0 +1,11 @@
CREATE TABLE `vn`.`docuware` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`code` varchar(50) NULL,
`fileCabinetName` varchar(50) NULL,
`dialogName` varchar(255) DEFAULT NULL,
`find` varchar(50) DEFAULT NULL
);
INSERT INTO `vn`.`docuware` (`code`, `fileCabinetName`, `dialogName` , `find`)
VALUES
('deliveryClient', 'Albaranes cliente', 'findTicket', 'N__ALBAR_N');

View File

@ -0,0 +1,9 @@
CREATE TABLE `vn`.`docuwareConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`url` varchar(75) NULL,
`token` varchar(1000) DEFAULT NULL
);
INSERT INTO `vn`.`docuwareConfig` (`url`)
VALUES
('https://verdnatura.docuware.cloud/docuware/platform');

View File

@ -6,20 +6,23 @@ CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`ticket_getMovable`(vTicketFk INT, vDat
BEGIN BEGIN
/** /**
* Cálcula el stock movible para los artículos de un ticket * Cálcula el stock movible para los artículos de un ticket
* vDatedNew debe ser menor que vDatedOld, en los otros casos se
* asume que siempre es posible
* *
* @param vTicketFk -> Ticket * @param vTicketFk -> Ticket
* @param vDatedNew -> Nueva fecha * @param vDatedNew -> Nueva fecha
* @return Sales con Movible * @return Sales con Movible
*/ */
DECLARE vDatedOld DATETIME; DECLARE vDatedOld DATETIME;
SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY);
SELECT t.shipped INTO vDatedOld SELECT t.shipped INTO vDatedOld
FROM ticket t FROM ticket t
WHERE t.id = vTicketFk; WHERE t.id = vTicketFk;
CALL itemStock(vWarehouseFk, DATE_SUB(vDatedNew, INTERVAL 1 DAY), NULL); CALL itemStock(vWarehouseFk, vDatedNew, NULL);
CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(vDatedOld, vDatedNew), NULL); CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(DATE_SUB(vDatedOld, INTERVAL 1 DAY), vDatedNew), NULL);
SELECT s.id, SELECT s.id,
s.itemFk, s.itemFk,
s.quantity, s.quantity,

View File

@ -0,0 +1 @@
delete file

View File

@ -2443,3 +2443,11 @@ INSERT INTO `bs`.`defaulter` (`clientFk`, `amount`, `created`, `defaulterSinced`
(1103, 500, CURDATE(), CURDATE()), (1103, 500, CURDATE(), CURDATE()),
(1107, 500, CURDATE(), CURDATE()), (1107, 500, CURDATE(), CURDATE()),
(1109, 500, CURDATE(), CURDATE()); (1109, 500, CURDATE(), CURDATE());
INSERT INTO `vn`.`docuware` (`code`, `fileCabinetName`, `dialogName` , `find`)
VALUES
('deliveryClientTest', 'deliveryClientTest', 'findTest', 'word');
INSERT INTO `vn`.`docuwareConfig` (`url`)
VALUES
('https://verdnatura.docuware.cloud/docuware/platform');

View File

@ -305,11 +305,11 @@ export default {
anyCreditInsuranceLine: 'vn-client-credit-insurance-insurance-index vn-tbody > vn-tr', anyCreditInsuranceLine: 'vn-client-credit-insurance-insurance-index vn-tbody > vn-tr',
}, },
clientDefaulter: { clientDefaulter: {
anyClient: 'vn-client-defaulter-index vn-tbody > vn-tr', anyClient: 'vn-client-defaulter-index tbody > tr',
firstClientName: 'vn-client-defaulter-index vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(2) > span', firstClientName: 'vn-client-defaulter-index tbody > tr:nth-child(1) > td:nth-child(2) > span',
firstSalesPersonName: 'vn-client-defaulter-index vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(3) > span', firstSalesPersonName: 'vn-client-defaulter-index tbody > tr:nth-child(1) > td:nth-child(3) > span',
firstObservation: 'vn-client-defaulter-index vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(6) > vn-textarea[ng-model="defaulter.observation"]', firstObservation: 'vn-client-defaulter-index tbody > tr:nth-child(1) > td:nth-child(6) > vn-textarea[ng-model="defaulter.observation"]',
allDefaulterCheckbox: 'vn-client-defaulter-index vn-thead vn-multi-check', allDefaulterCheckbox: 'vn-client-defaulter-index thead vn-multi-check',
addObservationButton: 'vn-client-defaulter-index vn-button[icon="icon-notes"]', addObservationButton: 'vn-client-defaulter-index 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"]',
saveButton: 'button[response="accept"]' saveButton: 'button[response="accept"]'

View File

@ -28,8 +28,8 @@ describe('Client defaulter path', () => {
const salesPersonName = const salesPersonName =
await page.waitToGetProperty(selectors.clientDefaulter.firstSalesPersonName, 'innerText'); await page.waitToGetProperty(selectors.clientDefaulter.firstSalesPersonName, 'innerText');
expect(clientName).toEqual('Ororo Munroe'); expect(clientName).toEqual('Batman');
expect(salesPersonName).toEqual('salesPerson'); expect(salesPersonName).toEqual('salesPersonNick');
}); });
it('should first observation not changed', async() => { it('should first observation not changed', async() => {
@ -65,6 +65,7 @@ describe('Client defaulter path', () => {
it('should first observation changed', async() => { it('should first observation changed', async() => {
const message = await page.waitForSnackbar(); const message = await page.waitForSnackbar();
await page.waitForSelector(selectors.clientDefaulter.firstObservation);
const result = await page.waitToGetProperty(selectors.clientDefaulter.firstObservation, 'value'); const result = await page.waitToGetProperty(selectors.clientDefaulter.firstObservation, 'value');
expect(message.text).toContain('Observation saved!'); expect(message.text).toContain('Observation saved!');

View File

@ -1,6 +1,10 @@
module.exports = Self => { module.exports = Self => {
Self.getSynchronizer = async function() { Self.getSynchronizer = async function() {
let NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV || NODE_ENV == 'development')
return null;
return await Self.findOne({ return await Self.findOne({
fields: ['id', 'rolePrefix', 'userPrefix', 'userHost'] fields: ['id', 'rolePrefix', 'userPrefix', 'userHost']
}); });

View File

@ -57,7 +57,7 @@ describe('Claim createFromSales()', () => {
const todayMinusEightDays = new Date(); const todayMinusEightDays = new Date();
todayMinusEightDays.setDate(todayMinusEightDays.getDate() - 8); todayMinusEightDays.setDate(todayMinusEightDays.getDate() - 8);
const ticket = await models.Ticket.findById(ticketId, options); const ticket = await models.Ticket.findById(ticketId, null, options);
await ticket.updateAttribute('landed', todayMinusEightDays, options); await ticket.updateAttribute('landed', todayMinusEightDays, options);
const claim = await models.Claim.createFromSales(ctx, ticketId, newSale, options); const claim = await models.Claim.createFromSales(ctx, ticketId, newSale, options);
@ -88,7 +88,7 @@ describe('Claim createFromSales()', () => {
const todayMinusEightDays = new Date(); const todayMinusEightDays = new Date();
todayMinusEightDays.setDate(todayMinusEightDays.getDate() - 8); todayMinusEightDays.setDate(todayMinusEightDays.getDate() - 8);
const ticket = await models.Ticket.findById(ticketId, options); const ticket = await models.Ticket.findById(ticketId, null, options);
await ticket.updateAttribute('landed', todayMinusEightDays, options); await ticket.updateAttribute('landed', todayMinusEightDays, options);
await models.Claim.createFromSales(ctx, ticketId, newSale, options); await models.Claim.createFromSales(ctx, ticketId, newSale, options);

View File

@ -1,7 +1,8 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
const soap = require('soap'); const soap = require('soap');
describe('client sendSms()', () => { // #3673 sendSms tests excluded
xdescribe('client sendSms()', () => {
it('should now send a message and log it', async() => { it('should now send a message and log it', async() => {
spyOn(soap, 'createClientAsync').and.returnValue('a so fake client'); spyOn(soap, 'createClientAsync').and.returnValue('a so fake client');
const tx = await models.Client.beginTransaction({}); const tx = await models.Client.beginTransaction({});

View File

@ -35,7 +35,7 @@ describe('Client updateFiscalData', () => {
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
const client = await models.Client.findById(clientId, options); const client = await models.Client.findById(clientId, null, options);
await client.updateAttribute('isTaxDataChecked', false, options); await client.updateAttribute('isTaxDataChecked', false, options);
const ctx = {req: {accessToken: {userId: salesAssistantId}}}; const ctx = {req: {accessToken: {userId: salesAssistantId}}};

View File

@ -56,18 +56,18 @@ module.exports = Self => {
FROM ( FROM (
SELECT SELECT
DISTINCT c.id clientFk, DISTINCT c.id clientFk,
c.name clientName, c.socialName clientName,
c.salesPersonFk, c.salesPersonFk,
u.name salesPersonName, u.nickname salesPersonName,
d.amount, d.amount,
co.created, co.created,
CONCAT(DATE(co.created), ' ', co.text) observation, co.text observation,
uw.id workerFk, uw.id workerFk,
uw.name workerName, uw.nickname workerName,
c.creditInsurance, c.creditInsurance,
d.defaulterSinced d.defaulterSinced
FROM vn.defaulter d FROM vn.defaulter d
JOIN vn.client c ON c.id = d.clientFk JOIN vn.client c ON c.id = d.clientFk
LEFT JOIN vn.clientObservation co ON co.clientFk = c.id LEFT JOIN vn.clientObservation co ON co.clientFk = c.id
LEFT JOIN account.user u ON u.id = c.salesPersonFk LEFT JOIN account.user u ON u.id = c.salesPersonFk
LEFT JOIN account.user uw ON uw.id = co.workerFk LEFT JOIN account.user uw ON uw.id = co.workerFk

View File

@ -47,12 +47,12 @@ describe('defaulter filter()', () => {
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 'bruce'}}; const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 'spider'}};
const result = await models.Defaulter.filter(ctx, null, options); const result = await models.Defaulter.filter(ctx, null, options);
const firstRow = result[0]; const firstRow = result[0];
expect(firstRow.clientName).toEqual('Bruce Wayne'); expect(firstRow.clientName).toEqual('Spider man');
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {

View File

@ -1,6 +1,7 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
describe('sms send()', () => { // #3673 sendSms tests excluded
xdescribe('sms send()', () => {
it('should not return status error', async() => { it('should not return status error', async() => {
const ctx = {req: {accessToken: {userId: 1}}}; const ctx = {req: {accessToken: {userId: 1}}};
const result = await app.models.Sms.send(ctx, 1105, '123456789', 'My SMS Body'); const result = await app.models.Sms.send(ctx, 1105, '123456789', 'My SMS Body');

View File

@ -15,17 +15,18 @@
model="model"> model="model">
</vn-searchbar> </vn-searchbar>
</vn-portal> </vn-portal>
<vn-data-viewer <vn-card>
model="model" <smart-table
class="vn-w-xl"> model="model"
<vn-card> options="$ctrl.smartTableOptions"
<vn-tool-bar> expr-builder="$ctrl.exprBuilder(param, value)">
<div class="vn-pa-md"> <slot-actions>
<div>
<div class="totalBox" style="text-align: center;"> <div class="totalBox" style="text-align: center;">
<h6 translate>Total</h6> <h6 translate>Total</h6>
<vn-label-value <vn-label-value
label="Balance due" label="Balance due"
value="{{$ctrl.balanceDueTotal}}"> value="{{$ctrl.balanceDueTotal | currency: 'EUR': 2}}">
</vn-label-value> </vn-label-value>
</div> </div>
</div> </div>
@ -38,90 +39,109 @@
icon="icon-notes"> icon="icon-notes">
</vn-button> </vn-button>
</div> </div>
</vn-tool-bar> </slot-actions>
<vn-table model="model"> <slot-table>
<vn-thead> <table>
<vn-tr> <thead>
<vn-th shrink> <tr>
<vn-multi-check <th shrink>
model="model"> <vn-multi-check
</vn-multi-check> model="model">
</vn-th> </vn-multi-check>
<vn-th field="clientName">Client</vn-th> </th>
<vn-th field="salesPersonFk">Comercial</vn-th> <th field="clientName">
<vn-th <span translate>Client</span>
field="amount" </th>
vn-tooltip="Balance due" <th field="salesPersonFk">
number> <span translate>Comercial</span>
Balance D. </th>
</vn-th> <th
<vn-th field="amount"
vn-tooltip="Worker who made the last observation" vn-tooltip="Balance due">
shrink> <span translate>Balance D.</span>
Author </th>
</vn-th> <th
<vn-th expand>Last observation</vn-th> field="workerFk"
<vn-th vn-tooltip="Worker who made the last observation">
vn-tooltip="Credit insurance" <span translate>Author</span>
number> </th>
Credit I. <th field="observation" expand>
</vn-th> <span translate>Last observation</span>
<vn-th shrink-datetime>From</vn-th> </th>
</vn-tr> <th
</vn-thead> vn-tooltip="Last observation date"
<vn-tbody> field="created"
<vn-tr ng-repeat="defaulter in defaulters"> shrink-datetime>
<vn-td shrink> <span translate>Last observation D.</span>
<vn-check </th>
ng-model="defaulter.checked" <th
vn-click-stop> vn-tooltip="Credit insurance"
</vn-check> field="creditInsurance" >
</vn-td> <span translate>Credit I.</span>
<vn-td> </th>
<span <th field="defaulterSinced">
vn-click-stop="clientDescriptor.show($event, defaulter.clientFk)" <span translate>From</span>
title ="{{::defaulter.clientName}}" </th>
class="link"> </tr>
{{::defaulter.clientName}} </thead>
</span> <tbody>
</vn-td> <tr ng-repeat="defaulter in defaulters">
<vn-td> <td shrink>
<span <vn-check
title="{{::defaulter.salesPersonName}}" ng-model="defaulter.checked"
vn-click-stop="workerDescriptor.show($event, defaulter.salesPersonFk)" vn-click-stop>
class="link" > </vn-check>
{{::defaulter.salesPersonName | dashIfEmpty}} </td>
</span> <td title="{{::defaulter.clientName}}">
</vn-td> <span
<vn-td number>{{::defaulter.amount}}</vn-td> vn-click-stop="clientDescriptor.show($event, defaulter.clientFk)"
<vn-td shrink> title ="{{::defaulter.clientName}}"
<span class="link">
title="{{::defaulter.workerName}}" {{::defaulter.clientName}}
vn-click-stop="workerDescriptor.show($event, defaulter.workerFk)" </span>
class="link" > </td>
{{::defaulter.workerName | dashIfEmpty}} <td>
</span> <span
</vn-td> title="{{::defaulter.salesPersonName}}"
<vn-td expand> vn-click-stop="workerDescriptor.show($event, defaulter.salesPersonFk)"
<vn-textarea class="link">
vn-three {{::defaulter.salesPersonName | dashIfEmpty}}
disabled="true" </span>
label="Observation" </td>
ng-model="defaulter.observation"> <td>{{::defaulter.amount | currency: 'EUR': 2}}</td>
</vn-textarea> <td>
</vn-td> <span
<vn-td number>{{::defaulter.creditInsurance}}</vn-td> title="{{::defaulter.workerName}}"
<vn-td shrink-datetime>{{::defaulter.defaulterSinced | date: 'dd/MM/yyyy'}}</vn-td> vn-click-stop="workerDescriptor.show($event, defaulter.workerFk)"
</vn-tr> class="link">
</vn-tbody> {{::defaulter.workerName | dashIfEmpty}}
</vn-table> </span>
</vn-card> </td>
</vn-data-viewer> <td expand>
<vn-textarea
vn-three
disabled="true"
ng-model="defaulter.observation">
</vn-textarea>
</td>
<td shrink-datetime>
<span class="chip {{::$ctrl.chipColor(defaulter.created)}}">
{{::defaulter.created | date: 'dd/MM/yyyy'}}
</span>
</td>
<td>{{::defaulter.creditInsurance | currency: 'EUR': 2}}</td>
<td>{{::defaulter.defaulterSinced | date: 'dd/MM/yyyy'}}</td>
</tr>
</tbody>
</table>
</slot-table>
</smart-table>
</vn-card>
<vn-client-descriptor-popover <vn-client-descriptor-popover
vn-id="clientDescriptor"> vn-id="client-descriptor">
</vn-client-descriptor-popover> </vn-client-descriptor-popover>
<vn-worker-descriptor-popover <vn-worker-descriptor-popover
vn-id="workerDescriptor"> vn-id="worker-descriptor">
</vn-worker-descriptor-popover> </vn-worker-descriptor-popover>
<vn-popup vn-id="dialog-summary-client"> <vn-popup vn-id="dialog-summary-client">
<vn-client-summary <vn-client-summary
@ -129,37 +149,6 @@
</vn-client-summary> </vn-client-summary>
</vn-popup> </vn-popup>
<!--Context menu-->
<vn-contextmenu vn-id="contextmenu" targets="['vn-data-viewer']" model="model"
expr-builder="$ctrl.exprBuilder(param, value)">
<slot-menu>
<vn-item translate
ng-if="contextmenu.isFilterAllowed()"
ng-click="contextmenu.filterBySelection()">
Filter by selection
</vn-item>
<vn-item translate
ng-if="contextmenu.isFilterAllowed()"
ng-click="contextmenu.excludeSelection()">
Exclude selection
</vn-item>
<vn-item translate
ng-if="contextmenu.isFilterAllowed()"
ng-click="contextmenu.removeFilter()">
Remove filter
</vn-item>
<vn-item translate
ng-click="contextmenu.removeAllFilters()">
Remove all filters
</vn-item>
<vn-item translate
ng-if="contextmenu.isActionAllowed()"
ng-click="contextmenu.copyValue()">
Copy value
</vn-item>
</slot-menu>
</vn-contextmenu>
<!-- Dialog of add notes button --> <!-- Dialog of add notes button -->
<vn-dialog <vn-dialog
vn-id="notesDialog" vn-id="notesDialog"

View File

@ -6,17 +6,61 @@ export default class Controller extends Section {
constructor($element, $) { constructor($element, $) {
super($element, $); super($element, $);
this.defaulter = {}; this.defaulter = {};
this.smartTableOptions = {
activeButtons: {
search: true
},
columns: [
{
field: 'clientName',
autocomplete: {
url: 'Clients',
showField: 'socialName',
valueField: 'socialName'
}
},
{
field: 'salesPersonFk',
autocomplete: {
url: 'Workers/activeWithInheritedRole',
where: `{role: 'salesPerson'}`,
searchFunction: '{firstName: $search}',
showField: 'nickname',
valueField: 'id',
}
},
{
field: 'workerFk',
autocomplete: {
url: 'Workers/activeWithInheritedRole',
searchFunction: '{firstName: $search}',
showField: 'nickname',
valueField: 'id',
}
},
{
field: 'observation',
searchable: false
},
{
field: 'created',
searchable: false
},
{
field: 'defaulterSinced',
searchable: false
}
]
};
} }
get balanceDueTotal() { get balanceDueTotal() {
let balanceDueTotal = 0; let balanceDueTotal = 0;
const defaulters = this.$.model.data || [];
if (this.checked.length > 0) { for (let defaulter of defaulters)
for (let defaulter of this.checked) balanceDueTotal += defaulter.amount;
balanceDueTotal += defaulter.amount;
return balanceDueTotal;
}
return balanceDueTotal; return balanceDueTotal;
} }
@ -32,6 +76,22 @@ export default class Controller extends Section {
return checkedLines; return checkedLines;
} }
chipColor(date) {
const day = 24 * 60 * 60 * 1000;
const today = new Date();
today.setHours(0, 0, 0, 0);
const observationShipped = new Date(date);
observationShipped.setHours(0, 0, 0, 0);
const difference = today - observationShipped;
if (difference > (day * 20))
return 'alert';
if (difference > (day * 10))
return 'warning';
}
onResponse() { onResponse() {
if (!this.defaulter.observation) if (!this.defaulter.observation)
throw new UserError(`The message can't be empty`); throw new UserError(`The message can't be empty`);
@ -52,7 +112,10 @@ export default class Controller extends Section {
exprBuilder(param, value) { exprBuilder(param, value) {
switch (param) { switch (param) {
case 'creditInsurance':
case 'amount':
case 'clientName': case 'clientName':
case 'workerFk':
case 'salesPersonFk': case 'salesPersonFk':
return {[`d.${param}`]: value}; return {[`d.${param}`]: value};
} }

View File

@ -39,11 +39,7 @@ describe('client defaulter', () => {
describe('balanceDueTotal() getter', () => { describe('balanceDueTotal() getter', () => {
it('should return balance due total', () => { it('should return balance due total', () => {
const data = controller.$.model.data; const data = controller.$.model.data;
data[1].checked = true; const expectedAmount = data[0].amount + data[1].amount + data[2].amount;
data[2].checked = true;
const checkedRows = controller.checked;
const expectedAmount = checkedRows[0].amount + checkedRows[1].amount;
const result = controller.balanceDueTotal; const result = controller.balanceDueTotal;
@ -51,6 +47,31 @@ describe('client defaulter', () => {
}); });
}); });
describe('chipColor()', () => {
it('should return undefined when the date is the present', () => {
let today = new Date();
let result = controller.chipColor(today);
expect(result).toEqual(undefined);
});
it('should return warning when the date is 10 days in the past', () => {
let pastDate = new Date();
pastDate = pastDate.setDate(pastDate.getDate() - 11);
let result = controller.chipColor(pastDate);
expect(result).toEqual('warning');
});
it('should return alert when the date is 20 days in the past', () => {
let pastDate = new Date();
pastDate = pastDate.setDate(pastDate.getDate() - 21);
let result = controller.chipColor(pastDate);
expect(result).toEqual('alert');
});
});
describe('onResponse()', () => { describe('onResponse()', () => {
it('should return error for empty message', () => { it('should return error for empty message', () => {
let error; let error;

View File

@ -1,7 +1,9 @@
Last observation: Última observación
Add observation: Añadir observación Add observation: Añadir observación
Search client: Buscar clientes
Add observation to all selected clients: Añadir observación a {{total}} cliente(s) seleccionado(s) Add observation to all selected clients: Añadir observación a {{total}} cliente(s) seleccionado(s)
Credit I.: Crédito A.
Balance D.: Saldo V. Balance D.: Saldo V.
Credit I.: Crédito A.
Last observation: Última observación
Last observation D.: Fecha última O.
Last observation date: Fecha última observación
Search client: Buscar clientes
Worker who made the last observation: Trabajador que ha realizado la última observación Worker who made the last observation: Trabajador que ha realizado la última observación

View File

@ -10,7 +10,6 @@
name="showInvoicePdf" name="showInvoicePdf"
translate> translate>
Show invoice... Show invoice...
<vn-menu vn-id="showInvoiceMenu"> <vn-menu vn-id="showInvoiceMenu">
<vn-list> <vn-list>
<a class="vn-item" <a class="vn-item"
@ -33,7 +32,6 @@
name="sendInvoice" name="sendInvoice"
translate> translate>
Send invoice... Send invoice...
<vn-menu vn-id="sendInvoiceMenu"> <vn-menu vn-id="sendInvoiceMenu">
<vn-list> <vn-list>
<vn-item <vn-item

View File

@ -3,13 +3,21 @@
url="Items/getWasteByWorker" url="Items/getWasteByWorker"
data="details"> data="details">
</vn-crud-model> </vn-crud-model>
<vn-data-viewer model="model"> <vn-data-viewer model="model">
<vn-card> <section ng-repeat="detail in details" class="vn-pa-md">
<section ng-repeat="detail in details" class="vn-pa-md"> <vn-horizontal class="header">
<vn-horizontal class="header"> <h5><span translate>{{detail.buyer}}</span></h5>
<h5><span><span translate>{{detail.buyer}}</span></h5> <vn-none>
</vn-horizontal> <vn-icon
ng-class="{'hidden': !$ctrl.wasteConfig[detail.buyer].hidden}"
class="arrow pointer"
icon="keyboard_arrow_up"
vn-tooltip="Minimize/Maximize"
ng-click="$ctrl.toggleHidePanel(detail)">
</vn-icon>
</vn-none>
</vn-horizontal>
<vn-card ng-class="{'hidden': !$ctrl.wasteConfig[detail.buyer].hidden}">
<vn-table> <vn-table>
<vn-thead> <vn-thead>
<vn-tr> <vn-tr>
@ -21,7 +29,7 @@
</vn-thead> </vn-thead>
<vn-tbody> <vn-tbody>
<a ng-repeat="waste in detail.lines" class="clickable vn-tr" <a ng-repeat="waste in detail.lines" class="clickable vn-tr"
ui-sref="item.waste.detail({buyer: waste.buyer, family: waste.family})" > ui-sref="item.waste.detail({buyer: waste.buyer, family: waste.family})">
<vn-td class="waste-family">{{::waste.family}}</vn-td> <vn-td class="waste-family">{{::waste.family}}</vn-td>
<vn-td number>{{::(waste.percentage / 100) | percentage: 2}}</vn-td> <vn-td number>{{::(waste.percentage / 100) | percentage: 2}}</vn-td>
<vn-td number>{{::waste.dwindle | currency: 'EUR'}}</vn-td> <vn-td number>{{::waste.dwindle | currency: 'EUR'}}</vn-td>
@ -29,6 +37,6 @@
</vn-tr> </vn-tr>
</vn-tbody> </vn-tbody>
</vn-table> </vn-table>
</section> </vn-card>
</vn-card> </section>
</vn-data-viewer> </vn-data-viewer>

View File

@ -2,7 +2,34 @@ import ngModule from '../../module';
import Section from 'salix/components/section'; import Section from 'salix/components/section';
import './style.scss'; import './style.scss';
export default class Controller extends Section {
constructor($element, $) {
super($element, $);
this.getWasteConfig();
}
getWasteConfig() {
return this.wasteConfig = JSON.parse(localStorage.getItem('wasteConfig')) || {};
}
setWasteConfig() {
localStorage.setItem('wasteConfig', JSON.stringify(this.wasteConfig));
}
toggleHidePanel(detail) {
if (!this.wasteConfig[detail.buyer]) {
this.wasteConfig[detail.buyer] = {
hidden: true
};
} else
this.wasteConfig[detail.buyer].hidden = !this.wasteConfig[detail.buyer].hidden;
this.setWasteConfig();
}
}
ngModule.vnComponent('vnItemWasteIndex', { ngModule.vnComponent('vnItemWasteIndex', {
template: require('./index.html'), template: require('./index.html'),
controller: Section controller: Controller
}); });

View File

@ -0,0 +1,53 @@
import './index.js';
import crudModel from 'core/mocks/crud-model';
describe('Item', () => {
describe('Component vnItemWasteIndex', () => {
let $scope;
let controller;
beforeEach(ngModule('item'));
beforeEach(inject(($componentController, $rootScope) => {
$scope = $rootScope.$new();
$scope.model = crudModel;
const $element = angular.element('<vn-item-waste-index></vn-item-waste-index>');
controller = $componentController('vnItemWasteIndex', {$element, $scope});
}));
describe('getWasteConfig / setWasteConfig', () => {
it('should return the local storage wasteConfig', () => {
const result = controller.getWasteConfig();
expect(result).toEqual({});
});
it('should set and return the local storage wasteConfig', () => {
controller.wasteConfig = {salesPerson: {hidden: true}};
controller.setWasteConfig();
const result = controller.getWasteConfig();
expect(result).toEqual(controller.wasteConfig);
});
});
describe('toggleHidePanel()', () => {
it('should make details hidden by default', () => {
controller.wasteConfig = {};
controller.toggleHidePanel({buyer: 'salesPerson'});
expect(controller.wasteConfig.salesPerson.hidden).toEqual(true);
});
it('should toggle hidden false', () => {
controller.wasteConfig = {salesPerson: {hidden: true}};
controller.toggleHidePanel({buyer: 'salesPerson'});
expect(controller.wasteConfig.salesPerson.hidden).toEqual(false);
});
});
});
});

View File

@ -1,21 +1,24 @@
@import "variables"; @import "variables";
@import "effects";
vn-item-waste-index, vn-item-waste-index,
vn-item-waste-detail { vn-item-waste-detail {
.header { .header {
margin-bottom: 16px; padding: 12px 0 5px 0;
text-transform: uppercase; color: gray;
font-size: 1.25rem; font-size: 1.2rem;
line-height: 1; border-bottom: $border;
padding: 7px; margin-bottom: 10px;
padding-bottom: 7px;
padding-bottom: 4px; & > vn-none > vn-icon {
font-weight: lighter; @extend %clickable-light;
background-color: $color-bg; color: $color-button;
border-bottom: 1px solid #f7931e; font-size: 1.4rem;
white-space: nowrap; }
overflow: hidden;
text-overflow: ellipsis; vn-none > .arrow {
transition: transform 200ms;
}
} }
vn-table vn-th.waste-family, vn-table vn-th.waste-family,
@ -23,4 +26,12 @@ vn-item-waste-detail {
max-width: 64px; max-width: 64px;
width: 64px width: 64px
} }
.hidden {
display: none;
}
.header > vn-none > .arrow.hidden {
display: block;
transform: rotate(180deg);
}
} }

View File

@ -1,3 +1,4 @@
Family: Familia Family: Familia
Percentage: Porcentaje Percentage: Porcentaje
Dwindle: Mermas Dwindle: Mermas
Minimize/Maximize: Minimizar/Maximizar

View File

@ -25,6 +25,7 @@ module.exports = Self => {
Object.assign(myOptions, options); Object.assign(myOptions, options);
const route = await Self.app.models.Route.findById(id, null, myOptions); const route = await Self.app.models.Route.findById(id, null, myOptions);
const zoneAgencyModes = await Self.app.models.ZoneAgencyMode.find({ const zoneAgencyModes = await Self.app.models.ZoneAgencyMode.find({
where: { where: {
agencyModeFk: route.agencyModeFk agencyModeFk: route.agencyModeFk
@ -52,6 +53,12 @@ module.exports = Self => {
fields: ['id', 'name'] fields: ['id', 'name']
} }
}, },
{
relation: 'zone',
scope: {
fields: ['id', 'name']
}
},
{ {
relation: 'address', relation: 'address',
scope: { scope: {

View File

@ -0,0 +1,33 @@
const models = require('vn-loopback/server/server').models;
describe('route unlink()', () => {
it('should show no tickets since the link between zone and route for the give agencymode was removed', async() => {
const tx = await models.ZoneAgencyMode.beginTransaction({});
const agencyModeId = 1;
const zoneId = 1;
routeId = 1;
try {
const options = {transaction: tx};
let zoneAgencyModes = await models.ZoneAgencyMode.find(null, options);
let tickets = await models.Route.getSuggestedTickets(routeId, options);
expect(zoneAgencyModes.length).toEqual(4);
expect(tickets.length).toEqual(3);
await models.Route.unlink(agencyModeId, zoneId, options);
zoneAgencyModes = await models.ZoneAgencyMode.find(null, options);
tickets = await models.Route.getSuggestedTickets(routeId, options);
expect(zoneAgencyModes.length).toEqual(3);
expect(tickets.length).toEqual(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -0,0 +1,42 @@
module.exports = Self => {
Self.remoteMethod('unlink', {
description: 'Removes the matching entries from zoneAgencyMode',
accessType: 'WRITE',
accepts: [
{
arg: 'agencyModeId',
type: 'number',
required: true,
description: 'The agencyMode id',
},
{
arg: 'zoneId',
type: 'number',
required: true,
description: 'The zone id',
},
],
returns: {
type: ['object'],
root: true
},
http: {
path: `/unlink`,
verb: 'POST'
}
});
Self.unlink = async(agencyModeId, zoneId, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const where = {
agencyModeFk: agencyModeId,
zoneFk: zoneId
};
await Self.app.models.ZoneAgencyMode.destroyAll(where, myOptions);
};
};

View File

@ -8,6 +8,7 @@ module.exports = Self => {
require('../methods/route/insertTicket')(Self); require('../methods/route/insertTicket')(Self);
require('../methods/route/clone')(Self); require('../methods/route/clone')(Self);
require('../methods/route/getSuggestedTickets')(Self); require('../methods/route/getSuggestedTickets')(Self);
require('../methods/route/unlink')(Self);
Self.validate('kmStart', validateDistance, { Self.validate('kmStart', validateDistance, {
message: 'Distance must be lesser than 1000' message: 'Distance must be lesser than 1000'

View File

@ -150,7 +150,7 @@
</vn-th> </vn-th>
<vn-th expand>PC</vn-th> <vn-th expand>PC</vn-th>
<vn-th>Address</vn-th> <vn-th>Address</vn-th>
<vn-th shrink>Warehouse</vn-th> <vn-th shrink>Zone</vn-th>
</vn-tr> </vn-tr>
</vn-thead> </vn-thead>
<vn-tbody> <vn-tbody>
@ -174,7 +174,15 @@
<vn-td shrink>{{::ticket.address.city}}</vn-td> <vn-td shrink>{{::ticket.address.city}}</vn-td>
<vn-td number shrink>{{::ticket.address.postalCode}}</vn-td> <vn-td number shrink>{{::ticket.address.postalCode}}</vn-td>
<vn-td expand title="{{::ticket.address.street}}">{{::ticket.address.street}}</vn-td> <vn-td expand title="{{::ticket.address.street}}">{{::ticket.address.street}}</vn-td>
<vn-td expand>{{::ticket.warehouse.name}}</vn-td> <vn-td expand>
{{::ticket.zone.name}}
<vn-icon-button
icon="link_off"
class="pointer"
translate-attr="{title: 'Unlink zone: {{::ticket.zone.name}} from agency: {{::ticket.agencyMode.name}}'}"
ng-click="unlinkZoneConfirmation.show(ticket)">
</vn-icon-button>
</vn-td>
</vn-tr> </vn-tr>
</vn-tbody> </vn-tbody>
</vn-table> </vn-table>
@ -196,3 +204,11 @@
<vn-client-descriptor-popover <vn-client-descriptor-popover
vn-id="client-descriptor"> vn-id="client-descriptor">
</vn-client-descriptor-popover> </vn-client-descriptor-popover>
<!-- Unlink zone confirmation dialog -->
<vn-confirm
vn-id="unlinkZoneConfirmation"
on-accept="$ctrl.unlinkZone($data)"
question="{{$ctrl.confirmationMessage}}"
message="Unlink selected zone?">
</vn-confirm>

View File

@ -37,6 +37,19 @@ class Controller extends Section {
}); });
} }
unlinkZone(ticket) {
const params = {
agencyModeId: this.route.agencyModeFk,
zoneId: ticket.zoneFk,
};
const query = `Routes/unlink`;
this.$http.post(query, params).then(() => {
this.vnApp.showSuccess(this.$t('Data saved!'));
this.$.possibleTicketsModel.refresh();
});
}
getSelectedItems(items) { getSelectedItems(items) {
const selectedItems = []; const selectedItems = [];

View File

@ -1,3 +1,4 @@
/* eslint max-len: ["error", { "code": 150 }]*/
import './index'; import './index';
describe('Route', () => { describe('Route', () => {
@ -73,6 +74,32 @@ describe('Route', () => {
}); });
}); });
describe('unlink()', () => {
it('should call the route unlink endpoint with the agency and zone ids', () => {
controller.$.possibleTicketsModel = {refresh: jest.fn()};
jest.spyOn(controller.vnApp, 'showSuccess');
controller.route = {
agencyModeFk: 1
};
const ticket = {
zoneFk: 2,
};
const params = {
agencyModeId: controller.route.agencyModeFk,
zoneId: ticket.zoneFk,
};
$httpBackend.expectPOST(`Routes/unlink`, params).respond('ok');
controller.unlinkZone(ticket);
$httpBackend.flush();
expect(controller.vnApp.showSuccess).toHaveBeenCalled();
expect(controller.$.possibleTicketsModel.refresh).toHaveBeenCalledWith();
});
});
describe('getSelectedItems()', () => { describe('getSelectedItems()', () => {
it('should return the selected items', () => { it('should return the selected items', () => {
let items = [ let items = [

View File

@ -11,4 +11,5 @@ The selected ticket is not suitable for this route: El ticket seleccionado no es
PC: CP PC: CP
The route's vehicle doesn't have a delivery point: El vehículo de la ruta no tiene un punto de entrega The route's vehicle doesn't have a delivery point: El vehículo de la ruta no tiene un punto de entrega
The route doesn't have a vehicle: La ruta no tiene un vehículo The route doesn't have a vehicle: La ruta no tiene un vehículo
Population: Población Population: Población
Unlink selected zone?: Desvincular zona seleccionada?

View File

@ -86,8 +86,8 @@ describe('sale priceDifference()', () => {
const firstItem = result.items[0]; const firstItem = result.items[0];
const secondtItem = result.items[1]; const secondtItem = result.items[1];
expect(firstItem.movable).toEqual(440); expect(firstItem.movable).toEqual(410);
expect(secondtItem.movable).toEqual(1980); expect(secondtItem.movable).toEqual(1870);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {

View File

@ -1,7 +1,8 @@
const models = require('vn-loopback/server/server').models; const models = require('vn-loopback/server/server').models;
const soap = require('soap'); const soap = require('soap');
describe('ticket sendSms()', () => { // #3673 sendSms tests excluded
xdescribe('ticket sendSms()', () => {
it('should send a message and log it', async() => { it('should send a message and log it', async() => {
const tx = await models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});

View File

@ -18,7 +18,14 @@
</vn-thead> </vn-thead>
<vn-tbody> <vn-tbody>
<vn-tr ng-repeat="sale in $ctrl.ticket.sale.items track by sale.id"> <vn-tr ng-repeat="sale in $ctrl.ticket.sale.items track by sale.id">
<vn-td number>{{("000000"+sale.itemFk).slice(-6)}}</vn-td> <vn-td number>
<span
title="{{::sale.item.name}}"
vn-click-stop="itemDescriptor.show($event, sale.itemFk, sale.id)"
class="link">
{{::sale.itemFk | zeroFill:6}}
</span>
</vn-td>
<vn-td vn-fetched-tags> <vn-td vn-fetched-tags>
<div> <div>
<vn-one title="{{::sale.item.name}}">{{::sale.item.name}}</vn-one> <vn-one title="{{::sale.item.name}}">{{::sale.item.name}}</vn-one>
@ -83,5 +90,9 @@
</div> </div>
</div> </div>
</vn-side-menu> </vn-side-menu>
<vn-item-descriptor-popover
vn-id="item-descriptor"
warehouse-fk="$ctrl.ticket.warehouseFk"
ticket-fk="$ctrl.ticket.id">
</vn-item-descriptor-popover>

View File

@ -20,14 +20,22 @@
<vn-menu vn-id="showDeliveryNoteMenu"> <vn-menu vn-id="showDeliveryNoteMenu">
<vn-list> <vn-list>
<vn-item <vn-item
ng-if="!$ctrl.hasDocuwareFile"
ng-click="$ctrl.showPdfDeliveryNote()" ng-click="$ctrl.showPdfDeliveryNote()"
translate> translate>
Show as PDF as PDF
</vn-item> </vn-item>
<a class="vn-item"
ng-if="$ctrl.hasDocuwareFile"
href='api/Docuwares/{{$ctrl.ticket.id}}/download/deliveryClient/findTicket?access_token={{$ctrl.vnToken.token}}'
target="_blank"
translate>
as PDF
</a>
<vn-item <vn-item
ng-click="$ctrl.showCsvDeliveryNote()" ng-click="$ctrl.showCsvDeliveryNote()"
translate> translate>
Show as CSV as CSV
</vn-item> </vn-item>
</vn-list> </vn-list>
</vn-menu> </vn-menu>

View File

@ -84,6 +84,7 @@ class Controller extends Section {
.then(() => { .then(() => {
this.canStowaway(); this.canStowaway();
this.isTicketEditable(); this.isTicketEditable();
this.hasDocuware();
}); });
} }
@ -122,6 +123,15 @@ class Controller extends Section {
}); });
} }
hasDocuware() {
const params = {
fileCabinet: 'deliveryClient',
dialog: 'findTicket'
};
this.$http.post(`Docuwares/${this.id}/checkFile`, params)
.then(res => this.hasDocuwareFile = res.data);
}
showCsvDeliveryNote() { showCsvDeliveryNote() {
this.vnReport.showCsv('delivery-note', { this.vnReport.showCsv('delivery-note', {
recipientId: this.ticket.client.id, recipientId: this.ticket.client.id,

View File

@ -206,7 +206,8 @@ describe('Ticket Component vnTicketDescriptorMenu', () => {
it('should make a query and show a success snackbar', () => { it('should make a query and show a success snackbar', () => {
jest.spyOn(controller.vnApp, 'showSuccess'); jest.spyOn(controller.vnApp, 'showSuccess');
$httpBackend.whenGET(`Tickets/16`).respond(); $httpBackend.whenPOST(`Docuwares/${ticket.id}/checkFile`).respond();
$httpBackend.whenGET(`Tickets/${ticket.id}`).respond();
$httpBackend.expectPOST(`InvoiceOuts/${ticket.invoiceOut.id}/createPdf`).respond(); $httpBackend.expectPOST(`InvoiceOuts/${ticket.invoiceOut.id}/createPdf`).respond();
controller.createPdfInvoice(); controller.createPdfInvoice();
$httpBackend.flush(); $httpBackend.flush();
@ -275,4 +276,12 @@ describe('Ticket Component vnTicketDescriptorMenu', () => {
}); });
}); });
}); });
describe('hasDocuware()', () => {
it('should call hasDocuware method', () => {
$httpBackend.whenPOST(`Docuwares/${ticket.id}/checkFile`).respond();
controller.hasDocuware();
$httpBackend.flush();
});
});
}); });

View File

@ -1,7 +1,7 @@
Show Delivery Note...: Ver albarán... Show Delivery Note...: Ver albarán...
Send Delivery Note...: Enviar albarán... Send Delivery Note...: Enviar albarán...
Show as PDF: Ver como PDF as PDF: como PDF
Show as CSV: Ver como CSV as CSV: como CSV
Send PDF: Enviar PDF Send PDF: Enviar PDF
Send CSV: Enviar CSV Send CSV: Enviar CSV
Send CSV Delivery Note: Enviar albarán en CSV Send CSV Delivery Note: Enviar albarán en CSV

View File

@ -9,11 +9,11 @@
"properties": { "properties": {
"id": { "id": {
"id": true, "id": true,
"type": "Number", "type": "number",
"forceId": false "forceId": false
}, },
"name": { "name": {
"type": "String", "type": "string",
"required": false "required": false
} }
} }

View File

@ -13,10 +13,10 @@
"properties": { "properties": {
"id": { "id": {
"id": true, "id": true,
"type": "Number" "type": "number"
}, },
"name": { "name": {
"type": "String", "type": "string",
"required": true "required": true
}, },
"hour": { "hour": {
@ -24,22 +24,22 @@
"required": true "required": true
}, },
"travelingDays": { "travelingDays": {
"type": "Number" "type": "number"
}, },
"price": { "price": {
"type": "Number" "type": "number"
}, },
"bonus": { "bonus": {
"type": "Number" "type": "number"
}, },
"isVolumetric": { "isVolumetric": {
"type": "Boolean" "type": "boolean"
}, },
"inflation": { "inflation": {
"type": "Number" "type": "number"
}, },
"itemMaxSize": { "itemMaxSize": {
"type": "Number" "type": "number"
} }
}, },
"relations": { "relations": {

View File

@ -2,9 +2,13 @@ SELECT
ir.id AS code, ir.id AS code,
ir.description AS description, ir.description AS description,
CAST(SUM(IFNULL(i.stems,1) * s.quantity) AS DECIMAL(10,2)) as stems, CAST(SUM(IFNULL(i.stems,1) * s.quantity) AS DECIMAL(10,2)) as stems,
CAST(SUM( weight) AS DECIMAL(10,2)) as netKg, CAST(SUM(IF(sv.physicalWeight, sv.physicalWeight, i.density * sub.cm3delivery/1000000)) AS DECIMAL(10,2)) netKg,
CAST(SUM((s.quantity * s.price * (100 - s.discount) / 100 )) AS DECIMAL(10,2)) AS subtotal CAST(SUM((s.quantity * s.price * (100 - s.discount) / 100 )) AS DECIMAL(10,2)) AS subtotal
FROM vn.sale s FROM vn.sale s
LEFT JOIN (SELECT ic.itemFk, ic.cm3, ic.cm3delivery
FROM vn.itemCost ic
WHERE ic.cm3
GROUP BY ic.itemFk) sub ON s.itemFk = sub.itemFk
LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id
LEFT JOIN vn.ticket t ON t.id = s.ticketFk LEFT JOIN vn.ticket t ON t.id = s.ticketFk
LEFT JOIN vn.invoiceOut io ON io.ref = t.refFk LEFT JOIN vn.invoiceOut io ON io.ref = t.refFk