Skip to content

Repository files navigation

CRM System Backend

A comprehensive, enterprise-grade Customer Relationship Management (CRM) system backend built with NestJS. Designed for businesses to manage customers, sales pipelines, multi-channel messaging, email campaigns, and team collaboration.

Tech Stack

  • Framework: NestJS 11
  • Database: PostgreSQL 16 + Prisma ORM
  • Cache/Queue: Redis 7 + BullMQ
  • Authentication: Passport (Credentials, Google OAuth, Facebook OAuth, 2FA)
  • File Storage: AWS S3
  • Email: React Email templates + Nodemailer
  • Real-time: Socket.IO (WebSockets)
  • i18n: nestjs-i18n

Features

πŸ” Authentication & User Management

  • Multi-method authentication (Credentials, Google OAuth, Facebook OAuth)
  • Email verification with secure tokens
  • Two-factor authentication (2FA)
  • Password reset flow
  • User profile management

🏒 Multi-Tenant Business Management

  • Multi-tenant architecture with business isolation
  • Role-based access control (Owner, Admin, Member)
  • Business email verification
  • Team member invitations with expiring tokens
  • Custom business types (Service-based, Product-based, Hybrid)
  • Business-specific SMTP configuration for email campaigns

πŸ‘₯ Customer Management

  • Comprehensive customer profiles with custom fields
  • Customer status tracking (New, Active, Inactive, Lost)
  • Priority levels (Low, Medium, High)
  • Customer tagging system with colors
  • Dynamic and static customer segments
  • Advanced filtering and search
  • Customer analytics

πŸ’¬ Multi-Channel Messaging

  • Telegram Integration β€” Bot integration, send/receive messages, media support, reply tracking
  • Viber Integration β€” Bot integration, message management
  • Instagram Direct Messages β€” Facebook Graph API integration, message delivery tracking, reactions
  • Facebook Messenger β€” Page integration, message management, delivery tracking, reactions
  • Unified message history across all channels
  • Automatic customer creation from messaging platforms
  • Media file handling (photos, videos, documents, voice messages)

πŸ“§ Email Campaigns

  • Broadcast email campaigns to customer segments
  • Campaign status tracking (Draft, Sending, Sent, Failed)
  • Individual recipient delivery tracking
  • Business-specific SMTP configuration support
  • React Email templates

🎯 Sales Pipelines & Deals

  • Kanban-style pipeline management
  • Customizable pipeline stages with colors
  • Deal tracking with value, currency, and discount support
  • Deal assignment to team members
  • Pipeline access control per member
  • Deal analytics

πŸ’Ό Internal Team Collaboration

  • Internal Chat System β€” Direct (1:1) and group chats
  • Real-time messaging with WebSocket support
  • Message replies and threading
  • Read receipts and unread count tracking
  • Chat participant management
  • Mute notifications per chat
  • File attachments support

πŸ”” Notifications System

  • Real-time notifications via WebSocket
  • Multiple notification categories (Messaging, Business, Pipeline, Customer, Campaign, Internal Chat)
  • Priority levels (Low, Medium, High)
  • Personal and broadcast notifications
  • Notification types include:
    • New messages from customers
    • New customer via messenger
    • Deal created/moved/assigned
    • Team member invitations
    • Campaign completion
    • Customer birthdays
    • And more...

πŸ“Š Analytics

  • Customer analytics
  • Deal analytics
  • Business performance metrics

Prerequisites

  • Node.js 20+
  • Yarn
  • Docker & Docker Compose
  • PostgreSQL 16
  • Redis 7

Getting Started

1. Clone and install dependencies

yarn install

2. Configure environment

Create .env file based on .env.example:

# --------------------------------------------------------
# Application Environment
# --------------------------------------------------------
NODE_ENV=development
APPLICATION_PORT=8080
APPLICATION_URL=http://localhost:8080/api
ALLOWED_ORIGIN=http://localhost:3000

# --------------------------------------------------------
# PostgreSQL Database Configuration
# --------------------------------------------------------
POSTGRES_USER=postgres
POSTGRES_PASSWORD=secret
POSTGRES_DB=crm
DATABASE_URL=postgresql://postgres:secret@localhost:5432/crm?schema=public

# --------------------------------------------------------
# Redis Configuration
# --------------------------------------------------------
REDIS_USER=default
REDIS_PASSWORD=secret
REDIS_PORT=6379
REDIS_URL=redis://default:secret@localhost:6379

# --------------------------------------------------------
# Session & Cookie Configuration
# --------------------------------------------------------
COOKIE_SECRET=your-cookie-secret
SESSION_SECRET=your-session-secret
SESSION_NAME=session
SESSION_DOMAIN=localhost
SESSION_MAX_AGE=30d
SESSION_HTTP_ONLY=true
SESSION_SECURE=false
SESSION_PREFIX=sessions:

# --------------------------------------------------------
# Cloudflare Turnstile Configuration
# --------------------------------------------------------
TURNSTILE_SECRET_KEY=your-turnstile-key

# --------------------------------------------------------
# Google OAuth Configuration
# --------------------------------------------------------
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

# --------------------------------------------------------
# SMTP / Email Configuration
# --------------------------------------------------------
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
SMTP_FROM_EMAIL=noreply@yourapp.com

