This repository has been archived by the owner on Sep 10, 2020. It is now read-only.
/
transactions.go
72 lines (58 loc) · 1.85 KB
/
transactions.go
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
package banktorrent
import (
"github.com/russross/meddler"
"fmt"
)
type Transaction struct {
Id int64 `meddler:"id,pk"`
LenderId int64 `meddler:"lender_id"`
DebtorId int64 `meddler:"debtor_id"`
Amount int `meddler:"amount"`
Date string `meddler:"date"`
ExpenseId int64 `meddler:"expense_id"`
}
func GetTransactionById(db meddler.DB, id int64) (*Transaction, error) {
trans := new(Transaction)
err := meddler.Load(db, "transactions", trans, id)
return trans, err
}
// Adds a transaction to the db, and updates the user's balances accordingly
func addTransaction(db meddler.DB, lender *User, debtor *User, amount int, expense *Expense) (*Transaction, error) {
trans := new(Transaction)
trans.LenderId = lender.Id
trans.DebtorId = debtor.Id
trans.Amount = amount
trans.Date = expense.Date
trans.ExpenseId = expense.Id
err := meddler.Insert(db, "transactions", trans)
if err != nil {
return nil, err
}
lender.UpdateBalance(db, amount)
debtor.UpdateBalance(db, -amount)
return trans, nil
}
func (t *Transaction) String() (string) {
return fmt.Sprintf("Transaction #%v [LenderID: %v, DebtorID: %v, Amount: %v, Date: %v, ExpenseID: %v]", t.Id, t.LenderId, t.DebtorId, t.Amount, t.Date, t.ExpenseId)
}
// Reverses a transaction, removes it from the DB, and frees the struct
func (t *Transaction) remove(db meddler.DB) error {
lender, err := GetUserById(db, t.LenderId)
if err != nil {
return err
}
debtor, err := GetUserById(db, t.DebtorId)
if err != nil {
return err
}
// reverse the balance updates due to this transaction
lender.UpdateBalance(db, -(t.Amount))
debtor.UpdateBalance(db, t.Amount)
// remove the transaction from the db
_, err = db.Exec("DELETE FROM transactions WHERE id = ?", t.Id)
if err != nil {
return err
}
t = nil
return nil
}