-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1863 lines (1682 loc) · 61 KB
/
Copy pathmain.go
File metadata and controls
1863 lines (1682 loc) · 61 KB
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 (
"bufio"
"bytes"
"crypto/rand"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os/exec"
"otapi-hub/config"
"otapi-hub/cscart"
"otapi-hub/db"
"otapi-hub/otapi"
"otapi-hub/push"
"otapi-hub/sync"
"otapi-hub/translate"
"sort"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
)
//go:embed web/templates/*.html
var templateFS embed.FS
var (
cfg *config.Config
store *db.Store
imp *sync.Importer
apiPusher *push.APIPusher
csClient *cscart.Client
sessionToken string
)
var funcMap template.FuncMap
// authMiddleware - проверяет cookie "otweb_session".
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Login/logout и img-proxy не требуют авторизации
if r.URL.Path == "/otweb/login" || r.URL.Path == "/otweb/img-proxy" || r.URL.Path == "/otweb/api/delivery-date" {
next.ServeHTTP(w, r)
return
}
// Если auth не настроен - пропускаем
if cfg.Auth.Username == "" {
next.ServeHTTP(w, r)
return
}
cookie, err := r.Cookie("otweb_session")
if err != nil || cookie.Value != sessionToken {
// Для JSON API возвращаем 401, для HTML — редирект
if strings.HasPrefix(r.URL.Path, "/otweb/api/v1/") {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"unauthorized"}`))
return
}
http.Redirect(w, r, "/otweb/login", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
func generateToken() string {
b := make([]byte, 32)
rand.Read(b)
return hex.EncodeToString(b)
}
func toInt(v interface{}) (int, bool) {
switch n := v.(type) {
case int:
return n, true
case int64:
return int(n), true
case float64:
return int(n), true
}
return 0, false
}
func main() {
// Пробуем загрузить config.yaml, если нет - используем Default()
loaded, loadErr := config.Load("config.yaml")
if loadErr == nil {
cfg = loaded
log.Println("[config] Загружен config.yaml")
} else {
cfg = config.Default()
log.Println("[config] Используется Default() конфигурация")
}
var err error
store, err = db.New(cfg.Database.HubDSN, cfg.Database.MirrorDSN)
if err != nil {
log.Fatalf("DB init: %v", err)
}
defer store.Close()
// Override cfg with keys saved in DB (takes priority over config.yaml)
if dbSettings := store.GetAllSettings(); dbSettings != nil {
if v := dbSettings["deepseek_api_key"]; v != "" {
cfg.DeepSeek.APIKey = v
}
if v := dbSettings["otapi_instance_key"]; v != "" {
cfg.OTAPI.InstanceKey = v
}
if v := dbSettings["cscart_api_key"]; v != "" {
cfg.CSCart.APIKey = v
}
log.Printf("[config] DB keys loaded: deepseek=%v, otapi=%v, cscart=%v",
cfg.DeepSeek.APIKey != "", cfg.OTAPI.InstanceKey != "", cfg.CSCart.APIKey != "")
}
client := otapi.NewClient(cfg.OTAPI.InstanceKey, cfg.OTAPI.LegacyURL)
imp = sync.NewImporter(store, client)
csClient = cscart.NewClient(cfg.CSCart.BaseURL, cfg.CSCart.Email, cfg.CSCart.APIKey)
dsClient := newDSClient()
apiPusher = push.NewAPIPusher(store, csClient, dsClient, cfg.CSCart.CompanyID)
apiPusher.SetProxyBase(cfg.CSCart.BaseURL)
// При пуше: скачиваем фото в локальный каталог магазина → CS-Cart получает
// публичный URL и сохраняет фото у себя. Пути берём из конфига (instance-specific).
imgPublicPath := cfg.Images.PublicPath
if imgPublicPath == "" {
imgPublicPath = "/images/otapi"
}
apiPusher.SetImageDownloader(
cfg.Images.LocalDir,
cfg.CSCart.BaseURL+imgPublicPath,
)
funcMap = template.FuncMap{
"p": func(path string) string { return "/otweb" + path },
"hasCSID": func(p *int) bool { return p != nil && *p > 0 },
"deref": func(p *int) int { if p != nil { return *p }; return 0 },
"imgProxy": func(url string) string {
if strings.Contains(url, "cbu01.alicdn.com") || strings.Contains(url, "cbu02.alicdn.com") || strings.Contains(url, "cbu03.alicdn.com") {
return "/otweb/img-proxy?url=" + url
}
return url
},
"filterQuery": func(f db.ProductFilter) string {
params := url.Values{}
if f.CategoryID != "" { params.Set("category", f.CategoryID) }
if f.Provider != "" { params.Set("provider", f.Provider) }
if f.TranslateStatus != "" { params.Set("translate", f.TranslateStatus) }
if f.Search != "" { params.Set("search", f.Search) }
if f.SortBy != "" { params.Set("sort", f.SortBy) }
if f.PushedOnly { params.Set("pushed", "1") }
if f.UnpushedOnly { params.Set("unpushed", "1") }
if f.EnabledOnly { params.Set("enabled", "1") }
if f.DisabledOnly { params.Set("disabled", "1") }
return params.Encode()
},
"inc": func(i interface{}) int {
if v, ok := toInt(i); ok {
return v + 1
}
return 0
},
"dec": func(i interface{}) int {
if v, ok := toInt(i); ok {
return v - 1
}
return 0
},
"not": func(b bool) bool { return !b },
"gt": func(a, b interface{}) bool {
ai, aok := toInt(a)
bi, bok := toInt(b)
return aok && bok && ai > bi
},
"lt": func(a, b interface{}) bool {
ai, aok := toInt(a)
bi, bok := toInt(b)
return aok && bok && ai < bi
},
"fmtTime": func(ts *int64) string {
if ts == nil {
return "-"
}
return time.Unix(*ts, 0).Format("02.01 15:04")
},
"fmtUnix": func(ts interface{}) string {
switch v := ts.(type) {
case int64:
if v == 0 {
return "-"
}
return time.Unix(v, 0).Format("02.01 15:04")
case int:
if v == 0 {
return "-"
}
return time.Unix(int64(v), 0).Format("02.01 15:04")
}
return "-"
},
}
sessionToken = generateToken()
r := mux.NewRouter()
prefix := "/otweb"
s := r.PathPrefix(prefix).Subrouter()
s.Use(authMiddleware)
s.HandleFunc("/login", handleLogin).Methods("GET", "POST")
s.HandleFunc("/logout", handleLogout).Methods("GET")
s.HandleFunc("/", handleDashboard).Methods("GET")
s.HandleFunc("/categories", handleCategories).Methods("GET")
s.HandleFunc("/categories/sync-all-meta", handleSyncMeta).Methods("POST")
s.HandleFunc("/categories/translate", handleCategoriesTranslate).Methods("POST")
s.HandleFunc("/attrs/translate", handleAttrsTranslate).Methods("POST")
s.HandleFunc("/attrs", handleAttrs).Methods("GET")
s.HandleFunc("/categories/{id}/toggle", handleCategoryToggle).Methods("POST")
s.HandleFunc("/categories/{id}/config", handleCategoryConfig).Methods("POST")
s.HandleFunc("/categories/{id}/products", handleCategoryProducts).Methods("GET")
s.HandleFunc("/products/translate-locations", handleTranslateLocations).Methods("POST")
s.HandleFunc("/products", handleProducts).Methods("GET")
s.HandleFunc("/products/{id}", handleProductDetail).Methods("GET")
s.HandleFunc("/products/{id}/translate", handleProductTranslate).Methods("POST")
s.HandleFunc("/products/{id}/push", handleProductPush).Methods("POST")
s.HandleFunc("/products/{id}/toggle-enabled", handleProductToggleEnabled).Methods("POST")
s.HandleFunc("/products/bulk-action", handleBulkAction).Methods("POST")
s.HandleFunc("/products/bulk-translate", handleBulkTranslate).Methods("POST")
s.HandleFunc("/sync", handleSyncPage).Methods("GET")
s.HandleFunc("/sync/run", handleSyncRun).Methods("POST")
s.HandleFunc("/sync/log/{id}", handleSyncLog).Methods("GET")
s.HandleFunc("/push", handlePushPage).Methods("GET")
s.HandleFunc("/push/add", handlePushAdd).Methods("POST")
s.HandleFunc("/push/execute", handlePushExecute).Methods("POST")
s.HandleFunc("/sync/prices", handleSyncPrices).Methods("POST")
s.HandleFunc("/mapping", handleMapping).Methods("GET")
s.HandleFunc("/mapping/add", handleMappingAdd).Methods("POST")
s.HandleFunc("/mapping/delete", handleMappingDelete).Methods("POST")
s.HandleFunc("/mapping/set-weight", handleMappingSetWeight).Methods("POST")
s.HandleFunc("/mapping/set-filters", handleMappingSetFilters).Methods("POST")
s.HandleFunc("/mapping/refresh-cscart", handleRefreshCSCart).Methods("POST")
s.HandleFunc("/push/api", handleAPIPush).Methods("POST")
s.HandleFunc("/settings", handleSettings).Methods("GET")
s.HandleFunc("/settings/keys", handleSettingsKeys).Methods("POST")
s.HandleFunc("/settings/product", handleSettingsProduct).Methods("POST")
s.HandleFunc("/settings/prompt", handleSettingsPrompt).Methods("POST")
s.HandleFunc("/settings/providers", handleSettingsProviders).Methods("POST")
s.HandleFunc("/settings/pricing", handleSettingsPricing).Methods("POST")
s.HandleFunc("/settings/delivery", handleSettingsDelivery).Methods("POST")
s.HandleFunc("/settings/cron", handleSettingsCron).Methods("POST")
// Image proxy (no auth - CS-Cart needs access)
s.HandleFunc("/img-proxy", handleImageProxy).Methods("GET")
// Delivery date API (no auth - used by the storefront frontend JS)
s.HandleFunc("/api/delivery-date", handleDeliveryDate).Methods("GET")
// ── JSON API v1 ──────────────────────────────────────────────
api := s.PathPrefix("/api/v1").Subrouter()
// Auth
api.HandleFunc("/auth/login", apiLogin).Methods("POST")
api.HandleFunc("/auth/logout", apiLogout).Methods("POST")
api.HandleFunc("/auth/me", apiMe).Methods("GET")
// Dashboard
api.HandleFunc("/dashboard", apiDashboard).Methods("GET")
// Categories
api.HandleFunc("/categories", apiCategories).Methods("GET")
api.HandleFunc("/categories/sync-meta", apiSyncMeta).Methods("POST")
api.HandleFunc("/categories/translate", apiCategoriesTranslate).Methods("POST")
api.HandleFunc("/categories/{id}/toggle", apiCategoryToggle).Methods("POST")
api.HandleFunc("/categories/{id}/config", apiCategoryConfig).Methods("POST")
// Attrs
api.HandleFunc("/attrs", apiAttrs).Methods("GET")
api.HandleFunc("/attrs/translate", apiAttrsTranslate).Methods("POST")
api.HandleFunc("/attrs/translate-selected", apiAttrsTranslateSelected).Methods("POST")
api.HandleFunc("/attrs/save", apiAttrsSave).Methods("POST")
api.HandleFunc("/settings/sync-cs-features", apiSyncCSFeatures).Methods("POST")
// Products
api.HandleFunc("/products", apiProducts).Methods("GET")
api.HandleFunc("/products/bulk-translate", apiBulkTranslate).Methods("POST")
api.HandleFunc("/products/translate-locations", apiTranslateLocations).Methods("POST")
api.HandleFunc("/products/bulk", apiBulkAction).Methods("POST")
api.HandleFunc("/products/{id}", apiProductDetail).Methods("GET")
api.HandleFunc("/products/{id}/translate", apiProductTranslate).Methods("POST")
api.HandleFunc("/products/{id}/translate-attrs", apiProductTranslateAttrs).Methods("POST")
api.HandleFunc("/products/{id}/push", apiProductPush).Methods("POST")
api.HandleFunc("/products/{id}/toggle", apiProductToggle).Methods("POST")
// Sync
api.HandleFunc("/sync", apiSyncPage).Methods("GET")
api.HandleFunc("/sync/run", apiSyncRun).Methods("POST")
api.HandleFunc("/sync/prices", apiSyncPrices).Methods("POST")
api.HandleFunc("/sync/jobs/{id}", apiSyncJobStatus).Methods("GET")
api.HandleFunc("/sync/brands", apiSyncBrands).Methods("GET")
api.HandleFunc("/sync/properties", apiSyncProperties).Methods("GET")
// Push
api.HandleFunc("/push", apiPushPage).Methods("GET")
api.HandleFunc("/push/api", apiPushCategory).Methods("POST")
// Mapping
api.HandleFunc("/mapping", apiMappingPage).Methods("GET")
api.HandleFunc("/mapping/add", apiMappingAdd).Methods("POST")
api.HandleFunc("/mapping/delete", apiMappingDelete).Methods("POST")
api.HandleFunc("/mapping/set-weight", apiMappingSetWeight).Methods("POST")
api.HandleFunc("/mapping/set-filters", apiMappingSetFilters).Methods("POST")
api.HandleFunc("/mapping/refresh-cscart", apiRefreshCSCart).Methods("POST")
// Settings
api.HandleFunc("/settings", apiSettings).Methods("GET")
api.HandleFunc("/settings/keys", apiSettingsKeys).Methods("POST")
api.HandleFunc("/settings/product", apiSettingsProduct).Methods("POST")
api.HandleFunc("/settings/pricing", apiSettingsPricing).Methods("POST")
api.HandleFunc("/settings/providers", apiSettingsProviders).Methods("POST")
api.HandleFunc("/settings/cron", apiSettingsCron).Methods("POST")
api.HandleFunc("/settings/prompt", apiSettingsPrompt).Methods("POST")
api.HandleFunc("/settings/delivery", apiSettingsDelivery).Methods("POST")
// ── React SPA (статика из frontend/dist) ────────────────────
s.PathPrefix("/app/").HandlerFunc(handleSPA)
// Корень редиректит на SPA
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, prefix+"/app/", http.StatusMovedPermanently)
})
addr := ":" + cfg.Server.Port
log.Printf("OTAPI Hub запущен на http://localhost%s%s/", addr, prefix)
log.Fatal(http.ListenAndServe(addr, r))
}
func render(w http.ResponseWriter, pageName, title string, data interface{}) {
bd, ok := data.(map[string]interface{})
if !ok {
bd = map[string]interface{}{}
}
bd["Title"] = title
bd["Page"] = pageName
bd["Prefix"] = "/otweb"
t, err := template.New("").Funcs(funcMap).ParseFS(templateFS,
"web/templates/layout.html",
"web/templates/"+pageName+".html",
)
if err != nil {
log.Printf("template parse error: %v", err)
http.Error(w, "Template error: "+err.Error(), 500)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, "layout.html", bd); err != nil {
log.Printf("template error: %v", err)
http.Error(w, "Template error: "+err.Error(), 500)
}
}
type D = map[string]interface{}
// CategoryNode - узел дерева категорий для шаблонов
type CategoryNode struct {
db.CategoryWithConfig
CSCategoryName string
ItemCountM string
ItemCountK string
Children []CategoryNode
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.New("").ParseFS(templateFS, "web/templates/login.html")
t.ExecuteTemplate(w, "login", map[string]string{})
return
}
r.ParseForm()
username := r.FormValue("username")
password := r.FormValue("password")
if username == cfg.Auth.Username && password == cfg.Auth.Password {
http.SetCookie(w, &http.Cookie{
Name: "otweb_session",
Value: sessionToken,
Path: "/otweb",
HttpOnly: true,
MaxAge: 86400 * 7, // 7 дней
})
http.Redirect(w, r, "/otweb/app/", http.StatusSeeOther)
return
}
t, _ := template.New("").ParseFS(templateFS, "web/templates/login.html")
t.ExecuteTemplate(w, "login", map[string]string{"Error": "Неверный логин или пароль"})
}
func handleLogout(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "otweb_session",
Value: "",
Path: "/otweb",
MaxAge: -1,
})
http.Redirect(w, r, "/otweb/login", http.StatusSeeOther)
}
// handleDeliveryDate возвращает JSON с датой следующей доставки.
// Логика: заказ до четверга (включительно) → следующий понедельник.
// Пятница/суббота/воскресенье → понедельник через 2 недели (следующий рейс).
// Формат: {"date":"26 maý","date_ru":"26 мая","days":3}
func handleDeliveryDate(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
now := time.Now()
weekday := now.Weekday() // 0=Sunday, 1=Monday ... 6=Saturday
// Считаем дни до следующего понедельника
var daysUntilMonday int
switch weekday {
case time.Monday:
daysUntilMonday = 7 // уже пн — следующий понедельник через неделю
case time.Tuesday:
daysUntilMonday = 6
case time.Wednesday:
daysUntilMonday = 5
case time.Thursday:
daysUntilMonday = 4
case time.Friday:
daysUntilMonday = 10 // пт — рейс уже уходит, следующий через 10 дней
case time.Saturday:
daysUntilMonday = 9
case time.Sunday:
daysUntilMonday = 8
}
delivery := now.AddDate(0, 0, daysUntilMonday)
tkMonths := []string{"", "ýan", "few", "mart", "apr", "maý", "iýun", "iýul", "awg", "sen", "okt", "noý", "dek"}
ruMonths := []string{"", "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"}
m := int(delivery.Month())
dateTK := fmt.Sprintf("%d %s", delivery.Day(), tkMonths[m])
dateRU := fmt.Sprintf("%d %s", delivery.Day(), ruMonths[m])
resp := map[string]interface{}{
"date": dateTK,
"date_ru": dateRU,
"days": daysUntilMonday,
"weekday": int(weekday),
}
json.NewEncoder(w).Encode(resp)
}
func handleImageProxy(w http.ResponseWriter, r *http.Request) {
rawURL := r.URL.Query().Get("url")
if rawURL == "" {
http.Error(w, "missing url", 400)
return
}
// URL параметр может быть URL-кодирован, нужно декодировать
imgURL, err := url.QueryUnescape(rawURL)
if err != nil {
imgURL = rawURL // fallback
}
log.Printf("[proxy] Fetching: %s (raw: %s)", imgURL, rawURL)
req, err := http.NewRequest("GET", imgURL, nil)
if err != nil {
log.Printf("[proxy] ERROR: bad url %s: %v", imgURL, err)
http.Error(w, "bad url", 400)
return
}
req.Header.Set("Referer", "https://detail.1688.com/")
req.Header.Set("User-Agent", "Mozilla/5.0")
client := &http.Client{Timeout: 60 * time.Second} // увеличил с 30 на 60 сек
resp, err := client.Do(req)
if err != nil {
log.Printf("[proxy] ERROR: fetch failed for %s: %v", imgURL, err)
http.Error(w, fmt.Sprintf("fetch failed: %v", err), 502)
return
}
defer resp.Body.Close()
log.Printf("[proxy] Response status: %d, content-type: %s, content-length: %d",
resp.StatusCode, resp.Header.Get("Content-Type"), resp.ContentLength)
if resp.StatusCode != 200 {
// Читаем тело ошибки для логирования
bodyErr, _ := io.ReadAll(resp.Body)
errLen := len(bodyErr)
if errLen > 200 {
errLen = 200
}
log.Printf("[proxy] ERROR: remote returned %d for %s, body: %s", resp.StatusCode, imgURL, string(bodyErr[:errLen]))
http.Error(w, fmt.Sprintf("remote error: %d", resp.StatusCode), resp.StatusCode)
return
}
w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
w.Header().Set("Cache-Control", "public, max-age=86400")
n, err := io.Copy(w, resp.Body)
if err != nil {
log.Printf("[proxy] ERROR: copy failed for %s (copied %d bytes): %v", imgURL, n, err)
return
}
log.Printf("[proxy] OK: %s (%d bytes, content-type: %s)", imgURL, n, resp.Header.Get("Content-Type"))
}
func handleDashboard(w http.ResponseWriter, r *http.Request) {
stats, _ := store.GetDashboardStats()
jobs, _ := store.GetRecentSyncJobs(10)
render(w, "dashboard", "Dashboard", D{
"Stats": stats,
"Jobs": jobs,
})
}
func handleCategories(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
providerFilter := q.Get("provider")
statusFilter := q.Get("status")
sortFilter := q.Get("sort")
searchFilter := q.Get("search")
if sortFilter == "" {
sortFilter = "items_desc"
}
cats, _ := store.GetCategoriesWithConfig()
mappings, _ := store.GetCategoryMappings()
mappingMap := make(map[string]db.CategoryMapping)
for _, m := range mappings {
mappingMap[m.OTCategoryID] = m
}
// Обогащаем данными маппинга, строим карту
allNodes := make(map[string]*CategoryNode)
for i := range cats {
c := &cats[i]
node := &CategoryNode{CategoryWithConfig: *c}
if m, ok := mappingMap[c.ID]; ok {
node.CSCategoryName = m.CSCategoryName
}
node.ItemCountM = fmt.Sprintf("%.1f", float64(c.ItemCount)/1000000)
node.ItemCountK = fmt.Sprintf("%.0f", float64(c.ItemCount)/1000)
allNodes[c.ID] = node
}
// Фильтрация
var filtered []CategoryNode
for _, c := range cats {
if providerFilter != "" && c.Provider != providerFilter {
continue
}
if searchFilter != "" && !strings.Contains(strings.ToLower(c.Name), strings.ToLower(searchFilter)) {
continue
}
if statusFilter == "enabled" && !c.Enabled {
continue
}
if statusFilter == "with_products" && c.LocalCount == 0 {
continue
}
if statusFilter == "mapped" {
if _, ok := mappingMap[c.ID]; !ok {
continue
}
}
filtered = append(filtered, *allNodes[c.ID])
}
// Сортировка
switch sortFilter {
case "items_desc":
sort.Slice(filtered, func(i, j int) bool { return filtered[i].ItemCount > filtered[j].ItemCount })
case "name":
sort.Slice(filtered, func(i, j int) bool { return filtered[i].Name < filtered[j].Name })
case "synced":
sort.Slice(filtered, func(i, j int) bool { return filtered[i].LocalCount > filtered[j].LocalCount })
}
// Строим дерево из всех категорий
var treeNodes []CategoryNode
for _, c := range cats {
if c.ParentID == "" {
node := *allNodes[c.ID]
for _, child := range cats {
if child.ParentID == c.ID {
node.Children = append(node.Children, *allNodes[child.ID])
}
}
treeNodes = append(treeNodes, node)
}
}
sort.Slice(treeNodes, func(i, j int) bool { return treeNodes[i].Name < treeNodes[j].Name })
render(w, "categories", "Категории", D{
"Categories": cats,
"FilteredCategories": filtered,
"TreeNodes": treeNodes,
"ProviderFilter": providerFilter,
"StatusFilter": statusFilter,
"SortFilter": sortFilter,
"SearchFilter": searchFilter,
})
}
func handleSyncMeta(w http.ResponseWriter, r *http.Request) {
cleanFirst := r.FormValue("clean_first") == "1"
go func() {
if err := imp.SyncCategories(cleanFirst); err != nil {
log.Printf("sync meta error: %v", err)
}
}()
http.Redirect(w, r, "/otweb/categories", http.StatusSeeOther)
}
func handleCategoriesTranslate(w http.ResponseWriter, r *http.Request) {
if cfg.DeepSeek.APIKey == "" {
http.Redirect(w, r, "/otweb/categories", http.StatusSeeOther)
return
}
go func() {
dsClient := newDSClient()
// Берём категории где name_ru = name_zh (не переведены)
rows, err := store.Hub.Query(`SELECT id, name_ru FROM categories WHERE name_ru = name_zh AND name_ru != '' ORDER BY id`)
if err != nil {
log.Printf("[cat-translate] query error: %v", err)
return
}
defer rows.Close()
type catItem struct {
ID string
Name string
}
var items []catItem
for rows.Next() {
var it catItem
rows.Scan(&it.ID, &it.Name)
items = append(items, it)
}
rows.Close()
if len(items) == 0 {
log.Println("[cat-translate] all categories already translated")
return
}
log.Printf("[cat-translate] translating %d categories", len(items))
// Batch по 20 категорий за один запрос DeepSeek
batchSize := 20
for i := 0; i < len(items); i += batchSize {
end := i + batchSize
if end > len(items) {
end = len(items)
}
batch := items[i:end]
// Строим промпт для batch перевода
var lines []string
for _, it := range batch {
lines = append(lines, fmt.Sprintf("%s: %s", it.ID, it.Name))
}
prompt := fmt.Sprintf(`Переведи названия категорий товаров с китайского на русский и английский. Это категории маркетплейса 1688.com.
Правила:
- Краткие, понятные названия для e-commerce (1-3 слова)
- Без иероглифов в переводе
- Формат ответа: JSON объект, ключ = ID категории, значение = {"ru": "...", "en": "..."}
Категории:
%s
Ответ: только JSON.`, strings.Join(lines, "\n"))
result, err := dsClient.RawChat(prompt)
if err != nil {
log.Printf("[cat-translate] batch %d-%d error: %v", i, end, err)
continue
}
// Парсим JSON ответ
var translations map[string]struct {
RU string `json:"ru"`
EN string `json:"en"`
}
if err := json.Unmarshal([]byte(result), &translations); err != nil {
log.Printf("[cat-translate] parse error: %v (response: %s)", err, result[:min(200, len(result))])
continue
}
for catID, tr := range translations {
if tr.RU != "" {
store.Hub.Exec(`UPDATE categories SET name_ru=?, name_en=? WHERE id=?`, tr.RU, tr.EN, catID)
}
}
log.Printf("[cat-translate] batch %d-%d: %d translated", i, end, len(translations))
time.Sleep(500 * time.Millisecond)
}
log.Printf("[cat-translate] done")
}()
http.Redirect(w, r, "/otweb/categories", http.StatusSeeOther)
}
func handleAttrs(w http.ResponseWriter, r *http.Request) {
// Статистика по атрибутам
var total, translated int
store.Hub.QueryRow(`SELECT COUNT(DISTINCT pid, vid) FROM product_attrs WHERE pid != '' AND vid != ''`).Scan(&total)
store.Hub.QueryRow(`SELECT COUNT(*) FROM attr_translations`).Scan(&translated)
// Последние 100 переводов
rows, _ := store.Hub.Query(`SELECT pid, vid, property_name_zh, value_zh, property_name_ru, value_ru FROM attr_translations ORDER BY translated_at DESC LIMIT 100`)
var recent []db.AttrTranslation
if rows != nil {
defer rows.Close()
for rows.Next() {
var at db.AttrTranslation
rows.Scan(&at.Pid, &at.Vid, &at.PropertyNameZh, &at.ValueZh, &at.PropertyNameRu, &at.ValueRu)
recent = append(recent, at)
}
}
render(w, "attrs", "Атрибуты", D{
"Total": total,
"Translated": translated,
"Pending": total - translated,
"Recent": recent,
})
}
func handleAttrsTranslate(w http.ResponseWriter, r *http.Request) {
if cfg.DeepSeek.APIKey == "" {
http.Redirect(w, r, "/otweb/attrs", http.StatusSeeOther)
return
}
go func() {
dsClient := newDSClient()
const batchSize = 50
translated := 0
for {
untranslated, err := store.GetUntranslatedAttrs(batchSize)
if err != nil || len(untranslated) == 0 {
break
}
pairs := make([]translate.AttrPair, len(untranslated))
for i, a := range untranslated {
pairs[i] = translate.AttrPair{Pid: a.Pid, Vid: a.Vid, Name: a.PropertyNameZh, Value: a.ValueZh}
}
results, err := dsClient.TranslateAttrs(pairs)
if err != nil {
log.Printf("[attrs-translate] error: %v", err)
break
}
for _, res := range results {
// Ищем оригинал
var nameZh, valueZh string
for _, p := range pairs {
if p.Pid == res.Pid && p.Vid == res.Vid {
nameZh, valueZh = p.Name, p.Value
break
}
}
store.SaveAttrTranslation(res.Pid, res.Vid, nameZh, res.NameRu, valueZh, res.ValueRu)
}
translated += len(results)
log.Printf("[attrs-translate] batch done: %d translated (total so far: %d)", len(results), translated)
time.Sleep(500 * time.Millisecond)
}
log.Printf("[attrs-translate] done. Total translated: %d", translated)
}()
http.Redirect(w, r, "/otweb/attrs", http.StatusSeeOther)
}
func handleCategoryToggle(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
var enabled bool
store.Hub.QueryRow(`SELECT IFNULL(enabled, 0) FROM category_config WHERE category_id=?`, id).Scan(&enabled)
store.UpsertCategoryConfig(id, !enabled, "manual", 500, nil, "")
http.Redirect(w, r, "/otweb/categories", http.StatusSeeOther)
}
func handleCategoryConfig(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
r.ParseForm()
schedule := r.FormValue("schedule")
maxP, _ := strconv.Atoi(r.FormValue("max_products"))
if maxP == 0 {
maxP = 500
}
enabled := r.FormValue("enabled") == "true"
store.UpsertCategoryConfig(id, enabled, schedule, maxP, nil, "")
http.Redirect(w, r, "/otweb/categories", http.StatusSeeOther)
}
// handleTranslateLocations заполняет location_city_ru / location_state_ru
// для всех товаров у которых оригинал есть, но перевод пустой.
func handleTranslateLocations(w http.ResponseWriter, r *http.Request) {
// Обновляем state
stateRows, _ := store.Hub.Query(`SELECT DISTINCT location_state FROM products WHERE location_state != '' AND location_state_ru = ''`)
var states []string
if stateRows != nil {
for stateRows.Next() {
var s string
stateRows.Scan(&s)
states = append(states, s)
}
stateRows.Close()
}
stateUpdated := 0
for _, s := range states {
ru := sync.TranslateState(s)
if ru != "" {
store.Hub.Exec(`UPDATE products SET location_state_ru=? WHERE location_state=? AND location_state_ru=''`, ru, s)
stateUpdated++
}
}
// Обновляем city
cityRows, _ := store.Hub.Query(`SELECT DISTINCT location_city FROM products WHERE location_city != '' AND location_city_ru = ''`)
var cities []string
if cityRows != nil {
for cityRows.Next() {
var s string
cityRows.Scan(&s)
cities = append(cities, s)
}
cityRows.Close()
}
cityUpdated := 0
for _, s := range cities {
ru := sync.TranslateCity(s)
if ru != "" {
store.Hub.Exec(`UPDATE products SET location_city_ru=? WHERE location_city=? AND location_city_ru=''`, ru, s)
cityUpdated++
}
}
log.Printf("[locations] translated %d states, %d cities", stateUpdated, cityUpdated)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"states":%d,"cities":%d}`, stateUpdated, cityUpdated)
}
func handleProducts(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page, _ := strconv.Atoi(q.Get("page"))
if page < 1 {
page = 1
}
limit, _ := strconv.Atoi(q.Get("per_page"))
if limit != 80 && limit != 120 && limit != 200 {
limit = 40
}
filter := db.ProductFilter{
CategoryID: q.Get("category"),
Provider: q.Get("provider"),
TranslateStatus: q.Get("translate"),
Search: q.Get("search"),
SortBy: q.Get("sort"),
LocationState: q.Get("location"),
HasWeight: q.Get("has_weight") == "1",
PushedOnly: q.Get("pushed") == "1",
UnpushedOnly: q.Get("unpushed") == "1",
EnabledOnly: q.Get("enabled") == "1",
DisabledOnly: q.Get("disabled") == "1",
}
products, total, _ := store.GetProductsFiltered(filter, page, limit)
cats, _ := store.GetCategoriesWithConfig()
totalPages := (total + limit - 1) / limit
var untranslatedCount int
store.Hub.QueryRow(`SELECT COUNT(*) FROM products WHERE (translate_status IS NULL OR translate_status IN ('','none')) AND enabled = 1`).Scan(&untranslatedCount)
// Уникальные провинции для фильтра
type LocationOption struct {
State string
StateRu string
}
var locations []LocationOption
locRows, _ := store.Hub.Query(`SELECT DISTINCT location_state, location_state_ru FROM products WHERE location_state != '' ORDER BY COALESCE(NULLIF(location_state_ru,''), location_state)`)
if locRows != nil {
for locRows.Next() {
var opt LocationOption
locRows.Scan(&opt.State, &opt.StateRu)
locations = append(locations, opt)
}
locRows.Close()
}
render(w, "products", "Товары", D{
"Products": products,
"Total": total,
"TotalPages": totalPages,
"CurrentPage": page,
"PerPage": limit,
"Filter": filter,
"Categories": cats,
"Locations": locations,
"UntranslatedCount": untranslatedCount,
})
}
func handleProductDetail(w http.ResponseWriter, r *http.Request) {
idStr := mux.Vars(r)["id"]
id, _ := strconv.ParseInt(idStr, 10, 64)
product, err := store.GetProductByID(id)
if err != nil {
http.NotFound(w, r)
return
}
// Загружаем маппинг Pid:Vid -> человеческое имя из атрибутов-конфигураторов
confMap := make(map[string]string) // "Pid:Vid" -> "Размер: XL"
confRows, _ := store.Hub.Query(`SELECT pid, vid, property_name, value FROM product_attrs WHERE product_id=? AND is_configurator=1`, id)
if confRows != nil {
for confRows.Next() {
var pid, vid, name, val string
confRows.Scan(&pid, &vid, &name, &val)
confMap[pid+":"+vid] = name + ": " + val
}
confRows.Close()
}
type sku struct {
SKUID string
Quantity int
PriceCNY float64
Configurators string
HumanName string
}
var skus []sku
rows, _ := store.Hub.Query(`SELECT sku_id, quantity, price_cny, IFNULL(configurators,'') FROM product_skus WHERE product_id=? ORDER BY sku_id`, id)
if rows != nil {
defer rows.Close()
for rows.Next() {
var s sku
rows.Scan(&s.SKUID, &s.Quantity, &s.PriceCNY, &s.Configurators)
// Расшифровываем Pid:Vid в человеческие имена
var names []string
var confs []struct{ Pid, Vid string }
json.Unmarshal([]byte(s.Configurators), &confs)
for _, c := range confs {
if name, ok := confMap[c.Pid+":"+c.Vid]; ok {
names = append(names, name)
}
}
s.HumanName = strings.Join(names, " / ")
skus = append(skus, s)
}
}
type attr struct {
PropertyName string
Value string
IsConfigurator bool
}
var attrs []attr
arows, _ := store.Hub.Query(`SELECT property_name, value, is_configurator FROM product_attrs WHERE product_id=? ORDER BY is_configurator DESC, property_name`, id)
if arows != nil {
defer arows.Close()
for arows.Next() {
var a attr
arows.Scan(&a.PropertyName, &a.Value, &a.IsConfigurator)
attrs = append(attrs, a)
}
}
type img struct {
URL string
}
var images []img
irows, _ := store.Hub.Query(`SELECT url FROM product_images WHERE product_id=? ORDER BY is_main DESC, position LIMIT 8`, id)
if irows != nil {
defer irows.Close()
for irows.Next() {
var im img
irows.Scan(&im.URL)
images = append(images, im)
}
}
// Загружаем raw_json и форматируем для отображения
var rawJSON string
store.Hub.QueryRow(`SELECT IFNULL(raw_json,'') FROM products WHERE id=?`, id).Scan(&rawJSON)
if rawJSON != "" {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(rawJSON), "", " "); err == nil {
rawJSON = prettyJSON.String()
}