vynfi 1.0.0

Rust SDK for the VynFi synthetic financial data API
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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Integration tests against a real VynFi API.
//!
//! These tests are `#[ignore]`d by default so `cargo test` skips them.
//!
//! Run them with:
//!
//! ```sh
//! VYNFI_API_KEY=vf_live_... cargo test --test integration -- --ignored
//! VYNFI_API_KEY=vf_live_... VYNFI_BASE_URL=http://localhost:3001 cargo test --test integration -- --ignored
//! ```

use vynfi::{
    Client, CreateApiKeyRequest, CreateConfigRequest, CreateScenarioRequest, CreateSessionRequest,
    EstimateCostRequest, GenerateRequest, ListConfigsParams, ListJobsParams,
    ListNotificationsParams, MarkReadRequest, TableSpec, UpdateApiKeyRequest, UpdateConfigRequest,
    ValidateConfigRequest, VynFiError,
};

/// Build a client from environment variables.
fn client() -> Client {
    let api_key = std::env::var("VYNFI_API_KEY").expect("VYNFI_API_KEY must be set");
    let mut builder = Client::builder(api_key);
    if let Ok(url) = std::env::var("VYNFI_BASE_URL") {
        builder = builder.base_url(url);
    }
    builder.build().expect("failed to build client")
}

// ===========================================================================
// Catalog / Sectors
// ===========================================================================

#[tokio::test]
#[ignore]
async fn catalog_list_sectors() {
    let c = client();
    let sectors = c.catalog().list_sectors().await.unwrap();
    assert!(!sectors.is_empty(), "expected at least one sector");
    for s in &sectors {
        assert!(!s.slug.is_empty());
        assert!(s.table_count > 0, "sector {} has 0 tables", s.slug);
    }
}

#[tokio::test]
#[ignore]
async fn catalog_get_sector_retail() {
    let c = client();
    let sector = c.catalog().get_sector("retail").await.unwrap();
    assert_eq!(sector.slug, "retail");
    assert!(!sector.tables.is_empty(), "retail should have tables");
    let names: Vec<&str> = sector.tables.iter().map(|t| t.name.as_str()).collect();
    assert!(
        names.contains(&"Journal Entries"),
        "retail should include Journal Entries, got: {names:?}"
    );
}

#[tokio::test]
#[ignore]
async fn catalog_get_sector_not_found() {
    let c = client();
    let err = c
        .catalog()
        .get_sector("nonexistent-sector-slug")
        .await
        .unwrap_err();
    assert!(
        matches!(err, VynFiError::NotFound(_)),
        "expected NotFound, got: {err:?}"
    );
}

#[tokio::test]
#[ignore]
async fn catalog_list() {
    let c = client();
    let items = c.catalog().list(None, None).await.unwrap();
    assert!(!items.is_empty(), "expected at least one catalog item");
}

#[tokio::test]
#[ignore]
async fn catalog_list_filtered() {
    let c = client();
    let items = c.catalog().list(Some("retail"), None).await.unwrap();
    for item in &items {
        assert_eq!(item.slug, "retail");
    }
}

// ===========================================================================
// Usage
// ===========================================================================

#[tokio::test]
#[ignore]
async fn usage_summary() {
    let c = client();
    let summary = c.usage().summary(None).await.unwrap();
    assert!(summary.period_days > 0);
}

#[tokio::test]
#[ignore]
async fn usage_daily() {
    let c = client();
    let resp = c.usage().daily(Some(7)).await.unwrap();
    assert!(resp.daily.len() <= 7);
}

// ===========================================================================
// Jobs — list & get (read-only, no credits spent)
// ===========================================================================

#[tokio::test]
#[ignore]
async fn jobs_list() {
    let c = client();
    let list = c
        .jobs()
        .list(&ListJobsParams {
            limit: Some(5),
            ..Default::default()
        })
        .await
        .unwrap();
    for job in &list.data {
        assert!(!job.id.is_empty());
        assert!(!job.status.is_empty());
    }
}

