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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Account Management Workflow
//
// This workflow handles entity, merchant, and bank account operations.
//
// Key features:
// - Entity lookup by custom field
// - Merchant lookup by entity
// - Bank account management
// - Funds and payout operations
//
// Generic API - callers control their own custom field usage and account routing

use crate::{EntityType, PayrixClient, Result, SearchBuilder};
use serde::{Deserialize, Serialize};

/// Bank account information
#[derive(Debug, Clone, Serialize)]
pub struct BankAccount {
    /// The Payrix account ID
    pub id: String,
    /// The account token used for transactions
    pub token: String,
    /// The account type code
    pub account_type: i32,
}

/// Payout schedule type
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[repr(i32)]
pub enum PayoutSchedule {
    /// One-time payout
    #[default]
    Single = 5,
    /// Daily payouts
    Daily = 1,
    /// Weekly payouts
    Weekly = 2,
    /// Bi-weekly payouts
    BiWeekly = 3,
    /// Monthly payouts
    Monthly = 4,
}

impl PayoutSchedule {
    /// Returns the numeric representation of the payout schedule
    pub fn as_i32(&self) -> i32 {
        *self as i32
    }
}

/// Payout usage method
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[repr(i32)]
pub enum PayoutUsageMethod {
    /// Percentage of available balance
    Percentage = 1,
    /// Actual dollar amount
    #[default]
    Actual = 2,
}

impl PayoutUsageMethod {
    /// Returns the numeric representation of the usage method
    pub fn as_i32(&self) -> i32 {
        *self as i32
    }
}

/// Configuration for creating a payout
#[derive(Debug, Clone)]
pub struct PayoutConfig {
    /// Payout schedule type (default: Single)
    pub schedule: PayoutSchedule,
    /// Schedule factor - multiplier for the schedule period (default: 1)
    pub schedule_factor: i32,
    /// Usage method - Percentage or Actual amount (default: Actual)
    pub usage_method: PayoutUsageMethod,
    /// Whether to use same-day ACH (default: false)
    pub same_day: bool,
}

impl Default for PayoutConfig {
    fn default() -> Self {
        Self {
            schedule: PayoutSchedule::Single,
            schedule_factor: 1,
            usage_method: PayoutUsageMethod::Actual,
            same_day: false,
        }
    }
}

impl PayoutConfig {
    /// Create a single payout configuration (most common case)
    pub fn single() -> Self {
        Self::default()
    }

    /// Create a single payout with same-day ACH
    pub fn single_same_day() -> Self {
        Self {
            same_day: true,
            ..Self::default()
        }
    }

    /// Create a recurring payout configuration
    pub fn recurring(schedule: PayoutSchedule, factor: i32) -> Self {
        Self {
            schedule,
            schedule_factor: factor,
            ..Self::default()
        }
    }
}

/// Get an entity by custom field value
///
/// It is common practice to store domain-specific IDs (e.g. your application's transactionID
/// or customerID) in a payrix custom field. This provides a simple lookup function to find
/// a payrix entity based on your domain's related ID.
///
/// # Arguments
/// * `client` - Payrix API client
/// * `custom_value` - Value to search for in the custom field
///
/// # Returns
/// The Payrix entity if found
pub async fn get_entity_by_custom_field(
    client: &PayrixClient,
    custom_value: &str,
) -> Result<serde_json::Value> {
    let search = SearchBuilder::new().field("custom", custom_value).build();

    let entities = client
        .search::<serde_json::Value>(EntityType::Entities, &search)
        .await?;

    entities.into_iter().next().ok_or_else(|| {
        crate::Error::NotFound(format!(
            "No Payrix entity found with custom={}",
            custom_value
        ))
    })
}

/// Get an entity by ID
///
/// # Arguments
/// * `client` - Payrix API client
/// * `entity_id` - Payrix entity ID
///
/// # Returns
/// The Payrix entity if found
pub async fn get_entity(
    client: &PayrixClient,
    entity_id: &str,
) -> Result<Option<serde_json::Value>> {
    client
        .get_one::<serde_json::Value>(EntityType::Entities, entity_id)
        .await
}

/// Get the merchant for an entity
///
/// # Arguments
/// * `client` - Payrix API client
/// * `entity_id` - Payrix entity ID
///
/// # Returns
/// The Payrix merchant associated with this entity
pub async fn get_merchant_for_entity(
    client: &PayrixClient,
    entity_id: &str,
) -> Result<serde_json::Value> {
    let search = SearchBuilder::new().field("entity", entity_id).build();

    let merchants = client
        .search::<serde_json::Value>(EntityType::Merchants, &search)
        .await?;

    merchants.into_iter().next().ok_or_else(|| {
        crate::Error::NotFound(format!(
            "No Payrix merchant found for entity {}",
            entity_id
        ))
    })
}

