EmailComunications.php 14 KB

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