1
0
mirror of https://github.com/aclindsa/moneygo.git synced 2024-12-26 23:42:29 -05:00

transactions.go: Split calculation of imbalance $$ from Balanced() method

This commit is contained in:
Aaron Lindsay 2016-02-11 06:08:05 -05:00
parent 380e66ed0c
commit b71c862cbf

View File

@ -111,19 +111,21 @@ func (t *Transaction) Valid() bool {
return true return true
} }
func (t *Transaction) Balanced() (bool, error) { // Return a map of security ID's to big.Rat's containing the amount that
var zero big.Rat // security is imbalanced by
func (t *Transaction) GetImbalances() (map[int64]big.Rat, error) {
sums := make(map[int64]big.Rat) sums := make(map[int64]big.Rat)
if !t.Valid() { if !t.Valid() {
return false, errors.New("Transaction invalid") return nil, errors.New("Transaction invalid")
} }
for i := range t.Splits { for i := range t.Splits {
securityid := t.Splits[i].SecurityId securityid := t.Splits[i].SecurityId
if t.Splits[i].AccountId != -1 { if t.Splits[i].AccountId != -1 {
account, err := GetAccount(t.Splits[i].AccountId, t.UserId) account, err := GetAccount(t.Splits[i].AccountId, t.UserId)
if err != nil { if err != nil {
return false, err return nil, err
} }
securityid = account.SecurityId securityid = account.SecurityId
} }
@ -132,6 +134,19 @@ func (t *Transaction) Balanced() (bool, error) {
(&sum).Add(&sum, amount) (&sum).Add(&sum, amount)
sums[securityid] = sum sums[securityid] = sum
} }
return sums, nil
}
// Returns true if all securities contained in this transaction are balanced,
// false otherwise
func (t *Transaction) Balanced() (bool, error) {
var zero big.Rat
sums, err := t.GetImbalances()
if err != nil {
return false, err
}
for _, security_sum := range sums { for _, security_sum := range sums {
if security_sum.Cmp(&zero) != 0 { if security_sum.Cmp(&zero) != 0 {
return false, nil return false, nil