app_base.js 19.6 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
// SearchEngine Frontend - Modern UI (Multi-Tenant)

const API_BASE_URL = 'http://localhost:6002';
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
}

// 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() {
    console.log('SearchEngine loaded');
    console.log('Debug mode: always enabled (test frontend)');
    
    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();
    
    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 = [
        {
            "field": "category_keyword",
            "size": 15,
            "type": "terms"
        },
        {
            "field": "vendor_keyword",
            "size": 15,
            "type": "terms"
        },
        {
            "field": "tags_keyword",
            "size": 10,
            "type": "terms"
        },
        {
            "field": "min_price",
            "type": "range",
            "ranges": [
                {"key": "0-50", "to": 50},
                {"key": "50-100", "from": 50, "to": 100},
                {"key": "100-200", "from": 100, "to": 200},
                {"key": "200+", "from": 200}
            ]
        }
    ];
    
    // 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,
                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((product) => {
                const score = product.relevance_score;
        html += `
            <div class="product-card">
                <div class="product-image-wrapper">
                    ${product.image_url ? `
                        <img src="${escapeHtml(product.image_url)}" 
                             alt="${escapeHtml(product.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">
                    ${product.price ? `$${product.price.toFixed(2)}` : 'N/A'}${product.compare_at_price && product.compare_at_price > product.price ? `<span style="text-decoration: line-through; color: #999; font-size: 0.9em; margin-left: 8px;">$${product.compare_at_price.toFixed(2)}</span>` : ''}
                </div>
                
                <div class="product-stock">
                    ${product.in_stock ? '<span style="color: green;">In Stock</span>' : '<span style="color: red;">Out of Stock</span>'}
                    ${product.variants && product.variants.length > 0 ? `<span style="color: #666; font-size: 0.9em;">(${product.variants.length} variants)</span>` : ''}
                </div>
                
                                                <div class="product-title">
                    ${escapeHtml(product.title || 'N/A')}
                </div>
                
                <div class="product-meta">${product.vendor ? escapeHtml(product.vendor) : ''}${product.product_type ? ' | ' + escapeHtml(product.product_type) : ''}${product.category ? ' | ' + escapeHtml(product.category) : ''}                ${product.tags ? `
                    <div class="product-tags">
                        Tags: ${escapeHtml(product.tags)}
                    </div>
                ` : ''}
            </div>
        `;
    });
    
    grid.innerHTML = html;
}

// Display facets as filter tags (重构版 - 标准化格式)
function displayFacets(facets) {
    if (!facets) return;
    
    facets.forEach(facet => {
        // 根据字段名找到对应的容器
        let containerId = null;
        let maxDisplay = 10;
        
        if (facet.field === 'category_keyword') {
            containerId = 'categoryTags';
            maxDisplay = 10;
        } else if (facet.field === 'vendor_keyword') {
            containerId = 'brandTags';
            maxDisplay = 10;
        } else if (facet.field === 'tags_keyword') {
            containerId = 'supplierTags';
            maxDisplay = 8;
        }
        
        if (!containerId) return;
        
        const container = document.getElementById(containerId);
        if (!container) return;
        
        let html = '';
        
        // 渲染分面值
        facet.values.slice(0, maxDisplay).forEach(facetValue => {
            const value = facetValue.value;
            const count = facetValue.count;
            const selected = facetValue.selected;
            
            html += `
                <span class="filter-tag ${selected ? 'active' : ''}" 
                      onclick="toggleFilter('${escapeAttr(facet.field)}', '${escapeAttr(value)}')">
                    ${escapeHtml(value)} (${count})
                </span>
            `;
        });
        
        container.innerHTML = html;
    });
}

// Toggle filter
function toggleFilter(field, value) {
    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.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.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()} products 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(JSON.stringify(debugInfo.es_query, null, 2))}</pre>`;
        html += '</div>';
    }
    
    html += '</div>';
    debugInfoDiv.innerHTML = html;
}

// 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, '&quot;');
}

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;
}