Skip to content

yang05051/study-room-booking

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

693 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Study Room Booking System

A comprehensive WeChat Mini Program for study room reservations with advanced backend infrastructure, featuring real-time booking management, integrated payment systems, membership tiers, administrative controls, and sophisticated caching mechanisms.

πŸ“‹ Table of Contents

🎯 Overview

This study room booking system is a production-ready WeChat Mini Program that provides comprehensive room reservation management with a sophisticated backend architecture. The system supports real-time booking, payment processing, membership management, administrative controls, and advanced caching for optimal performance.

Key Highlights

  • WeChat Integration: Native WeChat Mini Program with official API integration
  • Real-time Booking: Advanced seat selection with live availability updates
  • Payment Processing: WeChat Pay integration with order management
  • Membership System: Tiered membership with benefits and automatic management
  • Admin Dashboard: Comprehensive administrative interface with batch operations
  • Caching System: Multi-layer caching with intelligent invalidation
  • Scalable Backend: Microservice-oriented architecture with connection pooling

πŸ—οΈ System Architecture

Frontend Architecture

  • Framework: WeChat Mini Program Native Framework
  • Language: TypeScript with WXSS styling
  • State Management: Global App state with behavior-based components
  • UI Pattern: Component-based architecture with reusable behaviors
  • Build System: Native WeChat Developer Tools with TypeScript compilation

Backend Architecture

  • Runtime: Node.js with Express.js framework
  • Database: MySQL with connection pooling
  • Caching: Multi-layer cache system with Redis-style operations
  • Services: Microservice pattern with dependency injection
  • Authentication: JWT-based with WeChat OAuth integration
  • Monitoring: Centralized logging and error handling

πŸ“± Frontend Features

Core User Experience

πŸ” Authentication System

  • WeChat Login: Official WeChat OAuth integration
  • Session Management: Persistent login with token refresh
  • User Profiles: Avatar management and user information
  • Ban System: Integrated ban information display with appeals

🏠 Home & Navigation

  • Tab-based Navigation: 5-tab interface (Booking, My Bookings, Wallet & Membership, Self-service, Customer Service)
  • Real-time Updates: Live room availability and booking status
  • Search & Filter: Advanced room discovery with availability sorting
  • Quick Actions: Fast access to common operations

πŸ“š Room Management

  • Room Discovery: Visual room browsing with images and details
  • Availability Timeline: Interactive time-slot visualization
  • Seat Selection: Advanced grid-based seat picker with real-time status
  • Room Details: Comprehensive information with booking history

⏰ Booking System

  • Interactive Booking: Drag-and-drop time selection
  • Conflict Detection: Real-time validation and collision prevention
  • Price Calculation: Dynamic pricing with membership discounts
  • Booking Confirmation: Multi-step confirmation with payment integration
  • QR Code Generation: Check-in QR codes for booked seats

Advanced Features

πŸ‘€ My Bookings Management

  • Booking History: Complete booking lifecycle tracking
  • Status Management: Real-time booking status updates
  • Cancellation System: Flexible cancellation with fee calculation
  • Batch Operations: Multi-booking management capabilities
  • Check-in/Check-out: QR code-based attendance system

πŸ’° Wallet & Membership System

  • Balance Management: Real-time balance tracking and recharge
  • Payment Integration: WeChat Pay with order tracking
  • Membership Tiers: Automatic tier management with benefits
  • Coupon System: Advanced coupon management with validation
  • Transaction History: Detailed financial transaction tracking

πŸ› οΈ Self-Service Features

  • Service Status: Real-time service availability
  • QR Scanner: Integrated QR code scanning for check-ins
  • Developer Tools: Debug panel for development/testing

Administrative Interface

πŸ‘¨β€πŸ’Ό Admin Panel (packageAdmin)

  • Dashboard: Comprehensive system overview
  • User Management: User profiles, bans, and bulk operations
  • Room Management: Room creation, editing, and layout management
  • Batch Operations: Multi-user operations with progress tracking
  • Tag Management: User categorization and automatic tagging
  • Coupon Management: Coupon creation, distribution, and analytics
  • Parameter Management: System configuration management
  • Refund Review: Financial dispute resolution interface

πŸ“’ Announcement System (packageAnnouncement)

  • Announcement Creation: Rich text announcement composer
  • Content Management: Announcement lifecycle management
  • Preview System: Pre-publication preview functionality
  • Distribution Control: Targeted announcement delivery

