const {Email} = require('vn-print'); module.exports = Self => { Self.remoteMethodCtx('consumptionSendQueued', { description: 'Send all queued invoices', accessType: 'WRITE', accepts: [], returns: { type: 'object', root: true }, http: { path: '/consumption-send-queued', verb: 'POST' } }); Self.consumptionSendQueued = async ctx => { const queues = await Self.rawSql(` SELECT id, params FROM clientConsumptionQueue WHERE status = '' OR status IS NULL`); for (const queue of queues) { try { const params = JSON.parse(queue.params); const clients = await Self.rawSql(` SELECT c.id AS clientFk, c.email AS clientEmail, eu.email salesPersonEmail FROM client c JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk JOIN ticket t ON t.clientFk = c.id JOIN sale s ON s.ticketFk = t.id JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk WHERE c.id IN(?) AND it.isPackaging = FALSE AND DATE(t.shipped) BETWEEN ? AND ? GROUP BY c.id`, [params.clients, params.from, params.to]); for (const client of clients) { try { const args = { id: client.clientFk, recipient: client.clientEmail, replyTo: client.salesPersonEmail, from: params.from, to: params.to }; const email = new Email('campaign-metrics', args); await email.send(); } catch (error) { if (error.code === 'EENVELOPE') continue; throw error; } } await Self.rawSql(` UPDATE clientConsumptionQueue SET status = 'printed', printed = ? WHERE id = ?`, [Date.vnNew(), queue.id], {userId: ctx.req.accessToken.userId}); } catch (error) { await Self.rawSql(` UPDATE clientConsumptionQueue SET status = ? WHERE id = ?`, [error.message, queue.id]); throw error; } } return { message: 'Success' }; }; };