/// Get a merchant by ID
///
/// # Arguments
/// * `client` - Payrix API client
/// * `merchant_id` - Payrix merchant ID
///
/// # Returns
/// The Payrix merchant if found
pub async fn get_merchant(
    client: &PayrixClient,
    merchant_id: &str,
) -> Result<Option<serde_json::Value>> {
    client
        .get_one::<serde_json::Value>(EntityType::Merchants, merchant_id)
        .await
}

/// Get all bank accounts for an entity
///
/// # Arguments
/// * `client` - Payrix API client
/// * `entity_id` - Payrix entity ID
///
/// # Returns
/// Vector of bank accounts for this entity
pub async fn get_accounts_for_entity(
    client: &PayrixClient,
    entity_id: &str,
) -> Result<Vec<BankAccount>> {
    let search = SearchBuilder::new().field("entity", entity_id).build();

    let accounts = client
        .search::<serde_json::Value>(EntityType::Accounts, &search)
        .await?;

    let result: Vec<BankAccount> = accounts
        .iter()
        .map(|account| {
            let account_type = account
                .get("type")
                .and_then(|t| t.as_i64())
                .unwrap_or(0) as i32;
            let id = account
                .get("id")
                .and_then(|i| i.as_str())
                .unwrap_or("")
                .to_string();
            let token = account
                .get("token")
                .and_then(|t| t.as_str())
                .unwrap_or("")
                .to_string();

            BankAccount {
                id,
                token,
                account_type,
            }
        })
        .collect();

    Ok(result)
}

/// Get an account by type for an entity
///
/// # Arguments
/// * `client` - Payrix API client
/// * `entity_id` - Payrix entity ID
/// * `account_type` - Account type to find
///
/// # Returns
/// The bank account of the specified type if found
pub async fn get_account_by_type(
    client: &PayrixClient,
    entity_id: &str,
    account_type: i32,
) -> Result<Option<BankAccount>> {
    let accounts = get_accounts_for_entity(client, entity_id).await?;
    Ok(accounts.into_iter().find(|a| a.account_type == account_type))
}

/// Get available and pending funds for an entity
///
/// # Arguments
/// * `client` - Payrix API client
/// * `entity_id` - Payrix entity ID
///
/// # Returns
/// Tuple of (available_cents, pending_cents)
pub async fn get_funds_for_entity(client: &PayrixClient, entity_id: &str) -> Result<(i64, i64)> {
    let search = SearchBuilder::new().field("entity", entity_id).build();

    let funds = client
        .search::<serde_json::Value>(EntityType::Funds, &search)
        .await?;

    let fund = funds.into_iter().next().ok_or_else(|| {
        crate::Error::NotFound(
            "No funds found - processor may not have processed any transactions yet".to_string(),
        )
    })?;

    let available = fund
        .get("available")
        .and_then(|a| a.as_i64())
        .unwrap_or(0);
    let pending = fund.get("pending").and_then(|p| p.as_i64()).unwrap_or(0);

    Ok((available, pending))
}

/// Get payout history for an entity
///
/// # Arguments
/// * `client` - Payrix API client
/// * `entity_id` - Payrix entity ID
/// * `start_date` - Optional start date in YYYYMMDD format
/// * `end_date` - Optional end date in YYYYMMDD format
///
/// # Returns
/// Vector of payouts
pub async fn get_payouts_for_entity(
    client: &PayrixClient,
    entity_id: &str,
    start_date: Option<&str>,
    end_date: Option<&str>,
) -> Result<Vec<serde_json::Value>> {
    let mut search = SearchBuilder::new().field("entity", entity_id);

    if let Some(start) = start_date {
        // Note: Payrix uses 'greater' (not 'gte'), which is > (exclusive)
        // To include the start date, callers may need to subtract one day
        search = search.field("created[greater]", start);
    }
    if let Some(end) = end_date {
        // Note: Payrix uses 'less' (not 'lte'), which is < (exclusive)
        // To include the end date, callers may need to add one day
        search = search.field("created[less]", end);
    }

    let payouts = client
        .search::<serde_json::Value>(EntityType::Payouts, &search.build())
        .await?;

    Ok(payouts)
}

