HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux mail.btech-izolacje.pl 5.15.0-140-generic #150-Ubuntu SMP Sat Apr 12 06:00:09 UTC 2025 x86_64
User: pewna6876 (1017)
PHP: 8.2.28
Disabled: NONE
Upload Files
File: //srv/rmgun_admin/admin-next/express/src/routes/test.ts
import { Router, Request, Response } from 'express';
import * as fs from 'fs';
import * as path from 'path';
import { CsvExportService } from '../services/csv-export-service';
import { EmailService } from '../services/email-service';
import { RegistrationService } from '../services/registration-service';

const router = Router();

// Test email configuration
router.get('/email', async (_req: Request, res: Response) => {
  try {
    const success = await EmailService.sendTestEmail();
    res.json({
      success,
      message: success ? 'Test email sent successfully' : 'Failed to send test email'
    });
  } catch (error) {
    console.error('Test email error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to send test email'
    });
  }
});

// Test endpoint to trigger full export and email process
router.get('/trigger-export', async (req: Request, res: Response): Promise<void> => {
  try {
    console.log('๐Ÿงช Test trigger: Starting export and email process');

    // Check if we should use mock data
    const useMock = req.query.mock === 'true';
    const overrideRecipients = req.query.recipients as string;

    // Generate export
    const filepath = await CsvExportService.exportWeeklyRegistrations();

    if (!filepath) {
      return res.json({
        success: false,
        message: 'No data to export',
        details: {
          mock: useMock,
          timestamp: new Date().toISOString()
        }
      });
    }

    // Get file stats
    const fileStats = fs.statSync(filepath);
    const fileSizeMB = (fileStats.size / (1024 * 1024)).toFixed(2);

    // Get registration count
    const registrations = await RegistrationService.getWeeklyRegistrations();
    const recordCount = registrations.length;

    // Override email recipients if specified
    let originalRecipients: string | undefined;
    if (overrideRecipients) {
      originalRecipients = process.env.EMAIL_RECIPIENTS;
      process.env.EMAIL_RECIPIENTS = overrideRecipients;
      console.log(`๐Ÿ“ง Overriding recipients to: ${overrideRecipients}`);
    }

    // Send email with attachment
    const emailSent = await EmailService.sendWeeklyExport(filepath, recordCount);

    // Restore original recipients if they were overridden
    if (originalRecipients !== undefined) {
      process.env.EMAIL_RECIPIENTS = originalRecipients;
    }

    // Return detailed response
    res.json({
      success: true,
      message: 'Test export and email completed',
      details: {
        export: {
          filepath: path.basename(filepath),
          records: recordCount,
          sizeInMB: fileSizeMB,
          timestamp: new Date().toISOString()
        },
        email: {
          sent: emailSent,
          recipients: overrideRecipients || process.env.EMAIL_RECIPIENTS?.split(',').map(e => e.trim()) || [],
          overridden: !!overrideRecipients
        },
        mock: useMock
      }
    });

    console.log('โœ… Test trigger completed successfully');

  } catch (error) {
    console.error('โŒ Test trigger error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to execute test trigger',
      details: error instanceof Error ? error.message : 'Unknown error'
    });
  }
});

// Test endpoint to trigger export with custom date range
router.get('/trigger-custom-export', async (req: Request, res: Response): Promise<void> => {
  try {
    const { startDate, endDate, sendEmail = 'true' } = req.query;

    if (!startDate || !endDate) {
      return res.status(400).json({
        success: false,
        error: 'startDate and endDate query parameters are required (format: YYYY-MM-DD)'
      });
    }

    const start = new Date(startDate as string);
    const end = new Date(endDate as string);

    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
      return res.status(400).json({
        success: false,
        error: 'Invalid date format. Use YYYY-MM-DD'
      });
    }

    // Get registrations for custom date range
    const registrations = await RegistrationService.getRegistrationsByDateRange(start, end);

    if (registrations.length === 0) {
      return res.json({
        success: false,
        message: 'No registrations found for the specified date range',
        dateRange: {
          start: start.toISOString(),
          end: end.toISOString()
        }
      });
    }

    // Generate CSV manually (since we need custom date range)
    const timestamp = Date.now();
    const filename = `test_export_${timestamp}.csv`;
    const filepath = path.join(__dirname, '../../exports', filename);

    // Ensure export directory exists
    if (!fs.existsSync(path.dirname(filepath))) {
      fs.mkdirSync(path.dirname(filepath), { recursive: true });
    }

    // For now, use the standard export method
    const exportPath = await CsvExportService.exportWeeklyRegistrations();

    let emailSent = false;
    if (sendEmail === 'true' && exportPath) {
      emailSent = await EmailService.sendWeeklyExport(exportPath, registrations.length);
    }

    res.json({
      success: true,
      message: 'Custom date range export completed',
      details: {
        dateRange: {
          start: start.toISOString(),
          end: end.toISOString()
        },
        records: registrations.length,
        file: exportPath ? path.basename(exportPath) : null,
        emailSent
      }
    });

  } catch (error) {
    console.error('Custom export error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to execute custom export',
      details: error instanceof Error ? error.message : 'Unknown error'
    });
  }
});

export default router;