SmartPlugCard.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. import { useState } from 'react';
  2. import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
  3. import { Plug, Power, PowerOff, Loader2, Trash2, Settings2, Thermometer, Clock, Wifi, WifiOff, Edit2, Bell, Calendar, LayoutGrid, ExternalLink, Home, Radio, Eye } from 'lucide-react';
  4. import { useTranslation } from 'react-i18next';
  5. import { api } from '../api/client';
  6. import type { SmartPlug, SmartPlugUpdate } from '../api/client';
  7. import { Card, CardContent } from './Card';
  8. import { Button } from './Button';
  9. import { ConfirmModal } from './ConfirmModal';
  10. import { useToast } from '../contexts/ToastContext';
  11. interface SmartPlugCardProps {
  12. plug: SmartPlug;
  13. onEdit: (plug: SmartPlug) => void;
  14. }
  15. export function SmartPlugCard({ plug, onEdit }: SmartPlugCardProps) {
  16. const { t } = useTranslation();
  17. const queryClient = useQueryClient();
  18. const { showToast } = useToast();
  19. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  20. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  21. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  22. const [isExpanded, setIsExpanded] = useState(false);
  23. // Fetch current status
  24. const { data: status, isLoading: statusLoading } = useQuery({
  25. queryKey: ['smart-plug-status', plug.id],
  26. queryFn: () => api.getSmartPlugStatus(plug.id),
  27. refetchInterval: 30000, // Refresh every 30 seconds
  28. });
  29. // Fetch printers for linking
  30. const { data: printers } = useQuery({
  31. queryKey: ['printers'],
  32. queryFn: api.getPrinters,
  33. });
  34. const linkedPrinter = printers?.find(p => p.id === plug.printer_id);
  35. // Control mutation with optimistic updates
  36. const controlMutation = useMutation({
  37. mutationFn: (action: 'on' | 'off' | 'toggle') => api.controlSmartPlug(plug.id, action),
  38. onMutate: async (action) => {
  39. // Cancel any outgoing refetches
  40. await queryClient.cancelQueries({ queryKey: ['smart-plug-status', plug.id] });
  41. // Snapshot the previous value
  42. const previousStatus = queryClient.getQueryData(['smart-plug-status', plug.id]);
  43. // Optimistically update to the new value
  44. const newState = action === 'on' ? 'ON' : action === 'off' ? 'OFF' : (status?.state === 'ON' ? 'OFF' : 'ON');
  45. queryClient.setQueryData(['smart-plug-status', plug.id], (old: typeof status) => ({
  46. ...old,
  47. state: newState,
  48. }));
  49. return { previousStatus };
  50. },
  51. onError: (_err, action, context) => {
  52. // Rollback on error
  53. if (context?.previousStatus) {
  54. queryClient.setQueryData(['smart-plug-status', plug.id], context.previousStatus);
  55. }
  56. showToast(`Failed to turn ${action} "${plug.name}"`, 'error');
  57. },
  58. onSettled: () => {
  59. // Refetch after a short delay to get actual state
  60. setTimeout(() => {
  61. queryClient.invalidateQueries({ queryKey: ['smart-plug-status', plug.id] });
  62. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  63. }, 1000);
  64. },
  65. });
  66. // Update mutation
  67. const updateMutation = useMutation({
  68. mutationFn: (data: SmartPlugUpdate) => api.updateSmartPlug(plug.id, data),
  69. onSuccess: () => {
  70. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  71. // Also invalidate printer-specific smart plug queries to keep PrintersPage in sync
  72. if (plug.printer_id) {
  73. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', plug.printer_id] });
  74. queryClient.invalidateQueries({ queryKey: ['scriptPlugsByPrinter', plug.printer_id] });
  75. }
  76. },
  77. });
  78. // Delete mutation
  79. const deleteMutation = useMutation({
  80. mutationFn: () => api.deleteSmartPlug(plug.id),
  81. onSuccess: () => {
  82. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  83. // Also invalidate printer card HA entity queries
  84. if (plug.printer_id) {
  85. queryClient.invalidateQueries({ queryKey: ['scriptPlugsByPrinter', plug.printer_id] });
  86. }
  87. },
  88. });
  89. const isOn = status?.state === 'ON';
  90. // For MQTT plugs, consider reachable if we have power data (even if backend says not reachable)
  91. const hasMqttData = plug.plug_type === 'mqtt' && (status?.energy?.power !== null && status?.energy?.power !== undefined);
  92. const isReachable = (status?.reachable ?? false) || hasMqttData;
  93. const isPending = controlMutation.isPending;
  94. // Generate admin URL with auto-login credentials (Tasmota only)
  95. const getAdminUrl = () => {
  96. if (plug.plug_type !== 'tasmota' || !plug.ip_address) return null;
  97. const ip = plug.ip_address;
  98. if (plug.username && plug.password) {
  99. // Use HTTP Basic Auth in URL for auto-login
  100. return `http://${encodeURIComponent(plug.username)}:${encodeURIComponent(plug.password)}@${ip}/`;
  101. }
  102. return `http://${ip}/`;
  103. };
  104. const adminUrl = getAdminUrl();
  105. return (
  106. <>
  107. <Card className="relative">
  108. <CardContent className="p-4">
  109. {/* Header Row */}
  110. <div className="flex items-start justify-between gap-2 mb-3">
  111. <div className="flex items-center gap-3 min-w-0 flex-1">
  112. <div className={`p-2 rounded-lg flex-shrink-0 ${
  113. plug.plug_type === 'mqtt'
  114. ? (isReachable ? 'bg-teal-500/20' : 'bg-red-500/20')
  115. : (isReachable ? (isOn ? 'bg-bambu-green/20' : 'bg-bambu-dark') : 'bg-red-500/20')
  116. }`}>
  117. {plug.plug_type === 'mqtt' ? (
  118. <Radio className={`w-5 h-5 ${isReachable ? 'text-teal-400' : 'text-red-400'}`} />
  119. ) : plug.plug_type === 'homeassistant' ? (
  120. <Home className={`w-5 h-5 ${isReachable ? (isOn ? 'text-bambu-green' : 'text-bambu-gray') : 'text-red-400'}`} />
  121. ) : (
  122. <Plug className={`w-5 h-5 ${isReachable ? (isOn ? 'text-bambu-green' : 'text-bambu-gray') : 'text-red-400'}`} />
  123. )}
  124. </div>
  125. <div className="min-w-0">
  126. <h3 className="font-medium text-white truncate">{plug.name}</h3>
  127. <p
  128. className="text-sm text-bambu-gray truncate"
  129. title={plug.plug_type === 'mqtt' ? plug.mqtt_topic ?? undefined : plug.plug_type === 'homeassistant' ? plug.ha_entity_id ?? undefined : plug.ip_address ?? undefined}
  130. >
  131. {plug.plug_type === 'mqtt' ? plug.mqtt_topic : plug.plug_type === 'homeassistant' ? plug.ha_entity_id : plug.ip_address}
  132. </p>
  133. </div>
  134. </div>
  135. {/* Status indicator */}
  136. <div className="flex flex-col items-end gap-1 flex-shrink-0">
  137. {statusLoading ? (
  138. <Loader2 className="w-4 h-4 text-bambu-gray animate-spin" />
  139. ) : plug.plug_type === 'mqtt' ? (
  140. /* MQTT plugs - show badge and checkmark when receiving data */
  141. <div className="flex items-center gap-1.5 text-sm whitespace-nowrap">
  142. <span className="px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0">MQTT</span>
  143. {isReachable && <span className="text-status-ok">✓</span>}
  144. </div>
  145. ) : plug.plug_type === 'homeassistant' ? (
  146. <div className="flex items-center gap-1 text-sm">
  147. <span className="px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded">HA</span>
  148. <span className={isReachable ? (isOn ? 'text-status-ok' : 'text-bambu-gray') : 'text-status-error'}>
  149. {isReachable ? (status?.state || '?') : 'Offline'}
  150. </span>
  151. </div>
  152. ) : isReachable ? (
  153. <div className="flex items-center gap-1 text-sm">
  154. <Wifi className="w-4 h-4 text-status-ok" />
  155. <span className={isOn ? 'text-status-ok' : 'text-bambu-gray'}>{status?.state || 'Unknown'}</span>
  156. </div>
  157. ) : (
  158. <div className="flex items-center gap-1 text-sm text-status-error">
  159. <WifiOff className="w-4 h-4" />
  160. <span>{t('smartPlugs.offline')}</span>
  161. </div>
  162. )}
  163. {/* Admin page link - only for Tasmota */}
  164. {adminUrl && (
  165. <a
  166. href={adminUrl}
  167. target="_blank"
  168. rel="noopener noreferrer"
  169. className="flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors"
  170. title={t('smartPlugs.openPlugAdminPage')}
  171. >
  172. <ExternalLink className="w-3 h-3" />
  173. {t('smartPlugs.admin')}
  174. </a>
  175. )}
  176. </div>
  177. </div>
  178. {/* Linked Printer */}
  179. {linkedPrinter && (
  180. <div className="mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg">
  181. <span className="text-xs text-bambu-gray">Linked to: </span>
  182. <span className="text-sm text-white">{linkedPrinter.name}</span>
  183. </div>
  184. )}
  185. {/* Feature Badges */}
  186. {(plug.power_alert_enabled || plug.schedule_enabled || plug.plug_type === 'mqtt') && (
  187. <div className="flex flex-wrap gap-1.5 mb-3">
  188. {plug.plug_type === 'mqtt' && (
  189. <span className="flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full">
  190. <Eye className="w-3 h-3" />
  191. Monitor Only
  192. </span>
  193. )}
  194. {plug.power_alert_enabled && (
  195. <span className="flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full">
  196. <Bell className="w-3 h-3" />
  197. Alerts
  198. </span>
  199. )}
  200. {plug.schedule_enabled && (
  201. <span className="flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full">
  202. <Calendar className="w-3 h-3" />
  203. {plug.schedule_on_time && plug.schedule_off_time
  204. ? `${plug.schedule_on_time} - ${plug.schedule_off_time}`
  205. : plug.schedule_on_time
  206. ? `On ${plug.schedule_on_time}`
  207. : `Off ${plug.schedule_off_time}`}
  208. </span>
  209. )}
  210. </div>
  211. )}
  212. {/* Quick Controls - hidden for MQTT plugs (monitor-only) */}
  213. {plug.plug_type !== 'mqtt' && (
  214. <div className="flex gap-2 mb-3">
  215. <Button
  216. size="sm"
  217. variant={isOn ? 'primary' : 'secondary'}
  218. disabled={!isReachable || isPending}
  219. onClick={() => setShowPowerOnConfirm(true)}
  220. className="flex-1"
  221. >
  222. {isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Power className="w-4 h-4" />}
  223. On
  224. </Button>
  225. <Button
  226. size="sm"
  227. variant={!isOn ? 'primary' : 'secondary'}
  228. disabled={!isReachable || isPending}
  229. onClick={() => setShowPowerOffConfirm(true)}
  230. className="flex-1"
  231. >
  232. {isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <PowerOff className="w-4 h-4" />}
  233. Off
  234. </Button>
  235. </div>
  236. )}
  237. {/* Energy display for MQTT plugs */}
  238. {plug.plug_type === 'mqtt' && status?.energy && (
  239. <div className="flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg">
  240. {status.energy.power !== null && status.energy.power !== undefined && (
  241. <div className="flex-1 text-center">
  242. <p className="text-lg font-semibold text-white">{Math.round(status.energy.power)}W</p>
  243. <p className="text-xs text-bambu-gray">Power</p>
  244. </div>
  245. )}
  246. {status.energy.today !== null && status.energy.today !== undefined && (
  247. <div className="flex-1 text-center border-l border-bambu-dark-tertiary">
  248. <p className="text-lg font-semibold text-white">{status.energy.today.toFixed(2)}</p>
  249. <p className="text-xs text-bambu-gray">kWh Today</p>
  250. </div>
  251. )}
  252. </div>
  253. )}
  254. {/* Toggle Settings Panel */}
  255. <button
  256. onClick={() => setIsExpanded(!isExpanded)}
  257. className="w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors"
  258. >
  259. <span className="flex items-center gap-2">
  260. <Settings2 className="w-4 h-4" />
  261. {plug.plug_type === 'mqtt' ? 'Settings' : 'Automation Settings'}
  262. </span>
  263. <span>{isExpanded ? '-' : '+'}</span>
  264. </button>
  265. {/* Expanded Settings */}
  266. {isExpanded && (
  267. <div className="pt-3 border-t border-bambu-dark-tertiary space-y-4">
  268. {/* Show in Switchbar Toggle */}
  269. <div className="flex items-center justify-between">
  270. <div className="flex items-center gap-2">
  271. <LayoutGrid className="w-4 h-4 text-bambu-green" />
  272. <div>
  273. <p className="text-sm text-white">Show in Switchbar</p>
  274. <p className="text-xs text-bambu-gray">Quick access from sidebar</p>
  275. </div>
  276. </div>
  277. <label className="relative inline-flex items-center cursor-pointer">
  278. <input
  279. type="checkbox"
  280. checked={plug.show_in_switchbar}
  281. onChange={(e) => updateMutation.mutate({ show_in_switchbar: e.target.checked })}
  282. className="sr-only peer"
  283. />
  284. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  285. </label>
  286. </div>
  287. {/* Automation controls - only for controllable plugs (not MQTT) */}
  288. {plug.plug_type !== 'mqtt' && (
  289. <>
  290. {/* Enabled Toggle */}
  291. <div className="flex items-center justify-between">
  292. <div>
  293. <p className="text-sm text-white">Enabled</p>
  294. <p className="text-xs text-bambu-gray">Enable automation for this plug</p>
  295. </div>
  296. <label className="relative inline-flex items-center cursor-pointer">
  297. <input
  298. type="checkbox"
  299. checked={plug.enabled}
  300. onChange={(e) => updateMutation.mutate({ enabled: e.target.checked })}
  301. className="sr-only peer"
  302. />
  303. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  304. </label>
  305. </div>
  306. {/* Auto On */}
  307. <div className="flex items-center justify-between">
  308. <div>
  309. <p className="text-sm text-white">Auto On</p>
  310. <p className="text-xs text-bambu-gray">Turn on when print starts</p>
  311. </div>
  312. <label className="relative inline-flex items-center cursor-pointer">
  313. <input
  314. type="checkbox"
  315. checked={plug.auto_on}
  316. onChange={(e) => updateMutation.mutate({ auto_on: e.target.checked })}
  317. className="sr-only peer"
  318. />
  319. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  320. </label>
  321. </div>
  322. {/* Auto Off */}
  323. <div className="flex items-center justify-between">
  324. <div>
  325. <p className="text-sm text-white">Auto Off</p>
  326. <p className="text-xs text-bambu-gray">Turn off when print completes (one-shot)</p>
  327. </div>
  328. <label className="relative inline-flex items-center cursor-pointer">
  329. <input
  330. type="checkbox"
  331. checked={plug.auto_off}
  332. onChange={(e) => updateMutation.mutate({ auto_off: e.target.checked })}
  333. className="sr-only peer"
  334. />
  335. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  336. </label>
  337. </div>
  338. {/* Delay Mode */}
  339. {plug.auto_off && (
  340. <div className="space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary">
  341. <div>
  342. <p className="text-sm text-white mb-2">Turn Off Delay Mode</p>
  343. <div className="flex gap-2">
  344. <button
  345. onClick={() => updateMutation.mutate({ off_delay_mode: 'time' })}
  346. className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
  347. plug.off_delay_mode === 'time'
  348. ? 'bg-bambu-green text-white'
  349. : 'bg-bambu-dark text-bambu-gray hover:text-white'
  350. }`}
  351. >
  352. <Clock className="w-4 h-4" />
  353. Time
  354. </button>
  355. <button
  356. onClick={() => updateMutation.mutate({ off_delay_mode: 'temperature' })}
  357. className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
  358. plug.off_delay_mode === 'temperature'
  359. ? 'bg-bambu-green text-white'
  360. : 'bg-bambu-dark text-bambu-gray hover:text-white'
  361. }`}
  362. >
  363. <Thermometer className="w-4 h-4" />
  364. Temp
  365. </button>
  366. </div>
  367. </div>
  368. {plug.off_delay_mode === 'time' ? (
  369. <div>
  370. <label className="block text-xs text-bambu-gray mb-1">Delay (minutes)</label>
  371. <input
  372. type="number"
  373. min="1"
  374. max="60"
  375. value={plug.off_delay_minutes}
  376. onChange={(e) => updateMutation.mutate({ off_delay_minutes: parseInt(e.target.value) || 5 })}
  377. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  378. />
  379. </div>
  380. ) : (
  381. <div>
  382. <label className="block text-xs text-bambu-gray mb-1">Temperature threshold (C)</label>
  383. <input
  384. type="number"
  385. min="30"
  386. max="100"
  387. value={plug.off_temp_threshold}
  388. onChange={(e) => updateMutation.mutate({ off_temp_threshold: parseInt(e.target.value) || 70 })}
  389. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  390. />
  391. <p className="text-xs text-bambu-gray mt-1">Turns off when nozzle cools below this temperature</p>
  392. </div>
  393. )}
  394. </div>
  395. )}
  396. </>
  397. )}
  398. {/* Action Buttons */}
  399. <div className="flex gap-2 pt-2">
  400. <Button
  401. size="sm"
  402. variant="secondary"
  403. onClick={() => onEdit(plug)}
  404. className="flex-1"
  405. >
  406. <Edit2 className="w-4 h-4" />
  407. Edit
  408. </Button>
  409. <Button
  410. size="sm"
  411. variant="secondary"
  412. onClick={() => setShowDeleteConfirm(true)}
  413. className="text-red-400 hover:text-red-300"
  414. >
  415. <Trash2 className="w-4 h-4" />
  416. </Button>
  417. </div>
  418. </div>
  419. )}
  420. </CardContent>
  421. </Card>
  422. {/* Delete Confirmation */}
  423. {showDeleteConfirm && (
  424. <ConfirmModal
  425. title={t('smartPlugs.deleteSmartPlug')}
  426. message={`Are you sure you want to delete "${plug.name}"? This cannot be undone.`}
  427. confirmText="Delete"
  428. variant="danger"
  429. onConfirm={() => {
  430. deleteMutation.mutate();
  431. setShowDeleteConfirm(false);
  432. }}
  433. onCancel={() => setShowDeleteConfirm(false)}
  434. />
  435. )}
  436. {/* Power On Confirmation */}
  437. {showPowerOnConfirm && (
  438. <ConfirmModal
  439. title={t('smartPlugs.turnOnSmartPlug')}
  440. message={`Are you sure you want to turn on "${plug.name}"?`}
  441. confirmText={t('smartPlugs.turnOn')}
  442. variant="default"
  443. onConfirm={() => {
  444. controlMutation.mutate('on');
  445. setShowPowerOnConfirm(false);
  446. }}
  447. onCancel={() => setShowPowerOnConfirm(false)}
  448. />
  449. )}
  450. {/* Power Off Confirmation */}
  451. {showPowerOffConfirm && (
  452. <ConfirmModal
  453. title={t('smartPlugs.turnOffSmartPlug')}
  454. message={`Are you sure you want to turn off "${plug.name}"? This will cut power to the connected device.`}
  455. confirmText={t('smartPlugs.turnOff')}
  456. variant="danger"
  457. onConfirm={() => {
  458. controlMutation.mutate('off');
  459. setShowPowerOffConfirm(false);
  460. }}
  461. onCancel={() => setShowPowerOffConfirm(false)}
  462. />
  463. )}
  464. </>
  465. );
  466. }