Developer Guide
Comprehensive technical documentation for the JGPNR System.
Table of Contents
1. Introduction to the System
The JGPNR system is a high-performance, monolithic application designed for managing ticket sales, user sessions, and customer relationships for a gaming/event arena. It follows a rigorous minimalist design philosophy, prioritizing speed, clean code, and zero-downtime reliability.
Core Goals
- Reliability: Robust handling of payments and ticket states.
- Performance: Lightweight frontends using Vite and optimized Backend.
- Maintainability: Strongly typed (TypeScript) codebase with shared conventions.
2. Technology Stack Overview
Frontend (Customer App) Libraries
| Library | Purpose |
|---|---|
| React 19 + Vite 7 | Core UI framework with fast HMR build tool |
| React Router 7 | Client-side routing and navigation |
| TailwindCSS 4 | Utility-first CSS framework |
| GSAP 3 | High-performance animations (ScrollTrigger, page transitions) |
| Axios | HTTP client for API requests with interceptors |
| react-hook-form + Yup | Form handling and schema validation |
| react-helmet-async | SEO meta tags and document head management |
| date-fns | Date formatting and manipulation |
| lucide-react | Icon library (Feather-based) |
Admin Panel Libraries
| Library | Purpose |
|---|---|
| React 19 + TypeScript 5 | Type-safe UI development |
| TailAdmin Template | Admin dashboard base template |
| React Query 5 (TanStack) | Server state management, caching, refetching |
| Socket.IO Client 4 | Real-time WebSocket notifications |
| FullCalendar 6 | Session calendar and task scheduling |
| TipTap 3 | Rich text editor for emails and content |
| ApexCharts 4 | Dashboard analytics charts |
| @zxing/library | QR code scanner for ticket validation |
| react-dropzone | File uploads (images, documents) |
Backend Libraries
| Library | Purpose |
|---|---|
| Node.js 18+ / TypeScript 5 | Runtime with type safety |
| Express 5 | REST API framework with async middleware |
| Prisma 6 | Type-safe ORM, migrations, schema management |
| PostgreSQL 14+ | Primary relational database |
| Redis + BullMQ 4 | Caching, rate limiting, background job queues |
| Socket.IO 4 | Real-time WebSocket notifications |
| Nodemailer 6 | SMTP email sending |
| jsonwebtoken + bcrypt | JWT auth and password hashing |
| Zod 3 | Runtime schema validation |
| Helmet 7 | HTTP security headers |
| express-rate-limit | API rate limiting with Redis store |
| Winston 3 | Structured logging |
| Sentry 7 | Error tracking and monitoring |
| qrcode | QR code generation for tickets |
| PDFKit | PDF generation for receipts |
| Multer + Sharp | File uploads and image processing |
Infrastructure
| Tool | Purpose |
|---|---|
| Nginx | Reverse proxy, SSL termination, static file serving |
| PM2 | Process manager with clustering and auto-restart |
| Docker Compose | Container orchestration for local development |
3. Frontend Architecture (Customer App)
Located in /my-app.
Directory Structure
/src
├── assets/ # Static assets (images, fonts)
├── components/ # Reusable UI components (Buttons, Inputs)
├── context/ # React Context (CartContext, AuthContext)
├── pages/ # Route components (Home, Checkout, Login)
├── hooks/ # Custom React Hooks
└── utils/ # Helper functions (Currency formatting, dates)
Key Patterns
- Context API: Used for global state like
CartContext(managing the shopping cart across pages) andAuthContext. - GSAP Animations: Used for high-performance, complex animations (Hero sections, interactions).
- Responsive Mobile-First: All components built with Tailwind's mobile-first breakpoints.
4. Admin Panel Architecture
Located in /admin. Designed for data density and quick actions.
UI Philosophy
- Dashboard First: Immediate view of key metrics (Sales, Active Sessions, Ticket Counts).
- Data Tables: High-density tables with filtering, sorting, and pagination for Orders and Customers.
- Forms: Uses
react-hook-formwithyupvalidation for robust input handling (e.g., Creating Sessions, Editing Users).
Scanner Module
The Admin panel includes a dedicated Ticket Scanner module
(/pages/Scanner/TicketScanner.tsx) that interfaces with the Backend API to validate tickets
in real-time. It handles:
- QR Code input/decoding.
- Real-time validation against
TicketStatus. - Preventing double-use or specific day restriction violations.
5. Backend / API Architecture
Located in /backend. The core business logic layer.
Layered Architecture
Key Modules
- Modules/Auth: Handles Login, Registration, Password Reset, and Token Management.
- Modules/Order: Manages Cart checkout, Payment Intent creation, and Order Fulfillment.
- Modules/Ticket: Generates unique ticket codes, handles Validation logic, and transfers.
- Jobs/: Background tasks defined here (Reminder Jobs, Expiry Jobs).
6. Database & Data Modeling
The data model (Prisma Schema) is complex and interconnected.
Key Entities
- User: Admin/Staff users with RBAC (Super Admin, Admin, Staff).
- Customer: End-users purchasing tickets. Tracking total spent, order history.
- Order: Central entity linking Customers to Tickets and Payments.
- Ticket: The core product. Contains
ticketCode,status(ACTIVE, SCANNED), and validity dates. - Campaigns & Subscribers: Email marketing system built directly into the database.
7. Authentication & Authorization
Authentication Flow
Uses JWT (JSON Web Tokens) for stateless authentication.
- Access Token: Short-lived, used for API requests.
- Refresh Token: Secure HTTP-only cookie used to obtain new access tokens.
- Blacklist:
BlacklistedTokentable prevents usage of compromised or logged-out tokens.
RBAC (Role-Based Access Control)
Middleware allowRoles('SUPER_ADMIN', 'ADMIN') protects sensitive routes.
CSRF Protection
Implemented via csurf with stateless double-submit cookie pattern.
- Middleware:
autoCSRFProtectionautomatically enforces checks on state-changing methods (POST, PUT, DELETE). - Exemptions: Public endpoints (e.g., Webhooks, Login, Cart) are explicitly whitelisted.
- Cookie: HTTP-Only, Secure, `SameSite=Strict`.
8. Payments & Financial Flows
Integrated Gateways
- Paystack: Primary gateway for Nigerian markets.
- Flutterwave: Secondary/Backup support.
Payment Flow
- Initiation: User checks out -> Backend creates pending Order -> Returns Gateway URL.
- Processing: User pays on Gateway.
- Webhook: Gateway calls
/api/webhooks-> Backend verifies signature -> Updates Order toPAID-> Generates Tickets.
Manual Payments: Supported via File Upload (Proof of Payment). Admins manually review and approve usually via the Admin Panel, which triggers the same "Order Paid" logic.
9. Notifications System
Architecture
Notifications are decoupled from the request cycle using BullMQ.
- Trigger: Event occurs (e.g.
OrderCreated). - Queue: Metadata added to
email-queuein Redis. - Worker: Separate process picks up job, compiles HTML from
/templates, and sends via Nodemailer (SMTP).
10. Analytics & Reporting
Real-Time Aggregation
Analytics are calculated in real-time via AnalyticsService using Prisma Aggregates.
- Dashboard: Fetches consolidated metrics (Revenue, Active Tickets, Scan Success Rate).
- Trends: Revenue grouped by Day/Week/Month.
- Export: Data can be exported to CSV using `json2csv` for:
- Orders (Financial reconciliation)
- Tickets (Validity checks)
- Customers (CRM data)
- Scans (Security audit)
11. Performance & Security
Performance
- Caching: Redis used to cache heavy Analytics queries (
AnalyticsCachemodel). - Indexing: Heavy use of
@@indexon foreign keys and frequently searched fields (email, status, dates) in PostgreSQL. - Lazy Loading: React routes loaded lazily to reduce initial bundle size.
Security Checklist
- Helmet: HTTP Header security.
- Rate Limiting:
express-rate-limiton Auth routes to prevent brute force. - Input Validation:
YupandZodused to strictly validate all incoming API payloads.
12. Developer Workflow
Setup & Run
# Backend
cd backend
cp .env.example .env
npm install
npx prisma generate
npm run dev
# Frontend
cd my-app
npm install
npm run dev
# Admin
cd admin
npm install
npm run dev
Testing
Standard testing command in Backend:
npm run test # Unit tests
npm run test:e2e # Integration tests
13. Deployment
Build Commands
# Backend
cd backend && npm run build
# Frontend
cd my-app && npm run build
# Admin
cd admin && npm run build
PM2 Configuration
# Start services
pm2 start ecosystem.config.js
# Restart after deploy
pm2 reload all
14. Environment Variables
| Variable | Required | Description |
|---|---|---|
| DATABASE_URL | Yes | PostgreSQL connection string |
| REDIS_URL | Yes | Redis connection string |
| JWT_SECRET | Yes | Secret for JWT signing |
| PAYSTACK_SECRET | Yes | Paystack API secret key |
| SMTP_HOST | Yes | Email server host |
15. Change-Impact Mapping
Use this guide to identify all files that need modification when changing a feature.
Modifying Ticket Settings
| Layer | Files to Modify |
|---|---|
| Database | prisma/schema.prisma (TicketSettings model) |
| Backend | modules/tickets/ticket.service.ts, ticket.schema.ts |
| Admin | pages/Settings/TicketSettings.tsx |
| Frontend | components/TicketBookingWidget.jsx |
Modifying Email Templates
| Layer | Files to Modify |
|---|---|
| Templates | modules/email/templates/*.ts |
| Backend | modules/email/email.service.ts |
| Jobs | jobs/expiryReminder.jobs.ts |
16. Background Jobs
| Job | Schedule | Purpose |
|---|---|---|
| Session Reminders | Hourly | Send 24h/2h reminders |
| Expiry Reminders | Daily (9 AM) | Send 7/3/1 day warnings |
| Ticket Expiry | Daily (midnight) | Mark expired tickets |
| Analytics Update | Every 15 min | Refresh dashboard cache |