# implement-api-changes

## When to Use

Use this command when:
- `ManagingApi.ts` has been updated (regenerated from backend)
- New API endpoints or types have been added to the backend
- You need to implement frontend features that use the new API changes

## Prerequisites

- Git repository initialized
- `ManagingApi.ts` file exists at `src/Managing.WebApp/src/generated/ManagingApi.ts`
- Backend API is running and accessible
- Frontend project structure is intact

## Execution Steps

### Step 1: Check if ManagingApi.ts Has Changed

Check git status for changes to ManagingApi.ts:

Run: `git status --short src/Managing.WebApp/src/generated/ManagingApi.ts`

**If file is modified:**
- Continue to Step 2

**If file is not modified:**
- Check if file exists: `test -f src/Managing.WebApp/src/generated/ManagingApi.ts`
- If missing: Error "ManagingApi.ts not found. Please regenerate it first."
- If exists but not modified: Inform "No changes detected in ManagingApi.ts. Nothing to implement."
- **STOP**: No changes to process

### Step 2: Analyze Git Changes

Get the diff to see what was added/changed:

Run: `git diff HEAD src/Managing.WebApp/src/generated/ManagingApi.ts`

**Analyze the diff to identify:**
- New client classes (e.g., `export class JobClient`)
- New methods in existing clients (e.g., `backtest_NewMethod()`)
- New interfaces/types (e.g., `export interface NewType`)
- New enums (e.g., `export enum NewEnum`)
- Modified existing types/interfaces

**Extract key information:**
- Client class names (e.g., `JobClient`, `BacktestClient`)
- Method names and signatures (e.g., `job_GetJobs(page: number, pageSize: number)`)
- Request/Response types (e.g., `PaginatedJobsResponse`, `JobStatus`)
- HTTP methods (GET, POST, PUT, DELETE)

### Step 3: Determine Frontend Implementation Needs

Based on the changes, determine what needs to be implemented:

**For new client classes:**
- Create or update hooks/services to use the new client
- Identify which pages/components should use the new API
- Determine data fetching patterns (useQuery, useMutation)

**For new methods in existing clients:**
- Find existing components using that client
- Determine if new UI components are needed
- Check if existing components need updates

**For new types/interfaces:**
- Identify where these types should be used
- Check if new form components are needed
- Determine if existing components need type updates

**Common patterns to look for:**
- `*Client` classes → Create hooks in `src/Managing.WebApp/src/hooks/`
- `Get*` methods → Use `useQuery` for data fetching
- `Post*`, `Put*`, `Delete*` methods → Use `useMutation` for mutations
- `Paginated*` responses → Create paginated table components
- `*Request` types → Create form components

### Step 4: Search Existing Frontend Code

Search for related code to understand context:

**For new client classes:**
- Search: `grep -r "Client" src/Managing.WebApp/src --include="*.tsx" --include="*.ts" | grep -i "similar"`
- Look for similar client usage patterns
- Find related pages/components

**For new methods:**
- Search: `grep -r "ClientName" src/Managing.WebApp/src --include="*.tsx" --include="*.ts"`
- Find where the client is already used
- Check existing patterns

**For new types:**
- Search: `grep -r "TypeName" src/Managing.WebApp/src --include="*.tsx" --include="*.ts"`
- Find if type is referenced anywhere
- Check related components

### Step 5: Implement Frontend Features

Based on analysis, implement the frontend code:

#### 5.1: Create/Update API Hooks

**For new client classes:**
- Create hook file: `src/Managing.WebApp/src/hooks/use[ClientName].tsx`
- Pattern:
```typescript
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { [ClientName] } from '../generated/ManagingApi'
import { useApiUrlStore } from '../app/store/apiUrlStore'

export const use[ClientName] = () => {
  const { apiUrl } = useApiUrlStore()
  const queryClient = useQueryClient()
  const client = new [ClientName]({}, apiUrl)
  
  // Add useQuery hooks for GET methods
  // Add useMutation hooks for POST/PUT/DELETE methods
  
  return { /* hooks */ }
}
```

**For new methods in existing clients:**
- Update existing hook file
- Add new useQuery/useMutation hooks following existing patterns

#### 5.2: Create/Update Components

**For GET methods (data fetching):**
- Create components that use `useQuery` with the new hook
- Follow existing component patterns (e.g., tables, lists, detail views)
- Use TypeScript types from ManagingApi.ts

**For POST/PUT/DELETE methods (mutations):**
- Create form components or action buttons
- Use `useMutation` with proper error handling
- Show success/error toasts
- Invalidate relevant queries after mutations

**For paginated responses:**
- Create paginated table components
- Use existing pagination patterns from the codebase
- Include sorting, filtering if supported

#### 5.3: Create/Update Pages

**If new major feature:**
- Create new page in `src/Managing.WebApp/src/pages/`
- Add routing if needed
- Follow existing page structure patterns

**If extending existing feature:**
- Update existing page component
- Add new sections/components as needed

#### 5.4: Update Types and Interfaces

**If new types are needed:**
- Import types from ManagingApi.ts
- Use types in component props/interfaces
- Ensure type safety throughout

