# CLAUDE.md

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

## Project Overview

HZHub (汇智中台) is an enterprise-level business platform integrating AI capabilities, system management, approval workflows, and ERP data adaptation. It consists of multiple frontend portals, backend microservices, and an API gateway, orchestrated via Docker Compose.

## Commands

### Docker Deployment (Production-like)

```bash
# Start all services
cd hzhub-deploy
docker-compose up -d

# View service status
docker-compose ps

# View logs
docker-compose logs -f hzhub-ai
docker-compose logs -f hzhub-system

# Restart services
docker-compose restart hzhub-ai

# Stop all services
docker-compose down
```

### Backend Development (Spring Boot)

```bash
# Build hzhub-ai common modules first (required by hzhub-system)
cd hzhub-ai
mvn clean install -DskipTests

# Run AI service locally (foreground)
cd hzhub-ai/hzhub-admin
mvn spring-boot:run -Dspring-boot.run.profiles=dev

# Run system service locally (foreground)
cd hzhub-system
mvn spring-boot:run -Dspring-boot.run.profiles=dev

# Run ERP service locally (foreground)
cd hzhub-erp
mvn spring-boot:run -Dspring-boot.run.profiles=dev

# Run tests
mvn test
```

**Important:** hzhub-system depends on hzhub-ai's common modules. Always run `mvn clean install -DskipTests` in hzhub-ai first.

### Frontend Development (Vue 3)

```bash
# Admin portal (Vben Admin + Ant Design Vue)
cd hzhub-admin
pnpm install
pnpm dev                    # Port 5666

# Employee portal (Element Plus)
cd hzhub-portal-employee
pnpm install
pnpm dev                    # Port 5137

# Dealer portal (Element Plus)
cd hzhub-portal-dealer
pnpm install
pnpm dev                    # Port 5138
```

## Architecture

### Multi-Service Structure

```
┌─────────────────────────────────────────┐
│           Frontend Layer                 │
│  hzhub-admin | hzhub-portal-employee    │
│              | hzhub-portal-dealer       │
└────────────┬────────────────────────────┘
             │
    ┌────────┴────────┐
    │  hzhub-gateway  │  (API Gateway, port 8080)
    │  Spring Cloud   │  JWT auth, routing, rate limiting, XSS
    └───┬──────┬──────┘
        │      │
    ┌───▼──┐  ┌▼────────────┐
    │hzhub │  │ hzhub-system│  hzhub-erp
    │ -ai  │  │ (System Mgmt)│ (SQL Server)
    │ 6039 │  │   8083       │   8082
    └──────┘  └─────────────┘
```

### Gateway Routes

| Path Prefix | Target Service | Features |
|-------------|---------------|----------|
| `/ai/**` | hzhub-ai:6039 | AI chat, knowledge base, AI workflow |
| `/system/**` | hzhub-system:8083 | Users, roles, permissions, tenants, OSS |
| `/monitor/**` | hzhub-system:8083 | Operation logs, online users, cache |
| `/auth/**` | hzhub-system:8083 | Login, register, captcha, tenant list |
| `/resource/**` | hzhub-system:8083 | Email/SMS code, SSE, WebSocket |
| `/workflow/**` | hzhub-system:8083 | Approval workflows (warm-flow) |
| `/tool/**` | hzhub-system:8083 | Code generator (velocity) |
| `/erp/**` | hzhub-erp:8082 | ERP customer data |

### Backend Service Organization

**hzhub-ai** (AI Service, port 6039):
- **hzhub-admin**: Main application entry point (`HZHubAIApplication.java`)
- **hzhub-common**: Shared utility modules (core, redis, mybatis, security, oss, chat, etc.)
- **hzhub-modules**:
  - **hzhub-chat**: AI conversation, knowledge base, MCP
  - **hzhub-aiflow**: AI workflow orchestration (LangGraph4j)
- **hzhub-extend**: Monitoring (spring-boot-admin), job scheduling

