# Developer Onboarding Guide

Chào mừng đến với **GoodGo Platform** — một sàn giao dịch bất động sản Việt Nam được xây dựng trên NestJS, Next.js, PostgreSQL, và PostGIS.

Hướng dẫn này giúp bạn setup môi trường phát triển trong **< 30 phút**.

---

## Prerequisites (Yêu cầu)

Trước khi bắt đầu, hãy cài đặt:

| Tool | Version | Link |
|------|---------|------|
| **Node.js** | ≥ 22.0.0 | https://nodejs.org/ |
| **pnpm** | ≥ 10.0.0 | https://pnpm.io/ |
| **PostgreSQL** | 16 + PostGIS | https://www.postgresql.org/ |
| **Docker & Docker Compose** | Latest | https://docker.com/ |
| **Git** | Latest | https://git-scm.com/ |
| **VS Code** (recommended) | Latest | https://code.visualstudio.com/ |

### macOS

```bash
# Install Homebrew (if not already)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install dependencies
brew install node@22 pnpm postgresql@16 docker
brew install postgis  # PostGIS extension

# Verify
node --version     # v22.x.x
pnpm --version     # 10.x.x
psql --version     # PostgreSQL 16.x
```

### Ubuntu/Debian

```bash
# Update package manager
sudo apt update

# Install Node.js 22
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install -y nodejs

# Install pnpm
npm install -g pnpm@latest

# Install PostgreSQL 16 + PostGIS
sudo apt install -y postgresql-16 postgresql-16-postgis

# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
```

### Windows (WSL2 Recommended)

```bash
# Inside WSL2 Ubuntu:
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install -y nodejs postgresql-16 postgresql-16-postgis
npm install -g pnpm@latest
```

---

## 1. Clone Repository

```bash
# Clone the repo
git clone https://github.com/hongochai10/goodgo-bds-platform-ai.git
cd goodgo-platform-ai

# Add your SSH key to GitHub (for faster clone/push)
# https://docs.github.com/en/authentication/connecting-to-github-with-ssh
```

---

## 2. Install Dependencies

```bash
# Install all packages using pnpm workspaces
pnpm install

# This installs:
# - Root dependencies
# - apps/api dependencies
# - apps/web dependencies
# - libs/ai-services dependencies
# - libs/mcp-servers dependencies
```

**Expected time:** ~2-5 minutes

---

## 3. Setup PostgreSQL (Database)

### Option A: Docker Compose (Recommended for Development)

```bash
# Start PostgreSQL + Redis in Docker
docker-compose -f docker-compose.dev.yml up -d

# Verify containers are running
docker-compose ps

# Output should show:
# NAME              STATUS
# goodgo-postgres   Up 2 seconds
# goodgo-redis      Up 2 seconds
```

### Option B: Local PostgreSQL Installation

```bash
# Create database
createdb goodgo_dev

# Enable PostGIS extension
psql goodgo_dev -c "CREATE EXTENSION IF NOT EXISTS postgis;"

# Verify
psql goodgo_dev -c "SELECT PostGIS_version();"
```

---

## 4. Setup Environment Variables

```bash
# Copy .env.example to .env
cp .env.example .env

# Edit .env with your local values
# Minimal required variables:
cat > .env << 'EOF'
NODE_ENV=development
DATABASE_URL="postgresql://postgres:password@localhost:5432/goodgo_dev"
REDIS_URL="redis://localhost:6379"
JWT_SECRET="dev-secret-change-in-production"
JWT_REFRESH_SECRET="dev-refresh-secret-change-in-production"
MAPBOX_TOKEN="your-mapbox-token-here"  # Get from https://account.mapbox.com/
EOF

# For Firebase Cloud Messaging (optional, for push notifications):
# FIREBASE_PROJECT_ID="your-project-id"
# FIREBASE_PRIVATE_KEY="..."
# FIREBASE_CLIENT_EMAIL="..."
```

---

## 5. Initialize Database

