This repository has been archived by the owner on Apr 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
upload.go
1472 lines (1263 loc) · 38.5 KB
/
upload.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 (
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"path"
"sort"
"strconv"
"strings"
"time"
"unicode"
"github.com/PuerkitoBio/goquery"
"github.com/extrame/xls"
cleanhttp "github.com/hashicorp/go-cleanhttp"
"github.com/xuri/excelize/v2"
"golang.org/x/exp/slices"
"gopkg.in/Iwark/spreadsheet.v2"
"github.com/mtgban/go-mtgban/mtgmatcher"
)
const (
MinLowValueSpread = 60.0
VisualPercSpread = 100.0
MinLowValueAbs = 1.0
MaxHighValueSpread = 0.0
MaxHighValueAbs = 0.0
MaxUploadEntries = 350
MaxUploadProEntries = 1000
MaxUploadTotalEntries = 10000
MaxUploadFileSize = 5 << 20
DefaultPercentageMargin = 0.1
TooManyEntriesMessage = "Note: you reached the maximum number of entries supported by this tool"
)
// Keep TCG_DIRECT_LOW last so that it can be ignored ranges and used as backup only
var UploadIndexKeys = []string{TCG_LOW, TCG_MARKET, TCG_DIRECT, TCG_DIRECT_LOW}
var ErrUploadDecklist = errors.New("decklist")
var ErrReloadFirstRow = errors.New("firstrow")
// Data coming from the user upload
type UploadEntry struct {
// A reference to the parsed card
Card mtgmatcher.Card
// The UUID of the card
CardId string
// Error when mtgmatcher.Match() fails
MismatchError error
// Error when multiple results are found
MismatchAlias bool
// Price as found in the source data
OriginalPrice float64
// Condition as found in the source data
OriginalCondition string
// Whether source data had Quantity information
HasQuantity bool
// Quantity as found in the source data
Quantity int
// Price as found in the source data
Notes string
}
// Subset of data used in the optimizer
type OptimizedUploadEntry struct {
// The UUID of the card
CardId string
// Condition as found in the source data
Condition string
// Price of the card provided in the source data (or TCG_LOW)
Price float64
// Percentage of the store price vs uploaded price
Spread float64
// Price of the card provided by the Store (condition accounted)
BestPrice float64
// Quantity as found in the source data
Quantity int
// Price used to display a visual indicator
VisualPrice float64
}
func Upload(w http.ResponseWriter, r *http.Request) {
sig := getSignatureFromCookies(r)
pageVars := genPageNav("Upload", sig)
// Maximum form size
r.ParseMultipartForm(MaxUploadFileSize)
// See if we need to download the ck csv only
hashTag := r.FormValue("tag")
switch hashTag {
case "CK", "SCG":
hashes := r.Form[hashTag+"hashes"]
hashesQtys := r.Form[hashTag+"hashesQtys"]
if hashes != nil {
w.Header().Set("Content-Type", "text/csv")
w.Header().Set("Content-Disposition", "attachment; filename=\"mtgban_"+strings.ToLower(hashTag)+".csv\"")
csvWriter := csv.NewWriter(w)
var err error
switch hashTag {
case "CK":
err = UUID2CKCSV(csvWriter, hashes, hashesQtys)
case "SCG":
err = UUID2SCGCSV(csvWriter, hashes, hashesQtys)
}
if err != nil {
w.Header().Del("Content-Type")
UserNotify("upload", err.Error())
pageVars.InfoMessage = "Unable to download CSV right now"
render(w, "upload.html", pageVars)
}
return
}
pageVars.ErrorMessage = "Invalid tag option: " + hashTag
render(w, "upload.html", pageVars)
return
}
// Check cookies to set preferences
blMode := readSetFlag(w, r, "mode", "uploadMode")
// Disable buylist if not permitted
canBuylist, _ := strconv.ParseBool(GetParamFromSig(sig, "UploadBuylistEnabled"))
if DevMode && !SigCheck {
canBuylist = true
}
if !canBuylist {
blMode = false
}
// Disable changing stores if not permitted
canChangeStores, _ := strconv.ParseBool(GetParamFromSig(sig, "UploadChangeStoresEnabled"))
if DevMode && !SigCheck {
canChangeStores = true
}
// Enable optimizer customization
var skipLowValue, skipLowValueAbs, skipHighValue, skipHighValueAbs bool
var skipMargin, skipConds, skipPrices bool
var visualIndicator bool
if blMode {
skipLowValue = r.FormValue("lowval") != ""
skipLowValueAbs = r.FormValue("lowvalabs") != ""
skipHighValue = r.FormValue("highval") != ""
skipHighValueAbs = r.FormValue("highvalabs") != ""
skipMargin = r.FormValue("minmargin") != ""
skipConds = r.FormValue("nocond") != ""
skipPrices = r.FormValue("noprice") != ""
visualIndicator = r.FormValue("customperc") != ""
}
sorting := r.FormValue("sorting")
percSpread := MinLowValueSpread
customSpread, err := strconv.ParseFloat(r.FormValue("percspread"), 64)
if err == nil && customSpread > 0 {
percSpread = customSpread
}
percSpreadMax := MaxHighValueSpread
customSpreadMax, err := strconv.ParseFloat(r.FormValue("percspreadmax"), 64)
if err == nil && customSpreadMax > percSpread {
percSpreadMax = customSpreadMax
}
minLowVal := MinLowValueAbs
customMin, err := strconv.ParseFloat(r.FormValue("minval"), 64)
if err == nil && customMin > 0 {
minLowVal = customMin
}
maxHighVal := MaxHighValueAbs
customMax, err := strconv.ParseFloat(r.FormValue("maxval"), 64)
if err == nil && customMax > minLowVal {
maxHighVal = customMax
}
percMargin := 1.0
if !skipMargin {
percMargin = 1 - DefaultPercentageMargin
customMargin, err := strconv.ParseFloat(r.FormValue("margin"), 64)
if err == nil && customMargin >= 0 {
percMargin = 1 - customMargin/100.0
}
}
visualPerc := VisualPercSpread
customVisual, err := strconv.ParseFloat(r.FormValue("custompercmax"), 64)
if err == nil && customMin > 0 {
visualPerc = customVisual
}
pageVars.CanFilterByPrice = visualIndicator
// Set flags needed to show elements on the page ui
pageVars.IsBuylist = blMode
pageVars.CanBuylist = canBuylist
pageVars.CanChangeStores = canChangeStores
blocklistRetail, blocklistBuylist := getDefaultBlocklists(sig)
var enabledStores []string
var allSellers []string
var allVendors []string
// Load all possible sellers, and vendors according to user permissions
for _, seller := range Sellers {
if seller != nil && !slices.Contains(blocklistRetail, seller.Info().Shorthand) && !seller.Info().SealedMode && !seller.Info().MetadataOnly {
allSellers = append(allSellers, seller.Info().Shorthand)
}
}
for _, vendor := range Vendors {
if vendor != nil && !slices.Contains(blocklistBuylist, vendor.Info().Shorthand) && !vendor.Info().SealedMode {
allVendors = append(allVendors, vendor.Info().Shorthand)
}
}
// Set the store names for the <select> box
pageVars.SellerKeys = allSellers
pageVars.VendorKeys = allVendors
// Load the preferred list of enabled stores for the <select> box
// The first check is for when the cookie is not yet set
// Force stores if not allowed to change them
enabledSellers := readCookie(r, "enabledSellers")
if len(enabledSellers) == 0 || !canChangeStores {
pageVars.EnabledSellers = Config.AffiliatesList
} else {
pageVars.EnabledSellers = strings.Split(enabledSellers, "|")
}
enabledVendors := readCookie(r, "enabledVendors")
if len(enabledVendors) == 0 {
pageVars.EnabledVendors = allVendors
} else {
pageVars.EnabledVendors = strings.Split(enabledVendors, "|")
}
cachedGdocURL := readCookie(r, "gdocURL")
pageVars.RemoteLinkURL = cachedGdocURL
// Filter out any unselected store from the full list
stores := r.Form["stores"]
if blMode {
for _, store := range stores {
if slices.Contains(allVendors, store) {
enabledStores = append(enabledStores, store)
}
}
} else {
// Override in case not allowed to change list
if !canChangeStores {
stores = Config.AffiliatesList
}
for _, store := range stores {
if slices.Contains(allSellers, store) {
enabledStores = append(enabledStores, store)
}
}
}
// Private call from newspaper
hashes := r.Form["hashes"]
if len(hashes) != 0 && len(stores) == 0 {
if blMode {
enabledStores = pageVars.EnabledVendors
} else {
enabledStores = pageVars.EnabledSellers
}
}
// Load spreadsheet cloud url if present
gdocURL := r.FormValue("gdocURL")
// Load from the freeform text area
textArea := r.FormValue("textArea")
// FormFile returns the first file for the given key `cardListFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
file, handler, err := r.FormFile("cardListFile")
if err != nil && gdocURL == "" && textArea == "" && len(hashes) == 0 {
render(w, "upload.html", pageVars)
return
} else if err == nil {
defer file.Close()
}
if len(hashes) != 0 {
log.Printf("Loading from POST %d cards", len(hashes))
pageVars.CardHashes = hashes
} else if gdocURL != "" {
log.Printf("Loading spreadsheet: %+v", gdocURL)
} else if textArea != "" {
log.Printf("Loading freeform text area (%d bytes)", len(textArea))
} else {
log.Printf("Uploaded File: %+v", handler.Filename)
log.Printf("File Size: %+v bytes", handler.Size)
log.Printf("MIME Header: %+v", handler.Header)
}
log.Printf("Buylist mode: %+v", blMode)
log.Printf("Enabled stores: %+v", enabledStores)
// Reset the cookie for this preference
if cachedGdocURL != gdocURL {
setCookie(w, r, "gdocURL", gdocURL)
pageVars.RemoteLinkURL = gdocURL
}
// Save user preferred stores in cookies and make sure the page is updated with those
if blMode {
setCookie(w, r, "enabledVendors", strings.Join(enabledStores, "|"))
pageVars.EnabledVendors = enabledStores
} else {
setCookie(w, r, "enabledSellers", strings.Join(enabledStores, "|"))
pageVars.EnabledSellers = enabledStores
}
estimate, _ := strconv.ParseBool(r.FormValue("estimate"))
start := time.Now()
// Set upload limit
maxRows := MaxUploadEntries
// Increase upload limit if allowed
optimizerOpt, _ := strconv.ParseBool(GetParamFromSig(sig, "UploadOptimizer"))
increaseMaxRows := optimizerOpt || (DevMode && !SigCheck)
if increaseMaxRows {
maxRows = MaxUploadProEntries
}
// Allow a larger upload limit if set, if dev, or if it's an external call
limitOpt, _ := strconv.ParseBool(GetParamFromSig(sig, "UploadNoLimit"))
uploadNoLimit := limitOpt || (DevMode && !SigCheck) || estimate
if uploadNoLimit {
maxRows = MaxUploadTotalEntries
}
// Load data
var uploadedData []UploadEntry
if len(hashes) != 0 {
uploadedData, err = loadHashes(hashes)
} else if textArea != "" {
uploadedData, err = loadCsv(strings.NewReader(textArea), ',', maxRows)
} else if handler != nil {
if strings.HasSuffix(handler.Filename, ".xls") {
uploadedData, err = loadOldXls(file, maxRows)
} else if strings.HasSuffix(handler.Filename, ".xlsx") {
uploadedData, err = loadXlsx(file, maxRows)
} else {
uploadedData, err = loadCsv(file, ',', maxRows)
}
} else if gdocURL != "" {
if strings.HasPrefix(gdocURL, "https://store.tcgplayer.com/collection/view/") {
uploadedData, err = loadCollection(gdocURL, maxRows)
} else if strings.HasPrefix(gdocURL, "https://docs.google.com/spreadsheets/") {
uploadedData, err = loadSpreadsheet(gdocURL, maxRows)
} else {
err = errors.New("unsupported URL")
}
}
if err != nil {
pageVars.WarningMessage = err.Error()
render(w, "upload.html", pageVars)
return
}
uploadedData = mergeIdenticalEntries(uploadedData)
// Allow estimating on a separate page
if estimate {
var items []CCItem
for i := range uploadedData {
if uploadedData[i].CardId == "" {
continue
}
co, err := mtgmatcher.GetUUID(uploadedData[i].CardId)
if err != nil {
continue
}
scryfallId, found := co.Identifiers["scryfallId"]
if !found {
continue
}
var cond string
if uploadedData[i].OriginalCondition != "" {
cond = map[string]string{
"NM": "nm",
"SP": "lp",
"MP": "mp",
"HP": "hp",
"PO": "dmg",
}[uploadedData[i].OriginalCondition]
}
var qty int
if uploadedData[i].HasQuantity {
qty = uploadedData[i].Quantity
}
items = append(items, CCItem{
ScryfallID: scryfallId,
Condition: cond,
Quantity: qty,
IsFoil: co.Foil,
IsEtched: co.Etched,
})
}
link, err := sendCardConduitEstimate(items)
if err != nil {
UserNotify("upload", err.Error())
pageVars.InfoMessage = "Unable to process your list to CardConduit right now"
render(w, "upload.html", pageVars)
return
}
http.Redirect(w, r, link, http.StatusFound)
return
}
var shouldCheckForConditions bool
// Extract card Ids
cardIds := make([]string, 0, len(uploadedData))
for i := range uploadedData {
// Filter out empty ids
if uploadedData[i].CardId == "" {
continue
}
cardIds = append(cardIds, uploadedData[i].CardId)
// Check if conditions should be retrieved
if uploadedData[i].OriginalCondition != "" && !skipConds {
shouldCheckForConditions = true
}
}
// Check not too many entries got uploaded
if len(cardIds) >= maxRows {
pageVars.InfoMessage = TooManyEntriesMessage
}
// Search
var results map[string]map[string]*BanPrice
if blMode {
results = getVendorPrices("", enabledStores, "", cardIds, "", false, shouldCheckForConditions)
} else {
results = getSellerPrices("", enabledStores, "", cardIds, "", false, shouldCheckForConditions)
}
// Allow downloading data as CSV
download, _ := strconv.ParseBool(r.FormValue("download"))
if download && canBuylist {
w.Header().Set("Content-Type", "text/csv")
w.Header().Set("Content-Disposition", "attachment; filename=\"mtgban_prices.csv\"")
csvWriter := csv.NewWriter(w)
err = SimplePrice2CSV(csvWriter, results, uploadedData)
if err != nil {
w.Header().Del("Content-Type")
UserNotify("upload", err.Error())
pageVars.InfoMessage = "Unable to download CSV right now"
render(w, "upload.html", pageVars)
}
return
}
indexResults := getSellerPrices("", UploadIndexKeys, "", cardIds, "", false, shouldCheckForConditions)
pageVars.IndexKeys = UploadIndexKeys[:len(UploadIndexKeys)-1]
// Orders implies priority of argument search
pageVars.Metadata = map[string]GenericCard{}
if len(hashes) != 0 {
pageVars.SearchQuery = "hashes"
} else if textArea != "" {
pageVars.SearchQuery = "pasted text"
} else if gdocURL != "" {
pageVars.SearchQuery = gdocURL
} else {
pageVars.SearchQuery = handler.Filename
}
pageVars.ScraperKeys = enabledStores
pageVars.TotalEntries = map[string]float64{}
skipResults := r.FormValue("noresults") != ""
if !(blMode && skipResults) {
pageVars.UploadEntries = uploadedData
}
// Load up image links
for _, data := range uploadedData {
if data.MismatchError != nil {
continue
}
_, found := pageVars.Metadata[data.CardId]
if !found {
pageVars.Metadata[data.CardId] = uuid2card(data.CardId, true, false)
}
if pageVars.Metadata[data.CardId].Reserved {
pageVars.HasReserved = true
}
if pageVars.Metadata[data.CardId].Stocks {
pageVars.HasStocks = true
}
if pageVars.Metadata[data.CardId].SypList {
pageVars.HasSypList = true
}
}
var highestTotal float64
optimizedResults := map[string][]OptimizedUploadEntry{}
optimizedTotals := map[string]float64{}
missingCounts := map[string]int{}
missingPrices := map[string]float64{}
resultPrices := map[string]map[string]float64{}
for i := range uploadedData {
// Skip unmatched cards
if uploadedData[i].MismatchError != nil {
continue
}
var bestPrices []float64
var bestStores []string
cardId := uploadedData[i].CardId
// Search for any missing entries (ie cards not sold or bought by a vendor)
for _, shorthand := range enabledStores {
_, found := results[cardId][shorthand]
if !found {
missingCounts[shorthand]++
missingPrices[shorthand] += getPrice(indexResults[cardId][TCG_LOW], "")
}
}
// Summary of the index entries
for indexKey, indexResult := range indexResults[cardId] {
var conds string
// TCG_DIRECT is the only index price that varies by condition
if indexKey == TCG_DIRECT {
conds = uploadedData[i].OriginalCondition
}
if skipConds {
conds = ""
}
indexPrice := getPrice(indexResult, conds)
if resultPrices[cardId+conds] == nil {
resultPrices[cardId+conds] = map[string]float64{}
}
resultPrices[cardId+conds][indexKey] = indexPrice
if uploadedData[i].HasQuantity {
indexPrice *= float64(uploadedData[i].Quantity)
}
pageVars.TotalEntries[indexKey] += indexPrice
}
// Quantity summary
if uploadedData[i].HasQuantity {
pageVars.TotalQuantity += uploadedData[i].Quantity
}
// Run summaries for each vendor
for shorthand, banPrice := range results[cardId] {
conds := uploadedData[i].OriginalCondition
if skipConds {
conds = ""
}
price := getPrice(banPrice, conds)
// Store computed price
if resultPrices[cardId+conds] == nil {
resultPrices[cardId+conds] = map[string]float64{}
}
resultPrices[cardId+conds][shorthand] = price
// Skip empty results
if price == 0 {
continue
}
// Adjust for quantity
if uploadedData[i].HasQuantity {
price *= float64(uploadedData[i].Quantity)
}
// Add to totals (unless it was an index, since it was already added)
_, found := indexResults[cardId][shorthand]
if !found {
pageVars.TotalEntries[shorthand] += price
}
// Save the lowest or highest price depending on mode
// If price is tied, or within a set % difference, save them all
if len(bestPrices) == 0 || (blMode && price*percMargin > bestPrices[0]) || (!blMode && price*percMargin < bestPrices[0]) {
bestPrices = []float64{price}
bestStores = []string{shorthand}
} else if (blMode && price > bestPrices[0]*percMargin) || (!blMode && price < bestPrices[0]*percMargin) {
bestPrices = append(bestPrices, price)
bestStores = append(bestStores, shorthand)
}
}
for j, bestPrice := range bestPrices {
bestStore := bestStores[j]
var spread float64
conds := uploadedData[i].OriginalCondition
if skipConds {
conds = ""
}
cardId := uploadedData[i].CardId
// Load comparison price, either the loaded one or tcg low
comparePrice := uploadedData[i].OriginalPrice
if comparePrice == 0 || skipPrices {
comparePrice = getPrice(indexResults[cardId][TCG_LOW], "")
}
// Load the single item priceprice
price := resultPrices[cardId+conds][bestStore]
// Skip if needed
if skipLowValueAbs && price < minLowVal {
continue
}
if skipHighValueAbs && maxHighVal != 0 && price >= maxHighVal {
continue
}
// Compute spread (and skip if needed)
if comparePrice != 0 {
spread = price / comparePrice * 100
if skipLowValue && spread < percSpread {
continue
}
if skipHighValue && percSpreadMax != 0 && spread >= percSpreadMax {
continue
}
}
// Break down by store
optimizedResults[bestStore] = append(optimizedResults[bestStore], OptimizedUploadEntry{
CardId: cardId,
Condition: conds,
Price: comparePrice,
Spread: spread,
BestPrice: price,
Quantity: uploadedData[i].Quantity,
VisualPrice: comparePrice * visualPerc / 100.0,
})
// Save totals
optimizedTotals[bestStore] += bestPrice
if j == 0 {
highestTotal += bestPrice
}
}
// Keep cards sorted by edition, following the same rules of search
for store := range optimizedResults {
switch sorting {
case "highprice":
sort.Slice(optimizedResults[store], func(i, j int) bool {
return optimizedResults[store][i].BestPrice > optimizedResults[store][j].BestPrice
})
case "highspread":
sort.Slice(optimizedResults[store], func(i, j int) bool {
return optimizedResults[store][i].Spread > optimizedResults[store][j].Spread
})
case "alphabetical":
sort.Slice(optimizedResults[store], func(i, j int) bool {
return sortSetsAlphabeticalSet(optimizedResults[store][i].CardId, optimizedResults[store][j].CardId)
})
default:
sort.Slice(optimizedResults[store], func(i, j int) bool {
return sortSets(optimizedResults[store][i].CardId, optimizedResults[store][j].CardId)
})
}
}
pageVars.Optimized = optimizedResults
pageVars.OptimizedTotals = optimizedTotals
pageVars.HighestTotal = highestTotal
pageVars.Editions = AllEditionsKeys
pageVars.EditionsMap = AllEditionsMap
}
pageVars.MissingCounts = missingCounts
pageVars.MissingPrices = missingPrices
pageVars.ResultPrices = resultPrices
// Logs
user := GetParamFromSig(sig, "UserEmail")
msgMode := "retail"
if blMode {
msgMode = "buylist"
}
msg := fmt.Sprintf("%s uploaded %d %s entries from %s, took %v", user, len(cardIds), msgMode, pageVars.SearchQuery, time.Since(start))
UserNotify("upload", msg)
LogPages["Upload"].Println(msg)
if DevMode {
log.Println(msg)
}
// Touchdown!
render(w, "upload.html", pageVars)
}
func getPrice(banPrice *BanPrice, conds string) float64 {
if banPrice == nil {
return 0
}
var price float64
// Grab the correct Price
if conds == "" {
price = banPrice.Regular
if price == 0 {
price = banPrice.Foil
if price == 0 {
price = banPrice.Etched
}
}
} else {
price = banPrice.Conditions[conds]
if price == 0 {
price = banPrice.Conditions[conds+"_foil"]
if price == 0 {
price = banPrice.Conditions[conds+"_etched"]
}
}
}
return price
}
func getQuantity(qty string) (int, error) {
qty = strings.TrimSuffix(qty, "x")
qty = strings.TrimSpace(qty)
return strconv.Atoi(qty)
}
func mergeIdenticalEntries(uploadedData []UploadEntry) []UploadEntry {
var uploadedDataClean []UploadEntry
duplicatedHashes := map[string]bool{}
for i := range uploadedData {
// Preserve empty results (for errors and whatnot)
if uploadedData[i].CardId == "" {
uploadedDataClean = append(uploadedDataClean, uploadedData[i])
continue
}
// Use id + condition to mimic a "sku"
sku := uploadedData[i].CardId + uploadedData[i].OriginalCondition
if duplicatedHashes[sku] {
qty := 1
if uploadedData[i].HasQuantity {
qty = uploadedData[i].Quantity
}
// Iterate on the already added cards to update the quantity
for j := range uploadedDataClean {
if uploadedData[i].CardId == uploadedDataClean[j].CardId &&
uploadedData[i].OriginalCondition == uploadedDataClean[j].OriginalCondition {
if uploadedDataClean[j].Quantity == 0 {
uploadedDataClean[j].Quantity++
}
uploadedDataClean[j].Quantity += qty
uploadedDataClean[j].HasQuantity = true
break
}
}
continue
}
duplicatedHashes[sku] = true
uploadedDataClean = append(uploadedDataClean, uploadedData[i])
}
return uploadedDataClean
}
func parseHeader(first []string) (map[string]int, error) {
if len(first) < 1 {
return nil, errors.New("too few fields")
}
indexMap := map[string]int{}
// If there is a single element, try using a different mode
if len(first) == 1 {
indexMap["cardName"] = 0
log.Println("No Header map, decklist mode (single element)")
return indexMap, ErrUploadDecklist
}
// Parse the header to understand where these fields are
for i, field := range first {
field = strings.ToLower(field)
switch {
// Skip "tcgplayer id" because it could mean SKU or Product, and the two systems often overlap
case field == "id" || strings.Contains(field, "uuid") || (strings.Contains(field, "id") && field != "tcgplayer id" && (strings.Contains(field, "tcg") || strings.Contains(field, "scryfall"))):
_, found := indexMap["id"]
if !found {
indexMap["id"] = i
}
case (strings.Contains(field, "name") && !strings.Contains(field, "edition") && !strings.Contains(field, "set") || strings.Contains(field, "expansion")) || field == "card":
_, found := indexMap["cardName"]
if !found {
indexMap["cardName"] = i
}
case strings.Contains(field, "edition") || strings.Contains(field, "set") || strings.Contains(field, "expansion"):
_, found := indexMap["edition"]
if !found {
indexMap["edition"] = i
}
case strings.Contains(field, "comment") ||
strings.Contains(field, "number") ||
strings.Contains(field, "variant") ||
strings.Contains(field, "variation") ||
strings.Contains(field, "version"):
_, found := indexMap["variant"]
if !found {
indexMap["variant"] = i
}
case strings.Contains(field, "foil") || strings.Contains(field, "printing") || strings.Contains(field, "finish") || strings.Contains(field, "extra") || field == "f/nf" || field == "nf/f":
_, found := indexMap["printing"]
if !found {
indexMap["printing"] = i
}
case strings.Contains(field, "sku"):
_, found := indexMap["sku"]
if !found {
indexMap["sku"] = i
}
case strings.Contains(field, "condition"):
_, found := indexMap["conditions"]
if !found {
indexMap["conditions"] = i
}
case strings.Contains(field, "price") || strings.Contains(field, "low"):
_, found := indexMap["price"]
if !found {
indexMap["price"] = i
}
case (strings.Contains(field, "quantity") ||
strings.Contains(field, "qty") ||
strings.Contains(field, "stock") ||
strings.Contains(field, "count") ||
strings.Contains(field, "have")) &&
!strings.HasPrefix(field, "set") && !strings.Contains(field, "pending"):
// Keep headers like "Add To Quantity" as backup if nothing is found later
_, found := indexMap["quantity"]
if !found && !strings.HasPrefix(field, "add") {
indexMap["quantity"] = i
} else {
_, found := indexMap["quantity_backup"]
if !found {
indexMap["quantity_backup"] = i
}
}
case strings.Contains(field, "title") && !strings.Contains(field, "variant"):
_, found := indexMap["title"]
if !found {
indexMap["title"] = i
}
case strings.Contains(field, "notes") || strings.Contains(field, "data"):
_, found := indexMap["notes"]
if !found {
indexMap["notes"] = i
}
}
}
// In case there was actually a single element, but the comma appears in the card name
// Performing this after processing the map in case of a weird header with spaces
// after the names
if len(indexMap) < 2 && strings.Contains(strings.Join(first, ","), ", ") {
indexMap["cardName"] = 0
log.Println("No Header map, decklist mode (comma in card name)")
return indexMap, ErrUploadDecklist
}
// If a clean quantity header was not found see if there is a backup option
_, foundQty := indexMap["quantity"]
if !foundQty {
i, found := indexMap["quantity_backup"]
if found {
indexMap["quantity"] = i
}
}
// If this field is present we don't need safe defaults
_, foundId := indexMap["id"]
// Set some default values for the mandatory fields
_, foundName := indexMap["cardName"]
if !foundName && !foundId {
indexMap["cardName"] = 0
// Used by some formats that do not set a card name
i, found := indexMap["title"]
if found {
indexMap["cardName"] = i
foundName = true
}
}
_, foundEdition := indexMap["edition"]
if !foundEdition && !foundId {
indexMap["edition"] = 1
}
// If nothing at all was found, send an error to reprocess the first line
if !foundName && !foundEdition && !foundId {
log.Println("Fake Header map:", indexMap)
return indexMap, ErrReloadFirstRow
}
log.Println("Header map:", indexMap)
return indexMap, nil
}
func parseRow(indexMap map[string]int, record []string) (UploadEntry, error) {
var res UploadEntry
// Skip empty lines
hasContent := false
for _, field := range record {
if field != "" {
hasContent = true
break
}
}
if !hasContent {
return res, errors.New("empty line")
}
// Ensure fields can be parsed correctly
for i := range record {
record[i] = strings.TrimSpace(record[i])
}
// Decklist mode
if len(record) == 1 {
line := record[indexMap["cardName"]]
if unicode.IsDigit(rune(line[0])) {
// Parse both "4 x <name>" and "4x <name>"
fields := strings.Split(line, " ")
field := strings.TrimSuffix(fields[0], "x")
num, err := strconv.Atoi(field)
if err == nil {
// Cleanup and append
line = strings.TrimPrefix(line, field)
line = strings.TrimSpace(line)
line = strings.TrimPrefix(line, "x")
res.HasQuantity = true
res.Quantity = num
}
}
// Parse "Rift Bolt (TSP)"
vars := mtgmatcher.SplitVariants(line)
if len(vars) > 1 {
maybeEdition := vars[1]
// Only assign edition if it's a known set code
set, err := mtgmatcher.GetSetByName(maybeEdition)
if err == nil {
// Remove the parsed part, leaving any other detail available downstream