@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.
- package/.medusa/server/src/admin/index.cjs +4215 -0
- package/.medusa/server/src/admin/index.js +4193 -0
- package/.medusa/server/src/api/admin/mpn/broadcasts/route.js +99 -0
- package/.medusa/server/src/api/admin/mpn/channels/route.js +109 -0
- package/.medusa/server/src/api/admin/mpn/logs/route.js +33 -0
- package/.medusa/server/src/api/admin/mpn/mappings/[id]/route.js +33 -0
- package/.medusa/server/src/api/admin/mpn/mappings/route.js +51 -0
- package/.medusa/server/src/api/admin/mpn/render-template/route.js +37 -0
- package/.medusa/server/src/api/admin/mpn/sandbox/route.js +36 -0
- package/.medusa/server/src/api/admin/mpn/send/route.js +135 -0
- package/.medusa/server/src/api/admin/mpn/templates/[id]/route.js +77 -0
- package/.medusa/server/src/api/admin/mpn/templates/route.js +71 -0
- package/.medusa/server/src/api/admin/plugin/route.js +4 -0
- package/.medusa/server/src/api/middlewares.js +28 -0
- package/.medusa/server/src/api/store/mpn/consent/route.js +37 -0
- package/.medusa/server/src/api/store/mpn/webhooks/[provider]/route.js +97 -0
- package/.medusa/server/src/api/store/plugin/route.js +4 -0
- package/.medusa/server/src/api/validators.js +118 -0
- package/.medusa/server/src/hooks/index.js +7 -0
- package/.medusa/server/src/hooks/use-mpn-channels.js +13 -0
- package/.medusa/server/src/hooks/use-mpn-dispatch.js +45 -0
- package/.medusa/server/src/hooks/use-mpn-mappings.js +21 -0
- package/.medusa/server/src/hooks/use-mpn-templates.js +34 -0
- package/.medusa/server/src/hooks/use-order-notifications-widget-state.js +79 -0
- package/.medusa/server/src/hooks/use-sdk-primitives.js +113 -0
- package/.medusa/server/src/index.js +14 -0
- package/.medusa/server/src/integrations/automations-action-handler.js +112 -0
- package/.medusa/server/src/jobs/abandoned-cart-recovery.js +123 -0
- package/.medusa/server/src/jobs/log-retention-and-broadcasts.js +15 -0
- package/.medusa/server/src/modules/notifications/i18n/index.js +65 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/ar.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/de.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/en.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/es.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/fr.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/it.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/nl.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/pl.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/pt.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/locales/tr.js +76 -0
- package/.medusa/server/src/modules/notifications/i18n/types.js +2 -0
- package/.medusa/server/src/modules/notifications/index.js +9 -0
- package/.medusa/server/src/modules/notifications/integrations/documents-and-b2b-resolver.js +129 -0
- package/.medusa/server/src/modules/notifications/migrations/Migration20261010000000.js +184 -0
- package/.medusa/server/src/modules/notifications/models/index.js +118 -0
- package/.medusa/server/src/modules/notifications/renderer/block-helpers.js +36 -0
- package/.medusa/server/src/modules/notifications/renderer/email.js +161 -0
- package/.medusa/server/src/modules/notifications/renderer/index.js +240 -0
- package/.medusa/server/src/modules/notifications/renderer/slack.js +114 -0
- package/.medusa/server/src/modules/notifications/renderer/telegram.js +99 -0
- package/.medusa/server/src/modules/notifications/renderer/whatsapp.js +91 -0
- package/.medusa/server/src/modules/notifications/service-helpers/channel-config.js +45 -0
- package/.medusa/server/src/modules/notifications/service-helpers/consent.js +65 -0
- package/.medusa/server/src/modules/notifications/service-helpers/delivery-log.js +29 -0
- package/.medusa/server/src/modules/notifications/service-helpers/event-conditions.js +46 -0
- package/.medusa/server/src/modules/notifications/service-helpers/external-templates.js +80 -0
- package/.medusa/server/src/modules/notifications/service-helpers/recipient-resolution.js +85 -0
- package/.medusa/server/src/modules/notifications/service-helpers/sender-profiles.js +29 -0
- package/.medusa/server/src/modules/notifications/service-helpers/template-blocks.js +81 -0
- package/.medusa/server/src/modules/notifications/service-helpers/template-catalog.js +129 -0
- package/.medusa/server/src/modules/notifications/service-helpers/template-render.js +65 -0
- package/.medusa/server/src/modules/notifications/service.js +339 -0
- package/.medusa/server/src/modules/notifications/types.js +2 -0
- package/.medusa/server/src/modules/notifications/utils/auth-presets.js +140 -0
- package/.medusa/server/src/modules/notifications/utils/interpolation.js +178 -0
- package/.medusa/server/src/modules/notifications/utils/security.js +312 -0
- package/.medusa/server/src/modules/notifications/utils/system-presets.js +651 -0
- package/.medusa/server/src/modules/notifications/utils/transformers.js +358 -0
- package/.medusa/server/src/providers/dummy-sandbox/index.js +96 -0
- package/.medusa/server/src/providers/email-smtp/index.js +187 -0
- package/.medusa/server/src/providers/index.js +7 -0
- package/.medusa/server/src/providers/slack/index.js +54 -0
- package/.medusa/server/src/providers/sms/index.js +254 -0
- package/.medusa/server/src/providers/telegram/index.js +119 -0
- package/.medusa/server/src/providers/whatsapp/index.js +371 -0
- package/.medusa/server/src/rbac.js +109 -0
- package/.medusa/server/src/sdk/client.js +186 -0
- package/.medusa/server/src/sdk/index.js +3 -0
- package/.medusa/server/src/sdk/query-keys.js +61 -0
- package/.medusa/server/src/subscribers/customer-and-document-events.js +33 -0
- package/.medusa/server/src/subscribers/fulfillment-and-inventory-events.js +30 -0
- package/.medusa/server/src/subscribers/order-events.js +28 -0
- package/.medusa/server/src/types/constants.js +129 -0
- package/.medusa/server/src/types/core.js +2 -0
- package/.medusa/server/src/types/domain.js +2 -0
- package/.medusa/server/src/types/enums.js +53 -0
- package/.medusa/server/src/types/errors.js +28 -0
- package/.medusa/server/src/types/hooks.js +2 -0
- package/.medusa/server/src/types/index.js +12 -0
- package/.medusa/server/src/types/providers.js +2 -0
- package/.medusa/server/src/types/records.js +2 -0
- package/.medusa/server/src/types/render.js +2 -0
- package/.medusa/server/src/types/sdk-api.js +2 -0
- package/.medusa/server/src/types/translations.js +2 -0
- package/.medusa/server/src/workflows/index.js +461 -0
- package/LICENSE +21 -0
- package/README.md +389 -2
- package/package.json +138 -3
- package/src/admin/README.md +123 -0
- package/src/admin/components/mpn/broadcast-consent-section.tsx +62 -0
- package/src/admin/components/mpn/broadcasts-tab.tsx +208 -0
- package/src/admin/components/mpn/channels-main-section.tsx +205 -0
- package/src/admin/components/mpn/channels-side-section.tsx +88 -0
- package/src/admin/components/mpn/channels-tab.tsx +130 -0
- package/src/admin/components/mpn/constants.ts +8 -0
- package/src/admin/components/mpn/delivery-logs-tab.tsx +70 -0
- package/src/admin/components/mpn/event-mapping-form.tsx +191 -0
- package/src/admin/components/mpn/event-mappings-tab.tsx +165 -0
- package/src/admin/components/mpn/header-bar.tsx +35 -0
- package/src/admin/components/mpn/index.ts +17 -0
- package/src/admin/components/mpn/overview-cards.tsx +103 -0
- package/src/admin/components/mpn/sandbox-tab.tsx +93 -0
- package/src/admin/components/mpn/template-editor-section.tsx +203 -0
- package/src/admin/components/mpn/template-preview-section.tsx +122 -0
- package/src/admin/components/mpn/templates-list-section.tsx +115 -0
- package/src/admin/components/mpn/templates-tab.tsx +188 -0
- package/src/admin/components/mpn/use-notification-studio.ts +84 -0
- package/src/admin/components/rbac-guard.tsx +153 -0
- package/src/admin/i18n/README.md +134 -0
- package/src/admin/i18n/index.ts +23 -0
- package/src/admin/i18n/json/ar.json +157 -0
- package/src/admin/i18n/json/de.json +157 -0
- package/src/admin/i18n/json/en.json +157 -0
- package/src/admin/i18n/json/es.json +157 -0
- package/src/admin/i18n/json/fr.json +157 -0
- package/src/admin/i18n/json/it.json +157 -0
- package/src/admin/i18n/json/nl.json +157 -0
- package/src/admin/i18n/json/pl.json +157 -0
- package/src/admin/i18n/json/pt.json +157 -0
- package/src/admin/i18n/json/tr.json +157 -0
- package/src/admin/routes/mpn/broadcasts/page.tsx +75 -0
- package/src/admin/routes/mpn/channels/page.tsx +66 -0
- package/src/admin/routes/mpn/logs/page.tsx +50 -0
- package/src/admin/routes/mpn/mappings/page.tsx +62 -0
- package/src/admin/routes/mpn/page.tsx +200 -0
- package/src/admin/routes/mpn/sandbox/page.tsx +53 -0
- package/src/admin/routes/mpn/templates/page.tsx +55 -0
- package/src/admin/tsconfig.json +23 -0
- package/src/admin/vite-env.d.ts +1 -0
- package/src/admin/widgets/order-notifications-widget.tsx +178 -0
- package/src/api/README.md +98 -0
- package/src/api/admin/mpn/broadcasts/route.ts +130 -0
- package/src/api/admin/mpn/channels/route.ts +143 -0
- package/src/api/admin/mpn/logs/route.ts +41 -0
- package/src/api/admin/mpn/mappings/[id]/route.ts +45 -0
- package/src/api/admin/mpn/mappings/route.ts +68 -0
- package/src/api/admin/mpn/render-template/route.ts +46 -0
- package/src/api/admin/mpn/sandbox/route.ts +51 -0
- package/src/api/admin/mpn/send/route.ts +163 -0
- package/src/api/admin/mpn/templates/[id]/route.ts +101 -0
- package/src/api/admin/mpn/templates/route.ts +99 -0
- package/src/api/admin/plugin/route.ts +5 -0
- package/src/api/middlewares.ts +42 -0
- package/src/api/store/mpn/consent/route.ts +45 -0
- package/src/api/store/mpn/webhooks/[provider]/route.ts +119 -0
- package/src/api/store/plugin/route.ts +5 -0
- package/src/api/validators.ts +149 -0
- package/src/hooks/index.ts +14 -0
- package/src/hooks/use-mpn-channels.ts +43 -0
- package/src/hooks/use-mpn-dispatch.ts +149 -0
- package/src/hooks/use-mpn-mappings.ts +75 -0
- package/src/hooks/use-mpn-templates.ts +120 -0
- package/src/hooks/use-order-notifications-widget-state.ts +103 -0
- package/src/hooks/use-sdk-primitives.ts +157 -0
- package/src/index.ts +16 -0
- package/src/integrations/automations-action-handler.ts +156 -0
- package/src/jobs/README.md +41 -0
- package/src/jobs/abandoned-cart-recovery.ts +152 -0
- package/src/jobs/log-retention-and-broadcasts.ts +23 -0
- package/src/links/README.md +52 -0
- package/src/modules/README.md +99 -0
- package/src/modules/notifications/i18n/index.ts +83 -0
- package/src/modules/notifications/i18n/locales/ar.ts +84 -0
- package/src/modules/notifications/i18n/locales/de.ts +83 -0
- package/src/modules/notifications/i18n/locales/en.ts +84 -0
- package/src/modules/notifications/i18n/locales/es.ts +84 -0
- package/src/modules/notifications/i18n/locales/fr.ts +82 -0
- package/src/modules/notifications/i18n/locales/it.ts +82 -0
- package/src/modules/notifications/i18n/locales/nl.ts +83 -0
- package/src/modules/notifications/i18n/locales/pl.ts +84 -0
- package/src/modules/notifications/i18n/locales/pt.ts +82 -0
- package/src/modules/notifications/i18n/locales/tr.ts +86 -0
- package/src/modules/notifications/i18n/types.ts +1 -0
- package/src/modules/notifications/index.ts +10 -0
- package/src/modules/notifications/integrations/documents-and-b2b-resolver.ts +168 -0
- package/src/modules/notifications/migrations/Migration20261010000000.ts +185 -0
- package/src/modules/notifications/models/index.ts +125 -0
- package/src/modules/notifications/renderer/block-helpers.ts +51 -0
- package/src/modules/notifications/renderer/email.ts +281 -0
- package/src/modules/notifications/renderer/index.ts +301 -0
- package/src/modules/notifications/renderer/slack.ts +168 -0
- package/src/modules/notifications/renderer/telegram.ts +161 -0
- package/src/modules/notifications/renderer/whatsapp.ts +156 -0
- package/src/modules/notifications/service-helpers/channel-config.ts +65 -0
- package/src/modules/notifications/service-helpers/consent.ts +88 -0
- package/src/modules/notifications/service-helpers/delivery-log.ts +56 -0
- package/src/modules/notifications/service-helpers/event-conditions.ts +66 -0
- package/src/modules/notifications/service-helpers/external-templates.ts +127 -0
- package/src/modules/notifications/service-helpers/recipient-resolution.ts +124 -0
- package/src/modules/notifications/service-helpers/sender-profiles.ts +34 -0
- package/src/modules/notifications/service-helpers/template-blocks.ts +116 -0
- package/src/modules/notifications/service-helpers/template-catalog.ts +170 -0
- package/src/modules/notifications/service-helpers/template-render.ts +113 -0
- package/src/modules/notifications/service.ts +588 -0
- package/src/modules/notifications/types.ts +1 -0
- package/src/modules/notifications/utils/auth-presets.ts +145 -0
- package/src/modules/notifications/utils/interpolation.ts +231 -0
- package/src/modules/notifications/utils/security.ts +378 -0
- package/src/modules/notifications/utils/system-presets.ts +695 -0
- package/src/modules/notifications/utils/transformers.ts +456 -0
- package/src/providers/README.md +92 -0
- package/src/providers/dummy-sandbox/index.ts +143 -0
- package/src/providers/email-smtp/index.ts +257 -0
- package/src/providers/index.ts +38 -0
- package/src/providers/slack/index.ts +82 -0
- package/src/providers/sms/index.ts +342 -0
- package/src/providers/telegram/index.ts +181 -0
- package/src/providers/whatsapp/index.ts +505 -0
- package/src/rbac.ts +123 -0
- package/src/sdk/client.ts +319 -0
- package/src/sdk/index.ts +48 -0
- package/src/sdk/query-keys.ts +89 -0
- package/src/subscribers/README.md +50 -0
- package/src/subscribers/customer-and-document-events.ts +36 -0
- package/src/subscribers/fulfillment-and-inventory-events.ts +35 -0
- package/src/subscribers/order-events.ts +31 -0
- package/src/types/constants.ts +143 -0
- package/src/types/core.ts +96 -0
- package/src/types/domain.ts +84 -0
- package/src/types/enums.ts +73 -0
- package/src/types/errors.ts +32 -0
- package/src/types/hooks.ts +48 -0
- package/src/types/index.ts +11 -0
- package/src/types/providers.ts +96 -0
- package/src/types/records.ts +100 -0
- package/src/types/render.ts +74 -0
- package/src/types/sdk-api.ts +228 -0
- package/src/types/translations.ts +75 -0
- package/src/workflows/README.md +67 -0
- package/src/workflows/index.ts +619 -0
- package/tsconfig.json +40 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { Modules } from "@medusajs/framework/utils"
|
|
2
|
+
|
|
3
|
+
export interface AutomationActionHandlerParams {
|
|
4
|
+
trigger: Record<string, any>
|
|
5
|
+
action: Record<string, any>
|
|
6
|
+
context: Record<string, any>
|
|
7
|
+
container: any
|
|
8
|
+
eventName: string
|
|
9
|
+
contextType?: string | null
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface AutomationActionHandlerResult {
|
|
13
|
+
success: boolean
|
|
14
|
+
message?: string
|
|
15
|
+
data?: unknown
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function resolvePathValue(
|
|
19
|
+
source: Record<string, any>,
|
|
20
|
+
rawValue: unknown
|
|
21
|
+
): string {
|
|
22
|
+
if (typeof rawValue !== "string" || !rawValue.trim()) {
|
|
23
|
+
return String(
|
|
24
|
+
source?.email ||
|
|
25
|
+
source?.customer?.email ||
|
|
26
|
+
source?.order?.email ||
|
|
27
|
+
source?.phone ||
|
|
28
|
+
source?.customer?.phone ||
|
|
29
|
+
""
|
|
30
|
+
).trim()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const trimmed = rawValue.trim()
|
|
34
|
+
const match = /^\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}$/.exec(trimmed)
|
|
35
|
+
if (!match) {
|
|
36
|
+
return trimmed
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let current: any = source
|
|
40
|
+
for (const segment of match[1].split(".")) {
|
|
41
|
+
if (
|
|
42
|
+
segment === "__proto__" ||
|
|
43
|
+
segment === "constructor" ||
|
|
44
|
+
segment === "prototype"
|
|
45
|
+
) {
|
|
46
|
+
return ""
|
|
47
|
+
}
|
|
48
|
+
if (current == null || typeof current !== "object") {
|
|
49
|
+
return ""
|
|
50
|
+
}
|
|
51
|
+
current = current[segment]
|
|
52
|
+
}
|
|
53
|
+
return current != null ? String(current).trim() : ""
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Custom ActionHandler bridge for `@codee-sh/medusa-plugin-automations` that
|
|
58
|
+
* dispatches multi-channel notifications (Email, WhatsApp, Telegram, SMS,
|
|
59
|
+
* Slack, Sandbox) through `@vicacha-devs/medusa-plugin-notifications`.
|
|
60
|
+
*/
|
|
61
|
+
export class MpnAutomationActionHandler {
|
|
62
|
+
id = "mpn-notification-studio"
|
|
63
|
+
label = "Notification Studio (Multi-Channel)"
|
|
64
|
+
description =
|
|
65
|
+
"Dispatch Email, WhatsApp, Telegram, SMS, or Slack via @vicacha-devs/medusa-plugin-notifications"
|
|
66
|
+
enabled = true
|
|
67
|
+
|
|
68
|
+
fields = [
|
|
69
|
+
{
|
|
70
|
+
name: "channel",
|
|
71
|
+
key: "channel",
|
|
72
|
+
label: "Channel",
|
|
73
|
+
type: "select" as const,
|
|
74
|
+
required: false,
|
|
75
|
+
defaultValue: "email",
|
|
76
|
+
options: [
|
|
77
|
+
{ value: "email", name: "Email" },
|
|
78
|
+
{ value: "whatsapp", name: "WhatsApp" },
|
|
79
|
+
{ value: "telegram", name: "Telegram" },
|
|
80
|
+
{ value: "sms", name: "SMS" },
|
|
81
|
+
{ value: "slack", name: "Slack" },
|
|
82
|
+
],
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: "template_id",
|
|
86
|
+
key: "template_id",
|
|
87
|
+
label: "Template ID (leave empty to use Event Mappings)",
|
|
88
|
+
type: "text" as const,
|
|
89
|
+
required: false,
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
name: "to",
|
|
93
|
+
key: "to",
|
|
94
|
+
label: "Recipient (or {{customer.email}})",
|
|
95
|
+
type: "text" as const,
|
|
96
|
+
required: false,
|
|
97
|
+
},
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
async executeAction({
|
|
101
|
+
action,
|
|
102
|
+
context,
|
|
103
|
+
container,
|
|
104
|
+
eventName,
|
|
105
|
+
contextType,
|
|
106
|
+
}: AutomationActionHandlerParams): Promise<AutomationActionHandlerResult> {
|
|
107
|
+
const config = action?.config || action || {}
|
|
108
|
+
const templateId = String(
|
|
109
|
+
config.template_id || config.templateName || ""
|
|
110
|
+
).trim()
|
|
111
|
+
|
|
112
|
+
if (!templateId) {
|
|
113
|
+
const { executeEventNotificationsDispatch } =
|
|
114
|
+
await import("../workflows/index.js")
|
|
115
|
+
const dispatchResult = await executeEventNotificationsDispatch(
|
|
116
|
+
container,
|
|
117
|
+
{
|
|
118
|
+
event_name: eventName,
|
|
119
|
+
event_data: context || {},
|
|
120
|
+
}
|
|
121
|
+
)
|
|
122
|
+
return {
|
|
123
|
+
success: true,
|
|
124
|
+
message: `Dispatched Notification Studio mappings for ${eventName}`,
|
|
125
|
+
data: dispatchResult,
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const channel = String(config.channel || "email").trim()
|
|
130
|
+
const to = resolvePathValue(context || {}, config.to)
|
|
131
|
+
if (!to) {
|
|
132
|
+
return {
|
|
133
|
+
success: false,
|
|
134
|
+
message: "Notification recipient could not be resolved",
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const notificationService = container.resolve(Modules.NOTIFICATION)
|
|
139
|
+
const result = await notificationService.createNotifications({
|
|
140
|
+
to,
|
|
141
|
+
channel,
|
|
142
|
+
template: templateId,
|
|
143
|
+
data: {
|
|
144
|
+
...context,
|
|
145
|
+
event_name: eventName,
|
|
146
|
+
context_type: contextType,
|
|
147
|
+
},
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
success: true,
|
|
152
|
+
message: `Notification dispatched via ${channel}`,
|
|
153
|
+
data: result,
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Scheduled Jobs
|
|
2
|
+
|
|
3
|
+
Background scheduled jobs (`src/jobs/`) registered automatically by Medusa v2 for abandoned cart recovery, delivery log retention cleanup, and scheduled broadcast campaigns.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
jobs/
|
|
7
|
+
├── abandoned-cart-recovery.ts Every 15m abandoned cart scanner with TCPA consent & 24h cooldown
|
|
8
|
+
└── log-retention-and-broadcasts.ts Hourly delivery log retention pruner & scheduled broadcasts runner
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Job Schedule Summary
|
|
14
|
+
|
|
15
|
+
| Job Name | File | Cron Schedule | Frequency | Purpose |
|
|
16
|
+
| ---------------------------------- | --------------------------------- | -------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
|
17
|
+
| `mpn-abandoned-cart-recovery` | `abandoned-cart-recovery.ts` | `*/15 * * * *` | Every 15 minutes | Scans abandoned carts, verifies `opted_in` TCPA consent & 24h per-phone cooldown, and dispatches `cart.abandoned` notifications. |
|
|
18
|
+
| `mpn-log-retention-and-broadcasts` | `log-retention-and-broadcasts.ts` | `0 * * * *` | Every hour | Prunes `mpn_delivery_log` records older than `logRetentionDays` (default `30` days). |
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 1. `mpn-abandoned-cart-recovery` (`abandoned-cart-recovery.ts`)
|
|
23
|
+
|
|
24
|
+
Exports `runAbandonedCartRecoveryJob(container)` and the default Medusa job handler (`config.schedule = "*/15 * * * *"`).
|
|
25
|
+
|
|
26
|
+
### Execution Rules & Safeguards
|
|
27
|
+
|
|
28
|
+
1. **Opt-In Activation**: Runs only when `options.enableCartRecovery === true` or `SIGNALHOUSE_CART_ABANDONMENT_ENABLED="true"`.
|
|
29
|
+
2. **Inactivity Threshold**: Queries incomplete carts (`completed_at === null`) with at least 1 line item whose `updated_at` timestamp is older than `cartAbandonmentThresholdMinutes` (default `60` minutes, minimum `15` minutes).
|
|
30
|
+
3. **E.164 Phone Normalization**: Normalizes `cart.shipping_address.phone` or `cart.customer.phone` via `normalizeE164Phone`.
|
|
31
|
+
4. **Explicit TCPA / 10DLC Consent Verification**: Requires an active `mpn_consent_record` row with `status === "opted_in"` for the customer's phone number.
|
|
32
|
+
5. **Strict 24-Hour Per-Phone Cooldown**: Checks `activeConsent.last_cart_recovery_at` and skips any phone number that has already received a cart recovery message within the last 24 hours (`24 * 60 * 60 * 1000` ms).
|
|
33
|
+
6. **Event Dispatch**: Invokes `executeEventNotificationsDispatch` with `event_name: "cart.abandoned"` and `recovery_url: "${recoveryBaseUrl}?cart_id=${cart.id}"` (paired with the built-in `system_sms_cart_recovery` preset), then updates `last_cart_recovery_at`.
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## 2. `mpn-log-retention-and-broadcasts` (`log-retention-and-broadcasts.ts`)
|
|
38
|
+
|
|
39
|
+
Runs at the top of every hour (`0 * * * *`) and invokes `mpnService.pruneExpiredDeliveryLogs()`:
|
|
40
|
+
|
|
41
|
+
- Deletes `mpn_delivery_log` rows whose `created_at` is older than `options.logRetentionDays` (or `MAILER_LOG_RETENTION_DAYS`, default `30` days) to keep the database ledger compact and GDPR/privacy compliant.
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { MedusaContainer } from "@medusajs/framework/types"
|
|
2
|
+
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
|
|
3
|
+
import type NotificationsModuleService from "../modules/notifications/service"
|
|
4
|
+
import { NOTIFICATIONS_MODULE } from "../modules/notifications/types"
|
|
5
|
+
import { normalizeE164Phone } from "../modules/notifications/utils/security"
|
|
6
|
+
import { executeEventNotificationsDispatch } from "../workflows"
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Abandoned Cart Recovery Runner (inspired by `@signalhouse-sms/medusa-plugin`).
|
|
10
|
+
* Checks every 15 minutes, enforces explicit opt-in consent and a strict 24-hour per-phone cooldown,
|
|
11
|
+
* and emits `cart.abandoned` notifications with a direct checkout recovery link.
|
|
12
|
+
*/
|
|
13
|
+
export async function runAbandonedCartRecoveryJob(
|
|
14
|
+
container: MedusaContainer
|
|
15
|
+
): Promise<{ checked: number; sent: number; skipped: number }> {
|
|
16
|
+
const mpnService = container.resolve(
|
|
17
|
+
NOTIFICATIONS_MODULE
|
|
18
|
+
) as NotificationsModuleService
|
|
19
|
+
const opts = mpnService.getPluginOptions()
|
|
20
|
+
|
|
21
|
+
const enabled =
|
|
22
|
+
opts.enableCartRecovery ??
|
|
23
|
+
process.env.SIGNALHOUSE_CART_ABANDONMENT_ENABLED === "true"
|
|
24
|
+
if (!enabled) {
|
|
25
|
+
return { checked: 0, sent: 0, skipped: 0 }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const thresholdMinutes = Math.max(
|
|
29
|
+
15,
|
|
30
|
+
Number(
|
|
31
|
+
opts.cartAbandonmentThresholdMinutes ||
|
|
32
|
+
process.env.SIGNALHOUSE_CART_ABANDONMENT_THRESHOLD_MINUTES ||
|
|
33
|
+
60
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
const recoveryBaseUrl = (
|
|
37
|
+
opts.cartRecoveryUrlBase ||
|
|
38
|
+
process.env.SIGNALHOUSE_CART_RECOVERY_URL_BASE ||
|
|
39
|
+
opts.storeUrl ||
|
|
40
|
+
process.env.STORE_URL ||
|
|
41
|
+
"https://store.example.com/cart/recover"
|
|
42
|
+
).replace(/\/$/, "")
|
|
43
|
+
|
|
44
|
+
let carts: Array<Record<string, any>> = []
|
|
45
|
+
try {
|
|
46
|
+
const query = container.resolve(ContainerRegistrationKeys.QUERY) as any
|
|
47
|
+
if (query && typeof query.graph === "function") {
|
|
48
|
+
const { data } = await query.graph({
|
|
49
|
+
entity: "cart",
|
|
50
|
+
fields: [
|
|
51
|
+
"id",
|
|
52
|
+
"email",
|
|
53
|
+
"total",
|
|
54
|
+
"currency_code",
|
|
55
|
+
"completed_at",
|
|
56
|
+
"updated_at",
|
|
57
|
+
"shipping_address.*",
|
|
58
|
+
"customer.*",
|
|
59
|
+
"items.*",
|
|
60
|
+
],
|
|
61
|
+
})
|
|
62
|
+
if (Array.isArray(data)) {
|
|
63
|
+
carts = data
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
return { checked: 0, sent: 0, skipped: 0 }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const nowMs = Date.now()
|
|
71
|
+
const cutoffMs = nowMs - thresholdMinutes * 60 * 1000
|
|
72
|
+
const cooldownMs = 24 * 60 * 60 * 1000
|
|
73
|
+
let sent = 0
|
|
74
|
+
let skipped = 0
|
|
75
|
+
|
|
76
|
+
for (const cart of carts) {
|
|
77
|
+
if (cart.completed_at) continue
|
|
78
|
+
if (!Array.isArray(cart.items) || cart.items.length === 0) continue
|
|
79
|
+
|
|
80
|
+
const updatedAtMs = cart.updated_at
|
|
81
|
+
? new Date(cart.updated_at).getTime()
|
|
82
|
+
: 0
|
|
83
|
+
if (!updatedAtMs || updatedAtMs > cutoffMs) {
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const phone = normalizeE164Phone(
|
|
88
|
+
cart.shipping_address?.phone || cart.customer?.phone
|
|
89
|
+
)
|
|
90
|
+
if (!phone) {
|
|
91
|
+
skipped++
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const consentRows = await mpnService.listMpnConsentRecords({
|
|
96
|
+
identifier: phone,
|
|
97
|
+
})
|
|
98
|
+
const activeConsent = consentRows.find((r: any) => r.status === "opted_in")
|
|
99
|
+
if (!activeConsent) {
|
|
100
|
+
skipped++
|
|
101
|
+
continue
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Enforce max 1 cart recovery text per phone per 24 hours
|
|
105
|
+
if (activeConsent.last_cart_recovery_at) {
|
|
106
|
+
const lastSentMs = new Date(activeConsent.last_cart_recovery_at).getTime()
|
|
107
|
+
if (nowMs - lastSentMs < cooldownMs) {
|
|
108
|
+
skipped++
|
|
109
|
+
continue
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const outcome = await executeEventNotificationsDispatch(container, {
|
|
114
|
+
event_name: "cart.abandoned",
|
|
115
|
+
event_data: {
|
|
116
|
+
id: cart.id,
|
|
117
|
+
first_name:
|
|
118
|
+
cart.shipping_address?.first_name ||
|
|
119
|
+
cart.customer?.first_name ||
|
|
120
|
+
"Customer",
|
|
121
|
+
email: cart.email || cart.customer?.email || "",
|
|
122
|
+
phone,
|
|
123
|
+
total: cart.total,
|
|
124
|
+
currency_code: cart.currency_code || "USD",
|
|
125
|
+
recovery_url: `${recoveryBaseUrl}?cart_id=${encodeURIComponent(cart.id)}`,
|
|
126
|
+
},
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
if (outcome.sent_count > 0) {
|
|
130
|
+
await mpnService.updateMpnConsentRecords({
|
|
131
|
+
id: activeConsent.id,
|
|
132
|
+
last_cart_recovery_at: new Date(),
|
|
133
|
+
})
|
|
134
|
+
sent++
|
|
135
|
+
} else {
|
|
136
|
+
skipped++
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return { checked: carts.length, sent, skipped }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export default async function abandonedCartRecoveryJobHandler(
|
|
144
|
+
container: MedusaContainer
|
|
145
|
+
) {
|
|
146
|
+
await runAbandonedCartRecoveryJob(container)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export const config = {
|
|
150
|
+
name: "mpn-abandoned-cart-recovery",
|
|
151
|
+
schedule: "*/15 * * * *",
|
|
152
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { MedusaContainer } from "@medusajs/framework/types"
|
|
2
|
+
import type NotificationsModuleService from "../modules/notifications/service"
|
|
3
|
+
import { NOTIFICATIONS_MODULE } from "../modules/notifications/types"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Hourly maintenance job:
|
|
7
|
+
* 1. Prunes expired delivery logs older than `logRetentionDays` (default 30 days)
|
|
8
|
+
* 2. Executes any scheduled customer group broadcast campaigns whose `scheduled_at` is due
|
|
9
|
+
*/
|
|
10
|
+
export default async function logRetentionAndBroadcastsJob(
|
|
11
|
+
container: MedusaContainer
|
|
12
|
+
) {
|
|
13
|
+
const mpnService = container.resolve(
|
|
14
|
+
NOTIFICATIONS_MODULE
|
|
15
|
+
) as NotificationsModuleService
|
|
16
|
+
|
|
17
|
+
await mpnService.pruneExpiredDeliveryLogs()
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const config = {
|
|
21
|
+
name: "mpn-log-retention-and-broadcasts",
|
|
22
|
+
schedule: "0 * * * *",
|
|
23
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Module Links & Loose Entity Associations
|
|
2
|
+
|
|
3
|
+
How `@vicacha-devs/medusa-plugin-notifications` associates notification records with Medusa core entities (`Order`, `Customer`, `Fulfillment`, `Cart`) and optional sibling plugins (`medusa-plugin-documents`, B2B modules) while maintaining strict module isolation.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
links/
|
|
7
|
+
└── README.md Documentation on loose entity associations and optional custom module links
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Loose Coupled Association Strategy (Zero Cross-Module FK Lock-In)
|
|
13
|
+
|
|
14
|
+
Rather than enforcing hard foreign-key links that would couple `notificationsModuleService` to optional modules or prevent log retention pruning when orders/carts are archived, `medusa-plugin-notifications` associates entities using **indexed string identifiers and customer metadata**:
|
|
15
|
+
|
|
16
|
+
| Model / Storage | Field | Associated Entity | Purpose |
|
|
17
|
+
| ------------------------ | ------------------------------------------------------------------------ | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
18
|
+
| `mpn_delivery_log` | `entity_id` | `order.id`, `fulfillment.id`, `cart.id`, `document.id`, `product.id` | Associates delivery logs with any Medusa or custom entity. Queried by the Order Details widget (`GET /admin/mpn/logs?entity_id=order_01J...`). |
|
|
19
|
+
| `mpn_delivery_log` | `recipient_masked` & `recipient_hash` | Customer email, E.164 phone, or Telegram `chat_id` | Allows privacy-safe lookup and audit verification without storing raw PII in the delivery ledger. |
|
|
20
|
+
| `mpn_consent_record` | `customer_id` & `identifier` | `customer.id` + E.164 phone or Telegram `chat_id` | Links TCPA/10DLC `JOIN`/`STOP` and Telegram `/start <customer_id>` opt-ins to a Medusa customer. |
|
|
21
|
+
| `mpn_broadcast_campaign` | `customer_group_id` | `customer_group.id` | Associates a broadcast campaign with a Medusa Customer Group. |
|
|
22
|
+
| `customer.metadata` | `telegram_chat_id`, `telegram_username`, `whatsapp_opt_in`, `sms_opt_in` | `Customer` | Populated automatically by `POST /store/mpn/webhooks/telegram` (`/start <customer_id>`) and read by `resolveRecipientForRule` during event dispatch. |
|
|
23
|
+
| `order.metadata` | `company_id`, `accounting_email`, `accounting_phone`, `telegram_chat_id` | `Order` / B2B Company | Read by `resolveB2BNotificationContacts` (`src/modules/notifications/integrations/documents-and-b2b-resolver.ts`) when `recipient_rule === "b2b_accounting"`. |
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## Querying Across Entities (`query.graph`)
|
|
28
|
+
|
|
29
|
+
When an event fires (e.g., `order.placed` or `shipment.created`), `hydrateEntityContextData` in `src/workflows/index.ts` uses `ContainerRegistrationKeys.QUERY` (`query.graph`) to hydrate the full entity graph (`order.*`, `customer.*`, `items.*`, `shipping_address.*`, `billing_address.*`, `fulfillment.labels.*`) on the fly without requiring a custom link table.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Defining Optional Custom Links (`defineLink`)
|
|
34
|
+
|
|
35
|
+
If your host Medusa application wants to traverse `mpn_consent_record` or `mpn_delivery_log` directly through `query.graph` from `Customer` or `Order`, you can add a link file in `src/links/` using `defineLink`:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import CustomerModule from "@medusajs/medusa/customer"
|
|
39
|
+
import { defineLink } from "@medusajs/framework/utils"
|
|
40
|
+
import NotificationsModule from "../modules/notifications"
|
|
41
|
+
|
|
42
|
+
export default defineLink(CustomerModule.linkable.customer, {
|
|
43
|
+
linkable: NotificationsModule.linkable.mpnConsentRecord,
|
|
44
|
+
isList: true,
|
|
45
|
+
})
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
After adding a link file, sync the link table in the host application:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
npx medusa db:migrate
|
|
52
|
+
```
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Modules
|
|
2
|
+
|
|
3
|
+
Standalone Medusa v2 Notification Studio module (`notificationsModuleService`) managing templates, visual block trees, event mappings, delivery logs, TCPA/10DLC consent records, customer group broadcasts, channel gateway configs, and sandbox messages.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
modules/
|
|
7
|
+
└── notifications/
|
|
8
|
+
├── index.ts Exports NOTIFICATIONS_MODULE ("notificationsModuleService") + Module() definition
|
|
9
|
+
├── types.ts Re-exports module types, channels, drivers & options
|
|
10
|
+
├── service.ts NotificationsModuleService extending MedusaService with custom studio methods
|
|
11
|
+
├── models/
|
|
12
|
+
│ └── index.ts 8 DML models (mpn_template, mpn_template_block, mpn_event_mapping, mpn_delivery_log, mpn_consent_record, mpn_broadcast_campaign, mpn_channel_config, mpn_sandbox_message)
|
|
13
|
+
├── migrations/
|
|
14
|
+
│ └── Migration20261010000000.ts PostgreSQL DDL & partial unique idempotency index (UQ_mpn_delivery_log_idempotency_active)
|
|
15
|
+
├── i18n/
|
|
16
|
+
│ ├── index.ts 10-locale dictionary loader, RTL detection & deep-merge overrides
|
|
17
|
+
│ ├── types.ts NotificationTranslationDictionary interface
|
|
18
|
+
│ └── locales/ 10 built-in locales (ar, de, en, es, fr, it, nl, pl, pt, tr)
|
|
19
|
+
├── integrations/
|
|
20
|
+
│ └── documents-and-b2b-resolver.ts Optional medusa-plugin-documents PDF attachment & B2B buyer contact resolver
|
|
21
|
+
├── utils/
|
|
22
|
+
│ ├── security.ts E.164/WhatsApp phone normalizer, PII masking, payload redaction, HTML/Telegram sanitizers, SSRF guard, HMAC verifier, SMS segment calculator, rate limiter
|
|
23
|
+
│ ├── interpolation.ts Multi-pass {{data.*}}, {{translations.*}}, Go-style {{ .var }}, and variable_map engine
|
|
24
|
+
│ ├── transformers.ts Entity data transformers & mock preview contexts (order, shipment, inventory-level, product, cart, document, otp)
|
|
25
|
+
│ └── system-presets.ts 13 built-in system presets across Email, WhatsApp/OpenWA, Telegram, SMS, and Slack
|
|
26
|
+
└── renderer/
|
|
27
|
+
└── index.ts Dual-Mode (Blocks + Raw) multi-channel template compiler
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Service Token
|
|
33
|
+
|
|
34
|
+
- **Module Key**: `NOTIFICATIONS_MODULE = "notificationsModuleService"`
|
|
35
|
+
- **Import Path**: `@vicacha-devs/medusa-plugin-notifications/modules/notifications`
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import {
|
|
39
|
+
NOTIFICATIONS_MODULE,
|
|
40
|
+
type NotificationsModuleService,
|
|
41
|
+
} from "@vicacha-devs/medusa-plugin-notifications"
|
|
42
|
+
|
|
43
|
+
const mpnService = req.scope.resolve(
|
|
44
|
+
NOTIFICATIONS_MODULE
|
|
45
|
+
) as NotificationsModuleService
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Data Models (`mpn_` Prefix)
|
|
51
|
+
|
|
52
|
+
All 8 data models are defined in `src/modules/notifications/models/index.ts` using Medusa's DML (`model.define`):
|
|
53
|
+
|
|
54
|
+
| Model Class | Table Name | ID Prefix | Key Fields | Purpose |
|
|
55
|
+
| ---------------------- | ------------------------ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
56
|
+
| `MpnTemplate` | `mpn_template` | `mpntpl` | `name`, `label`, `channel`, `mode` (`"blocks" \| "raw"`), `locale`, `subject`, `raw_content`, `variable_map`, `meta_template_name`, `meta_language_code`, `styles`, `is_active`, `source_preset_id` | Multi-channel notification template metadata and raw content |
|
|
57
|
+
| `MpnTemplateBlock` | `mpn_template_block` | `mpnblk` | `template_id`, `type`, `position`, `parent_id`, `metadata` | Hierarchical visual block tree nodes (`section`, `heading`, `text`, `row`, `separator`, `group`, `repeater`, `product-item`, `button`, `actions`, `divider`, `attachment`) |
|
|
58
|
+
| `MpnEventMapping` | `mpn_event_mapping` | `mpnmap` | `event_name`, `channel`, `template_id`, `recipient_rule`, `custom_recipient`, `sender_profile_index`, `telegram_thread_id`, `attach_document_types`, `variable_map`, `conditions`, `is_active`, `priority` | Routes Medusa store events to a target channel, template, recipient rule, and optional PDF document attachment |
|
|
59
|
+
| `MpnDeliveryLog` | `mpn_delivery_log` | `mpnlog` | `idempotency_key`, `event_name`, `entity_id`, `channel`, `provider_id`, `driver`, `template_id`, `mapping_id`, `recipient_masked`, `recipient_hash`, `status`, `attempts`, `external_message_id`, `payload_redacted`, `error_code`, `error_message` | PII-masked, idempotent audit ledger enforced by partial unique index `UQ_mpn_delivery_log_idempotency_active` |
|
|
60
|
+
| `MpnConsentRecord` | `mpn_consent_record` | `mpncns` | `identifier`, `channel`, `customer_id`, `status` (`"opted_in" \| "opted_out" \| "pending"`), `source`, `first_message_sent`, `last_cart_recovery_at`, `opted_in_at`, `opted_out_at` | TCPA/10DLC SMS, WhatsApp, and Telegram Bot opt-in/opt-out ledger |
|
|
61
|
+
| `MpnBroadcastCampaign` | `mpn_broadcast_campaign` | `mpnbrc` | `name`, `channel`, `template_id`, `customer_group_id`, `custom_recipients`, `status`, `scheduled_at`, `sent_at`, `total_recipients`, `sent_count`, `failed_count`, `attributed_orders_count`, `attributed_revenue` | Customer group or custom recipient marketing broadcast campaigns |
|
|
62
|
+
| `MpnChannelConfig` | `mpn_channel_config` | `mpncfg` | `channel`, `driver`, `is_enabled`, `is_verified`, `verified_at`, `rate_limit_per_sec`, `config_json` | Non-secret operational gateway config and Telegram supergroup verification state |
|
|
63
|
+
| `MpnSandboxMessage` | `mpn_sandbox_message` | `mpnsbx` | `channel`, `recipient`, `sender`, `subject`, `body`, `html`, `otp_code`, `media_urls`, `attachments_meta` | Local/staging captured notifications and extracted OTP verification codes |
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Core Custom Methods on `NotificationsModuleService`
|
|
68
|
+
|
|
69
|
+
In addition to the auto-generated `MedusaService` CRUD methods (`listMpnTemplates`, `createMpnEventMappings`, `listMpnDeliveryLogs`, etc.), `NotificationsModuleService` provides:
|
|
70
|
+
|
|
71
|
+
| Method | Description |
|
|
72
|
+
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
73
|
+
| `getPluginOptions()` | Returns the resolved `NotificationsPluginOptions` passed in `medusa-config.ts`. |
|
|
74
|
+
| `getSenderProfiles()` | Resolves up to 5 SMTP sender profiles (`MAILER_FROM_NAME_1..5`, `MAILER_FROM_ADDRESS_1..5`, `MAILER_REPLY_TO_1..5`). |
|
|
75
|
+
| `listAllTemplates(filters?)` | Aggregates read-only System Presets (`system_*`), External Templates (`external_*`), and DB Templates (`mpntpl_*`). |
|
|
76
|
+
| `getTemplateWithBlocks(templateId)` | Loads a preset or DB template along with its nested `TemplateBlockNode[]` tree and `flatBlocks`. |
|
|
77
|
+
| `cloneSystemPresetToDb(presetId, overrides?)` | 1-click clones a `system_*` preset and its hierarchical block tree into editable `mpn_template` + `mpn_template_block` rows. |
|
|
78
|
+
| `replaceTemplateBlocks(templateId, blocks)` | Replaces all `mpn_template_block` rows for a DB template while preserving parent-child tree relationships. |
|
|
79
|
+
| `renderTemplateById(params)` | Compiles a template (Blocks or Raw) against entity data, `variable_map`, locale dictionary (`10` locales), and channel rules into a `RenderedNotificationPayload`. |
|
|
80
|
+
| `evaluateEventConditions(conditions, data)` | Evaluates optional currency, region, sales channel, minimum order total, or field-match conditions on an event mapping. |
|
|
81
|
+
| `resolveRecipientForRule(params)` | Resolves the target recipient address/phone/chat ID for `customer_auto`, `order_email`, `order_phone`, `customer_telegram`, `merchant_channel`, `b2b_accounting`, or `custom`. |
|
|
82
|
+
| `verifyRecipientConsent(params)` | Checks `mpn_consent_record` for TCPA/10DLC compliance and determines whether to append the first-message `"Reply STOP to opt out"` footer. |
|
|
83
|
+
| `recordConsentChange(params)` | Upserts an `opted_in` or `opted_out` record in `mpn_consent_record` from checkout, Admin, or inbound `JOIN`/`STOP`/`/start` webhooks. |
|
|
84
|
+
| `checkIdempotency(params)` | Computes deterministic `idempotency_key` and checks `mpn_delivery_log` for active (`pending`/`sent`/`delivered`) duplicates. |
|
|
85
|
+
| `recordDeliveryLog(params)` | Masks recipient PII (`maskRecipientPii`), hashes the recipient (`hashRecipient`), redacts sensitive payload fields (`redactSensitivePayload`), and writes to `mpn_delivery_log`. |
|
|
86
|
+
| `getOrCreateChannelConfig(channel)` | Retrieves or initializes the `mpn_channel_config` row for a channel. |
|
|
87
|
+
| `updateChannelConfig(params)` | Updates channel driver/config and automatically resets `is_verified = false` if a Telegram `channel_id` is changed. |
|
|
88
|
+
| `captureSandboxMessage(params)` | Extracts 4–8 digit OTP codes (`extractOtpCode`) and stores captured test messages in `mpn_sandbox_message`. |
|
|
89
|
+
| `pruneExpiredDeliveryLogs()` | Deletes `mpn_delivery_log` entries older than `logRetentionDays` (default `30` days). |
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## Generating Migrations
|
|
94
|
+
|
|
95
|
+
After editing any model in `src/modules/notifications/models/index.ts`, regenerate migrations from the plugin root:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
npx medusa plugin:db:generate
|
|
99
|
+
```
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { SUPPORTED_LOCALES, type SupportedLocale } from "../types"
|
|
2
|
+
import { ar } from "./locales/ar"
|
|
3
|
+
import { de } from "./locales/de"
|
|
4
|
+
import { en } from "./locales/en"
|
|
5
|
+
import { es } from "./locales/es"
|
|
6
|
+
import { fr } from "./locales/fr"
|
|
7
|
+
import { it } from "./locales/it"
|
|
8
|
+
import { nl } from "./locales/nl"
|
|
9
|
+
import { pl } from "./locales/pl"
|
|
10
|
+
import { pt } from "./locales/pt"
|
|
11
|
+
import { tr } from "./locales/tr"
|
|
12
|
+
import type { NotificationTranslationDictionary } from "./types"
|
|
13
|
+
|
|
14
|
+
export type { NotificationTranslationDictionary }
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_LOCALE_DICTIONARIES: Record<
|
|
17
|
+
SupportedLocale,
|
|
18
|
+
NotificationTranslationDictionary
|
|
19
|
+
> = {
|
|
20
|
+
en,
|
|
21
|
+
es,
|
|
22
|
+
pl,
|
|
23
|
+
de,
|
|
24
|
+
fr,
|
|
25
|
+
pt,
|
|
26
|
+
it,
|
|
27
|
+
nl,
|
|
28
|
+
tr,
|
|
29
|
+
ar,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const RTL_LOCALES: ReadonlyArray<SupportedLocale> = ["ar"]
|
|
33
|
+
|
|
34
|
+
export function normalizeLocale(input?: string | null): SupportedLocale {
|
|
35
|
+
if (!input) return "en"
|
|
36
|
+
const clean = input.trim().toLowerCase().split(/[-_]/)[0]
|
|
37
|
+
if ((SUPPORTED_LOCALES as readonly string[]).includes(clean)) {
|
|
38
|
+
return clean as SupportedLocale
|
|
39
|
+
}
|
|
40
|
+
return "en"
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function isRtlLocale(locale?: string | null): boolean {
|
|
44
|
+
return RTL_LOCALES.includes(normalizeLocale(locale))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function deepMergeDict(
|
|
48
|
+
target: Record<string, any>,
|
|
49
|
+
source?: Record<string, any>
|
|
50
|
+
): Record<string, any> {
|
|
51
|
+
if (!source || typeof source !== "object") {
|
|
52
|
+
return target
|
|
53
|
+
}
|
|
54
|
+
const output: Record<string, any> = { ...target }
|
|
55
|
+
for (const [key, value] of Object.entries(source)) {
|
|
56
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") {
|
|
57
|
+
continue
|
|
58
|
+
}
|
|
59
|
+
if (
|
|
60
|
+
value &&
|
|
61
|
+
typeof value === "object" &&
|
|
62
|
+
!Array.isArray(value) &&
|
|
63
|
+
typeof output[key] === "object" &&
|
|
64
|
+
output[key] !== null
|
|
65
|
+
) {
|
|
66
|
+
output[key] = deepMergeDict(output[key], value)
|
|
67
|
+
} else if (value !== undefined) {
|
|
68
|
+
output[key] = value
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return output
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function getNotificationTranslations(
|
|
75
|
+
locale?: string | null,
|
|
76
|
+
customOverrides?: Partial<Record<SupportedLocale, Record<string, any>>> | null
|
|
77
|
+
): Record<string, any> {
|
|
78
|
+
const normalized = normalizeLocale(locale)
|
|
79
|
+
const base =
|
|
80
|
+
DEFAULT_LOCALE_DICTIONARIES[normalized] || DEFAULT_LOCALE_DICTIONARIES.en
|
|
81
|
+
const override = customOverrides?.[normalized]
|
|
82
|
+
return deepMergeDict(base as unknown as Record<string, any>, override)
|
|
83
|
+
}
|