feat: add new frontend components, MH batch worker, and gitignore rules

- Add all new Frontend source files (pages, components, hooks, utils)
- Add selenium_MHBatchPaymentCheckWorker.py and MHSinglePaymentCheckWorker.py
- Add install-steps-5-13.sh setup script
- Update .gitignore to exclude runtime/sensitive data (backups, uploads,
  chat-history, keys, downloads, generated .d.ts files) while keeping folders
- Add .gitkeep to preserve empty runtime folders in git

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-26 00:23:43 -04:00
co-authored by Claude Sonnet 4.6
parent b7e06adf2f
commit 1edf73fdc8
173 changed files with 33469 additions and 0 deletions
@@ -0,0 +1,179 @@
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
import { FolderOpen, HardDrive, Trash2 } from "lucide-react";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { FolderBrowserModal } from "./folder-browser-modal";
export function BackupDestinationManager() {
const { toast } = useToast();
const [path, setPath] = useState("");
const [deleteId, setDeleteId] = useState(null);
const [browserOpen, setBrowserOpen] = useState(false);
// ==============================
// Queries
// ==============================
const { data: destinations = [] } = useQuery({
queryKey: ["/db/destination"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/destination");
return res.json();
},
});
const { data: usbSettingData } = useQuery({
queryKey: ["/db/usb-backup-setting"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/usb-backup-setting");
return res.json();
},
});
const usbBackupEnabled = usbSettingData?.usbBackupEnabled ?? false;
const usbBackupHour = usbSettingData?.usbBackupHour ?? 21;
const usbToggleMutation = useMutation({
mutationFn: async (patch) => {
const res = await apiRequest("PUT", "/api/database-management/usb-backup-setting", patch);
return res.json();
},
onSuccess: (data) => {
queryClient.setQueryData(["/db/usb-backup-setting"], data);
toast({ title: "Setting Saved" });
},
onError: () => {
toast({
title: "Error",
description: "Failed to update USB backup setting.",
variant: "destructive",
});
},
});
// ==============================
// Mutations
// ==============================
const saveMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("POST", "/api/database-management/destination", { path });
if (!res.ok)
throw new Error((await res.json()).error);
},
onSuccess: () => {
toast({ title: "Backup destination saved" });
setPath("");
queryClient.invalidateQueries({ queryKey: ["/db/destination"] });
},
});
const deleteMutation = useMutation({
mutationFn: async (id) => {
await apiRequest("DELETE", `/api/database-management/destination/${id}`);
},
onSuccess: () => {
toast({ title: "Backup destination deleted" });
queryClient.invalidateQueries({ queryKey: ["/db/destination"] });
setDeleteId(null);
},
});
const backupNowMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("POST", "/api/database-management/backup-path");
if (!res.ok) {
const body = await res.json();
throw new Error(body.details || body.error || "Backup failed");
}
return res.json();
},
onSuccess: (data) => {
toast({ title: "Backup complete", description: `Saved: ${data.filename}` });
queryClient.invalidateQueries({ queryKey: ["/db/status"] });
},
onError: (err) => {
toast({ title: "Backup failed", description: err.message, variant: "destructive" });
},
});
// ==============================
// Folder browser
// ==============================
const handleFolderSelect = (selectedPath) => {
setPath(selectedPath);
};
// ==============================
// UI
// ==============================
return (<Card>
<CardHeader>
<CardTitle>External Backup Destination</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<Switch id="usb-backup-toggle" checked={usbBackupEnabled} onCheckedChange={(checked) => usbToggleMutation.mutate({ usbBackupEnabled: checked })} disabled={usbToggleMutation.isPending}/>
<label htmlFor="usb-backup-toggle" className="text-sm font-medium text-gray-700 cursor-pointer select-none">
USB Backup
</label>
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600">at</label>
<select className="border rounded px-2 py-1 text-sm text-gray-700 bg-white" value={usbBackupHour} onChange={(e) => usbToggleMutation.mutate({ usbBackupHour: Number(e.target.value) })}>
{Array.from({ length: 24 }, (_, h) => {
const label = h === 0 ? "12:00 AM" : h < 12 ? `${h}:00 AM` : h === 12 ? "12:00 PM" : `${h - 12}:00 PM`;
return <option key={h} value={h}>{label}</option>;
})}
</select>
</div>
</div>
<p className="text-sm text-gray-500">
Enter the root path of your USB drive below. The app will automatically back up to the{" "}
<span className="font-medium text-gray-700">USB Backup</span> folder inside it at the scheduled time when the toggle is on.
</p>
<div className="flex gap-2">
<Input placeholder="/media/usb-drive or D:\\Backups" value={path} onChange={(e) => setPath(e.target.value)}/>
<Button variant="outline" onClick={() => setBrowserOpen(true)} title="Browse folders">
<FolderOpen className="h-4 w-4"/>
</Button>
</div>
<FolderBrowserModal open={browserOpen} onClose={() => setBrowserOpen(false)} onSelect={handleFolderSelect}/>
<Button onClick={() => saveMutation.mutate()} disabled={!path || saveMutation.isPending}>
Save Destination
</Button>
<div className="space-y-2">
{destinations.map((d) => (<div key={d.id} className="flex justify-between items-center border rounded p-2">
<span className="text-sm text-gray-700">{d.path}</span>
<div className="flex gap-2">
<Button size="sm" variant="outline" onClick={() => backupNowMutation.mutate()} disabled={backupNowMutation.isPending} title="Backup now to this destination">
<HardDrive className="h-4 w-4 mr-1"/>
{backupNowMutation.isPending ? "Backing up..." : "Backup Now"}
</Button>
<Button size="sm" variant="destructive" onClick={() => setDeleteId(d.id)}>
<Trash2 className="h-4 w-4"/>
</Button>
</div>
</div>))}
</div>
{/* Confirm delete dialog */}
<AlertDialog open={deleteId !== null}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete backup destination?</AlertDialogTitle>
<AlertDialogDescription>
This will remove the destination and stop automatic backups.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => setDeleteId(null)}>
Cancel
</AlertDialogCancel>
<AlertDialogAction onClick={() => deleteId && deleteMutation.mutate(deleteId)}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</CardContent>
</Card>);
}
@@ -0,0 +1,75 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { apiRequest } from "@/lib/queryClient";
import { Folder, FolderOpen, ChevronLeft, Loader2 } from "lucide-react";
export function FolderBrowserModal({ open, onClose, onSelect }) {
const [browsePath, setBrowsePath] = useState("/");
const [selected, setSelected] = useState("/");
const { data, isLoading, isError } = useQuery({
queryKey: ["/db/browse", browsePath],
queryFn: async () => {
const res = await apiRequest("GET", `/api/database-management/browse?path=${encodeURIComponent(browsePath)}`);
if (!res.ok)
throw new Error((await res.json()).error);
return res.json();
},
enabled: open,
});
const handleNavigate = (path) => {
setSelected(path);
setBrowsePath(path);
};
const handleConfirm = () => {
onSelect(selected);
onClose();
};
return (<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>Select Folder</DialogTitle>
</DialogHeader>
{/* Current path breadcrumb */}
<div className="text-xs text-gray-500 bg-gray-50 rounded px-3 py-2 font-mono break-all">
{data?.current ?? browsePath}
</div>
{/* Back button */}
{data?.parent && (<Button variant="ghost" size="sm" className="justify-start text-gray-600" onClick={() => handleNavigate(data.parent)}>
<ChevronLeft className="h-4 w-4 mr-1"/>
Back
</Button>)}
{/* Directory list */}
<div className="border rounded-md overflow-y-auto max-h-64">
{isLoading && (<div className="flex items-center justify-center py-8 text-gray-400">
<Loader2 className="h-5 w-5 animate-spin mr-2"/>
Loading...
</div>)}
{isError && (<p className="text-sm text-red-500 p-4">Cannot read this directory.</p>)}
{!isLoading && !isError && data?.dirs.length === 0 && (<p className="text-sm text-gray-400 p-4">No sub-folders here.</p>)}
{!isLoading &&
!isError &&
data?.dirs.map((dir) => (<button key={dir.path} className={`w-full flex items-center gap-2 px-3 py-2 text-sm text-left hover:bg-gray-50 transition-colors ${selected === dir.path ? "bg-blue-50 text-blue-700 font-medium" : "text-gray-700"}`} onClick={() => setSelected(dir.path)} onDoubleClick={() => handleNavigate(dir.path)}>
{selected === dir.path ? (<FolderOpen className="h-4 w-4 shrink-0 text-blue-500"/>) : (<Folder className="h-4 w-4 shrink-0 text-yellow-500"/>)}
{dir.name}
</button>))}
</div>
<p className="text-xs text-gray-400">
Single-click to select · Double-click to open
</p>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
<Button onClick={handleConfirm}>
Select Folder
</Button>
</DialogFooter>
</DialogContent>
</Dialog>);
}
@@ -0,0 +1,116 @@
import { useRef, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Upload, UploadCloud } from "lucide-react";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
import { useToast } from "@/hooks/use-toast";
export function ImportDatabaseSection() {
const { toast } = useToast();
const fileInputRef = useRef(null);
const [selectedFile, setSelectedFile] = useState(null);
const [confirmOpen, setConfirmOpen] = useState(false);
const restoreMutation = useMutation({
mutationFn: async (file) => {
const formData = new FormData();
formData.append("file", file);
const token = localStorage.getItem("token");
const res = await fetch("/api/database-management/restore", {
method: "POST",
headers: token ? { Authorization: `Bearer ${token}` } : {},
body: formData,
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || "Restore failed");
}
return res.json();
},
onSuccess: () => {
toast({
title: "Database Restored",
description: "Database restored successfully. Redirecting to login...",
});
setSelectedFile(null);
if (fileInputRef.current)
fileInputRef.current.value = "";
// Clear auth token and reload so the user re-authenticates against the
// restored database. This is necessary because the restored data may have
// a different userId than the current JWT, which would cause all
// user-scoped queries to return empty results.
setTimeout(() => {
localStorage.removeItem("token");
window.location.href = "/";
}, 2000);
},
onError: (err) => {
toast({
title: "Restore Failed",
description: err.message,
variant: "destructive",
});
},
});
const handleFileChange = (e) => {
const file = e.target.files?.[0] ?? null;
setSelectedFile(file);
};
const handleImportClick = () => {
if (!selectedFile)
return;
setConfirmOpen(true);
};
const handleConfirm = () => {
setConfirmOpen(false);
if (selectedFile)
restoreMutation.mutate(selectedFile);
};
return (<>
<Card>
<CardHeader>
<CardTitle className="flex items-center space-x-2">
<UploadCloud className="h-5 w-5"/>
<span>Import Database</span>
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-gray-500">
Restore the database from a <span className="font-medium text-gray-700">.sql</span> or <span className="font-medium text-gray-700">.zip</span> backup file.
This will overwrite all existing data.
</p>
<div className="flex items-center gap-3">
<input ref={fileInputRef} type="file" accept=".sql,.zip" onChange={handleFileChange} className="block text-sm text-gray-600 file:mr-3 file:py-1.5 file:px-3 file:rounded file:border file:border-gray-300 file:text-sm file:bg-white file:text-gray-700 hover:file:bg-gray-50 cursor-pointer"/>
</div>
{selectedFile && (<p className="text-sm text-gray-500">
Selected: <span className="font-medium text-gray-800">{selectedFile.name}</span>{" "}
({(selectedFile.size / 1024 / 1024).toFixed(1)} MB)
</p>)}
<Button onClick={handleImportClick} disabled={!selectedFile || restoreMutation.isPending} variant="destructive" className="flex items-center space-x-2">
<Upload className="h-4 w-4"/>
<span>{restoreMutation.isPending ? "Restoring..." : "Import & Restore"}</span>
</Button>
</CardContent>
</Card>
<AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Restore database?</AlertDialogTitle>
<AlertDialogDescription>
This will overwrite <strong>all existing data</strong> with the contents of{" "}
<strong>{selectedFile?.name}</strong>. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleConfirm} className="bg-red-600 hover:bg-red-700">
Yes, restore
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>);
}
@@ -0,0 +1,516 @@
import { useState, useEffect } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
import { Copy, Eye, EyeOff, RefreshCw, Network, RotateCcw, HardDrive } from "lucide-react";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
const HOUR_OPTIONS = Array.from({ length: 24 }, (_, h) => {
const label = h === 0
? "12:00 AM (midnight)"
: h < 12
? `${h}:00 AM`
: h === 12
? "12:00 PM (noon)"
: `${h - 12}:00 PM`;
return { value: h, label };
});
export function NetworkBackupManager() {
return (<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Network className="h-5 w-5"/>
Network Backup
</CardTitle>
</CardHeader>
<CardContent>
<Tabs defaultValue="rclone">
<TabsList className="mb-4">
<TabsTrigger value="rclone">
<HardDrive className="h-4 w-4 mr-1"/>
Rclone
</TabsTrigger>
<TabsTrigger value="apikey">
<Network className="h-4 w-4 mr-1"/>
API Key
</TabsTrigger>
</TabsList>
<TabsContent value="rclone">
<RcloneBackupSection />
</TabsContent>
<TabsContent value="apikey">
<ApiKeyBackupSection />
</TabsContent>
</Tabs>
</CardContent>
</Card>);
}
// ============================================================
// Tab 1: Rclone
// ============================================================
function RcloneBackupSection() {
const { toast } = useToast();
// Server (source) state
const [serverEnabled, setServerEnabled] = useState(false);
const [serverPort, setServerPort] = useState(8080);
// Receiver state
const [receiverEnabled, setReceiverEnabled] = useState(false);
const [receiverSyncHour, setReceiverSyncHour] = useState(21);
const [sourceIp, setSourceIp] = useState("");
const [sourcePort, setSourcePort] = useState(8080);
// Auto-import state
const [autoImportEnabled, setAutoImportEnabled] = useState(false);
const [autoImportHour, setAutoImportHour] = useState(22);
const [formLoaded, setFormLoaded] = useState(false);
const { data: rcloneConfig } = useQuery({
queryKey: ["/db/rclone-config"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/rclone-config");
return res.json();
},
});
const { data: rcloneStatus } = useQuery({
queryKey: ["/db/rclone-status"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/rclone-status");
return res.json();
},
refetchInterval: 5000,
});
useEffect(() => {
if (rcloneConfig && !formLoaded) {
setServerEnabled(rcloneConfig.serverEnabled ?? false);
setServerPort(rcloneConfig.serverPort ?? 8080);
setReceiverEnabled(rcloneConfig.receiverEnabled ?? false);
setReceiverSyncHour(rcloneConfig.receiverSyncHour ?? 21);
setSourceIp(rcloneConfig.sourceIp ?? "");
setSourcePort(rcloneConfig.sourcePort ?? 8080);
setAutoImportEnabled(rcloneConfig.autoImportEnabled ?? false);
setAutoImportHour(rcloneConfig.autoImportHour ?? 22);
setFormLoaded(true);
}
}, [rcloneConfig, formLoaded]);
const saveMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("PUT", "/api/database-management/rclone-config", {
serverEnabled,
serverPort,
receiverEnabled,
receiverSyncHour,
sourceIp,
sourcePort,
autoImportEnabled,
autoImportHour,
});
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/db/rclone-config"] });
toast({ title: "Rclone settings saved" });
},
onError: () => {
toast({ title: "Error", description: "Failed to save rclone settings.", variant: "destructive" });
},
});
const pullNowMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("POST", "/api/database-management/rclone-pull-now");
if (!res.ok) {
const body = await res.json();
throw new Error(body.details || body.error || "Pull failed");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/db/rclone-config"] });
toast({ title: "Rclone pull complete", description: "Backup files copied from source PC." });
},
onError: (err) => {
queryClient.invalidateQueries({ queryKey: ["/db/rclone-config"] });
toast({ title: "Rclone pull failed", description: err.message, variant: "destructive" });
},
});
const importNowMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("POST", "/api/database-management/auto-import-now");
if (!res.ok) {
const body = await res.json();
throw new Error(body.details || body.error || "Import failed");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/db/rclone-config"] });
toast({ title: "Import complete", description: "Latest backup restored to database." });
},
onError: (err) => {
queryClient.invalidateQueries({ queryKey: ["/db/rclone-config"] });
toast({ title: "Import failed", description: err.message, variant: "destructive" });
},
});
const serverRunning = rcloneStatus?.serverRunning ?? false;
return (<div className="space-y-6">
{/* ── Source PC: Serve backups via WebDAV ── */}
<div className="space-y-3 border rounded-lg p-4">
<div className="flex items-center justify-between">
<p className="text-sm font-semibold text-gray-800">Source PC — Serve Backups</p>
<div className={`flex items-center gap-1.5 text-xs ${serverRunning ? "text-green-600" : "text-gray-400"}`}>
<div className={`w-2 h-2 rounded-full ${serverRunning ? "bg-green-500" : "bg-gray-300"}`}/>
{serverRunning ? "Running" : "Stopped"}
</div>
</div>
<p className="text-xs text-gray-500">
Enable this on the source PC to serve the <code>backups/</code> folder via WebDAV.
The backup PC will connect to this machine to pull files.
</p>
<div className="flex flex-wrap items-center gap-4">
<div className="flex items-center gap-2">
<Switch id="rclone-server-toggle" checked={serverEnabled} onCheckedChange={setServerEnabled}/>
<label htmlFor="rclone-server-toggle" className="text-sm font-medium text-gray-700 cursor-pointer select-none">
Enable WebDAV server
</label>
</div>
</div>
<div className="space-y-1 max-w-xs">
<label className="text-xs font-medium text-gray-600">Port</label>
<Input type="number" placeholder="8080" value={serverPort} onChange={(e) => setServerPort(Number(e.target.value))}/>
</div>
</div>
{/* ── Receiver PC: Pull backups from source ── */}
<div className="space-y-3 border rounded-lg p-4">
<p className="text-sm font-semibold text-gray-800">Receiver PC — Pull Backups</p>
<p className="text-xs text-gray-500">
Enable this on the backup PC to pull backup files from the source PC's WebDAV server
at a scheduled time each day.
</p>
<div className="flex flex-wrap items-center gap-4">
<div className="flex items-center gap-2">
<Switch id="rclone-receiver-toggle" checked={receiverEnabled} onCheckedChange={setReceiverEnabled}/>
<label htmlFor="rclone-receiver-toggle" className="text-sm font-medium text-gray-700 cursor-pointer select-none">
Enable daily pull
</label>
</div>
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600 whitespace-nowrap">at</label>
<select className="border rounded px-2 py-1 text-sm text-gray-700 bg-white" value={receiverSyncHour} onChange={(e) => setReceiverSyncHour(Number(e.target.value))}>
{HOUR_OPTIONS.map((o) => (<option key={o.value} value={o.value}>
{o.label}
</option>))}
</select>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div className="space-y-1">
<label className="text-xs font-medium text-gray-600">Source PC IP</label>
<Input placeholder="192.168.0.94" value={sourceIp} onChange={(e) => setSourceIp(e.target.value)}/>
</div>
<div className="space-y-1">
<label className="text-xs font-medium text-gray-600">Source PC Port</label>
<Input type="number" placeholder="8080" value={sourcePort} onChange={(e) => setSourcePort(Number(e.target.value))}/>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => pullNowMutation.mutate()} disabled={pullNowMutation.isPending || !sourceIp}>
<RotateCcw className="h-4 w-4 mr-1"/>
{pullNowMutation.isPending ? "Pulling..." : "Pull Now"}
</Button>
</div>
<RcloneSyncStatus />
</div>
{/* ── Auto-Import: restore latest backup to database ── */}
<div className="space-y-3 border rounded-lg p-4">
<p className="text-sm font-semibold text-gray-800">Auto-Import Database</p>
<p className="text-xs text-gray-500">
Automatically restore the latest backup file from the <code>backups/</code> folder
into this PC's database after rclone finishes pulling.
</p>
<div className="flex flex-wrap items-center gap-4">
<div className="flex items-center gap-2">
<Switch id="auto-import-toggle" checked={autoImportEnabled} onCheckedChange={setAutoImportEnabled}/>
<label htmlFor="auto-import-toggle" className="text-sm font-medium text-gray-700 cursor-pointer select-none">
Enable auto-import
</label>
</div>
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600 whitespace-nowrap">at</label>
<select className="border rounded px-2 py-1 text-sm text-gray-700 bg-white" value={autoImportHour} onChange={(e) => setAutoImportHour(Number(e.target.value))}>
{HOUR_OPTIONS.map((o) => (<option key={o.value} value={o.value}>
{o.label}
</option>))}
</select>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => importNowMutation.mutate()} disabled={importNowMutation.isPending}>
<RotateCcw className="h-4 w-4 mr-1"/>
{importNowMutation.isPending ? "Importing..." : "Import Now"}
</Button>
</div>
<AutoImportStatus />
</div>
{/* Save all settings */}
<Button onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}>
{saveMutation.isPending ? "Saving..." : "Save Rclone Settings"}
</Button>
</div>);
}
function RcloneSyncStatus() {
const { data } = useQuery({
queryKey: ["/db/rclone-config"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/rclone-config");
return res.json();
},
});
if (!data?.lastSyncAt)
return null;
const date = new Date(data.lastSyncAt).toLocaleString();
const ok = data.lastSyncStatus === "success";
return (<div className={`text-xs rounded p-2 ${ok ? "bg-green-50 text-green-700" : "bg-red-50 text-red-700"}`}>
{ok ? "Last pull: " : "Last pull failed: "}{date}
{!ok && data.lastSyncError && (<span className="block mt-0.5 text-red-500">{data.lastSyncError}</span>)}
</div>);
}
function AutoImportStatus() {
const { data } = useQuery({
queryKey: ["/db/rclone-config"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/rclone-config");
return res.json();
},
});
if (!data?.lastImportAt)
return null;
const date = new Date(data.lastImportAt).toLocaleString();
const ok = data.lastImportStatus === "success";
return (<div className={`text-xs rounded p-2 ${ok ? "bg-green-50 text-green-700" : "bg-red-50 text-red-700"}`}>
{ok ? "Last import: " : "Last import failed: "}{date}
{!ok && data.lastImportError && (<span className="block mt-0.5 text-red-500">{data.lastImportError}</span>)}
</div>);
}
// ============================================================
// Tab 2: API Key (existing behavior)
// ============================================================
function ApiKeyBackupSection() {
const { toast } = useToast();
const [showKey, setShowKey] = useState(false);
const [showReceiverKey, setShowReceiverKey] = useState(false);
const [confirmRegenOpen, setConfirmRegenOpen] = useState(false);
const [enabled, setEnabled] = useState(false);
const [syncHour, setSyncHour] = useState(0);
const [sourceUrl, setSourceUrl] = useState("");
const [receiverApiKey, setReceiverApiKey] = useState("");
const [formLoaded, setFormLoaded] = useState(false);
const { data: keyData } = useQuery({
queryKey: ["/db/network-backup-key"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/network-backup-key");
return res.json();
},
});
const { data: syncConfig } = useQuery({
queryKey: ["/db/network-sync-config"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/network-sync-config");
return res.json();
},
});
useEffect(() => {
if (syncConfig && !formLoaded) {
setEnabled(syncConfig.enabled ?? false);
setSyncHour(syncConfig.syncHour ?? 0);
setSourceUrl(syncConfig.sourceUrl ?? "");
setReceiverApiKey(syncConfig.apiKey ?? "");
setFormLoaded(true);
}
}, [syncConfig, formLoaded]);
const regenMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("POST", "/api/database-management/network-backup-key/regenerate");
return res.json();
},
onSuccess: (data) => {
queryClient.setQueryData(["/db/network-backup-key"], data);
setConfirmRegenOpen(false);
toast({ title: "API key regenerated", description: "Update the key on your backup PC." });
},
onError: () => {
toast({ title: "Error", description: "Failed to regenerate key.", variant: "destructive" });
},
});
const saveMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("PUT", "/api/database-management/network-sync-config", {
enabled,
syncHour,
sourceUrl: sourceUrl.trim(),
apiKey: receiverApiKey.trim(),
});
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/db/network-sync-config"] });
toast({ title: "Network sync settings saved" });
},
onError: () => {
toast({ title: "Error", description: "Failed to save settings.", variant: "destructive" });
},
});
const syncNowMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("POST", "/api/database-management/network-sync-now");
if (!res.ok) {
const body = await res.json();
throw new Error(body.details || body.error || "Sync failed");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/db/network-sync-config"] });
toast({ title: "Sync complete", description: "Database synced from source PC." });
},
onError: (err) => {
queryClient.invalidateQueries({ queryKey: ["/db/network-sync-config"] });
toast({ title: "Sync failed", description: err.message, variant: "destructive" });
},
});
const displayKey = keyData?.apiKey ?? "";
const maskedKey = displayKey ? "••••••••-••••-••••-••••-" + displayKey.slice(-12) : "—";
return (<div className="space-y-6">
{/* Source role */}
<div className="space-y-3">
<p className="text-sm font-semibold text-gray-800">This Machine's Backup Key</p>
<p className="text-xs text-gray-500">
Share this key with the backup PC so it can pull a copy of this machine's
database. The key survives database restores (stored in a local file).
</p>
<div className="flex items-center gap-2">
<Input readOnly value={showKey ? displayKey : maskedKey} className="font-mono text-sm"/>
<Button variant="outline" size="icon" title={showKey ? "Hide key" : "Show key"} onClick={() => setShowKey((v) => !v)}>
{showKey ? <EyeOff className="h-4 w-4"/> : <Eye className="h-4 w-4"/>}
</Button>
<Button variant="outline" size="icon" title="Copy to clipboard" onClick={() => {
navigator.clipboard.writeText(displayKey);
toast({ title: "Copied to clipboard" });
}} disabled={!displayKey}>
<Copy className="h-4 w-4"/>
</Button>
<Button variant="outline" size="icon" title="Regenerate key" onClick={() => setConfirmRegenOpen(true)} disabled={regenMutation.isPending}>
<RefreshCw className="h-4 w-4"/>
</Button>
</div>
</div>
<div className="border-t"/>
{/* Receiver role */}
<div className="space-y-4">
<p className="text-sm font-semibold text-gray-800">Sync from Another PC</p>
<p className="text-xs text-gray-500">
Configure this machine to pull a fresh copy of the database and all uploaded
files (patient photos, cloud storage, documents) from another PC at a scheduled
time each day. Enter the source PC's URL (e.g. http://192.168.0.94 — no port number) and the Backup Key shown in the source PC's Network Backup section.
</p>
<div className="flex flex-wrap items-center gap-4">
<div className="flex items-center gap-2">
<Switch id="network-sync-toggle" checked={enabled} onCheckedChange={setEnabled}/>
<label htmlFor="network-sync-toggle" className="text-sm font-medium text-gray-700 cursor-pointer select-none">
Enable daily sync
</label>
</div>
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600 whitespace-nowrap">at</label>
<select className="border rounded px-2 py-1 text-sm text-gray-700 bg-white" value={syncHour} onChange={(e) => setSyncHour(Number(e.target.value))}>
{HOUR_OPTIONS.map((o) => (<option key={o.value} value={o.value}>
{o.label}
</option>))}
</select>
</div>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-gray-600">Source PC URL</label>
<Input placeholder="http://192.168.0.94" value={sourceUrl} onChange={(e) => setSourceUrl(e.target.value)}/>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-gray-600">Source PC API Key</label>
<div className="flex items-center gap-2">
<Input type={showReceiverKey ? "text" : "password"} placeholder="Paste the key from the source PC" value={receiverApiKey} onChange={(e) => setReceiverApiKey(e.target.value)}/>
<Button variant="outline" size="icon" title={showReceiverKey ? "Hide key" : "Show key"} onClick={() => setShowReceiverKey((v) => !v)} type="button">
{showReceiverKey ? <EyeOff className="h-4 w-4"/> : <Eye className="h-4 w-4"/>}
</Button>
</div>
</div>
<div className="flex gap-2">
<Button onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}>
{saveMutation.isPending ? "Saving..." : "Save Settings"}
</Button>
<Button variant="outline" onClick={() => syncNowMutation.mutate()} disabled={syncNowMutation.isPending || !sourceUrl || !receiverApiKey} title="Pull and restore now — replaces this machine's database and uploads folder">
<RotateCcw className="h-4 w-4 mr-1"/>
{syncNowMutation.isPending ? "Syncing..." : "Sync Now"}
</Button>
</div>
<ApiKeySyncStatus />
</div>
{/* Confirm regenerate dialog */}
<AlertDialog open={confirmRegenOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Regenerate backup key?</AlertDialogTitle>
<AlertDialogDescription>
The old key will stop working immediately. You will need to update the API key
on any backup PC that is currently configured to sync from this machine.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => setConfirmRegenOpen(false)}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => regenMutation.mutate()} disabled={regenMutation.isPending}>
Regenerate
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>);
}
function ApiKeySyncStatus() {
const { data } = useQuery({
queryKey: ["/db/network-sync-config"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/database-management/network-sync-config");
return res.json();
},
});
if (!data?.lastSyncAt)
return null;
const date = new Date(data.lastSyncAt).toLocaleString();
const ok = data.lastSyncStatus === "success";
return (<div className={`text-xs rounded p-2 ${ok ? "bg-green-50 text-green-700" : "bg-red-50 text-red-700"}`}>
{ok ? "Last sync: " : "Last sync failed: "}{date}
{!ok && data.lastSyncError && (<span className="block mt-0.5 text-red-500">{data.lastSyncError}</span>)}
</div>);
}