const http = require('http'); const fs = require('fs'); const path = require('path'); const xlsx = require('xlsx'); // Import the app from server.js by refactoring or starting server // Let's create an automated test against the server async function runTests() { const PORT = 3055; process.env.PORT = PORT; console.log('--- Starting Server for Integration Tests ---'); require('./server.js'); // Wait 1s for server to listen await new Promise(r => setTimeout(r, 1000)); console.log('\n--- Test 1: GET /api/files ---'); const getFilesRes = await fetch(`http://localhost:${PORT}/api/files`); const getFilesData = await getFilesRes.json(); console.log('GET /api/files status:', getFilesRes.status); console.log('Initial files count:', getFilesData.files ? getFilesData.files.length : 0); console.log('\n--- Test 2: Invalid File Upload Handling ---'); const invalidBlob = new Blob(['This is not an excel file'], { type: 'text/plain' }); const invalidForm = new FormData(); invalidForm.append('file', invalidBlob, 'test_invalid.txt'); const invalidRes = await fetch(`http://localhost:${PORT}/api/upload`, { method: 'POST', body: invalidForm }); const invalidData = await invalidRes.json(); console.log('Invalid upload status:', invalidRes.status, '(Expected 400)'); console.log('Invalid upload error message:', invalidData.error); if (invalidRes.status !== 400) { throw new Error('Test 2 failed: server did not reject invalid file'); } console.log('\n--- Test 3: Upload Real Multi-Sheet Excel File ---'); const sampleFilePath = path.join(__dirname, 'sample_company_data.xlsx'); const fileBuffer = fs.readFileSync(sampleFilePath); const sampleBlob = new Blob([fileBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const validForm = new FormData(); validForm.append('file', sampleBlob, 'sample_company_data.xlsx'); const uploadRes = await fetch(`http://localhost:${PORT}/api/upload`, { method: 'POST', body: validForm }); const uploadData = await uploadRes.json(); console.log('Upload status:', uploadRes.status); console.log('Uploaded file record:', uploadData.file); if (!uploadData.success || !uploadData.file) { throw new Error('Test 3 failed: upload was unsuccessful'); } const uploadedFileId = uploadData.file.id; console.log('\n--- Test 4: Verify Worksheet List ---'); const fileInfoRes = await fetch(`http://localhost:${PORT}/api/files/${uploadedFileId}`); const fileInfo = await fileInfoRes.json(); console.log('File sheets detected:', fileInfo.sheetNames); if (!fileInfo.sheetNames.includes('Employees') || !fileInfo.sheetNames.includes('Quarterly Sales')) { throw new Error('Test 4 failed: sheets not properly detected'); } console.log('\n--- Test 5: Fetch Sheet 1 Data ("Employees") ---'); const sheet1Res = await fetch(`http://localhost:${PORT}/api/files/${uploadedFileId}/sheet?name=Employees`); const sheet1Data = await sheet1Res.json(); console.log('Sheet 1 name:', sheet1Data.sheetName); console.log('Sheet 1 dimensions:', `${sheet1Data.totalRows} rows × ${sheet1Data.totalCols} cols`); console.log('Sheet 1 header row:', sheet1Data.rows[0]); console.log('Sheet 1 sample row:', sheet1Data.rows[1]); if (sheet1Data.totalRows !== 9 || sheet1Data.totalCols !== 7) { throw new Error(`Test 5 failed: unexpected row/col count (${sheet1Data.totalRows}x${sheet1Data.totalCols})`); } console.log('\n--- Test 6: Fetch Sheet 2 Data ("Quarterly Sales") ---'); const sheet2Res = await fetch(`http://localhost:${PORT}/api/files/${uploadedFileId}/sheet?name=Quarterly%20Sales`); const sheet2Data = await sheet2Res.json(); console.log('Sheet 2 name:', sheet2Data.sheetName); console.log('Sheet 2 dimensions:', `${sheet2Data.totalRows} rows × ${sheet2Data.totalCols} cols`); console.log('Sheet 2 header row:', sheet2Data.rows[0]); if (sheet2Data.totalRows !== 5 || sheet2Data.totalCols !== 7) { throw new Error('Test 6 failed: Sheet 2 data mismatch'); } console.log('\n--- Test 7: Download Original File & Verify Integrity ---'); const downloadRes = await fetch(`http://localhost:${PORT}/api/files/${uploadedFileId}/download`); console.log('Download status:', downloadRes.status); console.log('Download Content-Disposition:', downloadRes.headers.get('content-disposition')); const downloadedArrayBuffer = await downloadRes.arrayBuffer(); const downloadedWb = xlsx.read(Buffer.from(downloadedArrayBuffer)); console.log('Downloaded workbook sheets:', downloadedWb.SheetNames); if (downloadedWb.SheetNames.length !== 2 || !downloadedWb.SheetNames.includes('Employees')) { throw new Error('Test 7 failed: Downloaded file corrupted or incomplete'); } console.log('\n--- Test 8: Upload and Parse Legacy .xls File ---'); const legacyBuf = fs.readFileSync(path.join(__dirname, 'sample_legacy.xls')); const legacyForm = new FormData(); legacyForm.append('file', new Blob([legacyBuf]), 'sample_legacy.xls'); const xlsUploadRes = await fetch(`http://localhost:${PORT}/api/upload`, { method: 'POST', body: legacyForm }); const xlsUploadData = await xlsUploadRes.json(); console.log('Legacy .xls upload status:', xlsUploadRes.status); console.log('Legacy .xls file info:', xlsUploadData.file); if (xlsUploadRes.status !== 200 || !xlsUploadData.success) { throw new Error('Test 8 failed: .xls upload failed'); } const xlsSheetRes = await fetch(`http://localhost:${PORT}/api/files/${xlsUploadData.file.id}/sheet`); const xlsSheetData = await xlsSheetRes.json(); console.log('Legacy .xls sheet data:', xlsSheetData.rows); if (xlsSheetData.rows.length !== 2 || xlsSheetData.rows[1][1] !== 'Widget') { throw new Error('Test 8 failed: .xls sheet parsing mismatch'); } console.log('\n========================================='); console.log('ALL WORKFLOW INTEGRATION TESTS PASSED!'); console.log('=========================================\n'); process.exit(0); } runTests().catch(err => { console.error('Test run failed:', err); process.exit(1); });