# Dental Clinic Backend - Implementation Documentation

**Date:** December 2024  
**Project:** Dental Clinic Website Backend API  
**Technology Stack:** Node.js, Express.js, Sequelize ORM, MySQL, JWT Authentication

---

## Table of Contents

1. [Overview](#overview)
2. [Project Structure](#project-structure)
3. [Features Implemented](#features-implemented)
4. [API Endpoints](#api-endpoints)
5. [Database Models](#database-models)
6. [Authentication System](#authentication-system)
7. [Image Upload System](#image-upload-system)
8. [Installation & Setup](#installation--setup)
9. [Configuration](#configuration)
10. [File Structure](#file-structure)
11. [Code Examples](#code-examples)

---

## Overview

This backend API provides a complete solution for managing a dental clinic website with the following core functionalities:

- **Appointment Booking System** - Public endpoint for patients to book appointments
- **Blog Management** - Create, read, update, and delete blog posts with image uploads
- **Service Management** - Manage dental services with images
- **Doctor Profiles** - Manage doctor information and photos
- **Contact Form** - Handle contact form submissions
- **Gallery** - Upload and manage gallery images
- **Admin Authentication** - JWT-based authentication for admin endpoints

---

## Project Structure

```
backend/
├── config/
│   └── db.js                 # Database configuration
├── controllers/
│   ├── appointment.js        # Appointment CRUD operations
│   ├── auth.js               # Authentication (register/login)
│   ├── blog.js               # Blog CRUD operations
│   ├── contact.js            # Contact message handling
│   ├── doctor.js             # Doctor profile management
│   ├── gallery.js            # Gallery image management
│   └── service.js            # Service management
├── Database/
│   └── dental_db.sql        # Database schema SQL file
├── middleware/
│   ├── auth.js              # JWT authentication middleware
│   └── upload.js            # Image upload middleware (Multer)
├── models/
│   └── schema.js            # Sequelize models
├── routes/
│   └── route.js             # API route definitions
├── uploads/                 # Image storage (created automatically)
│   ├── services/
│   ├── doctors/
│   ├── blogs/
│   └── gallery/
├── .gitignore
├── index.js                 # Main server file
├── package.json             # Dependencies and scripts
└── README.md                # Setup instructions
```

---

## Features Implemented

### 1. **Authentication System**
- JWT-based token authentication
- Password hashing using bcryptjs
- Admin user registration and login
- Protected admin routes with middleware

### 2. **Appointment Management**
- Public endpoint for booking appointments
- Admin endpoints for viewing and managing appointments
- Status updates (pending, confirmed, completed)
- Integration with services table

### 3. **Blog Management**
- Create, read, update, delete blog posts
- Automatic slug generation from title
- Image upload support
- Status management (draft/published)
- Public access to published blogs only

### 4. **Service Management**
- CRUD operations for dental services
- Image upload for service images
- Active/inactive status management
- Public access to active services only

### 5. **Doctor Profile Management**
- Complete doctor profile management
- Photo upload support
- Experience years tracking
- Active/inactive status

### 6. **Contact Form Handling**
- Public endpoint for contact submissions
- Admin access to view all messages
- Pagination support

### 7. **Gallery Management**
- Image upload with category support
- Public viewing with optional category filtering
- Admin deletion capability

### 8. **Image Upload System**
- Local filesystem storage
- Category-based organization
- Automatic directory creation
- File type validation (jpeg, jpg, png, gif, webp)
- 5MB file size limit
- Unique filename generation
- Cloud-ready structure for future migration

---

## API Endpoints

### Authentication Endpoints

#### Register Admin User
```
POST /api/auth/register
Body: {
  "username": "admin",
  "email": "admin@example.com",
  "password": "password123"
}
Response: {
  "success": true,
  "message": "User registered successfully",
  "token": "jwt_token_here",
  "user": { ... }
}
```

#### Login Admin User
```
POST /api/auth/login
Body: {
  "email": "admin@example.com",
  "password": "password123"
}
Response: {
  "success": true,
  "message": "Login successful",
  "token": "jwt_token_here",
  "user": { ... }
}
```

### Appointment Endpoints

#### Book Appointment (Public)
```
POST /api/appointments
Body: {
  "patient_name": "John Doe",
  "phone": "1234567890",
  "email": "john@example.com",
  "service_id": 1,
  "preferred_date": "2024-12-25",
  "preferred_time": "10:00"
}
```

#### Get All Appointments (Admin)
```
GET /api/appointments?status=pending&page=1&limit=10
Headers: Authorization: Bearer <token>
```

#### Get Appointment by ID (Admin)
```
GET /api/appointments/:id
Headers: Authorization: Bearer <token>
```

#### Update Appointment Status (Admin)
```
PATCH /api/appointments/:id/status
Headers: Authorization: Bearer <token>
Body: {
  "status": "confirmed"
}
```

### Blog Endpoints

#### Create Blog Post (Admin)
```
POST /api/blogs
Headers: Authorization: Bearer <token>
Content-Type: multipart/form-data
Body: {
  "title": "Blog Title",
  "excerpt": "Short description",
  "content": "Full blog content",
  "author_name": "Author Name",
  "status": "published",
  "image": <file>
}
```

#### Get All Blogs
```
GET /api/blogs?page=1&limit=10&status=published
(Public: returns only published, Admin: returns all)
```

#### Get Blog by Slug (Public)
```
GET /api/blogs/:slug
```

#### Update Blog Post (Admin)
```
PUT /api/blogs/:id
Headers: Authorization: Bearer <token>
Content-Type: multipart/form-data
Body: {
  "title": "Updated Title",
  "content": "Updated content",
  "image": <file> (optional)
}
```

#### Delete Blog Post (Admin)
```
DELETE /api/blogs/:id
Headers: Authorization: Bearer <token>
```

### Service Endpoints

#### Create Service (Admin)
```
POST /api/services
Headers: Authorization: Bearer <token>
Content-Type: multipart/form-data
Body: {
  "name": "Teeth Cleaning",
  "description": "Professional teeth cleaning service",
  "is_active": true,
  "image": <file>
}
```

#### Get All Services
```
GET /api/services
(Public: returns only active, Admin: returns all)
```

#### Get Service by ID
```
GET /api/services/:id
```

#### Update Service (Admin)
```
PUT /api/services/:id
Headers: Authorization: Bearer <token>
Content-Type: multipart/form-data
```

#### Delete Service (Admin)
```
DELETE /api/services/:id
Headers: Authorization: Bearer <token>
```

### Doctor Endpoints

#### Create Doctor Profile (Admin)
```
POST /api/doctors
Headers: Authorization: Bearer <token>
Content-Type: multipart/form-data
Body: {
  "name": "Dr. Jane Smith",
  "title": "DDS",
  "specialty": "Orthodontics",
  "biography": "Doctor biography",
  "email": "doctor@example.com",
  "phone": "1234567890",
  "experience_years": 10,
  "is_active": true,
  "image": <file>
}
```

#### Get All Doctors
```
GET /api/doctors
(Public: returns only active, Admin: returns all)
```

#### Get Doctor by ID
```
GET /api/doctors/:id
```

#### Update Doctor (Admin)
```
PUT /api/doctors/:id
Headers: Authorization: Bearer <token>
Content-Type: multipart/form-data
```

#### Delete Doctor (Admin)
```
DELETE /api/doctors/:id
Headers: Authorization: Bearer <token>
```

### Contact Endpoints

#### Submit Contact Message (Public)
```
POST /api/contact
Body: {
  "name": "John Doe",
  "email": "john@example.com",
  "phone": "1234567890",
  "message": "Contact message"
}
```

#### Get All Contact Messages (Admin)
```
GET /api/contact?page=1&limit=10
Headers: Authorization: Bearer <token>
```

### Gallery Endpoints

#### Upload Gallery Image (Admin)
```
POST /api/gallery
Headers: Authorization: Bearer <token>
Content-Type: multipart/form-data
Body: {
  "title": "Image Title",
  "category": "before-after",
  "image": <file>
}
```

#### Get Gallery Images
```
GET /api/gallery?category=before-after&page=1&limit=20
```

#### Delete Gallery Image (Admin)
```
DELETE /api/gallery/:id
Headers: Authorization: Bearer <token>
```

---

## Database Models

### User Model
- `id` (INT, Primary Key, Auto Increment)
- `username` (VARCHAR(100), Unique, Not Null)
- `email` (VARCHAR(100), Unique, Not Null)
- `password_hash` (VARCHAR(255), Not Null)
- `created_at` (TIMESTAMP)
- `updated_at` (TIMESTAMP)

### Service Model
- `id` (INT, Primary Key, Auto Increment)
- `name` (VARCHAR(100), Not Null)
- `description` (TEXT)
- `image_url` (VARCHAR(255))
- `is_active` (BOOLEAN, Default: true)
- `created_at` (TIMESTAMP)

### Doctor Model
- `id` (INT, Primary Key, Auto Increment)
- `name` (VARCHAR(100), Not Null)
- `title` (VARCHAR(100))
- `specialty` (VARCHAR(100))
- `biography` (TEXT)
- `photo_url` (VARCHAR(255))
- `email` (VARCHAR(100))
- `phone` (VARCHAR(20))
- `experience_years` (INT)
- `is_active` (BOOLEAN, Default: true)

### Appointment Model
- `id` (INT, Primary Key, Auto Increment)
- `patient_name` (VARCHAR(100), Not Null)
- `phone` (VARCHAR(20), Not Null)
- `email` (VARCHAR(100))
- `service_id` (INT, Foreign Key → services.id)
- `preferred_date` (DATE)
- `preferred_time` (TIME)
- `status` (ENUM: 'pending', 'confirmed', 'completed', Default: 'pending')
- `created_at` (TIMESTAMP)

### Blog Model
- `id` (INT, Primary Key, Auto Increment)
- `title` (VARCHAR(150), Not Null)
- `slug` (VARCHAR(150), Unique)
- `excerpt` (TEXT)
- `content` (TEXT)
- `image_url` (VARCHAR(255))
- `author_name` (VARCHAR(100))
- `published_at` (TIMESTAMP)
- `status` (ENUM: 'draft', 'published', Default: 'draft')

### ContactMessage Model
- `id` (INT, Primary Key, Auto Increment)
- `name` (VARCHAR(100))
- `email` (VARCHAR(100))
- `phone` (VARCHAR(20))
- `message` (TEXT)
- `created_at` (TIMESTAMP)

### Gallery Model
- `id` (INT, Primary Key, Auto Increment)
- `title` (VARCHAR(100))
- `image_url` (VARCHAR(255))
- `category` (VARCHAR(50))
- `created_at` (TIMESTAMP)

---

## Authentication System

### JWT Token Structure
```javascript
{
  userId: user.id,
  username: user.username
}
```

### Token Expiration
- Default: 7 days (configurable via `JWT_EXPIRE` environment variable)

### Protected Routes
All admin endpoints require the JWT token in the Authorization header:
```
Authorization: Bearer <jwt_token>
```

### Authentication Middleware
Located in `backend/middleware/auth.js`:
- Extracts token from Authorization header
- Verifies token signature
- Checks if user exists
- Attaches user info to request object

---

## Image Upload System

### Storage Structure
```
backend/uploads/
├── services/     # Service images
├── doctors/      # Doctor photos
├── blogs/        # Blog post images
└── gallery/      # Gallery images
```

### Image URL Format
Images are accessible via:
```
/api/uploads/{category}/{filename}
```

Example:
```
/api/uploads/blogs/my-image-1234567890-987654321.jpg
```

### Upload Configuration
- **Maximum File Size:** 5MB
- **Allowed Formats:** jpeg, jpg, png, gif, webp
- **Filename Generation:** `{originalname}-{timestamp}-{random}.{ext}`
- **Automatic Directory Creation:** Yes

### Cloud Migration Ready
The upload system is structured to easily migrate to cloud storage (AWS S3, Cloudinary, etc.) by:
- Storing only URLs in database
- Centralized upload middleware
- Easy to replace storage destination

---

## Installation & Setup

### Prerequisites
- Node.js (v14 or higher)
- MySQL database
- npm or yarn

### Step 1: Install Dependencies
```bash
cd backend
npm install
```

### Step 2: Database Setup
1. Create MySQL database:
```sql
CREATE DATABASE dental_clinic_website;
```

2. Run the SQL script:
```bash
mysql -u root -p dental_clinic_website < Database/dental_db.sql
```

Or import `Database/dental_db.sql` using MySQL Workbench or phpMyAdmin.

### Step 3: Environment Configuration
Create a `.env` file in the `backend` directory:

```env
# Server Configuration
PORT=5000
NODE_ENV=development

# Database Configuration
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=dental_clinic_website
DB_PORT=3306

# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
JWT_EXPIRE=7d

# Upload Configuration
UPLOAD_DIR=./uploads
```

### Step 4: Start the Server
```bash
# Production
npm start

# Development (with auto-reload)
npm run dev
```

The server will start on `http://localhost:5000`

---

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | Server port | 5000 |
| `NODE_ENV` | Environment mode | development |
| `DB_HOST` | Database host | localhost |
| `DB_USER` | Database user | root |
| `DB_PASSWORD` | Database password | (empty) |
| `DB_NAME` | Database name | dental_clinic_website |
| `DB_PORT` | Database port | 3306 |
| `JWT_SECRET` | JWT secret key | (required) |
| `JWT_EXPIRE` | Token expiration | 7d |
| `UPLOAD_DIR` | Upload directory | ./uploads |

### Database Connection Pool
- **Max Connections:** 5
- **Min Connections:** 0
- **Acquire Timeout:** 30000ms
- **Idle Timeout:** 10000ms

---

## File Structure

### Controllers
All controllers follow a consistent pattern:
- Input validation using express-validator
- Error handling with try-catch
- Consistent response format
- Database operations using Sequelize

### Models
- Defined using Sequelize DataTypes
- Relationships defined with `belongsTo` and `hasMany`
- Table names match database schema
- Timestamps configured appropriately

### Routes
- Organized by resource
- Validation middleware applied
- Authentication middleware for admin routes
- Upload middleware for image endpoints

### Middleware
- **auth.js:** JWT token verification
- **upload.js:** Multer configuration for file uploads

---

## Code Examples

### Creating a Blog Post (with image)
```javascript
// Using fetch API
const formData = new FormData();
formData.append('title', 'My Blog Post');
formData.append('content', 'Blog content here');
formData.append('status', 'published');
formData.append('image', imageFile);

fetch('http://localhost:5000/api/blogs', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ' + token
  },
  body: formData
})
.then(res => res.json())
.then(data => console.log(data));
```

### Booking an Appointment
```javascript
fetch('http://localhost:5000/api/appointments', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    patient_name: 'John Doe',
    phone: '1234567890',
    email: 'john@example.com',
    service_id: 1,
    preferred_date: '2024-12-25',
    preferred_time: '10:00'
  })
})
.then(res => res.json())
.then(data => console.log(data));
```

### Authenticated Request
```javascript
fetch('http://localhost:5000/api/appointments', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer ' + jwtToken
  }
})
.then(res => res.json())
.then(data => console.log(data));
```

---

## Error Handling

### Standard Error Response Format
```json
{
  "success": false,
  "message": "Error message",
  "error": "Detailed error information"
}
```

### Error Types Handled
- **Validation Errors:** 400 status with validation details
- **Authentication Errors:** 401 status
- **Not Found Errors:** 404 status
- **Multer Errors:** 400 status (file upload issues)
- **Sequelize Errors:** 400/500 status (database issues)
- **Server Errors:** 500 status

---

## Security Features

1. **Password Hashing:** bcryptjs with salt rounds
2. **JWT Tokens:** Secure token-based authentication
3. **Input Validation:** express-validator on all endpoints
4. **File Type Validation:** Only image files allowed
5. **File Size Limits:** 5MB maximum
6. **SQL Injection Protection:** Sequelize ORM parameterized queries
7. **CORS:** Configured for cross-origin requests

---

## Testing the API

### Using cURL

#### Register Admin
```bash
curl -X POST http://localhost:5000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "email": "admin@example.com",
    "password": "password123"
  }'
```

#### Login
```bash
curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@example.com",
    "password": "password123"
  }'
```

#### Create Service (with image)
```bash
curl -X POST http://localhost:5000/api/services \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -F "name=Teeth Cleaning" \
  -F "description=Professional cleaning" \
  -F "image=@/path/to/image.jpg"
```

---

## Future Enhancements

1. **Email Notifications:** Send emails for appointment bookings
2. **Image Optimization:** Automatic image resizing and compression
3. **Cloud Storage:** Migrate to AWS S3 or Cloudinary
4. **Rate Limiting:** Prevent API abuse
5. **Caching:** Implement Redis for better performance
6. **API Documentation:** Swagger/OpenAPI documentation
7. **Unit Tests:** Comprehensive test coverage
8. **Logging:** Structured logging system

---

## Support & Maintenance

### Common Issues

**Database Connection Error:**
- Check database credentials in `.env`
- Ensure MySQL is running
- Verify database exists

**Image Upload Fails:**
- Check upload directory permissions
- Verify file size is under 5MB
- Ensure file is a valid image format

**Authentication Fails:**
- Verify JWT_SECRET is set
- Check token expiration
- Ensure token is in Authorization header

### Logs
Server logs are output to console. In production, consider using a logging library like Winston.

---

## Conclusion

This backend implementation provides a complete, production-ready API for a dental clinic website. All core functionalities have been implemented with proper error handling, validation, and security measures.

The codebase is well-organized, follows best practices, and is ready for deployment. The image upload system is structured to easily migrate to cloud storage when needed.

---

**Document Version:** 1.0  
**Last Updated:** December 2024  
**Author:** AI Assistant  
**Project:** Dental Clinic Backend API

