/* Dashboard V2 page interactions extracted from dashboard_v2.html. */ let priceChartInstance = null; let activeHistoryRange = 'month'; let currentHistoryProductId = null; let currentHistoryProductName = ''; let dashboardChartLoader = null; function getCSRFToken() { return document.querySelector('meta[name="csrf-token"]').getAttribute('content'); } function formatPriceTick(value) { return '$' + Number(value || 0).toLocaleString(); } function setHistoryChartState(message, showCanvas = false) { const state = document.getElementById('historyChartState'); const canvas = document.getElementById('priceChart'); if (!state || !canvas) return; state.textContent = message; state.classList.toggle('is-hidden', showCanvas); canvas.classList.toggle('is-hidden', !showCanvas); } function destroyHistoryChart() { if (priceChartInstance) { priceChartInstance.destroy(); priceChartInstance = null; } } function ensureDashboardChart() { if (window.EwoooCChartTheme && window.EwoooCChartTheme.loadChartJs) { return window.EwoooCChartTheme.loadChartJs(); } if (typeof Chart !== 'undefined') { return Promise.resolve(window.Chart); } if (dashboardChartLoader) { return dashboardChartLoader; } dashboardChartLoader = new Promise((resolve, reject) => { const existing = document.querySelector('script[data-chartjs-loader="dashboard"]'); if (existing) { existing.addEventListener('load', () => resolve(window.Chart), { once: true }); existing.addEventListener('error', () => reject(new Error('Chart.js 載入失敗')), { once: true }); return; } const script = document.createElement('script'); script.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js'; script.async = true; script.dataset.chartjsLoader = 'dashboard'; script.onload = () => resolve(window.Chart); script.onerror = () => reject(new Error('Chart.js 載入失敗')); document.head.appendChild(script); }); return dashboardChartLoader; } function updateHistoryRangeButtons() { document.querySelectorAll('[data-history-range]').forEach(button => { button.classList.toggle('is-active', button.dataset.historyRange === activeHistoryRange); }); } function showHistory(productId, productName, range = activeHistoryRange) { const modalEl = document.getElementById('historyModal'); const title = document.getElementById('historyModalLabel'); const subtitle = document.getElementById('historyModalSubtitle'); const canvas = document.getElementById('priceChart'); if (!modalEl || !title || !subtitle || !canvas) return; currentHistoryProductId = productId; currentHistoryProductName = productName || '歷史價格走勢'; activeHistoryRange = range; updateHistoryRangeButtons(); title.textContent = productName || '歷史價格走勢'; subtitle.textContent = `商品 ID ${productId} · 讀取真實價格紀錄`; destroyHistoryChart(); setHistoryChartState('載入價格歷史中...'); const modal = bootstrap.Modal.getOrCreateInstance(modalEl); modal.show(); ensureDashboardChart() .then(() => fetch(`/api/history/${productId}?range=${activeHistoryRange}&format=v2`)) .then(response => { if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); }) .then(data => { const series = Array.isArray(data) ? { momo: data, pchome: [] } : (data.series || {}); const momoPoints = Array.isArray(series.momo) ? series.momo : (Array.isArray(data.data) ? data.data : []); const pchomePoints = Array.isArray(series.pchome) ? series.pchome : []; const rangeLabel = Array.isArray(data) ? '' : (data.range_label || ''); if (rangeLabel) { const pchomeNote = pchomePoints.length > 0 ? ' · 含 PChome 歷史快照' : ''; subtitle.textContent = `商品 ID ${productId} · ${rangeLabel}真實價格紀錄${pchomeNote}`; } if (momoPoints.length === 0 && pchomePoints.length === 0) { setHistoryChartState('目前沒有可顯示的歷史價格紀錄。'); return; } setHistoryChartState('', true); const ctx = canvas.getContext('2d'); const momoGradient = ctx.createLinearGradient(0, 0, 0, 380); momoGradient.addColorStop(0, 'rgba(190, 106, 45, 0.26)'); momoGradient.addColorStop(1, 'rgba(190, 106, 45, 0.04)'); const pchomeGradient = ctx.createLinearGradient(0, 0, 0, 380); pchomeGradient.addColorStop(0, 'rgba(70, 127, 181, 0.18)'); pchomeGradient.addColorStop(1, 'rgba(70, 127, 181, 0.03)'); const labels = Array.from(new Set([ ...momoPoints.map(point => point.t), ...pchomePoints.map(point => point.t) ])).sort(); const toPriceMap = points => points.reduce((acc, point) => { acc[point.t] = point.p; return acc; }, {}); const momoMap = toPriceMap(momoPoints); const pchomeMap = toPriceMap(pchomePoints); const datasets = [{ label: 'MOMO', data: labels.map(label => momoMap[label] ?? null), borderColor: '#be6a2d', backgroundColor: momoGradient, borderWidth: 3, fill: true, tension: 0.35, spanGaps: true, pointRadius: 3, pointHoverRadius: 7, pointBackgroundColor: '#be6a2d', pointBorderColor: '#fff', pointBorderWidth: 2 }]; if (pchomePoints.length > 0) { datasets.push({ label: 'PChome', data: labels.map(label => pchomeMap[label] ?? null), borderColor: '#467fb5', backgroundColor: pchomeGradient, borderWidth: 2, fill: false, tension: 0.28, spanGaps: true, pointRadius: 3, pointHoverRadius: 7, pointBackgroundColor: '#467fb5', pointBorderColor: '#fff', pointBorderWidth: 2 }); } priceChartInstance = new Chart(ctx, { type: 'line', data: { labels, datasets }, options: { responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { display: pchomePoints.length > 0, labels: { color: '#6d604f', usePointStyle: true, boxWidth: 8, boxHeight: 8 } }, tooltip: { backgroundColor: 'rgba(55, 45, 35, 0.94)', titleColor: '#faf7f0', bodyColor: '#faf7f0', borderColor: '#be6a2d', borderWidth: 1, displayColors: true, padding: 12, callbacks: { label: context => `${context.dataset.label} ${formatPriceTick(context.parsed.y)}` } } }, scales: { y: { beginAtZero: false, grid: { color: 'rgba(71, 61, 49, 0.08)' }, ticks: { color: '#7f715f', callback: formatPriceTick } }, x: { grid: { display: false }, ticks: { color: '#9b8a77', maxRotation: 0, autoSkip: true, maxTicksLimit: 8 } } } } }); }) .catch(error => { console.error('圖表載入失敗:', error); setHistoryChartState('價格歷史載入失敗,請稍後再試。'); }); } document.querySelectorAll('.dashboard-table tbody tr[data-product-id]').forEach(row => { row.addEventListener('click', event => { if (event.target.closest('a')) return; showHistory(row.dataset.productId, row.dataset.productName); }); }); document.querySelectorAll('[data-history-trigger]').forEach(button => { button.addEventListener('click', event => { event.stopPropagation(); showHistory(button.dataset.productId, button.dataset.productName); }); }); document.querySelectorAll('[data-history-range]').forEach(button => { button.addEventListener('click', () => { if (!currentHistoryProductId) return; showHistory(currentHistoryProductId, currentHistoryProductName, button.dataset.historyRange); }); }); document.querySelectorAll('[data-dashboard-auto-submit]').forEach(select => { select.addEventListener('change', () => { if (select.form) { select.form.submit(); } }); }); const dashboardTaskMap = { crawler: { confirmText: '確定要手動執行全站爬蟲嗎?可能需要一段時間。', url: '/api/run_task' }, notification: { confirmText: '確定要發送今日商品異動通知嗎?', url: '/api/trigger_momo_notification' } }; function runDashboardTask(taskName) { const task = dashboardTaskMap[taskName]; if (!task || !confirm(task.confirmText)) return; fetch(task.url, { method: 'POST', headers: { 'X-CSRFToken': getCSRFToken() } }) .then(response => response.json()) .then(data => alert(data.message)) .catch(error => alert('錯誤: ' + error)); } document.querySelectorAll('[data-dashboard-task]').forEach(button => { button.addEventListener('click', () => runDashboardTask(button.dataset.dashboardTask)); }); function trackMomoLinkClick(event) { const link = event.target.closest('.momo-tracked-link'); if (!link) { return; } const href = link.getAttribute('href') || ''; const originalHref = link.dataset.momoOriginalUrl || href; if (!href || href === '#') { return; } const isBlocked = isBlockedMomoUrl(href); const payload = { url: originalHref, page: location.pathname, source: link.dataset.trackSource || 'unknown', platform: link.dataset.trackPlatform || 'momo', product_id: link.dataset.trackProductId || '', i_code: link.dataset.trackIcode || '', product_name: link.dataset.trackProductName || '', label: (link.textContent || '').trim(), effective_url: href }; if (isBlocked) { console.warn('[DashboardV2] 嘗試打開 MOMO 404 網址', payload); event.preventDefault(); const fallbackUrl = link.dataset.momoFallbackUrl || getSafeMomoFallbackUrl(link); if (fallbackUrl && fallbackUrl !== '#' && fallbackUrl !== href) { link.dataset.momoFallbackUrl = fallbackUrl; link.setAttribute('href', fallbackUrl); payload.effective_url = fallbackUrl; openMomoUrl(link, fallbackUrl); fetch('/api/track_momo_link', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCSRFToken() }, body: JSON.stringify(payload) }).catch(() => {}); return; } } fetch('/api/track_momo_link', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCSRFToken() }, body: JSON.stringify(payload) }).catch(() => {}); } function getSafeMomoFallbackUrl(link) { const iCode = (link.dataset.trackIcode || link.dataset.trackProductId || '').trim(); if (!isLikelyMomoProductCode(iCode)) { return '#'; } return `https://www.momoshop.com.tw/goods/GoodsDetail.jsp?i_code=${encodeURIComponent(iCode)}`; } function openMomoUrl(link, url) { if (!url || url === '#') { return; } const target = (link.getAttribute('target') || '_self').toLowerCase(); if (target === '_blank') { window.open(url, '_blank', 'noopener,noreferrer'); return; } if (target === '_self' || target === '') { window.location.href = url; return; } window.open(url, target); } function isBlockedMomoUrl(url) { const lowered = (url || '').toLowerCase(); if (lowered.includes('EC404.html') || lowered.includes('ec404')) { return true; } try { const parsed = new URL(url, location.origin); const path = (parsed.pathname || '').toLowerCase(); if (!path.includes('goodsdetail')) { return false; } const code = (parsed.searchParams.get('i_code') || '').trim(); if (code) { return !isLikelyMomoProductCode(code); } return !/\/goodsdetail\/[^/?#]+/i.test(path); } catch (error) { if (!/goodsdetail\.jsp/i.test(lowered)) { return false; } const hasCode = /[?&]i_code=([^&#]+)/i.test(lowered); if (!hasCode) { return true; } const match = /[?&]i_code=([^&#]+)/i.exec(lowered); const code = match ? (match[1] || '').trim() : ''; return !isLikelyMomoProductCode(code); } } function isLikelyMomoProductCode(value) { const cleaned = (value || '').trim(); if (!cleaned) { return false; } const lowered = cleaned.toLowerCase(); if (lowered === 'nan' || lowered === 'none' || lowered === 'null' || lowered === 'undefined') { return false; } if (lowered.startsWith('momo_') || lowered.startsWith('manual_') || lowered.startsWith('pchome_')) { return false; } return /^[A-Za-z0-9_-]{4,}$/.test(cleaned); } document.addEventListener('click', trackMomoLinkClick);