```bash
# Generate Prisma client
pnpm db:generate

# Run migrations
pnpm db:migrate:dev

# Seed sample data (users, listings, districts)
pnpm db:seed

# Verify seeding
pnpm db:studio  # Opens Prisma Studio GUI at http://localhost:5555
```

---

## 6. Start Development Servers

```bash
# Start all services (API + Web + AI services) in watch mode
pnpm dev

# Output shows:
# - API running at http://localhost:3001
# - Web running at http://localhost:3000
# - Logs from both services
```

**Expected time:** ~30 seconds for startup

### Alternative: Start Individual Services

```bash
# Terminal 1: API only
pnpm --filter api dev

# Terminal 2: Web only  
pnpm --filter web dev

# Terminal 3: AI services (Python) - optional
pnpm --filter ai-services dev
```

---

## 7. Verify Setup

Open your browser and test:

### API Health Check

```bash
# Terminal or Postman
curl http://localhost:3001/health

# Should return:
# {
#   "status": "ok",
#   "timestamp": "2026-04-22T10:30:00Z"
# }
```

### Web App

Open http://localhost:3000 in your browser

- You should see the GoodGo home page
- Try registering an account (test phone: `0987654321`, any password)

### API Swagger Docs

Open http://localhost:3001/api/docs

- Interactive API documentation
- Try endpoints: GET `/api/v1/listings`, POST `/api/v1/auth/login`, etc.

---

## Key Commands

| Command | Purpose |
|---------|---------|
| `pnpm install` | Install all dependencies |
| `pnpm dev` | Start all services in watch mode |
| `pnpm lint` | Run ESLint (check code style) |
| `pnpm lint --fix` | Auto-fix lint issues |
| `pnpm typecheck` | TypeScript type checking |
| `pnpm test` | Run unit tests |
| `pnpm test:e2e` | Run E2E tests with Playwright |
| `pnpm build` | Production build |
| `pnpm db:generate` | Generate Prisma client |
| `pnpm db:migrate:dev` | Run pending migrations |
| `pnpm db:seed` | Seed sample data |
| `pnpm db:studio` | Open Prisma Studio GUI |

---

## Project Structure

```
goodgo-platform-ai/
├── apps/
│   ├── api/                    # NestJS backend
│   │   ├── src/
│   │   │   ├── main.ts         # Entry point
│   │   │   └── modules/        # Domain modules
│   │   │       ├── auth/
│   │   │       ├── listings/
│   │   │       ├── payments/
│   │   │       └── ...
│   │   └── package.json
│   └── web/                    # Next.js frontend
│       ├── src/
│       │   ├── app/            # App Router pages
│       │   ├── components/
│       │   ├── lib/
│       │   └── hooks/
│       └── package.json
├── libs/
│   ├── ai-services/            # Python FastAPI (AVM, moderation)
│   └── mcp-servers/            # MCP server library
├── prisma/
│   ├── schema.prisma           # Database schema
│   └── migrations/             # SQL migrations
├── docs/                       # Documentation
├── .github/workflows/          # CI/CD
└── package.json (root)         # pnpm workspaces config
```

---

## Development Workflow

### 1. Create a Feature Branch

```bash
# Always create a feature branch from main/master
git checkout -b feature/awesome-feature

# Branch naming convention:
# - feature/new-feature-name
# - fix/bug-description
# - refactor/code-cleanup
# - docs/documentation-update
```

### 2. Make Changes

```bash
# Install dependencies for new package
pnpm install

# Run type checking + linting
pnpm typecheck
pnpm lint

# Run tests for your changes
pnpm test -- path/to/module

# Fix auto-fixable issues
pnpm lint --fix
```

### 3. Commit & Push

```bash
# Commit following conventional commits format
git add .
git commit -m "feat(module): short description"

# Commit message format:
# feat(scope): description
# fix(scope): description
# docs(scope): description
# refactor(scope): description
# test(scope): description
# chore(scope): description

# Push branch
git push origin feature/awesome-feature
```

### 4. Create Pull Request

