# CLAUDE.md

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

## Project Overview

This is a sophisticated Angular 20.1.2 monorepo managed by Nx 21.3.2. The main application is `isa-app`, a comprehensive inventory and returns management system for retail/e-commerce operations. The system handles complex workflows including order management (OMS), returns processing (remission), customer relationship management (CRM), product cataloging, and checkout/reward systems.

## Architecture

### Monorepo Structure
- **apps/isa-app**: Main Angular application
- **libs/**: Reusable libraries organized by domain and type
  - **core/**: Core utilities (config, logging, storage, tabs)
  - **common/**: Shared utilities (data-access, decorators, print)
  - **ui/**: UI component libraries (buttons, dialogs, inputs, etc.)
  - **shared/**: Shared domain components (filter, scanner, product components)
  - **oms/**: Order Management System features and utilities
  - **remission/**: Remission/returns management features
  - **catalogue/**: Product catalogue functionality
  - **utils/**: General utilities (validation, scroll position, parsing)
  - **icons/**: Icon library
- **generated/swagger/**: Auto-generated API client code from OpenAPI specs

### Key Architectural Patterns
- **Domain-Driven Design**: Clear domain boundaries with dedicated modules (OMS, remission, CRM, catalogue, checkout)
- **Layered Architecture**: Strict dependency hierarchy (Feature → Shared/UI → Data Access → Infrastructure)
- **Standalone Components**: All new components use Angular standalone architecture with explicit imports
- **Feature Libraries**: Domain features organized as separate libraries (e.g., `oms-feature-return-search`, `remission-feature-remission-list`)
- **Data Access Layer**: Separate data-access libraries for each domain with NgRx Signals stores
- **Shared UI Components**: 15 dedicated UI component libraries with design system integration
- **Generated API Clients**: 10 auto-generated Swagger/OpenAPI clients with post-processing pipeline
- **Path Aliases**: Comprehensive TypeScript path mapping (`@isa/domain/layer/feature`)
- **Component Prefixes**: Domain-specific prefixes (OMS: `oms-feature-*`, Remission: `remi-*`, UI: `ui-*`)
- **Modern State Management**: NgRx Signals with entities, session persistence, and reactive patterns

## Common Development Commands

### Build Commands
```bash
# Build the main application (development) - default configuration
npm run build
# Or: npx nx build isa-app --configuration=development

# Build for production
npm run build-prod
# Or: npx nx build isa-app --configuration=production

# Serve the application with SSL (development server)
npm start
# Or: npx nx serve isa-app --ssl
```

### Testing Commands
```bash
# Run tests for all libraries except the main app (default command)
npm test
# Or: npx nx run-many -t test --exclude isa-app --skip-cache

# Run tests for a specific library (always use --skip-cache for fresh results)
npx nx run <project-name>:test --skip-cache
# Example: npx nx run oms-data-access:test --skip-cache

# Run a single test file
npx nx run <project-name>:test --testFile=<path-to-test-file> --skip-cache

# Run tests with coverage
npx nx run <project-name>:test --code-coverage --skip-cache

# Run tests in watch mode
npx nx run <project-name>:test --watch

# Run CI tests with coverage (for CI/CD)
npm run ci
# Or: npx nx run-many -t test --exclude isa-app -c ci
```

### Linting Commands
```bash
# Lint a specific project
npx nx lint <project-name>
# Example: npx nx lint remission-data-access

# Run linting for all projects
npx nx run-many -t lint
```

### Other Useful Commands
```bash
# Generate Swagger API clients (regenerates all API clients)
npm run generate:swagger
# Or: npx nx run-many -t generate -p tag:generated,swagger

# Start Storybook for UI component development
npm run storybook
# Or: npx nx run isa-app:storybook

# Format code with Prettier
npm run prettier

# Format staged files only (used in pre-commit hooks)
npm run pretty-quick

# List all projects in the workspace
npx nx list

# Show project dependencies graph (visual)
npx nx graph

# Run affected tests (based on git changes)
npx nx affected:test
```

## Testing Framework

### Current Setup (Migration in Progress)
- **Jest**: Used by 40 libraries (76% of codebase) - existing/legacy libraries
- **Vitest**: Used by 13 libraries (24% of codebase) - newer libraries and migrations
- **Testing Utilities Migration**:
  - **Angular Testing Utilities** (TestBed, ComponentFixture): Preferred for new tests (25 test files)
  - **Spectator**: Legacy testing utility for existing tests (56 test files)
  - **ng-mocks**: For advanced mocking scenarios and child component mocking

### Migration Status by Domain
- **Migrated to Vitest**: `crm-data-access`, `checkout-*`, several `ui/*` components, `remission/*` libraries
- **Still on Jest**: Core `oms/*` libraries, main application, most legacy libraries
- **New Libraries**: Should use Vitest + Angular Testing Utilities from the start

### Test File Requirements
- Test files must end with `.spec.ts`
- Use AAA pattern (Arrange-Act-Assert) consistently across both frameworks
- Include E2E testing attributes (`data-what`, `data-which`, dynamic `data-*` attributes) in HTML templates
- Mock external dependencies and child components using appropriate framework tools
- Verify E2E attributes are correctly applied in component unit tests

## State Management
- **NgRx Signals**: Primary state management with modern functional approach using `signalStore()`
- **Entity Management**: Uses `withEntities()` for normalized data storage
- **Session Persistence**: State persistence with `withStorage()` using SessionStorageProvider
- **Reactive Methods**: `rxMethod()` with `takeUntilKeydownEscape()` for user-cancellable operations
- **Custom RxJS Operators**: Specialized operators like `takeUntilAborted()`, `takeUntilKeydown()`
- **Error Handling**: `tapResponse()` for handling success/error states in stores
- **Lifecycle Hooks**: `withHooks()` for cleanup and initialization (e.g., orphaned entity cleanup)

## Styling and Design System
- **Tailwind CSS**: Primary styling framework with extensive ISA-specific customization
  - **Custom Breakpoints**: `isa-desktop` (1024px), `isa-desktop-l` (1440px), `isa-desktop-xl` (1920px)
  - **Brand Color System**: Comprehensive `isa-*` color palette with semantic naming
  - **Design Tokens**: Consistent spacing, typography, shadows, and border-radius values
- **Custom Tailwind Plugins** (7 plugins): `button`, `typography`, `menu`, `label`, `input`, `section`, `select-bullet`
- **SCSS Integration**: Component-scoped SCSS with BEM-like naming conventions
- **CSS Custom Properties**: Extensive use of CSS variables for theming and component variants
- **Typography System**: 14 custom text utilities (`.isa-text-heading-1-bold`, `.isa-text-body-2-regular`)
- **UI Component Libraries**: 15 specialized UI libraries with consistent API patterns
- **Storybook Integration**: Component documentation and development environment

## API Integration and Data Access
- **Generated Swagger Clients**: 10 auto-generated TypeScript clients from OpenAPI specs in `generated/swagger/`
  - **Available APIs**: availability-api, cat-search-api, checkout-api, crm-api, eis-api, inventory-api, isa-api, oms-api, print-api, wws-api
  - **Generation Tool**: `ng-swagger-gen` with custom configurations per API
  - **Post-processing**: Automatic Unicode character cleanup via `tools/fix-files.js`
- **Data Access Architecture**:
  - **Business Logic Services**: Domain-specific services that wrap generated API clients
  - **Type Safety**: Full TypeScript integration with Zod schema validation
  - **Error Handling**: Global HTTP interceptor with custom error classes and automatic re-authentication
  - **Configuration Management**: Dynamic API endpoint configuration through dependency injection
  - **Request Cancellation**: Built-in support via AbortSignal and custom operators
- **Service Patterns**:
  - **Modern Injection**: Uses `inject()` function with private field pattern
  - **Logging Integration**: Comprehensive logging throughout data access layer
  - **Consistent API**: Standardized service interfaces across all domains

## Build Configuration
- **Angular 20.1.2**: Latest Angular version
- **TypeScript 5.8.3**: For type safety
- **Node.js >= 22.0.0**: Required Node version (specified in package.json engines)
- **npm >= 10.0.0**: Required npm version (specified in package.json engines)
- **Nx 21.3.2**: Monorepo build system and development tools
- **Vite 6.3.5**: Build tool for faster development and testing (used with Vitest)

## Important Conventions and Patterns

### Library Organization
- **Naming Pattern**: `[domain]-[layer]-[feature]` (e.g., `oms-feature-return-search`, `ui-buttons`)
- **Path Aliases**: `@isa/[domain]/[layer]/[feature]` (e.g., `@isa/oms/data-access`, `@isa/ui/buttons`)
- **Project Names**: Found in each library's `project.json` file, following consistent naming

### Component Architecture
- **Standalone Components**: All new components must be standalone with explicit imports
- **Component Prefixes**: Domain-specific prefixes for clear identification
  - OMS features: `oms-feature-*` (e.g., `oms-feature-return-search-main`)
  - Remission features: `remi-*`
  - UI components: `ui-*`
  - Core utilities: `core-*`
- **Signal-based Inputs**: Use Angular signals (`input()`, `computed()`) for reactive properties
- **Host Binding**: Dynamic CSS classes via Angular host properties

### Dependency Rules
- **Unidirectional Dependencies**: Feature → Shared/UI → Data Access → Infrastructure
- **Import Boundaries**: Use path aliases, avoid relative imports across domain boundaries
- **Generated API Imports**: Import from `@generated/swagger/[api-name]` for API clients

### Code Quality
- **Modern Angular Patterns**: Prefer `inject()` over constructor injection
- **Type Safety**: Use Zod schemas for runtime validation alongside TypeScript
- **Error Handling**: Custom error classes with specific error codes
- **E2E Testing**: Always include `data-what` and `data-which` attributes in templates

## Development Workflow and Best Practices

### Essential Commands
- **Development**: `npm start` (serves with SSL enabled by default)
- **Testing**: `npm test` (runs all library tests, skips main app)
- **Building**: `npm run build` (development), `npm run build-prod` (production)
- **Code Generation**: `npm run generate:swagger` (regenerates all API clients)
- **Code Quality**: `npm run prettier` (formats all files), `npm run pretty-quick` (staged files only)

### Nx Workflow Optimization
- Always use `npx nx run` pattern for executing specific tasks
- Include `--skip-cache` flag when running tests to ensure fresh results
- Use affected commands for CI/CD optimization: `npx nx affected:test`
- Visualize project dependencies: `npx nx graph`
- The default git branch is `develop` (not `main`)

### Testing Best Practices
- **New Libraries**: Use Vitest + Angular Testing Utilities
- **Legacy Libraries**: Continue using Jest + Spectator until migrated
- **Migration Priority**: UI components and new domains migrate first
- **E2E Attributes**: Verify `data-what`, `data-which`, and dynamic `data-*` attributes in tests
- **Mock Strategy**: Use appropriate framework tools (Spectator's `mocks` array vs TestBed providers)

### Code Quality Guidelines
- **Linting**: ESLint flat config with Nx dependency checks
- **Formatting**: Prettier with pre-commit hooks via Husky and lint-staged
- **Type Safety**: Zod validation for API boundaries, TypeScript strict mode
- **Bundle Optimization**: Monitor bundle sizes (2MB warning, 5MB error for main bundle)
- **Performance**: Use NgRx Signals for reactive state management with session persistence

## Development Notes and Guidelines

### Getting Started
- **Application Startup**: Only `isa-app` can be started - it's the main application entry point
- **SSL Development**: The development server runs with SSL by default (`npm start`), which is crucial for production-like authentication flows
- **Node Requirements**: Ensure Node.js ≥22.0.0 and npm ≥10.0.0 before starting development
- **First-Time Setup**: After cloning, run `npm install` then `npm start` to verify everything works

### Essential Documentation References
- **Testing Guidelines**: Review `docs/guidelines/testing.md` before writing any tests - it covers the Jest→Vitest migration, Spectator→Angular Testing Utilities transition, and E2E attribute requirements
- **Code Review Standards**: Follow the structured review process in `.github/review-instructions.md` with categorized feedback (🚨 Critical, ❗ Minor, ⚠️ Warnings, ✅ Good Practices)
- **E2E Testing Requirements**: Always include `data-what`, `data-which`, and dynamic `data-*` attributes in HTML templates - these are essential for automated testing by QA colleagues

### Library Development Patterns
- **New Library Creation**: Use Nx generators with domain-specific naming (`[domain]-[layer]-[feature]`)
- **Standalone Components**: All new components must be standalone with explicit imports - no more NgModules
- **Testing Framework Selection**:
  - **New libraries**: Use Vitest + Angular Testing Utilities
  - **Existing libraries**: Continue with Jest + Spectator until migrated
- **Path Aliases**: Always use `@isa/[domain]/[layer]/[feature]` - avoid relative imports across domain boundaries

### API Integration Workflow
- **Swagger Generation**: Run `npm run generate:swagger` to regenerate all 10 API clients when backend changes
- **Data Services**: Wrap generated API clients in domain-specific data-access services with proper error handling and Zod validation
- **State Management**: Use NgRx Signals with `signalStore()`, entity management, and session persistence for complex state

### Performance and Quality Considerations
- **Bundle Monitoring**: Watch bundle sizes (2MB warning, 5MB error for main bundle)
- **Testing Cache**: Always use `--skip-cache` flag when running tests to ensure reliable results
- **Code Quality**: Pre-commit hooks enforce Prettier formatting and ESLint rules automatically
- **Memory Management**: Clean up subscriptions and use OnPush change detection for optimal performance

### Common Troubleshooting
- **Build Issues**: Check Node version and run `npm install` if encountering module resolution errors
- **Test Failures**: Use `--skip-cache` flag and ensure test isolation (no shared state between tests)
- **SSL Certificates**: Development server uses SSL - accept certificate warnings in browser for localhost
- **Import Errors**: Verify path aliases in `tsconfig.base.json` and use absolute imports for cross-library dependencies

### Domain-Specific Conventions
- **Component Prefixes**: Use `oms-feature-*` for OMS, `remi-*` for remission, `ui-*` for shared components
- **Git Workflow**: Default branch is `develop` (not main), use conventional commits without co-author tags
- **Design System**: Use ISA-specific Tailwind utilities (`isa-accent-*`, `isa-text-*`) and custom breakpoints (`isa-desktop-*`)
- **Logging**: Use centralized logging service (`@isa/core/logging`) with contextual information for debugging

## Claude Code Workflow Definition

Based on comprehensive analysis of development patterns and available tools/MCP servers, here's the formal workflow for handling requests using the Task tool with specialized subagents:

### Phase 1: Request Analysis and Routing

#### 1.1 Initial Analysis (Always Use Subagents)
**Trigger**: Any user request
**Subagents**: `general-purpose` (for research) + domain specialists as needed

```
1. Parse request intent and complexity level
2. Classify request type:
   - Feature Development (new functionality)
   - Bug Fix/Maintenance (corrections)
   - Code Quality/Refactoring (improvements)
   - Testing/QA (validation)
   - Architecture/Design (structure)
   - Research/Investigation (exploration)
3. Assess information completeness and ambiguity
4. Determine required domains and expertise
```

#### 1.2 Clarification Decision Matrix
```
IF (high ambiguity + high impact) → REQUEST clarification
IF (medium ambiguity + architectural changes) → REQUEST optional clarification
IF (low ambiguity OR simple changes) → PROCEED with documented assumptions
```

### Phase 2: Task Decomposition and Agent Assignment

#### 2.1 Complexity-Based Routing

**Simple Tasks (Single file, isolated change)**:
- Route directly to specialist (`frontend-developer`, `typescript-pro`, etc.)
- Single quality gate at completion

**Moderate Tasks (Multiple related files, limited scope)**:
- Decompose into 2-4 parallel subagent tasks
- Example: `angular-mcp` + `test-automator` + `docs-architect`

**Complex Tasks (Multiple domains, significant scope)**:
- Hierarchical task tree with dependencies
- Example: `general-purpose` (analysis) → `nx-mcp` (structure) → `frontend-developer` + `test-automator` (parallel) → `code-reviewer` (validation)

**Architectural Tasks (System-wide changes)**:
- Multi-phase with user approval gates
- Example: `architect-review` → user approval → `frontend-developer` + `backend-architect` + `database-optimizer` → `performance-engineer` (validation)

#### 2.2 Optimal Agent Combinations

**Feature Development Pattern**:
```
context7 (fetch latest APIs)
→ frontend-developer + test-automator (parallel TDD)
→ ui-ux-designer (if UI changes)
→ code-reviewer (quality validation)
```

**Bug Fix Pattern**:
```
error-detective (analyze issue)
→ debugger (reproduce and fix)
→ test-automator (regression tests)
→ performance-engineer (if performance-related)
```

**Refactoring Pattern**:
```
general-purpose (understand current state)
→ legacy-modernizer (plan modernization)
→ test-automator (safety tests)
→ frontend-developer (implement changes)
→ architect-review (validate architecture)
```

### Phase 3: Execution with Progressive Quality Gates

#### 3.1 Standard Execution Flow
```
1. Each subagent receives atomic task with clear requirements
2. Subagent performs implementation with embedded quality checks
3. Results validated against project standards (E2E attributes, naming conventions)
4. Integration compatibility verified
5. Progress reported to user with next steps
```

#### 3.2 Quality Gates by Task Type
- **Code Changes**: `test-automator` → `code-reviewer` → `performance-engineer`
- **UI Changes**: `ui-visual-validator` → `frontend-security-coder` → `code-reviewer`
- **Architecture Changes**: `architect-review` → user approval → implementation → `performance-engineer`
- **API Changes**: `api-documenter` → `backend-security-coder` → integration tests

### Phase 4: Integration and Validation

#### 4.1 Continuous Validation
```
- Every file change triggers appropriate quality subagent
- Integration points validated by architect-review
- Performance impacts assessed by performance-engineer
- Security changes reviewed by security-auditor
```

#### 4.2 User Communication Strategy
```
- Real-time: Critical decisions and blockers
- Milestone-based: Major phase completions
- Exception-driven: Alternative approaches or issues
- Summary-based: Long-running workflow progress
```

### Specialized Subagent Usage Patterns

#### **Always Use These Subagents Proactively**:
- `general-purpose`: For codebase analysis, research, and complex multi-step tasks
- Available specialist agents based on task requirements (see full list below)

#### **Available MCP Server Integration**:
- **nx-mcp**: `nx_workspace`, `nx_project_details`, `nx_run_generator`, `nx_visualize_graph`, etc.
- **angular-mcp**: `list_projects`, `search_documentation`
- **context7**: `resolve-library-id`, `get-library-docs` for latest package documentation

#### **Project-Relevant Subagent Types**:

**Tier 1 - Essential (Most Frequently Needed)**:
- `frontend-developer`: Angular 20.1.2 feature development, standalone components, domain library implementation
- `typescript-pro`: Advanced TypeScript 5.8.3 patterns, type system optimization, interface design
- `test-automator`: Jest→Vitest migration, Spectator→Angular Testing Utilities, unit testing, E2E attributes
- `ui-ux-designer`: Tailwind CSS design system, UI component libraries, responsive design

**Tier 2 - Important (Regularly Needed)**:
- `code-reviewer`: ESLint compliance, Angular best practices, code quality validation
- `performance-engineer`: Angular optimization, bundle analysis, NgRx performance patterns
- `api-documenter`: Swagger/OpenAPI integration, API client documentation
- `docs-architect`: Technical documentation, architecture guides, CLAUDE.md maintenance

**Tier 3 - Specialized (Domain-Specific)**:
- `architect-review`: Nx monorepo architecture, domain-driven design validation
- `frontend-security-coder`: Angular security patterns, XSS prevention, authentication flows
- `deployment-engineer`: Angular build pipelines, Nx CI/CD, npm script automation
- `debugger`: Error analysis, RxJS debugging, state management troubleshooting

**Cross-Cutting Support**:
- `general-purpose`: Complex analysis, codebase research, multi-domain investigations
- `error-detective`: Production issue investigation, log analysis, performance bottlenecks

### Escalation and Error Handling

#### Immediate Escalation Triggers:
- Subagent cannot access required files or resources
- Conflicting requirements between parallel tasks
- Security vulnerabilities discovered
- Breaking changes with no compatibility path

#### Recovery Hierarchy:
1. Subagent self-resolution (retry with different approach)
2. Alternative subagent assignment (different specialist)
3. Task redecomposition (break down further)
4. User consultation (clarification or decision needed)

### Example Workflow: "Add Dark Mode Feature"

```
1. ANALYSIS PHASE:
   Task(general-purpose, "Research Angular/Tailwind dark mode patterns and analyze ISA theme system")

2. PLANNING PHASE:
   Task(ui-ux-designer, "Design dark mode integration with ISA color system and Tailwind classes")
   Task(frontend-developer, "Plan component modifications and theme service architecture")

3. IMPLEMENTATION PHASE (can run in parallel):
   Task(frontend-developer, "Implement Angular theme service and component modifications")
   Task(typescript-pro, "Create TypeScript interfaces and type-safe theme system")
   Task(test-automator, "Create Jest/Vitest tests with E2E attributes for theme functionality")

4. VALIDATION PHASE:
   Task(code-reviewer, "Review Angular patterns, NgRx integration, and code quality")
   Task(performance-engineer, "Assess bundle size impact and runtime performance")

5. INTEGRATION PHASE:
   Task(test-automator, "Run full Nx test suite and validate E2E attributes")
   Task(docs-architect, "Update Storybook documentation and component usage guides")
```

### MCP Server Integration Workflow: "Integrate New Angular Library"

```
1. RESEARCH PHASE:
   - Use mcp__context7__resolve-library-id to find the library
   - Use mcp__context7__get-library-docs to understand APIs
   - Use mcp__angular-mcp__search_documentation for Angular integration patterns

2. PROJECT SETUP:
   - Use mcp__nx-mcp__nx_generators to find appropriate generators
   - Use mcp__nx-mcp__nx_run_generator to scaffold integration components
   - Use mcp__nx-mcp__nx_project_details to understand impact scope

3. IMPLEMENTATION WITH SUBAGENTS:
   Task(typescript-pro, "Create TypeScript interfaces for library integration")
   Task(frontend-developer, "Implement Angular service wrapping the library")
   Task(test-automator, "Create unit and integration tests")

4. VALIDATION:
   - Use mcp__nx-mcp__nx_visualize_graph to verify dependency relationships
   - Use mcp__nx-mcp__nx_current_running_tasks_details to monitor builds
   Task(code-reviewer, "Review integration patterns and code quality")
```

This comprehensive workflow leverages ALL available MCP servers and specialized subagents for maximum efficiency, with each agent handling both analysis AND implementation tasks according to their expertise.
