rust-ynab 0.4.1

A Rust client for the YNAB 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
use chrono::{DateTime, NaiveDate};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::Client;
use crate::Error;
use crate::PlanId;
use crate::ynab::common::NO_PARAMS;

#[derive(Debug, Serialize, Deserialize)]
struct CategoriesDataEnvelope {
    data: CategoriesData,
}

#[derive(Debug, Serialize, Deserialize)]
struct CategoriesData {
    category_groups: Vec<CategoryGroup>,
    server_knowledge: i64,
}

#[derive(Debug, Serialize, Deserialize)]
struct CategoryDataEnvelope {
    data: CategoryData,
}

#[derive(Debug, Serialize, Deserialize)]
struct CategoryData {
    category: Category,
}

#[derive(Debug, Serialize, Deserialize)]
struct SaveCategoryGroupDataEnvelope {
    data: CategoryGroupData,
}

#[derive(Debug, Serialize, Deserialize)]
struct CategoryGroupData {
    category_group: CategoryGroup,
    server_knowledge: i64,
}

/// A group of budget categories.
#[derive(Debug, Serialize, Deserialize)]
pub struct CategoryGroup {
    pub id: Uuid,
    pub name: String,
    pub hidden: bool,
    pub deleted: bool,
    #[serde(default)]
    pub categories: Vec<Category>,
}

/// A budget category. Amounts (assigned, activity, available, etc.) are specific to the current
/// plan month (UTC) and are in milliunits (divide by 1000 for display).
#[derive(Debug, Serialize, Deserialize)]
pub struct Category {
    pub id: Uuid,
    pub category_group_id: Uuid,
    pub category_group_name: Option<String>,
    pub name: String,
    pub hidden: bool,
    pub original_category_group_id: Option<Uuid>,
    pub note: Option<String>,
    pub budgeted: i64,
    pub activity: i64,
    pub balance: i64,
    pub goal_type: Option<GoalType>,
    pub goal_needs_whole_amount: Option<bool>,
    pub goal_day: Option<usize>,
    pub goal_cadence: Option<usize>,
    pub goal_cadence_frequency: Option<usize>,
    pub goal_creation_month: Option<NaiveDate>,
    pub goal_target: Option<i64>,
    pub goal_target_date: Option<NaiveDate>,
    pub goal_target_month: Option<NaiveDate>,
    pub goal_percentage_complete: Option<usize>,
    pub goal_months_to_budget: Option<usize>,
    pub goal_under_funded: Option<i64>,
    pub goal_overall_funded: Option<i64>,
    pub goal_overall_left: Option<i64>,
    pub goal_snoozed_at: Option<DateTime<chrono::Utc>>,
    pub deleted: bool,
}

/// The type of savings or spending goal assigned to a category.
#[derive(Debug, Serialize, Deserialize)]
pub enum GoalType {
    #[serde(rename = "TB")]
    TargetBalance, // "TB"
    #[serde(rename = "TBD")]
    TargetBalanceByDate, // "TBD"
    #[serde(rename = "NEED")]
    PlanYourSpending, // "NEED"
    #[serde(rename = "MF")]
    MonthlyFunding, // "MF"
    #[serde(rename = "DEBT")]
    Debt, // "DEBT"
    #[serde(other)]
    Other,
}

#[derive(Debug)]
pub struct GetCategoriesBuilder<'a> {
    client: &'a Client,
    plan_id: PlanId,
    last_knowledge_of_server: Option<i64>,
}

impl<'a> GetCategoriesBuilder<'a> {
    pub fn with_server_knowledge(mut self, sk: i64) -> GetCategoriesBuilder<'a> {
        self.last_knowledge_of_server = Some(sk);
        self
    }

    pub async fn send(self) -> Result<(Vec<CategoryGroup>, i64), Error> {
        let params: Option<&[(&str, &str)]> = if let Some(sk) = self.last_knowledge_of_server {
            Some(&[("last_knowledge_of_server", &sk.to_string())])
        } else {
            None
        };
        let result: CategoriesDataEnvelope = self
            .client
            .get(&format!("plans/{}/categories", self.plan_id), params)
            .await?;
        Ok((result.data.category_groups, result.data.server_knowledge))
    }
}

