12 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
Hybrid React dashboard for financial/trading analysis with Flask backend. Built on Argon Dashboard Chakra PRO template.
Tech Stack
Frontend
- React 18.3.1 + Chakra UI 2.8.2 + Ant Design
- Redux Toolkit for state management
- React Router v6 with React.lazy() code splitting
- CRACO build system with aggressive webpack optimization
- Charts: ApexCharts, ECharts, Recharts, D3
- Additional: Three.js, FullCalendar, Leaflet maps
Backend
- Flask + SQLAlchemy ORM
- ClickHouse (analytics) + MySQL/PostgreSQL (transactional)
- Flask-SocketIO for WebSocket real-time updates
- Celery + Redis for background jobs
- Tencent Cloud SMS + WeChat Pay integration
Development Commands
Frontend Development
npm start # Start with mock data (.env.mock), proxies to localhost:5001
npm run start:real # Start with real backend (.env.local)
npm run start:dev # Start with development config (.env.development)
npm run start:test # Starts both backend (app_2.py) and frontend (.env.test) concurrently
npm run dev # Alias for 'npm start'
npm run backend # Start Flask server only (python app_2.py)
npm run build # Production build with Gulp license headers
npm run build:analyze # Build with webpack bundle analyzer
npm test # Run React test suite with CRACO
npm run lint:check # Check ESLint rules (exits 0)
npm run lint:fix # Auto-fix ESLint issues
npm run clean # Remove node_modules and package-lock.json
npm run reinstall # Clean install (runs clean + install)
Backend Development
python app.py # Main Flask server
python simulation_background_processor.py # Background task processor for trading simulations
pip install -r requirements.txt # Install Python dependencies
Deployment
npm run deploy # Deploy from local (scripts/deploy-from-local.sh)
npm run rollback # Rollback to previous version
Architecture
Application Entry Flow
src/index.js
└── src/App.js (root component)
├── AppProviders (src/providers/AppProviders.js)
│ ├── ReduxProvider (store from src/store/)
│ ├── ChakraProvider (theme from src/theme/)
│ ├── NotificationProvider (src/contexts/NotificationContext.js)
│ └── AuthProvider (src/contexts/AuthContext.js)
├── AppRoutes (src/routes/index.js)
│ ├── MainLayout routes (with navbar/footer)
│ └── Standalone routes (auth pages, fullscreen views)
└── GlobalComponents (modal overlays, global UI)
Routing Architecture (Modular Design)
Routing is declarative and split across multiple files in src/routes/:
- index.js - Main router (combines config + renders routes)
- routeConfig.js - Route definitions (path, component, protection, layout, children)
- lazy-components.js - React.lazy() imports for code splitting
- homeRoutes.js - Nested home page routes
- constants/ - Protection modes, layout mappings
- utils/ - Route rendering logic (wrapWithProtection, renderRoute)
Route protection modes (PROTECTION_MODES):
PUBLIC- No authentication requiredMODAL- Shows auth modal if not logged inREDIRECT- Redirects to /auth/sign-in if not logged in
Frontend Directory Structure
src/
├── App.js - Root component (providers + routing)
├── providers/ - Provider composition (AppProviders.js)
├── routes/ - Modular routing system (see above)
├── layouts/ - Page layouts (MainLayout, Auth)
├── views/ - Page components (Community, TradingSimulation, etc.)
├── components/ - Reusable UI components
├── contexts/ - React contexts (Auth, Notification, Sidebar)
├── store/ - Redux store + slices (auth, posthog, stock, industry, etc.)
├── services/ - API layer (axios wrappers)
├── utils/ - Utility functions (apiConfig, priceFormatters, logger)
├── constants/ - App constants (animations, etc.)
├── hooks/ - Custom React hooks
├── theme/ - Chakra UI theme customization
└── mocks/ - MSW handlers for development
├── handlers/ - Request handlers by domain (auth, stock, company, etc.)
├── data/ - Mock data files
└── browser.js - MSW setup (starts when REACT_APP_ENABLE_MOCK=true)
Backend Structure
app.py - Flask server (routes, auth, business logic)
simulation_background_processor.py - Celery worker for trading simulations
concept_api.py - Concept/industry analysis API
wechat_pay.py / wechat_pay_config.py - WeChat payment integration
tdays.csv - Trading days calendar (loaded at startup)
requirements.txt - Python dependencies
State Management Strategy
- Redux Toolkit: Global state (auth modal, posthog, stock data, industry data, subscriptions, community data)
- React Context: Cross-cutting concerns (AuthContext, NotificationContext, SidebarContext)
- Component State: Local UI state (forms, toggles, etc.)
Real-time Updates
- Flask-SocketIO for WebSocket connections
- Example: Community event notifications push via WebSocket
- Client:
socket.io-clientlibrary
Configuration
Environment Files
.env.mock - Mock mode (default): MSW intercepts all API calls, no backend needed
.env.development - Dev mode: Connects to dev backend
.env.test - Test mode: Used by 'npm run start:test' (backend + frontend together)
.env.production - Production build config
Key environment variables:
REACT_APP_ENABLE_MOCK=true- Enable MSW mockingREACT_APP_API_URL- Backend URL (empty string = use relative paths or MSW)
MSW (Mock Service Worker) Setup
MSW is used for API mocking during development:
- Activation: Set
REACT_APP_ENABLE_MOCK=truein env file - Worker file:
public/mockServiceWorker.js(auto-generated) - Handlers:
src/mocks/handlers/(organized by domain: auth, stock, company, etc.) - Mode:
onUnhandledRequest: 'warn'- unhandled requests pass through to backend
When MSW is active, the dev server proxy is disabled (MSW intercepts first).
Path Aliases (craco.config.js)
All aliases resolve to src/ subdirectories:
@/ → src/
@components/ → src/components/
@views/ → src/views/
@assets/ → src/assets/
@contexts/ → src/contexts/
@layouts/ → src/layouts/
@services/ → src/services/
@store/ → src/store/
@utils/ → src/utils/
@hooks/ → src/hooks/
@theme/ → src/theme/
@mocks/ → src/mocks/
@constants/ → src/constants/
Webpack Optimizations (craco.config.js)
Performance features:
- Filesystem cache (50-80% rebuild speedup)
- Aggressive code splitting by library:
react-vendor- React core (priority 30)charts-lib- echarts, d3, apexcharts, recharts (priority 25)chakra-ui- Chakra UI + Emotion (priority 23)antd-lib- Ant Design (priority 22)three-lib- Three.js (priority 20)calendar-lib- moment, date-fns, FullCalendar (priority 18)
- ESLint plugin removed from build (20-30% speedup)
- Babel caching enabled
- moment locale stripping (IgnorePlugin)
- Source maps: disabled in production,
eval-cheap-module-source-mapin dev
Dev server:
- Port 3000 (kills existing process on prestart)
- Proxy (when MSW disabled):
/api→http://49.232.185.254:5001 - Bundle analyzer:
ANALYZE=true npm run build:analyze
Build Process
npm run buildcompiles with CRACO + webpack optimizations- Gulp task (
gulp licenses) adds Creative Tim license headers to JS/HTML - Output:
build/directory
Node compatibility:
NODE_OPTIONS='--openssl-legacy-provider --max_old_space_size=4096'
Development Workflow
Working with Routes
To add a new route:
- Add lazy import in
src/routes/lazy-components.js - Add route config in
src/routes/routeConfig.jswith:path- URL pathcomponent- From lazyComponentsprotection- MODAL/REDIRECT/PUBLIClayout- 'main' (with nav) or 'none' (fullscreen)
- Routes automatically render with Suspense + ErrorBoundary (handled by PageTransitionWrapper)
Component Organization Patterns
Based on recent refactoring (see README.md for details):
Atomic Design Pattern:
- Atoms - Basic UI elements (buttons, badges, inputs)
- Molecules - Combinations of atoms (cards, forms)
- Organisms - Complex components (lists, panels)
Example structure for large components (1000+ lines):
src/views/Community/components/
├── EventCard/
│ ├── index.js - Smart wrapper (routes compact vs detailed)
│ ├── CompactEventCard.js - Compact view
│ ├── DetailedEventCard.js - Detailed view
│ ├── EventTimeline.js - Atomic component
│ ├── EventImportanceBadge.js - Atomic component
│ └── ...
Utility extraction:
- Extract reusable logic to
src/utils/(e.g.,priceFormatters.js) - Extract shared constants to
src/constants/(e.g.,animations.js)
API Integration
Service layer (src/services/):
- Use
getApiBase()fromsrc/utils/apiConfig.jsfor base URL - Example:
${getApiBase()}/api/endpoint - In mock mode, MSW intercepts; in dev/prod, hits backend
Adding new API endpoints:
- Add service function in
src/services/(or inline in component) - If using MSW: Add handler in
src/mocks/handlers/{domain}.js - Import handler in
src/mocks/handlers/index.js
Redux State Management
Existing slices (src/store/slices/):
authModalSlice- Auth modal stateposthogSlice- PostHog analyticsstockSlice- Stock dataindustrySlice- Industry/concept datasubscriptionSlice- User subscriptionscommunityDataSlice- Community content
Adding new slice:
- Create
src/store/slices/yourSlice.js - Import and add to
src/store/index.js - Access via
useSelector, dispatch viauseDispatch
Backend Architecture
Flask Application (app.py)
- Authentication: Flask-Login + session management
- Database: SQLAlchemy models + ClickHouse client
- Background jobs: Celery tasks for async processing
- Real-time: Flask-SocketIO for WebSocket events
- Trading days:
tdays.csvloaded into memory at startup (globaltrading_daysvariable)
Key Backend Patterns
- ClickHouse: Used for high-volume analytics queries (stock data, time series)
- MySQL/PostgreSQL: Used for transactional data (users, orders, subscriptions)
- Celery: Background processor runs in separate process (
simulation_background_processor.py) - CORS: Enabled for frontend communication
API Proxy Configuration
When not in mock mode, frontend proxies to backend:
/api→http://49.232.185.254:5001(main API)/concept-api→http://49.232.185.254:6801(concept analysis API)
Important Notes
Code Splitting Strategy
Heavy pages are lazy-loaded to reduce initial bundle size:
- Community, TradingSimulation, Company pages use
React.lazy() - Webpack splits large libraries into separate chunks
- Check bundle size with
npm run build:analyze
Error Boundaries
- Layout-level: Each layout (MainLayout, Auth) has its own ErrorBoundary
- Page-level: PageTransitionWrapper wraps each route with ErrorBoundary
- Strategy: Errors are isolated to prevent entire app crashes
PostHog Analytics
- Initialized in Redux (
posthogSlice) - Configured during app startup in
App.js - Used for user behavior tracking
Performance Considerations
- Large components: If component exceeds ~500 lines, consider refactoring (see README.md)
- Re-renders: Use
React.memo,useMemo,useCallbackfor expensive operations - Bundle size: Monitor with webpack-bundle-analyzer
- Caching: Webpack filesystem cache speeds up rebuilds significantly