# CLAUDE.md

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

## Project Overview

**Customer Management Orchestration Service** - A Spring Boot microservice that orchestrates customer lifecycle flows including onboarding (self-service signup) and offboarding. The service manages customer record creation/destruction, billing account setup, identity/auth provisioning, and network resource assignments.

- **Build Tool**: Maven 3 (with wrapper: `./mvnw`)
- **Java Version**: 21
- **Spring Boot**: 3.4.10
- **Port**: 8101
- **Artifact**: `io.netfoundry:customer-management:0.0.4-SNAPSHOT`

## Build & Development Commands

### Build
```bash
./mvnw clean install              # Full build with tests
./mvnw clean package              # Build without running tests
./mvnw clean install -DskipTests  # Build skipping test execution
```

### Testing
```bash
./mvnw test                                    # Run all unit tests
./mvnw test -Dtest=CustomerControllerTest     # Run specific test class
./mvnw test -Dtest=CustomerControllerTest#testFindCustomers  # Run specific test method
```

### Run Locally
```bash
./run.sh                  # Run application with Maven (./mvnw spring-boot:run) + local development profile
./run.sh -Xmx2048m       # Pass JVM options through
```

The `run.sh` script automatically:
- Sets `SPRING_PROFILES_ACTIVE=development`
- Validates Java 21 is installed
- Configures AWS region and credentials from local files
- Sets timezone to UTC

### Code Quality & Documentation
```bash
./mvnw clean install -Pdocs  # Build with documentation generation (Javadoc, AsciiDoc, Spring REST Docs)
./sonar.sh                    # Run SonarQube analysis (requires SonarCloud credentials)
```

## Architecture Overview

### High-Level Design Pattern: Process-Driven Orchestration

The service uses a **process-based orchestration pattern** where complex customer workflows are decomposed into named, tracked steps:

