EmailComunications.php 15 KB

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