Raphaelcoolj/investment-site

investment-site Documentation

Generated May 13, 2026View repository β†—

Project Documentation

πŸš€ 1. Overview

Merrick Investments PLC. – Cryptocurrency Investment Simulator: Comprehensive Project Overview

Project Purpose and Core Value Proposition

Merrick Investments PLC. is a high-fidelity cryptocurrency investment simulator designed to replicate real-world trading and portfolio management in a controlled, educational, and risk-free environment. Unlike traditional crypto exchanges, this platform does not execute real blockchain transactions. Instead, it simulates market behavior, investment growth, and transactional workflows using live market data from multiple API providers (CoinGecko, CryptoCompare) with robust fallback mechanisms. The platform serves dual purposes: as a financial modeling tool for users to practice investment strategies and as a management dashboard for administrators to oversee user activity, configure profit systems, and enforce platform-wide policies.

The system is built with Next.js 14 and leverages modern web technologies to deliver a responsive, secure, and visually polished user experience. It emphasizes real-time data visualization, automated profit generation, and granular administrative control, making it suitable for educational institutions, financial training programs, or internal corporate investment simulations. The inclusion of multi-currency support, transaction logging, and role-based access control ensures scalability and usability across diverse user bases.

Core Problem Solved

The primary challenge Merrick Investments PLC. addresses is the lack of accessible, realistic cryptocurrency investment simulators that combine real-time market data, automated profit modeling, and comprehensive administrative oversight. Many existing platforms either:

  • Use static or delayed price feeds,
  • Lack automation in profit generation,
  • Fail to provide detailed transaction histories,
  • Or do not offer robust admin tools for managing user accounts and system parameters.

This project solves these issues by:

  • Delivering live market data with triple-layered fallback pricing to ensure reliability,
  • Automating daily profit increments based on admin-defined rates,
  • Enabling multi-asset deposits (BTC, ETH, SOL, USDT, fiat) with transparent conversion tracking,
  • Providing a full admin suite for user management, role assignment, and system configuration,
  • Ensuring secure authentication and data integrity through NextAuth.js and MongoDB.

The result is a production-grade simulation environment that closely mirrors real-world crypto investing while maintaining full control and visibility for administrators.

Architectural Design and Workflow

The application follows a client-server architecture with a Next.js 14 App Router frontend and a Node.js-based API layer that interacts with MongoDB for data persistence. Authentication is handled via NextAuth.js, supporting email/password login with role-based session management. User roles include standard users and administrators, with elevated permissions for managing deposits, withdrawals, and system settings.

Key workflows include:

  • User Registration & Login: Secure onboarding with password reset support.
  • Dashboard Interaction: Real-time balance updates, interactive charts (using Chart.js), and transaction history.
  • Deposit & Withdrawal Processing: Users initiate transactions, which are logged and tracked in pending or completed states.
  • Automated Profit Generation: Daily increments are calculated server-side and applied to user balances.
  • Admin Oversight: Admins can view all users, adjust balances, toggle profit systems, and manage system-wide settings.

The system uses Axios for API calls with multi-provider fallback logic to ensure price data availability even if primary APIs fail. Images are stored via Cloudinary, and transaction receipts are dynamically generated with crypto-to-USD conversions.

Security and User Experience Considerations

Security is implemented through NextAuth.js with session encryption, MongoDB data encryption at rest, and SMTP-based email notifications for critical actions. The UI is fully responsive, employing Tailwind CSS and Vanilla CSS with glassmorphism aesthetics for a modern, intuitive interface.

Key UX features include:

  • Interactive charts with real-time price updates,
  • Clickable transaction rows that reveal detailed receipts,
  • Responsive design optimized for mobile, tablet, and desktop,
  • Customizable user profiles with image uploads,
  • Error handling with user-friendly feedback.

The platform is designed to be ad-blocker resistant through server-side price fetching and robust API fallbacks, ensuring consistent performance.


Tech Stack at a Glance