πŸ’³ Enhanced Recharge (packageRecharge)

  • Coupon Integration: Coupon application during recharge
  • Payment Confirmation: Multi-step recharge confirmation
  • Payment Methods: Multiple payment option support

Component Architecture

🧩 Reusable Components

  • Navigation Bar: Custom navigation with dynamic titles
  • Behaviors: Shared functionality modules
    • accordionBehavior.js: Collapsible content management
    • modalBehavior.js: Modal dialog management
    • pageScrollBehavior.js: Scroll state management
    • paginationBehavior.js: Data pagination handling
    • tabBarBehavior.js: Tab navigation management

πŸ› οΈ Utility Systems

  • Access Control (accessControl.ts): Permission management
  • API Integration (api.ts): Centralized API communication
  • Configuration (config.ts): Environment-based configuration
  • User Info Manager (userInfoManager.ts): User session management
  • Monitoring (monitoring.ts): Performance and error tracking
  • Markdown Support (markdown.ts): Rich content rendering

βš™οΈ Backend Features

Core Infrastructure

πŸ”§ Service Architecture

  • Base Service Pattern: Standardized service inheritance
  • Instance Manager: Centralized service instance management
  • Transaction Manager: Database transaction coordination
  • Cache Manager: Multi-layer caching system
  • Graceful Shutdown: Proper resource cleanup

πŸ—„οΈ Database Management

  • Connection Pooling: Optimized MySQL connection management
  • Migration System: Version-controlled database schema updates
  • Transaction Safety: ACID-compliant operations
  • Query Optimization: Intelligent query caching and optimization

Authentication & Authorization

πŸ” Security Layer

  • JWT Authentication: Token-based authentication with refresh
  • WeChat OAuth: Official WeChat login integration
  • Role-based Access: Admin/user permission system
  • Ban Management: User restriction system with appeal process
  • Rate Limiting: API request throttling with role-based limits

πŸ›‘οΈ Middleware Stack

  • Auth Middleware: Request authentication validation
  • Ban Check Middleware: User status validation
  • Admin Middleware: Administrative access control
  • Parameter Validation: Input validation and sanitization

Rate Limiting & Performance

🚦 Lua-Based Role-Based Rate Limiting

  • OpenResty Integration: High-performance rate limiting using OpenResty (a custom branch of NGINX with built-in Lua scripting)
  • Role-Based Limits: Different rate limits for admin users vs regular users
  • Intelligent Admin Bypass: Automatic admin role detection and bypass for privileged operations
  • Request Classification: Automatic categorization of requests by sensitivity and operation type
  • Real-time Monitoring: Live rate limiting statistics and health checking
  • Granular Controls: Per-endpoint rate limiting with customizable thresholds

⚑ Performance Optimizations

  • Multi-tier Rate Limiting: Different limits for read, write, sensitive, and admin operations
  • Smart Caching Integration: Rate limiting works seamlessly with backend cache layers
  • Connection Pooling: Optimized upstream connections with load balancing
  • HTTP/2 Support: Modern protocol support for improved performance
  • Gzip Compression: Automatic response compression for bandwidth optimization

🎯 Endpoint-Specific Rate Limiting Zones

Administrative Routes (/admin)

  • Write Operations (POST, PUT, DELETE, PATCH): Strict sensitive limits with admin bypass
  • Read Operations (GET): Permissive admin_read limits for dashboard queries
  • Purpose: Protects administrative functions while allowing efficient admin workflows

Authentication & Security Routes (/auth, /reset, /password)

  • All Operations: Strict sensitive limits with admin bypass capability
  • Purpose: Prevents brute force attacks and credential stuffing attempts

Membership Routes (/memberships)

  • Purchase Operations (/purchase POST): Sensitive limits (financial operations)
  • Other Write Operations: Standard write limits
  • Read Operations: Standard read limits
  • Purpose: Protects financial transactions while allowing membership queries

User Membership Status (/my/membership)

  • All Operations: Read limits (frequently accessed due to 5-minute cache TTL)
  • Purpose: Handles high-frequency membership status checks from frontend

Booking & Batch Operations (/bookings, /batch)

  • Write Operations: Strict write limits (resource-intensive operations)
  • Read Operations: Standard read limits
  • Purpose: Manages high-concurrency booking operations and prevents system overload