impl Client {
    /// Returns all categories grouped by category group. Amounts (assigned, activity, available,
    /// etc.) are specific to the current plan month (UTC). The second return value is server
    /// knowledge for delta requests.
    pub fn get_categories(&self, plan_id: PlanId) -> GetCategoriesBuilder<'_> {
        GetCategoriesBuilder {
            client: self,
            plan_id,
            last_knowledge_of_server: None,
        }
    }

    /// Returns a single category. Amounts (assigned, activity, available, etc.) are specific to
    /// the current plan month (UTC).
    pub async fn get_category(&self, plan_id: PlanId, cat_id: Uuid) -> Result<Category, Error> {
        let result: CategoryDataEnvelope = self
            .get(
                &format!("plans/{}/categories/{}", plan_id, cat_id),
                NO_PARAMS,
            )
            .await?;

        Ok(result.data.category)
    }

    /// Returns a single category for a specific plan month. Amounts (assigned, activity,
    /// available, etc.) are specific to the current plan month (UTC).
    pub async fn get_category_for_month(
        &self,
        plan_id: PlanId,
        month: NaiveDate,
        cat_id: Uuid,
    ) -> Result<Category, Error> {
        let result: CategoryDataEnvelope = self
            .get(
                &format!("plans/{}/months/{}/categories/{}", plan_id, month, cat_id),
                NO_PARAMS,
            )
            .await?;

        Ok(result.data.category)
    }
}

/// The category group to create or update.
#[derive(Debug, Serialize)]
pub struct SaveCategoryGroup {
    pub name: String,
}

/// The category to create.
#[derive(Debug, Serialize)]
pub struct NewCategory {
    pub name: String,
    pub category_group_id: Uuid,
    pub note: Option<String>,
    pub goal_target: Option<i64>,
    pub goal_target_date: Option<NaiveDate>,
    pub goal_needs_whole_amount: Option<bool>,
}

/// The category to update. Only specified (non-`None`) fields will be changed.
#[derive(Debug, Serialize)]
pub struct SaveCategory {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category_group_id: Option<Uuid>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub goal_target: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub goal_target_date: Option<NaiveDate>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub goal_needs_whole_amount: Option<bool>,
}

/// The month category to update. Only `budgeted` (assigned) can be changed.
#[derive(Debug, Serialize)]
pub struct SaveMonthCategory {
    pub budgeted: i64,
}

#[derive(Debug, Serialize)]
struct NewCategoryBody {
    category: NewCategory,
}

#[derive(Debug, Serialize)]
struct SaveCategoryBody {
    category: SaveCategory,
}

#[derive(Debug, Serialize)]
struct SaveMonthCategoryBody {
    category: SaveMonthCategory,
}

#[derive(Debug, Serialize)]
struct SaveCategoryGroupBody {
    category_group: SaveCategoryGroup,
}

#[derive(Debug, Serialize, Deserialize)]
struct SaveCategoryDataEnvelope {
    data: SaveCategoryData,
}

#[derive(Debug, Serialize, Deserialize)]
struct SaveCategoryData {
    category: Category,
    server_knowledge: i64,
}

impl Client {
    /// Creates a new category.
    pub async fn create_category(
        &self,
        plan_id: PlanId,
        category: NewCategory,
    ) -> Result<(Category, i64), Error> {
        let result: SaveCategoryDataEnvelope = self
            .post(
                &format!("plans/{plan_id}/categories"),
                NewCategoryBody { category },
            )
            .await?;
        Ok((result.data.category, result.data.server_knowledge))
    }

    /// Creates a new category group.
    pub async fn create_category_group(
        &self,
        plan_id: PlanId,
        category_group: SaveCategoryGroup,
    ) -> Result<(CategoryGroup, i64), Error> {
        let result: SaveCategoryGroupDataEnvelope = self
            .post(
                &format!("plans/{plan_id}/category_groups"),
                SaveCategoryGroupBody { category_group },
            )
            .await?;
        Ok((result.data.category_group, result.data.server_knowledge))
    }

    /// Update a category.
    pub async fn update_category(
        &self,
        plan_id: PlanId,
        category_id: Uuid,
        category: SaveCategory,
    ) -> Result<(Category, i64), Error> {
        let result: SaveCategoryDataEnvelope = self
            .patch(
                &format!("plans/{plan_id}/categories/{category_id}"),
                SaveCategoryBody { category },
            )
            .await?;
        Ok((result.data.category, result.data.server_knowledge))
    }

