1
0
Code Issues Pull Requests Actions Packages Projects Releases Wiki Activity Security Code Quality

Add custom page

This commit is contained in:
2025-07-06 16:24:34 +07:00
parent e8f76f395a
commit 815de2932b
28 changed files with 4457 additions and 22 deletions

View File

@@ -0,0 +1,210 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/database/database";
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
// Initialize database
await db.read();
// Parse dependant ID from params
const dependantId = parseInt(params.id);
if (isNaN(dependantId)) {
return NextResponse.json(
{
success: false,
message: "Invalid dependant ID provided",
},
{ status: 400 }
);
}
// Get customer dependants
const customerDependants = db.data!.customerDependants;
// Find the specific dependant
const dependant = customerDependants.find((d) => d.id === dependantId);
if (!dependant) {
return NextResponse.json(
{
success: false,
message: "Dependant not found",
},
{ status: 404 }
);
}
return NextResponse.json(
{
success: true,
data: dependant,
},
{ status: 200 }
);
} catch (error) {
console.error("Error fetching dependant:", error);
return NextResponse.json(
{
success: false,
message: "Failed to fetch dependant",
error: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
// Initialize database
await db.read();
// Parse dependant ID from params
const dependantId = parseInt(params.id);
if (isNaN(dependantId)) {
return NextResponse.json(
{
success: false,
message: "Invalid dependant ID provided",
},
{ status: 400 }
);
}
// Parse and validate request body
const body = await request.json();
console.log("Received dependant update data:", body);
// Find the dependant to update
const dependantIndex = db.data!.customerDependants.findIndex(
(d) => d.id === dependantId
);
if (dependantIndex === -1) {
return NextResponse.json(
{
success: false,
message: "Dependant not found",
},
{ status: 404 }
);
}
// Update dependant data
const updatedDependant = {
...db.data!.customerDependants[dependantIndex],
firstNameEn: body.dependantInfo.firstNameEn,
lastNameEn: body.dependantInfo.lastNameEn,
originAdd1: body.dependantInfo.originAdd1,
localAdd1: body.dependantInfo.localAdd1,
email: body.dependantContact.email,
mobile: body.dependantContact.mobile,
};
db.data!.customerDependants[dependantIndex] = updatedDependant;
// Save to database
await db.write();
console.log("Dependant updated successfully");
// Return success response
return NextResponse.json(
{
success: true,
message: "Dependant updated successfully",
data: updatedDependant,
},
{ status: 200 }
);
} catch (error) {
console.error("Error updating dependant:", error);
return NextResponse.json(
{
success: false,
message: "Failed to update dependant",
error: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
// Initialize database
await db.read();
// Parse dependant ID from params
const dependantId = parseInt(params.id);
if (isNaN(dependantId)) {
return NextResponse.json(
{
success: false,
message: "Invalid dependant ID provided",
},
{ status: 400 }
);
}
// Find the dependant to delete
const dependantIndex = db.data!.customerDependants.findIndex(
(d) => d.id === dependantId
);
if (dependantIndex === -1) {
return NextResponse.json(
{
success: false,
message: "Dependant not found",
},
{ status: 404 }
);
}
// Get dependant info before deletion
const dependantToDelete = db.data!.customerDependants[dependantIndex];
// Delete the dependant
db.data!.customerDependants.splice(dependantIndex, 1);
// Save to database
await db.write();
console.log(`Dependant ${dependantId} deleted successfully`);
// Return success response
return NextResponse.json(
{
success: true,
message: "Dependant deleted successfully",
data: dependantToDelete,
},
{ status: 200 }
);
} catch (error) {
console.error("Error deleting dependant:", error);
return NextResponse.json(
{
success: false,
message: "Failed to delete dependant",
error: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,262 @@
import { NextRequest, NextResponse } from "next/server";
import { db, getNextId } from "@/database/database";
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
// Initialize database
await db.read();
// Parse customer ID from params
const { id } = await params;
const customerId = parseInt(id);
if (isNaN(customerId)) {
return NextResponse.json(
{
success: false,
message: "Invalid customer ID provided",
},
{ status: 400 }
);
}
// Get all customers and customer dependants
const customers = db.data!.customers;
const customerDependants = db.data!.customerDependants;
// Find the specific customer
const customer = customers.find((c) => c.id === customerId);
if (!customer) {
return NextResponse.json(
{
success: false,
message: "Customer not found",
},
{ status: 404 }
);
}
// Get customer dependants for this customer
const dependants = customerDependants.filter(
(dependant) => dependant.custId === customerId
);
// Return customer with dependants
const customerWithDependants = {
...customer,
dependants: dependants,
};
return NextResponse.json(
{
success: true,
data: customerWithDependants,
},
{ status: 200 }
);
} catch (error) {
console.error("Error fetching customer:", error);
return NextResponse.json(
{
success: false,
message: "Failed to fetch customer",
error: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
// Initialize database
await db.read();
// Parse customer ID from params
const { id } = await params;
const customerId = parseInt(id);
if (isNaN(customerId)) {
return NextResponse.json(
{
success: false,
message: "Invalid customer ID provided",
},
{ status: 400 }
);
}
// Parse and validate request body
const body = await request.json();
console.log("Received customer update data:", body);
// Find the customer to update
const customerIndex = db.data!.customers.findIndex((c) => c.id === customerId);
if (customerIndex === -1) {
return NextResponse.json(
{
success: false,
message: "Customer not found",
},
{ status: 404 }
);
}
// Update customer data
const updatedCustomer = {
...db.data!.customers[customerIndex],
firstNameEn: body.customerInfo.firstNameEn,
lastNameEn: body.customerInfo.lastNameEn,
originAdd1: body.customerInfo.originAdd1,
localAdd1: body.customerInfo.localAdd1,
email: body.customerContact.email,
mobile: body.customerContact.mobile,
};
db.data!.customers[customerIndex] = updatedCustomer;
// Handle dependants - remove existing ones and add new ones
db.data!.customerDependants = db.data!.customerDependants.filter(
(dependant) => dependant.custId !== customerId
);
// Add new dependants
const newDependants = [];
if (body.customerDependants && body.customerDependants.length > 0) {
for (const dependant of body.customerDependants) {
const newDependant = {
id: dependant.id && !isNaN(parseInt(dependant.id)) ?
parseInt(dependant.id) :
getNextId(db.data!.customerDependants),
custId: customerId,
firstNameEn: dependant.firstNameEn,
lastNameEn: dependant.lastNameEn,
originAdd1: dependant.originAdd1,
localAdd1: dependant.localAdd1,
email: dependant.email,
mobile: dependant.mobile,
};
newDependants.push(newDependant);
db.data!.customerDependants.push(newDependant);
}
}
// Save to database
await db.write();
console.log("Customer updated successfully");
// Return success response
return NextResponse.json(
{
success: true,
message: "Customer updated successfully",
data: {
customer: updatedCustomer,
dependants: newDependants,
},
},
{ status: 200 }
);
} catch (error) {
console.error("Error updating customer:", error);
return NextResponse.json(
{
success: false,
message: "Failed to update customer",
error: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
// Initialize database
await db.read();
// Parse customer ID from params
const { id } = await params;
const customerId = parseInt(id);
if (isNaN(customerId)) {
return NextResponse.json(
{
success: false,
message: "Invalid customer ID provided",
},
{ status: 400 }
);
}
// Find the customer to delete
const customerIndex = db.data!.customers.findIndex((c) => c.id === customerId);
if (customerIndex === -1) {
return NextResponse.json(
{
success: false,
message: "Customer not found",
},
{ status: 404 }
);
}
// Get customer info before deletion
const customerToDelete = db.data!.customers[customerIndex];
// Delete customer dependants first
const dependantsToDelete = db.data!.customerDependants.filter(
(dependant) => dependant.custId === customerId
);
db.data!.customerDependants = db.data!.customerDependants.filter(
(dependant) => dependant.custId !== customerId
);
// Delete the customer
db.data!.customers.splice(customerIndex, 1);
// Save to database
await db.write();
console.log(`Customer ${customerId} and ${dependantsToDelete.length} dependants deleted successfully`);
// Return success response
return NextResponse.json(
{
success: true,
message: `Customer and ${dependantsToDelete.length} dependant(s) deleted successfully`,
data: {
deletedCustomer: customerToDelete,
deletedDependants: dependantsToDelete,
},
},
{ status: 200 }
);
} catch (error) {
console.error("Error deleting customer:", error);
return NextResponse.json(
{
success: false,
message: "Failed to delete customer",
error: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,189 @@
import { NextRequest, NextResponse } from "next/server";
import { db, getNextId } from "@/database/database";
import { Customer, CustomerDependant } from "@/database/database.schema";
import { customerFormSchema } from "@/schemas/customer.schema";
export async function POST(request: NextRequest) {
try {
// Initialize database
await db.read();
// Parse and validate request body
const body = await request.json();
console.log("Received customer data:", body);
const validatedData = customerFormSchema.parse(body);
// Create customer object
const newCustomer: Customer = {
id: getNextId(db.data!.customers),
firstNameEn: validatedData.customerInfo.firstNameEn,
lastNameEn: validatedData.customerInfo.lastNameEn,
email: validatedData.customerContact.email,
mobile: validatedData.customerContact.mobile,
originAdd1: validatedData.customerInfo.originAdd1,
localAdd1: validatedData.customerInfo.localAdd1,
};
// Add customer to database
db.data!.customers.push(newCustomer);
console.log("Customer added to database:", newCustomer);
// Create customer dependants if any
const customerDependants: CustomerDependant[] = [];
if (validatedData.customerDependants && validatedData.customerDependants.length > 0) {
for (const dependant of validatedData.customerDependants) {
const newDependant: CustomerDependant = {
id: getNextId(db.data!.customerDependants),
custId: newCustomer.id,
firstNameEn: dependant.firstNameEn,
lastNameEn: dependant.lastNameEn,
email: dependant.email,
mobile: dependant.mobile,
originAdd1: dependant.originAdd1,
localAdd1: dependant.localAdd1,
};
customerDependants.push(newDependant);
db.data!.customerDependants.push(newDependant);
}
console.log("Customer dependants added:", customerDependants);
}
// Save to database
await db.write();
console.log("Database updated successfully");
// Return success response
return NextResponse.json(
{
success: true,
message: "Customer and dependants saved successfully",
data: {
customer: newCustomer,
dependants: customerDependants,
},
},
{ status: 201 }
);
} catch (error) {
console.error("Error saving customer:", error);
// Handle validation errors
if (error instanceof Error && error.name === "ZodError") {
return NextResponse.json(
{
success: false,
message: "Invalid data provided",
errors: error.message,
},
{ status: 400 }
);
}
// Handle other errors
return NextResponse.json(
{
success: false,
message: "Failed to save customer",
error: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
}
}
export async function GET(request: NextRequest) {
try {
// Initialize database
await db.read();
// Get query parameters
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get("page") || "1");
const pageSize = parseInt(searchParams.get("pageSize") || "10");
const search = searchParams.get("search") || "";
const sortBy = searchParams.get("sortBy") || "id";
const sortOrder = searchParams.get("sortOrder") || "asc";
// Get all customers with their dependants
const customers = db.data!.customers;
const customerDependants = db.data!.customerDependants;
// Group dependants by customer ID
let customersWithDependants = customers.map((customer) => ({
...customer,
name: `${customer.firstNameEn} ${customer.lastNameEn}`,
dependants: customerDependants.filter(
(dependant) => dependant.custId === customer.id
),
}));
// Apply search filter
if (search) {
const searchLower = search.toLowerCase();
customersWithDependants = customersWithDependants.filter((customer) =>
customer.firstNameEn.toLowerCase().includes(searchLower) ||
customer.lastNameEn.toLowerCase().includes(searchLower) ||
customer.email.toLowerCase().includes(searchLower) ||
customer.mobile.includes(search)
);
}
// Apply sorting
customersWithDependants.sort((a, b) => {
let aValue: string | number = a[sortBy as keyof typeof a] as string | number;
let bValue: string | number = b[sortBy as keyof typeof b] as string | number;
// Handle special cases
if (sortBy === "name") {
aValue = `${a.firstNameEn} ${a.lastNameEn}`;
bValue = `${b.firstNameEn} ${b.lastNameEn}`;
}
if (typeof aValue === "string") {
aValue = aValue.toLowerCase();
bValue = (bValue as string).toLowerCase();
}
if (sortOrder === "desc") {
return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
} else {
return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
}
});
// Calculate pagination
const total = customersWithDependants.length;
const totalPages = Math.ceil(total / pageSize);
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const paginatedCustomers = customersWithDependants.slice(startIndex, endIndex);
return NextResponse.json(
{
success: true,
data: paginatedCustomers,
pagination: {
page,
pageSize,
total,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
},
{ status: 200 }
);
} catch (error) {
console.error("Error fetching customers:", error);
return NextResponse.json(
{
success: false,
message: "Failed to fetch customers",
error: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,613 @@
"use client";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useParams, useRouter } from "next/navigation";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Plus, Trash2, ArrowLeft, Save, Loader2 } from "lucide-react";
import { toast } from "sonner";
import {
customerFormSchema,
customerDependantFormSchema,
type CustomerForm,
type CustomerDependantForm,
type CustomerDependant,
} from "@/schemas/customer.schema";
import axios from "axios";
export default function CustomerEditPage() {
const params = useParams();
const router = useRouter();
const customerId = params.id as string;
const [activeTab, setActiveTab] = useState("info");
const [dependantDialogOpen, setDependantDialogOpen] = useState(false);
const [dependantDialogTab, setDependantDialogTab] = useState("info");
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [editingDependant, setEditingDependant] = useState<CustomerDependant | null>(null);
// Main form
const form = useForm<CustomerForm>({
resolver: zodResolver(customerFormSchema),
defaultValues: {
customerInfo: {
firstNameEn: "",
lastNameEn: "",
originAdd1: "",
localAdd1: "",
},
customerContact: {
email: "",
mobile: "",
},
customerDependants: [],
},
});
// Dependant dialog form
const dependantForm = useForm<CustomerDependantForm>({
resolver: zodResolver(customerDependantFormSchema),
defaultValues: {
dependantInfo: {
firstNameEn: "",
lastNameEn: "",
originAdd1: "",
localAdd1: "",
},
dependantContact: {
email: "",
mobile: "",
},
},
});
const watchedDependants = form.watch("customerDependants");
// Fetch customer data on component mount
useEffect(() => {
const fetchCustomerData = async () => {
try {
setIsLoading(true);
const response = await axios.get(`/api/customer/${customerId}`);
if (response.data.success) {
const customerData = response.data.data;
// Populate form with customer data
form.setValue("customerInfo.firstNameEn", customerData.firstNameEn);
form.setValue("customerInfo.lastNameEn", customerData.lastNameEn);
form.setValue("customerInfo.originAdd1", customerData.originAdd1);
form.setValue("customerInfo.localAdd1", customerData.localAdd1);
form.setValue("customerContact.email", customerData.email);
form.setValue("customerContact.mobile", customerData.mobile);
// Convert dependants to the expected format
const dependants: CustomerDependant[] = customerData.dependants.map((dep: {
id: number;
firstNameEn: string;
lastNameEn: string;
email: string;
mobile: string;
originAdd1: string;
localAdd1: string;
}) => ({
id: dep.id,
firstNameEn: dep.firstNameEn,
lastNameEn: dep.lastNameEn,
email: dep.email,
mobile: dep.mobile,
originAdd1: dep.originAdd1,
localAdd1: dep.localAdd1,
}));
form.setValue("customerDependants", dependants);
toast.success("Customer data loaded successfully");
} else {
toast.error(response.data.message || "Failed to load customer data");
}
} catch (error) {
console.error("Error fetching customer data:", error);
toast.error("Failed to load customer data");
} finally {
setIsLoading(false);
}
};
if (customerId) {
fetchCustomerData();
}
}, [customerId, form]);
const onSubmit = async (data: CustomerForm) => {
try {
setIsSaving(true);
console.log("Submitting customer data:", data);
const response = await axios.put(`/api/customer/${customerId}`, data);
console.log("API response:", response.data);
if (response.data.success) {
toast.success("Customer updated successfully!");
router.push("/modules/customer");
} else {
throw new Error(response.data.message || "Failed to update customer");
}
} catch (error) {
console.error("Error updating customer:", error);
toast.error("Failed to update customer. Please try again.");
} finally {
setIsSaving(false);
}
};
// handleSaveClick removed: now using form submit
const onDependantSubmit = async (data: CustomerDependantForm) => {
try {
// Validate the entire dependant form
const isValid = await dependantForm.trigger();
if (!isValid) {
toast.error("Please fill in all required fields.");
return;
}
const currentDependants = form.getValues("customerDependants");
if (editingDependant) {
// Update existing dependant
const updatedDependants = currentDependants.map((dep) =>
dep.id === editingDependant.id
? {
...dep,
firstNameEn: data.dependantInfo.firstNameEn,
lastNameEn: data.dependantInfo.lastNameEn,
originAdd1: data.dependantInfo.originAdd1,
localAdd1: data.dependantInfo.localAdd1,
email: data.dependantContact.email,
mobile: data.dependantContact.mobile,
}
: dep
);
form.setValue("customerDependants", updatedDependants);
toast.success("Dependant updated successfully!");
} else {
// Add new dependant - just add to the table, don't submit parent form
const newDependant: CustomerDependant = {
id: Date.now(),
firstNameEn: data.dependantInfo.firstNameEn,
lastNameEn: data.dependantInfo.lastNameEn,
originAdd1: data.dependantInfo.originAdd1,
localAdd1: data.dependantInfo.localAdd1,
email: data.dependantContact.email,
mobile: data.dependantContact.mobile,
};
// Add new row to dependant table without submitting parent form
form.setValue("customerDependants", [...currentDependants, newDependant]);
toast.success("Dependant added successfully!");
}
// Reset dependant form and close dialog
dependantForm.reset();
setDependantDialogOpen(false);
setDependantDialogTab("info");
setEditingDependant(null);
} catch (error) {
console.error("Error handling dependant:", error);
toast.error("Failed to save dependant. Please try again.");
}
};
const handleEditDependant = (dependant: CustomerDependant) => {
setEditingDependant(dependant);
dependantForm.setValue("dependantInfo.firstNameEn", dependant.firstNameEn);
dependantForm.setValue("dependantInfo.lastNameEn", dependant.lastNameEn);
dependantForm.setValue("dependantInfo.originAdd1", dependant.originAdd1);
dependantForm.setValue("dependantInfo.localAdd1", dependant.localAdd1);
dependantForm.setValue("dependantContact.email", dependant.email);
dependantForm.setValue("dependantContact.mobile", dependant.mobile);
setDependantDialogOpen(true);
setDependantDialogTab("info");
};
const handleAddDependant = () => {
setEditingDependant(null);
dependantForm.reset();
setDependantDialogOpen(true);
setDependantDialogTab("info");
};
const removeDependant = (dependantId: number | undefined) => {
if (!dependantId) return;
const currentDependants = form.getValues("customerDependants");
const updatedDependants = currentDependants.filter(
(dependant) => dependant.id !== dependantId
);
form.setValue("customerDependants", updatedDependants);
toast.success("Dependant removed successfully!");
};
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="flex items-center space-x-2">
<Loader2 className="h-6 w-6 animate-spin" />
<span>Loading customer data...</span>
</div>
</div>
);
}
return (
<div className="container mx-auto p-6 max-w-6xl">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center space-x-4">
<Button
variant="outline"
onClick={() => router.push("/modules/customer")}
className="flex items-center space-x-2"
>
<ArrowLeft className="h-4 w-4" />
<span>Back to Customers</span>
</Button>
<h1 className="text-2xl font-bold">Edit Customer</h1>
</div>
<Button
type="submit"
form="customer-edit-form"
disabled={isSaving}
className="flex items-center space-x-2"
>
{isSaving ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</>
) : (
<>
<Save className="h-4 w-4" />
<span>Save Changes</span>
</>
)}
</Button>
</div>
<Form {...form}>
<form id="customer-edit-form" className="space-y-6" onSubmit={form.handleSubmit(onSubmit)}>
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="info">Customer Info</TabsTrigger>
<TabsTrigger value="contact">Contact Details</TabsTrigger>
<TabsTrigger value="dependants">Dependants</TabsTrigger>
</TabsList>
<TabsContent value="info" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Customer Information</CardTitle>
<CardDescription>Edit the customer&apos;s basic information</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerInfo.firstNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>First Name (English)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerInfo.lastNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>Last Name (English)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerInfo.originAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Origin Address</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerInfo.localAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Local Address</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="contact" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Contact Details</CardTitle>
<CardDescription>Edit the customer&apos;s contact information</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<FormField
control={form.control}
name="customerContact.email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerContact.mobile"
render={({ field }) => (
<FormItem>
<FormLabel>Mobile</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="dependants" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Customer Dependants</CardTitle>
<CardDescription>Manage customer dependants</CardDescription>
</CardHeader>
<CardContent>
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold">
Dependants ({watchedDependants.length})
</h3>
<Dialog open={dependantDialogOpen} onOpenChange={setDependantDialogOpen}>
<DialogTrigger asChild>
<Button onClick={handleAddDependant} className="flex items-center space-x-2">
<Plus className="h-4 w-4" />
<span>Add Dependant</span>
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>
{editingDependant ? "Edit Dependant" : "Add New Dependant"}
</DialogTitle>
</DialogHeader>
<Form {...dependantForm}>
<form>
<Tabs value={dependantDialogTab} onValueChange={setDependantDialogTab}>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="info">Personal Info</TabsTrigger>
<TabsTrigger value="contact">Contact Details</TabsTrigger>
</TabsList>
<TabsContent value="info" className="space-y-4 mt-4">
<div className="grid grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantInfo.firstNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>First Name (English)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantInfo.lastNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>Last Name (English)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantInfo.originAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Origin Address</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantInfo.localAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Local Address</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</TabsContent>
<TabsContent value="contact" className="space-y-4 mt-4">
<FormField
control={dependantForm.control}
name="dependantContact.email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantContact.mobile"
render={({ field }) => (
<FormItem>
<FormLabel>Mobile</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TabsContent>
</Tabs>
<div className="flex justify-end space-x-2 mt-6">
<Button
type="button"
variant="outline"
onClick={() => {
setDependantDialogOpen(false);
setEditingDependant(null);
dependantForm.reset();
}}
>
Cancel
</Button>
<Button
type="button"
onClick={async () => {
const isValid = await dependantForm.trigger();
if (isValid) {
const formData = dependantForm.getValues();
onDependantSubmit(formData);
} else {
toast.error("Please fill in all required fields.");
}
}}
>
{editingDependant ? "Update Dependant" : "Add Dependant"}
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
{watchedDependants.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Email</TableHead>
<TableHead>Mobile</TableHead>
<TableHead>Origin Address</TableHead>
<TableHead>Local Address</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{watchedDependants.map((dependant) => (
<TableRow key={dependant.id}>
<TableCell>
{dependant.firstNameEn} {dependant.lastNameEn}
</TableCell>
<TableCell>{dependant.email}</TableCell>
<TableCell>{dependant.mobile}</TableCell>
<TableCell>{dependant.originAdd1}</TableCell>
<TableCell>{dependant.localAdd1}</TableCell>
<TableCell>
<div className="flex space-x-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => handleEditDependant(dependant)}
>
Edit
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => removeDependant(dependant.id)}
className="text-red-600 hover:text-red-700"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="text-center py-8 text-gray-500">
No dependants added yet. Click &quot;Add Dependant&quot; to get started.
</div>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</form>
</Form>
</div>
);
}

View File

@@ -0,0 +1,572 @@
"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Plus, Trash2, ArrowLeft } from "lucide-react";
import { toast } from "sonner";
import {
customerFormSchema,
customerDependantFormSchema,
type CustomerForm,
type CustomerDependantForm,
type CustomerDependant,
} from "@/schemas/customer.schema";
import axios from "axios";
export default function CustomerAddPage() {
const router = useRouter();
const [activeTab, setActiveTab] = useState("info");
const [dependantDialogOpen, setDependantDialogOpen] = useState(false);
const [dependantDialogTab, setDependantDialogTab] = useState("info");
// Main form
const form = useForm<CustomerForm>({
resolver: zodResolver(customerFormSchema),
defaultValues: {
customerInfo: {
firstNameEn: "",
lastNameEn: "",
originAdd1: "",
localAdd1: "",
},
customerContact: {
email: "",
mobile: "",
},
customerDependants: [],
},
});
// Dependant dialog form
const dependantForm = useForm<CustomerDependantForm>({
resolver: zodResolver(customerDependantFormSchema),
defaultValues: {
dependantInfo: {
firstNameEn: "",
lastNameEn: "",
originAdd1: "",
localAdd1: "",
},
dependantContact: {
email: "",
mobile: "",
},
},
});
const watchedDependants = form.watch("customerDependants");
const onSubmit = async (data: CustomerForm) => {
try {
const response = await axios.post("/api/customer", data);
if (response.status !== 200 && response.status !== 201) {
throw new Error(response.data?.message || "Failed to save customer");
}
console.log("Customer saved successfully:", response.data);
toast.success("Customer added successfully!");
// Reset form after successful submission
form.reset();
} catch (error) {
console.error("Error submitting form:", error);
toast.error("Failed to add customer. Please try again.");
}
};
const onDependantSubmit = async (data: CustomerDependantForm) => {
try {
// Validate the entire dependant form
const isValid = await dependantForm.trigger();
if (!isValid) {
toast.error("Please fill in all required fields.");
return;
}
const newDependant: CustomerDependant = {
id: Date.now(), // Generate unique ID
firstNameEn: data.dependantInfo.firstNameEn,
lastNameEn: data.dependantInfo.lastNameEn,
email: data.dependantContact.email,
mobile: data.dependantContact.mobile,
originAdd1: data.dependantInfo.originAdd1,
localAdd1: data.dependantInfo.localAdd1,
};
const currentDependants = form.getValues("customerDependants");
form.setValue("customerDependants", [...currentDependants, newDependant]);
// Reset dependant form and close dialog
dependantForm.reset();
setDependantDialogOpen(false);
setDependantDialogTab("info");
toast.success("Dependant added successfully!");
} catch (error) {
console.error("Error adding dependant:", error);
toast.error("Failed to add dependant. Please try again.");
}
};
const removeDependant = (dependantId: number) => {
const currentDependants = form.getValues("customerDependants");
const updatedDependants = currentDependants.filter(dep => dep.id !== dependantId);
form.setValue("customerDependants", updatedDependants);
toast.success("Dependant removed successfully!");
};
const handleNextTab = async () => {
if (activeTab === "info") {
// Validate customer info fields before proceeding
const isValid = await form.trigger([
"customerInfo.firstNameEn",
"customerInfo.lastNameEn",
"customerInfo.originAdd1",
"customerInfo.localAdd1"
]);
if (isValid) {
setActiveTab("contact");
} else {
toast.error("Please fill in all required fields in Customer Info tab.");
}
} else if (activeTab === "contact") {
// Validate customer contact fields before proceeding
const isValid = await form.trigger(["customerContact.email", "customerContact.mobile"]);
if (isValid) {
setActiveTab("dependants");
} else {
toast.error("Please fill in all required fields in Customer Contact tab.");
}
}
};
const handlePreviousTab = () => {
if (activeTab === "contact") {
setActiveTab("info");
} else if (activeTab === "dependants") {
setActiveTab("contact");
}
};
const isTabValid = (tabName: string) => {
const values = form.getValues();
const errors = form.formState.errors;
if (tabName === "info") {
return (
values.customerInfo?.firstNameEn?.trim() !== "" &&
values.customerInfo?.lastNameEn?.trim() !== "" &&
values.customerInfo?.originAdd1?.trim() !== "" &&
values.customerInfo?.localAdd1?.trim() !== "" &&
!errors.customerInfo?.firstNameEn &&
!errors.customerInfo?.lastNameEn &&
!errors.customerInfo?.originAdd1 &&
!errors.customerInfo?.localAdd1
);
} else if (tabName === "contact") {
return (
values.customerContact?.email?.trim() !== "" &&
values.customerContact?.mobile?.trim() !== "" &&
!errors.customerContact?.email &&
!errors.customerContact?.mobile
);
}
return true;
};
return (
<div className="container mx-auto p-6 max-w-6xl">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center space-x-4">
<Button
variant="outline"
onClick={() => router.push("/modules/customer")}
className="flex items-center space-x-2"
>
<ArrowLeft className="h-4 w-4" />
<span>Back to Customers</span>
</Button>
<h1 className="text-2xl font-bold">Add New Customer</h1>
</div>
</div>
<Card>
<CardHeader>
<CardDescription>
Please fill in the customer information across the three tabs below.
</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<Tabs value={activeTab} className="w-full">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger
value="info"
className={!isTabValid("info") ? "text-red-500" : ""}
>
Customer Info
</TabsTrigger>
<TabsTrigger
value="contact"
className={!isTabValid("contact") ? "text-red-500" : ""}
disabled={!isTabValid("info")}
>
Customer Contact
</TabsTrigger>
<TabsTrigger
value="dependants"
disabled={!isTabValid("info") || !isTabValid("contact")}
>
Customer Dependants
</TabsTrigger>
</TabsList>
{/* Tab 1: Customer Info */}
<TabsContent value="info" className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerInfo.firstNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>First Name (English)</FormLabel>
<FormControl>
<Input placeholder="Enter first name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerInfo.lastNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>Last Name (English)</FormLabel>
<FormControl>
<Input placeholder="Enter last name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerInfo.originAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Origin Address</FormLabel>
<FormControl>
<Input placeholder="Enter origin address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerInfo.localAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Local Address</FormLabel>
<FormControl>
<Input placeholder="Enter local address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-end">
<Button type="button" onClick={handleNextTab}>
Next
</Button>
</div>
</TabsContent>
{/* Tab 2: Customer Contact */}
<TabsContent value="contact" className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerContact.email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" placeholder="Enter email address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerContact.mobile"
render={({ field }) => (
<FormItem>
<FormLabel>Mobile Number</FormLabel>
<FormControl>
<Input placeholder="Enter mobile number" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-between">
<Button type="button" variant="outline" onClick={handlePreviousTab}>
Previous
</Button>
<Button type="button" onClick={handleNextTab}>
Next
</Button>
</div>
</TabsContent>
{/* Tab 3: Customer Dependants */}
<TabsContent value="dependants" className="space-y-4">
<div className="flex justify-between items-center">
<h3 className="text-lg font-semibold">Customer Dependants</h3>
<Dialog open={dependantDialogOpen} onOpenChange={setDependantDialogOpen}>
<DialogTrigger asChild>
<Button type="button" className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Add Dependant
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Add New Dependant</DialogTitle>
</DialogHeader>
<Form {...dependantForm}>
<form onSubmit={dependantForm.handleSubmit(onDependantSubmit)} className="space-y-4">
<Tabs value={dependantDialogTab} onValueChange={setDependantDialogTab} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="info">Dependant Info</TabsTrigger>
<TabsTrigger value="contact">Dependant Contact</TabsTrigger>
</TabsList>
<TabsContent value="info" className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantInfo.firstNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>First Name (English)</FormLabel>
<FormControl>
<Input placeholder="Enter first name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantInfo.lastNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>Last Name (English)</FormLabel>
<FormControl>
<Input placeholder="Enter last name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantInfo.originAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Origin Address</FormLabel>
<FormControl>
<Input placeholder="Enter origin address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantInfo.localAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Local Address</FormLabel>
<FormControl>
<Input placeholder="Enter local address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-end">
<Button
type="button"
onClick={async () => {
const isValid = await dependantForm.trigger([
"dependantInfo.firstNameEn",
"dependantInfo.lastNameEn",
"dependantInfo.originAdd1",
"dependantInfo.localAdd1"
]);
if (isValid) {
setDependantDialogTab("contact");
} else {
toast.error("Please fill in all required fields in Dependant Info tab.");
}
}}
>
Next
</Button>
</div>
</TabsContent>
<TabsContent value="contact" className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantContact.email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" placeholder="Enter email address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantContact.mobile"
render={({ field }) => (
<FormItem>
<FormLabel>Mobile Number</FormLabel>
<FormControl>
<Input placeholder="Enter mobile number" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-start">
<Button
type="button"
variant="outline"
onClick={() => setDependantDialogTab("info")}
>
Previous
</Button>
</div>
</TabsContent>
</Tabs>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => setDependantDialogOpen(false)}
>
Cancel
</Button>
<Button
type="button"
onClick={async () => {
const isValid = await dependantForm.trigger();
if (isValid) {
const formData = dependantForm.getValues();
onDependantSubmit(formData);
} else {
toast.error("Please fill in all required fields.");
}
}}
>
Add Dependant
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
{watchedDependants.length > 0 ? (
<div className="border rounded-lg">
<Table>
<TableHeader>
<TableRow>
<TableHead>First Name</TableHead>
<TableHead>Last Name</TableHead>
<TableHead>Email</TableHead>
<TableHead>Mobile</TableHead>
<TableHead>Origin Address</TableHead>
<TableHead>Local Address</TableHead>
<TableHead className="w-[100px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{watchedDependants.map((dependant) => (
<TableRow key={dependant.id}>
<TableCell>{dependant.firstNameEn}</TableCell>
<TableCell>{dependant.lastNameEn}</TableCell>
<TableCell>{dependant.email}</TableCell>
<TableCell>{dependant.mobile}</TableCell>
<TableCell>{dependant.originAdd1}</TableCell>
<TableCell>{dependant.localAdd1}</TableCell>
<TableCell>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeDependant(dependant.id!)}
className="text-red-500 hover:text-red-700 hover:bg-red-50"
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<div className="text-center text-muted-foreground py-8">
No dependants added yet. Click &quot;Add Dependant&quot; to add one.
</div>
)}
<div className="flex justify-between">
<Button type="button" variant="outline" onClick={handlePreviousTab}>
Previous
</Button>
<Button type="submit">
Save Customer
</Button>
</div>
</TabsContent>
</Tabs>
</form>
</Form>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,219 @@
"use client";
import { useState, useEffect, useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Plus, Loader2, Users, RefreshCw } from "lucide-react";
import { toast } from "sonner";
import axios from "axios";
import { ServerDataTable } from "@/components/ui/server-data-table";
import { Customer, createCustomerColumns } from "@/components/customers/customer-columns";
interface PaginationInfo {
page: number;
pageSize: number;
total: number;
totalPages: number;
hasNextPage: boolean;
hasPreviousPage: boolean;
}
interface CustomerResponse {
success: boolean;
data: Customer[];
pagination: PaginationInfo;
message?: string;
}
export default function CustomerPage() {
const router = useRouter();
const [customers, setCustomers] = useState<Customer[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const [query, setQuery] = useState({
page: 1,
pageSize: 10,
search: "",
sortBy: "id",
sortOrder: "asc" as "asc" | "desc",
});
const [pagination, setPagination] = useState<PaginationInfo>({
page: 1,
pageSize: 10,
total: 0,
totalPages: 0,
hasNextPage: false,
hasPreviousPage: false,
});
// Initialize search and sorting state to match query
const [searchValue, setSearchValue] = useState(query.search);
const [sorting, setSorting] = useState<{ id: string; desc: boolean }[]>(
query.sortBy ? [{ id: query.sortBy, desc: query.sortOrder === "desc" }] : []
);
const fetchCustomers = useCallback(async () => {
try {
setIsLoading(true);
const params = new URLSearchParams({
page: query.page.toString(),
pageSize: query.pageSize.toString(),
search: query.search,
sortBy: query.sortBy,
sortOrder: query.sortOrder,
});
const response = await axios.get<CustomerResponse>(`/api/customer?${params}`);
if (response.data.success) {
setCustomers(response.data.data);
setPagination(response.data.pagination);
} else {
toast.error(response.data.message || "Failed to load customers");
}
} catch (error) {
console.error("Error fetching customers:", error);
toast.error("Failed to load customers");
} finally {
setIsLoading(false);
setIsRefreshing(false);
}
}, [query]);
// Fetch customers when query changes
useEffect(() => {
fetchCustomers();
}, [fetchCustomers]);
const handleAddCustomer = useCallback(() => {
router.push("/modules/customer/add");
}, [router]);
const handleEditCustomer = useCallback((customerId: number) => {
router.push(`/modules/customer/${customerId}`);
}, [router]);
const handleDeleteCustomer = useCallback(async (customerId: number) => {
// Find the customer to get their name for confirmation
const customerToDelete = customers.find(c => c.id === customerId);
const customerName = customerToDelete ? `${customerToDelete.firstNameEn} ${customerToDelete.lastNameEn}` : `Customer #${customerId}`;
if (!window.confirm(`Are you sure you want to delete ${customerName} and all their dependants? This action cannot be undone.`)) {
return;
}
try {
const response = await axios.delete(`/api/customer/${customerId}`);
if (response.data.success) {
toast.success(response.data.message || "Customer deleted successfully");
// Refresh the customer list
await fetchCustomers();
} else {
toast.error(response.data.message || "Failed to delete customer");
}
} catch (error) {
console.error("Error deleting customer:", error);
toast.error("Failed to delete customer");
}
}, [fetchCustomers, customers]);
const handleRefresh = useCallback(async () => {
setIsRefreshing(true);
await fetchCustomers();
toast.success("Customer list refreshed");
}, [fetchCustomers]);
const handlePaginationChange = useCallback((page: number, pageSize: number) => {
setQuery((prev) => ({ ...prev, page, pageSize }));
}, []);
// Search handler - will be called from ServerDataTable after debounce
const handleSearchChange = useCallback((search: string) => {
setQuery((prev) => ({ ...prev, search, page: 1 }));
}, []);
// Sorting handler - will be called from ServerDataTable
const handleSortingChange = useCallback((sortByField: string, sortOrderValue: "asc" | "desc") => {
setQuery((prev) => ({ ...prev, sortBy: sortByField, sortOrder: sortOrderValue }));
setSorting([{ id: sortByField, desc: sortOrderValue === "desc" }]);
}, []);
const columns = useMemo(() => createCustomerColumns({
onEdit: handleEditCustomer,
onDelete: handleDeleteCustomer,
}), [handleEditCustomer, handleDeleteCustomer]);
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="flex items-center space-x-2">
<Loader2 className="h-6 w-6 animate-spin" />
<span>Loading customers...</span>
</div>
</div>
);
}
return (
<div className="container mx-auto p-6">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center space-x-2">
<Users className="h-8 w-8" />
<h1 className="text-3xl font-bold">Customer Management</h1>
</div>
<div className="flex items-center space-x-2">
<Button
onClick={handleRefresh}
variant="outline"
size="sm"
disabled={isRefreshing}
className="flex items-center space-x-2"
>
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
<span>Refresh</span>
</Button>
<Button onClick={handleAddCustomer} className="flex items-center space-x-2">
<Plus className="h-4 w-4" />
<span>Add Customer</span>
</Button>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>Customers</CardTitle>
<CardDescription>
Manage your customer database ({pagination.total} total)
</CardDescription>
</CardHeader>
<CardContent>
{pagination.total > 0 ? (
<ServerDataTable
columns={columns}
data={customers}
pagination={pagination}
searchKey="name"
searchPlaceholder="Search customers by name..."
isLoading={isLoading}
onPaginationChange={handlePaginationChange}
onSearchChange={handleSearchChange}
onSortingChange={handleSortingChange}
searchValue={searchValue}
sorting={sorting}
setSearchValue={setSearchValue}
setSorting={setSorting}
/>
) : (
<div className="text-center py-8 text-gray-500">
<Users className="h-12 w-12 mx-auto mb-4 text-gray-400" />
<p className="text-lg font-medium">No customers found</p>
<p className="text-sm">Get started by adding your first customer</p>
<Button onClick={handleAddCustomer} className="mt-4">
<Plus className="h-4 w-4 mr-2" />
Add Customer
</Button>
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,44 @@
import { AppSidebar } from "@/components/sidebar/app-sidebar";
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
import {
SidebarInset,
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar";
import { Separator } from "@radix-ui/react-select";
export default function ModulesLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<main>
<SidebarProvider>
<AppSidebar />
<SidebarInset>
<header className="flex h-16 shrink-0 items-center gap-2 border-b px-4">
<SidebarTrigger className="-ml-1" />
<Separator
className="mr-2 data-[orientation=vertical]:h-4"
/>
<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem className="hidden md:block">
<BreadcrumbLink href="#">
Building Your Application
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator className="hidden md:block" />
<BreadcrumbItem>
<BreadcrumbPage>Data Fetching</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
</header>
{children}
</SidebarInset>
</SidebarProvider>
</main>
);
}

View File

@@ -0,0 +1,152 @@
"use client";
import { ColumnDef } from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import { ArrowUpDown, Trash2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
export interface Customer {
id: number;
firstNameEn: string;
lastNameEn: string;
name: string;
email: string;
mobile: string;
originAdd1: string;
localAdd1: string;
dependants?: Array<{
id: number;
custId: number;
firstNameEn: string;
lastNameEn: string;
email: string;
mobile: string;
originAdd1: string;
localAdd1: string;
}>;
}
interface CustomerColumnsProps {
onEdit: (customerId: number) => void;
onDelete: (customerId: number) => void;
}
export const createCustomerColumns = ({
onEdit,
onDelete,
}: CustomerColumnsProps): ColumnDef<Customer>[] => [
{
accessorKey: "id",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="h-8 px-2 lg:px-3"
>
ID
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
return <div className="font-medium">{row.getValue("id")}</div>;
},
},
{
accessorKey: "name",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="h-8 px-2 lg:px-3"
>
Name
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
const customer = row.original;
return (
<div
className="font-medium cursor-pointer hover:text-blue-600 hover:underline"
onClick={() => onEdit(customer.id)}
>
{customer.firstNameEn} {customer.lastNameEn}
</div>
);
},
filterFn: (row, id, value) => {
const customer = row.original;
const fullName = `${customer.firstNameEn} ${customer.lastNameEn}`.toLowerCase();
return fullName.includes(value.toLowerCase());
},
},
{
accessorKey: "email",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="h-8 px-2 lg:px-3"
>
Email
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
return <div className="lowercase">{row.getValue("email")}</div>;
},
},
{
accessorKey: "mobile",
header: "Mobile",
cell: ({ row }) => {
return <div className="font-mono">{row.getValue("mobile")}</div>;
},
},
{
id: "dependants",
header: "Dependants",
cell: ({ row }) => {
const customer = row.original;
const dependantCount = customer.dependants?.length || 0;
return (
<div className="flex items-center">
{dependantCount > 0 ? (
<Badge variant="secondary" className="text-xs">
{dependantCount} dependant{dependantCount > 1 ? "s" : ""}
</Badge>
) : (
<span className="text-muted-foreground text-sm">None</span>
)}
</div>
);
},
},
{
id: "actions",
header: "Actions",
enableHiding: false,
cell: ({ row }) => {
const customer = row.original;
return (
<Button
variant="outline"
size="sm"
onClick={() => onDelete(customer.id)}
className="text-red-600 hover:text-red-800 hover:bg-red-50"
>
<Trash2 className="h-4 w-4 mr-2" />
Delete
</Button>
);
},
},
];

View File

@@ -0,0 +1,73 @@
'use client'
import * as React from "react"
import { GalleryVerticalEnd } from "lucide-react"
import { NavMain } from "@/components/sidebar/nav-main"
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
} from "@/components/ui/sidebar"
// This is sample data.
const data = {
navMain: [
{
title: "Customer",
url: "/modules/customer",
},
{
title: "User",
url: "/modules/user",
},
{
title: "Mail Template",
url: "/modules/mail-template",
},
],
}
import { usePathname } from "next/navigation"
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const pathname = usePathname()
const navItems = data.navMain.map((item) => ({
...item,
isActive: pathname.startsWith(item.url),
}))
return (
<Sidebar {...props}>
<SidebarHeader>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton size="lg" asChild>
<a href="#">
<div className="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
<GalleryVerticalEnd className="size-4" />
</div>
<div className="flex flex-col gap-0.5 leading-none">
<span className="font-medium">Documentation</span>
<span className="">v1.0.0</span>
</div>
</a>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<NavMain items={navItems} />
</SidebarContent>
<SidebarFooter>
<div className="p-1">
</div>
</SidebarFooter>
<SidebarRail />
</Sidebar>
)
}

View File

@@ -0,0 +1,31 @@
"use client"
import { type LucideIcon } from "lucide-react"
import { SidebarGroup, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "@/components/ui/sidebar"
export function NavMain({
items,
}: {
items: {
title: string
url: string
icon?: LucideIcon
isActive?: boolean
}[]
}) {
return (
<SidebarGroup>
<SidebarMenu>
{items.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton asChild className={item.isActive ? "bg-sidebar-accent text-sidebar-accent-foreground" : undefined}>
<a href={item.url}>
{item.title}
</a>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroup>
)
}

View File

@@ -0,0 +1,36 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,109 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
className
)}
{...props}
/>
)
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-item"
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
)
}
function BreadcrumbLink({
asChild,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="breadcrumb-link"
className={cn("hover:text-foreground transition-colors", className)}
{...props}
/>
)
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
className={cn("text-foreground font-normal", className)}
{...props}
/>
)
}
function BreadcrumbSeparator({
children,
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:size-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
}
function BreadcrumbEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="size-4" />
<span className="sr-only">More</span>
</span>
)
}
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}

View File

@@ -0,0 +1,179 @@
"use client";
import {
ColumnDef,
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
SortingState,
useReactTable,
ColumnFiltersState,
getFilteredRowModel,
} from "@tanstack/react-table";
import { useState } from "react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
searchKey?: string;
searchPlaceholder?: string;
}
export function DataTable<TData, TValue>({
columns,
data,
searchKey,
searchPlaceholder = "Search...",
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = useState<SortingState>([]);
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
state: {
sorting,
columnFilters,
},
});
return (
<div className="space-y-4">
{/* Search Input */}
{searchKey && (
<div className="flex items-center py-4">
<Input
placeholder={searchPlaceholder}
value={(table.getColumn(searchKey)?.getFilterValue() as string) ?? ""}
onChange={(event) =>
table.getColumn(searchKey)?.setFilterValue(event.target.value)
}
className="max-w-sm"
/>
</div>
)}
{/* Table */}
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id} className="font-medium">
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id} data-state={row.getIsSelected() && "selected"}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
{/* Pagination */}
<div className="flex items-center justify-between px-2">
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredRowModel().rows.length} of{" "}
{data.length} total entries
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
<p className="text-sm font-medium">Rows per page</p>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger className="h-8 w-[70px]">
<SelectValue placeholder={table.getState().pagination.pageSize} />
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of{" "}
{table.getPageCount()}
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
<ChevronsLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
<ChevronsRight className="h-4 w-4" />
</Button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,200 @@
"use client";
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
);
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};

View File

@@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

View File

@@ -0,0 +1,252 @@
"use client";
import {
ColumnDef,
flexRender,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import { useEffect, useRef, useCallback } from "react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
interface PaginationInfo {
page: number;
pageSize: number;
total: number;
totalPages: number;
hasNextPage: boolean;
hasPreviousPage: boolean;
}
interface ServerDataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
pagination: PaginationInfo;
searchKey?: string;
searchPlaceholder?: string;
isLoading?: boolean;
onPaginationChange: (page: number, pageSize: number) => void;
onSearchChange: (search: string) => void;
onSortingChange: (sortBy: string, sortOrder: "asc" | "desc") => void;
searchValue: string;
sorting: { id: string; desc: boolean }[];
setSearchValue: (value: string) => void;
setSorting: (value: { id: string; desc: boolean }[]) => void;
}
export function ServerDataTable<TData, TValue>({
columns,
data,
pagination,
searchKey,
searchPlaceholder = "Search...",
isLoading = false,
onPaginationChange,
onSearchChange,
onSortingChange,
searchValue,
sorting,
setSearchValue,
setSorting,
}: ServerDataTableProps<TData, TValue>) {
const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
onSortingChange: (updater) => {
// updater can be a function or value
const nextSorting = typeof updater === "function" ? updater(sorting) : updater;
setSorting(nextSorting);
if (nextSorting.length > 0) {
const sort = nextSorting[0];
onSortingChange(sort.id, sort.desc ? "desc" : "asc");
}
},
state: {
sorting,
},
manualPagination: true,
manualSorting: true,
manualFiltering: true,
pageCount: pagination.totalPages,
});
// Handle search input change with debounce
const handleSearchInputChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.target.value;
setSearchValue(value);
// Clear existing timeout
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
// Set new timeout for API call
searchTimeoutRef.current = setTimeout(() => {
onSearchChange(value);
}, 300);
}, [setSearchValue, onSearchChange]);
// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
};
}, []);
const handlePageSizeChange = (newPageSize: number) => {
onPaginationChange(1, newPageSize);
};
const handlePageChange = (newPage: number) => {
onPaginationChange(newPage, pagination.pageSize);
};
return (
<div className="space-y-4">
{/* Search Input */}
{searchKey && (
<div className="flex items-center py-4">
<Input
placeholder={searchPlaceholder}
value={searchValue}
onChange={handleSearchInputChange}
className="max-w-sm"
disabled={isLoading}
/>
</div>
)}
{/* Table */}
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id} className="font-medium">
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{isLoading ? (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
Loading...
</TableCell>
</TableRow>
) : table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id} data-state={row.getIsSelected() && "selected"}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
{/* Pagination */}
<div className="flex items-center justify-between px-2">
<div className="flex-1 text-sm text-muted-foreground">
{pagination.total > 0 ? (
<>
Showing {(pagination.page - 1) * pagination.pageSize + 1} to{" "}
{Math.min(pagination.page * pagination.pageSize, pagination.total)} of{" "}
{pagination.total} entries
</>
) : (
"No entries found"
)}
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
<p className="text-sm font-medium">Rows per page</p>
<Select
value={`${pagination.pageSize}`}
onValueChange={(value) => handlePageSizeChange(Number(value))}
disabled={isLoading}
>
<SelectTrigger className="h-8 w-[70px]">
<SelectValue placeholder={pagination.pageSize} />
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
Page {pagination.page} of {pagination.totalPages}
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => handlePageChange(1)}
disabled={!pagination.hasPreviousPage || isLoading}
>
<span className="sr-only">Go to first page</span>
<ChevronsLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => handlePageChange(pagination.page - 1)}
disabled={!pagination.hasPreviousPage || isLoading}
>
<span className="sr-only">Go to previous page</span>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => handlePageChange(pagination.page + 1)}
disabled={!pagination.hasNextPage || isLoading}
>
<span className="sr-only">Go to next page</span>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => handlePageChange(pagination.totalPages)}
disabled={!pagination.hasNextPage || isLoading}
>
<span className="sr-only">Go to last page</span>
<ChevronsRight className="h-4 w-4" />
</Button>
</div>
</div>
</div>
</div>
);
}

139
src/components/ui/sheet.tsx Normal file
View File

@@ -0,0 +1,139 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
)
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
)
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@@ -0,0 +1,726 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, VariantProps } from "class-variance-authority"
import { PanelLeftIcon } from "lucide-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContextProps = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}) {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
_setOpen(openState)
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
},
[setOpenProp, open]
)
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
}
}
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className
)}
{...props}
>
{children}
</div>
)
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
)
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar()
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
)
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className
)}
{...props}
/>
)
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
)
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
)
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
)
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
)
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
)
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
)
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
)
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button"
const { isMobile, state } = useSidebar()
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
if (!tooltip) {
return button
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
}
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
)
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
)
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
)
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -0,0 +1,61 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
)
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@@ -11,14 +11,14 @@ export interface Customer {
email: string;
// email2?: string;
mobile: string;
// originAdd1: string;
originAdd1: string;
// originAdd2: string;
// originAdd3: string;
// originCity: string;
// originState: string;
// originPostcode: string;
// originCountry: string;
// localAdd1: string;
localAdd1: string;
// localAdd2: string;
// localAdd3: string;
// localCity: string;
@@ -54,9 +54,22 @@ export interface User {
isDeleted: boolean;
}
export interface UserPermission {
id: number;
userId: number;
permissionId: number;
}
export interface Permission {
id: number;
name: string;
description: string;
isActive: boolean;
}
export interface CustomerDependant {
id: number;
custId: string;
custId: number;
// deptSeq: number;
firstNameEn: string;
lastNameEn: string;
@@ -65,16 +78,16 @@ export interface CustomerDependant {
// firstNameJpKana: string;
// lastNameJpKana: string;
email: string;
email2?: string;
// mobile: string;
// originAdd1: string;
// email2?: string;
mobile: string;
originAdd1: string;
// originAdd2: string;
// originAdd3: string;
// originCity: string;
// originState: string;
// originPostcode: string;
// originCountry: string;
// localAdd1: string;
localAdd1: string;
// localAdd2: string;
// localAdd3: string;
// localCity: string;
@@ -97,5 +110,7 @@ export interface CustomerDependant {
export interface DBSchema {
customers: Customer[];
users: User[];
userPermissions: UserPermission[];
permissions: Permission[];
customerDependants: CustomerDependant[];
}

View File

@@ -1,5 +1,93 @@
{
"customers": [],
"customers": [
{
"id": 6,
"firstNameEn": "David",
"lastNameEn": "Brown",
"email": "david.brown@example.com",
"mobile": "0987901234",
"originAdd1": "sadfsa",
"localAdd1": "sadfsaf"
},
{
"id": 7,
"firstNameEn": "Emily",
"lastNameEn": "Davis",
"email": "emily.davis@example.com",
"mobile": "0987567890",
"originAdd1": "sadfsa",
"localAdd1": "asdfsaf"
},
{
"id": 8,
"firstNameEn": "Robert",
"lastNameEn": "Miller",
"email": "robert.miller@example.com",
"mobile": "0987234567"
},
{
"id": 9,
"firstNameEn": "Lisa",
"lastNameEn": "Wilson",
"email": "lisa.wilson@example.com",
"mobile": "0987890123",
"originAdd1": "ssss",
"localAdd1": "sssss"
},
{
"id": 10,
"firstNameEn": "James",
"lastNameEn": "Moore",
"email": "james.moore@example.com",
"mobile": "0987456789"
},
{
"id": 11,
"firstNameEn": "Ashley",
"lastNameEn": "Taylor",
"email": "ashley.taylor@example.com",
"mobile": "0987012345"
},
{
"id": 12,
"firstNameEn": "Christopher",
"lastNameEn": "Anderson",
"email": "christopher.anderson@example.com",
"mobile": "0987678901"
},
{
"id": 13,
"firstNameEn": "sdfas",
"lastNameEn": "sadfasf",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491"
},
{
"id": 14,
"firstNameEn": "sdaf",
"lastNameEn": "asdfasf",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491"
},
{
"id": 15,
"firstNameEn": "Đỗ",
"lastNameEn": "Thanh Tùng",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491",
"originAdd1": "123",
"localAdd1": "asdfsdaf"
},
{
"id": 16,
"firstNameEn": "Đỗ",
"lastNameEn": "Thanh Tùng",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491",
"originAdd1": "12344444",
"localAdd1": "asdfsdaf11111"
}
],
"users": [
{
"id": 1,
@@ -11,5 +99,50 @@
"isDeleted": false
}
],
"customerDependants": []
"customerDependants": [
{
"id": 5,
"custId": 13,
"firstNameEn": "do thanh",
"lastNameEn": "tung",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491"
},
{
"id": 6,
"custId": 13,
"firstNameEn": "do thanh",
"lastNameEn": "tung",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417492"
},
{
"id": 1751787328700,
"custId": 14,
"firstNameEn": "222",
"lastNameEn": "3333",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491"
},
{
"id": 1751787328701,
"custId": 15,
"firstNameEn": "Đỗ",
"lastNameEn": "Thanh Tùng",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491",
"originAdd1": "123",
"localAdd1": "sdfgsdfg"
},
{
"id": 1751787328702,
"custId": 16,
"firstNameEn": "Đỗ",
"lastNameEn": "Tùng",
"originAdd1": "1231231231",
"localAdd1": "asdfsdaf",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491"
}
]
}

19
src/hooks/use-mobile.ts Normal file
View File

@@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

View File

@@ -1,24 +1,52 @@
import { z } from "zod";
export const customerSchema = z.object({
id: z.number(),
firstNameEn: z.string(),
lastNameEn: z.string(),
email: z.string().email(),
mobile: z.string(),
// If you want to add optional or commented fields from the database schema, add them here as needed
export const customerInfoSchema = z.object({
firstNameEn: z.string().min(1, "First name is required"),
lastNameEn: z.string().min(1, "Last name is required"),
originAdd1: z.string().min(1, "Origin address is required"),
localAdd1: z.string().min(1, "Local address is required"),
});
export type Customer = z.infer<typeof customerSchema>;
export const customerContactSchema = z.object({
email: z.string().email("Invalid email address"),
mobile: z.string().min(1, "Mobile number is required"),
});
export const customerDependantInfoSchema = z.object({
firstNameEn: z.string().min(1, "First name is required"),
lastNameEn: z.string().min(1, "Last name is required"),
originAdd1: z.string().min(1, "Origin address is required"),
localAdd1: z.string().min(1, "Local address is required"),
});
export const customerDependantContactSchema = z.object({
email: z.string().email("Invalid email address"),
mobile: z.string().min(1, "Mobile number is required"),
});
export const customerDependantSchema = z.object({
id: z.number(),
custId: z.string(),
id: z.number().optional(),
firstNameEn: z.string(),
lastNameEn: z.string(),
email: z.string().email(),
email2: z.string().email().optional(),
// Add more fields as needed from the database schema
email: z.string(),
mobile: z.string(),
originAdd1: z.string(),
localAdd1: z.string(),
});
export const customerFormSchema = z.object({
customerInfo: customerInfoSchema,
customerContact: customerContactSchema,
customerDependants: z.array(customerDependantSchema),
});
export const customerDependantFormSchema = z.object({
dependantInfo: customerDependantInfoSchema,
dependantContact: customerDependantContactSchema,
});
export type CustomerInfo = z.infer<typeof customerInfoSchema>;
export type CustomerContact = z.infer<typeof customerContactSchema>;
export type CustomerDependant = z.infer<typeof customerDependantSchema>;
export type CustomerForm = z.infer<typeof customerFormSchema>;
export type CustomerDependantForm = z.infer<typeof customerDependantFormSchema>;