Default API Routes (All other endpoints)

  • Write Operations: Standard write limits
  • Read Operations: Standard read limits
  • Purpose: Balanced protection for general API usage

πŸ”’ Enhanced Security & SSL/TLS Configuration

Security Headers

  • HSTS: Strict-Transport-Security with 2-year max-age, includeSubDomains, and preload
  • Frame Protection: X-Frame-Options set to DENY to prevent clickjacking
  • Content Type: X-Content-Type-Options set to nosniff to prevent MIME type confusion
  • XSS Protection: X-XSS-Protection enabled with blocking mode
  • Referrer Policy: strict-origin-when-cross-origin for privacy protection
  • Permissions Policy: Restricts geolocation, microphone, and camera access

SSL/TLS Security

  • Protocol Support: TLSv1.2 and TLSv1.3 only (deprecated protocols disabled)
  • Modern Ciphers: ECDHE ciphers with AES-GCM and ChaCha20-Poly1305 for forward secrecy
  • ECDH Curve: secp384r1 for enhanced elliptic curve cryptography
  • Session Management: 10-minute session timeout with shared cache, session tickets disabled
  • OCSP Stapling: Enabled with verification for certificate transparency
  • Buffer Optimization: 8k SSL buffer size for optimal performance

HTTP/HTTPS Configuration

  • Automatic Redirect: All HTTP traffic redirected to HTTPS (301 permanent redirect)
  • HTTP/2 Support: Enabled for improved performance and multiplexing
  • Server Tokens: Disabled to prevent server version disclosure

πŸ“Š Rate Limiting Monitoring & Health Checks

Health Check Endpoint (/health/rate-limit)

  • Purpose: Real-time health status of the rate limiting system
  • Access: Internal monitoring and alerting systems
  • Response: JSON status indicating system health and any issues
  • Logging: Access logging disabled to reduce monitoring noise

Statistics Endpoint (/stats/rate-limit)

  • Purpose: Live rate limiting statistics and metrics
  • Metrics Included: Request counts, rate limit hits, bypass counts, error rates
  • Access: Administrative monitoring and performance analysis
  • Response: Detailed JSON metrics for operational insights
  • Usage: Performance monitoring, capacity planning, troubleshooting

Internal Subrequest Endpoints

  • Role Check (/auth_role_check): Fast user role validation for rate limiting decisions
  • Admin Bypass (/auth_admin_bypass): Lua-based admin privilege verification
  • Purpose: Support high-performance rate limiting with minimal latency overhead

Operational Benefits

  • Real-time Monitoring: Immediate visibility into rate limiting effectiveness
  • Proactive Alerting: Early detection of rate limiting issues or attacks
  • Performance Metrics: Data-driven optimization of rate limiting thresholds
  • Troubleshooting: Detailed insights for diagnosing rate limiting problems

Business Logic Services

πŸ“… Booking Services

  • Booking Controller: Complete booking lifecycle management
  • Booking Status Service: Real-time status tracking
  • Booking Cleanup Service: Automated booking maintenance
  • Booking Cache Service: High-performance booking data caching
  • Booking Config Service: Dynamic booking rule management

🏠 Room Management

  • Room Controller: Room CRUD operations
  • Room Cache Service: Optimized room data caching
  • Layout Management: Dynamic seat layout configuration
  • Availability Engine: Real-time availability calculations

πŸ‘₯ User Management

  • User Service: User profile and preference management
  • User Cache Service: Optimized user data caching
  • User Session Cleanup: Automatic session maintenance
  • Tag Management: User categorization and automatic tagging

πŸ’° Financial Services

  • Payment Controller: WeChat Pay integration
  • Transaction Controller: Financial transaction management
  • Transaction Cleanup: Automated transaction maintenance
  • Recharge System: Balance management with payment processing

🎫 Coupon & Membership System

  • Coupon Management: Advanced coupon creation and validation
  • Coupon Cache Service: High-performance coupon caching
  • Coupon Cleanup Service: Automated coupon maintenance
  • Membership Service: Tier management and benefit calculation
  • Membership Purchase Service: Automated membership processing

Advanced Features

πŸ“Š Caching System

  • Multi-layer Caching: Application and database level caching
  • Cache Invalidation: Intelligent cache refresh strategies
  • Version Control: Cache version management for consistency
  • Group Caching: Related data bundling for performance
  • Selective Refresh: Targeted cache updates

