EmailComunications.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Livewire\WithFileUploads;
  5. use Illuminate\Support\Facades\DB;
  6. use Carbon\Carbon;
  7. use Illuminate\Support\Facades\Storage;
  8. use App\Http\Middleware\TenantMiddleware;
  9. use App\Models\EmailMessage;
  10. use App\Models\Member;
  11. class EmailComunications extends Component
  12. {
  13. use WithFileUploads;
  14. public ?int $messageId = null;
  15. public string $subject = '';
  16. public string $content_html = '';
  17. public array $recipients = [];
  18. public array $existingAttachments = [];
  19. public $newAttachments = [];
  20. public string $mode = 'now'; // 'now' | 'schedule'
  21. public ?string $schedule_at = null;
  22. public ?string $timezone = 'UTC';
  23. public $records;
  24. public $categories;
  25. public $courses;
  26. public bool $showForm = false;
  27. public bool $locked = false;
  28. public $success;
  29. public $error;
  30. public function boot()
  31. {
  32. app(TenantMiddleware::class)->setupTenantConnection();
  33. }
  34. public function mount()
  35. {
  36. if (auth()->user()?->level != env('LEVEL_ADMIN', 0)) {
  37. return redirect()->to('/dashboard');
  38. }
  39. $this->categories = [];
  40. $this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->orderBy('name')->get(), 0);
  41. $this->courses = [];
  42. $this->getCourses(\App\Models\Course::select('id', 'name')->where('parent_id', null)->orderBy('name', 'ASC')->get(), 0);
  43. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  44. }
  45. public function render()
  46. {
  47. if (!$this->showForm) {
  48. $this->records = EmailMessage::withCount(['attachments', 'recipients'])
  49. ->orderBy('created_at', 'desc')
  50. ->get();
  51. } else {
  52. $this->categories = [];
  53. $this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->orderBy('name')->get(), 0);
  54. $this->courses = [];
  55. $this->getCourses(\App\Models\Course::select('id', 'name')->where('parent_id', null)->orderBy('name', 'ASC')->get(), 0);
  56. }
  57. return view('livewire.email_comunications');
  58. }
  59. protected function baseRules(): array
  60. {
  61. return [
  62. 'subject' => 'required|string|max:255',
  63. 'content_html' => 'required|string',
  64. 'recipients' => 'required|array|min:1',
  65. 'recipients.*.email_address' => 'required|email',
  66. 'newAttachments' => 'nullable',
  67. 'newAttachments.*' => 'file|max:20480',
  68. ];
  69. }
  70. protected function baseMessages(): array
  71. {
  72. return [
  73. 'subject.*' => 'Il campo oggetto è richiesto',
  74. 'content_html.*' => 'Il messaggio è richiesto',
  75. 'recipients.*' => 'Selezionare almeno un destinatario',
  76. 'schedule_at.after' => 'La data di invio deve essere nel futuro',
  77. 'schedule_at.*' => 'Il campo data è richiesto',
  78. ];
  79. }
  80. protected function validateDraft(): void
  81. {
  82. $rules = [];
  83. // $rules = $this->baseRules();
  84. $rules['subject'] = 'required|string|max:255';
  85. $this->validate($rules, $this->baseMessages());
  86. }
  87. protected function validateSend(): void
  88. {
  89. $this->validate($this->baseRules(), $this->baseMessages());
  90. }
  91. protected function validateSchedule(): void
  92. {
  93. $rules = $this->baseRules();
  94. $rules['schedule_at'] = 'required|date|after:now';
  95. $this->validate($rules, $this->baseMessages());
  96. }
  97. public function add()
  98. {
  99. $this->reset(['messageId', 'subject', 'content_html', 'recipients', 'newAttachments', 'mode', 'schedule_at']);
  100. $this->mode = 'now';
  101. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  102. $this->existingAttachments = [];
  103. $this->showForm = true;
  104. $this->dispatchBrowserEvent('load-editor', [
  105. 'html' => $this->content_html ?? '',
  106. 'locked' => $this->locked,
  107. ]);
  108. $this->dispatchBrowserEvent('init-recipients-table', [
  109. 'selected' => collect($this->recipients)->pluck('member_id')->filter()->values()->all(),
  110. ]);
  111. }
  112. public function edit($id)
  113. {
  114. try {
  115. $msg = EmailMessage::with(['recipients', 'attachments'])->findOrFail($id);
  116. $this->messageId = $msg->id;
  117. $this->subject = $msg->subject;
  118. $this->content_html = $msg->content_html;
  119. $this->recipients = $msg->recipients->map(fn($r) => [
  120. 'member_id' => $r->member_id,
  121. 'email_address' => $r->email_address,
  122. 'first_name' => optional($r->member)->first_name,
  123. 'last_name' => optional($r->member)->last_name,
  124. ])->toArray();
  125. usort($this->recipients, function($a, $b) {
  126. $last_name = strcmp($a['last_name'], $b['last_name']);
  127. $first_name = strcmp($a['first_name'], $b['first_name']);
  128. return $last_name == 0 ? $first_name : $last_name;
  129. });
  130. $this->mode = $msg->status === 'scheduled' ? 'schedule' : 'now';
  131. $this->schedule_at = optional($msg->schedule_at)?->setTimezone($this->timezone)?->format('Y-m-d\TH:i');
  132. $this->existingAttachments = $msg->attachments->map(fn($a) => [
  133. 'id' => $a->id,
  134. 'name' => $a->name ?: basename($a->path),
  135. 'size' => $a->size_human,
  136. 'url' => $a->public_url,
  137. 'img' => $a->is_image,
  138. ])->toArray();
  139. $this->showForm = true;
  140. $this->locked = $msg->isLocked();
  141. $this->dispatchBrowserEvent('load-editor', [
  142. 'html' => $this->content_html ?? '',
  143. 'locked' => $this->locked,
  144. ]);
  145. $this->dispatchBrowserEvent('init-recipients-table', [
  146. 'selected' => collect($this->recipients)->pluck('member_id')->filter()->values()->all(),
  147. ]);
  148. } catch (\Throwable $ex) {
  149. $this->error = 'Errore (' . $ex->getMessage() . ')';
  150. }
  151. }
  152. public function duplicate($id, $withRecipients = true)
  153. {
  154. try {
  155. $copy = EmailMessage::with(['recipients', 'attachments'])->findOrFail($id)->duplicate($withRecipients);
  156. $this->edit($copy->id);
  157. $this->success = 'Bozza duplicata';
  158. } catch (\Throwable $ex) {
  159. $this->error = 'Errore (' . $ex->getMessage() . ')';
  160. }
  161. }
  162. public function saveDraft($html = null)
  163. {
  164. if ($html !== null) $this->content_html = $html;
  165. $this->validateDraft();
  166. DB::transaction(function () {
  167. $msg = $this->upsertMessage(status: 'draft', scheduleAt: null);
  168. $this->upsertRecipients($msg);
  169. $this->upsertAttachments($msg);
  170. $this->messageId = $msg->id;
  171. $this->locked = $msg->isLocked();
  172. $this->refreshAttachments($msg);
  173. });
  174. $this->success = 'Bozza salvata';
  175. $this->dispatchBrowserEvent('scroll-top');
  176. $this->dispatchBrowserEvent('load-editor', [
  177. 'html' => $this->content_html ?? '',
  178. 'locked' => $this->locked,
  179. ]);
  180. }
  181. public function sendNow($html = null)
  182. {
  183. if ($html !== null) $this->content_html = $html;
  184. $this->validateSend();
  185. if ($this->messageId) {
  186. $existing = EmailMessage::findOrFail($this->messageId);
  187. if ($existing->isLocked()) {
  188. $this->error = 'Questa email è già in invio o inviata e non può essere modificata.';
  189. return;
  190. }
  191. }
  192. DB::transaction(function () {
  193. $msg = $this->upsertMessage(status: 'processing', scheduleAt: null);
  194. $this->upsertRecipients($msg, true);
  195. $this->upsertAttachments($msg, true);
  196. $this->messageId = $msg->id;
  197. $this->locked = true;
  198. $this->refreshAttachments($msg);
  199. });
  200. dispatch(new \App\Jobs\SendEmailMessage($this->messageId));
  201. $this->success = 'Invio avviato';
  202. $this->dispatchBrowserEvent('scroll-top');
  203. $this->dispatchBrowserEvent('load-editor', [
  204. 'html' => $this->content_html ?? '',
  205. 'locked' => $this->locked,
  206. ]);
  207. }
  208. public function scheduleMessage($html = null)
  209. {
  210. if ($html !== null) $this->content_html = $html;
  211. $this->validateSchedule();
  212. if ($this->messageId) {
  213. $existing = EmailMessage::findOrFail($this->messageId);
  214. if ($existing->isLocked()) {
  215. $this->error = 'Questa email è già in invio o inviata e non può essere modificata.';
  216. return;
  217. }
  218. }
  219. $scheduledAt = \Carbon\Carbon::parse($this->schedule_at, $this->timezone)->setTimezone('UTC');
  220. DB::transaction(function () use ($scheduledAt) {
  221. $msg = $this->upsertMessage(status: 'scheduled', scheduleAt: $scheduledAt);
  222. $this->upsertRecipients($msg, true);
  223. $this->upsertAttachments($msg, true);
  224. $this->messageId = $msg->id;
  225. $this->locked = $msg->isLocked();
  226. $this->refreshAttachments($msg);
  227. });
  228. $this->success = 'Email programmata';
  229. $this->dispatchBrowserEvent('scroll-top');
  230. $this->dispatchBrowserEvent('load-editor', [
  231. 'html' => $this->content_html ?? '',
  232. 'locked' => $this->locked,
  233. ]);
  234. }
  235. protected function upsertMessage(string $status, $scheduleAt): EmailMessage
  236. {
  237. return EmailMessage::updateOrCreate(
  238. ['id' => $this->messageId],
  239. [
  240. 'subject' => $this->subject,
  241. 'content_html' => $this->content_html,
  242. 'status' => $status,
  243. 'schedule_at' => $scheduleAt,
  244. 'created_by' => auth()->id(),
  245. ]
  246. );
  247. }
  248. protected function upsertRecipients(EmailMessage $msg, bool $force = false): void
  249. {
  250. if (!$force && $msg->isLocked()) return;
  251. $msg->recipients()->delete();
  252. $rows = collect($this->recipients)->map(fn($r) => [
  253. 'email_message_id' => $msg->id,
  254. 'member_id' => $r['member_id'] ?? null,
  255. 'email_address' => $r['email_address'],
  256. 'status' => 'pending',
  257. 'created_at' => now(),
  258. 'updated_at' => now(),
  259. ])->values()->all();
  260. if ($rows) \App\Models\EmailMessageRecipient::insert($rows);
  261. }
  262. protected function upsertAttachments(EmailMessage $msg, bool $force = false): void
  263. {
  264. if (!$force && $msg->isLocked()) return;
  265. $files = is_array($this->newAttachments) ? $this->newAttachments : [$this->newAttachments];
  266. foreach ($files as $upload) {
  267. if (!$upload) continue;
  268. $path = $upload->store('emails/' . \Illuminate\Support\Str::uuid(), 'public');
  269. $msg->attachments()->create([
  270. 'disk' => 'public',
  271. 'path' => $path,
  272. 'name' => $upload->getClientOriginalName(),
  273. 'size' => $upload->getSize(),
  274. ]);
  275. }
  276. }
  277. public function cancel()
  278. {
  279. $this->showForm = false;
  280. $this->reset(['messageId', 'subject', 'content_html', 'recipients', 'newAttachments', 'mode', 'schedule_at']);
  281. $this->mode = 'now';
  282. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  283. $this->dispatchBrowserEvent('init-archive-table');
  284. }
  285. public function getCategories($records, $indentation)
  286. {
  287. foreach ($records as $record) {
  288. $this->categories[] = array('id' => $record->id, 'name' => $record->getTree());
  289. if (count($record->childs))
  290. $this->getCategories($record->childs, $indentation + 1);
  291. }
  292. }
  293. public function getCourses($records, $indentation)
  294. {
  295. /** @var \App\Models\Course $record */
  296. foreach ($records as $record) {
  297. $this->courses[] = array('id' => $record->id, 'name' => $record->getTree());
  298. if (count($record->childs))
  299. $this->getCourses($record->childs, $indentation + 1);
  300. }
  301. }
  302. public function toggleRecipient($id)
  303. {
  304. $id = (int)$id;
  305. $idx = collect($this->recipients)->search(fn($r) => (int)($r['member_id'] ?? 0) === $id);
  306. if ($idx !== false) {
  307. array_splice($this->recipients, $idx, 1);
  308. return;
  309. }
  310. $m = Member::select('id', 'email', 'first_name', 'last_name')->find($id);
  311. if (!$m || empty($m->email)) return;
  312. $this->recipients[] = [
  313. 'member_id' => $m->id,
  314. 'email_address' => $m->email,
  315. 'first_name' => $m->first_name,
  316. 'last_name' => $m->last_name,
  317. ];
  318. usort($this->recipients, function($a, $b) {
  319. $last_name = strcmp($a['last_name'], $b['last_name']);
  320. $first_name = strcmp($a['first_name'], $b['first_name']);
  321. return $last_name == 0 ? $first_name : $last_name;
  322. });
  323. }
  324. public function removeNewAttachment(int $index): void
  325. {
  326. if ($this->locked) return;
  327. if (is_array($this->newAttachments) && array_key_exists($index, $this->newAttachments)) {
  328. array_splice($this->newAttachments, $index, 1);
  329. }
  330. }
  331. public function removeExistingAttachment(int $id): void
  332. {
  333. if ($this->locked || !$this->messageId) return;
  334. $att = \App\Models\EmailMessageAttachment::find($id);
  335. if (!$att || $att->email_message_id !== $this->messageId) return;
  336. try {
  337. if ($att->disk && $att->path) {
  338. $disk = Storage::disk($att->disk);
  339. $dir = dirname($att->path);
  340. $disk->delete($att->path);
  341. if (empty($disk->files($dir)) && empty($disk->directories($dir))) {
  342. $disk->deleteDirectory($dir);
  343. }
  344. }
  345. } catch (\Throwable $e) {
  346. }
  347. $att->delete();
  348. $this->existingAttachments = array_values(array_filter(
  349. $this->existingAttachments,
  350. fn($a) => (int)$a['id'] !== (int)$id
  351. ));
  352. }
  353. protected function refreshAttachments(EmailMessage $msg): void
  354. {
  355. $this->existingAttachments = $msg->attachments()
  356. ->get()
  357. ->map(fn($a) => [
  358. 'id' => $a->id,
  359. 'name' => $a->name ?: basename($a->path),
  360. 'size' => $a->size_human,
  361. 'url' => $a->public_url,
  362. 'img' => $a->is_image,
  363. ])->toArray();
  364. $this->newAttachments = [];
  365. }
  366. public function deleteMessage(int $id)
  367. {
  368. $msg = \App\Models\EmailMessage::with(['attachments'])->findOrFail($id);
  369. if (! in_array($msg->status, ['draft', 'failed'], true)) {
  370. return;
  371. }
  372. foreach ($msg->attachments as $a) {
  373. try {
  374. Storage::disk($a->disk ?? 'public')->delete($a->path);
  375. } catch (\Throwable $e) {
  376. }
  377. }
  378. $msg->delete();
  379. $this->dispatchBrowserEvent('email-deleted', ['id' => $id]);
  380. }
  381. }