diff --git a/app/Console/Commands/SendDailyTaskReport.php b/app/Console/Commands/SendDailyTaskReport.php index dc2282f6..4723f42f 100644 --- a/app/Console/Commands/SendDailyTaskReport.php +++ b/app/Console/Commands/SendDailyTaskReport.php @@ -34,72 +34,193 @@ class SendDailyTaskReport extends Command /** * Execute the console command. */ + // public function handle() + // { + // $directory = 'task_updates'; + // $scheduleType = $this->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) { + if ($mailRules->isEmpty()) { $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', @@ -107,17 +228,73 @@ class SendDailyTaskReport extends Command 'Srimathi Ramamoorthy', ]; - $uploadedEmployees = array_map( - fn ($row) => strtolower(trim($row['name'])), - $rows - ); + // 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) { - if (! in_array( - strtolower(trim($employeeName)), - $uploadedEmployees, - true - )) { + + $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, @@ -125,46 +302,97 @@ class SendDailyTaskReport extends Command 'task' => 'PDF not received', 'status' => 'Missing', 'completed' => '-', + 'submission-type' => now()->format('h:i A'), ]; - $this->warn("PDF not uploaded by: {$employeeName}"); + $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) { - // TO email if (!empty($mailRule->email)) { $toEmails = array_merge( $toEmails, - array_map( - 'trim', - explode(',', $mailRule->email) - ) + array_map('trim', explode(',', $mailRule->email)) ); } - // CC emails if (!empty($mailRule->cc_emails)) { - $ccEmails = array_merge( $ccEmails, - array_map( - 'trim', - explode(',', $mailRule->cc_emails) - ) + 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); @@ -177,31 +405,43 @@ class SendDailyTaskReport extends Command new DailyTaskReportMail($attachments, $rows) ); - foreach ($pdfFiles as $file) { + // 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: ' . basename($file)); + $this->info('Deleted: ' . $attachment['name']); } } - $this->info( - $pdfFiles->count() . ' PDF(s) mailed and deleted successfully.' - ); + $this->info('Daily Task Report mail sent 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; } } - protected function extractNameFromFilename(string $filename): string { $name = preg_replace('/[-_]?task.*$/i', '', $filename);