File size: 15,982 Bytes
120e2d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/**

 * API Connection Test Script

 * =========================

 * 

 * Automated test script to validate all backend API endpoints

 * and provide detailed reporting on frontend-backend integration.

 */

class APIConnectionTester {
    constructor() {
        this.baseURL = window.location.origin;
        this.results = [];
        this.startTime = null;
        this.endTime = null;
    }

    /**

     * Run comprehensive API tests

     */
    async runAllTests() {
        console.log('πŸš€ Starting API Connection Tests...');
        this.startTime = Date.now();

        const tests = [
            // System Health Tests
            { name: 'Health Check', url: '/api/health', method: 'GET', category: 'System' },

            // Dashboard Tests
            { name: 'Dashboard Summary', url: '/api/dashboard/summary', method: 'GET', category: 'Dashboard' },
            { name: 'Charts Data', url: '/api/dashboard/charts-data', method: 'GET', category: 'Dashboard' },
            { name: 'AI Suggestions', url: '/api/dashboard/ai-suggestions', method: 'GET', category: 'Dashboard' },
            { name: 'Performance Metrics', url: '/api/dashboard/performance-metrics', method: 'GET', category: 'Dashboard' },
            { name: 'Trends', url: '/api/dashboard/trends', method: 'GET', category: 'Dashboard' },

            // Documents Tests
            { name: 'Documents List', url: '/api/documents?limit=5', method: 'GET', category: 'Documents' },
            { name: 'Document Categories', url: '/api/documents/categories/', method: 'GET', category: 'Documents' },
            { name: 'Document Sources', url: '/api/documents/sources/', method: 'GET', category: 'Documents' },
            { name: 'Document Search', url: '/api/documents/search/?q=test', method: 'GET', category: 'Documents' },

            // OCR Tests
            { name: 'OCR Status', url: '/api/ocr/status', method: 'GET', category: 'OCR' },
            { name: 'OCR Models', url: '/api/ocr/models', method: 'GET', category: 'OCR' },

            // Analytics Tests
            { name: 'Analytics Overview', url: '/api/analytics/overview', method: 'GET', category: 'Analytics' },
            { name: 'Analytics Performance', url: '/api/analytics/performance', method: 'GET', category: 'Analytics' },
            { name: 'Analytics Entities', url: '/api/analytics/entities?limit=10', method: 'GET', category: 'Analytics' },
            { name: 'Analytics Quality', url: '/api/analytics/quality-analysis', method: 'GET', category: 'Analytics' },

            // Scraping Tests
            { name: 'Scraping Statistics', url: '/api/scraping/statistics', method: 'GET', category: 'Scraping' },
            { name: 'Scraping Status', url: '/api/scraping/status', method: 'GET', category: 'Scraping' },
            { name: 'Rating Summary', url: '/api/scraping/rating/summary', method: 'GET', category: 'Scraping' },
            { name: 'Scraping Health', url: '/api/scraping/health', method: 'GET', category: 'Scraping' },

            // Phase 2 - File Upload Tests
            { name: 'OCR Upload', url: '/api/ocr/upload', method: 'POST', category: 'File Upload' },
            { name: 'OCR Process', url: '/api/ocr/process', method: 'POST', category: 'File Upload' },
            { name: 'OCR Quality Metrics', url: '/api/ocr/quality-metrics', method: 'GET', category: 'File Upload' },

            // Phase 2 - Document Management Tests
            { name: 'Create Document', url: '/api/documents', method: 'POST', category: 'Document Management' },
            { name: 'Update Document', url: '/api/documents/1', method: 'PUT', category: 'Document Management' },
            { name: 'Delete Document', url: '/api/documents/1', method: 'DELETE', category: 'Document Management' },

            // Phase 2 - Advanced Scraping Tests
            { name: 'Scraping Start', url: '/api/scraping/start', method: 'POST', category: 'Advanced Scraping' },
            { name: 'Scraping Stop', url: '/api/scraping/stop', method: 'POST', category: 'Advanced Scraping' },
            { name: 'Scraping Results', url: '/api/scraping/results', method: 'GET', category: 'Advanced Scraping' }
        ];

        console.log(`πŸ“‹ Running ${tests.length} API tests...`);

        for (const test of tests) {
            await this.runSingleTest(test);
            // Small delay to avoid overwhelming the server
            await this.delay(100);
        }

        this.endTime = Date.now();
        this.generateReport();
    }

