# Gym Khana Management System - Backend API

Complete backend API for Club Gym Khana Management System in Hyderabad, Pakistan.

## 📋 Table of Contents

- [Overview](#overview)
- [Tech Stack](#tech-stack)
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Database Setup](#database-setup)
- [Configuration](#configuration)
- [Running the Application](#running-the-application)
- [Creating Super Admin](#creating-super-admin)
- [API Documentation](#api-documentation)
- [Project Structure](#project-structure)
- [Business Rules](#business-rules)
- [Security](#security)
- [Contributing](#contributing)

## 🎯 Overview

This is a comprehensive management system for a gym/club facility that handles:
- **Membership Management** - Member registration, family members, renewals
- **Restaurant & Food Service** - Menu management, ordering, billing
- **Sports Facilities** - Badminton, swimming pool, cricket nets, booking management
- **Warehouse & Inventory** - Stock management, purchase orders, suppliers
- **Financial Management** - Member accounts, payments, outstanding balances
- **Member Portal** - Self-service portal for members
- **Reports & Analytics** - Comprehensive reporting system

## 🛠️ Tech Stack

- **Node.js**: v24.11.1 (LTS)
- **Express.js**: v5.1.0
- **PostgreSQL**: v18
- **Authentication**: JWT (JSON Web Tokens)
- **Password Hashing**: bcryptjs
- **Logging**: Winston
- **Validation**: express-validator
- **Security**: Helmet, CORS, Rate Limiting

## ✨ Features

### 🔐 Authentication & Authorization
- JWT-based authentication
- Role-based access control (RBAC)
- Separate authentication for staff and members
- Password change functionality

### 👥 User Management (Staff)
- Create and manage staff users
- Multiple roles: Admin, Front Desk, Restaurant Staff, Warehouse Manager, Accountant, Sports Manager
- User activation/deactivation
- Password reset by admin

### 👨‍👩‍👧‍👦 Membership Management
- Register primary members
- Add family members (spouse, sons, daughters)
- Member ID generation (e.g., 1223, 1223-w, 1223-s1, 1223-d1)
- Six membership types
- Member search and filtering
- Status management (Active, Suspended, Inactive, Expired)

### 🍽️ Restaurant & Food Service
- Menu management with categories
- Table management
- Order processing (Dine-in/Takeaway)
- Tax calculation (16% on food items)
- Payment methods: Cash or Credit to member account
- Daily sales reports

### 💰 Member Account Management
- Real-time outstanding balance tracking
- 10,000 PKR credit limit enforcement
- Payment posting (Cash, Cheque, Bank Transfer)
- Transaction history
- Member statements (monthly/annual)
- Service eligibility checking

### 🏸 Sports Facility Management
- Facility management (Badminton, Pool, Cricket, etc.)
- Booking system
- Monthly fee charging (one-time per month)
- Usage tracking
- Facility schedule management

### 📦 Warehouse & Inventory
- Item management with categories
- Stock in/out/adjustment tracking
- Purchase orders
- Supplier management
- Low stock alerts
- Automatic deduction for restaurant orders

### 📊 Reports & Analytics
- Daily sales reports
- Monthly revenue reports
- Outstanding members report
- Defaulters list
- Sports facility usage
- Inventory consumption
- Payment collection reports

## 📋 Prerequisites

- Node.js v24.11.1 or higher
- PostgreSQL 18 or higher
- npm or yarn package manager
- Git

## 🚀 Installation

### 1. Clone the Repository

```bash
git clone <repository-url>
cd gym-khana-new-backend
```

### 2. Install Dependencies

```bash
npm install
```

### 3. Environment Configuration

Copy the example environment file and configure it:

```bash
cp .env.example .env
```

Edit `.env` file with your configuration:

```env
# Server Configuration
NODE_ENV=development
PORT=3000

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=gym_khana_db
DB_USER=postgres
DB_PASSWORD=your_password_here

# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
JWT_EXPIRES_IN=24h

# ... (see .env.example for all options)
```

## 🗄️ Database Setup

### 1. Create Database

```bash
# Connect to PostgreSQL
psql -U postgres

# Create database
CREATE DATABASE gym_khana_db;

# Exit psql
\q
```

### 2. Run Database Schema

```bash
# Run the schema file
psql -U postgres -d gym_khana_db -f database/schema.sql
```

This will:
- Create all required tables
- Set up relationships and constraints
- Create indexes for performance
- Add triggers for automation
- Insert initial data (roles, membership types, sample menu, facilities)

### 3. Verify Database Setup

```bash
# Connect to database
psql -U postgres -d gym_khana_db

# List tables
\dt

# You should see tables like: users, members, roles, transactions, etc.
```

## ⚙️ Configuration

### Database Connection

The application uses connection pooling for better performance. Configure in `.env`:

```env
DB_HOST=localhost
DB_PORT=5432
DB_NAME=gym_khana_db
DB_USER=postgres
DB_PASSWORD=your_password
DB_MAX_CONNECTIONS=20
```

### JWT Configuration

```env
JWT_SECRET=your_secret_key_here
JWT_EXPIRES_IN=24h
JWT_REFRESH_SECRET=your_refresh_secret
JWT_REFRESH_EXPIRES_IN=7d
```

### Business Configuration

```env
DEFAULT_CREDIT_LIMIT=10000
NEAR_LIMIT_THRESHOLD=8000
TAX_PERCENTAGE=16
CURRENCY=PKR
```

## 🏃 Running the Application

### Development Mode

```bash
npm run dev
```

This will start the server with nodemon for auto-restart on file changes.

### Production Mode

```bash
npm start
```

### Server Output

When the server starts successfully, you'll see:

```
✅ Database connection established
🚀 Server running on port 3000
📝 Environment: development
🔗 API Base URL: http://localhost:3000/api/v1
📚 API Documentation: http://localhost:3000/api/v1/docs
❤️  Health Check: http://localhost:3000/api/v1/health
```

## 👤 Creating Super Admin

After setting up the database, create the first super admin user:

```bash
npm run create-admin
```

Follow the interactive prompts:

```
Enter username: admin
Enter email address: admin@gymkhana.pk
Enter password: ********
Confirm password: ********
Enter first name: System
Enter last name: Administrator
Enter phone number: (optional)

✅ Super admin created successfully!
```

### Default Login

Use the credentials you just created to log in:

**Endpoint**: `POST /api/v1/auth/login`

```json
{
  "username": "admin",
  "password": "your_password"
}
```

## 📖 API Documentation

### Base URL

```
http://localhost:3000/api/v1
```

### Authentication

Most endpoints require authentication using JWT tokens.

**Header**:
```
Authorization: Bearer <your_jwt_token>
```

### API Endpoints

#### 🔐 Authentication

| Method | Endpoint | Description | Access |
|--------|----------|-------------|--------|
| POST | `/auth/login` | Staff login | Public |
| POST | `/auth/member/login` | Member login | Public |
| GET | `/auth/me` | Get current user | Authenticated |
| PUT | `/auth/change-password` | Change password | Authenticated |

#### 👥 User Management

| Method | Endpoint | Description | Access |
|--------|----------|-------------|--------|
| POST | `/users` | Create new user | Admin |
| GET | `/users` | Get all users | Admin |
| GET | `/users/:userId` | Get user by ID | Admin |
| PUT | `/users/:userId` | Update user | Admin |
| DELETE | `/users/:userId` | Delete user | Admin |
| POST | `/users/:userId/reset-password` | Reset user password | Admin |
| GET | `/users/roles` | Get all roles | Admin |

#### 👨‍👩‍👧‍👦 Membership Management

| Method | Endpoint | Description | Access |
|--------|----------|-------------|--------|
| POST | `/members/register` | Register new member | Admin, Front Desk |
| POST | `/members/:memberId/family` | Add family member | Admin, Front Desk |
| GET | `/members` | Get all members | Admin, Front Desk, Accountant |
| GET | `/members/search?q={query}` | Search members | All Staff |
| GET | `/members/:memberId` | Get member details | All Staff |
| PUT | `/members/:memberId/profile` | Update member profile | Admin, Front Desk |
| PUT | `/members/:memberId/status` | Update member status | Admin, Front Desk |
| GET | `/members/:memberId/family` | Get family members | All Staff |
| DELETE | `/members/:memberId/family/:familyMemberId` | Remove family member | Admin, Front Desk |

### Request & Response Examples

#### 1. Staff Login

**Request**:
```http
POST /api/v1/auth/login
Content-Type: application/json

{
  "username": "admin",
  "password": "Admin@123"
}
```

**Response**:
```json
{
  "success": true,
  "message": "Login successful",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "data": {
    "user": {
      "userId": 1,
      "username": "admin",
      "email": "admin@gymkhana.pk",
      "firstName": "System",
      "lastName": "Administrator",
      "role": "admin"
    },
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}
```

#### 2. Register New Member

**Request**:
```http
POST /api/v1/members/register
Authorization: Bearer <token>
Content-Type: application/json

{
  "memberId": "1223",
  "membershipTypeId": 1,
  "firstName": "Ahmed",
  "lastName": "Khan",
  "fatherName": "Muhammad Khan",
  "cnic": "4210112345678",
  "dateOfBirth": "1980-05-15",
  "gender": "Male",
  "phonePrimary": "03001234567",
  "phoneSecondary": "03219876543",
  "email": "ahmed@example.com",
  "address": "House 123, Street 45, Hyderabad",
  "emergencyContactName": "Ali Khan",
  "emergencyContactPhone": "03331234567",
  "membershipStartDate": "2024-01-01",
  "membershipExpiryDate": "2024-12-31",
  "password": "Member@123"
}
```

**Response**:
```json
{
  "success": true,
  "message": "Member registered successfully",
  "timestamp": "2024-01-15T10:35:00.000Z",
  "data": {
    "member": {
      "member_id": "1223",
      "first_name": "Ahmed",
      "last_name": "Khan",
      "status": "Active",
      "membership_start_date": "2024-01-01",
      "created_at": "2024-01-15T10:35:00.000Z"
    }
  }
}
```

#### 3. Add Family Member

**Request**:
```http
POST /api/v1/members/1223/family
Authorization: Bearer <token>
Content-Type: application/json

{
  "firstName": "Fatima",
  "lastName": "Ahmed",
  "relationToPrimary": "Spouse",
  "dateOfBirth": "1985-03-20",
  "gender": "Female",
  "cnic": "4210198765432",
  "password": "Spouse@123"
}
```

**Response**:
```json
{
  "success": true,
  "message": "Family member added successfully",
  "timestamp": "2024-01-15T10:40:00.000Z",
  "data": {
    "familyMember": {
      "member_id": "1223-w",
      "primary_member_id": "1223",
      "first_name": "Fatima",
      "last_name": "Ahmed",
      "relation_to_primary": "Spouse",
      "status": "Active"
    }
  }
}
```

## 📁 Project Structure

```
gym-khana-new-backend/
├── database/
│   └── schema.sql              # Complete database schema
├── scripts/
│   └── createSuperAdmin.js     # Super admin creation script
├── src/
│   ├── config/
│   │   ├── app.js              # App configuration
│   │   ├── database.js         # Database connection
│   │   └── logger.js           # Winston logger configuration
│   ├── controllers/
│   │   ├── authController.js   # Authentication controller
│   │   ├── userController.js   # User management controller
│   │   └── memberController.js # Membership controller
│   ├── middleware/
│   │   ├── auth.js             # Authentication middleware
│   │   ├── errorHandler.js     # Error handling middleware
│   │   └── validator.js        # Validation middleware
│   ├── routes/
│   │   └── index.js            # API routes
│   ├── utils/
│   │   ├── auth.js             # Auth utilities (JWT, bcrypt)
│   │   └── helpers.js          # Helper functions
│   └── server.js               # Main server file
├── logs/                       # Application logs
├── uploads/                    # Uploaded files
├── .env.example                # Environment variables example
├── .gitignore                  # Git ignore rules
├── package.json                # Dependencies and scripts
└── README.md                   # This file
```

## 📜 Business Rules

### Member ID Structure

- **Primary Member**: 4-digit number (e.g., `1223`)
- **Spouse**: Primary ID + "-w" (e.g., `1223-w`, `1223-w2` for second wife)
- **Son**: Primary ID + "-s" + number (e.g., `1223-s1`, `1223-s2`)
- **Daughter**: Primary ID + "-d" + number (e.g., `1223-d1`, `1223-d2`)

### Outstanding Balance

- **Credit Limit**: 10,000 PKR per member account
- **Warning Threshold**: 8,000 PKR (80% of limit)
- **Service Block**: Automatic when limit is exceeded
- **Family Linking**: All family member transactions linked to primary account

### Sports Facility Fees

- **Charging**: One-time per calendar month
- **Timing**: Charged on first usage of the month
- **Monthly Fee**: Fixed regardless of usage frequency
- **Examples**:
  - Badminton Court: 800 PKR/month
  - Swimming Pool: 1,500 PKR/month
  - Cricket Practice Net: 1,000 PKR/month

### Tax Rules

- **Tax Rate**: 16% (GST)
- **Taxable Items**: All food items from restaurant
- **Non-Taxable**: Membership fees, sports facility fees
- **Invoice**: Tax must be shown separately on all bills

### Payment Methods

- **Restaurant**: Cash or Credit to member account
- **Membership Fees**: Cash only at registration
- **Sports Fees**: Cash or Credit to member account
- **Payment Posting**: Cash, Cheque, Bank Transfer

## 🔒 Security

### Authentication
- JWT-based authentication with access and refresh tokens
- Passwords hashed using bcrypt (10 rounds)
- Token expiry: 24 hours (configurable)

### Authorization
- Role-based access control (RBAC)
- Route-level permission checking
- Resource-level authorization

### Security Headers
- Helmet.js for security headers
- CORS configuration
- Rate limiting (100 requests per 15 minutes)

### Input Validation
- Express-validator for request validation
- SQL injection prevention using parameterized queries
- XSS protection through input sanitization

### Best Practices
- Environment variables for sensitive data
- Audit logging for all critical operations
- Graceful error handling
- SQL transactions for data consistency

## 🧪 Testing

### Health Check

```bash
curl http://localhost:3000/api/v1/health
```

### Test Login

```bash
curl -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"your_password"}'
```

## 📝 Logging

Logs are stored in the `./logs` directory:

- `combined.log` - All logs
- `error.log` - Error logs only

**Log Format**:
```json
{
  "level": "info",
  "message": "User logged in",
  "timestamp": "2024-01-15 10:30:00",
  "userId": 1,
  "username": "admin"
}
```

## 🚧 Development Roadmap

### Phase 1 (MVP) - ✅ Completed
- [x] Database schema
- [x] Authentication system
- [x] User management
- [x] Member registration and management
- [x] Basic API structure

### Phase 2 - 🔄 In Progress
- [ ] Restaurant module completion
- [ ] Payment processing
- [ ] Transaction management
- [ ] Member account management

### Phase 3 - 📋 Planned
- [ ] Sports facility management
- [ ] Warehouse and inventory
- [ ] Member self-service portal
- [ ] Reports and analytics

### Phase 4 - 🔮 Future
- [ ] SMS and email notifications
- [ ] PDF statement generation
- [ ] Mobile app API support
- [ ] Online payment integration

## 🤝 Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## 📄 License

This project is proprietary and confidential.

## 👥 Team

- **Project**: Gym Khana Management System
- **Location**: Hyderabad, Pakistan
- **Tech Stack**: Node.js, Express.js, PostgreSQL

## 📞 Support

For support and queries:
- Email: support@gymkhana.pk
- Phone: +92-XXX-XXXXXXX

---

**Built with ❤️ for Club Gym Khana, Hyderabad, Pakistan**
