Add pagination and server-side search to the whitelist page
Implement server-side pagination and search functionality for the whitelist page, including API route updates, storage layer modifications, and frontend enhancements in `Whitelist.tsx`. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 7a657272-55ba-4a79-9a2e-f1ed9bc7a528 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: 1971ce5e-1b30-49d5-90b7-63e075ccb563 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/449cf7c4-c97a-45ae-8234-e5c5b8d6a84f/7a657272-55ba-4a79-9a2e-f1ed9bc7a528/RyXWGQA
This commit is contained in:
parent
1f9ee3919f
commit
dd0e44f78f
@ -2,9 +2,9 @@ import { useQuery, useMutation } from "@tanstack/react-query";
|
|||||||
import { queryClient, apiRequest } from "@/lib/queryClient";
|
import { queryClient, apiRequest } from "@/lib/queryClient";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Shield, Plus, Trash2, CheckCircle2, XCircle, Search } from "lucide-react";
|
import { Shield, Plus, Trash2, CheckCircle2, XCircle, Search, ChevronLeft, ChevronRight } from "lucide-react";
|
||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import { useState } from "react";
|
import { useState, useEffect, useMemo } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
@ -31,6 +31,8 @@ import {
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
|
||||||
|
const ITEMS_PER_PAGE = 50;
|
||||||
|
|
||||||
const whitelistFormSchema = insertWhitelistSchema.extend({
|
const whitelistFormSchema = insertWhitelistSchema.extend({
|
||||||
ipAddress: z.string()
|
ipAddress: z.string()
|
||||||
.min(7, "Inserisci un IP valido")
|
.min(7, "Inserisci un IP valido")
|
||||||
@ -41,10 +43,17 @@ const whitelistFormSchema = insertWhitelistSchema.extend({
|
|||||||
}, "Ogni ottetto deve essere tra 0 e 255"),
|
}, "Ogni ottetto deve essere tra 0 e 255"),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
interface WhitelistResponse {
|
||||||
|
items: Whitelist[];
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
export default function WhitelistPage() {
|
export default function WhitelistPage() {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
|
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
|
||||||
const [searchQuery, setSearchQuery] = useState("");
|
const [searchInput, setSearchInput] = useState("");
|
||||||
|
const [debouncedSearch, setDebouncedSearch] = useState("");
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
const form = useForm<z.infer<typeof whitelistFormSchema>>({
|
const form = useForm<z.infer<typeof whitelistFormSchema>>({
|
||||||
resolver: zodResolver(whitelistFormSchema),
|
resolver: zodResolver(whitelistFormSchema),
|
||||||
@ -56,16 +65,33 @@ export default function WhitelistPage() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: whitelist, isLoading } = useQuery<Whitelist[]>({
|
useEffect(() => {
|
||||||
queryKey: ["/api/whitelist"],
|
const timer = setTimeout(() => {
|
||||||
|
setDebouncedSearch(searchInput);
|
||||||
|
setCurrentPage(1);
|
||||||
|
}, 300);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [searchInput]);
|
||||||
|
|
||||||
|
const queryParams = useMemo(() => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.set("limit", ITEMS_PER_PAGE.toString());
|
||||||
|
params.set("offset", ((currentPage - 1) * ITEMS_PER_PAGE).toString());
|
||||||
|
if (debouncedSearch.trim()) {
|
||||||
|
params.set("search", debouncedSearch.trim());
|
||||||
|
}
|
||||||
|
return params.toString();
|
||||||
|
}, [currentPage, debouncedSearch]);
|
||||||
|
|
||||||
|
const { data, isLoading } = useQuery<WhitelistResponse>({
|
||||||
|
queryKey: ["/api/whitelist", currentPage, debouncedSearch],
|
||||||
|
queryFn: () => fetch(`/api/whitelist?${queryParams}`).then(r => r.json()),
|
||||||
|
refetchInterval: 10000,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Filter whitelist based on search query
|
const whitelistItems = data?.items || [];
|
||||||
const filteredWhitelist = whitelist?.filter((item) =>
|
const totalCount = data?.total || 0;
|
||||||
item.ipAddress.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
const totalPages = Math.ceil(totalCount / ITEMS_PER_PAGE);
|
||||||
item.reason?.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
|
||||||
item.comment?.toLowerCase().includes(searchQuery.toLowerCase())
|
|
||||||
);
|
|
||||||
|
|
||||||
const addMutation = useMutation({
|
const addMutation = useMutation({
|
||||||
mutationFn: async (data: z.infer<typeof whitelistFormSchema>) => {
|
mutationFn: async (data: z.infer<typeof whitelistFormSchema>) => {
|
||||||
@ -203,9 +229,9 @@ export default function WhitelistPage() {
|
|||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
<Input
|
<Input
|
||||||
placeholder="Cerca per IP, motivo o note..."
|
placeholder="Cerca per IP, motivo, note o sorgente..."
|
||||||
value={searchQuery}
|
value={searchInput}
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => setSearchInput(e.target.value)}
|
||||||
className="pl-9"
|
className="pl-9"
|
||||||
data-testid="input-search-whitelist"
|
data-testid="input-search-whitelist"
|
||||||
/>
|
/>
|
||||||
@ -215,9 +241,36 @@ export default function WhitelistPage() {
|
|||||||
|
|
||||||
<Card data-testid="card-whitelist">
|
<Card data-testid="card-whitelist">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="flex items-center gap-2">
|
<CardTitle className="flex items-center justify-between gap-2 flex-wrap">
|
||||||
<Shield className="h-5 w-5" />
|
<div className="flex items-center gap-2">
|
||||||
IP Protetti ({filteredWhitelist?.length || 0}{searchQuery && whitelist ? ` di ${whitelist.length}` : ''})
|
<Shield className="h-5 w-5" />
|
||||||
|
IP Protetti ({totalCount})
|
||||||
|
</div>
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<div className="flex items-center gap-2 text-sm font-normal">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
data-testid="button-prev-page"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<span data-testid="text-pagination">
|
||||||
|
Pagina {currentPage} di {totalPages}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
data-testid="button-next-page"
|
||||||
|
>
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
@ -225,9 +278,9 @@ export default function WhitelistPage() {
|
|||||||
<div className="text-center py-8 text-muted-foreground" data-testid="text-loading">
|
<div className="text-center py-8 text-muted-foreground" data-testid="text-loading">
|
||||||
Caricamento...
|
Caricamento...
|
||||||
</div>
|
</div>
|
||||||
) : filteredWhitelist && filteredWhitelist.length > 0 ? (
|
) : whitelistItems.length > 0 ? (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{filteredWhitelist.map((item) => (
|
{whitelistItems.map((item) => (
|
||||||
<div
|
<div
|
||||||
key={item.id}
|
key={item.id}
|
||||||
className="p-4 rounded-lg border hover-elevate"
|
className="p-4 rounded-lg border hover-elevate"
|
||||||
@ -272,12 +325,45 @@ export default function WhitelistPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
|
{/* Bottom pagination */}
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<div className="flex items-center justify-center gap-4 mt-6 pt-4 border-t">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
data-testid="button-prev-page-bottom"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4 mr-1" />
|
||||||
|
Precedente
|
||||||
|
</Button>
|
||||||
|
<span className="text-sm text-muted-foreground" data-testid="text-pagination-bottom">
|
||||||
|
Pagina {currentPage} di {totalPages} ({totalCount} totali)
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
data-testid="button-next-page-bottom"
|
||||||
|
>
|
||||||
|
Successiva
|
||||||
|
<ChevronRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="text-center py-12 text-muted-foreground" data-testid="text-empty">
|
<div className="text-center py-12 text-muted-foreground" data-testid="text-empty">
|
||||||
<Shield className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
<Shield className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
||||||
<p className="font-medium">Nessun IP in whitelist</p>
|
<p className="font-medium">Nessun IP in whitelist</p>
|
||||||
<p className="text-sm mt-2">Aggiungi indirizzi IP fidati per proteggerli dal blocco automatico</p>
|
{debouncedSearch ? (
|
||||||
|
<p className="text-sm mt-2">Prova con un altro termine di ricerca</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm mt-2">Aggiungi indirizzi IP fidati per proteggerli dal blocco automatico</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@ -122,8 +122,12 @@ export async function registerRoutes(app: Express): Promise<Server> {
|
|||||||
// Whitelist
|
// Whitelist
|
||||||
app.get("/api/whitelist", async (req, res) => {
|
app.get("/api/whitelist", async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const whitelist = await storage.getAllWhitelist();
|
const limit = parseInt(req.query.limit as string) || 50;
|
||||||
res.json(whitelist);
|
const offset = parseInt(req.query.offset as string) || 0;
|
||||||
|
const search = req.query.search as string || undefined;
|
||||||
|
|
||||||
|
const result = await storage.getAllWhitelist({ limit, offset, search });
|
||||||
|
res.json(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[DB ERROR] Failed to fetch whitelist:', error);
|
console.error('[DB ERROR] Failed to fetch whitelist:', error);
|
||||||
res.status(500).json({ error: "Failed to fetch whitelist" });
|
res.status(500).json({ error: "Failed to fetch whitelist" });
|
||||||
@ -480,7 +484,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
|
|||||||
const routers = await storage.getAllRouters();
|
const routers = await storage.getAllRouters();
|
||||||
const detectionsResult = await storage.getAllDetections({ limit: 1000 });
|
const detectionsResult = await storage.getAllDetections({ limit: 1000 });
|
||||||
const recentLogs = await storage.getRecentLogs(1000);
|
const recentLogs = await storage.getRecentLogs(1000);
|
||||||
const whitelist = await storage.getAllWhitelist();
|
const whitelistResult = await storage.getAllWhitelist({ limit: 1 });
|
||||||
const latestTraining = await storage.getLatestTraining();
|
const latestTraining = await storage.getLatestTraining();
|
||||||
|
|
||||||
const detectionsList = detectionsResult.detections;
|
const detectionsList = detectionsResult.detections;
|
||||||
@ -503,7 +507,7 @@ export async function registerRoutes(app: Express): Promise<Server> {
|
|||||||
recent: recentLogs.length
|
recent: recentLogs.length
|
||||||
},
|
},
|
||||||
whitelist: {
|
whitelist: {
|
||||||
total: whitelist.length
|
total: whitelistResult.total
|
||||||
},
|
},
|
||||||
latestTraining: latestTraining
|
latestTraining: latestTraining
|
||||||
});
|
});
|
||||||
|
|||||||
@ -55,7 +55,7 @@ export interface IStorage {
|
|||||||
getUnblockedDetections(): Promise<Detection[]>;
|
getUnblockedDetections(): Promise<Detection[]>;
|
||||||
|
|
||||||
// Whitelist
|
// Whitelist
|
||||||
getAllWhitelist(): Promise<Whitelist[]>;
|
getAllWhitelist(options?: { limit?: number; offset?: number; search?: string }): Promise<{ items: Whitelist[]; total: number }>;
|
||||||
getWhitelistByIp(ipAddress: string): Promise<Whitelist | undefined>;
|
getWhitelistByIp(ipAddress: string): Promise<Whitelist | undefined>;
|
||||||
createWhitelist(whitelist: InsertWhitelist): Promise<Whitelist>;
|
createWhitelist(whitelist: InsertWhitelist): Promise<Whitelist>;
|
||||||
deleteWhitelist(id: string): Promise<boolean>;
|
deleteWhitelist(id: string): Promise<boolean>;
|
||||||
@ -271,12 +271,40 @@ export class DatabaseStorage implements IStorage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Whitelist
|
// Whitelist
|
||||||
async getAllWhitelist(): Promise<Whitelist[]> {
|
async getAllWhitelist(options?: { limit?: number; offset?: number; search?: string }): Promise<{ items: Whitelist[]; total: number }> {
|
||||||
return await db
|
const limit = options?.limit || 50;
|
||||||
|
const offset = options?.offset || 0;
|
||||||
|
const search = options?.search?.trim().toLowerCase();
|
||||||
|
|
||||||
|
const conditions: any[] = [eq(whitelist.active, true)];
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
conditions.push(
|
||||||
|
sql`(
|
||||||
|
LOWER(${whitelist.ipAddress}) LIKE ${'%' + search + '%'}
|
||||||
|
OR LOWER(COALESCE(${whitelist.reason}, '')) LIKE ${'%' + search + '%'}
|
||||||
|
OR LOWER(COALESCE(${whitelist.comment}, '')) LIKE ${'%' + search + '%'}
|
||||||
|
OR LOWER(COALESCE(${whitelist.source}, '')) LIKE ${'%' + search + '%'}
|
||||||
|
)`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const whereClause = and(...conditions);
|
||||||
|
|
||||||
|
const [countResult] = await db
|
||||||
|
.select({ count: sql<number>`cast(count(*) as integer)` })
|
||||||
|
.from(whitelist)
|
||||||
|
.where(whereClause);
|
||||||
|
|
||||||
|
const items = await db
|
||||||
.select()
|
.select()
|
||||||
.from(whitelist)
|
.from(whitelist)
|
||||||
.where(eq(whitelist.active, true))
|
.where(whereClause)
|
||||||
.orderBy(desc(whitelist.createdAt));
|
.orderBy(desc(whitelist.createdAt))
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset);
|
||||||
|
|
||||||
|
return { items, total: countResult.count };
|
||||||
}
|
}
|
||||||
|
|
||||||
async getWhitelistByIp(ipAddress: string): Promise<Whitelist | undefined> {
|
async getWhitelistByIp(ipAddress: string): Promise<Whitelist | undefined> {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user