πŸ“± WeChat Integration

  • WeChat Auth Service: OAuth flow management
  • WeChat Pay Service: Payment processing integration
  • WeChat JSSDK Service: Frontend SDK support
  • WeChat Notification Service: Push notification management
  • WeChat Access Token Service: Token lifecycle management

πŸ”§ System Services

  • Self-Service Controller: Service status management
  • System Controller: System health and configuration
  • Developer Controller: Development and debugging tools
  • Cache Controller: Manual cache management interface

πŸ› οΈ Technical Stack

Frontend Technologies

  • Framework: WeChat Mini Program Native
  • Languages: TypeScript, WXSS, WXML
  • Preprocessors: Less for styling
  • Build Tools: WeChat Developer Tools
  • UI Components: Native WeChat components
  • State Management: App-level state with behavior patterns

Backend Technologies

  • Runtime: Node.js 14+
  • Framework: Express.js
  • Database: MySQL 8.0+
  • Languages: JavaScript (ES6+)
  • Authentication: JWT + WeChat OAuth
  • Payment: WeChat Pay API
  • Logging: Morgan + Custom logging
  • Process Management: PM2 (production)

Development Tools

  • Version Control: Git
  • API Testing: Postman/Thunder Client
  • Database Tools: MySQL Workbench
  • IDE: VS Code with WeChat Developer Tools
  • Monitoring: Custom monitoring utilities

Infrastructure

  • Web Server: Express.js with Node.js runtime
  • Reverse Proxy: OpenResty (a custom branch of NGINX) with built-in Lua scripting support
  • Rate Limiting: Lua-based role-aware rate limiting with OpenResty (a custom branch of NGINX)
  • SSL/TLS: HTTPS with modern TLS configuration and OCSP stapling
  • Connection Pooling: MySQL2 connection pools with intelligent balancing
  • Caching: Multi-layer caching with Redis-style operations and intelligent invalidation
  • Load Balancing: Upstream connection pooling with health checks
  • Security: Enhanced security headers and comprehensive SSL/TLS hardening
  • Monitoring: Built-in rate limiting health checks and performance metrics

πŸ“ Project Structure

