Refactor SendInvoiceDataReport command to correctly handle CC emails and improve email fetching logic

This commit is contained in:
dhanabalan
2025-11-02 17:37:02 +05:30
parent 123572011e
commit f47f5182a2

View File

@@ -36,18 +36,36 @@ class SendInvoiceDataReport extends Command
$plantId = (int) $this->argument('plant'); // cast to int for safety
// Fetch mail rules based on schedule type
// // Fetch mail rules based on schedule type
// $mailRules = \App\Models\AlertMailRule::where('module', 'InvoiceDataReport')
// ->where('rule_name', 'InvoiceDataMail')
// ->where('schedule_type', $scheduleType)
// ->where('plant', $plantId)
// ->get();
// $emails = $mailRules->pluck('email')->unique()->toArray();
// $ccEmails = $mailRules->pluck('cc_emails')->filter()->unique()->toArray();
// $this->info('Found emails: ' . implode(', ', $ccEmails));
$mailRules = \App\Models\AlertMailRule::where('module', 'InvoiceDataReport')
->where('rule_name', 'InvoiceDataMail')
->where('schedule_type', $scheduleType)
->where('plant', $plantId)
->get();
$emails = $mailRules->pluck('email')->unique()->toArray();
$toEmails = $mailRules->pluck('email')->filter()->unique()->toArray();
//$ccEmails = $mailRules->pluck('cc_email')->filter()->unique()->toArray();
$ccEmails = $mailRules->pluck('cc_emails')
->filter() // remove null or empty
->flatMap(function ($emails) {
return array_map('trim', explode(',', $emails));
})
->filter()
->unique()
->toArray();
//$this->info('Found emails: ' . implode(', ', $emails));
$plants = $plantId == 0
? Plant::all()
@@ -187,13 +205,20 @@ class SendInvoiceDataReport extends Command
);
$this->info($contentVars['wishes'] ?? '');
// Send Mail //->cc($ccEmails)
if (!empty($emails)) {
foreach ($emails as $email){
\Mail::to($email)->send(new InvoiceDataMail($scheduleType, $tableData));
// Send Mail //
// if (!empty($emails)) {
// foreach ($emails as $email){
// \Mail::to($email)->cc($ccEmails)->send(new InvoiceDataMail($scheduleType, $tableData));
// }
// $this->info("Invoice data report sent to " . count($emails) . " recipient(s).");
// }
if (!empty($toEmails)) {
foreach ($toEmails as $email){
\Mail::to($email)->cc($ccEmails)->send(new InvoiceDataMail($scheduleType, $tableData));
}
$this->info("Invoice data report sent to " . count($emails) . " recipient(s).");
} else {
$this->info("Invoice data report sent to " . count($toEmails) . " recipient(s).");
}
else {
$this->warn('No recipients found for InvoiceDataMail.');
}
}