import fetch from 'node-fetch'; import { createClient } from '@supabase/supabase-js'; import * as dotenv from 'dotenv'; import * as path from 'path'; import * as fs from 'fs'; // Load environment variables const envLocalPath = path.resolve(process.cwd(), '../.env.local'); if (fs.existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); dotenv.config(); // Try loading from default .env } async function testCategory61() { console.log('Testing Category 61 (LLMs) counts...'); // Initialize Supabase client for direct database verification const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseKey) { console.error('Missing Supabase environment variables. Add NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY to .env.local'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseKey); const categoryId = 61; // LLMs // Adjust URL based on your local development setup const baseUrl = 'http://localhost:3000'; try { // 1. Check category details directly from the database console.log('\n1. Checking category details in the database...'); const { data: categoryData, error: categoryError } = await supabase .from('categories') .select('*') .eq('id', categoryId) .single(); if (categoryError) { console.error('Error fetching category:', categoryError); return; } console.log('Category in database:'); console.log(categoryData); // 2. Check all tools in the database that have category_id = 61 console.log('\n2a. Checking tools directly linked to category ID 61...'); const { data: directTools, error: directToolsError } = await supabase .from('tools') .select('id, name, published, category_id') .eq('category_id', categoryId); if (directToolsError) { console.error('Error fetching direct tools:', directToolsError); } else { console.log(`Found ${directTools?.length || 0} tools directly linked to category ${categoryId}:`); directTools?.forEach(item => { console.log(`- ${item.name} (ID: ${item.id}, Published: ${item.published})`); }); } // 3. Check the tools_categories junction table console.log('\n2b. Checking tools_categories junction table...'); // Debug: Log all entries in the tools_categories table const { data: allToolsCategories, error: allToolsCategoriesError } = await supabase .from('tools_categories') .select('*') .limit(10); if (allToolsCategoriesError) { console.error('Error fetching tools_categories sample:', allToolsCategoriesError); } else { console.log(`Sample of tools_categories table (first 10 entries):`); console.log(allToolsCategories); // Check field names and types if (allToolsCategories && allToolsCategories.length > 0) { console.log('Field names:', Object.keys(allToolsCategories[0])); console.log('tool_id type:', typeof allToolsCategories[0].tool_id); console.log('category_id type:', typeof allToolsCategories[0].category_id); } } // Now check entries specifically for category 61 const { data: toolsJunctionData, error: toolsJunctionError } = await supabase .from('tools_categories') .select('tool_id, category_id') .eq('category_id', categoryId); if (toolsJunctionError) { console.error('Error fetching tools junction data:', toolsJunctionError); } else { console.log(`\nFound ${toolsJunctionData?.length || 0} entries in tools_categories for category ${categoryId}`); if (toolsJunctionData && toolsJunctionData.length > 0) { console.log('Raw junction entries:'); toolsJunctionData.forEach(item => { console.log(`- tool_id: ${item.tool_id}, category_id: ${item.category_id}`); }); // Get details of these tools const toolIds = toolsJunctionData.map(item => item.tool_id); console.log(`\nTool IDs from junction: [${toolIds.join(', ')}]`); // Get all tools regardless of published status to see what's there const { data: allJunctionTools, error: allJunctionToolsError } = await supabase .from('tools') .select('id, name, published') .in('id', toolIds); if (allJunctionToolsError) { console.error('Error fetching all tools from junction:', allJunctionToolsError); } else { console.log(`\nAll tools found via junction table (${allJunctionTools?.length || 0}):`); allJunctionTools?.forEach(item => { console.log(`- ${item.name} (ID: ${item.id}, Published: ${item.published})`); }); } // Get only published tools const { data: junctionTools, error: junctionToolsError } = await supabase .from('tools') .select('id, name, published') .in('id', toolIds) .eq('published', true); if (junctionToolsError) { console.error('Error fetching published tools from junction:', junctionToolsError); } else { console.log(`\nPublished tools found via junction table (${junctionTools?.length || 0}):`); junctionTools?.forEach(item => { console.log(`- ${item.name} (ID: ${item.id}, Published: ${item.published})`); }); } } } // 4. Fetch from API and check counts console.log('\n3. Fetching from categories API...'); const response = await fetch(`${baseUrl}/api/categories`); if (!response.ok) { throw new Error(`API request failed with status ${response.status}`); } interface Category { id: number; name: string; slug: string; icon: string; description: string; tools_count: number; news_count: number; learning_count: number; posts_count: number; total_count: number; [key: string]: any; } const categories = await response.json() as Category[]; const apiCategory = categories.find((c: Category) => c.id === categoryId); if (!apiCategory) { console.error('Category not found in API response'); return; } console.log('Category from API:'); console.log(JSON.stringify(apiCategory, null, 2)); // 5. Verify our ID comparison logic - Type conversion test console.log('\n4. Testing ID comparison logic...'); // Get first few tools entries to test const { data: testTools } = await supabase .from('tools') .select('id') .limit(5); // Get first few tools_categories entries const { data: testJunctions } = await supabase .from('tools_categories') .select('tool_id, category_id') .limit(5); if (testTools && testTools.length > 0 && testJunctions && testJunctions.length > 0) { console.log('Sample tool ID:', testTools[0].id, 'Type:', typeof testTools[0].id); console.log('Sample junction tool_id:', testJunctions[0].tool_id, 'Type:', typeof testJunctions[0].tool_id); const toolIdSet = new Set(testTools.map(t => t.id)); // Test if we can find a match const matchFound = testJunctions.some(j => toolIdSet.has(j.tool_id)); console.log('Match test using Set: ', matchFound); // Test with explicit comparison for first items console.log('Direct comparison:', testTools[0].id === testJunctions[0].tool_id); console.log('String comparison:', String(testTools[0].id) === String(testJunctions[0].tool_id)); console.log('Number comparison:', Number(testTools[0].id) === Number(testJunctions[0].tool_id)); } // 6. Calculate what counts should be from database data console.log('\n5. Computing expected counts directly...'); // Get all published tools const { data: allPublishedTools } = await supabase .from('tools') .select('id') .eq('published', true); // Get all junction entries for this category const { data: allCategoryJunctions } = await supabase .from('tools_categories') .select('tool_id') .eq('category_id', categoryId); if (allPublishedTools && allCategoryJunctions) { const publishedToolIds = new Set(allPublishedTools.map(t => t.id)); const junctionToolIds = allCategoryJunctions.map(j => j.tool_id); // Count how many junction entries match published tools const expectedCount = junctionToolIds.filter(id => publishedToolIds.has(id)).length; console.log(`Expected tools count: ${expectedCount}`); console.log(`API tools_count: ${apiCategory.tools_count}`); if (expectedCount === apiCategory.tools_count) { console.log('✅ Counts match expected value!'); } else { console.log('❌ Counts do not match expected value!'); // Show differences console.log('\nDetailed analysis:'); console.log(`Number of published tools: ${publishedToolIds.size}`); console.log(`Number of junction entries for category ${categoryId}: ${junctionToolIds.length}`); // Find the specific tool IDs that should be counted const matchingIds = junctionToolIds.filter(id => publishedToolIds.has(id)); console.log(`Tool IDs that should be counted: [${matchingIds.join(', ')}]`); // Get details for these tools if (matchingIds.length > 0) { const { data: matchingTools } = await supabase .from('tools') .select('id, name, published') .in('id', matchingIds); console.log('Tools that should be counted:'); matchingTools?.forEach(tool => { console.log(`- ${tool.name} (ID: ${tool.id}, Published: ${tool.published})`); }); } } } } catch (error) { console.error('Error during testing:', error); } } // Run the function testCategory61() .then(() => { console.log('Testing completed'); process.exit(0); }) .catch((error) => { console.error('Testing failed:', error); process.exit(1); });