← back to Wine Finder

test-search.js

132 lines

const puppeteer = require('puppeteer');

async function testWineTracker() {
  console.log('🧪 Testing Wine Tracker...\n');

  const browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });

  try {
    const page = await browser.newPage();

    // Enable console logging from page
    page.on('console', msg => {
      if (msg.type() === 'error') {
        console.log('❌ Browser Error:', msg.text());
      }
    });

    // Navigate to Wine Tracker
    console.log('1️⃣  Navigating to http://localhost:9222...');
    await page.goto('http://localhost:9222', { waitUntil: 'networkidle0', timeout: 10000 });

    // Check if redirected to login
    const url = page.url();
    console.log('   Current URL:', url);

    if (url.includes('/login')) {
      console.log('2️⃣  Logging in...');
      await page.waitForSelector('input[name="username"]', { timeout: 5000 });
      await page.type('input[name="username"]', 'admin');
      await page.type('input[name="password"]', '2025');
      await page.click('button[type="submit"]');

      await Promise.race([
        page.waitForNavigation({ waitUntil: 'networkidle0', timeout: 10000 }),
        page.waitForSelector('#searchInput', { timeout: 10000 })
      ]);

      const finalUrl = page.url();
      console.log('   ✅ Logged in successfully - now at:', finalUrl);
    }

    // Wait for search input
    console.log('3️⃣  Waiting for search interface...');
    await page.waitForSelector('#searchInput', { timeout: 5000 });
    console.log('   ✅ Search interface loaded');

    // Check source checkboxes
    const checkboxes = await page.$$('.source-checkbox input[type="checkbox"]');
    console.log(`   📦 Found ${checkboxes.length} source checkboxes`);

    // Uncheck K&L (blocked), keep Vivino and Total Wine
    console.log('4️⃣  Configuring sources (unchecking K&L)...');
    await page.evaluate(() => {
      document.getElementById('sourceKL').checked = false;
      document.getElementById('sourceVivino').checked = true;
      document.getElementById('sourceTotalWine').checked = true;
    });

    // Type search query
    console.log('5️⃣  Searching for "Pinot Noir"...');
    await page.type('#searchInput', 'Pinot Noir');

    // Click search button
    await page.click('#searchBtn');

    // Wait for results or error
    console.log('6️⃣  Waiting for results...');

    try {
      // Wait for either results or error
      await Promise.race([
        page.waitForSelector('#resultsTable .wine-item', { timeout: 30000 }),
        page.waitForSelector('.error-notification', { timeout: 30000 }),
        page.waitForSelector('#noResults', { visible: true, timeout: 30000 })
      ]);

      // Check what we got
      const hasResults = await page.$('#resultsTable .wine-item');
      const hasError = await page.$('.error-notification');
      const noResults = await page.$eval('#noResults', el => el.style.display !== 'none').catch(() => false);

      if (hasError) {
        const errorText = await page.$eval('.error-notification', el => el.textContent);
        console.log('\n❌ ERROR DISPLAYED:');
        console.log(errorText);
      } else if (hasResults) {
        const wineCount = await page.$$eval('#resultsTable .wine-item', items => items.length);
        console.log(`\n✅ SUCCESS! Found ${wineCount} wines`);

        // Get first few wine names
        const wines = await page.$$eval('#resultsTable .wine-item', items =>
          items.slice(0, 5).map(item => ({
            name: item.querySelector('.wine-name')?.textContent || 'Unknown',
            price: item.querySelector('.wine-price')?.textContent || 'N/A',
            source: item.querySelector('.wine-detail-item span:last-child')?.textContent || 'Unknown'
          }))
        );

        console.log('\n📋 Sample Results:');
        wines.forEach((wine, i) => {
          console.log(`   ${i + 1}. ${wine.name}`);
          console.log(`      Price: ${wine.price}`);
          console.log(`      Source: ${wine.source}`);
        });
      } else if (noResults) {
        console.log('\n⚠️  No results found');
      }

    } catch (err) {
      console.log('\n❌ TIMEOUT: No results after 30 seconds');
      console.log('Error:', err.message);

      // Capture any console errors
      const logs = await page.evaluate(() => {
        return window.localStorage.getItem('debug-logs') || 'No logs';
      });
      console.log('Page logs:', logs);
    }

  } catch (error) {
    console.log('\n❌ TEST FAILED:');
    console.log(error.message);
  } finally {
    await browser.close();
  }
}

testWineTracker().catch(console.error);