study-room-order/
β”œβ”€β”€ miniprogram-1/                    # WeChat Mini Program Frontend
β”‚   └── miniprogram/
β”‚       β”œβ”€β”€ pages/                    # Core Application Pages
β”‚       β”‚   β”œβ”€β”€ login/               # User authentication
β”‚       β”‚   β”œβ”€β”€ home/                # Main booking interface
β”‚       β”‚   β”œβ”€β”€ my-bookings/         # Booking management
β”‚       β”‚   β”œβ”€β”€ recharge/            # Wallet and membership
β”‚       β”‚   β”œβ”€β”€ room-detail/         # Room information
β”‚       β”‚   β”œβ”€β”€ seat-selection/      # Seat selection interface
β”‚       β”‚   β”œβ”€β”€ payment/             # Payment processing
β”‚       β”‚   β”œβ”€β”€ booking-detail/      # Booking details view
β”‚       β”‚   β”œβ”€β”€ contact-service/     # Customer support
β”‚       β”‚   β”œβ”€β”€ self-service/        # Self-service tools
β”‚       β”‚   β”œβ”€β”€ ban-info/            # Ban information display
β”‚       β”‚   β”œβ”€β”€ room-info/           # Additional room details
β”‚       β”‚   └── developer-settings/  # Development tools
β”‚       β”œβ”€β”€ packageAdmin/            # Administrative Interface
β”‚       β”‚   └── pages/
β”‚       β”‚       β”œβ”€β”€ admin-panel/     # Admin dashboard
β”‚       β”‚       β”œβ”€β”€ user-management/ # User administration
β”‚       β”‚       β”œβ”€β”€ room-management/ # Room administration
β”‚       β”‚       β”œβ”€β”€ batch-operations/ # Bulk operations
β”‚       β”‚       β”œβ”€β”€ coupon-management/ # Coupon administration
β”‚       β”‚       β”œβ”€β”€ tag-management/  # User tagging system
β”‚       β”‚       β”œβ”€β”€ param-management/ # System configuration
β”‚       β”‚       β”œβ”€β”€ refund-review/   # Financial dispute resolution
β”‚       β”‚       └── room-layout-edit/ # Room layout editor
β”‚       β”œβ”€β”€ packageAnnouncement/     # Announcement System
β”‚       β”‚   └── pages/
β”‚       β”‚       β”œβ”€β”€ announcement/    # Announcement display
β”‚       β”‚       β”œβ”€β”€ announcement-edit/ # Announcement editor
β”‚       β”‚       β”œβ”€β”€ announcement-management/ # Announcement admin
β”‚       β”‚       └── announcement-preview/ # Preview interface
β”‚       β”œβ”€β”€ packageRecharge/         # Enhanced Recharge Features
β”‚       β”‚   └── pages/
β”‚       β”‚       β”œβ”€β”€ coupons/         # Coupon selection
β”‚       β”‚       └── recharge-confirm/ # Payment confirmation
β”‚       β”œβ”€β”€ packageUtils/            # Utility Pages
β”‚       β”‚   └── pages/
β”‚       β”‚       β”œβ”€β”€ cancel-confirm/  # Cancellation confirmation
β”‚       β”‚       β”œβ”€β”€ qr-generator/    # QR code generation
β”‚       β”‚       └── scan-handler/    # QR code scanning
β”‚       β”œβ”€β”€ components/              # Reusable UI Components
β”‚       β”‚   └── navigation-bar/      # Custom navigation
β”‚       β”œβ”€β”€ behaviors/               # Shared Behaviors
β”‚       β”‚   β”œβ”€β”€ accordionBehavior.js # Accordion functionality
β”‚       β”‚   β”œβ”€β”€ modalBehavior.js     # Modal management
β”‚       β”‚   β”œβ”€β”€ pageScrollBehavior.js # Scroll handling
β”‚       β”‚   β”œβ”€β”€ paginationBehavior.js # Pagination logic
β”‚       β”‚   └── tabBarBehavior.js    # Tab navigation
β”‚       β”œβ”€β”€ utils/                   # Frontend Utilities
β”‚       β”‚   β”œβ”€β”€ api.ts               # API communication
β”‚       β”‚   β”œβ”€β”€ config.ts            # Configuration management
β”‚       β”‚   β”œβ”€β”€ userInfoManager.ts   # User session management
β”‚       β”‚   β”œβ”€β”€ accessControl.ts     # Permission management
β”‚       β”‚   β”œβ”€β”€ monitoring.ts        # Performance monitoring
β”‚       β”‚   └── [other utilities]    # Additional utility modules
β”‚       β”œβ”€β”€ images/                  # Static Image Assets
β”‚       β”œβ”€β”€ app.json                 # Mini Program configuration
β”‚       β”œβ”€β”€ app.ts                   # Application entry point
β”‚       └── app.wxss                 # Global styles
β”œβ”€β”€ mysql/                           # Backend API Server
β”‚   β”œβ”€β”€ api/                         # API Controllers
β”‚   β”‚   β”œβ”€β”€ authController.js        # Authentication endpoints
β”‚   β”‚   β”œβ”€β”€ bookingController.js     # Booking management
β”‚   β”‚   β”œβ”€β”€ roomController.js        # Room management
β”‚   β”‚   β”œβ”€β”€ paymentController.js     # Payment processing
β”‚   β”‚   β”œβ”€β”€ couponController.js      # Coupon management
β”‚   β”‚   β”œβ”€β”€ membershipController.js  # Membership management
β”‚   β”‚   β”œβ”€β”€ adminController.js       # Administrative functions
β”‚   β”‚   β”œβ”€β”€ selfServiceController.js # Self-service features
β”‚   β”‚   β”œβ”€β”€ systemController.js      # System management
β”‚   β”‚   β”œβ”€β”€ transactionController.js # Financial transactions
β”‚   β”‚   β”œβ”€β”€ tagController.js         # User tagging
β”‚   β”‚   β”œβ”€β”€ announcementController.js # Announcement system
β”‚   β”‚   β”œβ”€β”€ wechatJSSDKController.js # WeChat SDK integration
β”‚   β”‚   β”œβ”€β”€ middleware/              # Express Middleware
β”‚   β”‚   β”‚   β”œβ”€β”€ authMiddleware.js    # Authentication validation
β”‚   β”‚   β”‚   β”œβ”€β”€ adminMiddleware.js   # Admin access control
β”‚   β”‚   β”‚   └── banCheckMiddleware.js # User ban checking
β”‚   β”‚   └── routes.js                # API route definitions
β”‚   β”œβ”€β”€ services/                    # Business Logic Services
β”‚   β”‚   β”œβ”€β”€ baseService.js           # Base service class
β”‚   β”‚   β”œβ”€β”€ instanceManager.js       # Service instance management
β”‚   β”‚   β”œβ”€β”€ transactionManager.js    # Database transaction management
β”‚   β”‚   β”œβ”€β”€ cacheFetchService.js     # Cache data fetching
β”‚   β”‚   β”œβ”€β”€ cacheInvalidationService.js # Cache invalidation
β”‚   β”‚   β”œβ”€β”€ cacheManager.js          # Cache coordination
β”‚   β”‚   β”œβ”€β”€ bookingCacheService.js   # Booking data caching
β”‚   β”‚   β”œβ”€β”€ userCacheService.js      # User data caching
β”‚   β”‚   β”œβ”€β”€ roomCacheService.js      # Room data caching
β”‚   β”‚   β”œβ”€β”€ couponCacheService.js    # Coupon data caching
β”‚   β”‚   β”œβ”€β”€ membershipCacheService.js # Membership data caching
β”‚   β”‚   β”œβ”€β”€ bookingStatusService.js  # Booking status management
β”‚   β”‚   β”œβ”€β”€ membershipStatusService.js # Membership status tracking
β”‚   β”‚   β”œβ”€β”€ bookingCleanupService.js # Automated booking cleanup
β”‚   β”‚   β”œβ”€β”€ userSessionCleanupService.js # Session maintenance
β”‚   β”‚   β”œβ”€β”€ couponCleanupService.js  # Coupon maintenance
β”‚   β”‚   β”œβ”€β”€ transactionCleanupService.js # Transaction cleanup
β”‚   β”‚   β”œβ”€β”€ tagExpiryCleanupService.js # Tag maintenance
β”‚   β”‚   β”œβ”€β”€ wechatAuthService.js     # WeChat authentication
β”‚   β”‚   β”œβ”€β”€ wechatPayConfigService.js # WeChat Pay configuration
β”‚   β”‚   β”œβ”€β”€ wechatNotificationService.js # Push notifications
β”‚   β”‚   β”œβ”€β”€ wechatAccessTokenService.js # WeChat token management
β”‚   β”‚   β”œβ”€β”€ wechatJSSDKService.js    # WeChat JSSDK support
β”‚   β”‚   β”œβ”€β”€ sensitiveConfigService.js # Configuration management
β”‚   β”‚   └── [additional services]    # Other business services
β”‚   β”œβ”€β”€ database/                    # Database Management
β”‚   β”‚   β”œβ”€β”€ create_tables_simplified.sql # Database schema
β”‚   β”‚   β”œβ”€β”€ init_data_simplified.sql # Initial data
β”‚   β”‚   β”œβ”€β”€ sample_coupons.sql       # Sample coupon data
β”‚   β”‚   └── db.js                    # Database connection management
β”‚   β”œβ”€β”€ utils/                       # Backend Utilities
β”‚   β”‚   β”œβ”€β”€ apiResponseBuilder.js    # Standardized API responses
β”‚   β”‚   β”œβ”€β”€ timezoneUtil.js          # Timezone handling
β”‚   β”‚   β”œβ”€β”€ gracefulShutdown.js      # Process cleanup
β”‚   β”‚   └── db.js                    # Database utilities
β”‚   β”œβ”€β”€ config/                      # Configuration Files
β”‚   β”œβ”€β”€ server.js                    # Application entry point
β”‚   └── package.json                 # Node.js dependencies
β”œβ”€β”€ mysql-migrations/                # Database Migration Scripts
β”œβ”€β”€ docs/                           # Comprehensive Documentation
β”‚   β”œβ”€β”€ README.md                   # This file
β”‚   β”œβ”€β”€ cache-guide/                # Caching system documentation
β”‚   β”œβ”€β”€ error-handling-guide/       # Error handling patterns
β”‚   β”œβ”€β”€ service_layer/              # Service architecture guides
β”‚   β”œβ”€β”€ instanceManager/            # Instance management documentation
β”‚   └── [additional docs]           # Feature-specific documentation
β”œβ”€β”€ tests/                          # Test Suite
β”‚   β”œβ”€β”€ integration.test.ts         # Integration tests
β”‚   β”œβ”€β”€ performance.test.ts         # Performance tests
β”‚   β”œβ”€β”€ services/                   # Service-specific tests
β”‚   └── [test files]                # Unit and integration tests
β”œβ”€β”€ deprecated/                     # Legacy Code Archive
└── debug-logs-and-images/          # Development Debug Resources

