Skip to content

A subscription-based AI chatbot system built with TypeScript, following Clean Architecture and DDD principles. Features RESTful API, PostgreSQL database, quota management, and subscription bundles with multiple tiers (Basic, Pro, Enterprise).

Notifications You must be signed in to change notification settings

Usama-Fiaz/AIChatBot-Subscription-System

Repository files navigation

AI Chatbot Subscription System

A comprehensive subscription-based AI chatbot system built with TypeScript, following Clean Architecture principles and Domain-Driven Design (DDD).

Overview

This system implements two main modules:

  1. AI Chat Module: Handles user questions, returns mocked OpenAI responses, tracks usage, and manages quotas
  2. Subscription Bundle Module: Manages subscription bundles with different tiers, billing cycles, and auto-renewal

Architecture

The project follows Clean Architecture principles with clear separation of concerns:

src/
├── domain/           # Domain layer (entities, value objects)
│   ├── chat/
│   ├── subscriptions/
│   └── users/
├── repositories/     # Data access layer
├── services/         # Business logic layer
├── controllers/      # Presentation layer (REST API)
├── routes/           # Route definitions
├── database/         # Database connection and schema
└── jobs/             # Scheduled jobs (quota reset, renewals)

Key Design Patterns

  • Domain-Driven Design (DDD): Entities and value objects encapsulate business logic
  • Repository Pattern: Abstracts data access
  • Service Layer: Contains business logic and orchestration
  • Dependency Injection: Services depend on repository interfaces

Features

AI Chat Module

  • âś… Accepts user questions and returns mocked OpenAI responses
  • âś… Stores questions, answers, and token usage in the database
  • âś… Tracks monthly usage per user (3 free messages per month)
  • âś… Supports multiple subscription tiers:
    • Basic: 10 responses
    • Pro: 100 responses
    • Enterprise: Unlimited responses
  • âś… Deducts usage from the bundle with the latest remaining quota
  • âś… Auto-resets free quota on the 1st of each month
  • âś… Throws structured errors when quota is exceeded
  • âś… Simulates OpenAI API response time delay (1-3 seconds)

Subscription Bundle Module

  • âś… Create subscription bundles (Basic, Pro, Enterprise)
  • âś… Choose billing cycle: monthly or yearly
  • âś… Toggle auto-renew
  • âś… Each subscription includes:
    • maxMessages: Maximum messages allowed
    • price: Subscription price
    • startDate: Subscription start date
    • endDate: Subscription end date
    • renewalDate: Next renewal date
  • âś… Simulates billing logic:
    • Auto-renew subscriptions if enabled
    • Randomly fails payment 10% of the time (marks subscription inactive)
  • âś… Support cancellation:
    • Ends current billing cycle
    • Prevents renewal
    • Preserves usage history

Technology Stack

  • Runtime: Node.js
  • Language: TypeScript
  • Framework: Express.js
  • Database: PostgreSQL
  • Validation: Zod
  • Code Quality: ESLint, Prettier

Prerequisites

  • Node.js (v18 or higher)
  • PostgreSQL (v12 or higher)
  • npm or yarn

Installation

  1. Clone the repository:
git clone <repository-url>
cd AIChatBot-Subscription-System
  1. Install dependencies:
npm install
  1. Set up environment variables: Create a .env file in the root directory:
DATABASE_URL=postgresql://user:password@localhost:5432/ai_chatbot_db
PORT=3000
NODE_ENV=development
  1. Create the PostgreSQL database:
createdb ai_chatbot_db
  1. Build the project:
npm run build

Running the Application

Development Mode

npm run dev

Production Mode

npm run build
npm start

The server will start on http://localhost:3000 (or the port specified in .env).

API Endpoints

User Management

Create User

POST /api/users
Content-Type: application/json

{
  "email": "user@example.com",
  "name": "John Doe"
}

Get User

GET /api/users/:userId

Chat Module

Send Message

POST /api/chat/users/:userId/messages
Content-Type: application/json

{
  "question": "What is artificial intelligence?"
}

Response:

{
  "id": 1,
  "question": "What is artificial intelligence?",
  "answer": "This is a mocked response...",
  "tokensUsed": 45,
  "subscriptionBundleId": null,
  "usedFreeQuota": true,
  "createdAt": "2024-01-15T10:30:00Z"
}

