SmartCane/laravel_app/app/Livewire/Forms/MailingForm.php
Timon 6bdbea12cc feat: Add implementation guide for SmartCane code improvements
- Introduced core and optional features for the code improvements merge.
- Documented detailed implementation checklist for core features including database migration, model updates, job changes, form modifications, shell script wrappers, and Python package files.
- Added optional enhancements such as country-based project organization, download scheduling, project search feature, and harvest prediction setup documentation.
- Included testing checklist and post-merge data recreation strategy.
2026-02-19 15:03:14 +01:00

81 lines
2.4 KiB
PHP

<?php
namespace App\Livewire\Forms;
use App\Models\ProjectMailing;
use App\Models\ProjectReport;
use Illuminate\Support\Facades\Mail;
use Livewire\Attributes\Rule;
use Livewire\Form;
class MailingForm extends Form
{
#[Rule('required|min:3')]
public string $subject = '';
#[Rule('required')]
public string $message = '';
#[Rule('required')]
public array $recipients = [];
#[Rule('required')]
public ProjectReport $report;
public function setReport(ProjectReport $report)
{
$this->report = $report;
$this->subject = $report->project->mail_subject;
$this->message = $report->project->mail_template;
$this->recipients = $this->report->project->emailRecipients()->get(['email', 'name'])->toArray();
}
public function save()
{
$this->validate();
self::saveAndSendMailing($this->report, $this->subject, $this->message, $this->recipients);
$this->setReport($this->report);
}
public static function saveAndSendMailing($report, $subject, $message, $recipients) {
if ($report->documentExists()) {
$mailing = $report->project->mailings()->create([
'subject' => $subject,
'message' => $message,
'report_id' => $report->id,
]);
// Attach main report
$mailing->attachments()->create([
'name' => $report->name,
'path' => $report->path,
]);
// For cane_supply projects, also attach latest KPI Excel file
if ($report->project->client_type === 'cane_supply') {
$kpiFile = $report->project->getLatestKpiFile();
if ($kpiFile) {
$mailing->attachments()->create([
'name' => 'KPI Data - ' . basename($kpiFile),
'path' => $kpiFile,
]);
}
}
$mailing->recipients()->createMany($recipients);
Mail::to($mailing->recipients()->pluck('email')->toArray())
->send(new \App\Mail\ReportMailer($mailing, $report));
} else {
self::sendReportNotFoundNotificationToAdmin($report);
}
}
private static function sendReportNotFoundNotificationToAdmin($report) {
Mail::to(config('mail.from.address'))
->send(new \App\Mail\ReportNotFound($report));
}
}