# QuickConnect Backend

A comprehensive Node.js and TypeScript backend platform that enables users and organizations to create customizable QR profiles (static & dynamic), securely share documents, enable masked/proxy communications, and capture scan analytics. The platform supports both consumer flows and an enterprise/HIPAA-compliant mode for handling sensitive data.

## Table of Contents

- [Features](#features)
- [Tech Stack](#tech-stack)
- [Architecture Overview](#architecture-overview)
- [Project Structure](#project-structure)
- [Installation](#installation)
- [Environment Variables](#environment-variables)
- [Scripts](#scripts)
- [API Endpoints](#api-endpoints)
- [Security Features](#security-features)
- [Development Guidelines](#development-guidelines)
- [Testing](#testing)
- [Code Wiki](#code-wiki)
- [Deployment](#deployment)
- [Contributing](#contributing)
- [License](#license)

## Features

- **QR Profile Management**: Create customizable static and dynamic QR codes with multiple types (Memory Tag, Medical, Car, Luggage, Pet, Identification, Document)
- **Secure Document Sharing**: Upload and securely share documents with access control
- **Push Notifications**: Real-time notification system with Firebase integration
- **Scan Analytics**: Track and analyze QR code scan statistics with detailed reporting
- **Subscription Management**: Stripe-integrated subscription system with automated billing
- **HIPAA Compliance**: Enterprise mode with encryption and audit logging for sensitive data
- **Access Control**: Role-based access control (RBAC) for secure operations
- **Comprehensive Audit Logging**: Complete audit trail system with 70+ action types
- **Real-time Communication**: Socket.IO-based real-time notifications and messaging
- **Medical Data Encryption**: AES-256-CBC encryption for HIPAA-compliant medical QR codes
- **Geocoding Services**: Automatic address resolution and location-based features

## Tech Stack

- **Runtime Environment**: Node.js (>=18)
- **Language**: TypeScript with strict mode enabled
- **Framework**: Express.js with Socket.IO for real-time features
- **Database**: MongoDB with Mongoose ODM
- **Authentication**: JWT (JSON Web Tokens) with refresh token support
- **Payment Processing**: Stripe integration for subscription management
- **File Handling**: Multer for multipart/form-data uploads
- **Push Notifications**: Firebase Admin SDK integration
- **QR Code Generation**: qrcode library for dynamic QR generation
- **Email Service**: Nodemailer for transactional emails
- **Validation**: Joi for request validation
- **Security**: bcryptjs, helmet, express-rate-limit, CORS
- **Geocoding**: OpenStreetMap Nominatim API
- **Compression**: Built-in response compression
- **Audit Logging**: Comprehensive audit trail with compliance tracking
- **Scheduled Tasks**: node-cron for automated background processes
- **Environment Management**: dotenv
- **Code Formatting**: Prettier
- **Testing Framework**: Jest

## Architecture Overview

The QuickConnect backend follows a layered architecture pattern with clear separation of concerns:

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                           API Layer (Express.js)                            │
├─────────────────────────────────────────────────────────────────────────────┤
│  Authentication  │  Validation  │  Routing  │  Rate Limiting  │  CORS       │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                        Controller Layer (MVC)                               │
├─────────────────────────────────────────────────────────────────────────────┤
│  Auth  │  QR Code  │  Scan  │  Subscription  │  Admin  │  Notification  │   │
│  Ctrl  │  Ctrl     │  Ctrl  │  Ctrl        │  Ctrl  │  Ctrl          │   │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                         Service Layer                                       │
├─────────────────────────────────────────────────────────────────────────────┤
│  User  │  QR Code  │  Scan  │  Subscription  │  Notification  │  Audit      │
│  Serv  │  Serv     │  Serv  │  Serv        │  Serv        │  Serv       │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                        Data Access Layer (Mongoose)                         │
├─────────────────────────────────────────────────────────────────────────────┤
│  User  │  QR Code  │  Scan  │  Subscription  │  Notification  │  Audit      │
│  Model│  Model    │  Model │  Model       │  Model       │  Model     │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                           Database (MongoDB)                                │
└─────────────────────────────────────────────────────────────────────────────┘

```

### Mermaid Diagram

```mermaid
graph TD
    A[Client Applications] --> B[API Layer - Express.js]
    B --> C[Authentication & Validation Middleware]
    C --> D[Controller Layer]
    D --> E[Service Layer]
    E --> F[Data Access Layer - Mongoose]
    F --> G[MongoDB Database]

    D --> H[QR Code Management]
    D --> I[User Authentication]
    D --> J[Subscription Management]
    D --> K[Scan Analytics]
    D --> L[Admin Functions]

    E --> M[User Service]
    E --> N[QR Code Service]
    E --> O[Scan Service]
    E --> P[Subscription Service]
    E --> Q[Audit Service]

    H --> N
    I --> M
    J --> P
    K --> O
    L --> M

    N --> F
    M --> F
    O --> F
    P --> F
    Q --> F
```

## Project Structure

```
quickconnect-backend/
├── src/                    # Source code (TypeScript)
│   ├── config/            # Configuration & setup (MongoDB, Firebase)
│   ├── controllers/       # Business logic (feature-based organization)
│   │   ├── auth/          # Authentication services and controllers
│   │   ├── qr-code/       # QR code management (controller, service, repository)
│   │   ├── scan/          # QR code scanning logic
│   │   ├── subscription/  # Stripe subscription management and billing
│   │   ├── admin/         # Administrative functions
│   │   ├── notification/  # Push notification handling
│   │   ├── memory-tag/    # Memory tag management
│   │   ├── dashboard/     # Analytics and dashboard data
│   │   ├── media/         # File upload and media management
│   │   └── AuditLogs/     # Audit logging functionality
│   ├── models/            # Database schemas (Mongoose)
│   ├── routes/            # API endpoints
│   ├── middleware/        # Express middleware (auth, upload handling)
│   ├── services/          # External service integration
│   ├── utils/             # Utility functions and helpers
│   ├── validations/       # Request validation schemas (Joi)
│   ├── types/             # TypeScript type definitions
│   ├── lib/               # Shared libraries (UniResponse, StatusCode)
│   ├── templates/         # Email templates
│   ├── seeders/           # Database seeders
│   └── server.ts          # Main application entry point
├── uploads/               # Static file uploads (profile pictures, QR codes)
├── dist/                  # Compiled JavaScript output
├── .kiro/                 # Kiro AI assistant configuration
├── package.json           # Dependencies and scripts
└── Readme.md             # Project documentation
```

## Installation

### Prerequisites
- Node.js (>=18)
- MongoDB (local instance or cloud service like MongoDB Atlas)
- Git

### Steps
1. Clone the repository:
   ```bash
   git clone <repository-url>
   cd quick-connect-backend
   ```

2. Install dependencies:
   ```bash
   npm install
   ```

3. Set up environment variables:
   ```bash
   cp .env.example .env
   ```

4. Configure your `.env` file with appropriate values

5. Start the development server:
   ```bash
   npm run dev
   ```

The server will run at `http://localhost:3002` (or your configured port).

## Environment Variables

Key environment variables include:
- `NODE_ENV` - Environment (development, production)
- `PORT` - Server port
- `DATABASE_URL` - MongoDB connection string
- `JWT_SECRET` - JWT signing secret
- `STRIPE_SECRET_KEY` - Stripe API secret key
- Various Firebase, encryption, and email configuration variables

## Scripts

- `npm run dev` — Start development server with hot reload
- `npm run build` — Clean and compile TypeScript to JavaScript
- `npm run start` — Run compiled application from dist/
- `npm run format` — Format code with Prettier
- `npm run test` — Run Jest tests
- `npm run seed:admin` — Run admin seeder

## API Endpoints

The API uses `/api/` prefix for all endpoints:

### Authentication
- `POST /api/auth/register` - User registration
- `POST /api/auth/login` - User login
- `POST /api/auth/verify-otp` - Verify OTP for account activation
- `POST /api/auth/forgot-password` - Password reset request
- `POST /api/auth/reset-password` - Password reset with token

### QR Code Management
- `GET /api/qrcodes` - Get user's QR codes
- `POST /api/qrcodes` - Create new QR code
- `GET /api/qrcodes/:id` - Get specific QR code
- `PUT /api/qrcodes/:id` - Update QR code
- `DELETE /api/qrcodes/:id` - Delete QR code

### Subscription Management
- `GET /api/subscription/all` - Get all available subscription packages
- `POST /api/subscription/checkout-session` - Create Stripe checkout session
- `GET /api/subscription/status` - Get user's subscription status
- `DELETE /api/subscription/cancel/:subscriptionId` - Cancel user subscription

### Scan Analytics
- `POST /api/scans/public` - Public scan QR code
- `GET /api/scans/public/:id` - Get public scan details
- `POST /api/scans` - Create new scan record

### Admin Endpoints
- `GET /api/admin/users` - Get all users (admin only)
- `GET /api/admin/qrcodes` - Get all QR codes (admin only)
- `GET /api/admin/analytics` - Get system analytics (admin only)

## Security Features

### General Security
- All API endpoints use HTTPS in production
- Input validation and sanitization for all user inputs
- Rate limiting to prevent abuse
- JWT tokens with proper expiration times
- Secure password hashing with bcrypt
- Enhanced login security with IP address and user agent tracking
- Comprehensive security event logging

### QR Code Encryption
- **QR Code Data Encryption**: AES-256-GCM (Galois/Counter Mode) for authenticated encryption
- **PIN Protection Encryption**: Bcrypt-based hashing for PIN access
- **Medical Data Encryption**: AES-256-CBC for HIPAA-compliant medical QR code data

### HIPAA Compliance
- Medical data encryption with AES-256-CBC
- Immutable audit logs for PHI access
- Role-based access control with least privilege principle
- Data retention policies
- Business Associate Agreements with cloud providers

### Audit Logging
- 70+ predefined action types covering all system operations
- HIPAA compliance tracking for medical data access
- Security event monitoring and failed attempt tracking
- Resource type tracking (USER, QRCODE, SCAN, etc.)
- Four-level severity system (LOW, MEDIUM, HIGH, CRITICAL)

## Development Guidelines

### Code Style
- Follow existing code style and conventions
- Use ESLint and Prettier for consistent formatting
- Write clear, descriptive commit messages
- Include JSDoc comments for complex functions
- Follow TypeScript strict mode guidelines

### Architecture Patterns
- **Layered Architecture**: Route → Controller → Service → Repository pattern
- **Consistent Structure**: Standardized file organization and naming conventions
- **Error Handling**: Unified error handling with asyncHandler integration
- **Validation**: Joi schema validation for all inputs
- **Response Formatting**: Consistent API responses using UniResponse

### Commit Guidelines
Follow the Conventional Commits specification:
```
<type>(<scope>): <description>

[optional body]

[optional footer(s)]
```

Examples:
- `feat(auth): add JWT refresh token functionality`
- `fix(user): resolve issue with profile updates`
- `docs(readme): update installation instructions`
- `refactor(api): restructure route organization`

## Testing

The project uses Jest for testing. To run tests:
```bash
# Run all tests once
npm run test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test -- --coverage
```

Tests are organized in the `tests/` directory (not visible in the current structure) with:
- Unit tests
- Integration tests
- Test utilities and fixtures

## Code Wiki

This section provides a comprehensive guide to understanding the QuickConnect codebase, its key components, and how to navigate the code effectively.

### Core Architecture Components

#### 1. Controllers (`src/controllers/`)
Controllers handle the business logic for each feature area:

- **Auth Controllers**: User registration, login, OTP verification, password reset
- **QR Code Controllers**: QR code creation, retrieval, updates, deletion
- **Scan Controllers**: QR code scanning logic and analytics
- **Subscription Controllers**: Stripe integration and billing management
- **Admin Controllers**: Administrative functions and system analytics
- **Notification Controllers**: Push notification handling
- **Memory Tag Controllers**: Memory tag management
- **Dashboard Controllers**: Analytics and dashboard data
- **Media Controllers**: File upload and media management
- **Audit Logs Controllers**: Audit logging functionality

#### 2. Models (`src/models/`)
Database schemas using Mongoose ODM:

- **User Model**: User account information, authentication data, and permissions
- **QRCode Model**: QR code data, metadata, and analytics
- **Scan Model**: Scan records, analytics, and user behavior tracking
- **Subscription Model**: Subscription plans, billing information, and status
- **Notification Model**: Push notification records and delivery status
- **AuditLog Model**: Comprehensive audit trail for all system operations

#### 3. Routes (`src/routes/`)
API endpoint definitions organized by feature:

- **Auth Routes**: `/api/auth/*` - Authentication endpoints
- **QR Code Routes**: `/api/qrcodes/*` - QR code management endpoints
- **Scan Routes**: `/api/scans/*` - Scan analytics endpoints
- **Subscription Routes**: `/api/subscription/*` - Billing and subscription endpoints
- **Admin Routes**: `/api/admin/*` - Administrative endpoints
- **Notification Routes**: `/api/notifications/*` - Notification endpoints

#### 4. Middleware (`src/middleware/`)
Reusable middleware functions:

- **Authentication Middleware**: JWT token verification and user authentication
- **Authorization Middleware**: Role-based access control (RBAC)
- **Validation Middleware**: Request validation using Joi schemas
- **Upload Middleware**: File upload handling with Multer
- **Rate Limiting Middleware**: API rate limiting to prevent abuse
- **Error Handling Middleware**: Global error handling and logging

#### 5. Services (`src/services/`)
External service integrations:

- **Stripe Service**: Payment processing and subscription management
- **Firebase Service**: Push notifications and cloud messaging
- **Email Service**: Transactional email delivery
- **Encryption Service**: Data encryption for HIPAA compliance
- **Geocoding Service**: Address resolution and location services

#### 6. Utilities (`src/utils/`)
Helper functions and utilities:

- **Response Formatter**: Consistent API response formatting
- **Token Generator**: JWT token creation and validation
- **Encryption Utilities**: AES-256 encryption/decryption functions
- **Validation Utilities**: Common validation functions
- **Logging Utilities**: Structured logging for debugging and monitoring

### Key Code Patterns

#### 1. Async Handler Pattern
All async route handlers use the `asyncHandler` wrapper to simplify error handling:

```typescript
const asyncHandler = (fn: RequestHandler) => (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};

// Usage in routes:
router.get('/users', asyncHandler(getAllUsers));
```

#### 2. Repository Pattern
Data access is abstracted through repository classes:

```typescript
class UserRepository {
  async findByEmail(email: string): Promise<User | null> {
    return User.findOne({ email });
  }

  async create(userData: Partial<User>): Promise<User> {
    return User.create(userData);
  }
}
```

#### 3. Service Layer Pattern
Business logic is encapsulated in service classes:

```typescript
class QRCodeService {
  private qrCodeRepository: QRCodeRepository;

  async createQRCode(userId: string, data: QRCodeData): Promise<QRCode> {
    // Business logic here
    return this.qrCodeRepository.create({ userId, ...data });
  }
}
```

### Common Development Tasks

#### Adding a New API Endpoint
1. Define the route in the appropriate route file
2. Create a controller function to handle the business logic
3. Implement validation using Joi schemas
4. Add the route to the main server file
5. Write tests for the new endpoint

#### Adding a New Database Model
1. Create a new Mongoose schema in `src/models/`
2. Define the model interface in `src/types/`
3. Create a repository class for data access
4. Add the model to the main server file if needed

#### Adding a New Middleware
1. Create the middleware function in `src/middleware/`
2. Export the middleware for use in routes
3. Apply the middleware to the appropriate routes

### Security Considerations

#### Data Encryption
- QR code data is encrypted using AES-256-GCM
- Medical data uses AES-256-CBC for HIPAA compliance
- Passwords are hashed with bcrypt

#### Input Validation
- All API inputs are validated using Joi schemas
- Sanitization is performed on user inputs
- Rate limiting prevents abuse

#### Authentication & Authorization
- JWT tokens with refresh token support
- Role-based access control (RBAC)
- Session management with proper token expiration

### Testing Guidelines

#### Unit Tests
- Test individual functions and methods in isolation
- Mock external dependencies and services
- Focus on business logic and edge cases

#### Integration Tests
- Test API endpoints with real database connections
- Verify integration between different layers
- Test authentication and authorization flows

#### Test Structure
- Organize tests by feature area
- Use descriptive test names
- Follow the AAA pattern (Arrange, Act, Assert)

## Deployment

For production deployment:
1. Build the application: `npm run build`
2. Set environment variables for production
3. Start the server: `npm start`

The application is configured to run with SSL in production when `USE_SSL=true` and `NODE_ENV=production`.

## Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Commit your changes using conventional commits (`git commit -m "feat: add amazing feature"`)
5. Push to the branch (`git push origin feature/amazing-feature`)
6. Open a Pull Request

## License

This project is licensed under the ISC License.

---

## Maintainers

- QuickConnect Team

## Support

For support, please contact the development team or create an issue in the repository.