EmailComunications.php.bak 14 KB

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