Skip to main content

qail_workflow/
step.rs

1//! Workflow steps — the composable building blocks of a workflow.
2//!
3//! Each step represents a single atomic action: execute a query,
4//! send a notification, wait for an event, or branch on a condition.
5
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9
10use crate::channel::ChannelKind;
11use crate::payment::PaymentKind;
12
13/// A branch predicate evaluated against one workflow context key.
14#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
15pub enum WorkflowBranchCondition {
16    /// Text equality. Strings compare directly; other JSON values compare by JSON text.
17    Equals(String),
18    /// Text inequality. Missing context does not match.
19    NotEquals(String),
20    /// Text membership. Strings compare directly; other JSON values compare by JSON text.
21    OneOf(Vec<String>),
22    /// Context key exists.
23    Exists,
24    /// Context key does not exist.
25    Missing,
26    /// Context key is JSON null.
27    Null,
28    /// Context key is a boolean with this value.
29    Bool(bool),
30    /// Numeric comparison.
31    NumberGt(i64),
32    /// Numeric comparison.
33    NumberGte(i64),
34    /// Numeric comparison.
35    NumberLt(i64),
36    /// Numeric comparison.
37    NumberLte(i64),
38    /// Text contains a substring.
39    StringContains(String),
40}
41
42/// A single step in a workflow execution.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub enum WorkflowStep {
45    /// Execute a QAIL query against the database.
46    /// The `cmd_json` field stores QAIL wire text (`qail_core::wire::encode_cmd_text`).
47    /// The `store_as` key saves the result into WorkflowContext for later steps.
48    Query {
49        /// QAIL command encoded in QAIL wire text.
50        cmd_json: String,
51        /// Optional key to store query results in context
52        store_as: Option<String>,
53    },
54
55    /// Send a notification via a channel (WhatsApp, Email, SMS, Push).
56    Notify {
57        /// Which channel to send through
58        channel: ChannelKind,
59        /// Template name (e.g., "opportunity_alert", "booking_confirmed")
60        template: String,
61        /// Context key that resolves to the recipient address
62        recipient_key: String,
63        /// Optional extra payload (template variables)
64        payload_key: Option<String>,
65    },
66
67    /// Wait for an external event (webhook callback, user action, timeout).
68    Wait {
69        /// Event key to listen for (matched against incoming webhook/callback)
70        event: String,
71        /// Maximum time to wait before triggering on_timeout
72        timeout: Duration,
73        /// Steps to execute if timeout is reached
74        on_timeout: Vec<WorkflowStep>,
75    },
76
77    /// Conditional branching based on a context value.
78    Branch {
79        /// Context key to evaluate
80        condition_key: String,
81        /// Map of value → steps to execute
82        branches: Vec<(String, Vec<WorkflowStep>)>,
83        /// Default steps if no branch matches
84        default: Vec<WorkflowStep>,
85    },
86
87    /// Conditional branching with richer predicates.
88    BranchWhen {
89        /// Context key to evaluate
90        condition_key: String,
91        /// Ordered predicates and steps. The first matching predicate is selected.
92        branches: Vec<(WorkflowBranchCondition, Vec<WorkflowStep>)>,
93        /// Default steps if no predicate matches
94        default: Vec<WorkflowStep>,
95    },
96
97    /// Execute steps for each item in a context list.
98    ForEach {
99        /// Context key containing a JSON array
100        list_key: String,
101        /// Steps to execute per item (item available as "item" in context)
102        steps: Vec<WorkflowStep>,
103    },
104
105    /// Transition to a new workflow state.
106    Transition {
107        /// Target state name
108        to: String,
109    },
110
111    /// Log a message (useful for debugging/audit trails).
112    Log {
113        /// Message template (can reference context keys with {key})
114        message: String,
115    },
116
117    /// Create a payment charge via a payment provider.
118    ///
119    /// Resolves amount and reference from context, calls the provider,
120    /// and stores a redacted `PaymentDisplay` in context for downstream steps.
121    Charge {
122        /// Which payment provider to use
123        provider: PaymentKind,
124        /// Context key that resolves to the charge amount (i64)
125        amount_key: String,
126        /// Context key that resolves to the reference ID (string)
127        reference_key: String,
128        /// Optional context key for description
129        description_key: Option<String>,
130        /// Optional context key for payment method override
131        payment_method_key: Option<String>,
132        /// Optional context key for the order origin (`whatsapp`, `mcp`, `web`, `ios_app`, `android_app`, or `api`).
133        #[serde(default, skip_serializing_if = "Option::is_none")]
134        order_origin_key: Option<String>,
135        /// Optional key to store redacted payment display details in context
136        store_as: Option<String>,
137    },
138}
139
140impl WorkflowStep {
141    /// Create a Query step from a Qail command.
142    pub fn query(cmd: &qail_core::Qail, store_as: Option<&str>) -> Self {
143        // Serialize the Qail AST into QAIL wire text for persistence.
144        let cmd_json = qail_core::wire::encode_cmd_text(cmd);
145        WorkflowStep::Query {
146            cmd_json,
147            store_as: store_as.map(String::from),
148        }
149    }
150
151    /// Create a Notify step.
152    pub fn notify(channel: ChannelKind, template: &str, recipient_key: &str) -> Self {
153        WorkflowStep::Notify {
154            channel,
155            template: template.into(),
156            recipient_key: recipient_key.into(),
157            payload_key: None,
158        }
159    }
160
161    /// Create a Notify step with payload.
162    pub fn notify_with_payload(
163        channel: ChannelKind,
164        template: &str,
165        recipient_key: &str,
166        payload_key: &str,
167    ) -> Self {
168        WorkflowStep::Notify {
169            channel,
170            template: template.into(),
171            recipient_key: recipient_key.into(),
172            payload_key: Some(payload_key.into()),
173        }
174    }
175
176    /// Create a Wait step.
177    pub fn wait(event: &str, timeout: Duration) -> Self {
178        WorkflowStep::Wait {
179            event: event.into(),
180            timeout,
181            on_timeout: vec![],
182        }
183    }
184
185    /// Create a Wait step with timeout fallback.
186    pub fn wait_or(event: &str, timeout: Duration, on_timeout: Vec<WorkflowStep>) -> Self {
187        WorkflowStep::Wait {
188            event: event.into(),
189            timeout,
190            on_timeout,
191        }
192    }
193
194    /// Create a ForEach step.
195    pub fn for_each(list_key: &str, steps: Vec<WorkflowStep>) -> Self {
196        WorkflowStep::ForEach {
197            list_key: list_key.into(),
198            steps,
199        }
200    }
201
202    /// Create a Transition step.
203    pub fn transition(to: &str) -> Self {
204        WorkflowStep::Transition { to: to.into() }
205    }
206
207    /// Create a Log step.
208    pub fn log(message: &str) -> Self {
209        WorkflowStep::Log {
210            message: message.into(),
211        }
212    }
213
214    /// Create a Charge step.
215    pub fn charge(
216        provider: PaymentKind,
217        amount_key: &str,
218        reference_key: &str,
219        store_as: Option<&str>,
220    ) -> Self {
221        WorkflowStep::Charge {
222            provider,
223            amount_key: amount_key.into(),
224            reference_key: reference_key.into(),
225            description_key: None,
226            payment_method_key: None,
227            order_origin_key: None,
228            store_as: store_as.map(String::from),
229        }
230    }
231
232    /// Create a Charge step with full options.
233    pub fn charge_with(
234        provider: PaymentKind,
235        amount_key: &str,
236        reference_key: &str,
237        description_key: Option<&str>,
238        payment_method_key: Option<&str>,
239        store_as: Option<&str>,
240    ) -> Self {
241        WorkflowStep::Charge {
242            provider,
243            amount_key: amount_key.into(),
244            reference_key: reference_key.into(),
245            description_key: description_key.map(String::from),
246            payment_method_key: payment_method_key.map(String::from),
247            order_origin_key: None,
248            store_as: store_as.map(String::from),
249        }
250    }
251
252    /// Create a Charge step with explicit source-channel tracking.
253    pub fn charge_with_origin(
254        provider: PaymentKind,
255        amount_key: &str,
256        reference_key: &str,
257        description_key: Option<&str>,
258        payment_method_key: Option<&str>,
259        order_origin_key: Option<&str>,
260        store_as: Option<&str>,
261    ) -> Self {
262        WorkflowStep::Charge {
263            provider,
264            amount_key: amount_key.into(),
265            reference_key: reference_key.into(),
266            description_key: description_key.map(String::from),
267            payment_method_key: payment_method_key.map(String::from),
268            order_origin_key: order_origin_key.map(String::from),
269            store_as: store_as.map(String::from),
270        }
271    }
272
273    /// Create a Branch step.
274    pub fn branch(
275        condition_key: &str,
276        branches: Vec<(&str, Vec<WorkflowStep>)>,
277        default: Vec<WorkflowStep>,
278    ) -> Self {
279        WorkflowStep::Branch {
280            condition_key: condition_key.into(),
281            branches: branches
282                .into_iter()
283                .map(|(k, v)| (k.to_string(), v))
284                .collect(),
285            default,
286        }
287    }
288
289    /// Create a BranchWhen step with richer predicates.
290    pub fn branch_when(
291        condition_key: &str,
292        branches: Vec<(WorkflowBranchCondition, Vec<WorkflowStep>)>,
293        default: Vec<WorkflowStep>,
294    ) -> Self {
295        WorkflowStep::BranchWhen {
296            condition_key: condition_key.into(),
297            branches,
298            default,
299        }
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306
307    #[test]
308    fn test_notify_step() {
309        let step = WorkflowStep::notify(ChannelKind::WhatsApp, "booking_confirm", "guest.phone");
310        match step {
311            WorkflowStep::Notify {
312                channel,
313                template,
314                recipient_key,
315                payload_key,
316            } => {
317                assert!(matches!(channel, ChannelKind::WhatsApp));
318                assert_eq!(template, "booking_confirm");
319                assert_eq!(recipient_key, "guest.phone");
320                assert!(payload_key.is_none());
321            }
322            _ => panic!("Expected Notify step"),
323        }
324    }
325
326    #[test]
327    fn test_wait_with_timeout() {
328        let step = WorkflowStep::wait_or(
329            "operator_accept",
330            Duration::from_secs(3600),
331            vec![WorkflowStep::transition("cancelled")],
332        );
333        match step {
334            WorkflowStep::Wait {
335                event,
336                timeout,
337                on_timeout,
338            } => {
339                assert_eq!(event, "operator_accept");
340                assert_eq!(timeout.as_secs(), 3600);
341                assert_eq!(on_timeout.len(), 1);
342            }
343            _ => panic!("Expected Wait step"),
344        }
345    }
346
347    #[test]
348    fn test_branch_step() {
349        let step = WorkflowStep::branch(
350            "decline_reason",
351            vec![
352                ("full", vec![WorkflowStep::log("Boat is full")]),
353                (
354                    "maintenance",
355                    vec![WorkflowStep::log("Boat under maintenance")],
356                ),
357            ],
358            vec![WorkflowStep::log("Unknown reason")],
359        );
360        match step {
361            WorkflowStep::Branch {
362                condition_key,
363                branches,
364                default,
365            } => {
366                assert_eq!(condition_key, "decline_reason");
367                assert_eq!(branches.len(), 2);
368                assert_eq!(default.len(), 1);
369            }
370            _ => panic!("Expected Branch step"),
371        }
372    }
373
374    #[test]
375    fn test_branch_when_step() {
376        let step = WorkflowStep::branch_when(
377            "payment.attempts",
378            vec![(
379                WorkflowBranchCondition::NumberGte(3),
380                vec![WorkflowStep::log("Manual review")],
381            )],
382            vec![WorkflowStep::log("Retry")],
383        );
384        match step {
385            WorkflowStep::BranchWhen {
386                condition_key,
387                branches,
388                default,
389            } => {
390                assert_eq!(condition_key, "payment.attempts");
391                assert_eq!(branches.len(), 1);
392                assert_eq!(branches[0].0, WorkflowBranchCondition::NumberGte(3));
393                assert_eq!(default.len(), 1);
394            }
395            _ => panic!("Expected BranchWhen step"),
396        }
397    }
398
399    #[test]
400    fn test_for_each_step() {
401        let step = WorkflowStep::for_each(
402            "alternatives",
403            vec![WorkflowStep::notify(
404                ChannelKind::WhatsApp,
405                "opportunity",
406                "item.phone",
407            )],
408        );
409        match step {
410            WorkflowStep::ForEach { list_key, steps } => {
411                assert_eq!(list_key, "alternatives");
412                assert_eq!(steps.len(), 1);
413            }
414            _ => panic!("Expected ForEach step"),
415        }
416    }
417
418    #[test]
419    fn test_step_serialization() {
420        let step = WorkflowStep::transition("fulfilled");
421        let json = serde_json::to_string(&step).unwrap();
422        let _: WorkflowStep = serde_json::from_str(&json).unwrap();
423    }
424}