telegram_config.html 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <!-- Telegram Tab -->
  2. <div x-show="activeTab === 'telegram'" class="mt-6">
  3. <div class="max-w-5xl mx-auto space-y-6" x-data="telegramApp()" x-init="init()">
  4. <!-- ── Header ──────────────────────────────────────────────────────── -->
  5. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  6. <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
  7. <div>
  8. <h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
  9. <i class="fab fa-telegram text-blue-500 text-2xl"></i>
  10. {{ _("Notificaciones Telegram") }}
  11. </h2>
  12. <p class="text-sm text-gray-500 mt-1">
  13. {{ _("Configura las credenciales y los destinatarios para las alertas automáticas.") }}
  14. </p>
  15. </div>
  16. <!-- Status badge -->
  17. <div>
  18. <span :class="statusBadgeClass()"
  19. class="inline-flex items-center gap-2 px-4 py-2 rounded-full text-sm font-semibold">
  20. <span class="w-2 h-2 rounded-full" :class="statusDotClass()"></span>
  21. <span x-text="connectionStatus"></span>
  22. </span>
  23. </div>
  24. </div>
  25. </div>
  26. <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
  27. <div class="xl:col-span-1 bg-white shadow rounded-lg border border-gray-200 p-6 space-y-4">
  28. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
  29. <i class="fas fa-cog text-gray-500"></i>
  30. {{ _("Credenciales API") }}
  31. </h3>
  32. <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-200">
  33. <label for="tg_enabled" class="text-sm font-medium text-gray-700 select-none cursor-pointer">
  34. {{ _("Habilitar notificaciones Telegram") }}
  35. </label>
  36. <button type="button" @click="cfg.enabled = !cfg.enabled"
  37. :class="cfg.enabled ? 'bg-blue-600' : 'bg-gray-300'"
  38. class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1">
  39. <span :class="cfg.enabled ? 'translate-x-6' : 'translate-x-1'"
  40. class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform"></span>
  41. </button>
  42. </div>
  43. <div>
  44. <label class="block text-xs font-medium text-gray-600 mb-1">
  45. {{ _("API ID") }}
  46. <a href="https://my.telegram.org/apps" target="_blank" rel="noopener noreferrer"
  47. class="ml-1 text-blue-500 hover:underline text-xs">
  48. (my.telegram.org)
  49. </a>
  50. </label>
  51. <input x-model="cfg.api_id" type="text" placeholder="12345678"
  52. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  53. </div>
  54. <div>
  55. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("API Hash") }}</label>
  56. <input x-model="cfg.api_hash" type="password" autocomplete="off"
  57. :placeholder="hasApiHash ? '{{ _('Guardado — dejar vacío para no cambiar') }}' : 'abc123...'"
  58. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  59. <template x-if="hasApiHash && !cfg.api_hash">
  60. <p class="mt-1 text-xs text-slate-500">
  61. {{ _('API Hash guardado. Deja este campo vacío para no cambiarlo.') }}
  62. </p>
  63. </template>
  64. </div>
  65. <div>
  66. <label class="block text-xs font-medium text-gray-600 mb-1">
  67. {{ _("Token del Bot") }}
  68. <span class="text-gray-400 font-normal">({{ _("opcional si usa cuenta de usuario") }})</span>
  69. </label>
  70. <input x-model="cfg.bot_token" type="password" autocomplete="off"
  71. :placeholder="hasBotToken ? '{{ _('Guardado — dejar vacío para no cambiar') }}' : '@BotFather token'"
  72. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  73. <template x-if="hasBotToken && !cfg.bot_token">
  74. <p class="mt-1 text-xs text-slate-500">
  75. {{ _('Token guardado. Deja este campo vacío para no cambiarlo.') }}
  76. </p>
  77. </template>
  78. </div>
  79. <div>
  80. <label class="block text-xs font-medium text-gray-600 mb-1">
  81. {{ _("Teléfono (cuenta de usuario)") }}
  82. <span class="text-gray-400 font-normal">({{ _("opcional") }})</span>
  83. </label>
  84. <input x-model="cfg.phone" type="text" placeholder="+5491112345678"
  85. :disabled="hasBotToken || cfg.bot_token"
  86. :class="(hasBotToken || cfg.bot_token) ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : ''"
  87. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  88. <template x-if="hasBotToken || cfg.bot_token">
  89. <p class="mt-1 text-xs text-amber-600 flex items-center gap-1">
  90. <i class="fas fa-triangle-exclamation"></i>
  91. {{ _("En modo bot este campo debe estar vacío — los bots no pueden usar número de teléfono.") }}
  92. </p>
  93. </template>
  94. </div>
  95. <div>
  96. <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Nombre de sesión") }}</label>
  97. <input x-model="cfg.session_name" type="text" placeholder="squidstats_bot"
  98. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
  99. </div>
  100. <div class="flex gap-2 pt-2">
  101. <button @click="saveConfig()" :disabled="saving"
  102. class="flex-1 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors flex items-center justify-center gap-2">
  103. <i class="fas fa-save"></i>
  104. <span x-text="saving ? '{{ _('Guardando…') }}' : '{{ _('Guardar') }}'"></span>
  105. </button>
  106. <button @click="testConnection()" :disabled="testing"
  107. class="flex-1 bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors flex items-center justify-center gap-2">
  108. <i class="fas fa-plug"></i>
  109. <span x-text="testing ? '{{ _('Probando…') }}' : '{{ _('Probar') }}'"></span>
  110. </button>
  111. </div>
  112. <template x-if="alert.message">
  113. <div :class="alert.type === 'success'
  114. ? 'bg-green-50 border-green-200 text-green-800'
  115. : 'bg-red-50 border-red-200 text-red-800'"
  116. class="rounded-lg border p-3 text-sm flex items-start gap-2">
  117. <i :class="alert.type === 'success'
  118. ? 'fas fa-check-circle text-green-600'
  119. : 'fas fa-exclamation-circle text-red-600'"
  120. class="mt-0.5 flex-shrink-0"></i>
  121. <span x-text="alert.message"></span>
  122. </div>
  123. </template>
  124. </div>
  125. <div class="xl:col-span-2 space-y-6">
  126. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  127. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
  128. <i class="fas fa-users text-blue-500"></i>
  129. {{ _("Destinatarios") }}
  130. </h3>
  131. <p class="text-sm text-gray-500 mb-3">
  132. {{ _("Introduce un destinatario por línea: @username, ID numérico de usuario o ID de chat/grupo.") }}
  133. </p>
  134. <textarea x-model="recipientsText" rows="6"
  135. placeholder="@usuario1&#10;@usuario2&#10;123456789"
  136. class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"></textarea>
  137. <p class="text-xs text-gray-400 mt-1">
  138. {{ _("Cada línea es un destinatario independiente.") }}
  139. </p>
  140. <div class="mt-4 flex items-center gap-3">
  141. <button @click="sendTestMessage()" :disabled="sendingTest || !cfg.enabled"
  142. class="bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors flex items-center gap-2">
  143. <i class="fab fa-telegram"></i>
  144. <span x-text="sendingTest ? '{{ _('Enviando…') }}' : '{{ _('Enviar mensaje de prueba') }}'"></span>
  145. </button>
  146. <span x-show="!cfg.enabled" class="text-xs text-gray-400 italic">
  147. {{ _("Habilita Telegram para enviar mensajes de prueba.") }}
  148. </span>
  149. </div>
  150. <template x-if="testAlert.message">
  151. <div :class="testAlert.type === 'success'
  152. ? 'bg-green-50 border-green-200 text-green-800'
  153. : 'bg-red-50 border-red-200 text-red-800'"
  154. class="mt-3 rounded-lg border p-3 text-sm flex items-start gap-2">
  155. <i :class="testAlert.type === 'success'
  156. ? 'fas fa-check-circle text-green-600'
  157. : 'fas fa-exclamation-circle text-red-600'"
  158. class="mt-0.5 flex-shrink-0"></i>
  159. <span x-text="testAlert.message"></span>
  160. </div>
  161. </template>
  162. </div>
  163. <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
  164. <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
  165. <i class="fas fa-info-circle text-gray-400"></i>
  166. {{ _("Estado de la conexión") }}
  167. </h3>
  168. <dl class="grid grid-cols-2 gap-x-6 gap-y-3 text-sm">
  169. <div>
  170. <dt class="text-gray-500 font-medium">{{ _("Servicio") }}</dt>
  171. <dd x-text="statusDetails.enabled ? '{{ _('Habilitado') }}' : '{{ _('Deshabilitado') }}'"
  172. :class="statusDetails.enabled ? 'text-green-700 font-semibold' : 'text-gray-400'"></dd>
  173. </div>
  174. <div>
  175. <dt class="text-gray-500 font-medium">{{ _("Conectado") }}</dt>
  176. <dd x-text="statusDetails.connected ? '{{ _('Sí') }}' : '{{ _('No') }}'"
  177. :class="statusDetails.connected ? 'text-green-700 font-semibold' : 'text-red-600'"></dd>
  178. </div>
  179. <div>
  180. <dt class="text-gray-500 font-medium">{{ _("Modo") }}</dt>
  181. <dd x-text="statusDetails.bot_mode ? 'Bot' : '{{ _('Cuenta de usuario') }}'"></dd>
  182. </div>
  183. <div>
  184. <dt class="text-gray-500 font-medium">{{ _("Sesión") }}</dt>
  185. <dd class="font-mono text-gray-700" x-text="statusDetails.session || '—'"></dd>
  186. </div>
  187. <template x-if="statusDetails.username">
  188. <div class="col-span-2">
  189. <dt class="text-gray-500 font-medium">{{ _("Usuario Telegram") }}</dt>
  190. <dd class="font-mono text-gray-700" x-text="'@' + statusDetails.username"></dd>
  191. </div>
  192. </template>
  193. <template x-if="statusDetails.error">
  194. <div class="col-span-2">
  195. <dt class="text-gray-500 font-medium text-red-600">{{ _("Error") }}</dt>
  196. <dd class="text-red-700 text-xs" x-text="statusDetails.error"></dd>
  197. </div>
  198. </template>
  199. </dl>
  200. <button @click="loadStatus()" :disabled="loadingStatus"
  201. class="mt-4 text-sm text-blue-600 hover:underline flex items-center gap-1 disabled:opacity-50">
  202. <i class="fas fa-sync-alt" :class="loadingStatus ? 'animate-spin' : ''"></i>
  203. {{ _("Actualizar estado") }}
  204. </button>
  205. </div>
  206. </div>
  207. </div>
  208. </div>
  209. </div>
  210. </div>
  211. <script>
  212. function telegramApp() {
  213. return {
  214. cfg: {
  215. enabled: {{ 'true' if cfg.enabled else 'false' }},
  216. api_id: {{ cfg.api_id | tojson }},
  217. api_hash: '',
  218. bot_token: '',
  219. phone: {{ cfg.phone | tojson }},
  220. session_name: {{ cfg.session_name | tojson }},
  221. },
  222. hasApiHash: {{ 'true' if cfg.has_api_hash else 'false' }},
  223. hasBotToken: {{ 'true' if cfg.has_bot_token else 'false' }},
  224. recipientsText: {{ (cfg.recipients | join('\n')) | tojson }},
  225. saving: false,
  226. testing: false,
  227. sendingTest: false,
  228. loadingStatus: false,
  229. alert: { type: '', message: '' },
  230. testAlert: { type: '', message: '' },
  231. connectionStatus: '{{ _('Verificando…') }}',
  232. statusDetails: {
  233. enabled: false,
  234. connected: false,
  235. bot_mode: false,
  236. session: '',
  237. username: null,
  238. error: null,
  239. },
  240. async init() {
  241. await this.loadStatus();
  242. },
  243. statusBadgeClass() {
  244. if (this.statusDetails.connected)
  245. return 'bg-green-100 text-green-800';
  246. if (this.statusDetails.enabled)
  247. return 'bg-yellow-100 text-yellow-800';
  248. return 'bg-gray-100 text-gray-500';
  249. },
  250. statusDotClass() {
  251. if (this.statusDetails.connected) return 'bg-green-500';
  252. if (this.statusDetails.enabled) return 'bg-yellow-400';
  253. return 'bg-gray-400';
  254. },
  255. _recipientsList() {
  256. return this.recipientsText
  257. .split('\n')
  258. .map(r => r.trim())
  259. .filter(r => r.length > 0);
  260. },
  261. async saveConfig() {
  262. this.saving = true;
  263. this.alert = { type: '', message: '' };
  264. try {
  265. const payload = {
  266. ...this.cfg,
  267. recipients: this._recipientsList(),
  268. };
  269. const res = await fetch('/admin/api/telegram/save-config', {
  270. method: 'POST',
  271. headers: { 'Content-Type': 'application/json' },
  272. body: JSON.stringify(payload),
  273. });
  274. const data = await res.json();
  275. if (data.status === 'success') {
  276. this.alert = { type: 'success', message: data.message };
  277. this.hasApiHash = this.hasApiHash || !!this.cfg.api_hash;
  278. this.hasBotToken = this.hasBotToken || !!this.cfg.bot_token;
  279. this.cfg.api_hash = '';
  280. this.cfg.bot_token = '';
  281. await this.loadStatus();
  282. } else {
  283. this.alert = { type: 'error', message: data.message };
  284. }
  285. } catch (e) {
  286. this.alert = { type: 'error', message: '{{ _('Error de red al guardar.') }}' };
  287. } finally {
  288. this.saving = false;
  289. }
  290. },
  291. async testConnection() {
  292. this.testing = true;
  293. this.alert = { type: '', message: '' };
  294. try {
  295. const res = await fetch('/admin/api/telegram/test', {
  296. method: 'POST',
  297. headers: { 'Content-Type': 'application/json' },
  298. });
  299. const data = await res.json();
  300. this.alert = {
  301. type: data.status === 'success' ? 'success' : 'error',
  302. message: data.message,
  303. };
  304. await this.loadStatus();
  305. } catch (e) {
  306. this.alert = { type: 'error', message: '{{ _('Error de red al probar la conexión.') }}' };
  307. } finally {
  308. this.testing = false;
  309. }
  310. },
  311. async sendTestMessage() {
  312. this.sendingTest = true;
  313. this.testAlert = { type: '', message: '' };
  314. try {
  315. const res = await fetch('/admin/api/telegram/send-test', {
  316. method: 'POST',
  317. headers: { 'Content-Type': 'application/json' },
  318. });
  319. const data = await res.json();
  320. this.testAlert = {
  321. type: data.status === 'success' ? 'success' : 'error',
  322. message: data.message,
  323. };
  324. } catch (e) {
  325. this.testAlert = { type: 'error', message: '{{ _('Error de red al enviar.') }}' };
  326. } finally {
  327. this.sendingTest = false;
  328. }
  329. },
  330. async loadStatus() {
  331. this.loadingStatus = true;
  332. try {
  333. const res = await fetch('/admin/api/telegram/status');
  334. const data = await res.json();
  335. if (data.status === 'ok') {
  336. this.statusDetails = {
  337. enabled: data.enabled ?? false,
  338. connected: data.connected ?? false,
  339. bot_mode: data.bot_mode ?? false,
  340. session: data.session ?? '',
  341. username: data.username ?? null,
  342. error: data.error ?? null,
  343. };
  344. if (this.statusDetails.connected) {
  345. this.connectionStatus = '{{ _('Conectado') }}';
  346. } else if (this.statusDetails.enabled) {
  347. this.connectionStatus = '{{ _('Desconectado') }}';
  348. } else {
  349. this.connectionStatus = '{{ _('Deshabilitado') }}';
  350. }
  351. }
  352. } catch (_) {
  353. // status is best-effort
  354. } finally {
  355. this.loadingStatus = false;
  356. }
  357. },
  358. };
  359. }
  360. </script>