Refactor admin vendors page to use client-side fetching and pagination

Migrates the admin vendors page to use client-side data fetching with pagination, search, and improved loading states. Updates the vendor table to show last login, status, and admin badges. Also, optimizes the broadcast dialog by lazy-loading the ReactMarkdown component for preview rendering.
This commit is contained in:
g
2025-12-31 06:54:37 +00:00
parent 18ac2224ca
commit 66e95438fe
4 changed files with 248 additions and 92 deletions

79
UPGRADE_NEXT16.md Normal file
View File

@@ -0,0 +1,79 @@
# Next.js 16 Upgrade Guide
## Current Status
- **Current Version**: Next.js 15.2.6
- **Target Version**: Next.js 16.1.1
- **React Version**: 19.0.0 ✅ (Compatible)
## Upgrade Steps
### 1. Backup First
```bash
git add .
git commit -m "Before Next.js 16 upgrade"
```
### 2. Update Dependencies
```bash
npm install next@16 react@19 react-dom@19 eslint-config-next@16
```
### 3. Update Related Packages
```bash
npm install @next/bundle-analyzer@latest
```
### 4. Test Build
```bash
npm run build
```
### 5. Test Development Server
```bash
npm run dev
```
## Potential Breaking Changes
### 1. Route Handlers
- Check all API routes in `app/api/` for compatibility
- Ensure async/await patterns are correct
### 2. Server Components
- Verify all server components work correctly
- Check for any client component boundaries
### 3. Image Optimization
- `next/image` may have minor API changes
- Check image imports
### 4. Font Loading
- `next/font` should work the same, but verify
## Performance Improvements Expected
1. **Faster Builds**: 10-20% faster production builds
2. **Better Caching**: Improved static generation caching
3. **Smaller Bundles**: Better tree-shaking and code splitting
4. **Faster Dev Server**: Turbopack improvements
## Rollback Plan
If issues occur:
```bash
npm install next@15.2.6 react@19 react-dom@19 eslint-config-next@15.2.3
```
## Testing Checklist
- [ ] Build completes successfully
- [ ] Dev server starts without errors
- [ ] All pages load correctly
- [ ] API routes work
- [ ] Images load properly
- [ ] Fonts load correctly
- [ ] Admin dashboard works
- [ ] Order management works
- [ ] Analytics charts render
- [ ] Authentication works

View File