    /**

     * Run a single API test

     */
    async runSingleTest(test) {
        const startTime = Date.now();
        let result = {
            name: test.name,
            category: test.category,
            url: test.url,
            method: test.method,
            success: false,
            status: null,
            responseTime: 0,
            data: null,
            error: null,
            timestamp: new Date().toISOString()
        };

        try {
            const response = await fetch(test.url, {
                method: test.method,
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            result.status = response.status;
            result.responseTime = Date.now() - startTime;

            if (response.ok) {
                result.success = true;
                try {
                    result.data = await response.json();
                } catch (e) {
                    result.data = 'Non-JSON response';
                }
            } else {
                result.error = `${response.status}: ${response.statusText}`;
            }

        } catch (error) {
            result.error = error.message;
            result.responseTime = Date.now() - startTime;
        }

        this.results.push(result);

        // Log result
        const status = result.success ? 'βœ…' : '❌';
        console.log(`${status} ${test.name}: ${result.success ? 'PASS' : 'FAIL'} (${result.responseTime}ms)`);

        return result;
    }

    /**

     * Generate comprehensive test report

     */
    generateReport() {
        const totalTests = this.results.length;
        const passedTests = this.results.filter(r => r.success).length;
        const failedTests = totalTests - passedTests;
        const totalTime = this.endTime - this.startTime;
        const avgResponseTime = this.results.reduce((sum, r) => sum + r.responseTime, 0) / totalTests;

        console.log('\nπŸ“Š API Connection Test Report');
        console.log('='.repeat(50));
        console.log(`Total Tests: ${totalTests}`);
        console.log(`Passed: ${passedTests} βœ…`);
        console.log(`Failed: ${failedTests} ❌`);
        console.log(`Success Rate: ${((passedTests / totalTests) * 100).toFixed(1)}%`);
        console.log(`Total Time: ${totalTime}ms`);
        console.log(`Average Response Time: ${avgResponseTime.toFixed(0)}ms`);

        // Group results by category
        const categories = {};
        this.results.forEach(result => {
            if (!categories[result.category]) {
                categories[result.category] = [];
            }
            categories[result.category].push(result);
        });

        console.log('\nπŸ“ˆ Results by Category:');
        Object.entries(categories).forEach(([category, results]) => {
            const passed = results.filter(r => r.success).length;
            const total = results.length;
            const rate = ((passed / total) * 100).toFixed(1);
            console.log(`${category}: ${passed}/${total} (${rate}%)`);
        });

        // Show failed tests
        const failedTests = this.results.filter(r => !r.success);
        if (failedTests.length > 0) {
            console.log('\n❌ Failed Tests:');
            failedTests.forEach(test => {
                console.log(`  - ${test.name}: ${test.error}`);
            });
        }

        // Show slow tests
        const slowTests = this.results.filter(r => r.responseTime > 1000);
        if (slowTests.length > 0) {
            console.log('\n🐌 Slow Tests (>1s):');
            slowTests.forEach(test => {
                console.log(`  - ${test.name}: ${test.responseTime}ms`);
            });
        }

        this.displayResultsInUI();
    }

    /**

     * Display results in the UI

     */
    displayResultsInUI() {
        const container = document.getElementById('apiTestResults');
        if (!container) {
            console.warn('No #apiTestResults container found');
            return;
        }

        const totalTests = this.results.length;
        const passedTests = this.results.filter(r => r.success).length;
        const failedTests = totalTests - passedTests;
        const successRate = ((passedTests / totalTests) * 100).toFixed(1);

        container.innerHTML = `

            <div class="test-report">

                <h3>API Connection Test Results</h3>

                <div class="test-summary">

                    <div class="test-stat">

                        <span class="stat-label">Total Tests:</span>

                        <span class="stat-value">${totalTests}</span>

                    </div>

                    <div class="test-stat">

                        <span class="stat-label">Passed:</span>

                        <span class="stat-value success">${passedTests} βœ…</span>

                    </div>

                    <div class="test-stat">

                        <span class="stat-label">Failed:</span>

                        <span class="stat-value error">${failedTests} ❌</span>

                    </div>

                    <div class="test-stat">

                        <span class="stat-label">Success Rate:</span>

                        <span class="stat-value">${successRate}%</span>

                    </div>

                </div>

                

                <div class="test-details">

                    <h4>Test Details:</h4>

                    <div class="test-list">

                        ${this.results.map(result => `

                            <div class="test-item ${result.success ? 'success' : 'error'}">

                                <span class="test-name">${result.name}</span>

                                <span class="test-status">${result.success ? 'PASS' : 'FAIL'}</span>

                                <span class="test-time">${result.responseTime}ms</span>

                                ${result.error ? `<span class="test-error">${result.error}</span>` : ''}

                            </div>

                        `).join('')}

                    </div>

                </div>

            </div>

        `;
    }

    /**

     * Test specific endpoint patterns

     */
    async testEndpointPatterns() {
        console.log('\nπŸ” Testing Endpoint Patterns...');

        const patterns = [
            // Test the broken endpoints that frontend is trying to call
            { name: 'Frontend Dashboard Summary (BROKEN)', url: '/api/dashboard-summary', expected: false },
            { name: 'Frontend Charts Data (BROKEN)', url: '/api/charts-data', expected: false },
            { name: 'Frontend AI Suggestions (BROKEN)', url: '/api/ai-suggestions', expected: false },
            { name: 'Frontend Train AI (BROKEN)', url: '/api/train-ai', expected: false },
            { name: 'Frontend Scrape Trigger (BROKEN)', url: '/api/scrape-trigger', expected: false },

            // Test the correct endpoints
            { name: 'Backend Dashboard Summary (CORRECT)', url: '/api/dashboard/summary', expected: true },
            { name: 'Backend Charts Data (CORRECT)', url: '/api/dashboard/charts-data', expected: true },
            { name: 'Backend AI Suggestions (CORRECT)', url: '/api/dashboard/ai-suggestions', expected: true },
            { name: 'Backend AI Feedback (CORRECT)', url: '/api/dashboard/ai-feedback', expected: true },
            { name: 'Backend Scrape (CORRECT)', url: '/api/scraping/scrape', expected: true }
        ];

        for (const pattern of patterns) {
            try {
                const response = await fetch(pattern.url);
                const actual = response.ok;
                const status = actual === pattern.expected ? 'βœ…' : '❌';
                console.log(`${status} ${pattern.name}: ${actual ? 'EXISTS' : 'MISSING'} (Expected: ${pattern.expected ? 'EXISTS' : 'MISSING'})`);
            } catch (error) {
                const status = pattern.expected ? '❌' : 'βœ…';
                console.log(`${status} ${pattern.name}: MISSING (Expected: ${pattern.expected ? 'EXISTS' : 'MISSING'})`);
            }
        }
    }

    /**

     * Test file upload functionality

     */
    async testFileUpload() {
        console.log('\nπŸ“ Testing File Upload...');

        // Create a test file
        const testFile = new File(['Test PDF content'], 'test.pdf', { type: 'application/pdf' });
        const formData = new FormData();
        formData.append('file', testFile);
        formData.append('title', 'Test Document');
        formData.append('source', 'Test');
        formData.append('category', 'Test');

        try {
            const response = await fetch('/api/ocr/process-and-save', {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                console.log('βœ… File upload endpoint is accessible');
                const result = await response.json();
                console.log('πŸ“„ Upload response:', result);
            } else {
                console.log('❌ File upload failed:', response.status, response.statusText);
            }
        } catch (error) {
            console.log('❌ File upload error:', error.message);
        }
    }

    /**

     * Utility function for delays

     */
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// Global instance
window.apiTester = new APIConnectionTester();

// Auto-run tests when page loads
document.addEventListener('DOMContentLoaded', () => {
    console.log('πŸ”§ API Connection Tester loaded');

    // Add test button if not exists
    if (!document.getElementById('runAPITests')) {
        const testButton = document.createElement('button');
        testButton.id = 'runAPITests';
        testButton.textContent = 'Run API Tests';
        testButton.style.cssText = `

            position: fixed;

            top: 10px;

            right: 10px;

            z-index: 10000;

            padding: 10px 20px;

            background: #007bff;

            color: white;

            border: none;

            border-radius: 5px;

            cursor: pointer;

        `;
        testButton.onclick = () => {
            window.apiTester.runAllTests();
        };
        document.body.appendChild(testButton);
    }

    // Add results container if not exists
    if (!document.getElementById('apiTestResults')) {
        const resultsContainer = document.createElement('div');
        resultsContainer.id = 'apiTestResults';
        resultsContainer.style.cssText = `

            position: fixed;

            top: 60px;

            right: 10px;

            width: 400px;

            max-height: 500px;

            overflow-y: auto;

            background: white;

            border: 1px solid #ccc;

            border-radius: 5px;

            padding: 15px;

            z-index: 10000;

            display: none;

        `;
        document.body.appendChild(resultsContainer);
    }
});

// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = APIConnectionTester;
}