CategoryTechnologyPurpose
FrameworkNext.js 14 (App Router)Full-stack React framework with server components and routing
LanguageTypeScriptStrongly typed JavaScript for scalability and maintainability
DatabaseMongoDB (Mongoose ODM)NoSQL database for storing user data, transactions, and settings
AuthenticationNextAuth.jsSecure session management and role-based access control
StylingTailwind CSS, Vanilla CSSResponsive, modern UI with glassmorphism effects
Charts & VisualizationChart.js, React-ChartJS-2Real-time market data visualization
API IntegrationAxiosHTTP client with multi-provider fallback logic
Market Data SourcesCoinGecko, CryptoCompareReal-time cryptocurrency pricing with redundancy
Image ManagementCloudinaryCloud-based image storage and CDN delivery
Email & NotificationsNodemailer (SMTP)Sending transaction confirmations and system alerts
TestingPlaywright (E2E)End-to-end testing of authentication and transaction flows
EnvironmentNode.jsJavaScript runtime for server-side logic
Version ControlGit (implied)Source code management and collaboration

Conclusion

Merrick Investments PLC. represents a sophisticated fusion of financial simulation, real-time data engineering, and enterprise-grade administration. By combining Next.js 14’s modern web capabilities with MongoDB’s flexible data model and NextAuth.js’s robust security, the platform delivers a secure, scalable, and visually compelling investment simulator. Its emphasis on automation, fallback resilience, and admin control sets it apart from conventional crypto tools, making it ideal for educational, training, or internal financial modeling use cases. The project demonstrates best practices in full-stack development, API design, and user experienceβ€”positioning it as a reference implementation for similar simulation platforms.


πŸ“‚ 2. Project Structure

Directory Structure

The codebase contains the following primary files and directories:

  • .gitignore
  • .vscode/settings.json
  • README.md
  • delete_tests.bat
  • e2e/auth.spec.ts
  • jest.config.js
  • jest.setup.js
  • legal.txt
  • next-auth.d.ts
  • next.config.mjs
  • package-lock.json
  • package.json
  • playwright.config.ts
  • postcss.config.js
  • src/app/admin/investments/page.tsx
  • src/app/admin/layout.tsx
  • src/app/admin/page.tsx
  • src/app/admin/settings/page.tsx
  • src/app/admin/users/[id]/investments/page.tsx
  • src/app/admin/users/[id]/page.tsx

Generated via local analysis.


πŸ—οΈ 3. Architecture & Data Flow

Deep Architecture Analysis: Merrick Investments PLC. Cryptocurrency Investment Platform

1. Deep-Dive Architecture Reasoning

1.1 System Overview

Merrick Investments PLC. is a Next.js 14 application using the App Router architecture, implementing a monorepo-style structure with clear separation between frontend, backend, and shared components. The system follows a hybrid architecture combining:

  • Serverless API Routes (Next.js API endpoints)
  • Server Components (React Server Components)
  • Client Components (interactive UI elements)
  • Edge Functions (via middleware)
  • Database Layer (MongoDB with Mongoose ODM)

1.2 Core Architecture Patterns

1.2.1 Domain-Driven Design (DDD) with Modular Monolith

The codebase exhibits modular monolith characteristics with clear domain separation:

  • User Domain: Authentication, profiles, transactions
  • Investment Domain: Portfolio management, deposits, profit tracking
  • Admin Domain: User management, system settings, investment controls
  • Shared Kernel: Common utilities, models, and types

1.2.2 Clean Architecture Layers

The architecture follows Clean Architecture principles with:

  • Presentation Layer: React components (both server and client)
  • Application Layer: API routes, business logic handlers
  • Domain Layer: Core models (User, Investment, Transaction)
  • Infrastructure Layer: Database connections, external APIs

1.2.3 CQRS (Command Query Responsibility Segregation)

The API structure demonstrates CQRS patterns:

  • Commands (POST/PUT/DELETE routes) handle state mutations
  • Queries (GET routes) handle data retrieval
  • Separate read/write models (e.g., User model vs. profile DTOs)

1.2.4 Repository Pattern

The database access follows the Repository Pattern through:

  • Centralized lib/db.ts connection management
  • Model-specific repositories (implicit in Mongoose models)
  • Separation of database concerns from business logic

1.2.5 Strategy Pattern for Price Fetching

The pricing system implements a Strategy Pattern for resilient price fetching:

// In lib/prices.ts
const providers = [coinGecko, cryptoCompare, staticPrices];
let lastPrice = null;

