Compare commits

...

2 Commits

Author SHA1 Message Date
6bce311762 added roles admin,patient,staff 2025-04-16 17:50:08 +05:30
eaff6a0b8a new booking implementation 2025-04-16 10:38:20 +05:30
13 changed files with 1144 additions and 533 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 (
<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">
@ -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">
<h2 className="text-[14px] text-[#667085]">Missed Token</h2>
<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>
<button className="bg-[#465FFF] text-white text-[8px] px-[24px] py-[4px] w-full rounded-[4px]">
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>
<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 className="flex flex-row items-center gap-5 2xl:gap-[6rem]">
<div>
<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>
<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>
@ -60,4 +69,4 @@ export default function Header() {
</div>
</div>
);
}
}

View File

@ -1,13 +1,14 @@
// src/app/context/AuthContext.js
"use client"; // Mark this as a client component
"use client";
import { createContext, useContext, useState, useEffect } from "react";
import { account } from "../lib/appwrite"; // Import Appwrite account
import { account,databases,DATABASE_ID,USERS_COLLECTION_ID,Query } from "../lib/appwrite";
import { useRouter } from "next/navigation";
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [userRole, setUserRole] = useState("");
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
const router = useRouter();
@ -15,14 +16,32 @@ export const AuthProvider = ({ children }) => {
useEffect(() => {
const checkAuth = async () => {
try {
await account.get(); // Check if the user is authenticated
const session = await account.get(); // Get user session
setIsAuthenticated(true);
const userId = session.$id; // Appwrite auth user ID
// ✅ Fetch custom user data from your collection
const userData = await databases.listDocuments(
DATABASE_ID,
USERS_COLLECTION_ID,
[Query.equal("userId", userId)]
);
const userDoc = userData.documents[0];
if (userDoc) {
setUser(userDoc);
setUserRole(userDoc.role || "user");
} else {
console.warn("User document not found in DB.");
}
} catch (error) {
console.error("Auth Error:", error);
if (error.code === 401) {
// Session expired or invalid
localStorage.removeItem("isLoggedIn");
setIsAuthenticated(false);
router.push("/signup"); // Redirect to sign-in page
router.push("/signup");
}
} finally {
setLoading(false);
@ -33,10 +52,18 @@ export const AuthProvider = ({ children }) => {
}, [router]);
return (
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated, loading }}>
<AuthContext.Provider
value={{
isAuthenticated,
setIsAuthenticated,
loading,
userRole,
user,
}}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
export const useAuth = () => useContext(AuthContext);

View File

@ -5,9 +5,11 @@ import { useAuth } from "../context/AuthContext";
import { useEffect } from "react";
import { useTheme } from "../context/ThemeContext";
export default function DashboardPage() {
const router = useRouter();
const { isAuthenticated, loading } = useAuth();
const { isAuthenticated, loading, userRole } = useAuth();
const { darkMode } = useTheme();
useEffect(() => {
@ -20,7 +22,7 @@ export default function DashboardPage() {
return (
<div className="flex items-center justify-center min-h-screen bg-white dark:bg-gray-900">
<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'}`}>
Loading...
</p>
@ -38,7 +40,20 @@ export default function DashboardPage() {
<h1 className={`text-3xl font-bold mb-6 ${darkMode ? 'text-white' : 'text-gray-900'}`}>
Dashboard
</h1>
{/* -------------user role-------------- */}
<h2 className={`text-xl font-semibold mb-4 ${darkMode ? 'text-white' : 'text-gray-800'}`}>
User Profile
</h2>
<div className="flex items-center space-x-4">
<div className={`w-16 h-16 rounded-full ${darkMode ? 'bg-gray-700' : 'bg-gray-200'}`}></div>
<div>
<p className={`font-medium ${darkMode ? 'text-white' : 'text-gray-800'}`}>John Doe</p>
<p className={`text-sm ${darkMode ? 'text-gray-400' : 'text-gray-500'}`}>john@example.com</p>
<p className={`text-xs mt-1 ${darkMode ? 'text-gray-400' : 'text-gray-500'}`}>Role: {userRole}</p> {/* 👈 Added */}
</div>
</div>
{/* */}
{/* 2x2 Grid Layout */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
{/* Box 1 - User Profile */}

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,145 @@
import { Client, Account, Databases, ID } from "appwrite";
import { Client, Account, Databases, Query, ID } from "appwrite";
// Initialize Appwrite Client
const client = new Client();
client
.setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT) // Use environment variable
.setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID); // Use environment variable
const client = new Client()
.setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT)
.setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID);
// Services
const account = new Account(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;
const USERS_COLLECTION_ID = process.env.NEXT_PUBLIC_APPWRITE_USERS_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;
}
// 🔐 Get User Role from `users` collection
async function getUserRole() {
try {
const user = await account.get();
const userId = user.$id;
const response = await databases.listDocuments(
DATABASE_ID,
USERS_COLLECTION_ID,
[Query.equal("userId", userId)]
);
if (response.total === 0) {
throw new Error("User not found in users collection.");
}
return response.documents[0].role;
} catch (error) {
console.error("Error fetching role:", error.message);
return null;
}
}
export {
getUserRole,
client,
account,
databases,
DATABASE_ID,
COLLECTION_ID,
USERS_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 */}
<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 */}
<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...
</p>
</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 { useTheme } from "../../context/ThemeContext";
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 (
<>
<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>
<div className={`flex h-screen overflow-hidden ${darkMode ? 'bg-gray-900' : 'bg-white'}`}>
<div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
<Header />
<div className="flex h-screen overflow-hidden">
{/* Content Area */}
<div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
{/* Header would be included here */}
<Header />
<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>
)}
{/* Main Content */}
<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" />
<div className="mb-8">
<h2 className={`text-2xl mb-4 ${darkMode ? 'text-white' : 'text-black'}`}>
Staff Multi-Booking
</h2>
<div className="mb-4">
<label htmlFor="appointmentDate" className={`block mb-2 ${darkMode ? 'text-gray-300' : 'text-gray-700'}`}>
Date:
</label>
</div>
<div className="max-w-2xl mx-auto my-20 lg:my-32">
<div className="space-y-4 text-center mb-6 lg:mb-16">
<div className="flex justify-between items-center mx-4">
<h2 className="text-2xl"><span>1.</span> John Doe</h2>
<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>
<input
type="date"
id="appointmentDate"
value={appointmentDate}
onChange={(e) => setAppointmentDate(e.target.value)}
className={`p-2 border rounded ${darkMode ? 'bg-gray-800 text-white border-gray-700' : 'bg-white'}`}
/>
</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>
);
}
}

View File

@ -1,76 +1,173 @@
"use client";
import Head from 'next/head';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Header from "../../components/partials/header";
import { useTheme } from "../../context/ThemeContext";
export default function BookAppointment() {
const [darkMode, setDarkMode] = useState(false);
export default function MultiBooking() {
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 (
<div className={`flex h-screen overflow-hidden ${darkMode ? 'dark bg-gray-900' : ''}`}>
<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>
<div className={`flex h-screen overflow-hidden ${darkMode ? 'dark bg-gray-900' : 'bg-white'}`}>
{/* Content Area */}
<div className="relative flex flex-1 flex-col overflow-x-hidden overflow-y-auto">
{/* Sticky Header */}
<header className="sticky top-0 z-50 bg-white shadow-sm dark:bg-gray-800">
<div className="flex items-center justify-between p-4">
<Header></Header>
<Header />
</div>
</header>
{/* Main Content */}
<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>
<h2 className="text-2xl">Book Appointment</h2>
<label htmlFor="appointmentDate">
Date:
<div className="mx-auto max-w-[--breakpoint-2xl] p-4 md:p-6 pt-20">
{error && (
<div className="mb-4 p-4 bg-red-100 text-red-700 rounded-md">
{error}
</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
type="date"
name="appointmentDate"
id="appointmentDate"
className="ml-2 p-1 border rounded"
value={appointmentDate}
onChange={(e) => setAppointmentDate(e.target.value)}
className={`p-1 border rounded ${darkMode ? 'bg-gray-800 text-white border-gray-700' : 'bg-white'}`}
/>
</label>
</div>
</div>
<div className="mx-auto my-20 flex max-w-2xl flex-col items-center justify-center gap-6 lg:my-32">
<div className="w-full space-y-4">
{[1, 2, 3, 4, 5].map((item) => (
<div key={item}>
<label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
Enter Name
</label>
<form onSubmit={handleSubmit} className="max-w-2xl mx-auto my-8">
<div className="space-y-4 mb-6">
{patients.map((patient) => (
<div key={patient.id} className="flex items-center gap-3">
<span className={`w-6 text-right ${darkMode ? 'text-gray-300' : 'text-gray-700'}`}>
{patient.id}.
</span>
<input
type="text"
placeholder="John Doe"
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"
value={patient.name}
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 className="w-full">
<a href="/multi-booked.html">
<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"
>
Submit
</button>
</a>
<div className="flex flex-wrap gap-3 mb-6">
<button
type="button"
onClick={addMorePatients}
className={`px-4 py-2 rounded-lg text-sm font-medium ${
darkMode ?
'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 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">
<p>
Note: Token booking is available for current date only i.e.
Today
</p>
<div className={`text-center mt-8 text-sm ${
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>
<p className="mt-1">Minimum 1 patient required. Maximum 20 patients per batch.</p>
</div>
</div>
</main>

View File

@ -1,62 +1,128 @@
"use client";
import { useSearchParams } from 'next/navigation';
import { useEffect, useState, useRef } 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 Head from 'next/head';
import Link from 'next/link';
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 bookingCreated = useRef(false);
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 () => {
if (bookingCreated.current) return; // Prevent duplicate calls
try {
bookingCreated.current = true; // Mark as created
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);
bookingCreated.current = false; // Reset on error to allow retry
} finally {
setLoading(false);
}
};
useEffect(() => {
if (name && appointmentDate) {
createBooking();
}
}, [name, appointmentDate]);
return (
<>
<div className="flex h-screen overflow-hidden">
{/* 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'>
<div className="flex h-screen overflow-hidden">
<div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
<div className="flex bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-50 w-full">
<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>
<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>
);
}

View File

@ -1,21 +1,19 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Head from 'next/head';
import Link from 'next/link';
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 Preloader from '../../components/partials/preloaders';
import Overlay from '../../components/partials/overlay';
import Header from '../../components/partials/header';
export default function SingleBooking() {
const [darkMode, setDarkMode] = useState(false);
const [loaded, setLoaded] = useState(false);
const [name, setName] = useState('');
const [appointmentDate, setAppointmentDate] = useState('');
const router = useRouter();
useEffect(() => {
// Load dark mode preference from localStorage
const savedDarkMode = JSON.parse(localStorage.getItem('darkMode'));
if (savedDarkMode !== null) {
setDarkMode(savedDarkMode);
@ -24,13 +22,23 @@ export default function SingleBooking() {
}, []);
useEffect(() => {
// Save dark mode preference to localStorage when it changes
localStorage.setItem('darkMode', JSON.stringify(darkMode));
}, [darkMode]);
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission logic here
if (!name) {
alert('Please enter your name');
return;
}
// Get current date in YYYY-MM-DD format
const today = new Date();
const appointmentDate = today.toISOString().split('T')[0];
// Navigate to confirmation page with name and current date as query params
router.push(`/pages/SingleBooked?name=${encodeURIComponent(name)}&date=${encodeURIComponent(appointmentDate)}`);
};
if (!loaded) {
@ -40,7 +48,7 @@ export default function SingleBooking() {
return (
<div className={`flex flex-col min-h-screen ${darkMode ? 'dark bg-gray-900' : ''}`}>
<Head>
<title>eCommerce Dashboard | TailAdmin - Tailwind CSS Admin Dashboard Template</title>
<title>Book Appointment</title>
<meta charSet="UTF-8" />
<meta
name="viewport"
@ -49,119 +57,48 @@ export default function SingleBooking() {
<meta httpEquiv="X-UA-Compatible" content="ie=edge" />
</Head>
{/* ===== Page Wrapper Start ===== */}
<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">
{/* Small Device Overlay Start */}
<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 />
</div>
{/* ===== Header End ===== */}
<div className="flex bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-50 w-full">
<Header />
</div>
{/* ===== Main Content Start ===== */}
<main>
<div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6">
<div>
<h2 className="text-2xl">Book Appointment</h2>
<label htmlFor="appointmentDate">
Date:
<input
type="date"
name="appointmentDate"
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 max-w-2xl mx-auto my-20 lg:my-32">
<div className="w-full">
<label className="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
Enter Name
<div className="p-4 mx-auto max-w-4xl md:p-6">
<h2 className="text-2xl font-semibold mb-6 text-gray-800 dark:text-white">Book Appointment</h2>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1.5">
Full 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">
<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"
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"
required
/>
</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>
<button
type="submit"
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"
>
Submit
</button>
</form>
<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 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 className="mt-6 text-center text-sm text-gray-600 dark:text-gray-300">
Note: Token booking is available for today's date only.
</div>
</div>
</main>
{/* ===== Main Content End ===== */}
</div>
{/* ===== Content Area End ===== */}
</div>
{/* ===== Page Wrapper End ===== */}
</div>
);
}

View File

@ -1,133 +1,150 @@
'use client'; // Required for client-side interactivity
import Image from 'next/image';
'use client';
import { useState, useEffect } from 'react';
import Head from 'next/head';
import Link from 'next/link';
// 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 { useRouter } from 'next/navigation';
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";
export default function BookingPage() {
const [darkMode, setDarkMode] = useState(false);
const [loaded, setLoaded] = useState(false);
const [appointmentDate, setAppointmentDate] = useState('');
export default function StaffBooking() {
const { darkMode } = useTheme();
const router = useRouter();
const [appointmentDate] = useState(new Date().toISOString().split('T')[0]);
const [stats, setStats] = useState({
totalTokens: 0,
booked: 0,
done: 0,
missed: 0
});
const [loading, setLoading] = useState(true);
useEffect(() => {
// Load dark mode preference from localStorage
const savedDarkMode = JSON.parse(localStorage.getItem('darkMode'));
if (savedDarkMode !== null) {
setDarkMode(savedDarkMode);
}
setLoaded(true);
const fetchStats = async () => {
try {
const today = new Date().toISOString().split('T')[0];
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');
setStats({
totalTokens: allTokens.length,
booked: bookedTokens.length,
done: doneTokens.length,
missed: missedTokens.length
});
} catch (error) {
console.error("Error fetching statistics:", error);
} finally {
setLoading(false);
}
};
fetchStats();
}, []);
useEffect(() => {
// Save dark mode preference to localStorage when it changes
localStorage.setItem('darkMode', JSON.stringify(darkMode));
}, [darkMode]);
if (!loaded) {
return <Preloader />;
if (loading) {
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 (
<div className={`flex flex-col min-h-screen ${darkMode ? 'dark bg-gray-900' : ''}`}>
<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 flex-col min-h-screen ${darkMode ? 'dark bg-gray-900' : 'bg-white'}`}>
<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">
{/* Small Device Overlay Start */}
<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'>
<div className={`flex ${darkMode ? 'bg-gray-800' : 'bg-white'} shadow-sm sticky top-0 z-50 w-full`}>
<Header />
</div>
{/* ===== Header End ===== */}
{/* ===== Main Content Start ===== */}
<main>
<div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6">
<div>
<h2 className="text-2xl">Book Appointment</h2>
<label htmlFor="appointmentDate">
Date:
<input
type="date"
name="appointmentDate"
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"
/>
<main className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6">
{/* Statistics Overview */}
<div className={`mb-8 p-6 rounded-lg ${darkMode ? 'bg-gray-800' : 'bg-gray-50'} border ${darkMode ? 'border-gray-700' : 'border-gray-200'}`}>
<h3 className={`text-lg font-medium mb-4 ${darkMode ? 'text-white' : 'text-gray-800'}`}>
Today's Overview
</h3>
<div className="grid grid-cols-2 md:grid-cols-3 gap-4">
<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'}`}>Total Tokens</p>
<p className={`text-2xl font-bold ${darkMode ? 'text-white' : 'text-gray-900'}`}>{stats.totalTokens}</p>
</div>
<div className="flex flex-col gap-4 md:flex-row lg:flex-col w-full">
<Link href="/single-booking" className="w-full">
<button
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"
>
<img
src="/images/icons/Vector.png"
alt="single booking"
className="p-1 text-blue-500"
/>
Single
</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 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'}`}>Pending</p>
<p className={`text-2xl font-bold ${darkMode ? 'text-white' : 'text-gray-900'}`}>{stats.booked}</p>
</div>
<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>
<p className={`text-2xl font-bold ${darkMode ? 'text-white' : 'text-gray-900'}`}>{stats.done}</p>
</div>
</div>
<div className="text-center">
<p>Note: Token booking is available for current date only i.e. Today</p>
</div>
</div>
{/* Booking Options */}
<div className="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>
<div className={`text-center text-sm mt-8 ${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 Content End ===== */}
</div>
{/* ===== Content Area End ===== */}
</div>
{/* ===== Page Wrapper End ===== */}
</div>
);
}

View File

@ -1,139 +1,274 @@
"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";
import { useAuth } from "../../context/AuthContext";
const EntriesTable = () => {
// Removed theme-related code
const entries = [
{
token: 1,
name: "John Doe",
status: "Done",
statusColor: "text-green-500 bg-green-50",
},
{
token: 2,
name: "Jane Smith",
status: "In-Queue",
statusColor: "text-amber-500 bg-amber-50",
},
{
token: 3,
name: "Alice Johnson",
status: "Cancelled",
statusColor: "text-red-500 bg-red-50",
},
{
token: 4,
name: "Bob Williams",
status: "Done",
statusColor: "text-green-500 bg-green-50",
},
];
export default function EntriesTable() {
const { userRole } = useAuth();
const { darkMode } = useTheme();
const [entries, setEntries] = useState([]);
const [filteredEntries, setFilteredEntries] = useState([]);
const [searchQuery, setSearchQuery] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const [avgConsultTime, setAvgConsultTime] = useState(15); // Default 15 mins
const entriesPerPage = 20;
const [currentToken, setCurrentToken] = useState(null);
const [previousToken, setPreviousToken] = useState(null);
const [nextToken, setNextToken] = useState(null);
const [missedTokens, setMissedTokens] = useState("");
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// Calculate waiting time based on position in queue
const calculateWaitTime = (tokenNumber) => {
const bookedEntries = entries.filter(e => e.status === "booked");
const position = bookedEntries.findIndex(e => e.tokenNumber === tokenNumber);
return position >= 0 ? (position * avgConsultTime) : 0;
};
const getEntries = async () => {
try {
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(() => {
if (userRole === "patient") return; // Don't load data if patient
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();
}, [userRole]);
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>;
// Check user role and show permission message if patient
if (userRole === "patient") {
return (
<div className={`min-h-screen w-full ${darkMode ? 'bg-gray-900 text-white' : 'bg-white text-black'}`}>
<div className="flex items-center justify-center h-screen">
<div className="text-center">
<h1 className="text-2xl font-bold mb-4">Access Denied</h1>
<p>You don't have permission to view this page.</p>
</div>
</div>
</div>
);
}
return (
<div className="min-h-screen w-full flex flex-col items-center justify-start bg-gray-50 p-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">
<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="flex flex-col gap-3">
<div className="grid grid-cols-4 gap-4">
{[1, 2, 3, 4].map((item) => (
<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 className="flex gap-5 -mt-1">
<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={`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">
<Header
currentToken={currentToken}
previousToken={previousToken}
nextToken={nextToken}
missedTokens={missedTokens}
/>
</div>
<h1 className="text-2xl font-bold mb-4">Today's Entries</h1>
<div className="w-[43rem] h-[7rem] border-2 rounded-[10px] px-2 py-2 flex flex-col gap-2">
<h2 className="text-[14px] text-[#667085]">Missed Token</h2>
<p className="text-[20px]">
J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159, J-134, J-159
</p>
<button className="bg-[#465FFF] text-white text-[8px] px-[24px] py-[4px] w-full rounded-[4px]">
View List
</button>
</div>
</div>
<input
type="text"
placeholder="Search by token or name"
className="mb-4 p-2 border rounded bg-white w-full max-w-sm"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
<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">
<div>
<h2 className="text-[14px] text-[#667085]">Current Token</h2>
<p className="font-bold text-[25px] text-center">J-369</p>
</div>
{filteredEntries.length === 0 ? (
<div className="p-4">No entries found for today.</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]">
<div>
<h2 className="text-[14px] text-[#667085]">Previous Token</h2>
<p className="font-bold text-red-500 text-[25px] text-center">J-210</p>
</div>
<div>
<h2 className="text-[14px] text-[#667085]">Next Token</h2>
<p className="text-green-500 font-bold text-[25px] text-center">J-309</p>
</div>
</div>
<button className="bg-[#465FFF] text-white text-[8px] px-[24px] py-[6px] w-full rounded-[4px] 2xl:text-[12px]">
View List
</button>
</div>
</div>
</div>
{/* ------------------------------------------------------------------- */}
<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">
<table className="w-full min-w-max table-auto">
<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>
{/* Pagination */}
<div className={`flex justify-between items-center mt-4 ${
darkMode ? 'text-white' : 'text-gray-700'
}`}>
<button
disabled={currentPage === 1}
onClick={() => setCurrentPage((prev) => prev - 1)}
className="px-3 py-1 border rounded disabled:opacity-50"
>
Previous
</button>
<span className="text-sm">
Page {currentPage} of {totalPages}
</span>
<button
disabled={currentPage === totalPages}
onClick={() => setCurrentPage((prev) => prev + 1)}
className="px-3 py-1 border rounded disabled:opacity-50"
>
Next
</button>
</div>
</>
)}
</div>
);
};
export default EntriesTable;
}