# --------------------------------------------------------
# Facebook / Instagram OAuth Configuration
# --------------------------------------------------------
FACEBOOK_APP_ID=your-facebook-app-id
FACEBOOK_APP_SECRET=your-facebook-app-secret
INSTAGRAM_OAUTH_SUCCESS_REDIRECT=http://localhost:3000/settings/integrations
INSTAGRAM_WEBHOOK_BASE_URL=http://localhost:8080/api
INSTAGRAM_VERIFY_TOKEN=your-verify-token

3. Start infrastructure

./start-containers.sh
# or
docker-compose up -d

4. Run database migrations

yarn prisma:generate       # generate Prisma client
yarn prisma:migrate:prod   # apply migrations (production)
# or
yarn prisma:push           # sync schema (development)

5. Start the application

yarn start:dev    # development (watch mode)
yarn start:prod   # production

The API will be available at http://localhost:8080/api

Swagger documentation: http://localhost:8080/api/docs

Scripts

Command Description
yarn start:dev Run in watch mode
yarn start:prod Run production build
yarn build Build the project
yarn lint Run ESLint
yarn test Run unit tests
yarn test:e2e Run E2E tests
yarn prisma:studio Open Prisma Studio
yarn prisma:generate Generate Prisma client
yarn prisma:migrate:commit <name> Create new migration
yarn prisma:migrate:prod Apply migrations (production)
yarn prisma:push Sync schema (development only)

Project Structure

src/
β”œβ”€β”€ config/                      # Configuration modules
β”œβ”€β”€ i18n/                        # Internationalization files (en, ru, am, no)
β”œβ”€β”€ infra/                       # Infrastructure layer
β”‚   β”œβ”€β”€ mail/                    # Email service + React Email templates
β”‚   β”œβ”€β”€ orm/                     # Prisma service
β”‚   β”œβ”€β”€ redis/                   # Redis configuration
β”‚   └── s3/                      # S3 file storage
β”œβ”€β”€ modules/
β”‚   β”œβ”€β”€ auth/                    # Authentication & authorization
β”‚   β”‚   β”œβ”€β”€ strategies/          # Passport strategies (local, Google, Facebook, 2FA)
β”‚   β”‚   β”œβ”€β”€ guards/              # Auth guards
β”‚   β”‚   └── dto/                 # Auth DTOs
β”‚   β”œβ”€β”€ user/                    # User profile management
β”‚   β”œβ”€β”€ notification/            # Notification system
β”‚   β”‚   β”œβ”€β”€ notification.gateway.ts    # WebSocket gateway
β”‚   β”‚   β”œβ”€β”€ notification.listener.ts   # Event listeners
β”‚   β”‚   └── notification.service.ts
β”‚   └── business/                # Business module (multi-tenant)
β”‚       β”œβ”€β”€ customer/            # Customer management
β”‚       β”œβ”€β”€ pipeline/            # Sales pipelines & deals
β”‚       β”œβ”€β”€ tag/                 # Customer tags
β”‚       β”œβ”€β”€ segment/             # Customer segments
β”‚       β”œβ”€β”€ invite/              # Team invitations
β”‚       β”œβ”€β”€ analytics/           # Business analytics
β”‚       β”œβ”€β”€ broadcast/           # Email campaigns
β”‚       β”œβ”€β”€ telegram/            # Telegram integration
β”‚       β”œβ”€β”€ viber/               # Viber integration
β”‚       β”œβ”€β”€ instagram/           # Instagram DM integration
β”‚       β”œβ”€β”€ facebook-messenger/  # Facebook Messenger integration
β”‚       └── chat/                # Internal team chat
└── shared/                      # Shared utilities, guards, decorators

Key Integrations

Telegram Bot Integration

  1. Create a bot via @BotFather
  2. Get the bot token
  3. Configure webhook in your business settings
  4. Start receiving and sending messages

Viber Bot Integration

  1. Create a bot via Viber Admin Panel
  2. Get the auth token
  3. Configure webhook
  4. Connect with customers

Instagram Direct Messages

  1. Create a Facebook App
  2. Add Instagram Basic Display and Instagram Messaging products
  3. Configure webhook subscriptions
  4. Link Instagram Business Account
  5. OAuth flow to get page access token

Facebook Messenger

  1. Create a Facebook App
  2. Add Messenger product
  3. Configure webhook subscriptions
  4. Get page access token
  5. Start messaging customers

WebSocket Events

The notification gateway (/notifications) supports the following events:

  • Client β†’ Server:

    • join β€” Join notification room for a business
    • mark_as_read β€” Mark notification as read
  • Server β†’ Client:

    • notification β€” New notification received
    • error β€” Error message

API Documentation

Swagger UI is available at /api/docs when running in development mode.

The API uses:

  • Session-based authentication with Redis storage
  • CORS with configurable allowed origins
  • Rate limiting with Redis-backed throttler
  • Request validation with class-validator
  • i18n support via x-lang header

Database Schema Highlights

  • 27 tables with comprehensive relationships
  • Soft deletes for critical entities (customers, deals, pipelines)
  • Optimized indexes for common query patterns
  • JSON fields for flexible custom fields and metadata
  • Multi-tenant isolation via businessId

Security Features

  • Argon2 password hashing
  • Session management with Redis
  • CSRF protection ready
  • Rate limiting per IP
  • Input validation and sanitization
  • Cloudflare Turnstile support
  • Secure cookie configuration
  • OAuth 2.0 flows

License

Private / Unlicensed

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages