(options: BatchEmailOptions)
| 152 | } |
| 153 | |
| 154 | export async function sendBatchEmails(options: BatchEmailOptions): Promise<BatchSendEmailResult> { |
| 155 | try { |
| 156 | const entries = await prepareBatch(options.emails) |
| 157 | const sendable = entries.filter( |
| 158 | (e): e is PreparedBatchEntry & { data: ProcessedEmailData } => e.data !== null |
| 159 | ) |
| 160 | |
| 161 | if (sendable.length === 0) { |
| 162 | const results = entries.map((e) => e.skippedResult ?? SKIPPED_UNSUBSCRIBED_RESULT) |
| 163 | const allUnsubscribed = |
| 164 | entries.length > 0 && entries.every((e) => e.skippedResult === SKIPPED_UNSUBSCRIBED_RESULT) |
| 165 | return { |
| 166 | success: results.every((r) => r.success), |
| 167 | message: |
| 168 | options.emails.length === 0 |
| 169 | ? 'No emails to send' |
| 170 | : allUnsubscribed |
| 171 | ? 'All batch emails skipped (users unsubscribed)' |
| 172 | : 'No emails sent (all entries skipped or failed validation)', |
| 173 | results, |
| 174 | data: { count: 0 }, |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | const batchProvider = activeProviders.find((p) => p.sendBatch) |
| 179 | if (batchProvider) { |
| 180 | try { |
| 181 | const batchResult = await batchProvider.sendBatch!(sendable.map((e) => e.data)) |
| 182 | return mergeBatchResults(entries, sendable, batchResult.results) |
| 183 | } catch (error) { |
| 184 | logger.warn(`${batchProvider.name} batch failed, falling back to per-message sends`, error) |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | const sentResults = await Promise.all( |
| 189 | sendable.map((entry) => sendEmail(options.emails[entry.index])) |
| 190 | ) |
| 191 | return mergeBatchResults(entries, sendable, sentResults) |
| 192 | } catch (error) { |
| 193 | logger.error('Error in batch email sending:', error) |
| 194 | return { success: false, message: 'Failed to send batch emails', results: [] } |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | function mergeBatchResults( |
| 199 | entries: PreparedBatchEntry[], |
no test coverage detected