Branchwell

AI Resource Pro / website / scripts / seed-faqs.ts

1import { createClient } from '@supabase/supabase-js';
2import { readFileSync } from 'fs';
3import * as path from 'path';
4import * as dotenv from 'dotenv';
5import { existsSync } from 'fs';
6import { fileURLToPath } from 'url';
7
8// Get the current file's directory path in ESM
9const __filename = fileURLToPath(import.meta.url);
10const __dirname = path.dirname(__filename);
11
12// Load environment variables from .env.local
13const envLocalPath = path.resolve(process.cwd(), '.env.local');
14if (existsSync(envLocalPath)) {
15 console.log(`Loading environment from: ${envLocalPath}`);
16 dotenv.config({ path: envLocalPath });
17} else {
18 console.log(`No .env.local file found at: ${envLocalPath}`);
19 dotenv.config(); // Try loading from default .env
20}
21
22interface FAQ {
23 id: number;
24 question: string;
25 answer: string;
26}
27
28async function seedFaqs() {
29 console.log('Starting FAQ seeding process...');
30
31 // Initialize Supabase client
32 const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
33 const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
34
35 if (!supabaseUrl || !supabaseServiceKey) {
36 console.error('Missing Supabase environment variables. Please set NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.');
37 process.exit(1);
38 }
39
40 console.log(`Using Supabase URL: ${supabaseUrl}`);
41
42 // Create Supabase client
43 const supabase = createClient(supabaseUrl, supabaseServiceKey, {
44 auth: {
45 autoRefreshToken: false,
46 persistSession: false
47 }
48 });
49
50 try {
51 // Read FAQ data
52 const faqDataPath = path.join(process.cwd(), 'src/data/faq.json');
53 console.log(`Reading FAQ data from: ${faqDataPath}`);
54
55 if (!existsSync(faqDataPath)) {
56 console.error(`FAQ data file not found at: ${faqDataPath}`);
57 process.exit(1);
58 }
59
60 const faqData = JSON.parse(readFileSync(faqDataPath, 'utf-8')) as FAQ[];
61 console.log(`Found ${faqData.length} FAQs to process`);
62
63 // Verify the table exists
64 console.log('Checking if faqs table exists...');
65 const { error: tableError } = await supabase
66 .from('faqs')
67 .select('id')
68 .limit(1);
69
70 if (tableError) {
71 console.error('Error accessing faqs table:', tableError);
72 console.error('Please make sure the faqs table has been created with the correct structure.');
73 process.exit(1);
74 }
75
76 console.log('Successfully connected to faqs table');
77
78 // Option to delete existing records
79 if (process.argv.includes('--clean')) {
80 console.log('Cleaning existing FAQ records...');
81 const { error: deleteError } = await supabase
82 .from('faqs')
83 .delete()
84 .neq('id', 0);
85
86 if (deleteError) {
87 console.error('Error deleting existing FAQs:', deleteError);
88 } else {
89 console.log('Successfully deleted existing FAQs');
90 }
91 }
92
93 // Process each FAQ
94 console.log('Beginning to process FAQs...');
95 let successful = 0;
96 let failed = 0;
97
98 for (const faq of faqData) {
99 console.log(`Processing FAQ ID ${faq.id}: "${faq.question.substring(0, 30)}..."`);
100
101 // First check if it exists
102 const { data: existingFaq, error: checkError } = await supabase
103 .from('faqs')
104 .select('id')
105 .eq('id', faq.id)
106 .single();
107
108 // "No rows found" is expected when the FAQ doesn't exist yet, so we treat it as non-existent
109 if (checkError && !checkError.message.includes('No rows found') && !checkError.details?.includes('contains 0 rows')) {
110 console.error(`Error checking for FAQ ID ${faq.id}:`, checkError);
111 failed++;
112 continue;
113 }
114
115 // Prepare the data to insert or update
116 const faqRecord = {
117 id: faq.id,
118 question: faq.question,
119 answer: faq.answer,
120 updated_at: new Date().toISOString()
121 };
122
123 // If no error or a "No rows found" error, determine whether to update or insert
124 if (existingFaq) {
125 // Update existing
126 console.log(`Updating existing FAQ ID ${faq.id}`);
127 const { error: updateError } = await supabase
128 .from('faqs')
129 .update(faqRecord)
130 .eq('id', faq.id);
131
132 if (updateError) {
133 console.error(`Failed to update FAQ ID ${faq.id}:`, updateError);
134 failed++;
135 } else {
136 console.log(`Successfully updated FAQ ID ${faq.id}`);
137 successful++;
138 }
139 } else {
140 // Insert new - this will happen when checkError indicates no rows were found
141 console.log(`Inserting new FAQ ID ${faq.id}`);
142 const { error: insertError } = await supabase
143 .from('faqs')
144 .insert({
145 ...faqRecord,
146 created_at: new Date().toISOString()
147 });
148
149 if (insertError) {
150 console.error(`Failed to insert FAQ ID ${faq.id}:`, insertError);
151 failed++;
152 } else {
153 console.log(`Successfully inserted FAQ ID ${faq.id}`);
154 successful++;
155 }
156 }
157 }
158
159 // Final summary
160 console.log('\n===== FAQ SEEDING SUMMARY =====');
161 console.log(`Total FAQs: ${faqData.length}`);
162 console.log(`Successfully processed: ${successful}`);
163 console.log(`Failed: ${failed}`);
164 console.log('===============================');
165
166 if (successful > 0) {
167 console.log('FAQ seeding completed with some success!');
168 } else {
169 console.error('FAQ seeding completed with no successful entries.');
170 process.exit(1);
171 }
172 } catch (error) {
173 console.error('Unexpected error during FAQ seeding:', error);
174 process.exit(1);
175 }
176}
177
178// Run the seeding function
179seedFaqs()
180 .then(() => {
181 console.log('FAQ seeding script completed.');
182 process.exit(0);
183 })
184 .catch((error) => {
185 console.error('Error in FAQ seeding script:', error);
186 process.exit(1);
187 });