@vicacha-devs/medusa-plugin-automations 0.0.0-stage → 0.2.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 (82) hide show
  1. package/.medusa/server/src/admin/index.cjs +134 -0
  2. package/.medusa/server/src/admin/index.js +134 -0
  3. package/.medusa/server/src/api/admin/automations/[id]/logs/route.d.ts +2 -0
  4. package/.medusa/server/src/api/admin/automations/[id]/logs/route.js +7 -0
  5. package/.medusa/server/src/api/admin/automations/[id]/logs/route.js.map +1 -0
  6. package/.medusa/server/src/api/admin/automations/[id]/route.d.ts +4 -0
  7. package/.medusa/server/src/api/admin/automations/[id]/route.js +31 -0
  8. package/.medusa/server/src/api/admin/automations/[id]/route.js.map +1 -0
  9. package/.medusa/server/src/api/admin/automations/[id]/trigger/route.d.ts +2 -0
  10. package/.medusa/server/src/api/admin/automations/[id]/trigger/route.js +14 -0
  11. package/.medusa/server/src/api/admin/automations/[id]/trigger/route.js.map +1 -0
  12. package/.medusa/server/src/api/admin/automations/actions/route.d.ts +2 -0
  13. package/.medusa/server/src/api/admin/automations/actions/route.js +6 -0
  14. package/.medusa/server/src/api/admin/automations/actions/route.js.map +1 -0
  15. package/.medusa/server/src/api/admin/automations/route.d.ts +3 -0
  16. package/.medusa/server/src/api/admin/automations/route.js +23 -0
  17. package/.medusa/server/src/api/admin/automations/route.js.map +1 -0
  18. package/.medusa/server/src/api/middlewares.d.ts +2 -0
  19. package/.medusa/server/src/api/middlewares.js +26 -0
  20. package/.medusa/server/src/api/middlewares.js.map +1 -0
  21. package/.medusa/server/src/api/validators.d.ts +97 -0
  22. package/.medusa/server/src/api/validators.js +40 -0
  23. package/.medusa/server/src/api/validators.js.map +1 -0
  24. package/.medusa/server/src/index.d.ts +6 -0
  25. package/.medusa/server/src/index.js +7 -0
  26. package/.medusa/server/src/index.js.map +1 -0
  27. package/.medusa/server/src/modules/automations/actions/built-in-handlers.d.ts +100 -0
  28. package/.medusa/server/src/modules/automations/actions/built-in-handlers.js +194 -0
  29. package/.medusa/server/src/modules/automations/actions/built-in-handlers.js.map +1 -0
  30. package/.medusa/server/src/modules/automations/index.d.ts +35 -0
  31. package/.medusa/server/src/modules/automations/index.js +7 -0
  32. package/.medusa/server/src/modules/automations/index.js.map +1 -0
  33. package/.medusa/server/src/modules/automations/models/automation-execution-log.d.ts +10 -0
  34. package/.medusa/server/src/modules/automations/models/automation-execution-log.js +12 -0
  35. package/.medusa/server/src/modules/automations/models/automation-execution-log.js.map +1 -0
  36. package/.medusa/server/src/modules/automations/models/automation-rule.d.ts +14 -0
  37. package/.medusa/server/src/modules/automations/models/automation-rule.js +16 -0
  38. package/.medusa/server/src/modules/automations/models/automation-rule.js.map +1 -0
  39. package/.medusa/server/src/modules/automations/service.d.ts +53 -0
  40. package/.medusa/server/src/modules/automations/service.js +97 -0
  41. package/.medusa/server/src/modules/automations/service.js.map +1 -0
  42. package/.medusa/server/src/modules/automations/utils/rule-evaluator.d.ts +4 -0
  43. package/.medusa/server/src/modules/automations/utils/rule-evaluator.js +85 -0
  44. package/.medusa/server/src/modules/automations/utils/rule-evaluator.js.map +1 -0
  45. package/.medusa/server/src/sdk/index.d.ts +4 -0
  46. package/.medusa/server/src/sdk/index.js +5 -0
  47. package/.medusa/server/src/sdk/index.js.map +1 -0
  48. package/.medusa/server/src/subscribers/automation-events.d.ts +3 -0
  49. package/.medusa/server/src/subscribers/automation-events.js +29 -0
  50. package/.medusa/server/src/subscribers/automation-events.js.map +1 -0
  51. package/.medusa/server/src/types/index.d.ts +72 -0
  52. package/.medusa/server/src/types/index.js +2 -0
  53. package/.medusa/server/src/types/index.js.map +1 -0
  54. package/.medusa/server/src/workflows/index.d.ts +23 -0
  55. package/.medusa/server/src/workflows/index.js +30 -0
  56. package/.medusa/server/src/workflows/index.js.map +1 -0
  57. package/README.md +61 -2
  58. package/package.json +90 -3
  59. package/src/__tests__/automations.spec.ts +113 -0
  60. package/src/admin/i18n/en.json +4 -0
  61. package/src/admin/i18n/es.json +4 -0
  62. package/src/admin/i18n/index.ts +9 -0
  63. package/src/admin/routes/automations/page.tsx +134 -0
  64. package/src/api/admin/automations/[id]/logs/route.ts +20 -0
  65. package/src/api/admin/automations/[id]/route.ts +57 -0
  66. package/src/api/admin/automations/[id]/trigger/route.ts +26 -0
  67. package/src/api/admin/automations/actions/route.ts +16 -0
  68. package/src/api/admin/automations/route.ts +43 -0
  69. package/src/api/middlewares.ts +34 -0
  70. package/src/api/validators.ts +44 -0
  71. package/src/index.ts +9 -0
  72. package/src/modules/automations/actions/built-in-handlers.ts +228 -0
  73. package/src/modules/automations/index.ts +8 -0
  74. package/src/modules/automations/models/automation-execution-log.ts +15 -0
  75. package/src/modules/automations/models/automation-rule.ts +16 -0
  76. package/src/modules/automations/service.ts +144 -0
  77. package/src/modules/automations/utils/rule-evaluator.ts +95 -0
  78. package/src/sdk/index.ts +4 -0
  79. package/src/subscribers/automation-events.ts +32 -0
  80. package/src/types/index.ts +87 -0
  81. package/src/workflows/index.ts +56 -0
  82. package/tsconfig.json +17 -0
