-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
48 lines (42 loc) · 901 Bytes
/
transaction.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
package entity
import (
"errors"
"time"
"github.com/google/uuid"
)
type Transaction struct {
Entity
To *Account
From *Account
Amount float64
}
func NewTransaction(to, from *Account, amount float64) (*Transaction, error) {
transaction := &Transaction{
Entity: Entity{
Id: uuid.NewString(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
To: to,
From: from,
Amount: amount,
}
if err := transaction.IsValid(); err != nil {
return nil, err
}
transaction.Commit()
return transaction, nil
}
func (e *Transaction) IsValid() error {
if e.Amount < 0 {
return errors.New("unable to execute transaction: negative amount is not allowed")
}
if e.Amount > e.From.Balance {
return errors.New("unable to execute transaction: insufficient funds")
}
return nil
}
func (e *Transaction) Commit() {
e.To.Deposit(e.Amount)
e.From.Withdraw(e.Amount)
}