qail-workflow 3.0.2

QAIL Flow Engine - declarative state-machine workflows with waits, retries, and side-effect checkpoints
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Workflow steps — the composable building blocks of a workflow.
//!
//! Each step represents a single atomic action: execute a query,
//! send a notification, wait for an event, or branch on a condition.

use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::channel::ChannelKind;
use crate::payment::PaymentKind;

/// A branch predicate evaluated against one workflow context key.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum WorkflowBranchCondition {
    /// Text equality. Strings compare directly; other JSON values compare by JSON text.
    Equals(String),
    /// Text inequality. Missing context does not match.
    NotEquals(String),
    /// Text membership. Strings compare directly; other JSON values compare by JSON text.
    OneOf(Vec<String>),
    /// Context key exists.
    Exists,
    /// Context key does not exist.
    Missing,
    /// Context key is JSON null.
    Null,
    /// Context key is a boolean with this value.
    Bool(bool),
    /// Numeric comparison.
    NumberGt(i64),
    /// Numeric comparison.
    NumberGte(i64),
    /// Numeric comparison.
    NumberLt(i64),
    /// Numeric comparison.
    NumberLte(i64),
    /// Text contains a substring.
    StringContains(String),
}

/// A single step in a workflow execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkflowStep {
    /// Execute a QAIL query against the database.
    /// The `cmd_json` field stores QAIL wire text (`qail_core::wire::encode_cmd_text`).
    /// The `store_as` key saves the result into WorkflowContext for later steps.
    Query {
        /// QAIL command encoded in QAIL wire text.
        cmd_json: String,
        /// Optional key to store query results in context
        store_as: Option<String>,
    },

    /// Send a notification via a channel (WhatsApp, Email, SMS, Push).
    Notify {
        /// Which channel to send through
        channel: ChannelKind,
        /// Template name (e.g., "opportunity_alert", "booking_confirmed")
        template: String,
        /// Context key that resolves to the recipient address
        recipient_key: String,
        /// Optional extra payload (template variables)
        payload_key: Option<String>,
    },

    /// Wait for an external event (webhook callback, user action, timeout).
    Wait {
        /// Event key to listen for (matched against incoming webhook/callback)
        event: String,
        /// Maximum time to wait before triggering on_timeout
        timeout: Duration,
        /// Steps to execute if timeout is reached
        on_timeout: Vec<WorkflowStep>,
    },

    /// Conditional branching based on a context value.
    Branch {
        /// Context key to evaluate
        condition_key: String,
        /// Map of value → steps to execute
        branches: Vec<(String, Vec<WorkflowStep>)>,
        /// Default steps if no branch matches
        default: Vec<WorkflowStep>,
    },

    /// Conditional branching with richer predicates.
    BranchWhen {
        /// Context key to evaluate
        condition_key: String,
        /// Ordered predicates and steps. The first matching predicate is selected.
        branches: Vec<(WorkflowBranchCondition, Vec<WorkflowStep>)>,
        /// Default steps if no predicate matches
        default: Vec<WorkflowStep>,
    },

    /// Execute steps for each item in a context list.
    ForEach {
        /// Context key containing a JSON array
        list_key: String,
        /// Steps to execute per item (item available as "item" in context)
        steps: Vec<WorkflowStep>,
    },

    /// Transition to a new workflow state.
    Transition {
        /// Target state name
        to: String,
    },

    /// Log a message (useful for debugging/audit trails).
    Log {
        /// Message template (can reference context keys with {key})
        message: String,
    },

    /// Create a payment charge via a payment provider.
    ///
    /// Resolves amount and reference from context, calls the provider,
    /// and stores a redacted `PaymentDisplay` in context for downstream steps.
    Charge {
        /// Which payment provider to use
        provider: PaymentKind,
        /// Context key that resolves to the charge amount (i64)
        amount_key: String,
        /// Context key that resolves to the reference ID (string)
        reference_key: String,
        /// Optional context key for description
        description_key: Option<String>,
        /// Optional context key for payment method override
        payment_method_key: Option<String>,
        /// Optional context key for the order origin (`whatsapp`, `mcp`, `web`, `ios_app`, `android_app`, or `api`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        order_origin_key: Option<String>,
        /// Optional key to store redacted payment display details in context
        store_as: Option<String>,
    },
}

