@vicacha-devs/medusa-plugin-notifications 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/.medusa/server/src/admin/index.cjs +4215 -0
  2. package/.medusa/server/src/admin/index.js +4193 -0
  3. package/.medusa/server/src/api/admin/mpn/broadcasts/route.js +99 -0
  4. package/.medusa/server/src/api/admin/mpn/channels/route.js +109 -0
  5. package/.medusa/server/src/api/admin/mpn/logs/route.js +33 -0
  6. package/.medusa/server/src/api/admin/mpn/mappings/[id]/route.js +33 -0
  7. package/.medusa/server/src/api/admin/mpn/mappings/route.js +51 -0
  8. package/.medusa/server/src/api/admin/mpn/render-template/route.js +37 -0
  9. package/.medusa/server/src/api/admin/mpn/sandbox/route.js +36 -0
  10. package/.medusa/server/src/api/admin/mpn/send/route.js +135 -0
  11. package/.medusa/server/src/api/admin/mpn/templates/[id]/route.js +77 -0
  12. package/.medusa/server/src/api/admin/mpn/templates/route.js +71 -0
  13. package/.medusa/server/src/api/admin/plugin/route.js +4 -0
  14. package/.medusa/server/src/api/middlewares.js +28 -0
  15. package/.medusa/server/src/api/store/mpn/consent/route.js +37 -0
  16. package/.medusa/server/src/api/store/mpn/webhooks/[provider]/route.js +97 -0
  17. package/.medusa/server/src/api/store/plugin/route.js +4 -0
  18. package/.medusa/server/src/api/validators.js +118 -0
  19. package/.medusa/server/src/hooks/index.js +7 -0
  20. package/.medusa/server/src/hooks/use-mpn-channels.js +13 -0
  21. package/.medusa/server/src/hooks/use-mpn-dispatch.js +45 -0
  22. package/.medusa/server/src/hooks/use-mpn-mappings.js +21 -0
  23. package/.medusa/server/src/hooks/use-mpn-templates.js +34 -0
  24. package/.medusa/server/src/hooks/use-order-notifications-widget-state.js +79 -0
  25. package/.medusa/server/src/hooks/use-sdk-primitives.js +113 -0
  26. package/.medusa/server/src/index.js +14 -0
  27. package/.medusa/server/src/integrations/automations-action-handler.js +112 -0
  28. package/.medusa/server/src/jobs/abandoned-cart-recovery.js +123 -0
  29. package/.medusa/server/src/jobs/log-retention-and-broadcasts.js +15 -0
  30. package/.medusa/server/src/modules/notifications/i18n/index.js +65 -0
  31. package/.medusa/server/src/modules/notifications/i18n/locales/ar.js +76 -0
  32. package/.medusa/server/src/modules/notifications/i18n/locales/de.js +76 -0
  33. package/.medusa/server/src/modules/notifications/i18n/locales/en.js +76 -0
  34. package/.medusa/server/src/modules/notifications/i18n/locales/es.js +76 -0
  35. package/.medusa/server/src/modules/notifications/i18n/locales/fr.js +76 -0
  36. package/.medusa/server/src/modules/notifications/i18n/locales/it.js +76 -0
  37. package/.medusa/server/src/modules/notifications/i18n/locales/nl.js +76 -0
  38. package/.medusa/server/src/modules/notifications/i18n/locales/pl.js +76 -0
  39. package/.medusa/server/src/modules/notifications/i18n/locales/pt.js +76 -0
  40. package/.medusa/server/src/modules/notifications/i18n/locales/tr.js +76 -0
  41. package/.medusa/server/src/modules/notifications/i18n/types.js +2 -0
  42. package/.medusa/server/src/modules/notifications/index.js +9 -0
  43. package/.medusa/server/src/modules/notifications/integrations/documents-and-b2b-resolver.js +129 -0
  44. package/.medusa/server/src/modules/notifications/migrations/Migration20261010000000.js +184 -0
  45. package/.medusa/server/src/modules/notifications/models/index.js +118 -0
  46. package/.medusa/server/src/modules/notifications/renderer/block-helpers.js +36 -0
  47. package/.medusa/server/src/modules/notifications/renderer/email.js +161 -0
  48. package/.medusa/server/src/modules/notifications/renderer/index.js +240 -0
  49. package/.medusa/server/src/modules/notifications/renderer/slack.js +114 -0
  50. package/.medusa/server/src/modules/notifications/renderer/telegram.js +99 -0
  51. package/.medusa/server/src/modules/notifications/renderer/whatsapp.js +91 -0
  52. package/.medusa/server/src/modules/notifications/service-helpers/channel-config.js +45 -0
  53. package/.medusa/server/src/modules/notifications/service-helpers/consent.js +65 -0
  54. package/.medusa/server/src/modules/notifications/service-helpers/delivery-log.js +29 -0
  55. package/.medusa/server/src/modules/notifications/service-helpers/event-conditions.js +46 -0
  56. package/.medusa/server/src/modules/notifications/service-helpers/external-templates.js +80 -0
  57. package/.medusa/server/src/modules/notifications/service-helpers/recipient-resolution.js +85 -0
  58. package/.medusa/server/src/modules/notifications/service-helpers/sender-profiles.js +29 -0
  59. package/.medusa/server/src/modules/notifications/service-helpers/template-blocks.js +81 -0
  60. package/.medusa/server/src/modules/notifications/service-helpers/template-catalog.js +129 -0
  61. package/.medusa/server/src/modules/notifications/service-helpers/template-render.js +65 -0
  62. package/.medusa/server/src/modules/notifications/service.js +339 -0
  63. package/.medusa/server/src/modules/notifications/types.js +2 -0
  64. package/.medusa/server/src/modules/notifications/utils/auth-presets.js +140 -0
  65. package/.medusa/server/src/modules/notifications/utils/interpolation.js +178 -0
  66. package/.medusa/server/src/modules/notifications/utils/security.js +312 -0
  67. package/.medusa/server/src/modules/notifications/utils/system-presets.js +651 -0
  68. package/.medusa/server/src/modules/notifications/utils/transformers.js +358 -0
  69. package/.medusa/server/src/providers/dummy-sandbox/index.js +96 -0
  70. package/.medusa/server/src/providers/email-smtp/index.js +187 -0
  71. package/.medusa/server/src/providers/index.js +7 -0
  72. package/.medusa/server/src/providers/slack/index.js +54 -0
  73. package/.medusa/server/src/providers/sms/index.js +254 -0
  74. package/.medusa/server/src/providers/telegram/index.js +119 -0
  75. package/.medusa/server/src/providers/whatsapp/index.js +371 -0
  76. package/.medusa/server/src/rbac.js +109 -0
  77. package/.medusa/server/src/sdk/client.js +186 -0
  78. package/.medusa/server/src/sdk/index.js +3 -0
  79. package/.medusa/server/src/sdk/query-keys.js +61 -0
  80. package/.medusa/server/src/subscribers/customer-and-document-events.js +33 -0
  81. package/.medusa/server/src/subscribers/fulfillment-and-inventory-events.js +30 -0
  82. package/.medusa/server/src/subscribers/order-events.js +28 -0
  83. package/.medusa/server/src/types/constants.js +129 -0
  84. package/.medusa/server/src/types/core.js +2 -0
  85. package/.medusa/server/src/types/domain.js +2 -0
  86. package/.medusa/server/src/types/enums.js +53 -0
  87. package/.medusa/server/src/types/errors.js +28 -0
  88. package/.medusa/server/src/types/hooks.js +2 -0
  89. package/.medusa/server/src/types/index.js +12 -0
  90. package/.medusa/server/src/types/providers.js +2 -0
  91. package/.medusa/server/src/types/records.js +2 -0
  92. package/.medusa/server/src/types/render.js +2 -0
  93. package/.medusa/server/src/types/sdk-api.js +2 -0
  94. package/.medusa/server/src/types/translations.js +2 -0
  95. package/.medusa/server/src/workflows/index.js +461 -0
  96. package/LICENSE +21 -0
  97. package/README.md +389 -2
  98. package/package.json +138 -3
  99. package/src/admin/README.md +123 -0
  100. package/src/admin/components/mpn/broadcast-consent-section.tsx +62 -0
  101. package/src/admin/components/mpn/broadcasts-tab.tsx +208 -0
  102. package/src/admin/components/mpn/channels-main-section.tsx +205 -0
  103. package/src/admin/components/mpn/channels-side-section.tsx +88 -0
  104. package/src/admin/components/mpn/channels-tab.tsx +130 -0
  105. package/src/admin/components/mpn/constants.ts +8 -0
  106. package/src/admin/components/mpn/delivery-logs-tab.tsx +70 -0
  107. package/src/admin/components/mpn/event-mapping-form.tsx +191 -0
  108. package/src/admin/components/mpn/event-mappings-tab.tsx +165 -0
  109. package/src/admin/components/mpn/header-bar.tsx +35 -0
  110. package/src/admin/components/mpn/index.ts +17 -0
  111. package/src/admin/components/mpn/overview-cards.tsx +103 -0
  112. package/src/admin/components/mpn/sandbox-tab.tsx +93 -0
  113. package/src/admin/components/mpn/template-editor-section.tsx +203 -0
  114. package/src/admin/components/mpn/template-preview-section.tsx +122 -0
  115. package/src/admin/components/mpn/templates-list-section.tsx +115 -0
  116. package/src/admin/components/mpn/templates-tab.tsx +188 -0
  117. package/src/admin/components/mpn/use-notification-studio.ts +84 -0
  118. package/src/admin/components/rbac-guard.tsx +153 -0
  119. package/src/admin/i18n/README.md +134 -0
  120. package/src/admin/i18n/index.ts +23 -0
  121. package/src/admin/i18n/json/ar.json +157 -0
  122. package/src/admin/i18n/json/de.json +157 -0
  123. package/src/admin/i18n/json/en.json +157 -0
  124. package/src/admin/i18n/json/es.json +157 -0
  125. package/src/admin/i18n/json/fr.json +157 -0
  126. package/src/admin/i18n/json/it.json +157 -0
  127. package/src/admin/i18n/json/nl.json +157 -0
  128. package/src/admin/i18n/json/pl.json +157 -0
  129. package/src/admin/i18n/json/pt.json +157 -0
  130. package/src/admin/i18n/json/tr.json +157 -0
  131. package/src/admin/routes/mpn/broadcasts/page.tsx +75 -0
  132. package/src/admin/routes/mpn/channels/page.tsx +66 -0
  133. package/src/admin/routes/mpn/logs/page.tsx +50 -0
  134. package/src/admin/routes/mpn/mappings/page.tsx +62 -0
  135. package/src/admin/routes/mpn/page.tsx +200 -0
  136. package/src/admin/routes/mpn/sandbox/page.tsx +53 -0
  137. package/src/admin/routes/mpn/templates/page.tsx +55 -0
  138. package/src/admin/tsconfig.json +23 -0
  139. package/src/admin/vite-env.d.ts +1 -0
  140. package/src/admin/widgets/order-notifications-widget.tsx +178 -0
  141. package/src/api/README.md +98 -0
  142. package/src/api/admin/mpn/broadcasts/route.ts +130 -0
  143. package/src/api/admin/mpn/channels/route.ts +143 -0
  144. package/src/api/admin/mpn/logs/route.ts +41 -0
  145. package/src/api/admin/mpn/mappings/[id]/route.ts +45 -0
  146. package/src/api/admin/mpn/mappings/route.ts +68 -0
  147. package/src/api/admin/mpn/render-template/route.ts +46 -0
  148. package/src/api/admin/mpn/sandbox/route.ts +51 -0
  149. package/src/api/admin/mpn/send/route.ts +163 -0
  150. package/src/api/admin/mpn/templates/[id]/route.ts +101 -0
  151. package/src/api/admin/mpn/templates/route.ts +99 -0
  152. package/src/api/admin/plugin/route.ts +5 -0
  153. package/src/api/middlewares.ts +42 -0
  154. package/src/api/store/mpn/consent/route.ts +45 -0
  155. package/src/api/store/mpn/webhooks/[provider]/route.ts +119 -0
  156. package/src/api/store/plugin/route.ts +5 -0
  157. package/src/api/validators.ts +149 -0
  158. package/src/hooks/index.ts +14 -0
  159. package/src/hooks/use-mpn-channels.ts +43 -0
  160. package/src/hooks/use-mpn-dispatch.ts +149 -0
  161. package/src/hooks/use-mpn-mappings.ts +75 -0
  162. package/src/hooks/use-mpn-templates.ts +120 -0
  163. package/src/hooks/use-order-notifications-widget-state.ts +103 -0
  164. package/src/hooks/use-sdk-primitives.ts +157 -0
  165. package/src/index.ts +16 -0
  166. package/src/integrations/automations-action-handler.ts +156 -0
  167. package/src/jobs/README.md +41 -0
  168. package/src/jobs/abandoned-cart-recovery.ts +152 -0
  169. package/src/jobs/log-retention-and-broadcasts.ts +23 -0
  170. package/src/links/README.md +52 -0
  171. package/src/modules/README.md +99 -0
  172. package/src/modules/notifications/i18n/index.ts +83 -0
  173. package/src/modules/notifications/i18n/locales/ar.ts +84 -0
  174. package/src/modules/notifications/i18n/locales/de.ts +83 -0
  175. package/src/modules/notifications/i18n/locales/en.ts +84 -0
  176. package/src/modules/notifications/i18n/locales/es.ts +84 -0
  177. package/src/modules/notifications/i18n/locales/fr.ts +82 -0
  178. package/src/modules/notifications/i18n/locales/it.ts +82 -0
  179. package/src/modules/notifications/i18n/locales/nl.ts +83 -0
  180. package/src/modules/notifications/i18n/locales/pl.ts +84 -0
  181. package/src/modules/notifications/i18n/locales/pt.ts +82 -0
  182. package/src/modules/notifications/i18n/locales/tr.ts +86 -0
  183. package/src/modules/notifications/i18n/types.ts +1 -0
  184. package/src/modules/notifications/index.ts +10 -0
  185. package/src/modules/notifications/integrations/documents-and-b2b-resolver.ts +168 -0
  186. package/src/modules/notifications/migrations/Migration20261010000000.ts +185 -0
  187. package/src/modules/notifications/models/index.ts +125 -0
  188. package/src/modules/notifications/renderer/block-helpers.ts +51 -0
  189. package/src/modules/notifications/renderer/email.ts +281 -0
  190. package/src/modules/notifications/renderer/index.ts +301 -0
  191. package/src/modules/notifications/renderer/slack.ts +168 -0
  192. package/src/modules/notifications/renderer/telegram.ts +161 -0
  193. package/src/modules/notifications/renderer/whatsapp.ts +156 -0
  194. package/src/modules/notifications/service-helpers/channel-config.ts +65 -0
  195. package/src/modules/notifications/service-helpers/consent.ts +88 -0
  196. package/src/modules/notifications/service-helpers/delivery-log.ts +56 -0
  197. package/src/modules/notifications/service-helpers/event-conditions.ts +66 -0
  198. package/src/modules/notifications/service-helpers/external-templates.ts +127 -0
  199. package/src/modules/notifications/service-helpers/recipient-resolution.ts +124 -0
  200. package/src/modules/notifications/service-helpers/sender-profiles.ts +34 -0
  201. package/src/modules/notifications/service-helpers/template-blocks.ts +116 -0
  202. package/src/modules/notifications/service-helpers/template-catalog.ts +170 -0
  203. package/src/modules/notifications/service-helpers/template-render.ts +113 -0
  204. package/src/modules/notifications/service.ts +588 -0
  205. package/src/modules/notifications/types.ts +1 -0
  206. package/src/modules/notifications/utils/auth-presets.ts +145 -0
  207. package/src/modules/notifications/utils/interpolation.ts +231 -0
  208. package/src/modules/notifications/utils/security.ts +378 -0
  209. package/src/modules/notifications/utils/system-presets.ts +695 -0
  210. package/src/modules/notifications/utils/transformers.ts +456 -0
  211. package/src/providers/README.md +92 -0
  212. package/src/providers/dummy-sandbox/index.ts +143 -0
  213. package/src/providers/email-smtp/index.ts +257 -0
  214. package/src/providers/index.ts +38 -0
  215. package/src/providers/slack/index.ts +82 -0
  216. package/src/providers/sms/index.ts +342 -0
  217. package/src/providers/telegram/index.ts +181 -0
  218. package/src/providers/whatsapp/index.ts +505 -0
  219. package/src/rbac.ts +123 -0
  220. package/src/sdk/client.ts +319 -0
  221. package/src/sdk/index.ts +48 -0
  222. package/src/sdk/query-keys.ts +89 -0
  223. package/src/subscribers/README.md +50 -0
  224. package/src/subscribers/customer-and-document-events.ts +36 -0
  225. package/src/subscribers/fulfillment-and-inventory-events.ts +35 -0
  226. package/src/subscribers/order-events.ts +31 -0
  227. package/src/types/constants.ts +143 -0
  228. package/src/types/core.ts +96 -0
  229. package/src/types/domain.ts +84 -0
  230. package/src/types/enums.ts +73 -0
  231. package/src/types/errors.ts +32 -0
  232. package/src/types/hooks.ts +48 -0
  233. package/src/types/index.ts +11 -0
  234. package/src/types/providers.ts +96 -0
  235. package/src/types/records.ts +100 -0
  236. package/src/types/render.ts +74 -0
  237. package/src/types/sdk-api.ts +228 -0
  238. package/src/types/translations.ts +75 -0
  239. package/src/workflows/README.md +67 -0
  240. package/src/workflows/index.ts +619 -0
  241. package/tsconfig.json +40 -0