#[tokio::test]
#[ignore]
async fn jobs_get_not_found() {
    let c = client();
    let err = c
        .jobs()
        .get("00000000-0000-0000-0000-000000000000")
        .await
        .unwrap_err();
    assert!(
        matches!(err, VynFiError::NotFound(_)),
        "expected NotFound, got: {err:?}"
    );
}

// ===========================================================================
// Jobs — generate quick (spends credits)
// ===========================================================================

#[tokio::test]
#[ignore]
async fn jobs_generate_quick_and_download() {
    let c = client();

    let req = GenerateRequest::new(
        vec![TableSpec {
            name: "journal_entries".to_string(),
            rows: 10,
            base_rate: None,
        }],
        "retail",
    );

    let resp = c.jobs().generate_quick(&req).await.unwrap();
    assert_eq!(resp.status, "completed");
    assert!(resp.rows_generated > 0);
    assert!(resp.credits_used > 0);

    // Download the output
    let bytes = c.jobs().download(&resp.id).await.unwrap();
    assert!(!bytes.is_empty());
}

#[tokio::test]
#[ignore]
async fn jobs_generate_async() {
    let c = client();

    let req = GenerateRequest::new(
        vec![TableSpec {
            name: "journal_entries".to_string(),
            rows: 10,
            base_rate: None,
        }],
        "retail",
    );

    let resp = c.jobs().generate(&req).await.unwrap();
    assert!(!resp.id.is_empty());
    assert!(!resp.status.is_empty());
    assert!(resp.credits_reserved > 0);
}

#[tokio::test]
#[ignore]
async fn jobs_generate_validation_error() {
    let c = client();

    let req = GenerateRequest {
        tables: vec![],
        format: None,
        sector_slug: Some("retail".to_string()),
        options: None,
    };

    let err = c.jobs().generate_quick(&req).await.unwrap_err();
    assert!(
        matches!(err, VynFiError::Validation(_)),
        "expected Validation, got: {err:?}"
    );
}

// ===========================================================================
// API Keys — full CRUD lifecycle
// ===========================================================================

#[tokio::test]
#[ignore]
async fn api_keys_lifecycle() {
    let c = client();

    // Create
    let created = c
        .api_keys()
        .create(&CreateApiKeyRequest {
            name: "integration-test-key".to_string(),
            environment: Some("test".to_string()),
        })
        .await
        .unwrap();

    assert!(!created.id.is_empty());
    assert!(!created.key.is_empty(), "full secret should be returned");
    assert!(
        created.key.starts_with("vf_test_"),
        "test env key should have vf_test_ prefix, got: {}",
        created.key
    );
    assert_eq!(created.name, "integration-test-key");
    assert_eq!(created.environment, "test");

    let key_id = created.id.clone();

    // List — the new key should appear
    let keys = c.api_keys().list().await.unwrap();
    assert!(
        keys.iter().any(|k| k.id == key_id),
        "newly created key should appear in list"
    );

    // Get
    let fetched = c.api_keys().get(&key_id).await.unwrap();
    assert_eq!(fetched.id, key_id);
    assert_eq!(fetched.name, "integration-test-key");

    // Update
    let updated = c
        .api_keys()
        .update(
            &key_id,
            &UpdateApiKeyRequest {
                name: Some("integration-test-key-updated".to_string()),
                scopes: None,
            },
        )
        .await
        .unwrap();
    assert_eq!(updated.name, "integration-test-key-updated");

    // Revoke (cleanup)
    let revoked = c.api_keys().revoke(&key_id).await.unwrap();
    assert_eq!(revoked.id, key_id);
    assert_eq!(revoked.status, "revoked");
}

// ===========================================================================
// Quality
// ===========================================================================

