Branchwell

AI Resource Pro / website / scripts / test-seed-categories.ts

1import { createClient } from '@supabase/supabase-js';
2import * as dotenv from 'dotenv';
3import path from 'path';
4import { fileURLToPath } from 'url';
5import fs from 'fs';
6
7// Load environment variables from .env file
8const __filename = fileURLToPath(import.meta.url);
9const __dirname = path.dirname(__filename);
10dotenv.config({ path: path.resolve(__dirname, '../.env') });
11
12// Read the .env file directly as a fallback
13const envPath = path.resolve(__dirname, '../.env');
14const envContent = fs.readFileSync(envPath, 'utf8');
15const envVars = envContent.split('\n').reduce((acc, line) => {
16 const match = line.match(/^([^#=]+)=(.*)$/);
17 if (match) {
18 const key = match[1].trim();
19 const value = match[2].trim().replace(/^["']|["']$/g, ''); // Remove quotes if present
20 acc[key] = value;
21 }
22 return acc;
23}, {} as Record<string, string>);
24
25// Set environment variables if not already set
26if (!process.env.NEXT_PUBLIC_SUPABASE_URL) {
27 process.env.NEXT_PUBLIC_SUPABASE_URL = envVars.NEXT_PUBLIC_SUPABASE_URL;
28}
29if (!process.env.SUPABASE_SERVICE_ROLE_KEY) {
30 process.env.SUPABASE_SERVICE_ROLE_KEY = envVars.SUPABASE_SERVICE_ROLE_KEY;
31}
32
33// Create a Supabase client with the service role key
34const createServiceClient = () => {
35 const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || envVars.NEXT_PUBLIC_SUPABASE_URL;
36 const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || envVars.SUPABASE_SERVICE_ROLE_KEY;
37
38 if (!supabaseUrl || !supabaseServiceKey) {
39 console.error('Missing Supabase environment variables for service client.');
40 throw new Error('Missing Supabase environment variables for service client');
41 }
42
43 return createClient(supabaseUrl, supabaseServiceKey, {
44 auth: {
45 persistSession: false,
46 }
47 });
48};
49
50async function seedCategories() {
51 const supabase = createServiceClient();
52 console.log('Supabase client created successfully');
53
54 // Get categories from the JSON file
55 const categoriesPath = path.resolve(__dirname, '../src/data/categories.json');
56 const categories = JSON.parse(fs.readFileSync(categoriesPath, 'utf8'));
57
58 // Get news from the JSON file
59 const newsPath = path.resolve(__dirname, '../src/data/news.json');
60 const newsItems = JSON.parse(fs.readFileSync(newsPath, 'utf8'));
61
62 console.log(`Loaded ${categories.length} categories and ${newsItems.length} news items from JSON files`);
63
64 // Get all existing categories with their IDs, slugs, and icons
65 const { data: existingCategories, error: fetchError } = await supabase
66 .from('categories')
67 .select('id, name, slug, icon');
68
69 if (fetchError) {
70 console.error('Error fetching existing categories:', fetchError);
71 throw fetchError;
72 }
73
74 console.log(`Found ${existingCategories?.length || 0} existing categories in the database`);
75
76 // Create a map of existing categories by ID
77 const categoriesById = new Map();
78 existingCategories?.forEach(cat => {
79 if (cat.id) categoriesById.set(cat.id, cat);
80 });
81
82 // Process each news item
83 console.log('Processing news items...');
84 let processedCount = 0;
85
86 // Check if --all flag is provided to process all news items
87 const processAllItems = process.argv.includes('--all');
88 const itemsToProcess = processAllItems ? newsItems : newsItems.slice(0, 5); // Process only the first 5 for testing unless --all is specified
89
90 for (const newsItem of itemsToProcess) {
91 try {
92 // Check if the news item already exists by URL - use select() instead of maybeSingle()
93 const { data: existingNewsItems, error: checkError } = await supabase
94 .from('news')
95 .select('id, title, url')
96 .ilike('url', `%${newsItem.url.replace(/https?:\/\//, '')}%`);
97
98 if (checkError) {
99 console.error(`Error checking for existing news item ${newsItem.title}:`, checkError);
100 continue;
101 }
102
103 let newsId: string;
104
105 if (existingNewsItems && existingNewsItems.length > 0) {
106 // Use the first matching news item
107 const existingNews = existingNewsItems[0];
108 console.log(`News item "${newsItem.title}" already exists with ID ${existingNews.id}, updating...`);
109 newsId = existingNews.id;
110
111 // Update the existing news item
112 const { error: updateError } = await supabase
113 .from('news')
114 .update({
115 title: newsItem.title,
116 content: newsItem.summary,
117 image_url: newsItem.imageUrl || '',
118 source: newsItem.source,
119 article_date: new Date(newsItem.date).toISOString(),
120 updated_at: new Date().toISOString()
121 })
122 .eq('id', newsId);
123
124 if (updateError) {
125 console.error(`Error updating news item ${newsItem.title}:`, updateError);
126 continue;
127 }
128
129 // Delete existing category relationships
130 const { error: deleteError } = await supabase
131 .from('news_categories')
132 .delete()
133 .eq('news_id', newsId);
134
135 if (deleteError) {
136 console.error(`Error deleting existing categories for news item ${newsItem.title}:`, deleteError);
137 }
138 } else {
139 // Create new news item
140 const { data: createdNews, error: createError } = await supabase
141 .from('news')
142 .insert({
143 title: newsItem.title,
144 content: newsItem.summary,
145 url: newsItem.url,
146 image_url: newsItem.imageUrl || '',
147 source: newsItem.source,
148 article_date: new Date(newsItem.date).toISOString(),
149 created_at: new Date().toISOString(),
150 updated_at: new Date().toISOString()
151 })
152 .select()
153 .single();
154
155 if (createError) {
156 console.error(`Error creating news item ${newsItem.title}:`, createError);
157 continue;
158 }
159
160 newsId = createdNews.id;
161 console.log(`Created news item "${newsItem.title}" with ID ${newsId}`);
162 }
163
164 // Add primary category relationship
165 if (newsItem.primary_category_id) {
166 const primaryCategory = categoriesById.get(newsItem.primary_category_id);
167
168 if (primaryCategory) {
169 const { error: primaryCatError } = await supabase
170 .from('news_categories')
171 .insert({
172 news_id: newsId,
173 category_id: primaryCategory.id,
174 is_primary: true
175 });
176
177 if (primaryCatError) {
178 console.error(`Error adding primary category to news item ${newsItem.title}:`, primaryCatError);
179 } else {
180 console.log(`Added primary category ${primaryCategory.name} to news item "${newsItem.title}"`);
181 }
182 } else {
183 console.warn(`Primary category ID ${newsItem.primary_category_id} not found for news item ${newsItem.title}`);
184 }
185 }
186
187 // Add secondary category relationships
188 if (newsItem.categories && newsItem.categories.length > 0) {
189 for (const categoryId of newsItem.categories) {
190 // Skip if this is the same as the primary category
191 if (categoryId === newsItem.primary_category_id) continue;
192
193 const category = categoriesById.get(categoryId);
194
195 if (category) {
196 const { error: secondaryCatError } = await supabase
197 .from('news_categories')
198 .insert({
199 news_id: newsId,
200 category_id: category.id,
201 is_primary: false
202 });
203
204 if (secondaryCatError) {
205 console.error(`Error adding secondary category ${categoryId} to news item ${newsItem.title}:`, secondaryCatError);
206 } else {
207 console.log(`Added secondary category ${category.name} to news item "${newsItem.title}"`);
208 }
209 } else {
210 console.warn(`Secondary category ID ${categoryId} not found for news item ${newsItem.title}`);
211 }
212 }
213 }
214
215 processedCount++;
216 console.log(`Successfully processed news item: ${newsItem.title}`);
217 } catch (error) {
218 console.error(`Error processing news item ${newsItem.title}:`, error);
219 }
220 }
221
222 console.log(`News items seeding completed. Processed ${processedCount} items.`);
223}
224
225// Run the test
226seedCategories()
227 .then(() => {
228 console.log('Test script completed');
229 process.exit(0);
230 })
231 .catch(error => {
232 console.error('Test script failed:', error);
233 process.exit(1);
234 });