Get Chat History

GET /api/chat/users/:userId/messages?limit=50

Subscription Module

Create Subscription

POST /api/subscriptions/users/:userId/subscriptions
Content-Type: application/json

{
  "tier": "Pro",
  "billingCycle": "monthly",
  "price": 29.99,
  "autoRenew": true
}

Available tiers: Basic, Pro, Enterprise Available billing cycles: monthly, yearly

Get User Subscriptions

GET /api/subscriptions/users/:userId/subscriptions

Get Active Subscriptions

GET /api/subscriptions/users/:userId/subscriptions/active

Cancel Subscription

POST /api/subscriptions/subscriptions/:bundleId/cancel

Renew Subscription (Manual)

POST /api/subscriptions/subscriptions/:bundleId/renew

Health Check

GET /health

Scheduled Jobs

The system includes scheduled jobs that should be run via cron:

Monthly Quota Reset

Runs on the 1st of each month to reset free quotas:

# Cron: 0 0 1 * *
node dist/jobs/quotaResetJob.js

Subscription Renewal

Runs daily to process subscription renewals:

# Cron: 0 0 * * *
node dist/jobs/subscriptionRenewalJob.js

Database Schema

The system uses the following main tables:

  • users: User accounts
  • subscription_bundles: Subscription bundles
  • chat_messages: Chat message history
  • monthly_usage: Monthly free quota tracking
  • bundle_usage: Subscription bundle usage tracking

See src/database/schema.sql for the complete schema.

Error Handling

The system uses structured error responses:

{
  "error": "Error message here"
}

Common Error Codes:

  • 400: Bad Request (validation errors)
  • 403: Forbidden (quota exceeded)
  • 404: Not Found
  • 409: Conflict (e.g., duplicate email)
  • 500: Internal Server Error

Usage Flow Example

  1. Create a user:
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "name": "Test User"}'
  1. Send chat messages (uses free quota):
curl -X POST http://localhost:3000/api/chat/users/1/messages \
  -H "Content-Type: application/json" \
  -d '{"question": "Hello, how are you?"}'
  1. Create a subscription:
curl -X POST http://localhost:3000/api/subscriptions/users/1/subscriptions \
  -H "Content-Type: application/json" \
  -d '{
    "tier": "Pro",
    "billingCycle": "monthly",
    "price": 29.99,
    "autoRenew": true
  }'
  1. Continue sending messages (uses subscription quota):
curl -X POST http://localhost:3000/api/chat/users/1/messages \
  -H "Content-Type: application/json" \
  -d '{"question": "What is TypeScript?"}'

Development

Code Quality

Run linting:

npm run lint

Fix linting issues:

npm run lint:fix

Format code:

npm run format

Check formatting:

npm run format:check

Project Structure

  • Domain Layer: Pure business logic, no dependencies on infrastructure
  • Repository Layer: Data access abstraction
  • Service Layer: Business logic orchestration
  • Controller Layer: HTTP request/response handling
  • Routes: API endpoint definitions

Testing

While the project structure supports testing, comprehensive test suites are not included in this implementation. In a production environment, you would add:

  • Unit tests for domain entities
  • Integration tests for services
  • API tests for controllers
  • Database migration tests

Future Enhancements

Potential improvements for production:

  1. Add comprehensive test coverage
  2. Implement authentication and authorization
  3. Add rate limiting
  4. Implement proper logging (Winston, Pino)
  5. Add monitoring and metrics
  6. Implement database migrations (e.g., using Knex.js or TypeORM)
  7. Add API documentation (Swagger/OpenAPI)
  8. Implement caching layer (Redis)
  9. Add message queue for async processing
  10. Implement proper error tracking (Sentry)

License

MIT

Author

[Your Name]


Note: This is a demonstration project implementing Clean Architecture principles. For production use, additional considerations such as security, scalability, and monitoring should be addressed.

About

A subscription-based AI chatbot system built with TypeScript, following Clean Architecture and DDD principles. Features RESTful API, PostgreSQL database, quota management, and subscription bundles with multiple tiers (Basic, Pro, Enterprise).

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published