salix/print/core/email.js

94 lines
2.7 KiB
JavaScript

const path = require('path');
const smtp = require('./smtp');
const Component = require('./component');
const Report = require('./report');
const db = require('./database');
const config = require('./config');
if (!process.env.OPENSSL_CONF)
process.env.OPENSSL_CONF = '/etc/ssl/';
class Email extends Component {
constructor(name, args) {
super(name);
this.args = args;
}
get path() {
return `../templates/email/${this.name}`;
}
async getSubject() {
if (!this.lang) await this.getLang();
const locale = this.locale.messages;
const userLocale = locale[this.lang];
if (!userLocale) {
const fallbackLocale = config.i18n.fallbackLocale;
return locale[fallbackLocale].subject;
}
return userLocale.subject;
}
async getLang() {
const clientId = this.args.clientId;
const lang = await db.findOne(`
SELECT lang FROM account.user
WHERE id = ?`, [clientId]).then(rows => {
return rows.lang;
});
this.lang = lang;
}
async send() {
const instance = this.build();
const rendered = await this.render();
const attachments = [];
const getAttachments = async(componentPath, files) => {
for (file of files) {
const fileCopy = Object.assign({}, file);
if (fileCopy.cid) {
const templatePath = `${componentPath}/${file.path}`;
const fullFilePath = path.resolve(__dirname, templatePath);
fileCopy.path = path.resolve(__dirname, fullFilePath);
} else {
const reportName = fileCopy.filename.replace('.pdf', '');
const report = new Report(reportName, this.args);
fileCopy.content = await report.toPdfStream();
}
attachments.push(fileCopy);
}
};
if (instance.components) {
const components = instance.components;
for (let componentName in components) {
const component = components[componentName];
const componentPath = `./components/${componentName}`;
await getAttachments(componentPath, component.attachments);
}
}
if (this.attachments)
await getAttachments(this.path, this.attachments);
const localeSubject = await this.getSubject();
const options = {
to: this.args.recipient,
subject: localeSubject,
html: rendered,
attachments: attachments
};
return smtp.send(options);
}
}
module.exports = Email;