app.js
23 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
// SearchEngine Frontend - Modern UI (Multi-Tenant)
const API_BASE_URL = window.API_BASE_URL || 'http://localhost:6002';
if (document.getElementById('apiUrl')) {
document.getElementById('apiUrl').textContent = API_BASE_URL;
}
// Get tenant ID from input
function getTenantId() {
const tenantInput = document.getElementById('tenantInput');
if (tenantInput) {
return tenantInput.value.trim();
}
return '1'; // Default fallback
}
// 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
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('searchInput').focus();
});
// Keyboard handler
function handleKeyPress(event) {
if (event.key === 'Enter') {
performSearch();
}
}
// Toggle filters visibility
function toggleFilters() {
const filterSection = document.getElementById('filterSection');
filterSection.classList.toggle('hidden');
}
// 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 (一级分类 + 三个属性分面)
const facets = [
"category1_name", // 一级分类
"specifications.color", // 颜色属性
"specifications.size", // 尺寸属性
"specifications.material" // 材质属性
];
// Show loading
document.getElementById('loading').style.display = 'block';
document.getElementById('productGrid').innerHTML = '';
try {
const response = await fetch(`${API_BASE_URL}/search/`, {
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: state.debug
})
});
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 = '';
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 || '';
html += `
<div class="product-card">
<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>
<div class="product-meta">
${category ? escapeHtml(category) : ''}
${vendor ? ' | ' + escapeHtml(vendor) : ''}
</div>
</div>
`;
});
grid.innerHTML = html;
}
// Display facets as filter tags (一级分类 + 三个属性分面)
function displayFacets(facets) {
if (!facets || !Array.isArray(facets)) {
return;
}
facets.forEach((facet) => {
// 根据字段名找到对应的容器
let containerId = null;
let maxDisplay = 10;
// 一级分类
if (facet.field === 'category1_name') {
containerId = 'category1Tags';
maxDisplay = 10;
}
// 颜色属性分面 (specifications.color)
else if (facet.field === 'specifications.color') {
containerId = 'colorTags';
maxDisplay = 10;
}
// 尺寸属性分面 (specifications.size)
else if (facet.field === 'specifications.size') {
containerId = 'sizeTags';
maxDisplay = 10;
}
// 材质属性分面 (specifications.material)
else if (facet.field === 'specifications.material') {
containerId = 'materialTags';
maxDisplay = 10;
}
if (!containerId) {
return;
}
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等)
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' });
}
// Display debug info
function displayDebugInfo(data) {
const debugInfoDiv = document.getElementById('debugInfo');
if (!state.debug || !data.debug_info) {
// If debug mode is off or no debug info, show basic query info
if (data.query_info) {
let html = '<div style="padding: 10px;">';
html += `<div><strong>original_query:</strong> ${escapeHtml(data.query_info.original_query || 'N/A')}</div>`;
html += `<div><strong>detected_language:</strong> ${getLanguageName(data.query_info.detected_language)}</div>`;
html += '</div>';
debugInfoDiv.innerHTML = html;
} else {
debugInfoDiv.innerHTML = '';
}
return;
}
// Display comprehensive debug info when debug mode is on
const debugInfo = data.debug_info;
let html = '<div style="padding: 10px; font-family: monospace; font-size: 12px;">';
// Query Analysis
if (debugInfo.query_analysis) {
html += '<div style="margin-bottom: 15px;"><strong style="font-size: 14px;">Query Analysis:</strong>';
html += `<div>original_query: ${escapeHtml(debugInfo.query_analysis.original_query || 'N/A')}</div>`;
html += `<div>normalized_query: ${escapeHtml(debugInfo.query_analysis.normalized_query || 'N/A')}</div>`;
html += `<div>rewritten_query: ${escapeHtml(debugInfo.query_analysis.rewritten_query || 'N/A')}</div>`;
html += `<div>detected_language: ${getLanguageName(debugInfo.query_analysis.detected_language)}</div>`;
html += `<div>domain: ${escapeHtml(debugInfo.query_analysis.domain || 'default')}</div>`;
html += `<div>is_simple_query: ${debugInfo.query_analysis.is_simple_query ? 'yes' : 'no'}</div>`;
if (debugInfo.query_analysis.translations && Object.keys(debugInfo.query_analysis.translations).length > 0) {
html += '<div>translations: ';
for (const [lang, translation] of Object.entries(debugInfo.query_analysis.translations)) {
if (translation) {
html += `${getLanguageName(lang)}: ${escapeHtml(translation)}; `;
}
}
html += '</div>';
}
if (debugInfo.query_analysis.boolean_ast) {
html += `<div>boolean_ast: ${escapeHtml(debugInfo.query_analysis.boolean_ast)}</div>`;
}
html += `<div>has_vector: ${debugInfo.query_analysis.has_vector ? 'enabled' : 'disabled'}</div>`;
html += '</div>';
}
// Feature Flags
if (debugInfo.feature_flags) {
html += '<div style="margin-bottom: 15px;"><strong style="font-size: 14px;">Feature Flags:</strong>';
html += `<div>translation_enabled: ${debugInfo.feature_flags.translation_enabled ? 'enabled' : 'disabled'}</div>`;
html += `<div>embedding_enabled: ${debugInfo.feature_flags.embedding_enabled ? 'enabled' : 'disabled'}</div>`;
html += `<div>rerank_enabled: ${debugInfo.feature_flags.rerank_enabled ? 'enabled' : 'disabled'}</div>`;
html += '</div>';
}
// ES Response
if (debugInfo.es_response) {
html += '<div style="margin-bottom: 15px;"><strong style="font-size: 14px;">ES Response:</strong>';
html += `<div>took_ms: ${debugInfo.es_response.took_ms}ms</div>`;
html += `<div>total_hits: ${debugInfo.es_response.total_hits}</div>`;
html += `<div>max_score: ${debugInfo.es_response.max_score?.toFixed(3) || 0}</div>`;
html += '</div>';
}
// Stage Timings
if (debugInfo.stage_timings) {
html += '<div style="margin-bottom: 15px;"><strong style="font-size: 14px;">Stage Timings:</strong>';
for (const [stage, duration] of Object.entries(debugInfo.stage_timings)) {
html += `<div>${stage}: ${duration.toFixed(2)}ms</div>`;
}
html += '</div>';
}
// ES Query
if (debugInfo.es_query) {
html += '<div style="margin-bottom: 15px;"><strong style="font-size: 14px;">ES Query DSL:</strong>';
html += `<pre style="background: #f5f5f5; padding: 10px; overflow: auto; max-height: 400px;">${escapeHtml(customStringify(debugInfo.es_query))}</pre>`;
html += '</div>';
}
html += '</div>';
debugInfoDiv.innerHTML = html;
}
// 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 escapeHtml(text) {
if (!text) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
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;
}
}
function getLanguageName(code) {
const names = {
'zh': '中文',
'en': 'English',
'ru': 'Русский',
'ar': 'العربية',
'ja': '日本語',
'unknown': 'Unknown'
};
return names[code] || code;
}