# ShiftOps API Endpoints

**Last Updated:** 2026-01-09

Complete API reference for all 11 ShiftOps API endpoints, including request/response formats, error handling, and caching strategies.

## Main Analysis Endpoint

### POST `/v2/api/shiftops.php`

**Purpose:** Main analysis endpoint that orchestrates all analysis components.

**Request Method:** POST

**Request Headers:**

```
Content-Type: application/json
```

**Request Body:**

```json
{
  "place_id": "ChIJ...",
  "name": "Business Name",
  "formatted_address": "Street Address, City",
  "website": "https://example.com",
  "types": ["restaurant", "food", "point_of_interest"],
  "rating": 4.2,
  "user_ratings_total": 150,
  "photos": [...],
  "geometry": {
    "location": {
      "lat": 48.1351,
      "lng": 11.5820
    }
  },
  "opening_hours": {...},
  "business_status": "OPERATIONAL",
  "price_level": 2,
  "reviews": [...],
  "mode": "essential" // or "enhanced"
}
```

**Response Format:**

```json
{
  "success": true,
  "analysis": {
    "business_info": {...},
    "shiftops_score": {
      "total_score": 70,
      "grade": "B",
      "pillar_scores": {
        "scheduling_efficiency": 12,
        "absence_stability": 12,
        "time_tracking_hygiene": 17,
        "compliance_docs": 14,
        "payroll_readiness": 15
      },
      "data_completeness": {...}
    },
    "cost_savings": {...},
    "location_analysis": {...},
    "online_presence": {...},
    "context_data": {...},
    "recommendations": {...},
    "is_ordio_customer": false,
    "customer_match_confidence": 0
  },
  "mode": "essential",
  "timestamp": "2026-01-09 12:00:00",
  "request_id": "shiftops_abc123"
}
```

**Error Response:**

```json
{
  "success": true,
  "analysis": {...}, // Fallback data
  "fallback": true,
  "error_message": "Analysis completed with fallback data"
}
```

**Caching:** 1-hour TTL based on business data hash

**Code Location:** `v2/api/shiftops.php` (6,084 lines)

## Cost Savings Calculator

### Class: `ShiftOpsCostCalculator`

**Purpose:** Calculates potential cost savings, team size estimation, ROI analysis, and break-even calculations.

**Key Methods:**

- `calculateCostSavings($businessData, $shiftopsScores)` - Main calculation function
- `estimateTeamSize($businessData)` - Multi-factor team size estimation
- `calculateROI($businessData, $shiftopsScores, $teamSize, $industry, $monthlyLaborCost)` - ROI analysis
- `calculateBreakEven($monthlyLaborCost, $shiftopsScores, $industry, $teamSize, $businessData)` - Break-even analysis

**Team Size Estimation Factors:**

- Factor 1: Customer Volume Proxy (35% weight)
- Factor 2: Operating Hours (25% weight)
- Factor 3: Service Complexity (20% weight)
- Factor 4: Quality/Scale Indicator (15% weight)
- Factor 5: Review Velocity (5% weight)

**Code Location:** `v2/api/shiftops-cost-calculator.php` (922 lines)

## Competitive Analyzer

### Class: `ShiftOpsCompetitiveAnalyzer`

**Purpose:** Analyzes market positioning, competitor density, and growth potential.

**Key Methods:**

- `analyzeCompetitivePosition($businessData, $shiftopsScores)` - Main analysis function
- `getDetailedCompetitorAnalysis($businessData)` - Google Places Nearby Search
- `calculateMarketPosition($businessData, $competitorAnalysis)` - Market position calculation
- `assessGrowthPotential($businessData, $competitorAnalysis, $shiftopsScores)` - Growth potential assessment

**Competitor Analysis:**

- Uses Google Places Nearby Search API
- 1km radius for comprehensive analysis
- Maps business types to Google Places types
- Calculates average rating, review count, price level
- Categorizes competition density (low/medium/high)

**Code Location:** `v2/api/shiftops-competitive-analyzer.php` (910 lines)

## Recommendations Engine

### Class: `ShiftOpsRecommendationsEngine`

**Purpose:** Generates priority-ranked recommendations with ROI estimates.

**Key Methods:**

- `generateRecommendations($businessData, $shiftopsScores, $costSavings, $competitiveAnalysis)` - Main generation function
- `prioritizeRecommendations($recommendations)` - Priority ranking
- `addROIEstimates($recommendations, $costSavings)` - ROI calculation

**Recommendation Categories:**

- Quick Wins: High impact, low effort
- High Value: High impact, medium effort
- Strategic: High impact, high effort

**Code Location:** `v2/api/shiftops-recommendations-engine.php` (947 lines)

## Customer Matcher

### Class: `ShiftOpsCustomerMatcher`