export async function getPrice(currency: string): Promise<number> {
  for (const provider of providers) {
    try {
      const price = await provider.getPrice(currency);
      lastPrice = price;
      return price;
    } catch (error) {
      console.error(`Price provider ${provider.name} failed`, error);
    }
  }
  return lastPrice; // Fallback to last known price
}

1.2.6 Observer Pattern for State Changes

The investment system uses an Observer Pattern for:

  • Daily profit increments
  • Transaction state changes
  • Balance updates Implemented via:
  • Database change streams (MongoDB)
  • React state management
  • Next.js revalidation triggers

1.3 Authentication Architecture

1.3.1 NextAuth.js Integration

The authentication system uses NextAuth.js with:

  • Custom Credentials Provider (username/password)
  • Session Management with JWT
  • Role-Based Access Control (RBAC)
  • Edge Middleware for route protection

Key authentication flows:

  1. Login: Credentials β†’ Session creation β†’ JWT
  2. Protected Routes: Middleware checks session
  3. Role-Based UI: Components render differently based on session.user.role

1.3.2 Password Reset Flow

Implements a Token-Based Reset Pattern:

  1. User requests reset β†’ Token generated (JWT with expiry)
  2. Token sent via email (Nodemailer)
  3. User clicks link β†’ Server validates token β†’ Allows password change
  4. Token invalidated after use

1.4 Data Flow Architecture

1.4.1 Transaction Processing Pipeline

  1. Client Request β†’ API Route (Next.js)
  2. Validation Layer β†’ Zod schemas
  3. Business Logic β†’ Service layer
  4. Database Transaction β†’ Mongoose operations
  5. State Update β†’ Revalidation triggers
  6. Notification β†’ Email/SMTP (if applicable)

1.4.2 Investment System Architecture

The investment system follows a Saga Pattern for complex operations:

  1. Deposit β†’ Creates transaction β†’ Updates balance β†’ Triggers profit calculation
  2. Daily Increment β†’ Scheduled job β†’ Updates investments β†’ Credits profits
  3. Withdrawal β†’ Validates balance β†’ Creates transaction β†’ Updates balance

1.5 Frontend Architecture

1.5.1 Hybrid Rendering Strategy

The frontend uses a hybrid rendering approach:

  • Server Components for:
    • Layouts
    • Data fetching
    • SEO-critical content
  • Client Components for:
    • Interactive elements (modals, charts)
    • State management
    • Browser APIs

1.5.2 State Management

Uses a multi-tier state management approach:

  1. React Context (AuthProvider.tsx) for authentication state
  2. Component State (useState/useReducer) for local UI state
  3. URL State for shareable views (e.g., transaction filters)
  4. Server State via React Server Components

1.5.3 Charting Architecture

The CryptoChart component implements:

  • Adapter Pattern for charting libraries
  • Responsive Design with Tailwind
  • Real-time Updates via WebSocket or polling
  • Fallback Static Charts when APIs fail

1.6 Admin System Architecture

1.6.1 RBAC Implementation

The admin system uses a Role-Based Access Control pattern:

  • Roles: user, admin, superadmin
  • Permissions: Fine-grained via middleware checks
  • UI Components: Conditionally rendered based on permissions

1.6.2 Bulk Operations

Admin operations implement:

  • Command Pattern for bulk actions
  • Batch Processing for large datasets
  • Progress Tracking via UI feedback

1.7 Resilience Patterns

1.7.1 Circuit Breaker Pattern

The pricing system implements circuit breakers:

// In lib/prices.ts
const circuitBreakers = {
  coinGecko: { failureCount: 0, timeout: 30000 },
  cryptoCompare: { failureCount: 0, timeout: 30000 }
};

async function withCircuitBreaker(provider, fn) {
  if (circuitBreakers[provider].failureCount > 5) {
    if (Date.now() - circuitBreakers[provider].lastFailure < circuitBreakers[provider].timeout) {
      throw new Error(`${provider} service unavailable`);
    }
    circuitBreakers[provider].failureCount = 0;
  }

  try {
    const result = await fn();
    circuitBreakers[provider].failureCount = 0;
    return result;
  } catch (error) {
    circuitBreakers[provider].failureCount++;
    circuitBreakers[provider].lastFailure = Date.now();
    throw error;
  }
}