πŸ“š API Documentation

Authentication Endpoints

POST /api/auth/wechat/login         # WeChat OAuth login
POST /api/auth/refresh              # Token refresh
GET  /api/user/info                 # User profile
PUT  /api/user/info                 # Update profile

Booking Management

GET  /api/bookings                  # User bookings
POST /api/bookings                  # Create booking
GET  /api/bookings/:id              # Booking details
PUT  /api/bookings/:id/cancel       # Cancel booking
POST /api/bookings/checkin          # Check-in
POST /api/bookings/checkout         # Check-out

Room Management

GET  /api/rooms                     # Room list
GET  /api/rooms/:id                 # Room details
GET  /api/rooms/:id/bookings        # Room bookings

Payment & Financial

POST /api/payment/recharge          # Create recharge order
GET  /api/payment/status/:orderId   # Check payment status
GET  /api/transactions              # Transaction history
GET  /api/transactions/stats        # Transaction statistics

Administrative APIs

GET  /api/admin/rooms               # Admin room management
POST /api/admin/rooms               # Create room
PUT  /api/admin/rooms/:id           # Update room
DELETE /api/admin/rooms/:id         # Delete room

Membership & Coupons

GET  /api/user/membership           # Membership status
POST /api/coupons/apply             # Apply coupon
GET  /api/coupons/user              # User coupons

