Skip to content

datnt19213/kasma-backend-megaplatform

Repository files navigation

πŸš€ Kasma Mega Platform - Backend API

Kasma Backend is a high-performance, scalable, and modular server-side application built with NestJS. It serves as the core infrastructure for the Kasma Mega Platform, providing robust authentication, multi-tenancy support, and complex resource management.


πŸ—οΈ System Architecture

The project follows a Modular Architecture pattern, emphasizing separation of concerns and maintainability.

High-Level Architecture

graph TD
    Client[Client Applications] <--> Gateway[API Gateway / Load Balancer]
    Gateway <--> NestJS[NestJS Application]

    subgraph "Backend Core"
        NestJS --> Controllers[Controllers]
        Controllers --> Services[Services]
        Services --> Modules[Modules]
    end

    subgraph "Data Layer"
        Modules --> PG[(PostgreSQL - Primary Data)]
        Modules --> MG[(MongoDB - Audit Logs)]
        Modules --> RD[(Redis - Caching)]
    end

    subgraph "Security & Integration"
        NestJS --> Auth[Auth / JWT / Session]
        NestJS --> RBAC[RBAC / Permissions]
        NestJS --> Middlewares[Cors / Idempotency / Validation]
    end
Loading

Key Pillars

  • NestJS Framework: Leveraging TypeScript for reliable and maintainable code.
  • Hybrid Storage:
    • PostgreSQL: Structured primary data (Users, Tenants, Roles).
    • MongoDB: Flexible data requirements and audit logging.
    • Redis: Low-latency caching for performance optimization.
  • Background Processing: Leveraging BullMQ for reliable, asynchronous task execution (Email notifications, stock synchronization, abandoned cart recovery).
  • Multi-Tenancy: Built-in support for tenant isolation via headers (X-Tenant-Kasma-Id).
  • RBAC (Role-Based Access Control): Granular permission management across different user roles.

✨ Core Functionalities

πŸ” Authentication & Security

  • JWT & Session Based Auth: Secure user authentication with support for both token-based and session-based flows.
  • Idempotency: Protects against duplicate requests using specialized interceptors.
  • Global Validation: Strict input validation using class-validator and ValidationPipe.
  • CORS Management: Fine-grained cross-origin resource sharing configuration.

🏒 Identity & Access Management (IAM)

  • User Management: Complete user lifecycle management (Registration, Profile, Credentials).
  • Tenant Management: Organization/Tenant isolation and specialized access keys.
  • Permission System: Dynamic role and permission mapping for fine-grained access control.

πŸ›’ Ecommerce & Sales Management

  • Product Catalog: Full CRUD for products with hybrid storage synchronization (Postgres for core, MongoDB for rich content).
  • Categories & Tags: Hierarchical organization and flexible tagging systems.
  • Sales Operations: Complete shopping cart, wishlist, and order management workflows.
  • Subscription & Pre-orders: Support for recurring plans and early product reservations.
  • Advanced Search: Powerful filtering by search terms, categories, tags, price range, and status.

πŸ“’ Marketing & Growth

  • Promotion Engine: Advanced discount rules including B1G1, Flash Sales, and fixed/percentage discounts.
  • Coupon Management: Flexible voucher system with usage limits, activation dates, and minimum order requirements.
  • Loyalty & Membership: Tier-based membership system with points earning/redemption history.
  • Affiliate & Referral: Program management with unique affiliate link generation and tracking.
  • Abandoned Cart Recovery: Automated tracking of inactive carts (MongoDB) and scheduled background notification jobs (BullMQ) to improve conversion rates.
  • Product Bundling: Create and manage product combos with specialized pricing.

πŸ“¦ Logistics & Warehouse Management

  • Inventory Control: Real-time stock tracking with multi-warehouse support and adjustment logs.
  • Inventory Buffer: MongoDB-based virtual stock rules to prevent over-selling.
  • Shipping & Zones: Geographic-based shipping calculation and weight-based rules.
  • Fulfillment: Granular picking, packing, and labeling workflow with carrier integration (GHTK, GHN, etc.).
  • Procurement & PO: Purchase order management from draft to received status.

πŸ’° Finance & Payment Management

  • Tax & VAT Compliance: Hierarchical tax rule matching by country/region/zip with inclusive/exclusive calculation support.
  • Multi-Currency: Global commerce support with real-time exchange rate conversion and base currency synchronization.
  • Store Credit & Wallet: Integrated user wallet for internal balance management (Reloads, Refunds, Payments).
  • Gift Card Engine: Secure prepaid card registry with transactional redemption logic.
  • Financial Ledger: MongoDB-based high-volume auditing for all internal value movements.
  • Transaction Bridge: Seamless integration with the Kasma Transaction microservice for external payment gateways (Stripe, PayPal, COD).

πŸ› οΈ Post-Purchase Operations

  • Product Reviews & Ratings: Customer feedback system with rating aggregation and visibility moderation.
  • RMA (Return Merchandise): End-to-end return workflow from initial request to inspection findings (MongoDB) and restocking.
  • Refund & Credit Memo: Transaction-safe refunds via external gateways or internal wallet, including automated memo generation.
  • Customer Support Tickets: Multi-channel support system with ticket priority tracking and full conversation histories (MongoDB).

