# Project Workflow Analyzer

This utility analyzes project structure to identify user workflows, API endpoints, components, and navigation patterns for automated E2E test generation.

## Purpose
Scan and analyze project codebase to extract structural information needed for inferring user workflows and generating comprehensive E2E tests.

## Analysis Targets

### Frontend Analysis (Next.js/Nuxt.js/React/Vue)

#### 1. Route Structure Analysis
```bash
# Scan for route files and patterns
find src/pages src/app src/routes -name "*.tsx" -o -name "*.vue" -o -name "*.js" | head -20
```
Identifies:
- Page components and their routes
- Dynamic routes with parameters
- Nested routing structures
- Protected/authenticated routes
- API route handlers

#### 2. Component Hierarchy
```bash
# Find component files and their relationships
find src/components src/layouts -name "*.tsx" -o -name "*.vue" | head -20
```
Analyzes:
- Reusable components and their props
- Layout components and navigation
- Form components and their fields
- Modal and dialog components
- Data display components

#### 3. State Management
```bash
# Look for state management patterns
find src -name "*store*" -o -name "*context*" -o -name "*reducer*" | head -10
```
Discovers:
- Global state structure
- User authentication state
- Data fetching patterns
- Form state management

#### 4. Navigation Patterns
```bash
# Find navigation components and links
grep -r "useRouter\|Link\|navigate\|router" src --include="*.tsx" --include="*.js" | head -10
```
Maps:
- Navigation menus and links
- Programmatic navigation
- Route guards and redirects
- Breadcrumb patterns

### Backend Analysis (.NET Core/Node.js/Express)

#### 1. API Endpoint Discovery
```bash
# Find controller files and API routes
find . -name "*Controller.cs" -o -name "*controller.js" -o -name "routes.js" | head -20
```
Identifies:
- REST API endpoints and methods
- Controller actions and parameters
- Route patterns and middleware
- Authentication requirements

#### 2. Database Models
```bash
# Find model/entity definitions
find . -name "*Model.cs" -o -name "*Entity.cs" -o -name "models" -type d | head -10
```
Analyzes:
- Data models and relationships
- Entity properties and validation
- Database schema structure
- CRUD operation patterns

#### 3. Business Logic & Complex Patterns
```bash
# Find service and business logic files
find . -name "*Service.cs" -o -name "*service.js" -o -name "*Repository.cs" | head -15
```
Discovers:
- Business workflows and processes
- Service dependencies
- Data transformation logic
- Integration points
- Workflow state machines
- Multi-step business processes
- Transaction boundaries
- Event-driven patterns
- Saga patterns
- Compensation logic

## Workflow Inference Engine

### 1. Authentication Flow Detection
```javascript
// Pseudo-code for auth flow analysis
function analyzeAuthFlows(project) {
  const authPatterns = [
    'login', 'register', 'signup', 'signin', 'logout',
    'password-reset', 'forgot-password', 'verify-email'
  ];
  
  return {
    hasLogin: findFiles(authPatterns),
    authMethod: detectAuthMethod(), // JWT, session, OAuth
    protectedRoutes: findProtectedRoutes(),
    redirectPatterns: analyzeRedirects()
  };
}
```

### 2. CRUD Operation Mapping
```javascript
// Map CRUD operations for each entity
function mapCRUDOperations(models, controllers) {
  return models.map(model => ({
    entity: model.name,
    operations: {
      create: findCreateEndpoints(model, controllers),
      read: findReadEndpoints(model, controllers),
      update: findUpdateEndpoints(model, controllers),
      delete: findDeleteEndpoints(model, controllers)
    },
    frontendForms: findRelatedForms(model),
    listViews: findListComponents(model)
  }));
}
```

