SmartPlugCard.tsx 22 KB

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