{"id":31136992,"url":"https://github.com/arnobt78/university-library-management-system--nextjs-fullstack","last_synced_at":"2025-09-18T08:05:12.863Z","repository":{"id":312466758,"uuid":"1047454914","full_name":"arnobt78/University-Library-Management-System--NextJS-FullStack","owner":"arnobt78","description":"Built with Next.js, TypeScript, Postgres, the University Library Management System is a production-grade platform featuring a public-facing app and admin interface. It offers advanced functionalities like seamless book borrowing with reminders and receipts, robust user management, automated workflows, optimized tech stack for real-world scalability","archived":false,"fork":false,"pushed_at":"2025-09-14T23:26:17.000Z","size":2449,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-15T01:14:58.682Z","etag":null,"topics":["account-request","admin-dashboard","admin-panel","admin-profile-services","analytics-dashboard","borrow-book-reminder","drizzle-orm","imagekit","library-management","library-management-system","library-systems","nextauth","nextjs-typescript-tailwindcss","postgresql","resend","role-management","shadcn","university-library","university-library-management","upstash-qstash"],"latest_commit_sha":null,"homepage":"https://university-library-managment.vercel.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/arnobt78.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-30T13:08:48.000Z","updated_at":"2025-09-14T23:26:21.000Z","dependencies_parsed_at":"2025-09-07T21:22:56.012Z","dependency_job_id":"dae29e0b-9fca-446b-a112-6bfce13ec80d","html_url":"https://github.com/arnobt78/University-Library-Management-System--NextJS-FullStack","commit_stats":null,"previous_names":["arnobt78/university-library-managment--nextjs-fullstack","arnobt78/university-library-management-system--nextjs-fullstack"],"tags_count":0,"template":true,"template_full_name":null,"purl":"pkg:github/arnobt78/University-Library-Management-System--NextJS-FullStack","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arnobt78%2FUniversity-Library-Management-System--NextJS-FullStack","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arnobt78%2FUniversity-Library-Management-System--NextJS-FullStack/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arnobt78%2FUniversity-Library-Management-System--NextJS-FullStack/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arnobt78%2FUniversity-Library-Management-System--NextJS-FullStack/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/arnobt78","download_url":"https://codeload.github.com/arnobt78/University-Library-Management-System--NextJS-FullStack/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arnobt78%2FUniversity-Library-Management-System--NextJS-FullStack/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":275732391,"owners_count":25518099,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-18T02:00:09.552Z","response_time":77,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["account-request","admin-dashboard","admin-panel","admin-profile-services","analytics-dashboard","borrow-book-reminder","drizzle-orm","imagekit","library-management","library-management-system","library-systems","nextauth","nextjs-typescript-tailwindcss","postgresql","resend","role-management","shadcn","university-library","university-library-management","upstash-qstash"],"created_at":"2025-09-18T08:05:09.240Z","updated_at":"2025-09-18T08:05:12.849Z","avatar_url":"https://github.com/arnobt78.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# University Library Management System - Next.js, PostgreSQL, Redis, Upstash, Resend, ImageKit FullStack Project\n\nA modern, full-stack university library management solution built with Next.js 15, TypeScript, and Drizzle ORM. BookWise provides comprehensive book borrowing, user management, and administrative features for educational institutions.\n\n![Screenshot 2025-09-16 at 14 52 48](https://github.com/user-attachments/assets/6e8ca29b-0aa9-468d-adcc-e6d496786140)\n![Screenshot 2025-09-16 at 14 58 43](https://github.com/user-attachments/assets/b9b8237b-0e43-46f3-86c6-dcd2922a3f6f)\n![Screenshot 2025-09-16 at 15 00 16](https://github.com/user-attachments/assets/20e637e9-9e76-44b7-9923-317372a02a98)\n![Screenshot 2025-09-16 at 15 00 38](https://github.com/user-attachments/assets/e495275c-a7b2-45aa-bd37-cd37ca1dadf8)\n![Screenshot 2025-09-16 at 15 00 50](https://github.com/user-attachments/assets/e39465de-e514-44c6-b385-29ab210717e9)\n![Screenshot 2025-09-16 at 15 01 00](https://github.com/user-attachments/assets/a610b78a-bf72-4371-8f95-abc5c3bf7179)\n![Screenshot 2025-09-16 at 15 02 05](https://github.com/user-attachments/assets/22a8f0bb-ac89-4ab7-a93f-630306d946a1)\n![Screenshot 2025-09-16 at 15 02 23](https://github.com/user-attachments/assets/89349b88-6b62-4099-8e35-fb90056d6cf4)\n![Screenshot 2025-09-16 at 15 02 38](https://github.com/user-attachments/assets/7cdd7016-dd42-4211-bcb2-7abd34caacb1)\n![Screenshot 2025-09-16 at 15 02 58](https://github.com/user-attachments/assets/82ed8082-54b6-41d7-a8ab-0ff5fa59646a)\n![Screenshot 2025-09-16 at 15 04 06](https://github.com/user-attachments/assets/b025b991-5495-49b1-9b6f-a8c8411e204a)\n![Screenshot 2025-09-16 at 15 04 24](https://github.com/user-attachments/assets/c946f818-a44a-4d2e-ba8c-27dea921876e)\n![Screenshot 2025-09-16 at 15 04 41](https://github.com/user-attachments/assets/b60521d6-4597-4ad7-a3a3-1cedf41a0d0e)\n![Screenshot 2025-09-16 at 15 04 58](https://github.com/user-attachments/assets/864b1033-6aa6-420b-a6a4-7420fec78652)\n![Screenshot 2025-09-16 at 15 05 09](https://github.com/user-attachments/assets/854cb805-d12a-4923-8d8a-2832f5594343)\n![Screenshot 2025-09-16 at 15 05 36](https://github.com/user-attachments/assets/0eacf5a5-5b47-43cb-8c05-203aba379296)\n![Screenshot 2025-09-16 at 15 05 50](https://github.com/user-attachments/assets/9d004d70-20ee-406e-8c90-047e05fabb86)\n![Screenshot 2025-09-16 at 15 06 03](https://github.com/user-attachments/assets/beac954e-8ace-452c-9dac-e9518d4ccb14)\n![Screenshot 2025-09-16 at 15 06 14](https://github.com/user-attachments/assets/fe312128-bd0f-427f-ac26-5ad218dc9207)\n![Screenshot 2025-09-16 at 15 06 20](https://github.com/user-attachments/assets/d4d516a9-22d2-4d53-b1bf-9f777cea2906)\n![Screenshot 2025-09-16 at 15 07 49](https://github.com/user-attachments/assets/c2218bb1-52d9-4705-a252-85a2287a0b27)\n![Screenshot 2025-09-16 at 15 08 19](https://github.com/user-attachments/assets/0a3c6b4d-734e-4450-b322-fec62daec6f6)\n![Screenshot 2025-09-16 at 15 08 38](https://github.com/user-attachments/assets/715470c5-db57-4a71-8141-f559bf82ddd1)\n![Screenshot 2025-09-16 at 15 08 50](https://github.com/user-attachments/assets/3db52269-da0a-4bef-9216-8451ac2f7676)\n![Screenshot 2025-09-16 at 15 09 23](https://github.com/user-attachments/assets/1548d4a8-16fc-49b4-a47d-2ea86f257f30)\n\n---\n\nBuilt with Next.js, TypeScript, Postgres, the University Library Management System is a production-grade platform featuring a public-facing app and admin interface. It offers advanced functionalities like seamless book borrowing with reminders and receipts, robust user management, automated workflows, optimized tech stack for real-world scalability.\n\n- **Live-Demo:** [https://university-library-managment.vercel.app/](https://university-library-managment.vercel.app/)\n\n---\n\n## 🚀 Features\n\n### **Core Functionality**\n\n- **User Authentication \u0026 Authorization** - Secure login with role-based access (USER/ADMIN)\n- **Book Management** - Complete CRUD operations for library books\n- **Borrowing System** - Request, approve, and track book borrows\n- **User Profiles** - Personal dashboards with borrowing history\n- **Review System** - Rate and review books with comments\n- **Admin Dashboard** - Comprehensive administrative controls\n\n### **Advanced Features**\n\n- **Real-time API Monitoring** - Live system health and metrics dashboard\n- **API Documentation** - Interactive Swagger-style API docs\n- **Admin Request System** - Users can request admin privileges\n- **Fine Management** - Automated overdue fine calculations\n- **Email Notifications** - Automated reminders and notifications\n- **Performance Analytics** - System performance monitoring\n- **Export Functionality** - Data export for analytics and reporting\n\n### **Technical Features**\n\n- **Responsive Design** - Mobile-first approach with Tailwind CSS\n- **Real-time Updates** - Live data updates with React Query\n- **Image Management** - Cloud-based image storage with ImageKit\n- **Rate Limiting** - Protection against abuse with Upstash Redis\n- **Database Migrations** - Version-controlled schema changes\n- **Type Safety** - Full TypeScript implementation\n\n---\n\n## 🛠️ Technology Stack\n\n### **Frontend**\n\n- **Next.js 15** - React framework with App Router\n- **TypeScript** - Type-safe JavaScript\n- **Tailwind CSS** - Utility-first CSS framework\n- **Shadcn/ui** - Modern component library\n- **Lucide React** - Beautiful icons\n- **React Hook Form** - Form management\n- **Zod** - Schema validation\n- **TanStack Query** - Server state management\n\n### **Backend**\n\n- **Next.js API Routes** - Serverless API endpoints\n- **NextAuth.js** - Authentication framework\n- **Drizzle ORM** - Type-safe database ORM\n- **PostgreSQL** - Primary database (Neon)\n- **Redis** - Caching and rate limiting (Upstash)\n\n### **External Services**\n\n- **ImageKit** - Image storage and optimization\n- **Resend** - Email delivery service\n- **Upstash** - Redis and QStash for background jobs\n- **Vercel** - Deployment platform\n\n### **Development Tools**\n\n- **ESLint** - Code linting\n- **Prettier** - Code formatting\n- **Drizzle Kit** - Database migrations\n- **Turbopack** - Fast development builds\n\n---\n\n## 📁 Project Structure\n\n```bash\nuniversity-library/\n├── app/                          # Next.js App Router\n│   ├── (auth)/                   # Authentication pages\n│   │   ├── sign-in/\n│   │   └── sign-up/\n│   ├── (root)/                   # Main application pages\n│   │   ├── all-books/\n│   │   ├── books/[id]/\n│   │   ├── my-profile/\n│   │   └── performance/\n│   ├── admin/                    # Admin dashboard\n│   │   ├── books/\n│   │   ├── users/\n│   │   ├── book-requests/\n│   │   └── business-insights/\n│   ├── api/                      # API endpoints\n│   │   ├── auth/\n│   │   ├── admin/\n│   │   ├── reviews/\n│   │   └── status/\n│   ├── api-docs/                 # API documentation\n│   └── api-status/               # System monitoring\n├── components/                   # Reusable components\n│   ├── ui/                       # Shadcn/ui components\n│   ├── admin/                    # Admin-specific components\n│   └── [feature-components]      # Feature-specific components\n├── database/                     # Database configuration\n│   ├── schema.ts                 # Drizzle schema\n│   ├── drizzle.ts               # Database connection\n│   └── seed.ts                   # Database seeding\n├── lib/                          # Utility libraries\n│   ├── actions/                  # Server actions\n│   ├── admin/                    # Admin utilities\n│   ├── services/                 # External services\n│   └── stores/                   # State management\n├── migrations/                   # Database migrations\n├── public/                       # Static assets\n└── styles/                       # Global styles\n```\n\n---\n\n## 🗄️ Database Schema\n\n### **Core Tables**\n\n#### **Users Table**\n\n```typescript\nexport const users = pgTable(\"users\", {\n  id: uuid(\"id\").primaryKey().defaultRandom(),\n  fullName: varchar(\"full_name\", { length: 255 }).notNull(),\n  email: text(\"email\").notNull().unique(),\n  universityId: integer(\"university_id\").notNull().unique(),\n  password: text(\"password\").notNull(),\n  universityCard: text(\"university_card\").notNull(),\n  status: STATUS_ENUM(\"status\").default(\"PENDING\"),\n  role: ROLE_ENUM(\"role\").default(\"USER\"),\n  lastActivityDate: date(\"last_activity_date\").defaultNow(),\n  lastLogin: timestamp(\"last_login\", { withTimezone: true }),\n  createdAt: timestamp(\"created_at\", { withTimezone: true }).defaultNow(),\n});\n```\n\n#### **Books Table**\n\n```typescript\nexport const books = pgTable(\"books\", {\n  id: uuid(\"id\").primaryKey().defaultRandom(),\n  title: varchar(\"title\", { length: 255 }).notNull(),\n  author: varchar(\"author\", { length: 255 }).notNull(),\n  genre: text(\"genre\").notNull(),\n  rating: integer(\"rating\").notNull(),\n  coverUrl: text(\"cover_url\").notNull(),\n  coverColor: varchar(\"cover_color\", { length: 7 }).notNull(),\n  description: text(\"description\").notNull(),\n  totalCopies: integer(\"total_copies\").notNull().default(1),\n  availableCopies: integer(\"available_copies\").notNull().default(0),\n  videoUrl: text(\"video_url\").notNull(),\n  summary: varchar(\"summary\").notNull(),\n  // Enhanced fields\n  isbn: varchar(\"isbn\", { length: 20 }),\n  publicationYear: integer(\"publication_year\"),\n  publisher: varchar(\"publisher\", { length: 255 }),\n  language: varchar(\"language\", { length: 50 }).default(\"English\"),\n  pageCount: integer(\"page_count\"),\n  edition: varchar(\"edition\", { length: 50 }),\n  isActive: boolean(\"is_active\").default(true).notNull(),\n  updatedAt: timestamp(\"updated_at\", { withTimezone: true }).defaultNow(),\n  updatedBy: uuid(\"updated_by\").references(() =\u003e users.id),\n  createdAt: timestamp(\"created_at\", { withTimezone: true }).defaultNow(),\n});\n```\n\n#### **Borrow Records Table**\n\n```typescript\nexport const borrowRecords = pgTable(\"borrow_records\", {\n  id: uuid(\"id\").primaryKey().defaultRandom(),\n  userId: uuid(\"user_id\")\n    .references(() =\u003e users.id)\n    .notNull(),\n  bookId: uuid(\"book_id\")\n    .references(() =\u003e books.id)\n    .notNull(),\n  borrowDate: timestamp(\"borrow_date\", { withTimezone: true })\n    .defaultNow()\n    .notNull(),\n  dueDate: date(\"due_date\"),\n  returnDate: date(\"return_date\"),\n  status: BORROW_STATUS_ENUM(\"status\").default(\"BORROWED\").notNull(),\n  // Enhanced tracking\n  borrowedBy: text(\"borrowed_by\"),\n  returnedBy: text(\"returned_by\"),\n  fineAmount: decimal(\"fine_amount\", { precision: 10, scale: 2 }).default(\n    \"0.00\"\n  ),\n  notes: text(\"notes\"),\n  renewalCount: integer(\"renewal_count\").default(0).notNull(),\n  lastReminderSent: timestamp(\"last_reminder_sent\", { withTimezone: true }),\n  updatedAt: timestamp(\"updated_at\", { withTimezone: true }).defaultNow(),\n  updatedBy: text(\"updated_by\"),\n  createdAt: timestamp(\"created_at\", { withTimezone: true }).defaultNow(),\n});\n```\n\n---\n\n## 🔧 Installation \u0026 Setup\n\n### **Prerequisites**\n\n- Node.js 18+\n- PostgreSQL database (Neon recommended)\n- Redis instance (Upstash recommended)\n\n### **1. Clone the Repository**\n\n```bash\ngit clone https://github.com/your-username/university-library.git\ncd university-library\n```\n\n### **2. Install Dependencies**\n\n```bash\nnpm install\n```\n\n### **3. Environment Variables**\n\nCreate a `.env.local` file in the root directory:\n\n```env\n# Database\nDATABASE_URL=\"postgresql://username:password@host:port/database\"\n\n# NextAuth.js\nNEXTAUTH_SECRET=\"your-secret-key\"\nNEXTAUTH_URL=\"http://localhost:3000\"\n\n# ImageKit Configuration\nNEXT_PUBLIC_IMAGEKIT_PUBLIC_KEY=\"your-imagekit-public-key\"\nNEXT_PUBLIC_IMAGEKIT_URL_ENDPOINT=\"https://ik.imagekit.io/your-id\"\nIMAGEKIT_PRIVATE_KEY=\"your-imagekit-private-key\"\n\n# Upstash Redis\nUPSTASH_REDIS_URL=\"your-redis-url\"\nUPSTASH_REDIS_TOKEN=\"your-redis-token\"\n\n# QStash (Background Jobs)\nQSTASH_URL=\"https://qstash.upstash.io/v2\"\nQSTASH_TOKEN=\"your-qstash-token\"\n\n# Email Service (Resend)\nRESEND_TOKEN=\"your-resend-token\"\n\n# API Endpoints\nNEXT_PUBLIC_API_ENDPOINT=\"http://localhost:3000\"\nNEXT_PUBLIC_PROD_API_ENDPOINT=\"https://your-domain.vercel.app\"\n\n# SMTP Configuration (Optional)\nSMTP_HOST=\"smtp.gmail.com\"\nSMTP_PORT=\"587\"\nSMTP_USER=\"your-email@gmail.com\"\nSMTP_PASS=\"your-app-password\"\n```\n\n### **4. Database Setup**\n\n```bash\n# Generate migration files\nnpm run db:generate\n\n# Apply migrations\nnpm run db:migrate\n\n# Seed the database with sample data\nnpm run seed\n```\n\n### **5. Start Development Server**\n\n```bash\nnpm run dev\n```\n\nVisit `http://localhost:3000` to see the application.\n\n---\n\n## 🚀 Getting Started\n\n### **Default Admin Account**\n\nAfter seeding the database, you can log in with:\n\n- **Email**: `test@admin.com`\n- **Password**: `12345678`\n\n### **User Registration**\n\n1. Visit `/sign-up`\n2. Fill in your details\n3. Wait for admin approval\n4. Start borrowing books!\n\n### **Admin Functions**\n\n1. Log in as admin\n2. Visit `/admin` dashboard\n3. Manage users, books, and requests\n4. Monitor system performance\n\n---\n\n## 📚 API Documentation\n\n### **Authentication Endpoints**\n\n```typescript\nPOST /api/auth/signin     # User login\nPOST /api/auth/signout    # User logout\nGET  /api/auth/session    # Get current session\n```\n\n### **Book Management**\n\n```typescript\nGET    /api/books         # Get all books\nGET    /api/books/[id]    # Get book by ID\nPOST   /api/books         # Create new book (Admin)\nPUT    /api/books/[id]    # Update book (Admin)\nDELETE /api/books/[id]    # Delete book (Admin)\n```\n\n### **Borrowing System**\n\n```typescript\nPOST   /api/borrow        # Request book borrow\nPUT    /api/borrow/[id]   # Update borrow status\nDELETE /api/borrow/[id]   # Cancel borrow request\n```\n\n### **Review System**\n\n```typescript\nGET    /api/reviews/[bookId]     # Get book reviews\nPOST   /api/reviews/[bookId]     # Create review\nPUT    /api/reviews/edit         # Update review\nDELETE /api/reviews/delete       # Delete review\n```\n\n### **Admin Endpoints**\n\n```typescript\nGET    /api/admin/users          # Get all users\nPUT    /api/admin/users/[id]     # Update user status\nGET    /api/admin/books          # Get all books\nPOST   /api/admin/books          # Create book\nPUT    /api/admin/books/[id]     # Update book\nDELETE /api/admin/books/[id]     # Delete book\n```\n\n### **System Monitoring**\n\n```typescript\nGET    /api/status/health        # Overall system health\nGET    /api/status/database      # Database status\nGET    /api/status/api-server    # API server status\nGET    /api/status/metrics       # System metrics\n```\n\n---\n\n## 🎨 Component Architecture\n\n### **Reusable Components**\n\n#### **BookCard Component**\n\n```typescript\ninterface BookCardProps {\n  book: Book;\n  onBorrow?: (bookId: string) =\u003e void;\n  onViewDetails?: (bookId: string) =\u003e void;\n  showBorrowButton?: boolean;\n}\n\nexport const BookCard = ({ book, onBorrow, onViewDetails, showBorrowButton }: BookCardProps) =\u003e {\n  return (\n    \u003cCard className=\"group hover:shadow-lg transition-shadow\"\u003e\n      \u003cCardContent className=\"p-4\"\u003e\n        \u003cdiv className=\"flex gap-4\"\u003e\n          \u003cBookCover book={book} /\u003e\n          \u003cdiv className=\"flex-1\"\u003e\n            \u003ch3 className=\"font-semibold text-lg\"\u003e{book.title}\u003c/h3\u003e\n            \u003cp className=\"text-gray-600\"\u003e{book.author}\u003c/p\u003e\n            \u003cp className=\"text-sm text-gray-500\"\u003e{book.genre}\u003c/p\u003e\n            \u003cdiv className=\"flex items-center gap-2 mt-2\"\u003e\n              \u003cStarRating rating={book.rating} /\u003e\n              \u003cspan className=\"text-sm\"\u003e{book.rating}/5\u003c/span\u003e\n            \u003c/div\u003e\n            {showBorrowButton \u0026\u0026 (\n              \u003cButton onClick={() =\u003e onBorrow?.(book.id)} className=\"mt-3\"\u003e\n                Borrow Book\n              \u003c/Button\u003e\n            )}\n          \u003c/div\u003e\n        \u003c/div\u003e\n      \u003c/CardContent\u003e\n    \u003c/Card\u003e\n  );\n};\n```\n\n#### **ReviewFormDialog Component**\n\n```typescript\ninterface ReviewFormDialogProps {\n  bookId: string;\n  isOpen: boolean;\n  onClose: () =\u003e void;\n  onReviewSubmitted: () =\u003e void;\n}\n\nexport const ReviewFormDialog = ({ bookId, isOpen, onClose, onReviewSubmitted }: ReviewFormDialogProps) =\u003e {\n  const [rating, setRating] = useState(0);\n  const [comment, setComment] = useState(\"\");\n\n  const handleSubmit = async (e: React.FormEvent) =\u003e {\n    e.preventDefault();\n    // Submit review logic\n    await submitReview(bookId, rating, comment);\n    onReviewSubmitted();\n    onClose();\n  };\n\n  return (\n    \u003cDialog open={isOpen} onOpenChange={onClose}\u003e\n      \u003cDialogContent\u003e\n        \u003cDialogHeader\u003e\n          \u003cDialogTitle\u003eReview This Book\u003c/DialogTitle\u003e\n        \u003c/DialogHeader\u003e\n        \u003cform onSubmit={handleSubmit}\u003e\n          \u003cdiv className=\"space-y-4\"\u003e\n            \u003cStarRating value={rating} onChange={setRating} /\u003e\n            \u003cTextarea\n              placeholder=\"Write your review...\"\n              value={comment}\n              onChange={(e) =\u003e setComment(e.target.value)}\n            /\u003e\n            \u003cdiv className=\"flex gap-2\"\u003e\n              \u003cButton type=\"submit\"\u003eSubmit Review\u003c/Button\u003e\n              \u003cButton type=\"button\" variant=\"outline\" onClick={onClose}\u003e\n                Cancel\n              \u003c/Button\u003e\n            \u003c/div\u003e\n          \u003c/div\u003e\n        \u003c/form\u003e\n      \u003c/DialogContent\u003e\n    \u003c/Dialog\u003e\n  );\n};\n```\n\n### **Custom Hooks**\n\n#### **usePerformance Hook**\n\n```typescript\nexport const usePerformance = () =\u003e {\n  const [metrics, setMetrics] = useState\u003cPerformanceMetrics | null\u003e(null);\n  const [isLoading, setIsLoading] = useState(true);\n\n  useEffect(() =\u003e {\n    const fetchMetrics = async () =\u003e {\n      try {\n        const response = await fetch(\"/api/status/metrics\");\n        const data = await response.json();\n        setMetrics(data.metrics);\n      } catch (error) {\n        console.error(\"Failed to fetch metrics:\", error);\n      } finally {\n        setIsLoading(false);\n      }\n    };\n\n    fetchMetrics();\n    const interval = setInterval(fetchMetrics, 30000); // Refresh every 30s\n\n    return () =\u003e clearInterval(interval);\n  }, []);\n\n  return { metrics, isLoading };\n};\n```\n\n---\n\n## 🔐 Authentication \u0026 Authorization\n\n### **NextAuth.js Configuration**\n\n```typescript\nexport const { handlers, signIn, signOut, auth } = NextAuth({\n  session: { strategy: \"jwt\" },\n  providers: [\n    CredentialsProvider({\n      async authorize(credentials) {\n        const user = await db\n          .select()\n          .from(users)\n          .where(eq(users.email, credentials.email))\n          .limit(1);\n\n        if (user.length === 0) return null;\n\n        // Password verification with salt\n        const [saltB64, hashB64] = user[0].password.split(\":\");\n        const salt = Uint8Array.from(Buffer.from(saltB64, \"base64\"));\n        const expectedHash = Buffer.from(hashB64, \"base64\");\n\n        const passwordBytes = new TextEncoder().encode(credentials.password);\n        const hashBuffer = sha256(concatUint8Arrays(passwordBytes, salt));\n        const isPasswordValid = Buffer.from(hashBuffer).equals(expectedHash);\n\n        if (!isPasswordValid) return null;\n\n        return {\n          id: user[0].id.toString(),\n          email: user[0].email,\n          name: user[0].fullName,\n        };\n      },\n    }),\n  ],\n  callbacks: {\n    async jwt({ token, user }) {\n      if (user) {\n        token.id = user.id;\n        token.name = user.name;\n\n        // Update last_login timestamp\n        await db\n          .update(users)\n          .set({ lastLogin: new Date() })\n          .where(eq(users.id, user.id));\n      }\n      return token;\n    },\n    async session({ session, token }) {\n      if (session.user) {\n        session.user.id = token.id as string;\n        session.user.name = token.name as string;\n      }\n      return session;\n    },\n  },\n});\n```\n\n### **Middleware Protection**\n\n```typescript\nexport default auth((req) =\u003e {\n  const { nextUrl } = req;\n  const isLoggedIn = !!req.auth;\n\n  // Protect admin routes\n  if (nextUrl.pathname.startsWith(\"/admin\")) {\n    if (!isLoggedIn) {\n      return Response.redirect(new URL(\"/sign-in\", nextUrl));\n    }\n    // Additional admin role check can be added here\n  }\n\n  // Protect authenticated routes\n  if (nextUrl.pathname.startsWith(\"/my-profile\")) {\n    if (!isLoggedIn) {\n      return Response.redirect(new URL(\"/sign-in\", nextUrl));\n    }\n  }\n});\n```\n\n---\n\n## 📊 Real-time Monitoring\n\n### **System Health Dashboard**\n\nThe application includes a comprehensive monitoring system accessible at `/api-status`:\n\n#### **Service Status Monitoring**\n\n- **API Server** - Response time and uptime tracking\n- **Database** - Connection pool and query performance\n- **File Storage** - ImageKit CDN status\n- **Authentication** - NextAuth.js service health\n- **Email Service** - SMTP configuration status\n- **External APIs** - Third-party service monitoring\n\n#### **System Metrics**\n\n- **Database Performance** - Active connections and pool status\n- **API Performance** - Requests per minute tracking\n- **Error Rate** - Failed request percentage\n- **Storage Usage** - Database storage consumption\n- **Active Users** - Currently online users\n- **SSL Certificate** - Certificate validity and expiration\n\n### **API Documentation**\n\nInteractive API documentation is available at `/api-docs` with:\n\n- Complete endpoint listings\n- Request/response examples\n- Authentication requirements\n- Interactive testing capabilities\n\n---\n\n## 🎯 Key Features Deep Dive\n\n### **1. Book Borrowing System**\n\n```typescript\n// Request a book borrow\nconst borrowBook = async (bookId: string, userId: string) =\u003e {\n  const borrowRecord = await db.insert(borrowRecords).values({\n    userId,\n    bookId,\n    status: \"PENDING\",\n    borrowDate: new Date(),\n  });\n\n  // Send notification to admin\n  await sendBorrowRequestNotification(bookId, userId);\n\n  return borrowRecord;\n};\n\n// Admin approval process\nconst approveBorrowRequest = async (borrowId: string, dueDate: Date) =\u003e {\n  await db\n    .update(borrowRecords)\n    .set({\n      status: \"BORROWED\",\n      dueDate,\n      updatedAt: new Date(),\n    })\n    .where(eq(borrowRecords.id, borrowId));\n\n  // Update book availability\n  await updateBookAvailability(borrowId);\n};\n```\n\n### **2. Review System**\n\n```typescript\n// Submit a book review\nconst submitReview = async (\n  bookId: string,\n  userId: string,\n  rating: number,\n  comment: string\n) =\u003e {\n  const review = await db.insert(bookReviews).values({\n    bookId,\n    userId,\n    rating,\n    comment,\n  });\n\n  // Update book average rating\n  await updateBookRating(bookId);\n\n  return review;\n};\n\n// Calculate average rating\nconst updateBookRating = async (bookId: string) =\u003e {\n  const reviews = await db\n    .select({ rating: bookReviews.rating })\n    .from(bookReviews)\n    .where(eq(bookReviews.bookId, bookId));\n\n  const averageRating =\n    reviews.reduce((sum, r) =\u003e sum + r.rating, 0) / reviews.length;\n\n  await db\n    .update(books)\n    .set({ rating: Math.round(averageRating) })\n    .where(eq(books.id, bookId));\n};\n```\n\n### **3. Admin Request System**\n\n```typescript\n// Request admin privileges\nconst createAdminRequest = async (userId: string, reason: string) =\u003e {\n  const request = await db.insert(adminRequests).values({\n    userId,\n    requestReason: reason,\n    status: \"PENDING\",\n  });\n\n  // Notify existing admins\n  await notifyAdminsOfNewRequest(request);\n\n  return request;\n};\n\n// Approve admin request\nconst approveAdminRequest = async (requestId: string, reviewedBy: string) =\u003e {\n  const request = await db\n    .select()\n    .from(adminRequests)\n    .where(eq(adminRequests.id, requestId))\n    .limit(1);\n\n  if (request.length === 0) return;\n\n  // Update request status\n  await db\n    .update(adminRequests)\n    .set({\n      status: \"APPROVED\",\n      reviewedBy,\n      reviewedAt: new Date(),\n    })\n    .where(eq(adminRequests.id, requestId));\n\n  // Grant admin role\n  await db\n    .update(users)\n    .set({ role: \"ADMIN\" })\n    .where(eq(users.id, request[0].userId));\n};\n```\n\n---\n\n## 🚀 Deployment\n\n### **Vercel Deployment**\n\n1. Connect your GitHub repository to Vercel\n2. Set environment variables in Vercel dashboard\n3. Deploy automatically on push to main branch\n\n### **Environment Variables for Production**\n\n```env\n# Production Database\nDATABASE_URL=\"postgresql://username:password@host:port/database\"\n\n# Production URLs\nNEXTAUTH_URL=\"https://your-domain.vercel.app\"\nNEXT_PUBLIC_PROD_API_ENDPOINT=\"https://your-domain.vercel.app\"\n\n# Production Services\nNEXT_PUBLIC_IMAGEKIT_URL_ENDPOINT=\"https://ik.imagekit.io/your-id\"\nUPSTASH_REDIS_URL=\"your-production-redis-url\"\nRESEND_TOKEN=\"your-production-resend-token\"\n```\n\n### **Database Migration in Production**\n\n```bash\n# Generate production migration\nnpm run db:generate\n\n# Apply to production database\nnpm run db:migrate\n```\n\n---\n\n## 🧪 Testing\n\n### **Running Tests**\n\n```bash\n# Run all tests\nnpm test\n\n# Run tests in watch mode\nnpm run test:watch\n\n# Run tests with coverage\nnpm run test:coverage\n```\n\n### **Test Structure**\n\n```bash\n__tests__/\n├── components/          # Component tests\n├── pages/              # Page tests\n├── api/                # API endpoint tests\n└── utils/              # Utility function tests\n```\n\n---\n\n## 📈 Performance Optimization\n\n### **Database Optimization**\n\n- **Indexes** - Strategic indexing on frequently queried columns\n- **Connection Pooling** - Efficient database connection management\n- **Query Optimization** - Optimized Drizzle ORM queries\n\n### **Frontend Optimization**\n\n- **Code Splitting** - Automatic route-based code splitting\n- **Image Optimization** - Next.js Image component with ImageKit\n- **Caching** - React Query for server state caching\n- **Bundle Analysis** - Regular bundle size monitoring\n\n### **API Optimization**\n\n- **Rate Limiting** - Upstash Redis for API protection\n- **Response Caching** - Strategic caching of API responses\n- **Background Jobs** - QStash for non-blocking operations\n\n---\n\n## 🔧 Customization Guide\n\n### **Adding New Features**\n\n#### **1. Create New Database Table**\n\n```typescript\n// database/schema.ts\nexport const newTable = pgTable(\"new_table\", {\n  id: uuid(\"id\").primaryKey().defaultRandom(),\n  name: varchar(\"name\", { length: 255 }).notNull(),\n  createdAt: timestamp(\"created_at\", { withTimezone: true }).defaultNow(),\n});\n```\n\n#### **2. Generate Migration**\n\n```bash\nnpm run db:generate\nnpm run db:migrate\n```\n\n#### **3. Create API Endpoints**\n\n```typescript\n// app/api/new-feature/route.ts\nexport async function GET() {\n  const data = await db.select().from(newTable);\n  return NextResponse.json(data);\n}\n\nexport async function POST(request: NextRequest) {\n  const body = await request.json();\n  const result = await db.insert(newTable).values(body);\n  return NextResponse.json(result);\n}\n```\n\n#### **4. Create Components**\n\n```typescript\n// components/NewFeatureComponent.tsx\nexport const NewFeatureComponent = () =\u003e {\n  const [data, setData] = useState([]);\n\n  useEffect(() =\u003e {\n    fetch('/api/new-feature')\n      .then(res =\u003e res.json())\n      .then(setData);\n  }, []);\n\n  return (\n    \u003cdiv\u003e\n      {data.map(item =\u003e (\n        \u003cdiv key={item.id}\u003e{item.name}\u003c/div\u003e\n      ))}\n    \u003c/div\u003e\n  );\n};\n```\n\n### **Styling Customization**\n\n```typescript\n// tailwind.config.ts\nmodule.exports = {\n  theme: {\n    extend: {\n      colors: {\n        primary: {\n          50: \"#eff6ff\",\n          500: \"#3b82f6\",\n          900: \"#1e3a8a\",\n        },\n      },\n      fontFamily: {\n        sans: [\"Inter\", \"system-ui\", \"sans-serif\"],\n      },\n    },\n  },\n};\n```\n\n---\n\n## 🤝 Contributing\n\n### **Development Workflow**\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature/new-feature`\n3. Make your changes\n4. Run tests: `npm test`\n5. Commit changes: `git commit -m 'Add new feature'`\n6. Push to branch: `git push origin feature/new-feature`\n7. Create a Pull Request\n\n### **Code Standards**\n\n- Use TypeScript for all new code\n- Follow ESLint configuration\n- Write tests for new features\n- Update documentation as needed\n- Use conventional commit messages\n\n### **Pull Request Guidelines**\n\n- Clear description of changes\n- Reference related issues\n- Include screenshots for UI changes\n- Ensure all tests pass\n- Update README if needed\n\n---\n\n## 📝 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n---\n\n## 🙏 Acknowledgments\n\n- **Next.js Team** - For the amazing React framework\n- **Drizzle Team** - For the excellent TypeScript ORM\n- **Shadcn/ui** - For beautiful component library\n- **Vercel** - For seamless deployment platform\n- **Neon** - For PostgreSQL hosting\n- **Upstash** - For Redis and background jobs\n- **ImageKit** - For image optimization\n- **Resend** - For email delivery\n\n---\n\n## 📞 Support\n\n### **Getting Help**\n\n- 📧 Email: \u003carnob_t78@yahoo.com\u003e\n- 🌐 Portfolio: [https://arnob-mahmud.vercel.app/](https://arnob-mahmud.vercel.app/)\n- 🐛 Issues: [GitHub Issues](https://github.com/your-username/university-library/issues)\n\n### **Documentation**\n\n- 📚 [Next.js Documentation](https://nextjs.org/docs)\n- 🗄️ [Drizzle ORM Documentation](https://orm.drizzle.team/)\n- 🎨 [Tailwind CSS Documentation](https://tailwindcss.com/docs)\n- 🔐 [NextAuth.js Documentation](https://next-auth.js.org/)\n\n---\n\n## 🎯 Roadmap\n\n### **Upcoming Features**\n\n- [ ] **Mobile App** - React Native mobile application\n- [ ] **Advanced Analytics** - Detailed usage analytics\n- [ ] **Multi-language Support** - Internationalization\n- [ ] **Advanced Search** - Full-text search with filters\n- [ ] **Notification System** - Real-time push notifications\n- [ ] **Integration APIs** - Third-party library system integration\n- [ ] **Automated Testing** - Comprehensive test suite\n- [ ] **Performance Monitoring** - Advanced APM integration\n\n### **Technical Improvements**\n\n- [ ] **GraphQL API** - Alternative to REST API\n- [ ] **Microservices** - Service-oriented architecture\n- [ ] **Docker Support** - Containerization\n- [ ] **CI/CD Pipeline** - Automated deployment\n- [ ] **Security Audit** - Comprehensive security review\n\n---\n\n## Happy Coding! 🎉\n\nFree to use this project repository and extend this project further!\n\nIf you have any questions or want to share your work, reach out via GitHub or my portfolio at [https://arnob-mahmud.vercel.app/](https://arnob-mahmud.vercel.app/).\n\n**Enjoy building and learning!** 🚀\n\nThank you! 😊\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farnobt78%2Funiversity-library-management-system--nextjs-fullstack","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Farnobt78%2Funiversity-library-management-system--nextjs-fullstack","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farnobt78%2Funiversity-library-management-system--nextjs-fullstack/lists"}