@@ -0,0 +1,113 @@
1
+ import type {
2
+ ContextType,
3
+ NotificationAttachment,
4
+ NotificationChannel,
5
+ NotificationsPluginOptions,
6
+ RenderedNotificationPayload,
7
+ RenderTemplateInput,
8
+ TemplateBlockNode,
9
+ SupportedLocale,
10
+ TemplateMode,
11
+ } from "../types"
12
+
13
+ export type RenderTemplateByIdParams = {
14
+ template_id: string
15
+ context_type?: ContextType
16
+ data?: Record<string, any>
17
+ locale?: string | null
18
+ subject?: string | null
19
+ variable_map_override?: Record<string, string> | null
20
+ telegram_thread_id?: number | null
21
+ attachments?: NotificationAttachment[]
22
+ append_sms_consent_footer?: boolean
23
+ }
24
+
25
+ /**
26
+ * Delegates to an external service's `render` callback for `external_*` templates
27
+ * that were not loaded as block templates. Returns `null` when none produces output.
28
+ */
29
+ export async function renderWithExternalService(
30
+ options: NotificationsPluginOptions,
31
+ params: { template_id: string; subject?: string | null },
32
+ contextData: Record<string, any>,
33
+ locale: SupportedLocale,
34
+ translations: Record<string, any>
35
+ ): Promise<RenderedNotificationPayload | null> {
36
+ const extServices = options.extend?.services || []
37
+ for (const svc of extServices) {
38
+ if (typeof svc.render !== "function") continue
39
+ const res = await svc.render({
40
+ templateId: params.template_id,
41
+ context: contextData,
42
+ locale,
43
+ translations,
44
+ subject: params.subject,
45
+ })
46
+ if (res && res.text) {
47
+ return {
48
+ channel: (svc.channel || "email") as NotificationChannel,
49
+ template_id: params.template_id,
50
+ template_name: params.template_id,
51
+ locale,
52
+ text: res.text,
53
+ ...res,
54
+ }
55
+ }
56
+ }
57
+ return null
58
+ }
59
+
60
+ /**
61
+ * Assembles the `renderNotificationTemplate` input from a resolved template and call params.
62
+ */
63
+ export function buildRenderInput(args: {
64
+ template: Record<string, any>
65
+ blocks: TemplateBlockNode[]
66
+ params: RenderTemplateByIdParams
67
+ options: NotificationsPluginOptions
68
+ locale: SupportedLocale
69
+ translations: Record<string, any>
70
+ contextData: Record<string, any>
71
+ }): RenderTemplateInput {
72
+ const {
73
+ template,
74
+ blocks,
75
+ params,
76
+ options,
77
+ locale,
78
+ translations,
79
+ contextData,
80
+ } = args
81
+ const mergedVariableMap = {
82
+ ...template.variable_map,
83
+ ...params.variable_map_override,
84
+ }
85
+
86
+ const effectiveSubject =
87
+ params.subject ??
88
+ template.subject ??
89
+ (translations.headerTitle || translations.general?.headerTitle
90
+ ? "{{translations.headerTitle}}"
91
+ : undefined)
92
+
93
+ return {
94
+ template_id: template.id,
95
+ template_name: template.name,
96
+ channel: template.channel as NotificationChannel,
97
+ mode: (template.mode || "blocks") as TemplateMode,
98
+ locale: params.locale || template.locale || locale,
99
+ subject: effectiveSubject,
100
+ raw_content: template.raw_content,
101
+ blocks,
102
+ variable_map: mergedVariableMap,
103
+ meta_template_name: template.meta_template_name,
104
+ meta_language_code: template.meta_language_code || locale,
105
+ styles: template.styles,
106
+ data: contextData,
107
+ translations,
108
+ pluginOptions: options,
109
+ attachments: params.attachments,
110
+ telegram_thread_id: params.telegram_thread_id,
111
+ append_sms_consent_footer: params.append_sms_consent_footer,
112
+ }
113
+ }
@@ -0,0 +1,588 @@
1
+ import { MedusaService } from "@medusajs/framework/utils"
2
+ import { getNotificationTranslations, normalizeLocale } from "./i18n"
3
+ import type { B2BNotificationContacts } from "./integrations/documents-and-b2b-resolver"
4
+ import {
5
+ MpnBroadcastCampaign,
6
+ MpnChannelConfig,
7
+ MpnConsentRecord,
8
+ MpnDeliveryLog,
9
+ MpnEventMapping,
10
+ MpnSandboxMessage,
11
+ MpnTemplate,
12
+ MpnTemplateBlock,
13
+ } from "./models"
14
+ import { renderNotificationTemplate } from "./renderer"
15
+ import {
16
+ buildDefaultChannelConfig,
17
+ mergeChannelConfigUpdate,
18
+ } from "./service-helpers/channel-config"
19
+ import {
20
+ evaluateConsent,
21
+ normalizeConsentIdentifier,
22
+ parseConsentKeyword,
23
+ } from "./service-helpers/consent"
24
+ import {
25
+ buildDeliveryLogRow,
26
+ type DeliveryLogParams,
27
+ } from "./service-helpers/delivery-log"
28
+ import { evaluateEventConditions } from "./service-helpers/event-conditions"
29
+ import {
30
+ loadExternalTemplates,
31
+ type LoadedExternalTemplate,
32
+ type ModuleLogger,
33
+ } from "./service-helpers/external-templates"
34
+ import { resolveRecipientForRule } from "./service-helpers/recipient-resolution"
35
+ import { resolveSenderProfiles } from "./service-helpers/sender-profiles"
36
+ import {
37
+ buildClonedTemplateRow,
38
+ createBlocksFromInput,
39
+ createPresetBlocks,
40
+ type BlockInput,
41
+ } from "./service-helpers/template-blocks"
42
+ import {
43
+ listExternalTemplates,
44
+ listSystemTemplates,
45
+ mergeTemplateTranslations,
46
+ resolveExternalTemplate,
47
+ resolveSystemPreset,
48
+ type TemplateListFilters,
49
+ } from "./service-helpers/template-catalog"
50
+ import {
51
+ buildRenderInput,
52
+ renderWithExternalService,
53
+ type RenderTemplateByIdParams,
54
+ } from "./service-helpers/template-render"
55
+ import type {
56
+ EventMappingCondition,
57
+ NotificationChannel,
58
+ NotificationsPluginOptions,
59
+ RecipientRule,
60
+ RenderedNotificationPayload,
61
+ SenderProfileConfig,
62
+ TemplateBlockNode,
63
+ } from "./types"
64
+ import {
65
+ buildIdempotencyKey,
66
+ ChannelRateLimiter,
67
+ extractOtpCode,
68
+ } from "./utils/security"
69
+ import {
70
+ buildBlockTreeFromFlatBlocks,
71
+ getSystemPresetById,
72
+ } from "./utils/system-presets"
73
+ import { getMockContextByType } from "./utils/transformers"
74
+
75
+ type InjectedDependencies = {
76
+ logger?: ModuleLogger
77
+ [key: string]: unknown
78
+ }
79
+
80
+ export class NotificationsModuleService extends MedusaService({
81
+ MpnTemplate,
82
+ MpnTemplateBlock,
83
+ MpnEventMapping,
84
+ MpnDeliveryLog,
85
+ MpnConsentRecord,
86
+ MpnBroadcastCampaign,
87
+ MpnChannelConfig,
88
+ MpnSandboxMessage,
89
+ }) {
90
+ protected readonly options_: NotificationsPluginOptions
91
+ protected readonly logger_?: InjectedDependencies["logger"]
92
+ protected readonly externalTemplates_: Map<string, LoadedExternalTemplate>
93
+ public readonly rateLimiter: ChannelRateLimiter
94
+
95
+ constructor(
96
+ container: InjectedDependencies,
97
+ options?: NotificationsPluginOptions
98
+ ) {
99
+ super(...arguments)
100
+ this.options_ = options ?? {}
101
+ this.logger_ = container?.logger
102
+ this.rateLimiter = new ChannelRateLimiter()
103
+ this.externalTemplates_ = loadExternalTemplates(this.options_, this.logger_)
104
+ }
105
+
106
+ // eslint-disable-next-line @medusajs/service-methods-must-be-async -- pure synchronous helper
107
+ getPluginOptions(): NotificationsPluginOptions {
108
+ return this.options_
109
+ }
110
+
111
+ // eslint-disable-next-line @medusajs/service-methods-must-be-async -- pure synchronous helper
112
+ getSenderProfiles(): SenderProfileConfig[] {
113
+ return resolveSenderProfiles(this.options_)
114
+ }
115
+
116
+ /**
117
+ * Lists all templates across System Presets (`system_*`), External Services (`external_*`), and Database (`mpntpl_*`).
118
+ */
119
+ async listAllTemplates(
120
+ filters?: TemplateListFilters
121
+ ): Promise<Array<Record<string, any>>> {
122
+ const results: Array<Record<string, any>> = []
123
+
124
+ if (!filters?.source || filters.source === "system") {
125
+ results.push(...listSystemTemplates(filters))
126
+ }
127
+
128
+ if (!filters?.source || filters.source === "external") {
129
+ results.push(
130
+ ...listExternalTemplates(
131
+ this.externalTemplates_,
132
+ this.options_,
133
+ filters
134
+ )
135
+ )
136
+ }
137
+
138
+ if (!filters?.source || filters.source === "db") {
139
+ const dbQuery: Record<string, any> = {}
140
+ if (filters?.channel) dbQuery.channel = filters.channel
141
+ if (filters?.locale) dbQuery.locale = filters.locale
142
+ const dbTemplates = await this.listMpnTemplates(dbQuery)
143
+ for (const t of dbTemplates) {
144
+ const blocks = await this.listMpnTemplateBlocks({ template_id: t.id })
145
+ results.push({
146
+ ...t,
147
+ source: "db",
148
+ blocks_count: blocks.length,
149
+ })
150
+ }
151
+ }
152
+
153
+ return results
154
+ }
155
+
156
+ /**
157
+ * Retrieves a single template (System Preset, External Template, or DB Template) with its hierarchical block tree.
158
+ */
159
+ async getTemplateWithBlocks(templateId: string): Promise<{
160
+ template: Record<string, any>
161
+ blocks: TemplateBlockNode[]
162
+ flatBlocks: Array<Record<string, any>>
163
+ } | null> {
164
+ if (!templateId) return null
165
+
166
+ const extTpl = this.externalTemplates_.get(templateId)
167
+ if (extTpl) return resolveExternalTemplate(extTpl)
168
+
169
+ const preset = getSystemPresetById(templateId)
170
+ if (preset) return resolveSystemPreset(preset)
171
+
172
+ const dbList = await this.listMpnTemplates({ id: templateId })
173
+ if (dbList.length === 0) {
174
+ const byName = await this.listMpnTemplates({ name: templateId })
175
+ if (byName.length === 0) return null
176
+ dbList.push(byName[0])
177
+ }
178
+
179
+ const tpl = dbList[0]
180
+ const flatBlocks = await this.listMpnTemplateBlocks({
181
+ template_id: tpl.id,
182
+ })
183
+ return {
184
+ template: { ...tpl, source: "db" },
185
+ blocks: buildBlockTreeFromFlatBlocks(flatBlocks as any),
186
+ flatBlocks,
187
+ }
188
+ }
189
+
190
+ /**
191
+ * 1-Click Clone: Copies a read-only `system_*` preset and its hierarchical block tree
192
+ * into editable `mpn_template` + `mpn_template_block` database rows.
193
+ */
194
+ async cloneSystemPresetToDb(
195
+ presetId: string,
196
+ overrides?: {
197
+ name?: string
198
+ label?: string
199
+ locale?: string
200
+ }
201
+ ): Promise<{
202
+ template: Record<string, any>
203
+ blocks: TemplateBlockNode[]
204
+ }> {
205
+ const preset = getSystemPresetById(presetId)
206
+ if (!preset) {
207
+ throw new Error(`System preset '${presetId}' not found`)
208
+ }
209
+
210
+ const createdTemplate = await this.createMpnTemplates(
211
+ buildClonedTemplateRow(preset, overrides)
212
+ )
213
+ const createdBlocks = await createPresetBlocks(
214
+ (data) => this.createMpnTemplateBlocks(data),
215
+ createdTemplate.id,
216
+ preset.blocks
217
+ )
218
+
219
+ return {
220
+ template: { ...createdTemplate, source: "db" },
221
+ blocks: buildBlockTreeFromFlatBlocks(createdBlocks as any),
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Replaces all blocks for an editable DB template with a new list of blocks.
227
+ */
228
+ async replaceTemplateBlocks(
229
+ templateId: string,
230
+ blocks: BlockInput[]
231
+ ): Promise<TemplateBlockNode[]> {
232
+ const existing = await this.listMpnTemplateBlocks({
233
+ template_id: templateId,
234
+ })
235
+ if (existing.length > 0) {
236
+ await this.deleteMpnTemplateBlocks(existing.map((b: any) => b.id))
237
+ }
238
+
239
+ const created = await createBlocksFromInput(
240
+ (data) => this.createMpnTemplateBlocks(data),
241
+ templateId,
242
+ blocks
243
+ )
244
+ return buildBlockTreeFromFlatBlocks(created as any)
245
+ }
246
+
247
+ /**
248
+ * Renders any System, External, or DB template by ID against either provided entity data
249
+ * or a mock context for `contextType`.
250
+ */
251
+ async renderTemplateById(
252
+ params: RenderTemplateByIdParams
253
+ ): Promise<RenderedNotificationPayload> {
254
+ const locale = normalizeLocale(
255
+ params.locale || this.options_.defaultLocale || "en"
256
+ )
257
+ const baseTranslations = getNotificationTranslations(
258
+ locale,
259
+ this.options_.customTranslations
260
+ )
261
+
262
+ const contextData =
263
+ params.data ||
264
+ getMockContextByType(
265
+ params.context_type || "order",
266
+ this.options_,
267
+ locale
268
+ )
269
+
270
+ // Check external template service `render` callback first if prefixed with `external_` and not in `externalTemplates_`
271
+ if (
272
+ params.template_id.startsWith("external_") &&
273
+ !this.externalTemplates_.has(params.template_id)
274
+ ) {
275
+ const external = await renderWithExternalService(
276
+ this.options_,
277
+ params,
278
+ contextData,
279
+ locale,
280
+ baseTranslations
281
+ )
282
+ if (external) return external
283
+ }
284
+
285
+ const resolved = await this.getTemplateWithBlocks(params.template_id)
286
+ if (!resolved) {
287
+ throw new Error(`Template '${params.template_id}' not found`)
288
+ }
289
+
290
+ const { template, blocks } = resolved
291
+
292
+ // Merge external template module translations (fallback to `en`) if provided
293
+ const translations = mergeTemplateTranslations(
294
+ baseTranslations,
295
+ template.translations,
296
+ locale
297
+ )
298
+
299
+ return renderNotificationTemplate(
300
+ buildRenderInput({
301
+ template,
302
+ blocks,
303
+ params,
304
+ options: this.options_,
305
+ locale,
306
+ translations,
307
+ contextData,
308
+ })
309
+ )
310
+ }
311
+
312
+ // eslint-disable-next-line @medusajs/service-methods-must-be-async -- pure synchronous helper
313
+ evaluateEventConditions(
314
+ conditions: EventMappingCondition | null | undefined,
315
+ data: Record<string, any>
316
+ ): boolean {
317
+ return evaluateEventConditions(conditions, data)
318
+ }
319
+
320
+ // eslint-disable-next-line @medusajs/service-methods-must-be-async -- pure synchronous helper
321
+ resolveRecipientForRule(params: {
322
+ rule: RecipientRule | string
323
+ custom_recipient?: string | null
324
+ channel: NotificationChannel
325
+ data: Record<string, any>
326
+ b2b_contacts?: B2BNotificationContacts
327
+ channel_config?: Record<string, any> | null
328
+ }): string | null {
329
+ return resolveRecipientForRule(params)
330
+ }
331
+
332
+ /**
333
+ * TCPA / 10DLC / WhatsApp / Telegram Consent Ledger Manager.
334
+ * Supports `JOIN` / `START` opt-ins and `STOP` / `UNSUBSCRIBE` / `CANCEL` / `END` / `QUIT` opt-outs.
335
+ */
336
+ async upsertConsent(params: {
337
+ identifier: string
338
+ channel: "sms" | "whatsapp" | "telegram"
339
+ customer_id?: string | null
340
+ action: "opt_in" | "opt_out"
341
+ source?: string
342
+ metadata?: Record<string, any>
343
+ }): Promise<Record<string, any>> {
344
+ const cleanId = normalizeConsentIdentifier(
345
+ params.channel,
346
+ params.identifier
347
+ )
348
+ const existing = await this.listMpnConsentRecords({
349
+ identifier: cleanId,
350
+ channel: params.channel,
351
+ })
352
+
353
+ const now = new Date()
354
+ if (existing.length > 0) {
355
+ const current = existing[0]
356
+ return await this.updateMpnConsentRecords({
357
+ id: current.id,
358
+ customer_id: params.customer_id ?? current.customer_id,
359
+ status: params.action === "opt_in" ? "opted_in" : "opted_out",
360
+ source: params.source || current.source,
361
+ opted_in_at: params.action === "opt_in" ? now : current.opted_in_at,
362
+ opted_out_at: params.action === "opt_out" ? now : current.opted_out_at,
363
+ metadata: {
364
+ ...current.metadata,
365
+ ...params.metadata,
366
+ },
367
+ })
368
+ }
369
+
370
+ return await this.createMpnConsentRecords({
371
+ identifier: cleanId,
372
+ channel: params.channel,
373
+ customer_id: params.customer_id ?? null,
374
+ status: params.action === "opt_in" ? "opted_in" : "opted_out",
375
+ source: params.source || "checkout",
376
+ first_message_sent: false,
377
+ opted_in_at: params.action === "opt_in" ? now : null,
378
+ opted_out_at: params.action === "opt_out" ? now : null,
379
+ metadata: params.metadata ?? null,
380
+ })
381
+ }
382
+
383
+ /**
384
+ * Parses an inbound SMS/WhatsApp keyword reply (`JOIN`, `START`, `YES` vs `STOP`, `END`, `QUIT`, `CANCEL`, `UNSUBSCRIBE`)
385
+ * and updates the consent ledger accordingly.
386
+ */
387
+ async processInboundConsentKeyword(params: {
388
+ from: string
389
+ body: string
390
+ channel?: "sms" | "whatsapp"
391
+ }): Promise<{
392
+ handled: boolean
393
+ action?: "opt_in" | "opt_out"
394
+ record?: Record<string, any>
395
+ autoReplyText?: string
396
+ }> {
397
+ const action = parseConsentKeyword(params.body)
398
+ if (!action) return { handled: false }
399
+
400
+ const channel = params.channel || "sms"
401
+ const record = await this.upsertConsent({
402
+ identifier: params.from,
403
+ channel,
404
+ action,
405
+ source: action === "opt_in" ? "webhook_join" : "webhook_stop",
406
+ })
407
+
408
+ if (action === "opt_out") {
409
+ return { handled: true, action, record }
410
+ }
411
+
412
+ const storeName =
413
+ this.options_.storeName || process.env.STORE_NAME || "Medusa Store"
414
+ return {
415
+ handled: true,
416
+ action,
417
+ record,
418
+ autoReplyText: `${storeName}: You are now opted in to receive notifications. Reply STOP at any time to opt out.`,
419
+ }
420
+ }
421
+
422
+ /**
423
+ * Checks whether sending is permitted for a recipient on SMS/WhatsApp based on consent state,
424
+ * and indicates whether the `"Reply STOP to opt out."` footer should be appended.
425
+ */
426
+ async verifyRecipientConsent(params: {
427
+ recipient: string
428
+ channel: NotificationChannel
429
+ requireExplicitOptIn?: boolean
430
+ }): Promise<{
431
+ allowed: boolean
432
+ reason?: string
433
+ appendStopFooter: boolean
434
+ consentRecordId?: string
435
+ }> {
436
+ if (params.channel !== "sms" && params.channel !== "whatsapp") {
437
+ return { allowed: true, appendStopFooter: false }
438
+ }
439
+
440
+ const cleanId = normalizeConsentIdentifier(params.channel, params.recipient)
441
+ const records = await this.listMpnConsentRecords({
442
+ identifier: cleanId,
443
+ channel: params.channel,
444
+ })
445
+ return evaluateConsent(records, params, this.options_)
446
+ }
447
+
448
+ /**
449
+ * Checks idempotency for `(event_name, entity_id, channel, template_id, recipient)`.
450
+ * Returns `{ duplicate: true, existingLog }` if already `pending`, `sent`, or `delivered`.
451
+ */
452
+ async checkIdempotency(params: {
453
+ event_name: string
454
+ entity_id?: string | null
455
+ channel: NotificationChannel
456
+ template_id: string
457
+ recipient: string
458
+ }): Promise<{
459
+ idempotencyKey: string
460
+ duplicate: boolean
461
+ existingLog?: Record<string, any>
462
+ }> {
463
+ const idempotencyKey = buildIdempotencyKey(params)
464
+ const existing = await this.listMpnDeliveryLogs({
465
+ idempotency_key: idempotencyKey,
466
+ })
467
+
468
+ const activeMatch = existing.find((row: any) =>
469
+ ["pending", "sent", "delivered"].includes(row.status)
470
+ )
471
+
472
+ return {
473
+ idempotencyKey,
474
+ duplicate: Boolean(activeMatch),
475
+ existingLog: activeMatch,
476
+ }
477
+ }
478
+
479
+ /**
480
+ * Records a delivery log entry with masked PII and redacted payload.
481
+ */
482
+ async recordDeliveryLog(
483
+ params: DeliveryLogParams
484
+ ): Promise<Record<string, any>> {
485
+ return await this.createMpnDeliveryLogs(buildDeliveryLogRow(params))
486
+ }
487
+
488
+ /**
489
+ * Captures a message in the Dummy Sandbox table (`mpn_sandbox_message`) and extracts any OTP code.
490
+ */
491
+ async captureSandboxMessage(params: {
492
+ channel: NotificationChannel
493
+ recipient: string
494
+ sender?: string | null
495
+ subject?: string | null
496
+ body: string
497
+ html?: string | null
498
+ media_urls?: string[] | null
499
+ attachments_meta?: Array<Record<string, any>> | null
500
+ metadata?: Record<string, any> | null
501
+ }): Promise<Record<string, any>> {
502
+ const otpCode =
503
+ extractOtpCode(params.body) || extractOtpCode(params.subject)
504
+ return await this.createMpnSandboxMessages({
505
+ channel: params.channel,
506
+ recipient: params.recipient,
507
+ sender: params.sender ?? null,
508
+ subject: params.subject ?? null,
509
+ body: params.body,
510
+ html: params.html ?? null,
511
+ otp_code: otpCode,
512
+ media_urls: (params.media_urls as any) ?? null,
513
+ attachments_meta: (params.attachments_meta as any) ?? null,
514
+ metadata: params.metadata ?? null,
515
+ })
516
+ }
517
+
518
+ /**
519
+ * Retrieves or initializes non-secret operational configuration for a channel.
520
+ */
521
+ async getOrCreateChannelConfig(
522
+ channel: NotificationChannel,
523
+ defaultDriver = "default"
524
+ ): Promise<Record<string, any>> {
525
+ const existing = await this.listMpnChannelConfigs({ channel })
526
+ if (existing.length > 0) {
527
+ return existing[0]
528
+ }
529
+ return await this.createMpnChannelConfigs(
530
+ buildDefaultChannelConfig(channel, defaultDriver)
531
+ )
532
+ }
533
+
534
+ /**
535
+ * Updates non-secret operational configuration for a channel.
536
+ */
537
+ async saveChannelConfig(params: {
538
+ channel: NotificationChannel
539
+ driver?: string
540
+ is_enabled?: boolean
541
+ is_verified?: boolean
542
+ rate_limit_per_sec?: number
543
+ config_json?: Record<string, any>
544
+ }): Promise<Record<string, any>> {
545
+ const current = await this.getOrCreateChannelConfig(
546
+ params.channel,
547
+ params.driver || "default"
548
+ )
549
+ const { nextConfigJson, isVerified } = mergeChannelConfigUpdate(
550
+ current,
551
+ params
552
+ )
553
+
554
+ return await this.updateMpnChannelConfigs({
555
+ id: current.id,
556
+ driver: params.driver ?? current.driver,
557
+ is_enabled: params.is_enabled ?? current.is_enabled,
558
+ is_verified: isVerified,
559
+ verified_at: isVerified ? new Date() : current.verified_at,
560
+ rate_limit_per_sec:
561
+ params.rate_limit_per_sec ?? current.rate_limit_per_sec,
562
+ config_json: nextConfigJson,
563
+ })
564
+ }
565
+
566
+ /**
567
+ * Deletes delivery logs older than `retentionDays` (default 30 days).
568
+ */
569
+ async pruneExpiredDeliveryLogs(retentionDays?: number): Promise<number> {
570
+ const days =
571
+ retentionDays ??
572
+ this.options_.logRetentionDays ??
573
+ Number(process.env.WHATSAPP_LOG_RETENTION_DAYS || 30)
574
+ const cutoff = new Date(Date.now() - Math.max(1, days) * 86400 * 1000)
575
+
576
+ const allLogs = await this.listMpnDeliveryLogs({})
577
+ const expiredIds = allLogs
578
+ .filter((row: any) => row.created_at && new Date(row.created_at) < cutoff)
579
+ .map((row: any) => row.id)
580
+
581
+ if (expiredIds.length > 0) {
582
+ await this.deleteMpnDeliveryLogs(expiredIds)
583
+ }
584
+ return expiredIds.length
585
+ }
586
+ }
587
+
588
+ export default NotificationsModuleService
@@ -0,0 +1 @@
1
+ export * from "../../types"