**hzhub-system** (System Service, port 8083):
- Independent Spring Boot service
- Depends on hzhub-ai common modules (must build hzhub-ai first)
- Entry point: `HZHubSystemApplication.java`
- **Auth**: login, register, captcha, tenant list (`/auth/**`, `/resource/**`)
- **System**: users, roles, menus, departments, dicts, config, posts, tenants, OSS, clients, social login (`/system/**`)
- **Monitor**: operation logs, online users, login logs, cache (`/monitor/**`)
- **Workflow**: approval process definitions, instances, tasks (`/workflow/**`)
- **Generator**: code generation from database tables (`/tool/gen`)

**hzhub-erp** (ERP Service, port 8082):
- SQL Server 2008 R2 data adapter
- Customer management, sales data exploration

### Frontend Architecture

**hzhub-admin** (Vben Admin monorepo):
- Vue 3 + TypeScript + Ant Design Vue
- Pinia state management
- Features: system management, workflow, AI flow, knowledge base, chat, monitoring, code generator

**hzhub-portal-employee** (Element Plus):
- Vue 3 + TypeScript + Element Plus
- Features: dashboard, approval center, CRM, dealer management, supply chain, BI reports, AI chat, ERP

**hzhub-portal-dealer** (Element Plus):
- Vue 3 + TypeScript + Element Plus
- Features: AI chat interface only

### Key Technologies

**Backend**:
- Spring Boot 3.5.8, Java 17
- LangChain4j + LangGraph4j for AI/LLM integration
- Sa-Token for authentication (JWT-based, HmacSHA256)
- MyBatis-Plus for database access
- Dynamic datasource for multi-database support
- warm-flow 1.8.2 for approval workflows
- Velocity 2.3 for code generation templates
- Weaviate for vector database (knowledge retrieval)

**Frontend**:
- Vue 3 with Composition API
- Vben Admin framework (admin portal)
- Element Plus + element-plus-x (portal UI)
- Pinia for state management
- UnoCSS for atomic CSS

**Infrastructure**:
- MySQL 8.0 (business data)
- Redis 7 (cache, session, rate limiting)
- Weaviate 1.25.0 (vector database)
- n8n (workflow automation)
- MinIO (object storage)

## Important Patterns

### Backend API Structure

Controllers follow REST conventions:

```java
@RestController
@RequestMapping("/chat")
public class ChatController {
    @PostMapping("/message")
    public R<ChatResponse> sendMessage(@RequestBody ChatRequest request) {
        // Response wrapper: R<T>
    }
}
```

Response wrapper `R<T>` from `hzhub-common-core` provides standardized API responses.

### Multi-tenancy & Authentication

- Sa-Token handles JWT authentication
- Client ID header required: `ClientID` (passed in frontend requests)
- Token auto-injected via `Authorization: Bearer <token>`
- Gateway injects `X-User-Id`, `X-Client-Id`, `X-Gateway-Verified: true` headers
- Backend services trust `X-Gateway-Verified` header to skip redundant JWT validation

### Dynamic Datasource

`hzhub-common-mybatis` uses `dynamic-datasource-spring-boot-starter`:

```yaml
spring:
  datasource:
    dynamic:
      primary: master
      datasource:
        master:  # MySQL for business data
        erp:     # SQL Server (planned)
```

Switch datasource in code: `@Ds("erp")` annotation on service methods.

### SSE Streaming

AI chat uses Server-Sent Events for streaming responses:

```java
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamChat(@RequestParam String message) {
    // Returns SSE stream
}
```

Frontend uses `hook-fetch` with `sseTextDecoderPlugin` to handle SSE.

### Configuration Profiles

Backend uses Spring profiles:
- `application.yml` - Base configuration
- `application-dev.yml` - Development
- `application-prod.yml` - Production

Profile set via `SPRING_PROFILES_ACTIVE` env var or `spring.profiles.active` property.

## Development Workflow

### Service Dependencies

When running locally, backend services need infrastructure:
- MySQL (localhost:3306)
- Redis (localhost:6379)
- Weaviate (localhost:28080)

Start infrastructure via Docker Compose first:
```bash
cd hzhub-deploy
docker-compose up -d mysql redis weaviate
```