@@ -1,55 +1,83 @@
import React from "react"; "use client";
import React, { useState, useEffect, useCallback } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Search, MoreHorizontal, UserCheck, UserX, Mail } from "lucide-react"; import { Search, MoreHorizontal, UserCheck, UserX, Mail, Loader2 } from "lucide-react";
import { fetchServer } from "@/lib/api"; import { fetchClient } from "@/lib/api-client";
import { useToast } from "@/hooks/use-toast";
interface Vendor { interface Vendor {
_id: string; _id: string;
username: string; username: string;
email?: string;
storeId?: string; storeId?: string;
pgpKey?: string;
createdAt?: string; createdAt?: string;
currentToken?: string; lastLogin?: string;
isAdmin?: boolean; isAdmin?: boolean;
isActive: boolean;
} }
export default async function AdminVendorsPage() { interface PaginationResponse {
let vendors: Vendor[] = []; success: boolean;
let error: string | null = null; vendors: Vendor[];
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
hasNextPage: boolean;
hasPrevPage: boolean;
};
}
export default function AdminVendorsPage() {
const { toast } = useToast();
const [loading, setLoading] = useState(true);
const [vendors, setVendors] = useState<Vendor[]>([]);
const [page, setPage] = useState(1);
const [pagination, setPagination] = useState<PaginationResponse['pagination'] | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const fetchVendors = useCallback(async () => {
try { try {
vendors = await fetchServer<Vendor[]>("/admin/vendors"); setLoading(true);
} catch (err) { const params = new URLSearchParams({
console.error("Failed to fetch vendors:", err); page: page.toString(),
error = "Failed to load vendors"; limit: '25'
});
const data = await fetchClient<PaginationResponse>(`/admin/vendors?${params.toString()}`);
setVendors(data.vendors);
setPagination(data.pagination);
} catch (error: any) {
console.error("Failed to fetch vendors:", error);
toast({
title: "Error",
description: error.message || "Failed to load vendors",
variant: "destructive",
});
} finally {
setLoading(false);
} }
}, [page, toast]);
if (error) { useEffect(() => {
return ( fetchVendors();
<div className="space-y-6"> }, [fetchVendors]);
<div>
<h1 className="text-2xl font-semibold tracking-tight">All Vendors</h1>
<p className="text-sm text-muted-foreground mt-1">Manage vendor accounts and permissions</p>
</div>
<Card>
<CardContent className="pt-6">
<div className="text-center text-red-500">
<p>{error}</p>
</div>
</CardContent>
</Card>
</div>
);
}
const activeVendors = vendors.filter(v => v.currentToken); const filteredVendors = searchQuery.trim()
? vendors.filter(v =>
v.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
(v.storeId && v.storeId.toString().toLowerCase().includes(searchQuery.toLowerCase()))
)
: vendors;
const activeVendors = vendors.filter(v => v.isActive);
const suspendedVendors = vendors.filter(v => !v.isActive);
const adminVendors = vendors.filter(v => v.isAdmin); const adminVendors = vendors.filter(v => v.isAdmin);
const suspendedVendors = vendors.filter(v => !v.currentToken); const totalVendors = pagination?.total || vendors.length;
return ( return (
<div className="space-y-6"> <div className="space-y-6">
@@ -65,7 +93,7 @@ export default async function AdminVendorsPage() {
<CardTitle className="text-sm font-medium">Total Vendors</CardTitle> <CardTitle className="text-sm font-medium">Total Vendors</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold">{vendors.length}</div> <div className="text-2xl font-bold">{totalVendors}</div>
<p className="text-xs text-muted-foreground">Registered vendors</p> <p className="text-xs text-muted-foreground">Registered vendors</p>
</CardContent> </CardContent>
</Card> </Card>
@@ -113,7 +141,12 @@ export default async function AdminVendorsPage() {
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<div className="relative"> <div className="relative">
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" /> <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
<Input placeholder="Search vendors..." className="pl-8 w-64" /> <Input
placeholder="Search vendors..."
className="pl-8 w-64"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div> </div>
<Button variant="outline" size="sm"> <Button variant="outline" size="sm">
<Mail className="h-4 w-4 mr-2" /> <Mail className="h-4 w-4 mr-2" />
@@ -123,6 +156,16 @@ export default async function AdminVendorsPage() {
</div> </div>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{loading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : filteredVendors.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
{searchQuery.trim() ? "No vendors found matching your search" : "No vendors found"}
</div>
) : (
<>
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow> <TableRow>
@@ -130,11 +173,12 @@ export default async function AdminVendorsPage() {
<TableHead>Store</TableHead> <TableHead>Store</TableHead>
<TableHead>Status</TableHead> <TableHead>Status</TableHead>
<TableHead>Join Date</TableHead> <TableHead>Join Date</TableHead>
<TableHead>Last Login</TableHead>
<TableHead className="text-right">Actions</TableHead> <TableHead className="text-right">Actions</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{vendors.map((vendor) => ( {filteredVendors.map((vendor) => (
<TableRow key={vendor._id}> <TableRow key={vendor._id}>
<TableCell> <TableCell>
<div className="font-medium">{vendor.username}</div> <div className="font-medium">{vendor.username}</div>
@@ -143,9 +187,9 @@ export default async function AdminVendorsPage() {
<TableCell> <TableCell>
<div className="flex flex-col space-y-1"> <div className="flex flex-col space-y-1">
<Badge <Badge
variant={vendor.currentToken ? "default" : "destructive"} variant={vendor.isActive ? "default" : "destructive"}
> >
{vendor.currentToken ? "active" : "suspended"} {vendor.isActive ? "active" : "suspended"}
</Badge> </Badge>
{vendor.isAdmin && ( {vendor.isAdmin && (
<Badge variant="secondary" className="text-xs"> <Badge variant="secondary" className="text-xs">
@@ -157,6 +201,9 @@ export default async function AdminVendorsPage() {
<TableCell> <TableCell>
{vendor.createdAt ? new Date(vendor.createdAt).toLocaleDateString() : 'N/A'} {vendor.createdAt ? new Date(vendor.createdAt).toLocaleDateString() : 'N/A'}
</TableCell> </TableCell>
<TableCell>
{vendor.lastLogin ? new Date(vendor.lastLogin).toLocaleDateString() : 'Never'}
</TableCell>
<TableCell className="text-right"> <TableCell className="text-right">
<div className="flex items-center justify-end space-x-2"> <div className="flex items-center justify-end space-x-2">
<Button variant="outline" size="sm"> <Button variant="outline" size="sm">
@@ -174,6 +221,33 @@ export default async function AdminVendorsPage() {
))} ))}
</TableBody> </TableBody>
</Table> </Table>
{pagination && pagination.totalPages > 1 && (
<div className="mt-4 flex items-center justify-between text-sm text-muted-foreground">
<span>
Page {pagination.page} of {pagination.totalPages} ({pagination.total} total)
</span>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setPage(p => Math.max(1, p - 1))}
disabled={!pagination.hasPrevPage || loading}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPage(p => p + 1)}
disabled={!pagination.hasNextPage || loading}
>
Next
</Button>
</div>
</div>
)}
</>
)}
</CardContent> </CardContent>
</Card> </Card>
</div> </div>

View File

@@ -1,15 +1,16 @@
"use client"; "use client";
import { useState, useRef } from "react"; import { useState, useRef, lazy, Suspense } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Send, Bold, Italic, Code, Link as LinkIcon, Image as ImageIcon, X, Eye, EyeOff, Package } from "lucide-react"; import { Send, Bold, Italic, Code, Link as LinkIcon, Image as ImageIcon, X, Eye, EyeOff, Package } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
import { clientFetch } from "@/lib/api"; import { clientFetch } from "@/lib/api";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import ReactMarkdown from 'react-markdown';
import ProductSelector from "./product-selector"; import ProductSelector from "./product-selector";
const ReactMarkdown = lazy(() => import('react-markdown'));
interface BroadcastDialogProps { interface BroadcastDialogProps {
open: boolean; open: boolean;
setOpen: (open: boolean) => void; setOpen: (open: boolean) => void;
@@ -265,7 +266,9 @@ __italic text__
{showPreview && broadcastMessage.trim() && ( {showPreview && broadcastMessage.trim() && (
<div className="border rounded-lg p-4 bg-background/50"> <div className="border rounded-lg p-4 bg-background/50">
<div className="prose prose-sm dark:prose-invert max-w-none"> <div className="prose prose-sm dark:prose-invert max-w-none">
<Suspense fallback={<div className="text-sm text-muted-foreground">Loading preview...</div>}>
<ReactMarkdown>{broadcastMessage}</ReactMarkdown> <ReactMarkdown>{broadcastMessage}</ReactMarkdown>
</Suspense>
</div> </div>
</div> </div>
)} )}

View File

@@ -1,4 +1,4 @@
{ {
"commitHash": "5f1e294", "commitHash": "18ac222",
"buildTime": "2025-12-31T06:44:25.736Z" "buildTime": "2025-12-31T06:46:19.353Z"
} }