Edit Time: 9/11/2025
NestJS REST API handling business logic, integrations, and data management for the DispatchAI platform.
The Backend service is the core API layer that orchestrates all platform operations including authentication, telephony webhooks, payment processing, calendar integration, and data persistence.
- Framework: NestJS 11 (Node.js 18+)
- Language: TypeScript 5.8
- Database: MongoDB 7 with Mongoose ODM
- Cache: Redis 7 for sessions & caching
- Auth: JWT + Google OAuth 2.0
- Payment: Stripe
- Telephony: Twilio Voice API
- Calendar: Google Calendar API + Microsoft Graph (Outlook)
- Validation: class-validator + class-transformer
- Logging: Winston
- Testing: Jest + Supertest
apps/backend/
βββ src/
β βββ main.ts # Application entry point
β βββ modules/ # Feature modules
β β βββ auth/ # Authentication & authorization
β β βββ user/ # User management
β β βββ company/ # Company/business management
β β βββ plan/ # Subscription plans
β β βββ subscription/ # User subscriptions
β β βββ telephony/ # Twilio voice integration
β β βββ calllog/ # Call logs & history
β β βββ transcript/ # Call transcripts
β β βββ transcript-chunk/ # Transcript chunks
β β βββ service/ # Services catalog
β β βββ service-booking/ # Service bookings/appointments
β β βββ service-form-field/ # Dynamic form fields
β β βββ service-location-mapping/ # Service locations
β β βββ location/ # Location management
β β βββ availability/ # Business hours/availability
β β βββ google-calendar/ # Google Calendar integration
β β βββ google-places/ # Google Places API
β β βββ stripe/ # Stripe payment processing
β β βββ onboarding/ # User onboarding flow
β β βββ setting/ # User settings
β β βββ blog/ # Blog content
β β βββ health/ # Health check
β βββ common/ # Shared utilities
β β βββ constants/ # Constants
β β βββ decorators/ # Custom decorators
β β βββ filters/ # Exception filters
β β βββ guards/ # Auth guards
β β βββ interfaces/ # TypeScript interfaces
β βββ lib/ # External library wrappers
β β βββ ai/ # AI service HTTP client
β β βββ redis/ # Redis client
β β βββ twilio/ # Twilio client
β βββ config/ # Configuration
β β βββ swagger.config.ts # API documentation
β βββ utils/ # Utility functions
βββ test/ # Test suite
β βββ fixtures/ # Test data
β βββ helpers/ # Test utilities
β βββ integration/ # Integration tests
β βββ unit/ # Unit tests
βββ scripts/ # Utility scripts
β βββ seeds/ # Database seeding
βββ package.json # Dependencies & scripts
βββ tsconfig.json # TypeScript config
βββ jest.config.json # Jest config
βββ nest-cli.json # NestJS CLI config
βββ Dockerfile.dev # Development Docker image
βββ Dockerfile.uat # UAT Docker image
Development: http://localhost:4000/api
Swagger UI: http://localhost:4000/api
POST /auth/signup- User registrationPOST /auth/login- Login with email/passwordPOST /auth/google- Google OAuth loginPOST /auth/logout- Logout (clear cookie)GET /auth/me- Get current user
POST /telephony/voice- Handle incoming call (TwiML)POST /telephony/gather- Handle speech input (TwiML)POST /telephony/status- Handle call status callbacks
GET /calllog- List call logs (paginated, filtered)GET /calllog/:id- Get single call logGET /calllog/metrics- Get call metrics/statsPOST /calllog- Create call logPATCH /calllog/:id- Update call log
GET /transcript/call/:callSid- Get transcript by call SIDPOST /transcript- Create transcriptPATCH /transcript/:id- Update transcript
GET /service-booking- List bookingsPOST /service-booking- Create bookingPATCH /service-booking/:id- Update bookingDELETE /service-booking/:id- Cancel booking
GET /google-calendar/auth-url- Get OAuth URLGET /google-calendar/callback- OAuth callbackPOST /google-calendar/token- Store access tokenGET /google-calendar/token- Get stored token
POST /stripe/webhook- Handle Stripe webhooksPOST /stripe/create-checkout- Create checkout session
GET /service- List servicesPOST /service- Create servicePATCH /service/:id- Update serviceDELETE /service/:id- Soft delete service
{
firstName: string
lastName: string
email: string (unique, required)
password?: string
twilioPhoneNumber?: string
fullPhoneNumber?: string
role: 'admin' | 'user'
status: 'active' | 'inactive' | 'suspended'
address?: {
unitAptPOBox?: string
streetAddress: string
suburb: string
state: string
postcode: string
}
greeting: {
message: string
isCustom: boolean
}
createdAt: Date
updatedAt: Date
}{
businessName: string (required)
abn: string (unique, required)
user: ObjectId (ref: User)
calendar_access_token?: string
createdAt: Date
updatedAt: Date
}{
name: string
description: string
price: number
duration: number (minutes)
userId: string
isDeleted?: boolean
createdAt: Date
updatedAt: Date
}{
serviceId: string
client: {
name: string
phoneNumber: string
address: string
}
serviceFormValues: {
serviceFieldId: string
answer: string
}[]
status: 'Cancelled' | 'Confirmed' | 'Done'
note: string
bookingTime: Date
userId: string
callSid?: string
createdAt: Date
updatedAt: Date
}{
userId: string
callerNumber: string
duration: number (seconds)
status: 'completed' | 'no-answer' | 'busy' | 'failed'
serviceBookedId?: string
recordingUrl?: string
transcriptionUrl?: string
startAt: Date
createdAt: Date
updatedAt: Date
}{
callSid: string
userId: string
fullTranscript: string
summary?: string
keyPoints?: string[]
createdAt: Date
updatedAt: Date
}{
name: string (unique, required)
tier: 'FREE' | 'BASIC' | 'PRO'
pricing: {
rrule: string
price: number
stripePriceId: string
}[]
features: {
callMinutes: string
support: string
}
isActive: boolean
}{
userId: ObjectId (ref: User)
planId: ObjectId (ref: Plan)
subscriptionId?: string
stripeCustomerId?: string
chargeId?: string
startAt: Date
endAt: Date
status: 'active' | 'failed' | 'cancelled'
createdAt: Date
updatedAt: Date
}test/
βββ fixtures/ # Test data & factories
βββ helpers/ # Test utilities (DB helper)
βββ integration/ # Integration tests
β βββ calendar/
β βββ calllog/
β βββ plan/
β βββ subscription/
β βββ transcript/
βββ unit/ # Unit tests
βββ calendar/
βββ calllog/
βββ common/
βββ plan/
βββ subscription/
βββ transcript/cd apps/backend
# Run all tests
pnpm test
# Run unit tests only
pnpm test:unit
# Run integration tests only
pnpm test:integration
# Watch mode
pnpm test:watch
# With coverage
pnpm test -- --coverage
# Specific test file
pnpm test -- src/modules/auth/auth.service.spec.ts# Run all seeds
pnpm seed
# Seed telephony test data
pnpm seed:telephony
# Seed call logs
pnpm seed:calllogRequired:
# MongoDB
MONGODB_URI=mongodb://mongo:27017/dispatchai
# Redis
REDIS_HOST=redis
REDIS_PORT=6379
# JWT
JWT_SECRET=your_jwt_secret
JWT_EXPIRES_IN=7d
# Twilio
TWILIO_ACCOUNT_SID=ACxxx...
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=+1234567890Optional:
# Port
PORT=4000
# CORS
CORS_ORIGIN=http://localhost:3000
# Google OAuth
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REDIRECT_URI=http://localhost:4000/api/google-calendar/callback
# Stripe
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# AI Service
AI_SERVICE_URL=http://localhost:8000/api.eslintrc.js: ESLint configuration
tsconfig.json: TypeScript compiler options
jest.config.json: Jest test configuration
nest-cli.json: NestJS CLI settings
-
Install dependencies:
cd apps/backend pnpm installNote: This project uses pnpm as the package manager. If you don't have pnpm installed:
npm install -g pnpm
-
Set up environment:
# Create .env.local cp .env.example .env.local # Edit with your values
-
Start MongoDB & Redis:
docker compose up mongo redis
-
Run in watch mode:
pnpm dev
-
Access services:
- API: http://localhost:4000/api
- Swagger: http://localhost:4000/api
- Health: http://localhost:4000/api/health
# Lint code
pnpm lint
# Lint source only
pnpm lint:src
# Lint tests only
pnpm lint:test
# Type checking
pnpm type-check# Build image
docker build -f Dockerfile.dev -t dispatchai-backend:dev .
# Run container
docker run -p 4000:4000 dispatchai-backend:dev
# Or use docker-compose
docker compose up apiWebhooks:
/telephony/voice- Initial call/telephony/gather- Speech input/telephony/status- Call status updates
Features:
- Call routing & handling
- Speech recognition
- Text-to-speech
- Recording
References:
src/modules/telephony/src/lib/twilio/
Features:
- Subscription management
- Webhook handling
- Customer portal
References:
src/modules/stripe/src/modules/plan/src/modules/subscription/
Features:
- OAuth 2.0 flow
- Token storage
- Event creation
- Calendar sync
References:
src/modules/google-calendar/
Usage:
import { AiHttpModule } from '@/lib/ai/ai-http.module';
@Module({
imports: [AiHttpModule],
})
export class MyModule {}References:
src/lib/ai/
Features:
- Session storage
- CallSkeleton caching
- Rate limiting
References:
src/lib/redis/
Strategies:
- JWT strategy (Passport)
- Google OAuth strategy
Guards:
- JWT auth guard
- CSRF guard
Files:
src/modules/auth/auth.module.tssrc/modules/auth/auth.service.tssrc/modules/auth/strategies/jwt.strategy.tssrc/modules/auth/strategies/google.strategy.ts
Process Flow:
- Incoming call β
/telephony/voice - Gather speech β
/telephony/gather - Send to AI service
- Generate TwiML response
- Play AI response to customer
Files:
src/modules/telephony/telephony.module.tssrc/modules/telephony/telephony.service.tssrc/modules/telephony/services/call-processor.service.ts
Features:
- Store full transcripts
- Generate summaries
- Extract key points
- Chunk management
Files:
src/modules/transcript/transcript.service.tssrc/modules/transcript-chunk/transcript-chunk.service.ts
Fix: Ensure MongoDB is running and MONGODB_URI is correct
Fix: Ensure Redis is running and accessible
Fix: Check JWT_SECRET matches between services
Fix: Verify webhook URL in Twilio console, check authentication
Fix: Ensure STRIPE_WEBHOOK_SECRET matches Stripe dashboard
- NestJS Docs: https://docs.nestjs.com
- Mongoose Docs: https://mongoosejs.com
- Twilio Docs: https://www.twilio.com/docs
- Stripe Docs: https://stripe.com/docs
- Google Calendar API: https://developers.google.com/calendar
- Jest Docs: https://jestjs.io
When adding new modules:
- Generate module with Nest CLI:
nest g module module-name - Create schema in
schema/ - Add service in module root
- Add controller in module root
- Create DTOs in
dto/ - Write tests in
test/unit/ - Update
app.module.ts - Document in Swagger