πŸš€ Setup & Development

Prerequisites

Backend Requirements

  • Node.js: Version 14.0.0 or higher
  • MySQL: Version 8.0 or higher
  • OpenResty: Latest stable version (a custom branch of NGINX with Lua scripting) for production rate limiting
    • Alternative: Standard NGINX (rate limiting features will be disabled)
  • SSL Certificate: Valid SSL certificate for HTTPS deployment

Frontend Requirements

  • WeChat Developer Tools: Latest version
  • WeChat Mini Program Account: For testing and deployment

Production Infrastructure

  • OpenResty: Required for advanced rate limiting features (a custom branch of NGINX with built-in Lua scripting)
  • Process Manager: PM2 recommended for production deployment
  • SSL/TLS: Modern certificate with OCSP stapling support

Frontend Setup

  1. Install WeChat Developer Tools

    # Download from: https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
  2. Open Project in WeChat Developer Tools

    • Open WeChat Developer Tools
    • Select "Import Project"
    • Choose miniprogram-1/ directory
    • Configure AppID in project.config.json
  3. Configure Development Environment

    // utils/config.ts
    export const config = {
      apiBaseUrl: 'http://localhost:3000/api',
      environment: 'development'
    };

Backend Setup

  1. Install Dependencies

    cd mysql
    npm install
  2. Database Setup

    # Create database
    mysql -u root -p -e "CREATE DATABASE studyroom_booking;"
    
    # Import schema
    mysql -u root -p studyroom_booking < database/create_tables_simplified.sql
    
    # Import initial data
    mysql -u root -p studyroom_booking < database/init_data_simplified.sql
  3. Environment Configuration

    # Create configuration file
    cp config/config.example.js config/config.js
    
    # Edit database connection settings
    nano config/config.js
  4. Start Development Server

    npm run dev
    # Server will start on http://localhost:3000

Database Migrations

# Apply migrations in chronological order
mysql -u root -p studyroom_booking < mysql-migrations/[timestamp]_migration_name.sql

Testing

# Run integration tests
npm test

# Run specific test files
node tests/test_booking_fix.js
node tests/test_coupon_cleanup_fixed.js

🚒 Deployment

