# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

订单自动兑换系统 (Order Auto-Redemption System). 接收电商平台的 webhook 订单，通过 Playwright 浏览器自动化完成腾讯/QQ 等平台的兑换码兑换，生成用户领取链接。

## Architecture

**Monorepo**: `apps/backend` + `apps/frontend` + `deploy/`

### Backend (`apps/backend/`)
- **Stack**: Node.js (ESM), Express 5, PostgreSQL (pg), Playwright 1.42.1, Python OCR worker (ddddocr)
- **Entry**: `src/index.js` — Express app bootstrap with health checks and graceful shutdown
- **Layering**: `routes/` → `services/` → `repositories/` → `db/client.js` (pg Pool singleton)
- **Config**: `config/default.cjs` as base, `.env` overrides parsed in `src/config/runtime.js`. No dotenv library — custom env file parser.
- **DB migrations**: `src/db/migrations/` — SQL files run automatically on startup via `src/db/migrate.js` (tracks applied migrations in `schema_migrations` table)
- **Types**: Gradual TypeScript migration in progress. `tsconfig.json` with `allowJs: true, checkJs: false, strict: false` — JSDoc type annotations on selected files, types defined in `src/types/`
- **Test runner**: Node.js built-in `node --test`

**Key service domains**:
- `services/session/` — Playwright browser session management (login, redeem, screenshots), the core automation engine
- `services/claim/` — Claim token generation and user-facing claim page API
- `services/admin/` — Admin panel CRUD (split into read/write helpers, auth, dashboard, etc.)
- `services/order/` — Webhook processing, order/inventory management, Agiso platform integration
- `services/platforms/` — Third-party platform adapters (currently Agiso for 闲鱼/Xianyu)
- `subservices/ocr-worker/` — Python (uv) microservice for CAPTCHA OCR, invoked via subprocess

**Runtime data** (`data/` dir, mounted in Docker dev): logs, browser session artifacts, screenshots, `order-fulfillment-bindings.json`

### Frontend (`apps/frontend/`)
- **Stack**: Vue 3, Vite 8, Element Plus, vue-router (hash mode), TypeScript
- **Routes**: `/tx/browser` (browser session control), `/claim/:token` (user claim page), `/admin/*` (admin panel with role-based guards)
- **Auto-imports**: `unplugin-auto-import` + `unplugin-vue-components` for Element Plus

### Deployment (`deploy/`)
- Docker Compose: `docker-compose.yml` (production), `docker-compose.dev.yml` (hot-reload dev)
- Caddy reverse proxy: `/api/v1/*` → backend, `/*` → frontend
- Production Dockerfiles use Chinese mirrors (Tencent Cloud) for apt/npm/pip

## Common Commands

### Local Development (without Docker)
```bash
# Backend
cp .env.development.example .env
cd apps/backend
npm install
npm run dev                  # node --watch restart on src/ changes

# Frontend
cd apps/frontend
npm install
npm run dev                 # Vite dev server

# OCR worker (Python)
cd apps/backend/subservices/ocr-worker
uv sync
```

### Docker Development (recommended)
```bash
cp .env.development.example .env
docker compose -f docker-compose.dev.yml up -d --build
# Access: http://localhost, noVNC: http://localhost:6080/vnc.html
```

### Testing
```bash
# Run all backend tests
cd apps/backend && npm test

# Run a single test file
cd apps/backend && node --test src/services/session/session-redeem.test.js

# Run tests matching a pattern
cd apps/backend && node --test --test-name-pattern="redeem"
```

### Type Checking
```bash
cd apps/backend && npm run typecheck    # tsc --noEmit (selected files)
cd apps/frontend && npm run typecheck   # vue-tsc --noEmit
```

### Database
```bash
cd apps/backend && npm run db:migrate   # Run migrations manually
cd apps/backend && npm run seed:dev-data   # Seed dev data
cd apps/backend && npm run cleanup:dev-data # Clean dev data
```

### Browser (Playwright)
```bash
cd apps/backend && npm run browser:install        # macOS
cd apps/backend && npm run browser:install:linux  # Linux (with deps)
```

## API Routes

All backend routes are prefixed with `/api/v1/`:
- `/api/v1/tencent/browser/*` — Browser session CRUD and control
- `/api/v1/webhooks/agiso/*` — Agiso platform webhook receiver
- `/api/v1/claim/*` — Claim token validation and redemption
- `/api/v1/admin/*` — Admin panel API (auth, orders, tasks, inventory, etc.)

Health checks (no prefix): `/health`, `/health/live`, `/health/ready`

## Important Conventions

- Backend uses ESM throughout (`"type": "module"`) — always use `.js` extensions in imports
- Express route handlers use `buildSuccessPayload` / `sendRouteError` from `src/utils/http.js` for consistent response format
- Database queries go through `src/db/client.js` (`query()` / `withTransaction()`) — no raw pool usage in services
- Runtime config is accessed via `runtimeConfig` from `src/config/runtime.js` — never read `.env` directly outside that module
- Admin routes are split into separate files under `src/routes/admin/` with shared middleware in `shared.js`
- Frontend uses hash-based routing (`createWebHashHistory`) — claim links include `/#/claim/:token`
- Playwright version is pinned at `1.42.1` — do not upgrade without testing browser automation flows
