/
coupons.go
72 lines (62 loc) 路 1.97 KB
/
coupons.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
package routes
import (
"bytes"
"encoding/csv"
"encoding/json"
"net/http"
"github.com/MixinNetwork/supergroup.mixin.one/middlewares"
"github.com/MixinNetwork/supergroup.mixin.one/models"
"github.com/MixinNetwork/supergroup.mixin.one/session"
"github.com/MixinNetwork/supergroup.mixin.one/views"
"github.com/dimfeld/httptreemux"
)
type couponImpl struct{}
type couponRequest struct {
Quantity int `json:"quantity"`
}
func registerCoupons(router *httptreemux.TreeMux) {
impl := &couponImpl{}
router.POST("/coupons", impl.create)
router.POST("/coupons/:code", impl.occupy)
//router.GET("/coupon", impl.reward)
}
func (impl *couponImpl) create(w http.ResponseWriter, r *http.Request, params map[string]string) {
var body couponRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
views.RenderErrorResponse(w, r, session.BadRequestError(r.Context()))
return
}
coupons, err := models.CreateCoupons(r.Context(), middlewares.CurrentUser(r), body.Quantity)
if err != nil {
views.RenderErrorResponse(w, r, err)
} else {
b := &bytes.Buffer{}
wr := csv.NewWriter(b)
for _, coupon := range coupons {
wr.Write([]string{coupon.Code})
}
wr.Flush()
bytes := b.Bytes()
w.Header().Set("Content-Type", "text/csv")
w.Header().Set("Content-Disposition", "attachment;filename=coupons.csv")
w.Write(bytes)
}
}
func (impl *couponImpl) occupy(w http.ResponseWriter, r *http.Request, params map[string]string) {
coupon, err := models.Occupied(r.Context(), params["code"], middlewares.CurrentUser(r))
if err != nil {
views.RenderErrorResponse(w, r, err)
} else if coupon == nil {
views.RenderErrorResponse(w, r, session.NotFoundError(r.Context()))
} else {
views.RenderCoupon(w, r, coupon)
}
}
func (impl *couponImpl) reward(w http.ResponseWriter, r *http.Request, _ map[string]string) {
coupons, err := middlewares.CurrentUser(r).Coupons(r.Context())
if err != nil {
views.RenderErrorResponse(w, r, err)
} else {
views.RenderCoupons(w, r, coupons)
}
}