### 3. Comprehensive User Journey Reconstruction
```javascript
// Reconstruct all possible user journeys with edge cases
function reconstructUserJourneys(routes, components, businessLogic) {
  const journeys = [];
  
  // Authentication journey with all variations
  journeys.push({
    name: 'User Authentication - Complete Flow',
    variations: [
      // Happy path
      { 
        type: 'successful_login',
        steps: [
          { action: 'visit_login', route: '/login', validations: ['page_loads', 'form_visible'] },
          { action: 'enter_valid_credentials', component: 'LoginForm', data: 'valid_user_data' },
          { action: 'submit_login', endpoint: '/api/auth/login', expectedResponse: '200' },
          { action: 'redirect_dashboard', route: '/dashboard', validations: ['auth_token_set', 'user_data_loaded'] }
        ]
      },
      // Error scenarios
      {
        type: 'failed_login_invalid_credentials',
        steps: [
          { action: 'visit_login', route: '/login' },
          { action: 'enter_invalid_credentials', component: 'LoginForm', data: 'invalid_user_data' },
          { action: 'submit_login', endpoint: '/api/auth/login', expectedResponse: '401' },
          { action: 'display_error', validations: ['error_message_shown', 'form_remains_accessible'] }
        ]
      },
      {
        type: 'account_lockout',
        steps: [
          { action: 'attempt_multiple_failed_logins', iterations: 5 },
          { action: 'account_locked', validations: ['lockout_message', 'login_disabled'] },
          { action: 'wait_lockout_period', duration: 'configured_lockout_time' },
          { action: 'retry_login', expectedResult: 'success' }
        ]
      },
      // Edge cases
      {
        type: 'session_timeout_during_login',
        steps: [
          { action: 'start_login_process' },
          { action: 'simulate_session_timeout' },
          { action: 'complete_login', expectedResult: 'new_session_created' }
        ]
      }
    ]
  });
  
  // Complex business workflow journeys
  const businessWorkflows = extractBusinessWorkflows(businessLogic);
  businessWorkflows.forEach(workflow => {
    journeys.push(createComplexWorkflowJourney(workflow));
  });
  
  // Entity management journeys with exhaustive coverage
  const entities = extractEntities(routes, components);
  entities.forEach(entity => {
    journeys.push(createExhaustiveEntityJourney(entity));
  });
  
  // Integration and external service journeys
  const integrations = extractIntegrationPatterns(businessLogic);
  integrations.forEach(integration => {
    journeys.push(createIntegrationJourney(integration));
  });
  
  return journeys;
}

// Create exhaustive entity management journey
function createExhaustiveEntityJourney(entity) {
  return {
    name: `${entity.name} Management - Complete Lifecycle`,
    scenarios: [
      // List operations with all states
      {
        type: 'list_operations',
        variations: [
          { state: 'empty_list', validations: ['empty_state_message', 'create_button_available'] },
          { state: 'populated_list', validations: ['pagination', 'sorting', 'filtering'] },
          { state: 'loading_list', validations: ['loading_indicators', 'skeleton_screens'] },
          { state: 'error_loading', validations: ['error_messages', 'retry_mechanisms'] }
        ]
      },
      // Create operations with comprehensive coverage
      {
        type: 'create_operations',
        variations: [
          { case: 'valid_minimum_data', validations: ['required_fields_only', 'success_feedback'] },
          { case: 'valid_complete_data', validations: ['all_fields_populated', 'related_entities_linked'] },
          { case: 'validation_errors', validations: ['field_specific_errors', 'form_state_preserved'] },
          { case: 'duplicate_handling', validations: ['duplicate_detection', 'user_options_provided'] },
          { case: 'network_failure_during_create', validations: ['retry_mechanism', 'draft_preservation'] }
        ]
      },
      // Update operations with conflict resolution
      {
        type: 'update_operations',
        variations: [
          { case: 'concurrent_updates', validations: ['conflict_detection', 'merge_options'] },
          { case: 'partial_updates', validations: ['unchanged_field_preservation', 'optimistic_updates'] },
          { case: 'version_control', validations: ['version_tracking', 'rollback_capability'] },
          { case: 'permission_based_updates', validations: ['field_level_permissions', 'audit_trail'] }
        ]
      },
      // Delete operations with safety measures
      {
        type: 'delete_operations',
        variations: [
          { case: 'soft_delete', validations: ['recoverable_deletion', 'archive_functionality'] },
          { case: 'cascade_delete', validations: ['dependency_warning', 'related_data_cleanup'] },
          { case: 'bulk_delete', validations: ['batch_processing', 'progress_indicators'] },
          { case: 'permission_restricted_delete', validations: ['authorization_checks', 'audit_logging'] }
        ]
      }
    ]
  };
}

// Extract complex business workflows
function extractBusinessWorkflows(businessLogic) {
  return [
    {
      name: 'Multi-Step Approval Workflow',
      type: 'state_machine',
      states: ['draft', 'submitted', 'under_review', 'approved', 'rejected', 'published'],
      transitions: extractStateTransitions(businessLogic),
      validations: ['state_consistency', 'transition_permissions', 'rollback_capability']
    },
    {
      name: 'Payment Processing Workflow',
      type: 'saga_pattern',
      steps: ['initiate_payment', 'validate_payment', 'process_payment', 'confirm_payment'],
      compensations: extractCompensationLogic(businessLogic),
      validations: ['transaction_integrity', 'failure_recovery', 'idempotency']
    },
    {
      name: 'Document Lifecycle Management',
      type: 'event_driven',
      events: ['created', 'modified', 'approved', 'published', 'archived'],
      handlers: extractEventHandlers(businessLogic),
      validations: ['event_ordering', 'consistency', 'audit_trail']
    }
  ];
}
```