1.7.2 Retry Mechanism

API calls implement exponential backoff:

// In lib/api.ts
async function fetchWithRetry(url, options, retries = 3, backoff = 1000) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } catch (error) {
    if (retries <= 0) throw error;
    await new Promise(res => setTimeout(res, backoff));
    return fetchWithRetry(url, options, retries - 1, backoff * 2);
  }
}

1.8 Testing Architecture

1.8.1 Test Pyramid Implementation

The test suite follows:

  • Unit Tests: Jest for pure functions and components
  • Integration Tests: Jest for API routes
  • E2E Tests: Playwright for user flows
  • Contract Tests: API route tests against models

1.8.2 Test Isolation

Tests use:

  • Test Databases (in-memory MongoDB for unit tests)
  • Mock Services (for external APIs)
  • Fixtures (for consistent test data)

2. Data Flow & State Transitions

OriginActionLogic HandlerResulting State
User BrowserNavigate to /auth/loginNext.js routingLoads login page
User BrowserSubmit login formNextAuth credentials providerValidates credentials β†’ Creates session β†’ Redirects to /dashboard
User BrowserClick "Deposit" buttonDepositModal componentOpens deposit modal
User BrowserSubmit deposit form/api/deposit routeValidates amount β†’ Creates transaction β†’ Updates user balance β†’ Sends confirmation email
User BrowserNavigate to /dashboard/transactionsTransactions page componentFetches transactions β†’ Renders transaction list
Cron Job (Vercel)Daily at 00:00 UTC/api/invest routeCalculates daily profits β†’ Updates all investments β†’ Credits user balances
Admin BrowserNavigate to /admin/usersAdmin users pageFetches all users β†’ Renders user list
Admin BrowserClick "Toggle Daily Increments"/api/admin/users/[id] routeUpdates user settings β†’ Triggers profit calculation
Admin BrowserUpload profile image/api/upload routeProcesses image β†’ Uploads to Cloudinary β†’ Updates user profile
User BrowserClick "Reset Password"/auth/forgot-password pageGenerates reset token β†’ Sends email β†’ Shows confirmation
User BrowserSubmit new password/api/auth/reset-password routeValidates token β†’ Updates password β†’ Invalidates token
External API (CoinGecko)Price updatelib/prices.tsUpdates cached prices β†’ Triggers chart re-render
Database (MongoDB)Investment document updateMongoose middlewareUpdates investment β†’ Triggers balance recalculation
User BrowserClick transaction rowTransactionDetailModalFetches transaction details β†’ Opens modal with receipt
User BrowserNavigate to /dashboard/investmentsInvestments pageFetches investments β†’ Calculates current value β†’ Renders portfolio

3. Mermaid.js Architecture Diagram

Diagram Explanation:

  1. Client Layer:

    • Top-level components organized by route
    • AuthProvider wraps the entire application for session management
    • Interactive components (modals, charts) are client-side
  2. Authentication:

    • Centralized auth configuration (auth.ts)
    • NextAuth configuration with custom providers
    • Session management via JWT
  3. Data Layer:

    • MongoDB connection management (lib/db.ts)
    • Mongoose models for all domain entities
    • Clear separation of concerns between models
  4. API Routes:

    • Organized by domain (auth, user, admin, etc.)
    • Each route handles its own validation and business logic
    • Price fetching is centralized in lib/prices.ts
  5. External Services:

    • Multiple price providers for resilience
    • Email service for notifications
    • Cloudinary for file storage
  6. Middleware:

    • Route protection for admin and sensitive endpoints
    • Authentication validation
  7. Testing:

    • E2E tests with Playwright
    • API tests with Jest
    • Component tests with Jest

This architecture demonstrates a well-structured, maintainable system following modern React/Next.js patterns with clear separation of concerns and robust error handling.

πŸ“ˆ System Architecture Diagram

Rendering diagram…

πŸ› οΈ 4. Function Breakdowns

Core Functionality

Based on the file tree, this project implements logic across 17 key source files including .vscode/settings.json, README.md, e2e/auth.spec.ts.

Generated via local analysis.