**Purpose:** Identifies if a business is an Ordio customer.

**Matching Strategies (in order):**

1. Domain matching (exact domain match)
2. Exact name matching
3. Prefix matching (business name starts with customer name)
4. Fuzzy matching (similarity threshold)
5. Address matching (fuzzy address comparison)

**Customer List:** Loaded from `v2/data/ordio-customers.json` (3,018+ customers)

**Code Location:** `v2/api/shiftops-customer-matcher.php` (918 lines)

## HubSpot Integration

### POST `/v2/api/shiftops-hubspot.php`

**Purpose:** Submits lead data to HubSpot Forms API v3.

**Request Method:** POST

**Request Body:**

```json
{
  "email": "user@example.com",
  "firstname": "John",
  "lastname": "Doe",
  "phone": "+49123456789",
  "business_name": "Business Name",
  "place_id": "ChIJ...",
  "shiftops_score": 70,
  "grade": "B",
  "utm_source": "...",
  "utm_medium": "...",
  "utm_campaign": "..."
}
```

**Response:**

```json
{
  "success": true,
  "message": "Lead submitted successfully"
}
```

**HubSpot Configuration:**

- Form ID: `41d07332-6697-4daa-b27e-dd60515f9c0f`
- Portal ID: `145133546`

**Code Location:** `v2/api/shiftops-hubspot.php` (325 lines)

## NPS Survey

### POST `/v2/api/shiftops-nps.php`

**Purpose:** Submits NPS survey responses to HubSpot.

**Request Method:** POST

**Request Body:**

```json
{
  "nps_score": 8,
  "nps_feedback": "Optional feedback text",
  "business_name": "Business Name",
  "place_id": "ChIJ...",
  "shiftops_score": 70,
  "grade": "B"
}
```

**Validation:**

- NPS score must be integer 0-10
- Calculates NPS category (Promoter 9-10, Passive 7-8, Detractor 0-6)

**HubSpot Configuration:**

- Form ID: `804459f7-c18d-4da6-8a0b-a81f44bb8275`

**Code Location:** `v2/api/shiftops-nps.php` (238 lines)

## User Explanations

### Class: `ShiftOpsUserExplanations`

**Purpose:** Provides user-friendly score explanations.

**Key Methods:**

- `getScoreExplanation($totalScore, $grade)` - Overall score explanation
- `getPillarExplanation($pillarName, $score)` - Pillar-specific explanation
- `getGradeInterpretation($grade)` - Grade interpretation

**Code Location:** `v2/api/shiftops-user-explanations.php` (126 lines)

## Customer List Sync

### POST `/v2/api/shiftops-hubspot-customers.php`

**Purpose:** Syncs customer list from HubSpot to local JSON file.

**Functionality:**

- Fetches customers from HubSpot API
- Handles pagination
- Stores in `v2/data/ordio-customers.json`
- Conditional config loading (works without config file)

**Code Location:** `v2/api/shiftops-hubspot-customers.php` (547 lines)

## Health Check

### GET `/v2/api/shiftops-health-check.php`

**Purpose:** Diagnostic endpoint for customer matcher status.

**Response:**

```json
{
  "status": "ok",
  "customer_file_exists": true,
  "customer_count": 3018,
  "php_version": "8.1.0"
}
```

**Code Location:** `v2/api/shiftops-health-check.php` (123 lines)

## Test Matching

### POST `/v2/api/shiftops-test-matching.php`

**Purpose:** Test endpoint for customer matching debugging.

**Request Body:**

```json
{
  "business_name": "Test Business",
  "website": "https://example.com",
  "formatted_address": "Street Address"
}
```

**Response:** Detailed matching output with character-by-character comparison

**Code Location:** `v2/api/shiftops-test-matching.php` (172 lines)

## Error Handling

### Common Error Patterns

**API Timeout:**

- Essential mode: 15-second timeout
- Enhanced mode: 5-second timeout for competitive analysis
- Fallback data returned on timeout

**Missing Data:**

- Graceful degradation
- Fallback scores calculated
- Available data only displayed

**API Failures:**

- Try-catch blocks throughout
- Fallback responses with valid JSON structure
- Error logging to `logs/shiftops-debug.log`

## Caching Strategy

**Cache Key Generation:**

- MD5 hash of business data + mode
- Format: `shiftops_{hash}_{mode}`

**Cache Location:**

- File-based cache in `v2/cache/shiftops/`
- TTL: 1 hour

**Cache Invalidation:**

- Automatic after 1 hour
- Manual cache clearing available

## Related Documentation

- [Technical Implementation](03-technical-implementation.md) - Code structure
- [Scoring System](04-scoring-system.md) - Calculation details
- [System API Documentation](../../../systems/shiftops/SHIFTOPS_API_DOCUMENTATION.md) - Complete API reference
