SmsComunications.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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',
  59. 'recipients' => 'required|array|min:1',
  60. 'recipients.*.phone' => 'required|string',
  61. ];
  62. }
  63. protected function validateDraft(): void
  64. {
  65. $rules = [];
  66. // $rules = $this->baseRules();
  67. $rules['subject'] = 'required|string|max:255';
  68. $this->validate($rules);
  69. }
  70. protected function validateSend(): void
  71. {
  72. $this->validate($this->baseRules());
  73. }
  74. protected function validateSchedule(): void
  75. {
  76. $rules = $this->baseRules();
  77. $rules['schedule_at'] = 'required|date|after:now';
  78. $this->validate($rules);
  79. }
  80. public function add()
  81. {
  82. $this->reset(['messageId', 'subject', 'content', 'recipients', 'mode', 'schedule_at']);
  83. $this->mode = 'now';
  84. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  85. $this->showForm = true;
  86. $this->dispatchBrowserEvent('init-recipients-table', [
  87. 'selected' => collect($this->recipients)->pluck('member_id')->filter()->values()->all(),
  88. ]);
  89. }
  90. public function edit($id)
  91. {
  92. try {
  93. $msg = SmsMessage::with(['recipients'])->findOrFail($id);
  94. $this->messageId = $msg->id;
  95. $this->subject = $msg->subject;
  96. $this->content = $msg->content;
  97. $this->recipients = $msg->recipients->map(fn($r) => [
  98. 'member_id' => $r->member_id,
  99. 'phone' => $r->phone,
  100. 'first_name' => optional($r->member)->first_name,
  101. 'last_name' => optional($r->member)->last_name,
  102. ])->toArray();
  103. $this->mode = $msg->status === 'scheduled' ? 'schedule' : 'now';
  104. $this->schedule_at = optional($msg->schedule_at)?->setTimezone($this->timezone)?->format('Y-m-d\TH:i');
  105. $this->showForm = true;
  106. $this->locked = $msg->isLocked();
  107. $this->dispatchBrowserEvent('init-recipients-table', [
  108. 'selected' => collect($this->recipients)->pluck('member_id')->filter()->values()->all(),
  109. ]);
  110. } catch (\Throwable $ex) {
  111. $this->error = 'Errore (' . $ex->getMessage() . ')';
  112. }
  113. }
  114. public function duplicate($id, $withRecipients = true)
  115. {
  116. try {
  117. $copy = SmsMessage::with(['recipients'])->findOrFail($id)->duplicate($withRecipients);
  118. $this->edit($copy->id);
  119. $this->success = 'Bozza duplicata';
  120. } catch (\Throwable $ex) {
  121. $this->error = 'Errore (' . $ex->getMessage() . ')';
  122. }
  123. }
  124. public function saveDraft()
  125. {
  126. $this->validateDraft();
  127. DB::transaction(function () {
  128. $msg = $this->upsertMessage(status: 'draft', scheduleAt: null);
  129. $this->upsertRecipients($msg);
  130. $this->messageId = $msg->id;
  131. $this->locked = $msg->isLocked();
  132. });
  133. $this->success = 'Bozza salvata';
  134. $this->dispatchBrowserEvent('scroll-top');
  135. }
  136. public function sendNow()
  137. {
  138. $this->validateSend();
  139. if ($this->messageId) {
  140. $existing = SmsMessage::findOrFail($this->messageId);
  141. if ($existing->isLocked()) {
  142. $this->error = 'Questo sms è già in invio o inviato e non può essere modificato.';
  143. return;
  144. }
  145. }
  146. DB::transaction(function () {
  147. $msg = $this->upsertMessage(status: 'processing', scheduleAt: null);
  148. $this->upsertRecipients($msg, true);
  149. $this->messageId = $msg->id;
  150. $this->locked = true;
  151. });
  152. dispatch(new \App\Jobs\SendSmsMessage($this->messageId));
  153. $this->success = 'Invio avviato';
  154. $this->dispatchBrowserEvent('scroll-top');
  155. }
  156. public function scheduleMessage()
  157. {
  158. $this->validateSchedule();
  159. if ($this->messageId) {
  160. $existing = SmsMessage::findOrFail($this->messageId);
  161. if ($existing->isLocked()) {
  162. $this->error = 'Questo sms è già in invio o inviato e non può essere modificato.';
  163. return;
  164. }
  165. }
  166. $scheduledAt = \Carbon\Carbon::parse($this->schedule_at, $this->timezone)->setTimezone('UTC');
  167. DB::transaction(function () use ($scheduledAt) {
  168. $msg = $this->upsertMessage(status: 'scheduled', scheduleAt: $scheduledAt);
  169. $this->upsertRecipients($msg, true);
  170. $this->messageId = $msg->id;
  171. $this->locked = $msg->isLocked();
  172. });
  173. $this->success = 'Sms programmato';
  174. $this->dispatchBrowserEvent('scroll-top');
  175. }
  176. protected function upsertMessage(string $status, $scheduleAt): SmsMessage
  177. {
  178. return SmsMessage::updateOrCreate(
  179. ['id' => $this->messageId],
  180. [
  181. 'subject' => $this->subject,
  182. 'content' => $this->content,
  183. 'status' => $status,
  184. 'schedule_at' => $scheduleAt,
  185. 'created_by' => auth()->id(),
  186. ]
  187. );
  188. }
  189. protected function upsertRecipients(SmsMessage $msg, bool $force = false): void
  190. {
  191. if (!$force && $msg->isLocked()) return;
  192. $msg->recipients()->delete();
  193. $rows = collect($this->recipients)->map(fn($r) => [
  194. 'sms_message_id' => $msg->id,
  195. 'member_id' => $r['member_id'] ?? null,
  196. 'phone' => $r['phone'],
  197. 'status' => 'pending',
  198. 'created_at' => now(),
  199. 'updated_at' => now(),
  200. ])->values()->all();
  201. if ($rows) \App\Models\SmsMessageRecipient::insert($rows);
  202. }
  203. public function cancel()
  204. {
  205. $this->showForm = false;
  206. $this->reset(['messageId', 'subject', 'content', 'recipients', 'mode', 'schedule_at']);
  207. $this->mode = 'now';
  208. $this->schedule_at = now($this->timezone)->addHour()->format('Y-m-d\TH:i');
  209. $this->dispatchBrowserEvent('init-archive-table');
  210. }
  211. public function getCategories($records, $indentation)
  212. {
  213. foreach ($records as $record) {
  214. $this->categories[] = array('id' => $record->id, 'name' => $record->getTree());
  215. if (count($record->childs))
  216. $this->getCategories($record->childs, $indentation + 1);
  217. }
  218. }
  219. public function getCourses($records, $indentation)
  220. {
  221. /** @var \App\Models\Course $record */
  222. foreach ($records as $record) {
  223. $this->courses[] = array('id' => $record->id, 'name' => $record->getTree());
  224. if (count($record->childs))
  225. $this->getCourses($record->childs, $indentation + 1);
  226. }
  227. }
  228. public function toggleRecipient($id)
  229. {
  230. $id = (int)$id;
  231. $idx = collect($this->recipients)->search(fn($r) => (int)($r['member_id'] ?? 0) === $id);
  232. if ($idx !== false) {
  233. array_splice($this->recipients, $idx, 1);
  234. return;
  235. }
  236. $m = Member::select('id', 'phone', 'first_name', 'last_name')->find($id);
  237. if (!$m || empty($m->phone)) return;
  238. $this->recipients[] = [
  239. 'member_id' => $m->id,
  240. 'phone' => $m->phone,
  241. 'first_name' => $m->first_name,
  242. 'last_name' => $m->last_name,
  243. ];
  244. }
  245. public function deleteMessage(int $id)
  246. {
  247. $msg = \App\Models\SmsMessage::findOrFail($id);
  248. if (! in_array($msg->status, ['draft', 'failed'], true)) {
  249. return;
  250. }
  251. $msg->delete();
  252. $this->dispatchBrowserEvent('sms-deleted', ['id' => $id]);
  253. }
  254. }