-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.js
More file actions
327 lines (274 loc) · 12.4 KB
/
data.js
File metadata and controls
327 lines (274 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Data and Options functionality for displaying storage data and question statistics
// DOM elements
const urlParamsViewer = document.getElementById('urlParamsViewer');
const localStorageViewer = document.getElementById('localStorageViewer');
const clearLocalStorageBtn = document.getElementById('clearLocalStorageBtn');
const refreshLocalStorageBtn = document.getElementById('refreshLocalStorageBtn');
const statsLoadingSpinner = document.getElementById('statsLoadingSpinner');
const statsTableContainer = document.getElementById('statsTableContainer');
const statsTableBody = document.getElementById('statsTableBody');
const statsErrorContainer = document.getElementById('statsErrorContainer');
const fileHashLoadingSpinner = document.getElementById('fileHashLoadingSpinner');
const fileHashTableContainer = document.getElementById('fileHashTableContainer');
const fileHashTableBody = document.getElementById('fileHashTableBody');
const fileHashErrorContainer = document.getElementById('fileHashErrorContainer');
// Initialize the page
document.addEventListener('DOMContentLoaded', () => {
// Make sure Supabase is initialized
if (!window.supabaseClient) {
console.error("Supabase client is not initialized");
showError("Database connection not available. Please refresh the page and try again.");
return;
}
// Display URL parameters
displayUrlParameters();
// Display localStorage data
displayLocalStorage();
// Fetch question set statistics
fetchQuestionStats();
// Fetch file hash statistics
fetchFileHashStats();
// Add event listeners for buttons
clearLocalStorageBtn.addEventListener('click', clearLocalStorage);
refreshLocalStorageBtn.addEventListener('click', refreshLocalStorage);
});
// Display URL parameters
function displayUrlParameters() {
const urlParams = new URLSearchParams(window.location.search);
const paramsObject = {};
for (const [key, value] of urlParams.entries()) {
paramsObject[key] = value;
}
// Also include hash parameters if any
if (window.location.hash) {
paramsObject['#hash'] = window.location.hash.substring(1);
}
// Display parameters or show empty message
if (Object.keys(paramsObject).length === 0) {
urlParamsViewer.textContent = 'No URL parameters found.';
} else {
urlParamsViewer.textContent = JSON.stringify(paramsObject, null, 2);
}
}
// Display localStorage data
function displayLocalStorage() {
const storageObject = {};
try {
// Get all items from localStorage
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
let value = localStorage.getItem(key);
// Try to parse JSON values
try {
value = JSON.parse(value);
} catch (e) {
// Keep as string if not valid JSON
}
storageObject[key] = value;
}
// Display data or show empty message
if (Object.keys(storageObject).length === 0) {
localStorageViewer.textContent = 'No localStorage data found.';
} else {
localStorageViewer.textContent = JSON.stringify(storageObject, null, 2);
}
} catch (error) {
console.error('Error accessing localStorage:', error);
localStorageViewer.textContent = 'Error accessing localStorage: ' + error.message;
}
}
// Clear localStorage data
function clearLocalStorage() {
if (confirm('Are you sure you want to clear all localStorage data? This will remove all saved settings and preferences.')) {
try {
localStorage.clear();
refreshLocalStorage();
// Show success message
const alertDiv = document.createElement('div');
alertDiv.className = 'alert alert-success mt-3';
alertDiv.textContent = 'LocalStorage cleared successfully.';
localStorageViewer.parentNode.insertBefore(alertDiv, localStorageViewer.nextSibling);
// Remove the alert after a few seconds
setTimeout(() => {
alertDiv.remove();
}, 3000);
} catch (error) {
console.error('Error clearing localStorage:', error);
alert('Error clearing localStorage: ' + error.message);
}
}
}
// Refresh localStorage display
function refreshLocalStorage() {
displayLocalStorage();
}
// Fetch question set statistics from Supabase
async function fetchQuestionStats() {
try {
// Show loading spinner
statsLoadingSpinner.style.display = 'block';
statsTableContainer.style.display = 'none';
statsErrorContainer.style.display = 'none';
// Get current user ID from localStorage or use 'anonymous' if not available
const currentUserId = localStorage.getItem('userId') || 'anonymous';
// Query Supabase for question set counts using the correct syntax
// Include user_id in the query
const { data, error } = await window.supabaseClient
.from('questions')
.select(`
question_set,
count(),
total_answers:answer_count.sum()
`);
if (error) {
console.error('Error fetching question stats:', error);
throw new Error(error.message);
}
// Hide spinner and show table
statsLoadingSpinner.style.display = 'none';
statsTableContainer.style.display = 'block';
// Clear existing table data
statsTableBody.innerHTML = '';
if (!data || data.length === 0) {
// No data found
const noDataRow = document.createElement('tr');
noDataRow.innerHTML = `
<td colspan="4" class="text-center">No question sets found in the database.</td>
`;
statsTableBody.appendChild(noDataRow);
} else {
// Sort data by question set name
data.sort((a, b) => a.question_set.localeCompare(b.question_set));
// Add each question set to the table
data.forEach(set => {
const row = document.createElement('tr');
// Format total answers, handle nulls
const totalAnswers = set.total_answers !== null ? set.total_answers : 0;
row.innerHTML = `
<td>
<a href="app.html?qs=${encodeURIComponent(set.question_set)}" class="btn btn-sm btn-primary">Practice</a>
</td>
<td>${set.question_set}</td>
<td>${set.count}</td>
<td>${totalAnswers}</td>
`;
statsTableBody.appendChild(row);
});
// Add total row
const totalCount = data.reduce((sum, set) => sum + set.count, 0);
const totalAnswers = data.reduce((sum, set) => sum + (set.total_answers || 0), 0);
const totalRow = document.createElement('tr');
totalRow.className = 'table-secondary';
totalRow.innerHTML = `
<td>
<a href="app.html" class="btn btn-sm btn-outline-primary">Practice All</a>
</td>
<td><strong>Total</strong></td>
<td><strong>${totalCount}</strong></td>
<td><strong>${totalAnswers}</strong></td>
`;
statsTableBody.appendChild(totalRow);
}
} catch (error) {
console.error('Error in fetchQuestionStats:', error);
statsLoadingSpinner.style.display = 'none';
statsErrorContainer.style.display = 'block';
statsErrorContainer.textContent = 'Error loading statistics: ' + error.message;
}
}
// Fetch file hash statistics
async function fetchFileHashStats() {
try {
// Show loading spinner
fileHashLoadingSpinner.style.display = 'block';
fileHashTableContainer.style.display = 'none';
fileHashErrorContainer.style.display = 'none';
// Query Supabase for file hash statistics
const { data, error } = await window.supabaseClient
.from('view_file_content_aggas')
.select('*');
if (error) {
console.error('Error fetching file hash stats:', error);
throw new Error(error.message);
}
console.log('Raw data from view:', data);
// Hide spinner and show table
fileHashLoadingSpinner.style.display = 'none';
fileHashTableContainer.style.display = 'block';
// Clear existing table data
fileHashTableBody.innerHTML = '';
if (!data || data.length === 0) {
// No data found
const noDataRow = document.createElement('tr');
noDataRow.innerHTML = `
<td colspan="7" class="text-center">No file hash statistics found in the database.</td>
`;
fileHashTableBody.appendChild(noDataRow);
} else {
// Add each file hash to the table
data.forEach(file => {
const row = document.createElement('tr');
// Get the correct hash field based on database view
let hashField = file.src_file_content_hash;
// If the hash field doesn't exist, log all available fields and try alternatives
if (!hashField) {
console.log('Available fields:', Object.keys(file));
// Try alternative field names
hashField = file.src_file_content_hash ||
file.file_content_hash ||
file.content_hash ||
file.hash ||
Object.keys(file)[0]; // Fallback to first column
console.log('Using hash field:', hashField);
}
// Format arrays for display - handle potential field name variations
const questionSets = formatArrayField(file.questino_sets || file.question_sets);
const filenames = formatArrayField(file.filenames);
const descriptions = formatArrayField(file.descriptions);
// Display the full hash without shortening
let displayHash = 'Unknown';
if (hashField) {
displayHash = hashField;
}
row.innerHTML = `
<td>
<a href="app.html?fh=${encodeURIComponent(hashField)}" class="btn btn-sm btn-primary">Practice</a>
</td>
<td>${displayHash}</td>
<td>${file.distinct_id_count || 0}</td>
<td>${file.question_hash_count || 0}</td>
<td>${questionSets}</td>
<td>${filenames}</td>
<td>${descriptions}</td>
`;
fileHashTableBody.appendChild(row);
});
}
} catch (error) {
console.error('Error in fetchFileHashStats:', error);
fileHashLoadingSpinner.style.display = 'none';
fileHashErrorContainer.style.display = 'block';
fileHashErrorContainer.textContent = 'Error loading file hash statistics: ' + error.message;
}
}
// Helper function to format array fields from the database
function formatArrayField(arrayField) {
if (!arrayField || !Array.isArray(arrayField) || arrayField.length === 0) {
return 'N/A';
}
// Filter out null values and join with commas
const filteredArray = arrayField.filter(item => item !== null);
if (filteredArray.length === 0) {
return 'N/A';
}
// Return the full array without shortening
return filteredArray.join(', ');
}
// Helper function to show error message
function showError(message) {
statsLoadingSpinner.style.display = 'none';
statsErrorContainer.style.display = 'block';
statsErrorContainer.textContent = message;
urlParamsViewer.textContent = 'Error: ' + message;
localStorageViewer.textContent = 'Error: ' + message;
}