A comprehensive subscription-based AI chatbot system built with TypeScript, following Clean Architecture principles and Domain-Driven Design (DDD).
This system implements two main modules:
- AI Chat Module: Handles user questions, returns mocked OpenAI responses, tracks usage, and manages quotas
- Subscription Bundle Module: Manages subscription bundles with different tiers, billing cycles, and auto-renewal
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)
- 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
- âś… 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)
- âś… Create subscription bundles (Basic, Pro, Enterprise)
- âś… Choose billing cycle: monthly or yearly
- âś… Toggle auto-renew
- âś… Each subscription includes:
maxMessages: Maximum messages allowedprice: Subscription pricestartDate: Subscription start dateendDate: Subscription end daterenewalDate: 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
- Runtime: Node.js
- Language: TypeScript
- Framework: Express.js
- Database: PostgreSQL
- Validation: Zod
- Code Quality: ESLint, Prettier
- Node.js (v18 or higher)
- PostgreSQL (v12 or higher)
- npm or yarn
- Clone the repository:
git clone <repository-url>
cd AIChatBot-Subscription-System- Install dependencies:
npm install- Set up environment variables:
Create a
.envfile in the root directory:
DATABASE_URL=postgresql://user:password@localhost:5432/ai_chatbot_db
PORT=3000
NODE_ENV=development- Create the PostgreSQL database:
createdb ai_chatbot_db- Build the project:
npm run buildnpm run devnpm run build
npm startThe server will start on http://localhost:3000 (or the port specified in .env).
POST /api/users
Content-Type: application/json
{
"email": "user@example.com",
"name": "John Doe"
}GET /api/users/:userIdPOST /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 /api/chat/users/:userId/messages?limit=50POST /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 /api/subscriptions/users/:userId/subscriptionsGET /api/subscriptions/users/:userId/subscriptions/activePOST /api/subscriptions/subscriptions/:bundleId/cancelPOST /api/subscriptions/subscriptions/:bundleId/renewGET /healthThe system includes scheduled jobs that should be run via cron:
Runs on the 1st of each month to reset free quotas:
# Cron: 0 0 1 * *
node dist/jobs/quotaResetJob.jsRuns daily to process subscription renewals:
# Cron: 0 0 * * *
node dist/jobs/subscriptionRenewalJob.jsThe system uses the following main tables:
users: User accountssubscription_bundles: Subscription bundleschat_messages: Chat message historymonthly_usage: Monthly free quota trackingbundle_usage: Subscription bundle usage tracking
See src/database/schema.sql for the complete schema.
The system uses structured error responses:
{
"error": "Error message here"
}Common Error Codes:
400: Bad Request (validation errors)403: Forbidden (quota exceeded)404: Not Found409: Conflict (e.g., duplicate email)500: Internal Server Error
- Create a user:
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"email": "test@example.com", "name": "Test User"}'- 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?"}'- 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
}'- 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?"}'Run linting:
npm run lintFix linting issues:
npm run lint:fixFormat code:
npm run formatCheck formatting:
npm run format:check- 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
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
Potential improvements for production:
- Add comprehensive test coverage
- Implement authentication and authorization
- Add rate limiting
- Implement proper logging (Winston, Pino)
- Add monitoring and metrics
- Implement database migrations (e.g., using Knex.js or TypeORM)
- Add API documentation (Swagger/OpenAPI)
- Implement caching layer (Redis)
- Add message queue for async processing
- Implement proper error tracking (Sentry)
MIT
[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.