← back to Designer Wallcoverings

DW-Agents/dw-agents/amazon-order-fetcher.ts

182 lines

/**
 * Amazon Order Fetcher
 * Fetches real order history from Amazon accounts
 */

import fetch from 'node-fetch';
import * as cheerio from 'cheerio';

interface AmazonOrder {
  id: string;
  item: string;
  vendor: string;
  price: number;
  status: string;
  timestamp: Date;
  orderUrl?: string;
}

interface AmazonCredentials {
  email: string;
  password: string;
  type: 'Personal' | 'Business';
}

const PERSONAL_ACCOUNT: AmazonCredentials = {
  email: 'nataliaabrams@gmail.com',
  password: 'Urbanon341',
  type: 'Personal'
};

const BUSINESS_ACCOUNT: AmazonCredentials = {
  email: 'info@designerwallcoverings.com',
  password: '*Amazonaccess911*',
  type: 'Business'
};

/**
 * Fetch orders from Amazon using cookie-based authentication
 */
async function fetchAmazonOrders(credentials: AmazonCredentials, limit: number = 50): Promise<AmazonOrder[]> {
  try {
    console.log(`🔍 Fetching ${credentials.type} orders for ${credentials.email}...`);

    // Amazon order history URL
    const orderUrl = 'https://www.amazon.com/gp/your-account/order-history';

    // For now, we'll use a simpler approach with their order history API
    // This would need proper session handling in production

    // Placeholder for real implementation
    // In production, you would:
    // 1. Login to Amazon with credentials
    // 2. Get session cookie
    // 3. Fetch order history page
    // 4. Parse HTML with cheerio
    // 5. Extract order details

    return [];

  } catch (error) {
    console.error(`❌ Error fetching ${credentials.type} orders:`, error);
    return [];
  }
}

/**
 * Search Amazon for product prices
 */
async function searchAmazonPrice(productName: string, accountType: 'Personal' | 'Business' = 'Personal'): Promise<any> {
  try {
    console.log(`🔍 Searching Amazon ${accountType} for: ${productName}`);

    // Encode search query
    const searchQuery = encodeURIComponent(productName);
    const searchUrl = `https://www.amazon.com/s?k=${searchQuery}`;

    // Fetch search results
    const response = await fetch(searchUrl, {
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.5',
      }
    });

    const html = await response.text();
    const $ = cheerio.load(html);

    const results: any[] = [];

    // Parse product listings
    $('div[data-component-type="s-search-result"]').each((idx, element) => {
      if (idx >= 5) return; // Limit to top 5 results

      const title = $(element).find('h2 a span').text().trim();
      const priceWhole = $(element).find('.a-price-whole').first().text().replace(/[^0-9]/g, '');
      const priceFraction = $(element).find('.a-price-fraction').first().text().replace(/[^0-9]/g, '');
      const rating = $(element).find('.a-icon-star-small .a-icon-alt').text().trim();
      const reviewCount = $(element).find('span[aria-label*="stars"]').parent().parent().find('span').last().text().trim();
      const productUrl = 'https://www.amazon.com' + $(element).find('h2 a').attr('href');

      if (title && priceWhole) {
        const price = parseFloat(`${priceWhole}.${priceFraction || '00'}`);

        results.push({
          title,
          price,
          rating,
          reviewCount,
          url: productUrl,
          accountType
        });
      }
    });

    return results;

  } catch (error) {
    console.error(`❌ Error searching Amazon:`, error);
    return [];
  }
}

/**
 * Fetch all orders from both accounts
 */
export async function fetchAllOrders(): Promise<AmazonOrder[]> {
  console.log('📦 Fetching orders from all Amazon accounts...\n');

  const personalOrders = await fetchAmazonOrders(PERSONAL_ACCOUNT);
  const businessOrders = await fetchAmazonOrders(BUSINESS_ACCOUNT);

  const allOrders = [...personalOrders, ...businessOrders];

  console.log(`\n✅ Total orders fetched: ${allOrders.length}`);
  console.log(`   - Personal: ${personalOrders.length}`);
  console.log(`   - Business: ${businessOrders.length}`);

  return allOrders.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
}

/**
 * Compare prices across accounts
 */
export async function comparePrices(productName: string): Promise<any> {
  console.log(`\n💰 Comparing prices for: ${productName}\n`);

  const [personalResults, businessResults] = await Promise.all([
    searchAmazonPrice(productName, 'Personal'),
    searchAmazonPrice(productName, 'Business')
  ]);

  return {
    personal: personalResults,
    business: businessResults,
    bestDeal: findBestDeal([...personalResults, ...businessResults])
  };
}

function findBestDeal(results: any[]): any {
  if (results.length === 0) return null;

  return results.reduce((best, current) => {
    if (!best || current.price < best.price) {
      return current;
    }
    return best;
  }, null);
}

// Test function
if (require.main === module) {
  (async () => {
    console.log('🧪 Testing Amazon Order Fetcher\n');

    // Test price search
    const priceComparison = await comparePrices('printer paper');
    console.log('\n📊 Price Comparison Results:');
    console.log(JSON.stringify(priceComparison, null, 2));
  })();
}