-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata_handlers.go
1393 lines (1218 loc) · 50 KB
/
data_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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package handlers
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/go-playground/validator"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/meetnearme/api/functions/gateway/handlers/dynamodb_handlers"
"github.com/meetnearme/api/functions/gateway/helpers"
"github.com/meetnearme/api/functions/gateway/services"
"github.com/meetnearme/api/functions/gateway/services/dynamodb_service"
"github.com/meetnearme/api/functions/gateway/transport"
"github.com/meetnearme/api/functions/gateway/types"
internal_types "github.com/meetnearme/api/functions/gateway/types"
"github.com/stripe/stripe-go/v80"
"github.com/stripe/stripe-go/v80/checkout/session"
"github.com/stripe/stripe-go/v80/webhook"
)
var validate *validator.Validate = validator.New()
type MarqoHandler struct {
MarqoService services.MarqoServiceInterface
}
func NewMarqoHandler(marqoService services.MarqoServiceInterface) *MarqoHandler {
return &MarqoHandler{MarqoService: marqoService}
}
type PurchasableWebhookHandler struct {
PurchasableService internal_types.PurchasableServiceInterface
PurchaseService internal_types.PurchaseServiceInterface
}
func NewPurchasableWebhookHandler(purchasableService internal_types.PurchasableServiceInterface, purchaseService internal_types.PurchaseServiceInterface) *PurchasableWebhookHandler {
return &PurchasableWebhookHandler{PurchasableService: purchasableService, PurchaseService: purchaseService}
}
// Create a new struct for raw JSON operations
type rawEventData struct {
Id string `json:"id"`
EventOwners []string `json:"eventOwners" validate:"required,min=1"`
EventOwnerName string `json:"eventOwnerName" validate:"required"`
EventSourceType string `json:"eventSourceType" validate:"required"`
Name string `json:"name" validate:"required"`
Description string `json:"description" validate:"required"`
Address string `json:"address" validate:"required"`
Lat float64 `json:"lat" validate:"required"`
Long float64 `json:"long" validate:"required"`
Timezone string `json:"timezone" validate:"required"`
}
type rawEvent struct {
rawEventData
EventSourceId *string `json:"eventSourceId,omitempty"`
StartTime interface{} `json:"startTime" validate:"required"`
EndTime interface{} `json:"endTime,omitempty"`
StartingPrice *int32 `json:"startingPrice,omitempty"`
Currency *string `json:"currency,omitempty"`
PayeeId *string `json:"payeeId,omitempty"`
HasRegistrationFields *bool `json:"hasRegistrationFields,omitempty"`
HasPurchasable *bool `json:"hasPurchasable,omitempty"`
ImageUrl *string `json:"imageUrl,omitempty"`
Categories *[]string `json:"categories,omitempty"`
Tags *[]string `json:"tags,omitempty"`
CreatedAt *int64 `json:"createdAt,omitempty"`
UpdatedAt *int64 `json:"updatedAt,omitempty"`
UpdatedBy *string `json:"updatedBy,omitempty"`
HideCrossPromo *bool `json:"hideCrossPromo,omitempty"`
}
// Create a new struct that includes the createPurchase fields and the Stripe checkout URL
type PurchaseResponse struct {
internal_types.PurchaseInsert
StripeCheckoutURL string `json:"stripe_checkout_url"`
}
type BulkDeleteEventsPayload struct {
Events []string `json:"events" validate:"required,min=1"`
}
func ConvertRawEventToEvent(raw rawEvent, requireId bool) (types.Event, error) {
loc, err := time.LoadLocation(raw.Timezone)
if err != nil {
return types.Event{}, fmt.Errorf("invalid timezone: %w", err)
}
event := types.Event{
Id: raw.Id,
EventOwners: raw.EventOwners,
EventOwnerName: raw.EventOwnerName,
EventSourceType: raw.EventSourceType,
Name: raw.Name,
Description: raw.Description,
Address: raw.Address,
Lat: raw.Lat,
Long: raw.Long,
Timezone: *loc,
}
// Safely assign pointer values
if raw.StartingPrice != nil {
event.StartingPrice = *raw.StartingPrice
}
if raw.Currency != nil {
event.Currency = *raw.Currency
}
if raw.PayeeId != nil {
event.PayeeId = *raw.PayeeId
}
if raw.HasRegistrationFields != nil {
event.HasRegistrationFields = *raw.HasRegistrationFields
}
if raw.HasPurchasable != nil {
event.HasPurchasable = *raw.HasPurchasable
}
if raw.ImageUrl != nil {
event.ImageUrl = *raw.ImageUrl
}
if raw.Categories != nil {
event.Categories = *raw.Categories
}
if raw.Tags != nil {
event.Tags = *raw.Tags
}
if raw.CreatedAt != nil {
event.CreatedAt = *raw.CreatedAt
}
if raw.UpdatedAt != nil {
event.UpdatedAt = *raw.UpdatedAt
}
if raw.UpdatedBy != nil {
event.UpdatedBy = *raw.UpdatedBy
}
if raw.HideCrossPromo != nil {
event.HideCrossPromo = *raw.HideCrossPromo
}
if raw.EventSourceId != nil {
event.EventSourceId = *raw.EventSourceId
}
if raw.StartTime == nil {
return types.Event{}, fmt.Errorf("startTime is required")
}
startTime, err := helpers.UtcToUnix64(raw.StartTime, loc)
if err != nil || startTime == 0 {
return types.Event{}, fmt.Errorf("invalid StartTime: %w", err)
}
event.StartTime = startTime
if raw.EndTime != nil {
endTime, err := helpers.UtcToUnix64(raw.EndTime, loc)
if err != nil || endTime == 0 {
return types.Event{}, fmt.Errorf("invalid EndTime: %w", err)
}
event.EndTime = endTime
}
if raw.PayeeId != nil || raw.StartingPrice != nil || raw.Currency != nil {
if raw.PayeeId == nil || raw.StartingPrice == nil || raw.Currency == nil {
return types.Event{}, fmt.Errorf("all of 'PayeeId', 'StartingPrice', and 'Currency' are required if any are present")
}
if raw.PayeeId != nil {
event.PayeeId = *raw.PayeeId
}
if raw.Currency != nil {
event.Currency = *raw.Currency
}
if raw.StartingPrice != nil {
event.StartingPrice = *raw.StartingPrice
}
}
return event, nil
}
func ValidateSingleEventPaylod(w http.ResponseWriter, r *http.Request, requireId bool) (event types.Event, status int, err error) {
var raw rawEvent
body, err := io.ReadAll(r.Body)
if err != nil {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("failed to read request body: %w", err)
}
err = json.Unmarshal(body, &raw)
if err != nil {
return types.Event{}, http.StatusUnprocessableEntity, fmt.Errorf("invalid JSON payload: %w", err)
}
event, status, err = HandleSingleEventValidation(raw, requireId)
if err != nil {
return types.Event{}, status, fmt.Errorf("invalid body: %w", err)
}
return event, status, nil
}
func (h *MarqoHandler) PostEvent(w http.ResponseWriter, r *http.Request) {
createEvent, status, err := ValidateSingleEventPaylod(w, r, false)
if err != nil {
transport.SendServerRes(w, []byte("Failed to extract event from payload: "+err.Error()), status, err)
return
}
marqoClient, err := services.GetMarqoClient()
if err != nil {
transport.SendServerRes(w, []byte("Failed to get marqo client: "+err.Error()), http.StatusInternalServerError, err)
return
}
createEvents := []types.Event{createEvent}
res, err := services.BulkUpsertEventToMarqo(marqoClient, createEvents)
if err != nil {
transport.SendServerRes(w, []byte("Failed to upsert event: "+err.Error()), http.StatusInternalServerError, err)
return
}
json, err := json.Marshal(res)
if err != nil {
transport.SendServerRes(w, []byte("Error marshaling JSON"), http.StatusInternalServerError, err)
return
}
transport.SendServerRes(w, json, http.StatusCreated, nil)
}
func PostEventHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
marqoService := services.NewMarqoService()
handler := NewMarqoHandler(marqoService)
return func(w http.ResponseWriter, r *http.Request) {
handler.PostEvent(w, r)
}
}
func HandleSingleEventValidation(rawEvent rawEvent, requireId bool) (types.Event, int, error) {
if err := validate.Struct(rawEvent); err != nil {
// Type assert to get validation errors
if validationErrors, ok := err.(validator.ValidationErrors); ok {
// Get just the first validation error
firstErr := validationErrors[0]
// Extract just the field name and error
return types.Event{}, http.StatusBadRequest,
fmt.Errorf("Field validation for '%s' failed on the '%s' tag",
firstErr.Field(), firstErr.Tag())
}
return types.Event{}, http.StatusBadRequest, err
}
if requireId && rawEvent.Id == "" {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("event has no id")
}
if len(rawEvent.EventOwners) == 0 {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("event is missing eventOwners")
}
if requireId && rawEvent.Id == "" {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("event has no id")
}
if len(rawEvent.EventOwners) == 0 {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("event is missing eventOwners")
}
if rawEvent.EventOwnerName == "" {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("event is missing eventOwnerName")
}
if rawEvent.Timezone == "" {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("event is missing timezone")
}
if helpers.ArrFindFirst([]string{rawEvent.EventSourceType}, helpers.ALL_EVENT_SOURCE_TYPES) == "" {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("invalid eventSourceType: %s", rawEvent.EventSourceType)
}
event, err := ConvertRawEventToEvent(rawEvent, requireId)
if err != nil {
return types.Event{}, http.StatusBadRequest, fmt.Errorf("invalid event : %s", err.Error())
}
return event, http.StatusOK, nil
}
func HandleBatchEventValidation(w http.ResponseWriter, r *http.Request, requireIds bool) ([]types.Event, int, error) {
var payload struct {
Events []rawEvent `json:"events"`
}
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("failed to read request body: %w", err)
}
err = json.Unmarshal(body, &payload)
if err != nil {
return nil, http.StatusUnprocessableEntity, fmt.Errorf("invalid JSON payload: %w", err)
}
err = validate.Struct(&payload)
if err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("invalid body: %w", err)
}
events := make([]types.Event, len(payload.Events))
for i, rawEvent := range payload.Events {
event, statusCode, err := HandleSingleEventValidation(rawEvent, requireIds)
if err != nil {
return nil, statusCode, fmt.Errorf("invalid body: invalid event at index %d: %w", i, err)
}
events[i] = event
}
return events, http.StatusOK, nil
}
func (h *MarqoHandler) PostBatchEvents(w http.ResponseWriter, r *http.Request) {
events, status, err := HandleBatchEventValidation(w, r, false)
if err != nil {
transport.SendServerRes(w, []byte(err.Error()), status, err)
return
}
marqoClient, err := services.GetMarqoClient()
if err != nil {
transport.SendServerRes(w, []byte("Failed to get marqo client: "+err.Error()), http.StatusInternalServerError, err)
return
}
res, err := services.BulkUpsertEventToMarqo(marqoClient, events)
if err != nil {
transport.SendServerRes(w, []byte("Failed to upsert events: "+err.Error()), http.StatusInternalServerError, err)
return
}
json, err := json.Marshal(res)
if err != nil {
transport.SendServerRes(w, []byte("Error marshaling JSON"), http.StatusInternalServerError, err)
return
}
transport.SendServerRes(w, json, http.StatusCreated, nil)
}
func PostBatchEventsHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
marqoService := services.NewMarqoService()
handler := NewMarqoHandler(marqoService)
return func(w http.ResponseWriter, r *http.Request) {
handler.PostBatchEvents(w, r)
}
}
func (h *MarqoHandler) GetOneEvent(w http.ResponseWriter, r *http.Request) {
marqoClient, err := services.GetMarqoClient()
if err != nil {
transport.SendServerRes(w, []byte("Failed to get marqo client: "+err.Error()), http.StatusInternalServerError, err)
return
}
eventId := mux.Vars(r)[helpers.EVENT_ID_KEY]
parseDates := r.URL.Query().Get("parse_dates")
var event *types.Event
event, err = services.GetMarqoEventByID(marqoClient, eventId, parseDates)
if err != nil {
transport.SendServerRes(w, []byte("Failed to get event: "+err.Error()), http.StatusInternalServerError, err)
return
}
json, err := json.Marshal(event)
if err != nil {
transport.SendServerRes(w, []byte("Error marshaling JSON"), http.StatusInternalServerError, err)
return
}
transport.SendServerRes(w, json, http.StatusOK, nil)
}
func GetOneEventHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
marqoService := services.NewMarqoService()
handler := NewMarqoHandler(marqoService)
return func(w http.ResponseWriter, r *http.Request) {
handler.GetOneEvent(w, r)
}
}
func (h *MarqoHandler) BulkUpdateEvents(w http.ResponseWriter, r *http.Request) {
marqoClient, err := services.GetMarqoClient()
if err != nil {
transport.SendServerRes(w, []byte("Failed to get marqo client: "+err.Error()), http.StatusInternalServerError, err)
return
}
events, status, err := HandleBatchEventValidation(w, r, true)
if err != nil {
transport.SendServerRes(w, []byte("Failed to extract event from payload: "+err.Error()), status, err)
return
}
res, err := services.BulkUpdateMarqoEventByID(marqoClient, events)
if err != nil {
transport.SendServerRes(w, []byte("Failed to upsert event: "+err.Error()), http.StatusInternalServerError, err)
return
}
json, err := json.Marshal(res)
if err != nil {
transport.SendServerRes(w, []byte("Error marshaling JSON"), http.StatusInternalServerError, err)
return
}
transport.SendServerRes(w, json, http.StatusOK, nil)
}
func BulkUpdateEventsHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
marqoService := services.NewMarqoService()
handler := NewMarqoHandler(marqoService)
return func(w http.ResponseWriter, r *http.Request) {
handler.BulkUpdateEvents(w, r)
}
}
func SearchLocationsHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
// URL decode the query
decodedQuery, err := url.QueryUnescape(query)
if err != nil {
transport.SendServerRes(w, []byte("Failed to decode query"), http.StatusBadRequest, err)
return
}
// Search for matching cities
query = strings.ToLower(decodedQuery)
matches := helpers.SearchCitiesIndexed(query)
// Prepare the response
var jsonResponse []byte
if len(matches) < 1 {
jsonResponse = []byte("[]")
} else {
jsonResponse, err = json.Marshal(matches)
if err != nil {
transport.SendServerRes(w, []byte("Failed to create JSON response"), http.StatusInternalServerError, err)
return
}
}
w.Header().Set("Content-Type", "application/json")
transport.SendServerRes(w, jsonResponse, http.StatusOK, nil)
}
}
func GetUsersHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Get the ids parameter
idsParam := r.URL.Query().Get("ids")
if idsParam == "" {
transport.SendServerRes(w, []byte("Missing required 'ids' parameter"), http.StatusBadRequest, nil)
return
}
// Parse the comma-separated ids
ids := strings.Split(idsParam, ",")
// Validate each ID
for _, id := range ids {
// Check if ID is exactly 18 characters
if len(id) != 18 {
transport.SendServerRes(w,
[]byte(fmt.Sprintf("Invalid ID length: %s. Must be exactly 18 characters", id)),
http.StatusBadRequest,
nil)
return
}
// Check if ID contains only numeric characters
if !regexp.MustCompile(`^[0-9]+$`).MatchString(id) {
transport.SendServerRes(w,
[]byte(fmt.Sprintf("Invalid ID format: %s. Must contain only numbers", id)),
http.StatusBadRequest,
nil)
return
}
}
// Search for matching users
matches, err := helpers.SearchUsersByIDs(ids, false)
if err != nil {
transport.SendServerRes(w, []byte("Failed to search users: "+err.Error()), http.StatusInternalServerError, err)
return
}
var jsonResponse []byte
if len(matches) < 1 {
jsonResponse = []byte("[]")
} else {
jsonResponse, err = json.Marshal(matches)
if err != nil {
transport.SendServerRes(w, []byte("Failed to create JSON response"), http.StatusInternalServerError, err)
return
}
}
w.Header().Set("Content-Type", "application/json")
transport.SendServerRes(w, jsonResponse, http.StatusOK, nil)
}
}
func SearchUsersHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
// URL decode the query
decodedQuery, err := url.QueryUnescape(query)
if err != nil {
transport.SendServerRes(w, []byte("Failed to decode query"), http.StatusBadRequest, err)
return
}
// Search for matching users
query = strings.ToLower(decodedQuery)
matches, err := helpers.SearchUserByEmailOrName(query)
if err != nil {
transport.SendServerRes(w, []byte("Failed to search users: "+err.Error()), http.StatusInternalServerError, err)
return
}
var jsonResponse []byte
if len(matches) < 1 {
jsonResponse = []byte("[]")
} else {
jsonResponse, err = json.Marshal(matches)
if err != nil {
transport.SendServerRes(w, []byte("Failed to create JSON response"), http.StatusInternalServerError, err)
return
}
}
w.Header().Set("Content-Type", "application/json")
transport.SendServerRes(w, jsonResponse, http.StatusOK, nil)
}
}
func (h *MarqoHandler) UpdateOneEvent(w http.ResponseWriter, r *http.Request) {
marqoClient, err := services.GetMarqoClient()
if err != nil {
transport.SendServerRes(w, []byte("Failed to get marqo client: "+err.Error()), http.StatusInternalServerError, err)
return
}
eventId := mux.Vars(r)[helpers.EVENT_ID_KEY]
if eventId == "" {
transport.SendServerRes(w, []byte("Event must have an id "), http.StatusInternalServerError, err)
return
}
updateEvent, status, err := ValidateSingleEventPaylod(w, r, false)
if err != nil {
transport.SendServerRes(w, []byte("Failed to extract event from payload: "+err.Error()), status, err)
return
}
updateEvent.Id = eventId
updateEvents := []types.Event{updateEvent}
res, err := services.BulkUpdateMarqoEventByID(marqoClient, updateEvents)
if err != nil {
transport.SendServerRes(w, []byte("Failed to upsert event: "+err.Error()), http.StatusInternalServerError, err)
return
}
json, err := json.Marshal(res)
if err != nil {
transport.SendServerRes(w, []byte("Error marshaling JSON"), http.StatusInternalServerError, err)
return
}
transport.SendServerRes(w, json, http.StatusOK, nil)
}
func UpdateOneEventHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
marqoService := services.NewMarqoService()
handler := NewMarqoHandler(marqoService)
return func(w http.ResponseWriter, r *http.Request) {
handler.UpdateOneEvent(w, r)
}
}
func (h *MarqoHandler) SearchEvents(w http.ResponseWriter, r *http.Request) {
// Extract parameter values from the request query parameters
q, userLocation, radius, startTimeUnix, endTimeUnix, _, ownerIds, categories, address, parseDates, eventSourceTypes, eventSourceIds := GetSearchParamsFromReq(r)
marqoClient, err := services.GetMarqoClient()
if err != nil {
transport.SendServerRes(w, []byte("Failed to get marqo client: "+err.Error()), http.StatusInternalServerError, err)
return
}
var res types.EventSearchResponse
res, err = services.SearchMarqoEvents(marqoClient, q, userLocation, radius, startTimeUnix, endTimeUnix, ownerIds, categories, address, parseDates, eventSourceTypes, eventSourceIds)
if err != nil {
transport.SendServerRes(w, []byte("Failed to search events: "+err.Error()), http.StatusInternalServerError, err)
return
}
json, err := json.Marshal(res)
if err != nil {
transport.SendServerRes(w, []byte("Error marshaling JSON"), http.StatusInternalServerError, err)
return
}
transport.SendServerRes(w, json, http.StatusOK, nil)
}
func SearchEventsHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
marqoService := services.NewMarqoService()
handler := NewMarqoHandler(marqoService)
return func(w http.ResponseWriter, r *http.Request) {
handler.SearchEvents(w, r)
}
}
func CreateCheckoutSession(w http.ResponseWriter, r *http.Request) (err error) {
ctx := r.Context()
vars := mux.Vars(r)
eventId := vars[helpers.EVENT_ID_KEY]
eventSourceId := r.URL.Query().Get("event_source_id")
eventSourceType := r.URL.Query().Get("event_source_type")
if eventSourceId != "" && eventSourceType == helpers.ES_EVENT_SERIES {
eventId = eventSourceId
}
if eventId == "" {
transport.SendServerRes(w, []byte("Missing event ID"), http.StatusBadRequest, nil)
return
}
userInfo := helpers.UserInfo{}
if _, ok := ctx.Value("userInfo").(helpers.UserInfo); ok {
userInfo = ctx.Value("userInfo").(helpers.UserInfo)
}
userId := userInfo.Sub
if userId == "" {
transport.SendServerRes(w, []byte("Missing user ID"), http.StatusUnauthorized, nil)
return
}
// Create an empty struct
var createPurchase internal_types.PurchaseInsert
body, err := io.ReadAll(r.Body)
if err != nil {
transport.SendServerRes(w, []byte("Failed to read request body: "+err.Error()), http.StatusBadRequest, err)
return
}
// all purchases are pending and a client passing this status should be overridden
if createPurchase.Status == "" {
createPurchase.Status = "PENDING"
}
err = json.Unmarshal(body, &createPurchase)
if err != nil {
transport.SendServerRes(w, []byte("Invalid JSON payload: "+err.Error()), http.StatusUnprocessableEntity, err)
return
}
// Set the EventID and UserID after unmarshaling
createPurchase.EventID = eventId
createPurchase.UserID = userId
// Set CreatedAt and UpdatedAt to current time
now := time.Now()
createPurchase.CreatedAt = now.Unix()
createPurchase.UpdatedAt = now.Unix()
_createdAt := now.Unix()
createdAtString := fmt.Sprintf("%020d", _createdAt) // Pad with zeros to a fixed width of 20 digits
createPurchase.CreatedAtString = createdAtString
referenceId := "event-" + eventId + "-user-" + userId + "-time-" + createPurchase.CreatedAtString
// Create the composite key
compositeKey := fmt.Sprintf("%s_%s_%s", createPurchase.EventID, createPurchase.UserID, createPurchase.CreatedAtString)
// Add the composite key and createdAt to the purchase object
createPurchase.CompositeKey = compositeKey
// Create the purchase record immediately instead of deferring it
purchaseService := dynamodb_service.NewPurchaseService()
purchaseHandler := dynamodb_handlers.NewPurchaseHandler(purchaseService)
// when there are no purchased items, we treat this as an "RSVP" or "INTERESTED" status that shows
// in the users purchase / registration history. The empty PurchasedItems array signals that this
// is an event that does not have `RegistrationFields` or `PurchasableItems`
if len(createPurchase.PurchasedItems) == 0 {
db := transport.GetDB()
log.Printf("createPurchase: %+v", createPurchase)
_, err := purchaseHandler.PurchaseService.InsertPurchase(r.Context(), db, createPurchase)
if err != nil {
transport.SendServerRes(w, []byte("Failed to insert free purchase into database: "+err.Error()), http.StatusInternalServerError, err)
return err
}
// Create the response object
response := PurchaseResponse{
PurchaseInsert: createPurchase,
StripeCheckoutURL: "", // Empty URL for free items
}
// Marshal and send the response
purchaseJSON, err := json.Marshal(response)
if err != nil {
transport.SendServerRes(w, []byte("Failed to marshal purchase response: "+err.Error()), http.StatusInternalServerError, err)
return err
}
transport.SendServerRes(w, purchaseJSON, http.StatusOK, nil)
return nil
}
purchasableService := dynamodb_service.NewPurchasableService()
purchasableHandler := dynamodb_handlers.NewPurchasableHandler(purchasableService)
db := transport.GetDB()
purchasable, err := purchasableHandler.PurchasableService.GetPurchasablesByEventID(r.Context(), db, eventId)
if err != nil {
transport.SendServerRes(w, []byte("Failed to get purchasables for event id: "+eventId+" "+err.Error()), http.StatusInternalServerError, err)
return
}
// Validate inventory
var purchasableMap = map[string]internal_types.PurchasableItemInsert{}
if purchasableMap, err = validatePurchase(purchasable, createPurchase); err != nil {
transport.SendServerRes(w, []byte("Failed to validate inventory for event id: "+eventId+": "+err.Error()), http.StatusBadRequest, err)
return
}
// After validating inventory
inventoryUpdates := make([]internal_types.PurchasableInventoryUpdate, len(createPurchase.PurchasedItems))
for i, item := range createPurchase.PurchasedItems {
inventoryUpdates[i] = internal_types.PurchasableInventoryUpdate{
Name: item.Name,
Quantity: purchasableMap[item.Name].Inventory - item.Quantity,
PurchasableIndex: i,
}
}
// this boolean gets toggled in the scenario where stripe checkout fails to complete or other
// unrelated checkout failures AFTER the inventory is officially "held" + optimistically decremented
var needsRevert bool
err = purchasableHandler.PurchasableService.UpdatePurchasableInventory(r.Context(), db, eventId, inventoryUpdates, purchasableMap)
if err != nil {
transport.SendServerRes(w, []byte("Failed to update inventory: "+err.Error()), http.StatusInternalServerError, err)
return
}
defer func() {
if needsRevert {
// Revert inventory changes if there's an error
revertUpdates := make([]internal_types.PurchasableInventoryUpdate, len(inventoryUpdates))
for i, update := range inventoryUpdates {
revertUpdates[i] = internal_types.PurchasableInventoryUpdate{
Name: update.Name,
Quantity: purchasableMap[update.Name].Inventory, // Restore original inventory
PurchasableIndex: update.PurchasableIndex,
}
}
revertErr := purchasableHandler.PurchasableService.UpdatePurchasableInventory(r.Context(), db, eventId, revertUpdates, purchasableMap)
if revertErr != nil {
log.Printf("ERR: Failed to revert inventory changes: %v", revertErr)
}
}
}()
// Handle for free item purchases. These still need to track inventory and update the database, though we don't
// need to create a Stripe checkout session
if createPurchase.Total == 0 {
// Skip Stripe checkout for free items
createPurchase.Status = helpers.PurchaseStatus.Registered // Mark as registered immediately since it's free
db := transport.GetDB()
log.Printf("createPurchase: %+v", createPurchase)
_, err := purchaseHandler.PurchaseService.InsertPurchase(r.Context(), db, createPurchase)
if err != nil {
needsRevert = true
transport.SendServerRes(w, []byte("Failed to insert free purchase into database: "+err.Error()), http.StatusInternalServerError, err)
return err
}
// Create the response object
response := PurchaseResponse{
PurchaseInsert: createPurchase,
StripeCheckoutURL: "", // Empty URL for free items
}
// Marshal and send the response
purchaseJSON, err := json.Marshal(response)
if err != nil {
transport.SendServerRes(w, []byte("Failed to marshal purchase response: "+err.Error()), http.StatusInternalServerError, err)
return err
}
log.Printf("purchaseJSON: %s", string(purchaseJSON)) // Conve
transport.SendServerRes(w, purchaseJSON, http.StatusOK, nil)
return nil
}
// Continue with existing Stripe checkout logic for paid items
_, stripePrivKey := services.GetStripeKeyPair()
stripe.Key = stripePrivKey
lineItems := make([]*stripe.CheckoutSessionLineItemParams, len(createPurchase.PurchasedItems))
for i, item := range createPurchase.PurchasedItems {
lineItems[i] = &stripe.CheckoutSessionLineItemParams{
Quantity: stripe.Int64(int64(item.Quantity)),
PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
Currency: stripe.String("USD"),
UnitAmount: stripe.Int64(int64(item.Cost)), // Convert to cents
ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
Name: stripe.String(item.Name + " (" + createPurchase.EventName + ")"),
Metadata: map[string]string{
"EventId": eventId,
"ItemType": item.ItemType,
"DonationRatio": fmt.Sprint(item.DonationRatio),
},
},
},
}
}
params := &stripe.CheckoutSessionParams{
ClientReferenceID: stripe.String(referenceId), // Store purchase
SuccessURL: stripe.String(os.Getenv("APEX_URL") + "/admin/profile?new_purch_key=" + createPurchase.CompositeKey),
CancelURL: stripe.String(os.Getenv("APEX_URL") + "/event/" + eventId + "?checkout=cancel"),
LineItems: lineItems,
// NOTE: `mode` needs to be "subscription" if there's a subscription / recurring item,
// use `add_invoice_item` to then append the one-time payment items:
// https://stackoverflow.com/questions/64011643/how-to-combine-a-subscription-and-single-payments-in-one-charge-stripe-ap
Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
ExpiresAt: stripe.Int64(time.Now().Add(30 * time.Minute).Unix()),
}
stripeCheckoutResult, err := session.New(params)
if err != nil {
needsRevert = true
var errMsg = []byte("ERR: Failed to create Stripe checkout session: " + err.Error())
log.Println(string(errMsg))
transport.SendServerRes(w, errMsg, http.StatusInternalServerError, err)
return
}
createPurchase.StripeSessionId = stripeCheckoutResult.ID
// Now that the checks are in place, we defer the transaction creation in the database
// to respond to the client as quickly as possible
defer func() {
createPurchase.Status = helpers.PurchaseStatus.Pending
log.Printf("db payload `createPurchase`: %+v", createPurchase)
db := transport.GetDB()
_, err := purchaseHandler.PurchaseService.InsertPurchase(r.Context(), db, createPurchase)
if err != nil {
log.Printf("ERR: failed to insert purchase into purchases database for stripe session ID: %+v, err: %+v", stripeCheckoutResult.ID, err)
}
}()
log.Printf("\nstripe result: %+v", stripeCheckoutResult)
// Create the response object
response := PurchaseResponse{
PurchaseInsert: createPurchase,
StripeCheckoutURL: stripeCheckoutResult.URL,
}
// Marshal the response directly
purchaseJSON, err := json.Marshal(response)
if err != nil {
transport.SendServerRes(w, []byte("Failed to marshal purchase response: "+err.Error()), http.StatusInternalServerError, err)
return
}
// Send the response
transport.SendServerRes(w, purchaseJSON, http.StatusOK, nil)
return nil
// ✅ 1) check inventory in the `Purchasables` table where it is tracked
// ✅ 2) if not available, return "out of stock" error for that item
// ✅ 3) if available, decrement the `Purchasables` table items
// ❌ (not doing) 4) grab email from context (pull from token) and check for user in stripe customer id
// ❌ (not doing) 5) create stripe customer Id if not present already
// ✅ 6) Create a Stripe checkout session
// ✅ 7) submit the transaction as PENDING with stripe `sessionId` and `customerNumber` (add to `Purchases` table)
// ✅ 8) Handoff session to stripe
// ✅ 9) Listen to Stripe webhook to mark transaction SETTLED
// ❌ 10) If Stripe webhook misses, poll the stripe API for the Session ID status
// ❌ 11) Need an SNS queue to do polling, Lambda isn't guaranteed to be there
}
func CreateCheckoutSessionHandler(w http.ResponseWriter, r *http.Request) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
CreateCheckoutSession(w, r)
}
}
// Function to transform Purchase to PurchaseUpdate
func TransformPurchaseToUpdate(purchase internal_types.Purchase) internal_types.PurchaseUpdate {
return internal_types.PurchaseUpdate{
UserID: purchase.UserID,
EventID: purchase.EventID,
CompositeKey: purchase.CompositeKey,
EventName: purchase.EventName,
Status: purchase.Status,
UpdatedAt: time.Now().Unix(),
StripeTransactionId: purchase.StripeTransactionId,
StripeSessionId: purchase.StripeSessionId,
}
}
func (h *PurchasableWebhookHandler) HandleCheckoutWebhook(w http.ResponseWriter, r *http.Request) (err error) {
const MaxBodyBytes = int64(65536)
r.Body = http.MaxBytesReader(w, r.Body, MaxBodyBytes)
payload, err := io.ReadAll(r.Body)
if err != nil {
msg := fmt.Sprintf("ERR: Error reading request body: %v\n", err)
log.Println(msg)
transport.SendServerRes(w, []byte(msg), http.StatusInternalServerError, nil)
return
}
// If you are testing your webhook locally with the Stripe CLI you
// can find the endpoint's secret by running `stripe listen`
// Otherwise, find your endpoint's secret in your webhook settings
// in the Developer Dashboard
endpointSecret := services.GetStripeCheckoutWebhookSecret()
ctx := r.Context()
apiGwV2Req := ctx.Value(helpers.ApiGwV2ReqKey).(events.APIGatewayV2HTTPRequest)
stripeHeader := apiGwV2Req.Headers["stripe-signature"]
event, err := webhook.ConstructEvent(payload, stripeHeader,
endpointSecret)
if err != nil {
msg := fmt.Sprintf("ERR: Error verifying webhook signature: %v\n", err)
transport.SendServerRes(w, []byte(msg), http.StatusBadRequest, nil)
return err
}
switch event.Type {
case "checkout.session.completed":
var checkoutSession stripe.CheckoutSession
err := json.Unmarshal(event.Data.Raw, &checkoutSession)
if err != nil {
log.Printf("Error parsing webhook JSON: %v\n", err)
transport.SendServerRes(w, []byte("Error parsing webhook JSON"), http.StatusInternalServerError, nil)
return err
}
clientReferenceID := checkoutSession.ClientReferenceID
db := transport.GetDB()
re := regexp.MustCompile(`event-(.+?)-user-(.+?)-time-(.+)`)
matches := re.FindStringSubmatch(clientReferenceID)
eventID := ""
userID := ""
createdAt := ""
if len(matches) > 3 {
eventID = matches[1]
userID = matches[2]
createdAt = matches[3]
}
purchase, err := h.PurchaseService.GetPurchaseByPk(r.Context(), db, eventID, userID, createdAt)
if err != nil {
transport.SendServerRes(w, []byte("Failed to get purchases for event id: "+eventID+" by clientReferenceID: "+clientReferenceID+" | error: "+err.Error()), http.StatusInternalServerError, err)
return err
}
purchaseUpdate := TransformPurchaseToUpdate(*purchase)
purchaseUpdate.Status = helpers.PurchaseStatus.Settled
if checkoutSession.PaymentIntent != nil {
purchaseUpdate.StripeTransactionId = checkoutSession.PaymentIntent.ID
}
_, err = h.PurchaseService.UpdatePurchase(r.Context(), db, eventID, userID, createdAt, purchaseUpdate)
if err != nil {
transport.SendServerRes(w, []byte("Failed to update purchase status to SETTLED: "), http.StatusInternalServerError, err)
return err
}
msg := fmt.Sprintf("Checkout session marked as SETTLED for stripe clientReferenceID: %s", clientReferenceID)
log.Println(msg)
transport.SendServerRes(w, []byte(msg), http.StatusOK, err)
return err
case "checkout.session.expired":
var checkoutSession stripe.CheckoutSession
err := json.Unmarshal(event.Data.Raw, &checkoutSession)
if err != nil {
log.Printf("Error parsing webhook JSON: %v\n", err)
transport.SendServerRes(w, []byte("Error parsing webhook JSON"), http.StatusInternalServerError, nil)
return err
}
clientReferenceID := checkoutSession.ClientReferenceID
log.Printf("Checkout session expired: client reference ID: %s", clientReferenceID)
re := regexp.MustCompile(`event-(.+?)-user-(.+?)-time-(.+)`)
matches := re.FindStringSubmatch(clientReferenceID)