forked from isucon/isucon9-qualify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
2320 lines (1990 loc) · 59 KB
/
main.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 main
import (
crand "crypto/rand"
"database/sql"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-sql-driver/mysql"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
"golang.org/x/crypto/bcrypt"
)
const (
sessionName = "session_isucari"
DefaultPaymentServiceURL = "http://localhost:5555"
DefaultShipmentServiceURL = "http://localhost:7001"
ItemMinPrice = 100
ItemMaxPrice = 1000000
ItemPriceErrMsg = "商品価格は100イスコイン以上、1,000,000イスコイン以下にしてください"
ItemStatusOnSale = "on_sale"
ItemStatusTrading = "trading"
ItemStatusSoldOut = "sold_out"
ItemStatusStop = "stop"
ItemStatusCancel = "cancel"
PaymentServiceIsucariAPIKey = "a15400e46c83635eb181-946abb51ff26a868317c"
PaymentServiceIsucariShopID = "11"
TransactionEvidenceStatusWaitShipping = "wait_shipping"
TransactionEvidenceStatusWaitDone = "wait_done"
TransactionEvidenceStatusDone = "done"
ShippingsStatusInitial = "initial"
ShippingsStatusWaitPickup = "wait_pickup"
ShippingsStatusShipping = "shipping"
ShippingsStatusDone = "done"
BumpChargeSeconds = 3 * time.Second
ItemsPerPage = 48
TransactionsPerPage = 10
BcryptCost = 10
)
var (
templates *template.Template
dbx *sqlx.DB
store sessions.Store
)
type Config struct {
Name string `json:"name" db:"name"`
Val string `json:"val" db:"val"`
}
type User struct {
ID int64 `json:"id" db:"id"`
AccountName string `json:"account_name" db:"account_name"`
HashedPassword []byte `json:"-" db:"hashed_password"`
Address string `json:"address,omitempty" db:"address"`
NumSellItems int `json:"num_sell_items" db:"num_sell_items"`
LastBump time.Time `json:"-" db:"last_bump"`
CreatedAt time.Time `json:"-" db:"created_at"`
}
type UserSimple struct {
ID int64 `json:"id"`
AccountName string `json:"account_name"`
NumSellItems int `json:"num_sell_items"`
}
type Item struct {
ID int64 `json:"id" db:"id"`
SellerID int64 `json:"seller_id" db:"seller_id"`
BuyerID int64 `json:"buyer_id" db:"buyer_id"`
Status string `json:"status" db:"status"`
Name string `json:"name" db:"name"`
Price int `json:"price" db:"price"`
Description string `json:"description" db:"description"`
ImageName string `json:"image_name" db:"image_name"`
CategoryID int `json:"category_id" db:"category_id"`
CreatedAt time.Time `json:"-" db:"created_at"`
UpdatedAt time.Time `json:"-" db:"updated_at"`
}
type ItemSimple struct {
ID int64 `json:"id"`
SellerID int64 `json:"seller_id"`
Seller *UserSimple `json:"seller"`
Status string `json:"status"`
Name string `json:"name"`
Price int `json:"price"`
ImageURL string `json:"image_url"`
CategoryID int `json:"category_id"`
Category *Category `json:"category"`
CreatedAt int64 `json:"created_at"`
}
type ItemDetail struct {
ID int64 `json:"id"`
SellerID int64 `json:"seller_id"`
Seller *UserSimple `json:"seller"`
BuyerID int64 `json:"buyer_id,omitempty"`
Buyer *UserSimple `json:"buyer,omitempty"`
Status string `json:"status"`
Name string `json:"name"`
Price int `json:"price"`
Description string `json:"description"`
ImageURL string `json:"image_url"`
CategoryID int `json:"category_id"`
Category *Category `json:"category"`
TransactionEvidenceID int64 `json:"transaction_evidence_id,omitempty"`
TransactionEvidenceStatus string `json:"transaction_evidence_status,omitempty"`
ShippingStatus string `json:"shipping_status,omitempty"`
CreatedAt int64 `json:"created_at"`
}
type TransactionEvidence struct {
ID int64 `json:"id" db:"id"`
SellerID int64 `json:"seller_id" db:"seller_id"`
BuyerID int64 `json:"buyer_id" db:"buyer_id"`
Status string `json:"status" db:"status"`
ItemID int64 `json:"item_id" db:"item_id"`
ItemName string `json:"item_name" db:"item_name"`
ItemPrice int `json:"item_price" db:"item_price"`
ItemDescription string `json:"item_description" db:"item_description"`
ItemCategoryID int `json:"item_category_id" db:"item_category_id"`
ItemRootCategoryID int `json:"item_root_category_id" db:"item_root_category_id"`
CreatedAt time.Time `json:"-" db:"created_at"`
UpdatedAt time.Time `json:"-" db:"updated_at"`
}
type Shipping struct {
TransactionEvidenceID int64 `json:"transaction_evidence_id" db:"transaction_evidence_id"`
Status string `json:"status" db:"status"`
ItemName string `json:"item_name" db:"item_name"`
ItemID int64 `json:"item_id" db:"item_id"`
ReserveID string `json:"reserve_id" db:"reserve_id"`
ReserveTime int64 `json:"reserve_time" db:"reserve_time"`
ToAddress string `json:"to_address" db:"to_address"`
ToName string `json:"to_name" db:"to_name"`
FromAddress string `json:"from_address" db:"from_address"`
FromName string `json:"from_name" db:"from_name"`
ImgBinary []byte `json:"-" db:"img_binary"`
CreatedAt time.Time `json:"-" db:"created_at"`
UpdatedAt time.Time `json:"-" db:"updated_at"`
}
type Category struct {
ID int `json:"id" db:"id"`
ParentID int `json:"parent_id" db:"parent_id"`
CategoryName string `json:"category_name" db:"category_name"`
ParentCategoryName string `json:"parent_category_name,omitempty" db:"-"`
}
type reqInitialize struct {
PaymentServiceURL string `json:"payment_service_url"`
ShipmentServiceURL string `json:"shipment_service_url"`
}
type resInitialize struct {
Campaign int `json:"campaign"`
Language string `json:"language"`
}
type resNewItems struct {
RootCategoryID int `json:"root_category_id,omitempty"`
RootCategoryName string `json:"root_category_name,omitempty"`
HasNext bool `json:"has_next"`
Items []ItemSimple `json:"items"`
}
type resUserItems struct {
User *UserSimple `json:"user"`
HasNext bool `json:"has_next"`
Items []ItemSimple `json:"items"`
}
type resTransactions struct {
HasNext bool `json:"has_next"`
Items []ItemDetail `json:"items"`
}
type reqRegister struct {
AccountName string `json:"account_name"`
Address string `json:"address"`
Password string `json:"password"`
}
type reqLogin struct {
AccountName string `json:"account_name"`
Password string `json:"password"`
}
type reqItemEdit struct {
CSRFToken string `json:"csrf_token"`
ItemID int64 `json:"item_id"`
ItemPrice int `json:"item_price"`
}
type resItemEdit struct {
ItemID int64 `json:"item_id"`
ItemPrice int `json:"item_price"`
ItemCreatedAt int64 `json:"item_created_at"`
ItemUpdatedAt int64 `json:"item_updated_at"`
}
type reqBuy struct {
CSRFToken string `json:"csrf_token"`
ItemID int64 `json:"item_id"`
Token string `json:"token"`
}
type resBuy struct {
TransactionEvidenceID int64 `json:"transaction_evidence_id"`
}
type resSell struct {
ID int64 `json:"id"`
}
type reqPostShip struct {
CSRFToken string `json:"csrf_token"`
ItemID int64 `json:"item_id"`
}
type resPostShip struct {
Path string `json:"path"`
ReserveID string `json:"reserve_id"`
}
type reqPostShipDone struct {
CSRFToken string `json:"csrf_token"`
ItemID int64 `json:"item_id"`
}
type reqPostComplete struct {
CSRFToken string `json:"csrf_token"`
ItemID int64 `json:"item_id"`
}
type reqBump struct {
CSRFToken string `json:"csrf_token"`
ItemID int64 `json:"item_id"`
}
type resSetting struct {
CSRFToken string `json:"csrf_token"`
PaymentServiceURL string `json:"payment_service_url"`
User *User `json:"user,omitempty"`
Categories []Category `json:"categories"`
}
func init() {
store = sessions.NewCookieStore([]byte("abc"))
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
templates = template.Must(template.ParseFiles(
"../public/index.html",
))
}
func main() {
host := os.Getenv("MYSQL_HOST")
if host == "" {
host = "127.0.0.1"
}
port := os.Getenv("MYSQL_PORT")
if port == "" {
port = "3306"
}
_, err := strconv.Atoi(port)
if err != nil {
log.Fatalf("failed to read DB port number from an environment variable MYSQL_PORT.\nError: %s", err.Error())
}
user := os.Getenv("MYSQL_USER")
if user == "" {
user = "isucari"
}
dbname := os.Getenv("MYSQL_DBNAME")
if dbname == "" {
dbname = "isucari"
}
password := os.Getenv("MYSQL_PASS")
if password == "" {
password = "isucari"
}
conf := mysql.NewConfig()
conf.Net = "tcp"
conf.Addr = net.JoinHostPort(host, port)
conf.User = user
conf.Passwd = password
conf.DBName = dbname
conf.ParseTime = true
dbx, err = sqlx.Open("mysql", conf.FormatDSN())
if err != nil {
log.Fatalf("failed to connect to DB: %s.", err.Error())
}
defer dbx.Close()
r := chi.NewRouter()
// API
r.Post("/initialize", postInitialize)
r.Get("/new_items.json", getNewItems)
r.Get("/new_items/{root_category_id}.json", getNewCategoryItems)
r.Get("/users/transactions.json", getTransactions)
r.Get("/users/{user_id}.json", getUserItems)
r.Get("/items/{item_id}.json", getItem)
r.Post("/items/edit", postItemEdit)
r.Post("/buy", postBuy)
r.Post("/sell", postSell)
r.Post("/ship", postShip)
r.Post("/ship_done", postShipDone)
r.Post("/complete", postComplete)
r.Get("/transactions/{transaction_evidence_id}.png", getQRCode)
r.Post("/bump", postBump)
r.Get("/settings", getSettings)
r.Post("/login", postLogin)
r.Post("/register", postRegister)
r.Get("/reports.json", getReports)
// Frontend
r.Get("/", getIndex)
r.Get("/login", getIndex)
r.Get("/register", getIndex)
r.Get("/timeline", getIndex)
r.Get("/categories/{category_id}/items", getIndex)
r.Get("/sell", getIndex)
r.Get("/items/{item_id}", getIndex)
r.Get("/items/{item_id}/edit", getIndex)
r.Get("/items/{item_id}/buy", getIndex)
r.Get("/buy/complete", getIndex)
r.Get("/transactions/{transaction_id}", getIndex)
r.Get("/users/{user_id}", getIndex)
r.Get("/users/setting", getIndex)
// Assets
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.Dir("../public")).ServeHTTP(w, r)
})
log.Fatal(http.ListenAndServe(":8000", r))
}
func getSession(r *http.Request) *sessions.Session {
session, _ := store.Get(r, sessionName)
session.Options.Secure = false
return session
}
func getCSRFToken(r *http.Request) string {
session := getSession(r)
csrfToken, ok := session.Values["csrf_token"]
if !ok {
return ""
}
return csrfToken.(string)
}
func getUser(r *http.Request) (user User, errCode int, errMsg string) {
session := getSession(r)
userID, ok := session.Values["user_id"]
if !ok {
return user, http.StatusNotFound, "no session"
}
err := dbx.Get(&user, "SELECT * FROM `users` WHERE `id` = ?", userID)
if err == sql.ErrNoRows {
return user, http.StatusNotFound, "user not found"
}
if err != nil {
log.Print(err)
return user, http.StatusInternalServerError, "db error"
}
return user, http.StatusOK, ""
}
func getUserSimpleByID(q sqlx.Queryer, userID int64) (userSimple UserSimple, err error) {
user := User{}
err = sqlx.Get(q, &user, "SELECT * FROM `users` WHERE `id` = ?", userID)
if err != nil {
return userSimple, err
}
userSimple.ID = user.ID
userSimple.AccountName = user.AccountName
userSimple.NumSellItems = user.NumSellItems
return userSimple, err
}
func getCategoryByID(q sqlx.Queryer, categoryID int) (category Category, err error) {
err = sqlx.Get(q, &category, "SELECT * FROM `categories` WHERE `id` = ?", categoryID)
if category.ParentID != 0 {
parentCategory, err := getCategoryByID(q, category.ParentID)
if err != nil {
return category, err
}
category.ParentCategoryName = parentCategory.CategoryName
}
return category, err
}
func getConfigByName(name string) (string, error) {
config := Config{}
err := dbx.Get(&config, "SELECT * FROM `configs` WHERE `name` = ?", name)
if err == sql.ErrNoRows {
return "", nil
}
if err != nil {
log.Print(err)
return "", err
}
return config.Val, err
}
func getPaymentServiceURL() string {
val, _ := getConfigByName("payment_service_url")
if val == "" {
return DefaultPaymentServiceURL
}
return val
}
func getShipmentServiceURL() string {
val, _ := getConfigByName("shipment_service_url")
if val == "" {
return DefaultShipmentServiceURL
}
return val
}
func getIndex(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "index.html", struct{}{})
}
func postInitialize(w http.ResponseWriter, r *http.Request) {
ri := reqInitialize{}
err := json.NewDecoder(r.Body).Decode(&ri)
if err != nil {
outputErrorMsg(w, http.StatusBadRequest, "json decode error")
return
}
cmd := exec.Command("../init.sh")
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stderr
cmd.Run()
if err != nil {
outputErrorMsg(w, http.StatusInternalServerError, "exec init.sh error")
return
}
_, err = dbx.Exec(
"INSERT INTO `configs` (`name`, `val`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `val` = VALUES(`val`)",
"payment_service_url",
ri.PaymentServiceURL,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
_, err = dbx.Exec(
"INSERT INTO `configs` (`name`, `val`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `val` = VALUES(`val`)",
"shipment_service_url",
ri.ShipmentServiceURL,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
res := resInitialize{
// キャンペーン実施時には還元率の設定を返す。詳しくはマニュアルを参照のこと。
Campaign: 0,
// 実装言語を返す
Language: "Go",
}
w.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(w).Encode(res)
}
func getNewItems(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
itemIDStr := query.Get("item_id")
var itemID int64
var err error
if itemIDStr != "" {
itemID, err = strconv.ParseInt(itemIDStr, 10, 64)
if err != nil || itemID <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "item_id param error")
return
}
}
createdAtStr := query.Get("created_at")
var createdAt int64
if createdAtStr != "" {
createdAt, err = strconv.ParseInt(createdAtStr, 10, 64)
if err != nil || createdAt <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "created_at param error")
return
}
}
items := []Item{}
if itemID > 0 && createdAt > 0 {
// paging
err := dbx.Select(&items,
"SELECT * FROM `items` WHERE `status` IN (?,?) AND (`created_at` < ? OR (`created_at` <= ? AND `id` < ?)) ORDER BY `created_at` DESC, `id` DESC LIMIT ?",
ItemStatusOnSale,
ItemStatusSoldOut,
time.Unix(createdAt, 0),
time.Unix(createdAt, 0),
itemID,
ItemsPerPage+1,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
} else {
// 1st page
err := dbx.Select(&items,
"SELECT * FROM `items` WHERE `status` IN (?,?) ORDER BY `created_at` DESC, `id` DESC LIMIT ?",
ItemStatusOnSale,
ItemStatusSoldOut,
ItemsPerPage+1,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
}
itemSimples := []ItemSimple{}
for _, item := range items {
seller, err := getUserSimpleByID(dbx, item.SellerID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "seller not found")
return
}
category, err := getCategoryByID(dbx, item.CategoryID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "category not found")
return
}
itemSimples = append(itemSimples, ItemSimple{
ID: item.ID,
SellerID: item.SellerID,
Seller: &seller,
Status: item.Status,
Name: item.Name,
Price: item.Price,
ImageURL: getImageURL(item.ImageName),
CategoryID: item.CategoryID,
Category: &category,
CreatedAt: item.CreatedAt.Unix(),
})
}
hasNext := false
if len(itemSimples) > ItemsPerPage {
hasNext = true
itemSimples = itemSimples[0:ItemsPerPage]
}
rni := resNewItems{
Items: itemSimples,
HasNext: hasNext,
}
w.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(w).Encode(rni)
}
func getNewCategoryItems(w http.ResponseWriter, r *http.Request) {
rootCategoryIDStr := r.PathValue("root_category_id")
rootCategoryID, err := strconv.Atoi(rootCategoryIDStr)
if err != nil || rootCategoryID <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "incorrect category id")
return
}
rootCategory, err := getCategoryByID(dbx, rootCategoryID)
if err != nil || rootCategory.ParentID != 0 {
outputErrorMsg(w, http.StatusNotFound, "category not found")
return
}
var categoryIDs []int
err = dbx.Select(&categoryIDs, "SELECT id FROM `categories` WHERE parent_id=?", rootCategory.ID)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
query := r.URL.Query()
itemIDStr := query.Get("item_id")
var itemID int64
if itemIDStr != "" {
itemID, err = strconv.ParseInt(itemIDStr, 10, 64)
if err != nil || itemID <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "item_id param error")
return
}
}
createdAtStr := query.Get("created_at")
var createdAt int64
if createdAtStr != "" {
createdAt, err = strconv.ParseInt(createdAtStr, 10, 64)
if err != nil || createdAt <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "created_at param error")
return
}
}
var inQuery string
var inArgs []interface{}
if itemID > 0 && createdAt > 0 {
// paging
inQuery, inArgs, err = sqlx.In(
"SELECT * FROM `items` WHERE `status` IN (?,?) AND category_id IN (?) AND (`created_at` < ? OR (`created_at` <= ? AND `id` < ?)) ORDER BY `created_at` DESC, `id` DESC LIMIT ?",
ItemStatusOnSale,
ItemStatusSoldOut,
categoryIDs,
time.Unix(createdAt, 0),
time.Unix(createdAt, 0),
itemID,
ItemsPerPage+1,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
} else {
// 1st page
inQuery, inArgs, err = sqlx.In(
"SELECT * FROM `items` WHERE `status` IN (?,?) AND category_id IN (?) ORDER BY created_at DESC, id DESC LIMIT ?",
ItemStatusOnSale,
ItemStatusSoldOut,
categoryIDs,
ItemsPerPage+1,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
}
items := []Item{}
err = dbx.Select(&items, inQuery, inArgs...)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
itemSimples := []ItemSimple{}
for _, item := range items {
seller, err := getUserSimpleByID(dbx, item.SellerID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "seller not found")
return
}
category, err := getCategoryByID(dbx, item.CategoryID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "category not found")
return
}
itemSimples = append(itemSimples, ItemSimple{
ID: item.ID,
SellerID: item.SellerID,
Seller: &seller,
Status: item.Status,
Name: item.Name,
Price: item.Price,
ImageURL: getImageURL(item.ImageName),
CategoryID: item.CategoryID,
Category: &category,
CreatedAt: item.CreatedAt.Unix(),
})
}
hasNext := false
if len(itemSimples) > ItemsPerPage {
hasNext = true
itemSimples = itemSimples[0:ItemsPerPage]
}
rni := resNewItems{
RootCategoryID: rootCategory.ID,
RootCategoryName: rootCategory.CategoryName,
Items: itemSimples,
HasNext: hasNext,
}
w.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(w).Encode(rni)
}
func getUserItems(w http.ResponseWriter, r *http.Request) {
userIDStr := r.PathValue("user_id")
userID, err := strconv.ParseInt(userIDStr, 10, 64)
if err != nil || userID <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "incorrect user id")
return
}
userSimple, err := getUserSimpleByID(dbx, userID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "user not found")
return
}
query := r.URL.Query()
itemIDStr := query.Get("item_id")
var itemID int64
if itemIDStr != "" {
itemID, err = strconv.ParseInt(itemIDStr, 10, 64)
if err != nil || itemID <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "item_id param error")
return
}
}
createdAtStr := query.Get("created_at")
var createdAt int64
if createdAtStr != "" {
createdAt, err = strconv.ParseInt(createdAtStr, 10, 64)
if err != nil || createdAt <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "created_at param error")
return
}
}
items := []Item{}
if itemID > 0 && createdAt > 0 {
// paging
err := dbx.Select(&items,
"SELECT * FROM `items` WHERE `seller_id` = ? AND `status` IN (?,?,?) AND (`created_at` < ? OR (`created_at` <= ? AND `id` < ?)) ORDER BY `created_at` DESC, `id` DESC LIMIT ?",
userSimple.ID,
ItemStatusOnSale,
ItemStatusTrading,
ItemStatusSoldOut,
time.Unix(createdAt, 0),
time.Unix(createdAt, 0),
itemID,
ItemsPerPage+1,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
} else {
// 1st page
err := dbx.Select(&items,
"SELECT * FROM `items` WHERE `seller_id` = ? AND `status` IN (?,?,?) ORDER BY `created_at` DESC, `id` DESC LIMIT ?",
userSimple.ID,
ItemStatusOnSale,
ItemStatusTrading,
ItemStatusSoldOut,
ItemsPerPage+1,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
return
}
}
itemSimples := []ItemSimple{}
for _, item := range items {
category, err := getCategoryByID(dbx, item.CategoryID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "category not found")
return
}
itemSimples = append(itemSimples, ItemSimple{
ID: item.ID,
SellerID: item.SellerID,
Seller: &userSimple,
Status: item.Status,
Name: item.Name,
Price: item.Price,
ImageURL: getImageURL(item.ImageName),
CategoryID: item.CategoryID,
Category: &category,
CreatedAt: item.CreatedAt.Unix(),
})
}
hasNext := false
if len(itemSimples) > ItemsPerPage {
hasNext = true
itemSimples = itemSimples[0:ItemsPerPage]
}
rui := resUserItems{
User: &userSimple,
Items: itemSimples,
HasNext: hasNext,
}
w.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(w).Encode(rui)
}
func getTransactions(w http.ResponseWriter, r *http.Request) {
user, errCode, errMsg := getUser(r)
if errMsg != "" {
outputErrorMsg(w, errCode, errMsg)
return
}
query := r.URL.Query()
itemIDStr := query.Get("item_id")
var err error
var itemID int64
if itemIDStr != "" {
itemID, err = strconv.ParseInt(itemIDStr, 10, 64)
if err != nil || itemID <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "item_id param error")
return
}
}
createdAtStr := query.Get("created_at")
var createdAt int64
if createdAtStr != "" {
createdAt, err = strconv.ParseInt(createdAtStr, 10, 64)
if err != nil || createdAt <= 0 {
outputErrorMsg(w, http.StatusBadRequest, "created_at param error")
return
}
}
tx := dbx.MustBegin()
items := []Item{}
if itemID > 0 && createdAt > 0 {
// paging
err := tx.Select(&items,
"SELECT * FROM `items` WHERE (`seller_id` = ? OR `buyer_id` = ?) AND `status` IN (?,?,?,?,?) AND (`created_at` < ? OR (`created_at` <= ? AND `id` < ?)) ORDER BY `created_at` DESC, `id` DESC LIMIT ?",
user.ID,
user.ID,
ItemStatusOnSale,
ItemStatusTrading,
ItemStatusSoldOut,
ItemStatusCancel,
ItemStatusStop,
time.Unix(createdAt, 0),
time.Unix(createdAt, 0),
itemID,
TransactionsPerPage+1,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
tx.Rollback()
return
}
} else {
// 1st page
err := tx.Select(&items,
"SELECT * FROM `items` WHERE (`seller_id` = ? OR `buyer_id` = ?) AND `status` IN (?,?,?,?,?) ORDER BY `created_at` DESC, `id` DESC LIMIT ?",
user.ID,
user.ID,
ItemStatusOnSale,
ItemStatusTrading,
ItemStatusSoldOut,
ItemStatusCancel,
ItemStatusStop,
TransactionsPerPage+1,
)
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
tx.Rollback()
return
}
}
itemDetails := []ItemDetail{}
for _, item := range items {
seller, err := getUserSimpleByID(tx, item.SellerID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "seller not found")
tx.Rollback()
return
}
category, err := getCategoryByID(tx, item.CategoryID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "category not found")
tx.Rollback()
return
}
itemDetail := ItemDetail{
ID: item.ID,
SellerID: item.SellerID,
Seller: &seller,
// BuyerID
// Buyer
Status: item.Status,
Name: item.Name,
Price: item.Price,
Description: item.Description,
ImageURL: getImageURL(item.ImageName),
CategoryID: item.CategoryID,
// TransactionEvidenceID
// TransactionEvidenceStatus
// ShippingStatus
Category: &category,
CreatedAt: item.CreatedAt.Unix(),
}
if item.BuyerID != 0 {
buyer, err := getUserSimpleByID(tx, item.BuyerID)
if err != nil {
outputErrorMsg(w, http.StatusNotFound, "buyer not found")
tx.Rollback()
return
}
itemDetail.BuyerID = item.BuyerID
itemDetail.Buyer = &buyer
}
transactionEvidence := TransactionEvidence{}
err = tx.Get(&transactionEvidence, "SELECT * FROM `transaction_evidences` WHERE `item_id` = ?", item.ID)
if err != nil && err != sql.ErrNoRows {
// It's able to ignore ErrNoRows
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
tx.Rollback()
return
}
if transactionEvidence.ID > 0 {
shipping := Shipping{}
err = tx.Get(&shipping, "SELECT * FROM `shippings` WHERE `transaction_evidence_id` = ?", transactionEvidence.ID)
if err == sql.ErrNoRows {
outputErrorMsg(w, http.StatusNotFound, "shipping not found")
tx.Rollback()
return
}
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "db error")
tx.Rollback()
return
}
ssr, err := APIShipmentStatus(getShipmentServiceURL(), &APIShipmentStatusReq{
ReserveID: shipping.ReserveID,
})
if err != nil {
log.Print(err)
outputErrorMsg(w, http.StatusInternalServerError, "failed to request to shipment service")
tx.Rollback()
return
}
itemDetail.TransactionEvidenceID = transactionEvidence.ID
itemDetail.TransactionEvidenceStatus = transactionEvidence.Status
itemDetail.ShippingStatus = ssr.Status
}