EmailComunications.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Illuminate\Support\Facades\Auth;
  5. use App\Http\Middleware\TenantMiddleware;
  6. use App\Models\EmailTemplate;
  7. use App\Models\EmailScheduled;
  8. use App\Models\Category;
  9. use App\Models\Member;
  10. use App\Models\User;
  11. use Carbon\Carbon;
  12. use Illuminate\Support\Facades\Mail;
  13. use Illuminate\Support\Facades\Log;
  14. class EmailComunications extends Component
  15. {
  16. public $records, $subject, $message, $attachments = [], $recipients = [], $scheduledDateTime, $sendNow = true;
  17. public $dataId, $update = false, $add = false;
  18. public $users = [];
  19. public $categories = [];
  20. protected $rules = [
  21. 'subject' => 'required|string|max:255',
  22. 'message' => 'required|string',
  23. // 'recipients' => 'required|array|min:1',
  24. 'scheduledDateTime' => 'required_if:sendNow,false|date|after:now',
  25. ];
  26. protected $messages = [
  27. 'subject.required' => 'L\'oggetto è obbligatorio',
  28. 'message.required' => 'Il messaggio è obbligatorio',
  29. // 'recipients.required' => 'Seleziona almeno un gruppo di destinatari',
  30. 'scheduledDateTime.required_if' => 'La data di programmazione è obbligatoria',
  31. 'scheduledDateTime.after' => 'La data di programmazione deve essere futura',
  32. ];
  33. public $sortField = 'name';
  34. public $sortAsc = true;
  35. public function boot()
  36. {
  37. app(TenantMiddleware::class)->setupTenantConnection();
  38. }
  39. public function sortBy($field)
  40. {
  41. if ($this->sortField === $field) {
  42. $this->sortAsc = ! $this->sortAsc;
  43. } else {
  44. $this->sortAsc = true;
  45. }
  46. $this->sortField = $field;
  47. }
  48. public function resetFields()
  49. {
  50. $this->subject = '';
  51. $this->message = '';
  52. $this->attachments = [];
  53. $this->recipients = [];
  54. $this->sendNow = true;
  55. $this->scheduledDateTime = now()->addHour()->format('Y-m-d\TH:i');
  56. $this->emit('load-data-table');
  57. $this->emit('load-editor');
  58. }
  59. public function mount()
  60. {
  61. if (Auth::user()->level != env('LEVEL_ADMIN', 0))
  62. return redirect()->to('/dashboard');
  63. $this->users = Member::select('id', 'last_name', 'email')->get();
  64. $this->categories = [];
  65. $this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->orderBy('name')->get(), 0);
  66. $this->scheduledDateTime = now()->addHour()->format('Y-m-d\TH:i');
  67. }
  68. public function render()
  69. {
  70. $this->records = EmailTemplate::orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')->get();
  71. $this->categories = [];
  72. $this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->orderBy('name')->get(), 0);
  73. return view('livewire.email_comunications');
  74. }
  75. public function add()
  76. {
  77. $this->resetFields();
  78. $this->add = true;
  79. $this->update = false;
  80. }
  81. public function store()
  82. {
  83. $this->validate();
  84. try {
  85. $template = EmailTemplate::create([
  86. 'name' => $this->subject,
  87. 'content' => $this->message,
  88. 'created_by' => Auth::id(),
  89. ]);
  90. $recipients = User::whereIn('id', $this->recipients)->get();
  91. if ($this->sendNow) {
  92. $this->sendEmailNow($template, $recipients);
  93. session()->flash('success', 'Template creato e Email inviate a ' . $recipients->count() . ' destinatari!');
  94. } else {
  95. $this->scheduleEmail($template, $recipients);
  96. $scheduledDate = Carbon::parse($this->scheduledDateTime)->format('d/m/Y H:i');
  97. session()->flash('success', 'Template creato e Email programmate per ' . $scheduledDate);
  98. }
  99. $this->resetFields();
  100. $this->add = false;
  101. } catch (\Exception $ex) {
  102. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  103. }
  104. }
  105. public function edit($id)
  106. {
  107. try {
  108. $template = EmailTemplate::findOrFail($id);
  109. if (!$template) {
  110. session()->flash('error', 'Template Email non trovato');
  111. } else {
  112. $this->subject = $template->name;
  113. $this->message = $template->content;
  114. $this->dataId = $template->id;
  115. $this->update = true;
  116. $this->add = false;
  117. $this->emit('load-editor');
  118. }
  119. } catch (\Exception $ex) {
  120. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  121. }
  122. }
  123. public function update()
  124. {
  125. $this->validate([
  126. 'subject' => 'required|string|max:255',
  127. 'message' => 'required|string',
  128. ]);
  129. try {
  130. EmailTemplate::whereId($this->dataId)->update([
  131. 'name' => $this->subject,
  132. 'content' => $this->message,
  133. ]);
  134. session()->flash('success', 'Template Email aggiornato');
  135. $this->resetFields();
  136. $this->update = false;
  137. } catch (\Exception $ex) {
  138. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  139. }
  140. }
  141. public function cancel()
  142. {
  143. $this->add = false;
  144. $this->update = false;
  145. $this->resetFields();
  146. }
  147. public function sendTemplate($id)
  148. {
  149. try {
  150. $template = EmailTemplate::findOrFail($id);
  151. $this->subject = $template->name;
  152. $this->message = $template->content;
  153. $this->add = true;
  154. $this->update = false;
  155. } catch (\Exception $ex) {
  156. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  157. }
  158. }
  159. private function sendEmailNow($template, $recipients)
  160. {
  161. foreach ($recipients as $recipient) {
  162. if ($recipient->email) {
  163. try {
  164. Log::info("Email sent to {$recipient->name} ({$recipient->email}): Subject: {$template->name}");
  165. } catch (\Exception $e) {
  166. Log::error("Failed to send email to {$recipient->email}: " . $e->getMessage());
  167. }
  168. } else {
  169. Log::warning("User {$recipient->id} has no email address");
  170. }
  171. }
  172. }
  173. private function scheduleEmail($template, $recipients)
  174. {
  175. $scheduled = EmailScheduled::create([
  176. 'template_id' => $template->id,
  177. 'subject' => $template->name,
  178. 'content' => $template->content,
  179. 'scheduled_at' => Carbon::parse($this->scheduledDateTime),
  180. 'status' => 'scheduled',
  181. 'created_by' => Auth::id(),
  182. ]);
  183. $scheduled->recipients()->attach($recipients->pluck('id'));
  184. Log::info("Email scheduled for {$this->scheduledDateTime} to {$recipients->count()} recipients: {$template->name}");
  185. }
  186. public function getCategories($records, $indentation)
  187. {
  188. foreach ($records as $record) {
  189. $this->categories[] = array('id' => $record->id, 'name' => $record->getTree());
  190. if (count($record->childs))
  191. $this->getCategories($record->childs, $indentation + 1);
  192. }
  193. }
  194. }