From 5abad59a0e80cf8f543d9ee2af10922c35ea5d10 Mon Sep 17 00:00:00 2001 From: VLE2FE Date: Thu, 6 Aug 2020 11:25:41 +0200 Subject: [PATCH] improved mail service --- .idea/dictionaries/VLE2FE.xml | 1 + data_import/import.js | 38 ++++++------ src/helpers/mail.ts | 111 ++++++++++++++++++++-------------- 3 files changed, 87 insertions(+), 63 deletions(-) diff --git a/.idea/dictionaries/VLE2FE.xml b/.idea/dictionaries/VLE2FE.xml index 16f4de3..a241715 100644 --- a/.idea/dictionaries/VLE2FE.xml +++ b/.idea/dictionaries/VLE2FE.xml @@ -11,6 +11,7 @@ colordesignatiomsuppl colordesignationsuppl contentin + definma dfopdb dosiergeschw dpts diff --git a/data_import/import.js b/data_import/import.js index 6add295..565336a 100644 --- a/data_import/import.js +++ b/data_import/import.js @@ -47,7 +47,7 @@ let sampleDevices = {}; const sampleReferences = []; // references to other samples in format {sample, referencedSample, relation} let commentsLog = []; let customFieldsLog = []; -const vzValues = {}; // vz values from comments +const vnValues = {}; // vn values from comments const dptLog = []; const dptSampleAddLog = []; // log samples created during dpt insertion const typeLog = []; @@ -73,7 +73,7 @@ async function main() { await importCsv(docs[i]); await allSamples(); await saveSamples(); - await allKfVz(); + await allMcVn(); } // write logs fs.writeFileSync('./data_import/comments.txt', commentsLog.join('\r\n')); @@ -332,7 +332,7 @@ async function allDpts() { } } -async function allKfVz() { +async function allMcVn() { let res = await axios({ method: 'get', url: host + '/template/measurements', @@ -341,8 +341,8 @@ async function allKfVz() { password: 'Abc123!#' } }); - const kf_template = res.data.filter(e => e.name === 'kf').sort((a, b) => b.version - a.version)[0]._id; - const vz_template = res.data.filter(e => e.name === 'vz').sort((a, b) => b.version - a.version)[0]._id; + const mc_template = res.data.filter(e => e.name === 'moisture content').sort((a, b) => b.version - a.version)[0]._id; + const vn_template = res.data.filter(e => e.name === 'vn').sort((a, b) => b.version - a.version)[0]._id; const rmc_template = res.data.filter(e => e.name === 'reinforcement material content').sort((a, b) => b.version - a.version)[0]._id; res = await axios({ method: 'get', @@ -357,15 +357,15 @@ async function allKfVz() { sampleIds[sample.number] = sample._id; }); for (let index in data) { - console.info(`KF/VZ ${index}/${data.length}`); + console.info(`MC/VN ${index}/${data.length}`); let sample = data[index]; sample['samplenumber'] = sample['samplenumber'].replace(/[A-Z][a-z]0\d_/, ''); let credentials = ['admin', 'Abc123!#']; if (sampleDevices[sample['samplenumber']]) { credentials = [sampleDevices[sample['samplenumber']], '2020DeFinMachen!'] } - if (!sample['vz(ml/g)'] && vzValues[sample['samplenumber']]) { // fill in VZ values from comments - sample['vz(ml/g)'] = vzValues[sample['samplenumber']]; + if (!sample['vz(ml/g)'] && vnValues[sample['samplenumber']]) { // fill in VN values from comments + sample['vz(ml/g)'] = vnValues[sample['samplenumber']]; } if (sample['kfingew%']) { await axios({ @@ -377,7 +377,7 @@ async function allKfVz() { }, data: { sample_id: sampleIds[sample['samplenumber']], - measurement_template: kf_template, + measurement_template: mc_template, values: { 'weight %': sample['kfingew%'], 'standard deviation': sample['stabwn'] @@ -386,7 +386,7 @@ async function allKfVz() { }).catch(err => { console.log(sample['samplenumber']); console.error(err.response.data); - errors.push(`KF/VZ upload for ${JSON.stringify(sample)} failed: ${JSON.stringify(err.response.data)}`); + errors.push(`MC/VN upload for ${JSON.stringify(sample)} failed: ${JSON.stringify(err.response.data)}`); }); } if (sample['vz(ml/g)']) { @@ -399,15 +399,15 @@ async function allKfVz() { }, data: { sample_id: sampleIds[sample['samplenumber']], - measurement_template: vz_template, + measurement_template: vn_template, values: { - vz: sample['vz(ml/g)'] + vn: sample['vz(ml/g)'] } } }).catch(err => { console.log(sample['samplenumber']); console.error(err.response.data); - errors.push(`KF/VZ upload for ${JSON.stringify(sample)} failed: ${JSON.stringify(err.response.data)}`); + errors.push(`MC/VN upload for ${JSON.stringify(sample)} failed: ${JSON.stringify(err.response.data)}`); }); } if (sample['reinforcingmaterialcontent']) { @@ -428,7 +428,7 @@ async function allKfVz() { }).catch(err => { console.log(sample['samplenumber']); console.error(err.response.data); - errors.push(`KF/VZ upload for ${JSON.stringify(sample)} failed: ${JSON.stringify(err.response.data)}`); + errors.push(`MC/VN upload for ${JSON.stringify(sample)} failed: ${JSON.stringify(err.response.data)}`); }); } } @@ -514,7 +514,7 @@ async function allSamples() { samples[si].color = number.color; } } - else if (sampleColors[sample['samplenumber'].split('_')[0]]) { // derive color from main sample for kf/vz + else if (sampleColors[sample['samplenumber'].split('_')[0]]) { // derive color from main sample for mc/vn samples[si].color = sampleColors[sample['samplenumber'].split('_')[0]]; } if (!samples[si].color) { @@ -913,9 +913,9 @@ function customFields (comment, sampleNumber) { {docKey: 'zu', dbKey: 'belongs to', regex: /zu (\S*\d+)/, category: 'reference'}, {docKey: 'granulate zu', dbKey: 'granulate to', regex: /granulate zu.* (\S*\d+)/, category: 'reference'}, {docKey: 'construction part', dbKey: 'construction part', regex: /(? i > 0).join(' '); diff --git a/src/helpers/mail.ts b/src/helpers/mail.ts index 8ec71c8..901c5f5 100644 --- a/src/helpers/mail.ts +++ b/src/helpers/mail.ts @@ -2,44 +2,65 @@ import axios from 'axios'; // sends an email using the BIC service -export default (mailAddress, subject, content, f) => { // callback, executed empty or with error - if (process.env.NODE_ENV === 'production') { - const mailService = JSON.parse(process.env.VCAP_SERVICES).Mail[0]; - axios({ - method: 'post', - url: mailService.credentials.uri + '/email', - auth: {username: mailService.credentials.username, password: mailService.credentials.password}, - data: { - recipients: [{to: mailAddress}], - subject: {content: subject}, - body: { - content: content, - contentType: "text/html" - }, - from: { - eMail: "definma@bosch-iot.com", - password: "PlasticsOfFingerprintDigital" - } - } - }) - .then(() => { - f(); - }) - .catch((err) => { - f(err); - }); - } - else if (process.env.NODE_ENV === 'test') { - console.info('Sending mail to ' + mailAddress + ': -- ' + subject + ' -- ' + content); - f(); - } - else { // dev - axios({ +export default class Mail{ + + static readonly address = 'definma@bosch-iot.com'; + static uri: string; + static auth = {username: '', password: ''}; + static mailPass: string; + + static init() { + this.mailPass = Array(64).map(() => Math.floor(Math.random() * 10)).join(''); + this.uri = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.uri; + this.auth.username = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.username; + this.auth.password = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.password; + axios({ // get registered mail addresses method: 'get', - url: 'https://digital-fingerprint-of-plastics-mail-test.apps.de1.bosch-iot-cloud.com/api', - data: { + url: this.uri + '/management/userDomainMapping', + auth: this.auth + }).then(res => { + return new Promise(async (resolve, reject) => { + try { + if (res.data.addresses.indexOf(this.address) < 0) { // mail address not registered + if (res.data.addresses.length) { // delete wrong registered mail address + await axios({ + method: 'delete', + url: this.uri + '/management/mailAddresses/' + res.data.addresses[0], + auth: this.auth + }); + } + await axios({ // register right mail address + method: 'post', + url: this.uri + '/management/mailAddresses/' + this.address, + auth: this.auth + }); + } + resolve(); + } + catch (e) { + reject(e); + } + }); + }).then(() => { + return axios({ // set new mail password + method: 'put', + url: this.uri + '/management/mailAddresses/' + this.address + '/password/' + this.mailPass, + auth: this.auth + }); + }).then(() => { // init done successfully + this.send('lukas.veit@bosch.com', 'Mail Service started', new Date().toString()); + }).catch(err => { // anywhere an error occurred + console.error(`Mail init error: ${err.request.method} ${err.request.path}: ${err.response.status}`, + err.response.data); + }); + } + + static send (mailAddress, subject, content, f = () => {}) { // callback, executed empty or with error + if (process.env.NODE_ENV === 'production') { // only send mails in production + axios({ method: 'post', - url: '/email', + url: this.uri + '/email', + auth: this.auth, data: { recipients: [{to: mailAddress}], subject: {content: subject}, @@ -48,17 +69,19 @@ export default (mailAddress, subject, content, f) => { // callback, executed em contentType: "text/html" }, from: { - eMail: "dfop-test@bosch-iot.com", - password: "PlasticsOfFingerprintDigital" + eMail: this.address, + password: this.mailPass } } - } - }) - .then(() => { + }).then(() => { f(); - }) - .catch((err) => { + }).catch((err) => { f(err); }); + } + else { // dev dummy replacement + console.info('Sending mail to ' + mailAddress + ': -- ' + subject + ' -- ' + content); + f(); + } } -} \ No newline at end of file +}