mail models and fix checkInbox

This commit is contained in:
Bernat Exposito Domenech 2020-09-22 13:59:00 +02:00
parent 01574b8967
commit ca41b93995
6 changed files with 145 additions and 57 deletions

View File

@ -1,5 +1,5 @@
const Imap = require('imap');
const {NULL} = require('node-sass');
module.exports = Self => {
Self.remoteMethod('checkInbox', {
description: 'Check an email inbox and process it',
@ -26,7 +26,8 @@ module.exports = Self => {
tls: true
});
let isEmailOk;
let emailText = '';
let uid;
let emailBody;
function openInbox(cb) {
imap.openBox('INBOX', true, cb);
@ -35,7 +36,7 @@ module.exports = Self => {
imap.once('ready', function() {
openInbox(function(err, box) {
if (err) throw err;
let f = imap.seq.fetch('1:3', {
let f = imap.seq.fetch('1:*', {
bodies: ['HEADER.FIELDS (FROM SUBJECT)', '1'],
struct: true
});
@ -43,87 +44,143 @@ module.exports = Self => {
isEmailOk = false;
msg.on('body', function(stream, info) {
let buffer = '';
let bufferCopy = '';
stream.on('data', function(chunk) {
// console.log('chunk', chunk);
buffer = chunk.toString('utf8');
if (info.which === '1') {
emailText = buffer.split('\n')[0];
emailText = emailText.toUpperCase();
emailText = emailText.replace(/\s/g, '');
if (emailText === 'OK')
isEmailOk = true; // isEmailOk
// console.log('buffer', buffer);
if (info.which === '1' && bufferCopy.length == 0)
bufferCopy = buffer.replace(/\s/g, ' ');
});
stream.on('end', function() {
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)') {
console.log('isEmailOk', isEmailOk);
if (isEmailOk) {
imap.move(uid, 'exito', function(err) {
});
emailConfirm(buffer);
imap.seq.move(seqno, 'exito', function(err) {
console.log('Move correcte: ' + err);
console.log('Move error: ' + seqno);
});
} else {
emailReply(buffer);
imap.seq.move(seqno, 'error', function(err) {
console.log('Move error: ' + err);
console.log('Move error: ' + seqno);
imap.move(uid, 'error', function(err) {
});
emailReply(buffer, emailBody);
}
}
});
});
});
// msg.on('attributes', function(attrs) {
// console.log('ATRIBUTO', attrs.struct[0]);
// console.log('ATRIBUTO', attrs.struct[0].params);
// });
f.once('end', function() {
imap.end();
});
});
});
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) {
let now = new Date();
let from = JSON.stringify(Imap.parseHeader(buffer).from);
let subject = JSON.stringify(Imap.parseHeader(buffer).subject);
// try {
const now = new Date();
const from = JSON.stringify(Imap.parseHeader(buffer).from);
const subject = JSON.stringify(Imap.parseHeader(buffer).subject);
let timeControlDate = await getEmailDate(subject);
let week = timeControlDate[0];
let year = timeControlDate[1];
let user = await getUser(from);
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,
worker: user.id
workerFk: user.id
}
});
if (workerMail != NULL) {
await workerMail.updateAttributes({
updated: now,
state: 'CONFIRMED'
});
// MOVER A CARPETA EXITO
}
async function emailReply(subject, workerEmail) {
console.log('bbbbb');
// } catch (err) {
// throw err;
// }
}
// INSERT EN VN.MAIL
// UPDATE EN WORKERTIMECONTROLMAIL
// MOVER A CARPETA ERROR
async function emailReply(buffer, emailBody) {
// try {
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": {
"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": {
"id": {
"id": true,
"type": "Number",
"required": true
"type": "Number"
},
"sender": {
"type": "String"

View File

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

View File

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