impl WorkflowStep {
    /// Create a Query step from a Qail command.
    pub fn query(cmd: &qail_core::Qail, store_as: Option<&str>) -> Self {
        // Serialize the Qail AST into QAIL wire text for persistence.
        let cmd_json = qail_core::wire::encode_cmd_text(cmd);
        WorkflowStep::Query {
            cmd_json,
            store_as: store_as.map(String::from),
        }
    }

    /// Create a Notify step.
    pub fn notify(channel: ChannelKind, template: &str, recipient_key: &str) -> Self {
        WorkflowStep::Notify {
            channel,
            template: template.into(),
            recipient_key: recipient_key.into(),
            payload_key: None,
        }
    }

    /// Create a Notify step with payload.
    pub fn notify_with_payload(
        channel: ChannelKind,
        template: &str,
        recipient_key: &str,
        payload_key: &str,
    ) -> Self {
        WorkflowStep::Notify {
            channel,
            template: template.into(),
            recipient_key: recipient_key.into(),
            payload_key: Some(payload_key.into()),
        }
    }

    /// Create a Wait step.
    pub fn wait(event: &str, timeout: Duration) -> Self {
        WorkflowStep::Wait {
            event: event.into(),
            timeout,
            on_timeout: vec![],
        }
    }

    /// Create a Wait step with timeout fallback.
    pub fn wait_or(event: &str, timeout: Duration, on_timeout: Vec<WorkflowStep>) -> Self {
        WorkflowStep::Wait {
            event: event.into(),
            timeout,
            on_timeout,
        }
    }

    /// Create a ForEach step.
    pub fn for_each(list_key: &str, steps: Vec<WorkflowStep>) -> Self {
        WorkflowStep::ForEach {
            list_key: list_key.into(),
            steps,
        }
    }

    /// Create a Transition step.
    pub fn transition(to: &str) -> Self {
        WorkflowStep::Transition { to: to.into() }
    }

    /// Create a Log step.
    pub fn log(message: &str) -> Self {
        WorkflowStep::Log {
            message: message.into(),
        }
    }

    /// Create a Charge step.
    pub fn charge(
        provider: PaymentKind,
        amount_key: &str,
        reference_key: &str,
        store_as: Option<&str>,
    ) -> Self {
        WorkflowStep::Charge {
            provider,
            amount_key: amount_key.into(),
            reference_key: reference_key.into(),
            description_key: None,
            payment_method_key: None,
            order_origin_key: None,
            store_as: store_as.map(String::from),
        }
    }

    /// Create a Charge step with full options.
    pub fn charge_with(
        provider: PaymentKind,
        amount_key: &str,
        reference_key: &str,
        description_key: Option<&str>,
        payment_method_key: Option<&str>,
        store_as: Option<&str>,
    ) -> Self {
        WorkflowStep::Charge {
            provider,
            amount_key: amount_key.into(),
            reference_key: reference_key.into(),
            description_key: description_key.map(String::from),
            payment_method_key: payment_method_key.map(String::from),
            order_origin_key: None,
            store_as: store_as.map(String::from),
        }
    }

    /// Create a Charge step with explicit source-channel tracking.
    pub fn charge_with_origin(
        provider: PaymentKind,
        amount_key: &str,
        reference_key: &str,
        description_key: Option<&str>,
        payment_method_key: Option<&str>,
        order_origin_key: Option<&str>,
        store_as: Option<&str>,
    ) -> Self {
        WorkflowStep::Charge {
            provider,
            amount_key: amount_key.into(),
            reference_key: reference_key.into(),
            description_key: description_key.map(String::from),
            payment_method_key: payment_method_key.map(String::from),
            order_origin_key: order_origin_key.map(String::from),
            store_as: store_as.map(String::from),
        }
    }

