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 testCategory140() { console.log('Testing Category 140 (AI Assistants) 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 = 140; // AI Assistants // 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 news items directly from the database console.log('\n2. Checking news items in the database...'); // Direct news items const { data: directNews, error: directNewsError } = await supabase .from('news') .select('id, title, published') .eq('category_id', categoryId) .eq('published', true); if (directNewsError) { console.error('Error fetching direct news:', directNewsError); } else { console.log(`Found ${directNews?.length || 0} news items directly linked to category ${categoryId}:`); directNews?.forEach(item => { console.log(`- ${item.title} (ID: ${item.id})`); }); } // Junction table news items console.log('\n3. Checking news_categories junction table...'); const { data: junctionData, error: junctionError } = await supabase .from('news_categories') .select('news_id, category_id') .eq('category_id', categoryId); if (junctionError) { console.error('Error fetching junction data:', junctionError); } else { console.log(`Found ${junctionData?.length || 0} entries in news_categories for category ${categoryId}`); if (junctionData && junctionData.length > 0) { // Get details of these news items const newsIds = junctionData.map(item => item.news_id); const { data: junctionNews, error: junctionNewsError } = await supabase .from('news') .select('id, title, published') .in('id', newsIds) .eq('published', true); if (junctionNewsError) { console.error('Error fetching news items from junction:', junctionNewsError); } else { console.log(`Found ${junctionNews?.length || 0} published news items via junction table:`); junctionNews?.forEach(item => { console.log(`- ${item.title} (ID: ${item.id})`); }); } } } // Now also get details about tools console.log('\n2a. Checking tools associated with the category...'); // Direct tools const { data: directTools, error: directToolsError } = await supabase .from('tools') .select('id, name, published') .eq('category_id', categoryId) .eq('published', true); 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})`); }); } // Junction table tools console.log('\n2b. Checking tools_categories junction table...'); 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(`Found ${toolsJunctionData?.length || 0} entries in tools_categories for category ${categoryId}`); if (toolsJunctionData && toolsJunctionData.length > 0) { // Get details of these tools const toolIds = toolsJunctionData.map(item => item.tool_id); 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 tools items from junction:', junctionToolsError); } else { console.log(`Found ${junctionTools?.length || 0} published tools via junction table:`); junctionTools?.forEach(item => { console.log(`- ${item.name} (ID: ${item.id})`); }); } } } // 3. Fetch from API and check counts console.log('\n4. 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)); // 4. Detailed verification of counts console.log('\n5. Verifying counts...'); // Count tools via junction table (that are published) let publishedToolsJunctionCount = 0; const { data: publishedTools } = await supabase .from('tools') .select('id') .eq('published', true); if (publishedTools && publishedTools.length > 0) { const publishedToolIds = publishedTools.map(item => item.id); const { count, error } = await supabase .from('tools_categories') .select('*', { count: 'exact', head: true }) .eq('category_id', categoryId) .in('tool_id', publishedToolIds); if (!error) { publishedToolsJunctionCount = count || 0; } } console.log(`Published tools via junction table: ${publishedToolsJunctionCount}`); console.log(`API tools_count: ${apiCategory.tools_count}`); if (publishedToolsJunctionCount === apiCategory.tools_count) { console.log('✅ Tool counts match!'); } else { console.log('❌ Tool counts do not match!'); } // Count news via junction table (that are published) let publishedJunctionNewsCount = 0; const { data: publishedNews } = await supabase .from('news') .select('id') .eq('published', true); if (publishedNews && publishedNews.length > 0) { const publishedNewsIds = publishedNews.map(item => item.id); const { count, error } = await supabase .from('news_categories') .select('*', { count: 'exact', head: true }) .eq('category_id', categoryId) .in('news_id', publishedNewsIds); if (!error) { publishedJunctionNewsCount = count || 0; } } console.log(`Published news via junction table: ${publishedJunctionNewsCount}`); console.log(`API news_count: ${apiCategory.news_count}`); if (publishedJunctionNewsCount === apiCategory.news_count) { console.log('✅ Counts match!'); } else { console.log('❌ Counts do not match!'); } } catch (error) { console.error('Error during testing:', error); } } // Run the function testCategory140() .then(() => { console.log('Testing completed'); process.exit(0); }) .catch((error) => { console.error('Testing failed:', error); process.exit(1); });