### Step 6: Follow Frontend Patterns

**Always follow these patterns:**

1. **API Client Usage:**
   - Get `apiUrl` from `useApiUrlStore()`
   - Create client: `new ClientName({}, apiUrl)`
   - Use in hooks, not directly in components

2. **Data Fetching:**
   - Use `useQuery` from `@tanstack/react-query`
   - Set proper `queryKey` for caching
   - Handle loading/error states

3. **Mutations:**
   - Use `useMutation` from `@tanstack/react-query`
   - Invalidate related queries after success
   - Show user-friendly error messages

4. **Component Structure:**
   - Use functional components with TypeScript
   - Place static content at file end
   - Use DaisyUI/Tailwind for styling
   - Wrap in Suspense with fallback

5. **Error Handling:**
   - Catch errors in services/hooks
   - Return user-friendly error messages
   - Use error boundaries for unexpected errors

### Step 7: Verify Implementation

**Check for:**
- TypeScript compilation errors: `cd src/Managing.WebApp && npm run type-check` (if available)
- Import errors: All imports resolve correctly
- Type safety: All types from ManagingApi.ts are used correctly
- Pattern consistency: Follows existing codebase patterns

**If errors found:**
- Fix TypeScript errors
- Fix import paths
- Ensure types match API definitions
- **STOP** if critical errors cannot be resolved

### Step 8: Test Integration Points

**Verify:**
- API client is instantiated correctly
- Query keys are unique and appropriate
- Mutations invalidate correct queries
- Error handling works properly
- Loading states are handled

## Error Handling

**If ManagingApi.ts doesn't exist:**
- Check path: `src/Managing.WebApp/src/generated/ManagingApi.ts`
- If missing: Inform user to regenerate using NSwag
- Suggest: Run backend API, then `cd src/Managing.Nswag && dotnet build`

**If git diff is empty:**
- Check if file is staged: `git diff --cached`
- Check if file is untracked: `git status`
- If untracked: Use `git diff /dev/null src/Managing.WebApp/src/generated/ManagingApi.ts`

**If cannot determine changes:**
- Show the diff output to user
- Ask user to clarify what needs to be implemented
- Proceed with manual implementation guidance

**If frontend patterns unclear:**
- Search for similar implementations in codebase
- Follow closest matching pattern
- Ask user for clarification if needed

**If TypeScript errors:**
- Check type definitions in ManagingApi.ts
- Ensure imports are correct
- Verify types match API response structure
- Fix type mismatches

## Example Execution

**User input:** `/implement-api-changes`

**AI execution:**

1. Check changes: `git status --short src/Managing.WebApp/src/generated/ManagingApi.ts` → Modified
2. Analyze diff: `git diff HEAD src/Managing.WebApp/src/generated/ManagingApi.ts`
   - Found: New `JobClient` class
   - Found: Methods: `job_GetJobs()`, `job_GetJobStatus()`, `job_CancelJob()`
   - Found: Types: `PaginatedJobsResponse`, `BacktestJobStatusResponse`, `JobStatus` enum
3. Determine needs:
   - Create `useJobClient` hook
   - Create jobs list page/component
   - Create job status component
   - Add cancel job functionality
4. Search existing code:
   - Found similar pattern: `useBacktestClient` hook
   - Found similar page: `backtestPage` structure
5. Implement:
   - Create `src/Managing.WebApp/src/hooks/useJobClient.tsx`
   - Create `src/Managing.WebApp/src/pages/jobsPage/jobs.tsx`
   - Create `src/Managing.WebApp/src/components/mollecules/JobStatusCard.tsx`
   - Update routing if needed
6. Verify: Check TypeScript errors, imports, types
7. Success: "✅ Frontend implementation completed for Job API changes"

**If new method in existing client:**

1-2. Same as above
3. Found: New method `backtest_GetJobStatus(jobId: string)` in `BacktestClient`
4. Search: Found `BacktestClient` used in `backtestPage`
5. Implement:
   - Update existing `useBacktestClient` hook
   - Add job status display to backtest page
   - Add polling for job status updates
6. Verify and complete

## Important Notes

- ✅ **Always use TanStack Query** - Never use useEffect for data fetching
- ✅ **Follow existing patterns** - Match codebase style and structure
- ✅ **Type safety first** - Use types from ManagingApi.ts
- ✅ **Error handling** - Services throw user-friendly errors
- ✅ **Query invalidation** - Invalidate related queries after mutations
- ✅ **Component structure** - Functional components, static content at end
- ✅ **Styling** - Use DaisyUI/Tailwind, mobile-first approach
- ⚠️ **Don't update ManagingApi.ts** - It's auto-generated
- ⚠️ **Check existing code** - Reuse components/hooks when possible
- ⚠️ **Test integration** - Verify API calls work correctly
- 📦 **Hook location**: `src/Managing.WebApp/src/hooks/`
- 🔧 **Component location**: `src/Managing.WebApp/src/components/`
- 📄 **Page location**: `src/Managing.WebApp/src/pages/`
- 🗄️ **API types**: Import from `src/Managing.WebApp/src/generated/ManagingApi.ts`

