EmailComunications.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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 validateDraft(): void
  71. {
  72. $rules = [];
  73. // $rules = $this->baseRules();
  74. $rules['subject'] = 'required|string|max:255';
  75. $this->validate($rules);
  76. }
  77. protected function validateSend(): void
  78. {
  79. $this->validate($this->baseRules());
  80. }
  81. protected function validateSchedule(): void
  82. {
  83. $rules = $this->baseRules();
  84. $rules['schedule_at'] = 'required|date|after:now';
  85. $this->validate($rules);
  86. }
  87. public function add()
  88. {
  89. $this->reset(['messageId', 'subject', 'content_html', 'recipients', 'newAttachments', 'mode', 'schedule_at']);
  90. $this->mode = 'now';
  91. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  92. $this->existingAttachments = [];
  93. $this->showForm = true;
  94. $this->dispatchBrowserEvent('load-editor', [
  95. 'html' => $this->content_html ?? '',
  96. 'locked' => $this->locked,
  97. ]);
  98. $this->dispatchBrowserEvent('init-recipients-table', [
  99. 'selected' => collect($this->recipients)->pluck('member_id')->filter()->values()->all(),
  100. ]);
  101. }
  102. public function edit($id)
  103. {
  104. try {
  105. $msg = EmailMessage::with(['recipients', 'attachments'])->findOrFail($id);
  106. $this->messageId = $msg->id;
  107. $this->subject = $msg->subject;
  108. $this->content_html = $msg->content_html;
  109. $this->recipients = $msg->recipients->map(fn($r) => [
  110. 'member_id' => $r->member_id,
  111. 'email_address' => $r->email_address,
  112. 'first_name' => optional($r->member)->first_name,
  113. 'last_name' => optional($r->member)->last_name,
  114. ])->toArray();
  115. usort($this->recipients, function($a, $b) {
  116. $last_name = strcmp($a['last_name'], $b['last_name']);
  117. $first_name = strcmp($a['first_name'], $b['first_name']);
  118. return $last_name == 0 ? $first_name : $last_name;
  119. });
  120. $this->mode = $msg->status === 'scheduled' ? 'schedule' : 'now';
  121. $this->schedule_at = optional($msg->schedule_at)?->setTimezone($this->timezone)?->format('Y-m-d\TH:i');
  122. $this->existingAttachments = $msg->attachments->map(fn($a) => [
  123. 'id' => $a->id,
  124. 'name' => $a->name ?: basename($a->path),
  125. 'size' => $a->size_human,
  126. 'url' => $a->public_url,
  127. 'img' => $a->is_image,
  128. ])->toArray();
  129. $this->showForm = true;
  130. $this->locked = $msg->isLocked();
  131. $this->dispatchBrowserEvent('load-editor', [
  132. 'html' => $this->content_html ?? '',
  133. 'locked' => $this->locked,
  134. ]);
  135. $this->dispatchBrowserEvent('init-recipients-table', [
  136. 'selected' => collect($this->recipients)->pluck('member_id')->filter()->values()->all(),
  137. ]);
  138. } catch (\Throwable $ex) {
  139. $this->error = 'Errore (' . $ex->getMessage() . ')';
  140. }
  141. }
  142. public function duplicate($id, $withRecipients = true)
  143. {
  144. try {
  145. $copy = EmailMessage::with(['recipients', 'attachments'])->findOrFail($id)->duplicate($withRecipients);
  146. $this->edit($copy->id);
  147. $this->success = 'Bozza duplicata';
  148. } catch (\Throwable $ex) {
  149. $this->error = 'Errore (' . $ex->getMessage() . ')';
  150. }
  151. }
  152. public function saveDraft($html = null)
  153. {
  154. if ($html !== null) $this->content_html = $html;
  155. $this->validateDraft();
  156. DB::transaction(function () {
  157. $msg = $this->upsertMessage(status: 'draft', scheduleAt: null);
  158. $this->upsertRecipients($msg);
  159. $this->upsertAttachments($msg);
  160. $this->messageId = $msg->id;
  161. $this->locked = $msg->isLocked();
  162. $this->refreshAttachments($msg);
  163. });
  164. $this->success = 'Bozza salvata';
  165. $this->dispatchBrowserEvent('scroll-top');
  166. $this->dispatchBrowserEvent('load-editor', [
  167. 'html' => $this->content_html ?? '',
  168. 'locked' => $this->locked,
  169. ]);
  170. }
  171. public function sendNow($html = null)
  172. {
  173. if ($html !== null) $this->content_html = $html;
  174. $this->validateSend();
  175. if ($this->messageId) {
  176. $existing = EmailMessage::findOrFail($this->messageId);
  177. if ($existing->isLocked()) {
  178. $this->error = 'Questa email è già in invio o inviata e non può essere modificata.';
  179. return;
  180. }
  181. }
  182. DB::transaction(function () {
  183. $msg = $this->upsertMessage(status: 'processing', scheduleAt: null);
  184. $this->upsertRecipients($msg, true);
  185. $this->upsertAttachments($msg, true);
  186. $this->messageId = $msg->id;
  187. $this->locked = true;
  188. $this->refreshAttachments($msg);
  189. });
  190. dispatch(new \App\Jobs\SendEmailMessage($this->messageId));
  191. $this->success = 'Invio avviato';
  192. $this->dispatchBrowserEvent('scroll-top');
  193. $this->dispatchBrowserEvent('load-editor', [
  194. 'html' => $this->content_html ?? '',
  195. 'locked' => $this->locked,
  196. ]);
  197. }
  198. public function scheduleMessage($html = null)
  199. {
  200. if ($html !== null) $this->content_html = $html;
  201. $this->validateSchedule();
  202. if ($this->messageId) {
  203. $existing = EmailMessage::findOrFail($this->messageId);
  204. if ($existing->isLocked()) {
  205. $this->error = 'Questa email è già in invio o inviata e non può essere modificata.';
  206. return;
  207. }
  208. }
  209. $scheduledAt = \Carbon\Carbon::parse($this->schedule_at, $this->timezone)->setTimezone('UTC');
  210. DB::transaction(function () use ($scheduledAt) {
  211. $msg = $this->upsertMessage(status: 'scheduled', scheduleAt: $scheduledAt);
  212. $this->upsertRecipients($msg, true);
  213. $this->upsertAttachments($msg, true);
  214. $this->messageId = $msg->id;
  215. $this->locked = $msg->isLocked();
  216. $this->refreshAttachments($msg);
  217. });
  218. $this->success = 'Email programmata';
  219. $this->dispatchBrowserEvent('scroll-top');
  220. $this->dispatchBrowserEvent('load-editor', [
  221. 'html' => $this->content_html ?? '',
  222. 'locked' => $this->locked,
  223. ]);
  224. }
  225. protected function upsertMessage(string $status, $scheduleAt): EmailMessage
  226. {
  227. return EmailMessage::updateOrCreate(
  228. ['id' => $this->messageId],
  229. [
  230. 'subject' => $this->subject,
  231. 'content_html' => $this->content_html,
  232. 'status' => $status,
  233. 'schedule_at' => $scheduleAt,
  234. 'created_by' => auth()->id(),
  235. ]
  236. );
  237. }
  238. protected function upsertRecipients(EmailMessage $msg, bool $force = false): void
  239. {
  240. if (!$force && $msg->isLocked()) return;
  241. $msg->recipients()->delete();
  242. $rows = collect($this->recipients)->map(fn($r) => [
  243. 'email_message_id' => $msg->id,
  244. 'member_id' => $r['member_id'] ?? null,
  245. 'email_address' => $r['email_address'],
  246. 'status' => 'pending',
  247. 'created_at' => now(),
  248. 'updated_at' => now(),
  249. ])->values()->all();
  250. if ($rows) \App\Models\EmailMessageRecipient::insert($rows);
  251. }
  252. protected function upsertAttachments(EmailMessage $msg, bool $force = false): void
  253. {
  254. if (!$force && $msg->isLocked()) return;
  255. $files = is_array($this->newAttachments) ? $this->newAttachments : [$this->newAttachments];
  256. foreach ($files as $upload) {
  257. if (!$upload) continue;
  258. $path = $upload->store('emails/' . \Illuminate\Support\Str::uuid(), 'public');
  259. $msg->attachments()->create([
  260. 'disk' => 'public',
  261. 'path' => $path,
  262. 'name' => $upload->getClientOriginalName(),
  263. 'size' => $upload->getSize(),
  264. ]);
  265. }
  266. }
  267. public function cancel()
  268. {
  269. $this->showForm = false;
  270. $this->reset(['messageId', 'subject', 'content_html', 'recipients', 'newAttachments', 'mode', 'schedule_at']);
  271. $this->mode = 'now';
  272. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  273. $this->dispatchBrowserEvent('init-archive-table');
  274. }
  275. public function getCategories($records, $indentation)
  276. {
  277. foreach ($records as $record) {
  278. $this->categories[] = array('id' => $record->id, 'name' => $record->getTree());
  279. if (count($record->childs))
  280. $this->getCategories($record->childs, $indentation + 1);
  281. }
  282. }
  283. public function getCourses($records, $indentation)
  284. {
  285. /** @var \App\Models\Course $record */
  286. foreach ($records as $record) {
  287. $this->courses[] = array('id' => $record->id, 'name' => $record->getTree());
  288. if (count($record->childs))
  289. $this->getCourses($record->childs, $indentation + 1);
  290. }
  291. }
  292. public function toggleRecipient($id)
  293. {
  294. $id = (int)$id;
  295. $idx = collect($this->recipients)->search(fn($r) => (int)($r['member_id'] ?? 0) === $id);
  296. if ($idx !== false) {
  297. array_splice($this->recipients, $idx, 1);
  298. return;
  299. }
  300. $m = Member::select('id', 'email', 'first_name', 'last_name')->find($id);
  301. if (!$m || empty($m->email)) return;
  302. $this->recipients[] = [
  303. 'member_id' => $m->id,
  304. 'email_address' => $m->email,
  305. 'first_name' => $m->first_name,
  306. 'last_name' => $m->last_name,
  307. ];
  308. usort($this->recipients, function($a, $b) {
  309. $last_name = strcmp($a['last_name'], $b['last_name']);
  310. $first_name = strcmp($a['first_name'], $b['first_name']);
  311. return $last_name == 0 ? $first_name : $last_name;
  312. });
  313. }
  314. public function removeNewAttachment(int $index): void
  315. {
  316. if ($this->locked) return;
  317. if (is_array($this->newAttachments) && array_key_exists($index, $this->newAttachments)) {
  318. array_splice($this->newAttachments, $index, 1);
  319. }
  320. }
  321. public function removeExistingAttachment(int $id): void
  322. {
  323. if ($this->locked || !$this->messageId) return;
  324. $att = \App\Models\EmailMessageAttachment::find($id);
  325. if (!$att || $att->email_message_id !== $this->messageId) return;
  326. try {
  327. if ($att->disk && $att->path) {
  328. $disk = Storage::disk($att->disk);
  329. $dir = dirname($att->path);
  330. $disk->delete($att->path);
  331. if (empty($disk->files($dir)) && empty($disk->directories($dir))) {
  332. $disk->deleteDirectory($dir);
  333. }
  334. }
  335. } catch (\Throwable $e) {
  336. }
  337. $att->delete();
  338. $this->existingAttachments = array_values(array_filter(
  339. $this->existingAttachments,
  340. fn($a) => (int)$a['id'] !== (int)$id
  341. ));
  342. }
  343. protected function refreshAttachments(EmailMessage $msg): void
  344. {
  345. $this->existingAttachments = $msg->attachments()
  346. ->get()
  347. ->map(fn($a) => [
  348. 'id' => $a->id,
  349. 'name' => $a->name ?: basename($a->path),
  350. 'size' => $a->size_human,
  351. 'url' => $a->public_url,
  352. 'img' => $a->is_image,
  353. ])->toArray();
  354. $this->newAttachments = [];
  355. }
  356. public function deleteMessage(int $id)
  357. {
  358. $msg = \App\Models\EmailMessage::with(['attachments'])->findOrFail($id);
  359. if (! in_array($msg->status, ['draft', 'failed'], true)) {
  360. return;
  361. }
  362. foreach ($msg->attachments as $a) {
  363. try {
  364. Storage::disk($a->disk ?? 'public')->delete($a->path);
  365. } catch (\Throwable $e) {
  366. }
  367. }
  368. $msg->delete();
  369. $this->dispatchBrowserEvent('email-deleted', ['id' => $id]);
  370. }
  371. }