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

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 +340 -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 +133 -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 +589 -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,589 @@
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
+ // eslint-disable-next-line prefer-rest-params
100
+ super(...arguments)
101
+ this.options_ = options ?? {}
102
+ this.logger_ = container?.logger
103
+ this.rateLimiter = new ChannelRateLimiter()
104
+ this.externalTemplates_ = loadExternalTemplates(this.options_, this.logger_)
105
+ }
106
+
107
+ // eslint-disable-next-line @medusajs/service-methods-must-be-async -- pure synchronous helper
108
+ getPluginOptions(): NotificationsPluginOptions {
109
+ return this.options_
110
+ }
111
+
112
+ // eslint-disable-next-line @medusajs/service-methods-must-be-async -- pure synchronous helper
113
+ getSenderProfiles(): SenderProfileConfig[] {
114
+ return resolveSenderProfiles(this.options_)
115
+ }
116
+
117
+ /**
118
+ * Lists all templates across System Presets (`system_*`), External Services (`external_*`), and Database (`mpntpl_*`).
119
+ */
120
+ async listAllTemplates(
121
+ filters?: TemplateListFilters
122
+ ): Promise<Array<Record<string, any>>> {
123
+ const results: Array<Record<string, any>> = []
124
+
125
+ if (!filters?.source || filters.source === "system") {
126
+ results.push(...listSystemTemplates(filters))
127
+ }
128
+
129
+ if (!filters?.source || filters.source === "external") {
130
+ results.push(
131
+ ...listExternalTemplates(
132
+ this.externalTemplates_,
133
+ this.options_,
134
+ filters
135
+ )
136
+ )
137
+ }
138
+
139
+ if (!filters?.source || filters.source === "db") {
140
+ const dbQuery: Record<string, any> = {}
141
+ if (filters?.channel) dbQuery.channel = filters.channel
142
+ if (filters?.locale) dbQuery.locale = filters.locale
143
+ const dbTemplates = await this.listMpnTemplates(dbQuery)
144
+ for (const t of dbTemplates) {
145
+ const blocks = await this.listMpnTemplateBlocks({ template_id: t.id })
146
+ results.push({
147
+ ...t,
148
+ source: "db",
149
+ blocks_count: blocks.length,
150
+ })
151
+ }
152
+ }
153
+
154
+ return results
155
+ }
156
+
157
+ /**
158
+ * Retrieves a single template (System Preset, External Template, or DB Template) with its hierarchical block tree.
159
+ */
160
+ async getTemplateWithBlocks(templateId: string): Promise<{
161
+ template: Record<string, any>
162
+ blocks: TemplateBlockNode[]
163
+ flatBlocks: Array<Record<string, any>>
164
+ } | null> {
165
+ if (!templateId) return null
166
+
167
+ const extTpl = this.externalTemplates_.get(templateId)
168
+ if (extTpl) return resolveExternalTemplate(extTpl)
169
+
170
+ const preset = getSystemPresetById(templateId)
171
+ if (preset) return resolveSystemPreset(preset)
172
+
173
+ const dbList = await this.listMpnTemplates({ id: templateId })
174
+ if (dbList.length === 0) {
175
+ const byName = await this.listMpnTemplates({ name: templateId })
176
+ if (byName.length === 0) return null
177
+ dbList.push(byName[0])
178
+ }
179
+
180
+ const tpl = dbList[0]
181
+ const flatBlocks = await this.listMpnTemplateBlocks({
182
+ template_id: tpl.id,
183
+ })
184
+ return {
185
+ template: { ...tpl, source: "db" },
186
+ blocks: buildBlockTreeFromFlatBlocks(flatBlocks as any),
187
+ flatBlocks,
188
+ }
189
+ }
190
+
191
+ /**
192
+ * 1-Click Clone: Copies a read-only `system_*` preset and its hierarchical block tree
193
+ * into editable `mpn_template` + `mpn_template_block` database rows.
194
+ */
195
+ async cloneSystemPresetToDb(
196
+ presetId: string,
197
+ overrides?: {
198
+ name?: string
199
+ label?: string
200
+ locale?: string
201
+ }
202
+ ): Promise<{
203
+ template: Record<string, any>
204
+ blocks: TemplateBlockNode[]
205
+ }> {
206
+ const preset = getSystemPresetById(presetId)
207
+ if (!preset) {
208
+ throw new Error(`System preset '${presetId}' not found`)
209
+ }
210
+
211
+ const createdTemplate = await this.createMpnTemplates(
212
+ buildClonedTemplateRow(preset, overrides)
213
+ )
214
+ const createdBlocks = await createPresetBlocks(
215
+ (data) => this.createMpnTemplateBlocks(data),
216
+ createdTemplate.id,
217
+ preset.blocks
218
+ )
219
+
220
+ return {
221
+ template: { ...createdTemplate, source: "db" },
222
+ blocks: buildBlockTreeFromFlatBlocks(createdBlocks as any),
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Replaces all blocks for an editable DB template with a new list of blocks.
228
+ */
229
+ async replaceTemplateBlocks(
230
+ templateId: string,
231
+ blocks: BlockInput[]
232
+ ): Promise<TemplateBlockNode[]> {
233
+ const existing = await this.listMpnTemplateBlocks({
234
+ template_id: templateId,
235
+ })
236
+ if (existing.length > 0) {
237
+ await this.deleteMpnTemplateBlocks(existing.map((b: any) => b.id))
238
+ }
239
+
240
+ const created = await createBlocksFromInput(
241
+ (data) => this.createMpnTemplateBlocks(data),
242
+ templateId,
243
+ blocks
244
+ )
245
+ return buildBlockTreeFromFlatBlocks(created as any)
246
+ }
247
+
248
+ /**
249
+ * Renders any System, External, or DB template by ID against either provided entity data
250
+ * or a mock context for `contextType`.
251
+ */
252
+ async renderTemplateById(
253
+ params: RenderTemplateByIdParams
254
+ ): Promise<RenderedNotificationPayload> {
255
+ const locale = normalizeLocale(
256
+ params.locale || this.options_.defaultLocale || "en"
257
+ )
258
+ const baseTranslations = getNotificationTranslations(
259
+ locale,
260
+ this.options_.customTranslations
261
+ )
262
+
263
+ const contextData =
264
+ params.data ||
265
+ getMockContextByType(
266
+ params.context_type || "order",
267
+ this.options_,
268
+ locale
269
+ )
270
+
271
+ // Check external template service `render` callback first if prefixed with `external_` and not in `externalTemplates_`
272
+ if (
273
+ params.template_id.startsWith("external_") &&
274
+ !this.externalTemplates_.has(params.template_id)
275
+ ) {
276
+ const external = await renderWithExternalService(
277
+ this.options_,
278
+ params,
279
+ contextData,
280
+ locale,
281
+ baseTranslations
282
+ )
283
+ if (external) return external
284
+ }
285
+
286
+ const resolved = await this.getTemplateWithBlocks(params.template_id)
287
+ if (!resolved) {
288
+ throw new Error(`Template '${params.template_id}' not found`)
289
+ }
290
+
291
+ const { template, blocks } = resolved
292
+
293
+ // Merge external template module translations (fallback to `en`) if provided
294
+ const translations = mergeTemplateTranslations(
295
+ baseTranslations,
296
+ template.translations,
297
+ locale
298
+ )
299
+
300
+ return renderNotificationTemplate(
301
+ buildRenderInput({
302
+ template,
303
+ blocks,
304
+ params,
305
+ options: this.options_,
306
+ locale,
307
+ translations,
308
+ contextData,
309
+ })
310
+ )
311
+ }
312
+
313
+ // eslint-disable-next-line @medusajs/service-methods-must-be-async -- pure synchronous helper
314
+ evaluateEventConditions(
315
+ conditions: EventMappingCondition | null | undefined,
316
+ data: Record<string, any>
317
+ ): boolean {
318
+ return evaluateEventConditions(conditions, data)
319
+ }
320
+
321
+ // eslint-disable-next-line @medusajs/service-methods-must-be-async -- pure synchronous helper
322
+ resolveRecipientForRule(params: {
323
+ rule: RecipientRule | string
324
+ custom_recipient?: string | null
325
+ channel: NotificationChannel
326
+ data: Record<string, any>
327
+ b2b_contacts?: B2BNotificationContacts
328
+ channel_config?: Record<string, any> | null
329
+ }): string | null {
330
+ return resolveRecipientForRule(params)
331
+ }
332
+
333
+ /**
334
+ * TCPA / 10DLC / WhatsApp / Telegram Consent Ledger Manager.
335
+ * Supports `JOIN` / `START` opt-ins and `STOP` / `UNSUBSCRIBE` / `CANCEL` / `END` / `QUIT` opt-outs.
336
+ */
337
+ async upsertConsent(params: {
338
+ identifier: string
339
+ channel: "sms" | "whatsapp" | "telegram"
340
+ customer_id?: string | null
341
+ action: "opt_in" | "opt_out"
342
+ source?: string
343
+ metadata?: Record<string, any>
344
+ }): Promise<Record<string, any>> {
345
+ const cleanId = normalizeConsentIdentifier(
346
+ params.channel,
347
+ params.identifier
348
+ )
349
+ const existing = await this.listMpnConsentRecords({
350
+ identifier: cleanId,
351
+ channel: params.channel,
352
+ })
353
+
354
+ const now = new Date()
355
+ if (existing.length > 0) {
356
+ const current = existing[0]
357
+ return await this.updateMpnConsentRecords({
358
+ id: current.id,
359
+ customer_id: params.customer_id ?? current.customer_id,
360
+ status: params.action === "opt_in" ? "opted_in" : "opted_out",
361
+ source: params.source || current.source,
362
+ opted_in_at: params.action === "opt_in" ? now : current.opted_in_at,
363
+ opted_out_at: params.action === "opt_out" ? now : current.opted_out_at,
364
+ metadata: {
365
+ ...current.metadata,
366
+ ...params.metadata,
367
+ },
368
+ })
369
+ }
370
+
371
+ return await this.createMpnConsentRecords({
372
+ identifier: cleanId,
373
+ channel: params.channel,
374
+ customer_id: params.customer_id ?? null,
375
+ status: params.action === "opt_in" ? "opted_in" : "opted_out",
376
+ source: params.source || "checkout",
377
+ first_message_sent: false,
378
+ opted_in_at: params.action === "opt_in" ? now : null,
379
+ opted_out_at: params.action === "opt_out" ? now : null,
380
+ metadata: params.metadata ?? null,
381
+ })
382
+ }
383
+
384
+ /**
385
+ * Parses an inbound SMS/WhatsApp keyword reply (`JOIN`, `START`, `YES` vs `STOP`, `END`, `QUIT`, `CANCEL`, `UNSUBSCRIBE`)
386
+ * and updates the consent ledger accordingly.
387
+ */
388
+ async processInboundConsentKeyword(params: {
389
+ from: string
390
+ body: string
391
+ channel?: "sms" | "whatsapp"
392
+ }): Promise<{
393
+ handled: boolean
394
+ action?: "opt_in" | "opt_out"
395
+ record?: Record<string, any>
396
+ autoReplyText?: string
397
+ }> {
398
+ const action = parseConsentKeyword(params.body)
399
+ if (!action) return { handled: false }
400
+
401
+ const channel = params.channel || "sms"
402
+ const record = await this.upsertConsent({
403
+ identifier: params.from,
404
+ channel,
405
+ action,
406
+ source: action === "opt_in" ? "webhook_join" : "webhook_stop",
407
+ })
408
+
409
+ if (action === "opt_out") {
410
+ return { handled: true, action, record }
411
+ }
412
+
413
+ const storeName =
414
+ this.options_.storeName || process.env.STORE_NAME || "Medusa Store"
415
+ return {
416
+ handled: true,
417
+ action,
418
+ record,
419
+ autoReplyText: `${storeName}: You are now opted in to receive notifications. Reply STOP at any time to opt out.`,
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Checks whether sending is permitted for a recipient on SMS/WhatsApp based on consent state,
425
+ * and indicates whether the `"Reply STOP to opt out."` footer should be appended.
426
+ */
427
+ async verifyRecipientConsent(params: {
428
+ recipient: string
429
+ channel: NotificationChannel
430
+ requireExplicitOptIn?: boolean
431
+ }): Promise<{
432
+ allowed: boolean
433
+ reason?: string
434
+ appendStopFooter: boolean
435
+ consentRecordId?: string
436
+ }> {
437
+ if (params.channel !== "sms" && params.channel !== "whatsapp") {
438
+ return { allowed: true, appendStopFooter: false }
439
+ }
440
+
441
+ const cleanId = normalizeConsentIdentifier(params.channel, params.recipient)
442
+ const records = await this.listMpnConsentRecords({
443
+ identifier: cleanId,
444
+ channel: params.channel,
445
+ })
446
+ return evaluateConsent(records, params, this.options_)
447
+ }
448
+
449
+ /**
450
+ * Checks idempotency for `(event_name, entity_id, channel, template_id, recipient)`.
451
+ * Returns `{ duplicate: true, existingLog }` if already `pending`, `sent`, or `delivered`.
452
+ */
453
+ async checkIdempotency(params: {
454
+ event_name: string
455
+ entity_id?: string | null
456
+ channel: NotificationChannel
457
+ template_id: string
458
+ recipient: string
459
+ }): Promise<{
460
+ idempotencyKey: string
461
+ duplicate: boolean
462
+ existingLog?: Record<string, any>
463
+ }> {
464
+ const idempotencyKey = buildIdempotencyKey(params)
465
+ const existing = await this.listMpnDeliveryLogs({
466
+ idempotency_key: idempotencyKey,
467
+ })
468
+
469
+ const activeMatch = existing.find((row: any) =>
470
+ ["pending", "sent", "delivered"].includes(row.status)
471
+ )
472
+
473
+ return {
474
+ idempotencyKey,
475
+ duplicate: Boolean(activeMatch),
476
+ existingLog: activeMatch,
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Records a delivery log entry with masked PII and redacted payload.
482
+ */
483
+ async recordDeliveryLog(
484
+ params: DeliveryLogParams
485
+ ): Promise<Record<string, any>> {
486
+ return await this.createMpnDeliveryLogs(buildDeliveryLogRow(params))
487
+ }
488
+
489
+ /**
490
+ * Captures a message in the Dummy Sandbox table (`mpn_sandbox_message`) and extracts any OTP code.
491
+ */
492
+ async captureSandboxMessage(params: {
493
+ channel: NotificationChannel
494
+ recipient: string
495
+ sender?: string | null
496
+ subject?: string | null
497
+ body: string
498
+ html?: string | null
499
+ media_urls?: string[] | null
500
+ attachments_meta?: Array<Record<string, any>> | null
501
+ metadata?: Record<string, any> | null
502
+ }): Promise<Record<string, any>> {
503
+ const otpCode =
504
+ extractOtpCode(params.body) || extractOtpCode(params.subject)
505
+ return await this.createMpnSandboxMessages({
506
+ channel: params.channel,
507
+ recipient: params.recipient,
508
+ sender: params.sender ?? null,
509
+ subject: params.subject ?? null,
510
+ body: params.body,
511
+ html: params.html ?? null,
512
+ otp_code: otpCode,
513
+ media_urls: (params.media_urls as any) ?? null,
514
+ attachments_meta: (params.attachments_meta as any) ?? null,
515
+ metadata: params.metadata ?? null,
516
+ })
517
+ }
518
+
519
+ /**
520
+ * Retrieves or initializes non-secret operational configuration for a channel.
521
+ */
522
+ async getOrCreateChannelConfig(
523
+ channel: NotificationChannel,
524
+ defaultDriver = "default"
525
+ ): Promise<Record<string, any>> {
526
+ const existing = await this.listMpnChannelConfigs({ channel })
527
+ if (existing.length > 0) {
528
+ return existing[0]
529
+ }
530
+ return await this.createMpnChannelConfigs(
531
+ buildDefaultChannelConfig(channel, defaultDriver)
532
+ )
533
+ }
534
+
535
+ /**
536
+ * Updates non-secret operational configuration for a channel.
537
+ */
538
+ async saveChannelConfig(params: {
539
+ channel: NotificationChannel
540
+ driver?: string
541
+ is_enabled?: boolean
542
+ is_verified?: boolean
543
+ rate_limit_per_sec?: number
544
+ config_json?: Record<string, any>
545
+ }): Promise<Record<string, any>> {
546
+ const current = await this.getOrCreateChannelConfig(
547
+ params.channel,
548
+ params.driver || "default"
549
+ )
550
+ const { nextConfigJson, isVerified } = mergeChannelConfigUpdate(
551
+ current,
552
+ params
553
+ )
554
+
555
+ return await this.updateMpnChannelConfigs({
556
+ id: current.id,
557
+ driver: params.driver ?? current.driver,
558
+ is_enabled: params.is_enabled ?? current.is_enabled,
559
+ is_verified: isVerified,
560
+ verified_at: isVerified ? new Date() : current.verified_at,
561
+ rate_limit_per_sec:
562
+ params.rate_limit_per_sec ?? current.rate_limit_per_sec,
563
+ config_json: nextConfigJson,
564
+ })
565
+ }
566
+
567
+ /**
568
+ * Deletes delivery logs older than `retentionDays` (default 30 days).
569
+ */
570
+ async pruneExpiredDeliveryLogs(retentionDays?: number): Promise<number> {
571
+ const days =
572
+ retentionDays ??
573
+ this.options_.logRetentionDays ??
574
+ Number(process.env.WHATSAPP_LOG_RETENTION_DAYS || 30)
575
+ const cutoff = new Date(Date.now() - Math.max(1, days) * 86400 * 1000)
576
+
577
+ const allLogs = await this.listMpnDeliveryLogs({})
578
+ const expiredIds = allLogs
579
+ .filter((row: any) => row.created_at && new Date(row.created_at) < cutoff)
580
+ .map((row: any) => row.id)
581
+
582
+ if (expiredIds.length > 0) {
583
+ await this.deleteMpnDeliveryLogs(expiredIds)
584
+ }
585
+ return expiredIds.length
586
+ }
587
+ }
588
+
589
+ export default NotificationsModuleService
@@ -0,0 +1 @@
1
+ export * from "../../types"