/
split_the_bill.go
134 lines (114 loc) · 2.59 KB
/
split_the_bill.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package pgsql
import (
"context"
"database/sql/driver"
"encoding/json"
"github.com/SlamJam/dolgovnya-backend/internal/app/models"
"github.com/pkg/errors"
)
type dbBill models.Bill
// Value make the Attrs struct implement the driver.Valuer interface.
func (b dbBill) Value() (driver.Value, error) {
res, err := json.Marshal(b)
if err == nil {
return string(res), err
}
return res, err
}
// Scan make the PriceData struct implement the sql.Scanner interface.
func (b *dbBill) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
return json.Unmarshal(bytes, b)
}
type dbInvoice struct {
Accounting int64 `db:"owner_accounting"`
UserFrom models.UserID `db:"user_from"`
UserTo models.UserID `db:"user_to"`
Amount models.Money `db:"amount"`
}
func (s *Storage) SaveSplittedBill(ctx context.Context, ownerID models.UserID, bill models.Bill) (models.BillID, error) {
invoices, err := bill.ToInvoices()
if err != nil {
return 0, errors.WithStack(err)
}
tx, err := s.pool.BeginTxx(ctx, nil)
if err != nil {
return 0, errors.WithStack(err)
}
defer tx.Rollback()
var owningObjID int64
psql.Insert("owner_objects").
Columns(
"user_id",
).
Values(
ownerID,
).
Suffix(`RETURNING "id"`).
RunWith(tx).
QueryRow().
Scan(&owningObjID)
if err != nil {
return 0, errors.WithStack(err)
}
var billID models.BillID
psql.Insert("accounting_split_the_bill").
Columns(
"user_id",
"owning_object_id",
"schema_version",
"bill",
).
Values(
ownerID,
owningObjID,
bill.GetSchemaVersion(),
dbBill(bill),
).
Suffix(`RETURNING "id"`).
RunWith(tx).
QueryRow().
Scan(&billID)
if err != nil {
return 0, errors.WithStack(err)
}
q := psql.Insert("accounting_entries").
Columns(
"user_id",
"owning_object_id",
"user_from",
"user_to",
"amount",
)
for _, invoice := range invoices {
q = q.Values(
ownerID,
owningObjID,
invoice.UserFrom,
invoice.UserTo,
invoice.Value.Decimal,
)
}
rows, err := q.RunWith(tx).Query()
if err != nil {
return 0, errors.WithStack(err)
}
defer rows.Close()
err = tx.Commit()
if err != nil {
return 0, errors.WithStack(err)
}
return billID, nil
}
func (s *Storage) ListUserBills(ctx context.Context, userID models.UserID) ([]models.Bill, error) {
return nil, nil
}
func (s *Storage) GetBills(ctx context.Context, billIDs []models.BillID) ([]models.Bill, error) {
return nil, nil
}
func (s *Storage) DeleteBills(ctx context.Context, billIDs []models.BillID) ([]models.Bill, error) {
return nil, nil
}