2378-imap #385

Merged
joan merged 8 commits from 2378-imap into dev 2020-09-23 12:46:34 +00:00
6 changed files with 145 additions and 57 deletions
Showing only changes of commit 06f03c6b84 - Show all commits

View File

@ -1,5 +1,5 @@
const Imap = require('imap'); const Imap = require('imap');
const {NULL} = require('node-sass');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('checkInbox', { Self.remoteMethod('checkInbox', {
description: 'Check an email inbox and process it', description: 'Check an email inbox and process it',
@ -26,7 +26,8 @@ module.exports = Self => {
tls: true tls: true
}); });
let isEmailOk; let isEmailOk;
let emailText = ''; let uid;
let emailBody;
function openInbox(cb) { function openInbox(cb) {
imap.openBox('INBOX', true, cb); imap.openBox('INBOX', true, cb);
@ -35,7 +36,7 @@ module.exports = Self => {
imap.once('ready', function() { imap.once('ready', function() {
openInbox(function(err, box) { openInbox(function(err, box) {
if (err) throw err; if (err) throw err;
let f = imap.seq.fetch('1:3', { let f = imap.seq.fetch('1:*', {
bodies: ['HEADER.FIELDS (FROM SUBJECT)', '1'], bodies: ['HEADER.FIELDS (FROM SUBJECT)', '1'],
struct: true struct: true
}); });
@ -43,87 +44,143 @@ module.exports = Self => {
isEmailOk = false; isEmailOk = false;
msg.on('body', function(stream, info) { msg.on('body', function(stream, info) {
let buffer = ''; let buffer = '';
let bufferCopy = '';
stream.on('data', function(chunk) { stream.on('data', function(chunk) {
// console.log('chunk', chunk);
buffer = chunk.toString('utf8'); buffer = chunk.toString('utf8');
if (info.which === '1') { // console.log('buffer', buffer);
emailText = buffer.split('\n')[0]; if (info.which === '1' && bufferCopy.length == 0)
emailText = emailText.toUpperCase(); bufferCopy = buffer.replace(/\s/g, ' ');
emailText = emailText.replace(/\s/g, ''); });
if (emailText === 'OK') stream.on('end', function() {
isEmailOk = true; // isEmailOk if (bufferCopy.length > 0) {
emailBody = bufferCopy.toUpperCase().trim();
const bodyPositionOK = emailBody.match(/\bOK\b/i);
if (bodyPositionOK != null && (bodyPositionOK.index == 0 || bodyPositionOK.index == 122))
isEmailOk = true;
else
isEmailOk = false;
} }
}); });
stream.once('end', function() { msg.once('attributes', function(attrs) {
uid = attrs.uid;
// let structure = attrs.struct[2][0];
// console.log('attrs.struct', structure);
// console.log('attrs', structure.params);
// console.log('attrs.struct', structure.find(item => item.subtype === 'html'));
});
msg.once('end', function() {
if (info.which === 'HEADER.FIELDS (FROM SUBJECT)') { if (info.which === 'HEADER.FIELDS (FROM SUBJECT)') {
console.log('isEmailOk', isEmailOk);
if (isEmailOk) { if (isEmailOk) {
imap.move(uid, 'exito', function(err) {
});
emailConfirm(buffer); emailConfirm(buffer);
imap.seq.move(seqno, 'exito', function(err) {
console.log('Move correcte: ' + err);
console.log('Move error: ' + seqno);
});
} else { } else {
emailReply(buffer); imap.move(uid, 'error', function(err) {
imap.seq.move(seqno, 'error', function(err) {
console.log('Move error: ' + err);
console.log('Move error: ' + seqno);
}); });
emailReply(buffer, emailBody);
} }
} }
}); });
}); });
}); });
// msg.on('attributes', function(attrs) { f.once('end', function() {
// console.log('ATRIBUTO', attrs.struct[0]); imap.end();
// console.log('ATRIBUTO', attrs.struct[0].params); });
// });
}); });
}); });
imap.connect(); imap.connect();
return 'pepinillos'; return 'Leer emails de gestion horaria';
}; };
async function getUser(workerEmail) {
let firstPosition = workerEmail.search('<') + 1;
let lastPosition = workerEmail.search('@') - firstPosition;
let userName = workerEmail.substr(firstPosition, lastPosition);
let user = await Self.app.models.Account.findOne({where: {name: userName}});
return user;
}
async function getEmailDate(subject) {
let date = subject.match(/\d+/g);
return date;
}
async function emailConfirm(buffer) { async function emailConfirm(buffer) {
let now = new Date(); // try {
let from = JSON.stringify(Imap.parseHeader(buffer).from); const now = new Date();
let subject = JSON.stringify(Imap.parseHeader(buffer).subject); const from = JSON.stringify(Imap.parseHeader(buffer).from);
const subject = JSON.stringify(Imap.parseHeader(buffer).subject);
let timeControlDate = await getEmailDate(subject); const timeControlDate = await getEmailDate(subject);
let week = timeControlDate[0]; const week = timeControlDate[0];
let year = timeControlDate[1]; const year = timeControlDate[1];
let user = await getUser(from); const user = await getUser(from);
let workerMail = await Self.app.models.WorkerTimeControlMail.findOne({ let workerMail = await Self.app.models.WorkerTimeControlMail.findOne({
where: { where: {
week: week, week: week,
year: year, year: year,
worker: user.id workerFk: user.id
} }
}); });
await workerMail.updateAttributes({ if (workerMail != NULL) {
updated: now, await workerMail.updateAttributes({
state: 'CONFIRMED' updated: now,
}); state: 'CONFIRMED'
// MOVER A CARPETA EXITO });
}
// } catch (err) {
// throw err;
// }
} }
async function emailReply(subject, workerEmail) {
console.log('bbbbb');
// INSERT EN VN.MAIL async function emailReply(buffer, emailBody) {
// UPDATE EN WORKERTIMECONTROLMAIL // try {
// MOVER A CARPETA ERROR const now = new Date();
const from = JSON.stringify(Imap.parseHeader(buffer).from);
const subject = JSON.stringify(Imap.parseHeader(buffer).subject);
const timeControlDate = await getEmailDate(subject);
const week = timeControlDate[0];
const year = timeControlDate[1];
const user = await getUser(from);
let workerMail = await Self.app.models.WorkerTimeControlMail.findOne({
where: {
week: week,
year: year,
workerFk: user.id
}
});
if (workerMail != NULL) {
await workerMail.updateAttributes({
updated: now,
state: 'REVISE'
});
}
await sendMail(user, subject, emailBody);
// } catch (err) {
// throw err;
// }
}
async function getUser(workerEmail) {
const userEmail = workerEmail.match(/(?<=<)(.*?)(?=>)/);
let [user] = await Self.rawSql(`SELECT u.id,u.name FROM account.user u
LEFT JOIN account.mailForward m on m.account = u.id
WHERE forwardTo =? OR
CONCAT(u.name,'@verdnatura.es') = ?`,
[userEmail[0], userEmail[0]]);
return user;
}
async function getEmailDate(subject) {
const date = subject.match(/\d+/g);
return date;
}
async function sendMail(user, subject, emailBody) {
const sendTo = 'rrhh@verdnatura.es';
const emailSubject = subject + ' ' + user.name;
await Self.app.models.Mail.create({
sender: sendTo,
subject: emailSubject,
body: emailBody
});
} }
}; };