    /// Update a category for a specific month. Only `budgeted` (assigned) amount can be updated.`
    pub async fn update_category_for_month(
        &self,
        plan_id: PlanId,
        month: NaiveDate,
        category_id: Uuid,
        category: SaveMonthCategory,
    ) -> Result<(Category, i64), Error> {
        let result: SaveCategoryDataEnvelope = self
            .patch(
                &format!("plans/{plan_id}/months/{month}/categories/{category_id}"),
                SaveMonthCategoryBody { category },
            )
            .await?;
        Ok((result.data.category, result.data.server_knowledge))
    }

    /// Update a category group.
    pub async fn update_category_group(
        &self,
        plan_id: PlanId,
        category_group_id: Uuid,
        category_group: SaveCategoryGroup,
    ) -> Result<(CategoryGroup, i64), Error> {
        let result: SaveCategoryGroupDataEnvelope = self
            .patch(
                &format!("plans/{plan_id}/category_groups/{category_group_id}"),
                SaveCategoryGroupBody { category_group },
            )
            .await?;
        Ok((result.data.category_group, result.data.server_knowledge))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ynab::testutil::{
        TEST_ID_1, TEST_ID_2, category_fixture, category_group_fixture, error_body, new_test_client,
    };
    use serde_json::json;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, ResponseTemplate};

    #[tokio::test]
    async fn create_category_succeeds() {
        let (client, server) = new_test_client().await;

        let fixture = category_fixture();
        let envelope = json!({
            "data": {
                "category": fixture,
                "server_knowledge": 1
            }
        });

        Mock::given(method("POST"))
            .and(path(format!("/plans/{}/categories", TEST_ID_1)))
            .respond_with(ResponseTemplate::new(201).set_body_json(envelope))
            .expect(1)
            .mount(&server)
            .await;

        let category = NewCategory {
            name: fixture["name"].as_str().unwrap().to_string(),
            category_group_id: TEST_ID_2.parse().unwrap(),
            note: None,
            goal_target: None,
            goal_target_date: None,
            goal_needs_whole_amount: None,
        };

        let (response, sk) = client
            .create_category(PlanId::Id(TEST_ID_1.parse().unwrap()), category)
            .await
            .unwrap();

        assert_eq!(response.id.to_string(), TEST_ID_1);
        assert_eq!(response.name, fixture["name"].as_str().unwrap());
        assert_eq!(response.balance, fixture["balance"].as_i64().unwrap());
        assert_eq!(sk, 1);
    }

    #[tokio::test]
    async fn create_category_returns_internal_server_error() {
        let (client, server) = new_test_client().await;

        Mock::given(method("POST"))
            .and(path(format!("/plans/{}/categories", TEST_ID_1)))
            .respond_with(ResponseTemplate::new(500).set_body_json(error_body(
                "500",
                "internal_server_error",
                "An internal error occurred",
            )))
            .expect(1)
            .mount(&server)
            .await;

        let category = NewCategory {
            name: "Groceries".to_string(),
            category_group_id: TEST_ID_2.parse().unwrap(),
            note: None,
            goal_target: None,
            goal_target_date: None,
            goal_needs_whole_amount: None,
        };

        let result = client
            .create_category(PlanId::Id(TEST_ID_1.parse().unwrap()), category)
            .await;

        assert!(matches!(result, Err(Error::InternalServerError(_))));
    }