- **Core Framework**: `@Process` and `@Step` annotations (from `io.netfoundry.processing` - NetFoundry's process framework)
- **Execution Tracking**: Redis-backed process execution tracker with state management
- **Async Execution**: RabbitMQ-based distributed execution with retry/resilience built-in
- **Event Publishing**: Resource change notifications via messaging framework

**Key Processes** (in `src/main/java/io/netfoundry/customer/process/`):
- `SignupProcess` - Self-service customer signup orchestration (creates customer, org, identity providers, networks, billing)
- `OnboardCustomerProcess` - Provisions created resources across dependent services
- `OffboardCustomerProcess` - Deletes customer and all associated resources
- `SuspendCustomerProcess` / `ResumeCustomerProcess` - Pause/resume customer access
- `CreateCustomerNetworkProcess` / `DeleteCustomerNetworkProcess` - Network lifecycle
- `ProvisionNetworkGroupProcess` - Network group provisioning
- Various feature-specific provisioning processes (Frontdoor, CustomerConnect, SoftwareAccess)

### Layered Architecture

```
Controller Layer (REST endpoints)
         ↓
Domain/Service Layer (business logic, @Transactional)
         ↓
Process Layer (orchestration, multi-step workflows)
         ↓
External Service Clients (HTTP clients to dependent microservices)
         ↓
Repository Layer (Spring Data JPA/JDBC, MySQL persistence)
```

### Key Layers & Packages

**`controller/`** - 12 REST controllers mapping to API endpoints
- `CustomerController` - Core CRUD operations
- `SignupController` - Self-service signup endpoints
- `CustomerOperationsController` - Onboard/offboard/suspend/resume operations
- `CustomerProfileController` - Customer profile management
- Controllers use Spring HATEOAS for linked resource responses (HAL JSON)

**`domain/`** - 18+ subdirectories with entities, repositories, services
- `customer/` - Customer entity, service, repository, finder DTOs
- `signup/` - Signup entity and service for tracking signup flow state
- `assignment/` - Customer resource assignments (networks, identities, etc.)
- `execution/` - Execution tracking (process execution records)
- `externalaccount/` - External system account mappings
- Each domain has: Entity classes, Repository (Spring Data JPA), Service (business logic), Find/Create/Update DTOs

**`process/`** - 13+ Process classes implementing orchestration workflows
- Step-based execution with `@Step` annotation
- Support steps, helper services (SignupNetworkSupportService, SignupBillingSupportService, etc.)
- ProcessData context object carries state between steps
- Exception handlers for resilience and retry logic

**`external/`** - Integration clients to dependent microservices
- `authorization/` - AuthorizationClient (calls authorization service)
- `billing/` - BillingServiceClient (calls billing service)
- `core/` - NetworkClient, NetworkGroupClient (calls core/network service)
- `identity/` - IdentityClient (calls identity service)
- `frontdoor/` - FrontdoorClient (provisions edge/gateway resources)
- `customerconnect/` - CustomerConnectClient (provisions customer-facing connect service)
- `hubspot/` - HubspotCompanyService, HubspotDealService, HubspotContactService (CRM integration)
- Clients use RestTemplate with retry/timeout logic via `io.netfoundry.common` framework

**`config/`** - Spring configuration beans
- `DataSourceConfiguration` - MySQL datasource, Flyway migrations
- `RabbitMQConfiguration` - RabbitMQ for async process execution
- `AuthorizationConfig` - OAuth2/JWT security configuration
- `JacksonConfiguration` - JSON serialization (timestamps as ISO, HAL support)
- `WebConfig` - Web-specific bean registrations
- `SchedulingConfiguration` - Scheduled task configuration

**`validation/`** - Custom JSR-303 validators
- Custom annotations: `@CustomerNameUniqueValidator`, `@OrganizationLabelUniqueValidator`, etc.
- Integrated with controller request binding for DTO validation

**`util/`** - Utility classes (ID generation, common helpers)

**`email/`** - Email service integration (Simple Java Mail)

**`external/country/`** - Country service for locale/region support

### Data Persistence

**Database**: MySQL 8.0+ with UTF-8 encoding
- Schema: `Customer` (auto-created in dev)
- **Migrations**: Flyway (in `src/main/resources/database/migration/`)
- **ORM**: Spring Data JPA + custom JDBC queries for complex scenarios
- Tables: customer, customer_resource_assignment, signup, execution, system_notes, customer_profile, customer_profile_assignment, external_account, software_access, etc.

**Caching**: 
- Redisson (Redis client) for distributed caching
- Local Caffeine cache for short-lived data

**Messaging**:
- **RabbitMQ**: Process execution queue (prefetch=1 for distribution, concurrency=10-50)
- **Redis**: Process execution state tracking, finished timeout=48 hours

### External Service Dependencies

All service URLs configurable via properties (see `application.properties`):
- `io.netfoundry.core.serviceUrl` - Network/group management
- `io.netfoundry.identity.serviceUrl` - Identity provider management
- `io.netfoundry.auth.serviceUrl` - Authorization service
- `io.netfoundry.billing.serviceUrl` - Billing/subscription management
- `io.netfoundry.customerConnect.serviceUrl` - CustomerConnect provisioning
- `io.netfoundry.zrokConnector.serviceUrl` - Zrok connector integration
- HubSpot API for CRM integration (deal, contact, company syncing)

### Key Frameworks & Libraries

- **Spring Cloud** (2024.0.1) - Service discovery, config
- **Spring HATEOAS** - REST resource linking (HAL JSON default)
- **Spring REST Docs** - API documentation from tests
- **SpringDoc OpenAPI** - OpenAPI 3.0 spec generation (Swagger UI)
- **Lombok** - Annotation-based code generation (@Data, @Slf4j, etc.)
- **Jackson** - JSON serialization (YAML, CSV support)
- **Flyway** - Database migrations
- **Redisson** - Redis client abstraction
- **AWS SDK v2** - S3, DynamoDB, SSM integration
- **Micrometer + Elastic** - Metrics reporting
- **Brave/Tracing** - Distributed tracing
- **Spring Retry** - Declarative retry logic
- **JSON Schema Validator** - Request/response validation

### Testing

- **Framework**: Spring Boot Test + JUnit 5 (Jupiter)
- **Mocking**: Mockito + Mockito JUnit integration
- **Test Database**: H2 in-memory database
- **Test Infrastructure**: Embedded Redis, BaseServiceTest template
- **Documentation**: Spring REST Docs with Auto REST Docs plugin
- 67+ test classes covering controllers, services, processes, validators

Test structure mirrors main: `src/test/java/io/netfoundry/customer/{controller,domain,process,external,validation,util}/`

## Configuration & Environment

### Application Properties
Primary config: `src/main/resources/application.properties`

Environment-specific profiles:
- `-development` (localhost, debug logging, embedded services)
- `-sandbox` 
- `-staging`
- `-production`

Activated via `SPRING_PROFILES_ACTIVE` environment variable or `spring.profiles.active` property.

**Key Configurable Properties**:
- Database connection (spring.datasource.*)
- Auth0 OAuth credentials (io.netfoundry.auth.provider.auth0.*)
- Service URLs (io.netfoundry.*.serviceUrl)
- Email settings (io.netfoundry.customer.email.*)
- Billing plan mappings (io.netfoundry.customer.billing.plan.*)
- Entitlements (endpoint counts, network limits)
- HubSpot configuration (deal stages, pipelines, owner IDs)
- RabbitMQ listener concurrency (processing.executor.rabbit.concurrency)

### Bootstrap Configuration
`bootstrap.properties` - Spring Cloud Config bootstrapping

## API Documentation

OpenAPI spec auto-generated and accessible at:
- `/v3/api-docs` - JSON spec
- `/swagger-ui.html` - Swagger UI

Spec configured in `Application.java` with:
- Bearer JWT authentication
- Production gateway base URL
- All endpoints documented via annotations

## Project Structure

```
customer-management-dev/
├── src/
│   ├── main/java/io/netfoundry/customer/
│   │   ├── Application.java              (Spring Boot entry point)
│   │   ├── controller/                   (REST endpoints)
│   │   ├── domain/                       (entities, services, repos)
│   │   ├── process/                      (orchestration workflows)
│   │   ├── external/                     (microservice clients)
│   │   ├── config/                       (Spring bean configuration)
│   │   ├── validation/                   (custom validators)
│   │   ├── util/
│   │   └── email/
│   ├── main/resources/
│   │   ├── application.properties         (primary config)
│   │   ├── application-{env}.properties   (environment overrides)
│   │   ├── bootstrap.properties           (Spring Cloud Config)
│   │   ├── database/migration/            (Flyway SQL migrations)
│   │   └── email/                         (email templates)
│   └── test/                              (mirrored structure for tests)
├── pom.xml                               (Maven project definition)
├── run.sh                                (local dev launch script)
├── Dockerfile                            (Docker image for deployment)
└── jenkinsfiles/                         (CI/CD pipeline definitions)
```

## Deployment & Containerization

**Docker Image**: 
- Base: Amazon Corretto 21 Alpine
- Port: 8101
- Expects JAR: `target/customer-management-0.0.4-SNAPSHOT.jar`
- Entrypoint: `/app/entrypoint.sh`

**CI/CD**:
- Bitbucket Pipelines via Jenkinsfiles
- Build, SonarQube scan, Docker image push, deployment to ECS
- Automated dependency security checks (OWASP dependency-check)

## Important Notes

### Lombok Configuration
Project uses Lombok extensively. `src/main/java/io/netfoundry/customer/lombok.config` enables annotation processing.

### Error Handling & Validation
- Controllers validate input DTOs using JSR-303 annotations + custom validators
- Transactional services handle data consistency via `@Transactional`
- Process steps include exception handlers for resilience
- Resource not found errors return 404 with problem details

### Security
- OAuth2 JWT bearer token authentication (Auth0)
- Authorization service integration for fine-grained access control
- Audit logging via Http-Audit-Log framework
- Graceful shutdown configured (server.shutdown=graceful)

### Performance Considerations
- HATEOAS response building uses HalUtil to avoid N+1 queries
- Property injectors for lazy-loading related resource data
- Redis caching for frequently accessed data
- RabbitMQ prefetch=1 ensures work distribution across consumers
- Metrics exported to Elastic via Micrometer

### Common Development Patterns

**Creating a New API Endpoint**:
1. Create request/response DTOs in `domain/{entity}/`
2. Add service method in `{Entity}Service`
3. Create controller method in appropriate controller, annotate with `@GetMapping/@PostMapping/@PutMapping/@DeleteMapping`
4. Use Spring HATEOAS `EntityModel` or `CollectionModel` for responses
5. Add validation annotations to request DTOs
6. Write integration test in `src/test/java/io/netfoundry/customer/controller/`

**Extending a Process**:
1. Add new `@Step` method with clear naming
2. Use `@Next("stepName")` to define workflow order
3. Store context in shared `ProcessData` object (or create domain-specific context)
4. Use `@ExceptionHandler` for resilience patterns
5. Call external service clients as needed
6. Emit `@Metadata` updates to track progress
7. Test with embedded services (H2, embedded Redis)

**Working with Database**:
1. Migration files follow Flyway naming: `Vx.x.x__description.sql`
2. Entities use Lombok `@Data` for getters/setters
3. Repositories extend `JpaRepository` or use custom `@Query` methods
4. Service layer applies business logic and transactionality

## Useful References

- **OpenAPI Spec**: http://localhost:8101/v3/api-docs (when running)
- **Swagger UI**: http://localhost:8101/swagger-ui.html
- **Git Log**: Recent commits show feature additions (v7/v8 networks, Frontdoor v2, CustomerConnect, etc.)
- **NetFoundry Framework**: This service uses `io.netfoundry:common-util-framework`, `io.netfoundry:process-framework`, `io.netfoundry:messaging-framework` - custom internal libraries for common patterns