@@ -0,0 +1,134 @@
1
+ import { defineRouteConfig } from "@medusajs/admin-sdk"
2
+ import { Badge, Button, Container, Heading, Table, Text } from "@medusajs/ui"
3
+ import { useEffect, useState } from "react"
4
+
5
+ interface AutomationRuleRow {
6
+ id: string
7
+ name: string
8
+ trigger_type: "event" | "schedule" | "manual"
9
+ event_name?: string | null
10
+ is_active: boolean
11
+ run_count: number
12
+ }
13
+
14
+ const AutomationsPage = () => {
15
+ const [rules, setRules] = useState<AutomationRuleRow[]>([])
16
+ const [loading, setLoading] = useState(true)
17
+
18
+ const loadRules = () => {
19
+ setLoading(true)
20
+ fetch("/admin/automations", { credentials: "include" })
21
+ .then((res) => res.json())
22
+ .then((data: { rules?: AutomationRuleRow[] }) => {
23
+ setRules(data.rules ?? [])
24
+ })
25
+ .finally(() => setLoading(false))
26
+ }
27
+
28
+ useEffect(() => {
29
+ loadRules()
30
+ }, [])
31
+
32
+ const toggleActive = async (rule: AutomationRuleRow) => {
33
+ await fetch(`/admin/automations/${encodeURIComponent(rule.id)}`, {
34
+ method: "PATCH",
35
+ credentials: "include",
36
+ headers: { "Content-Type": "application/json" },
37
+ body: JSON.stringify({ is_active: !rule.is_active }),
38
+ })
39
+ loadRules()
40
+ }
41
+
42
+ const triggerNow = async (rule: AutomationRuleRow) => {
43
+ await fetch(`/admin/automations/${encodeURIComponent(rule.id)}/trigger`, {
44
+ method: "POST",
45
+ credentials: "include",
46
+ headers: { "Content-Type": "application/json" },
47
+ body: JSON.stringify({ context: {} }),
48
+ })
49
+ loadRules()
50
+ }
51
+
52
+ return (
53
+ <Container className="divide-y p-0">
54
+ <div className="flex items-center justify-between px-6 py-4">
55
+ <div>
56
+ <Heading level="h1">Automations</Heading>
57
+ <Text size="small" className="text-ui-fg-subtle">
58
+ Rule-based triggers, conditions, and notification/webhook actions.
59
+ </Text>
60
+ </div>
61
+ <Button size="small" variant="secondary" onClick={loadRules}>
62
+ Refresh
63
+ </Button>
64
+ </div>
65
+
66
+ <div className="px-6 py-4">
67
+ {loading ? (
68
+ <Text size="small" className="text-ui-fg-subtle">
69
+ Loading automation rules...
70
+ </Text>
71
+ ) : rules.length === 0 ? (
72
+ <Text size="small" className="text-ui-fg-subtle">
73
+ No automation rules configured yet. Create rules via POST
74
+ /admin/automations.
75
+ </Text>
76
+ ) : (
77
+ <Table>
78
+ <Table.Header>
79
+ <Table.Row>
80
+ <Table.HeaderCell>Rule</Table.HeaderCell>
81
+ <Table.HeaderCell>Trigger</Table.HeaderCell>
82
+ <Table.HeaderCell>Status</Table.HeaderCell>
83
+ <Table.HeaderCell>Runs</Table.HeaderCell>
84
+ <Table.HeaderCell>Actions</Table.HeaderCell>
85
+ </Table.Row>
86
+ </Table.Header>
87
+ <Table.Body>
88
+ {rules.map((rule) => (
89
+ <Table.Row key={rule.id}>
90
+ <Table.Cell>{rule.name}</Table.Cell>
91
+ <Table.Cell>
92
+ {rule.trigger_type}
93
+ {rule.event_name ? ` (${rule.event_name})` : ""}
94
+ </Table.Cell>
95
+ <Table.Cell>
96
+ <Badge
97
+ size="2xsmall"
98
+ color={rule.is_active ? "green" : "grey"}
99
+ >
100
+ {rule.is_active ? "Active" : "Paused"}
101
+ </Badge>
102
+ </Table.Cell>
103
+ <Table.Cell>{rule.run_count}</Table.Cell>
104
+ <Table.Cell className="flex gap-2">
105
+ <Button
106
+ size="small"
107
+ variant="secondary"
108
+ onClick={() => toggleActive(rule)}
109
+ >
110
+ {rule.is_active ? "Pause" : "Enable"}
111
+ </Button>
112
+ <Button
113
+ size="small"
114
+ variant="primary"
115
+ onClick={() => triggerNow(rule)}
116
+ >
117
+ Run
118
+ </Button>
119
+ </Table.Cell>
120
+ </Table.Row>
121
+ ))}
122
+ </Table.Body>
123
+ </Table>
124
+ )}
125
+ </div>
126
+ </Container>
127
+ )
128
+ }
129
+
130
+ export const config = defineRouteConfig({
131
+ label: "Automations",
132
+ })
133
+
134
+ export default AutomationsPage
@@ -0,0 +1,20 @@
1
+ import type {
2
+ AuthenticatedMedusaRequest,
3
+ MedusaResponse,
4
+ } from "@medusajs/framework/http"
5
+ import { AUTOMATIONS_MODULE } from "../../../../../modules/automations"
6
+ import type AutomationsModuleService from "../../../../../modules/automations/service"
7
+
8
+ export async function GET(
9
+ req: AuthenticatedMedusaRequest,
10
+ res: MedusaResponse
11
+ ) {
12
+ const service = req.scope.resolve(
13
+ AUTOMATIONS_MODULE
14
+ ) as AutomationsModuleService
15
+ const logs = await service.listAutomationExecutionLogs(
16
+ { rule_id: req.params.id },
17
+ { order: { created_at: "DESC" }, take: 50 }
18
+ )
19
+ res.json({ logs })
20
+ }
@@ -0,0 +1,57 @@
1
+ import type {
2
+ AuthenticatedMedusaRequest,
3
+ MedusaResponse,
4
+ } from "@medusajs/framework/http"
5
+ import { AUTOMATIONS_MODULE } from "../../../../modules/automations"
6
+ import type AutomationsModuleService from "../../../../modules/automations/service"
7
+ import type { UpdateAutomationRuleInput } from "../../../../types"
8
+
9
+ export async function GET(
10
+ req: AuthenticatedMedusaRequest,
11
+ res: MedusaResponse
12
+ ) {
13
+ const service = req.scope.resolve(
14
+ AUTOMATIONS_MODULE
15
+ ) as AutomationsModuleService
16
+ const rules = await service.listAutomationRules({ id: req.params.id })
17
+ if (!rules[0]) {
18
+ res.status(404).json({ message: "Automation rule not found" })
19
+ return
20
+ }
21
+ res.json({ rule: rules[0] })
22
+ }
23
+
24
+ export async function PATCH(
25
+ req: AuthenticatedMedusaRequest,
26
+ res: MedusaResponse
27
+ ) {
28
+ const service = req.scope.resolve(
29
+ AUTOMATIONS_MODULE
30
+ ) as AutomationsModuleService
31
+ const { conditions, actions, ...rest } = req.validatedBody as Omit<
32
+ UpdateAutomationRuleInput,
33
+ "id"
34
+ >
35
+ const rule = await service.updateAutomationRules({
36
+ id: req.params.id,
37
+ ...rest,
38
+ ...(conditions !== undefined
39
+ ? { conditions: conditions as unknown as Record<string, unknown> }
40
+ : {}),
41
+ ...(actions !== undefined
42
+ ? { actions: actions as unknown as Record<string, unknown> }
43
+ : {}),
44
+ })
45
+ res.json({ rule })
46
+ }
47
+
48
+ export async function DELETE(
49
+ req: AuthenticatedMedusaRequest,
50
+ res: MedusaResponse
51
+ ) {
52
+ const service = req.scope.resolve(
53
+ AUTOMATIONS_MODULE
54
+ ) as AutomationsModuleService
55
+ await service.deleteAutomationRules([req.params.id])
56
+ res.json({ id: req.params.id, deleted: true })
57
+ }
@@ -0,0 +1,26 @@
1
+ import type {
2
+ AuthenticatedMedusaRequest,
3
+ MedusaResponse,
4
+ } from "@medusajs/framework/http"
5
+ import { evaluateAndExecuteAutomationsWorkflow } from "../../../../../workflows"
6
+
7
+ export async function POST(
8
+ req: AuthenticatedMedusaRequest,
9
+ res: MedusaResponse
10
+ ) {
11
+ const body = (req.validatedBody || {}) as {
12
+ context?: Record<string, unknown>
13
+ event_name?: string
14
+ }
15
+ const { result } = await evaluateAndExecuteAutomationsWorkflow(req.scope).run(
16
+ {
17
+ input: {
18
+ trigger_type: "manual",
19
+ event_name: body.event_name || "manual.trigger",
20
+ context: body.context || {},
21
+ rule_id: req.params.id,
22
+ },
23
+ }
24
+ )
25
+ res.json({ execution: result })
26
+ }
@@ -0,0 +1,16 @@
1
+ import type {
2
+ AuthenticatedMedusaRequest,
3
+ MedusaResponse,
4
+ } from "@medusajs/framework/http"
5
+ import { AUTOMATIONS_MODULE } from "../../../../modules/automations"
6
+ import type AutomationsModuleService from "../../../../modules/automations/service"
7
+
8
+ export async function GET(
9
+ req: AuthenticatedMedusaRequest,
10
+ res: MedusaResponse
11
+ ) {
12
+ const service = req.scope.resolve(
13
+ AUTOMATIONS_MODULE
14
+ ) as AutomationsModuleService
15
+ res.json({ actions: await service.listActionHandlers() })
16
+ }
@@ -0,0 +1,43 @@
1
+ import type {
2
+ AuthenticatedMedusaRequest,
3
+ MedusaResponse,
4
+ } from "@medusajs/framework/http"
5
+ import { AUTOMATIONS_MODULE } from "../../../modules/automations"
6
+ import type AutomationsModuleService from "../../../modules/automations/service"
7
+ import type { CreateAutomationRuleInput } from "../../../types"
8
+
9
+ export async function GET(
10
+ req: AuthenticatedMedusaRequest,
11
+ res: MedusaResponse
12
+ ) {
13
+ const service = req.scope.resolve(
14
+ AUTOMATIONS_MODULE
15
+ ) as AutomationsModuleService
16
+ const rules = await service.listAutomationRules(
17
+ {},
18
+ { order: { created_at: "DESC" } }
19
+ )
20
+ res.json({ rules })
21
+ }
22
+
23
+ export async function POST(
24
+ req: AuthenticatedMedusaRequest,
25
+ res: MedusaResponse
26
+ ) {
27
+ const service = req.scope.resolve(
28
+ AUTOMATIONS_MODULE
29
+ ) as AutomationsModuleService
30
+ const input = req.validatedBody as CreateAutomationRuleInput
31
+ const rule = await service.createAutomationRules({
32
+ name: input.name,
33
+ description: input.description ?? null,
34
+ trigger_type: input.trigger_type ?? "event",
35
+ event_name: input.event_name ?? null,
36
+ cron_expression: input.cron_expression ?? null,
37
+ conditions: (input.conditions ?? []) as unknown as Record<string, unknown>,
38
+ actions: input.actions as unknown as Record<string, unknown>,
39
+ is_active: input.is_active ?? true,
40
+ metadata: input.metadata ?? null,
41
+ })
42
+ res.status(201).json({ rule })
43
+ }
@@ -0,0 +1,34 @@
1
+ import {
2
+ authenticate,
3
+ defineMiddlewares,
4
+ validateAndTransformBody,
5
+ } from "@medusajs/framework/http"
6
+ import {
7
+ createAutomationRuleSchema,
8
+ triggerAutomationRuleSchema,
9
+ updateAutomationRuleSchema,
10
+ } from "./validators"
11
+
12
+ export default defineMiddlewares({
13
+ routes: [
14
+ {
15
+ matcher: "/admin/automations*",
16
+ middlewares: [authenticate("user", ["session", "bearer", "api-key"])],
17
+ },
18
+ {
19
+ matcher: "/admin/automations",
20
+ method: "POST",
21
+ middlewares: [validateAndTransformBody(createAutomationRuleSchema)],
22
+ },
23
+ {
24
+ matcher: "/admin/automations/:id",
25
+ method: "PATCH",
26
+ middlewares: [validateAndTransformBody(updateAutomationRuleSchema)],
27
+ },
28
+ {
29
+ matcher: "/admin/automations/:id/trigger",
30
+ method: "POST",
31
+ middlewares: [validateAndTransformBody(triggerAutomationRuleSchema)],
32
+ },
33
+ ],
34
+ })
@@ -0,0 +1,44 @@
1
+ import { z } from "@medusajs/framework/zod"
2
+
3
+ export const conditionSchema = z.object({
4
+ field: z.string().min(1),
5
+ operator: z.enum([
6
+ "eq",
7
+ "neq",
8
+ "gt",
9
+ "gte",
10
+ "lt",
11
+ "lte",
12
+ "in",
13
+ "not_in",
14
+ "contains",
15
+ "not_contains",
16
+ "exists",
17
+ "not_exists",
18
+ ]),
19
+ value: z.unknown().optional(),
20
+ })
21
+
22
+ export const actionConfigSchema = z.object({
23
+ type: z.string().min(1),
24
+ config: z.record(z.string(), z.unknown()).optional(),
25
+ })
26
+
27
+ export const createAutomationRuleSchema = z.object({
28
+ name: z.string().min(1),
29
+ description: z.string().nullable().optional(),
30
+ trigger_type: z.enum(["event", "schedule", "manual"]).optional(),
31
+ event_name: z.string().nullable().optional(),
32
+ cron_expression: z.string().nullable().optional(),
33
+ conditions: z.array(conditionSchema).optional(),
34
+ actions: z.array(actionConfigSchema).min(1),
35
+ is_active: z.boolean().optional(),
36
+ metadata: z.record(z.string(), z.unknown()).nullable().optional(),
37
+ })
38
+
39
+ export const updateAutomationRuleSchema = createAutomationRuleSchema.partial()
40
+
41
+ export const triggerAutomationRuleSchema = z.object({
42
+ context: z.record(z.string(), z.unknown()).optional(),
43
+ event_name: z.string().optional(),
44
+ })
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ export * from "./types"
2
+ export {
3
+ AUTOMATIONS_MODULE,
4
+ default as AutomationsModule,
5
+ } from "./modules/automations"
6
+ export { AutomationsModuleService } from "./modules/automations/service"
7
+ export * from "./modules/automations/utils/rule-evaluator"
8
+ export * from "./modules/automations/actions/built-in-handlers"
9
+ export * from "./workflows"
@@ -0,0 +1,228 @@
1
+ import { Modules } from "@medusajs/framework/utils"
2
+ import type { AutomationActionHandler } from "../../../types"
3
+ import { resolveContextPath } from "../utils/rule-evaluator"
4
+
5
+ function resolveRecipient(
6
+ rawTo: unknown,
7
+ context: Record<string, any>
8
+ ): string {
9
+ if (typeof rawTo !== "string" || !rawTo.trim()) {
10
+ return String(
11
+ context?.email ||
12
+ context?.customer?.email ||
13
+ context?.order?.email ||
14
+ context?.phone ||
15
+ context?.customer?.phone ||
16
+ ""
17
+ ).trim()
18
+ }
19
+ const trimmed = rawTo.trim()
20
+ const match = /^\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}$/.exec(trimmed)
21
+ if (!match) return trimmed
22
+ const resolved = resolveContextPath(context, match[1])
23
+ return resolved != null ? String(resolved).trim() : ""
24
+ }
25
+
26
+ function isSafeWebhookUrl(rawUrl: string): boolean {
27
+ try {
28
+ const parsed = new URL(rawUrl)
29
+ if (parsed.protocol === "https:") return true
30
+ if (
31
+ parsed.protocol === "http:" &&
32
+ process.env.NODE_ENV !== "production" &&
33
+ (parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost")
34
+ ) {
35
+ return true
36
+ }
37
+ return false
38
+ } catch {
39
+ return false
40
+ }
41
+ }
42
+
43
+ export class MedusaNotificationActionHandler implements AutomationActionHandler {
44
+ id = "notification"
45
+ label = "Medusa Notification"
46
+ description =
47
+ "Dispatch notifications via Medusa Modules.NOTIFICATION (Email, SMS, WhatsApp, Telegram, Slack)"
48
+ enabled = true
49
+ fields = [
50
+ {
51
+ name: "channel",
52
+ key: "channel",
53
+ label: "Channel",
54
+ type: "select" as const,
55
+ required: true,
56
+ defaultValue: "email",
57
+ options: [
58
+ { value: "email", name: "Email" },
59
+ { value: "sms", name: "SMS" },
60
+ { value: "whatsapp", name: "WhatsApp" },
61
+ { value: "telegram", name: "Telegram" },
62
+ { value: "slack", name: "Slack" },
63
+ ],
64
+ },
65
+ {
66
+ name: "template",
67
+ key: "template",
68
+ label: "Template ID / Name",
69
+ type: "text" as const,
70
+ required: true,
71
+ },
72
+ {
73
+ name: "to",
74
+ key: "to",
75
+ label: "Recipient (or {{customer.email}})",
76
+ type: "text" as const,
77
+ required: false,
78
+ },
79
+ ]
80
+
81
+ async executeAction({
82
+ action,
83
+ context,
84
+ container,
85
+ eventName,
86
+ }: Parameters<AutomationActionHandler["executeAction"]>[0]) {
87
+ const cfg = action.config || {}
88
+ const channel = String(cfg.channel || "email").trim()
89
+ const template = String(cfg.template || cfg.template_id || "").trim()
90
+ const to = resolveRecipient(cfg.to, context)
91
+
92
+ if (!template) {
93
+ return { success: false, message: "Notification template is required" }
94
+ }
95
+ if (!to) {
96
+ return {
97
+ success: false,
98
+ message: "Notification recipient could not be resolved",
99
+ }
100
+ }
101
+
102
+ const notificationService = container.resolve(Modules.NOTIFICATION)
103
+ const result = await notificationService.createNotifications({
104
+ to,
105
+ channel,
106
+ template,
107
+ data: {
108
+ ...context,
109
+ event_name: eventName,
110
+ ...(cfg.subject ? { subject: String(cfg.subject) } : {}),
111
+ },
112
+ })
113
+
114
+ return {
115
+ success: true,
116
+ message: `Notification dispatched via ${channel}`,
117
+ data: result,
118
+ }
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Optional zero-hard-dependency bridge to `@vicacha-devs/medusa-plugin-notifications`.
124
+ * Resolves `notificationsModuleService` if installed, or falls back to `Modules.NOTIFICATION`.
125
+ */
126
+ export class NotificationStudioBridgeHandler implements AutomationActionHandler {
127
+ id = "mpn-notification-studio"
128
+ label = "Notification Studio (Optional Bridge)"
129
+ description =
130
+ "Dispatch via @vicacha-devs/medusa-plugin-notifications when installed, falling back to Modules.NOTIFICATION"
131
+ enabled = true
132
+ fields = [
133
+ {
134
+ name: "channel",
135
+ key: "channel",
136
+ label: "Channel",
137
+ type: "select" as const,
138
+ required: false,
139
+ defaultValue: "email",
140
+ options: [
141
+ { value: "email", name: "Email" },
142
+ { value: "whatsapp", name: "WhatsApp" },
143
+ { value: "telegram", name: "Telegram" },
144
+ { value: "sms", name: "SMS" },
145
+ { value: "slack", name: "Slack" },
146
+ ],
147
+ },
148
+ {
149
+ name: "template_id",
150
+ key: "template_id",
151
+ label: "Template ID",
152
+ type: "text" as const,
153
+ required: true,
154
+ },
155
+ {
156
+ name: "to",
157
+ key: "to",
158
+ label: "Recipient (or {{customer.email}})",
159
+ type: "text" as const,
160
+ required: false,
161
+ },
162
+ ]
163
+
164
+ async executeAction(
165
+ params: Parameters<AutomationActionHandler["executeAction"]>[0]
166
+ ) {
167
+ const fallback = new MedusaNotificationActionHandler()
168
+ return fallback.executeAction(params)
169
+ }
170
+ }
171
+
172
+ export class WebhookActionHandler implements AutomationActionHandler {
173
+ id = "webhook"
174
+ label = "Outgoing HTTP Webhook"
175
+ description =
176
+ "Send an SSRF-guarded JSON POST payload to an external HTTPS endpoint"
177
+ enabled = true
178
+ fields = [
179
+ {
180
+ name: "url",
181
+ key: "url",
182
+ label: "Webhook URL (https://...)",
183
+ type: "text" as const,
184
+ required: true,
185
+ },
186
+ ]
187
+
188
+ async executeAction({
189
+ action,
190
+ context,
191
+ eventName,
192
+ trigger,
193
+ }: Parameters<AutomationActionHandler["executeAction"]>[0]) {
194
+ const url = String(action.config?.url || "").trim()
195
+ if (!url || !isSafeWebhookUrl(url)) {
196
+ return {
197
+ success: false,
198
+ message:
199
+ "Webhook URL must use https:// (or loopback in non-production)",
200
+ }
201
+ }
202
+
203
+ const res = await fetch(url, {
204
+ method: "POST",
205
+ headers: { "Content-Type": "application/json" },
206
+ body: JSON.stringify({
207
+ event: eventName,
208
+ trigger: trigger.type,
209
+ data: context,
210
+ }),
211
+ signal: AbortSignal.timeout(10_000),
212
+ })
213
+
214
+ return {
215
+ success: res.ok,
216
+ message: `Webhook responded with HTTP ${res.status}`,
217
+ data: { status: res.status },
218
+ }
219
+ }
220
+ }
221
+
222
+ export function createBuiltInActionHandlers(): AutomationActionHandler[] {
223
+ return [
224
+ new MedusaNotificationActionHandler(),
225
+ new NotificationStudioBridgeHandler(),
226
+ new WebhookActionHandler(),
227
+ ]
228
+ }
@@ -0,0 +1,8 @@
1
+ import { Module } from "@medusajs/framework/utils"
2
+ import AutomationsModuleService from "./service"
3
+
4
+ export const AUTOMATIONS_MODULE = "automations"
5
+
6
+ export default Module(AUTOMATIONS_MODULE, {
7
+ service: AutomationsModuleService,
8
+ })
@@ -0,0 +1,15 @@
1
+ import { model } from "@medusajs/framework/utils"
2
+
3
+ export const AutomationExecutionLogModel = model.define(
4
+ "automation_execution_log",
5
+ {
6
+ id: model.id().primaryKey(),
7
+ rule_id: model.text(),
8
+ trigger_type: model.enum(["event", "schedule", "manual"]).default("event"),
9
+ event_name: model.text().nullable(),
10
+ status: model.enum(["success", "failed", "skipped"]).default("success"),
11
+ actions_executed: model.number().default(0),
12
+ result_summary: model.json().nullable(),
13
+ error_message: model.text().nullable(),
14
+ }
15
+ )
@@ -0,0 +1,16 @@
1
+ import { model } from "@medusajs/framework/utils"
2
+
3
+ export const AutomationRuleModel = model.define("automation_rule", {
4
+ id: model.id().primaryKey(),
5
+ name: model.text().searchable(),
6
+ description: model.text().nullable(),
7
+ trigger_type: model.enum(["event", "schedule", "manual"]).default("event"),
8
+ event_name: model.text().nullable(),
9
+ cron_expression: model.text().nullable(),
10
+ conditions: model.json().nullable(),
11
+ actions: model.json(),
12
+ is_active: model.boolean().default(true),
13
+ run_count: model.number().default(0),
14
+ last_run_at: model.dateTime().nullable(),
15
+ metadata: model.json().nullable(),
16
+ })