/
transaction.go
107 lines (84 loc) · 2.29 KB
/
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
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
package repo
import (
"errors"
"github.com/hrvadl/coursework_db/pkg/models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Transaction interface {
Get(userID int) ([]models.Transaction, error)
Add(t *models.Transaction) (*models.Transaction, error)
}
func NewTransaction(db *gorm.DB, irepo Inventory) Transaction {
return &transaction{
db: db,
irepo: irepo,
}
}
type transaction struct {
irepo Inventory
db *gorm.DB
}
func (t *transaction) Get(userID int) ([]models.Transaction, error) {
var transactions []models.Transaction
res := t.db.
Model(&models.Transaction{}).
Preload(clause.Associations).
Preload("Subject.Security").
Where(&models.Transaction{SellerID: uint(userID)}).
Or(&models.Transaction{BuyerID: uint(userID)}).
Find(&transactions)
if err := res.Error; err != nil {
return nil, err
}
return transactions, nil
}
func (t *transaction) Add(new *models.Transaction) (*models.Transaction, error) {
dealMoney := float64(new.Amount) * new.Subject.Price
err := t.db.Transaction(func(tx *gorm.DB) error {
sellingItem, err := t.irepo.GetUserInventoryBySecurityID(int(new.Seller.ID), int(new.Subject.SecurityID))
if err != nil {
return err
}
sellingItem.Amount -= new.Amount
if _, err := t.irepo.Patch(sellingItem); err != nil {
return err
}
boughtItem, err := t.irepo.GetUserInventoryBySecurityID(int(new.Buyer.ID), int(new.Subject.SecurityID))
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
if boughtItem == nil {
boughtItem = &models.InventoryItem{}
boughtItem.SecurityID = new.Subject.SecurityID
boughtItem.OwnerID = new.BuyerID
}
boughtItem.Amount += new.Amount
if err := t.irepo.Save(boughtItem); err != nil {
return err
}
if err := t.db.Create(new).Error; err != nil {
return err
}
new.Buyer.Balance -= int(dealMoney)
if err := tx.Save(new.Buyer).Error; err != nil {
return err
}
new.Seller.Balance += int(dealMoney)
if err := tx.Save(new.Seller).Error; err != nil {
return err
}
if new.Amount > new.Subject.Amount {
return errors.New("trying to buy to much")
}
new.Subject.Amount -= new.Amount
if new.Subject.Amount == 0 {
new.Subject.Active = false
}
if err := tx.Save(new.Subject).Error; err != nil {
return err
}
return nil
})
return new, err
}