|
| 1 | +/** |
| 2 | + * Module dependencies |
| 3 | + */ |
| 4 | +import config from '../../config/index.js'; |
| 5 | +import logger from '../../lib/services/logger.js'; |
| 6 | +import billingEvents from './lib/events.js'; |
| 7 | +import mailer from '../../lib/helpers/mailer/index.js'; |
| 8 | +import MembershipRepository from '../organizations/repositories/organizations.membership.repository.js'; |
| 9 | +import { MEMBERSHIP_ROLES, MEMBERSHIP_STATUSES } from '../organizations/lib/constants.js'; |
| 10 | + |
| 11 | +/** |
| 12 | + * Resolve owner/admin emails for an organization. |
| 13 | + * Returns an array of email strings (may be empty if none found or lookup fails). |
| 14 | + * @param {string} organizationId |
| 15 | + * @returns {Promise<string[]>} |
| 16 | + */ |
| 17 | +export const resolveOrgAdminEmails = async (organizationId) => { |
| 18 | + try { |
| 19 | + const memberships = await MembershipRepository.list({ |
| 20 | + organizationId, |
| 21 | + role: { $in: [MEMBERSHIP_ROLES.OWNER, MEMBERSHIP_ROLES.ADMIN] }, |
| 22 | + status: MEMBERSHIP_STATUSES.ACTIVE, |
| 23 | + }); |
| 24 | + return memberships.map((m) => m.userId?.email).filter(Boolean); |
| 25 | + } catch (err) { |
| 26 | + logger.warn('[billing.email] resolveOrgAdminEmails failed (non-fatal)', { |
| 27 | + organizationId, |
| 28 | + error: err?.message ?? err, |
| 29 | + }); |
| 30 | + return []; |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | +/** |
| 35 | + * Fire-and-forget email send. Logs mailer errors without re-throwing. |
| 36 | + * @param {Object} mailOpts - Options passed directly to mailer.sendMail |
| 37 | + * @param {string} context - Log prefix for error messages |
| 38 | + */ |
| 39 | +export const sendBillingEmail = (mailOpts, context) => { |
| 40 | + if (!mailer.isConfigured()) return; |
| 41 | + mailer.sendMail(mailOpts).catch((err) => { |
| 42 | + logger.error(`[billing.email] ${context} email failed`, { |
| 43 | + error: err?.message ?? err, |
| 44 | + stack: err?.stack, |
| 45 | + }); |
| 46 | + }); |
| 47 | +}; |
| 48 | + |
| 49 | +/** |
| 50 | + * Wire billing email listeners onto billingEvents. |
| 51 | + * Call once from billing.init.js after config is ready. |
| 52 | + * |
| 53 | + * Listeners registered: |
| 54 | + * - meter.threshold_crossed — sends 80% warning or 100% quota-reached email to org admins/owners |
| 55 | + * - payment.failed — sends payment-failed email prompting card update |
| 56 | + * |
| 57 | + * Template resolution: devkit ships generic templates in config/templates/billing-*.html. |
| 58 | + * Downstream projects override by placing same-named files in their own config/templates/ |
| 59 | + * directory — those shadow devkit defaults via the template-resolution glob-merge in config. |
| 60 | + */ |
| 61 | +export const setupBillingEmails = () => { |
| 62 | + // ── meter.threshold_crossed — 80% / 100% quota emails ────────────────────── |
| 63 | + |
| 64 | + billingEvents.on('meter.threshold_crossed', ({ organizationId, threshold, meterUsed, meterQuota }) => { |
| 65 | + if (threshold !== 80 && threshold !== 100) return; |
| 66 | + |
| 67 | + const appName = config.app?.title ?? ''; |
| 68 | + const billingUrl = config.app?.url ? `${config.app.url}/billing` : ''; |
| 69 | + |
| 70 | + resolveOrgAdminEmails(organizationId).then((emails) => { |
| 71 | + if (!emails.length) return; |
| 72 | + const isAt80 = threshold === 80; |
| 73 | + for (const email of emails) { |
| 74 | + sendBillingEmail( |
| 75 | + { |
| 76 | + to: email, |
| 77 | + subject: isAt80 |
| 78 | + ? `Approaching your ${appName} quota — ${threshold}% used` |
| 79 | + : `${appName} weekly quota reached`, |
| 80 | + template: isAt80 ? 'billing-quota-warning-80' : 'billing-quota-reached-100', |
| 81 | + params: { |
| 82 | + threshold, |
| 83 | + meterUsed: meterUsed ?? '?', |
| 84 | + meterQuota: meterQuota ?? '?', |
| 85 | + billingUrl, |
| 86 | + appName, |
| 87 | + appContact: config.app?.contact ?? '', |
| 88 | + }, |
| 89 | + }, |
| 90 | + isAt80 ? 'meter.threshold_crossed@80' : 'meter.threshold_crossed@100', |
| 91 | + ); |
| 92 | + } |
| 93 | + }); |
| 94 | + }); |
| 95 | + |
| 96 | + // ── payment.failed — update card prompt ───────────────────────────────────── |
| 97 | + |
| 98 | + billingEvents.on('payment.failed', ({ organizationId }) => { |
| 99 | + const appName = config.app?.title ?? ''; |
| 100 | + const billingPortalUrl = config.app?.url ? `${config.app.url}/billing` : ''; |
| 101 | + |
| 102 | + resolveOrgAdminEmails(organizationId).then((emails) => { |
| 103 | + if (!emails.length) return; |
| 104 | + for (const email of emails) { |
| 105 | + sendBillingEmail( |
| 106 | + { |
| 107 | + to: email, |
| 108 | + subject: `${appName} billing — please update your payment method`, |
| 109 | + template: 'billing-payment-failed', |
| 110 | + params: { |
| 111 | + billingPortalUrl, |
| 112 | + appName, |
| 113 | + appContact: config.app?.contact ?? '', |
| 114 | + }, |
| 115 | + }, |
| 116 | + 'payment.failed', |
| 117 | + ); |
| 118 | + } |
| 119 | + }); |
| 120 | + }); |
| 121 | +}; |
0 commit comments