@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,144 @@
1
+ import { MedusaService } from "@medusajs/framework/utils"
2
+ import type {
3
+ AutomationActionConfig,
4
+ AutomationActionHandler,
5
+ AutomationActionResult,
6
+ AutomationCondition,
7
+ AutomationTriggerType,
8
+ } from "../../types"
9
+ import { createBuiltInActionHandlers } from "./actions/built-in-handlers"
10
+ import { AutomationExecutionLogModel } from "./models/automation-execution-log"
11
+ import { AutomationRuleModel } from "./models/automation-rule"
12
+ import { evaluateConditions } from "./utils/rule-evaluator"
13
+
14
+ export interface ExecuteRuleParams {
15
+ rule: Record<string, any>
16
+ triggerType: AutomationTriggerType
17
+ eventName: string
18
+ context: Record<string, any>
19
+ container: any
20
+ }
21
+
22
+ export class AutomationsModuleService extends MedusaService({
23
+ AutomationRule: AutomationRuleModel,
24
+ AutomationExecutionLog: AutomationExecutionLogModel,
25
+ }) {
26
+ private readonly handlers_ = new Map<string, AutomationActionHandler>()
27
+
28
+ constructor(
29
+ container: Record<string, unknown>,
30
+ options?: { actionHandlers?: AutomationActionHandler[] }
31
+ ) {
32
+ super(container, options)
33
+ for (const handler of createBuiltInActionHandlers()) {
34
+ this.handlers_.set(handler.id, handler)
35
+ }
36
+ for (const custom of options?.actionHandlers ?? []) {
37
+ this.handlers_.set(custom.id, custom)
38
+ }
39
+ }
40
+
41
+ async registerActionHandler(handler: AutomationActionHandler): Promise<void> {
42
+ this.handlers_.set(handler.id, handler)
43
+ }
44
+
45
+ async listActionHandlers(): Promise<
46
+ Array<{
47
+ id: string
48
+ label: string
49
+ description?: string
50
+ enabled: boolean
51
+ fields: AutomationActionHandler["fields"]
52
+ }>
53
+ > {
54
+ return [...this.handlers_.values()].map((h) => ({
55
+ id: h.id,
56
+ label: h.label,
57
+ description: h.description,
58
+ enabled: h.enabled ?? true,
59
+ fields: h.fields ?? [],
60
+ }))
61
+ }
62
+
63
+ async executeRule({
64
+ rule,
65
+ triggerType,
66
+ eventName,
67
+ context,
68
+ container,
69
+ }: ExecuteRuleParams): Promise<{
70
+ status: "success" | "failed" | "skipped"
71
+ results: AutomationActionResult[]
72
+ }> {
73
+ const conditions = (rule.conditions ?? []) as AutomationCondition[]
74
+ if (!evaluateConditions(conditions, context)) {
75
+ await this.createAutomationExecutionLogs({
76
+ rule_id: String(rule.id),
77
+ trigger_type: triggerType,
78
+ event_name: eventName,
79
+ status: "skipped",
80
+ actions_executed: 0,
81
+ result_summary: { reason: "conditions_not_met" },
82
+ })
83
+ return { status: "skipped", results: [] }
84
+ }
85
+
86
+ const actions = (
87
+ Array.isArray(rule.actions) ? rule.actions : []
88
+ ) as AutomationActionConfig[]
89
+ const results: AutomationActionResult[] = []
90
+ let failed = false
91
+
92
+ for (const action of actions) {
93
+ const handler = this.handlers_.get(action.type)
94
+ if (!handler || handler.enabled === false) {
95
+ results.push({
96
+ success: false,
97
+ message: `Action handler '${action.type}' not found or disabled`,
98
+ })
99
+ failed = true
100
+ continue
101
+ }
102
+
103
+ try {
104
+ const res = await handler.executeAction({
105
+ trigger: { type: triggerType, event_name: eventName },
106
+ action,
107
+ context,
108
+ container,
109
+ eventName,
110
+ })
111
+ results.push(res)
112
+ if (!res.success) failed = true
113
+ } catch (err) {
114
+ const msg =
115
+ err instanceof Error ? err.message : "Action execution error"
116
+ results.push({ success: false, message: msg })
117
+ failed = true
118
+ }
119
+ }
120
+
121
+ const status = failed ? "failed" : "success"
122
+ await this.createAutomationExecutionLogs({
123
+ rule_id: String(rule.id),
124
+ trigger_type: triggerType,
125
+ event_name: eventName,
126
+ status,
127
+ actions_executed: results.length,
128
+ result_summary: { results },
129
+ error_message: failed
130
+ ? results.find((r) => !r.success)?.message || "Action failed"
131
+ : null,
132
+ })
133
+
134
+ await this.updateAutomationRules({
135
+ id: String(rule.id),
136
+ run_count: Number(rule.run_count || 0) + 1,
137
+ last_run_at: new Date(),
138
+ })
139
+
140
+ return { status, results }
141
+ }
142
+ }
143
+
144
+ export default AutomationsModuleService
@@ -0,0 +1,95 @@
1
+ import type { AutomationCondition } from "../../../types"
2
+
3
+ const BLOCKED_SEGMENTS = new Set(["__proto__", "constructor", "prototype"])
4
+
5
+ export function resolveContextPath(
6
+ source: Record<string, any> | null | undefined,
7
+ path: string
8
+ ): unknown {
9
+ if (!source || typeof source !== "object" || !path) {
10
+ return undefined
11
+ }
12
+ const segments = path.trim().split(".").filter(Boolean)
13
+ let current: any = source
14
+ for (const seg of segments) {
15
+ if (BLOCKED_SEGMENTS.has(seg)) {
16
+ return undefined
17
+ }
18
+ if (current == null || typeof current !== "object") {
19
+ return undefined
20
+ }
21
+ if (Array.isArray(current) && /^\d+$/.test(seg)) {
22
+ current = current[Number(seg)]
23
+ } else if (Object.prototype.hasOwnProperty.call(current, seg)) {
24
+ current = current[seg]
25
+ } else {
26
+ return undefined
27
+ }
28
+ }
29
+ return current
30
+ }
31
+
32
+ export function evaluateCondition(
33
+ condition: AutomationCondition,
34
+ context: Record<string, any>
35
+ ): boolean {
36
+ const actual = resolveContextPath(context, condition.field)
37
+ const expected = condition.value
38
+
39
+ switch (condition.operator) {
40
+ case "exists":
41
+ return actual !== undefined && actual !== null && actual !== ""
42
+ case "not_exists":
43
+ return actual === undefined || actual === null || actual === ""
44
+ case "eq":
45
+ return actual === expected
46
+ case "neq":
47
+ return actual !== expected
48
+ case "gt":
49
+ return typeof actual === "number" && typeof expected === "number"
50
+ ? actual > expected
51
+ : Number(actual) > Number(expected)
52
+ case "gte":
53
+ return typeof actual === "number" && typeof expected === "number"
54
+ ? actual >= expected
55
+ : Number(actual) >= Number(expected)
56
+ case "lt":
57
+ return typeof actual === "number" && typeof expected === "number"
58
+ ? actual < expected
59
+ : Number(actual) < Number(expected)
60
+ case "lte":
61
+ return typeof actual === "number" && typeof expected === "number"
62
+ ? actual <= expected
63
+ : Number(actual) <= Number(expected)
64
+ case "in":
65
+ return Array.isArray(expected) && expected.includes(actual)
66
+ case "not_in":
67
+ return Array.isArray(expected) && !expected.includes(actual)
68
+ case "contains": {
69
+ if (Array.isArray(actual)) return actual.includes(expected)
70
+ if (typeof actual === "string" && typeof expected === "string") {
71
+ return actual.toLowerCase().includes(expected.toLowerCase())
72
+ }
73
+ return false
74
+ }
75
+ case "not_contains": {
76
+ if (Array.isArray(actual)) return !actual.includes(expected)
77
+ if (typeof actual === "string" && typeof expected === "string") {
78
+ return !actual.toLowerCase().includes(expected.toLowerCase())
79
+ }
80
+ return true
81
+ }
82
+ default:
83
+ return false
84
+ }
85
+ }
86
+
87
+ export function evaluateConditions(
88
+ conditions: AutomationCondition[] | null | undefined,
89
+ context: Record<string, any>
90
+ ): boolean {
91
+ if (!Array.isArray(conditions) || conditions.length === 0) {
92
+ return true
93
+ }
94
+ return conditions.every((cond) => evaluateCondition(cond, context))
95
+ }
@@ -0,0 +1,4 @@
1
+ export const automationsEndpoints = {
2
+ adminBase: "/admin/automations",
3
+ storeBase: "/store/automations",
4
+ } as const
@@ -0,0 +1,32 @@
1
+ import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
2
+ import { evaluateAndExecuteAutomationsWorkflow } from "../workflows"
3
+
4
+ export default async function automationEventsSubscriber({
5
+ event: { name, data },
6
+ container,
7
+ }: SubscriberArgs<Record<string, any>>) {
8
+ if (!name) return
9
+ try {
10
+ await evaluateAndExecuteAutomationsWorkflow(container).run({
11
+ input: {
12
+ trigger_type: "event",
13
+ event_name: name,
14
+ context: data || {},
15
+ },
16
+ })
17
+ } catch {
18
+ // Non-blocking in event subscriber so commerce lifecycle never fails
19
+ }
20
+ }
21
+
22
+ export const config: SubscriberConfig = {
23
+ event: [
24
+ "order.placed",
25
+ "order.completed",
26
+ "order.canceled",
27
+ "customer.created",
28
+ "product.created",
29
+ "product.updated",
30
+ "inventory-level.updated",
31
+ ],
32
+ }
@@ -0,0 +1,87 @@
1
+ export type AutomationTriggerType = "event" | "schedule" | "manual"
2
+
3
+ export type RuleOperator =
4
+ | "eq"
5
+ | "neq"
6
+ | "gt"
7
+ | "gte"
8
+ | "lt"
9
+ | "lte"
10
+ | "in"
11
+ | "not_in"
12
+ | "contains"
13
+ | "not_contains"
14
+ | "exists"
15
+ | "not_exists"
16
+
17
+ export interface AutomationCondition {
18
+ field: string
19
+ operator: RuleOperator
20
+ value?: unknown
21
+ }
22
+
23
+ export interface AutomationActionConfig {
24
+ type: string
25
+ config?: Record<string, unknown>
26
+ }
27
+
28
+ export interface AutomationActionResult {
29
+ success: boolean
30
+ message?: string
31
+ data?: unknown
32
+ }
33
+
34
+ export interface AutomationActionField {
35
+ name: string
36
+ key: string
37
+ label: string
38
+ type: "text" | "email" | "textarea" | "select" | "boolean" | "number"
39
+ required?: boolean
40
+ defaultValue?: unknown
41
+ options?: Array<{ value: string; name: string }>
42
+ }
43
+
44
+ export interface AutomationActionHandler {
45
+ id: string
46
+ label: string
47
+ description?: string
48
+ enabled?: boolean
49
+ fields?: AutomationActionField[]
50
+ executeAction: (params: {
51
+ trigger: { type: AutomationTriggerType; event_name?: string | null }
52
+ action: AutomationActionConfig
53
+ context: Record<string, any>
54
+ container: any
55
+ eventName: string
56
+ }) => Promise<AutomationActionResult>
57
+ }
58
+
59
+ export interface CreateAutomationRuleInput {
60
+ name: string
61
+ description?: string | null
62
+ trigger_type?: AutomationTriggerType
63
+ event_name?: string | null
64
+ cron_expression?: string | null
65
+ conditions?: AutomationCondition[]
66
+ actions: AutomationActionConfig[]
67
+ is_active?: boolean
68
+ metadata?: Record<string, unknown> | null
69
+ }
70
+
71
+ export interface UpdateAutomationRuleInput {
72
+ id: string
73
+ name?: string
74
+ description?: string | null
75
+ trigger_type?: AutomationTriggerType
76
+ event_name?: string | null
77
+ cron_expression?: string | null
78
+ conditions?: AutomationCondition[]
79
+ actions?: AutomationActionConfig[]
80
+ is_active?: boolean
81
+ metadata?: Record<string, unknown> | null
82
+ }
83
+
84
+ export interface CreateAutomationsInput {
85
+ label: string
86
+ active?: boolean
87
+ }
@@ -0,0 +1,56 @@
1
+ import {
2
+ createStep,
3
+ createWorkflow,
4
+ StepResponse,
5
+ WorkflowResponse,
6
+ } from "@medusajs/framework/workflows-sdk"
7
+ import { AUTOMATIONS_MODULE } from "../modules/automations"
8
+ import type AutomationsModuleService from "../modules/automations/service"
9
+ import type { AutomationTriggerType } from "../types"
10
+
11
+ export interface DispatchAutomationEventInput {
12
+ trigger_type: AutomationTriggerType
13
+ event_name: string
14
+ context: Record<string, any>
15
+ rule_id?: string
16
+ }
17
+
18
+ export const evaluateAndExecuteAutomationsStep = createStep(
19
+ "evaluate-and-execute-automations",
20
+ async (input: DispatchAutomationEventInput, { container }) => {
21
+ const service = container.resolve(
22
+ AUTOMATIONS_MODULE
23
+ ) as AutomationsModuleService
24
+
25
+ const filters: Record<string, unknown> = input.rule_id
26
+ ? { id: input.rule_id }
27
+ : {
28
+ is_active: true,
29
+ trigger_type: input.trigger_type,
30
+ event_name: input.event_name,
31
+ }
32
+
33
+ const rules = await service.listAutomationRules(filters)
34
+ const executions = []
35
+ for (const rule of rules) {
36
+ const outcome = await service.executeRule({
37
+ rule,
38
+ triggerType: input.trigger_type,
39
+ eventName: input.event_name,
40
+ context: input.context || {},
41
+ container,
42
+ })
43
+ executions.push({ rule_id: rule.id, ...outcome })
44
+ }
45
+
46
+ return new StepResponse({ matched_rules: rules.length, executions })
47
+ }
48
+ )
49
+
50
+ export const evaluateAndExecuteAutomationsWorkflow = createWorkflow(
51
+ "evaluate-and-execute-automations",
52
+ (input: DispatchAutomationEventInput) => {
53
+ const result = evaluateAndExecuteAutomationsStep(input)
54
+ return new WorkflowResponse(result)
55
+ }
56
+ )
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "extends": "../../packages/typescript-config/plugin.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./",
5
+ "outDir": "./.medusa/server",
6
+ "noEmit": false
7
+ },
8
+ "include": ["**/*", ".medusa/types/*"],
9
+ "exclude": [
10
+ "node_modules",
11
+ ".medusa/server",
12
+ ".medusa/admin",
13
+ "src/admin",
14
+ "src/__tests__",
15
+ "eslint.config.*"
16
+ ]
17
+ }