Newer
Older
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
package api
import (
"encoding/json"
"log"
"net/http"
"time"
"gorm.io/gorm"
)
type Topup struct {
gorm.Model `json:"-"`
TransactionID int `json:"-" gorm:"column:transaction"`
MemberNum int `json:"member" gorm:"column:member"`
Member Member `json:"-" gorm:"foreignKey:MemberNum;references:Num"`
Comment string `json:"comment"`
}
func (a *api) AddTopup(adminNum int, w http.ResponseWriter, req *http.Request) {
var topup struct {
Member int `json:"member"`
Comment string `json:"comment"`
Ammount int `json:"ammount"`
}
err := json.NewDecoder(req.Body).Decode(&topup)
if err != nil {
log.Printf("Can't parse topup: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
httpStatus := a.updateMemberBalance(topup.Member, topup.Ammount)
if httpStatus != http.StatusOK {
w.WriteHeader(httpStatus)
return
}
transaction := Transaction{
MemberNum: topup.Member,
Date: time.Now(),
Topup: Topup{
MemberNum: adminNum,
Comment: topup.Comment,
},
Type: "toupup",
Total: topup.Ammount,
}
err = a.db.Create(&transaction).Error
if err != nil {
log.Printf("Can't create topup: %v\n%v", err, transaction)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
err = json.NewEncoder(w).Encode(transaction)
if err != nil {
log.Printf("Can't encode added topup: %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
}