# Backend Quick Start Guide ## Initial Setup ### 1. Install Dependencies ```bash cd /home/ren/Documents/math2/backend npm install ``` ### 2. Configure Environment Variables ```bash cp .env.example .env nano .env # Edit with your configuration ``` **Required variables to update:** - `DATABASE_URL` - PostgreSQL connection string - `JWT_SECRET` - Generate a secure random string - `AI_API_KEY` - Your AI service API key - `TELEGRAM_BOT_TOKEN` - Your Telegram bot token (if using) ### 3. Generate Prisma Client ```bash npm run prisma:generate ``` ### 4. Create and Run Migrations ```bash # Create initial migration npm run prisma:migrate # Or reset database (WARNING: deletes all data) npm run prisma:reset ``` ### 5. Seed Database ```bash npm run prisma:seed ``` This will create: - 3 Modules (Fundamentos, Sistemas/Espacios, Aplicaciones) - 5 Topics (Vectores, Matrices, Sistemas, Espacios Vectoriales, Programación Lineal) - 18 Achievements/Badges - System configuration ### 6. Start Development Server ```bash npm run dev ``` The API will be available at `http://localhost:3001` ## Development Workflow ### Running the Server ```bash # Development with hot reload npm run dev # Production build npm run build npm start ``` ### Database Operations ```bash # Open Prisma Studio (GUI) npm run prisma:studio # Generate client after schema changes npm run prisma:generate # Create migration npm run prisma:migrate # Reset database npm run prisma:reset # Seed database npm run prisma:seed ``` ### Code Quality ```bash # Type checking npm run type-check # Linting npm run lint npm run lint:fix # Format code npm run format # Run tests npm test npm run test:watch npm run test:coverage ``` ## API Endpoints (Placeholder) Once routes are implemented: ### Health Check - `GET /health` - Server health status - `GET /api/health` - API health status ### Authentication - `POST /api/auth/register` - Register new user - `POST /api/auth/login` - Login - `GET /api/auth/me` - Get current user ### Modules - `GET /api/modules` - List all modules - `GET /api/modules/:id` - Get module details ### More endpoints to be implemented... ## Database Schema Overview ### Core Entities - **User** - User accounts - **Module** - 3 pedagogical modules - **Topic** - 5 mathematical topics - **Exercise** - Exercises with LaTeX - **ExerciseAttempt** - User attempts - **Progress** - Module progress - **Achievement** - 18 gamification badges - **UserAchievement** - Unlocked badges - **Ranking** - Leaderboards - **Notification** - Telegram notifications - **ProcessedPdf** - PDF processing metadata ### Key Features - Type-safe with Prisma + TypeScript - Indexed queries for performance - Cascade deletes for integrity - JSON fields for flexible content - Enum types for data validation ## Architecture ``` backend/ ├── prisma/ │ ├── schema.prisma # Database schema │ └── seed.ts # Database seeding ├── src/ │ ├── config/ # Configuration modules │ ├── modules/ # Feature modules (auth, exercise, etc.) │ ├── shared/ # Shared utilities │ │ ├── database/ # Prisma client │ │ ├── middleware/ # Express middleware │ │ ├── types/ # TypeScript types │ │ ├── utils/ # Utilities (logger, etc.) │ │ └── constants/ # Application constants │ ├── workers/ # Background workers │ └── server.ts # Main server └── [config files] ``` ## Troubleshooting ### Database Connection Issues 1. Check PostgreSQL is running: ```bash sudo systemctl status postgresql ``` 2. Test connection: ```bash psql -h localhost -U mathuser -d mathdb ``` 3. Check DATABASE_URL in .env ### Prisma Issues 1. Regenerate client: ```bash npm run prisma:generate ``` 2. Reset migrations: ```bash npm run prisma:reset ``` 3. Check schema: ```bash npm run prisma:studio ``` ### Port Already in Use ```bash # Find process using port 3001 lsof -i :3001 # Kill process kill -9 # Or change port in .env PORT=3002 ``` ### Redis Connection Issues 1. Check Redis is running: ```bash redis-cli ping ``` 2. Start Redis: ```bash sudo systemctl start redis ``` 3. Check connection settings in .env ## Next Steps 1. **Implement Routes** - Create controllers in `/src/modules/*/` - Implement business logic - Add validation schemas 2. **Create Workers** - PDF processing worker - Exercise generation worker - Notification worker 3. **Add Tests** - Unit tests - Integration tests - E2E tests 4. **Setup Docker** - Create Dockerfile - Configure docker-compose - Test container deployment ## Useful Commands ```bash # Check database health curl http://localhost:3001/health # View logs tail -f logs/combined.log tail -f logs/error.log # Database backup docker exec postgres pg_dump -U mathuser mathdb > backup.sql # Restore database docker exec -T postgres psql -U mathuser mathdb < backup.sql ``` ## Environment Variables Reference See `.env.example` for all available variables. Key variables: - `PORT` - Server port (default: 3001) - `DATABASE_URL` - PostgreSQL connection string - `REDIS_HOST` - Redis server host - `JWT_SECRET` - JWT signing secret - `AI_API_KEY` - AI service API key - `TELEGRAM_BOT_TOKEN` - Telegram bot token - `NODE_ENV` - Environment (development/production) ## Support For issues or questions: 1. Check logs in `logs/` directory 2. Review Prisma Studio: `npm run prisma:studio` 3. Check PostgreSQL and Redis are running 4. Verify environment variables ## Production Deployment Before deploying to production: 1. Update `NODE_ENV=production` 2. Generate secure `JWT_SECRET` 3. Configure production database 4. Setup Redis cluster 5. Enable HTTPS 6. Configure CORS properly 7. Setup monitoring and logging 8. Test all functionality --- **Status**: Backend foundation is complete and ready for route implementation! **Created files**: 14 core files **Database entities**: 13 **Enums**: 10 **Achievements**: 18 **Modules**: 3 **Topics**: 5