- Go to GitHub: https://github.com/hongochai10/goodgo-bds-platform-ai/pulls
- Click **New Pull Request**
- Select your branch
- Add description (what changed, why, testing notes)
- Ensure all checks pass ✅ (lint, typecheck, test, build)
- Request review from team lead
- Merge after approval

---

## Debugging Tips

### API Debugging

```bash
# Enable debug logging
DEBUG=*:* pnpm --filter api dev

# Or in VS Code: use `.vscode/launch.json` for breakpoints
# F5 to start debugger
```

### Web Debugging

```bash
# Chrome DevTools: F12
# React DevTools extension: https://chrome.google.com/webstore/

# Debug Next.js:
# .next/server/pages shows compiled route handlers
```

### Database Debugging

```bash
# Connect to database directly
psql $DATABASE_URL

# Common queries:
SELECT * FROM "User" LIMIT 5;
SELECT COUNT(*) FROM "Listing";
SELECT * FROM "Listing" WHERE "status" = 'ACTIVE' LIMIT 5;
```

### Redis Debugging

```bash
# Connect to Redis CLI
redis-cli

# Check keys
KEYS *
GET session:user:123
INCR counter
```

---

## VS Code Setup (Optional)

### Recommended Extensions

```json
// .vscode/extensions.json
{
  "recommendations": [
    "esbenp.prettier-vscode",          // Code formatter
    "dbaeumer.vscode-eslint",          // ESLint linting
    "ms-vscode.makefile-tools",        // Makefile support
    "ms-vscode.extension-pack-fe",     // Frontend bundle
    "ms-vscode-remote.remote-containers", // Docker support
    "bradlc.vscode-tailwindcss",       // Tailwind CSS support
    "vivaxy.vscode-conventional-commits", // Commit helper
    "Prisma.prisma"                    // Prisma schema support
  ]
}
```

### Launch Configuration (Debugging)

Create `.vscode/launch.json`:

```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "NestJS Debug",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/@nestjs/cli/bin/nest.js",
      "args": ["start", "--debug", "--watch"],
      "cwd": "${workspaceFolder}/apps/api",
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}
```

---

## Troubleshooting

### Problem: `pnpm install` hangs

**Solution:**
```bash
rm -rf node_modules .pnpm-store pnpm-lock.yaml
pnpm install --no-frozen-lockfile
```

### Problem: PostgreSQL connection refused

**Solution:**
```bash
# Check if PostgreSQL is running
docker-compose ps

# If not running, start it
docker-compose -f docker-compose.dev.yml up -d

# Or check local PostgreSQL
pg_isready -h localhost -p 5432
```

### Problem: `pnpm dev` fails with "EADDRINUSE"

**Solution:**
```bash
# Port 3000 or 3001 is already in use
# Kill existing process
lsof -i :3000  # Find process ID
kill -9 <PID>

# Or use different port
PORT=3002 pnpm --filter web dev
```

### Problem: TypeScript errors in IDE but tests pass

**Solution:**
```bash
# Regenerate Prisma types
pnpm db:generate

# Restart VS Code
Cmd+Shift+P → "Developer: Reload Window"
```

---

## Getting Help

- **Slack:** `#dev` channel (if you have access)
- **GitHub Issues:** https://github.com/hongochai10/goodgo-bds-platform-ai/issues
- **Documentation:** `/docs` folder
- **Architecture:** `/docs/architecture.md`
- **API Reference:** `/docs/api-endpoints.md`

---

## Next Steps

1. ✅ **Setup complete?** Start with a small bug fix or feature
2. 📖 **Read Architecture:** `/docs/architecture.md` (understand module structure)
3. 🏗️ **Understand CQRS:** `/docs/QUICK_REFERENCE.md` (command/query handlers)
4. 🧪 **Write Tests:** Follow patterns in existing `.spec.ts` files
5. 📝 **Update Docs:** When adding features, update relevant docs

---

**Welcome to GoodGo! Happy coding! 🚀**
