/
handlers.go
204 lines (168 loc) · 5.96 KB
/
handlers.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package orders
import (
// "fmt"
"log"
"net/http"
"strconv"
"github.com/dfang/qor-demo/config"
"github.com/dfang/qor-demo/models/orders"
"github.com/dfang/qor-demo/utils"
"github.com/gorilla/schema"
// amazonpay "github.com/qor/amazon-pay-sdk-go"
"github.com/qor/gomerchant"
qorrender "github.com/qor/render"
"github.com/qor/responder"
"github.com/qor/session/manager"
)
// Controller products controller
type Controller struct {
View *qorrender.Render
}
var decoder = schema.NewDecoder()
// Cart shopping cart
func (ctrl Controller) Cart(w http.ResponseWriter, req *http.Request) {
tx := utils.GetDB(req)
order := getCurrentOrderWithItems(w, req)
log.Println("Order ID is ", order.ID)
var orderItems []orders.OrderItem
tx.Model(&order).Preload("SizeVariation.Size").Preload("ColorVariation").Find(&orderItems)
// tx.Where("order_id = ?", order.ID).Preload("SizeVariation").Find(&orderItems)
// tx.Model(&order).Association("SizeVariation").Find(&orderItems)
// tx.Where("order_id = ?", order.ID).Association("ColorVariation").Find(&orderItems)
log.Println("order.OrderItems count is", len(orderItems))
ctrl.View.Execute("cart", map[string]interface{}{"Order": order, "OrderItems": orderItems}, req, w)
}
// Checkout checkout shopping cart
func (ctrl Controller) Checkout(w http.ResponseWriter, req *http.Request) {
hasAmazon := req.URL.Query().Get("access_token")
order := getCurrentOrderWithItems(w, req)
ctrl.View.Execute("checkout", map[string]interface{}{"Order": order, "HasAmazon": hasAmazon}, req, w)
}
// Complete complete shopping cart
func (ctrl Controller) Complete(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
// order := getCurrentOrder(w, req)
// if order.AmazonOrderReferenceID = req.Form.Get("amazon_order_reference_id"); order.AmazonOrderReferenceID != "" {
// order.AmazonAddressAccessToken = req.Form.Get("amazon_address_access_token")
// tx := utils.GetDB(req)
// err := orders.OrderState.Trigger("checkout", order, tx, "")
// if err == nil {
// tx.Save(order)
// http.Redirect(w, req, "/cart/success", http.StatusFound)
// return
// }
// utils.AddFlashMessage(w, req, err.Error(), "error")
// } else {
utils.AddFlashMessage(w, req, "Order Reference ID not Found", "error")
// }
http.Redirect(w, req, "/cart", http.StatusFound)
}
// CompleteCreditCard complete shopping cart with credit card
func (ctrl Controller) CompleteCreditCard(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
order := getCurrentOrder(w, req)
expMonth, _ := strconv.Atoi(req.Form.Get("exp_month"))
expYear, _ := strconv.Atoi(req.Form.Get("exp_year"))
creditCard := gomerchant.CreditCard{
Name: req.Form.Get("name"),
Number: req.Form.Get("creditcard"),
CVC: req.Form.Get("cvv"),
ExpYear: uint(expYear),
ExpMonth: uint(expMonth),
}
if creditCard.ValidNumber() {
// TODO integrate with https://github.com/qor/gomerchant to handle those information
tx := utils.GetDB(req)
err := orders.OrderState.Trigger("checkout", order, tx, "")
if err == nil {
tx.Save(order)
http.Redirect(w, req, "/cart/success", http.StatusFound)
return
}
}
utils.AddFlashMessage(w, req, "Invalid Credit Card", "error")
http.Redirect(w, req, "/cart", http.StatusFound)
}
// CheckoutSuccess checkout success page
func (ctrl Controller) CheckoutSuccess(w http.ResponseWriter, req *http.Request) {
ctrl.View.Execute("success", map[string]interface{}{}, req, w)
}
type updateCartInput struct {
SizeVariationID uint `schema:"size_variation_id"`
Quantity uint `schema:"quantity"`
ProductID uint `schema:"product_id"`
ColorVariationID uint `schema:"color_variation_id"`
}
// UpdateCart update shopping cart
func (ctrl Controller) UpdateCart(w http.ResponseWriter, req *http.Request) {
var (
input updateCartInput
tx = utils.GetDB(req)
)
req.ParseForm()
decoder.Decode(&input, req.PostForm)
order := getCurrentOrder(w, req)
if input.Quantity > 0 {
tx.Where(&orders.OrderItem{
OrderID: order.ID,
SizeVariationID: input.SizeVariationID,
ColorVariationID: input.ColorVariationID,
}).
Assign(&orders.OrderItem{Quantity: input.Quantity}).
FirstOrCreate(&orders.OrderItem{})
} else {
tx.Where(&orders.OrderItem{
OrderID: order.ID,
SizeVariationID: input.SizeVariationID,
ColorVariationID: input.ColorVariationID,
}).
Delete(&orders.OrderItem{})
}
responder.With("html", func() {
http.Redirect(w, req, "/cart", http.StatusFound)
}).With([]string{"json", "xml"}, func() {
config.Render.JSON(w, http.StatusOK, map[string]string{"status": "ok"})
}).Respond(req)
}
// AmazonCallback amazon callback
func (ctrl Controller) AmazonCallback(w http.ResponseWriter, req *http.Request) {
// ipn, ok := amazonpay.VerifyIPNRequest(req)
// fmt.Printf("%#v\n", ipn)
// fmt.Printf("%#v\n", ok)
}
func getCurrentOrder(w http.ResponseWriter, req *http.Request) *orders.Order {
var (
order = orders.Order{}
cartID = manager.SessionManager.Get(req, "cart_id")
currentUser = utils.GetCurrentUser(req)
tx = utils.GetDB(req)
)
if cartID != "" {
if currentUser != nil && !tx.NewRecord(currentUser) {
if !tx.First(&order, "id = ? AND (user_id = ? OR user_id IS NULL)", cartID, currentUser.ID).RecordNotFound() && order.UserID == nil {
tx.Model(&order).Update("UserID", currentUser.ID)
}
} else {
tx.First(&order, "id = ? AND user_id IS NULL", cartID)
}
}
// only create new shopping cart if updating
if tx.NewRecord(order) || !order.IsCart() {
order = orders.Order{}
if req.Method != "GET" {
if currentUser != nil && !tx.NewRecord(currentUser) {
order.UserID = ¤tUser.ID
}
tx.Create(&order)
}
}
manager.SessionManager.Add(w, req, "cart_id", order.ID)
return &order
}
func getCurrentOrderWithItems(w http.ResponseWriter, req *http.Request) *orders.Order {
order := getCurrentOrder(w, req)
if tx := utils.GetDB(req); !tx.NewRecord(order) {
tx.Model(order).Association("OrderItems").Find(&order.OrderItems)
}
return order
}