-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
99 lines (75 loc) · 2.42 KB
/
service.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
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
package accounts
import (
"context"
"github.com/devdammit/shekel/cmd/unit/internal/entities"
"github.com/devdammit/shekel/pkg/currency"
"github.com/devdammit/shekel/pkg/types/datetime"
)
type Repository interface {
GetAll() ([]entities.Account, error)
}
type CurrencyRates interface {
Convert(amount currency.Amount, to currency.Code, date datetime.DateTime) (*currency.Amount, error)
}
type Service struct {
repo Repository
currencyRates CurrencyRates
}
func NewService(repo Repository, currencyRates CurrencyRates) *Service {
return &Service{
repo: repo,
currencyRates: currencyRates,
}
}
// CalculateBalances calculates the balances of all accounts affected by the given transactions.
func (s *Service) CalculateBalances(_ context.Context, chunk []entities.Transaction) (map[uint64]entities.Account, error) {
accounts, err := s.repo.GetAll()
if err != nil {
return nil, err
}
mapAccounts := make(map[uint64]currency.Amount, len(accounts))
affectedAccounts := make(map[uint64]struct{}, len(accounts))
for _, account := range accounts {
mapAccounts[account.ID] = account.Balance
}
for _, transaction := range chunk {
if transaction.From != nil {
acc := mapAccounts[transaction.From.ID]
affectedAccounts[transaction.From.ID] = struct{}{}
var value currency.Amount
if acc.CurrencyCode != transaction.Amount.CurrencyCode {
convertedAmount, err := s.currencyRates.Convert(transaction.Amount, acc.CurrencyCode, transaction.CreatedAt)
if err != nil {
return nil, err
}
value = acc.Subtract(*convertedAmount)
} else {
value = acc.Subtract(transaction.Amount)
}
mapAccounts[transaction.From.ID] = value
}
if transaction.To != nil {
acc := mapAccounts[transaction.To.ID]
affectedAccounts[transaction.To.ID] = struct{}{}
var value currency.Amount
if acc.CurrencyCode != transaction.Amount.CurrencyCode {
convertedAmount, err := s.currencyRates.Convert(transaction.Amount, acc.CurrencyCode, transaction.CreatedAt)
if err != nil {
return nil, err
}
value = acc.Add(*convertedAmount)
} else {
value = acc.Add(transaction.Amount)
}
mapAccounts[transaction.To.ID] = value
}
}
result := make(map[uint64]entities.Account, len(accounts))
for _, account := range accounts {
if _, ok := affectedAccounts[account.ID]; ok {
account.Balance = mapAccounts[account.ID]
result[account.ID] = account
}
}
return result, nil
}