Files
portal-api/app/Mail/InvoiceNotificationMail.php
2026-07-09 11:19:50 +07:00

109 lines
3.5 KiB
PHP

<?php
namespace App\Mail;
use App\Models\EmailNotificationTemplate;
use App\Models\Invoice;
use App\Services\EmailNotificationTemplateRenderer;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Support\Facades\Log;
/**
* KHÔNG implement ShouldQueue — gọi từ trong queued job, gửi đồng bộ.
*/
class InvoiceNotificationMail extends Mailable
{
public function __construct(
public readonly Invoice $invoice,
public readonly Collection $invoiceAttachments,
public readonly string $customerName,
public readonly string $message,
public readonly string $companyName,
public readonly string $type = 'invoice',
public readonly ?string $invoicePdf = null,
public readonly ?string $invoicePdfFileName = null,
public readonly ?string $paymentUrl = null,
) {}
public function envelope(): Envelope
{
$tpl = $this->activeTemplate();
$fallbackSubject = $this->type === 'renewal'
? "Thông báo gia hạn cước #{$this->invoice->invoice_number} - {$this->companyName}"
: "Thông báo hóa đơn #{$this->invoice->invoice_number} - {$this->companyName}";
$subject = $tpl
? $this->resolveSubject($tpl->subject)
: $fallbackSubject;
return new Envelope(subject: $subject);
}
public function content(): Content
{
$tpl = $this->activeTemplate();
if ($tpl) {
try {
$renderer = app(EmailNotificationTemplateRenderer::class);
$html = $renderer->render(
$tpl,
$this->invoice->load(['order.orderItems.product', 'customer', 'attachments']),
$this->companyName
);
return new Content(htmlString: $html);
} catch (\Throwable $e) {
Log::warning('InvoiceNotificationMail: renderer failed, falling back to blade', [
'template_id' => $tpl->id,
'error' => $e->getMessage(),
]);
}
}
return new Content(
view: 'emails.invoice-notification',
with: [
'invoice' => $this->invoice,
'attachments' => $this->invoiceAttachments,
'customerName' => $this->customerName,
'bodyMessage' => $this->message,
'companyName' => $this->companyName,
'type' => $this->type,
'paymentUrl' => $this->paymentUrl,
]
);
}
public function attachments(): array
{
if ($this->invoicePdf !== null && $this->invoicePdfFileName !== null) {
return [
Attachment::fromData(fn() => $this->invoicePdf, $this->invoicePdfFileName)
->withMime('application/pdf'),
];
}
return [];
}
private function activeTemplate(): ?EmailNotificationTemplate
{
return EmailNotificationTemplate::where('type', 'invoice_notification')
->where('is_active', true)
->first();
}
private function resolveSubject(string $subject): string
{
return str_replace(
['{{invoice_number}}', '{{company_name}}'],
[$this->invoice->invoice_number ?? '', $this->companyName],
$subject
);
}
}