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
use arrayvec::ArrayString;
use commodity::{Commodity, CommodityTypeID};
use nanoid::nanoid;
use rust_decimal::Decimal;
use std::rc::Rc;

#[cfg(feature = "serde-support")]
use serde::{Deserialize, Serialize};

/// The size in characters/bytes of the [Account](Account) id.
const ACCOUNT_ID_LENGTH: usize = 20;

/// The status of an [Account](Account) stored within an [AccountState](AccountState).
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum AccountStatus {
    /// The account is open
    Open,
    /// The account is closed
    Closed,
}
/// The type to use for the id of [Account](Account)s.
pub type AccountID = ArrayString<[u8; ACCOUNT_ID_LENGTH]>;

/// A way to categorize [Account](Account)s.
pub type AccountCategory = String;

/// Details for an account, which holds a [Commodity](Commodity)
/// with a type of [CommodityType](commodity::CommodityType).
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct Account {
    /// A unique identifier for this `Account`, currently generated using [nanoid](nanoid).
    pub id: AccountID,

    /// The name of this `Account`
    pub name: Option<String>,

    /// The id of the type of commodity to be stored in this account
    pub commodity_type_id: CommodityTypeID,

    /// The category that this account part of
    pub category: Option<AccountCategory>,
}

impl Account {
    /// Create a new account with an automatically generated id (using
    /// [nanoid](nanoid)) and add it to this program state (and create
    /// its associated [AccountState](AccountState)).
    pub fn new_with_id<S: Into<String>>(
        name: Option<S>,
        commodity_type_id: CommodityTypeID,
        category: Option<AccountCategory>,
    ) -> Account {
        let id_string: String = nanoid!(ACCOUNT_ID_LENGTH);
        Self::new(
            ArrayString::from(id_string.as_ref()).expect(
                format!(
                    "generated id string {0} should fit within ACCOUNT_ID_LENGTH: {1}",
                    id_string, ACCOUNT_ID_LENGTH
                )
                .as_ref(),
            ),
            name,
            commodity_type_id,
            category,
        )
    }

    /// Create a new account and add it to this program state (and create its associated
    /// [AccountState](AccountState)).
    pub fn new<S: Into<String>>(
        id: AccountID,
        name: Option<S>,
        commodity_type_id: CommodityTypeID,
        category: Option<AccountCategory>,
    ) -> Account {
        Account {
            id,
            name: name.map(|s| s.into()),
            commodity_type_id,
            category: category.map(|c| c.into()),
        }
    }
}

impl PartialEq for Account {
    fn eq(&self, other: &Account) -> bool {
        self.id == other.id
    }
}

/// Mutable state associated with an [Account](Account).
#[derive(Debug, Clone, PartialEq)]
pub struct AccountState {
    /// The [Account](Account) associated with this state
    pub account: Rc<Account>,

    /// The amount of the commodity currently stored in this account
    pub amount: Commodity,

    /// The status of this account (open/closed/etc...)
    pub status: AccountStatus,
}

impl AccountState {
    /// Create a new [AccountState](AccountState).
    pub fn new(account: Rc<Account>, amount: Commodity, status: AccountStatus) -> AccountState {
        AccountState {
            account,
            amount,
            status,
        }
    }

    /// Open this account, set the `status` to [Open](AccountStatus::Open)
    pub fn open(&mut self) {
        self.status = AccountStatus::Open;
    }

    // Close this account, set the `status` to [Closed](AccountStatus::Closed)
    pub fn close(&mut self) {
        self.status = AccountStatus::Closed;
    }

    pub fn eq_approx(&self, other: &AccountState, epsilon: Decimal) -> bool {
        self.account == other.account
            && self.status == other.status
            && self.amount.eq_approx(other.amount, epsilon)
    }
}

#[cfg(test)]
mod tests {
    use super::Account;
    use crate::AccountID;
    use commodity::CommodityTypeID;
    use std::str::FromStr;

    #[cfg(feature = "serde-support")]
    #[test]
    fn account_serde() {
        use serde_json;

        let json = r#"{
  "id": "ABCDEFGHIJKLMNOPQRST",
  "name": "Test Account",
  "commodity_type_id": "USD",
  "category": "Expense"
}"#;

        let account: Account = serde_json::from_str(json).unwrap();

        let reference_account = Account::new(
            AccountID::from("ABCDEFGHIJKLMNOPQRST").unwrap(),
            Some("TestAccount"),
            CommodityTypeID::from_str("AUD").unwrap(),
            Some("Expense".to_string()),
        );

        assert_eq!(reference_account, account);
        insta::assert_json_snapshot!(account);
    }
}