| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836 |
- import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
- import { Loader2, Plus, Plug, AlertTriangle, RotateCcw, Bell, Download, RefreshCw, ExternalLink, Globe, Droplets, Thermometer, FileText, Edit2, Send, CheckCircle, XCircle, History, Trash2, Upload, Zap, TrendingUp, Calendar, DollarSign, Power, PowerOff, Key, Copy, Database } from 'lucide-react';
- import { useTranslation } from 'react-i18next';
- import { api } from '../api/client';
- import type { AppSettings, SmartPlug, SmartPlugStatus, NotificationProvider, NotificationTemplate, UpdateStatus } from '../api/client';
- import { Card, CardContent, CardHeader } from '../components/Card';
- import { Button } from '../components/Button';
- import { SmartPlugCard } from '../components/SmartPlugCard';
- import { AddSmartPlugModal } from '../components/AddSmartPlugModal';
- import { NotificationProviderCard } from '../components/NotificationProviderCard';
- import { AddNotificationModal } from '../components/AddNotificationModal';
- import { NotificationTemplateEditor } from '../components/NotificationTemplateEditor';
- import { NotificationLogViewer } from '../components/NotificationLogViewer';
- import { ConfirmModal } from '../components/ConfirmModal';
- import { BackupModal } from '../components/BackupModal';
- import { RestoreModal } from '../components/RestoreModal';
- import { SpoolmanSettings } from '../components/SpoolmanSettings';
- import { ExternalLinksSettings } from '../components/ExternalLinksSettings';
- import { defaultNavItems, getDefaultView, setDefaultView } from '../components/Layout';
- import { availableLanguages } from '../i18n';
- import { useToast } from '../contexts/ToastContext';
- import { useState, useEffect, useRef, useCallback } from 'react';
- export function SettingsPage() {
- const queryClient = useQueryClient();
- const { t, i18n } = useTranslation();
- const { showToast } = useToast();
- const [localSettings, setLocalSettings] = useState<AppSettings | null>(null);
- const [showPlugModal, setShowPlugModal] = useState(false);
- const [editingPlug, setEditingPlug] = useState<SmartPlug | null>(null);
- const [showNotificationModal, setShowNotificationModal] = useState(false);
- const [editingProvider, setEditingProvider] = useState<NotificationProvider | null>(null);
- const [editingTemplate, setEditingTemplate] = useState<NotificationTemplate | null>(null);
- const [showLogViewer, setShowLogViewer] = useState(false);
- const [defaultView, setDefaultViewState] = useState<string>(getDefaultView());
- const [activeTab, setActiveTab] = useState<'general' | 'plugs' | 'notifications' | 'apikeys'>('general');
- const [showCreateAPIKey, setShowCreateAPIKey] = useState(false);
- const [newAPIKeyName, setNewAPIKeyName] = useState('');
- const [newAPIKeyPermissions, setNewAPIKeyPermissions] = useState({
- can_queue: true,
- can_control_printer: false,
- can_read_status: true,
- });
- const [createdAPIKey, setCreatedAPIKey] = useState<string | null>(null);
- const [showDeleteAPIKeyConfirm, setShowDeleteAPIKeyConfirm] = useState<number | null>(null);
- // Confirm modal states
- const [showClearLogsConfirm, setShowClearLogsConfirm] = useState(false);
- const [showClearStorageConfirm, setShowClearStorageConfirm] = useState(false);
- const [showBulkPlugConfirm, setShowBulkPlugConfirm] = useState<'on' | 'off' | null>(null);
- const [showBackupModal, setShowBackupModal] = useState(false);
- const [showRestoreModal, setShowRestoreModal] = useState(false);
- const handleDefaultViewChange = (path: string) => {
- setDefaultViewState(path);
- setDefaultView(path);
- };
- const handleResetSidebarOrder = () => {
- localStorage.removeItem('sidebarOrder');
- window.location.reload();
- };
- const { data: settings, isLoading } = useQuery({
- queryKey: ['settings'],
- queryFn: api.getSettings,
- });
- const { data: smartPlugs, isLoading: plugsLoading } = useQuery({
- queryKey: ['smart-plugs'],
- queryFn: api.getSmartPlugs,
- });
- // Fetch energy data for all smart plugs when on the plugs tab
- const { data: plugEnergySummary, isLoading: energyLoading } = useQuery({
- queryKey: ['smart-plugs-energy', smartPlugs?.map(p => p.id)],
- queryFn: async () => {
- if (!smartPlugs || smartPlugs.length === 0) return null;
- const statuses = await Promise.all(
- smartPlugs.filter(p => p.enabled).map(async (plug) => {
- try {
- const status = await api.getSmartPlugStatus(plug.id);
- return { plug, status };
- } catch {
- return { plug, status: null as SmartPlugStatus | null };
- }
- })
- );
- // Aggregate energy data
- let totalPower = 0;
- let totalToday = 0;
- let totalYesterday = 0;
- let totalLifetime = 0;
- let reachableCount = 0;
- for (const { status } of statuses) {
- if (status?.reachable && status.energy) {
- reachableCount++;
- if (status.energy.power != null) totalPower += status.energy.power;
- if (status.energy.today != null) totalToday += status.energy.today;
- if (status.energy.yesterday != null) totalYesterday += status.energy.yesterday;
- if (status.energy.total != null) totalLifetime += status.energy.total;
- }
- }
- return {
- totalPower,
- totalToday,
- totalYesterday,
- totalLifetime,
- reachableCount,
- totalPlugs: smartPlugs.filter(p => p.enabled).length,
- };
- },
- enabled: activeTab === 'plugs' && !!smartPlugs && smartPlugs.length > 0,
- refetchInterval: activeTab === 'plugs' ? 10000 : false, // Refresh every 10s when on plugs tab
- });
- const { data: notificationProviders, isLoading: providersLoading } = useQuery({
- queryKey: ['notification-providers'],
- queryFn: api.getNotificationProviders,
- });
- const { data: apiKeys, isLoading: apiKeysLoading } = useQuery({
- queryKey: ['api-keys'],
- queryFn: api.getAPIKeys,
- enabled: activeTab === 'apikeys',
- });
- const createAPIKeyMutation = useMutation({
- mutationFn: (data: { name: string; can_queue: boolean; can_control_printer: boolean; can_read_status: boolean }) =>
- api.createAPIKey(data),
- onSuccess: (data) => {
- setCreatedAPIKey(data.key || null);
- setShowCreateAPIKey(false);
- setNewAPIKeyName('');
- queryClient.invalidateQueries({ queryKey: ['api-keys'] });
- showToast('API key created');
- },
- onError: (error: Error) => {
- showToast(`Failed to create API key: ${error.message}`, 'error');
- },
- });
- const deleteAPIKeyMutation = useMutation({
- mutationFn: (id: number) => api.deleteAPIKey(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['api-keys'] });
- showToast('API key deleted');
- },
- onError: (error: Error) => {
- showToast(`Failed to delete API key: ${error.message}`, 'error');
- },
- });
- const { data: printers } = useQuery({
- queryKey: ['printers'],
- queryFn: api.getPrinters,
- });
- const { data: notificationTemplates, isLoading: templatesLoading } = useQuery({
- queryKey: ['notification-templates'],
- queryFn: api.getNotificationTemplates,
- });
- const { data: ffmpegStatus } = useQuery({
- queryKey: ['ffmpeg-status'],
- queryFn: api.checkFfmpeg,
- });
- const { data: versionInfo } = useQuery({
- queryKey: ['version'],
- queryFn: api.getVersion,
- });
- const { data: updateCheck, refetch: refetchUpdateCheck, isRefetching: isCheckingUpdate } = useQuery({
- queryKey: ['updateCheck'],
- queryFn: api.checkForUpdates,
- staleTime: 5 * 60 * 1000,
- });
- const { data: updateStatus, refetch: refetchUpdateStatus } = useQuery({
- queryKey: ['updateStatus'],
- queryFn: api.getUpdateStatus,
- refetchInterval: (query) => {
- const status = query.state.data as UpdateStatus | undefined;
- // Poll while update is in progress
- if (status?.status === 'downloading' || status?.status === 'installing') {
- return 1000;
- }
- return false;
- },
- });
- const applyUpdateMutation = useMutation({
- mutationFn: api.applyUpdate,
- onSuccess: () => {
- refetchUpdateStatus();
- },
- });
- // Test all notification providers
- const [testAllResult, setTestAllResult] = useState<{
- tested: number;
- success: number;
- failed: number;
- results: Array<{
- provider_id: number;
- provider_name: string;
- provider_type: string;
- success: boolean;
- message: string;
- }>;
- } | null>(null);
- const testAllMutation = useMutation({
- mutationFn: api.testAllNotificationProviders,
- onSuccess: (data) => {
- setTestAllResult(data);
- queryClient.invalidateQueries({ queryKey: ['notification-providers'] });
- if (data.failed === 0) {
- showToast(`All ${data.tested} providers tested successfully!`, 'success');
- } else {
- showToast(`${data.success}/${data.tested} providers succeeded`, data.failed > 0 ? 'error' : 'success');
- }
- },
- onError: (error: Error) => {
- showToast(`Failed to test providers: ${error.message}`, 'error');
- },
- });
- // Bulk action for smart plugs
- const bulkPlugActionMutation = useMutation({
- mutationFn: async (action: 'on' | 'off') => {
- if (!smartPlugs) return { success: 0, failed: 0 };
- const enabledPlugs = smartPlugs.filter(p => p.enabled);
- const results = await Promise.all(
- enabledPlugs.map(async (plug) => {
- try {
- await api.controlSmartPlug(plug.id, action);
- return { success: true };
- } catch {
- return { success: false };
- }
- })
- );
- return {
- success: results.filter(r => r.success).length,
- failed: results.filter(r => !r.success).length,
- };
- },
- onSuccess: (data, action) => {
- queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
- queryClient.invalidateQueries({ queryKey: ['smart-plugs-energy'] });
- if (data.failed === 0) {
- showToast(`All ${data.success} plugs turned ${action}`, 'success');
- } else {
- showToast(`${data.success} plugs turned ${action}, ${data.failed} failed`, 'error');
- }
- },
- onError: (error: Error) => {
- showToast(`Failed: ${error.message}`, 'error');
- },
- });
- // Ref for debounce timeout
- const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const isInitialLoadRef = useRef(true);
- // Sync local state when settings load
- useEffect(() => {
- if (settings && !localSettings) {
- setLocalSettings(settings);
- // Mark initial load complete after a short delay
- setTimeout(() => {
- isInitialLoadRef.current = false;
- }, 100);
- }
- }, [settings, localSettings]);
- const updateMutation = useMutation({
- mutationFn: api.updateSettings,
- onSuccess: (data) => {
- queryClient.setQueryData(['settings'], data);
- // Invalidate archive stats to reflect energy tracking mode change
- queryClient.invalidateQueries({ queryKey: ['archiveStats'] });
- showToast('Settings saved', 'success');
- },
- onError: (error: Error) => {
- showToast(`Failed to save: ${error.message}`, 'error');
- },
- });
- // Debounced auto-save when localSettings change
- useEffect(() => {
- // Skip if initial load or no settings
- if (isInitialLoadRef.current || !localSettings || !settings) {
- return;
- }
- // Check if there are actual changes
- const hasChanges =
- settings.auto_archive !== localSettings.auto_archive ||
- settings.save_thumbnails !== localSettings.save_thumbnails ||
- settings.capture_finish_photo !== localSettings.capture_finish_photo ||
- settings.default_filament_cost !== localSettings.default_filament_cost ||
- settings.currency !== localSettings.currency ||
- settings.energy_cost_per_kwh !== localSettings.energy_cost_per_kwh ||
- settings.energy_tracking_mode !== localSettings.energy_tracking_mode ||
- settings.check_updates !== localSettings.check_updates ||
- settings.notification_language !== localSettings.notification_language ||
- settings.ams_humidity_good !== localSettings.ams_humidity_good ||
- settings.ams_humidity_fair !== localSettings.ams_humidity_fair ||
- settings.ams_temp_good !== localSettings.ams_temp_good ||
- settings.ams_temp_fair !== localSettings.ams_temp_fair ||
- settings.ams_history_retention_days !== localSettings.ams_history_retention_days ||
- settings.date_format !== localSettings.date_format ||
- settings.time_format !== localSettings.time_format ||
- settings.default_printer_id !== localSettings.default_printer_id;
- if (!hasChanges) {
- return;
- }
- // Clear existing timeout
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current);
- }
- // Set new debounced save (500ms delay)
- saveTimeoutRef.current = setTimeout(() => {
- updateMutation.mutate(localSettings);
- }, 500);
- // Cleanup on unmount or when localSettings changes again
- return () => {
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current);
- }
- };
- }, [localSettings, settings, updateMutation]);
- const updateSetting = useCallback(<K extends keyof AppSettings>(key: K, value: AppSettings[K]) => {
- setLocalSettings(prev => prev ? { ...prev, [key]: value } : null);
- }, []);
- if (isLoading || !localSettings) {
- return (
- <div className="p-4 md:p-8 flex justify-center">
- <Loader2 className="w-8 h-8 text-bambu-green animate-spin" />
- </div>
- );
- }
- return (
- <div className="p-4 md:p-8">
- <div className="mb-8">
- <h1 className="text-2xl font-bold text-white">Settings</h1>
- <p className="text-bambu-gray">Configure Bambuddy</p>
- </div>
- {/* Tab Navigation */}
- <div className="flex gap-1 mb-6 border-b border-bambu-dark-tertiary">
- <button
- onClick={() => setActiveTab('general')}
- className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${
- activeTab === 'general'
- ? 'text-bambu-green border-bambu-green'
- : 'text-bambu-gray hover:text-white border-transparent'
- }`}
- >
- General
- </button>
- <button
- onClick={() => setActiveTab('plugs')}
- className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${
- activeTab === 'plugs'
- ? 'text-bambu-green border-bambu-green'
- : 'text-bambu-gray hover:text-white border-transparent'
- }`}
- >
- <Plug className="w-4 h-4" />
- Smart Plugs
- {smartPlugs && smartPlugs.length > 0 && (
- <span className="text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full">
- {smartPlugs.length}
- </span>
- )}
- </button>
- <button
- onClick={() => setActiveTab('notifications')}
- className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${
- activeTab === 'notifications'
- ? 'text-bambu-green border-bambu-green'
- : 'text-bambu-gray hover:text-white border-transparent'
- }`}
- >
- <Bell className="w-4 h-4" />
- Notifications
- {notificationProviders && notificationProviders.length > 0 && (
- <span className="text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full">
- {notificationProviders.length}
- </span>
- )}
- </button>
- <button
- onClick={() => setActiveTab('apikeys')}
- className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${
- activeTab === 'apikeys'
- ? 'text-bambu-green border-bambu-green'
- : 'text-bambu-gray hover:text-white border-transparent'
- }`}
- >
- <Key className="w-4 h-4" />
- API Keys
- {apiKeys && apiKeys.length > 0 && (
- <span className="text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full">
- {apiKeys.length}
- </span>
- )}
- </button>
- </div>
- {/* General Tab */}
- {activeTab === 'general' && (
- <div className="flex flex-col lg:flex-row gap-6 lg:gap-8">
- {/* Left Column - General Settings */}
- <div className="space-y-6 flex-1 lg:max-w-xl">
- <Card>
- <CardHeader>
- <h2 className="text-lg font-semibold text-white">{t('settings.general')}</h2>
- </CardHeader>
- <CardContent className="space-y-4">
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- <Globe className="w-4 h-4 inline mr-1" />
- {t('settings.language')}
- </label>
- <select
- value={i18n.language}
- onChange={(e) => i18n.changeLanguage(e.target.value)}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- >
- {availableLanguages.map((lang) => (
- <option key={lang.code} value={lang.code}>
- {lang.nativeName} ({lang.name})
- </option>
- ))}
- </select>
- <p className="text-xs text-bambu-gray mt-1">
- {t('settings.languageDescription')}
- </p>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- {t('settings.defaultView')}
- </label>
- <select
- value={defaultView}
- onChange={(e) => handleDefaultViewChange(e.target.value)}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- >
- {defaultNavItems.map((item) => (
- <option key={item.id} value={item.to}>
- {t(item.labelKey)}
- </option>
- ))}
- </select>
- <p className="text-xs text-bambu-gray mt-1">
- {t('settings.defaultViewDescription')}
- </p>
- </div>
- <div className="grid grid-cols-2 gap-3">
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Date Format
- </label>
- <select
- value={localSettings.date_format || 'system'}
- onChange={(e) => updateSetting('date_format', e.target.value as 'system' | 'us' | 'eu' | 'iso')}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- >
- <option value="system">System Default</option>
- <option value="us">US (MM/DD/YYYY)</option>
- <option value="eu">EU (DD/MM/YYYY)</option>
- <option value="iso">ISO (YYYY-MM-DD)</option>
- </select>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Time Format
- </label>
- <select
- value={localSettings.time_format || 'system'}
- onChange={(e) => updateSetting('time_format', e.target.value as 'system' | '12h' | '24h')}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- >
- <option value="system">System Default</option>
- <option value="12h">12-hour (3:30 PM)</option>
- <option value="24h">24-hour (15:30)</option>
- </select>
- </div>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Default Printer
- </label>
- <select
- value={localSettings.default_printer_id ?? ''}
- onChange={(e) => updateSetting('default_printer_id', e.target.value ? Number(e.target.value) : null)}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- >
- <option value="">No default (ask each time)</option>
- {printers?.map((printer) => (
- <option key={printer.id} value={printer.id}>
- {printer.name}
- </option>
- ))}
- </select>
- <p className="text-xs text-bambu-gray mt-1">
- Pre-select this printer for uploads, reprints, and other operations.
- </p>
- </div>
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Sidebar order</p>
- <p className="text-sm text-bambu-gray">
- Drag items in the sidebar to reorder. Reset to default order here.
- </p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={handleResetSidebarOrder}
- >
- <RotateCcw className="w-4 h-4" />
- Reset
- </Button>
- </div>
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <h2 className="text-lg font-semibold text-white">Archive Settings</h2>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Auto-archive prints</p>
- <p className="text-sm text-bambu-gray">
- Automatically save 3MF files when prints complete
- </p>
- </div>
- <label className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- checked={localSettings.auto_archive}
- onChange={(e) => updateSetting('auto_archive', e.target.checked)}
- className="sr-only peer"
- />
- <div className="w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"></div>
- </label>
- </div>
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Save thumbnails</p>
- <p className="text-sm text-bambu-gray">
- Extract and save preview images from 3MF files
- </p>
- </div>
- <label className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- checked={localSettings.save_thumbnails}
- onChange={(e) => updateSetting('save_thumbnails', e.target.checked)}
- className="sr-only peer"
- />
- <div className="w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"></div>
- </label>
- </div>
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Capture finish photo</p>
- <p className="text-sm text-bambu-gray">
- Take a photo from printer camera when print completes
- </p>
- </div>
- <label className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- checked={localSettings.capture_finish_photo}
- onChange={(e) => updateSetting('capture_finish_photo', e.target.checked)}
- className="sr-only peer"
- />
- <div className="w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"></div>
- </label>
- </div>
- {localSettings.capture_finish_photo && ffmpegStatus && !ffmpegStatus.installed && (
- <div className="flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
- <AlertTriangle className="w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5" />
- <div className="text-sm">
- <p className="text-yellow-500 font-medium">ffmpeg not installed</p>
- <p className="text-bambu-gray mt-1">
- Camera capture requires ffmpeg. Install it via{' '}
- <code className="bg-bambu-dark-tertiary px-1 rounded">brew install ffmpeg</code> (macOS) or{' '}
- <code className="bg-bambu-dark-tertiary px-1 rounded">apt install ffmpeg</code> (Linux).
- </p>
- </div>
- </div>
- )}
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <h2 className="text-lg font-semibold text-white">Cost Tracking</h2>
- </CardHeader>
- <CardContent className="space-y-4">
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Default filament cost (per kg)
- </label>
- <input
- type="number"
- step="0.01"
- min="0"
- value={localSettings.default_filament_cost}
- onChange={(e) =>
- updateSetting('default_filament_cost', parseFloat(e.target.value) || 0)
- }
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">Currency</label>
- <select
- value={localSettings.currency}
- onChange={(e) => updateSetting('currency', e.target.value)}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- >
- <option value="USD">USD ($)</option>
- <option value="EUR">EUR (€)</option>
- <option value="GBP">GBP (£)</option>
- <option value="CHF">CHF (Fr.)</option>
- <option value="JPY">JPY (¥)</option>
- <option value="CNY">CNY (¥)</option>
- <option value="CAD">CAD ($)</option>
- <option value="AUD">AUD ($)</option>
- </select>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Electricity cost per kWh
- </label>
- <input
- type="number"
- step="0.01"
- min="0"
- value={localSettings.energy_cost_per_kwh}
- onChange={(e) =>
- updateSetting('energy_cost_per_kwh', parseFloat(e.target.value) || 0)
- }
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Energy display mode
- </label>
- <select
- value={localSettings.energy_tracking_mode || 'total'}
- onChange={(e) => updateSetting('energy_tracking_mode', e.target.value as 'print' | 'total')}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- >
- <option value="print">Prints Only</option>
- <option value="total">Total Consumption</option>
- </select>
- <p className="text-xs text-bambu-gray mt-1">
- {localSettings.energy_tracking_mode === 'print'
- ? 'Dashboard shows sum of energy used during prints'
- : 'Dashboard shows lifetime energy from smart plugs'}
- </p>
- </div>
- </CardContent>
- </Card>
- </div>
- {/* Second Column - AMS & Spoolman */}
- <div className="space-y-6 flex-1 lg:max-w-md">
- <Card>
- <CardHeader>
- <h2 className="text-lg font-semibold text-white">AMS Display Thresholds</h2>
- </CardHeader>
- <CardContent className="space-y-4">
- <p className="text-sm text-bambu-gray">
- Configure color thresholds for AMS humidity and temperature indicators.
- </p>
- {/* Humidity Thresholds */}
- <div className="space-y-3">
- <div className="flex items-center gap-2 text-white">
- <Droplets className="w-4 h-4 text-blue-400" />
- <span className="font-medium">Humidity</span>
- </div>
- <div className="grid grid-cols-2 gap-3">
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Good (green) ≤
- </label>
- <div className="flex items-center gap-2">
- <input
- type="number"
- min="0"
- max="100"
- value={localSettings.ams_humidity_good ?? 40}
- onChange={(e) => updateSetting('ams_humidity_good', parseInt(e.target.value) || 40)}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- />
- <span className="text-bambu-gray">%</span>
- </div>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Fair (orange) ≤
- </label>
- <div className="flex items-center gap-2">
- <input
- type="number"
- min="0"
- max="100"
- value={localSettings.ams_humidity_fair ?? 60}
- onChange={(e) => updateSetting('ams_humidity_fair', parseInt(e.target.value) || 60)}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- />
- <span className="text-bambu-gray">%</span>
- </div>
- </div>
- </div>
- <p className="text-xs text-bambu-gray">
- Above fair threshold shows as red (bad)
- </p>
- </div>
- {/* Temperature Thresholds */}
- <div className="space-y-3 pt-2 border-t border-bambu-dark-tertiary">
- <div className="flex items-center gap-2 text-white">
- <Thermometer className="w-4 h-4 text-orange-400" />
- <span className="font-medium">Temperature</span>
- </div>
- <div className="grid grid-cols-2 gap-3">
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Good (blue) ≤
- </label>
- <div className="flex items-center gap-2">
- <input
- type="number"
- step="0.5"
- min="0"
- max="60"
- value={localSettings.ams_temp_good ?? 28}
- onChange={(e) => updateSetting('ams_temp_good', parseFloat(e.target.value) || 28)}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- />
- <span className="text-bambu-gray">°C</span>
- </div>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Fair (orange) ≤
- </label>
- <div className="flex items-center gap-2">
- <input
- type="number"
- step="0.5"
- min="0"
- max="60"
- value={localSettings.ams_temp_fair ?? 35}
- onChange={(e) => updateSetting('ams_temp_fair', parseFloat(e.target.value) || 35)}
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- />
- <span className="text-bambu-gray">°C</span>
- </div>
- </div>
- </div>
- <p className="text-xs text-bambu-gray">
- Above fair threshold shows as red (hot)
- </p>
- </div>
- {/* History Retention */}
- <div className="space-y-3 pt-4 border-t border-bambu-dark-tertiary">
- <div className="flex items-center gap-2 text-white">
- <Database className="w-4 h-4 text-purple-400" />
- <span className="font-medium">History Retention</span>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">
- Keep sensor history for
- </label>
- <div className="flex items-center gap-2">
- <input
- type="number"
- min="1"
- max="365"
- value={localSettings.ams_history_retention_days ?? 30}
- onChange={(e) => updateSetting('ams_history_retention_days', parseInt(e.target.value) || 30)}
- className="w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- />
- <span className="text-bambu-gray">days</span>
- </div>
- </div>
- <p className="text-xs text-bambu-gray">
- Older humidity and temperature data will be automatically deleted
- </p>
- </div>
- </CardContent>
- </Card>
- <SpoolmanSettings />
- <ExternalLinksSettings />
- </div>
- {/* Third Column - Updates */}
- <div className="space-y-6 flex-1 lg:max-w-sm">
- <Card>
- <CardHeader>
- <h2 className="text-lg font-semibold text-white">Updates</h2>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Check for updates</p>
- <p className="text-sm text-bambu-gray">
- Automatically check for new versions on startup
- </p>
- </div>
- <label className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- checked={localSettings.check_updates}
- onChange={(e) => updateSetting('check_updates', e.target.checked)}
- className="sr-only peer"
- />
- <div className="w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"></div>
- </label>
- </div>
- <div className="border-t border-bambu-dark-tertiary pt-4">
- <div className="flex items-center justify-between mb-2">
- <div>
- <p className="text-white">Current version</p>
- <p className="text-sm text-bambu-gray">v{versionInfo?.version || '...'}</p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => refetchUpdateCheck()}
- disabled={isCheckingUpdate}
- >
- {isCheckingUpdate ? (
- <Loader2 className="w-4 h-4 animate-spin" />
- ) : (
- <RefreshCw className="w-4 h-4" />
- )}
- Check now
- </Button>
- </div>
- {updateCheck?.update_available ? (
- <div className="mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg">
- <div className="flex items-start justify-between">
- <div>
- <p className="text-bambu-green font-medium">
- Update available: v{updateCheck.latest_version}
- </p>
- {updateCheck.release_name && updateCheck.release_name !== updateCheck.latest_version && (
- <p className="text-sm text-bambu-gray mt-1">{updateCheck.release_name}</p>
- )}
- {updateCheck.release_notes && (
- <p className="text-sm text-bambu-gray mt-2 whitespace-pre-line line-clamp-3">
- {updateCheck.release_notes}
- </p>
- )}
- </div>
- {updateCheck.release_url && (
- <a
- href={updateCheck.release_url}
- target="_blank"
- rel="noopener noreferrer"
- className="text-bambu-gray hover:text-white transition-colors"
- title="View release on GitHub"
- >
- <ExternalLink className="w-4 h-4" />
- </a>
- )}
- </div>
- {updateStatus?.status === 'downloading' || updateStatus?.status === 'installing' ? (
- <div className="mt-3">
- <div className="flex items-center gap-2 text-sm text-bambu-gray">
- <Loader2 className="w-4 h-4 animate-spin" />
- <span>{updateStatus.message}</span>
- </div>
- <div className="mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2">
- <div
- className="bg-bambu-green h-2 rounded-full transition-all duration-300"
- style={{ width: `${updateStatus.progress}%` }}
- />
- </div>
- </div>
- ) : updateStatus?.status === 'complete' ? (
- <div className="mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green">
- {updateStatus.message}
- </div>
- ) : updateStatus?.status === 'error' ? (
- <div className="mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400">
- {updateStatus.error || updateStatus.message}
- </div>
- ) : (
- <Button
- className="mt-3"
- onClick={() => applyUpdateMutation.mutate()}
- disabled={applyUpdateMutation.isPending}
- >
- {applyUpdateMutation.isPending ? (
- <Loader2 className="w-4 h-4 animate-spin" />
- ) : (
- <Download className="w-4 h-4" />
- )}
- Install Update
- </Button>
- )}
- </div>
- ) : updateCheck?.error ? (
- <div className="mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400">
- Failed to check for updates: {updateCheck.error}
- </div>
- ) : updateCheck && !updateCheck.update_available ? (
- <p className="mt-2 text-sm text-bambu-gray">
- You're running the latest version
- </p>
- ) : null}
- </div>
- </CardContent>
- </Card>
- {/* Data Management */}
- <Card>
- <CardHeader>
- <h2 className="text-lg font-semibold text-white">Data Management</h2>
- </CardHeader>
- <CardContent className="space-y-4">
- {/* Backup/Restore */}
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Backup Data</p>
- <p className="text-sm text-bambu-gray">
- Export settings, providers, printers, and more
- </p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowBackupModal(true)}
- >
- <Download className="w-4 h-4" />
- Export
- </Button>
- </div>
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Restore Backup</p>
- <p className="text-sm text-bambu-gray">
- Import settings from a backup file with duplicate handling options
- </p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowRestoreModal(true)}
- >
- <Upload className="w-4 h-4" />
- Restore
- </Button>
- </div>
- <div className="border-t border-bambu-dark-tertiary pt-4">
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Clear Notification Logs</p>
- <p className="text-sm text-bambu-gray">
- Delete notification logs older than 30 days
- </p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowClearLogsConfirm(true)}
- >
- <Trash2 className="w-4 h-4" />
- Clear
- </Button>
- </div>
- </div>
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white">Reset UI Preferences</p>
- <p className="text-sm text-bambu-gray">
- Reset sidebar order, theme, view modes, and layout preferences. Printers, archives, and settings are not affected.
- </p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowClearStorageConfirm(true)}
- >
- <Trash2 className="w-4 h-4" />
- Reset
- </Button>
- </div>
- </CardContent>
- </Card>
- </div>
- </div>
- )}
- {/* Smart Plugs Tab */}
- {activeTab === 'plugs' && (
- <div className="max-w-4xl">
- <div className="flex items-start justify-between mb-6">
- <div>
- <h2 className="text-lg font-semibold text-white flex items-center gap-2">
- <Plug className="w-5 h-5 text-bambu-green" />
- Smart Plugs
- </h2>
- <p className="text-sm text-bambu-gray mt-1">
- Connect Tasmota-based smart plugs to automate power control and track energy usage for your printers.
- </p>
- </div>
- <div className="flex items-center gap-2 pt-1 shrink-0">
- {smartPlugs && smartPlugs.filter(p => p.enabled).length > 1 && (
- <>
- <Button
- variant="secondary"
- size="sm"
- className="whitespace-nowrap"
- onClick={() => setShowBulkPlugConfirm('on')}
- disabled={bulkPlugActionMutation.isPending}
- title="Turn all plugs on"
- >
- {bulkPlugActionMutation.isPending ? (
- <Loader2 className="w-4 h-4 animate-spin" />
- ) : (
- <Power className="w-4 h-4 text-bambu-green" />
- )}
- All On
- </Button>
- <Button
- variant="secondary"
- size="sm"
- className="whitespace-nowrap"
- onClick={() => setShowBulkPlugConfirm('off')}
- disabled={bulkPlugActionMutation.isPending}
- title="Turn all plugs off"
- >
- {bulkPlugActionMutation.isPending ? (
- <Loader2 className="w-4 h-4 animate-spin" />
- ) : (
- <PowerOff className="w-4 h-4 text-red-400" />
- )}
- All Off
- </Button>
- </>
- )}
- <Button
- className="whitespace-nowrap"
- onClick={() => {
- setEditingPlug(null);
- setShowPlugModal(true);
- }}
- >
- <Plus className="w-4 h-4" />
- Add Smart Plug
- </Button>
- </div>
- </div>
- {/* Energy Summary Card */}
- {smartPlugs && smartPlugs.length > 0 && (
- <Card className="mb-6">
- <CardHeader>
- <h3 className="text-base font-semibold text-white flex items-center gap-2">
- <Zap className="w-4 h-4 text-yellow-400" />
- Energy Summary
- {energyLoading && (
- <Loader2 className="w-4 h-4 animate-spin text-bambu-gray ml-2" />
- )}
- </h3>
- </CardHeader>
- <CardContent>
- {plugEnergySummary ? (
- <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
- {/* Current Power */}
- <div className="bg-bambu-dark rounded-lg p-3">
- <div className="flex items-center gap-2 text-bambu-gray text-xs mb-1">
- <Zap className="w-3 h-3" />
- Current Power
- </div>
- <div className="text-xl font-bold text-white">
- {plugEnergySummary.totalPower.toFixed(1)}
- <span className="text-sm font-normal text-bambu-gray ml-1">W</span>
- </div>
- <div className="text-xs text-bambu-gray mt-1">
- {plugEnergySummary.reachableCount}/{plugEnergySummary.totalPlugs} plugs online
- </div>
- </div>
- {/* Today */}
- <div className="bg-bambu-dark rounded-lg p-3">
- <div className="flex items-center gap-2 text-bambu-gray text-xs mb-1">
- <Calendar className="w-3 h-3" />
- Today
- </div>
- <div className="text-xl font-bold text-white">
- {plugEnergySummary.totalToday.toFixed(2)}
- <span className="text-sm font-normal text-bambu-gray ml-1">kWh</span>
- </div>
- {localSettings && localSettings.energy_cost_per_kwh > 0 && (
- <div className="text-xs text-bambu-gray mt-1">
- ~{(plugEnergySummary.totalToday * localSettings.energy_cost_per_kwh).toFixed(2)} {localSettings.currency}
- </div>
- )}
- </div>
- {/* Yesterday */}
- <div className="bg-bambu-dark rounded-lg p-3">
- <div className="flex items-center gap-2 text-bambu-gray text-xs mb-1">
- <TrendingUp className="w-3 h-3" />
- Yesterday
- </div>
- <div className="text-xl font-bold text-white">
- {plugEnergySummary.totalYesterday.toFixed(2)}
- <span className="text-sm font-normal text-bambu-gray ml-1">kWh</span>
- </div>
- {localSettings && localSettings.energy_cost_per_kwh > 0 && (
- <div className="text-xs text-bambu-gray mt-1">
- ~{(plugEnergySummary.totalYesterday * localSettings.energy_cost_per_kwh).toFixed(2)} {localSettings.currency}
- </div>
- )}
- </div>
- {/* Total Lifetime */}
- <div className="bg-bambu-dark rounded-lg p-3">
- <div className="flex items-center gap-2 text-bambu-gray text-xs mb-1">
- <DollarSign className="w-3 h-3" />
- Total
- </div>
- <div className="text-xl font-bold text-white">
- {plugEnergySummary.totalLifetime.toFixed(1)}
- <span className="text-sm font-normal text-bambu-gray ml-1">kWh</span>
- </div>
- {localSettings && localSettings.energy_cost_per_kwh > 0 && (
- <div className="text-xs text-bambu-gray mt-1">
- ~{(plugEnergySummary.totalLifetime * localSettings.energy_cost_per_kwh).toFixed(2)} {localSettings.currency}
- </div>
- )}
- </div>
- </div>
- ) : !energyLoading ? (
- <p className="text-sm text-bambu-gray">
- Enable plugs to see energy summary
- </p>
- ) : null}
- </CardContent>
- </Card>
- )}
- {plugsLoading ? (
- <div className="flex justify-center py-12">
- <Loader2 className="w-8 h-8 text-bambu-green animate-spin" />
- </div>
- ) : smartPlugs && smartPlugs.length > 0 ? (
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
- {smartPlugs.map((plug) => (
- <SmartPlugCard
- key={plug.id}
- plug={plug}
- onEdit={(p) => {
- setEditingPlug(p);
- setShowPlugModal(true);
- }}
- />
- ))}
- </div>
- ) : (
- <Card>
- <CardContent className="py-12">
- <div className="text-center text-bambu-gray">
- <Plug className="w-16 h-16 mx-auto mb-4 opacity-30" />
- <p className="text-lg font-medium text-white mb-2">No smart plugs configured</p>
- <p className="text-sm mb-4">Add a Tasmota-based smart plug to track energy usage and automate power control.</p>
- <Button
- onClick={() => {
- setEditingPlug(null);
- setShowPlugModal(true);
- }}
- >
- <Plus className="w-4 h-4" />
- Add Your First Smart Plug
- </Button>
- </div>
- </CardContent>
- </Card>
- )}
- </div>
- )}
- {/* Notifications Tab */}
- {activeTab === 'notifications' && (
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
- {/* Left Column: Providers */}
- <div>
- <div className="flex items-center justify-between mb-4">
- <h2 className="text-lg font-semibold text-white flex items-center gap-2">
- <Bell className="w-5 h-5 text-bambu-green" />
- Providers
- </h2>
- <div className="flex items-center gap-2">
- <Button
- size="sm"
- variant="secondary"
- onClick={() => setShowLogViewer(true)}
- >
- <History className="w-4 h-4" />
- Log
- </Button>
- {notificationProviders && notificationProviders.length > 0 && (
- <Button
- size="sm"
- variant="secondary"
- onClick={() => {
- setTestAllResult(null);
- testAllMutation.mutate();
- }}
- disabled={testAllMutation.isPending}
- >
- {testAllMutation.isPending ? (
- <Loader2 className="w-4 h-4 animate-spin" />
- ) : (
- <Send className="w-4 h-4" />
- )}
- Test All
- </Button>
- )}
- <Button
- size="sm"
- onClick={() => {
- setEditingProvider(null);
- setShowNotificationModal(true);
- }}
- >
- <Plus className="w-4 h-4" />
- Add
- </Button>
- </div>
- </div>
- {/* Notification Language Setting */}
- <Card className="mb-4">
- <CardContent className="py-3">
- <div className="flex items-center justify-between">
- <div>
- <p className="text-white text-sm font-medium">{t('settings.notificationLanguage')}</p>
- <p className="text-xs text-bambu-gray">{t('settings.notificationLanguageDescription')}</p>
- </div>
- <select
- value={localSettings.notification_language || 'en'}
- onChange={(e) => updateSetting('notification_language', e.target.value)}
- className="px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green"
- >
- {availableLanguages.map((lang) => (
- <option key={lang.code} value={lang.code}>
- {lang.nativeName}
- </option>
- ))}
- </select>
- </div>
- </CardContent>
- </Card>
- {/* Test All Results */}
- {testAllResult && (
- <Card className="mb-4">
- <CardContent className="py-3">
- <div className="flex items-center justify-between mb-2">
- <span className="text-sm font-medium text-white">Test Results</span>
- <button
- onClick={() => setTestAllResult(null)}
- className="text-bambu-gray hover:text-white text-xs"
- >
- Dismiss
- </button>
- </div>
- <div className="flex items-center gap-4 text-sm mb-2">
- <span className="flex items-center gap-1 text-bambu-green">
- <CheckCircle className="w-4 h-4" />
- {testAllResult.success} passed
- </span>
- {testAllResult.failed > 0 && (
- <span className="flex items-center gap-1 text-red-400">
- <XCircle className="w-4 h-4" />
- {testAllResult.failed} failed
- </span>
- )}
- </div>
- {testAllResult.results.filter(r => !r.success).length > 0 && (
- <div className="space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary">
- {testAllResult.results.filter(r => !r.success).map((result) => (
- <div key={result.provider_id} className="text-xs text-red-400">
- <span className="font-medium">{result.provider_name}:</span> {result.message}
- </div>
- ))}
- </div>
- )}
- </CardContent>
- </Card>
- )}
- {providersLoading ? (
- <div className="flex justify-center py-12">
- <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
- </div>
- ) : notificationProviders && notificationProviders.length > 0 ? (
- <div className="space-y-3">
- {notificationProviders.map((provider) => (
- <NotificationProviderCard
- key={provider.id}
- provider={provider}
- onEdit={(p) => {
- setEditingProvider(p);
- setShowNotificationModal(true);
- }}
- />
- ))}
- </div>
- ) : (
- <Card>
- <CardContent className="py-8">
- <div className="text-center text-bambu-gray">
- <Bell className="w-12 h-12 mx-auto mb-3 opacity-30" />
- <p className="text-sm font-medium text-white mb-2">No providers configured</p>
- <p className="text-xs mb-3">Add a provider to receive alerts.</p>
- <Button
- size="sm"
- onClick={() => {
- setEditingProvider(null);
- setShowNotificationModal(true);
- }}
- >
- <Plus className="w-4 h-4" />
- Add Provider
- </Button>
- </div>
- </CardContent>
- </Card>
- )}
- </div>
- {/* Right Column: Templates */}
- <div>
- <h2 className="text-lg font-semibold text-white flex items-center gap-2 mb-4">
- <FileText className="w-5 h-5 text-bambu-green" />
- Message Templates
- </h2>
- <p className="text-sm text-bambu-gray mb-4">
- Customize notification messages for each event.
- </p>
- {templatesLoading ? (
- <div className="flex justify-center py-8">
- <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
- </div>
- ) : notificationTemplates && notificationTemplates.length > 0 ? (
- <div className="space-y-2">
- {notificationTemplates.map((template) => (
- <Card
- key={template.id}
- className="cursor-pointer hover:border-bambu-green/50 transition-colors"
- onClick={() => setEditingTemplate(template)}
- >
- <CardContent className="py-2.5 px-3">
- <div className="flex items-center justify-between">
- <div className="min-w-0 flex-1">
- <p className="text-white font-medium text-sm truncate">{template.name}</p>
- <p className="text-bambu-gray text-xs truncate mt-0.5">
- {template.title_template}
- </p>
- </div>
- <button
- className="p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2"
- onClick={(e) => {
- e.stopPropagation();
- setEditingTemplate(template);
- }}
- >
- <Edit2 className="w-4 h-4 text-bambu-gray" />
- </button>
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
- ) : (
- <Card>
- <CardContent className="py-8">
- <div className="text-center text-bambu-gray">
- <FileText className="w-12 h-12 mx-auto mb-3 opacity-30" />
- <p className="text-sm">No templates available. Restart the backend to seed default templates.</p>
- </div>
- </CardContent>
- </Card>
- )}
- </div>
- </div>
- )}
- {/* API Keys Tab */}
- {activeTab === 'apikeys' && (
- <div className="max-w-3xl">
- <div className="flex items-start justify-between gap-4 mb-6">
- <div className="flex-1">
- <h2 className="text-lg font-semibold text-white flex items-center gap-2">
- <Key className="w-5 h-5 text-bambu-green" />
- API Keys
- </h2>
- <p className="text-sm text-bambu-gray mt-1">
- Create API keys for external integrations and webhooks. Use these keys to control your printers from automation tools like Home Assistant.
- </p>
- </div>
- <Button size="sm" onClick={() => setShowCreateAPIKey(true)} className="flex-shrink-0">
- <Plus className="w-4 h-4" />
- Create Key
- </Button>
- </div>
- {/* Created Key Display */}
- {createdAPIKey && (
- <Card className="mb-6 border-bambu-green">
- <CardContent className="py-4">
- <div className="flex items-start gap-3">
- <CheckCircle className="w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5" />
- <div className="flex-1">
- <p className="text-white font-medium mb-1">API Key Created Successfully</p>
- <p className="text-sm text-bambu-gray mb-2">
- Copy this key now - it won't be shown again!
- </p>
- <div className="flex items-center gap-2 bg-bambu-dark rounded-lg p-2">
- <code className="flex-1 text-sm text-bambu-green font-mono break-all">
- {createdAPIKey}
- </code>
- <Button
- variant="secondary"
- size="sm"
- onClick={async () => {
- try {
- if (navigator.clipboard && navigator.clipboard.writeText) {
- await navigator.clipboard.writeText(createdAPIKey);
- } else {
- // Fallback for non-HTTPS contexts
- const textArea = document.createElement('textarea');
- textArea.value = createdAPIKey;
- textArea.style.position = 'fixed';
- textArea.style.left = '-999999px';
- document.body.appendChild(textArea);
- textArea.select();
- document.execCommand('copy');
- document.body.removeChild(textArea);
- }
- showToast('Key copied to clipboard');
- } catch {
- showToast('Failed to copy key', 'error');
- }
- }}
- >
- <Copy className="w-4 h-4" />
- </Button>
- </div>
- <Button
- variant="secondary"
- size="sm"
- className="mt-3"
- onClick={() => setCreatedAPIKey(null)}
- >
- Dismiss
- </Button>
- </div>
- </div>
- </CardContent>
- </Card>
- )}
- {/* Create Key Form */}
- {showCreateAPIKey && (
- <Card className="mb-6">
- <CardHeader>
- <h3 className="text-base font-semibold text-white">Create New API Key</h3>
- </CardHeader>
- <CardContent className="space-y-4">
- <div>
- <label className="block text-sm text-bambu-gray mb-1">Key Name</label>
- <input
- type="text"
- value={newAPIKeyName}
- onChange={(e) => setNewAPIKeyName(e.target.value)}
- placeholder="e.g., Home Assistant, OctoPrint"
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-2">Permissions</label>
- <div className="space-y-2">
- <label className="flex items-center gap-3 cursor-pointer">
- <input
- type="checkbox"
- checked={newAPIKeyPermissions.can_read_status}
- onChange={(e) => setNewAPIKeyPermissions(prev => ({ ...prev, can_read_status: e.target.checked }))}
- className="w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"
- />
- <div>
- <span className="text-white">Read Status</span>
- <p className="text-xs text-bambu-gray">View printer status and queue</p>
- </div>
- </label>
- <label className="flex items-center gap-3 cursor-pointer">
- <input
- type="checkbox"
- checked={newAPIKeyPermissions.can_queue}
- onChange={(e) => setNewAPIKeyPermissions(prev => ({ ...prev, can_queue: e.target.checked }))}
- className="w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"
- />
- <div>
- <span className="text-white">Manage Queue</span>
- <p className="text-xs text-bambu-gray">Add and remove items from print queue</p>
- </div>
- </label>
- <label className="flex items-center gap-3 cursor-pointer">
- <input
- type="checkbox"
- checked={newAPIKeyPermissions.can_control_printer}
- onChange={(e) => setNewAPIKeyPermissions(prev => ({ ...prev, can_control_printer: e.target.checked }))}
- className="w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"
- />
- <div>
- <span className="text-white">Control Printer</span>
- <p className="text-xs text-bambu-gray">Pause, resume, and stop prints</p>
- </div>
- </label>
- </div>
- </div>
- <div className="flex items-center gap-2 pt-2">
- <Button
- onClick={() => createAPIKeyMutation.mutate({
- name: newAPIKeyName || 'Unnamed Key',
- ...newAPIKeyPermissions,
- })}
- disabled={createAPIKeyMutation.isPending}
- >
- {createAPIKeyMutation.isPending ? (
- <Loader2 className="w-4 h-4 animate-spin" />
- ) : (
- <Plus className="w-4 h-4" />
- )}
- Create Key
- </Button>
- <Button variant="secondary" onClick={() => setShowCreateAPIKey(false)}>
- Cancel
- </Button>
- </div>
- </CardContent>
- </Card>
- )}
- {/* Existing Keys List */}
- {apiKeysLoading ? (
- <div className="flex justify-center py-12">
- <Loader2 className="w-8 h-8 text-bambu-green animate-spin" />
- </div>
- ) : apiKeys && apiKeys.length > 0 ? (
- <div className="space-y-3">
- {apiKeys.map((key) => (
- <Card key={key.id}>
- <CardContent className="py-3">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-3">
- <Key className={`w-5 h-5 ${key.enabled ? 'text-bambu-green' : 'text-bambu-gray'}`} />
- <div>
- <p className="text-white font-medium">{key.name}</p>
- <p className="text-xs text-bambu-gray">
- {key.key_prefix}••••••••
- {key.last_used && ` · Last used: ${new Date(key.last_used).toLocaleDateString()}`}
- </p>
- </div>
- </div>
- <div className="flex items-center gap-2">
- <div className="flex gap-1 text-xs">
- {key.can_read_status && (
- <span className="px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded">Read</span>
- )}
- {key.can_queue && (
- <span className="px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded">Queue</span>
- )}
- {key.can_control_printer && (
- <span className="px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded">Control</span>
- )}
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowDeleteAPIKeyConfirm(key.id)}
- >
- <Trash2 className="w-4 h-4 text-red-400" />
- </Button>
- </div>
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
- ) : (
- <Card>
- <CardContent className="py-12">
- <div className="text-center text-bambu-gray">
- <Key className="w-16 h-16 mx-auto mb-4 opacity-30" />
- <p className="text-lg font-medium text-white mb-2">No API keys</p>
- <p className="text-sm mb-4">Create an API key to integrate with external services.</p>
- <Button onClick={() => setShowCreateAPIKey(true)}>
- <Plus className="w-4 h-4" />
- Create Your First Key
- </Button>
- </div>
- </CardContent>
- </Card>
- )}
- {/* Webhook Documentation */}
- <Card className="mt-6">
- <CardHeader>
- <h3 className="text-base font-semibold text-white">Webhook Endpoints</h3>
- </CardHeader>
- <CardContent className="space-y-3 text-sm">
- <p className="text-bambu-gray">
- Use your API key in the <code className="text-bambu-green">X-API-Key</code> header.
- </p>
- <div className="space-y-2 font-mono text-xs">
- <div className="p-2 bg-bambu-dark rounded">
- <span className="text-blue-400">GET</span>{' '}
- <span className="text-white">/api/v1/webhook/status</span>
- <span className="text-bambu-gray"> - Get all printer status</span>
- </div>
- <div className="p-2 bg-bambu-dark rounded">
- <span className="text-blue-400">GET</span>{' '}
- <span className="text-white">/api/v1/webhook/status/:id</span>
- <span className="text-bambu-gray"> - Get specific printer status</span>
- </div>
- <div className="p-2 bg-bambu-dark rounded">
- <span className="text-green-400">POST</span>{' '}
- <span className="text-white">/api/v1/webhook/queue</span>
- <span className="text-bambu-gray"> - Add to print queue</span>
- </div>
- <div className="p-2 bg-bambu-dark rounded">
- <span className="text-orange-400">POST</span>{' '}
- <span className="text-white">/api/v1/webhook/printer/:id/pause</span>
- <span className="text-bambu-gray"> - Pause print</span>
- </div>
- <div className="p-2 bg-bambu-dark rounded">
- <span className="text-orange-400">POST</span>{' '}
- <span className="text-white">/api/v1/webhook/printer/:id/resume</span>
- <span className="text-bambu-gray"> - Resume print</span>
- </div>
- <div className="p-2 bg-bambu-dark rounded">
- <span className="text-red-400">POST</span>{' '}
- <span className="text-white">/api/v1/webhook/printer/:id/stop</span>
- <span className="text-bambu-gray"> - Stop print</span>
- </div>
- </div>
- </CardContent>
- </Card>
- </div>
- )}
- {/* Delete API Key Confirmation */}
- {showDeleteAPIKeyConfirm !== null && (
- <ConfirmModal
- title="Delete API Key"
- message="Are you sure you want to delete this API key? Any integrations using this key will stop working."
- confirmText="Delete Key"
- variant="danger"
- onConfirm={() => {
- deleteAPIKeyMutation.mutate(showDeleteAPIKeyConfirm);
- setShowDeleteAPIKeyConfirm(null);
- }}
- onCancel={() => setShowDeleteAPIKeyConfirm(null)}
- />
- )}
- {/* Smart Plug Modal */}
- {showPlugModal && (
- <AddSmartPlugModal
- plug={editingPlug}
- onClose={() => {
- setShowPlugModal(false);
- setEditingPlug(null);
- }}
- />
- )}
- {/* Notification Modal */}
- {showNotificationModal && (
- <AddNotificationModal
- provider={editingProvider}
- onClose={() => {
- setShowNotificationModal(false);
- setEditingProvider(null);
- }}
- />
- )}
- {/* Template Editor Modal */}
- {editingTemplate && (
- <NotificationTemplateEditor
- template={editingTemplate}
- onClose={() => setEditingTemplate(null)}
- />
- )}
- {/* Notification Log Viewer */}
- {showLogViewer && (
- <NotificationLogViewer
- onClose={() => setShowLogViewer(false)}
- />
- )}
- {/* Confirm Modal: Clear Notification Logs */}
- {showClearLogsConfirm && (
- <ConfirmModal
- title="Clear Notification Logs"
- message="This will permanently delete all notification logs older than 30 days. This action cannot be undone."
- confirmText="Clear Logs"
- variant="warning"
- onConfirm={async () => {
- setShowClearLogsConfirm(false);
- try {
- const result = await api.clearNotificationLogs(30);
- showToast(result.message, 'success');
- } catch {
- showToast('Failed to clear logs', 'error');
- }
- }}
- onCancel={() => setShowClearLogsConfirm(false)}
- />
- )}
- {/* Confirm Modal: Clear Local Storage */}
- {showClearStorageConfirm && (
- <ConfirmModal
- title="Reset UI Preferences"
- message="This will reset all UI preferences to defaults: sidebar order, theme, dashboard layout, view modes, and sorting preferences. Your printers, archives, and server settings will NOT be affected. The page will reload after clearing."
- confirmText="Reset Preferences"
- variant="default"
- onConfirm={() => {
- setShowClearStorageConfirm(false);
- localStorage.clear();
- showToast('UI preferences reset. Refreshing...', 'success');
- setTimeout(() => window.location.reload(), 1000);
- }}
- onCancel={() => setShowClearStorageConfirm(false)}
- />
- )}
- {/* Confirm Modal: Bulk Plug Action */}
- {showBulkPlugConfirm && (
- <ConfirmModal
- title={`Turn All Plugs ${showBulkPlugConfirm === 'on' ? 'On' : 'Off'}`}
- message={`This will turn ${showBulkPlugConfirm === 'on' ? 'ON' : 'OFF'} all ${smartPlugs?.filter(p => p.enabled).length || 0} enabled smart plugs. ${showBulkPlugConfirm === 'off' ? 'Any running printers may be affected!' : ''}`}
- confirmText={`Turn All ${showBulkPlugConfirm === 'on' ? 'On' : 'Off'}`}
- variant={showBulkPlugConfirm === 'off' ? 'danger' : 'warning'}
- onConfirm={() => {
- const action = showBulkPlugConfirm;
- setShowBulkPlugConfirm(null);
- bulkPlugActionMutation.mutate(action);
- }}
- onCancel={() => setShowBulkPlugConfirm(null)}
- />
- )}
- {/* Backup Modal */}
- {showBackupModal && (
- <BackupModal
- onClose={() => setShowBackupModal(false)}
- onExport={async (categories) => {
- setShowBackupModal(false);
- try {
- const { blob, filename } = await api.exportBackup(categories);
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = filename;
- a.click();
- URL.revokeObjectURL(url);
- showToast('Backup downloaded', 'success');
- } catch (err) {
- showToast('Failed to create backup', 'error');
- }
- }}
- />
- )}
- {/* Restore Modal */}
- {showRestoreModal && (
- <RestoreModal
- onClose={() => setShowRestoreModal(false)}
- onRestore={async (file, overwrite) => {
- return await api.importBackup(file, overwrite);
- }}
- onSuccess={() => {
- queryClient.invalidateQueries();
- }}
- />
- )}
- </div>
- );
- }
|