SmsComunications.php 9.3 KB

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