Add dockre file
This commit is contained in:
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function Loading() {
|
||||
return null
|
||||
}
|
||||
@@ -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
@@ -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>
|
||||
)
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
@import 'tailwindcss';
|
||||
@import 'tw-animate-css';
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
:root {
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--destructive-foreground: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--radius: 0.625rem;
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.145 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.145 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.985 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.396 0.141 25.723);
|
||||
--destructive-foreground: oklch(0.637 0.237 25.331);
|
||||
--border: oklch(0.269 0 0);
|
||||
--input: oklch(0.269 0 0);
|
||||
--ring: oklch(0.439 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(0.269 0 0);
|
||||
--sidebar-ring: oklch(0.439 0 0);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom animations for results page */
|
||||
@keyframes fade-in-up {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-fade-in-up {
|
||||
animation: fade-in-up 0.8s ease-out forwards;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
@keyframes countdown-pulse {
|
||||
0%, 100% {
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-countdown-pulse {
|
||||
animation: countdown-pulse 1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Bar chart animations */
|
||||
@keyframes bar-grow {
|
||||
0% {
|
||||
width: 0%;
|
||||
}
|
||||
100% {
|
||||
width: var(--final-width);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-bar-grow {
|
||||
animation: bar-grow 2s ease-out forwards;
|
||||
width: 0%;
|
||||
}
|
||||
|
||||
/* Profile image hover effects */
|
||||
.profile-image-container:hover {
|
||||
transform: scale(1.05);
|
||||
transition: transform 0.2s ease-out;
|
||||
}
|
||||
|
||||
/* Gradient backgrounds for bars */
|
||||
.bar-gradient-1 { background: linear-gradient(135deg, #3B82F6, #1D4ED8); }
|
||||
.bar-gradient-2 { background: linear-gradient(135deg, #10B981, #047857); }
|
||||
.bar-gradient-3 { background: linear-gradient(135deg, #F59E0B, #D97706); }
|
||||
.bar-gradient-4 { background: linear-gradient(135deg, #EF4444, #DC2626); }
|
||||
.bar-gradient-5 { background: linear-gradient(135deg, #8B5CF6, #7C3AED); }
|
||||
@@ -0,0 +1,35 @@
|
||||
import type React from "react"
|
||||
import type { Metadata } from "next"
|
||||
import { Inter } from "next/font/google"
|
||||
import "./globals.css"
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] })
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "E-Voting METI",
|
||||
description:
|
||||
"Sistem pemilihan elektronik yang aman dan transparan untuk pemilihan ketua umum METI (New & Renewable Energy)",
|
||||
icons: {
|
||||
icon: "/favicon.ico",
|
||||
shortcut: "/favicon.ico",
|
||||
apple: "/favicon.ico",
|
||||
},
|
||||
generator: 'v0.app'
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<html lang="id">
|
||||
<head>
|
||||
<link rel="icon" href="/favicon.ico" sizes="any" />
|
||||
<link rel="icon" href="/favicon.ico" type="image/png" />
|
||||
<link rel="apple-touch-icon" href="/favicon.ico" />
|
||||
</head>
|
||||
<body className={inter.className}>{children}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function Loading() {
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } 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 { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { Vote, ArrowLeft, Loader2 } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { useAuth } from "@/hooks/use-auth"
|
||||
|
||||
export default function LoginPage() {
|
||||
const [email, setEmail] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [error, setError] = useState("")
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const router = useRouter()
|
||||
const { login } = useAuth()
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const result = await login(email, password)
|
||||
|
||||
if (result.success) {
|
||||
// Redirect to home page after successful login
|
||||
router.push("/")
|
||||
} else {
|
||||
setError(result.message)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Login error:", err)
|
||||
setError("Terjadi kesalahan sistem. Silakan coba lagi.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="min-h-screen flex items-center justify-center p-4 relative bg-cover bg-center bg-no-repeat"
|
||||
style={{ backgroundImage: `url('/images/solar-background.jpg')` }}
|
||||
>
|
||||
{/* Dark overlay for better contrast */}
|
||||
<div className="absolute inset-0 bg-black/50"></div>
|
||||
|
||||
<Card className="w-full max-w-md relative z-10 bg-white/95 backdrop-blur-sm shadow-2xl">
|
||||
<CardHeader className="text-center">
|
||||
<Link href="/" className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 mb-4">
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||
Kembali ke Beranda
|
||||
</Link>
|
||||
<div className="flex justify-center mb-4">
|
||||
<img src="/images/meti-logo.png" alt="METI - New & Renewable Energy" className="h-16 w-auto" />
|
||||
</div>
|
||||
<Vote className="h-12 w-12 text-blue-600 mx-auto mb-4" />
|
||||
<CardTitle className="text-2xl text-gray-900">
|
||||
Login METI
|
||||
</CardTitle>
|
||||
<CardDescription className="text-gray-700">
|
||||
Masuk ke sistem voting METI
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleLogin} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email" className="text-gray-800">
|
||||
Email
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
placeholder="Masukkan email"
|
||||
className="bg-white/90"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password" className="text-gray-800">
|
||||
Password
|
||||
</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
placeholder="Masukkan password"
|
||||
className="bg-white/90"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Memproses...
|
||||
</>
|
||||
) : (
|
||||
"Login"
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+380
@@ -0,0 +1,380 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Vote, Users, Settings, BarChart3, LogOut, Clock, Calendar, Play, StopCircle, Timer, CheckCircle2, AlertCircle, Sparkles } from "lucide-react"
|
||||
import { useAuth } from "@/hooks/use-auth"
|
||||
import apiClient from "@/lib/api-client"
|
||||
import { API_CONFIG } from "@/lib/config"
|
||||
import { DashboardHeader } from "@/components/dashboard-header"
|
||||
|
||||
interface VoteEvent {
|
||||
id: string
|
||||
title: string
|
||||
description: string
|
||||
start_date: string
|
||||
end_date: string
|
||||
is_active: boolean
|
||||
is_voting_open: boolean
|
||||
status?: string
|
||||
}
|
||||
|
||||
interface Countdown {
|
||||
days: number
|
||||
hours: number
|
||||
minutes: number
|
||||
seconds: number
|
||||
isActive: boolean
|
||||
isEnded: boolean
|
||||
isUpcoming: boolean
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const { user, isAuthenticated, isAdmin, isSuperAdmin, logout, loading } = useAuth()
|
||||
const [voteEvents, setVoteEvents] = useState<VoteEvent[]>([])
|
||||
const [eventsLoading, setEventsLoading] = useState(true)
|
||||
const [countdowns, setCountdowns] = useState<Record<string, Countdown>>({})
|
||||
const router = useRouter()
|
||||
|
||||
// Fetch vote events
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
fetchVoteEvents()
|
||||
}
|
||||
}, [isAuthenticated])
|
||||
|
||||
// Update countdowns every second
|
||||
useEffect(() => {
|
||||
if (voteEvents.length > 0) {
|
||||
const interval = setInterval(() => {
|
||||
updateCountdowns()
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [voteEvents])
|
||||
|
||||
const fetchVoteEvents = async () => {
|
||||
try {
|
||||
setEventsLoading(true)
|
||||
const response = await apiClient.get(API_CONFIG.ENDPOINTS.VOTE_EVENTS)
|
||||
|
||||
if (response.data.success) {
|
||||
setVoteEvents(response.data.data.vote_events || [])
|
||||
// Initialize countdowns for all events
|
||||
const initialCountdowns: Record<string, Countdown> = {}
|
||||
response.data.data.vote_events.forEach((event: VoteEvent) => {
|
||||
initialCountdowns[event.id] = calculateCountdown(event.start_date, event.end_date)
|
||||
})
|
||||
setCountdowns(initialCountdowns)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching vote events:', error)
|
||||
} finally {
|
||||
setEventsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const calculateCountdown = (startDate: string, endDate: string): Countdown => {
|
||||
const now = new Date().getTime()
|
||||
const start = new Date(startDate).getTime()
|
||||
const end = new Date(endDate).getTime()
|
||||
|
||||
let targetTime: number
|
||||
let isActive = false
|
||||
let isEnded = false
|
||||
let isUpcoming = false
|
||||
|
||||
if (now < start) {
|
||||
// Event hasn't started yet
|
||||
targetTime = start
|
||||
isUpcoming = true
|
||||
} else if (now >= start && now <= end) {
|
||||
// Event is active
|
||||
targetTime = end
|
||||
isActive = true
|
||||
} else {
|
||||
// Event has ended
|
||||
targetTime = end
|
||||
isEnded = true
|
||||
}
|
||||
|
||||
const timeLeft = Math.max(0, targetTime - now)
|
||||
|
||||
const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24))
|
||||
const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
|
||||
const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60))
|
||||
const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000)
|
||||
|
||||
return {
|
||||
days,
|
||||
hours,
|
||||
minutes,
|
||||
seconds,
|
||||
isActive,
|
||||
isEnded,
|
||||
isUpcoming
|
||||
}
|
||||
}
|
||||
|
||||
const updateCountdowns = () => {
|
||||
const updatedCountdowns: Record<string, Countdown> = {}
|
||||
voteEvents.forEach((event) => {
|
||||
updatedCountdowns[event.id] = calculateCountdown(event.start_date, event.end_date)
|
||||
})
|
||||
setCountdowns(updatedCountdowns)
|
||||
}
|
||||
|
||||
const formatCountdown = (countdown: Countdown) => {
|
||||
if (countdown.isEnded) {
|
||||
return "Event Ended"
|
||||
}
|
||||
|
||||
if (countdown.days > 0) {
|
||||
return `${countdown.days}d ${countdown.hours}h ${countdown.minutes}m ${countdown.seconds}s`
|
||||
} else if (countdown.hours > 0) {
|
||||
return `${countdown.hours}h ${countdown.minutes}m ${countdown.seconds}s`
|
||||
} else if (countdown.minutes > 0) {
|
||||
return `${countdown.minutes}m ${countdown.seconds}s`
|
||||
} else {
|
||||
return `${countdown.seconds}s`
|
||||
}
|
||||
}
|
||||
|
||||
const getEventStatus = (countdown: Countdown) => {
|
||||
if (countdown.isEnded) return "ended"
|
||||
if (countdown.isActive) return "active"
|
||||
if (countdown.isUpcoming) return "upcoming"
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
const getStatusBadge = (status: string, isVotingOpen: boolean) => {
|
||||
if (isVotingOpen && status === "active") {
|
||||
return (
|
||||
<Badge className="bg-gradient-to-r from-green-500 to-emerald-500 text-white border-0 shadow-lg">
|
||||
<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">
|
||||
<AlertCircle className="h-3 w-3 mr-1" />
|
||||
Active (Voting Closed)
|
||||
</Badge>
|
||||
)
|
||||
case "upcoming":
|
||||
return (
|
||||
<Badge className="bg-blue-100 text-blue-800 border-blue-200">
|
||||
<Clock className="h-3 w-3 mr-1" />
|
||||
Coming Soon
|
||||
</Badge>
|
||||
)
|
||||
case "ended":
|
||||
return (
|
||||
<Badge className="bg-gray-100 text-gray-800 border-gray-200">
|
||||
<CheckCircle2 className="h-3 w-3 mr-1" />
|
||||
Completed
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return <Badge variant="outline">Unknown</Badge>
|
||||
}
|
||||
}
|
||||
|
||||
// Show loading while checking authentication
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600 mx-auto mb-4"></div>
|
||||
<p className="text-gray-600">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Redirect to login if not authenticated
|
||||
if (!isAuthenticated) {
|
||||
router.push("/login")
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* Dashboard Header */}
|
||||
<DashboardHeader
|
||||
title="E-Voting Platform"
|
||||
showStats={true}
|
||||
stats={{
|
||||
totalEvents: voteEvents.length,
|
||||
activeEvents: voteEvents.filter(event => event.is_voting_open).length
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
{/* Page Title Section */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="inline-flex items-center gap-2 bg-blue-50 rounded-full px-4 py-2 mb-4">
|
||||
<Sparkles className="h-4 w-4 text-blue-600" />
|
||||
<span className="text-blue-700 text-sm font-medium">Democratic Participation</span>
|
||||
</div>
|
||||
<h2 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-3">
|
||||
Available Vote Events
|
||||
</h2>
|
||||
<p className="text-base text-gray-600 max-w-xl mx-auto px-4">
|
||||
Participate in democratic decisions and make your voice heard
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Vote Events Section */}
|
||||
<div className="">
|
||||
|
||||
{eventsLoading ? (
|
||||
<div className="text-center py-16">
|
||||
<div className="animate-spin rounded-full h-16 w-16 border-4 border-gray-200 border-t-blue-600 mx-auto mb-6"></div>
|
||||
<p className="text-gray-900 text-lg font-medium">Loading vote events...</p>
|
||||
<p className="text-gray-600 text-sm mt-2">Please wait while we fetch the latest information</p>
|
||||
</div>
|
||||
) : voteEvents.length > 0 ? (
|
||||
<div className="grid gap-6 max-w-6xl mx-auto">
|
||||
{voteEvents.map((event) => {
|
||||
const countdown = countdowns[event.id]
|
||||
const status = getEventStatus(countdown)
|
||||
|
||||
return (
|
||||
<Card key={event.id} className="bg-white hover:shadow-lg transition-all duration-300 border overflow-hidden">
|
||||
<CardHeader className="pb-4">
|
||||
<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-2xl font-bold text-gray-900">{event.title}</CardTitle>
|
||||
{getStatusBadge(status, event.is_voting_open)}
|
||||
</div>
|
||||
<CardDescription className="text-base text-gray-600 leading-relaxed">
|
||||
{event.description}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{event.is_voting_open ? (
|
||||
<Link href={`/vote?event_id=${event.id}`} className="block">
|
||||
<Button className="bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] h-12 px-6">
|
||||
<Vote className="h-5 w-5 mr-2" />
|
||||
<span className="font-bold">🗳️ Vote Now</span>
|
||||
</Button>
|
||||
</Link>
|
||||
) : status === "upcoming" ? (
|
||||
<Button variant="outline" className="h-12 px-6 border-2 border-blue-200 text-blue-700 cursor-not-allowed" disabled>
|
||||
<Clock className="h-5 w-5 mr-2" />
|
||||
<span className="font-semibold">⏰ Coming Soon</span>
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="outline" className="h-12 px-6 border-2 border-gray-200 text-gray-600 bg-gray-50 cursor-not-allowed" disabled>
|
||||
<StopCircle className="h-5 w-5 mr-2" />
|
||||
<span className="font-semibold">🔒 Voting Closed</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{/* Event Dates and Countdown */}
|
||||
<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>
|
||||
|
||||
{/* Countdown Display for Active Events */}
|
||||
{!countdown?.isEnded && (event.is_voting_open || status === "upcoming") && (
|
||||
<div className={`mt-4 text-center p-4 rounded-lg border-2 ${
|
||||
event.is_voting_open && status === "active"
|
||||
? "bg-gradient-to-br from-green-50 to-emerald-50 border-green-200"
|
||||
: "bg-gradient-to-br from-blue-50 to-indigo-50 border-blue-200"
|
||||
}`}>
|
||||
<div className="flex items-center justify-center gap-2 mb-2">
|
||||
{event.is_voting_open && status === "active" ? (
|
||||
<Timer className="h-4 w-4 text-green-600 animate-pulse" />
|
||||
) : (
|
||||
<Clock className="h-4 w-4 text-blue-600" />
|
||||
)}
|
||||
<span className="text-sm font-semibold text-gray-900">
|
||||
{event.is_voting_open && status === "active"
|
||||
? "Voting ends in:"
|
||||
: "Starts in:"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-lg font-bold text-blue-700">
|
||||
{formatCountdown(countdown)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="bg-white border shadow-lg max-w-2xl mx-auto">
|
||||
<CardContent className="text-center py-16">
|
||||
<div className="relative mb-8">
|
||||
<div className="w-20 h-20 bg-gradient-to-br from-gray-100 to-gray-200 rounded-full mx-auto flex items-center justify-center">
|
||||
<Vote className="h-10 w-10 text-gray-400" />
|
||||
</div>
|
||||
<div className="absolute -top-2 -right-2 w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">
|
||||
<div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-gray-900 mb-3">No Vote Events Available</h3>
|
||||
<p className="text-gray-600 mb-6 max-w-md mx-auto">
|
||||
There are currently no active or upcoming vote events. Check back soon for new voting opportunities.
|
||||
</p>
|
||||
<Button
|
||||
onClick={fetchVoteEvents}
|
||||
variant="outline"
|
||||
className="bg-blue-50 border-blue-200 text-blue-700 hover:bg-blue-100"
|
||||
>
|
||||
<Calendar className="h-4 w-4 mr-2" />
|
||||
Refresh Events
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, Suspense } from "react"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { BarChart3, Users, Trophy, TrendingUp, ArrowLeft, RotateCcw, Download, Eye, Maximize2, Minimize2, Table } 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 { DashboardHeader } from "@/components/dashboard-header"
|
||||
import apiClient from "@/lib/api-client"
|
||||
import { API_CONFIG } from "@/lib/config"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts'
|
||||
|
||||
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
|
||||
vote_count: number
|
||||
}
|
||||
|
||||
interface VoteResults {
|
||||
vote_event_id: string
|
||||
candidates: Candidate[]
|
||||
total_votes: number
|
||||
}
|
||||
|
||||
interface ChartData {
|
||||
name: string
|
||||
votes: number
|
||||
percentage: number
|
||||
fill: string
|
||||
}
|
||||
|
||||
function ResultsPageContent() {
|
||||
const { user } = useAuth()
|
||||
const { toast } = useToast()
|
||||
const [events, setEvents] = useState<VoteEvent[]>([])
|
||||
const [selectedEventId, setSelectedEventId] = useState<string>("")
|
||||
const [results, setResults] = useState<VoteResults | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [eventsLoading, setEventsLoading] = useState(true)
|
||||
const [isFullPageChart, setIsFullPageChart] = useState(false)
|
||||
const [showCountdown, setShowCountdown] = useState(false)
|
||||
const [countdown, setCountdown] = useState(10)
|
||||
const [showResults, setShowResults] = useState(false)
|
||||
|
||||
// Chart colors
|
||||
const COLORS = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#06B6D4', '#84CC16', '#F97316']
|
||||
|
||||
useEffect(() => {
|
||||
fetchEvents()
|
||||
}, [])
|
||||
|
||||
// Note: URL parameter handling removed for now - can be added back later if needed
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedEventId) {
|
||||
fetchResults(selectedEventId)
|
||||
}
|
||||
}, [selectedEventId])
|
||||
|
||||
useEffect(() => {
|
||||
let interval: NodeJS.Timeout
|
||||
if (showCountdown && countdown > 0) {
|
||||
interval = setInterval(() => {
|
||||
setCountdown(prev => prev - 1)
|
||||
}, 1000)
|
||||
} else if (showCountdown && countdown === 0) {
|
||||
setShowCountdown(false)
|
||||
setShowResults(true)
|
||||
}
|
||||
return () => clearInterval(interval)
|
||||
}, [showCountdown, countdown])
|
||||
|
||||
const fetchEvents = async () => {
|
||||
try {
|
||||
setEventsLoading(true)
|
||||
const response = await apiClient.get(API_CONFIG.ENDPOINTS.VOTE_EVENTS)
|
||||
if (response.data.success) {
|
||||
const eventList = response.data.data.vote_events || []
|
||||
setEvents(eventList)
|
||||
// Auto-select the first event if available
|
||||
if (eventList.length > 0 && !selectedEventId) {
|
||||
setSelectedEventId(eventList[0].id)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching events:', error)
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to fetch vote events",
|
||||
variant: "destructive"
|
||||
})
|
||||
} finally {
|
||||
setEventsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchResults = async (eventId: string) => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const response = await apiClient.get(`${API_CONFIG.ENDPOINTS.RESULTS}/${eventId}/results`)
|
||||
if (response.data.success) {
|
||||
setResults(response.data.data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching results:', error)
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to fetch voting results",
|
||||
variant: "destructive"
|
||||
})
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const getChartData = (): (ChartData & { image_url: string; id: string })[] => {
|
||||
if (!results) return []
|
||||
|
||||
return results.candidates
|
||||
.sort((a, b) => b.vote_count - a.vote_count) // Sort by vote count descending
|
||||
.map((candidate, index) => ({
|
||||
name: candidate.name,
|
||||
votes: candidate.vote_count,
|
||||
percentage: results.total_votes > 0 ? (candidate.vote_count / results.total_votes) * 100 : 0,
|
||||
fill: COLORS[index % COLORS.length],
|
||||
image_url: candidate.image_url,
|
||||
id: candidate.id
|
||||
}))
|
||||
}
|
||||
|
||||
const getWinner = (): Candidate | null => {
|
||||
if (!results || results.candidates.length === 0) return null
|
||||
return results.candidates.reduce((prev, current) =>
|
||||
prev.vote_count > current.vote_count ? prev : current
|
||||
)
|
||||
}
|
||||
|
||||
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-green-500 text-white">Live Voting</Badge>
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case "active":
|
||||
return <Badge className="bg-orange-500 text-white">Active</Badge>
|
||||
case "upcoming":
|
||||
return <Badge className="bg-blue-500 text-white">Upcoming</Badge>
|
||||
case "ended":
|
||||
return <Badge className="bg-gray-500 text-white">Ended</Badge>
|
||||
default:
|
||||
return <Badge variant="outline">Unknown</Badge>
|
||||
}
|
||||
}
|
||||
|
||||
const handleShowResults = () => {
|
||||
if (!selectedEventId || !results) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Please select an event with available results",
|
||||
variant: "destructive"
|
||||
})
|
||||
return
|
||||
}
|
||||
setShowCountdown(true)
|
||||
setCountdown(10)
|
||||
setShowResults(false)
|
||||
}
|
||||
|
||||
const selectedEvent = events.find(e => e.id === selectedEventId)
|
||||
const chartData = getChartData()
|
||||
const winner = getWinner()
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<DashboardHeader title="Vote Results" />
|
||||
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
{/* Header Section */}
|
||||
<div className="mb-8">
|
||||
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Voting Results</h1>
|
||||
<p className="text-gray-600 mt-1">View detailed voting results and statistics</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{results && (
|
||||
<>
|
||||
<Button
|
||||
onClick={() => setIsFullPageChart(!isFullPageChart)}
|
||||
variant={isFullPageChart ? "default" : "outline"}
|
||||
className="gap-2"
|
||||
>
|
||||
{isFullPageChart ? (
|
||||
<>
|
||||
<Table className="h-4 w-4" />
|
||||
Table View
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Maximize2 className="h-4 w-4" />
|
||||
Full Chart
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button onClick={fetchEvents} variant="outline" className="gap-2">
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Event Selection */}
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<BarChart3 className="h-5 w-5" />
|
||||
Select Voting Event
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Choose an event to view its voting results and statistics
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-4 items-end">
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-700 mb-2 block">
|
||||
Vote Event
|
||||
</label>
|
||||
<Select value={selectedEventId} onValueChange={setSelectedEventId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a vote event" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{events.map((event) => (
|
||||
<SelectItem key={event.id} value={event.id}>
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<span>{event.title}</span>
|
||||
<div className="ml-2">
|
||||
{getStatusBadge(event)}
|
||||
</div>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedEvent && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm text-gray-600">
|
||||
<strong>Event:</strong> {selectedEvent.title}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">
|
||||
<strong>Period:</strong> {new Date(selectedEvent.start_date).toLocaleDateString()} - {new Date(selectedEvent.end_date).toLocaleDateString()}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Loading State */}
|
||||
{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 results...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Results Content */}
|
||||
{!loading && selectedEventId && results && (
|
||||
<>
|
||||
{/* Show Results Button */}
|
||||
{!showCountdown && !showResults && (
|
||||
<Card>
|
||||
<CardContent className="text-center py-16">
|
||||
<Trophy className="h-16 w-16 text-blue-500 mx-auto mb-6" />
|
||||
<h2 className="text-2xl font-bold mb-4">Ready to Reveal Results?</h2>
|
||||
<p className="text-gray-600 mb-8">
|
||||
Click the button below to see the voting results for "{selectedEvent?.title}"
|
||||
</p>
|
||||
<Button
|
||||
onClick={handleShowResults}
|
||||
size="lg"
|
||||
className="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-8 py-3 text-lg"
|
||||
>
|
||||
<BarChart3 className="mr-2 h-5 w-5" />
|
||||
Show Results
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Countdown Animation */}
|
||||
{showCountdown && (
|
||||
<Card>
|
||||
<CardContent className="text-center py-24">
|
||||
<div className="relative">
|
||||
<div className={`text-8xl font-bold mb-4 transition-all duration-1000 ${
|
||||
countdown <= 3 ? 'text-red-500 scale-125' : 'text-blue-500 scale-100'
|
||||
}`}>
|
||||
{countdown}
|
||||
</div>
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className={`w-32 h-32 border-4 border-blue-200 rounded-full animate-pulse ${
|
||||
countdown <= 3 ? 'border-red-200' : ''
|
||||
}`}></div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xl text-gray-600 animate-bounce">
|
||||
{countdown > 5 ? 'Preparing results...' :
|
||||
countdown > 3 ? 'Almost ready...' : 'Here we go!'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Animated Results Display */}
|
||||
{showResults && (
|
||||
<div className="space-y-8">
|
||||
{/* Winner Announcement */}
|
||||
<Card className="animate-fade-in-up">
|
||||
<CardContent className="text-center py-12">
|
||||
<div className="mb-6">
|
||||
<Trophy className="h-16 w-16 text-yellow-500 mx-auto animate-bounce" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-bold mb-2 text-gray-900">
|
||||
🎉 Winner: {winner?.name || "No votes yet"} 🎉
|
||||
</h2>
|
||||
<p className="text-xl text-gray-600">
|
||||
{winner ? `${winner.vote_count} votes (${((winner.vote_count / results.total_votes) * 100).toFixed(1)}%)` : "Waiting for votes"}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Animated Bar Chart with Profile Images */}
|
||||
<Card className="animate-fade-in-up" style={{ animationDelay: '0.3s' }}>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl">Final Results</CardTitle>
|
||||
<CardDescription>Vote distribution by candidate</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{chartData.length > 0 ? (
|
||||
<div className="space-y-6">
|
||||
{chartData.map((candidate, index) => {
|
||||
const maxVotes = Math.max(...chartData.map(c => c.votes))
|
||||
const barWidth = candidate.votes > 0 ? (candidate.votes / maxVotes) * 100 : 0
|
||||
|
||||
return (
|
||||
<div key={candidate.id} className="relative">
|
||||
{/* Candidate Info Row */}
|
||||
<div className="flex items-center gap-4 mb-3 p-3 bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow">
|
||||
{/* Profile Image */}
|
||||
<div className="relative w-20 h-20 flex-shrink-0 profile-image-container">
|
||||
{candidate.image_url ? (
|
||||
<Image
|
||||
src={candidate.image_url}
|
||||
alt={candidate.name}
|
||||
fill
|
||||
className="object-cover rounded-full border-4 shadow-lg transition-transform"
|
||||
style={{ borderColor: candidate.fill }}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="w-full h-full bg-gray-200 rounded-full flex items-center justify-center border-4 shadow-lg transition-transform"
|
||||
style={{ borderColor: candidate.fill }}
|
||||
>
|
||||
<Users className="h-8 w-8 text-gray-400" />
|
||||
</div>
|
||||
)}
|
||||
{/* Rank Badge */}
|
||||
<div className="absolute -top-2 -right-2">
|
||||
<div className={`px-3 py-1 rounded-full text-white font-bold text-sm shadow-lg ${
|
||||
index === 0 ? 'bg-gradient-to-r from-yellow-400 to-yellow-600' :
|
||||
index === 1 ? 'bg-gradient-to-r from-gray-400 to-gray-600' :
|
||||
index === 2 ? 'bg-gradient-to-r from-orange-400 to-orange-600' :
|
||||
'bg-gradient-to-r from-blue-400 to-blue-600'
|
||||
}`}>
|
||||
#{index + 1}
|
||||
</div>
|
||||
</div>
|
||||
{/* Winner Crown */}
|
||||
{index === 0 && candidate.votes > 0 && (
|
||||
<div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
|
||||
<Trophy className="h-6 w-6 text-yellow-500 animate-bounce" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Candidate Name and Info */}
|
||||
<div className="flex-grow">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="text-xl font-bold text-gray-900">{candidate.name}</h3>
|
||||
{index < 3 && (
|
||||
<span className="text-xs px-2 py-1 rounded-full bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-medium">
|
||||
{index === 0 ? '🏆 Winner' : index === 1 ? '🥈 2nd' : '🥉 3rd'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 font-medium">{candidate.votes} votes</p>
|
||||
</div>
|
||||
|
||||
{/* Percentage Display */}
|
||||
<div className="text-right">
|
||||
<div
|
||||
className="text-3xl font-bold mb-1"
|
||||
style={{ color: candidate.fill }}
|
||||
>
|
||||
{candidate.percentage.toFixed(1)}%
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 font-medium">
|
||||
of {results.total_votes} votes
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Enhanced Animated Bar */}
|
||||
<div className="relative bg-gradient-to-r from-gray-200 to-gray-300 rounded-full h-12 overflow-hidden shadow-inner mb-4">
|
||||
<div
|
||||
className="h-full rounded-full flex items-center justify-between px-4 shadow-lg relative overflow-hidden"
|
||||
style={{
|
||||
background: `linear-gradient(135deg, ${candidate.fill}, ${candidate.fill}dd)`,
|
||||
width: `${barWidth}%`,
|
||||
transition: 'width 2s ease-out',
|
||||
transitionDelay: `${index * 300}ms`
|
||||
}}
|
||||
>
|
||||
{/* Shimmer Effect */}
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent animate-pulse"></div>
|
||||
|
||||
{/* Vote count inside bar */}
|
||||
<div className="relative z-10 flex items-center justify-between w-full">
|
||||
{barWidth > 20 && (
|
||||
<span className="text-white font-bold text-sm">
|
||||
{candidate.name}
|
||||
</span>
|
||||
)}
|
||||
{barWidth > 10 && (
|
||||
<span className="text-white font-bold text-lg">
|
||||
{candidate.votes}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Percentage label outside bar for small bars */}
|
||||
{barWidth < 20 && candidate.votes > 0 && (
|
||||
<div className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-700 font-bold text-sm">
|
||||
{candidate.votes}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Total Votes Summary */}
|
||||
<div className="mt-8 p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border-2 border-blue-200">
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-gray-900 mb-2">
|
||||
{results.total_votes}
|
||||
</div>
|
||||
<p className="text-gray-600">Total Votes Cast</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-96 flex items-center justify-center bg-gray-50 rounded-lg">
|
||||
<div className="text-center">
|
||||
<BarChart3 className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||
<p className="text-gray-600">No voting data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Summary Stats */}
|
||||
<div className="grid md:grid-cols-3 gap-6 animate-fade-in-up" style={{ animationDelay: '0.6s' }}>
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total Votes</CardTitle>
|
||||
<Users className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold text-blue-600">{results.total_votes}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Cast across all candidates
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Candidates</CardTitle>
|
||||
<Trophy className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold text-green-600">{results.candidates.length}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Participated in voting
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Winning Margin</CardTitle>
|
||||
<TrendingUp className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold text-purple-600">
|
||||
{winner && results.candidates.length > 1 ?
|
||||
`${Math.max(0, winner.vote_count - Math.max(...results.candidates.filter(c => c.id !== winner.id).map(c => c.vote_count)))}` :
|
||||
'0'
|
||||
}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Vote difference
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* No Event Selected */}
|
||||
{!loading && !selectedEventId && (
|
||||
<Card>
|
||||
<CardContent className="text-center py-12">
|
||||
<BarChart3 className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium mb-2">Select a Vote Event</h3>
|
||||
<p className="text-gray-600">Choose an event from the dropdown above to view its results</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* No Results Available */}
|
||||
{!loading && selectedEventId && !results && (
|
||||
<Card>
|
||||
<CardContent className="text-center py-12">
|
||||
<BarChart3 className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium mb-2">No Results Available</h3>
|
||||
<p className="text-gray-600">Results for this event are not yet available</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ResultsPage() {
|
||||
return (
|
||||
<AuthGuard requiredRole="superadmin">
|
||||
<Suspense fallback={
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600 mx-auto mb-4"></div>
|
||||
<p className="text-gray-600">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
}>
|
||||
<ResultsPageContent />
|
||||
</Suspense>
|
||||
</AuthGuard>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, Suspense } from "react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import {
|
||||
Vote,
|
||||
ArrowLeft,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
AlertCircle,
|
||||
User,
|
||||
Image as ImageIcon,
|
||||
Loader2,
|
||||
Shield,
|
||||
Timer,
|
||||
CheckCircle
|
||||
} from "lucide-react"
|
||||
import { useAuth } from "@/hooks/use-auth"
|
||||
import apiClient from "@/lib/api-client"
|
||||
import { API_CONFIG } from "@/lib/config"
|
||||
|
||||
interface Candidate {
|
||||
id: string
|
||||
vote_event_id: string
|
||||
name: string
|
||||
image_url: string
|
||||
description: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
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 VoteStatus {
|
||||
has_voted: boolean
|
||||
}
|
||||
|
||||
interface VoteRequest {
|
||||
vote_event_id: string
|
||||
candidate_id: string
|
||||
}
|
||||
|
||||
function VotePageContent() {
|
||||
const { user, isAuthenticated, loading } = useAuth()
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const eventId = searchParams.get('event_id')
|
||||
|
||||
const [event, setEvent] = useState<VoteEvent | null>(null)
|
||||
const [voteStatus, setVoteStatus] = useState<VoteStatus | null>(null)
|
||||
const [selectedCandidate, setSelectedCandidate] = useState<string | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isVoting, setIsVoting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState<string | null>(null)
|
||||
|
||||
// Fetch event details and voting status
|
||||
useEffect(() => {
|
||||
if (isAuthenticated && eventId) {
|
||||
fetchEventDetails()
|
||||
fetchVoteStatus()
|
||||
}
|
||||
}, [isAuthenticated, eventId])
|
||||
|
||||
const fetchEventDetails = async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const response = await apiClient.get(`${API_CONFIG.ENDPOINTS.VOTE_EVENTS}/${eventId}`)
|
||||
|
||||
if (response.data.success) {
|
||||
setEvent(response.data.data)
|
||||
} else {
|
||||
setError("Failed to fetch event details")
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Error fetching event details:', error)
|
||||
setError(error.response?.data?.errors || "Failed to fetch event details")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchVoteStatus = async () => {
|
||||
try {
|
||||
const response = await apiClient.get(`${API_CONFIG.ENDPOINTS.VOTE_EVENTS}/${eventId}/vote-status`)
|
||||
|
||||
if (response.data.success) {
|
||||
setVoteStatus(response.data.data)
|
||||
} else {
|
||||
setError("Failed to fetch voting status")
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Error fetching vote status:', error)
|
||||
setError(error.response?.data?.errors || "Failed to fetch voting status")
|
||||
}
|
||||
}
|
||||
|
||||
const handleVote = async () => {
|
||||
if (!selectedCandidate || !event) return
|
||||
|
||||
try {
|
||||
setIsVoting(true)
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
|
||||
const voteData: VoteRequest = {
|
||||
vote_event_id: event.id,
|
||||
candidate_id: selectedCandidate
|
||||
}
|
||||
|
||||
const response = await apiClient.post(API_CONFIG.ENDPOINTS.VOTES, voteData)
|
||||
|
||||
if (response.data.success) {
|
||||
setSuccess("Your vote has been recorded successfully!")
|
||||
setVoteStatus({ has_voted: true })
|
||||
// Refresh vote status
|
||||
setTimeout(() => {
|
||||
fetchVoteStatus()
|
||||
}, 1000)
|
||||
} else {
|
||||
setError(response.data.errors || "Failed to submit vote")
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Error submitting vote:', error)
|
||||
setError(error.response?.data?.errors || "Failed to submit vote. Please try again.")
|
||||
} finally {
|
||||
setIsVoting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCandidateSelect = (candidateId: string) => {
|
||||
setSelectedCandidate(candidateId)
|
||||
setError(null)
|
||||
}
|
||||
|
||||
// Show loading while checking authentication
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600 mx-auto mb-4"></div>
|
||||
<p className="text-gray-600">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Redirect to login if not authenticated
|
||||
if (!isAuthenticated) {
|
||||
router.push("/login")
|
||||
return null
|
||||
}
|
||||
|
||||
// Redirect to home if no event ID
|
||||
if (!eventId) {
|
||||
router.push("/")
|
||||
return null
|
||||
}
|
||||
|
||||
// Check if event is still active and voting is open
|
||||
const isEventActive = event && new Date() >= new Date(event.start_date) && new Date() <= new Date(event.end_date)
|
||||
const canVote = event && event.is_voting_open && isEventActive && !voteStatus?.has_voted
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
|
||||
{/* Header */}
|
||||
<header className="bg-white shadow-sm border-b">
|
||||
<div className="container mx-auto px-4 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link href="/">
|
||||
<Button variant="ghost" size="sm" className="gap-2">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to Home
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="h-6 w-px bg-gray-300"></div>
|
||||
<h1 className="text-xl font-semibold text-gray-900">Voting Interface</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||
<User className="h-4 w-4" />
|
||||
<span>{user?.name}</span>
|
||||
</div>
|
||||
<Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
|
||||
<Shield className="h-3 w-3 mr-1" />
|
||||
Authenticated
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
{isLoading ? (
|
||||
<div className="text-center py-16">
|
||||
<div className="relative">
|
||||
<div className="animate-spin rounded-full h-16 w-16 border-4 border-blue-200 border-t-blue-600 mx-auto mb-6"></div>
|
||||
</div>
|
||||
<p className="text-gray-600 text-lg">Loading event details...</p>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<Alert className="border-red-200 bg-red-50">
|
||||
<AlertCircle className="h-4 w-4 text-red-600" />
|
||||
<AlertDescription className="text-red-800">
|
||||
{error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<div className="mt-4 text-center">
|
||||
<Button onClick={() => window.location.reload()} variant="outline">
|
||||
Try Again
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : event ? (
|
||||
<div className="max-w-4xl mx-auto space-y-8">
|
||||
{/* Event Header */}
|
||||
<Card className="bg-white shadow-lg border-0">
|
||||
<CardHeader className="text-center pb-6">
|
||||
<div className="flex items-center justify-center gap-2 mb-4">
|
||||
{event.is_voting_open && isEventActive ? (
|
||||
<Badge className="bg-green-100 text-green-800 border-green-200">
|
||||
<Timer className="h-3 w-3 mr-1" />
|
||||
Voting Open
|
||||
</Badge>
|
||||
) : !isEventActive ? (
|
||||
<Badge className="bg-gray-100 text-gray-800 border-gray-200">
|
||||
<Clock className="h-3 w-3 mr-1" />
|
||||
Event Ended
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge className="bg-blue-100 text-blue-800 border-blue-200">
|
||||
<Clock className="h-3 w-3 mr-1" />
|
||||
Coming Soon
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-3xl font-bold text-gray-900 mb-3">
|
||||
{event.title}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-lg text-gray-600 max-w-2xl mx-auto">
|
||||
{event.description}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="text-center">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 text-sm text-gray-600">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Clock className="h-4 w-4 text-blue-600" />
|
||||
<span>Start: {new Date(event.start_date).toLocaleDateString('id-ID', {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Clock className="h-4 w-4 text-red-600" />
|
||||
<span>End: {new Date(event.end_date).toLocaleDateString('id-ID', {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Voting Status - Only show if user hasn't voted */}
|
||||
{voteStatus && !voteStatus.has_voted && (
|
||||
<Card className="border-0 shadow-lg bg-blue-50 border-blue-200">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<Vote className="h-6 w-6 text-blue-600" />
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold text-blue-800">Ready to vote</h3>
|
||||
<p className="text-blue-600">Please select your preferred candidate below</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Success Message */}
|
||||
{success && (
|
||||
<Alert className="border-green-200 bg-green-50">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-800">
|
||||
{success}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Candidates Section - Only show if user hasn't voted */}
|
||||
{!voteStatus?.has_voted && event.candidates && event.candidates.length > 0 ? (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">Candidates</h2>
|
||||
<p className="text-gray-600">
|
||||
Choose your preferred candidate by clicking on their card
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{event.candidates.map((candidate) => (
|
||||
<Card
|
||||
key={candidate.id}
|
||||
className={`cursor-pointer transition-all duration-300 border-2 hover:shadow-lg ${
|
||||
selectedCandidate === candidate.id
|
||||
? 'border-blue-500 bg-blue-50 shadow-lg'
|
||||
: 'border-gray-200 hover:border-blue-300'
|
||||
}`}
|
||||
onClick={() => handleCandidateSelect(candidate.id)}
|
||||
>
|
||||
<CardHeader className="text-center pb-4">
|
||||
<div className="w-20 h-20 mx-auto mb-4 rounded-full bg-gradient-to-br from-blue-100 to-purple-100 flex items-center justify-center">
|
||||
{candidate.image_url ? (
|
||||
<img
|
||||
src={candidate.image_url}
|
||||
alt={candidate.name}
|
||||
className="w-full h-full rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<ImageIcon className="h-8 w-8 text-gray-400" />
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-xl font-bold text-gray-900">
|
||||
{candidate.name}
|
||||
</CardTitle>
|
||||
{candidate.description && (
|
||||
<CardDescription className="text-gray-600">
|
||||
{candidate.description}
|
||||
</CardDescription>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="text-center">
|
||||
{selectedCandidate === candidate.id && (
|
||||
<div className="mb-4">
|
||||
<Badge className="bg-blue-100 text-blue-800 border-blue-200">
|
||||
<CheckCircle2 className="h-3 w-3 mr-1" />
|
||||
Selected
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Voting Button */}
|
||||
{canVote && (
|
||||
<div className="text-center pt-6">
|
||||
<Button
|
||||
onClick={handleVote}
|
||||
disabled={!selectedCandidate || isVoting}
|
||||
size="lg"
|
||||
className="bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-105 active:scale-95 px-8 py-3 text-lg"
|
||||
>
|
||||
{isVoting ? (
|
||||
<>
|
||||
<Loader2 className="h-5 w-5 mr-2 animate-spin" />
|
||||
Submitting Vote...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Vote className="h-5 w-5 mr-2" />
|
||||
Submit Vote
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{!selectedCandidate && (
|
||||
<p className="text-sm text-gray-500 mt-2">
|
||||
Please select a candidate first
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Cannot Vote Messages */}
|
||||
{!canVote && (
|
||||
<div className="text-center pt-6">
|
||||
{!event.is_voting_open && (
|
||||
<Alert className="border-orange-200 bg-orange-50 max-w-md mx-auto">
|
||||
<AlertCircle className="h-4 w-4 text-orange-600" />
|
||||
<AlertDescription className="text-orange-800">
|
||||
Voting is currently closed for this event
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{!isEventActive && (
|
||||
<Alert className="border-gray-200 bg-gray-50 max-w-md mx-auto">
|
||||
<Clock className="h-4 w-4 text-gray-600" />
|
||||
<AlertDescription className="text-gray-800">
|
||||
This event has ended
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : voteStatus?.has_voted ? (
|
||||
/* Show message when user has already voted */
|
||||
<Card className="bg-green-50 border-green-200 shadow-lg border-0">
|
||||
<CardContent className="text-center py-16">
|
||||
<CheckCircle2 className="h-16 w-16 text-green-600 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-semibold text-green-800 mb-2">Vote Submitted Successfully!</h3>
|
||||
<p className="text-green-600 mb-6">
|
||||
Thank you for participating in this election. Your vote has been recorded.
|
||||
</p>
|
||||
<div className="flex flex-col sm:flex-row gap-3 justify-center">
|
||||
<Button variant="outline" onClick={() => router.push('/')}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
Back to Home
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
/* Show when no candidates available */
|
||||
<Card className="bg-white shadow-lg border-0">
|
||||
<CardContent className="text-center py-16">
|
||||
<User className="h-16 w-16 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2">No Candidates Available</h3>
|
||||
<p className="text-gray-600 mb-6">
|
||||
There are no candidates registered for this voting event yet.
|
||||
</p>
|
||||
<Button variant="outline" onClick={() => router.push('/')}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
Back to Home
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-16">
|
||||
<AlertCircle className="h-16 w-16 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2">Event Not Found</h3>
|
||||
<p className="text-gray-600 mb-6">
|
||||
The voting event you're looking for could not be found.
|
||||
</p>
|
||||
<Button onClick={() => router.push('/')} variant="outline">
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
Back to Home
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function VotePage() {
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600 mx-auto mb-4"></div>
|
||||
<p className="text-gray-600">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
}>
|
||||
<VotePageContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user