← back to Wine Finder

setup-google-sheets.js

181 lines

const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function question(query) {
  return new Promise(resolve => rl.question(query, resolve));
}

async function setupGoogleSheets() {
  console.log('\n🍷 Red Thunder Wine Tracker - Google Sheets Setup\n');
  console.log('This script will help you set up Google Sheets integration.\n');

  const email = await question('Enter your Google account email (steve@designerwallcoverings.com): ');
  const password = await question('Enter your Google account password: ');

  console.log('\n🚀 Launching browser...\n');

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

  const page = await browser.newPage();
  await page.setViewport({ width: 1280, height: 800 });

  try {
    console.log('📝 Step 1: Creating Google Sheet...\n');

    // Go to Google Sheets
    await page.goto('https://sheets.google.com', { waitUntil: 'networkidle2' });

    // Check if we need to login
    const currentUrl = page.url();
    if (currentUrl.includes('accounts.google.com')) {
      console.log('🔐 Logging into Google...\n');

      // Enter email
      await page.waitForSelector('input[type="email"]', { timeout: 10000 });
      await page.type('input[type="email"]', email);
      await page.click('#identifierNext');

      // Wait for password field
      await page.waitForSelector('input[type="password"]', { visible: true, timeout: 10000 });
      await page.type('input[type="password"]', password);
      await page.click('#passwordNext');

      // Wait for navigation after login
      await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 30000 });

      console.log('✅ Logged in successfully!\n');
    }

    // Create new blank spreadsheet
    console.log('Creating new spreadsheet...\n');
    await page.goto('https://docs.google.com/spreadsheets/create', { waitUntil: 'networkidle2' });
    await page.waitForTimeout(3000);

    // Rename the sheet
    await page.waitForSelector('input[aria-label*="Rename"]', { timeout: 10000 });
    await page.click('input[aria-label*="Rename"]');
    await page.keyboard.selectAll();
    await page.type('input[aria-label*="Rename"]', 'Red Thunder Wine Tracker');
    await page.keyboard.press('Enter');
    await page.waitForTimeout(2000);

    // Get Sheet ID from URL
    const sheetUrl = page.url();
    const sheetIdMatch = sheetUrl.match(/\/d\/([a-zA-Z0-9-_]+)/);
    const sheetId = sheetIdMatch ? sheetIdMatch[1] : null;

    if (!sheetId) {
      throw new Error('Could not extract Sheet ID from URL');
    }

    console.log('✅ Sheet created successfully!');
    console.log(`📊 Sheet ID: ${sheetId}\n`);

    // Now go to Google Cloud Console
    console.log('📝 Step 2: Setting up Google Cloud Service Account...\n');

    await page.goto('https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts', {
      waitUntil: 'networkidle2',
      timeout: 60000
    });

    await page.waitForTimeout(3000);

    console.log('Please follow these manual steps in the browser:\n');
    console.log('1. Select or create a project (e.g., "Wine Tracker")');
    console.log('2. Click "CREATE SERVICE ACCOUNT"');
    console.log('3. Name: "wine-tracker-service"');
    console.log('4. Click "CREATE AND CONTINUE"');
    console.log('5. Skip optional steps and click "DONE"');
    console.log('6. Click on the service account email');
    console.log('7. Go to "KEYS" tab');
    console.log('8. Click "ADD KEY" → "Create new key"');
    console.log('9. Select JSON and click "CREATE"');
    console.log('10. Save the downloaded JSON file as: /root/DW-MCP/google-sheets-credentials.json');
    console.log('\nAlso enable Google Sheets API:');
    console.log('https://console.cloud.google.com/apis/library/sheets.googleapis.com\n');

    await question('Press Enter when you have downloaded the credentials JSON file...');

    // Check if credentials file exists
    const credsPath = '/root/DW-MCP/google-sheets-credentials.json';
    if (fs.existsSync(credsPath)) {
      const creds = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
      const serviceEmail = creds.client_email;

      console.log(`\n✅ Credentials file found!`);
      console.log(`📧 Service account email: ${serviceEmail}\n`);

      // Now share the sheet with service account
      console.log('📝 Step 3: Sharing sheet with service account...\n');

      await page.goto(`https://docs.google.com/spreadsheets/d/${sheetId}/edit`, {
        waitUntil: 'networkidle2'
      });
      await page.waitForTimeout(2000);

      // Click Share button
      await page.waitForSelector('button[aria-label*="Share"]', { timeout: 10000 });
      await page.click('button[aria-label*="Share"]');
      await page.waitForTimeout(1000);

      // Enter service account email
      const shareInput = await page.waitForSelector('input[aria-label*="Add people"]', { timeout: 10000 });
      await shareInput.type(serviceEmail);
      await page.waitForTimeout(1000);

      // Press Enter to add
      await page.keyboard.press('Enter');
      await page.waitForTimeout(1000);

      // Click Send/Done
      await page.click('button[name="ok"]');
      await page.waitForTimeout(2000);

      console.log('✅ Sheet shared with service account!\n');

      // Update .env file
      console.log('📝 Step 4: Updating configuration...\n');

      const envPath = '/root/WebsitesMisc/WineFinder/.env';
      let envContent = fs.readFileSync(envPath, 'utf8');
      envContent = envContent.replace(
        /GOOGLE_SHEET_ID=.*/,
        `GOOGLE_SHEET_ID=${sheetId}`
      );
      fs.writeFileSync(envPath, envContent);

      console.log('✅ Configuration updated!\n');
      console.log('🎉 Setup Complete!\n');
      console.log('Sheet URL: ' + sheetUrl);
      console.log('Sheet ID: ' + sheetId);
      console.log('Service Account: ' + serviceEmail);
      console.log('\nRestart the Wine Tracker application to use the new configuration.\n');

    } else {
      console.log('\n❌ Credentials file not found at: ' + credsPath);
      console.log('Please save the downloaded JSON file to that location.\n');
    }

  } catch (error) {
    console.error('Error during setup:', error.message);
    console.log('\nPlease complete the setup manually following the instructions in SETUP.md\n');
  }

  await question('Press Enter to close browser...');
  await browser.close();
  rl.close();
}

setupGoogleSheets().catch(console.error);