argument('schedule_type'); // $mailRules = AlertMailRule::where('module', 'DailyTaskReport') // ->where('rule_name', 'DailyTaskReportMail') // ->where('schedule_type', $scheduleType) // ->get(); // if (!$mailRules) { // $this->error('Daily Task Report mail rule not found.'); // return self::FAILURE; // } // // Get all PDF files // $pdfFiles = collect(Storage::disk('local')->files($directory)) // ->filter(function ($file) { // return strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'pdf'; // }) // ->values(); // // if ($pdfFiles->isEmpty()) { // // $this->info('No PDF files found.'); // // return self::SUCCESS; // // } // $parser = new Parser(); // $attachments = []; // $rows = []; // $sno = 1; // $attachments = []; // foreach ($pdfFiles as $file) { // $fullPath = Storage::disk('local')->path($file); // $filename = basename($file, '.pdf'); // $attachments[] = [ // 'path' => Storage::disk('local')->path($file), // 'name' => basename($file), // ]; // // Read PDF content for name/task/status // try { // $pdf = $parser->parseFile($fullPath); // $text = $pdf->getText(); // \Log::info('PDF RAW TEXT: ' . $text); // } catch (\Throwable $e) { // $text = ''; // } // $rows[] = [ // 'sno' => $sno++, // 'name' => $this->extractNameFromFilename($filename), // // 'project-name' => $this->extractProjectName($text), // 'project-name' => $pdf ? $this->extractProjectName($pdf) : 'Unknown project', // 'task' => $this->extractTaskTitle($text), // 'status' => $this->extractStatus($text), // 'completed' => $this->extractPercentComplete($text), // ]; // $this->info('Attached: ' . basename($file)); // } // // Expected employees // $expectedEmployees = [ // 'Dhanabalan Saravanan', // 'Ranjith', // 'Srimathi Ramamoorthy', // ]; // $uploadedEmployees = array_map( // fn ($row) => strtolower(trim($row['name'])), // $rows // ); // foreach ($expectedEmployees as $employeeName) { // if (! in_array( // strtolower(trim($employeeName)), // $uploadedEmployees, // true // )) { // $rows[] = [ // 'sno' => $sno++, // 'name' => $employeeName, // 'project-name' => 'Not uploaded', // 'task' => 'PDF not received', // 'status' => 'Missing', // 'completed' => '-', // ]; // $this->warn("PDF not uploaded by: {$employeeName}"); // } // } // $toEmails = []; // $ccEmails = []; // foreach ($mailRules as $mailRule) { // // TO email // if (!empty($mailRule->email)) { // $toEmails = array_merge( // $toEmails, // array_map( // 'trim', // explode(',', $mailRule->email) // ) // ); // } // // CC emails // if (!empty($mailRule->cc_emails)) { // $ccEmails = array_merge( // $ccEmails, // array_map( // 'trim', // explode(',', $mailRule->cc_emails) // ) // ); // } // } // // Remove duplicate emails // $toEmails = array_values(array_unique(array_filter($toEmails))); // $ccEmails = array_values(array_unique(array_filter($ccEmails))); // try { // $mail = Mail::to($toEmails); // if (!empty($ccEmails)) { // $mail->cc($ccEmails); // } // $mail->send( // new DailyTaskReportMail($attachments, $rows) // ); // foreach ($pdfFiles as $file) { // if (Storage::disk('local')->exists($file)) { // Storage::disk('local')->delete($file); // $this->info('Deleted: ' . basename($file)); // } // } // $this->info( // $pdfFiles->count() . ' PDF(s) mailed and deleted successfully.' // ); // return self::SUCCESS; // } catch (\Throwable $e) { // // Mail failed -> DO NOT delete PDFs // $this->error('Mail sending failed.'); // $this->error($e->getMessage()); // return self::FAILURE; // } // } public function handle() { $directory = 'task_updates'; $scheduleType = $this->argument('schedule_type'); $reportDate = now()->format('Y-m-d'); $trackingFile = 'task_updates/sent_employees.json'; $mailRules = AlertMailRule::where('module', 'DailyTaskReport') ->where('rule_name', 'DailyTaskReportMail') ->where('schedule_type', $scheduleType) ->get(); if ($mailRules->isEmpty()) { $this->error('Daily Task Report mail rule not found.'); return self::FAILURE; } // Expected employees $expectedEmployees = [ 'Dhanabalan Saravanan', 'Ranjith', 'Srimathi Ramamoorthy', ]; // Normalize names $normalizeName = function ($name) { return strtolower( preg_replace('/[^a-z0-9]/i', '', trim($name)) ); }; // Read tracking JSON $trackingData = []; if (Storage::disk('local')->exists($trackingFile)) { $trackingData = json_decode( Storage::disk('local')->get($trackingFile), true ) ?? []; } // Unique tracking key for date + schedule $trackingKey = $reportDate . '_' . $scheduleType; $sentEmployees = $trackingData[$trackingKey] ?? []; // Get PDF files $pdfFiles = collect( Storage::disk('local')->files($directory) ) ->filter(fn ($file) => strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'pdf' ) ->values(); $parser = new Parser(); $attachments = []; $rows = []; $sentNow = []; $sno = 1; // Map available PDFs by employee $uploadedPdfs = []; foreach ($pdfFiles as $file) { $filename = pathinfo($file, PATHINFO_FILENAME); $employeeName = $this->extractNameFromFilename($filename); $normalizedName = $normalizeName($employeeName); $uploadedPdfs[$normalizedName] = $file; } foreach ($expectedEmployees as $employeeName) { $normalizedName = $normalizeName($employeeName); // Already mailed -> don't include again if (in_array($normalizedName, $sentEmployees, true)) { $this->info("Already mailed: {$employeeName}"); continue; } // PDF not available if (!isset($uploadedPdfs[$normalizedName])) { $rows[] = [ 'sno' => $sno++, 'name' => $employeeName, 'project-name' => 'Not uploaded', 'task' => 'PDF not received', 'status' => 'Missing', 'completed' => '-', 'submission-type' => now()->format('h:i A'), ]; $this->warn("PDF not uploaded: {$employeeName}"); continue; } // PDF available $file = $uploadedPdfs[$normalizedName]; $uploadedAt = \Carbon\Carbon::createFromTimestamp( Storage::disk('local')->lastModified($file) ); $submissionType = $uploadedAt->format('H:i') > '09:00' ? 'Late Submission' : '-'; $fullPath = Storage::disk('local')->path($file); $filename = basename($file); try { $pdf = $parser->parseFile($fullPath); $text = $pdf->getText(); } catch (\Throwable $e) { $this->error("PDF parsing failed: {$filename}"); $this->error($e->getMessage()); continue; } // Attach PDF $attachments[] = [ 'path' => $fullPath, 'name' => $filename, ]; // Report row $rows[] = [ 'sno' => $sno++, 'name' => $employeeName, 'project-name' => $this->extractProjectName($pdf), 'task' => $this->extractTaskTitle($text), 'status' => $this->extractStatus($text), 'completed' => $this->extractPercentComplete($text), 'submission-type' => $submissionType, ]; // Mark as sent only after successful email $sentNow[] = $normalizedName; $this->info("Attached: {$filename}"); } // If no pending employees, stop if (empty($rows)) { $this->info('All employees reports already mailed.'); return self::SUCCESS; } // Prepare TO and CC emails $toEmails = []; $ccEmails = []; foreach ($mailRules as $mailRule) { if (!empty($mailRule->email)) { $toEmails = array_merge( $toEmails, array_map('trim', explode(',', $mailRule->email)) ); } if (!empty($mailRule->cc_emails)) { $ccEmails = array_merge( $ccEmails, array_map('trim', explode(',', $mailRule->cc_emails)) ); } } $toEmails = array_values(array_unique(array_filter($toEmails))); $ccEmails = array_values(array_unique(array_filter($ccEmails))); try { $mail = Mail::to($toEmails); if (!empty($ccEmails)) { $mail->cc($ccEmails); } $mail->send( new DailyTaskReportMail($attachments, $rows) ); // Update tracking only for employees whose PDFs were attached $trackingData[$trackingKey] = array_values( array_unique( array_merge($sentEmployees, $sentNow) ) ); Storage::disk('local')->put( $trackingFile, json_encode($trackingData, JSON_PRETTY_PRINT) ); // Delete only PDFs that were successfully attached foreach ($attachments as $attachment) { $file = $directory . '/' . $attachment['name']; if (Storage::disk('local')->exists($file)) { Storage::disk('local')->delete($file); $this->info('Deleted: ' . $attachment['name']); } } $this->info('Daily Task Report mail sent successfully.'); return self::SUCCESS; } catch (\Throwable $e) { $this->error('Mail sending failed.'); $this->error($e->getMessage()); return self::FAILURE; } } protected function extractNameFromFilename(string $filename): string { $name = preg_replace('/[-_]?task.*$/i', '', $filename); $name = preg_replace('/[-_]+/', ' ', $name); $name = preg_replace('/(?knownStatuses as $status) { $pos = stripos($title, $status); if ($pos != false) { $title = trim(substr($title, 0, $pos)); break; } } return $title; } return 'Unknown task'; } protected function extractStatus(string $text): string { // Replace non-breaking spaces (common in OpenProject PDF exports) with regular spaces $normalized = str_replace("\xC2\xA0", ' ', $text); $normalized = preg_replace('/\s+/', ' ', $normalized); foreach ($this->knownStatuses as $status) { if (stripos($normalized, $status) !== false) { return ucwords($status); } } return 'Unknown'; } protected function extractPercentComplete(string $text): string { $normalized = str_replace("\xC2\xA0", ' ', $text); $normalized = preg_replace('/[ \t]+/', ' ', $normalized); if (preg_match('/%\s*Complete\s*([0-9]{1,3}\s*%)/i', $normalized, $matches)) { return trim(str_replace(' ', '', $matches[1])); } return '0%'; } // protected function extractProjectName(string $text): string // { // $normalized = str_replace("\xC2\xA0", ' ', $text); // // Footer pattern: \t at the very end of the PDF text // if (preg_match('/\d{1,2}-\d{2}-\d{4}\s*\t\s*(.+?)\s*$/s', $normalized, $matches)) { // return trim($matches[1]); // } // return 'Unknown project'; // } protected function extractProjectName($pdf): string { $pages = $pdf->getPages(); if (empty($pages)) { return 'Unknown project'; } $firstPageText = str_replace("\xC2\xA0", ' ', $pages[0]->getText()); if (preg_match('/\d{1,2}-\d{2}-\d{4}\s*\t\s*(.+?)\s*$/s', $firstPageText, $matches)) { return trim($matches[1]); } return 'Unknown project'; } }