plugin.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { ModuleRef } from '@nestjs/core';
  2. import {
  3. createProxyHandler,
  4. EventBus,
  5. Injector,
  6. JobQueue,
  7. JobQueueService,
  8. Logger,
  9. OnVendureBootstrap,
  10. OnVendureClose,
  11. PluginCommonModule,
  12. RuntimeVendureConfig,
  13. Type,
  14. VendurePlugin,
  15. WorkerService,
  16. } from '@vendure/core';
  17. import { isDevModeOptions } from './common';
  18. import { EMAIL_PLUGIN_OPTIONS } from './constants';
  19. import { DevMailbox } from './dev-mailbox';
  20. import { EmailProcessor } from './email-processor';
  21. import { EmailProcessorController } from './email-processor.controller';
  22. import { EmailEventHandler, EmailEventHandlerWithAsyncData } from './event-handler';
  23. import {
  24. EmailPluginDevModeOptions,
  25. EmailPluginOptions,
  26. EmailWorkerMessage,
  27. EventWithContext,
  28. IntermediateEmailDetails,
  29. } from './types';
  30. /**
  31. * @description
  32. * The EmailPlugin creates and sends transactional emails based on Vendure events. It uses an [MJML](https://mjml.io/)-based
  33. * email generator to generate the email body and [Nodemailer](https://nodemailer.com/about/) to send the emais.
  34. *
  35. * ## Installation
  36. *
  37. * `yarn add \@vendure/email-plugin`
  38. *
  39. * or
  40. *
  41. * `npm install \@vendure/email-plugin`
  42. *
  43. * @example
  44. * ```ts
  45. * import { defaultEmailHandlers, EmailPlugin } from '\@vendure/email-plugin';
  46. *
  47. * const config: VendureConfig = {
  48. * // Add an instance of the plugin to the plugins array
  49. * plugins: [
  50. * EmailPlugin.init({
  51. * handlers: defaultEmailHandlers,
  52. * templatePath: path.join(__dirname, 'vendure/email/templates'),
  53. * transport: {
  54. * type: 'smtp',
  55. * host: 'smtp.example.com',
  56. * port: 587,
  57. * auth: {
  58. * user: 'username',
  59. * pass: 'password',
  60. * }
  61. * },
  62. * }),
  63. * ],
  64. * };
  65. * ```
  66. *
  67. * ## Email templates
  68. *
  69. * In the example above, the plugin has been configured to look in `<app-root>/vendure/email/templates`
  70. * for the email template files. If you used `\@vendure/create` to create your application, the templates will have
  71. * been copied to that location during setup.
  72. *
  73. * If you are installing the EmailPlugin separately, then you'll need to copy the templates manually from
  74. * `node_modules/\@vendure/email-plugin/templates` to a location of your choice, and then point the `templatePath` config
  75. * property at that directory.
  76. *
  77. * ## Customizing templates
  78. *
  79. * Emails are generated from templates which use [MJML](https://mjml.io/) syntax. MJML is an open-source HTML-like markup
  80. * language which makes the task of creating responsive email markup simple. By default, the templates are installed to
  81. * `<project root>/vendure/email/templates` and can be freely edited.
  82. *
  83. * Dynamic data such as the recipient's name or order items are specified using [Handlebars syntax](https://handlebarsjs.com/):
  84. *
  85. * ```HTML
  86. * <p>Dear {{ order.customer.firstName }} {{ order.customer.lastName }},</p>
  87. *
  88. * <p>Thank you for your order!</p>
  89. *
  90. * <mj-table cellpadding="6px">
  91. * {{#each order.lines }}
  92. * <tr class="order-row">
  93. * <td>{{ quantity }} x {{ productVariant.name }}</td>
  94. * <td>{{ productVariant.quantity }}</td>
  95. * <td>{{ formatMoney totalPrice }}</td>
  96. * </tr>
  97. * {{/each}}
  98. * </mj-table>
  99. * ```
  100. *
  101. * ### Handlebars helpers
  102. *
  103. * The following helper functions are available for use in email templates:
  104. *
  105. * * `formatMoney`: Formats an amount of money (which are always stored as integers in Vendure) as a decimal, e.g. `123` => `1.23`
  106. * * `formatDate`: Formats a Date value with the [dateformat](https://www.npmjs.com/package/dateformat) package.
  107. *
  108. * ## Extending the default email handlers
  109. *
  110. * The `defaultEmailHandlers` array defines the default handlers such as for handling new account registration, order confirmation, password reset
  111. * etc. These defaults can be extended by adding custom templates for languages other than the default, or even completely new types of emails
  112. * which respond to any of the available [VendureEvents](/docs/typescript-api/events/). See the {@link EmailEventHandler} documentation for
  113. * details on how to do so.
  114. *
  115. * ## Dev mode
  116. *
  117. * For development, the `transport` option can be replaced by `devMode: true`. Doing so configures Vendure to use the
  118. * file transport (See {@link FileTransportOptions}) and outputs emails as rendered HTML files in the directory specified by the
  119. * `outputPath` property.
  120. *
  121. * ```ts
  122. * EmailPlugin.init({
  123. * devMode: true,
  124. * handlers: defaultEmailHandlers,
  125. * templatePath: path.join(__dirname, 'vendure/email/templates'),
  126. * outputPath: path.join(__dirname, 'test-emails'),
  127. * mailboxPort: 5003,
  128. * })
  129. * ```
  130. *
  131. * ### Dev mailbox
  132. *
  133. * In dev mode, specifying the optional `mailboxPort` will start a webmail-like interface available at the `/mailbox` path, e.g.
  134. * http://localhost:3000/mailbox. This is a simple way to view the output of all emails generated by the EmailPlugin while in dev mode.
  135. *
  136. * ## Troubleshooting SMTP Connections
  137. *
  138. * If you are having trouble sending email over and SMTP connection, set the `logging` and `debug` options to `true`. This will
  139. * send detailed information from the SMTP transporter to the configured logger (defaults to console). For maximum detail combine
  140. * this with a detail log level in the configured VendureLogger:
  141. *
  142. * ```TypeScript
  143. * const config: VendureConfig = {
  144. * logger: new DefaultLogger({ level: LogLevel.Debug })
  145. * // ...
  146. * plugins: [
  147. * EmailPlugin.init({
  148. * // ...
  149. * transport: {
  150. * type: 'smtp',
  151. * host: 'smtp.example.com',
  152. * port: 587,
  153. * auth: {
  154. * user: 'username',
  155. * pass: 'password',
  156. * },
  157. * logging: true,
  158. * debug: true,
  159. * },
  160. * }),
  161. * ],
  162. * };
  163. * ```
  164. *
  165. * @docsCategory EmailPlugin
  166. */
  167. @VendurePlugin({
  168. imports: [PluginCommonModule],
  169. providers: [{ provide: EMAIL_PLUGIN_OPTIONS, useFactory: () => EmailPlugin.options }],
  170. workers: [EmailProcessorController],
  171. configuration: config => EmailPlugin.configure(config),
  172. })
  173. export class EmailPlugin implements OnVendureBootstrap, OnVendureClose {
  174. private static options: EmailPluginOptions | EmailPluginDevModeOptions;
  175. private devMailbox: DevMailbox | undefined;
  176. private jobQueue: JobQueue<IntermediateEmailDetails> | undefined;
  177. private testingProcessor: EmailProcessor | undefined;
  178. /** @internal */
  179. constructor(
  180. private eventBus: EventBus,
  181. private moduleRef: ModuleRef,
  182. private workerService: WorkerService,
  183. private jobQueueService: JobQueueService,
  184. ) {}
  185. /**
  186. * Set the plugin options.
  187. */
  188. static init(options: EmailPluginOptions | EmailPluginDevModeOptions): Type<EmailPlugin> {
  189. this.options = options;
  190. return EmailPlugin;
  191. }
  192. /** @internal */
  193. static configure(config: RuntimeVendureConfig): RuntimeVendureConfig {
  194. if (isDevModeOptions(this.options) && this.options.mailboxPort !== undefined) {
  195. const route = 'mailbox';
  196. config.apiOptions.middleware.push({
  197. handler: createProxyHandler({ port: this.options.mailboxPort, route, label: 'Dev Mailbox' }),
  198. route,
  199. });
  200. }
  201. return config;
  202. }
  203. /** @internal */
  204. async onVendureBootstrap(): Promise<void> {
  205. const options = EmailPlugin.options;
  206. if (isDevModeOptions(options) && options.mailboxPort !== undefined) {
  207. this.devMailbox = new DevMailbox();
  208. this.devMailbox.serve(options);
  209. this.devMailbox.handleMockEvent((handler, event) => this.handleEvent(handler, event));
  210. }
  211. await this.setupEventSubscribers();
  212. if (!isDevModeOptions(options) && options.transport.type === 'testing') {
  213. // When running tests, we don't want to go through the JobQueue system,
  214. // so we just call the email sending logic directly.
  215. this.testingProcessor = new EmailProcessor(options);
  216. await this.testingProcessor.init();
  217. } else {
  218. this.jobQueue = this.jobQueueService.createQueue({
  219. name: 'send-email',
  220. concurrency: 5,
  221. process: job => {
  222. this.workerService.send(new EmailWorkerMessage(job.data)).subscribe({
  223. complete: () => job.complete(),
  224. error: err => job.fail(err),
  225. });
  226. },
  227. });
  228. }
  229. }
  230. /** @internal */
  231. async onVendureClose() {
  232. if (this.devMailbox) {
  233. this.devMailbox.destroy();
  234. }
  235. }
  236. private async setupEventSubscribers() {
  237. for (const handler of EmailPlugin.options.handlers) {
  238. this.eventBus.ofType(handler.event).subscribe(event => {
  239. return this.handleEvent(handler, event);
  240. });
  241. }
  242. }
  243. private async handleEvent(
  244. handler: EmailEventHandler | EmailEventHandlerWithAsyncData<any>,
  245. event: EventWithContext,
  246. ) {
  247. Logger.debug(`Handling event "${handler.type}"`, 'EmailPlugin');
  248. const { type } = handler;
  249. try {
  250. const injector = new Injector(this.moduleRef);
  251. const result = await handler.handle(
  252. event as any,
  253. EmailPlugin.options.globalTemplateVars,
  254. injector,
  255. );
  256. if (!result) {
  257. return;
  258. }
  259. if (this.jobQueue) {
  260. await this.jobQueue.add(result);
  261. } else if (this.testingProcessor) {
  262. await this.testingProcessor.process(result);
  263. }
  264. } catch (e) {
  265. Logger.error(e.message, 'EmailPlugin', e.stack);
  266. }
  267. }
  268. }