Thanks to visit codestin.com
Credit goes to github.com

Skip to content

ammar1zahid/ai_chat

Repository files navigation

AI Chat & Subscription Bundle API

A TypeScript backend application implementing AI Chat and Subscription Bundle modules

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)
  • Auto-resets free quota on the 1st of each month
  • Deducts usage from subscription bundles when free quota is exhausted
  • Simulates OpenAI API response time delay

Subscription Bundle Module

  • Create subscription bundles (Basic, Pro, Enterprise)
  • Monthly or yearly billing cycles
  • Auto-renew toggle functionality
  • Simulated billing logic with random payment failures
  • Cancellation support with usage history preservation

Subscription Tiers

Tier Messages Monthly Price Yearly Price
Basic 10 $9.99 $99.99
Pro 100 $29.99 $299.99
Enterprise Unlimited $99.99 $999.99

Project Structure

src/
├── index.ts                          # Application entry point
├── shared/
│   ├── config/                       # Configuration
│   ├── database/                     # Database connection
│   ├── errors/                       # Custom error classes
│   └── middleware/                   # Express middleware
├── modules/
│   ├── user/
│   │   ├── domain/entities/          # User entity
│   │   ├── repositories/             # User repository
│   │   ├── services/                 # User service
│   │   ├── controllers/              # User controller
│   │   └── routes/                   # User routes
│   ├── chat/
│   │   ├── domain/entities/          # ChatMessage, MonthlyUsage entities
│   │   ├── repositories/             # Chat repositories
│   │   ├── services/                 # Chat service, OpenAI mock
│   │   ├── controllers/              # Chat controller
│   │   └── routes/                   # Chat routes
│   └── subscription/
│       ├── domain/
│       │   ├── entities/             # SubscriptionBundle entity
│       │   └── types.ts              # Enums and constants
│       ├── repositories/             # Subscription repository
│       ├── services/                 # Subscription service
│       ├── controllers/              # Subscription controller
│       └── routes/                   # Subscription routes

Prerequisites

  • Node.js (v18+)
  • PostgreSQL database
  • npm or yarn

Installation

  1. Clone the repository and install dependencies:
npm install
  1. Copy the example environment file and configure:
cp .env.example .env
  1. Update .env with your database credentials:
NODE_ENV=development
PORT=3000
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=your_password
DB_NAME=ai_chat_db
OPENAI_RESPONSE_DELAY_MS=1000
  1. Create the PostgreSQL database:
CREATE DATABASE ai_chat_db;
  1. Run the application:
# Development mode
npm run dev

# Production build
npm run build
npm start

API Endpoints

Users

Method Endpoint Description
POST /api/users Create a new user
GET /api/users Get all users
GET /api/users/:id Get user by ID

Chat

Method Endpoint Description
POST /api/chat/message Send a message
GET /api/chat/history/:userId Get chat history
GET /api/chat/usage/:userId Get usage information

Subscriptions

Method Endpoint Description
POST /api/subscriptions Create subscription
GET /api/subscriptions/:id Get subscription by ID
GET /api/subscriptions/user/:userId Get user subscriptions
PATCH /api/subscriptions/:id Update subscription
POST /api/subscriptions/:id/cancel Cancel subscription
POST /api/subscriptions/process-renewals Process auto-renewals

Example Requests

Create User

curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "name": "John Doe"}'

Send Chat Message

curl -X POST http://localhost:3000/api/chat/message \
  -H "Content-Type: application/json" \
  -d '{"userId": "user-uuid", "question": "What is the weather today?"}'

Create Subscription

curl -X POST http://localhost:3000/api/subscriptions \
  -H "Content-Type: application/json" \
  -d '{"userId": "user-uuid", "tier": "pro", "billingCycle": "monthly", "autoRenew": true}'

Get Usage Info

curl http://localhost:3000/api/chat/usage/user-uuid

Error Handling

The API returns structured errors:

{
  "error": {
    "code": "FREE_QUOTA_EXCEEDED",
    "message": "Free quota exceeded and no active subscription with remaining messages",
    "details": {
      "freeMessagesUsed": 3,
      "freeMessagesLimit": 3,
      "suggestion": "Please purchase a subscription bundle to continue using the service"
    }
  }
}

Available Scripts

  • npm run dev - Start development server with hot reload
  • npm run build - Build for production
  • npm start - Run production build
  • npm run lint - Run ESLint
  • npm run lint:fix - Fix ESLint errors
  • npm run format - Format code with Prettier
  • npm run typecheck - Run TypeScript type checking

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published