changemaker.lite/mkdocs/docs/v2/contributing/development-setup.md

597 lines
13 KiB
Markdown

# Development Setup
This guide will help you set up a complete development environment for contributing to Changemaker Lite V2.
## Prerequisites
Before beginning, ensure you have the following installed:
### Required Software
- **Node.js 20+** ([download](https://nodejs.org/))
```bash
node --version # Should be v20.x.x or higher
```
- **npm 10+** (comes with Node.js)
```bash
npm --version # Should be 10.x.x or higher
```
- **Docker Desktop** ([download](https://www.docker.com/products/docker-desktop))
```bash
docker --version # Should be 20.10.x or higher
docker compose version # Should be 2.0.x or higher
```
- **Git** ([download](https://git-scm.com/downloads))
```bash
git --version # Should be 2.x.x or higher
```
### Recommended Software
- **VSCode** ([download](https://code.visualstudio.com/)) - Recommended code editor
- **GitHub CLI** ([download](https://cli.github.com/)) - Simplifies GitHub operations
- **Postman** or **Thunder Client** - API testing (Thunder Client is VSCode extension)
### System Requirements
- **Operating System**: Linux, macOS, or Windows (with WSL2)
- **RAM**: 8GB minimum (16GB recommended)
- **Disk Space**: 20GB free space
- **Internet**: Required for npm packages and Docker images
## Fork and Clone
### 1. Fork the Repository
1. Visit [https://github.com/changemaker-lite/v2](https://github.com/changemaker-lite/v2)
2. Click **Fork** button (top right)
3. Select your GitHub account as the destination
### 2. Clone Your Fork
```bash
# Clone your fork (replace YOUR-USERNAME)
git clone https://github.com/YOUR-USERNAME/changemaker-lite.git
cd changemaker-lite
# Add upstream remote (original repository)
git remote add upstream https://github.com/changemaker-lite/v2.git
# Verify remotes
git remote -v
# Should show:
# origin https://github.com/YOUR-USERNAME/changemaker-lite.git (fetch)
# origin https://github.com/YOUR-USERNAME/changemaker-lite.git (push)
# upstream https://github.com/changemaker-lite/v2.git (fetch)
# upstream https://github.com/changemaker-lite/v2.git (push)
```
### 3. Checkout V2 Branch
```bash
# Switch to v2 branch
git checkout v2
# Verify you're on v2
git branch
# Should show: * v2
```
## Environment Setup
### 1. Create Environment File
```bash
# Copy example environment file
cp .env.example .env
# Edit .env with your preferred editor
nano .env # or: code .env (VSCode)
```
### 2. Configure Environment Variables
**Minimal development configuration**:
```bash
# Database
DATABASE_URL=postgresql://changemaker:devpassword@localhost:5433/changemaker_v2?schema=public
V2_POSTGRES_USER=changemaker
V2_POSTGRES_PASSWORD=devpassword
V2_POSTGRES_DB=changemaker_v2
# Redis
REDIS_URL=redis://:devpassword@localhost:6379
REDIS_PASSWORD=devpassword
# JWT Secrets (generate with: openssl rand -hex 32)
JWT_ACCESS_SECRET=your_access_secret_here_32_chars_min
JWT_REFRESH_SECRET=your_refresh_secret_here_32_chars_min
ENCRYPTION_KEY=your_encryption_key_here_32_chars_min
# API
API_PORT=4000
MEDIA_API_PORT=4100
NODE_ENV=development
# Email (test mode - uses MailHog)
EMAIL_TEST_MODE=true
SMTP_HOST=localhost
SMTP_PORT=1025
SMTP_FROM=dev@localhost
# Feature Flags
ENABLE_MEDIA_FEATURES=true
LISTMONK_SYNC_ENABLED=false
```
**Generate secrets**:
```bash
# Generate JWT secrets (run 3 times for each secret)
openssl rand -hex 32
# On Windows (PowerShell):
[Convert]::ToBase64String((1..32 | ForEach-Object { Get-Random -Minimum 0 -Maximum 256 }))
```
!!! warning "Security"
Use different secrets for JWT_ACCESS_SECRET, JWT_REFRESH_SECRET, and ENCRYPTION_KEY. Never commit .env to Git!
## Install Dependencies
### API Dependencies
```bash
cd api
# Install npm packages
npm install
# Verify installation
npm list prisma # Should show @prisma/client and prisma packages
```
### Admin Dependencies
```bash
cd ../admin
# Install npm packages
npm install
# Verify installation
npm list react # Should show react 19.x.x
```
## Database Setup
### Option 1: Docker (Recommended for Development)
Start PostgreSQL and Redis in Docker:
```bash
cd /home/bunker-admin/changemaker.lite
# Start database services
docker compose up -d v2-postgres redis
# Wait for PostgreSQL to be ready (about 10 seconds)
sleep 10
# Verify services running
docker compose ps
# Should show v2-postgres and redis as "running"
```
Run Prisma migrations:
```bash
cd api
# Run all migrations
npx prisma migrate deploy
# Seed initial data (admin user, settings, blocks)
npx prisma db seed
# Verify database
npx prisma studio
# Opens browser at http://localhost:5555
```
**Default admin credentials** (from seed):
- Email: `admin@example.com`
- Password: `Admin123!`
!!! warning "Change Default Password"
Change the default admin password immediately after first login in development.
### Option 2: Local PostgreSQL (Advanced)
If you have PostgreSQL 16 installed locally:
```bash
# Create database and user
psql -U postgres
CREATE USER changemaker WITH PASSWORD 'devpassword';
CREATE DATABASE changemaker_v2 OWNER changemaker;
\q
# Update .env DATABASE_URL
DATABASE_URL=postgresql://changemaker:devpassword@localhost:5432/changemaker_v2?schema=public
# Run migrations
cd api
npx prisma migrate deploy
npx prisma db seed
```
## Running Development Servers
### Method 1: Docker Compose (Full Stack)
Run all services in Docker:
```bash
# Start all services
docker compose up -d
# View logs
docker compose logs -f api admin
# Stop services
docker compose down
```
**Access points**:
- Admin: http://localhost:3000
- API: http://localhost:4000
- Media API: http://localhost:4100
- Prisma Studio: `cd api && npx prisma studio`
- MailHog: http://localhost:8025
### Method 2: Local Development (Hot Reload)
Run services locally for faster development:
**Terminal 1 - API**:
```bash
cd api
npm run dev
# Runs on http://localhost:4000
# Hot reload enabled (nodemon)
```
**Terminal 2 - Admin**:
```bash
cd admin
npm run dev
# Runs on http://localhost:3000
# Hot reload enabled (Vite HMR)
```
**Terminal 3 - Media API** (optional):
```bash
cd api
npm run dev:media
# Runs on http://localhost:4100
# Hot reload enabled (nodemon)
```
**Terminal 4 - Database** (Docker):
```bash
# Keep PostgreSQL and Redis running
docker compose up -d v2-postgres redis
```
!!! tip "Recommended Workflow"
Use Method 2 (local) for frontend/backend development (faster hot reload). Use Method 1 (Docker) for testing full stack integration.
## VSCode Setup
### Recommended Extensions
Install these VSCode extensions for better development experience:
```json
{
"recommendations": [
"dbaeumer.vscode-eslint", // ESLint
"esbenp.prettier-vscode", // Prettier
"prisma.prisma", // Prisma syntax
"bradlc.vscode-tailwindcss", // Tailwind (if using)
"ms-azuretools.vscode-docker", // Docker
"rangav.vscode-thunder-client", // API testing
"editorconfig.editorconfig", // EditorConfig
"streetsidesoftware.code-spell-checker" // Spell check
]
}
```
### Workspace Settings
Create `.vscode/settings.json`:
```json
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/node_modules": true,
"**/dist": true
}
}
```
### Debug Configuration
Create `.vscode/launch.json` for debugging:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "API (Node)",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "dev"],
"cwd": "${workspaceFolder}/api",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"]
},
{
"name": "Admin (Chrome)",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/admin/src",
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
}
}
]
}
```
## Making Changes
### 1. Create Feature Branch
```bash
# Fetch latest changes
git fetch upstream
git checkout v2
git merge upstream/v2
# Create feature branch
git checkout -b feature/your-feature-name
# Or for bug fix
git checkout -b fix/bug-description
```
### 2. Code Style
Follow project conventions:
**Run linter**:
```bash
cd api && npm run lint # Backend
cd admin && npm run lint # Frontend
```
**Auto-fix**:
```bash
cd api && npm run lint:fix # Backend
cd admin && npm run lint:fix # Frontend
```
**Format code**:
```bash
cd api && npm run format # Backend
cd admin && npm run format # Frontend
```
**Type check**:
```bash
cd api && npx tsc --noEmit # Backend
cd admin && npx tsc --noEmit # Frontend
```
### 3. Run Tests
```bash
# API unit tests
cd api && npm test
# API integration tests
cd api && npm run test:integration
# Frontend tests
cd admin && npm test
# End-to-end tests
npm run test:e2e
```
### 4. Test Your Changes
**Manual testing checklist**:
- [ ] API endpoints work (use Postman/Thunder Client)
- [ ] Frontend renders correctly
- [ ] No console errors
- [ ] Works in Chrome, Firefox, Safari
- [ ] Responsive design (mobile, tablet, desktop)
- [ ] Accessibility (keyboard navigation, screen reader)
- [ ] Error handling (try invalid inputs)
- [ ] Loading states (try slow network)
**Integration testing**:
```bash
# Start full stack
docker compose up -d
# Run integration tests
./scripts/test-integration.sh
# Check logs for errors
docker compose logs -f
```
## Staying Synced with Upstream
Regularly sync your fork with the upstream repository:
```bash
# Fetch upstream changes
git fetch upstream
# Merge into your local v2 branch
git checkout v2
git merge upstream/v2
# Push to your fork
git push origin v2
# Rebase your feature branch (optional, cleaner history)
git checkout feature/your-feature-name
git rebase v2
```
!!! tip "Rebase vs Merge"
Use `git rebase v2` for cleaner commit history. Use `git merge v2` if you're unsure about rebasing.
## Troubleshooting
### Port Conflicts
**Error**: `Port 3000 already in use`
**Solution**:
```bash
# Find process using port
lsof -i :3000 # macOS/Linux
netstat -ano | findstr :3000 # Windows
# Kill process or change port
# Edit .env: ADMIN_PORT=3001
```
### Database Connection Errors
**Error**: `Can't reach database server at localhost:5433`
**Solution**:
```bash
# Check if PostgreSQL is running
docker compose ps v2-postgres
# Restart PostgreSQL
docker compose restart v2-postgres
# Check logs
docker compose logs v2-postgres
# Verify DATABASE_URL in .env
```
### Migration Errors
**Error**: `Migration failed`
**Solution**:
```bash
# Reset database (WARNING: deletes all data)
cd api
npx prisma migrate reset
# Or manually drop and recreate
docker compose exec v2-postgres psql -U changemaker -d postgres -c "DROP DATABASE changemaker_v2;"
docker compose exec v2-postgres psql -U changemaker -d postgres -c "CREATE DATABASE changemaker_v2 OWNER changemaker;"
npx prisma migrate deploy
npx prisma db seed
```
### Dependency Installation Errors
**Error**: `npm install` fails
**Solution**:
```bash
# Clear npm cache
npm cache clean --force
# Remove node_modules and package-lock.json
rm -rf node_modules package-lock.json
# Reinstall
npm install
# If still fails, try older Node version
nvm install 20.11.0
nvm use 20.11.0
npm install
```
### Docker Issues
**Error**: Docker daemon not running
**Solution**:
- **macOS/Windows**: Start Docker Desktop
- **Linux**: `sudo systemctl start docker`
**Error**: Permission denied (Docker)
**Solution** (Linux):
```bash
# Add user to docker group
sudo usermod -aG docker $USER
# Log out and back in, or:
newgrp docker
```
## Next Steps
Now that your environment is set up:
1. **[Find an issue](https://github.com/changemaker-lite/v2/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)** to work on
2. **[Review code style guidelines](../contributing/index.md#development-guidelines)**
3. **[Create your first PR](pull-requests.md)**
4. **[Join the community](../contributing/index.md#communication-channels)**
## Related Documentation
- [Contributing Guide](index.md) - Contribution overview
- [Pull Request Guidelines](pull-requests.md) - PR process
- [Code of Conduct](code-of-conduct.md) - Community standards
- [Architecture](../architecture/index.md) - System design
## Getting Help
Stuck on setup? Ask for help:
- **GitHub Discussions**: [Ask a question](https://github.com/changemaker-lite/v2/discussions)
- **Discord**: [Join our server](https://discord.gg/changemaker-lite)
- **Email**: dev@cmlite.org
Happy coding! 🚀