#[tokio::test]
#[ignore]
async fn quality_scores() {
    let c = client();
    let scores = c.quality().scores().await.unwrap();
    for s in &scores {
        assert!(!s.id.is_empty());
        assert!(s.overall_score >= 0.0);
    }
}

#[tokio::test]
#[ignore]
async fn quality_timeline() {
    let c = client();
    let timeline = c.quality().timeline(Some(7)).await.unwrap();
    for day in &timeline {
        assert!(day.score >= 0.0);
    }
}

// ===========================================================================
// Billing
// ===========================================================================

#[tokio::test]
#[ignore]
async fn billing_subscription() {
    let c = client();
    let sub = c.billing().subscription().await.unwrap();
    assert!(!sub.tier.is_empty());
    assert!(!sub.status.is_empty());
}

#[tokio::test]
#[ignore]
async fn billing_invoices() {
    let c = client();
    let invoices = c.billing().invoices().await.unwrap();
    for inv in &invoices {
        assert!(!inv.id.is_empty());
    }
}

// ===========================================================================
// Templates
// ===========================================================================

#[tokio::test]
#[ignore]
async fn catalog_list_templates() {
    let c = client();
    let templates = c.catalog().list_templates(None).await.unwrap();
    assert!(!templates.is_empty(), "expected at least one template");
    for t in &templates {
        assert!(!t.slug.is_empty());
        assert!(!t.name.is_empty());
        assert!(!t.sector.is_empty());
    }
}

#[tokio::test]
#[ignore]
async fn catalog_list_templates_filtered() {
    let c = client();
    let templates = c.catalog().list_templates(Some("retail")).await.unwrap();
    for t in &templates {
        assert_eq!(t.sector, "retail", "expected only retail templates");
    }
}

// ===========================================================================
// Configs — CRUD lifecycle + validation + cost estimation
// ===========================================================================

#[tokio::test]
#[ignore]
async fn configs_lifecycle() {
    let c = client();

    // Create
    let created = c
        .configs()
        .create(&CreateConfigRequest {
            name: "integration-test-config".to_string(),
            description: Some("Created by integration test".to_string()),
            config: serde_json::json!({"rows": 100, "sector": "retail"}),
            source_template_id: None,
            visibility: Some("private".to_string()),
            tags: Some(vec!["test".to_string()]),
        })
        .await
        .unwrap();

    assert!(!created.id.is_empty());
    assert_eq!(created.name, "integration-test-config");
    assert_eq!(created.visibility, "private");
    let config_id = created.id.clone();

    // List — new config should appear
    let configs = c
        .configs()
        .list(&ListConfigsParams::default())
        .await
        .unwrap();
    assert!(
        configs.iter().any(|cfg| cfg.id == config_id),
        "newly created config should appear in list"
    );

    // Get
    let fetched = c.configs().get(&config_id).await.unwrap();
    assert_eq!(fetched.id, config_id);
    assert_eq!(fetched.name, "integration-test-config");

    // Update
    let updated = c
        .configs()
        .update(
            &config_id,
            &UpdateConfigRequest {
                name: Some("integration-test-config-updated".to_string()),
                description: None,
                config: None,
                visibility: None,
                tags: None,
            },
        )
        .await
        .unwrap();
    assert_eq!(updated.name, "integration-test-config-updated");

    // Delete (cleanup)
    let deleted = c.configs().delete(&config_id).await.unwrap();
    assert!(deleted.deleted);
}

#[tokio::test]
#[ignore]
async fn configs_validate() {
    let c = client();
    let resp = c
        .configs()
        .validate(&ValidateConfigRequest {
            config: serde_json::json!({"rows": 1000, "sector": "retail"}),
            partial: None,
            step: None,
        })
        .await
        .unwrap();
    // Whether valid or not, should get a structured response
    assert!(resp.valid || !resp.errors.is_empty());
}

