HASensorModal.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import { useEffect, useMemo, useState } from 'react';
  2. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { Gauge, Loader2, Save, Search, X } from 'lucide-react';
  4. import { useTranslation } from 'react-i18next';
  5. import { api } from '../api/client';
  6. import type { HADisplayEntity, Printer, PrinterHASensor } from '../api/client';
  7. import { Button } from './Button';
  8. import { useToast } from '../contexts/ToastContext';
  9. /**
  10. * Bind a Home Assistant entity to a printer, or edit an existing binding
  11. * (#1148, #448).
  12. *
  13. * The entity picker is the load-bearing part: kind, device_class and unit all
  14. * come from the entity rather than from the user, because getting any of them
  15. * wrong is a validation error from the backend that nobody could act on.
  16. */
  17. interface Props {
  18. sensor?: PrinterHASensor | null;
  19. printers: Printer[];
  20. onClose: () => void;
  21. }
  22. // The alert wording follows the device class, so a door offers "Open" rather
  23. // than "On". Shared with PrinterHASensorRow's rendering of the same classes.
  24. const ALERT_LABEL_KEYS: Record<string, { on: string; off: string }> = {
  25. door: { on: 'open', off: 'closed' },
  26. garage_door: { on: 'open', off: 'closed' },
  27. window: { on: 'open', off: 'closed' },
  28. opening: { on: 'open', off: 'closed' },
  29. lock: { on: 'unlocked', off: 'locked' },
  30. motion: { on: 'detected', off: 'clear' },
  31. occupancy: { on: 'detected', off: 'clear' },
  32. presence: { on: 'detected', off: 'clear' },
  33. smoke: { on: 'detected', off: 'clear' },
  34. gas: { on: 'detected', off: 'clear' },
  35. moisture: { on: 'wet', off: 'dry' },
  36. problem: { on: 'problem', off: 'ok' },
  37. safety: { on: 'problem', off: 'ok' },
  38. running: { on: 'running', off: 'stopped' },
  39. };
  40. export function HASensorModal({ sensor, printers, onClose }: Props) {
  41. const { t } = useTranslation();
  42. const queryClient = useQueryClient();
  43. const { showToast } = useToast();
  44. const isEditing = !!sensor;
  45. const [printerId, setPrinterId] = useState<number | ''>(sensor?.printer_id ?? printers[0]?.id ?? '');
  46. const [entityId, setEntityId] = useState(sensor?.entity_id ?? '');
  47. const [kind, setKind] = useState<'binary' | 'numeric'>(sensor?.kind ?? 'binary');
  48. const [deviceClass, setDeviceClass] = useState<string | null>(sensor?.device_class ?? null);
  49. const [unit, setUnit] = useState<string | null>(sensor?.unit ?? null);
  50. const [name, setName] = useState(sensor?.name ?? '');
  51. const [alertState, setAlertState] = useState<'on' | 'off' | ''>(sensor?.alert_state ?? '');
  52. const [alertAbove, setAlertAbove] = useState(sensor?.alert_above?.toString() ?? '');
  53. const [alertBelow, setAlertBelow] = useState(sensor?.alert_below?.toString() ?? '');
  54. const [showOnCard, setShowOnCard] = useState(sensor?.show_on_printer_card ?? true);
  55. const [notifyOnAlert, setNotifyOnAlert] = useState(sensor?.notify_on_alert ?? false);
  56. const [blockPrint, setBlockPrint] = useState(sensor?.block_print ?? false);
  57. const [search, setSearch] = useState('');
  58. const [error, setError] = useState<string | null>(null);
  59. useEffect(() => {
  60. const onKey = (e: KeyboardEvent) => {
  61. if (e.key === 'Escape') onClose();
  62. };
  63. window.addEventListener('keydown', onKey);
  64. return () => window.removeEventListener('keydown', onKey);
  65. }, [onClose]);
  66. // Same gate and the same wording as AddSmartPlugModal: without a configured
  67. // Home Assistant the picker can only return an error, so say why up front
  68. // instead of showing an empty list.
  69. const { data: settings } = useQuery({
  70. queryKey: ['settings'],
  71. queryFn: api.getSettings,
  72. });
  73. const haConfigured = !!(settings?.ha_enabled && settings?.ha_url && settings?.ha_token);
  74. const { data: entities, isLoading: entitiesLoading, error: entitiesError } = useQuery({
  75. queryKey: ['bindableHAEntities'],
  76. queryFn: () => api.getBindableHAEntities(),
  77. enabled: haConfigured,
  78. });
  79. const filtered = useMemo(() => {
  80. const needle = search.trim().toLowerCase();
  81. const all = entities ?? [];
  82. if (!needle) return all;
  83. return all.filter(
  84. (e) => e.entity_id.toLowerCase().includes(needle) || e.friendly_name.toLowerCase().includes(needle)
  85. );
  86. }, [entities, search]);
  87. const selectEntity = (entity: HADisplayEntity) => {
  88. setEntityId(entity.entity_id);
  89. setDeviceClass(entity.device_class);
  90. setUnit(entity.unit_of_measurement);
  91. const nextKind = entity.domain === 'binary_sensor' ? 'binary' : 'numeric';
  92. setKind(nextKind);
  93. // Switching kind strands the other kind's alert fields, and the backend
  94. // rejects a numeric sensor that still carries an alert_state.
  95. if (nextKind === 'numeric') setAlertState('');
  96. else {
  97. setAlertAbove('');
  98. setAlertBelow('');
  99. }
  100. // Sliced to the column width: Home Assistant friendly names have no length
  101. // limit, and a long one would come back as a Pydantic error on a field the
  102. // user did not type into.
  103. if (!name.trim()) setName(entity.friendly_name.slice(0, 100));
  104. };
  105. const invalidate = () => {
  106. queryClient.invalidateQueries({ queryKey: ['haSensors'] });
  107. queryClient.invalidateQueries({ queryKey: ['haSensorReadings'] });
  108. };
  109. const saveMutation = useMutation({
  110. mutationFn: () => {
  111. const payload = {
  112. name: name.trim(),
  113. entity_id: entityId,
  114. kind,
  115. device_class: deviceClass,
  116. unit,
  117. alert_state: kind === 'binary' && alertState ? alertState : null,
  118. alert_above: kind === 'numeric' && alertAbove !== '' ? Number(alertAbove) : null,
  119. alert_below: kind === 'numeric' && alertBelow !== '' ? Number(alertBelow) : null,
  120. block_print: blockPrint,
  121. notify_on_alert: notifyOnAlert,
  122. show_on_printer_card: showOnCard,
  123. };
  124. return isEditing
  125. ? api.updateHASensor(sensor.id, payload)
  126. : api.createHASensor({ ...payload, printer_id: Number(printerId) });
  127. },
  128. onSuccess: () => {
  129. invalidate();
  130. showToast(isEditing ? t('haSensors.toast.updated') : t('haSensors.toast.created'), 'success');
  131. onClose();
  132. },
  133. onError: (err: Error) => setError(err.message),
  134. });
  135. const deleteMutation = useMutation({
  136. mutationFn: () => api.deleteHASensor(sensor!.id),
  137. onSuccess: () => {
  138. invalidate();
  139. showToast(t('haSensors.toast.deleted'), 'success');
  140. onClose();
  141. },
  142. onError: (err: Error) => setError(err.message),
  143. });
  144. const hasAlertCondition =
  145. kind === 'binary' ? alertState !== '' : alertAbove !== '' || alertBelow !== '';
  146. const handleSubmit = (e: React.FormEvent) => {
  147. e.preventDefault();
  148. setError(null);
  149. if (!entityId) return setError(t('haSensors.error.pickEntity'));
  150. if (!name.trim()) return setError(t('haSensors.error.nameRequired'));
  151. if (printerId === '') return setError(t('haSensors.error.printerRequired'));
  152. // Mirrors the backend rule, so the user is told before the round trip
  153. // rather than by a 422.
  154. if ((blockPrint || notifyOnAlert) && !hasAlertCondition) {
  155. return setError(t('haSensors.error.alertRequired'));
  156. }
  157. saveMutation.mutate();
  158. };
  159. const alertLabels = ALERT_LABEL_KEYS[deviceClass ?? ''];
  160. const stateLabel = (which: 'on' | 'off') => {
  161. const key = alertLabels?.[which] ?? which;
  162. return t(`haSensors.states.${key}`, { defaultValue: key });
  163. };
  164. const isPending = saveMutation.isPending || deleteMutation.isPending;
  165. return (
  166. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4" onClick={onClose}>
  167. <div
  168. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto"
  169. onClick={(e) => e.stopPropagation()}
  170. >
  171. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  172. <div className="flex items-center gap-3">
  173. <div className="p-2 rounded-full bg-bambu-green/20 text-bambu-green">
  174. <Gauge className="w-5 h-5" />
  175. </div>
  176. <h2 className="text-lg font-semibold text-white">
  177. {isEditing ? t('haSensors.editTitle') : t('haSensors.addTitle')}
  178. </h2>
  179. </div>
  180. <button onClick={onClose} className="text-bambu-gray hover:text-white transition-colors">
  181. <X className="w-5 h-5" />
  182. </button>
  183. </div>
  184. <form onSubmit={handleSubmit} className="p-6 space-y-4">
  185. {error && (
  186. <div className="p-3 bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 rounded-lg text-sm text-red-700 dark:text-red-400">
  187. {error}
  188. </div>
  189. )}
  190. {!isEditing && (
  191. <div>
  192. <label className="block text-sm text-bambu-gray mb-1">{t('haSensors.printer')}</label>
  193. <select
  194. value={printerId}
  195. onChange={(e) => setPrinterId(e.target.value === '' ? '' : Number(e.target.value))}
  196. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white"
  197. >
  198. {printers.map((p) => (
  199. <option key={p.id} value={p.id}>
  200. {p.name}
  201. </option>
  202. ))}
  203. </select>
  204. </div>
  205. )}
  206. {!haConfigured && (
  207. <div className="p-3 bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-400 dark:border-yellow-500/50 rounded-lg text-sm text-yellow-700 dark:text-yellow-400">
  208. {t('smartPlugs.haNotConfigured')}{' '}
  209. <span className="font-medium">{t('smartPlugs.haSettingsPath')}</span>
  210. </div>
  211. )}
  212. <div>
  213. <label className={`block text-sm text-bambu-gray mb-1 ${haConfigured ? '' : 'opacity-50'}`}>
  214. {t('haSensors.entity')}
  215. </label>
  216. {entitiesError && (
  217. <div className="p-3 mb-2 bg-red-100 dark:bg-red-500/20 rounded-lg text-sm text-red-700 dark:text-red-400">
  218. {(entitiesError as Error).message}
  219. </div>
  220. )}
  221. <div className="relative mb-2">
  222. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  223. <input
  224. type="text"
  225. value={search}
  226. onChange={(e) => setSearch(e.target.value)}
  227. placeholder={t('haSensors.searchPlaceholder')}
  228. disabled={!haConfigured}
  229. className="w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white disabled:opacity-50 disabled:cursor-not-allowed"
  230. />
  231. </div>
  232. <div
  233. className={`max-h-44 overflow-y-auto rounded-lg border border-bambu-dark-tertiary ${
  234. haConfigured ? '' : 'opacity-50'
  235. }`}
  236. >
  237. {!haConfigured && (
  238. <div className="p-3 text-sm text-bambu-gray">{t('haSensors.noEntities')}</div>
  239. )}
  240. {haConfigured && entitiesLoading && (
  241. <div className="flex items-center gap-2 p-3 text-sm text-bambu-gray">
  242. <Loader2 className="w-4 h-4 animate-spin" />
  243. {t('common.loading')}
  244. </div>
  245. )}
  246. {haConfigured && !entitiesLoading && filtered.length === 0 && (
  247. <div className="p-3 text-sm text-bambu-gray">{t('haSensors.noEntities')}</div>
  248. )}
  249. {haConfigured &&
  250. !entitiesLoading &&
  251. filtered.map((entity) => (
  252. <button
  253. key={entity.entity_id}
  254. type="button"
  255. onClick={() => selectEntity(entity)}
  256. className={`w-full text-left px-3 py-2 text-sm transition-colors ${
  257. entity.entity_id === entityId
  258. ? 'bg-bambu-green/20 text-bambu-green'
  259. : 'text-white hover:bg-bambu-dark'
  260. }`}
  261. >
  262. <div className="font-medium">{entity.friendly_name}</div>
  263. <div className="text-xs text-bambu-gray">
  264. {entity.entity_id}
  265. {entity.state !== null && ` — ${entity.state}`}
  266. {entity.unit_of_measurement ? ` ${entity.unit_of_measurement}` : ''}
  267. </div>
  268. </button>
  269. ))}
  270. </div>
  271. </div>
  272. <div>
  273. <label className="block text-sm text-bambu-gray mb-1">{t('haSensors.name')}</label>
  274. <input
  275. type="text"
  276. value={name}
  277. onChange={(e) => setName(e.target.value)}
  278. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white"
  279. />
  280. </div>
  281. <div>
  282. <label className="block text-sm text-bambu-gray mb-1">{t('haSensors.alertWhen')}</label>
  283. {kind === 'binary' ? (
  284. <select
  285. value={alertState}
  286. onChange={(e) => setAlertState(e.target.value as 'on' | 'off' | '')}
  287. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white"
  288. >
  289. <option value="">{t('haSensors.alertNever')}</option>
  290. <option value="on">{stateLabel('on')}</option>
  291. <option value="off">{stateLabel('off')}</option>
  292. </select>
  293. ) : (
  294. <div className="grid grid-cols-2 gap-3">
  295. <div>
  296. <span className="block text-xs text-bambu-gray mb-1">
  297. {t('haSensors.alertAbove')} {unit ?? ''}
  298. </span>
  299. <input
  300. type="number"
  301. step="any"
  302. value={alertAbove}
  303. onChange={(e) => setAlertAbove(e.target.value)}
  304. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white"
  305. />
  306. </div>
  307. <div>
  308. <span className="block text-xs text-bambu-gray mb-1">
  309. {t('haSensors.alertBelow')} {unit ?? ''}
  310. </span>
  311. <input
  312. type="number"
  313. step="any"
  314. value={alertBelow}
  315. onChange={(e) => setAlertBelow(e.target.value)}
  316. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white"
  317. />
  318. </div>
  319. </div>
  320. )}
  321. <p className="mt-1 text-xs text-bambu-gray">{t('haSensors.alertHint')}</p>
  322. </div>
  323. <label className="flex items-center gap-3 cursor-pointer">
  324. <input
  325. type="checkbox"
  326. checked={showOnCard}
  327. onChange={(e) => setShowOnCard(e.target.checked)}
  328. className="w-4 h-4"
  329. />
  330. <span className="text-sm text-white">{t('haSensors.showOnCard')}</span>
  331. </label>
  332. <label className="flex items-center gap-3 cursor-pointer">
  333. <input
  334. type="checkbox"
  335. checked={notifyOnAlert}
  336. onChange={(e) => setNotifyOnAlert(e.target.checked)}
  337. disabled={!hasAlertCondition}
  338. className="w-4 h-4"
  339. />
  340. <span className={`text-sm ${hasAlertCondition ? 'text-white' : 'text-bambu-gray'}`}>
  341. {t('haSensors.notifyOnAlert')}
  342. </span>
  343. </label>
  344. <label className="flex items-start gap-3 cursor-pointer">
  345. <input
  346. type="checkbox"
  347. checked={blockPrint}
  348. onChange={(e) => setBlockPrint(e.target.checked)}
  349. disabled={!hasAlertCondition}
  350. className="w-4 h-4 mt-0.5"
  351. />
  352. <span>
  353. <span className={`block text-sm ${hasAlertCondition ? 'text-white' : 'text-bambu-gray'}`}>
  354. {t('haSensors.blockPrint')}
  355. </span>
  356. <span className="block text-xs text-bambu-gray">{t('haSensors.blockPrintHint')}</span>
  357. </span>
  358. </label>
  359. <div className="flex items-center justify-between pt-2">
  360. {isEditing ? (
  361. <Button type="button" variant="danger" onClick={() => deleteMutation.mutate()} disabled={isPending}>
  362. {t('common.delete')}
  363. </Button>
  364. ) : (
  365. <span />
  366. )}
  367. <div className="flex items-center gap-2">
  368. <Button type="button" variant="secondary" onClick={onClose} disabled={isPending}>
  369. {t('common.cancel')}
  370. </Button>
  371. {/* An unconfigured Home Assistant leaves nothing to bind to.
  372. Editing an existing sensor still saves — its alert rule and
  373. card visibility are Bambuddy's own settings and do not need
  374. Home Assistant to be reachable to change. */}
  375. <Button type="submit" disabled={isPending || (!haConfigured && !isEditing)}>
  376. {isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
  377. {t('common.save')}
  378. </Button>
  379. </div>
  380. </div>
  381. </form>
  382. </div>
  383. </div>
  384. );
  385. }