-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.go
329 lines (259 loc) · 11.1 KB
/
api.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package giftcard
import (
"github.com/ottemo/commerce/api"
"github.com/ottemo/commerce/app/models/order"
"github.com/ottemo/commerce/app/models/visitor"
"github.com/ottemo/commerce/db"
"github.com/ottemo/commerce/env"
"github.com/ottemo/commerce/utils"
"math"
"strings"
"time"
)
// setupAPI configures the API endpoints for the giftcard package
func setupAPI() error {
service := api.GetRestService()
// store
service.GET("giftcards/:giftcode", GetSingleCode)
service.GET("giftcards", GetList)
// cart endpoints
service.POST("cart/giftcards/:giftcode", Apply)
service.DELETE("cart/giftcards/:giftcode", Remove)
// Admin Only
service.GET("giftcard/:id/history", api.IsAdminHandler(GetHistory))
service.POST("giftcard", api.IsAdminHandler(createFromAdmin))
return nil
}
// GetSingleCode returns the gift card and related info
// - giftcode must be specified on the request
func GetSingleCode(context api.InterfaceApplicationContext) (interface{}, error) {
giftCardID := context.GetRequestArgument("giftcode")
if giftCardID == "" {
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "06792fd7-c838-4acc-9c6f-cb8fcff833dd", "No giftcard code specified in the request.")
}
rows, err := getGiftCardsByCode(giftCardID)
if err != nil {
context.SetResponseStatusBadRequest()
return nil, env.ErrorDispatch(err)
}
if len(rows) == 0 {
return nil, env.ErrorNew(ConstErrorModule, ConstErrorLevel, "dd7b2130-b5ed-4b26-b1fc-2d36c3bf147f", "No giftcard code matching the one supplied on the request found.")
}
return rows[0], nil
}
// GetList returns a list of gift cards for the visitor id in the context passed
// - visitor must be logged in
func GetList(context api.InterfaceApplicationContext) (interface{}, error) {
// check request context
//---------------------
collection, err := db.GetCollection(ConstCollectionNameGiftCard)
if err != nil {
context.SetResponseStatusInternalServerError()
return nil, env.ErrorDispatch(err)
}
if api.ValidateAdminRights(context) != nil {
visitorID := visitor.GetCurrentVisitorID(context)
if visitorID == "" {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "77d16dff-95bc-433d-9876-cc36e3645489", "Please log in to complete your request.")
}
collection.AddFilter("visitor_id", "=", visitorID)
}
// checking for a "count" request
if context.GetRequestArgument(api.ConstRESTActionParameter) == "count" {
return collection.Count()
}
dbRecords, err := collection.Load()
if err != nil {
context.SetResponseStatusInternalServerError()
return nil, env.ErrorDispatch(err)
}
for _, value := range dbRecords {
initialAmount := utils.InterfaceToFloat64(value["amount"])
for _, amount := range utils.InterfaceToMap(value["orders_used"]) {
initialAmount = initialAmount + math.Abs(utils.InterfaceToFloat64(amount))
}
value["initial_amount"] = initialAmount
}
return dbRecords, nil
}
// Apply applies the provided gift card to current checkout
// - Gift Card code should be specified in "giftcode" argument
func Apply(context api.InterfaceApplicationContext) (interface{}, error) {
giftCardCode := context.GetRequestArgument("giftcode")
// getting applied gift codes array for current session
appliedGiftCardCodes := utils.InterfaceToStringArray(context.GetSession().Get(ConstSessionKeyAppliedGiftCardCodes))
// checking if codes have previously been applied
if utils.IsInArray(giftCardCode, appliedGiftCardCodes) {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "1c310f79-0f79-493a-b761-ad4f24542559", "This code, "+giftCardCode+" has already been applied.")
}
// loading gift codes for specified code
records, err := getGiftCardsByCode(giftCardCode)
if err != nil {
context.SetResponseStatusBadRequest()
return nil, env.ErrorDispatch(err)
}
// checking and applying provided gift card codes
if len(records) == 1 && utils.InterfaceToString(records[0]["code"]) == giftCardCode {
if utils.InterfaceToFloat64(records[0]["amount"]) <= 0 {
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "ce349f59-51c7-43ec-a64c-80f7d4af6d3c", "The provided giftcard value has been exhausted.")
}
// giftcard code is valid - applying it
appliedGiftCardCodes = append(appliedGiftCardCodes, giftCardCode)
context.GetSession().Set(ConstSessionKeyAppliedGiftCardCodes, appliedGiftCardCodes)
} else {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "2b55d714-2cba-49f8-ad7d-fdc542bfc2a3", "The provided giftcard code cannot be found, "+giftCardCode+".")
}
return "ok", nil
}
// Remove removes the application of the gift card value from the
// current checkout
// - giftcard code should be specified in the "giftcode" argument
// - use "*" as giftcard code to 'remove' all giftcard discounts
func Remove(context api.InterfaceApplicationContext) (interface{}, error) {
giftCardID := context.GetRequestArgument("giftcode")
if giftCardID == "" {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "e2bad33a-36e7-41d4-aea7-8fe1b97eb31c", "No giftcard code found on the request.")
}
if giftCardID == "*" {
context.GetSession().Set(ConstSessionKeyAppliedGiftCardCodes, make([]string, 0))
return "Remove successful", nil
}
appliedCoupons := utils.InterfaceToStringArray(context.GetSession().Get(ConstSessionKeyAppliedGiftCardCodes))
if len(appliedCoupons) > 0 {
var newAppliedCoupons []string
for _, value := range appliedCoupons {
if value != giftCardID {
newAppliedCoupons = append(newAppliedCoupons, value)
}
}
context.GetSession().Set(ConstSessionKeyAppliedGiftCardCodes, newAppliedCoupons)
}
return "Remove successful", nil
}
// GetHistory returns a history of gift cards for the admin in the context passed
// - giftcard id should be specified in the "giftid" argument
func GetHistory(context api.InterfaceApplicationContext) (interface{}, error) {
giftCardID := context.GetRequestArgument("id")
if giftCardID == "" {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "10ab8fd5-05ca-43e2-9da9-8acac0ea13f9", "No giftcard code specified in the request.")
}
collection, err := db.GetCollection(ConstCollectionNameGiftCard)
if err != nil {
context.SetResponseStatusBadRequest()
return nil, env.ErrorDispatch(err)
}
row, err := collection.LoadByID(giftCardID)
if err != nil {
context.SetResponseStatusBadRequest()
return nil, env.ErrorDispatch(err)
}
if len(row) == 0 {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, ConstErrorLevel, "5caad227-e93b-46a9-9833-1b2eb53d19e1", "No giftcard code matching the one supplied on the request found.")
}
var historyData []map[string]interface{}
for orderId, amount := range utils.InterfaceToMap(row["orders_used"]) {
orderData, err := order.LoadOrderByID(orderId)
if err != nil {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "cb86e6de-b94d-4480-bc87-90301676f4fe", "system error loading id from db: "+utils.InterfaceToString(orderId))
}
historyData = append(historyData, map[string]interface{}{
"order_id": utils.InterfaceToString(orderId),
"amount": math.Abs(utils.InterfaceToFloat64(amount)),
"transaction_date": orderData.Get("created_at"),
})
}
return historyData, nil
}
// createFromAdmin
func createFromAdmin(context api.InterfaceApplicationContext) (interface{}, error) {
requestData, err := api.GetRequestContentAsMap(context)
if err != nil {
context.SetResponseStatusBadRequest()
return nil, env.ErrorDispatch(err)
}
if !utils.KeysInMapAndNotBlank(requestData, "amount", "message", "name", "recipient_mailbox", "sku") {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, ConstErrorLevel, "e4a6ad26-fd34-428b-8cca-9baed590a67e", "amount or message or name or recipient_mailbox or sku have not been specified")
}
currentTime := time.Now()
deliveryDate := utils.InterfaceToTime(requestData["delivery_date"])
giftCardAmount := utils.InterfaceToInt(requestData["amount"])
customMessage := utils.InterfaceToString(requestData["message"])
recipientName := utils.InterfaceToString(requestData["name"])
recipientEmail := utils.InterfaceToString(requestData["recipient_mailbox"])
giftCardSku := utils.InterfaceToString(requestData["sku"])
giftCardUniqueCode := utils.InterfaceToString(requestData["code"])
rows, err := getGiftCardsByCode(giftCardUniqueCode)
if err != nil {
context.SetResponseStatusBadRequest()
return nil, env.ErrorDispatch(err)
}
if giftCardUniqueCode == "" || len(rows) != 0 {
// generate unique code by unix nano time
giftCardUniqueCode = utils.InterfaceToString(time.Now().UnixNano())
}
// collect necessary info to variables
// get a customer and his mail to set him as addressee
visitorID := visitor.GetCurrentVisitorID(context)
if visitorID == "" {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "39a37b12-93fb-4660-836e-ef5e07c2af52", "Please log in to complete your request.")
}
giftCardSkuElement := utils.InterfaceToString(env.ConfigGetValue(ConstConfigPathGiftCardSKU))
if strings.Contains(giftCardSku, giftCardSkuElement) == false {
context.SetResponseStatusBadRequest()
return nil, env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "bdb67702-5939-483b-8be3-079bdc576ae6", "Please log in to complete your request.")
}
giftCardCollection, err := db.GetCollection(ConstCollectionNameGiftCard)
if err != nil {
context.SetResponseStatusBadRequest()
return false, env.ErrorDispatch(err)
}
giftCard := make(map[string]interface{})
giftCard["code"] = giftCardUniqueCode
giftCard["sku"] = giftCardSku
giftCard["amount"] = giftCardAmount
giftCard["visitor_id"] = visitorID
giftCard["status"] = ConstGiftCardStatusNew
giftCard["orders_used"] = make(map[string]float64)
giftCard["name"] = recipientName
giftCard["message"] = customMessage
giftCard["recipient_mailbox"] = recipientEmail
giftCard["delivery_date"] = deliveryDate
giftCardID, err := giftCardCollection.Save(giftCard)
if err != nil {
context.SetResponseStatusBadRequest()
return false, env.ErrorDispatch(err)
}
var giftCardsToSendImmediately []string
// run SendTask task to send immediately if delivery_date is today's date
if deliveryDate.Truncate(time.Hour).Before(currentTime) {
giftCardsToSendImmediately = append(giftCardsToSendImmediately, giftCardID)
params := map[string]interface{}{
"giftCards": giftCardsToSendImmediately,
"ignoreDeliveryDate": true,
}
go SendTask(params)
}
return true, nil
}
// getGiftCardsByCode returns a list of gift cards for the giftCardCode
func getGiftCardsByCode(giftCardCode string) ([]map[string]interface{}, error) {
collection, err := db.GetCollection(ConstCollectionNameGiftCard)
if err != nil {
return nil, env.ErrorDispatch(err)
}
collection.AddFilter("code", "=", giftCardCode)
rows, err := collection.Load()
if err != nil {
return nil, env.ErrorDispatch(err)
}
return rows, nil
}