View File

@ -79,6 +79,9 @@
}, },
"Mail": { "Mail": {
"dataSource": "vn" "dataSource": "vn"
},
"MailForward": {
"dataSource": "vn"
} }
} }

View File

@ -0,0 +1,26 @@
{
"name": "MailForward",
"base": "VnModel",
"options": {
"mysql": {
"table": "account.mailForward"
}
},
"properties": {
"account": {
"id": true,
"type": "Number"
},
"forwardTo": {
"type": "String"
}
},
"acls": [
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
]
}

View File

@ -9,8 +9,7 @@
"properties": { "properties": {
"id": { "id": {
"id": true, "id": true,
"type": "Number", "type": "Number"
"required": true
}, },
"sender": { "sender": {
"type": "String" "type": "String"

View File

@ -1,7 +1,7 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
// #2257 xdescribe dbtest workerTimeControl_check() // #2261 xdescribe dbtest workerTimeControl_check()
xdescribe('worker workerTimeControl_check()', () => { xdescribe('worker workerTimeControl_check()', () => {
it(`should throw an error if the worker can't sign on that tablet`, async() => { it(`should throw an error if the worker can't sign on that tablet`, async() => {
let stmts = []; let stmts = [];

View File

@ -31,6 +31,9 @@
"userFk": { "userFk": {
"type" : "Number", "type" : "Number",
"required": true "required": true
},
"bossFk": {
"type" : "Number"
} }
}, },
"relations": { "relations": {