← back to Daily Reporting

daily-report-runner.ts

202 lines

#!/usr/bin/env node
/**
 * Daily Report Runner
 *
 * Main entry point for generating and sending daily reports
 * Can be run manually or via cron
 */

import { generateDailyReport } from './report-generator';
import { sendToSlack, saveReportToFile, testSlackConnection } from './slack-notifier';

// Configuration
const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL || '';
const SLACK_CHANNEL = process.env.SLACK_CHANNEL || '#morning-report';
const REPORTS_DIR = process.env.REPORTS_DIR || '/root/DW-Agents/reports';

/**
 * Main runner function
 */
async function runDailyReport(reportType: 'morning' | 'eod'): Promise<void> {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`🤖 DW-AGENTS DAILY REPORTING SYSTEM`);
  console.log(`${'='.repeat(60)}\n`);

  console.log(`📊 Report Type: ${reportType.toUpperCase()}`);
  console.log(`⏰ Started at: ${new Date().toLocaleString()}\n`);

  try {
    // Step 1: Generate report
    console.log('📋 Step 1: Generating report...');
    const report = await generateDailyReport(reportType);
    console.log('✅ Report generated successfully\n');

    // Step 2: Save to file
    console.log('💾 Step 2: Saving report to file...');
    const filepath = await saveReportToFile(report, REPORTS_DIR);
    console.log(`✅ Report saved: ${filepath}\n`);

    // Step 3: Send to Slack (if webhook configured)
    if (SLACK_WEBHOOK_URL) {
      console.log('📤 Step 3: Sending report to Slack...');

      const slackConfig = {
        webhookUrl: SLACK_WEBHOOK_URL,
        channel: SLACK_CHANNEL,
        username: 'DW-Agents Reporter',
        iconEmoji: reportType === 'morning' ? ':sunrise:' : ':city_sunset:',
        mentionChannelOnIssues: true
      };

      const success = await sendToSlack(report, slackConfig);

      if (success) {
        console.log(`✅ Report sent to Slack channel: ${SLACK_CHANNEL}\n`);
      } else {
        console.log('⚠️ Failed to send report to Slack (report saved to file)\n');
      }
    } else {
      console.log('⏭️ Step 3: Skipping Slack (webhook not configured)\n');
    }

    // Summary
    console.log('📊 REPORT SUMMARY:');
    console.log(`   System Health: ${report.executiveSummary.systemHealth}%`);
    console.log(`   Agents Online: ${report.executiveSummary.agentsOnline}/${report.executiveSummary.totalAgents}`);
    console.log(`   Tasks Completed: ${report.executiveSummary.tasksCompletedToday}`);
    console.log(`   Critical Issues: ${report.executiveSummary.criticalIssues}`);
    console.log(`   Q&A Readiness: ${report.qnaStatus.overallReadiness}%\n`);

    if (report.issuesRequiringAttention.length > 0) {
      console.log('⚠️ ISSUES REQUIRING ATTENTION:');
      report.issuesRequiringAttention.slice(0, 5).forEach((issue, i) => {
        console.log(`   ${i + 1}. [${issue.severity.toUpperCase()}] ${issue.agent}: ${issue.issue}`);
      });
      console.log('');
    }

    console.log('✅ Daily report completed successfully!\n');
    console.log(`${'='.repeat(60)}\n`);

  } catch (error) {
    console.error('\n❌ ERROR: Failed to generate daily report');
    console.error(error);
    console.log(`\n${'='.repeat(60)}\n`);
    process.exit(1);
  }
}

/**
 * Test Slack webhook connection
 */
async function testSlack(): Promise<void> {
  console.log('🧪 Testing Slack webhook connection...\n');

  if (!SLACK_WEBHOOK_URL) {
    console.error('❌ SLACK_WEBHOOK_URL environment variable not set');
    console.log('\nTo configure Slack:');
    console.log('1. Create a Slack incoming webhook at: https://api.slack.com/messaging/webhooks');
    console.log('2. Set environment variable: export SLACK_WEBHOOK_URL="your-webhook-url"');
    console.log('3. Optionally set channel: export SLACK_CHANNEL="#morning-report"\n');
    process.exit(1);
  }

  const success = await testSlackConnection(SLACK_WEBHOOK_URL);

  if (success) {
    console.log(`✅ Slack connection successful!`);
    console.log(`   Channel: ${SLACK_CHANNEL}`);
    console.log('   Check your Slack channel for a test message.\n');
  } else {
    console.error('❌ Slack connection failed!');
    console.log('   Please check your webhook URL and try again.\n');
    process.exit(1);
  }
}

/**
 * Display usage information
 */
function showUsage(): void {
  console.log(`
🤖 DW-AGENTS DAILY REPORTING SYSTEM

USAGE:
  tsx daily-report-runner.ts [command]

COMMANDS:
  morning     Generate and send morning standup report (6:00 AM)
  eod         Generate and send end-of-day summary report (5:00 PM)
  test        Test Slack webhook connection
  help        Show this help message

ENVIRONMENT VARIABLES:
  SLACK_WEBHOOK_URL     Required: Your Slack incoming webhook URL
  SLACK_CHANNEL         Optional: Target Slack channel (default: #morning-report)
  REPORTS_DIR           Optional: Directory for report backups (default: /root/DW-Agents/reports)

EXAMPLES:
  # Generate morning report
  tsx daily-report-runner.ts morning

  # Generate end-of-day report
  tsx daily-report-runner.ts eod

  # Test Slack connection
  tsx daily-report-runner.ts test

CRON SETUP:
  # Add to crontab (crontab -e):
  0 6 * * * cd /root/.claude/skills/daily-reporting && /root/DW-Agents/node_modules/.bin/tsx daily-report-runner.ts morning
  0 17 * * * cd /root/.claude/skills/daily-reporting && /root/DW-Agents/node_modules/.bin/tsx daily-report-runner.ts eod

SLACK SETUP:
  1. Go to: https://api.slack.com/messaging/webhooks
  2. Create an incoming webhook for your workspace
  3. Create a channel named #morning-report (or use existing)
  4. Copy the webhook URL
  5. Set environment variable:
     export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
  6. Add to ~/.bashrc or ~/.profile to persist

SLACK CHANNEL INVITATION:
  To invite the webhook to your channel:
  1. Create or open the #morning-report channel
  2. Type: /invite @DW-Agents Reporter
  3. The webhook will be able to post messages

`);
}

// Main execution
if (require.main === module) {
  const command = process.argv[2];

  switch (command) {
    case 'morning':
      runDailyReport('morning');
      break;

    case 'eod':
      runDailyReport('eod');
      break;

    case 'test':
      testSlack();
      break;

    case 'help':
    case '--help':
    case '-h':
      showUsage();
      break;

    default:
      console.error('❌ Invalid command\n');
      showUsage();
      process.exit(1);
  }
}

export { runDailyReport };