## Analysis Output Format

### Project Structure Summary
```json
{
  "project": {
    "type": "fullstack", // frontend, backend, fullstack
    "frontend": {
      "framework": "nextjs", // react, vue, nuxt
      "routing": "app-router", // pages, app-router, vue-router
      "stateManagement": "zustand", // redux, context, vuex
      "testingFramework": "playwright"
    },
    "backend": {
      "framework": "dotnet-core", // express, fastapi
      "database": "postgresql", // mysql, mongodb
      "authentication": "jwt", // session, oauth
      "testingFramework": "karate"
    }
  }
}
```

### Discovered Workflows
```json
{
  "workflows": [
    {
      "name": "User Authentication",
      "type": "authentication",
      "steps": [
        {
          "step": 1,
          "action": "navigate_to_login",
          "frontend": { "route": "/login", "component": "LoginPage" },
          "backend": null
        },
        {
          "step": 2,
          "action": "submit_credentials",
          "frontend": { "component": "LoginForm", "fields": ["email", "password"] },
          "backend": { "endpoint": "/api/auth/login", "method": "POST" }
        },
        {
          "step": 3,
          "action": "handle_success",
          "frontend": { "redirect": "/dashboard", "stateUpdate": "setUser" },
          "backend": { "response": "jwt_token", "statusCode": 200 }
        }
      ]
    },
    {
      "name": "Product Management",
      "type": "crud",
      "entity": "Product",
      "operations": {
        "create": {
          "frontend": { "route": "/products/new", "component": "ProductForm" },
          "backend": { "endpoint": "/api/products", "method": "POST" }
        },
        "read": {
          "frontend": { "route": "/products", "component": "ProductList" },
          "backend": { "endpoint": "/api/products", "method": "GET" }
        },
        "update": {
          "frontend": { "route": "/products/:id/edit", "component": "ProductForm" },
          "backend": { "endpoint": "/api/products/:id", "method": "PUT" }
        },
        "delete": {
          "frontend": { "action": "deleteConfirmation", "component": "DeleteModal" },
          "backend": { "endpoint": "/api/products/:id", "method": "DELETE" }
        }
      }
    }
  ]
}
```

### Navigation Map
```json
{
  "navigation": {
    "public": ["/", "/login", "/register", "/about"],
    "protected": ["/dashboard", "/profile", "/products", "/orders"],
    "admin": ["/admin", "/users", "/settings"],
    "api": ["/api/auth", "/api/users", "/api/products", "/api/orders"]
  },
  "flows": [
    {
      "from": "/login",
      "to": "/dashboard",
      "condition": "successful_authentication"
    },
    {
      "from": "/products",
      "to": "/products/:id",
      "condition": "product_selection"
    }
  ]
}
```

## Implementation Steps

### 1. Project Type Detection
```bash
# Detect project type and framework
if [[ -f "package.json" ]]; then
  FRONTEND_FRAMEWORK=$(grep -E "next|nuxt|react|vue" package.json)
fi

if [[ -f "*.csproj" ]] || [[ -f "Program.cs" ]]; then
  BACKEND_FRAMEWORK="dotnet"
elif [[ -f "requirements.txt" ]] || [[ -f "main.py" ]]; then
  BACKEND_FRAMEWORK="python"
fi
```

### 2. File System Scanning
```bash
# Comprehensive project scan
find . -type f \( -name "*.tsx" -o -name "*.ts" -o -name "*.js" -o -name "*.vue" -o -name "*.cs" -o -name "*.py" \) \
  | grep -v node_modules \
  | grep -v .git \
  | grep -v dist \
  | grep -v build
```

### 3. Pattern Recognition
Use regex and AST parsing to identify:
- Component definitions and props
- Route definitions and parameters
- API endpoint definitions
- Database model relationships
- Authentication patterns

### 4. Workflow Correlation
Cross-reference frontend and backend patterns to:
- Match forms with API endpoints
- Connect routes with components
- Identify data flow patterns
- Map user interactions to system responses

## Usage in E2E Generation
This analyzer provides the foundation data for:
- User story extraction
- Test scenario generation
- Mock data creation
- Test organization structure
- Coverage planning

The output feeds directly into the `user-story-extractor.md` utility for intelligent test generation.