/// Create a payout to a specific account
///
/// # Arguments
/// * `client` - Payrix API client
/// * `entity_id` - Payrix entity ID
/// * `account_token` - Bank account token (from `account.token`, not `account.id`)
/// * `amount_cents` - Amount in cents (can be negative for pulling funds)
/// * `description` - Description for the payout
/// * `start_date` - Payout start date in YYYYMMDD format
/// * `config` - Payout configuration (schedule, usage method, same-day options)
///
/// # Example
/// ```rust,ignore
/// use payrix::workflows::account_management::{create_payout, PayoutConfig};
///
/// // Simple single payout
/// let payout = create_payout(
///     &client,
///     "t1_ent_123",
///     "tok_abc",
///     10000, // $100.00
///     "Monthly disbursement",
///     "20240115",
///     PayoutConfig::single(),
/// ).await?;
///
/// // Same-day ACH payout
/// let payout = create_payout(
///     &client,
///     "t1_ent_123",
///     "tok_abc",
///     10000,
///     "Urgent payout",
///     "20240115",
///     PayoutConfig::single_same_day(),
/// ).await?;
///
/// // Weekly recurring payout
/// let payout = create_payout(
///     &client,
///     "t1_ent_123",
///     "tok_abc",
///     10000,
///     "Weekly settlement",
///     "20240115",
///     PayoutConfig::recurring(PayoutSchedule::Weekly, 1),
/// ).await?;
/// ```
///
/// # Returns
/// The created payout
pub async fn create_payout(
    client: &PayrixClient,
    entity_id: &str,
    account_token: &str,
    amount_cents: i64,
    description: &str,
    start_date: &str,
    config: PayoutConfig,
) -> Result<serde_json::Value> {
    let payout_data = serde_json::json!({
        "entity": entity_id,
        "account": account_token,
        "amount": amount_cents,
        "schedule": config.schedule.as_i32(),
        "scheduleFactor": config.schedule_factor,
        "start": start_date,
        "description": description,
        "um": config.usage_method.as_i32(),
        "sameDay": if config.same_day { 1 } else { 0 },
    });

    let payout = client
        .create::<_, serde_json::Value>(EntityType::Payouts, &payout_data)
        .await?;

    tracing::info!(
        "Created payout {} for ${:.2} to account {}",
        payout
            .get("id")
            .and_then(|i| i.as_str())
            .unwrap_or("unknown"),
        amount_cents as f64 / 100.0,
        account_token
    );

    Ok(payout)
}

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

    #[test]
    fn test_bank_account_struct() {
        let account = BankAccount {
            id: "acc_1".to_string(),
            token: "tok_1".to_string(),
            account_type: 1,
        };

        assert_eq!(account.id, "acc_1");
        assert_eq!(account.token, "tok_1");
        assert_eq!(account.account_type, 1);
    }

    #[test]
    fn test_payout_schedule_values() {
        assert_eq!(PayoutSchedule::Single.as_i32(), 5);
        assert_eq!(PayoutSchedule::Daily.as_i32(), 1);
        assert_eq!(PayoutSchedule::Weekly.as_i32(), 2);
        assert_eq!(PayoutSchedule::BiWeekly.as_i32(), 3);
        assert_eq!(PayoutSchedule::Monthly.as_i32(), 4);
    }

    #[test]
    fn test_payout_usage_method_values() {
        assert_eq!(PayoutUsageMethod::Percentage.as_i32(), 1);
        assert_eq!(PayoutUsageMethod::Actual.as_i32(), 2);
    }

    #[test]
    fn test_payout_config_default() {
        let config = PayoutConfig::default();
        assert_eq!(config.schedule.as_i32(), 5); // Single
        assert_eq!(config.schedule_factor, 1);
        assert_eq!(config.usage_method.as_i32(), 2); // Actual
        assert!(!config.same_day);
    }

    #[test]
    fn test_payout_config_single() {
        let config = PayoutConfig::single();
        assert_eq!(config.schedule.as_i32(), 5);
        assert!(!config.same_day);
    }

    #[test]
    fn test_payout_config_single_same_day() {
        let config = PayoutConfig::single_same_day();
        assert_eq!(config.schedule.as_i32(), 5);
        assert!(config.same_day);
    }

    #[test]
    fn test_payout_config_recurring() {
        let config = PayoutConfig::recurring(PayoutSchedule::Weekly, 2);
        assert_eq!(config.schedule.as_i32(), 2); // Weekly
        assert_eq!(config.schedule_factor, 2);
        assert!(!config.same_day);
    }
}