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
package api
import (
"encoding/json"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Transaction struct {
gorm.Model
MemberNum int `json:"-" gorm:"column:member"`
Member Member `json:"member" gorm:"foreignKey:MemberNum;references:Num"`
Date time.Time `json:"date"`
Total int `json:"total"`
Type string `json:"type"`
Purchase []Purchase `json:"purchase"`
}
func (a *api) ListTransactions(w http.ResponseWriter, req *http.Request) {
var transactions []Transaction
err := a.db.Preload("Purchase.Product").
Preload(clause.Associations).
Find(&transactions).Error
if err != nil {
log.Printf("Can't list transactions: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(transactions)
if err != nil {
log.Printf("Can't encode transactions: %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
}
func (a *api) GetTransaction(num int, role string, w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
var transaction Transaction
err := a.db.Preload("Purchase.Product").
Preload(clause.Associations).
First(&transaction, vars["id"]).Error
if err != nil {
if err.Error() == "record not found" {
w.WriteHeader(http.StatusNotFound)
return
}
log.Printf("Can't get transaction %s: %v", vars["code"], err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if transaction.MemberNum != num && role != "admin" {
w.WriteHeader(http.StatusUnauthorized)
return
}
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
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(transaction)
if err != nil {
log.Printf("Can't encode transaction: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (a *api) GetMemberTransactions(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
num, _ := strconv.Atoi(vars["num"])
a.getTransactionsByMember(num, w, req)
}
func (a *api) getTransactionsByMember(num int, w http.ResponseWriter, req *http.Request) {
var transactions []Transaction
err := a.db.Where("member = ?", num).
Preload("Purchase.Product").
Preload(clause.Associations).
Find(&transactions).Error
if err != nil {
log.Printf("Can't list transactions: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(transactions)
if err != nil {
log.Printf("Can't encode transactions: %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
}