#[tokio::test]
#[ignore]
async fn configs_estimate_cost() {
    let c = client();
    let resp = c
        .configs()
        .estimate_cost(&EstimateCostRequest {
            config: serde_json::json!({"rows": 1000, "sector": "retail"}),
        })
        .await
        .unwrap();
    assert!(resp.base_credits > 0);
    assert!(resp.total_credits > 0);
    assert!(!resp.balance.status.is_empty());
}

// ===========================================================================
// Credits — read-only (purchase would create a Stripe session)
// ===========================================================================

#[tokio::test]
#[ignore]
async fn credits_balance() {
    let c = client();
    let resp = c.credits().balance().await.unwrap();
    // total_prepaid_credits may be 0 if no packs purchased; just check it parses
    assert!(resp.total_prepaid_credits >= 0);
}

#[tokio::test]
#[ignore]
async fn credits_history() {
    let c = client();
    let resp = c.credits().history().await.unwrap();
    // History may be empty; just check it parses
    for batch in &resp.batches {
        assert!(!batch.id.is_empty());
        assert!(!batch.pack.is_empty());
    }
}

// ===========================================================================
// Sessions — list + create
// ===========================================================================

#[tokio::test]
#[ignore]
async fn sessions_list() {
    let c = client();
    let sessions = c.sessions().list().await.unwrap();
    for s in &sessions {
        assert!(!s.id.is_empty());
        assert!(!s.status.is_empty());
    }
}

#[tokio::test]
#[ignore]
async fn sessions_create() {
    let c = client();
    let session = c
        .sessions()
        .create(&CreateSessionRequest {
            name: "integration-test-session".to_string(),
            fiscal_year_start: "2026-01-01".to_string(),
            period_length_months: 3,
            periods: 4,
            generation_config: serde_json::json!({"rows": 100, "sector": "retail"}),
        })
        .await
        .unwrap();

    assert!(!session.id.is_empty());
    assert_eq!(session.name, "integration-test-session");
    assert_eq!(session.periods_total, 4);
    assert_eq!(session.period_length_months, 3);
    assert_eq!(session.periods_generated, 0);
}

// ===========================================================================
// Scenarios — list + create
// ===========================================================================

#[tokio::test]
#[ignore]
async fn scenarios_list() {
    let c = client();
    let scenarios = c.scenarios().list().await.unwrap();
    for s in &scenarios {
        assert!(!s.id.is_empty());
        assert!(!s.status.is_empty());
    }
}

#[tokio::test]
#[ignore]
async fn scenarios_create() {
    let c = client();
    let scenario = c
        .scenarios()
        .create(&CreateScenarioRequest {
            name: "integration-test-scenario".to_string(),
            template_id: "supply-chain".to_string(),
            interventions: serde_json::json!({"fraudRate": 0.05}),
            generation_config: serde_json::json!({"rows": 100, "sector": "retail"}),
        })
        .await
        .unwrap();

    assert!(!scenario.id.is_empty());
    assert_eq!(scenario.name, "integration-test-scenario");
    assert_eq!(scenario.status, "created");
}

#[tokio::test]
#[ignore]
async fn scenarios_templates() {
    let c = client();
    let templates = c.scenarios().templates().await.unwrap();
    for t in &templates {
        assert!(!t.id.is_empty());
        assert!(!t.name.is_empty());
    }
}

// ===========================================================================
// Notifications — list + mark read
// ===========================================================================

#[tokio::test]
#[ignore]
async fn notifications_list() {
    let c = client();
    let notifs = c
        .notifications()
        .list(&ListNotificationsParams::default())
        .await
        .unwrap();
    for n in &notifs {
        assert!(!n.id.is_empty());
        assert!(!n.title.is_empty());
    }
}

#[tokio::test]
#[ignore]
async fn notifications_mark_all_read() {
    let c = client();
    // Mark all as read — should succeed even if there are no notifications
    c.notifications()
        .mark_read(&MarkReadRequest {
            ids: None,
            all: Some(true),
        })
        .await
        .unwrap();
}