-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
1361 lines (1279 loc) · 43.3 KB
/
Copy pathapi.go
File metadata and controls
1361 lines (1279 loc) · 43.3 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 (
"encoding/json"
"fmt"
"log"
"net/http"
"otapi-hub/db"
"otapi-hub/sync"
"otapi-hub/translate"
"sort"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
)
func jsonOK(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"ok":true}`))
}
func jsonErr(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
func jsonData(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"data": data, "ok": true})
}
func parseJSON(r *http.Request, dest interface{}) error {
return json.NewDecoder(r.Body).Decode(dest)
}
// ── AUTH ──────────────────────────────────────────────────────────
func apiLogin(w http.ResponseWriter, r *http.Request) {
var body struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := parseJSON(r, &body); err != nil {
jsonErr(w, 400, "invalid json")
return
}
if body.Username != cfg.Auth.Username || body.Password != cfg.Auth.Password {
jsonErr(w, 401, "invalid credentials")
return
}
http.SetCookie(w, &http.Cookie{
Name: "otweb_session", Value: sessionToken, Path: "/otweb",
HttpOnly: true, SameSite: http.SameSiteLaxMode,
})
jsonOK(w)
}
func apiLogout(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{Name: "otweb_session", Value: "", Path: "/otweb", MaxAge: -1})
jsonOK(w)
}
func apiMe(w http.ResponseWriter, r *http.Request) {
jsonData(w, map[string]string{"username": cfg.Auth.Username})
}
// ── DASHBOARD ────────────────────────────────────────────────────
func apiDashboard(w http.ResponseWriter, r *http.Request) {
stats, _ := store.GetDashboardStats()
jobs, _ := store.GetRecentSyncJobs(10)
jsonData(w, map[string]interface{}{"stats": stats, "jobs": jobs})
}
// ── CATEGORIES ───────────────────────────────────────────────────
func apiCategories(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 = strconv.FormatFloat(float64(c.ItemCount)/1_000_000, 'f', 1, 64)
node.ItemCountK = strconv.FormatFloat(float64(c.ItemCount)/1_000, 'f', 0, 64)
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 })
jsonData(w, map[string]interface{}{
"categories": filtered,
"tree": treeNodes,
"total": len(cats),
})
}
func apiSyncMeta(w http.ResponseWriter, r *http.Request) {
var body struct {
CleanFirst bool `json:"clean_first"`
}
parseJSON(r, &body)
go imp.SyncCategories(body.CleanFirst)
jsonOK(w)
}
func apiCategoriesTranslate(w http.ResponseWriter, r *http.Request) {
if cfg.DeepSeek.APIKey == "" {
jsonErr(w, 400, "DeepSeek API key not configured")
return
}
go func() {
dsClient := newDSClient()
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 {
return
}
defer rows.Close()
type catItem struct{ ID, Name string }
var items []catItem
for rows.Next() {
var it catItem
rows.Scan(&it.ID, &it.Name)
items = append(items, it)
}
rows.Close()
for i := 0; i < len(items); i += 20 {
end := i + 20
if end > len(items) {
end = len(items)
}
batch := items[i:end]
names := make([]string, len(batch))
for j, it := range batch {
names[j] = it.Name
}
prompt := `Переведи названия категорий товаров с китайского на русский. Верни JSON: {"translations": [{"original": "...", "ru": "..."}]}
Категории: ` + strings.Join(names, ", ")
resp, err := dsClient.RawChat(prompt)
if err != nil {
continue
}
var result struct {
Translations []struct {
Original string `json:"original"`
Ru string `json:"ru"`
} `json:"translations"`
}
if err := json.Unmarshal([]byte(resp), &result); err != nil {
continue
}
origToRu := make(map[string]string)
for _, t := range result.Translations {
origToRu[t.Original] = t.Ru
}
for _, it := range batch {
if ru, ok := origToRu[it.Name]; ok && ru != "" {
store.Hub.Exec(`UPDATE categories SET name_ru=? WHERE id=?`, ru, it.ID)
}
}
}
}()
jsonOK(w)
}
func apiCategoryToggle(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, "")
jsonData(w, map[string]bool{"enabled": !enabled})
}
func apiCategoryConfig(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
var body struct {
Enabled bool `json:"enabled"`
Schedule string `json:"schedule"`
MaxProducts int `json:"max_products"`
}
if err := parseJSON(r, &body); err != nil {
jsonErr(w, 400, "invalid json")
return
}
if body.MaxProducts == 0 {
body.MaxProducts = 500
}
store.UpsertCategoryConfig(id, body.Enabled, body.Schedule, body.MaxProducts, nil, "")
jsonOK(w)
}
// ── ATTRS ────────────────────────────────────────────────────────
func apiAttrs(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page, _ := strconv.Atoi(q.Get("page"))
if page < 1 {
page = 1
}
perPage, _ := strconv.Atoi(q.Get("per_page"))
if perPage < 1 || perPage > 200 {
perPage = 50
}
search := q.Get("search")
status := q.Get("status") // all | translated | pending
var totalAll, translated int
store.Hub.QueryRow(`SELECT COUNT(DISTINCT pid, vid) FROM product_attrs WHERE pid != '' AND vid != ''`).Scan(&totalAll)
store.Hub.QueryRow(`SELECT COUNT(*) FROM attr_translations`).Scan(&translated)
pending := totalAll - translated
// Build filtered query
var whereClauses []string
var args []interface{}
switch status {
case "translated":
whereClauses = append(whereClauses, `at.pid IS NOT NULL AND at.property_name_ru != ''`)
case "pending":
whereClauses = append(whereClauses, `(at.pid IS NULL OR at.property_name_ru = '')`)
}
if search != "" {
like := "%" + search + "%"
whereClauses = append(whereClauses, `(pa.pid LIKE ? OR pa.vid LIKE ? OR pa.property_name LIKE ? OR pa.value LIKE ? OR at.property_name_ru LIKE ? OR at.value_ru LIKE ?)`)
args = append(args, like, like, like, like, like, like)
}
baseQuery := `
FROM (SELECT DISTINCT pid, vid, property_name, value FROM product_attrs WHERE pid != '' AND vid != '') pa
LEFT JOIN attr_translations at ON at.pid=pa.pid AND at.vid=pa.vid`
if len(whereClauses) > 0 {
baseQuery += " WHERE " + strings.Join(whereClauses, " AND ")
}
var totalFiltered int
store.Hub.QueryRow(`SELECT COUNT(*) `+baseQuery, args...).Scan(&totalFiltered)
offset := (page - 1) * perPage
selectArgs := append(args, perPage, offset)
rows, _ := store.Hub.Query(`
SELECT pa.pid, pa.vid,
COALESCE(at.property_name_zh, pa.property_name) AS property_name_zh,
COALESCE(at.value_zh, pa.value) AS value_zh,
COALESCE(at.property_name_ru, '') AS property_name_ru,
COALESCE(at.value_ru, '') AS value_ru,
IFNULL(at.translated_at, 0) AS translated_at
`+baseQuery+`
ORDER BY at.translated_at DESC
LIMIT ? OFFSET ?`, selectArgs...)
var items []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, &at.TranslatedAt)
items = append(items, at)
}
}
jsonData(w, map[string]interface{}{
"total_all": totalAll,
"total_filtered": totalFiltered,
"translated": translated,
"pending": pending,
"page": page,
"per_page": perPage,
"items": items,
})
}
func apiAttrsTranslateSelected(w http.ResponseWriter, r *http.Request) {
if cfg.DeepSeek.APIKey == "" {
jsonErr(w, 400, "DeepSeek API key not configured")
return
}
var body struct {
Pairs []struct {
Pid string `json:"pid"`
Vid string `json:"vid"`
} `json:"pairs"`
}
if err := parseJSON(r, &body); err != nil {
jsonErr(w, 400, "invalid json")
return
}
if len(body.Pairs) == 0 {
jsonErr(w, 400, "no pairs")
return
}
type pairData struct {
Pid, Vid, Name, Value string
}
var pairs []pairData
for _, p := range body.Pairs {
var name, value string
store.Hub.QueryRow(`SELECT property_name, value FROM product_attrs WHERE pid=? AND vid=? LIMIT 1`, p.Pid, p.Vid).Scan(&name, &value)
pairs = append(pairs, pairData{Pid: p.Pid, Vid: p.Vid, Name: name, Value: value})
}
go func() {
dsClient := newDSClient()
for i := 0; i < len(pairs); i += 50 {
end := i + 50
if end > len(pairs) {
end = len(pairs)
}
batch := pairs[i:end]
apairs := make([]translate.AttrPair, len(batch))
for j, p := range batch {
apairs[j] = translate.AttrPair{Pid: p.Pid, Vid: p.Vid, Name: p.Name, Value: p.Value}
}
results, err := dsClient.TranslateAttrs(apairs)
if err != nil {
break
}
for _, res := range results {
var nameZh, valueZh string
for _, p := range batch {
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)
}
}
}()
jsonData(w, map[string]interface{}{"translating": len(pairs)})
}
func apiAttrsSave(w http.ResponseWriter, r *http.Request) {
var body struct {
Pid string `json:"pid"`
Vid string `json:"vid"`
PropertyNameRu string `json:"property_name_ru"`
ValueRu string `json:"value_ru"`
}
if err := parseJSON(r, &body); err != nil {
jsonErr(w, 400, "invalid json")
return
}
var nameZh, valueZh string
store.Hub.QueryRow(`SELECT COALESCE(property_name_zh,''), COALESCE(value_zh,'') FROM attr_translations WHERE pid=? AND vid=?`, body.Pid, body.Vid).Scan(&nameZh, &valueZh)
if nameZh == "" {
store.Hub.QueryRow(`SELECT property_name, value FROM product_attrs WHERE pid=? AND vid=? LIMIT 1`, body.Pid, body.Vid).Scan(&nameZh, &valueZh)
}
if err := store.SaveAttrTranslation(body.Pid, body.Vid, nameZh, body.PropertyNameRu, valueZh, body.ValueRu); err != nil {
jsonErr(w, 500, err.Error())
return
}
jsonOK(w)
}
func apiAttrsTranslate(w http.ResponseWriter, r *http.Request) {
if cfg.DeepSeek.APIKey == "" {
jsonErr(w, 400, "DeepSeek API key not configured")
return
}
go func() {
dsClient := newDSClient()
for {
untranslated, err := store.GetUntranslatedAttrs(50)
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 {
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)
}
time.Sleep(500 * time.Millisecond)
}
}()
jsonOK(w)
}
// ── PRODUCTS ────────────────────────────────────────────────────
func apiProducts(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page, _ := strconv.Atoi(q.Get("page"))
if page < 1 {
page = 1
}
perPage, _ := strconv.Atoi(q.Get("per_page"))
if perPage < 1 || perPage > 200 {
perPage = 50
}
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, err := store.GetProductsFiltered(filter, page, perPage)
if err != nil {
jsonErr(w, 500, err.Error())
return
}
totalPages := (total + perPage - 1) / perPage
var untranslatedCount int
store.Hub.QueryRow(`SELECT COUNT(*) FROM products WHERE translate_status='pending' OR translate_status='' OR translate_status IS NULL`).Scan(&untranslatedCount)
cats, _ := store.GetCategoriesWithConfig()
jsonData(w, map[string]interface{}{
"products": products, "total": total,
"total_pages": totalPages, "current_page": page, "per_page": perPage,
"untranslated_count": untranslatedCount,
"categories": cats,
})
}
func apiProductDetail(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
product, err := store.GetProductByID(id)
if err != nil {
jsonErr(w, 404, "not found")
return
}
type skuRow struct {
SkuID string `json:"sku_id"`
Qty int `json:"qty"`
PriceCNY float64 `json:"price_cny"`
}
var skus []skuRow
skuRows, _ := store.Hub.Query(`SELECT sku_id, qty, price_cny FROM product_skus WHERE product_id=?`, id)
if skuRows != nil {
defer skuRows.Close()
for skuRows.Next() {
var s skuRow
skuRows.Scan(&s.SkuID, &s.Qty, &s.PriceCNY)
skus = append(skus, s)
}
}
type attrRow struct {
Name string `json:"name"`
Value string `json:"value"`
NameRu string `json:"name_ru"`
ValueRu string `json:"value_ru"`
IsConfigurator bool `json:"is_configurator"`
}
var attrs []attrRow
rows, _ := store.Hub.Query(`
SELECT pa.property_name, pa.value, pa.is_configurator,
COALESCE(at.property_name_ru,''), COALESCE(at.value_ru,'')
FROM product_attrs pa
LEFT JOIN attr_translations at ON at.pid=pa.pid AND at.vid=pa.vid
WHERE pa.product_id=?
ORDER BY pa.is_configurator DESC, pa.property_name`, id)
if rows != nil {
defer rows.Close()
for rows.Next() {
var a attrRow
rows.Scan(&a.Name, &a.Value, &a.IsConfigurator, &a.NameRu, &a.ValueRu)
attrs = append(attrs, a)
}
}
var untranslatedAttrs int
store.Hub.QueryRow(`
SELECT COUNT(*) FROM product_attrs pa
LEFT JOIN attr_translations at ON at.pid=pa.pid AND at.vid=pa.vid
WHERE pa.product_id=? AND (at.pid IS NULL OR at.property_name_ru='')`, id).Scan(&untranslatedAttrs)
type imageRow struct {
URL string `json:"url"`
}
var images []imageRow
irows, _ := store.Hub.Query(`SELECT IFNULL(medium_url, url) FROM product_images WHERE product_id=? ORDER BY sort_order`, id)
if irows != nil {
defer irows.Close()
for irows.Next() {
var img imageRow
irows.Scan(&img.URL)
images = append(images, img)
}
}
jsonData(w, map[string]interface{}{
"product": product, "skus": skus, "attrs": attrs, "images": images,
"untranslated_attrs": untranslatedAttrs,
})
}
func apiProductTranslate(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
var body struct {
Action string `json:"action"`
TitleRu string `json:"title_ru"`
TitleEn string `json:"title_en"`
TitleTk string `json:"title_tk"`
DescRu string `json:"desc_ru"`
DescEn string `json:"desc_en"`
DescTk string `json:"desc_tk"`
}
parseJSON(r, &body)
if body.Action == "manual" {
store.Hub.Exec(`UPDATE products SET title_ru=?, title_en=?, title_tk=?, description_ru=?, description_en=?, description_tk=?, translate_status='done', updated_at=? WHERE id=?`,
body.TitleRu, body.TitleEn, body.TitleTk, body.DescRu, body.DescEn, body.DescTk, time.Now().Unix(), id)
jsonOK(w)
return
}
go func() {
if cfg.DeepSeek.APIKey == "" {
return
}
product, err := store.GetProductByID(id)
if err != nil {
return
}
dsClient := newDSClient()
attrs := make(map[string]string)
rows, _ := store.Hub.Query(`SELECT property_name, value FROM product_attrs WHERE product_id=? AND is_configurator=0`, id)
if rows != nil {
defer rows.Close()
for rows.Next() {
var k, v string
rows.Scan(&k, &v)
attrs[k] = v
}
}
result, err := dsClient.Normalize(translate.NormalizeInput{
TitleOriginal: product.TitleOriginal, TitleRu: product.TitleRu, Attributes: attrs,
})
if err != nil {
return
}
store.Hub.Exec(`UPDATE products SET title_ru=?, description_ru=?, translate_status='done', updated_at=? WHERE id=?`,
result.TitleRU, result.DescriptionRU, time.Now().Unix(), id)
}()
jsonData(w, map[string]string{"status": "started"})
}
func apiProductPush(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
// find category mapping
var categoryCS int
store.Hub.QueryRow(`
SELECT IFNULL(cm.cs_category_id, 0) FROM products p
LEFT JOIN category_map cm ON cm.otapi_category_id = p.category_id
WHERE p.id=?`, id).Scan(&categoryCS)
go apiPusher.PushSingleProduct(id, categoryCS)
jsonData(w, map[string]string{"status": "started"})
}
func apiProductTranslateAttrs(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
if cfg.DeepSeek.APIKey == "" {
jsonErr(w, 400, "DeepSeek API key not configured")
return
}
// Gather untranslated (pid,vid) pairs for this product
type pair struct{ Pid, Vid, Name, Value string }
var pairs []pair
rows, _ := store.Hub.Query(`
SELECT pa.pid, pa.vid, pa.property_name, pa.value
FROM product_attrs pa
LEFT JOIN attr_translations at ON at.pid=pa.pid AND at.vid=pa.vid
WHERE pa.product_id=? AND pa.pid!='' AND (at.pid IS NULL OR at.property_name_ru='')
GROUP BY pa.pid, pa.vid`, id)
if rows != nil {
defer rows.Close()
for rows.Next() {
var p pair
rows.Scan(&p.Pid, &p.Vid, &p.Name, &p.Value)
pairs = append(pairs, p)
}
}
if len(pairs) == 0 {
jsonData(w, map[string]interface{}{"translated": 0, "message": "all attrs already translated"})
return
}
go func() {
log.Printf("[translate-attrs] product %d: starting translation of %d pairs", id, len(pairs))
dsClient := newDSClient()
totalSaved := 0
// Batch by 50
for i := 0; i < len(pairs); i += 50 {
end := i + 50
if end > len(pairs) {
end = len(pairs)
}
batch := pairs[i:end]
apairs := make([]translate.AttrPair, len(batch))
for j, p := range batch {
apairs[j] = translate.AttrPair{Pid: p.Pid, Vid: p.Vid, Name: p.Name, Value: p.Value}
}
results, err := dsClient.TranslateAttrs(apairs)
if err != nil {
log.Printf("[translate-attrs] product %d: batch %d-%d error: %v", id, i, end, err)
break
}
log.Printf("[translate-attrs] product %d: batch %d-%d got %d results", id, i, end, len(results))
for _, res := range results {
var nameZh, valueZh string
for _, p := range batch {
if p.Pid == res.Pid && p.Vid == res.Vid {
nameZh, valueZh = p.Name, p.Value
break
}
}
if err := store.SaveAttrTranslation(res.Pid, res.Vid, nameZh, res.NameRu, valueZh, res.ValueRu); err != nil {
log.Printf("[translate-attrs] SaveAttrTranslation(%s,%s): %v", res.Pid, res.Vid, err)
} else {
totalSaved++
}
}
}
log.Printf("[translate-attrs] product %d: done, saved %d translations", id, totalSaved)
}()
jsonData(w, map[string]interface{}{"translating": len(pairs), "message": "translation started"})
}
func apiProductToggle(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
var enabled bool
store.Hub.QueryRow(`SELECT enabled FROM products WHERE id=?`, id).Scan(&enabled)
store.Hub.Exec(`UPDATE products SET enabled=? WHERE id=?`, !enabled, id)
jsonData(w, map[string]bool{"enabled": !enabled})
}
func apiBulkAction(w http.ResponseWriter, r *http.Request) {
var body struct {
Action string `json:"action"`
ProductIDs []int64 `json:"product_ids"`
}
if err := parseJSON(r, &body); err != nil {
jsonErr(w, 400, "invalid json")
return
}
if len(body.ProductIDs) == 0 {
jsonErr(w, 400, "no product_ids")
return
}
switch body.Action {
case "enable":
for _, id := range body.ProductIDs {
store.Hub.Exec(`UPDATE products SET enabled=1 WHERE id=?`, id)
}
case "disable":
for _, id := range body.ProductIDs {
store.Hub.Exec(`UPDATE products SET enabled=0 WHERE id=?`, id)
}
case "delete":
for _, id := range body.ProductIDs {
store.Hub.Exec(`DELETE FROM products WHERE id=?`, id)
}
}
jsonOK(w)
}
func apiBulkTranslate(w http.ResponseWriter, r *http.Request) {
go func() {
rows, _ := store.Hub.Query(`SELECT id FROM products WHERE (translate_status='pending' OR translate_status='') AND enabled=1 LIMIT 100`)
if rows == nil {
return
}
var ids []int64
for rows.Next() {
var id int64
rows.Scan(&id)
ids = append(ids, id)
}
rows.Close()
// trigger individual translations
for _, id := range ids {
if cfg.DeepSeek.APIKey == "" {
break
}
product, err := store.GetProductByID(id)
if err != nil {
continue
}
dsClient := newDSClient()
result, err := dsClient.Normalize(translate.NormalizeInput{
TitleOriginal: product.TitleOriginal, TitleRu: product.TitleRu,
})
if err != nil {
continue
}
store.Hub.Exec(`UPDATE products SET title_ru=?, description_ru=?, translate_status='done', updated_at=? WHERE id=?`,
result.TitleRU, result.DescriptionRU, time.Now().Unix(), id)
time.Sleep(200 * time.Millisecond)
}
}()
jsonOK(w)
}
func apiTranslateLocations(w http.ResponseWriter, r *http.Request) {
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++
}
}
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++
}
}
jsonData(w, map[string]int{"states": stateUpdated, "cities": cityUpdated})
}
// ── SYNC ─────────────────────────────────────────────────────────
func apiSyncPage(w http.ResponseWriter, r *http.Request) {
jobs, _ := store.GetRecentSyncJobs(20)
cats, _ := store.GetCategoriesWithConfig()
jsonData(w, map[string]interface{}{"jobs": jobs, "categories": cats})
}
func apiSyncRun(w http.ResponseWriter, r *http.Request) {
var body struct {
CategoryID string `json:"category_id"`
ItemTitle string `json:"item_title"`
MaxProducts int `json:"max_products"`
MinVolume int `json:"min_volume"`
MinPrice float64 `json:"min_price"`
MaxPrice float64 `json:"max_price"`
MaxPriceLimit float64 `json:"max_price_limit"`
VendorName string `json:"vendor_name"`
BrandName string `json:"brand_name"`
PropertySearch string `json:"property_search"`
OrderBy string `json:"order_by"`
StuffStatus string `json:"stuff_status"`
SearchMethod string `json:"search_method"`
MinVendorRating int `json:"min_vendor_rating"`
MaxVendorRating int `json:"max_vendor_rating"`
FirstLotMin int `json:"first_lot_min"`
FirstLotMax int `json:"first_lot_max"`
FeatureComplete bool `json:"feature_complete"`
FeatureDiscount bool `json:"feature_discount"`
FeatureTmall bool `json:"feature_tmall"`
PricesOnly bool `json:"prices_only"`
}
if err := parseJSON(r, &body); err != nil {
jsonErr(w, 400, "invalid json")
return
}
if body.MaxProducts == 0 {
body.MaxProducts = 500
}
jobType := "products"
if body.PricesOnly {
jobType = "prices"
}
jobID, err := store.CreateSyncJob(jobType, body.CategoryID, "manual")
if err != nil {
jsonErr(w, 500, "create job: "+err.Error())
return
}
go func() {
store.UpdateSyncJob(jobID, "running", 0, 0, 0, 0, "")
if body.PricesOnly {
updated, apiReqs, syncErr := imp.SyncPricesOnly(body.CategoryID)
status := "done"
logText := fmt.Sprintf("Обновлено цен: %d, API: %d", updated, apiReqs)
if syncErr != nil {
status = "error"
logText += "\nERROR: " + syncErr.Error()
}
store.UpdateSyncJob(jobID, status, updated, 0, 0, apiReqs, logText)
} else {
opts := sync.SyncOptions{
ItemTitle: body.ItemTitle, MinVolume: body.MinVolume,
MinPrice: int(body.MinPrice), MaxPrice: int(body.MaxPrice), MaxPriceLimit: int(body.MaxPriceLimit),
VendorName: body.VendorName, BrandName: body.BrandName, PropertySearch: body.PropertySearch,
OrderBy: body.OrderBy, StuffStatus: body.StuffStatus, SearchMethod: body.SearchMethod,
MinVendorRating: body.MinVendorRating, MaxVendorRating: body.MaxVendorRating,
FirstLotMin: body.FirstLotMin, FirstLotMax: body.FirstLotMax,
FeatureComplete: body.FeatureComplete, FeatureDiscount: body.FeatureDiscount,
FeatureTmall: body.FeatureTmall, JobID: jobID,
}
result := imp.SyncProducts(body.CategoryID, body.MaxProducts, opts, nil)
status := "done"
if result.Errors > 0 && result.Processed == 0 {
status = "error"
}
store.Hub.Exec(`UPDATE sync_jobs SET status=?, finished_at=?, items_processed=?, items_skipped=?, errors_count=?, api_requests_made=? WHERE id=?`,
status, time.Now().Unix(), result.Processed, result.Skipped, result.Errors, result.APIRequests, jobID)
}
}()
jsonData(w, map[string]interface{}{"job_id": jobID})
}
func apiSyncPrices(w http.ResponseWriter, r *http.Request) {
var body struct {
CategoryID string `json:"category_id"`
}
parseJSON(r, &body)
jobID, err := store.CreateSyncJob("prices", body.CategoryID, "manual")
if err != nil {
jsonErr(w, 500, err.Error())
return
}
go func() {
store.UpdateSyncJob(jobID, "running", 0, 0, 0, 0, "")
updated, apiReqs, syncErr := imp.SyncPricesOnly(body.CategoryID)
status := "done"
logText := fmt.Sprintf("Обновлено цен: %d, API: %d", updated, apiReqs)
if syncErr != nil {
status = "error"
logText += "\nERROR: " + syncErr.Error()
}
store.UpdateSyncJob(jobID, status, updated, 0, 0, apiReqs, logText)
}()
jsonData(w, map[string]interface{}{"job_id": jobID})
}
func apiSyncBrands(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
like := "%" + q + "%"
rows, err := store.Hub.Query(`
SELECT brand_name, COUNT(*) as cnt
FROM products
WHERE brand_name != '' AND brand_name IS NOT NULL AND brand_name LIKE ?
GROUP BY brand_name ORDER BY cnt DESC LIMIT 30`, like)
if err != nil {
jsonErr(w, 500, err.Error())
return
}
defer rows.Close()
type item struct {
Name string `json:"name"`
Count int `json:"count"`
}
var result []item
for rows.Next() {
var it item
rows.Scan(&it.Name, &it.Count)
result = append(result, it)
}
if result == nil {
result = []item{}
}
jsonData(w, result)
}
func apiSyncProperties(w http.ResponseWriter, r *http.Request) {
// Returns list of known property pids with their names + values
pidQ := r.URL.Query().Get("pid") // if set, return values for that pid
if pidQ != "" {
rows, err := store.Hub.Query(`
SELECT pa.vid, pa.value, COALESCE(NULLIF(at.value_ru,''), pa.value) as label, COUNT(*) as cnt
FROM product_attrs pa
LEFT JOIN attr_translations at ON pa.pid=at.pid AND pa.vid=at.vid
WHERE pa.pid=?
GROUP BY pa.vid, pa.value, at.value_ru
ORDER BY cnt DESC LIMIT 100`, pidQ)
if err != nil {
jsonErr(w, 500, err.Error())
return
}
defer rows.Close()
type valItem struct {
Vid string `json:"vid"`
Value string `json:"value"`
Label string `json:"label"`
Count int `json:"count"`
}
var result []valItem
for rows.Next() {
var it valItem
rows.Scan(&it.Vid, &it.Value, &it.Label, &it.Count)
result = append(result, it)
}
if result == nil {
result = []valItem{}
}
jsonData(w, result)
return
}
// Return all known pids with name + count
rows, err := store.Hub.Query(`
SELECT pa.pid, COALESCE(NULLIF(at.property_name_ru,''), pa.property_name) as label, COUNT(DISTINCT pa.product_id) as cnt
FROM product_attrs pa
LEFT JOIN attr_translations at ON pa.pid=at.pid AND pa.vid=at.vid
GROUP BY pa.pid, at.property_name_ru, pa.property_name
ORDER BY cnt DESC LIMIT 100`)
if err != nil {
jsonErr(w, 500, err.Error())
return
}
defer rows.Close()
type propItem struct {
Pid string `json:"pid"`
Label string `json:"label"`
Count int `json:"count"`
}
var result []propItem
for rows.Next() {
var it propItem
rows.Scan(&it.Pid, &it.Label, &it.Count)
result = append(result, it)
}