ultimatepos/Modules/ManagementTools/Console/SendExecutiveBriefCommand.php

70 lines
2.4 KiB
PHP

<?php
namespace Modules\ManagementTools\Console;
use App\Business;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Modules\ManagementTools\Services\ExecutiveCockpitService;
class SendExecutiveBriefCommand extends Command
{
protected $signature = 'managementtools:send-executive-brief {--business_id=}';
protected $description = 'Send daily executive brief email';
public function handle(ExecutiveCockpitService $cockpitService)
{
$businessQuery = Business::query()->select('id', 'name');
if ($this->option('business_id')) {
$businessQuery->where('id', (int) $this->option('business_id'));
}
$businesses = $businessQuery->get();
$start = Carbon::today()->subDays(6)->startOfDay();
$end = Carbon::today()->endOfDay();
foreach ($businesses as $business) {
$data = $cockpitService->build((int) $business->id, $start, $end);
$subject = 'Executive Brief - '.$business->name;
$body = view('managementtools::executive_cockpit.email_brief', [
'business' => $business,
'data' => $data,
'date' => Carbon::today()->toDateString(),
])->render();
$recipients = User::where('business_id', $business->id)
->where('allow_login', 1)
->whereNotNull('email')
->where(function ($q) {
$q->where('user_type', 'admin')->orWhere('is_cmmsn_agnt', 1);
})
->limit(10)
->pluck('email')
->unique()
->values();
foreach ($recipients as $email) {
$fromAddress = config('mail.from.address');
if (empty($fromAddress)) {
$this->warn("Skipping {$email}: mail.from.address is not configured.");
continue;
}
Mail::html($body, function ($message) use ($email, $subject, $fromAddress) {
$message->from($fromAddress, config('mail.from.name', config('app.name', 'UltimatePOS')))
->to($email)
->subject($subject);
});
}
$this->info("Executive brief sent for business #{$business->id}");
}
return self::SUCCESS;
}
}