Add dockre file

This commit is contained in:
Aditya Siregar
2025-08-15 23:03:15 +07:00
commit 486f45bb92
106 changed files with 18736 additions and 0 deletions
@@ -0,0 +1,513 @@
"use client"
import { useState, useEffect } from "react"
import { useParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Plus, Edit, Trash2, ArrowLeft, User, Upload, X } from "lucide-react"
import Link from "next/link"
import Image from "next/image"
import { AuthGuard } from "@/components/auth-guard"
import { useAuth } from "@/hooks/use-auth"
import apiClient from "@/lib/api-client"
import { API_CONFIG } from "@/lib/config"
import { useToast } from "@/hooks/use-toast"
interface VoteEvent {
id: string
title: string
description: string
start_date: string
end_date: string
is_active: boolean
is_voting_open: boolean
}
interface Candidate {
id: string
vote_event_id: string
name: string
image_url: string
description: string
created_at: string
updated_at: string
}
interface CandidateFormData {
name: string
description: string
image_url: string
}
function CandidateManagementContent() {
const { user, logout } = useAuth()
const { toast } = useToast()
const params = useParams()
const eventId = params.eventId as string
const [event, setEvent] = useState<VoteEvent | null>(null)
const [candidates, setCandidates] = useState<Candidate[]>([])
const [loading, setLoading] = useState(true)
const [formData, setFormData] = useState<CandidateFormData>({
name: "",
description: "",
image_url: ""
})
const [editingCandidate, setEditingCandidate] = useState<Candidate | null>(null)
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [uploadingImage, setUploadingImage] = useState(false)
const [imageFile, setImageFile] = useState<File | null>(null)
const [imagePreview, setImagePreview] = useState<string>("")
useEffect(() => {
if (eventId) {
fetchEventDetails()
fetchCandidates()
}
}, [eventId])
const fetchEventDetails = async () => {
try {
const response = await apiClient.get(`${API_CONFIG.ENDPOINTS.VOTE_EVENTS}/${eventId}`)
if (response.data.success) {
setEvent(response.data.data)
}
} catch (error) {
console.error('Error fetching event details:', error)
toast({
title: "Error",
description: "Failed to fetch event details",
variant: "destructive"
})
}
}
const fetchCandidates = async () => {
try {
setLoading(true)
const response = await apiClient.get(`${API_CONFIG.ENDPOINTS.VOTE_EVENTS}/${eventId}/candidates`)
if (response.data.success) {
setCandidates(response.data.data.candidates || [])
}
} catch (error) {
console.error('Error fetching candidates:', error)
toast({
title: "Error",
description: "Failed to fetch candidates",
variant: "destructive"
})
} finally {
setLoading(false)
}
}
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
// Validate file type
const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
if (!validTypes.includes(file.type)) {
toast({
title: "Invalid File Type",
description: "Please select a valid image file (JPEG, PNG, GIF, WebP)",
variant: "destructive"
})
return
}
// Validate file size (max 5MB)
const maxSize = 5 * 1024 * 1024 // 5MB
if (file.size > maxSize) {
toast({
title: "File Too Large",
description: "Please select an image smaller than 5MB",
variant: "destructive"
})
return
}
setImageFile(file)
const reader = new FileReader()
reader.onloadend = () => {
setImagePreview(reader.result as string)
}
reader.readAsDataURL(file)
}
}
const uploadImage = async (file: File): Promise<string> => {
const formData = new FormData()
formData.append('file', file)
formData.append('type', file.type)
try {
const response = await apiClient.post(API_CONFIG.ENDPOINTS.FILES, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
if (response.data.success) {
return response.data.data.url
} else {
throw new Error('Upload failed')
}
} catch (error) {
console.error('Error uploading image:', error)
throw new Error('Failed to upload image')
}
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
try {
let imageUrl = formData.image_url
// Upload new image if selected
if (imageFile) {
setUploadingImage(true)
try {
imageUrl = await uploadImage(imageFile)
} catch (uploadError) {
setUploadingImage(false)
throw uploadError
}
setUploadingImage(false)
}
const payload = {
vote_event_id: eventId,
name: formData.name,
image_url: imageUrl,
description: formData.description
}
if (editingCandidate) {
// Update existing candidate
await apiClient.put(`${API_CONFIG.ENDPOINTS.CANDIDATES}/${editingCandidate.id}`, payload)
toast({
title: "Success",
description: "Candidate updated successfully"
})
} else {
// Create new candidate
await apiClient.post(API_CONFIG.ENDPOINTS.CANDIDATES, payload)
toast({
title: "Success",
description: "Candidate created successfully"
})
}
setIsDialogOpen(false)
resetForm()
fetchCandidates()
} catch (error) {
console.error('Error saving candidate:', error)
toast({
title: "Error",
description: editingCandidate ? "Failed to update candidate" : "Failed to create candidate",
variant: "destructive"
})
} finally {
setSubmitting(false)
}
}
const handleEdit = (candidate: Candidate) => {
setEditingCandidate(candidate)
setFormData({
name: candidate.name,
description: candidate.description,
image_url: candidate.image_url
})
setImagePreview(candidate.image_url)
setIsDialogOpen(true)
}
const handleDelete = async (candidateId: string) => {
try {
await apiClient.delete(`${API_CONFIG.ENDPOINTS.CANDIDATES}/${candidateId}`)
toast({
title: "Success",
description: "Candidate deleted successfully"
})
fetchCandidates()
} catch (error) {
console.error('Error deleting candidate:', error)
toast({
title: "Error",
description: "Failed to delete candidate",
variant: "destructive"
})
}
}
const resetForm = () => {
setFormData({
name: "",
description: "",
image_url: ""
})
setEditingCandidate(null)
setImageFile(null)
setImagePreview("")
setUploadingImage(false)
}
const removeImage = () => {
setImageFile(null)
setImagePreview("")
setFormData({ ...formData, image_url: "" })
}
return (
<div className="min-h-screen bg-gray-50">
<header className="bg-white shadow-sm border-b">
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
<div className="flex items-center gap-4">
<Link href="/admin/events" className="text-gray-600 hover:text-gray-900">
<ArrowLeft className="h-6 w-6" />
</Link>
<img src="/images/meti-logo.png" alt="METI - New & Renewable Energy" className="h-12 w-auto" />
<div>
<h1 className="text-2xl font-bold text-gray-900">Candidate Management</h1>
{event && (
<p className="text-sm text-gray-600">{event.title}</p>
)}
</div>
</div>
<div className="flex items-center gap-4">
<span className="text-sm text-gray-600">Welcome, {user?.username || 'Admin'}</span>
<Button variant="outline" size="sm" onClick={logout}>
Logout
</Button>
</div>
</div>
</header>
<div className="container mx-auto px-4 py-8">
{/* Header with Create Button */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-8">
<div>
<h2 className="text-3xl font-bold text-gray-900">Candidates</h2>
<p className="text-gray-600 mt-1">Manage candidates for this voting event</p>
</div>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<Button
onClick={() => {
resetForm()
setIsDialogOpen(true)
}}
className="bg-blue-600 hover:bg-blue-700"
>
<Plus className="h-4 w-4 mr-2" />
Add Candidate
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{editingCandidate ? 'Edit Candidate' : 'Add New Candidate'}</DialogTitle>
<DialogDescription>
{editingCandidate ? 'Update the candidate details below.' : 'Fill in the details to add a new candidate.'}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="name">Candidate Name</Label>
<Input
id="name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="Enter candidate name"
required
/>
</div>
<div>
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Enter candidate description"
rows={3}
/>
</div>
<div>
<Label>Candidate Photo</Label>
<div className="mt-2">
{imagePreview ? (
<div className="relative w-32 h-32 mx-auto">
<Image
src={imagePreview}
alt="Preview"
fill
className="object-cover rounded-lg border-2 border-gray-200"
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={removeImage}
className="absolute -top-2 -right-2 h-6 w-6 rounded-full p-0 bg-white border-red-200 hover:bg-red-50 hover:border-red-300"
>
<X className="h-3 w-3 text-red-600" />
</Button>
</div>
) : (
<div className="border-2 border-dashed border-gray-300 hover:border-gray-400 rounded-lg p-6 text-center transition-colors">
<Upload className="h-8 w-8 text-gray-400 mx-auto mb-2" />
<p className="text-sm text-gray-600 mb-1">Upload candidate photo</p>
<p className="text-xs text-gray-500 mb-3">JPEG, PNG, GIF, WebP (max 5MB)</p>
<Input
type="file"
accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
onChange={handleImageChange}
className="hidden"
id="image-upload"
/>
<Label htmlFor="image-upload" className="cursor-pointer">
<Button type="button" variant="outline" size="sm" asChild>
<span>Choose File</span>
</Button>
</Label>
</div>
)}
</div>
</div>
<div className="flex gap-2 pt-4">
<Button
type="button"
variant="outline"
onClick={() => setIsDialogOpen(false)}
className="flex-1"
>
Cancel
</Button>
<Button type="submit" disabled={submitting || uploadingImage} className="flex-1">
{uploadingImage ? 'Uploading...' : submitting ? 'Saving...' : editingCandidate ? 'Update' : 'Add'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</div>
{/* Event Info Card */}
{event && (
<Card className="mb-6">
<CardHeader>
<CardTitle className="text-lg">{event.title}</CardTitle>
<CardDescription>{event.description}</CardDescription>
</CardHeader>
</Card>
)}
{/* Candidates List */}
{loading ? (
<div className="text-center py-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-gray-600">Loading candidates...</p>
</div>
) : candidates.length > 0 ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{candidates.map((candidate) => (
<Card key={candidate.id} className="hover:shadow-lg transition-shadow">
<CardHeader className="text-center">
<div className="w-24 h-24 mx-auto mb-4 relative">
{candidate.image_url ? (
<Image
src={candidate.image_url}
alt={candidate.name}
fill
className="object-cover rounded-full"
/>
) : (
<div className="w-full h-full bg-gray-200 rounded-full flex items-center justify-center">
<User className="h-12 w-12 text-gray-400" />
</div>
)}
</div>
<CardTitle className="text-xl">{candidate.name}</CardTitle>
<CardDescription className="text-sm">
{candidate.description || "No description provided"}
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleEdit(candidate)}
className="flex-1"
>
<Edit className="h-4 w-4 mr-2" />
Edit
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="outline"
size="sm"
className="flex-1 text-red-600 hover:text-red-700"
>
<Trash2 className="h-4 w-4 mr-2" />
Delete
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Candidate</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{candidate.name}"? This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => handleDelete(candidate.id)}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
))}
</div>
) : (
<Card>
<CardContent className="text-center py-12">
<User className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium mb-2">No Candidates Found</h3>
<p className="text-gray-600 mb-4">Add candidates to this voting event.</p>
<Button onClick={() => setIsDialogOpen(true)}>
<Plus className="h-4 w-4 mr-2" />
Add Candidate
</Button>
</CardContent>
</Card>
)}
</div>
</div>
)
}
export default function CandidateManagementPage() {
return (
<AuthGuard requiredRole="superadmin">
<CandidateManagementContent />
</AuthGuard>
)
}
+490
View File
@@ -0,0 +1,490 @@
"use client"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Switch } from "@/components/ui/switch"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Plus, Edit, Trash2, Users, Calendar, Clock, Play, StopCircle, Eye, ArrowLeft } from "lucide-react"
import Link from "next/link"
import { AuthGuard } from "@/components/auth-guard"
import { useAuth } from "@/hooks/use-auth"
import apiClient from "@/lib/api-client"
import { API_CONFIG } from "@/lib/config"
import { useToast } from "@/hooks/use-toast"
interface VoteEvent {
id: string
title: string
description: string
start_date: string
end_date: string
is_active: boolean
is_voting_open: boolean
created_at: string
updated_at: string
candidates?: Candidate[]
}
interface Candidate {
id: string
vote_event_id: string
name: string
image_url: string
description: string
created_at: string
updated_at: string
}
interface EventFormData {
title: string
description: string
start_date: string
end_date: string
is_active: boolean
results_open: boolean
}
function EventManagementContent() {
const { user, logout } = useAuth()
const { toast } = useToast()
const [events, setEvents] = useState<VoteEvent[]>([])
const [loading, setLoading] = useState(true)
const [formData, setFormData] = useState<EventFormData>({
title: "",
description: "",
start_date: "",
end_date: "",
is_active: true,
results_open: false
})
const [editingEvent, setEditingEvent] = useState<VoteEvent | null>(null)
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
fetchEvents()
}, [])
const fetchEvents = async () => {
try {
setLoading(true)
const response = await apiClient.get(API_CONFIG.ENDPOINTS.VOTE_EVENTS)
if (response.data.success) {
setEvents(response.data.data.vote_events || [])
}
} catch (error) {
console.error('Error fetching events:', error)
toast({
title: "Error",
description: "Failed to fetch vote events",
variant: "destructive"
})
} finally {
setLoading(false)
}
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
try {
if (editingEvent) {
// Update existing event - includes is_active field
const updatePayload = {
title: formData.title,
description: formData.description,
start_date: new Date(formData.start_date).toISOString(),
end_date: new Date(formData.end_date).toISOString(),
is_active: formData.is_active,
results_open: formData.results_open
}
await apiClient.put(`${API_CONFIG.ENDPOINTS.VOTE_EVENTS}/${editingEvent.id}`, updatePayload)
toast({
title: "Success",
description: "Event updated successfully"
})
} else {
// Create new event - different payload structure (no is_active field)
const createPayload = {
title: formData.title,
description: formData.description,
start_date: new Date(formData.start_date).toISOString(),
end_date: new Date(formData.end_date).toISOString(),
results_open: formData.results_open
}
await apiClient.post(API_CONFIG.ENDPOINTS.VOTE_EVENTS, createPayload)
toast({
title: "Success",
description: "Event created successfully"
})
}
setIsDialogOpen(false)
resetForm()
fetchEvents()
} catch (error) {
console.error('Error saving event:', error)
toast({
title: "Error",
description: editingEvent ? "Failed to update event" : "Failed to create event",
variant: "destructive"
})
} finally {
setSubmitting(false)
}
}
const handleEdit = (event: VoteEvent) => {
setEditingEvent(event)
setFormData({
title: event.title,
description: event.description,
start_date: new Date(event.start_date).toISOString().slice(0, 16),
end_date: new Date(event.end_date).toISOString().slice(0, 16),
is_active: event.is_active,
results_open: false // Default to false since this field might not exist in the current event object
})
setIsDialogOpen(true)
}
const handleDelete = async (eventId: string) => {
try {
await apiClient.delete(`${API_CONFIG.ENDPOINTS.VOTE_EVENTS}/${eventId}`)
toast({
title: "Success",
description: "Event deleted successfully"
})
fetchEvents()
} catch (error) {
console.error('Error deleting event:', error)
toast({
title: "Error",
description: "Failed to delete event",
variant: "destructive"
})
}
}
const resetForm = () => {
setFormData({
title: "",
description: "",
start_date: "",
end_date: "",
is_active: true,
results_open: false
})
setEditingEvent(null)
}
const getEventStatus = (event: VoteEvent) => {
const now = new Date()
const start = new Date(event.start_date)
const end = new Date(event.end_date)
if (now < start) return "upcoming"
if (now >= start && now <= end) return "active"
return "ended"
}
const getStatusBadge = (event: VoteEvent) => {
const status = getEventStatus(event)
if (event.is_voting_open && status === "active") {
return (
<Badge className="bg-gradient-to-r from-green-500 to-emerald-500 text-white border-0">
<Play className="h-3 w-3 mr-1" />
Live Voting
</Badge>
)
}
switch (status) {
case "active":
return (
<Badge className="bg-orange-100 text-orange-800 border-orange-200">
<Clock className="h-3 w-3 mr-1" />
Active
</Badge>
)
case "upcoming":
return (
<Badge className="bg-blue-100 text-blue-800 border-blue-200">
<Calendar className="h-3 w-3 mr-1" />
Upcoming
</Badge>
)
case "ended":
return (
<Badge className="bg-gray-100 text-gray-800 border-gray-200">
<StopCircle className="h-3 w-3 mr-1" />
Ended
</Badge>
)
}
}
return (
<div className="min-h-screen bg-gray-50">
<header className="bg-white shadow-sm border-b">
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
<div className="flex items-center gap-4">
<Link href="/admin" className="text-gray-600 hover:text-gray-900">
<ArrowLeft className="h-6 w-6" />
</Link>
<img src="/images/meti-logo.png" alt="METI - New & Renewable Energy" className="h-12 w-auto" />
<h1 className="text-2xl font-bold text-gray-900">Event Management</h1>
</div>
<div className="flex items-center gap-4">
<span className="text-sm text-gray-600">Welcome, {user?.username || 'Admin'}</span>
<Button variant="outline" size="sm" onClick={logout}>
Logout
</Button>
</div>
</div>
</header>
<div className="container mx-auto px-4 py-8">
{/* Header with Create Button */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-8">
<div>
<h2 className="text-3xl font-bold text-gray-900">Vote Events</h2>
<p className="text-gray-600 mt-1">Manage voting events and candidates</p>
</div>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<Button
onClick={() => {
resetForm()
setIsDialogOpen(true)
}}
className="bg-blue-600 hover:bg-blue-700"
>
<Plus className="h-4 w-4 mr-2" />
Create Event
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{editingEvent ? 'Edit Event' : 'Create New Event'}</DialogTitle>
<DialogDescription>
{editingEvent ? 'Update the event details below.' : 'Fill in the details to create a new voting event.'}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="title">Event Title</Label>
<Input
id="title"
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
placeholder="Enter event title"
required
/>
</div>
<div>
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Enter event description"
rows={3}
required
/>
</div>
<div>
<Label htmlFor="start_date">Start Date & Time</Label>
<Input
id="start_date"
type="datetime-local"
value={formData.start_date}
onChange={(e) => setFormData({ ...formData, start_date: e.target.value })}
required
/>
</div>
<div>
<Label htmlFor="end_date">End Date & Time</Label>
<Input
id="end_date"
type="datetime-local"
value={formData.end_date}
onChange={(e) => setFormData({ ...formData, end_date: e.target.value })}
required
/>
</div>
{/* Event Settings */}
<div className="space-y-4 pt-2">
{/* Only show Active Event toggle when editing */}
{editingEvent && (
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="is_active">Active Event</Label>
<p className="text-sm text-gray-500">Event is active and visible to users</p>
</div>
<Switch
id="is_active"
checked={formData.is_active}
onCheckedChange={(checked) => setFormData({ ...formData, is_active: checked })}
/>
</div>
)}
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="results_open">Results Open</Label>
<p className="text-sm text-gray-500">Allow viewing of voting results</p>
</div>
<Switch
id="results_open"
checked={formData.results_open}
onCheckedChange={(checked) => setFormData({ ...formData, results_open: checked })}
/>
</div>
</div>
<div className="flex gap-2 pt-4">
<Button
type="button"
variant="outline"
onClick={() => setIsDialogOpen(false)}
className="flex-1"
>
Cancel
</Button>
<Button type="submit" disabled={submitting} className="flex-1">
{submitting ? 'Saving...' : editingEvent ? 'Update' : 'Create'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</div>
{/* Events List */}
{loading ? (
<div className="text-center py-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-gray-600">Loading events...</p>
</div>
) : events.length > 0 ? (
<div className="grid gap-6">
{events.map((event) => (
<Card key={event.id} className="hover:shadow-lg transition-shadow">
<CardHeader>
<div className="flex flex-col sm:flex-row justify-between items-start gap-4">
<div className="flex-1">
<div className="flex items-start gap-3 mb-2">
<CardTitle className="text-xl">{event.title}</CardTitle>
{getStatusBadge(event)}
</div>
<CardDescription className="text-base">
{event.description}
</CardDescription>
</div>
<div className="flex gap-2">
<Link href={`/admin/events/${event.id}/candidates`}>
<Button variant="outline" size="sm">
<Users className="h-4 w-4 mr-2" />
Candidates
</Button>
</Link>
<Button variant="outline" size="sm" onClick={() => handleEdit(event)}>
<Edit className="h-4 w-4 mr-2" />
Edit
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700">
<Trash2 className="h-4 w-4 mr-2" />
Delete
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Event</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{event.title}"? This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => handleDelete(event.id)}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
</CardHeader>
<CardContent>
<div className="grid sm:grid-cols-2 gap-4 text-sm">
<div className="flex items-center gap-2">
<Calendar className="h-4 w-4 text-blue-600" />
<span className="text-gray-600">Start:</span>
<span className="font-medium">
{new Date(event.start_date).toLocaleDateString('id-ID', {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</span>
</div>
<div className="flex items-center gap-2">
<Calendar className="h-4 w-4 text-red-600" />
<span className="text-gray-600">End:</span>
<span className="font-medium">
{new Date(event.end_date).toLocaleDateString('id-ID', {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</span>
</div>
</div>
</CardContent>
</Card>
))}
</div>
) : (
<Card>
<CardContent className="text-center py-12">
<Calendar className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium mb-2">No Events Found</h3>
<p className="text-gray-600 mb-4">Create your first voting event to get started.</p>
<Button onClick={() => setIsDialogOpen(true)}>
<Plus className="h-4 w-4 mr-2" />
Create Event
</Button>
</CardContent>
</Card>
)}
</div>
</div>
)
}
export default function EventManagementPage() {
return (
<AuthGuard requiredRole="superadmin">
<EventManagementContent />
</AuthGuard>
)
}
+3
View File
@@ -0,0 +1,3 @@
export default function Loading() {
return null
}
+910
View File
@@ -0,0 +1,910 @@
"use client"
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import {
Users,
UserCheck,
Clock,
Search,
Filter,
ArrowLeft,
CheckCircle,
XCircle,
AlertCircle,
Plus,
Loader2,
Upload,
} from "lucide-react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import Link from "next/link"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { AuthGuard } from "@/components/auth-guard"
import { useAuth } from "@/hooks/use-auth"
import { useToast } from "@/hooks/use-toast"
import apiClient from "@/lib/api-client"
import * as XLSX from "xlsx"
import { Checkbox } from "@/components/ui/checkbox"
interface User {
id: string
name: string
email: string
is_active: boolean
created_at: string
updated_at: string
roles: Array<{
id: string
name: string
code: string
}>
department_response?: {
name: string
} | null
}
interface ApiResponse {
success: boolean
data: {
users: User[]
pagination: {
total_count: number
page: number
limit: number
total_pages: number
}
}
errors: any
}
interface BulkUserRequest {
name: string
email: string
password: string
role: string
}
interface BulkCreateUsersRequest {
users: BulkUserRequest[]
}
interface BulkCreateAsyncResponse {
job_id: string
message: string
status: string
}
interface BulkJobResult {
job_id: string
status: string
message: string
started_at: string
finished_at?: string
summary: {
total: number
succeeded: number
failed: number
}
created: Array<{
id: string
name: string
email: string
is_active: boolean
created_at: string
updated_at: string
roles: Array<{
id: string
name: string
code: string
}>
department_response: Array<{
name: string
}>
}>
failed: Array<{
user: BulkUserRequest
error: string
}>
}
interface ExcelUser {
Nama: string
Password: string
Email: string
Role: string
}
function MembersPageContent() {
const { user } = useAuth("admin")
const { toast } = useToast()
const router = useRouter()
const [users, setUsers] = useState<User[]>([])
const [loading, setLoading] = useState(false)
const [searchTerm, setSearchTerm] = useState("")
const [statusFilter, setStatusFilter] = useState("all")
// Bulk upload states
const [showBulkUpload, setShowBulkUpload] = useState(false)
const [bulkUsers, setBulkUsers] = useState<BulkUserRequest[]>([])
const [selectedUsers, setSelectedUsers] = useState<Set<number>>(new Set())
const [bulkLoading, setBulkLoading] = useState(false)
const [selectAll, setSelectAll] = useState(false)
// Job tracking states
const [currentJobId, setCurrentJobId] = useState<string | null>(null)
const [jobStatus, setJobStatus] = useState<BulkJobResult | null>(null)
const [jobLoading, setJobLoading] = useState(false)
const [showJobStatus, setShowJobStatus] = useState(false)
useEffect(() => {
if (user) {
fetchUsers()
loadStoredJob()
}
}, [user])
const fetchUsers = async () => {
try {
setLoading(true)
const response = await apiClient.get('/api/v1/users')
const data: ApiResponse = response.data
if (data.success) {
setUsers(data.data.users)
toast({
title: "Success",
description: `Fetched ${data.data.users.length} users`,
})
} else {
toast({
title: "Error",
description: "Failed to fetch users",
variant: "destructive"
})
}
} catch (error: any) {
console.error('Error fetching users:', error)
toast({
title: "Error",
description: error.response?.data?.errors || "Failed to fetch users from API",
variant: "destructive"
})
} finally {
setLoading(false)
}
}
const getStatusBadge = (isActive: boolean) => {
if (isActive) {
return (
<Badge className="bg-green-100 text-green-800 border-green-200">
<CheckCircle className="h-3 w-3 mr-1" />
Active
</Badge>
)
} else {
return (
<Badge className="bg-red-100 text-red-800 border-red-200">
<XCircle className="h-3 w-3 mr-1" />
Inactive
</Badge>
)
}
}
const getRoleBadge = (roles: User['roles']) => {
if (roles && roles.length > 0) {
return (
<Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
{roles[0].name}
</Badge>
)
}
return (
<Badge variant="outline" className="bg-gray-50 text-gray-700 border-gray-200">
No Role
</Badge>
)
}
const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
try {
const data = new Uint8Array(e.target?.result as ArrayBuffer)
const workbook = XLSX.read(data, { type: 'array' })
const sheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[sheetName]
const jsonData = XLSX.utils.sheet_to_json(worksheet) as ExcelUser[]
// Transform Excel data to API format
const transformedUsers: BulkUserRequest[] = jsonData.map((row, index) => ({
name: row.Nama?.trim() || '',
email: row.Email?.trim() || '',
password: row.Password?.trim() || '',
role: row.Role?.trim() || 'Staff'
})).filter(user => user.name && user.email && user.password)
setBulkUsers(transformedUsers)
setSelectedUsers(new Set())
setSelectAll(false)
setShowBulkUpload(true)
toast({
title: "File Uploaded",
description: `Processed ${transformedUsers.length} users from Excel file`,
})
} catch (error) {
console.error('Error processing Excel file:', error)
toast({
title: "Error",
description: "Failed to process Excel file. Please check the format.",
variant: "destructive"
})
}
}
reader.readAsArrayBuffer(file)
}
const handleSelectUser = (index: number) => {
const newSelected = new Set(selectedUsers)
if (newSelected.has(index)) {
newSelected.delete(index)
} else {
newSelected.add(index)
}
setSelectedUsers(newSelected)
}
const handleSelectAll = () => {
if (selectAll) {
setSelectedUsers(new Set())
setSelectAll(false)
} else {
setSelectedUsers(new Set(bulkUsers.map((_, index) => index)))
setSelectAll(true)
}
}
const handleBulkCreate = async () => {
if (selectedUsers.size === 0) {
toast({
title: "No Users Selected",
description: "Please select at least one user to create",
variant: "destructive"
})
return
}
const selectedUserData = Array.from(selectedUsers).map(index => bulkUsers[index])
try {
setBulkLoading(true)
const response = await apiClient.post('/api/v1/users/bulk', {
users: selectedUserData
})
if (response.data.success) {
const jobData: BulkCreateAsyncResponse = response.data.data
// Store job ID in localStorage
localStorage.setItem("bulk_job_id", jobData.job_id)
setCurrentJobId(jobData.job_id)
toast({
title: "Bulk Upload Started",
description: `Job ${jobData.job_id} created. You can track progress below.`,
})
// Show job status dialog
setShowJobStatus(true)
setShowBulkUpload(false)
// Start polling for job status
setTimeout(() => {
checkJobStatus(jobData.job_id)
}, 2000)
} else {
toast({
title: "Error",
description: response.data.errors || "Failed to create users",
variant: "destructive"
})
}
} catch (error: any) {
console.error('Error creating bulk users:', error)
toast({
title: "Error",
description: error.response?.data?.errors || "Failed to create users",
variant: "destructive"
})
} finally {
setBulkLoading(false)
}
}
const checkJobStatus = async (jobId: string) => {
try {
setJobLoading(true)
const response = await apiClient.get(`/api/v1/users/bulk/job/${jobId}`)
if (response.data.success) {
const jobResult: BulkJobResult = response.data.data
setJobStatus(jobResult)
// If job is completed, refresh users list
if (jobResult.status === 'completed' || jobResult.status === 'failed') {
await fetchUsers()
// Show completion message
if (jobResult.status === 'completed') {
toast({
title: "Bulk Upload Completed",
description: `Successfully created ${jobResult.summary.succeeded} users. ${jobResult.summary.failed} failed.`,
})
} else {
toast({
title: "Bulk Upload Failed",
description: `Failed to create users: ${jobResult.message}`,
variant: "destructive"
})
}
} else {
// Continue polling if job is still running
setTimeout(() => {
checkJobStatus(jobId)
}, 5000)
}
}
} catch (error: any) {
console.error('Error checking job status:', error)
toast({
title: "Error",
description: "Failed to check job status",
variant: "destructive"
})
} finally {
setJobLoading(false)
}
}
const loadStoredJob = () => {
const storedJobId = localStorage.getItem("bulk_job_id")
if (storedJobId) {
setCurrentJobId(storedJobId)
setShowJobStatus(true)
checkJobStatus(storedJobId)
}
}
const filteredUsers = users.filter((user) => {
const matchesSearch =
user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
(user.department_response?.name || "").toLowerCase().includes(searchTerm.toLowerCase())
const matchesStatus = statusFilter === "all" ||
(statusFilter === "active" && user.is_active) ||
(statusFilter === "inactive" && !user.is_active)
return matchesSearch && matchesStatus
})
if (!user) return null
return (
<div className="min-h-screen bg-gray-50">
{/* Header */}
<header className="bg-white shadow-sm border-b">
<div className="container mx-auto px-4 py-4">
<div className="flex items-center gap-4">
<Link href="/admin">
<Button variant="ghost" size="sm" className="gap-2">
<ArrowLeft className="h-4 w-4" />
Back to Admin
</Button>
</Link>
<div className="h-6 w-px bg-gray-300"></div>
<h1 className="text-xl font-semibold text-gray-900">User Management</h1>
</div>
</div>
</header>
<div className="container mx-auto px-4 py-8">
{/* Statistics */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Users</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{users.length}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Active Users</CardTitle>
<UserCheck className="h-4 w-4 text-green-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">
{users.filter(u => u.is_active).length}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Inactive Users</CardTitle>
<Clock className="h-4 w-4 text-yellow-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-yellow-600">
{users.filter(u => !u.is_active).length}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Departments</CardTitle>
<AlertCircle className="h-4 w-4 text-blue-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-blue-600">
{new Set(users.map(u => u.department_response?.name).filter(Boolean)).size}
</div>
</CardContent>
</Card>
</div>
{/* Filters and Search */}
<Card className="mb-6">
<CardHeader>
<CardTitle>Filters & Search</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col md:flex-row gap-4">
<div className="flex-1">
<Label htmlFor="search">Search</Label>
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
<Input
id="search"
placeholder="Search by name, email, or department..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
</div>
<div className="w-full md:w-48">
<Label htmlFor="status">Status</Label>
<Select value={statusFilter} onValueChange={setStatusFilter}>
<SelectTrigger>
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Status</SelectItem>
<SelectItem value="active">Active</SelectItem>
<SelectItem value="inactive">Inactive</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-end gap-2">
<Button onClick={fetchUsers} disabled={loading} className="gap-2">
{loading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Filter className="h-4 w-4" />
)}
Refresh
</Button>
<div className="relative">
<input
type="file"
accept=".xlsx,.xls"
onChange={handleFileUpload}
className="hidden"
id="excel-upload"
/>
<Button
variant="outline"
onClick={() => document.getElementById('excel-upload')?.click()}
className="gap-2"
>
<Upload className="h-4 w-4" />
Upload Excel
</Button>
</div>
{currentJobId && (
<Button
variant="outline"
onClick={() => {
setShowJobStatus(true)
checkJobStatus(currentJobId)
}}
className="gap-2"
>
<Clock className="h-4 w-4" />
Check Job Status
</Button>
)}
</div>
</div>
</CardContent>
</Card>
{/* Users Table */}
<Card>
<CardHeader>
<CardTitle>Users List</CardTitle>
<CardDescription>
Showing {filteredUsers.length} of {users.length} users
</CardDescription>
</CardHeader>
<CardContent>
{loading ? (
<div className="text-center py-8">
<Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
<p className="text-gray-600">Loading users...</p>
</div>
) : filteredUsers.length === 0 ? (
<div className="text-center py-8">
<Users className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium mb-2">No users found</h3>
<p className="text-gray-600">Try adjusting your search or filters</p>
</div>
) : (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Email</TableHead>
<TableHead>Department</TableHead>
<TableHead>Role</TableHead>
<TableHead>Status</TableHead>
<TableHead>Created</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredUsers.map((user) => (
<TableRow key={user.id}>
<TableCell className="font-medium">{user.name}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
{user.department_response?.name || "N/A"}
</TableCell>
<TableCell>
{getRoleBadge(user.roles)}
</TableCell>
<TableCell>
{getStatusBadge(user.is_active)}
</TableCell>
<TableCell>
{new Date(user.created_at).toLocaleDateString()}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
{/* Bulk Upload Dialog */}
{showBulkUpload && (
<Dialog open={showBulkUpload} onOpenChange={setShowBulkUpload}>
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Bulk User Upload</DialogTitle>
<DialogDescription>
Review and select users from the uploaded Excel file. Selected users will be created in the system.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{/* Bulk Actions */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Checkbox
id="select-all"
checked={selectAll}
onCheckedChange={handleSelectAll}
/>
<Label htmlFor="select-all">Select All ({bulkUsers.length})</Label>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-gray-600">
{selectedUsers.size} of {bulkUsers.length} selected
</span>
<Button
onClick={handleBulkCreate}
disabled={bulkLoading || selectedUsers.size === 0}
className="gap-2"
>
{bulkLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Plus className="h-4 w-4" />
)}
Create {selectedUsers.size} Users
</Button>
</div>
</div>
{/* Users Table */}
<div className="border rounded-lg">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12">Select</TableHead>
<TableHead>Name</TableHead>
<TableHead>Email</TableHead>
<TableHead>Password</TableHead>
<TableHead>Role</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bulkUsers.map((user, index) => (
<TableRow key={index}>
<TableCell>
<Checkbox
checked={selectedUsers.has(index)}
onCheckedChange={() => handleSelectUser(index)}
/>
</TableCell>
<TableCell className="font-medium">{user.name}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell className="font-mono text-sm">
{user.password.length > 8 ? `${user.password.substring(0, 8)}...` : user.password}
</TableCell>
<TableCell>
<Badge variant="outline">{user.role}</Badge>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{/* Instructions */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<h4 className="font-medium text-blue-900 mb-2">Excel Format Requirements:</h4>
<ul className="text-sm text-blue-800 space-y-1">
<li> <strong>Nama:</strong> User's full name (required)</li>
<li>• <strong>Password:</strong> User's password (min 6 characters)</li>
<li> <strong>Email:</strong> Valid email address (required)</li>
<li> <strong>Role:</strong> User role (defaults to "Staff" if empty)</li>
</ul>
<div className="mt-3 pt-3 border-t border-blue-200">
<p className="text-sm text-blue-800">
<strong>Note:</strong> Bulk user creation is processed asynchronously.
You'll receive a job ID to track progress.
</p>
</div>
</div>
</div>
</DialogContent>
</Dialog>
)}
{/* Job Status Dialog */}
{showJobStatus && (
<Dialog open={showJobStatus} onOpenChange={setShowJobStatus}>
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Bulk Upload Job Status</DialogTitle>
<DialogDescription>
{currentJobId && `Job ID: ${currentJobId}`}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{jobLoading ? (
<div className="text-center py-8">
<Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
<p className="text-gray-600">Checking job status...</p>
</div>
) : jobStatus ? (
<>
{/* Job Summary */}
<Card>
<CardHeader>
<CardTitle>Job Summary</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="text-center">
<div className="text-2xl font-bold text-blue-600">{jobStatus.summary.total}</div>
<div className="text-sm text-gray-600">Total Users</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-green-600">{jobStatus.summary.succeeded}</div>
<div className="text-sm text-gray-600">Succeeded</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-red-600">{jobStatus.summary.failed}</div>
<div className="text-sm text-gray-600">Failed</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-gray-600">
{jobStatus.status === 'completed' ? '' :
jobStatus.status === 'failed' ? '' : ''}
</div>
<div className="text-sm text-gray-600 capitalize">{jobStatus.status}</div>
</div>
</div>
<div className="mt-4 p-3 bg-gray-50 rounded-lg">
<div className="text-sm">
<strong>Started:</strong> {new Date(jobStatus.started_at).toLocaleString()}
</div>
{jobStatus.finished_at && (
<div className="text-sm">
<strong>Finished:</strong> {new Date(jobStatus.finished_at).toLocaleString()}
</div>
)}
<div className="text-sm">
<strong>Message:</strong> {jobStatus.message}
</div>
</div>
</CardContent>
</Card>
{/* Created Users */}
{jobStatus.created.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-green-700">Successfully Created Users</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Email</TableHead>
<TableHead>Status</TableHead>
<TableHead>Created</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{jobStatus.created.map((user) => (
<TableRow key={user.id}>
<TableCell className="font-medium">{user.name}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
<Badge className="bg-green-100 text-green-800 border-green-200">
<CheckCircle className="h-3 w-3 mr-1" />
Active
</Badge>
</TableCell>
<TableCell>
{new Date(user.created_at).toLocaleDateString()}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
)}
{/* Failed Users */}
{jobStatus.failed.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-red-700">Failed Users</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Email</TableHead>
<TableHead>Role</TableHead>
<TableHead>Error</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{jobStatus.failed.map((failedUser, index) => (
<TableRow key={index}>
<TableCell className="font-medium">{failedUser.user.name}</TableCell>
<TableCell>{failedUser.user.email}</TableCell>
<TableCell>{failedUser.user.role}</TableCell>
<TableCell className="text-red-600 text-sm">
{failedUser.error}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
)}
{/* Action Buttons */}
<div className="flex justify-end gap-3">
{jobStatus.status === 'completed' && (
<Button
onClick={() => {
setShowJobStatus(false)
setCurrentJobId(null)
localStorage.removeItem("bulk_job_id")
}}
>
Close & Clear Job
</Button>
)}
{jobStatus.status !== 'completed' && jobStatus.status !== 'failed' && (
<Button
onClick={() => checkJobStatus(currentJobId!)}
disabled={jobLoading}
variant="outline"
>
{jobLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Checking...
</>
) : (
'Refresh Status'
)}
</Button>
)}
</div>
</>
) : (
<div className="text-center py-8">
<Clock className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<p className="text-gray-600">No job status available</p>
</div>
)}
</div>
</DialogContent>
</Dialog>
)}
</div>
</div>
)
}
export default function MembersPage() {
return (
<AuthGuard requiredRole="superadmin">
<MembersPageContent />
</AuthGuard>
)
}
File diff suppressed because it is too large Load Diff
+202
View File
@@ -0,0 +1,202 @@
"use client"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Users, Vote, BarChart3, LogOut, Calendar, Settings } from "lucide-react"
import Link from "next/link"
import { AuthGuard } from "@/components/auth-guard"
import { useAuth } from "@/hooks/use-auth"
import apiClient from "@/lib/api-client"
import { API_CONFIG } from "@/lib/config"
function AdminPageContent() {
const { user, logout } = useAuth()
const [stats, setStats] = useState({
totalEvents: 0,
activeEvents: 0,
totalCandidates: 0
})
const [loading, setLoading] = useState(true)
useEffect(() => {
fetchStats()
}, [])
const fetchStats = async () => {
try {
const response = await apiClient.get(API_CONFIG.ENDPOINTS.VOTE_EVENTS)
if (response.data.success) {
const events = response.data.data.vote_events || []
const now = new Date()
const activeEvents = events.filter((event: any) => {
const start = new Date(event.start_date)
const end = new Date(event.end_date)
return now >= start && now <= end
})
const totalCandidates = events.reduce((total: number, event: any) => {
return total + (event.candidates?.length || 0)
}, 0)
setStats({
totalEvents: events.length,
activeEvents: activeEvents.length,
totalCandidates
})
}
} catch (error) {
console.error('Error fetching stats:', error)
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen bg-gray-50">
<header className="bg-white shadow-sm border-b">
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
<div className="flex items-center gap-4">
<img src="/images/meti-logo.png" alt="METI - New & Renewable Energy" className="h-12 w-auto" />
<h1 className="text-2xl font-bold text-gray-900">Admin Dashboard METI</h1>
</div>
<div className="flex items-center gap-4">
<span className="text-sm text-gray-600">Welcome, {user?.username || 'Admin'}</span>
<Button variant="outline" size="sm" onClick={logout}>
<LogOut className="h-4 w-4 mr-2" />
Logout
</Button>
</div>
</div>
</header>
<div className="container mx-auto px-4 py-8">
{/* Statistics Cards */}
<div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Events</CardTitle>
<Vote className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{loading ? '...' : stats.totalEvents}</div>
<p className="text-xs text-muted-foreground">Vote events created</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Active Events</CardTitle>
<BarChart3 className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{loading ? '...' : stats.activeEvents}</div>
<p className="text-xs text-muted-foreground">Currently running</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Candidates</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{loading ? '...' : stats.totalCandidates}</div>
<p className="text-xs text-muted-foreground">Across all events</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">System Status</CardTitle>
<Settings className="h-4 w-4 text-green-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">Online</div>
<p className="text-xs text-muted-foreground">All systems operational</p>
</CardContent>
</Card>
</div>
{/* Quick Actions */}
<div className="mb-8">
<h2 className="text-2xl font-bold text-gray-900 mb-6">Quick Actions</h2>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
<Card className="hover:shadow-lg transition-shadow cursor-pointer group">
<CardHeader>
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center group-hover:bg-blue-200 transition-colors">
<Calendar className="h-6 w-6 text-blue-600" />
</div>
<div>
<CardTitle className="text-lg">Manage Events</CardTitle>
<CardDescription>Create and manage voting events</CardDescription>
</div>
</div>
</CardHeader>
<CardContent>
<Link href="/admin/events">
<Button className="w-full bg-blue-600 hover:bg-blue-700">
<Settings className="h-4 w-4 mr-2" />
Event Management
</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-lg transition-shadow cursor-pointer group">
<CardHeader>
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center group-hover:bg-green-200 transition-colors">
<Users className="h-6 w-6 text-green-600" />
</div>
<div>
<CardTitle className="text-lg">Manage Members</CardTitle>
<CardDescription>Verify and manage members</CardDescription>
</div>
</div>
</CardHeader>
<CardContent>
<Link href="/admin/members">
<Button className="w-full bg-green-600 hover:bg-green-700">
<Users className="h-4 w-4 mr-2" />
Member Management
</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-lg transition-shadow cursor-pointer group">
<CardHeader>
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center group-hover:bg-purple-200 transition-colors">
<BarChart3 className="h-6 w-6 text-purple-600" />
</div>
<div>
<CardTitle className="text-lg">View Results</CardTitle>
<CardDescription>Monitor voting results</CardDescription>
</div>
</div>
</CardHeader>
<CardContent>
<Link href="/results">
<Button className="w-full bg-purple-600 hover:bg-purple-700">
<BarChart3 className="h-4 w-4 mr-2" />
View Results
</Button>
</Link>
</CardContent>
</Card>
</div>
</div>
</div>
</div>
)
}
export default function AdminPage() {
return (
<AuthGuard requiredRole="superadmin">
<AdminPageContent />
</AuthGuard>
)
}