πŸ“ Blog & Content Management (CMS)

  • Article Editor: Professional WYSIWYG/Markdown support with dual-database persistence (Postgres for indexing, MongoDB for rich content).
  • Taxonomy Management: Hierarchical categories and multi-tagging system for article organization.
  • Media Library: Integrated media management with support for multiple providers (Cloudinary/KEDIA) via strategy keys.
  • Revision Control: Comprehensive history tracking (MongoDB) allowing for article comparison and restoration to any point in time.
  • Scheduling: Automated publishing engine for future-dated articles.
  • Post Formats: Support for diverse content types including Standard, Video, Gallery, Audio, and Quote formats.
  • SEO & Metadata: Integrated metadata manager (Meta Title, Description, OG) with automatic XML sitemap generation.
  • URL Redirection: Automated 301/302 redirect tracking for slug changes to preserve search ranking.
  • Keyword Analysis: Built-in utility to analyze keyword density and provide SEO optimization suggestions.
  • Navigation & Layout: Multi-level menu manager (Header/Footer) and dynamic sidebar widget engine.
  • Content Enrichment: Automatic Table of Contents (ToC) extraction and related posts suggestion engine based on tag similarity.
  • Content Analytics: High-performance engagement tracking (Views, Avg Duration, Bounce Rate) and search query logging using MongoDB.
  • Advanced Distribution: RSS 2.0 feed generation, Guest Post portal with moderation workflow, and internal Shortlink generator for social sharing.

πŸŽ“ Learning & Education

  • Course Management: Structured syllabus management (Course > Chapter > Lesson) with support for rich learning materials.
  • Flexible Media Storage: Seamlessly toggle between Kedia (Internal) and Cloudinary storage for video lessons, PDFs, and assets.
  • Content Engagement: Progress tracking with resume playback, timestamped note-taking, and drip content unlocking.
  • Assessment & Grading: Comprehensive quiz/exam engine with auto-grading for objective questions and multi-provider assignment uploads.
  • Credential & Certification: Automated PDF certificate generation upon course completion with a public verification portal and digital badges.
  • Operation & Management: Multi-tenant enrollment approval workflows, instructor analytics dashboards, and structured learning path skill-mapping.
  • Reporting & Analytics: Comprehensive cross-database insights into student engagement, completion rates, and instructor revenue trends.
  • Advanced Engagement: Gamification engine with XP, leveling, and leaderboards, plus SCORM/xAPI support for standard e-learning content.

⚑ Performance & Scalability

  • Distributed Locking (Redlock): Strict concurrency control for sensitive resources (Inventory, Wallets) using Redis to prevent race conditions during high-traffic events.
  • Asynchronous Workers (BullMQ): Offloading heavy operations to dedicated workers (Order confirmation, inventory sync, marketing notifications, revenue settlement).
  • Analytics Hub: Real-time business intelligence dashboard aggregating metrics across Postgres (Sales) and MongoDB (Fraud, Finance).

πŸ›£οΈ API Standardization

  • User-Centric Routes: Modern /me prefix for all user-specific resources (e.g., /sales/orders/me, /sales/cart/me) replacing legacy my-* prefixes.

πŸ› οΈ Developer Experience

  • Swagger Documentation: (Optional) Integrated API documentation for easy exploration.
  • Automated Testing: Robust E2E and unit testing suite using Jest.
  • Standardized Code Style: Enforced with ESLint and Prettier for consistency.

πŸ› οΈ Tech Stack

  • Runtime: Node.js (v20+)
  • Framework: NestJS
  • ORM: TypeORM
  • Databases:
    • PostgreSQL (Primary)
    • MongoDB (Logging)
    • Redis (Cache)
  • Security: bcrypt, jsonwebtoken, cookie-parser
  • Validation: class-validator, class-transformer

πŸ“‚ Project Structure

src/
β”œβ”€β”€ common/          # Global decorators, filters, guards, and interceptors
β”œβ”€β”€ config/          # Application and environment configurations
β”œβ”€β”€ database/        # Database connection and module setup
β”œβ”€β”€ dto/             # Data Transfer Objects
β”œβ”€β”€ entities/        # Primary entities (Ecommerce, Sales, Marketing, Logistics, Finance, IAM, Blog - PostgreSQL)
β”‚   β”œβ”€β”€ ecommerce/
β”‚   β”œβ”€β”€ sales/
β”‚   β”œβ”€β”€ marketing/
β”‚   β”œβ”€β”€ logistics/
β”‚   β”œβ”€β”€ finance/
β”‚   └── blog/
β”œβ”€β”€ entities/mongo/  # MongoDB entities (Product Details, Blog Details, Revisions, Cart, Wishlist...)
β”œβ”€β”€ modules/         # Core business logic (Auth, User, Ecommerce, Sales, Marketing, Logistics, Blog)
β”œβ”€β”€ shared/          # Shared utilities and services
└── main.ts          # Application entry point

πŸš€ Getting Started

Prerequisites

  • Node.js (Refer to package.json for version)
  • Yarn or NPM
  • Running instances of PostgreSQL, MongoDB, and Redis

Installation

yarn install

Environment Setup

Create a .env file in the root directory and configure the necessary environment variables (Database URLs, API Keys, etc.).

Running the App

# Development mode
yarn dev

# Production build
yarn build
yarn start:prod

Testing

# Unit tests
yarn test

# E2E tests
yarn test:e2e

πŸ“„ License

This project is UNLICENSED and intended for private use.


Maintained by KumoD

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors