new booking implementation

This commit is contained in:
ATUL GUNJAL 2025-04-16 10:38:20 +05:30
parent 35e73223fa
commit eaff6a0b8a
12 changed files with 1143 additions and 517 deletions

View File

@ -1,6 +1,9 @@
"use client"; // Add this if you're using the App Router and need client-side interactivity "use client";
export default function Header({ currentToken, previousToken, nextToken, missedTokens }) {
// Extract missed tokens from props or calculate them
const missedTokensList = missedTokens || "J-134, J-159"; // Default or from props
export default function Header() {
return ( return (
<div className="flex grow flex-col items-center justify-between lg:flex-row lg:px-6 w-full"> <div className="flex grow flex-col items-center justify-between lg:flex-row lg:px-6 w-full">
<div className="hidden sm:hidden md:hidden lg:block lg:gap-16 lg:w-full lg:px-6 lg:py-3 xl:flex xl:gap-4 xl:w-full xl:px-6 2xl:flex 2xl:gap-16 2xl:w-full 2xl:px-6"> <div className="hidden sm:hidden md:hidden lg:block lg:gap-16 lg:w-full lg:px-6 lg:py-3 xl:flex xl:gap-4 xl:w-full xl:px-6 2xl:flex 2xl:gap-16 2xl:w-full 2xl:px-6">
@ -28,7 +31,7 @@ export default function Header() {
<div className="w-[43rem] h-[auto] border-2 rounded-[10px] px-2 py-2 flex flex-col gap-2"> <div className="w-[43rem] h-[auto] border-2 rounded-[10px] px-2 py-2 flex flex-col gap-2">
<h2 className="text-[14px] text-[#667085]">Missed Token</h2> <h2 className="text-[14px] text-[#667085]">Missed Token</h2>
<p className="text-[19px]"> <p className="text-[19px]">
J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159 {missedTokensList}
</p> </p>
<button className="bg-[#465FFF] text-white text-[8px] px-[24px] py-[4px] w-full rounded-[4px]"> <button className="bg-[#465FFF] text-white text-[8px] px-[24px] py-[4px] w-full rounded-[4px]">
View List View List
@ -39,17 +42,23 @@ export default function Header() {
<div className="lg:border-2 lg:rounded-[10px] lg:px-6 lg:py-6 lg:w-[50%] lg:h-[auto] lg:flex-col lg:items-center lg:gap-5 lg:hidden xl:block xl:border-2 xl:rounded-[10px] xl:px-6 xl:py-6 xl:w-[50%] xl:h-[full] xl:flex xl:flex-col xl:items-center xl:gap-5 2xl:border-2 2xl:rounded-[10px] 2xl:px-8 2xl:pt-6 2xl:pb-8 2xl:w-[50%] 2xl:h-[15rem] 2xl:flex 2xl:flex-col 2xl:items-center 2xl:gap-5"> <div className="lg:border-2 lg:rounded-[10px] lg:px-6 lg:py-6 lg:w-[50%] lg:h-[auto] lg:flex-col lg:items-center lg:gap-5 lg:hidden xl:block xl:border-2 xl:rounded-[10px] xl:px-6 xl:py-6 xl:w-[50%] xl:h-[full] xl:flex xl:flex-col xl:items-center xl:gap-5 2xl:border-2 2xl:rounded-[10px] 2xl:px-8 2xl:pt-6 2xl:pb-8 2xl:w-[50%] 2xl:h-[15rem] 2xl:flex 2xl:flex-col 2xl:items-center 2xl:gap-5">
<div> <div>
<h2 className="text-[14px] text-[#667085]">Current Token</h2> <h2 className="text-[14px] text-[#667085]">Current Token</h2>
<p className="font-bold text-[25px] text-center">J-369</p> <p className="font-bold text-[25px] text-center">
{currentToken || "---"}
</p>
</div> </div>
<div className="flex flex-row items-center gap-5 2xl:gap-[6rem]"> <div className="flex flex-row items-center gap-5 2xl:gap-[6rem]">
<div> <div>
<h2 className="text-[14px] text-[#667085]">Previous Token</h2> <h2 className="text-[14px] text-[#667085]">Previous Token</h2>
<p className="font-bold text-red-500 text-[25px] text-center">J-210</p> <p className="font-bold text-red-500 text-[25px] text-center">
{previousToken || "---"}
</p>
</div> </div>
<div> <div>
<h2 className="text-[14px] text-[#667085]">Next Token</h2> <h2 className="text-[14px] text-[#667085]">Next Token</h2>
<p className="text-green-500 font-bold text-[25px] text-center">J-309</p> <p className="text-green-500 font-bold text-[25px] text-center">
{nextToken || "---"}
</p>
</div> </div>
</div> </div>
@ -60,4 +69,4 @@ export default function Header() {
</div> </div>
</div> </div>
); );
} }

View File

@ -20,7 +20,7 @@ export default function DashboardPage() {
return ( return (
<div className="flex items-center justify-center min-h-screen bg-white dark:bg-gray-900"> <div className="flex items-center justify-center min-h-screen bg-white dark:bg-gray-900">
<div className="text-center"> <div className="text-center">
<div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${darkMode ? 'border-gray-100' : 'border-gray-900'} mx-auto`}></div> <div className={`animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto ${darkMode ? 'border-gray-100' : 'border-gray-900'} mx-auto`}></div>
<p className={`mt-4 text-lg font-semibold ${darkMode ? 'text-gray-100' : 'text-gray-900'}`}> <p className={`mt-4 text-lg font-semibold ${darkMode ? 'text-gray-100' : 'text-gray-900'}`}>
Loading... Loading...
</p> </p>

55
src/app/lib/api.js Normal file
View File

@ -0,0 +1,55 @@
// lib/api.js
import { databases, Query } from "./appwrite";
import { DATABASE_ID, COLLECTION_ID } from "./config";
export async function getTodayTokens() {
const today = new Date().toISOString().split('T')[0];
return databases.listDocuments(
DATABASE_ID,
COLLECTION_ID,
[
Query.equal('date', today),
Query.orderAsc('tokenId')
]
);
}
export async function getPatientTokens(patientId, date) {
return databases.listDocuments(
DATABASE_ID,
COLLECTION_ID,
[
Query.equal('patientId', patientId),
Query.equal('date', date),
Query.notEqual('status', 'done')
]
);
}
export async function createToken(document) {
return databases.createDocument(
DATABASE_ID,
COLLECTION_ID,
ID.unique(),
document
);
}
export async function updateTokenStatus(documentId, status) {
return databases.updateDocument(
DATABASE_ID,
COLLECTION_ID,
documentId,
{ status }
);
}
export async function getSettings() {
return databases.getDocument(
DATABASE_ID,
'settings',
'current_settings' // Single document ID
);
}
export { DATABASE_ID, COLLECTION_ID };

View File

@ -1,14 +1,121 @@
import { Client, Account, Databases, ID } from "appwrite"; import { Client, Account, Databases, Query, ID } from "appwrite";
// Initialize Appwrite Client const client = new Client()
const client = new Client(); .setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT)
client .setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID);
.setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT) // Use environment variable
.setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID); // Use environment variable
// Services
const account = new Account(client); const account = new Account(client);
const databases = new Databases(client); const databases = new Databases(client);
// Export everything, including `ID`
export { account, databases, ID }; const DATABASE_ID = process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID;
const COLLECTION_ID = process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_ID;
// Initialize with proper schema
async function initDatabase() {
try {
// Main tokens collection
await databases.createCollection(
DATABASE_ID,
COLLECTION_ID,
"Token Management"
);
// Add attributes matching new schema
await databases.createStringAttribute(
DATABASE_ID,
COLLECTION_ID,
"tokenId",
20,
true
);
await databases.createDatetimeAttribute(
DATABASE_ID,
COLLECTION_ID,
"date",
true
);
await databases.createStringAttribute(
DATABASE_ID,
COLLECTION_ID,
"patientName",
100,
true
);
await databases.createStringAttribute(
DATABASE_ID,
COLLECTION_ID,
"patientId",
50,
false
);
await databases.createEnumAttribute(
DATABASE_ID,
COLLECTION_ID,
"bookedBy",
["self", "staff"]
);
await databases.createEnumAttribute(
DATABASE_ID,
COLLECTION_ID,
"status",
["booked", "done", "missed"]
);
// Settings collection
await databases.createCollection(
DATABASE_ID,
'settings',
"System Settings"
);
await databases.createIntegerAttribute(
DATABASE_ID,
'settings',
"avgConsultationTime",
true
);
} catch (error) {
console.error("Initialization error:", error);
if (!error.message.includes('already exists')) {
throw error;
}
}
}
// Date-based token generator
// lib/appwrite.js
async function generateTokenNumber(date) {
// Step 1: Get all documents for the selected date
const response = await databases.listDocuments(
DATABASE_ID,
COLLECTION_ID,
[Query.equal("date", date)]
);
// Step 2: Get the next token count
const nextNumber = response.total + 1;
// Step 3: Pad the number with zeros (e.g., 1 => 001)
const paddedToken = String(nextNumber).padStart(3, '0');
return paddedToken;
}
export {
client,
account,
databases,
DATABASE_ID,
COLLECTION_ID,
Query,
ID,
initDatabase,
generateTokenNumber,
};

11
src/app/lib/config.js Normal file
View File

@ -0,0 +1,11 @@
// lib/config.js
// export const DATABASE_ID = "entries_db";
// export const COLLECTION_ID = "entries";
// export const TOKEN_COLLECTION_ID = "token_sequences";
// lib/config.js
export const DATABASE_ID = "67e1452b00016444b37f";
export const COLLECTION_ID = "67fe4029000f7e0a7b92";
export const SETTINGS_COLLECTION_ID = "settings";
export const AVG_CONSULTATION_KEY = "avg_consultation";

View File

@ -26,7 +26,7 @@ export default function Home() {
{/* Spinner */} {/* Spinner */}
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 dark:border-gray-100 mx-auto"></div> <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 dark:border-gray-100 mx-auto"></div>
{/* Loading Text */} {/* Loading Text */}
<p className="mt-4 text-lg font-semibold text-gray-900 dark:text-gray-100"> <p className="mt-4 text-lg font-semibold text-gray-900 dark:text-gray-100 ">
Loading... Loading...
</p> </p>
</div> </div>

View File

@ -1,79 +1,190 @@
import Head from 'next/head'; "use client";
import { useState, useEffect } from "react";
import { databases, ID, Query } from "../../lib/appwrite";
import { DATABASE_ID, COLLECTION_ID } from "../../lib/api";
import Header from "../../components/partials/header"; import Header from "../../components/partials/header";
import { useTheme } from "../../context/ThemeContext";
export default function MultiBooked() { export default function MultiBooked() {
const { darkMode } = useTheme();
const [appointmentDate, setAppointmentDate] = useState(new Date().toISOString().split('T')[0]);
const [bookings, setBookings] = useState([
{ id: 1, name: "", tokenNumber: "" },
{ id: 2, name: "", tokenNumber: "" },
{ id: 3, name: "", tokenNumber: "" },
{ id: 4, name: "", tokenNumber: "" },
{ id: 5, name: "", tokenNumber: "" }
]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const bookingData = sessionStorage.getItem('multiBookingData');
if (bookingData) {
const { date, patients } = JSON.parse(bookingData);
setAppointmentDate(date);
setBookings(patients.map(p => ({ ...p, tokenNumber: "" })));
sessionStorage.removeItem('multiBookingData');
}
}, []);
// ------------------create entries--------------------------------
const createEntries = async () => {
setLoading(true);
setError(null);
try {
const validBookings = bookings.filter(b => b.name.trim() !== "");
if (validBookings.length === 0) {
throw new Error("Please enter at least one patient name");
}
// Step 1: Get the highest token number
const response = await databases.listDocuments(
DATABASE_ID,
COLLECTION_ID,
[Query.orderDesc('tokenNumber'), Query.limit(1)]
);
let lastTokenNum = response.documents[0]
? parseInt(response.documents[0].tokenNumber)
: 0;
// Step 2: Prepare all token numbers first
const tokenAssignments = validBookings.map((_, index) => {
return (lastTokenNum + index + 1).toString().padStart(3, '0');
});
// Step 3: Create documents and update state
const updatedBookings = [...bookings];
let bookingIndex = 0;
for (let i = 0; i < bookings.length; i++) {
if (bookings[i].name.trim() !== "") {
await databases.createDocument(
DATABASE_ID,
COLLECTION_ID,
ID.unique(),
{
tokenNumber: tokenAssignments[bookingIndex],
patientName: bookings[i].name,
date: appointmentDate,
bookedBy: "staff",
status: "booked",
patientId: ID.unique(),
}
);
updatedBookings[i].tokenNumber = tokenAssignments[bookingIndex];
bookingIndex++;
}
}
setBookings(updatedBookings);
alert(`${validBookings.length} tokens created successfully!`);
} catch (error) {
console.error("Creation error:", error);
setError(error.message);
} finally {
setLoading(false);
}
};
const handleNameChange = (id, value) => {
setBookings(bookings.map(b =>
b.id === id ? { ...b, name: value } : b
));
};
return ( return (
<> <div className={`flex h-screen overflow-hidden ${darkMode ? 'bg-gray-900' : 'bg-white'}`}>
<Head> <div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
<title>eCommerce Dashboard | TailAdmin - Tailwind CSS Admin Dashboard Template</title> <Header />
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<meta httpEquiv="X-UA-Compatible" content="ie=edge" />
</Head>
<div className="flex h-screen overflow-hidden"> <main>
{/* Content Area */} <div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6">
<div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto"> {error && (
{/* Header would be included here */} <div className="mb-4 p-4 bg-red-100 text-red-700 rounded">
<Header /> {error}
</div>
)}
{/* Main Content */} <div className="mb-8">
<main> <h2 className={`text-2xl mb-4 ${darkMode ? 'text-white' : 'text-black'}`}>
<div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6"> Staff Multi-Booking
<div> </h2>
<h2 className="text-2xl">Generate Appointment Code</h2> <div className="mb-4">
<label htmlFor="appointmentDate">Date: <label htmlFor="appointmentDate" className={`block mb-2 ${darkMode ? 'text-gray-300' : 'text-gray-700'}`}>
<input type="date" name="appointmentDate" id="appointmentDate" /> Date:
</label> </label>
</div> <input
type="date"
<div className="max-w-2xl mx-auto my-20 lg:my-32"> id="appointmentDate"
<div className="space-y-4 text-center mb-6 lg:mb-16"> value={appointmentDate}
<div className="flex justify-between items-center mx-4"> onChange={(e) => setAppointmentDate(e.target.value)}
<h2 className="text-2xl"><span>1.</span> John Doe</h2> className={`p-2 border rounded ${darkMode ? 'bg-gray-800 text-white border-gray-700' : 'bg-white'}`}
<h1 className="text-3xl text-blue-800">35</h1> />
</div>
<div className="flex justify-between items-center mx-4">
<h2 className="text-2xl"><span>2.</span> John Doe</h2>
<h1 className="text-3xl text-blue-800">63</h1>
</div>
<div className="flex justify-between items-center mx-4">
<h2 className="text-2xl"><span>3.</span> John Doe</h2>
<h1 className="text-3xl text-blue-800">45</h1>
</div>
<div className="flex justify-between items-center mx-4">
<h2 className="text-2xl"><span>4.</span> John Doe</h2>
<h1 className="text-3xl text-blue-800">15</h1>
</div>
<div className="flex justify-between items-center mx-4">
<h2 className="text-2xl"><span>5.</span> John Doe</h2>
<h1 className="text-3xl text-blue-800">06</h1>
</div>
</div>
<div className="flex flex-col gap-4 md:flex-row w-full">
<a href="/staff-booking.html" className="w-full">
<button
className="text-center rounded-lg bg-blue-700 px-5 py-3.5 text-sm font-medium text-white shadow-theme-xs transition hover:bg-blue-600 w-full"
>
Book Another
</button>
</a>
<a href="#" className="w-full">
<button
className="text-center rounded-lg bg-white px-5 py-3.5 text-sm font-medium text-gray-700 shadow-theme-xs ring-1 ring-inset ring-gray-300 transition hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-400 dark:ring-gray-700 dark:hover:bg-white/[0.03] w-full"
>
Manage
</button>
</a>
</div>
</div>
<div className="text-center">
<p>Note: Token booking is available for current date only i.e. Today</p>
</div> </div>
</div> </div>
</main>
</div> <div className="max-w-2xl mx-auto my-8">
<div className="space-y-4 mb-8">
{bookings.map((booking) => (
<div key={booking.id} className="flex flex-col md:flex-row gap-4 items-center">
<div className="w-full md:w-3/4">
<label className={`block mb-1 ${darkMode ? 'text-gray-300' : 'text-gray-700'}`}>
Patient {booking.id} Name:
</label>
<input
type="text"
value={booking.name}
onChange={(e) => handleNameChange(booking.id, e.target.value)}
placeholder="Enter patient name"
className={`w-full p-2 border rounded ${darkMode ? 'bg-gray-800 text-white border-gray-700' : 'bg-white'}`}
/>
</div>
<div className="w-full md:w-1/4">
<label className={`block mb-1 ${darkMode ? 'text-gray-300' : 'text-gray-700'}`}>
Token:
</label>
<div className={`p-2 font-mono text-center rounded ${darkMode ? 'bg-gray-800 text-blue-400' : 'bg-blue-50 text-blue-800'}`}>
{booking.tokenNumber || "---"}
</div>
</div>
</div>
))}
</div>
<div className="flex flex-col gap-4 md:flex-row w-full">
<button
onClick={createEntries}
disabled={loading}
className={`text-center rounded-lg px-5 py-3.5 text-sm font-medium text-white shadow-theme-xs transition w-full ${
loading ? 'bg-blue-400 cursor-not-allowed' : 'bg-blue-700 hover:bg-blue-600'
}`}
>
{loading ? 'Creating Tokens...' : 'Create Tokens'}
</button>
<a href="pages/entries" className="w-full">
<button
className={`text-center rounded-lg px-5 py-3.5 text-sm font-medium shadow-theme-xs ring-1 ring-inset transition w-full ${
darkMode ? 'bg-gray-800 text-gray-300 ring-gray-700 hover:bg-gray-700' :
'bg-white text-gray-700 ring-gray-300 hover:bg-gray-50'
}`}
>
View All Entries
</button>
</a>
</div>
</div>
<div className={`text-center mt-8 ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
<p>Staff can book multiple tokens at once. All tokens will be assigned for the same date.</p>
</div>
</div>
</main>
</div> </div>
</> </div>
); );
} }

View File

@ -1,76 +1,173 @@
"use client"; "use client";
import Head from 'next/head';
import { useState } from 'react'; import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Header from "../../components/partials/header"; import Header from "../../components/partials/header";
import { useTheme } from "../../context/ThemeContext";
export default function BookAppointment() { export default function MultiBooking() {
const [darkMode, setDarkMode] = useState(false); const { darkMode } = useTheme();
const router = useRouter();
const [appointmentDate, setAppointmentDate] = useState(new Date().toISOString().split('T')[0]);
const [patients, setPatients] = useState(
Array(5).fill().map((_, i) => ({ id: i+1, name: "" }))
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleNameChange = (id, value) => {
setPatients(patients.map(p =>
p.id === id ? { ...p, name: value } : p
));
};
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
// Filter out empty names and validate
const validPatients = patients.filter(p => p.name.trim() !== "");
if (validPatients.length === 0) {
throw new Error("Please enter at least one patient name");
}
// Store in session to use in MultiBooked page
sessionStorage.setItem('multiBookingData', JSON.stringify({
date: appointmentDate,
patients: validPatients
}));
router.push('/pages/MultiBooked');
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
};
const addMorePatients = () => {
const newId = patients.length > 0 ?
Math.max(...patients.map(p => p.id)) + 1 : 1;
setPatients([...patients, { id: newId, name: "" }]);
};
return ( return (
<div className={`flex h-screen overflow-hidden ${darkMode ? 'dark bg-gray-900' : ''}`}> <div className={`flex h-screen overflow-hidden ${darkMode ? 'dark bg-gray-900' : 'bg-white'}`}>
<Head>
<title>eCommerce Dashboard | TailAdmin - Tailwind CSS Admin Dashboard Template</title>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<meta httpEquiv="X-UA-Compatible" content="ie=edge" />
</Head>
{/* Content Area */} {/* Content Area */}
<div className="relative flex flex-1 flex-col overflow-x-hidden overflow-y-auto"> <div className="relative flex flex-1 flex-col overflow-x-hidden overflow-y-auto">
{/* Sticky Header */} {/* Sticky Header */}
<header className="sticky top-0 z-50 bg-white shadow-sm dark:bg-gray-800"> <header className="sticky top-0 z-50 bg-white shadow-sm dark:bg-gray-800">
<div className="flex items-center justify-between p-4"> <div className="flex items-center justify-between p-4">
<Header></Header> <Header />
</div> </div>
</header> </header>
{/* Main Content */} {/* Main Content */}
<main className="flex-1 overflow-y-auto"> <main className="flex-1 overflow-y-auto">
<div className="mx-auto max-w-[--breakpoint-2xl] p-4 md:p-6 pt-20"> {/* Added pt-20 to account for sticky header */} <div className="mx-auto max-w-[--breakpoint-2xl] p-4 md:p-6 pt-20">
<div> {error && (
<h2 className="text-2xl">Book Appointment</h2> <div className="mb-4 p-4 bg-red-100 text-red-700 rounded-md">
<label htmlFor="appointmentDate"> {error}
Date: </div>
)}
<div className="mb-6">
<h2 className={`text-2xl mb-2 ${darkMode ? 'text-white' : 'text-black'}`}>
Staff Multi-Booking
</h2>
<div className="flex items-center">
<label className={`mr-2 ${darkMode ? 'text-gray-300' : 'text-gray-700'}`}>
Date:
</label>
<input <input
type="date" type="date"
name="appointmentDate" value={appointmentDate}
id="appointmentDate" onChange={(e) => setAppointmentDate(e.target.value)}
className="ml-2 p-1 border rounded" className={`p-1 border rounded ${darkMode ? 'bg-gray-800 text-white border-gray-700' : 'bg-white'}`}
/> />
</label> </div>
</div> </div>
<div className="mx-auto my-20 flex max-w-2xl flex-col items-center justify-center gap-6 lg:my-32"> <form onSubmit={handleSubmit} className="max-w-2xl mx-auto my-8">
<div className="w-full space-y-4"> <div className="space-y-4 mb-6">
{[1, 2, 3, 4, 5].map((item) => ( {patients.map((patient) => (
<div key={item}> <div key={patient.id} className="flex items-center gap-3">
<label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400"> <span className={`w-6 text-right ${darkMode ? 'text-gray-300' : 'text-gray-700'}`}>
Enter Name {patient.id}.
</label> </span>
<input <input
type="text" type="text"
placeholder="John Doe" value={patient.name}
className="dark:bg-dark-900 shadow-theme-xs focus:border-blue-300 focus:ring-blue-500/10 dark:focus:border-blue-800 h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 placeholder:text-gray-400 focus:ring-3 focus:outline-hidden dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30" onChange={(e) => handleNameChange(patient.id, e.target.value)}
placeholder="Patient name"
className={`flex-1 shadow-theme-xs h-11 rounded-lg border px-4 py-2.5 text-sm focus:outline-none focus:ring-2 ${
darkMode ?
'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:border-blue-800 focus:ring-blue-800/30' :
'bg-white border-gray-300 text-gray-800 placeholder-gray-400 focus:border-blue-300 focus:ring-blue-500/10'
}`}
/> />
{patient.id > 5 && (
<button
type="button"
onClick={() => setPatients(patients.filter(p => p.id !== patient.id))}
className={`p-2 rounded-full ${
darkMode ? 'text-red-400 hover:bg-gray-700' : 'text-red-500 hover:bg-gray-100'
}`}
>
</button>
)}
</div> </div>
))} ))}
</div> </div>
<div className="w-full">
<a href="/multi-booked.html"> <div className="flex flex-wrap gap-3 mb-6">
<button <button
className="bg-blue-500 shadow-theme-xs hover:bg-blue-600 w-full rounded-lg px-5 py-3.5 text-center text-sm font-medium text-white transition" type="button"
> onClick={addMorePatients}
Submit className={`px-4 py-2 rounded-lg text-sm font-medium ${
</button> darkMode ?
</a> 'bg-gray-700 text-white hover:bg-gray-600' :
'bg-gray-200 text-gray-700 hover:bg-gray-300'
}`}
>
+ Add More Patients
</button>
<div className="text-sm text-gray-500 dark:text-gray-400 mt-1">
{patients.length} patients entered
</div>
</div> </div>
</div>
<div className="flex flex-col gap-4 md:flex-row w-full">
<button
type="submit"
disabled={loading}
className={`text-center rounded-lg px-5 py-3.5 text-sm font-medium text-white shadow-theme-xs transition w-full ${
loading ? 'bg-blue-400 cursor-not-allowed' : 'bg-blue-700 hover:bg-blue-600'
}`}
>
{loading ? 'Processing...' : 'Generate Tokens'}
</button>
<button
type="button"
onClick={() => router.push('/entries')}
className={`text-center rounded-lg px-5 py-3.5 text-sm font-medium shadow-theme-xs ring-1 ring-inset transition w-full ${
darkMode ?
'bg-gray-800 text-gray-300 ring-gray-700 hover:bg-gray-700' :
'bg-white text-gray-700 ring-gray-300 hover:bg-gray-50'
}`}
>
View All Entries
</button>
</div>
</form>
<div className="text-center"> <div className={`text-center mt-8 text-sm ${
<p> darkMode ? 'text-gray-400' : 'text-gray-600'
Note: Token booking is available for current date only i.e. }`}>
Today <p>Staff can book multiple tokens at once. All tokens will be assigned for the same date.</p>
</p> <p className="mt-1">Minimum 1 patient required. Maximum 20 patients per batch.</p>
</div> </div>
</div> </div>
</main> </main>

View File

@ -1,62 +1,123 @@
"use client";
import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { databases, ID, Query } from "../../lib/appwrite"; // Added Query import
import { DATABASE_ID, COLLECTION_ID } from "../../lib/api";
import Header from '../../components/partials/header'; import Header from '../../components/partials/header';
import Head from 'next/head';
import Link from 'next/link'; import Link from 'next/link';
export default function SingleBooked() { export default function SingleBooked() {
const searchParams = useSearchParams();
const nameParam = searchParams.get('name');
const dateParam = searchParams.get('date');
const [appointmentDate] = useState(dateParam || new Date().toISOString().split('T')[0]);
const [name] = useState(nameParam || '');
const [token, setToken] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const generateTokenNumber = async (date) => {
try {
// Get the highest token number for the date
const response = await databases.listDocuments(
DATABASE_ID,
COLLECTION_ID,
[
Query.equal('date', date),
Query.orderDesc('tokenNumber'),
Query.limit(1)
]
);
const lastToken = response.documents[0]?.tokenNumber || "000";
return (parseInt(lastToken) + 1).toString().padStart(3, '0');
} catch (error) {
console.error("Token generation error:", error);
return "001"; // Fallback token number
}
};
const createBooking = async () => {
try {
setLoading(true);
setError(null);
const generatedToken = await generateTokenNumber(appointmentDate);
await databases.createDocument(
DATABASE_ID,
COLLECTION_ID,
ID.unique(),
{
tokenNumber: generatedToken,
date: appointmentDate,
patientName: name,
status: "booked",
bookedBy: "staff",
patientId: ID.unique(),
}
);
setToken(generatedToken);
} catch (error) {
console.error("Booking error:", error);
setError(error.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
if (name && appointmentDate) {
createBooking();
}
}, [name, appointmentDate]);
return ( return (
<> <div className="flex h-screen overflow-hidden">
<div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
<div className="flex h-screen overflow-hidden"> <div className="flex bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-50 w-full">
{/* Sidebar would go here */}
<div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
{/* Small Device Overlay would go here */}
{/* Header would go here */}
<div className='flex bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-50 w-full'>
<Header /> <Header />
</div>
<main>
<div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6">
<div>
<h2 className="text-2xl">Generate Appointment Code</h2>
<label htmlFor="appointmentDate">
Date:
<input type="date" name="appointmentDate" id="appointmentDate" />
</label>
</div>
<div className="max-w-2xl mx-auto my-20 lg:my-32">
<div className="text-center mb-6 lg:mb-16">
<h1 className="text-6xl text-blue-700 md:text-8xl">35</h1>
<h2 className="text-2xl">John Doe</h2>
</div>
<div className="flex flex-col gap-4 md:flex-row w-full">
<Link href="/staff-booking" className="w-full">
<button
className="text-center rounded-lg bg-blue-700 px-5 py-3.5 text-sm font-medium text-white shadow-theme-xs transition hover:bg-brand-600 w-full"
>
Book Another
</button>
</Link>
<Link href="#" className="w-full">
<button
className="text-center rounded-lg bg-white px-5 py-3.5 text-sm font-medium text-gray-700 shadow-theme-xs ring-1 ring-inset ring-gray-300 transition hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-400 dark:ring-gray-700 dark:hover:bg-white/[0.03] w-full"
>
Manage
</button>
</Link>
</div>
</div>
<div className="text-center">
<p>Note: Token booking is available for current date only i.e. Today</p>
</div>
</div>
</main>
</div> </div>
<main>
<div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6">
{error && (
<div className="mb-4 p-4 bg-red-100 text-red-700 rounded">
{error}
</div>
)}
<div className="text-center my-10">
<h2 className="text-xl mb-2">Staff Booking</h2>
<p className="text-2xl font-bold mb-4">{name || 'Staff Booking'}</p>
<h2 className="text-xl mb-2">Token Number:</h2>
<p className="text-6xl text-blue-700">
{loading ? 'Generating...' : token || '---'}
</p>
</div>
<div className="flex flex-col gap-4 md:flex-row w-full max-w-lg mx-auto">
<Link href="/pages/StaffBooking" className="w-full">
<button className="rounded-lg bg-blue-700 px-5 py-3.5 text-sm font-medium text-white hover:bg-blue-800 w-full">
Book Another
</button>
</Link>
<Link href="/pages/entries" className="w-full">
<button className="rounded-lg bg-white px-5 py-3.5 text-sm font-medium text-gray-700 border border-gray-300 hover:bg-gray-100 w-full">
View All Entries
</button>
</Link>
</div>
<p className="text-center mt-6 text-sm text-gray-600">
Staff token booking system
</p>
</div>
</main>
</div> </div>
</> </div>
); );
} }

View File

@ -1,21 +1,20 @@
'use client'; 'use client';
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Head from 'next/head'; import Head from 'next/head';
import Link from 'next/link'; import Preloader from '../../components/partials/preloaders';
import Preloader from "../../components/partials/preloaders"; import Overlay from '../../components/partials/overlay';
// import Sidebar from '@/app/partials/sidebar'; import Header from '../../components/partials/header';
import Overlay from "../../components/partials/overlay";
import Header from "../../components/partials/header";
export default function SingleBooking() { export default function SingleBooking() {
const [darkMode, setDarkMode] = useState(false); const [darkMode, setDarkMode] = useState(false);
const [loaded, setLoaded] = useState(false); const [loaded, setLoaded] = useState(false);
const [name, setName] = useState(''); const [name, setName] = useState('');
const [appointmentDate, setAppointmentDate] = useState(''); const [appointmentDate, setAppointmentDate] = useState('');
const router = useRouter();
useEffect(() => { useEffect(() => {
// Load dark mode preference from localStorage
const savedDarkMode = JSON.parse(localStorage.getItem('darkMode')); const savedDarkMode = JSON.parse(localStorage.getItem('darkMode'));
if (savedDarkMode !== null) { if (savedDarkMode !== null) {
setDarkMode(savedDarkMode); setDarkMode(savedDarkMode);
@ -24,13 +23,19 @@ export default function SingleBooking() {
}, []); }, []);
useEffect(() => { useEffect(() => {
// Save dark mode preference to localStorage when it changes
localStorage.setItem('darkMode', JSON.stringify(darkMode)); localStorage.setItem('darkMode', JSON.stringify(darkMode));
}, [darkMode]); }, [darkMode]);
const handleSubmit = (e) => { const handleSubmit = (e) => {
e.preventDefault(); e.preventDefault();
// Handle form submission logic here
if (!name || !appointmentDate) {
alert('Please fill all the fields');
return;
}
// Navigate to confirmation page with name and appointmentDate as query params
router.push(`/pages/SingleBooked?name=${encodeURIComponent(name)}&date=${encodeURIComponent(appointmentDate)}`);
}; };
if (!loaded) { if (!loaded) {
@ -40,7 +45,7 @@ export default function SingleBooking() {
return ( return (
<div className={`flex flex-col min-h-screen ${darkMode ? 'dark bg-gray-900' : ''}`}> <div className={`flex flex-col min-h-screen ${darkMode ? 'dark bg-gray-900' : ''}`}>
<Head> <Head>
<title>eCommerce Dashboard | TailAdmin - Tailwind CSS Admin Dashboard Template</title> <title>Book Appointment</title>
<meta charSet="UTF-8" /> <meta charSet="UTF-8" />
<meta <meta
name="viewport" name="viewport"
@ -49,119 +54,59 @@ export default function SingleBooking() {
<meta httpEquiv="X-UA-Compatible" content="ie=edge" /> <meta httpEquiv="X-UA-Compatible" content="ie=edge" />
</Head> </Head>
{/* ===== Page Wrapper Start ===== */}
<div className="flex h-screen overflow-hidden"> <div className="flex h-screen overflow-hidden">
{/* ===== Sidebar Start ===== */}
{/* <Sidebar /> */}
{/* ===== Sidebar End ===== */}
{/* ===== Content Area Start ===== */}
<div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto"> <div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
{/* Small Device Overlay Start */}
<Overlay /> <Overlay />
{/* Small Device Overlay End */}
{/* ===== Header Start ===== */} <div className="flex bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-50 w-full">
<Header />
<div darkMode={darkMode} setDarkMode={setDarkMode} className='flex bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-50 w-full'> </div>
<Header />
</div>
{/* ===== Header End ===== */}
{/* ===== Main Content Start ===== */}
<main> <main>
<div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6"> <div className="p-4 mx-auto max-w-4xl md:p-6">
<div> <h2 className="text-2xl font-semibold mb-6 text-gray-800 dark:text-white">Book Appointment</h2>
<h2 className="text-2xl">Book Appointment</h2>
<label htmlFor="appointmentDate"> <form onSubmit={handleSubmit} className="space-y-6">
Date: <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1.5">
Appointment Date
</label>
<input <input
type="date" type="date"
name="appointmentDate"
id="appointmentDate"
value={appointmentDate} value={appointmentDate}
onChange={(e) => setAppointmentDate(e.target.value)} onChange={(e) => setAppointmentDate(e.target.value)}
className="ml-2" className="h-11 w-full rounded-lg border border-gray-300 bg-white dark:bg-gray-900 px-4 py-2.5 text-sm text-gray-800 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
/> />
</label> </div>
</div>
<div>
<div className="flex flex-col items-center justify-center gap-6 max-w-2xl mx-auto my-20 lg:my-32"> <label className="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1.5">
<div className="w-full"> Full Name
<label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
Enter Name
</label> </label>
<input <input
type="text" type="text"
placeholder="John Doe" placeholder="John Doe"
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
className="dark:bg-dark-900 shadow-theme-xs focus:border-brand-300 focus:ring-brand-500/10 dark:focus:border-brand-800 h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 placeholder:text-gray-400 focus:ring-3 focus:outline-hidden dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30" className="h-11 w-full rounded-lg border border-gray-300 bg-white dark:bg-gray-900 px-4 py-2.5 text-sm text-gray-800 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="w-full">
<label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
Enter Name
</label>
<input
type="text"
placeholder="John Doe"
value={name}
onChange={(e) => setName(e.target.value)}
className="dark:bg-dark-900 shadow-theme-xs focus:border-brand-300 focus:ring-brand-500/10 dark:focus:border-brand-800 h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 placeholder:text-gray-400 focus:ring-3 focus:outline-hidden dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30"
/> />
</div> </div>
<div className="w-full"> <button
<label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400"> type="submit"
Enter Name className="w-full rounded-lg bg-blue-700 px-5 py-3.5 text-sm font-medium text-white hover:bg-blue-800 transition duration-200"
</label> >
<input Submit
type="text" </button>
placeholder="John Doe" </form>
value={name}
onChange={(e) => setName(e.target.value)}
className="dark:bg-dark-900 shadow-theme-xs focus:border-brand-300 focus:ring-brand-500/10 dark:focus:border-brand-800 h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 placeholder:text-gray-400 focus:ring-3 focus:outline-hidden dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30"
/>
</div>
<div className="w-full"> <div className="mt-6 text-center text-sm text-gray-600 dark:text-gray-300">
<label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400"> Note: Token booking is available for the current date only (Today).
Enter Name
</label>
<input
type="text"
placeholder="John Doe"
value={name}
onChange={(e) => setName(e.target.value)}
className="dark:bg-dark-900 shadow-theme-xs focus:border-brand-300 focus:ring-brand-500/10 dark:focus:border-brand-800 h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 placeholder:text-gray-400 focus:ring-3 focus:outline-hidden dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30"
/>
</div>
<div className="w-full">
<Link href="/single-booked">
<button
className="text-center rounded-lg bg-blue-700 px-5 py-3.5 text-sm font-medium text-white shadow-theme-xs transition hover:bg-blue-800 w-full"
onClick={handleSubmit}
>
Submit
</button>
</Link>
</div>
</div>
<div className="text-center">
<p>Note: Token booking is available for current date only i.e. Today</p>
</div> </div>
</div> </div>
</main> </main>
{/* ===== Main Content End ===== */}
</div> </div>
{/* ===== Content Area End ===== */}
</div> </div>
{/* ===== Page Wrapper End ===== */}
</div> </div>
); );
} }

View File

@ -1,133 +1,246 @@
'use client'; // Required for client-side interactivity 'use client';
import Image from 'next/image';
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import Head from 'next/head'; import { useRouter } from 'next/navigation';
import Link from 'next/link'; import { databases, Query } from "../../lib/appwrite";
import { DATABASE_ID, COLLECTION_ID } from "../../lib/api";
// Import components (you'll need to create these)
import Preloader from "../../components/partials/preloaders";
// import Sidebar from '@/app/partials/sidebar';
import Overlay from "../../components/partials/overlay";
import Header from "../../components/partials/header"; import Header from "../../components/partials/header";
import { useTheme } from "../../context/ThemeContext";
export default function BookingPage() { export default function StaffBooking() {
const [darkMode, setDarkMode] = useState(false); const { darkMode } = useTheme();
const [loaded, setLoaded] = useState(false); const router = useRouter();
const [appointmentDate, setAppointmentDate] = useState(''); const [appointmentDate, setAppointmentDate] = useState(new Date().toISOString().split('T')[0]);
const [recentBookings, setRecentBookings] = useState([]);
const [stats, setStats] = useState({
totalTokens: 0,
avgWaitTime: 0,
booked: 0,
done: 0,
missed: 0
});
const [loading, setLoading] = useState(true);
useEffect(() => { useEffect(() => {
// Load dark mode preference from localStorage const fetchData = async () => {
const savedDarkMode = JSON.parse(localStorage.getItem('darkMode')); try {
if (savedDarkMode !== null) { const today = new Date().toISOString().split('T')[0];
setDarkMode(savedDarkMode);
} // Fetch recent bookings (last 5)
setLoaded(true); const recentResponse = await databases.listDocuments(
DATABASE_ID,
COLLECTION_ID,
[
Query.equal('date', today),
Query.orderDesc('$createdAt'),
Query.limit(5)
]
);
setRecentBookings(recentResponse.documents);
// Fetch statistics
const statsResponse = await databases.listDocuments(
DATABASE_ID,
COLLECTION_ID,
[Query.equal('date', today)]
);
const allTokens = statsResponse.documents;
const bookedTokens = allTokens.filter(t => t.status === 'booked');
const doneTokens = allTokens.filter(t => t.status === 'done');
const missedTokens = allTokens.filter(t => t.status === 'missed');
// Calculate average wait time (simplified)
const avgWaitTime = bookedTokens.length > 0 ?
Math.round((bookedTokens.length * 15) / bookedTokens.length) : 0;
setStats({
totalTokens: allTokens.length,
avgWaitTime,
booked: bookedTokens.length,
done: doneTokens.length,
missed: missedTokens.length
});
} catch (error) {
console.error("Error fetching data:", error);
} finally {
setLoading(false);
}
};
fetchData();
}, []); }, []);
useEffect(() => { const updateStatus = async (documentId, newStatus) => {
// Save dark mode preference to localStorage when it changes try {
localStorage.setItem('darkMode', JSON.stringify(darkMode)); await databases.updateDocument(
}, [darkMode]); DATABASE_ID,
COLLECTION_ID,
documentId,
{ status: newStatus }
);
// Refresh data after update
const updated = recentBookings.map(booking =>
booking.$id === documentId ? { ...booking, status: newStatus } : booking
);
setRecentBookings(updated);
} catch (error) {
console.error("Update error:", error);
}
};
if (!loaded) { if (loading) {
return <Preloader />; return <div className="flex items-center justify-center min-h-screen">
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
</div>;
} }
return ( return (
<div className={`flex flex-col min-h-screen ${darkMode ? 'dark bg-gray-900' : ''}`}> <div className={`flex flex-col min-h-screen ${darkMode ? 'dark bg-gray-900' : 'bg-white'}`}>
<Head>
<title>eCommerce Dashboard | TailAdmin - Tailwind CSS Admin Dashboard Template</title>
<meta charSet="UTF-8" />
<meta
name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
/>
<meta httpEquiv="X-UA-Compatible" content="ie=edge" />
</Head>
{/* ===== Page Wrapper Start ===== */}
<div className="flex h-screen overflow-hidden"> <div className="flex h-screen overflow-hidden">
{/* ===== Sidebar Start ===== */}
{/* <Sidebar /> */}
{/* ===== Sidebar End ===== */}
{/* ===== Content Area Start ===== */}
<div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto"> <div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
{/* Small Device Overlay Start */} <div className={`flex ${darkMode ? 'bg-gray-800' : 'bg-white'} shadow-sm sticky top-0 z-50 w-full`}>
<Overlay />
{/* Small Device Overlay End */}
{/* ===== Header Start ===== */}
<div darkMode={darkMode} setDarkMode={setDarkMode} className='flex bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-50 w-full'>
<Header /> <Header />
</div> </div>
{/* ===== Header End ===== */}
{/* ===== Main Content Start ===== */} <main className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6">
<main> {/* Statistics Overview */}
<div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6"> <div className={`mb-8 p-6 rounded-lg ${darkMode ? 'bg-gray-800' : 'bg-gray-50'} border ${darkMode ? 'border-gray-700' : 'border-gray-200'}`}>
<div> <h3 className={`text-lg font-medium mb-4 ${darkMode ? 'text-white' : 'text-gray-800'}`}>
<h2 className="text-2xl">Book Appointment</h2> Today's Overview
<label htmlFor="appointmentDate"> </h3>
Date: <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<input <div className={`p-4 rounded-lg text-center ${darkMode ? 'bg-gray-700' : 'bg-white'} border ${darkMode ? 'border-gray-600' : 'border-gray-200'}`}>
type="date" <p className={`text-sm ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>Total Tokens</p>
name="appointmentDate" <p className={`text-2xl font-bold ${darkMode ? 'text-white' : 'text-gray-900'}`}>{stats.totalTokens}</p>
id="appointmentDate"
value={appointmentDate}
onChange={(e) => setAppointmentDate(e.target.value)}
className="ml-2"
/>
</label>
</div>
<div className="flex flex-col items-center justify-center gap-6 lg:gap-24 lg:flex-row max-w-2xl mx-auto my-20 lg:my-32 lg:max-w-4xl">
<div className="lg:w-full">
<img
src="/images/user/appointment-booking-with-calendar 1.png"
alt="Appointment booking illustration"
className="w-full"
/>
</div> </div>
<div className="flex flex-col gap-4 md:flex-row lg:flex-col w-full"> <div className={`p-4 rounded-lg text-center ${darkMode ? 'bg-gray-700' : 'bg-white'} border ${darkMode ? 'border-gray-600' : 'border-gray-200'}`}>
<Link href="/single-booking" className="w-full"> <p className={`text-sm ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>Avg Wait Time</p>
<button <p className={`text-2xl font-bold ${darkMode ? 'text-white' : 'text-gray-900'}`}>{stats.avgWaitTime} mins</p>
className="inline-flex items-center justify-center gap-2 px-4 py-3 font-medium text-white transition rounded-lg bg-blue-500 shadow-theme-xs hover:bg-blue-600 w-full" </div>
> <div className={`p-4 rounded-lg text-center ${darkMode ? 'bg-gray-700' : 'bg-white'} border ${darkMode ? 'border-gray-600' : 'border-gray-200'}`}>
<img <p className={`text-sm ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>Pending</p>
src="/images/icons/Vector.png" <p className={`text-2xl font-bold ${darkMode ? 'text-white' : 'text-gray-900'}`}>{stats.booked}</p>
alt="single booking" </div>
className="p-1 text-blue-500" <div className={`p-4 rounded-lg text-center ${darkMode ? 'bg-gray-700' : 'bg-white'} border ${darkMode ? 'border-gray-600' : 'border-gray-200'}`}>
/> <p className={`text-sm ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>Completed</p>
Single <p className={`text-2xl font-bold ${darkMode ? 'text-white' : 'text-gray-900'}`}>{stats.done}</p>
</button>
</Link>
<Link href="/multi-booking" className="w-full">
<button
className="inline-flex items-center justify-center gap-2 px-4 py-3 font-medium text-blue-500 transition rounded-lg bg-white shadow-theme-xs hover:bg-gray-100 border border-gray-400 w-full"
>
<img
src="/images/icons/Group 1000011641.png"
alt="single booking"
className="p-1 text-blue-500"
/>
Bulk Booking
</button>
</Link>
</div> </div>
</div>
<div className="text-center">
<p>Note: Token booking is available for current date only i.e. Today</p>
</div> </div>
</div> </div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
{/* Booking Options */}
<div className="lg:col-span-2 space-y-4">
<h3 className={`text-lg font-medium ${darkMode ? 'text-white' : 'text-gray-800'}`}>
New Booking
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div
onClick={() => router.push('/pages/SingleBooking')}
className={`p-6 cursor-pointer rounded-lg border transition-all hover:shadow-md ${darkMode ?
'bg-gray-800 border-gray-700 hover:border-blue-600 hover:bg-gray-700' :
'bg-white border-gray-200 hover:border-blue-500 hover:bg-blue-50'
}`}
>
<div className="flex items-center gap-4">
<div className={`p-3 rounded-full ${darkMode ? 'bg-blue-900/30 text-blue-400' : 'bg-blue-100 text-blue-600'}`}>
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
</div>
<div>
<h3 className={`font-medium ${darkMode ? 'text-white' : 'text-gray-800'}`}>Single Booking</h3>
<p className={`text-sm ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
Book one token for a patient
</p>
</div>
</div>
</div>
<div
onClick={() => router.push('/pages/MultiBooking')}
className={`p-6 cursor-pointer rounded-lg border transition-all hover:shadow-md ${darkMode ?
'bg-gray-800 border-gray-700 hover:border-blue-600 hover:bg-gray-700' :
'bg-white border-gray-200 hover:border-blue-500 hover:bg-blue-50'
}`}
>
<div className="flex items-center gap-4">
<div className={`p-3 rounded-full ${darkMode ? 'bg-purple-900/30 text-purple-400' : 'bg-purple-100 text-purple-600'}`}>
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
</svg>
</div>
<div>
<h3 className={`font-medium ${darkMode ? 'text-white' : 'text-gray-800'}`}>Multi Booking</h3>
<p className={`text-sm ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
Book multiple tokens at once
</p>
</div>
</div>
</div>
</div>
</div>
{/* Recent Activity */}
<div>
<h3 className={`text-lg font-medium mb-4 ${darkMode ? 'text-white' : 'text-gray-800'}`}>
Recent Activity
</h3>
<div className={`space-y-3 ${darkMode ? 'bg-gray-800' : 'bg-white'} p-4 rounded-lg border ${darkMode ? 'border-gray-700' : 'border-gray-200'}`}>
{recentBookings.length > 0 ? (
recentBookings.map(booking => (
<div key={booking.$id} className={`p-3 rounded-lg ${darkMode ? 'bg-gray-700' : 'bg-gray-50'} border ${darkMode ? 'border-gray-600' : 'border-gray-200'}`}>
<div className="flex justify-between items-start">
<div>
<p className={`font-medium ${darkMode ? 'text-white' : 'text-gray-800'}`}>
{booking.patientName}
</p>
<p className={`text-sm ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
Token: <span className="font-mono">{booking.tokenId}</span>
</p>
</div>
<span className={`text-xs px-2 py-1 rounded-full ${booking.status === 'done' ? 'bg-green-100 text-green-800' :
booking.status === 'missed' ? 'bg-red-100 text-red-800' :
'bg-yellow-100 text-yellow-800'
}`}>
{booking.status}
</span>
</div>
{booking.status === 'booked' && (
<div className="flex gap-2 mt-2">
<button
onClick={() => updateStatus(booking.$id, 'done')}
className="text-xs px-2 py-1 bg-green-500 text-white rounded hover:bg-green-600"
>
Mark Done
</button>
<button
onClick={() => updateStatus(booking.$id, 'missed')}
className="text-xs px-2 py-1 bg-red-500 text-white rounded hover:bg-red-600"
>
Mark Missed
</button>
</div>
)}
</div>
))
) : (
<p className={`text-center py-4 ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
No recent bookings found
</p>
)}
</div>
</div>
</div>
<div className={`text-center text-sm ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
<p>Staff can book tokens for patients. Choose single booking for individual patients or multi-booking for group entries.</p>
<p>All tokens will be assigned for {new Date(appointmentDate).toLocaleDateString()}.</p>
</div>
</main> </main>
{/* ===== Main Content End ===== */}
</div> </div>
{/* ===== Content Area End ===== */}
</div> </div>
{/* ===== Page Wrapper End ===== */}
</div> </div>
); );
} }

View File

@ -1,139 +1,256 @@
"use client"; "use client";
import React from "react"; import { useEffect, useState } from "react";
import { databases, Query } from "../../lib/appwrite";
import { DATABASE_ID, COLLECTION_ID } from "../../lib/api";
import Header from "../../components/partials/header";
import { useTheme } from "../../context/ThemeContext";
const EntriesTable = () => { export default function EntriesTable() {
// Removed theme-related code const { darkMode } = useTheme();
const entries = [ const [entries, setEntries] = useState([]);
{ const [filteredEntries, setFilteredEntries] = useState([]);
token: 1, const [searchQuery, setSearchQuery] = useState("");
name: "John Doe", const [currentPage, setCurrentPage] = useState(1);
status: "Done", const [avgConsultTime, setAvgConsultTime] = useState(15); // Default 15 mins
statusColor: "text-green-500 bg-green-50", const entriesPerPage = 10;
},
{ const [currentToken, setCurrentToken] = useState(null);
token: 2, const [previousToken, setPreviousToken] = useState(null);
name: "Jane Smith", const [nextToken, setNextToken] = useState(null);
status: "In-Queue", const [missedTokens, setMissedTokens] = useState("");
statusColor: "text-amber-500 bg-amber-50", const [loading, setLoading] = useState(true);
}, const [error, setError] = useState(null);
{
token: 3, // Calculate waiting time based on position in queue
name: "Alice Johnson", const calculateWaitTime = (tokenNumber) => {
status: "Cancelled", const bookedEntries = entries.filter(e => e.status === "booked");
statusColor: "text-red-500 bg-red-50", const position = bookedEntries.findIndex(e => e.tokenNumber === tokenNumber);
}, return position >= 0 ? (position * avgConsultTime) : 0;
{ };
token: 4,
name: "Bob Williams", const getEntries = async () => {
status: "Done", try {
statusColor: "text-green-500 bg-green-50", const today = new Date().toISOString().split('T')[0];
}, const response = await databases.listDocuments(
]; DATABASE_ID,
COLLECTION_ID,
[
Query.equal('date', today),
Query.orderAsc('tokenNumber')
],
100
);
return response.documents;
} catch (error) {
console.error("Fetch error:", error);
throw error;
}
};
const updateTokenInfo = (entries) => {
if (entries.length === 0) {
setCurrentToken(null);
setPreviousToken(null);
setNextToken(null);
setMissedTokens("");
return;
}
const currentIndex = entries.findIndex((entry) => entry.status === "booked");
const current = currentIndex >= 0 ? entries[currentIndex] : null;
setCurrentToken(current?.tokenNumber || null);
setPreviousToken(currentIndex > 0 ? entries[currentIndex - 1]?.tokenNumber : null);
setNextToken(currentIndex < entries.length - 1 ? entries[currentIndex + 1]?.tokenNumber : null);
const missed = entries
.filter((entry) => entry.status === "missed")
.map((entry) => entry.tokenNumber)
.join(", ");
setMissedTokens(missed || "None");
};
const updateStatus = async (entryId, newStatus) => {
try {
setLoading(true);
await databases.updateDocument(
DATABASE_ID,
COLLECTION_ID,
entryId,
{ status: newStatus }
);
const data = await getEntries();
setEntries(data);
setFilteredEntries(data);
updateTokenInfo(data);
} catch (error) {
console.error("Update error:", error);
setError(error.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
const loadData = async () => {
try {
const data = await getEntries();
setEntries(data);
setFilteredEntries(data);
updateTokenInfo(data);
// Load settings (avg consultation time)
// const settings = await getSettings();
// setAvgConsultTime(settings?.avgConsultationTime || 15);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
loadData();
}, []);
useEffect(() => {
const filtered = entries.filter((entry) => {
return (
entry.patientName.toLowerCase().includes(searchQuery.toLowerCase()) ||
entry.tokenNumber.toString().includes(searchQuery)
);
});
setFilteredEntries(filtered);
setCurrentPage(1);
}, [searchQuery, entries]);
const indexOfLastEntry = currentPage * entriesPerPage;
const indexOfFirstEntry = indexOfLastEntry - entriesPerPage;
const currentEntries = filteredEntries.slice(indexOfFirstEntry, indexOfLastEntry);
const totalPages = Math.ceil(filteredEntries.length / entriesPerPage);
if (loading) return <div className="text-center mt-50">
<div className={`animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto`}></div>
<p className={`mt-4 text-lg font-semibold`}>Loading...</p>
</div>;
if (error) return <div className="p-4 text-red-500">Error: {error}</div>;
return ( return (
<div className="min-h-screen w-full flex flex-col items-center justify-start bg-gray-50 p-4"> <div className={`min-h-screen w-full ${darkMode ? 'bg-gray-900 text-white' : 'bg-white text-black'}`}>
{/* ----------------------------------------- */} <div className="sticky top-0 z-10 bg-white shadow-md mb-4">
<div className=" mt-10 w-full flex flex-col items-center justify-start bg-gray-50 p-4 rounded-md shadow-sm bg-white"> <Header
<div className="hidden sm:hidden md:hidden lg:block lg:gap-16 lg:w-full lg:px-6 lg:py-3 xl:flex xl:gap-4 xl:w-full xl:px-6 2xl:flex 2xl:gap-16 2xl:w-full 2xl:px-6"> currentToken={currentToken}
<div className="flex flex-col gap-3"> previousToken={previousToken}
<div className="grid grid-cols-4 gap-4"> nextToken={nextToken}
{[1, 2, 3, 4].map((item) => ( missedTokens={missedTokens}
<div key={item} className="border-2 rounded-[10px] px-2 py-2 flex flex-col gap-3 w-[10rem]"> />
<h2 className="text-[14px] text-[#667085]">Total Patients</h2> </div>
<div className="flex gap-5 -mt-1"> <h1 className="text-2xl font-bold mb-4">Today's Entries</h1>
<p className="text-[25px]">345</p>
<p className="text-[8px] text-[#667085] mt-[18px]">
<span className="text-green-400">+25%</span> vs Last Week
</p>
</div>
<button className="bg-[#465FFF] text-white text-[8px] px-[24px] py-[4px] w-full rounded-[4px]">
View List
</button>
</div>
))}
</div>
<div className="w-[43rem] h-[7rem] border-2 rounded-[10px] px-2 py-2 flex flex-col gap-2"> <input
<h2 className="text-[14px] text-[#667085]">Missed Token</h2> type="text"
<p className="text-[20px]"> placeholder="Search by token or name"
J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159 className="mb-4 p-2 border rounded bg-white w-full max-w-sm"
</p> value={searchQuery}
<button className="bg-[#465FFF] text-white text-[8px] px-[24px] py-[4px] w-full rounded-[4px]"> onChange={(e) => setSearchQuery(e.target.value)}
View List />
</button>
</div>
</div>
<div className="lg:border-2 lg:rounded-[10px] lg:px-6 lg:py-6 lg:w-[50%] lg:h-[15rem] lg:flex-col lg:items-center lg:gap-5 lg:hidden xl:block xl:border-2 xl:rounded-[10px] xl:px-6 xl:py-6 xl:w-[50%] xl:h-[15rem] xl:flex xl:flex-col xl:items-center xl:gap-5 2xl:border-2 2xl:rounded-[10px] 2xl:px-8 2xl:pt-6 2xl:pb-8 2xl:w-[50%] 2xl:h-[15rem] 2xl:flex 2xl:flex-col 2xl:items-center 2xl:gap-5"> {filteredEntries.length === 0 ? (
<div> <div className="p-4">No entries found for today.</div>
<h2 className="text-[14px] text-[#667085]">Current Token</h2> ) : (
<p className="font-bold text-[25px] text-center">J-369</p> <>
</div> <table className="w-full border-collapse">
<thead className={darkMode ? "bg-gray-800" : "bg-gray-100"}>
<tr>
<th className="p-3 text-left">Token</th>
<th className="p-3 text-left">Name</th>
<th className="p-3 text-left">Booked By</th>
<th className="p-3 text-left">Status</th>
<th className="p-3 text-left">Wait Time</th>
<th className="p-3 text-left">Actions</th>
</tr>
</thead>
<tbody>
{currentEntries.map((entry) => (
<tr
key={entry.$id}
className={`border ${darkMode ? 'border-gray-700' : 'border-gray-200'}`}
>
<td className="p-3 font-mono">{entry.tokenNumber}</td>
<td className="p-3">{entry.patientName}</td>
<td className="p-3">
<span className={`text-xs px-2 py-1 rounded ${
entry.bookedBy === 'staff' ?
'bg-purple-100 text-purple-800' :
'bg-blue-100 text-blue-800'
}`}>
{entry.bookedBy}
</span>
</td>
<td className="p-3">
<span
className={`px-2 py-1 rounded-full text-xs ${
entry.status === "done"
? "bg-green-100 text-green-800"
: entry.status === "booked"
? "bg-yellow-100 text-yellow-800"
: "bg-red-100 text-red-800"
} font-semibold`}
>
{entry.status}
</span>
</td>
<td className="p-3">
{entry.status === "booked" ?
`~${calculateWaitTime(entry.tokenNumber)} mins` :
'-'}
</td>
<td className="p-3 flex gap-2">
{entry.status === "booked" && (
<>
<button
onClick={() => updateStatus(entry.$id, "done")}
className="border border-green-600 text-green-600 rounded-full px-2 py-1 text-xs hover:bg-green-50"
>
Done
</button>
<button
onClick={() => updateStatus(entry.$id, "missed")}
className="border border-red-600 text-red-600 rounded-full px-2 py-1 text-xs hover:bg-red-50"
>
Missed
</button>
</>
)}
</td>
</tr>
))}
</tbody>
</table>
<div className="flex flex-row items-center gap-5 2xl:gap-[6rem]"> {/* Pagination */}
<div> <div className={`flex justify-between items-center mt-4 ${
<h2 className="text-[14px] text-[#667085]">Previous Token</h2> darkMode ? 'text-white' : 'text-gray-700'
<p className="font-bold text-red-500 text-[25px] text-center">J-210</p> }`}>
</div> <button
<div> disabled={currentPage === 1}
<h2 className="text-[14px] text-[#667085]">Next Token</h2> onClick={() => setCurrentPage((prev) => prev - 1)}
<p className="text-green-500 font-bold text-[25px] text-center">J-309</p> className="px-3 py-1 border rounded disabled:opacity-50"
</div> >
</div> Previous
</button>
<button className="bg-[#465FFF] text-white text-[8px] px-[24px] py-[6px] w-full rounded-[4px] 2xl:text-[12px]"> <span className="text-sm">
View List Page {currentPage} of {totalPages}
</button> </span>
</div> <button
</div> disabled={currentPage === totalPages}
</div> onClick={() => setCurrentPage((prev) => prev + 1)}
{/* ------------------------------------------------------------------- */} className="px-3 py-1 border rounded disabled:opacity-50"
>
Next
<div className="min-h-screen mt-10 w-full flex flex-col items-center justify-start bg-gray-50 p-4 rounded-md shadow-sm bg-white"> </button>
<table className="w-full min-w-max table-auto"> </div>
<thead> </>
<tr className="text-gray-600"> )}
<th className="p-4 font-medium text-left">Token</th>
<th className="p-4 font-medium text-left">Name</th>
<th className="p-4 font-medium text-left">Options</th>
<th className="p-4 font-medium text-left">Status</th>
</tr>
</thead>
<tbody>
{entries.map((entry, index) => (
<tr key={index} className="border-t border-gray-100">
<td className="p-4 font-semibold text-sm">{entry.token}</td>
<td className="p-4 text-sm">{entry.name}</td>
<td className="p-4">
<div className="flex gap-2">
<button className="px-3 py-1 text-xs border border-gray-200 rounded-full flex items-center gap-1 text-gray-700 hover:bg-gray-50">
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" fill="currentColor" className="bi bi-pencil" viewBox="0 0 16 16">
<path d="M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.468-.325"></path>
</svg>
Done
</button>
<button className="px-3 py-1 text-xs border border-gray-200 rounded-full flex items-center gap-1 text-gray-700 hover:bg-gray-50">
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" fill="currentColor" className="bi bi-pencil" viewBox="0 0 16 16">
<path d="M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.468-.325"></path>
</svg>
Missed
</button>
</div>
</td>
<td className="p-4">
<span className={`px-3 py-1 rounded-full text-sm ${entry.statusColor}`}>
{entry.status}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div> </div>
); );
}; }
export default EntriesTable;