/
main.go
177 lines (144 loc) · 4.54 KB
/
main.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package main
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-pg/pg/v10"
"log"
"net/http"
"os"
"time"
"context"
)
var db *pg.DB
func main() {
config, err := loadConfig("config.json")
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
db = pg.Connect(&pg.Options{
Addr: fmt.Sprintf("%s:%d", config.Host, config.Port),
User: config.User,
Password: config.Password,
Database: config.Database,
})
defer db.Close()
r := gin.Default()
r.POST("/users", createUser)
r.GET("/users/:uuid/balances", checkBalances)
r.POST("/payments", sendPayment)
r.Run(":8088")
}
//... (Other functions and types remain the same)
func checkBalances(c *gin.Context) {
uuid := c.Param("uuid")
if uuid == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "UUID is required"})
return
}
var balances []AccountType
err := db.Model(&balances).Where("customer_uuid = ?", uuid).Select()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve balances"})
return
}
c.JSON(http.StatusOK, gin.H{"balances": balances})
}
func createUser(c *gin.Context) {
var request UserCreationRequest
if err := c.ShouldBindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
return
}
user := &Customer{
Name: request.Name,
LastName: request.LastName,
State: request.State,
Country: request.Country,
ZipCode: request.ZipCode,
BankingStatus: request.BankingStatus,
}
_, err := db.Model(user).Insert()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "User created successfully"})
}
// Update makeTransfer function as per your business logic using go-pg
func sendPayment(c *gin.Context) {
var payment PaymentRequest
if err := c.ShouldBindJSON(&payment); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
return
}
if payment.Amount <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Amount must be greater than 0"})
return
}
if payment.FromUUID == payment.ToUUID {
c.JSON(http.StatusBadRequest, gin.H{"error": "Sender and receiver cannot be the same"})
return
}
err := makeTransfer(payment.FromUUID, payment.ToUUID, payment.Amount)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to make transfer: " + err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Payment successful"})
}
func loadConfig(filename string) (*DBConfig, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("failed to open config file: %v", err)
}
defer file.Close()
var config DBConfig
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
return nil, fmt.Errorf("failed to decode config file: %v", err)
}
return &config, nil
}
// ... (Other functions remain the same)
func makeTransfer(fromUUID, toUUID string, amount float64) error {
return db.RunInTransaction(context.Background(), func(tx *pg.Tx) error {
// Retrieve sender and receiver account details.
var fromAccount, toAccount AccountType
if err := tx.Model(&fromAccount).Where("customer_uuid = ?", fromUUID).For("UPDATE").Select(); err != nil {
return fmt.Errorf("failed to retrieve sender account: %v", err)
}
if err := tx.Model(&toAccount).Where("customer_uuid = ?", toUUID).For("UPDATE").Select(); err != nil {
return fmt.Errorf("failed to retrieve receiver account: %v", err)
}
// Check if sender has enough balance.
if fromAccount.Balance < amount {
return fmt.Errorf("insufficient funds")
}
// Update balances.
fromAccount.Balance -= amount
toAccount.Balance += amount
// Update sender account in database.
if _, err := tx.Model(&fromAccount).WherePK().Update(); err != nil {
return fmt.Errorf("failed to update sender account: %v", err)
}
// Update receiver account in database.
if _, err := tx.Model(&toAccount).WherePK().Update(); err != nil {
return fmt.Errorf("failed to update receiver account: %v", err)
}
// Record transaction in ledger.
ledgerEntry := Ledger{
SenderUUID: fromUUID,
ReceiverUUID: toUUID,
Amount: amount,
AccountType: fromAccount.AccountType, // Assuming the AccountType is same for both accounts, adjust if needed
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if _, err := tx.Model(&ledgerEntry).Insert(); err != nil {
return fmt.Errorf("failed to record transaction in ledger: %v", err)
}
return nil
})
}