Archived
2

improved mail service

This commit is contained in:
VLE2FE 2020-08-06 11:25:41 +02:00
parent a910371882
commit 5abad59a0e
3 changed files with 87 additions and 63 deletions

View File

@ -11,6 +11,7 @@
<w>colordesignatiomsuppl</w> <w>colordesignatiomsuppl</w>
<w>colordesignationsuppl</w> <w>colordesignationsuppl</w>
<w>contentin</w> <w>contentin</w>
<w>definma</w>
<w>dfopdb</w> <w>dfopdb</w>
<w>dosiergeschw</w> <w>dosiergeschw</w>
<w>dpts</w> <w>dpts</w>

View File

@ -47,7 +47,7 @@ let sampleDevices = {};
const sampleReferences = []; // references to other samples in format {sample, referencedSample, relation} const sampleReferences = []; // references to other samples in format {sample, referencedSample, relation}
let commentsLog = []; let commentsLog = [];
let customFieldsLog = []; let customFieldsLog = [];
const vzValues = {}; // vz values from comments const vnValues = {}; // vn values from comments
const dptLog = []; const dptLog = [];
const dptSampleAddLog = []; // log samples created during dpt insertion const dptSampleAddLog = []; // log samples created during dpt insertion
const typeLog = []; const typeLog = [];
@ -73,7 +73,7 @@ async function main() {
await importCsv(docs[i]); await importCsv(docs[i]);
await allSamples(); await allSamples();
await saveSamples(); await saveSamples();
await allKfVz(); await allMcVn();
} }
// write logs // write logs
fs.writeFileSync('./data_import/comments.txt', commentsLog.join('\r\n')); 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({ let res = await axios({
method: 'get', method: 'get',
url: host + '/template/measurements', url: host + '/template/measurements',
@ -341,8 +341,8 @@ async function allKfVz() {
password: 'Abc123!#' password: 'Abc123!#'
} }
}); });
const kf_template = res.data.filter(e => e.name === 'kf').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 vz_template = res.data.filter(e => e.name === 'vz').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; const rmc_template = res.data.filter(e => e.name === 'reinforcement material content').sort((a, b) => b.version - a.version)[0]._id;
res = await axios({ res = await axios({
method: 'get', method: 'get',
@ -357,15 +357,15 @@ async function allKfVz() {
sampleIds[sample.number] = sample._id; sampleIds[sample.number] = sample._id;
}); });
for (let index in data) { for (let index in data) {
console.info(`KF/VZ ${index}/${data.length}`); console.info(`MC/VN ${index}/${data.length}`);
let sample = data[index]; let sample = data[index];
sample['samplenumber'] = sample['samplenumber'].replace(/[A-Z][a-z]0\d_/, ''); sample['samplenumber'] = sample['samplenumber'].replace(/[A-Z][a-z]0\d_/, '');
let credentials = ['admin', 'Abc123!#']; let credentials = ['admin', 'Abc123!#'];
if (sampleDevices[sample['samplenumber']]) { if (sampleDevices[sample['samplenumber']]) {
credentials = [sampleDevices[sample['samplenumber']], '2020DeFinMachen!'] credentials = [sampleDevices[sample['samplenumber']], '2020DeFinMachen!']
} }
if (!sample['vz(ml/g)'] && vzValues[sample['samplenumber']]) { // fill in VZ values from comments if (!sample['vz(ml/g)'] && vnValues[sample['samplenumber']]) { // fill in VN values from comments
sample['vz(ml/g)'] = vzValues[sample['samplenumber']]; sample['vz(ml/g)'] = vnValues[sample['samplenumber']];
} }
if (sample['kfingew%']) { if (sample['kfingew%']) {
await axios({ await axios({
@ -377,7 +377,7 @@ async function allKfVz() {
}, },
data: { data: {
sample_id: sampleIds[sample['samplenumber']], sample_id: sampleIds[sample['samplenumber']],
measurement_template: kf_template, measurement_template: mc_template,
values: { values: {
'weight %': sample['kfingew%'], 'weight %': sample['kfingew%'],
'standard deviation': sample['stabwn'] 'standard deviation': sample['stabwn']
@ -386,7 +386,7 @@ async function allKfVz() {
}).catch(err => { }).catch(err => {
console.log(sample['samplenumber']); console.log(sample['samplenumber']);
console.error(err.response.data); 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)']) { if (sample['vz(ml/g)']) {
@ -399,15 +399,15 @@ async function allKfVz() {
}, },
data: { data: {
sample_id: sampleIds[sample['samplenumber']], sample_id: sampleIds[sample['samplenumber']],
measurement_template: vz_template, measurement_template: vn_template,
values: { values: {
vz: sample['vz(ml/g)'] vn: sample['vz(ml/g)']
} }
} }
}).catch(err => { }).catch(err => {
console.log(sample['samplenumber']); console.log(sample['samplenumber']);
console.error(err.response.data); 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']) { if (sample['reinforcingmaterialcontent']) {
@ -428,7 +428,7 @@ async function allKfVz() {
}).catch(err => { }).catch(err => {
console.log(sample['samplenumber']); console.log(sample['samplenumber']);
console.error(err.response.data); 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; 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]]; samples[si].color = sampleColors[sample['samplenumber'].split('_')[0]];
} }
if (!samples[si].color) { if (!samples[si].color) {
@ -913,9 +913,9 @@ function customFields (comment, sampleNumber) {
{docKey: 'zu', dbKey: 'belongs to', regex: /zu (\S*\d+)/, category: 'reference'}, {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: 'granulate zu', dbKey: 'granulate to', regex: /granulate zu.* (\S*\d+)/, category: 'reference'},
{docKey: 'construction part', dbKey: 'construction part', regex: /(?<!granulate)construction part.* (\S*\d+)/, category: 'reference'}, {docKey: 'construction part', dbKey: 'construction part', regex: /(?<!granulate)construction part.* (\S*\d+)/, category: 'reference'},
{docKey: 'VZ =', dbKey: 'vz', regex: /VZ = (\d+) cm³\/g/, category: 'vz'}, {docKey: 'VZ =', dbKey: 'vn', regex: /VZ = (\d+) cm³\/g/, category: 'vn'},
{docKey: 'VWZ', dbKey: 'vwz', regex: /(\d+ min) VWZ \//, category: 'customField'}, {docKey: 'VWZ', dbKey: 'vwz', regex: /(\d+ min) VWZ \//, category: 'customField'},
{docKey: 'VZ:', dbKey: 'vz', regex: /VZ: ([0-9.,]+) mL\/g[;]?/, category: 'vz'} {docKey: 'VZ:', dbKey: 'vn', regex: /VZ: ([0-9.,]+) mL\/g[;]?/, category: 'vn'}
]; ];
const res = {}; // returned result const res = {}; // returned result
const usedParts = []; // all substrings used for custom fields, subtract at the end, as some parts are used multiple times const usedParts = []; // all substrings used for custom fields, subtract at the end, as some parts are used multiple times
@ -928,8 +928,8 @@ function customFields (comment, sampleNumber) {
if (cField.category === 'reference') { if (cField.category === 'reference') {
sampleReferences.push({sample: sampleNumber, referencedSample: regexRes[1], relation: cField.dbKey}); sampleReferences.push({sample: sampleNumber, referencedSample: regexRes[1], relation: cField.dbKey});
} }
else if (cField.category === 'vz') { else if (cField.category === 'vn') {
vzValues[sampleNumber] = regexRes[1]; vnValues[sampleNumber] = regexRes[1];
} }
else { else {
res[cField.dbKey] = regexRes.filter((e, i) => i > 0).join(' '); res[cField.dbKey] = regexRes.filter((e, i) => i > 0).join(' ');

View File

@ -2,44 +2,65 @@ import axios from 'axios';
// sends an email using the BIC service // sends an email using the BIC service
export default (mailAddress, subject, content, f) => { // callback, executed empty or with error export default class Mail{
if (process.env.NODE_ENV === 'production') {
const mailService = JSON.parse(process.env.VCAP_SERVICES).Mail[0]; static readonly address = 'definma@bosch-iot.com';
axios({ static uri: string;
method: 'post', static auth = {username: '', password: ''};
url: mailService.credentials.uri + '/email', static mailPass: string;
auth: {username: mailService.credentials.username, password: mailService.credentials.password},
data: { static init() {
recipients: [{to: mailAddress}], this.mailPass = Array(64).map(() => Math.floor(Math.random() * 10)).join('');
subject: {content: subject}, this.uri = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.uri;
body: { this.auth.username = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.username;
content: content, this.auth.password = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.password;
contentType: "text/html" axios({ // get registered mail addresses
},
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({
method: 'get', method: 'get',
url: 'https://digital-fingerprint-of-plastics-mail-test.apps.de1.bosch-iot-cloud.com/api', url: this.uri + '/management/userDomainMapping',
data: { 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', method: 'post',
url: '/email', url: this.uri + '/email',
auth: this.auth,
data: { data: {
recipients: [{to: mailAddress}], recipients: [{to: mailAddress}],
subject: {content: subject}, subject: {content: subject},
@ -48,17 +69,19 @@ export default (mailAddress, subject, content, f) => { // callback, executed em
contentType: "text/html" contentType: "text/html"
}, },
from: { from: {
eMail: "dfop-test@bosch-iot.com", eMail: this.address,
password: "PlasticsOfFingerprintDigital" password: this.mailPass
} }
} }
} }).then(() => {
})
.then(() => {
f(); f();
}) }).catch((err) => {
.catch((err) => {
f(err); f(err);
}); });
}
else { // dev dummy replacement
console.info('Sending mail to ' + mailAddress + ': -- ' + subject + ' -- ' + content);
f();
}
} }
} }