db backup and restore implemented

This commit is contained in:
dimitar committed 2025-12-12 02:08:03 +01:00
1 parent 8353a24f6b
commit 19ec020046
18 files changed
+847 -118

No files matched your search

@@ -0,0 +1,47 @@
import { auth } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
import { getDatabase, DatabaseFactory } from '@/lib/database'
import { ensureUserSynced } from '@/lib/sync-user'
import fs from 'fs'
import path from 'path'
const BACKUP_DIR = path.join(process.cwd(), 'backups')
const DB_PATH = path.join(process.cwd(), 'data', 'fitai.db')
export async function POST(req: Request) {
try {
const { userId } = await auth()
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
const db = await getDatabase()
const user = await ensureUserSynced(userId, db)
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
return new NextResponse('Forbidden', { status: 403 })
}
const { filename } = await req.json()
if (!filename) {
return new NextResponse('Filename is required', { status: 400 })
}
const backupPath = path.join(BACKUP_DIR, filename)
if (!fs.existsSync(backupPath)) {
return new NextResponse('Backup file not found', { status: 404 })
}
// Close existing connection
await DatabaseFactory.disconnect()
// Restore file
fs.copyFileSync(backupPath, DB_PATH)
// Re-initialize connection (will happen automatically on next getDatabase call, but good to verify)
await getDatabase()
return NextResponse.json({ success: true })
} catch (error) {
console.error('Restore backup error:', error)
return new NextResponse('Internal Server Error', { status: 500 })
}
}
@@ -0,0 +1,78 @@
import { auth } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
import { getDatabase } from '@/lib/database'
import { ensureUserSynced } from '@/lib/sync-user'
import fs from 'fs'
import path from 'path'
const BACKUP_DIR = path.join(process.cwd(), 'backups')
const DB_PATH = path.join(process.cwd(), 'data', 'fitai.db')
export async function GET() {
try {
const { userId } = await auth()
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
const db = await getDatabase()
const user = await ensureUserSynced(userId, db)
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
return new NextResponse('Forbidden', { status: 403 })
}
if (!fs.existsSync(BACKUP_DIR)) {
fs.mkdirSync(BACKUP_DIR, { recursive: true })
}
const files = fs.readdirSync(BACKUP_DIR)
.filter(file => file.endsWith('.db'))
.map(file => {
const stats = fs.statSync(path.join(BACKUP_DIR, file))
return {
name: file,
size: stats.size,
createdAt: stats.birthtime
}
})
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
return NextResponse.json(files)
} catch (error) {
console.error('List backups error:', error)
return new NextResponse('Internal Server Error', { status: 500 })
}
}
export async function POST() {
try {
const { userId } = await auth()
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
const db = await getDatabase()
const user = await ensureUserSynced(userId, db)
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
return new NextResponse('Forbidden', { status: 403 })
}
if (!fs.existsSync(BACKUP_DIR)) {
fs.mkdirSync(BACKUP_DIR, { recursive: true })
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const backupPath = path.join(BACKUP_DIR, `backup-${timestamp}.db`)
// Ensure source DB exists
if (!fs.existsSync(DB_PATH)) {
return new NextResponse('Database file not found', { status: 404 })
}
// Copy file
fs.copyFileSync(DB_PATH, backupPath)
return NextResponse.json({ success: true, filename: `backup-${timestamp}.db` })
} catch (error) {
console.error('Create backup error:', error)
return new NextResponse('Internal Server Error', { status: 500 })
}
}
@@ -5,7 +5,7 @@ import { getDatabase } from '@/lib/database';
// POST - Mark goal as complete
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { userId } = await auth();
@@ -5,7 +5,7 @@ import { getDatabase } from '@/lib/database';
// GET - Get specific goal
export async function GET(
req: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { userId } = await auth();
@@ -40,7 +40,7 @@ export async function GET(
// PUT - Update goal
export async function PUT(
req: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { userId } = await auth();
@@ -82,7 +82,7 @@ export async function PUT(
// DELETE - Delete goal
export async function DELETE(
req: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { userId } = await auth();
+1 -1
View File
@@ -2,7 +2,7 @@
import { useEffect, useState } from "react";
import { useUser } from "@clerk/nextjs";
import { Button } from "@/components/ui/Button";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
interface UserProfile {
+175
View File
@@ -0,0 +1,175 @@
"use client";
import { useEffect, useState } from "react";
import axios from "axios";
import { Database, Download, RefreshCw, AlertTriangle, Check, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
interface Backup {
name: string;
size: number;
createdAt: string;
}
export default function SettingsPage() {
const [backups, setBackups] = useState<Backup[]>([]);
const [loading, setLoading] = useState(true);
const [creatingBackup, setCreatingBackup] = useState(false);
const [restoring, setRestoring] = useState<string | null>(null);
const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
const fetchBackups = async () => {
try {
const response = await axios.get("/api/admin/backups");
setBackups(response.data);
} catch (error) {
console.error("Failed to fetch backups:", error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchBackups();
}, []);
const handleCreateBackup = async () => {
setCreatingBackup(true);
setMessage(null);
try {
await axios.post("/api/admin/backups");
await fetchBackups();
setMessage({ type: 'success', text: 'Backup created successfully' });
} catch (error) {
console.error("Failed to create backup:", error);
setMessage({ type: 'error', text: 'Failed to create backup' });
} finally {
setCreatingBackup(false);
}
};
const handleRestore = async (filename: string) => {
if (!window.confirm(`Are you sure you want to restore from ${filename}? This will overwrite the current database.`)) {
return;
}
setRestoring(filename);
setMessage(null);
try {
await axios.post("/api/admin/backups/restore", { filename });
setMessage({ type: 'success', text: 'Database restored successfully' });
// Optional: Refresh page or force re-login if session is invalidated
} catch (error) {
console.error("Failed to restore backup:", error);
setMessage({ type: 'error', text: 'Failed to restore backup' });
} finally {
setRestoring(null);
}
};
const formatSize = (bytes: number) => {
const units = ['B', 'KB', 'MB', 'GB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(2)} ${units[unitIndex]}`;
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString();
};
return (
<div className="space-y-8 p-8">
<div>
<h2 className="text-3xl font-bold text-slate-900">Settings</h2>
<p className="text-slate-500 mt-2">Manage your application settings and database.</p>
</div>
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-3">
<div className="p-2 bg-blue-50 rounded-lg">
<Database className="w-6 h-6 text-blue-600" />
</div>
<div>
<h3 className="text-xl font-bold text-slate-900">Database Management</h3>
<p className="text-sm text-slate-500">Create backups and restore your database</p>
</div>
</div>
<Button
onClick={handleCreateBackup}
disabled={creatingBackup}
className="flex items-center gap-2"
>
{creatingBackup ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
Create Backup
</Button>
</div>
{message && (
<div className={`p-4 rounded-lg mb-6 flex items-center gap-2 ${message.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
}`}>
{message.type === 'success' ? <Check className="w-5 h-5" /> : <AlertTriangle className="w-5 h-5" />}
{message.text}
</div>
)}
<div className="border rounded-lg overflow-hidden">
<table className="w-full text-left text-sm">
<thead className="bg-slate-50 border-b">
<tr>
<th className="px-6 py-4 font-semibold text-slate-900">Filename</th>
<th className="px-6 py-4 font-semibold text-slate-900">Size</th>
<th className="px-6 py-4 font-semibold text-slate-900">Created At</th>
<th className="px-6 py-4 font-semibold text-slate-900 text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y">
{loading ? (
<tr>
<td colSpan={4} className="px-6 py-8 text-center text-slate-500">
Loading backups...
</td>
</tr>
) : backups.length === 0 ? (
<tr>
<td colSpan={4} className="px-6 py-8 text-center text-slate-500">
No backups found
</td>
</tr>
) : (
backups.map((backup) => (
<tr key={backup.name} className="hover:bg-slate-50 transition-colors">
<td className="px-6 py-4 font-medium text-slate-900">{backup.name}</td>
<td className="px-6 py-4 text-slate-600">{formatSize(backup.size)}</td>
<td className="px-6 py-4 text-slate-600">{formatDate(backup.createdAt)}</td>
<td className="px-6 py-4 text-right">
<Button
variant="ghost"
size="sm"
onClick={() => handleRestore(backup.name)}
disabled={!!restoring}
className="text-red-600 hover:text-red-700 hover:bg-red-50"
>
{restoring === backup.name ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<RefreshCw className="w-4 h-4 mr-2" />
)}
Restore
</Button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
}
+7 -2
View File
@@ -3,10 +3,10 @@
import { type ReactElement } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Home, Users, BarChart3, User, Brain } from "lucide-react";
import { Home, Users, BarChart3, User, Brain, Settings } from "lucide-react";
import { SignedIn, UserButton } from "@clerk/nextjs";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/Button";
import { Button } from "@/components/ui/button";
interface NavItem {
href: string;
@@ -40,6 +40,11 @@ const navItems: NavItem[] = [
label: "Profile",
icon: User,
},
{
href: "/settings",
label: "Settings",
icon: Settings,
},
];
export function Navigation(): ReactElement {
@@ -132,7 +132,13 @@ export function AnalyticsDashboard() {
<h3 className="text-lg font-semibold">Monthly Revenue</h3>
</CardHeader>
<CardContent>
<RevenueChart data={revenueData} />
<RevenueChart
data={revenueData.map(item => ({
category: item.label,
value: item.value,
color: item.color
}))}
/>
</CardContent>
</Card>
</div>
-23
View File
@@ -1,23 +0,0 @@
import React from 'react'
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary'
children: React.ReactNode
}
export function Button({ variant = 'primary', children, className = '', ...props }: ButtonProps) {
const baseClasses = 'px-4 py-2 rounded-md font-medium transition-colors'
const variantClasses = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300',
}
return (
<button
className={`${baseClasses} ${variantClasses[variant]} ${className}`}
{...props}
>
{children}
</button>
)
}
-30
View File
@@ -1,30 +0,0 @@
import React from 'react'
interface CardProps {
children: React.ReactNode
className?: string
}
export function Card({ children, className = '' }: CardProps) {
return (
<div className={`bg-white rounded-lg shadow-md p-6 ${className}`}>
{children}
</div>
)
}
export function CardHeader({ children, className = '' }: CardProps) {
return (
<div className={`mb-4 ${className}`}>
{children}
</div>
)
}
export function CardContent({ children, className = '' }: CardProps) {
return (
<div className={className}>
{children}
</div>
)
}
+45 -52
View File
@@ -1,56 +1,49 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import React from 'react'
import { cn } from '@/lib/utils'
import { Loader2 } from 'lucide-react'
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'ghost' | 'destructive' | 'outline' | 'default'
size?: 'default' | 'sm' | 'lg' | 'icon'
isLoading?: boolean
children: React.ReactNode
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
},
);
Button.displayName = "Button";
export function Button({
variant = 'primary',
size = 'default',
isLoading = false,
children,
className = '',
disabled,
...props
}: ButtonProps) {
const baseClasses = 'inline-flex items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50'
export { Button, buttonVariants };
const variantClasses = {
primary: 'bg-blue-600 text-white hover:bg-blue-700 shadow hover:bg-blue-700/90',
default: 'bg-blue-600 text-white hover:bg-blue-700 shadow hover:bg-blue-700/90',
secondary: 'bg-slate-100 text-slate-900 hover:bg-slate-200/80',
ghost: 'hover:bg-slate-100 hover:text-slate-900',
destructive: 'bg-red-500 text-white hover:bg-red-600/90',
outline: 'border border-input bg-transparent shadow-sm hover:bg-slate-100 hover:text-slate-900'
}
const sizeClasses = {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-8',
icon: 'h-9 w-9'
}
return (
<button
className={cn(baseClasses, variantClasses[variant], sizeClasses[size], className)}
disabled={disabled || isLoading}
{...props}
>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{children}
</button>
)
}
@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/Button";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent } from "@/components/ui/card";
interface Recommendation {
@@ -2,7 +2,7 @@
import { useState, useEffect } from "react";
import { UserGrid } from "@/components/users/UserGrid";
// import { Button } from "@/components/ui/Button";
// import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";