SmsComunications.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Illuminate\Support\Facades\DB;
  5. use Carbon\Carbon;
  6. use App\Http\Middleware\TenantMiddleware;
  7. use App\Models\SmsMessage;
  8. use App\Models\Member;
  9. class SmsComunications extends Component
  10. {
  11. public ?int $messageId = null;
  12. public string $subject = '';
  13. public string $content = '';
  14. public array $recipients = [];
  15. public string $mode = 'now'; // 'now' | 'schedule'
  16. public ?string $schedule_at = null;
  17. public ?string $timezone = 'UTC';
  18. public $records;
  19. public $categories;
  20. public $courses;
  21. public bool $showForm = false;
  22. public bool $locked = false;
  23. public $success;
  24. public $error;
  25. public function boot()
  26. {
  27. app(TenantMiddleware::class)->setupTenantConnection();
  28. }
  29. public function mount()
  30. {
  31. if (auth()->user()?->level != env('LEVEL_ADMIN', 0)) {
  32. return redirect()->to('/dashboard');
  33. }
  34. $this->categories = [];
  35. $this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->orderBy('name')->get(), 0);
  36. $this->courses = [];
  37. $this->getCourses(\App\Models\Course::select('id', 'name')->where('parent_id', null)->orderBy('name', 'ASC')->get(), 0);
  38. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  39. }
  40. public function render()
  41. {
  42. if (!$this->showForm) {
  43. $this->records = SmsMessage::withCount(['recipients'])
  44. ->orderBy('created_at', 'desc')
  45. ->get();
  46. } else {
  47. $this->categories = [];
  48. $this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->orderBy('name')->get(), 0);
  49. $this->courses = [];
  50. $this->getCourses(\App\Models\Course::select('id', 'name')->where('parent_id', null)->orderBy('name', 'ASC')->get(), 0);
  51. }
  52. return view('livewire.sms_comunications');
  53. }
  54. protected function baseRules(): array
  55. {
  56. return [
  57. 'subject' => 'required|string|max:255',
  58. 'content' => 'required|string|max:900',
  59. 'recipients' => 'required|array|min:1',
  60. 'recipients.*.phone' => 'required|string',
  61. ];
  62. }
  63. protected function baseMessages(): array
  64. {
  65. return [
  66. 'subject.*' => 'Il campo oggetto è richiesto',
  67. 'content.max' => 'Il messaggio non può essere più lungo di 900 caratteri',
  68. 'content.*' => 'Il messaggio è richiesto',
  69. 'recipients.*' => 'Selezionare almeno un destinatario',
  70. 'schedule_at.after' => 'La data di invio deve essere nel futuro',
  71. 'schedule_at.*' => 'Il campo data è richiesto',
  72. ];
  73. }
  74. protected function validateDraft(): void
  75. {
  76. $rules = [];
  77. // $rules = $this->baseRules();
  78. $rules['subject'] = 'required|string|max:255';
  79. $this->validate($rules, $this->baseMessages());
  80. }
  81. protected function validateSend(): void
  82. {
  83. $this->validate($this->baseRules(), $this->baseMessages());
  84. }
  85. protected function validateSchedule(): void
  86. {
  87. $rules = $this->baseRules();
  88. $rules['schedule_at'] = 'required|date|after:now';
  89. $this->validate($rules, $this->baseMessages());
  90. }
  91. public function add()
  92. {
  93. $this->reset(['messageId', 'subject', 'content', 'recipients', 'mode', 'schedule_at']);
  94. $this->mode = 'now';
  95. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  96. $this->showForm = true;
  97. $this->dispatchBrowserEvent('init-recipients-table', [
  98. 'selected' => collect($this->recipients)->pluck('member_id')->filter()->values()->all(),
  99. ]);
  100. }
  101. public function edit($id)
  102. {
  103. try {
  104. $msg = SmsMessage::with(['recipients'])->findOrFail($id);
  105. $this->messageId = $msg->id;
  106. $this->subject = $msg->subject;
  107. $this->content = $msg->content;
  108. $this->recipients = $msg->recipients->map(fn($r) => [
  109. 'member_id' => $r->member_id,
  110. 'phone' => $r->phone,
  111. 'first_name' => optional($r->member)->first_name,
  112. 'last_name' => optional($r->member)->last_name,
  113. ])->toArray();
  114. $this->mode = $msg->status === 'scheduled' ? 'schedule' : 'now';
  115. $this->schedule_at = optional($msg->schedule_at)?->setTimezone($this->timezone)?->format('Y-m-d\TH:i');
  116. $this->showForm = true;
  117. $this->locked = $msg->isLocked();
  118. $this->dispatchBrowserEvent('init-recipients-table', [
  119. 'selected' => collect($this->recipients)->pluck('member_id')->filter()->values()->all(),
  120. ]);
  121. } catch (\Throwable $ex) {
  122. $this->error = 'Errore (' . $ex->getMessage() . ')';
  123. }
  124. }
  125. public function duplicate($id, $withRecipients = true)
  126. {
  127. try {
  128. $copy = SmsMessage::with(['recipients'])->findOrFail($id)->duplicate($withRecipients);
  129. $this->edit($copy->id);
  130. $this->success = 'Bozza duplicata';
  131. } catch (\Throwable $ex) {
  132. $this->error = 'Errore (' . $ex->getMessage() . ')';
  133. }
  134. }
  135. public function saveDraft()
  136. {
  137. $this->validateDraft();
  138. DB::transaction(function () {
  139. $msg = $this->upsertMessage(status: 'draft', scheduleAt: null);
  140. $this->upsertRecipients($msg);
  141. $this->messageId = $msg->id;
  142. $this->locked = $msg->isLocked();
  143. });
  144. $this->success = 'Bozza salvata';
  145. $this->dispatchBrowserEvent('scroll-top');
  146. }
  147. public function sendNow()
  148. {
  149. $this->validateSend();
  150. if ($this->messageId) {
  151. $existing = SmsMessage::findOrFail($this->messageId);
  152. if ($existing->isLocked()) {
  153. $this->error = 'Questo sms è già in invio o inviato e non può essere modificato.';
  154. return;
  155. }
  156. }
  157. DB::transaction(function () {
  158. $msg = $this->upsertMessage(status: 'processing', scheduleAt: null);
  159. $this->upsertRecipients($msg, true);
  160. $this->messageId = $msg->id;
  161. $this->locked = true;
  162. });
  163. dispatch(new \App\Jobs\SendSmsMessage($this->messageId));
  164. $this->success = 'Invio avviato';
  165. $this->dispatchBrowserEvent('scroll-top');
  166. }
  167. public function scheduleMessage()
  168. {
  169. $this->validateSchedule();
  170. if ($this->messageId) {
  171. $existing = SmsMessage::findOrFail($this->messageId);
  172. if ($existing->isLocked()) {
  173. $this->error = 'Questo sms è già in invio o inviato e non può essere modificato.';
  174. return;
  175. }
  176. }
  177. $scheduledAt = \Carbon\Carbon::parse($this->schedule_at, $this->timezone)->setTimezone('UTC');
  178. DB::transaction(function () use ($scheduledAt) {
  179. $msg = $this->upsertMessage(status: 'scheduled', scheduleAt: $scheduledAt);
  180. $this->upsertRecipients($msg, true);
  181. $this->messageId = $msg->id;
  182. $this->locked = $msg->isLocked();
  183. });
  184. $this->success = 'Sms programmato';
  185. $this->dispatchBrowserEvent('scroll-top');
  186. }
  187. protected function upsertMessage(string $status, $scheduleAt): SmsMessage
  188. {
  189. return SmsMessage::updateOrCreate(
  190. ['id' => $this->messageId],
  191. [
  192. 'subject' => $this->subject,
  193. 'content' => $this->content,
  194. 'status' => $status,
  195. 'schedule_at' => $scheduleAt,
  196. 'created_by' => auth()->id(),
  197. ]
  198. );
  199. }
  200. protected function upsertRecipients(SmsMessage $msg, bool $force = false): void
  201. {
  202. if (!$force && $msg->isLocked()) return;
  203. $msg->recipients()->delete();
  204. $rows = collect($this->recipients)->map(fn($r) => [
  205. 'sms_message_id' => $msg->id,
  206. 'member_id' => $r['member_id'] ?? null,
  207. 'phone' => $r['phone'],
  208. 'status' => 'pending',
  209. 'created_at' => now(),
  210. 'updated_at' => now(),
  211. ])->values()->all();
  212. if ($rows) \App\Models\SmsMessageRecipient::insert($rows);
  213. }
  214. public function cancel()
  215. {
  216. $this->showForm = false;
  217. $this->reset(['messageId', 'subject', 'content', 'recipients', 'mode', 'schedule_at']);
  218. $this->mode = 'now';
  219. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  220. $this->dispatchBrowserEvent('init-archive-table');
  221. }
  222. public function getCategories($records, $indentation)
  223. {
  224. foreach ($records as $record) {
  225. $this->categories[] = array('id' => $record->id, 'name' => $record->getTree());
  226. if (count($record->childs))
  227. $this->getCategories($record->childs, $indentation + 1);
  228. }
  229. }
  230. public function getCourses($records, $indentation)
  231. {
  232. /** @var \App\Models\Course $record */
  233. foreach ($records as $record) {
  234. $this->courses[] = array('id' => $record->id, 'name' => $record->getTree());
  235. if (count($record->childs))
  236. $this->getCourses($record->childs, $indentation + 1);
  237. }
  238. }
  239. public function toggleRecipient($id)
  240. {
  241. $id = (int)$id;
  242. $idx = collect($this->recipients)->search(fn($r) => (int)($r['member_id'] ?? 0) === $id);
  243. if ($idx !== false) {
  244. array_splice($this->recipients, $idx, 1);
  245. return;
  246. }
  247. $m = Member::select('id', 'phone', 'first_name', 'last_name')->find($id);
  248. if (!$m || empty($m->phone)) return;
  249. $this->recipients[] = [
  250. 'member_id' => $m->id,
  251. 'phone' => $m->phone,
  252. 'first_name' => $m->first_name,
  253. 'last_name' => $m->last_name,
  254. ];
  255. }
  256. public function deleteMessage(int $id)
  257. {
  258. $msg = \App\Models\SmsMessage::findOrFail($id);
  259. if (! in_array($msg->status, ['draft', 'failed'], true)) {
  260. return;
  261. }
  262. $msg->delete();
  263. $this->dispatchBrowserEvent('sms-deleted', ['id' => $id]);
  264. }
  265. }