    /// Create a Branch step.
    pub fn branch(
        condition_key: &str,
        branches: Vec<(&str, Vec<WorkflowStep>)>,
        default: Vec<WorkflowStep>,
    ) -> Self {
        WorkflowStep::Branch {
            condition_key: condition_key.into(),
            branches: branches
                .into_iter()
                .map(|(k, v)| (k.to_string(), v))
                .collect(),
            default,
        }
    }

    /// Create a BranchWhen step with richer predicates.
    pub fn branch_when(
        condition_key: &str,
        branches: Vec<(WorkflowBranchCondition, Vec<WorkflowStep>)>,
        default: Vec<WorkflowStep>,
    ) -> Self {
        WorkflowStep::BranchWhen {
            condition_key: condition_key.into(),
            branches,
            default,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_notify_step() {
        let step = WorkflowStep::notify(ChannelKind::WhatsApp, "booking_confirm", "guest.phone");
        match step {
            WorkflowStep::Notify {
                channel,
                template,
                recipient_key,
                payload_key,
            } => {
                assert!(matches!(channel, ChannelKind::WhatsApp));
                assert_eq!(template, "booking_confirm");
                assert_eq!(recipient_key, "guest.phone");
                assert!(payload_key.is_none());
            }
            _ => panic!("Expected Notify step"),
        }
    }

    #[test]
    fn test_wait_with_timeout() {
        let step = WorkflowStep::wait_or(
            "operator_accept",
            Duration::from_secs(3600),
            vec![WorkflowStep::transition("cancelled")],
        );
        match step {
            WorkflowStep::Wait {
                event,
                timeout,
                on_timeout,
            } => {
                assert_eq!(event, "operator_accept");
                assert_eq!(timeout.as_secs(), 3600);
                assert_eq!(on_timeout.len(), 1);
            }
            _ => panic!("Expected Wait step"),
        }
    }

    #[test]
    fn test_branch_step() {
        let step = WorkflowStep::branch(
            "decline_reason",
            vec![
                ("full", vec![WorkflowStep::log("Boat is full")]),
                (
                    "maintenance",
                    vec![WorkflowStep::log("Boat under maintenance")],
                ),
            ],
            vec![WorkflowStep::log("Unknown reason")],
        );
        match step {
            WorkflowStep::Branch {
                condition_key,
                branches,
                default,
            } => {
                assert_eq!(condition_key, "decline_reason");
                assert_eq!(branches.len(), 2);
                assert_eq!(default.len(), 1);
            }
            _ => panic!("Expected Branch step"),
        }
    }

    #[test]
    fn test_branch_when_step() {
        let step = WorkflowStep::branch_when(
            "payment.attempts",
            vec![(
                WorkflowBranchCondition::NumberGte(3),
                vec![WorkflowStep::log("Manual review")],
            )],
            vec![WorkflowStep::log("Retry")],
        );
        match step {
            WorkflowStep::BranchWhen {
                condition_key,
                branches,
                default,
            } => {
                assert_eq!(condition_key, "payment.attempts");
                assert_eq!(branches.len(), 1);
                assert_eq!(branches[0].0, WorkflowBranchCondition::NumberGte(3));
                assert_eq!(default.len(), 1);
            }
            _ => panic!("Expected BranchWhen step"),
        }
    }

    #[test]
    fn test_for_each_step() {
        let step = WorkflowStep::for_each(
            "alternatives",
            vec![WorkflowStep::notify(
                ChannelKind::WhatsApp,
                "opportunity",
                "item.phone",
            )],
        );
        match step {
            WorkflowStep::ForEach { list_key, steps } => {
                assert_eq!(list_key, "alternatives");
                assert_eq!(steps.len(), 1);
            }
            _ => panic!("Expected ForEach step"),
        }
    }

    #[test]
    fn test_step_serialization() {
        let step = WorkflowStep::transition("fulfilled");
        let json = serde_json::to_string(&step).unwrap();
        let _: WorkflowStep = serde_json::from_str(&json).unwrap();
    }
}