DeviceEditSheet.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. import { useEffect, useState } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import type { LucideIcon } from 'lucide-react'
  4. import { ICON_OVERRIDES } from '@/components/DeviceRow'
  5. import { IconPicker } from '@/components/IconPicker'
  6. import { Button } from '@/components/ui/button'
  7. import { Input } from '@/components/ui/input'
  8. import {
  9. Select,
  10. SelectContent,
  11. SelectItem,
  12. SelectTrigger,
  13. SelectValue,
  14. } from '@/components/ui/select'
  15. import {
  16. Sheet,
  17. SheetContent,
  18. SheetHeader,
  19. SheetTitle,
  20. } from '@/components/ui/sheet'
  21. import { Switch } from '@/components/ui/switch'
  22. import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
  23. import { cn, fetchJson } from '@/lib/utils'
  24. import { useNetPulse } from '@/data/DataProvider'
  25. import type { ClientDevice } from '@/pages/devices-data'
  26. // #693: el server solo acepta hostnames DNS en la reserva DHCP. Un nombre
  27. // visible libre ("TV Salón") viaja vacío y la reserva usa la MAC como name.
  28. const DNS_HOSTNAME_RE = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
  29. const asDhcpHostname = (name: string) =>
  30. name.length > 0 && name.length <= 253 && DNS_HOSTNAME_RE.test(name) ? name : ''
  31. export interface DeviceEditSheetProps {
  32. open: boolean
  33. device: ClientDevice | null
  34. isDemo: boolean
  35. saving?: boolean
  36. onClose: () => void
  37. /** Patch absoluto: '' en un campo = volver al valor automático (#797). */
  38. onSave: (
  39. device: ClientDevice,
  40. patch: { icon: string; name: string; type: string; notifyOffline: boolean; nameSource: string },
  41. ) => void
  42. /** #1145: tras borrar el cliente del registro (el padre cierra y refresca). */
  43. onDeleted?: () => void
  44. /** #1151: resto de clientes (para el selector de enlace). */
  45. clients?: ClientDevice[]
  46. /** #1151: tras enlazar/desenlazar (el padre cierra y refresca). */
  47. onLinkChanged?: () => void
  48. }
  49. // #797: tipos válidos del clasificador (paridad con adapters.ValidDeviceTypes
  50. // y las claves devices.types.* de los locales).
  51. const DEVICE_TYPES = [
  52. 'movil', 'portatil', 'ordenador', 'tablet', 'tv', 'consola',
  53. 'camara', 'aspirador', 'videoportero', 'clima', 'caldera', 'placa', 'altavoz', 'servidor', 'iot', 'switch', 'modem', 'desconocido',
  54. ] as const
  55. export function DeviceEditSheet({
  56. open,
  57. device,
  58. isDemo,
  59. saving,
  60. onClose,
  61. onSave,
  62. onDeleted,
  63. clients,
  64. onLinkChanged,
  65. }: DeviceEditSheetProps) {
  66. const { t } = useTranslation()
  67. const { refresh } = useNetPulse()
  68. const [deleteOpen, setDeleteOpen] = useState(false)
  69. const [deleting, setDeleting] = useState(false)
  70. const [linkTarget, setLinkTarget] = useState('')
  71. const [linkBusy, setLinkBusy] = useState(false)
  72. const [icon, setIcon] = useState(device?.iconOverride ?? '')
  73. const [notifyOffline, setNotifyOffline] = useState(device?.notifyOffline ?? false)
  74. const otherClients = (clients ?? []).filter(
  75. (c) => c.mac && c.mac !== device?.mac && c.mac !== device?.id && !(device?.aliasMacs ?? []).includes(c.mac),
  76. )
  77. const linkClient = async () => {
  78. if (!linkTarget || !device?.mac) return
  79. setLinkBusy(true)
  80. try {
  81. await fetchJson(`/api/devices/${encodeURIComponent(linkTarget)}/link`, {
  82. method: 'PUT',
  83. headers: { 'Content-Type': 'application/json' },
  84. body: JSON.stringify({ target: device.mac }),
  85. })
  86. onLinkChanged?.()
  87. onClose()
  88. } catch {
  89. // fallo silencioso: el botón vuelve a habilitarse
  90. } finally {
  91. setLinkBusy(false)
  92. }
  93. }
  94. const unlinkAlias = async (alias: string) => {
  95. if (!alias) return
  96. setLinkBusy(true)
  97. try {
  98. await fetchJson(`/api/devices/${encodeURIComponent(alias)}/link`, { method: 'DELETE' })
  99. onLinkChanged?.()
  100. onClose()
  101. } catch {
  102. // fallo silencioso
  103. } finally {
  104. setLinkBusy(false)
  105. }
  106. }
  107. const [name, setName] = useState(device?.nameOverride ?? '')
  108. // #2163: fuente de nombre elegida para este cliente ('' = automática).
  109. const [nameSource, setNameSource] = useState(device?.nameSourceOverride ?? '')
  110. const [devType, setDevType] = useState(device?.typeOverride ?? '')
  111. const [reservation, setReservation] = useState<{ reserved: boolean; ip: string; loading: boolean }>({ reserved: false, ip: '', loading: false })
  112. const [reserveDraft, setReserveDraft] = useState(device?.ip ?? '')
  113. const [block, setBlock] = useState<{ blocked: boolean; loading: boolean }>({ blocked: false, loading: false })
  114. // #754: dry-run de comandos. Antes de escribir en el router (reservar o
  115. // bloquear) se pide el plan al server y se muestra; nada se aplica hasta
  116. // la confirmación explícita sobre esos comandos.
  117. const [plan, setPlan] = useState<{ host: string; apply: string[]; rollback: string[] } | null>(null)
  118. const [planRun, setPlanRun] = useState<null | (() => Promise<void>)>(null)
  119. const [planBusy, setPlanBusy] = useState(false)
  120. const closePlan = () => {
  121. setPlan(null)
  122. setPlanRun(null)
  123. }
  124. const openPlan = async (path: string, body: unknown, run: () => Promise<void>) => {
  125. const sep = path.includes('?') ? '&' : '?'
  126. const res = await fetchJson<{ host?: string; apply?: string[]; rollback?: string[] }>(path + sep + 'dry_run=1', {
  127. method: 'PUT',
  128. headers: { 'Content-Type': 'application/json' },
  129. body: JSON.stringify(body),
  130. })
  131. if (!res.ok || !res.data) return false
  132. setPlan({ host: res.data.host ?? '', apply: res.data.apply ?? [], rollback: res.data.rollback ?? [] })
  133. setPlanRun(() => run)
  134. return true
  135. }
  136. useEffect(() => {
  137. setIcon(device?.iconOverride ?? '')
  138. setName(device?.nameOverride ?? '')
  139. setDevType(device?.typeOverride ?? '')
  140. setNotifyOffline(device?.notifyOffline ?? false)
  141. setNameSource(device?.nameSourceOverride ?? '')
  142. setReserveDraft(device?.ip ?? '')
  143. }, [
  144. device?.id,
  145. device?.iconOverride,
  146. device?.nameOverride,
  147. device?.typeOverride,
  148. device?.notifyOffline,
  149. device?.nameSourceOverride,
  150. device?.ip,
  151. ])
  152. useEffect(() => {
  153. if (!device || isDemo) return
  154. let cancelled = false
  155. const load = async () => {
  156. setReservation((p) => ({ ...p, loading: true }))
  157. setBlock((p) => ({ ...p, loading: true }))
  158. const [res, blk] = await Promise.all([
  159. fetchJson<{ reserved: boolean; ip?: string }>(`/api/devices/${encodeURIComponent(device.mac)}/reservation`),
  160. fetchJson<{ blocked: boolean }>(`/api/devices/${encodeURIComponent(device.mac)}/block?router=${encodeURIComponent(device.routerId)}`),
  161. ])
  162. if (cancelled) return
  163. if (res.ok) {
  164. setReservation({ reserved: res.data.reserved, ip: res.data.ip ?? '', loading: false })
  165. if (res.data.ip) setReserveDraft(res.data.ip)
  166. } else {
  167. setReservation({ reserved: false, ip: '', loading: false })
  168. }
  169. if (blk.ok) {
  170. setBlock({ blocked: blk.data.blocked, loading: false })
  171. } else {
  172. setBlock({ blocked: false, loading: false })
  173. }
  174. }
  175. void load()
  176. return () => { cancelled = true }
  177. }, [device, isDemo])
  178. const handleSave = () => {
  179. if (!device) return
  180. onSave(device, { icon, name: name.trim(), type: devType, notifyOffline, nameSource })
  181. }
  182. // #800: hostname DNS derivado del nombre visible (input del sheet o nombre
  183. // actual). Vacío = el nombre visible no es aplicable como hostname DNS.
  184. const appliedHostname = device ? asDhcpHostname(name.trim() || device.name) : ''
  185. const selectedIconName = icon || null
  186. const PreviewIcon = (selectedIconName ? (ICON_OVERRIDES[selectedIconName] ?? ICON_OVERRIDES['help-circle']) : ICON_OVERRIDES['help-circle']) as LucideIcon
  187. return (
  188. <Sheet open={open} onOpenChange={(v) => !v && onClose()}>
  189. <SheetContent side="right" className="w-full sm:max-w-md">
  190. {/* #828: cabecera con título para que el X de cierre quede sobre ella
  191. (patrón estándar de los sheets) y no montado encima de la tarjeta
  192. de vista previa con la MAC. */}
  193. <SheetHeader className="px-4 pb-0 pt-4">
  194. <SheetTitle className="pr-8 font-display text-h2 text-text-primary">
  195. {t('devices.edit.title')}
  196. </SheetTitle>
  197. </SheetHeader>
  198. {device && (
  199. <div className="flex flex-col gap-5 overflow-y-auto px-4 py-2">
  200. {/* Vista previa */}
  201. <div className="flex items-center gap-3 rounded-xl border border-border bg-elevated/50 p-3">
  202. <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-elevated text-text-secondary">
  203. <PreviewIcon className="h-6 w-6" strokeWidth={1.75} />
  204. </div>
  205. <div className="min-w-0">
  206. <div className="truncate text-sm font-medium text-text-primary">{name.trim() || device.name}</div>
  207. <div className="truncate text-caption text-text-muted">{device.mac}</div>
  208. </div>
  209. </div>
  210. {/* Nombre visible (#797) */}
  211. <div className="space-y-2">
  212. <label className="text-label uppercase text-text-muted">{t('devices.edit.name')}</label>
  213. <Input
  214. value={name}
  215. onChange={(e) => setName(e.target.value)}
  216. placeholder={device.name}
  217. disabled={saving}
  218. maxLength={64}
  219. className="h-9 rounded-lg border-border bg-elevated text-sm text-text-primary placeholder:text-text-muted focus-visible:border-accent/50"
  220. />
  221. <p className="text-caption text-text-muted">{t('devices.edit.nameHint')}</p>
  222. </div>
  223. {/* #2163: fuente de nombre elegida para este cliente. Solo se
  224. ofrece lo que este cliente tiene de verdad: elegir mDNS en un
  225. equipo que no anuncia nada no cambiaría el nombre. */}
  226. <div className="space-y-2">
  227. <label className="text-label uppercase text-text-muted">{t('devices.edit.nameSource')}</label>
  228. <Select
  229. value={nameSource || 'auto'}
  230. onValueChange={(v) => setNameSource(v === 'auto' ? '' : v)}
  231. disabled={saving || (device.nameCandidates ?? []).length < 2}
  232. >
  233. <SelectTrigger className="h-9 rounded-lg border-border bg-elevated text-sm text-text-primary">
  234. <SelectValue />
  235. </SelectTrigger>
  236. <SelectContent>
  237. <SelectItem value="auto">{t('devices.edit.nameSourceAuto')}</SelectItem>
  238. {(device.nameCandidates ?? []).map((c) => (
  239. <SelectItem key={c.source} value={c.source}>
  240. {t(`devices.detail.source.${c.source}`)}
  241. </SelectItem>
  242. ))}
  243. </SelectContent>
  244. </Select>
  245. <p className="text-caption text-text-muted">
  246. {(device.nameCandidates ?? []).length < 2 ? t('devices.edit.nameSourceNone') : t('devices.edit.nameSourceHint')}
  247. </p>
  248. </div>
  249. {/* Tipo (#797) */}
  250. <div className="space-y-2">
  251. <label className="text-label uppercase text-text-muted">{t('devices.edit.type')}</label>
  252. <Select value={devType || 'auto'} onValueChange={(v) => setDevType(v === 'auto' ? '' : v)} disabled={saving}>
  253. <SelectTrigger className="h-9 rounded-lg border-border bg-elevated text-sm text-text-primary">
  254. <SelectValue />
  255. </SelectTrigger>
  256. <SelectContent>
  257. <SelectItem value="auto">{t('devices.edit.auto')}</SelectItem>
  258. {DEVICE_TYPES.map((ty) => (
  259. <SelectItem key={ty} value={ty}>{t(`devices.types.${ty}`)}</SelectItem>
  260. ))}
  261. </SelectContent>
  262. </Select>
  263. </div>
  264. {/* Icono */}
  265. <div className="space-y-2">
  266. <label className="text-label uppercase text-text-muted">{t('devices.edit.icon')}</label>
  267. <IconPicker value={icon} onChange={setIcon} disabled={saving} columns={5} />
  268. </div>
  269. {/* #1354: alerta opt-in cuando el dispositivo se desconecta */}
  270. <div className="flex items-center justify-between rounded-xl border border-border bg-elevated/40 p-3">
  271. <label className="text-label uppercase text-text-muted">{t('devices.edit.notifyOffline')}</label>
  272. <Switch
  273. checked={notifyOffline}
  274. onCheckedChange={setNotifyOffline}
  275. disabled={saving}
  276. aria-label={t('devices.edit.notifyOffline')}
  277. />
  278. </div>
  279. {/* #1096: Save/Cancel junto a la zona que editan (nombre, tipo,
  280. icono); abajo quedaban lejos, tras Reserva/Bloqueo, que son
  281. acciones independientes con sus propios botones. */}
  282. <div className="flex gap-3">
  283. <Button variant="outline" className="flex-1" onClick={onClose} disabled={saving}>
  284. {t('common.cancel')}
  285. </Button>
  286. <Button className="flex-1" onClick={handleSave} disabled={saving}>
  287. {saving ? t('common.loading') : t('devices.edit.save')}
  288. </Button>
  289. </div>
  290. {/* Detalles de red */}
  291. <div className="grid grid-cols-2 gap-3 rounded-xl border border-border bg-elevated/40 p-3 text-sm">
  292. <div>
  293. <div className="text-label uppercase text-text-muted">IP</div>
  294. <div className="font-mono text-text-primary">{device.ip}</div>
  295. </div>
  296. <div>
  297. <div className="text-label uppercase text-text-muted">{t('devices.colBand')}</div>
  298. <div className="text-text-primary">{device.band === 'cable' ? t('common.cable') : device.band}</div>
  299. </div>
  300. </div>
  301. {/* Reserva DHCP */}
  302. <div className="space-y-2 rounded-xl border border-border bg-elevated/40 p-3">
  303. <div className="flex items-center justify-between">
  304. <label className="text-label uppercase text-text-muted">{t('devices.edit.reserveTitle')}</label>
  305. {reservation.loading && <span className="text-caption text-text-muted">{t('common.loading')}</span>}
  306. </div>
  307. {reservation.reserved ? (
  308. <>
  309. <p className="text-sm text-text-secondary">
  310. {t('devices.edit.reservedAs', { ip: reservation.ip })}
  311. </p>
  312. <div className="flex gap-2">
  313. <Button
  314. variant="outline"
  315. size="sm"
  316. className="flex-1"
  317. disabled={reservation.loading || reserveDraft === device.ip}
  318. onClick={() => setReserveDraft(device.ip)}
  319. >
  320. {t('devices.edit.useCurrentIp')}
  321. </Button>
  322. <Button
  323. variant="outline"
  324. size="sm"
  325. className="flex-1 border-danger/30 text-danger hover:bg-danger/10"
  326. disabled={reservation.loading}
  327. onClick={async () => {
  328. if (!device) return
  329. setReservation((p) => ({ ...p, loading: true }))
  330. const res = await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}/reservation`, { method: 'DELETE' })
  331. setReservation({ reserved: !res.ok, ip: res.ok ? '' : reservation.ip, loading: false })
  332. }}
  333. >
  334. {t('devices.edit.removeReserve')}
  335. </Button>
  336. </div>
  337. </>
  338. ) : (
  339. <p className="text-caption text-text-muted">{t('devices.edit.reserveHint')}</p>
  340. )}
  341. <div className="flex items-center gap-2">
  342. <Input
  343. value={reserveDraft}
  344. onChange={(e) => setReserveDraft(e.target.value)}
  345. placeholder={device.ip}
  346. disabled={reservation.loading}
  347. className="h-9 rounded-lg border-border bg-elevated text-sm text-text-primary placeholder:text-text-muted focus-visible:border-accent/50"
  348. />
  349. <Button
  350. size="sm"
  351. disabled={reservation.loading || !reserveDraft}
  352. onClick={async () => {
  353. if (!device) return
  354. setReservation((p) => ({ ...p, loading: true }))
  355. const path = `/api/devices/${encodeURIComponent(device.mac)}/reservation`
  356. const body = { ip: reserveDraft, hostname: asDhcpHostname(device.name) }
  357. const applyReserve = async () => {
  358. const res = await fetchJson(path, {
  359. method: 'PUT',
  360. headers: { 'Content-Type': 'application/json' },
  361. body: JSON.stringify(body),
  362. })
  363. if (res.ok) {
  364. setReservation({ reserved: true, ip: reserveDraft, loading: false })
  365. } else {
  366. setReservation((p) => ({ ...p, loading: false }))
  367. }
  368. }
  369. // #754: primero el plan de comandos; se aplica al confirmar.
  370. const planned = await openPlan(path, body, applyReserve)
  371. if (!planned) {
  372. await applyReserve()
  373. } else {
  374. setReservation((p) => ({ ...p, loading: false }))
  375. }
  376. }}
  377. >
  378. {t('devices.edit.saveReserve')}
  379. </Button>
  380. </div>
  381. {/* #800: aplicar el nombre visible como hostname de la reserva */}
  382. <div className="space-y-1.5">
  383. <Button
  384. variant="outline"
  385. size="sm"
  386. className="w-full"
  387. disabled={reservation.loading || !appliedHostname}
  388. onClick={async () => {
  389. if (!device || !appliedHostname) return
  390. setReservation((p) => ({ ...p, loading: true }))
  391. const path = `/api/devices/${encodeURIComponent(device.mac)}/reservation-hostname`
  392. const body = { hostname: appliedHostname, ip: reserveDraft || device.ip }
  393. const applyName = async () => {
  394. const res = await fetchJson<{ ip?: string }>(path, {
  395. method: 'PUT',
  396. headers: { 'Content-Type': 'application/json' },
  397. body: JSON.stringify(body),
  398. })
  399. if (res.ok) {
  400. setReservation({ reserved: true, ip: res.data?.ip ?? body.ip, loading: false })
  401. } else {
  402. setReservation((p) => ({ ...p, loading: false }))
  403. }
  404. }
  405. // #754: primero el plan de comandos; se aplica al confirmar.
  406. const planned = await openPlan(path, body, applyName)
  407. if (!planned) {
  408. await applyName()
  409. } else {
  410. setReservation((p) => ({ ...p, loading: false }))
  411. }
  412. }}
  413. >
  414. {t('devices.edit.applyName')}
  415. </Button>
  416. <p className="text-caption text-text-muted">
  417. {appliedHostname ? t('devices.edit.applyNameHint') : t('devices.edit.applyNameInvalid')}
  418. </p>
  419. </div>
  420. </div>
  421. {/* Bloqueo de dispositivo */}
  422. <div className="space-y-2 rounded-xl border border-border bg-elevated/40 p-3">
  423. <div className="flex items-center justify-between">
  424. <label className="text-label uppercase text-text-muted">{t('devices.edit.blockTitle')}</label>
  425. {block.loading && <span className="text-caption text-text-muted">{t('common.loading')}</span>}
  426. </div>
  427. <p className="text-caption text-text-muted">{t('devices.edit.blockHint')}</p>
  428. <div className="flex items-center justify-between rounded-lg border border-border bg-elevated p-2">
  429. <span className={cn('text-sm font-medium', block.blocked ? 'text-danger' : 'text-text-secondary')}>
  430. {block.blocked ? t('devices.edit.blocked') : t('devices.edit.allowed')}
  431. </span>
  432. <Button
  433. variant={block.blocked ? 'default' : 'destructive'}
  434. size="sm"
  435. disabled={block.loading}
  436. onClick={async () => {
  437. if (!device) return
  438. const url = `/api/devices/${encodeURIComponent(device.mac)}/block`
  439. const body = { router: device.routerId }
  440. if (block.blocked) {
  441. // Desbloquear (DELETE): quitar la regla no necesita plan.
  442. setBlock((p) => ({ ...p, loading: true }))
  443. const res = await fetchJson(url, {
  444. method: 'DELETE',
  445. headers: { 'Content-Type': 'application/json' },
  446. body: JSON.stringify(body),
  447. })
  448. if (res.ok) {
  449. setBlock({ blocked: false, loading: false })
  450. } else {
  451. setBlock((p) => ({ ...p, loading: false }))
  452. }
  453. return
  454. }
  455. // Bloquear (#754): plan de comandos primero, aplicar al confirmar.
  456. setBlock((p) => ({ ...p, loading: true }))
  457. const applyBlock = async () => {
  458. const res = await fetchJson(url, {
  459. method: 'PUT',
  460. headers: { 'Content-Type': 'application/json' },
  461. body: JSON.stringify(body),
  462. })
  463. if (res.ok) {
  464. setBlock({ blocked: true, loading: false })
  465. } else {
  466. setBlock((p) => ({ ...p, loading: false }))
  467. }
  468. }
  469. const planned = await openPlan(url, body, applyBlock)
  470. if (!planned) {
  471. await applyBlock()
  472. } else {
  473. setBlock((p) => ({ ...p, loading: false }))
  474. }
  475. }}
  476. >
  477. {block.blocked ? t('devices.edit.unblock') : t('devices.edit.block')}
  478. </Button>
  479. </div>
  480. </div>
  481. {/* Plan de comandos (#754): nada se aplica hasta confirmar aquí */}
  482. {plan && (
  483. <div className="space-y-2 rounded-xl border border-warn/40 bg-warn/5 p-3" role="dialog" aria-label={t('devices.edit.planTitle', { host: plan.host })}>
  484. <div className="text-label uppercase tracking-wide text-warn">
  485. {t('devices.edit.planTitle', { host: plan.host || device?.routerId || '' })}
  486. </div>
  487. <pre className="overflow-x-auto rounded-lg border border-border bg-canvas p-2 font-mono text-caption leading-relaxed text-text-primary">
  488. {plan.apply.length ? plan.apply.join('\n') : t('devices.edit.planNone')}
  489. </pre>
  490. {plan.rollback.length > 0 && (
  491. <details className="text-caption text-text-muted">
  492. <summary className="cursor-pointer select-none">{t('devices.edit.planRollback')}</summary>
  493. <pre className="mt-1 overflow-x-auto rounded-lg border border-border bg-canvas p-2 font-mono text-caption leading-relaxed">
  494. {plan.rollback.join('\n')}
  495. </pre>
  496. </details>
  497. )}
  498. <div className="flex items-center gap-2">
  499. <Button
  500. size="sm"
  501. disabled={planBusy}
  502. onClick={async () => {
  503. setPlanBusy(true)
  504. try {
  505. await planRun?.()
  506. } finally {
  507. setPlanBusy(false)
  508. closePlan()
  509. }
  510. }}
  511. >
  512. {planBusy ? t('common.loading') : t('devices.edit.planRun')}
  513. </Button>
  514. <Button size="sm" variant="outline" disabled={planBusy} onClick={closePlan}>
  515. {t('common.cancel')}
  516. </Button>
  517. </div>
  518. </div>
  519. )}
  520. {/* #1151: MACs enlazadas (mismo dispositivo, varias MACs) */}
  521. {!isDemo && device?.mac && (
  522. <div className="rounded-xl border border-border bg-elevated/40 p-3">
  523. <div className="text-label uppercase tracking-wide text-text-muted">{t('devices.edit.linkedMacs')}</div>
  524. {(device.aliasMacs?.length ?? 0) > 0 && (
  525. <ul className="mb-2 mt-1.5 space-y-1">
  526. {device.aliasMacs?.map((alias) => (
  527. <li key={alias} className="flex items-center justify-between gap-2 rounded-lg bg-canvas/60 px-2 py-1.5">
  528. <span className="font-mono text-mono-sm text-text-primary">{alias}</span>
  529. <button
  530. type="button"
  531. disabled={linkBusy}
  532. onClick={() => void unlinkAlias(alias)}
  533. className="rounded-md px-2 py-0.5 text-caption text-text-secondary transition-colors hover:bg-hover hover:text-text-primary"
  534. >
  535. {t('devices.edit.unlink')}
  536. </button>
  537. </li>
  538. ))}
  539. </ul>
  540. )}
  541. {otherClients.length > 0 && (
  542. <div className="mt-2 flex items-center gap-2">
  543. <Select value={linkTarget} onValueChange={setLinkTarget}>
  544. <SelectTrigger className="h-9 flex-1">
  545. <SelectValue placeholder={t('devices.edit.linkPlaceholder')} />
  546. </SelectTrigger>
  547. <SelectContent>
  548. {otherClients.map((c) => (
  549. <SelectItem key={c.mac} value={c.mac ?? ''}>
  550. {c.name || c.mac}
  551. </SelectItem>
  552. ))}
  553. </SelectContent>
  554. </Select>
  555. <Button size="sm" variant="outline" disabled={!linkTarget || linkBusy} onClick={() => void linkClient()}>
  556. {linkBusy ? t('common.loading') : t('devices.edit.link')}
  557. </Button>
  558. </div>
  559. )}
  560. </div>
  561. )}
  562. {isDemo && (
  563. <p className="rounded-lg border border-warn/30 bg-warn/10 p-3 text-caption text-warn">
  564. {t('devices.edit.demoNotice')}
  565. </p>
  566. )}
  567. {/* #1145: borrado del cliente del registro. Un cliente borrado
  568. solo reaparece si se le vuelve a ver en vivo. #1205: el botón
  569. solo tiene sentido para clientes offline (los online los
  570. re-detecta el siguiente ciclo del poller y parece que "no
  571. borra"): para ellos se sugiere Bloquear. */}
  572. {!isDemo && device?.mac && device.online === false && (
  573. <div className="rounded-xl border border-danger/30 bg-danger/5 p-3">
  574. <div className="text-label uppercase tracking-wide text-danger">{t('devices.edit.dangerZone')}</div>
  575. <p className="mb-2 mt-1 text-caption text-text-muted">{t('devices.edit.deleteDesc')}</p>
  576. <Button variant="destructive" size="sm" onClick={() => setDeleteOpen(true)} disabled={deleting}>
  577. {t('devices.edit.delete')}
  578. </Button>
  579. </div>
  580. )}
  581. {!isDemo && device?.mac && device.online && (
  582. <div className="rounded-xl border border-border bg-elevated p-3">
  583. <div className="text-label uppercase tracking-wide text-text-muted">{t('devices.edit.dangerZone')}</div>
  584. <p className="mt-1 text-caption text-text-muted">{t('devices.edit.deleteOnlineHint')}</p>
  585. </div>
  586. )}
  587. </div>
  588. )}
  589. <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
  590. {/* #1205: el aviso lleva el mismo tinte rojo que la zona que lo abre */}
  591. <AlertDialogContent className="border-danger/40 bg-surface">
  592. <AlertDialogHeader>
  593. <AlertDialogTitle>{t('devices.edit.deleteTitle')}</AlertDialogTitle>
  594. <AlertDialogDescription>
  595. {t('devices.edit.deleteConfirmDesc', { name: device?.name || device?.mac || '' })}
  596. </AlertDialogDescription>
  597. </AlertDialogHeader>
  598. <AlertDialogFooter>
  599. <AlertDialogCancel disabled={deleting}>{t('common.cancel')}</AlertDialogCancel>
  600. <AlertDialogAction
  601. disabled={deleting}
  602. className="bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20"
  603. onClick={async (e) => {
  604. e.preventDefault()
  605. if (!device?.mac) return
  606. setDeleting(true)
  607. try {
  608. await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}`, { method: 'DELETE' })
  609. // #1205: refresco inmediato - si no, la fila seguiría en
  610. // pantalla hasta el próximo ciclo y parecería que no borra
  611. void refresh()
  612. setDeleteOpen(false)
  613. onDeleted?.()
  614. onClose()
  615. } catch {
  616. // el fallo deja la hoja abierta; el botón vuelve a habilitarse
  617. } finally {
  618. setDeleting(false)
  619. }
  620. }}
  621. >
  622. {deleting ? t('common.loading') : t('devices.edit.delete')}
  623. </AlertDialogAction>
  624. </AlertDialogFooter>
  625. </AlertDialogContent>
  626. </AlertDialog>
  627. </SheetContent>
  628. </Sheet>
  629. )
  630. }