This commit is contained in:
g
2025-02-07 21:33:13 +00:00
parent 8900bbcc76
commit 891f57d729
50 changed files with 165 additions and 444 deletions

View File

@@ -0,0 +1,301 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Eye,
Loader2,
CheckCircle2,
XCircle,
ChevronLeft,
ChevronRight,
ArrowUpDown,
Truck,
} from "lucide-react";
import Link from "next/link";
import { clientFetch } from '@/lib/client-utils';
import { toast } from "sonner";
import { Checkbox } from "@/components/ui/checkbox";
interface Order {
_id: string;
orderId: string;
status: string;
totalPrice: number;
createdAt: string;
telegramUsername?: string;
}
type SortableColumns = "orderId" | "totalPrice" | "status" | "createdAt";
export default function OrderTable() {
const [orders, setOrders] = useState<Order[]>([]);
const [loading, setLoading] = useState(true);
const [statusFilter, setStatusFilter] = useState("all");
const [currentPage, setCurrentPage] = useState(1);
const [sortConfig, setSortConfig] = useState<{
column: SortableColumns;
direction: "asc" | "desc";
}>({ column: "createdAt", direction: "desc" });
const [selectedOrders, setSelectedOrders] = useState<Set<string>>(new Set());
const ITEMS_PER_PAGE = 10;
// Fetch orders with error handling
const fetchOrders = useCallback(async () => {
try {
setLoading(true);
const data = await clientFetch("/orders");
setOrders(data.orders || []);
} catch (error) {
toast.error("Failed to fetch orders");
console.error("Fetch error:", error);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
// Derived data calculations
const filteredOrders = orders.filter(
(order) => statusFilter === "all" || order.status === statusFilter
);
const sortedOrders = [...filteredOrders].sort((a, b) => {
const aValue = a[sortConfig.column];
const bValue = b[sortConfig.column];
if (typeof aValue === "string" && typeof bValue === "string") {
return sortConfig.direction === "asc"
? aValue.localeCompare(bValue)
: bValue.localeCompare(aValue);
}
if (typeof aValue === "number" && typeof bValue === "number") {
return sortConfig.direction === "asc" ? aValue - bValue : bValue - aValue;
}
return 0;
});
const totalPages = Math.ceil(sortedOrders.length / ITEMS_PER_PAGE);
const paginatedOrders = sortedOrders.slice(
(currentPage - 1) * ITEMS_PER_PAGE,
currentPage * ITEMS_PER_PAGE
);
// Handlers
const handleSort = (column: SortableColumns) => {
setSortConfig(prev => ({
column,
direction: prev.column === column && prev.direction === "asc" ? "desc" : "asc"
}));
};
const toggleSelection = (orderId: string) => {
setSelectedOrders(prev => {
const newSet = new Set(prev);
newSet.has(orderId) ? newSet.delete(orderId) : newSet.add(orderId);
return newSet;
});
};
const toggleAll = () => {
if (selectedOrders.size === paginatedOrders.length) {
setSelectedOrders(new Set());
} else {
setSelectedOrders(new Set(paginatedOrders.map(o => o._id)));
}
};
const markAsShipped = async () => {
if (selectedOrders.size === 0) {
toast.warning("Please select orders to mark as shipped");
return;
}
try {
await clientFetch("/orders/mark-shipped", {
method: "POST",
body: JSON.stringify({ orderIds: Array.from(selectedOrders) })
});
setOrders(prev =>
prev.map(order =>
selectedOrders.has(order._id)
? { ...order, status: "shipped" }
: order
)
);
setSelectedOrders(new Set());
toast.success("Selected orders marked as shipped");
} catch (error) {
toast.error("Failed to update orders");
console.error("Shipping error:", error);
}
};
// Status display configuration
const statusConfig = {
paid: { icon: CheckCircle2, color: "text-green-500" },
unpaid: { icon: XCircle, color: "text-red-500" },
confirming: { icon: Loader2, color: "text-yellow-500 -" },
shipped: { icon: Truck, color: "text-blue-500" },
completed: { icon: CheckCircle2, color: "text-gray-500" },
disputed: { icon: XCircle, color: "text-orange-500" },
cancelled: { icon: XCircle, color: "text-gray-400" }
};
return (
<div className="rounded-lg border shadow-sm overflow-hidden">
{/* Toolbar */}
<div className="p-4 flex justify-between items-center border-b">
<Select value={statusFilter} onValueChange={setStatusFilter}>
<SelectTrigger className="w-40">
<SelectValue placeholder="Filter Status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Statuses</SelectItem>
{Object.keys(statusConfig).map(status => (
<SelectItem key={status} value={status}>
{status.charAt(0).toUpperCase() + status.slice(1)}
</SelectItem>
))}
</SelectContent>
</Select>
<Button onClick={markAsShipped} disabled={selectedOrders.size === 0}>
<Truck className="mr-2 h-5 w-5" />
Mark Shipped ({selectedOrders.size})
</Button>
</div>
{/* Table */}
<Table>
<TableHeader className="bg-muted">
<TableRow>
<TableHead className="w-12">
<Checkbox
checked={selectedOrders.size > 0 && selectedOrders.size === paginatedOrders.length}
onCheckedChange={toggleAll}
/>
</TableHead>
<TableHead className="cursor-pointer" onClick={() => handleSort("orderId")}>
Order ID <ArrowUpDown className="ml-2 inline h-4 w-4" />
</TableHead>
<TableHead className="cursor-pointer" onClick={() => handleSort("totalPrice")}>
Total <ArrowUpDown className="ml-2 inline h-4 w-4" />
</TableHead>
<TableHead className="cursor-pointer" onClick={() => handleSort("status")}>
Status <ArrowUpDown className="ml-2 inline h-4 w-4" />
</TableHead>
<TableHead className="cursor-pointer" onClick={() => handleSort("createdAt")}>
Date <ArrowUpDown className="ml-2 inline h-4 w-4" />
</TableHead>
<TableHead>Buyer</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={7} className="text-center h-24">
<Loader2 className="h-8 w-8 animate-spin mx-auto" />
</TableCell>
</TableRow>
) : paginatedOrders.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center h-24">
No orders found
</TableCell>
</TableRow>
) : (
paginatedOrders.map(order => {
const StatusIcon = statusConfig[order.status as keyof typeof statusConfig]?.icon || XCircle;
const statusColor = statusConfig[order.status as keyof typeof statusConfig]?.color || "text-red-500";
return (
<TableRow key={order._id}>
<TableCell>
<Checkbox
checked={selectedOrders.has(order._id)}
onCheckedChange={() => toggleSelection(order._id)}
/>
</TableCell>
<TableCell>#{order.orderId}</TableCell>
<TableCell>£{order.totalPrice.toFixed(2)}</TableCell>
<TableCell>
<div className={`flex items-center ${statusColor}`}>
<StatusIcon className="h-4 w-4 mr-2" />
{order.status.charAt(0).toUpperCase() + order.status.slice(1)}
</div>
</TableCell>
<TableCell>
{new Date(order.createdAt).toLocaleDateString("en-GB")}
</TableCell>
<TableCell>
{order.telegramUsername ? `@${order.telegramUsername}` : "-"}
</TableCell>
<TableCell className="text-right">
<Button variant="ghost" size="sm" asChild>
<Link href={`/dashboard/orders/${order._id}`}>
<Eye className="h-4 w-4" />
</Link>
</Button>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
{/* Pagination */}
<div className="p-4 flex justify-between items-center border-t">
<div className="flex-1 text-sm text-muted-foreground">
{selectedOrders.size} of {sortedOrders.length} row(s) selected
</div>
<div className="flex items-center gap-4">
<Button
variant="outline"
size="sm"
disabled={currentPage === 1}
onClick={() => setCurrentPage(p => Math.max(p - 1, 1))}
>
<ChevronLeft className="h-4 w-4 mr-2" /> Previous
</Button>
<span className="text-sm font-medium">
Page {currentPage} of {totalPages}
</span>
<Button
variant="outline"
size="sm"
disabled={currentPage >= totalPages}
onClick={() => setCurrentPage(p => p + 1)}
>
Next <ChevronRight className="h-4 w-4 ml-2" />
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,75 @@
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Edit, Trash } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Product } from "@/models/products";
interface ProductTableProps {
products: Product[];
loading: boolean;
onEdit: (product: Product) => void;
onDelete: (productId: string) => void; // Added onDelete prop
getCategoryNameById: (categoryId: string) => string;
}
const ProductTable = ({
products,
loading,
onEdit,
onDelete,
getCategoryNameById
}: ProductTableProps) => {
return (
<div className="rounded-lg border dark:border-zinc-700 shadow-sm overflow-hidden">
<Table className="relative">
<TableHeader className="bg-gray-50 dark:bg-zinc-800/50">
<TableRow className="hover:bg-transparent">
<TableHead className="w-[200px]">Product</TableHead>
<TableHead className="text-center">Category</TableHead>
<TableHead className="text-center">Unit</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
Array.from({ length: 1 }).map((_, index) => (
<TableRow key={index}>
<TableCell>Loading...</TableCell>
<TableCell>Loading...</TableCell>
<TableCell>Loading...</TableCell>
<TableCell>Loading...</TableCell>
</TableRow>
))
) : products.length > 0 ? (
products.map((product) => (
<TableRow key={product._id} className="transition-colors hover:bg-gray-50 dark:hover:bg-zinc-800/70">
<TableCell className="font-medium">{product.name}</TableCell>
<TableCell className="text-center">
{getCategoryNameById(product.category)} {/* Display category name */}
</TableCell>
<TableCell className="text-center uppercase text-sm">{product.unitType}</TableCell>
<TableCell className="text-right">
<div className="flex justify-end space-x-2">
<Button size="sm" variant="ghost" onClick={() => onEdit(product)}>
<Edit className="h-4 w-4" />
</Button>
<Button size="sm" variant="ghost" className="text-red-600 hover:text-red-700 dark:text-red-400" onClick={() => onDelete(product._id ?? "")}>
<Trash className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={4} className="h-24 text-center">
No products found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
};
export default ProductTable;

View File

@@ -0,0 +1,86 @@
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Edit, Trash } from "lucide-react";
import { ShippingMethod } from "@/lib/types";
interface ShippingTableProps {
shippingMethods: ShippingMethod[];
loading: boolean;
onEditShipping: (method: ShippingMethod) => void;
onDeleteShipping: (_id: string) => void;
}
export const ShippingTable: React.FC<ShippingTableProps> = ({
shippingMethods,
loading,
onEditShipping,
onDeleteShipping,
}) => {
return (
<div className="rounded-lg border dark:border-zinc-700 shadow-sm overflow-hidden">
<Table className="relative">
<TableHeader className="bg-gray-50 dark:bg-zinc-800/50">
<TableRow className="hover:bg-transparent">
<TableHead className="w-[60%]">Name</TableHead>
<TableHead className="text-center">Price</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={3} className="text-center">
<Skeleton className="h-4 w-[200px]" />
</TableCell>
</TableRow>
) : shippingMethods.length > 0 ? (
shippingMethods.map((method) => (
<TableRow
key={method._id}
className="transition-colors hover:bg-gray-50 dark:hover:bg-zinc-800/70"
>
<TableCell className="font-medium">{method.name}</TableCell>
<TableCell className="text-center">£{method.price}</TableCell>
<TableCell className="text-right">
<div className="flex justify-end">
<Button
size="sm"
variant="ghost"
className="text-blue-600 hover:text-blue-700 dark:text-blue-400"
onClick={() => onEditShipping(method)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="ghost"
className="text-red-600 hover:text-red-700 dark:text-red-400"
onClick={() => onDeleteShipping(method._id ?? "")}
>
<Trash className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={3} className="h-24 text-center">
No shipping methods found
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
};