Initial Release
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Settings } from "lucide-react";
|
||||
import { settingsService, type GeneralSettings } from "@/services/settingsService";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
|
||||
const GeneralSettingsPanel = () => {
|
||||
const { toast } = useToast();
|
||||
const [formData, setFormData] = useState<Partial<GeneralSettings>>({});
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
|
||||
const { data: settings, isLoading, error, refetch } = useQuery({
|
||||
queryKey: ['generalSettings'],
|
||||
queryFn: settingsService.getGeneralSettings,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (settings) {
|
||||
setFormData(settings);
|
||||
}
|
||||
}, [settings]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[name]: value
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!settings?.id || !formData) return;
|
||||
|
||||
try {
|
||||
const result = await settingsService.updateGeneralSettings(settings.id, formData);
|
||||
if (result) {
|
||||
toast({
|
||||
title: "Settings updated",
|
||||
description: "Your settings have been updated successfully.",
|
||||
variant: "default",
|
||||
});
|
||||
refetch();
|
||||
setIsEditing(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating settings:", error);
|
||||
toast({
|
||||
title: "Update failed",
|
||||
description: "There was a problem updating your settings.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="p-4">Loading settings...</div>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <div className="p-4 text-red-500">Error loading settings</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>System Settings</CardTitle>
|
||||
<CardDescription>
|
||||
Configure your system settings and preferences
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="system_name">System Name</Label>
|
||||
<Input
|
||||
id="system_name"
|
||||
name="system_name"
|
||||
value={formData?.system_name || ''}
|
||||
onChange={handleChange}
|
||||
disabled={!isEditing}
|
||||
placeholder="My Monitoring System"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex justify-between">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setIsEditing(false)}>Cancel</Button>
|
||||
<Button onClick={handleSave}>Save Changes</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button onClick={() => setIsEditing(true)}>Edit Settings</Button>
|
||||
)}
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default GeneralSettingsPanel;
|
||||
@@ -0,0 +1,91 @@
|
||||
import React from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Github, FileText, Twitter, MessageCircle, Code2, ServerIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLanguage } from "@/contexts/LanguageContext";
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { useSystemSettings } from "@/hooks/useSystemSettings";
|
||||
export const AboutSystem: React.FC = () => {
|
||||
const {
|
||||
t
|
||||
} = useLanguage();
|
||||
const {
|
||||
theme
|
||||
} = useTheme();
|
||||
const {
|
||||
systemName
|
||||
} = useSystemSettings();
|
||||
return <div className="space-y-6 animate-fade-in">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{t('aboutSystem')}</h1>
|
||||
<p className="text-muted-foreground text-base leading-relaxed mt-2">{t('aboutCheckCle')}</p>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="grid gap-8 md:grid-cols-2">
|
||||
<Card className="overflow-hidden border border-border transition-all duration-300 hover:shadow-md">
|
||||
<CardHeader className="bg-muted/50 pb-4">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<ServerIcon className={`h-5 w-5 ${theme === 'dark' ? 'text-sky-400' : 'text-sky-600'}`} />
|
||||
<span className="font-thin text-xl">{t('systemDescription')}</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6 pt-6">
|
||||
<div className="flex flex-col space-y-4">
|
||||
|
||||
|
||||
<div className="flex flex-col space-y-3 pt-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-muted-foreground">{t('systemVersion')}</span>
|
||||
<span className="text-foreground font-medium">{t('version')} 1.0.0</span>
|
||||
</div>
|
||||
<Separator className="my-1" />
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-muted-foreground">{t('license')}</span>
|
||||
<span className="text-foreground font-medium">{t('mitLicense')}</span>
|
||||
</div>
|
||||
<Separator className="my-1" />
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-muted-foreground">{t('releasedOn')}</span>
|
||||
<span className="text-foreground font-medium">May 10, 2025</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="overflow-hidden border border-border transition-all duration-300 hover:shadow-md">
|
||||
<CardHeader className="bg-muted/50 pb-4">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Code2 className={`h-5 w-5 ${theme === 'dark' ? 'text-emerald-400' : 'text-emerald-600'}`} />
|
||||
<span>{t('links')}</span>
|
||||
</CardTitle>
|
||||
<CardDescription className="font-medium text-base">{systemName || 'CheckCle'} {t('resources').toLowerCase()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 pt-6">
|
||||
<div className="grid grid-cols-1 gap-3">
|
||||
<Button variant="outline" className="flex items-center justify-start gap-3 h-12 hover:bg-muted/50 transition-all duration-200" onClick={() => window.open("https://github.com/operacle/checkcle", "_blank")}>
|
||||
<Github className={`h-5 w-5 ${theme === 'dark' ? 'text-white/80' : 'text-gray-700'}`} />
|
||||
<span>{t('viewOnGithub')}</span>
|
||||
</Button>
|
||||
<Button variant="outline" className="flex items-center justify-start gap-3 h-12 hover:bg-muted/50 transition-all duration-200" onClick={() => window.open("https://docs.checkcle.io", "_blank")}>
|
||||
<FileText className={`h-5 w-5 ${theme === 'dark' ? 'text-white/80' : 'text-gray-700'}`} />
|
||||
<span>{t('viewDocumentation')}</span>
|
||||
</Button>
|
||||
<Button variant="outline" className="flex items-center justify-start gap-3 h-12 hover:bg-muted/50 transition-all duration-200" onClick={() => window.open("https://x.com/tlengoss", "_blank")}>
|
||||
<Twitter className={`h-5 w-5 ${theme === 'dark' ? 'text-white/80' : 'text-gray-700'}`} />
|
||||
<span>{t('followOnX')}</span>
|
||||
</Button>
|
||||
<Button variant="outline" className="flex items-center justify-start gap-3 h-12 hover:bg-muted/50 transition-all duration-200" onClick={() => window.open("#", "_blank")}>
|
||||
<MessageCircle className={`h-5 w-5 ${theme === 'dark' ? 'text-white/80' : 'text-gray-700'}`} />
|
||||
<span>{t('joinDiscord')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>;
|
||||
};
|
||||
export default AboutSystem;
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
export { default as AboutSystem } from './AboutSystem';
|
||||
@@ -0,0 +1,89 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { templateService } from "@/services/templateService";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Plus, RefreshCcw } from "lucide-react";
|
||||
import { TemplateList } from "./TemplateList";
|
||||
import { TemplateDialog } from "./TemplateDialog";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
|
||||
export const AlertsTemplates = () => {
|
||||
const { toast } = useToast();
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [editingTemplate, setEditingTemplate] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
data: templates = [],
|
||||
isLoading,
|
||||
error,
|
||||
refetch
|
||||
} = useQuery({
|
||||
queryKey: ['notification_templates'],
|
||||
queryFn: templateService.getTemplates,
|
||||
});
|
||||
|
||||
const handleAddTemplate = () => {
|
||||
setEditingTemplate(null);
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleEditTemplate = (id: string) => {
|
||||
setEditingTemplate(id);
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleRefresh = () => {
|
||||
refetch();
|
||||
toast({
|
||||
title: "Refreshing",
|
||||
description: "Updating template list...",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle>Alert Templates</CardTitle>
|
||||
<div className="flex space-x-2">
|
||||
<Button variant="outline" onClick={handleRefresh} disabled={isLoading}>
|
||||
<RefreshCcw className="h-4 w-4 mr-2" />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button onClick={handleAddTemplate}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Template
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{error ? (
|
||||
<div className="text-center p-6">
|
||||
<p className="text-destructive mb-4">Error loading templates</p>
|
||||
<Button variant="outline" onClick={() => refetch()}>
|
||||
Try Again
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<TemplateList
|
||||
templates={templates}
|
||||
isLoading={isLoading}
|
||||
onEdit={handleEditTemplate}
|
||||
refetchTemplates={refetch}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<TemplateDialog
|
||||
open={isDialogOpen}
|
||||
templateId={editingTemplate}
|
||||
onOpenChange={setIsDialogOpen}
|
||||
onSuccess={() => {
|
||||
refetch();
|
||||
setIsDialogOpen(false);
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,123 @@
|
||||
|
||||
import React, { useEffect } from "react";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Form } from "@/components/ui/form";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { useTemplateForm } from "./hooks/useTemplateForm";
|
||||
import { BasicTemplateFields } from "./form/BasicTemplateFields";
|
||||
import { MessagesTabContent } from "./form/MessagesTabContent";
|
||||
import { PlaceholdersTabContent } from "./form/PlaceholdersTabContent";
|
||||
import { Loader2, ChevronDown } from "lucide-react";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
|
||||
interface TemplateDialogProps {
|
||||
open: boolean;
|
||||
templateId: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export const TemplateDialog: React.FC<TemplateDialogProps> = ({
|
||||
open,
|
||||
templateId,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
}) => {
|
||||
const {
|
||||
form,
|
||||
isEditMode,
|
||||
isLoadingTemplate,
|
||||
isSubmitting,
|
||||
onSubmit
|
||||
} = useTemplateForm({
|
||||
templateId,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess
|
||||
});
|
||||
|
||||
// For debugging purposes
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
console.log("Template dialog opened. Edit mode:", isEditMode, "Template ID:", templateId);
|
||||
|
||||
// Log form values when they change
|
||||
const subscription = form.watch((value) => {
|
||||
console.log("Current form values:", value);
|
||||
});
|
||||
|
||||
return () => subscription.unsubscribe();
|
||||
}
|
||||
}, [open, isEditMode, templateId, form]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] flex flex-col overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditMode ? "Edit Template" : "Add Template"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoadingTemplate ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<span className="ml-2">Loading template data...</span>
|
||||
</div>
|
||||
) : (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 flex-1 flex flex-col">
|
||||
<div className="relative flex-1">
|
||||
<ScrollArea className="pr-4 overflow-auto" style={{ height: "calc(80vh - 180px)" }}>
|
||||
<div className="space-y-6 pb-6 pr-4">
|
||||
<BasicTemplateFields control={form.control} />
|
||||
|
||||
<Tabs defaultValue="messages">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="messages">Messages</TabsTrigger>
|
||||
<TabsTrigger value="placeholders">Placeholders</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="messages" className="pt-4">
|
||||
<MessagesTabContent control={form.control} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="placeholders" className="pt-4">
|
||||
<PlaceholdersTabContent control={form.control} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="absolute bottom-2 right-4 text-muted-foreground opacity-60">
|
||||
<ChevronDown className="h-4 w-4 animate-bounce" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-2 pt-2 border-t border-border">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || isLoadingTemplate}
|
||||
className="relative"
|
||||
>
|
||||
{isSubmitting && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
{isSubmitting
|
||||
? (isEditMode ? "Updating..." : "Creating...")
|
||||
: (isEditMode ? "Update Template" : "Create Template")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,168 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { NotificationTemplate, templateService } from "@/services/templateService";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Edit, Trash2 } from "lucide-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
interface TemplateListProps {
|
||||
templates: NotificationTemplate[];
|
||||
isLoading: boolean;
|
||||
onEdit: (id: string) => void;
|
||||
refetchTemplates: () => void;
|
||||
}
|
||||
|
||||
export const TemplateList: React.FC<TemplateListProps> = ({
|
||||
templates,
|
||||
isLoading,
|
||||
onEdit,
|
||||
refetchTemplates,
|
||||
}) => {
|
||||
const { toast } = useToast();
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [templateToDelete, setTemplateToDelete] = useState<NotificationTemplate | null>(null);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
|
||||
const handleDeletePrompt = (template: NotificationTemplate) => {
|
||||
setTemplateToDelete(template);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteTemplate = async () => {
|
||||
if (!templateToDelete) return;
|
||||
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
await templateService.deleteTemplate(templateToDelete.id);
|
||||
toast({
|
||||
title: "Template deleted",
|
||||
description: `Template "${templateToDelete.name}" has been removed.`,
|
||||
});
|
||||
refetchTemplates();
|
||||
} catch (error) {
|
||||
console.error("Error deleting template:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to delete template. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
setDeleteDialogOpen(false);
|
||||
setTemplateToDelete(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="py-8 flex justify-center">
|
||||
<div className="animate-pulse flex flex-col items-center">
|
||||
<div className="h-4 bg-gray-200 rounded w-32 mb-4"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-64"></div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (templates.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-muted-foreground mb-2">No templates found</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create your first notification template to get started.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="border rounded-md overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead className="w-24">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{templates.map((template) => (
|
||||
<TableRow key={template.id}>
|
||||
<TableCell className="font-medium">{template.name}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline">{template.type}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{new Date(template.created).toLocaleDateString()}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => onEdit(template.id)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDeletePrompt(template)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Template</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete the template "{templateToDelete?.name}"? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleDeleteTemplate();
|
||||
}}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? "Deleting..." : "Delete"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
|
||||
import React from "react";
|
||||
import { FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Control } from "react-hook-form";
|
||||
|
||||
interface BasicTemplateFieldsProps {
|
||||
control: Control<any>;
|
||||
}
|
||||
|
||||
export const BasicTemplateFields: React.FC<BasicTemplateFieldsProps> = ({ control }) => {
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Template Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Enter template name"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name="type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Template Type</FormLabel>
|
||||
<FormControl>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
value={field.value}
|
||||
defaultValue={field.value}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select template type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="default">Default</SelectItem>
|
||||
<SelectItem value="service">Service</SelectItem>
|
||||
<SelectItem value="incident">Incident</SelectItem>
|
||||
<SelectItem value="maintenance">Maintenance</SelectItem>
|
||||
<SelectItem value="custom">Custom</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,124 @@
|
||||
|
||||
import React from "react";
|
||||
import { FormField, FormItem, FormLabel, FormControl, FormMessage, FormDescription } from "@/components/ui/form";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Control } from "react-hook-form";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
|
||||
interface MessagesTabContentProps {
|
||||
control: Control<any>;
|
||||
}
|
||||
|
||||
export const MessagesTabContent: React.FC<MessagesTabContentProps> = ({ control }) => {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="space-y-4">
|
||||
<FormField
|
||||
control={control}
|
||||
name="up_message"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Up Message</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Service ${service_name} is UP. Response time: ${response_time}ms"
|
||||
className="min-h-24"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Message sent when a service returns to UP status
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="down_message"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Down Message</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Service ${service_name} is DOWN. Status: ${status}"
|
||||
className="min-h-24"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Message sent when a service goes DOWN
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<FormField
|
||||
control={control}
|
||||
name="maintenance_message"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Maintenance Message</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Service ${service_name} is under maintenance"
|
||||
className="min-h-20"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="incident_message"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Incident Message</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Warning: Service ${service_name} has an incident"
|
||||
className="min-h-20"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="resolved_message"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Resolved Message</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Issue with service ${service_name} has been resolved"
|
||||
className="min-h-20"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,132 @@
|
||||
|
||||
import React from "react";
|
||||
import { FormField, FormItem, FormLabel, FormControl, FormMessage, FormDescription } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Control } from "react-hook-form";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
interface PlaceholdersTabContentProps {
|
||||
control: Control<any>;
|
||||
}
|
||||
|
||||
export const PlaceholdersTabContent: React.FC<PlaceholdersTabContentProps> = ({ control }) => {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-medium">Template Placeholders</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={control}
|
||||
name="service_name_placeholder"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Service Name Placeholder</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="${service_name}" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription className="text-xs">
|
||||
Used for service name in messages
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="response_time_placeholder"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Response Time Placeholder</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="${response_time}" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription className="text-xs">
|
||||
Used for response time in milliseconds
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="status_placeholder"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Status Placeholder</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="${status}" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription className="text-xs">
|
||||
Used for service status (UP, DOWN, etc.)
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="threshold_placeholder"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Threshold Placeholder</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="${threshold}" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription className="text-xs">
|
||||
Used for threshold values in alerts
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-medium">Placeholder Usage Guide</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
These placeholders will be replaced with actual values when notifications are sent:
|
||||
</p>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="bg-muted/30 p-2 rounded">
|
||||
<code className="text-xs">${"{service_name}"}</code>
|
||||
<p className="text-xs text-muted-foreground mt-1">The name of the service</p>
|
||||
</div>
|
||||
<div className="bg-muted/30 p-2 rounded">
|
||||
<code className="text-xs">${"{response_time}"}</code>
|
||||
<p className="text-xs text-muted-foreground mt-1">Response time in milliseconds</p>
|
||||
</div>
|
||||
<div className="bg-muted/30 p-2 rounded">
|
||||
<code className="text-xs">${"{status}"}</code>
|
||||
<p className="text-xs text-muted-foreground mt-1">Service status (UP, DOWN)</p>
|
||||
</div>
|
||||
<div className="bg-muted/30 p-2 rounded">
|
||||
<code className="text-xs">${"{threshold}"}</code>
|
||||
<p className="text-xs text-muted-foreground mt-1">Service threshold value</p>
|
||||
</div>
|
||||
<div className="bg-muted/30 p-2 rounded">
|
||||
<code className="text-xs">${"{url}"}</code>
|
||||
<p className="text-xs text-muted-foreground mt-1">Service URL</p>
|
||||
</div>
|
||||
<div className="bg-muted/30 p-2 rounded">
|
||||
<code className="text-xs">${"{time}"}</code>
|
||||
<p className="text-xs text-muted-foreground mt-1">Current date and time</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
|
||||
export * from './BasicTemplateFields';
|
||||
export * from './MessagesTabContent';
|
||||
export * from './PlaceholdersTabContent';
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
export * from './useTemplateForm';
|
||||
@@ -0,0 +1,199 @@
|
||||
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import * as z from "zod";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { templateService, CreateUpdateTemplateData } from "@/services/templateService";
|
||||
import { useEffect } from "react";
|
||||
|
||||
// Template form schema
|
||||
export const templateFormSchema = z.object({
|
||||
name: z.string().min(2, "Name is required and must be at least 2 characters"),
|
||||
type: z.string().min(1, "Type is required"),
|
||||
up_message: z.string().min(1, "Up message is required"),
|
||||
down_message: z.string().min(1, "Down message is required"),
|
||||
maintenance_message: z.string().min(1, "Maintenance message is required"),
|
||||
incident_message: z.string().min(1, "Incident message is required"),
|
||||
resolved_message: z.string().min(1, "Resolved message is required"),
|
||||
service_name_placeholder: z.string().min(1, "Service name placeholder is required"),
|
||||
response_time_placeholder: z.string().min(1, "Response time placeholder is required"),
|
||||
status_placeholder: z.string().min(1, "Status placeholder is required"),
|
||||
threshold_placeholder: z.string().min(1, "Threshold placeholder is required"),
|
||||
});
|
||||
|
||||
// Define the form data type from the schema
|
||||
export type TemplateFormData = z.infer<typeof templateFormSchema>;
|
||||
|
||||
// Default form values
|
||||
const defaultFormValues: TemplateFormData = {
|
||||
name: "",
|
||||
type: "default",
|
||||
up_message: "Service ${service_name} is UP. Response time: ${response_time}ms",
|
||||
down_message: "Service ${service_name} is DOWN. Status: ${status}",
|
||||
maintenance_message: "Service ${service_name} is under maintenance",
|
||||
incident_message: "Service ${service_name} has an incident",
|
||||
resolved_message: "Service ${service_name} issue has been resolved",
|
||||
service_name_placeholder: "${service_name}",
|
||||
response_time_placeholder: "${response_time}",
|
||||
status_placeholder: "${status}",
|
||||
threshold_placeholder: "${threshold}",
|
||||
};
|
||||
|
||||
export interface UseTemplateFormProps {
|
||||
templateId: string | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export const useTemplateForm = ({ templateId, open, onOpenChange, onSuccess }: UseTemplateFormProps) => {
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
const isEditMode = !!templateId;
|
||||
|
||||
console.log("Template form initialized with templateId:", templateId, "isEditMode:", isEditMode);
|
||||
|
||||
const form = useForm<TemplateFormData>({
|
||||
resolver: zodResolver(templateFormSchema),
|
||||
defaultValues: defaultFormValues,
|
||||
mode: "onChange"
|
||||
});
|
||||
|
||||
// Query to fetch template data for editing
|
||||
const { isLoading: isLoadingTemplate, data: templateData } = useQuery({
|
||||
queryKey: ['template', templateId],
|
||||
queryFn: () => {
|
||||
if (!templateId) return null;
|
||||
console.log("Fetching template data for ID:", templateId);
|
||||
return templateService.getTemplate(templateId);
|
||||
},
|
||||
enabled: !!templateId && open,
|
||||
});
|
||||
|
||||
// Set form values when template data is loaded
|
||||
useEffect(() => {
|
||||
if (templateData && open) {
|
||||
console.log("Setting form values with template data:", templateData);
|
||||
|
||||
form.reset({
|
||||
name: templateData.name || "",
|
||||
type: templateData.type || "default",
|
||||
up_message: templateData.up_message || "",
|
||||
down_message: templateData.down_message || "",
|
||||
maintenance_message: templateData.maintenance_message || "",
|
||||
incident_message: templateData.incident_message || "",
|
||||
resolved_message: templateData.resolved_message || "",
|
||||
service_name_placeholder: templateData.service_name_placeholder || "${service_name}",
|
||||
response_time_placeholder: templateData.response_time_placeholder || "${response_time}",
|
||||
status_placeholder: templateData.status_placeholder || "${status}",
|
||||
threshold_placeholder: templateData.threshold_placeholder || "${threshold}",
|
||||
});
|
||||
}
|
||||
}, [templateData, open, form]);
|
||||
|
||||
// Handle form errors
|
||||
useEffect(() => {
|
||||
const subscription = form.formState.errors.root?.message &&
|
||||
toast({
|
||||
title: "Error",
|
||||
description: form.formState.errors.root.message,
|
||||
variant: "destructive",
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (subscription) {
|
||||
// Clean up if needed
|
||||
}
|
||||
};
|
||||
}, [form.formState.errors.root, toast]);
|
||||
|
||||
// Create mutation
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: CreateUpdateTemplateData) => templateService.createTemplate(data),
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: "Template created",
|
||||
description: "Your notification template has been created successfully.",
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['notification_templates'] });
|
||||
onSuccess();
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error("Error creating template:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to create template. Please check your inputs and try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Update mutation
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, data }: { id: string; data: CreateUpdateTemplateData }) =>
|
||||
templateService.updateTemplate(id, data),
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: "Template updated",
|
||||
description: "Your notification template has been updated successfully.",
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['notification_templates'] });
|
||||
onSuccess();
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error("Error updating template:", error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to update template. Please check your inputs and try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const isSubmitting = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
// Handle form submission
|
||||
const onSubmit = (formData: TemplateFormData) => {
|
||||
console.log("Submitting form data:", formData);
|
||||
|
||||
// Ensure all required fields are present
|
||||
const completeData: CreateUpdateTemplateData = {
|
||||
name: formData.name,
|
||||
type: formData.type,
|
||||
up_message: formData.up_message,
|
||||
down_message: formData.down_message,
|
||||
maintenance_message: formData.maintenance_message,
|
||||
incident_message: formData.incident_message,
|
||||
resolved_message: formData.resolved_message,
|
||||
service_name_placeholder: formData.service_name_placeholder,
|
||||
response_time_placeholder: formData.response_time_placeholder,
|
||||
status_placeholder: formData.status_placeholder,
|
||||
threshold_placeholder: formData.threshold_placeholder,
|
||||
};
|
||||
|
||||
if (isEditMode && templateId) {
|
||||
console.log("Updating template with ID:", templateId);
|
||||
updateMutation.mutate({ id: templateId, data: completeData });
|
||||
} else {
|
||||
console.log("Creating new template");
|
||||
createMutation.mutate(completeData);
|
||||
}
|
||||
};
|
||||
|
||||
// Reset form when dialog closes
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
console.log("Dialog closed, resetting form");
|
||||
form.reset(defaultFormValues);
|
||||
}
|
||||
}, [open, form]);
|
||||
|
||||
return {
|
||||
form,
|
||||
isEditMode,
|
||||
isLoadingTemplate,
|
||||
isSubmitting,
|
||||
onSubmit
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
export { AlertsTemplates } from "./AlertsTemplates";
|
||||
+349
@@ -0,0 +1,349 @@
|
||||
|
||||
import React, { useEffect } from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { AlertConfiguration, alertConfigService } from "@/services/alertConfigService";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface NotificationChannelDialogProps {
|
||||
open: boolean;
|
||||
onClose: (refreshList: boolean) => void;
|
||||
editingConfig: AlertConfiguration | null;
|
||||
}
|
||||
|
||||
const baseSchema = z.object({
|
||||
notify_name: z.string().min(1, "Name is required"),
|
||||
notification_type: z.enum(["telegram", "discord", "slack", "signal", "email"]),
|
||||
enabled: z.boolean().default(true),
|
||||
service_id: z.string().default("global"), // Assuming global for now, could be linked to specific services
|
||||
template_id: z.string().optional(),
|
||||
});
|
||||
|
||||
const telegramSchema = baseSchema.extend({
|
||||
notification_type: z.literal("telegram"),
|
||||
telegram_chat_id: z.string().min(1, "Chat ID is required"),
|
||||
bot_token: z.string().min(1, "Bot token is required"),
|
||||
});
|
||||
|
||||
const discordSchema = baseSchema.extend({
|
||||
notification_type: z.literal("discord"),
|
||||
discord_webhook_url: z.string().url("Must be a valid URL"),
|
||||
});
|
||||
|
||||
const slackSchema = baseSchema.extend({
|
||||
notification_type: z.literal("slack"),
|
||||
slack_webhook_url: z.string().url("Must be a valid URL"),
|
||||
});
|
||||
|
||||
const signalSchema = baseSchema.extend({
|
||||
notification_type: z.literal("signal"),
|
||||
signal_number: z.string().min(1, "Signal number is required"),
|
||||
});
|
||||
|
||||
const emailSchema = baseSchema.extend({
|
||||
notification_type: z.literal("email"),
|
||||
// Email specific fields could be added here
|
||||
});
|
||||
|
||||
const formSchema = z.discriminatedUnion("notification_type", [
|
||||
telegramSchema,
|
||||
discordSchema,
|
||||
slackSchema,
|
||||
signalSchema,
|
||||
emailSchema
|
||||
]);
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export const NotificationChannelDialog = ({
|
||||
open,
|
||||
onClose,
|
||||
editingConfig
|
||||
}: NotificationChannelDialogProps) => {
|
||||
const isEditing = !!editingConfig;
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
notify_name: "",
|
||||
notification_type: "telegram" as const,
|
||||
enabled: true,
|
||||
service_id: "global",
|
||||
template_id: "",
|
||||
},
|
||||
});
|
||||
|
||||
const { watch, reset } = form;
|
||||
const notificationType = watch("notification_type");
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (editingConfig) {
|
||||
// Handle string vs boolean for enabled field
|
||||
const enabled = typeof editingConfig.enabled === 'string'
|
||||
? editingConfig.enabled === "true"
|
||||
: !!editingConfig.enabled;
|
||||
|
||||
reset({
|
||||
...editingConfig,
|
||||
enabled
|
||||
});
|
||||
} else if (open) {
|
||||
reset({
|
||||
notify_name: "",
|
||||
notification_type: "telegram" as const,
|
||||
enabled: true,
|
||||
service_id: "global",
|
||||
template_id: "",
|
||||
});
|
||||
}
|
||||
}, [editingConfig, open, reset]);
|
||||
|
||||
const handleClose = () => {
|
||||
onClose(false);
|
||||
};
|
||||
|
||||
const onSubmit = async (values: FormValues) => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
// Ensure service_id is always present
|
||||
const configData = {
|
||||
...values,
|
||||
service_id: values.service_id || "global",
|
||||
};
|
||||
|
||||
if (isEditing && editingConfig?.id) {
|
||||
await alertConfigService.updateAlertConfiguration(editingConfig.id, configData);
|
||||
} else {
|
||||
await alertConfigService.createAlertConfiguration(configData as any);
|
||||
}
|
||||
onClose(true); // Close with refresh
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={() => handleClose()}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{isEditing ? "Edit Notification Channel" : "Add Notification Channel"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="notify_name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="My Notification Channel" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
A name to identify this notification channel
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="notification_type"
|
||||
render={({ field }) => (
|
||||
<FormItem className="space-y-3">
|
||||
<FormLabel>Channel Type</FormLabel>
|
||||
<FormControl>
|
||||
<RadioGroup
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={field.value}
|
||||
value={field.value}
|
||||
className="flex flex-col space-y-1"
|
||||
>
|
||||
<FormItem className="flex items-center space-x-3 space-y-0">
|
||||
<FormControl>
|
||||
<RadioGroupItem value="telegram" />
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">
|
||||
Telegram
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
<FormItem className="flex items-center space-x-3 space-y-0">
|
||||
<FormControl>
|
||||
<RadioGroupItem value="discord" />
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">
|
||||
Discord
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
<FormItem className="flex items-center space-x-3 space-y-0">
|
||||
<FormControl>
|
||||
<RadioGroupItem value="slack" />
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">
|
||||
Slack
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
<FormItem className="flex items-center space-x-3 space-y-0">
|
||||
<FormControl>
|
||||
<RadioGroupItem value="signal" />
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">
|
||||
Signal
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
<FormItem className="flex items-center space-x-3 space-y-0">
|
||||
<FormControl>
|
||||
<RadioGroupItem value="email" />
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">
|
||||
Email
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Show different fields based on notification type */}
|
||||
{notificationType === "telegram" && (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="telegram_chat_id"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Chat ID</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Telegram Chat ID" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="bot_token"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Bot Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Telegram Bot Token" {...field} type="password" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{notificationType === "discord" && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="discord_webhook_url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Webhook URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Discord Webhook URL" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{notificationType === "slack" && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="slack_webhook_url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Webhook URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Slack Webhook URL" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{notificationType === "signal" && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="signal_number"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Signal Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="+1234567890" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enabled"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel>Enabled</FormLabel>
|
||||
<FormDescription>
|
||||
Turn notifications on or off
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" type="button" onClick={handleClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{isEditing ? "Update" : "Create"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
|
||||
import { AlertConfiguration } from "@/services/alertConfigService";
|
||||
import { Bell, Edit, Trash2 } from "lucide-react";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
} from "@/components/ui/table";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { alertConfigService } from "@/services/alertConfigService";
|
||||
|
||||
interface NotificationChannelListProps {
|
||||
channels: AlertConfiguration[];
|
||||
onEdit: (config: AlertConfiguration) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
export const NotificationChannelList = ({
|
||||
channels,
|
||||
onEdit,
|
||||
onDelete
|
||||
}: NotificationChannelListProps) => {
|
||||
const toggleEnabled = async (config: AlertConfiguration) => {
|
||||
if (!config.id) return;
|
||||
|
||||
await alertConfigService.updateAlertConfiguration(config.id, {
|
||||
enabled: !config.enabled
|
||||
});
|
||||
|
||||
// The parent component will refresh the list
|
||||
onEdit(config);
|
||||
};
|
||||
|
||||
const getChannelTypeLabel = (type: string) => {
|
||||
switch(type) {
|
||||
case "telegram": return "Telegram";
|
||||
case "discord": return "Discord";
|
||||
case "slack": return "Slack";
|
||||
case "signal": return "Signal";
|
||||
case "email": return "Email";
|
||||
default: return type;
|
||||
}
|
||||
};
|
||||
|
||||
if (channels.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-10 text-center">
|
||||
<Bell className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<h3 className="text-lg font-medium">No notification channels configured</h3>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
Add a notification channel to get alerts when your services go down.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{channels.map((channel) => (
|
||||
<TableRow key={channel.id}>
|
||||
<TableCell className="font-medium">{channel.notify_name}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline">{getChannelTypeLabel(channel.notification_type)}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Switch
|
||||
checked={
|
||||
typeof channel.enabled === 'string'
|
||||
? channel.enabled === "true"
|
||||
: !!channel.enabled
|
||||
}
|
||||
onCheckedChange={() => toggleEnabled(channel)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{channel.created ? new Date(channel.created).toLocaleDateString() : "-"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onEdit(channel)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (channel.id && confirm("Are you sure you want to delete this notification channel?")) {
|
||||
onDelete(channel.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Plus, Loader2 } from "lucide-react";
|
||||
import { AlertConfiguration, alertConfigService } from "@/services/alertConfigService";
|
||||
import { NotificationChannelDialog } from "./NotificationChannelDialog";
|
||||
import { NotificationChannelList } from "./NotificationChannelList";
|
||||
|
||||
const NotificationSettings = () => {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [alertConfigs, setAlertConfigs] = useState<AlertConfiguration[]>([]);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [currentTab, setCurrentTab] = useState<string>("all");
|
||||
const [editingConfig, setEditingConfig] = useState<AlertConfiguration | null>(null);
|
||||
|
||||
const fetchAlertConfigurations = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const configs = await alertConfigService.getAlertConfigurations();
|
||||
setAlertConfigs(configs);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchAlertConfigurations();
|
||||
}, []);
|
||||
|
||||
const handleAddNew = () => {
|
||||
setEditingConfig(null);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleEdit = (config: AlertConfiguration) => {
|
||||
setEditingConfig(config);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
const success = await alertConfigService.deleteAlertConfiguration(id);
|
||||
if (success) {
|
||||
fetchAlertConfigurations();
|
||||
}
|
||||
};
|
||||
|
||||
const handleDialogClose = (refreshList: boolean) => {
|
||||
setDialogOpen(false);
|
||||
if (refreshList) {
|
||||
fetchAlertConfigurations();
|
||||
}
|
||||
};
|
||||
|
||||
const getFilteredConfigs = () => {
|
||||
if (currentTab === "all") return alertConfigs;
|
||||
return alertConfigs.filter(config => config.notification_type === currentTab);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Notification Settings</CardTitle>
|
||||
<CardDescription>
|
||||
Configure notification channels for your services
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button onClick={handleAddNew}>
|
||||
<Plus className="mr-2 h-4 w-4" /> Add Channel
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Tabs
|
||||
defaultValue="all"
|
||||
value={currentTab}
|
||||
onValueChange={setCurrentTab}
|
||||
className="w-full"
|
||||
>
|
||||
<TabsList className="mb-4">
|
||||
<TabsTrigger value="all">All Channels</TabsTrigger>
|
||||
<TabsTrigger value="telegram">Telegram</TabsTrigger>
|
||||
<TabsTrigger value="discord">Discord</TabsTrigger>
|
||||
<TabsTrigger value="slack">Slack</TabsTrigger>
|
||||
<TabsTrigger value="signal">Signal</TabsTrigger>
|
||||
<TabsTrigger value="email">Email</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value={currentTab} className="mt-0">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
</div>
|
||||
) : (
|
||||
<NotificationChannelList
|
||||
channels={getFilteredConfigs()}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</CardContent>
|
||||
|
||||
<NotificationChannelDialog
|
||||
open={dialogOpen}
|
||||
onClose={handleDialogClose}
|
||||
editingConfig={editingConfig}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationSettings;
|
||||
@@ -0,0 +1,4 @@
|
||||
|
||||
import NotificationSettings from "./NotificationSettings";
|
||||
|
||||
export { NotificationSettings };
|
||||
@@ -0,0 +1,46 @@
|
||||
|
||||
import React from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { UseFormReturn } from "react-hook-form";
|
||||
import AddUserForm from "./form-fields/AddUserForm";
|
||||
|
||||
interface AddUserDialogProps {
|
||||
isOpen: boolean;
|
||||
setIsOpen: (open: boolean) => void;
|
||||
form: UseFormReturn<any>;
|
||||
onSubmit: (data: any) => void;
|
||||
isSubmitting: boolean;
|
||||
}
|
||||
|
||||
const AddUserDialog = ({ isOpen, setIsOpen, form, onSubmit, isSubmitting }: AddUserDialogProps) => {
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogContent className="sm:max-w-[700px] w-[95vw]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add New User</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new user account
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="h-[60vh]">
|
||||
<div className="p-4">
|
||||
<AddUserForm
|
||||
form={form}
|
||||
onSubmit={onSubmit}
|
||||
isSubmitting={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddUserDialog;
|
||||
@@ -0,0 +1,81 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { User } from "@/services/userService";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface DeleteUserDialogProps {
|
||||
isOpen: boolean;
|
||||
setIsOpen: (open: boolean) => void;
|
||||
user: User | null;
|
||||
onDelete: () => void;
|
||||
isDeleting?: boolean;
|
||||
}
|
||||
|
||||
const DeleteUserDialog = ({
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
user,
|
||||
onDelete,
|
||||
isDeleting = false,
|
||||
}: DeleteUserDialogProps) => {
|
||||
if (!user) return null;
|
||||
|
||||
const handleCancel = () => {
|
||||
if (!isDeleting) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (!isDeleting) {
|
||||
onDelete();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialog open={isOpen} onOpenChange={(newOpen) => {
|
||||
// Only allow closing if not currently deleting
|
||||
if (!isDeleting || !newOpen) {
|
||||
setIsOpen(newOpen);
|
||||
}
|
||||
}}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete user</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete {user.full_name || user.username}? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={handleCancel} disabled={isDeleting}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirm}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Deleting...
|
||||
</>
|
||||
) : (
|
||||
'Delete'
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default DeleteUserDialog;
|
||||
@@ -0,0 +1,124 @@
|
||||
|
||||
import React from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Form } from "@/components/ui/form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { UseFormReturn } from "react-hook-form";
|
||||
import { User } from "@/services/userService";
|
||||
import { Loader2, AlertCircle } from "lucide-react";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import UserTextField from "./form-fields/UserTextField";
|
||||
import UserToggleField from "./form-fields/UserToggleField";
|
||||
import UserProfilePictureField from "./form-fields/UserProfilePictureField";
|
||||
|
||||
interface EditUserDialogProps {
|
||||
isOpen: boolean;
|
||||
setIsOpen: (open: boolean) => void;
|
||||
form: UseFormReturn<any>;
|
||||
user: User | null;
|
||||
onSubmit: (data: any) => void;
|
||||
isSubmitting?: boolean;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
const EditUserDialog = ({
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
form,
|
||||
user,
|
||||
onSubmit,
|
||||
isSubmitting = false,
|
||||
error = null
|
||||
}: EditUserDialogProps) => {
|
||||
if (!user) return null;
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogContent className="sm:max-w-[700px] w-[95vw]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit User</DialogTitle>
|
||||
<DialogDescription>
|
||||
Update user information
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="h-[60vh]">
|
||||
<div className="p-4">
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<UserProfilePictureField control={form.control} />
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="full_name"
|
||||
label="Full Name"
|
||||
placeholder="Enter full name"
|
||||
/>
|
||||
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="email"
|
||||
label="Email"
|
||||
placeholder="Enter email"
|
||||
type="email"
|
||||
/>
|
||||
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="username"
|
||||
label="Username"
|
||||
placeholder="Enter username"
|
||||
/>
|
||||
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="role"
|
||||
label="Role"
|
||||
placeholder="Enter role (e.g. admin, user)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UserToggleField
|
||||
control={form.control}
|
||||
name="isActive"
|
||||
label="Active Status"
|
||||
description="User will be able to access the system"
|
||||
/>
|
||||
|
||||
<DialogFooter className="pt-4">
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Updating...
|
||||
</>
|
||||
) : (
|
||||
"Update User"
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditUserDialog;
|
||||
@@ -0,0 +1,117 @@
|
||||
|
||||
import React from "react";
|
||||
import UserTable from "./UserTable";
|
||||
import AddUserDialog from "./AddUserDialog";
|
||||
import EditUserDialog from "./EditUserDialog";
|
||||
import DeleteUserDialog from "./DeleteUserDialog";
|
||||
import { useUserManagement } from "./hooks";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger
|
||||
} from "@/components/ui/accordion";
|
||||
import { UserCog, Loader2, AlertCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const UserManagement = () => {
|
||||
const {
|
||||
users,
|
||||
loading,
|
||||
error,
|
||||
newUserForm,
|
||||
isAddUserDialogOpen,
|
||||
setIsAddUserDialogOpen,
|
||||
isDialogOpen,
|
||||
setIsDialogOpen,
|
||||
isDeleting,
|
||||
setIsDeleting,
|
||||
isSubmitting,
|
||||
updateError,
|
||||
form,
|
||||
currentUser,
|
||||
userToDelete,
|
||||
handleEditUser,
|
||||
handleDeletePrompt,
|
||||
handleDeleteUser,
|
||||
onSubmit,
|
||||
onAddUser,
|
||||
fetchUsers
|
||||
} = useUserManagement();
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Accordion type="single" collapsible className="w-full" defaultValue="user-management">
|
||||
<AccordionItem value="user-management">
|
||||
<AccordionTrigger className="py-4 px-5 bg-card hover:bg-card/90 hover:no-underline rounded-lg text-lg font-medium flex items-center w-full">
|
||||
<div className="flex items-center">
|
||||
<UserCog className="h-5 w-5 mr-2 text-green-500" />
|
||||
<span>User Management</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="p-4 pt-6 bg-background rounded-b-lg">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className="text-2xl font-bold">User Management</h2>
|
||||
<button
|
||||
onClick={() => setIsAddUserDialogOpen(true)}
|
||||
className="bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md flex items-center"
|
||||
>
|
||||
<span className="mr-1">+</span> Add User
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="p-8 flex flex-col items-center justify-center text-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin mb-2 text-primary" />
|
||||
<p className="text-muted-foreground">Loading users...</p>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-8 flex flex-col items-center justify-center text-center">
|
||||
<AlertCircle className="h-8 w-8 text-destructive mb-2" />
|
||||
<p className="text-destructive font-medium mb-2">Failed to load users</p>
|
||||
<p className="text-muted-foreground mb-4">{error}</p>
|
||||
<Button onClick={fetchUsers} variant="outline">
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<UserTable
|
||||
users={users}
|
||||
onUserUpdate={handleEditUser}
|
||||
onUserDelete={handleDeletePrompt}
|
||||
/>
|
||||
)}
|
||||
|
||||
<AddUserDialog
|
||||
isOpen={isAddUserDialogOpen}
|
||||
setIsOpen={setIsAddUserDialogOpen}
|
||||
form={newUserForm}
|
||||
onSubmit={onAddUser}
|
||||
isSubmitting={isSubmitting}
|
||||
/>
|
||||
|
||||
<EditUserDialog
|
||||
isOpen={isDialogOpen}
|
||||
setIsOpen={setIsDialogOpen}
|
||||
form={form}
|
||||
user={currentUser}
|
||||
onSubmit={onSubmit}
|
||||
isSubmitting={isSubmitting}
|
||||
error={updateError}
|
||||
/>
|
||||
|
||||
<DeleteUserDialog
|
||||
isOpen={isDeleting}
|
||||
setIsOpen={setIsDeleting}
|
||||
user={userToDelete}
|
||||
onDelete={handleDeleteUser}
|
||||
isDeleting={isSubmitting}
|
||||
/>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserManagement;
|
||||
@@ -0,0 +1,112 @@
|
||||
|
||||
import React from "react";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Edit, Trash2 } from "lucide-react";
|
||||
import { User } from "@/services/userService";
|
||||
|
||||
export interface UserTableProps {
|
||||
users: User[];
|
||||
onUserUpdate: (user: User) => void;
|
||||
onUserDelete: (user: User) => void;
|
||||
}
|
||||
|
||||
const UserTable = ({ users, onUserUpdate, onUserDelete }: UserTableProps) => {
|
||||
// Helper function to get the user's initials for the avatar fallback
|
||||
const getUserInitials = (user: User): string => {
|
||||
return (user.full_name || user.username || "").substring(0, 2).toUpperCase();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>Username</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Role</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="text-center py-8">
|
||||
No users found
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
users.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-8 w-8">
|
||||
{user.avatar ? (
|
||||
<AvatarImage
|
||||
src={user.avatar}
|
||||
alt={user.full_name || user.username}
|
||||
/>
|
||||
) : (
|
||||
<AvatarFallback>
|
||||
{getUserInitials(user)}
|
||||
</AvatarFallback>
|
||||
)}
|
||||
</Avatar>
|
||||
<span>{user.full_name || "-"}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>{user.username}</TableCell>
|
||||
<TableCell>{user.email}</TableCell>
|
||||
<TableCell>{user.role || "user"}</TableCell>
|
||||
<TableCell>
|
||||
{user.isActive !== false ? (
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
|
||||
Active
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">
|
||||
Inactive
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right space-x-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={() => onUserUpdate(user)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
<span className="sr-only">Edit</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => onUserDelete(user)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<span className="sr-only">Delete</span>
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserTable;
|
||||
@@ -0,0 +1,13 @@
|
||||
|
||||
export const avatarOptions = [
|
||||
{ url: "https://api.dicebear.com/7.x/bottts/svg?seed=Felix", label: "Avatar 1" },
|
||||
{ url: "https://api.dicebear.com/7.x/bottts/svg?seed=Aneka", label: "Avatar 2" },
|
||||
{ url: "https://api.dicebear.com/7.x/bottts/svg?seed=Milo", label: "Avatar 3" },
|
||||
{ url: "https://api.dicebear.com/7.x/fun-emoji/svg?seed=Cuddles", label: "Avatar 4" },
|
||||
{ url: "https://api.dicebear.com/7.x/fun-emoji/svg?seed=Bella", label: "Avatar 5" },
|
||||
{ url: "https://api.dicebear.com/7.x/fun-emoji/svg?seed=Shadow", label: "Avatar 6" },
|
||||
{ url: "https://api.dicebear.com/7.x/lorelei/svg?seed=Jasper", label: "Avatar 7" },
|
||||
{ url: "https://api.dicebear.com/7.x/lorelei/svg?seed=Willow", label: "Avatar 8" },
|
||||
{ url: "https://api.dicebear.com/7.x/notionists/svg?seed=Mittens", label: "Avatar 9" },
|
||||
{ url: "https://api.dicebear.com/7.x/notionists/svg?seed=Oliver", label: "Avatar 10" },
|
||||
];
|
||||
@@ -0,0 +1,95 @@
|
||||
|
||||
import React from "react";
|
||||
import { Form } from "@/components/ui/form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { UseFormReturn } from "react-hook-form";
|
||||
import UserProfilePictureField from "./UserProfilePictureField";
|
||||
import UserTextField from "./UserTextField";
|
||||
import UserToggleField from "./UserToggleField";
|
||||
import { DialogFooter } from "@/components/ui/dialog";
|
||||
|
||||
interface AddUserFormProps {
|
||||
form: UseFormReturn<any>;
|
||||
onSubmit: (data: any) => void;
|
||||
isSubmitting: boolean;
|
||||
}
|
||||
|
||||
const AddUserForm = ({ form, onSubmit, isSubmitting }: AddUserFormProps) => {
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<UserProfilePictureField control={form.control} />
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="full_name"
|
||||
label="Full Name"
|
||||
placeholder="Enter full name"
|
||||
/>
|
||||
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="email"
|
||||
label="Email"
|
||||
placeholder="Enter email"
|
||||
type="email"
|
||||
/>
|
||||
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="username"
|
||||
label="Username"
|
||||
placeholder="Enter username"
|
||||
/>
|
||||
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="role"
|
||||
label="Role"
|
||||
placeholder="Enter role (e.g. admin, user)"
|
||||
/>
|
||||
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="password"
|
||||
label="Password"
|
||||
placeholder="Enter password"
|
||||
type="password"
|
||||
/>
|
||||
|
||||
<UserTextField
|
||||
control={form.control}
|
||||
name="passwordConfirm"
|
||||
label="Confirm Password"
|
||||
placeholder="Confirm password"
|
||||
type="password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UserToggleField
|
||||
control={form.control}
|
||||
name="isActive"
|
||||
label="Active Status"
|
||||
description="User will be able to access the system"
|
||||
/>
|
||||
|
||||
<DialogFooter className="pt-4">
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
"Create User"
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddUserForm;
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
|
||||
import React from "react";
|
||||
import { FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Control } from "react-hook-form";
|
||||
|
||||
// Custom interface for local profile images
|
||||
interface ProfileImage {
|
||||
url: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
// Define local profile image paths - include all uploaded SVG images
|
||||
const localProfileImages: ProfileImage[] = [
|
||||
{ url: "/upload/profile/profile1.svg", label: "Profile 1" },
|
||||
{ url: "/upload/profile/profile2.svg", label: "Profile 2" },
|
||||
{ url: "/upload/profile/profile3.svg", label: "Profile 3" },
|
||||
{ url: "/upload/profile/profile4.svg", label: "Profile 4" },
|
||||
{ url: "/upload/profile/profile5.svg", label: "Profile 5" },
|
||||
{ url: "/upload/profile/profile6.svg", label: "Profile 6" },
|
||||
{ url: "/upload/profile/profile7.svg", label: "Profile 7" },
|
||||
{ url: "/upload/profile/profile8.svg", label: "Profile 8" }
|
||||
];
|
||||
|
||||
interface UserProfilePictureFieldProps {
|
||||
control: Control<any>;
|
||||
}
|
||||
|
||||
const UserProfilePictureField = ({ control }: UserProfilePictureFieldProps) => {
|
||||
return (
|
||||
<FormField
|
||||
control={control}
|
||||
name="avatar"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Profile Picture</FormLabel>
|
||||
<RadioGroup
|
||||
onValueChange={field.onChange}
|
||||
value={field.value}
|
||||
className="grid grid-cols-3 gap-4"
|
||||
>
|
||||
{localProfileImages.map((avatar) => (
|
||||
<FormItem key={avatar.url} className="flex flex-col items-center justify-center space-y-1">
|
||||
<FormControl>
|
||||
<RadioGroupItem
|
||||
value={avatar.url}
|
||||
id={`new-${avatar.url}`}
|
||||
className="sr-only"
|
||||
/>
|
||||
</FormControl>
|
||||
<label
|
||||
htmlFor={`new-${avatar.url}`}
|
||||
className={`cursor-pointer rounded-md p-1 ${
|
||||
field.value === avatar.url
|
||||
? "ring-2 ring-primary ring-offset-2"
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
<Avatar className="h-16 w-16">
|
||||
<AvatarImage src={avatar.url} alt={avatar.label} />
|
||||
<AvatarFallback>?</AvatarFallback>
|
||||
</Avatar>
|
||||
</label>
|
||||
<div className="text-xs text-center">{avatar.label}</div>
|
||||
</FormItem>
|
||||
))}
|
||||
</RadioGroup>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserProfilePictureField;
|
||||
@@ -0,0 +1,54 @@
|
||||
|
||||
import React from "react";
|
||||
import { FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Control } from "react-hook-form";
|
||||
|
||||
interface UserTextFieldProps {
|
||||
control: Control<any>;
|
||||
name: string;
|
||||
label: string;
|
||||
placeholder: string;
|
||||
type?: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
const UserTextField = ({
|
||||
control,
|
||||
name,
|
||||
label,
|
||||
placeholder,
|
||||
type = "text",
|
||||
required = false
|
||||
}: UserTextFieldProps) => {
|
||||
return (
|
||||
<FormField
|
||||
control={control}
|
||||
name={name}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{label}
|
||||
{required && <span className="text-destructive ml-1">*</span>}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type={type}
|
||||
placeholder={placeholder}
|
||||
{...field}
|
||||
value={field.value || ''}
|
||||
onChange={e => {
|
||||
// Handle the value change properly
|
||||
const value = e.target.value;
|
||||
field.onChange(value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserTextField;
|
||||
@@ -0,0 +1,39 @@
|
||||
|
||||
import React from "react";
|
||||
import { FormField, FormItem, FormLabel, FormControl, FormMessage, FormDescription } from "@/components/ui/form";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Control } from "react-hook-form";
|
||||
|
||||
interface UserToggleFieldProps {
|
||||
control: Control<any>;
|
||||
name: string;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
const UserToggleField = ({ control, name, label, description }: UserToggleFieldProps) => {
|
||||
return (
|
||||
<FormField
|
||||
control={control}
|
||||
name={name}
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel>{label}</FormLabel>
|
||||
<FormDescription>
|
||||
{description}
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserToggleField;
|
||||
@@ -0,0 +1,5 @@
|
||||
|
||||
export { default as UserProfilePictureField } from './UserProfilePictureField';
|
||||
export { default as UserTextField } from './UserTextField';
|
||||
export { default as UserToggleField } from './UserToggleField';
|
||||
export { default as AddUserForm } from './AddUserForm';
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
export * from './useUserManagement';
|
||||
export * from './useUsersList';
|
||||
export * from './useUserForm';
|
||||
export * from './useUserDialogs';
|
||||
export * from './useUserOperations';
|
||||
@@ -0,0 +1,51 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { User } from "@/services/userService";
|
||||
|
||||
export const useUserDialogs = () => {
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [isAddUserDialogOpen, setIsAddUserDialogOpen] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
||||
const [userToDelete, setUserToDelete] = useState<User | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [updateError, setUpdateError] = useState<string | null>(null);
|
||||
|
||||
const handleEditUser = (user: User, form: any) => {
|
||||
setUpdateError(null);
|
||||
setCurrentUser(user);
|
||||
form.reset({
|
||||
full_name: user.full_name || "",
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
isActive: user.isActive !== undefined ? user.isActive : true,
|
||||
role: user.role || "user",
|
||||
avatar: user.avatar || "",
|
||||
});
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeletePrompt = (user: User) => {
|
||||
setUserToDelete(user);
|
||||
setIsDeleting(true);
|
||||
};
|
||||
|
||||
return {
|
||||
isDialogOpen,
|
||||
setIsDialogOpen,
|
||||
isAddUserDialogOpen,
|
||||
setIsAddUserDialogOpen,
|
||||
isDeleting,
|
||||
setIsDeleting,
|
||||
isSubmitting,
|
||||
setIsSubmitting,
|
||||
updateError,
|
||||
setUpdateError,
|
||||
currentUser,
|
||||
setCurrentUser,
|
||||
userToDelete,
|
||||
setUserToDelete,
|
||||
handleEditUser,
|
||||
handleDeletePrompt,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { userFormSchema, newUserFormSchema, UserFormValues, NewUserFormValues } from "../userForms";
|
||||
import { avatarOptions } from "../avatarOptions";
|
||||
|
||||
export const useUserForm = () => {
|
||||
const form = useForm<UserFormValues>({
|
||||
resolver: zodResolver(userFormSchema),
|
||||
defaultValues: {
|
||||
full_name: "",
|
||||
email: "",
|
||||
username: "",
|
||||
isActive: true,
|
||||
role: "user",
|
||||
avatar: "",
|
||||
},
|
||||
});
|
||||
|
||||
const newUserForm = useForm<NewUserFormValues>({
|
||||
resolver: zodResolver(newUserFormSchema),
|
||||
defaultValues: {
|
||||
full_name: "",
|
||||
email: "",
|
||||
username: "",
|
||||
password: "",
|
||||
passwordConfirm: "",
|
||||
isActive: true,
|
||||
role: "user",
|
||||
avatar: avatarOptions[0].url,
|
||||
},
|
||||
});
|
||||
|
||||
return { form, newUserForm };
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
|
||||
import { useUsersList } from "./useUsersList";
|
||||
import { useUserForm } from "./useUserForm";
|
||||
import { useUserDialogs } from "./useUserDialogs";
|
||||
import { useUserOperations } from "./useUserOperations";
|
||||
import { User } from "@/services/userService";
|
||||
import { UserFormValues, NewUserFormValues } from "../userForms";
|
||||
|
||||
export const useUserManagement = () => {
|
||||
const { users, loading, error, fetchUsers } = useUsersList();
|
||||
const { form, newUserForm } = useUserForm();
|
||||
const {
|
||||
isDialogOpen,
|
||||
setIsDialogOpen,
|
||||
isAddUserDialogOpen,
|
||||
setIsAddUserDialogOpen,
|
||||
isDeleting,
|
||||
setIsDeleting,
|
||||
isSubmitting,
|
||||
setIsSubmitting,
|
||||
updateError,
|
||||
setUpdateError,
|
||||
currentUser,
|
||||
setCurrentUser,
|
||||
userToDelete,
|
||||
setUserToDelete,
|
||||
handleEditUser: baseHandleEditUser,
|
||||
handleDeletePrompt,
|
||||
} = useUserDialogs();
|
||||
|
||||
const {
|
||||
handleDeleteUser: baseHandleDeleteUser,
|
||||
onSubmit: baseOnSubmit,
|
||||
onAddUser: baseOnAddUser,
|
||||
} = useUserOperations(
|
||||
fetchUsers,
|
||||
setIsDialogOpen,
|
||||
setIsAddUserDialogOpen,
|
||||
setIsSubmitting,
|
||||
setIsDeleting,
|
||||
setUpdateError,
|
||||
newUserForm.reset
|
||||
);
|
||||
|
||||
// Wrapper functions to provide the needed arguments
|
||||
const handleEditUser = (user: User) => {
|
||||
baseHandleEditUser(user, form);
|
||||
};
|
||||
|
||||
const handleDeleteUser = async () => {
|
||||
await baseHandleDeleteUser(userToDelete);
|
||||
setUserToDelete(null);
|
||||
};
|
||||
|
||||
const onSubmit = (data: UserFormValues) => {
|
||||
baseOnSubmit(data, currentUser);
|
||||
};
|
||||
|
||||
const onAddUser = (data: NewUserFormValues) => {
|
||||
baseOnAddUser(data);
|
||||
};
|
||||
|
||||
return {
|
||||
users,
|
||||
loading,
|
||||
error,
|
||||
isDialogOpen,
|
||||
setIsDialogOpen,
|
||||
isAddUserDialogOpen,
|
||||
setIsAddUserDialogOpen,
|
||||
isDeleting,
|
||||
setIsDeleting,
|
||||
isSubmitting,
|
||||
updateError,
|
||||
form,
|
||||
newUserForm,
|
||||
currentUser,
|
||||
userToDelete,
|
||||
fetchUsers,
|
||||
handleEditUser,
|
||||
handleDeletePrompt,
|
||||
handleDeleteUser,
|
||||
onSubmit,
|
||||
onAddUser,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { userService, User, UpdateUserData, CreateUserData } from "@/services/userService";
|
||||
import { UserFormValues, NewUserFormValues } from "../userForms";
|
||||
import { avatarOptions } from "../avatarOptions";
|
||||
|
||||
export const useUserOperations = (
|
||||
fetchUsers: () => Promise<void>,
|
||||
setIsDialogOpen: (isOpen: boolean) => void,
|
||||
setIsAddUserDialogOpen: (isOpen: boolean) => void,
|
||||
setIsSubmitting: (isSubmitting: boolean) => void,
|
||||
setIsDeleting: (isDeleting: boolean) => void,
|
||||
setUpdateError: (error: string | null) => void,
|
||||
newUserFormReset: (values: any) => void
|
||||
) => {
|
||||
const { toast } = useToast();
|
||||
|
||||
const handleDeleteUser = async (userToDelete: User | null) => {
|
||||
if (!userToDelete) return;
|
||||
|
||||
try {
|
||||
const success = await userService.deleteUser(userToDelete.id);
|
||||
if (success) {
|
||||
toast({
|
||||
title: "User deleted",
|
||||
description: `${userToDelete.full_name || userToDelete.username} has been deleted.`,
|
||||
});
|
||||
fetchUsers();
|
||||
} else {
|
||||
throw new Error("Failed to delete user");
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Could not delete user. Please try again later.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = async (data: UserFormValues, currentUser: User | null) => {
|
||||
if (!currentUser) return;
|
||||
setIsSubmitting(true);
|
||||
setUpdateError(null);
|
||||
|
||||
try {
|
||||
// Create update object with only the fields we want to update
|
||||
const updateData: UpdateUserData = {
|
||||
full_name: data.full_name,
|
||||
email: data.email,
|
||||
username: data.username,
|
||||
role: data.role,
|
||||
isActive: data.isActive,
|
||||
};
|
||||
|
||||
// For avatar, only include if it's different from current one
|
||||
// Note: We're still sending the avatar path, but our updated userService will handle it properly
|
||||
if (data.avatar && data.avatar !== currentUser.avatar) {
|
||||
updateData.avatar = data.avatar;
|
||||
}
|
||||
|
||||
console.log("Submitting user update with data:", updateData);
|
||||
|
||||
await userService.updateUser(currentUser.id, updateData);
|
||||
|
||||
// After successful update, refresh the auth user data if this is the current user
|
||||
// In a real app, you'd check if the updated user is the current logged-in user
|
||||
|
||||
toast({
|
||||
title: "User updated",
|
||||
description: `${data.full_name || data.username}'s profile has been updated.`,
|
||||
});
|
||||
|
||||
setIsDialogOpen(false);
|
||||
await fetchUsers();
|
||||
} catch (error: any) {
|
||||
console.error("Error updating user:", error);
|
||||
let errorMessage = "Failed to update user. Please check your inputs and try again.";
|
||||
|
||||
if (error.data?.message) {
|
||||
errorMessage = error.data.message;
|
||||
} else if (error.message) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
setUpdateError(errorMessage);
|
||||
toast({
|
||||
title: "Error updating user",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onAddUser = async (data: NewUserFormValues) => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const newUserData: CreateUserData = {
|
||||
username: data.username,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
passwordConfirm: data.passwordConfirm,
|
||||
full_name: data.full_name,
|
||||
role: data.role,
|
||||
isActive: data.isActive,
|
||||
avatar: data.avatar,
|
||||
emailVisibility: true,
|
||||
};
|
||||
|
||||
await userService.createUser(newUserData);
|
||||
|
||||
toast({
|
||||
title: "User created",
|
||||
description: `${data.full_name || data.username} has been added successfully.`,
|
||||
});
|
||||
|
||||
setIsAddUserDialogOpen(false);
|
||||
newUserFormReset({
|
||||
full_name: "",
|
||||
email: "",
|
||||
username: "",
|
||||
password: "",
|
||||
passwordConfirm: "",
|
||||
isActive: true,
|
||||
role: "user",
|
||||
avatar: avatarOptions[0].url,
|
||||
});
|
||||
await fetchUsers();
|
||||
} catch (error: any) {
|
||||
let errorMessage = "Could not create user. Please try again later.";
|
||||
|
||||
if (error.data?.message) {
|
||||
errorMessage = error.data.message;
|
||||
} else if (error.message) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Error creating user",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
handleDeleteUser,
|
||||
onSubmit,
|
||||
onAddUser,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { userService, User } from "@/services/userService";
|
||||
|
||||
export const useUsersList = () => {
|
||||
const { toast } = useToast();
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchUsers = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
console.log("Fetching users list");
|
||||
const data = await userService.getUsers();
|
||||
console.log("Received users data:", data);
|
||||
|
||||
if (Array.isArray(data) && data.length >= 0) {
|
||||
setUsers(data);
|
||||
// Clear any previous errors
|
||||
setError(null);
|
||||
} else {
|
||||
console.error("Invalid users data format:", data);
|
||||
setUsers([]);
|
||||
setError("Invalid data format received from server");
|
||||
toast({
|
||||
title: "Warning",
|
||||
description: "No users found or could not load users.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching users:", error);
|
||||
setError(error instanceof Error ? error.message : "Unknown error");
|
||||
toast({
|
||||
title: "Error fetching users",
|
||||
description: "Could not load users. Please try again later.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setUsers([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, []);
|
||||
|
||||
return { users, loading, error, fetchUsers };
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
|
||||
import UserManagement from "./UserManagement";
|
||||
export default UserManagement;
|
||||
@@ -0,0 +1,32 @@
|
||||
|
||||
import * as z from "zod";
|
||||
|
||||
export const userFormSchema = z.object({
|
||||
full_name: z.string().min(2, {
|
||||
message: "Name must be at least 2 characters.",
|
||||
}),
|
||||
email: z.string().email({
|
||||
message: "Please enter a valid email address.",
|
||||
}),
|
||||
username: z.string().min(3, {
|
||||
message: "Username must be at least 3 characters.",
|
||||
}),
|
||||
isActive: z.boolean().optional(),
|
||||
role: z.string().optional(),
|
||||
avatar: z.string().optional(),
|
||||
});
|
||||
|
||||
export const newUserFormSchema = userFormSchema.extend({
|
||||
password: z.string().min(8, {
|
||||
message: "Password must be at least 8 characters.",
|
||||
}),
|
||||
passwordConfirm: z.string().min(8, {
|
||||
message: "Password confirmation must be at least 8 characters.",
|
||||
}),
|
||||
}).refine((data) => data.password === data.passwordConfirm, {
|
||||
message: "Passwords don't match",
|
||||
path: ["passwordConfirm"],
|
||||
});
|
||||
|
||||
export type UserFormValues = z.infer<typeof userFormSchema>;
|
||||
export type NewUserFormValues = z.infer<typeof newUserFormSchema>;
|
||||
Reference in New Issue
Block a user