app.js
48.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
// saas-search Frontend - Modern UI (Multi-Tenant)
// API 基础地址策略(优先级从高到低):
// 1. window.API_BASE_URL:若在 HTML / 部署层显式注入,则直接使用(可为绝对 URL 或相对路径,如 "/api")
// 2. 默认:空前缀(同源调用),由 6003 前端服务在服务端转发到本机 6002
//
// 说明:在“外网 web 服务器对 6002 另加认证”的场景下,
// 浏览器不应直接调用 web:6002,而应调用同源 web:6003/search/*,
// 再由 frontend_server.py 代理到 GPU 机本地 6002。
(function initApiBaseUrl() {
let base;
if (window.API_BASE_URL) {
base = window.API_BASE_URL;
} else {
base = '';
}
window.API_BASE_URL = base;
const apiUrlEl = document.getElementById('apiUrl');
if (apiUrlEl) {
apiUrlEl.textContent = base || '(same-origin)';
}
})();
const API_BASE_URL = window.API_BASE_URL;
// Get tenant ID from select
function getTenantId() {
const tenantSelect = document.getElementById('tenantSelect');
if (tenantSelect) {
return tenantSelect.value.trim();
}
return '';
}
// Get sku_filter_dimension (as list) from input
function getSkuFilterDimension() {
const skuFilterInput = document.getElementById('skuFilterDimension');
if (skuFilterInput) {
const value = skuFilterInput.value.trim();
if (!value.length) {
return null;
}
// 支持用逗号分隔多个维度,例如:color,size 或 option1,color
const parts = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
return parts.length > 0 ? parts : null;
}
return null;
}
// State Management
let state = {
query: '',
currentPage: 1,
pageSize: 20,
totalResults: 0,
filters: {},
rangeFilters: {},
sortBy: '',
sortOrder: 'desc',
facets: null,
lastSearchData: null,
debug: true // Always enable debug mode for test frontend
};
// Initialize
function initializeApp() {
// 初始化租户下拉框和分面面板
console.log('Initializing app...');
initTenantSelect();
setupProductGridResultDocToggle();
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.focus();
}
}
/** Delegated handler: toggle inline current result JSON under each result card (survives innerHTML refresh on re-search). */
function setupProductGridResultDocToggle() {
const grid = document.getElementById('productGrid');
if (!grid || grid.dataset.resultDocToggleBound === '1') {
return;
}
grid.dataset.resultDocToggleBound = '1';
grid.addEventListener('click', onProductGridResultDocToggleClick);
}
function onProductGridResultDocToggleClick(event) {
const btn = event.target.closest('[data-action="toggle-result-inline-doc"]');
if (!btn) {
return;
}
event.preventDefault();
const debugRoot = btn.closest('.product-debug');
if (!debugRoot) {
return;
}
const panel = debugRoot.querySelector('.product-result-doc-panel');
const pre = debugRoot.querySelector('.product-result-doc-pre');
if (!panel || !pre) {
return;
}
if (debugRoot.dataset.resultInlineOpen === '1') {
panel.setAttribute('hidden', '');
debugRoot.classList.remove('product-debug--result-expanded');
debugRoot.dataset.resultInlineOpen = '0';
btn.textContent = '在结果中显示当前结果数据';
return;
}
panel.removeAttribute('hidden');
debugRoot.classList.add('product-debug--result-expanded');
debugRoot.dataset.resultInlineOpen = '1';
btn.textContent = '隐藏当前结果数据';
if (pre.textContent.length === 0) {
pre.textContent = btn.getAttribute('data-result-json') || '{}';
}
panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
// 在 DOM 加载完成后初始化
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeApp);
} else {
// DOM 已经加载完成,直接执行
initializeApp();
}
// 备用初始化:如果上面的初始化失败,在 window.onload 时再试一次
window.addEventListener('load', function() {
const tenantList = document.getElementById('tenantList');
if (tenantList && tenantList.options.length === 0) {
console.log('Retrying tenant select initialization on window.load...');
initTenantSelect();
}
});
// 最后尝试:延迟执行,确保所有脚本都已加载
setTimeout(function() {
const tenantList = document.getElementById('tenantList');
if (tenantList && tenantList.options.length === 0) {
console.log('Final retry: Initializing tenant select after delay...');
if (typeof getAvailableTenantIds === 'function') {
initTenantSelect();
} else {
console.error('getAvailableTenantIds still not available after delay');
}
}
}, 100);
// Keyboard handler
function handleKeyPress(event) {
if (event.key === 'Enter') {
performSearch();
}
}
// 初始化租户输入框(带 162/170 等候选,可自行填写任意 tenant ID)
function initTenantSelect() {
const tenantSelect = document.getElementById('tenantSelect');
const tenantList = document.getElementById('tenantList');
if (!tenantSelect || !tenantList) {
console.error('tenantSelect or tenantList element not found');
return;
}
// 检查函数是否可用
if (typeof getAvailableTenantIds !== 'function') {
console.error('getAvailableTenantIds function not found. Make sure tenant_facets_config.js is loaded before app.js');
return;
}
const availableTenants = getAvailableTenantIds();
console.log('Available tenants:', availableTenants);
// 清空 datalist 现有选项
tenantList.innerHTML = '';
if (availableTenants && availableTenants.length > 0) {
availableTenants.forEach(tenantId => {
const option = document.createElement('option');
option.value = tenantId;
tenantList.appendChild(option);
});
// 设置默认值(仅当输入框为空时)
if (!tenantSelect.value.trim()) {
tenantSelect.value = availableTenants.includes('0') ? '0' : availableTenants[0];
}
}
// 初始化分面面板
renderFacetsPanel();
}
// 租户ID改变时的处理
function onTenantIdChange() {
renderFacetsPanel();
// 清空当前的分面数据
clearFacetsData();
}
// 根据当前 tenant_id 渲染分面面板结构
function renderFacetsPanel() {
const tenantId = getTenantId();
const config = getTenantFacetsConfig(tenantId);
const container = document.getElementById('specificationFacetsContainer');
if (!container) return;
// 清空现有规格分面
container.innerHTML = '';
// 为每个规格字段创建分面行
config.specificationFields.forEach(specField => {
const row = document.createElement('div');
row.className = 'filter-row';
row.setAttribute('data-facet-field', specField.field);
row.innerHTML = `
<div class="filter-label">${escapeHtml(specField.label)}:</div>
<div class="filter-tags" id="${specField.containerId}"></div>
`;
container.appendChild(row);
});
}
// 清空所有分面数据(保留结构)
function clearFacetsData() {
const allTagContainers = document.querySelectorAll('.filter-tags');
allTagContainers.forEach(container => {
container.innerHTML = '';
});
}
// Escape HTML to prevent XSS
function escapeHtml(text) {
if (!text) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Perform search
async function performSearch(page = 1) {
const query = document.getElementById('searchInput').value.trim();
const tenantId = getTenantId();
const skuFilterDimension = getSkuFilterDimension();
if (!query) {
alert('Please enter search keywords');
return;
}
if (!tenantId) {
alert('Please enter tenant ID');
return;
}
state.query = query;
state.currentPage = page;
state.pageSize = parseInt(document.getElementById('resultSize').value);
const from = (page - 1) * state.pageSize;
// Define facets
// 使用 disjunctive 控制分面行为:
// - 类目(category1/2/3)使用标准模式(disjunctive: false),用于层级下钻
// - 规格(color/size/material)使用 Multi-Select 模式(disjunctive: true)
const facets = [];
// 一级类目分面(始终存在,用于顶层类目导航)
facets.push({
field: "category1_name",
size: 15,
type: "terms",
disjunctive: false
});
// 如果已选择一级类目,则在该过滤条件下请求二级类目分面
if (state.filters.category1_name && state.filters.category1_name.length > 0) {
facets.push({
field: "category2_name",
size: 15,
type: "terms",
disjunctive: false
});
}
// 如果已选择二级类目,则在进一步过滤条件下请求三级类目分面
if (state.filters.category2_name && state.filters.category2_name.length > 0) {
facets.push({
field: "category3_name",
size: 15,
type: "terms",
disjunctive: false
});
}
// 规格相关分面(Multi-Select 模式)
// 根据 tenant_id 使用不同的配置
const tenantFacetsConfig = getTenantFacetsConfig(tenantId);
tenantFacetsConfig.specificationFields.forEach(specField => {
// 只发送查询参数,不包含显示相关的配置(label, containerId)
facets.push({
field: specField.field,
size: specField.size,
type: specField.type,
disjunctive: specField.disjunctive
});
});
// Show loading
document.getElementById('loading').style.display = 'block';
document.getElementById('productGrid').innerHTML = '';
try {
const searchUrl = new URL(`${API_BASE_URL}/search/`, window.location.origin);
searchUrl.searchParams.set('tenant_id', tenantId);
const response = await fetch(searchUrl.toString(), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Tenant-ID': tenantId,
},
body: JSON.stringify({
query: query,
size: state.pageSize,
from: from,
filters: Object.keys(state.filters).length > 0 ? state.filters : null,
range_filters: Object.keys(state.rangeFilters).length > 0 ? state.rangeFilters : null,
facets: facets,
sort_by: state.sortBy || null,
sort_order: state.sortOrder,
sku_filter_dimension: skuFilterDimension,
// 测试前端始终开启后端调试信息
debug: true
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
state.lastSearchData = data;
state.totalResults = data.total;
state.facets = data.facets;
displayResults(data);
displayFacets(data.facets);
displayPagination();
displayDebugInfo(data);
updateProductCount(data.total);
updateClearFiltersButton();
} catch (error) {
console.error('Search error:', error);
document.getElementById('productGrid').innerHTML = `
<div class="error-message">
<strong>Search Error:</strong> ${error.message}
<br><br>
<small>Please ensure backend service is running (${API_BASE_URL})</small>
</div>
`;
} finally {
document.getElementById('loading').style.display = 'none';
}
}
// Display results in grid
function displayResults(data) {
const grid = document.getElementById('productGrid');
if (!data.results || data.results.length === 0) {
grid.innerHTML = `
<div class="no-results" style="grid-column: 1 / -1;">
<h3>No Results Found</h3>
<p>Try different keywords or filters</p>
</div>
`;
return;
}
let html = '';
// Build per-SPU debug lookup from debug_info.per_result (if present)
let perResultDebugBySpu = {};
if (state.debug && data.debug_info && Array.isArray(data.debug_info.per_result)) {
data.debug_info.per_result.forEach((item) => {
if (item && item.spu_id) {
perResultDebugBySpu[String(item.spu_id)] = item;
}
});
}
const tenantId = getTenantId();
data.results.forEach((result) => {
const product = result;
const title = product.title || product.name || 'N/A';
const price = product.min_price || product.price || 'N/A';
const imageUrl = product.image_url || product.imageUrl || '';
const category = product.category || product.categoryName || '';
const vendor = product.vendor || product.brandName || '';
const spuId = product.spu_id || '';
const debug = spuId ? perResultDebugBySpu[String(spuId)] : null;
let debugHtml = '';
if (debug) {
debugHtml = buildProductDebugHtml({
debug,
result,
spuId,
tenantId,
});
}
html += `
<div class="product-card">
<div class="product-main">
<div class="product-image-wrapper">
${imageUrl ? `
<img src="${escapeHtml(imageUrl)}"
alt="${escapeHtml(title)}"
class="product-image"
onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22100%22 height=%22100%22%3E%3Crect fill=%22%23f0f0f0%22 width=%22100%22 height=%22100%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 font-size=%2214%22 text-anchor=%22middle%22 dy=%22.3em%22 fill=%22%23999%22%3ENo Image%3C/text%3E%3C/svg%3E'">
` : `
<div style="color: #ccc; font-size: 14px;">No Image</div>
`}
</div>
<div class="product-price">
${price !== 'N/A' ? `¥${price}` : 'N/A'}
</div>
<div class="product-title">
${escapeHtml(title)}
</div>
${debug ? buildMultilingualFieldsHtml(debug) : ''}
<div class="product-meta">
${category ? escapeHtml(category) : ''}
${vendor ? ' | ' + escapeHtml(vendor) : ''}
</div>
</div>
${debugHtml}
</div>
`;
});
grid.innerHTML = html;
}
function formatDebugNumber(value, digits = 4) {
if (typeof value === 'number' && Number.isFinite(value)) {
return value.toFixed(digits);
}
return value == null || value === '' ? 'N/A' : String(value);
}
function renderMetricList(items) {
const lines = items
.filter((item) => item && item.value !== undefined && item.value !== null && item.value !== '')
.map(
(item) => `
<div class="debug-metric-line">
<span class="debug-metric-k">${escapeHtml(item.label)}</span><span class="debug-metric-sep">:</span><span class="debug-metric-v">${escapeHtml(String(item.value))}</span>
</div>
`
)
.join('');
return lines ? `<div class="debug-metrics">${lines}</div>` : '';
}
function renderScorePills(items) {
const pills = items
.filter((item) => item && item.value !== undefined && item.value !== null && item.value !== '')
.map((item) => `
<div class="debug-score-pill ${item.tone || ''}">
<span class="debug-score-pill-label">${escapeHtml(item.label)}</span>
<span class="debug-score-pill-value">${escapeHtml(String(item.value))}</span>
</div>
`)
.join('');
return pills ? `<div class="debug-score-pills">${pills}</div>` : '';
}
function renderJsonDetails(title, payload, open = false) {
if (!payload || (typeof payload === 'object' && Object.keys(payload).length === 0)) {
return '';
}
return `
<details class="debug-details" ${open ? 'open' : ''}>
<summary>${escapeHtml(title)}</summary>
<pre class="debug-json-pre">${escapeHtml(customStringify(payload))}</pre>
</details>
`;
}
/** Multilingual title/brief/vendor from per-result debug; shown under image/price/title on the left. */
function buildMultilingualFieldsHtml(debug) {
if (!debug || typeof debug !== 'object') {
return '';
}
const titlePayload = {};
if (debug.title_multilingual) titlePayload.title = debug.title_multilingual;
if (debug.brief_multilingual) titlePayload.brief = debug.brief_multilingual;
if (debug.vendor_multilingual) titlePayload.vendor = debug.vendor_multilingual;
if (Object.keys(titlePayload).length === 0) {
return '';
}
return `<div class="product-main-multilingual">${renderJsonDetails('Multilingual Fields', titlePayload, true)}</div>`;
}
function buildProductDebugHtml({ debug, result, spuId, tenantId }) {
const resultJson = customStringify(result);
const rawUrl = `${API_BASE_URL}/search/es-doc/${encodeURIComponent(spuId)}?tenant_id=${encodeURIComponent(tenantId)}`;
const funnel = debug.ranking_funnel || {};
const esStage = funnel.es_recall || {};
const coarseStage = funnel.coarse_rank || {};
const fineStage = funnel.fine_rank || {};
const rerankStage = funnel.rerank || {};
const finalPageStage = funnel.final_page || {};
const rankSummary = renderMetricList([
{ label: 'Initial Rank', value: debug.initial_rank ?? 'N/A' },
{ label: 'Final Rank', value: debug.final_rank ?? 'N/A' },
{ label: 'Rank Delta', value: (debug.initial_rank && debug.final_rank) ? String(debug.initial_rank - debug.final_rank) : 'N/A' },
{ label: 'SPU', value: spuId || 'N/A' },
]);
const stageScores = renderScorePills([
{ label: 'ES', value: formatDebugNumber(esStage.score ?? debug.es_score), tone: 'tone-es' },
{ label: 'ES Norm', value: formatDebugNumber(esStage.normalized_score ?? debug.es_score_normalized), tone: 'tone-neutral' },
{ label: 'Coarse', value: formatDebugNumber(coarseStage.score ?? debug.coarse_score), tone: 'tone-coarse' },
{ label: 'Fine', value: formatDebugNumber(fineStage.score ?? debug.fine_score), tone: 'tone-fine' },
{ label: 'Rerank', value: formatDebugNumber(rerankStage.rerank_score ?? debug.rerank_score), tone: 'tone-rerank' },
{ label: 'Fused', value: formatDebugNumber(rerankStage.fused_score ?? debug.fused_score), tone: 'tone-final' },
]);
const stageGrid = `
<div class="debug-stage-grid">
${buildStageCard('ES Recall', 'Matched queries and ES raw score', [
{ label: 'rank', value: esStage.rank ?? debug.initial_rank ?? 'N/A' },
{ label: 'es_score', value: formatDebugNumber(esStage.score ?? debug.es_score) },
{ label: 'es_norm', value: formatDebugNumber(esStage.normalized_score ?? debug.es_score_normalized) },
], renderJsonDetails('Matched Queries', esStage.matched_queries ?? debug.matched_queries, true))}
${buildStageCard('Coarse Rank', 'Text + vector fusion', [
{ label: 'rank', value: coarseStage.rank ?? 'N/A' },
{ label: 'rank_change', value: coarseStage.rank_change ?? 'N/A' },
{ label: 'coarse_score', value: formatDebugNumber(coarseStage.score ?? debug.coarse_score) },
{ label: 'text_score', value: formatDebugNumber(coarseStage.text_score ?? debug.text_score) },
{ label: 'text_source', value: formatDebugNumber(coarseStage.signals?.text_source_score ?? debug.text_source_score) },
{ label: 'text_translation', value: formatDebugNumber(coarseStage.signals?.text_translation_score ?? debug.text_translation_score) },
{ label: 'text_primary', value: formatDebugNumber(coarseStage.signals?.text_primary_score ?? debug.text_primary_score) },
{ label: 'text_support', value: formatDebugNumber(coarseStage.signals?.text_support_score ?? debug.text_support_score) },
{ label: 'knn_score', value: formatDebugNumber(coarseStage.knn_score ?? debug.knn_score) },
{ label: 'text_knn', value: formatDebugNumber(coarseStage.signals?.text_knn_score ?? debug.text_knn_score) },
{ label: 'image_knn', value: formatDebugNumber(coarseStage.signals?.image_knn_score ?? debug.image_knn_score) },
{ label: 'text_factor', value: formatDebugNumber(coarseStage.text_factor ?? debug.coarse_text_factor) },
{ label: 'knn_factor', value: formatDebugNumber(coarseStage.knn_factor ?? debug.coarse_knn_factor) },
], renderJsonDetails('Coarse Signals', coarseStage.signals, true))}
${buildStageCard('Fine Rank', 'Lightweight reranker output', [
{ label: 'rank', value: fineStage.rank ?? 'N/A' },
{ label: 'rank_change', value: fineStage.rank_change ?? 'N/A' },
{ label: 'stage_score', value: formatDebugNumber(fineStage.score ?? debug.score) },
{ label: 'fine_score', value: formatDebugNumber(fineStage.fine_score ?? debug.fine_score) },
{ label: 'text_score', value: formatDebugNumber(fineStage.text_score ?? debug.text_score) },
{ label: 'knn_score', value: formatDebugNumber(fineStage.knn_score ?? debug.knn_score) },
], `${renderJsonDetails('Fine Fusion', fineStage.fusion_summary || debug.fusion_summary || fineStage.fusion_factors, true)}${renderJsonDetails('Fine Input', fineStage.rerank_input ?? debug.rerank_input, true)}`)}
${buildStageCard('Final Rerank', 'Heavy reranker + final fusion', [
{ label: 'rank', value: rerankStage.rank ?? finalPageStage.rank ?? debug.final_rank ?? 'N/A' },
{ label: 'rank_change', value: rerankStage.rank_change ?? finalPageStage.rank_change ?? 'N/A' },
{ label: 'stage_score', value: formatDebugNumber(rerankStage.score ?? rerankStage.fused_score ?? debug.score) },
{ label: 'rerank_score', value: formatDebugNumber(rerankStage.rerank_score ?? debug.rerank_score) },
{ label: 'fine_score', value: formatDebugNumber(rerankStage.fine_score ?? debug.fine_score) },
{ label: 'text_score', value: formatDebugNumber(rerankStage.text_score ?? debug.text_score) },
{ label: 'knn_score', value: formatDebugNumber(rerankStage.knn_score ?? debug.knn_score) },
{ label: 'fine_factor', value: formatDebugNumber(rerankStage.fine_factor ?? debug.fine_factor) },
{ label: 'rerank_factor', value: formatDebugNumber(rerankStage.rerank_factor ?? debug.rerank_factor) },
{ label: 'text_factor', value: formatDebugNumber(rerankStage.text_factor ?? debug.text_factor) },
{ label: 'knn_factor', value: formatDebugNumber(rerankStage.knn_factor ?? debug.knn_factor) },
{ label: 'fused_score', value: formatDebugNumber(rerankStage.fused_score ?? debug.fused_score) },
], `${renderJsonDetails('Final Fusion', rerankStage.fusion_summary || debug.fusion_summary || rerankStage.fusion_factors, false)}${renderJsonDetails('Rerank Signals', rerankStage.signals, false)}`)}
</div>
`;
return `
<div class="product-debug">
<div class="product-debug-title">Ranking Funnel</div>
${rankSummary}
${stageScores}
${stageGrid}
${renderJsonDetails('Selected SKU', debug.style_intent_sku, true)}
<div class="product-debug-actions">
<button type="button" class="product-debug-inline-result-btn"
data-action="toggle-result-inline-doc"
data-result-json="${escapeAttr(resultJson)}">
在结果中显示当前结果数据
</button>
<a class="product-debug-link" href="${rawUrl}" target="_blank" rel="noopener noreferrer">
查看 ES 原始文档
</a>
</div>
<div class="product-result-doc-panel" hidden>
<pre class="product-result-doc-pre"></pre>
</div>
</div>
`;
}
// Display facets as filter tags (一级分类 + 三个属性分面)
function displayFacets(facets) {
if (!facets || !Array.isArray(facets)) {
return;
}
const tenantId = getTenantId();
facets.forEach((facet) => {
// 根据配置获取分面显示信息
const displayConfig = getFacetDisplayConfig(tenantId, facet.field);
if (!displayConfig) {
// 如果没有配置,跳过该分面
return;
}
const containerId = displayConfig.containerId;
const maxDisplay = displayConfig.maxDisplay;
const container = document.getElementById(containerId);
if (!container) {
return;
}
// 检查values是否存在且是数组
if (!facet.values || !Array.isArray(facet.values) || facet.values.length === 0) {
container.innerHTML = '';
return;
}
let html = '';
// 渲染分面值
facet.values.slice(0, maxDisplay).forEach((facetValue) => {
if (!facetValue || typeof facetValue !== 'object') {
return;
}
const value = facetValue.value;
const count = facetValue.count;
// 允许value为0或空字符串,但不允许undefined/null
if (value === undefined || value === null) {
return;
}
// 检查是否已选中
let selected = false;
if (facet.field.startsWith('specifications.')) {
// 检查specifications过滤
const specName = facet.field.split('.')[1];
if (state.filters.specifications) {
const specs = Array.isArray(state.filters.specifications)
? state.filters.specifications
: [state.filters.specifications];
selected = specs.some(spec => spec && spec.name === specName && spec.value === value);
}
} else {
// 检查普通字段过滤
if (state.filters[facet.field]) {
selected = state.filters[facet.field].includes(value);
}
}
html += `
<span class="filter-tag ${selected ? 'active' : ''}"
onclick="toggleFilter('${escapeAttr(facet.field)}', '${escapeAttr(String(value))}')">
${escapeHtml(String(value))} (${count || 0})
</span>
`;
});
container.innerHTML = html;
});
}
// Toggle filter (支持specifications嵌套过滤)
function toggleFilter(field, value) {
// 处理specifications属性过滤 (specifications.color, specifications.size, specifications.material)
if (field.startsWith('specifications.')) {
const specName = field.split('.')[1]; // 提取name (color, size, material)
// 初始化specifications过滤
if (!state.filters.specifications) {
state.filters.specifications = [];
}
// 确保是数组格式
if (!Array.isArray(state.filters.specifications)) {
// 如果已经是单个对象,转换为数组
state.filters.specifications = [state.filters.specifications];
}
// 查找是否已存在相同的name和value组合
const existingIndex = state.filters.specifications.findIndex(
spec => spec.name === specName && spec.value === value
);
if (existingIndex > -1) {
// 移除
state.filters.specifications.splice(existingIndex, 1);
if (state.filters.specifications.length === 0) {
delete state.filters.specifications;
} else if (state.filters.specifications.length === 1) {
// 如果只剩一个,可以保持为数组,或转换为单个对象(API都支持)
// 这里保持为数组,更一致
}
} else {
// 添加
state.filters.specifications.push({ name: specName, value: value });
}
} else {
// 处理普通字段过滤 (category1_name 等)
// 对类目字段使用互斥单选 + 层级重置逻辑
const isCategoryField =
field === 'category1_name' ||
field === 'category2_name' ||
field === 'category3_name';
if (isCategoryField) {
// 点击已选中的类目 -> 取消该层和以下层级
const currentValues = state.filters[field] || [];
const isAlreadySelected = currentValues.includes(value);
if (isAlreadySelected) {
delete state.filters[field];
if (field === 'category1_name') {
delete state.filters.category2_name;
delete state.filters.category3_name;
} else if (field === 'category2_name') {
delete state.filters.category3_name;
}
} else {
// 选择新的类目值:该层级单选,下级全部重置
state.filters[field] = [value];
if (field === 'category1_name') {
delete state.filters.category2_name;
delete state.filters.category3_name;
} else if (field === 'category2_name') {
delete state.filters.category3_name;
}
}
} else {
// 其他普通字段维持原有多选行为
if (!state.filters[field]) {
state.filters[field] = [];
}
const index = state.filters[field].indexOf(value);
if (index > -1) {
state.filters[field].splice(index, 1);
if (state.filters[field].length === 0) {
delete state.filters[field];
}
} else {
state.filters[field].push(value);
}
}
}
performSearch(1); // Reset to page 1
}
// Handle price filter (重构版 - 使用 rangeFilters)
function handlePriceFilter(value) {
if (!value) {
delete state.rangeFilters.min_price;
} else {
const priceRanges = {
'0-50': { lt: 50 },
'50-100': { gte: 50, lt: 100 },
'100-200': { gte: 100, lt: 200 },
'200+': { gte: 200 }
};
if (priceRanges[value]) {
state.rangeFilters.min_price = priceRanges[value];
}
}
performSearch(1);
}
// Handle time filter (重构版 - 使用 rangeFilters)
function handleTimeFilter(value) {
if (!value) {
delete state.rangeFilters.create_time;
} else {
const now = new Date();
let fromDate;
switch(value) {
case 'today':
fromDate = new Date(now.setHours(0, 0, 0, 0));
break;
case 'week':
fromDate = new Date(now.setDate(now.getDate() - 7));
break;
case 'month':
fromDate = new Date(now.setMonth(now.getMonth() - 1));
break;
case '3months':
fromDate = new Date(now.setMonth(now.getMonth() - 3));
break;
case '6months':
fromDate = new Date(now.setMonth(now.getMonth() - 6));
break;
}
if (fromDate) {
state.rangeFilters.create_time = {
gte: fromDate.toISOString()
};
}
}
performSearch(1);
}
// Clear all filters
function clearAllFilters() {
state.filters = {};
state.rangeFilters = {};
document.getElementById('priceFilter').value = '';
document.getElementById('timeFilter').value = '';
performSearch(1);
}
// Update clear filters button visibility
function updateClearFiltersButton() {
const btn = document.getElementById('clearFiltersBtn');
if (Object.keys(state.filters).length > 0 || Object.keys(state.rangeFilters).length > 0) {
btn.style.display = 'inline-block';
} else {
btn.style.display = 'none';
}
}
// Update product count
function updateProductCount(total) {
document.getElementById('productCount').textContent = `${total.toLocaleString()} SPUs found`;
}
// Sort functions
function setSortByDefault() {
// Remove active from all buttons and arrows
document.querySelectorAll('.sort-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.arrow-up, .arrow-down').forEach(a => a.classList.remove('active'));
// Set default button active
const defaultBtn = document.querySelector('.sort-btn[data-sort=""]');
if (defaultBtn) defaultBtn.classList.add('active');
state.sortBy = '';
state.sortOrder = 'desc';
performSearch(1);
}
function sortByField(field, order) {
state.sortBy = field;
state.sortOrder = order;
// Remove active from all buttons (but keep "By default" if no sort)
document.querySelectorAll('.sort-btn').forEach(b => b.classList.remove('active'));
// Remove active from all arrows
document.querySelectorAll('.arrow-up, .arrow-down').forEach(a => a.classList.remove('active'));
// Add active to clicked arrow
const activeArrow = document.querySelector(`.arrow-up[data-field="${field}"][data-order="${order}"], .arrow-down[data-field="${field}"][data-order="${order}"]`);
if (activeArrow) {
activeArrow.classList.add('active');
}
performSearch(state.currentPage);
}
// Pagination
function displayPagination() {
const paginationDiv = document.getElementById('pagination');
if (state.totalResults <= state.pageSize) {
paginationDiv.style.display = 'none';
return;
}
paginationDiv.style.display = 'flex';
const totalPages = Math.ceil(state.totalResults / state.pageSize);
const currentPage = state.currentPage;
let html = `
<button class="page-btn" onclick="goToPage(${currentPage - 1})"
${currentPage === 1 ? 'disabled' : ''}>
← Previous
</button>
`;
// Page numbers
const maxVisible = 5;
let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
let endPage = Math.min(totalPages, startPage + maxVisible - 1);
if (endPage - startPage < maxVisible - 1) {
startPage = Math.max(1, endPage - maxVisible + 1);
}
if (startPage > 1) {
html += `<button class="page-btn" onclick="goToPage(1)">1</button>`;
if (startPage > 2) {
html += `<span class="page-info">...</span>`;
}
}
for (let i = startPage; i <= endPage; i++) {
html += `
<button class="page-btn ${i === currentPage ? 'active' : ''}"
onclick="goToPage(${i})">
${i}
</button>
`;
}
if (endPage < totalPages) {
if (endPage < totalPages - 1) {
html += `<span class="page-info">...</span>`;
}
html += `<button class="page-btn" onclick="goToPage(${totalPages})">${totalPages}</button>`;
}
html += `
<button class="page-btn" onclick="goToPage(${currentPage + 1})"
${currentPage === totalPages ? 'disabled' : ''}>
Next →
</button>
`;
html += `
<span class="page-info">
Page ${currentPage} of ${totalPages} (${state.totalResults.toLocaleString()} results)
</span>
`;
paginationDiv.innerHTML = html;
}
function goToPage(page) {
const totalPages = Math.ceil(state.totalResults / state.pageSize);
if (page < 1 || page > totalPages) return;
performSearch(page);
// Scroll to top
window.scrollTo({ top: 0, behavior: 'smooth' });
}
/** Query-analysis intent block: dimensions, matched surface form, canonical value, source query variant. */
function formatIntentDetectionHtml(intent) {
const profile = intent || null;
let block = '<div style="margin-top: 10px;"><strong style="font-size: 13px;">intent_detection:</strong></div>';
if (!profile || typeof profile !== 'object') {
block += '<div>(no intent payload — style intent may be disabled or context missing)</div>';
return block;
}
const active = !!profile.active;
block += `<div>active: ${active ? 'yes' : 'no'}</div>`;
const intents = Array.isArray(profile.intents) ? profile.intents : [];
if (!intents.length) {
block += '<div>intents: (none — no vocabulary match on query variants)</div>';
return block;
}
block += '<div style="margin-top: 4px;">intents:</div><ul style="margin: 4px 0 8px 20px; padding: 0;">';
for (const it of intents) {
const aliases = Array.isArray(it.dimension_aliases) ? it.dimension_aliases.join(', ') : '';
block += '<li style="margin-bottom: 6px;">';
block += `<div><strong>intent_type</strong>: ${escapeHtml(it.intent_type || '')}</div>`;
block += `<div><strong>dimension_aliases</strong>: ${escapeHtml(aliases || 'N/A')}</div>`;
block += `<div><strong>matched_term</strong>: ${escapeHtml(it.matched_term || '')}</div>`;
block += `<div><strong>canonical_value</strong>: ${escapeHtml(it.canonical_value || '')}</div>`;
block += `<div><strong>matched_query_text</strong>: ${escapeHtml(it.matched_query_text || '')}</div>`;
block += '</li>';
}
block += '</ul>';
if (Array.isArray(profile.query_variants) && profile.query_variants.length > 0) {
block += '<div style="margin-top: 6px;"><strong>query_variants</strong>:</div>';
block += `<pre style="background: #f5f5f5; padding: 8px; overflow: auto; max-height: 200px; margin-top: 4px;">${escapeHtml(customStringify(profile.query_variants))}</pre>`;
}
return block;
}
function buildStageCard(title, subtitle, metrics, extraHtml = '') {
return `
<div class="debug-stage-card">
<div class="debug-stage-title">${escapeHtml(title)}</div>
${subtitle ? `<div class="debug-stage-subtitle">${escapeHtml(subtitle)}</div>` : ''}
${renderMetricList(metrics)}
${extraHtml}
</div>
`;
}
function renderTimingBars(stageTimings) {
if (!stageTimings || typeof stageTimings !== 'object') {
return '';
}
const orderedStages = [
'query_parsing',
'query_building',
'elasticsearch_search_primary',
'coarse_ranking',
'style_sku_prepare_hits',
'fine_ranking',
'reranking',
'elasticsearch_page_fill',
'result_processing',
'total_search',
];
const entries = Object.entries(stageTimings)
.sort((a, b) => {
const ai = orderedStages.indexOf(a[0]);
const bi = orderedStages.indexOf(b[0]);
return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi);
});
const total = Number(stageTimings.total_search || 0);
return `
<div class="debug-timing-list">
${entries.map(([stage, duration]) => {
const numeric = Number(duration) || 0;
const width = total > 0 ? Math.max(2, Math.round((numeric / total) * 100)) : 2;
return `
<div class="debug-timing-row">
<div class="debug-timing-label">${escapeHtml(stage)}</div>
<div class="debug-timing-bar-wrap"><div class="debug-timing-bar" style="width:${width}%"></div></div>
<div class="debug-timing-value">${numeric.toFixed(2)}ms</div>
</div>
`;
}).join('')}
</div>
`;
}
function buildGlobalFunnelHtml(data, debugInfo) {
const queryAnalysis = debugInfo.query_analysis || {};
const searchParams = debugInfo.search_params || {};
const featureFlags = debugInfo.feature_flags || {};
const esResponse = debugInfo.es_response || {};
const esQueryContext = debugInfo.es_query_context || {};
const rankingFunnel = debugInfo.ranking_funnel || {};
const coarseInfo = rankingFunnel.coarse_rank || debugInfo.coarse_rank || {};
const fineInfo = rankingFunnel.fine_rank || debugInfo.fine_rank || {};
const rerankInfo = rankingFunnel.rerank || debugInfo.rerank || {};
const translations = queryAnalysis.translations || {};
const keywordsQueries = queryAnalysis.keywords_queries || {};
const summaryHtml = `
<div class="debug-section-block">
<div class="debug-section-title">Query Context</div>
${renderMetricList([
{ label: 'original_query', value: queryAnalysis.original_query || 'N/A' },
{ label: 'rewritten_query', value: queryAnalysis.rewritten_query || 'N/A' },
{ label: 'detected_language', value: queryAnalysis.detected_language || 'N/A' },
{ label: 'index_languages', value: (queryAnalysis.index_languages || []).join(', ') || 'N/A' },
{ label: 'query_tokens', value: (queryAnalysis.query_tokens || []).join(', ') || 'N/A' },
{ label: 'base_keywords', value: keywordsQueries.base || 'N/A' },
{ label: 'translation_enabled', value: featureFlags.translation_enabled ? 'enabled' : 'disabled' },
{ label: 'embedding_enabled', value: featureFlags.embedding_enabled ? 'enabled' : 'disabled' },
{ label: 'style_intent_active', value: featureFlags.style_intent_active ? 'yes' : 'no' },
])}
${Object.keys(translations).length ? renderJsonDetails('Translations', translations, true) : ''}
${Object.keys(keywordsQueries).length ? renderJsonDetails('Keywords Queries', keywordsQueries, true) : ''}
${formatIntentDetectionHtml(queryAnalysis.intent_detection ?? queryAnalysis.style_intent_profile)}
</div>
`;
const funnelHtml = `
<div class="debug-section-block">
<div class="debug-section-title">Ranking Funnel</div>
<div class="debug-stage-grid">
${buildStageCard('ES Recall', 'First-pass retrieval', [
{ label: 'fetch_from', value: searchParams.es_fetch_from ?? 0 },
{ label: 'fetch_size', value: searchParams.es_fetch_size ?? 'N/A' },
{ label: 'total_hits', value: esResponse.total_hits ?? 'N/A' },
{ label: 'es_took_ms', value: esResponse.took_ms ?? 'N/A' },
{ label: 'include_named_queries_score', value: esQueryContext.include_named_queries_score ? 'yes' : 'no' },
])}
${buildStageCard('Coarse Rank', 'Lexical + vector fusion only', [
{ label: 'docs_in', value: coarseInfo.docs_in ?? searchParams.es_fetch_size ?? 'N/A' },
{ label: 'docs_out', value: coarseInfo.docs_out ?? 'N/A' },
{ label: 'formula', value: 'text x knn' },
], coarseInfo.fusion ? renderJsonDetails('Coarse Fusion', coarseInfo.fusion, false) : '')}
${buildStageCard('Fine Rank', 'Lightweight reranker', [
{ label: 'service_url', value: fineInfo.service_url || 'N/A' },
{ label: 'docs_in', value: fineInfo.docs_in ?? 'N/A' },
{ label: 'docs_out', value: fineInfo.docs_out ?? fineInfo.top_n ?? 'N/A' },
{ label: 'top_n', value: fineInfo.top_n ?? 'N/A' },
{ label: 'backend', value: fineInfo.backend || 'N/A' },
{ label: 'model', value: fineInfo.model || fineInfo.backend_model_name || 'N/A' },
{ label: 'query_template', value: fineInfo.query_template || 'N/A' },
], fineInfo.meta ? renderJsonDetails('Fine Meta', fineInfo.meta, false) : '')}
${buildStageCard('Final Rerank', 'Heavy reranker + final fusion', [
{ label: 'service_url', value: rerankInfo.service_url || 'N/A' },
{ label: 'docs_in', value: rerankInfo.docs_in ?? 'N/A' },
{ label: 'docs_out', value: rerankInfo.docs_out ?? 'N/A' },
{ label: 'top_n', value: rerankInfo.top_n ?? 'N/A' },
{ label: 'backend', value: rerankInfo.backend || 'N/A' },
{ label: 'model', value: rerankInfo.model || rerankInfo.backend_model_name || 'N/A' },
{ label: 'query_template', value: rerankInfo.query_template || 'N/A' },
], `${rerankInfo.fusion ? renderJsonDetails('Final Fusion', rerankInfo.fusion, false) : ''}${rerankInfo.meta ? renderJsonDetails('Rerank Meta', rerankInfo.meta, false) : ''}`)}
${buildStageCard('Page Return', 'Final slice returned to UI', [
{ label: 'from', value: searchParams.from_ ?? 0 },
{ label: 'size', value: searchParams.size ?? 'N/A' },
{ label: 'returned', value: (data.results || []).length },
{ label: 'max_score', value: formatDebugNumber(esResponse.max_score, 3) },
])}
</div>
</div>
`;
const timingHtml = `
<div class="debug-section-block">
<div class="debug-section-title">Timing Breakdown</div>
${renderTimingBars(debugInfo.stage_timings)}
</div>
`;
const rawPayloadHtml = `
<div class="debug-section-block">
<div class="debug-section-title">Raw Payloads</div>
${renderJsonDetails('ES Query DSL', debugInfo.es_query, false)}
${renderJsonDetails('ES Query Context', debugInfo.es_query_context, false)}
${renderJsonDetails('Search Params', debugInfo.search_params, false)}
</div>
`;
return `
<div class="debug-panel">
${summaryHtml}
${funnelHtml}
${timingHtml}
${rawPayloadHtml}
</div>
`;
}
// Display debug info
function displayDebugInfo(data) {
const debugInfoDiv = document.getElementById('debugInfo');
if (!state.debug || !data.debug_info) {
if (data.query_info) {
debugInfoDiv.innerHTML = `
<div class="debug-panel">
<div class="debug-section-block">
<div class="debug-section-title">Query Context</div>
${renderMetricList([
{ label: 'original_query', value: data.query_info.original_query || 'N/A' },
{ label: 'detected_language', value: data.query_info.detected_language || 'N/A' },
])}
</div>
</div>
`;
} else {
debugInfoDiv.innerHTML = '';
}
return;
}
debugInfoDiv.innerHTML = buildGlobalFunnelHtml(data, data.debug_info);
}
// Custom JSON stringify that compresses numeric arrays (like embeddings) to single line
function customStringify(obj) {
return JSON.stringify(obj, (key, value) => {
if (Array.isArray(value)) {
// Only collapse arrays that contain numbers (like embeddings)
if (value.every(item => typeof item === 'number')) {
return JSON.stringify(value);
}
}
return value;
}, 2).replace(/"\[/g, '[').replace(/\]"/g, ']');
}
// Helper functions
function escapeAttr(text) {
if (!text) return '';
return text.replace(/'/g, "\\'").replace(/"/g, '"');
}
function formatDate(dateStr) {
if (!dateStr) return '';
try {
const date = new Date(dateStr);
return date.toLocaleDateString('zh-CN');
} catch {
return dateStr;
}
}