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.
The project follows a Modular Architecture pattern, emphasizing separation of concerns and maintainability.
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
- 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.
- 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-validatorandValidationPipe. - CORS Management: Fine-grained cross-origin resource sharing configuration.
- 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.
- 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.
- 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.
- 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.
- 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).
- 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).
- 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.
- 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.
- 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).
- User-Centric Routes: Modern
/meprefix for all user-specific resources (e.g.,/sales/orders/me,/sales/cart/me) replacing legacymy-*prefixes.
- 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.
- 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
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
- Node.js (Refer to
package.jsonfor version) - Yarn or NPM
- Running instances of PostgreSQL, MongoDB, and Redis
yarn installCreate a .env file in the root directory and configure the necessary environment variables (Database URLs, API Keys, etc.).
# Development mode
yarn dev
# Production build
yarn build
yarn start:prod# Unit tests
yarn test
# E2E tests
yarn test:e2eThis project is UNLICENSED and intended for private use.
Maintained by KumoD