payrix 0.3.0

Rust client for the Payrix payment processing API
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
425
426
427
428
429
430
431
432
433
434
435
436
//! Search helpers for building Payrix query parameters.
//!
//! Payrix uses a specific search syntax documented at:
//! <https://resource.payrix.com/resources/api-call-syntax>
//!
//! ## Validated Operators
//!
//! The following operators have been tested and confirmed to work with the Payrix API:
//!
//! | Operator | String | Description |
//! |----------|--------|-------------|
//! | `Equals` | `equals` | Exact match (default) |
//! | `Exact` | `exact` | Exact string match |
//! | `Greater` | `greater` | Greater than (>) |
//! | `Less` | `less` | Less than (<) |
//! | `Like` | `like` | Pattern match with % wildcard |
//! | `In` | `in` | Value in comma-separated list |
//! | `NotIn` | `notin` | Value NOT in list |
//! | `Diff` | `diff` | Not equal (!=) |
//! | `NotLike` | `notlike` | Pattern NOT matching |
//! | `Sort` | `sort` | Sort by field (asc/desc) |
//!
//! ## Non-Working Operators
//!
//! The following operators are NOT supported by Payrix (they return empty results):
//! - `gte`, `lte` (greater/less than or equal)
//! - `gt`, `lt` (short forms)
//! - `lesser` (alternative to less)
//! - `eq` (short form of equals)
//!
//! ## Compound Queries
//!
//! Multiple conditions are combined with AND logic by default.
//! For OR logic, use the [`SearchBuilder::or_group`] method.

use chrono::{Datelike, NaiveDate};

/// Operators for search field comparisons.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchOperator {
    /// Exact match (default)
    Equals,
    /// Exact string match
    Exact,
    /// Greater than
    Greater,
    /// Less than
    Less,
    /// Pattern match (use % as wildcard)
    Like,
    /// Value in list
    In,
    /// Sort by field
    Sort,
    /// Not equal
    Diff,
    /// Not like pattern
    NotLike,
    /// Value not in list
    NotIn,
}

impl SearchOperator {
    /// Get the Payrix query parameter name.
    pub fn as_str(&self) -> &'static str {
        match self {
            SearchOperator::Equals => "equals",
            SearchOperator::Exact => "exact",
            SearchOperator::Greater => "greater",
            SearchOperator::Less => "less",
            SearchOperator::Like => "like",
            SearchOperator::In => "in",
            SearchOperator::Sort => "sort",
            SearchOperator::Diff => "diff",
            SearchOperator::NotLike => "notlike",
            SearchOperator::NotIn => "notin",
        }
    }
}

/// Create a search field for Payrix queries.
///
/// # Examples
///
/// ```
/// use payrix::search::{make_search_field, SearchOperator};
///
/// // Simple equality
/// let search = make_search_field("merchant", "mer_123", None);
/// assert_eq!(search, "merchant[equals]=mer_123");
///
/// // Greater than
/// let search = make_search_field("created", "20240101", Some(SearchOperator::Greater));
/// assert_eq!(search, "created[greater]=20240101");
///
/// // In list
/// let search = make_search_field("id", "id1,id2,id3", Some(SearchOperator::In));
/// assert_eq!(search, "id[in]=id1,id2,id3");
/// ```
pub fn make_search_field(field: &str, value: &str, operator: Option<SearchOperator>) -> String {
    let op = operator.unwrap_or(SearchOperator::Equals);
    format!("{}[{}]={}", field, op.as_str(), value)
}

/// Create a search field with multiple values (for IN/NOTIN operators).
///
/// # Examples
///
/// ```
/// use payrix::search::{make_search_field_multi, SearchOperator};
///
/// let ids = vec!["id1", "id2", "id3"];
/// let search = make_search_field_multi("id", &ids, SearchOperator::In);
/// assert_eq!(search, "id[in]=id1,id2,id3");
/// ```
pub fn make_search_field_multi(field: &str, values: &[&str], operator: SearchOperator) -> String {
    let joined = values.join(",");
    format!("{}[{}]={}", field, operator.as_str(), joined)
}

/// Format a date as Payrix expects: YYYYMMDD.
///
/// # Examples
///
/// ```
/// use chrono::NaiveDate;
/// use payrix::search::make_payrix_date;
///
/// let date = NaiveDate::from_ymd_opt(2024, 3, 15).unwrap();
/// assert_eq!(make_payrix_date(&date), "20240315");
/// ```
pub fn make_payrix_date(date: &NaiveDate) -> String {
    format!("{:04}{:02}{:02}", date.year(), date.month(), date.day())
}

/// Parse a Payrix date (YYYYMMDD) into a NaiveDate.
///
/// # Examples
///
/// ```
/// use chrono::NaiveDate;
/// use payrix::search::parse_payrix_date;
///
/// let date = parse_payrix_date("20240315").unwrap();
/// assert_eq!(date, NaiveDate::from_ymd_opt(2024, 3, 15).unwrap());
/// ```
pub fn parse_payrix_date(date_str: &str) -> Option<NaiveDate> {
    if date_str.len() != 8 {
        return None;
    }
    let year = date_str[0..4].parse().ok()?;
    let month = date_str[4..6].parse().ok()?;
    let day = date_str[6..8].parse().ok()?;
    NaiveDate::from_ymd_opt(year, month, day)
}

/// Build expand query parameters for related resources.
///
/// # Examples
///
/// ```
/// use payrix::search::build_expand_query;
///
/// // Simple expansion
/// let query = build_expand_query(&["token", "customer"]);
/// assert_eq!(query, "expand[token][]&expand[customer][]");
///
/// // Nested expansion (token.customer)
/// let query = build_expand_query(&["token|customer"]);
/// assert_eq!(query, "expand[token][][customer][]");
/// ```
pub fn build_expand_query(expand: &[&str]) -> String {
    expand
        .iter()
        .map(|e| {
            if e.contains('|') {
                // Handle nested expansion like "token|customer"
                let parts: Vec<&str> = e.split('|').collect();
                format!(
                    "expand{}",
                    parts.iter().map(|p| format!("[{}][]", p)).collect::<String>()
                )
            } else {
                format!("expand[{}][]", e)
            }
        })
        .collect::<Vec<_>>()
        .join("&")
}

/// Search builder for constructing complex queries.
///
/// # Examples
///
/// ```
/// use payrix::search::{SearchBuilder, SearchOperator};
///
/// let search = SearchBuilder::new()
///     .field("merchant", "mer_123")
///     .field_with_op("created", "20240101", SearchOperator::Greater)
///     .field_with_op("status", "1", SearchOperator::Equals)
///     .build();
///
/// assert_eq!(search, "merchant[equals]=mer_123&created[greater]=20240101&status[equals]=1");
/// ```
#[derive(Debug, Clone, Default)]
pub struct SearchBuilder {
    parts: Vec<String>,
    expand_fields: Vec<String>,
}

impl SearchBuilder {
    /// Create a new search builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a field with equals operator.
    pub fn field(mut self, name: &str, value: &str) -> Self {
        self.parts.push(make_search_field(name, value, None));
        self
    }

    /// Add a field with a specific operator.
    pub fn field_with_op(mut self, name: &str, value: &str, operator: SearchOperator) -> Self {
        self.parts
            .push(make_search_field(name, value, Some(operator)));
        self
    }

    /// Add a field with multiple values.
    pub fn field_multi(mut self, name: &str, values: &[&str], operator: SearchOperator) -> Self {
        self.parts
            .push(make_search_field_multi(name, values, operator));
        self
    }

    /// Add expansion for related resources.
    ///
    /// # Examples
    ///
    /// ```
    /// use payrix::search::SearchBuilder;
    ///
    /// let search = SearchBuilder::new()
    ///     .field("customer", "cust_123")
    ///     .expand("payment")
    ///     .expand("token")
    ///     .build();
    ///
    /// assert_eq!(search, "customer[equals]=cust_123&expand[payment][]&expand[token][]");
    /// ```
    pub fn expand(mut self, field: &str) -> Self {
        self.expand_fields.push(field.to_string());
        self
    }

    /// Add a raw search string.
    pub fn raw(mut self, search: &str) -> Self {
        self.parts.push(search.to_string());
        self
    }

    /// Add an OR group with multiple conditions.
    ///
    /// Creates an OR condition where any of the conditions can match.
    /// Uses the Payrix syntax: `[or]field[operator]=value`
    ///
    /// # Examples
    ///
    /// ```
    /// use payrix::search::{SearchBuilder, SearchOperator};
    ///
    /// // Search for plans where inactive=0 OR inactive=1
    /// let search = SearchBuilder::new()
    ///     .or_group(&[
    ///         ("inactive", "0", SearchOperator::Equals),
    ///         ("inactive", "1", SearchOperator::Equals),
    ///     ])
    ///     .build();
    ///
    /// assert_eq!(search, "[or]inactive[equals]=0&[or]inactive[equals]=1");
    /// ```
    pub fn or_group(mut self, conditions: &[(&str, &str, SearchOperator)]) -> Self {
        for (field, value, operator) in conditions {
            self.parts
                .push(format!("[or]{}[{}]={}", field, operator.as_str(), value));
        }
        self
    }

    /// Build the final search string.
    pub fn build(self) -> String {
        let mut all_parts = self.parts;

        // Add expansion if present
        if !self.expand_fields.is_empty() {
            let expand_query = build_expand_query(
                &self.expand_fields.iter().map(|s| s.as_str()).collect::<Vec<_>>()
            );
            all_parts.push(expand_query);
        }

        all_parts.join("&")
    }
}

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

    #[test]
    fn test_make_search_field() {
        assert_eq!(
            make_search_field("merchant", "mer_123", None),
            "merchant[equals]=mer_123"
        );
        assert_eq!(
            make_search_field("created", "20240101", Some(SearchOperator::Greater)),
            "created[greater]=20240101"
        );
        assert_eq!(
            make_search_field("name", "%test%", Some(SearchOperator::Like)),
            "name[like]=%test%"
        );
    }

    #[test]
    fn test_make_search_field_multi() {
        assert_eq!(
            make_search_field_multi("id", &["a", "b", "c"], SearchOperator::In),
            "id[in]=a,b,c"
        );
    }

    #[test]
    fn test_payrix_date() {
        let date = NaiveDate::from_ymd_opt(2024, 3, 15).unwrap();
        assert_eq!(make_payrix_date(&date), "20240315");
        assert_eq!(parse_payrix_date("20240315"), Some(date));
        assert_eq!(parse_payrix_date("invalid"), None);
    }

    #[test]
    fn test_build_expand_query() {
        assert_eq!(
            build_expand_query(&["token", "customer"]),
            "expand[token][]&expand[customer][]"
        );
        assert_eq!(
            build_expand_query(&["token|customer"]),
            "expand[token][][customer][]"
        );
    }

    #[test]
    fn test_search_builder() {
        let search = SearchBuilder::new()
            .field("merchant", "mer_123")
            .field_with_op("created", "20240101", SearchOperator::Greater)
            .build();
        assert_eq!(
            search,
            "merchant[equals]=mer_123&created[greater]=20240101"
        );
    }

    #[test]
    fn test_date_range_filtering() {
        // Test date range with greater/less operators
        // Note: Payrix uses 'greater' (>) and 'less' (<), NOT 'gte' (>=) or 'lte' (<=)
        let start = NaiveDate::from_ymd_opt(2025, 12, 1).unwrap();
        let end = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();

        let search = SearchBuilder::new()
            .field("merchant", "mer_123")
            .field_with_op("created", &make_payrix_date(&start), SearchOperator::Greater)
            .field_with_op("created", &make_payrix_date(&end), SearchOperator::Less)
            .build();

        // Format must be YYYYMMDD (no dashes), operators must be 'greater'/'less'
        assert_eq!(
            search,
            "merchant[equals]=mer_123&created[greater]=20251201&created[less]=20260101"
        );

        // Verify the date format doesn't contain dashes
        let date_str = make_payrix_date(&start);
        assert!(!date_str.contains('-'), "Date format should not contain dashes");
        assert_eq!(date_str.len(), 8, "Date format should be 8 characters (YYYYMMDD)");
    }

    #[test]
    fn test_available_operators() {
        // Document all available operators
        assert_eq!(SearchOperator::Equals.as_str(), "equals");
        assert_eq!(SearchOperator::Exact.as_str(), "exact");
        assert_eq!(SearchOperator::Greater.as_str(), "greater");
        assert_eq!(SearchOperator::Less.as_str(), "less");
        assert_eq!(SearchOperator::Like.as_str(), "like");
        assert_eq!(SearchOperator::In.as_str(), "in");
        assert_eq!(SearchOperator::Sort.as_str(), "sort");
        assert_eq!(SearchOperator::Diff.as_str(), "diff");
        assert_eq!(SearchOperator::NotLike.as_str(), "notlike");
        assert_eq!(SearchOperator::NotIn.as_str(), "notin");
        // Note: There are NO 'gte' or 'lte' operators in Payrix!
    }

    #[test]
    fn test_or_group() {
        let search = SearchBuilder::new()
            .or_group(&[
                ("inactive", "0", SearchOperator::Equals),
                ("inactive", "1", SearchOperator::Equals),
            ])
            .build();

        assert_eq!(search, "[or]inactive[equals]=0&[or]inactive[equals]=1");
    }

    #[test]
    fn test_or_group_with_other_conditions() {
        let search = SearchBuilder::new()
            .field("merchant", "mer_123")
            .or_group(&[
                ("status", "1", SearchOperator::Equals),
                ("status", "2", SearchOperator::Equals),
            ])
            .build();

        assert_eq!(
            search,
            "merchant[equals]=mer_123&[or]status[equals]=1&[or]status[equals]=2"
        );
    }
}