### Environment Variables

**Backend**:
- `SPRING_DATASOURCE_DYNAMIC_DATASOURCE_MASTER_URL`: MySQL connection URL
- `SPRING_DATASOURCE_DYNAMIC_DATASOURCE_MASTER_USERNAME`: DB username
- `SPRING_DATASOURCE_DYNAMIC_DATASOURCE_MASTER_PASSWORD`: DB password
- `SPRING_DATA_REDIS_HOST`: Redis host
- `SPRING_DATA_REDIS_PORT`: Redis port
- `JWT_SECRET`: Shared JWT secret (all services)

**Frontend** (in `.env.development`):
- `VITE_API_URL=http://localhost:8080` (Gateway URL)
- `VITE_CLIENT_ID`: Client identifier for auth
- `VITE_WEB_TITLE`: Page title

### Testing

Backend tests use Spring Boot test framework:
```java
@SpringBootTest
class ChatServiceTest {
    @Test
    void testSendMessage() { ... }
}
```

## Deployment

### Docker Image Building

Backend Dockerfiles in each service directory:
- Multi-stage build (Maven → JRE)
- hzhub-ai: port 6039
- hzhub-system: port 8083
- hzhub-erp: port 8082

Frontend Dockerfiles in each portal directory:
- Builds with pnpm
- Served via Nginx

### Service Ports

| Service | Port | Access |
|---------|------|--------|
| hzhub-gateway | 8080 | http://localhost:8080 (统一入口) |
| hzhub-ai | 6039 | http://localhost:6039 |
| hzhub-system | 8083 | http://localhost:8083 |
| hzhub-erp | 8082 | http://localhost:8082 |
| hzhub-admin | 5666 | http://localhost:5666 |
| hzhub-portal-employee | 5137 | http://localhost:5137 |
| hzhub-portal-dealer | 5138 | http://localhost:5138 |
| MySQL | 3306 | localhost:3306 |
| Redis | 6379 | localhost:6379 |
| Weaviate | 28080 | http://localhost:28080 |
| n8n | 5678 | http://localhost:5678 |
| MinIO | 9000/9001 | http://localhost:9000 (API), http://localhost:9001 (Console) |

## Common Tasks

### Adding a New Backend Module

1. Decide which service it belongs to (AI, system, or ERP)
2. For hzhub-ai: create module in `hzhub-ai/hzhub-modules/`, add to parent pom.xml
3. For hzhub-system: create package under `src/main/java/org/hzhub/`, add dependencies to pom.xml
4. Create controller, service, mapper following existing patterns
5. Add gateway route in `hzhub-gateway/src/main/resources/application.yml`

### Adding a New API Endpoint

1. Create controller in the appropriate service
2. Use `@RestController` and `@RequestMapping`
3. Return `R<T>` wrapper for responses
4. Add permission check if needed: `@SaCheckPermission("system:user:list")`

### Adding Frontend Features

For admin portal:
1. Add API call in `apps/web-antd/src/api/`
2. Create view in `apps/web-antd/src/views/`
3. Add route in `apps/web-antd/src/router/`
4. Add menu configuration

For portals (employee/dealer):
1. Add API module in `src/api/` with `index.ts` and `types.ts`
2. Create page in `src/pages/`
3. Define route in `src/routers/modules/`
4. Add store if needed in `src/stores/`

### Working with Weaviate

Weaviate is used for knowledge retrieval (RAG). Collection creation and querying handled by LangChain4j integration in `hzhub-common-chat`.

## Notes

- **Package naming**: `org.hzhub.*` (renamed from `org.ruoyi.*`)
- **Java version**: JDK 17+
- **Node version**: Node 22+ with pnpm 10+
- **Code style**: ESLint `@antfu/eslint-config` for frontend; backend follows Spring conventions
- **Git hooks**: Lefthook configured (see `lefthook.yml`)
- **Build order**: hzhub-ai → hzhub-system → hzhub-erp (hzhub-system depends on hzhub-ai common modules)