    #[tokio::test]
    async fn get_categories_returns_category_groups() {
        let (client, server) = new_test_client().await;
        let fixture = json!({
            "data": { "category_groups": [category_group_fixture()], "server_knowledge": 2 }
        });
        Mock::given(method("GET"))
            .and(path(format!("/plans/{}/categories", TEST_ID_1)))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture))
            .expect(1)
            .mount(&server)
            .await;
        let (groups, sk) = client
            .get_categories(PlanId::Id(TEST_ID_1.parse().unwrap()))
            .send()
            .await
            .unwrap();
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].id.to_string(), TEST_ID_2);
        assert_eq!(groups[0].categories.len(), 1);
        assert_eq!(sk, 2);
    }

    #[tokio::test]
    async fn get_category_returns_category() {
        let (client, server) = new_test_client().await;
        let fixture = category_fixture();
        let envelope = json!({ "data": { "category": fixture } });
        Mock::given(method("GET"))
            .and(path(format!(
                "/plans/{}/categories/{}",
                TEST_ID_1, TEST_ID_1
            )))
            .respond_with(ResponseTemplate::new(200).set_body_json(envelope))
            .expect(1)
            .mount(&server)
            .await;
        let category = client
            .get_category(
                PlanId::Id(TEST_ID_1.parse().unwrap()),
                TEST_ID_1.parse().unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(category.id.to_string(), TEST_ID_1);
        assert_eq!(category.name, "Groceries");
    }

    #[tokio::test]
    async fn get_category_for_month_returns_category() {
        let (client, server) = new_test_client().await;
        let month = chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let fixture = category_fixture();
        let envelope = json!({ "data": { "category": fixture } });
        Mock::given(method("GET"))
            .and(path(format!(
                "/plans/{}/months/{}/categories/{}",
                TEST_ID_1, month, TEST_ID_1
            )))
            .respond_with(ResponseTemplate::new(200).set_body_json(envelope))
            .expect(1)
            .mount(&server)
            .await;
        let category = client
            .get_category_for_month(
                PlanId::Id(TEST_ID_1.parse().unwrap()),
                month,
                TEST_ID_1.parse().unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(category.id.to_string(), TEST_ID_1);
    }

    #[tokio::test]
    async fn create_category_group_succeeds() {
        let (client, server) = new_test_client().await;
        let fixture = category_group_fixture();
        let envelope = json!({ "data": { "category_group": fixture, "server_knowledge": 2 } });
        Mock::given(method("POST"))
            .and(path(format!("/plans/{}/category_groups", TEST_ID_1)))
            .respond_with(ResponseTemplate::new(201).set_body_json(envelope))
            .expect(1)
            .mount(&server)
            .await;
        let (group, sk) = client
            .create_category_group(
                PlanId::Id(TEST_ID_1.parse().unwrap()),
                SaveCategoryGroup {
                    name: "Everyday Expenses".to_string(),
                },
            )
            .await
            .unwrap();
        assert_eq!(group.id.to_string(), TEST_ID_2);
        assert_eq!(sk, 2);
    }

    #[tokio::test]
    async fn update_category_succeeds() {
        let (client, server) = new_test_client().await;
        let fixture = category_fixture();
        let envelope = json!({ "data": { "category": fixture, "server_knowledge": 4 } });
        Mock::given(method("PATCH"))
            .and(path(format!(
                "/plans/{}/categories/{}",
                TEST_ID_1, TEST_ID_1
            )))
            .respond_with(ResponseTemplate::new(200).set_body_json(envelope))
            .expect(1)
            .mount(&server)
            .await;
        let (category, sk) = client
            .update_category(
                PlanId::Id(TEST_ID_1.parse().unwrap()),
                TEST_ID_1.parse().unwrap(),
                SaveCategory {
                    name: Some("Groceries".to_string()),
                    category_group_id: None,
                    note: None,
                    goal_target: None,
                    goal_target_date: None,
                    goal_needs_whole_amount: None,
                },
            )
            .await
            .unwrap();
        assert_eq!(category.id.to_string(), TEST_ID_1);
        assert_eq!(sk, 4);
    }

    #[tokio::test]
    async fn update_category_group_succeeds() {
        let (client, server) = new_test_client().await;
        let fixture = category_group_fixture();
        let envelope = json!({ "data": { "category_group": fixture, "server_knowledge": 4 } });
        Mock::given(method("PATCH"))
            .and(path(format!(
                "/plans/{}/category_groups/{}",
                TEST_ID_1, TEST_ID_2
            )))
            .respond_with(ResponseTemplate::new(200).set_body_json(envelope))
            .expect(1)
            .mount(&server)
            .await;
        let (group, sk) = client
            .update_category_group(
                PlanId::Id(TEST_ID_1.parse().unwrap()),
                TEST_ID_2.parse().unwrap(),
                SaveCategoryGroup {
                    name: "Everyday Expenses".to_string(),
                },
            )
            .await
            .unwrap();
        assert_eq!(group.id.to_string(), TEST_ID_2);
        assert_eq!(sk, 4);
    }
}