Production Backend Deployment

  1. Server Configuration

    # Install PM2 for process management
    npm install -g pm2
    
    # Start production server
    pm2 start server.js --name "studyroom-api"
  2. OpenResty Configuration with Rate Limiting

    The production environment uses OpenResty (a custom branch of NGINX with built-in Lua scripting support) for Lua-based role-based rate limiting:

    # /etc/nginx/sites-available/goldenlist-api (based on mysql/goldenlist.cn.conf)
    
    # HTTP to HTTPS redirect
    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        return 301 https://$host$request_uri;
    }
    
    # Main API server with advanced rate limiting
    server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name api.yourdomain.com;
        charset utf-8;
        server_tokens off;
        
        # Variables for Lua rate limiting and logging
        set $rate_limit_status "-";
        set $rate_limit_key "-";
        set $rate_limit_zone "-";
        set $user_id "-";
        set $user_role "-";
        set $loc_group "-";
        
        # Enhanced security headers
        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
        add_header X-Frame-Options "DENY" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-XSS-Protection "1; mode=block" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;
        add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
        
        # SSL/TLS Configuration
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305;
        ssl_prefer_server_ciphers on;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
        ssl_session_tickets off;
        ssl_stapling on;
        ssl_stapling_verify on;
        ssl_certificate /path/to/your/certificate.pem;
        ssl_certificate_key /path/to/your/private.key;
        
        # Gzip compression
        gzip on;
        gzip_vary on;
        gzip_min_length 1024;
        gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
        
        # Admin routes with granular rate limiting
        location ~ ^/admin {
            access_by_lua_block {
                local role_rate_limit = require "role_based_rate_limit"
                local method = ngx.var.request_method
                
                -- Admin write operations get strict sensitive limits
                if method == "POST" or method == "PUT" or method == "DELETE" or method == "PATCH" then
                    role_rate_limit.apply_sensitive()
                else
                    -- Admin read operations get more permissive admin_read limits
                    role_rate_limit.apply_admin_read()
                end
            }
            
            proxy_pass http://api_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            proxy_connect_timeout 10s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }
        
        # Sensitive routes with strict rate limiting
        location ~ ^/(auth|reset|password) {
            access_by_lua_block {
                local role_rate_limit = require "role_based_rate_limit"
                role_rate_limit.apply_sensitive()
            }
            
            proxy_pass http://api_backend;
            # [standard proxy headers and timeouts]
        }
        
        # Write-heavy routes with strict limits
        location ~ ^/(bookings|batch) {
            access_by_lua_block {
                local role_rate_limit = require "role_based_rate_limit"
                if ngx.var.request_method ~= "GET" then
                    role_rate_limit.apply_write_strict()
                else
                    role_rate_limit.apply_read()
                end
            }
            
            proxy_pass http://api_backend;
            # [standard proxy headers and timeouts]
        }
        
        # Default API with role-based rate limiting
        location / {
            access_by_lua_block {
                local role_rate_limit = require "role_based_rate_limit"
                if ngx.var.request_method ~= "GET" then
                    role_rate_limit.apply_write()
                else
                    role_rate_limit.apply_read()
                end
            }
            
            proxy_pass http://api_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            proxy_connect_timeout 10s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }
    }

    Note: The complete configuration with all location blocks is available in mysql/goldenlist.cn.conf

  3. Database Production Setup

    # Configure production database
    mysql -u root -p studyroom_booking_prod < database/create_tables_simplified.sql
    
    # Apply all migrations
    for migration in mysql-migrations/*.sql; do
      mysql -u root -p studyroom_booking_prod < "$migration"
    done

WeChat Mini Program Deployment

  1. Production Build

    • Set production API endpoint in utils/config.ts
    • Build project in WeChat Developer Tools
    • Upload for review through WeChat Developer Platform
  2. WeChat Configuration

    • Configure server domain in WeChat MP Admin Panel
    • Set up payment merchant configuration
    • Configure message templates for notifications

🀝 Contributing

Development Guidelines

  1. Code Standards

    • Follow TypeScript best practices for frontend
    • Use ESLint configuration for backend
    • Maintain consistent naming conventions
    • Write comprehensive JSDoc comments
  2. Feature Development

    • Create feature branches from main
    • Write tests for new functionality
    • Update documentation for API changes
    • Follow the existing service architecture patterns
  3. Database Changes

    • Create migration scripts for schema changes
    • Test migrations on sample data
    • Document breaking changes

Pull Request Process

  1. Create detailed PR description with feature summary
  2. Include test coverage for new features
  3. Update relevant documentation
  4. Ensure all tests pass
  5. Request review from maintainers

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


Built with ❀️ using WeChat Mini Program and Node.js

For questions, issues, or contributions, please refer to the comprehensive documentation in the /docs directory or open an issue on the project repository.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors