# Managing Apps - Claude Code Guidelines

## Project Overview
This is a quantitative finance application with .NET backend and React TypeScript frontend, focusing on algorithmic trading, market indicators, and financial mathematics.

## Core Architecture Principles

### Quantitative Finance Requirements
- **IMPORTANT**: Use `decimal` for all monetary calculations (never `double` or `float`)
- Implement proven financial mathematics (Black-Scholes, Monte Carlo, etc.)
- Optimize time-series processing for tick data/OHLCV series
- Validate models with historical backtesting frameworks
- Maintain audit trails for all financial calculations
- Prioritize numerical precision in all calculations

### Backend (.NET/C#) Guidelines

#### Code Style and Structure
- Write concise, idiomatic C# code following .NET conventions
- Use object-oriented and functional programming patterns appropriately
- Prefer LINQ and lambda expressions for collection operations
- Use descriptive variable and method names (e.g., `IsUserSignedIn`, `CalculateTotal`)
- Structure files according to .NET conventions (Controllers, Models, Services, etc.)

#### Naming Conventions
- **PascalCase**: Class names, method names, public members
- **camelCase**: Local variables, private fields
- **UPPERCASE**: Constants
- **Prefix interfaces with "I"**: `IUserService`, `IAccountRepository`

#### C# and .NET Usage
- Use C# 10+ features (record types, pattern matching, null-coalescing assignment)
- Leverage built-in ASP.NET Core features and middleware
- Use `var` for implicit typing when type is obvious
- Use MongoDb and Influxdb for database operations

#### Architecture Layers (YOU MUST FOLLOW)
1. **Controller** → **Application** → **Repository** (NEVER inject repository in controllers)
2. Always implement methods you create
3. Check existing code before creating new objects/methods
4. Update all layers when necessary (database to frontend)

#### Error Handling and Validation
- Use exceptions for exceptional cases, not control flow
- Implement proper error logging with .NET logging
- Use Data Annotations or Fluent Validation for model validation
- Return appropriate HTTP status codes and consistent error responses
- Services in `services/` directory must throw user-friendly errors for tanStackQuery

#### API Design
- Follow RESTful API design principles
- Use attribute routing in controllers
- Implement versioning for APIs
- Use Swagger/OpenAPI for documentation

#### Performance Optimization
- Use `async/await` for I/O-bound operations
- Implement caching strategies (IMemoryCache or distributed caching)
- Use efficient LINQ queries, avoid N+1 query problems
- Implement pagination for large datasets

### Frontend (React/TypeScript) Guidelines

#### Component Structure
- Use functional components with TypeScript interfaces
- Use declarative JSX
- Use `function`, not `const` for components
- Use DaisyUI Tailwind Aria for components and styling
- Implement responsive design with Tailwind CSS (mobile-first approach)

#### File Organization
- Use lowercase with dashes for directories: `components/auth-wizard`
- Place static content and interfaces at file end
- Use content variables for static content outside render functions
- Favor named exports for components

#### State Management
- Minimize `use client`, `useEffect`, and `setState`
- Favor React Server Components (RSC)
- Wrap client components in Suspense with fallback
- Use dynamic loading for non-critical components
- Use `useActionState` with react-hook-form for form validation

#### Error Handling
- Model expected errors as return values (avoid try/catch for expected errors)
- Use error boundaries for unexpected errors (`error.tsx`, `global-error.tsx`)
- Use `useActionState` to manage errors and return them to client

#### Component Library
- **DO NOT** reference new React libraries if components exist in `mollecules` or `atoms`
- Check existing components before creating new ones

## Development Workflow

### Build and Run Commands
```bash
# Backend
dotnet build
dotnet run --project src/Managing.Api

# Frontend
npm run build
npm run dev

# Regenerate API client (after backend changes)
cd src/Managing.Nswag && dotnet build
```

### API Client Generation
1. **NEVER** update `ManagingApi.ts` manually
2. After backend endpoint changes:
   - Run the Managing.Api project
   - Execute: `cd src/Managing.Nswag && dotnet build`
   - This regenerates `ManagingApi.ts` automatically

### Testing
- Write unit tests using xUnit for backend
- Use Mock or NSubstitute for mocking dependencies
- Implement integration tests for API endpoints

## Security Guidelines
- **IMPORTANT**: Handle sensitive data carefully (API keys, private keys, etc.)
- Implement proper authentication and authorization
- Use secure communication protocols
- Validate all user inputs

## Database Guidelines
- Use PostgreSQL for relational data
- Use InfluxDB for time-series data (candles, metrics)
- Use MongoDB for document storage
- Implement proper migrations

## Orleans Integration (Co-Hosting)
- Use `IGrainFactory` instead of `IClusterClient` for co-hosting scenarios
- Orleans automatically provides `IGrainFactory` when using `UseOrleans()`
- Avoid circular dependency issues by not manually registering `IClusterClient`
- Use Orleans grains for high-availability trading bots

## Common Patterns

### Backend Service Pattern
```csharp
public class ExampleService : IExampleService
{
    private readonly IExampleRepository _repository;
    private readonly ILogger<ExampleService> _logger;

    public ExampleService(IExampleRepository repository, ILogger<ExampleService> logger)
    {
        _repository = repository;
        _logger = logger;
    }

    public async Task<Example> CreateExampleAsync(ExampleRequest request)
    {
        // Implementation
    }
}
```

### Frontend Component Pattern
```typescript
interface ComponentProps {
  isLoading: boolean;
  data: SomeType[];
}

function Component({ isLoading, data }: ComponentProps): JSX.Element {
  if (isLoading) return <Loader />;
  
  return (
    <div className="container mx-auto">
      {/* Component content */}
    </div>
  );
}

export default Component;
```

## File Structure Conventions
```
src/
├── Managing.Api/          # API Controllers
├── Managing.Application/  # Business Logic
├── Managing.Domain/       # Domain Models
├── Managing.Infrastructure/ # Data Access
└── Managing.WebApp/       # React Frontend
    └── src/
        ├── components/
        │   ├── atoms/     # Basic components
        │   ├── mollecules/ # Composite components
        │   └── organism/  # Complex components
        └── services/      # API calls
```

## Important Reminders
- Always implement methods you create
- Check existing code before creating new functionality
- Update multiple layers when necessary
- Build project after finishing edits
- Follow the controller → application → repository pattern
- Use existing components in mollecules/atoms before adding new libraries
- Use `IGrainFactory` for Orleans co-hosting (not `IClusterClient`)