# Role-Based Access Control (RBAC) Analysis Report
## Bakery-IA Microservices Platform

**Generated:** 2025-10-12
**Status:** Analysis Complete - Implementation Recommendations

---

## Executive Summary

This document provides a comprehensive analysis of the Role-Based Access Control (RBAC) requirements for the Bakery-IA platform, which consists of 15 microservices with 250+ API endpoints. The analysis identifies user roles, tenant roles, subscription tiers, and provides detailed access control recommendations for each service.

### Key Findings

- **4 User Roles** with hierarchical permissions: Viewer → Member → Admin → Owner
- **3 Subscription Tiers** with feature gating: Starter → Professional → Enterprise
- **250+ API Endpoints** requiring access control
- **Mixed Implementation Status**: Some endpoints have decorators, many need implementation
- **Tenant Isolation**: All services enforce tenant-level data isolation

---

## 1. Role System Architecture

### 1.1 User Role Hierarchy

The platform implements a hierarchical role system defined in [`shared/auth/access_control.py`](shared/auth/access_control.py):

```python
class UserRole(Enum):
    VIEWER = "viewer"    # Read-only access
    MEMBER = "member"    # Read + basic write operations
    ADMIN = "admin"      # Full operational access
    OWNER = "owner"      # Full control including tenant settings
```

**Role Hierarchy (Higher = More Permissions):**
1. **Viewer** (Level 1) - Read-only access to tenant data
2. **Member** (Level 2) - Can create and edit operational data
3. **Admin** (Level 3) - Can manage users, delete data, configure settings
4. **Owner** (Level 4) - Full control, billing, tenant deletion

### 1.2 Subscription Tier System

Subscription tiers control feature access defined in [`shared/auth/access_control.py`](shared/auth/access_control.py):

```python
class SubscriptionTier(Enum):
    STARTER = "starter"           # Basic features
    PROFESSIONAL = "professional" # Advanced analytics & ML
    ENTERPRISE = "enterprise"     # Full feature set + priority support
```

**Tier Features:**

| Feature | Starter | Professional | Enterprise |
|---------|---------|--------------|------------|
| Basic Inventory | ✓ | ✓ | ✓ |
| Basic Sales | ✓ | ✓ | ✓ |
| Basic Recipes | ✓ | ✓ | ✓ |
| ML Forecasting | ✓ | ✓ | ✓ |
| Advanced Analytics | ✗ | ✓ | ✓ |
| Custom Reports | ✗ | ✓ | ✓ |
| Production Optimization | ✓ | ✓ | ✓ |
| Multi-location | 1 | 2 | Unlimited |
| API Access | ✗ | ✗ | ✓ |
| Priority Support | ✗ | ✗ | ✓ |
| Max Users | 5 | 20 | Unlimited |
| Max Products | 50 | 500 | Unlimited |

### 1.3 Tenant Member Roles

Defined in [`services/tenant/app/models/tenants.py`](services/tenant/app/models/tenants.py):

```python
class TenantMember(Base):
    role = Column(String(50), default="member")  # owner, admin, member, viewer
```

**Permission Matrix by Action:**

| Action Type | Viewer | Member | Admin | Owner |
|-------------|--------|--------|-------|-------|
| Read data | ✓ | ✓ | ✓ | ✓ |
| Create records | ✗ | ✓ | ✓ | ✓ |
| Update records | ✗ | ✓ | ✓ | ✓ |
| Delete records | ✗ | ✗ | ✓ | ✓ |
| Manage users | ✗ | ✗ | ✓ | ✓ |
| Configure settings | ✗ | ✗ | ✓ | ✓ |
| Billing/subscription | ✗ | ✗ | ✗ | ✓ |
| Delete tenant | ✗ | ✗ | ✗ | ✓ |

---

## 2. Access Control Implementation

### 2.1 Available Decorators

The platform provides these decorators in [`shared/auth/access_control.py`](shared/auth/access_control.py):

```python
# Subscription tier enforcement
@require_subscription_tier(['professional', 'enterprise'])
@enterprise_tier_required  # Convenience decorator
@analytics_tier_required   # For analytics endpoints

# Role-based enforcement
@require_user_role(['admin', 'owner'])
@admin_role_required  # Convenience decorator
@owner_role_required  # Convenience decorator

# Combined enforcement
@require_tier_and_role(['professional', 'enterprise'], ['admin', 'owner'])
```

### 2.2 FastAPI Dependencies

Available in [`shared/auth/tenant_access.py`](shared/auth/tenant_access.py):

```python
# Basic authentication
current_user: Dict = Depends(get_current_user_dep)

# Tenant access verification
tenant_id: str = Depends(verify_tenant_access_dep)

# Resource permission check
tenant_id: str = Depends(verify_tenant_permission_dep(resource, action))
```

### 2.3 Current Implementation Status

**Implemented:**
- ✓ JWT authentication across all services
- ✓ Tenant isolation via path parameters
- ✓ Basic admin role checks in auth service
- ✓ Subscription tier checking framework

**Needs Implementation:**
- ✗ Role decorators on most service endpoints
- ✗ Subscription tier enforcement on premium features
- ✗ Fine-grained resource permissions
- ✗ Audit logging for sensitive operations

---

## 3. RBAC Matrix by Service

### 3.1 AUTH SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 17

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/register` | POST | Public | Any | No auth required |
| `/login` | POST | Public | Any | No auth required |
| `/refresh` | POST | Authenticated | Any | Valid refresh token |
| `/verify` | POST | Authenticated | Any | Valid access token |
| `/logout` | POST | Authenticated | Any | Valid access token |
| `/change-password` | POST | Authenticated | Any | Own account only |
| `/profile` | GET | Authenticated | Any | Own account only |
| `/profile` | PUT | Authenticated | Any | Own account only |
| `/verify-email` | POST | Public | Any | Email verification token |
| `/reset-password` | POST | Public | Any | Reset token required |
| `/me` | GET | Authenticated | Any | Own account only |
| `/me` | PUT | Authenticated | Any | Own account only |
| `/delete/{user_id}` | DELETE | **Admin** | Any | **🔴 CRITICAL** Admin only |
| `/delete/{user_id}/deletion-preview` | GET | **Admin** | Any | Admin only |
| `/me/onboarding/*` | * | Authenticated | Any | Own account only |
| `/{user_id}/onboarding/progress` | GET | **Admin** | Any | Admin/service only |
| `/health` | GET | Public | Any | No auth required |

**🔴 Critical Operations:**
- User deletion requires admin role + audit logging
- Password changes should enforce strong password policy
- Email verification prevents account takeover

**Recommendations:**
- ✅ IMPLEMENTED: Admin role check on deletion
- 🔧 ADD: Rate limiting on login/register (3-5 attempts)
- 🔧 ADD: Audit log for user deletion
- 🔧 ADD: MFA for admin accounts
- 🔧 ADD: Password strength validation
- 🔧 ADD: Session management (concurrent login limits)

---

### 3.2 TENANT SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 35+

#### Tenant Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}` | GET | **Viewer** | Any | Tenant member |
| `/{tenant_id}` | PUT | **Admin** | Any | Admin+ only |
| `/register` | POST | Authenticated | Any | Creates new tenant, user becomes owner |
| `/{tenant_id}/deactivate` | POST | **Owner** | Any | **🔴 CRITICAL** Owner only |
| `/{tenant_id}/activate` | POST | **Owner** | Any | Owner only |
| `/subdomain/{subdomain}` | GET | Public | Any | Public discovery |
| `/search` | GET | Public | Any | Public discovery |
| `/nearby` | GET | Public | Any | Geolocation-based discovery |
| `/users/{user_id}` | GET | Authenticated | Any | Own tenants only |
| `/user/{user_id}/owned` | GET | Authenticated | Any | Own tenants only |
| `/statistics` | GET | **Platform Admin** | Any | **🔴 CRITICAL** Platform-wide stats |

#### Team Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/members` | GET | **Viewer** | Any | Tenant member |
| `/{tenant_id}/members` | POST | **Admin** | Any | Admin+ can invite users |
| `/{tenant_id}/members/{user_id}/role` | PUT | **Admin** | Any | Admin+ can change roles (except owner) |
| `/{tenant_id}/members/{user_id}` | DELETE | **Admin** | Any | **🔴** Admin+ can remove members |
| `/{tenant_id}/my-access` | GET | Authenticated | Any | Own access info |
| `/{tenant_id}/access/{user_id}` | GET | Service | Any | Internal service verification |

#### Subscription Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/subscriptions/{tenant_id}/limits` | GET | **Viewer** | Any | Tenant member |
| `/subscriptions/{tenant_id}/usage` | GET | **Viewer** | Any | Tenant member |
| `/subscriptions/{tenant_id}/can-add-*` | GET | **Admin** | Any | Pre-check for admins |
| `/subscriptions/{tenant_id}/features/{feature}` | GET | **Viewer** | Any | Feature availability check |
| `/subscriptions/{tenant_id}/validate-upgrade/{plan}` | GET | **Owner** | Any | Owner can view upgrade options |
| `/subscriptions/{tenant_id}/upgrade` | POST | **Owner** | Any | **🔴 CRITICAL** Owner only |
| `/subscriptions/{tenant_id}/cancel` | POST | **Owner** | Any | **🔴 CRITICAL** Owner only |
| `/subscriptions/{tenant_id}/invoices` | GET | **Owner** | Any | Billing info for owner |
| `/subscriptions/register-with-subscription` | POST | Authenticated | Any | New tenant with payment |
| `/plans` | GET | Public | Any | Public plan information |

#### Webhooks & Internal

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/webhooks/stripe` | POST | Service | Any | Stripe signature verification |
| `/webhooks/generic` | POST | Service | Any | Webhook secret verification |
| `/clone` | POST | Service | Any | **Internal only** - Demo cloning |
| `/{tenant_id}/model-status` | PUT | Service | Any | **Internal only** - ML service |

**🔴 Critical Operations:**
- Tenant deactivation/deletion
- Subscription changes and cancellation
- Role modifications (prevent owner role changes)
- Member removal

**Recommendations:**
- ✅ IMPLEMENTED: Role checks for member management
- 🔧 ADD: Prevent removing the last owner
- 🔧 ADD: Prevent owner from changing their own role
- 🔧 ADD: Subscription change confirmation (email/2FA)
- 🔧 ADD: Grace period before tenant deletion
- 🔧 ADD: Audit log for all tenant modifications
- 🔧 ADD: Rate limiting on team invitations

---

### 3.3 SALES SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 10+

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/sales` | GET | **Viewer** | Any | Read sales data |
| `/{tenant_id}/sales` | POST | **Member** | Any | Create sales record |
| `/{tenant_id}/sales/{id}` | GET | **Viewer** | Any | Read single record |
| `/{tenant_id}/sales/{id}` | PUT | **Member** | Any | Update sales record |
| `/{tenant_id}/sales/{id}` | DELETE | **Admin** | Any | **🔴** Delete sales record |
| `/{tenant_id}/sales/import` | POST | **Admin** | Any | Bulk import |
| `/{tenant_id}/sales/export` | GET | **Member** | Any | Export data |
| `/{tenant_id}/products` | GET | **Viewer** | Any | Product catalog |
| `/{tenant_id}/products` | POST | **Admin** | Any | Add product |
| `/{tenant_id}/products/{id}` | PUT | **Admin** | Any | Update product |
| `/{tenant_id}/products/{id}` | DELETE | **Admin** | Any | **🔴** Delete product |
| `/{tenant_id}/analytics/*` | GET | **Viewer** | **Professional** | **💰** Advanced analytics |
| `/clone` | POST | Service | Any | **Internal only** |

**🔴 Critical Operations:**
- Sales record deletion (affects financial reports)
- Product deletion (affects historical data)
- Bulk imports (data integrity)

**💰 Premium Features:**
- Advanced analytics dashboards
- Custom reporting
- Sales forecasting integration
- Export to external systems

**Recommendations:**
- 🔧 ADD: Soft delete for sales records (audit trail)
- 🔧 ADD: Subscription tier check on analytics endpoints
- 🔧 ADD: Prevent deletion of products with sales history
- 🔧 ADD: Import validation and preview
- 🔧 ADD: Rate limiting on bulk operations

---

### 3.4 INVENTORY SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 30+

#### Ingredients Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/ingredients` | GET | **Viewer** | Any | List ingredients |
| `/{tenant_id}/ingredients` | POST | **Member** | Any | Add ingredient |
| `/{tenant_id}/ingredients/{id}` | GET | **Viewer** | Any | View ingredient |
| `/{tenant_id}/ingredients/{id}` | PUT | **Member** | Any | Update ingredient |
| `/{tenant_id}/ingredients/{id}` | DELETE | **Admin** | Any | **🔴** Delete ingredient |

#### Stock Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/stock` | GET | **Viewer** | Any | View stock levels |
| `/{tenant_id}/stock` | POST | **Member** | Any | Add stock entry |
| `/{tenant_id}/stock/{id}` | PUT | **Member** | Any | Update stock entry |
| `/{tenant_id}/stock/{id}` | DELETE | **Admin** | Any | **🔴** Delete stock entry |
| `/{tenant_id}/stock/adjustments` | POST | **Admin** | Any | **🔴** Manual stock adjustment |
| `/{tenant_id}/stock/low-stock-alerts` | GET | **Viewer** | Any | View alerts |

#### Food Safety & Compliance

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/compliance` | GET | **Viewer** | Any | View compliance records |
| `/{tenant_id}/compliance` | POST | **Member** | Any | Record compliance check |
| `/{tenant_id}/compliance/{id}` | PUT | **Member** | Any | Update compliance record |
| `/{tenant_id}/compliance/{id}` | DELETE | **Admin** | Any | **🔴** Delete compliance record |
| `/{tenant_id}/temperature-logs` | GET | **Viewer** | Any | View temperature logs |
| `/{tenant_id}/temperature-logs` | POST | **Member** | Any | Record temperature |
| `/{tenant_id}/safety-alerts` | GET | **Viewer** | Any | View safety alerts |
| `/{tenant_id}/safety-alerts/{id}/acknowledge` | POST | **Member** | Any | Acknowledge alert |

#### Analytics & Dashboard

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/dashboard` | GET | **Viewer** | Any | Basic dashboard |
| `/{tenant_id}/analytics/*` | GET | **Viewer** | **Professional** | **💰** Advanced analytics |
| `/{tenant_id}/reports/waste-analysis` | GET | **Viewer** | **Professional** | **💰** Waste analysis |
| `/{tenant_id}/reports/cost-analysis` | GET | **Admin** | **Professional** | **💰** Cost analysis (sensitive) |

**🔴 Critical Operations:**
- Ingredient deletion (affects recipes)
- Manual stock adjustments (inventory manipulation)
- Compliance record deletion (regulatory violation)
- Food safety alert dismissal

**💰 Premium Features:**
- Advanced inventory analytics
- Waste analysis and optimization
- Cost tracking and analysis
- Automated reorder recommendations
- FIFO optimization

**Recommendations:**
- 🔧 ADD: Prevent deletion of ingredients used in recipes
- 🔧 ADD: Audit log for all stock adjustments
- 🔧 ADD: Compliance record retention (cannot delete, only archive)
- 🔧 ADD: Food safety alerts require investigation notes
- 🔧 ADD: Subscription tier checks on analytics
- 🔧 ADD: Role check: only Admin+ can see cost data

---

### 3.5 PRODUCTION SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 40+

#### Production Batches

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/batches` | GET | **Viewer** | Any | View batches |
| `/{tenant_id}/batches` | POST | **Member** | Any | Create batch |
| `/{tenant_id}/batches/{id}` | GET | **Viewer** | Any | View batch details |
| `/{tenant_id}/batches/{id}` | PUT | **Member** | Any | Update batch |
| `/{tenant_id}/batches/{id}` | DELETE | **Admin** | Any | **🔴** Delete batch |
| `/{tenant_id}/batches/{id}/status` | PUT | **Member** | Any | Update batch status |
| `/{tenant_id}/batches/active` | GET | **Viewer** | Any | View active batches |

#### Production Schedules

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/schedules` | GET | **Viewer** | Any | View schedules |
| `/{tenant_id}/schedules` | POST | **Admin** | Any | Create schedule |
| `/{tenant_id}/schedules/{id}` | PUT | **Admin** | Any | Update schedule |
| `/{tenant_id}/schedules/{id}` | DELETE | **Admin** | Any | **🔴** Delete schedule |
| `/{tenant_id}/schedule-batch` | POST | **Member** | Any | Schedule production |
| `/{tenant_id}/start-batch` | POST | **Member** | Any | Start batch |
| `/{tenant_id}/complete-batch` | POST | **Member** | Any | Complete batch |

#### Production Operations

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/capacity/check` | GET | **Viewer** | Any | Capacity planning (basic) |
| `/{tenant_id}/capacity/optimize` | POST | **Admin** | Any | Basic optimization |
| `/{tenant_id}/bottlenecks` | GET | **Viewer** | Any | Basic bottleneck identification |
| `/{tenant_id}/resource-utilization` | GET | **Viewer** | Any | Basic resource metrics |
| `/{tenant_id}/adjust-schedule` | POST | **Admin** | Any | Adjust schedule |
| `/{tenant_id}/efficiency-metrics` | GET | **Viewer** | Any | Basic efficiency metrics |

#### Quality Control

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/quality-templates` | GET | **Viewer** | Any | View templates |
| `/{tenant_id}/quality-templates` | POST | **Admin** | Any | Create template |
| `/{tenant_id}/quality-templates/{id}` | PUT | **Admin** | Any | Update template |
| `/{tenant_id}/quality-templates/{id}` | DELETE | **Admin** | Any | Delete template |
| `/{tenant_id}/quality-check` | POST | **Member** | Any | Record quality check |
| `/{tenant_id}/batches/{id}/quality-checks` | POST | **Member** | Any | Batch quality check |

#### Analytics

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/production-volume` | GET | **Viewer** | Any | Basic production volume metrics |
| `/{tenant_id}/efficiency-trends` | GET | **Viewer** | **Professional** | **💰** Historical efficiency trends |
| `/{tenant_id}/quality-metrics` | GET | **Viewer** | Any | Basic quality metrics |
| `/{tenant_id}/equipment-performance` | GET | **Admin** | **Professional** | **💰** Detailed equipment metrics |
| `/{tenant_id}/capacity-analysis` | GET | **Admin** | **Professional** | **💰** Advanced capacity analysis |
| `/{tenant_id}/waste-analysis` | GET | **Viewer** | **Professional** | **💰** Detailed waste analysis |

**🔴 Critical Operations:**
- Batch deletion (affects inventory and tracking)
- Schedule changes (affects production timeline)
- Quality check modifications (compliance)
- Manual schedule adjustments (operational impact)

**💰 Premium Features:**
- **Starter Tier:**
  - Basic capacity checking
  - Simple bottleneck identification
  - Basic resource utilization
  - Simple optimization suggestions
  - Current day metrics only
- **Professional Tier:**
  - Historical efficiency trends
  - Detailed equipment performance tracking
  - Advanced capacity analysis
  - Waste analysis and optimization
  - Predictive alerts (30-day history)
  - Advanced optimization algorithms
- **Enterprise Tier:**
  - Predictive maintenance
  - Multi-location production optimization
  - Custom optimization parameters
  - Real-time production monitoring
  - Unlimited historical data
  - AI-powered scheduling

**Recommendations:**
- ✅ AVAILABLE TO ALL TIERS: Basic production optimization
- 🔧 ADD: Optimization depth limits per tier (basic suggestions Starter, advanced Professional)
- 🔧 ADD: Historical data limits (7 days Starter, 90 days Professional, unlimited Enterprise)
- 🔧 ADD: Prevent deletion of completed batches (audit trail)
- 🔧 ADD: Schedule change approval for large adjustments
- 🔧 ADD: Quality check cannot be deleted, only corrected
- 🔧 ADD: Advanced analytics only for Professional+
- 🔧 ADD: Audit log for all production schedule changes

---

### 3.6 FORECASTING SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 12+

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/forecasts` | GET | **Viewer** | Any | View forecasts (basic) |
| `/{tenant_id}/forecasts` | POST | **Admin** | Any | Generate forecast (basic) |
| `/{tenant_id}/forecasts/{id}` | GET | **Viewer** | Any | View single forecast |
| `/{tenant_id}/forecasts/generate` | POST | **Admin** | Any | Trigger ML forecast |
| `/{tenant_id}/forecasts/bulk-generate` | POST | **Admin** | Any | Bulk forecast generation |
| `/{tenant_id}/scenarios` | GET | **Viewer** | **Enterprise** | **💰** View scenarios |
| `/{tenant_id}/scenarios` | POST | **Admin** | **Enterprise** | **💰** Create scenario |
| `/{tenant_id}/scenarios/{id}/analyze` | POST | **Admin** | **Enterprise** | **💰** What-if analysis |
| `/{tenant_id}/scenarios/compare` | POST | **Admin** | **Enterprise** | **💰** Compare scenarios |
| `/{tenant_id}/analytics/accuracy` | GET | **Viewer** | **Professional** | **💰** Model accuracy metrics |
| `/{tenant_id}/analytics/performance` | GET | **Admin** | **Professional** | **💰** Model performance |
| `/alert-metrics` | GET | Service | Any | **Internal only** |

**🔴 Critical Operations:**
- Forecast generation (consumes ML resources)
- Bulk operations (resource intensive)
- Scenario creation (computational cost)

**💰 Premium Features:**
- **Starter Tier:**
  - Basic ML forecasting (limited to 7-day forecasts)
  - View basic forecast data
  - Simple demand predictions
- **Professional Tier:**
  - Extended forecasting (30+ days)
  - Historical forecast data
  - Accuracy metrics and analytics
  - Advanced model performance tracking
- **Enterprise Tier:**
  - Advanced scenario modeling
  - What-if analysis
  - Scenario comparison
  - Custom ML parameters
  - Multi-location forecasting

**Recommendations:**
- ✅ AVAILABLE TO ALL TIERS: Basic forecasting functionality
- 🔧 ADD: Forecast horizon limits per tier (7 days Starter, 30+ Professional)
- 🔧 ADD: Rate limiting on forecast generation based on tier (ML cost)
- 🔧 ADD: Quota limits per subscription tier (Starter: 10/day, Professional: 100/day, Enterprise: unlimited)
- 🔧 ADD: Scenario modeling only for Enterprise
- 🔧 ADD: Advanced analytics only for Professional+
- 🔧 ADD: Audit log for manual forecast overrides

---

### 3.7 TRAINING SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 15+ (including WebSocket)

#### Training Jobs

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/training-jobs` | GET | **Admin** | Any | View training jobs |
| `/{tenant_id}/training-jobs` | POST | **Admin** | Any | Start training (basic) |
| `/{tenant_id}/training-jobs/{id}` | GET | **Admin** | Any | View job status |
| `/{tenant_id}/training-jobs/{id}/cancel` | POST | **Admin** | Any | Cancel training |
| `/{tenant_id}/training-jobs/retrain` | POST | **Admin** | Any | **🔴** Retrain model |

#### Model Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/models` | GET | **Admin** | Any | View models |
| `/{tenant_id}/models/{id}` | GET | **Admin** | Any | View model details |
| `/{tenant_id}/models/{id}/deploy` | POST | **Admin** | Any | **🔴** Deploy model |
| `/{tenant_id}/models/{id}/artifacts` | GET | **Admin** | **Enterprise** | **💰** Download artifacts (Enterprise only)

#### Monitoring

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/monitoring/circuit-breakers` | GET | **Platform Admin** | Any | **🔴** Platform monitoring |
| `/monitoring/circuit-breakers/{name}/reset` | POST | **Platform Admin** | Any | **🔴** Reset breaker |
| `/monitoring/training-jobs` | GET | **Platform Admin** | Any | Platform metrics |
| `/monitoring/models` | GET | **Platform Admin** | Any | Platform metrics |
| `/monitoring/performance` | GET | **Platform Admin** | Any | Platform metrics |

#### WebSocket

| Endpoint | Protocol | Min Role | Min Tier | Access Control |
|----------|----------|----------|----------|----------------|
| `/ws/{tenant_id}/training` | WebSocket | **Admin** | Any | Real-time training updates |

**🔴 Critical Operations:**
- Model training (expensive ML operations)
- Model deployment (affects production forecasts)
- Circuit breaker reset (platform stability)
- Model retraining (overwrites existing models)

**💰 Premium Features:**
- **Starter Tier:**
  - Basic model training (limited dataset size)
  - Simple Prophet models
  - Training job monitoring
  - WebSocket updates
  - Maximum 1 training job per day
- **Professional Tier:**
  - Advanced model training (larger datasets)
  - Model versioning
  - Multiple concurrent training jobs
  - Historical model comparison
  - Maximum 5 training jobs per day
- **Enterprise Tier:**
  - Custom model parameters
  - Model artifact download
  - Priority training queue
  - Multiple model versions
  - Unlimited training jobs
  - Custom ML architectures

**Recommendations:**
- ✅ AVAILABLE TO ALL TIERS: Basic model training
- 🔧 ADD: Training quota per subscription tier (1/day Starter, 5/day Professional, unlimited Enterprise)
- 🔧 ADD: Dataset size limits per tier (1000 rows Starter, 10k Professional, unlimited Enterprise)
- 🔧 ADD: Queue priority based on subscription
- 🔧 ADD: Model deployment approval workflow for production
- 🔧 ADD: Artifact download only for Enterprise
- 🔧 ADD: Custom model parameters only for Enterprise
- 🔧 ADD: Rate limiting on training job creation based on tier

---

### 3.8 SUPPLIERS SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 20+

#### Supplier Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/suppliers` | GET | **Viewer** | Any | View suppliers |
| `/{tenant_id}/suppliers` | POST | **Admin** | Any | Add supplier |
| `/{tenant_id}/suppliers/{id}` | GET | **Viewer** | Any | View supplier |
| `/{tenant_id}/suppliers/{id}` | PUT | **Admin** | Any | Update supplier |
| `/{tenant_id}/suppliers/{id}` | DELETE | **Admin** | Any | **🔴** Delete supplier |
| `/{tenant_id}/suppliers/{id}/rate` | POST | **Member** | Any | Rate supplier |

#### Purchase Orders

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/purchase-orders` | GET | **Viewer** | Any | View POs |
| `/{tenant_id}/purchase-orders` | POST | **Member** | Any | Create PO |
| `/{tenant_id}/purchase-orders/{id}` | GET | **Viewer** | Any | View PO |
| `/{tenant_id}/purchase-orders/{id}` | PUT | **Member** | Any | Update PO |
| `/{tenant_id}/purchase-orders/{id}/approve` | POST | **Admin** | Any | **🔴** Approve PO |
| `/{tenant_id}/purchase-orders/{id}/reject` | POST | **Admin** | Any | Reject PO |
| `/{tenant_id}/purchase-orders/{id}` | DELETE | **Admin** | Any | **🔴** Delete PO |

#### Deliveries

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/deliveries` | GET | **Viewer** | Any | View deliveries |
| `/{tenant_id}/deliveries` | POST | **Member** | Any | Record delivery |
| `/{tenant_id}/deliveries/{id}` | GET | **Viewer** | Any | View delivery |
| `/{tenant_id}/deliveries/{id}/receive` | POST | **Member** | Any | Receive delivery |
| `/{tenant_id}/deliveries/{id}/items` | POST | **Member** | Any | Add delivery items |

#### Analytics

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/analytics/performance` | GET | **Viewer** | **Professional** | **💰** Supplier performance |
| `/{tenant_id}/analytics/cost-analysis` | GET | **Admin** | **Professional** | **💰** Cost analysis |
| `/{tenant_id}/analytics/scorecards` | GET | **Admin** | **Professional** | **💰** Supplier scorecards |
| `/{tenant_id}/analytics/benchmarking` | GET | **Admin** | **Enterprise** | **💰** Benchmarking |
| `/{tenant_id}/analytics/risk-assessment` | GET | **Admin** | **Enterprise** | **💰** Risk assessment |

**🔴 Critical Operations:**
- Supplier deletion (affects historical data)
- Purchase order approval (financial commitment)
- PO deletion (affects inventory and accounting)
- Delivery confirmation (affects inventory levels)

**💰 Premium Features:**
- **Professional Tier:**
  - Supplier performance analytics
  - Cost analysis
  - Quality scorecards
- **Enterprise Tier:**
  - Multi-supplier benchmarking
  - Risk assessment
  - Automated reorder optimization

**Recommendations:**
- 🔧 ADD: PO approval workflow with threshold amounts
- 🔧 ADD: Prevent supplier deletion if has active POs
- 🔧 ADD: Delivery confirmation requires photo/signature
- 🔧 ADD: Cost analysis only for Admin+ (sensitive data)
- 🔧 ADD: Subscription tier checks on analytics
- 🔧 ADD: Audit log for PO approvals and modifications

---

### 3.9 RECIPES SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 15+

#### Recipe Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/recipes` | GET | **Viewer** | Any | View recipes |
| `/{tenant_id}/recipes` | POST | **Member** | Any | Create recipe |
| `/{tenant_id}/recipes/{id}` | GET | **Viewer** | Any | View recipe |
| `/{tenant_id}/recipes/{id}` | PUT | **Member** | Any | Update recipe |
| `/{tenant_id}/recipes/{id}` | DELETE | **Admin** | Any | **🔴** Delete recipe |

#### Recipe Operations

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/recipes/validate` | POST | **Member** | Any | Validate recipe |
| `/{tenant_id}/recipes/duplicate` | POST | **Member** | Any | Duplicate recipe |
| `/{tenant_id}/recipes/{id}/cost` | GET | **Admin** | Any | **💰** Calculate cost (sensitive) |
| `/{tenant_id}/recipes/{id}/availability` | GET | **Viewer** | Any | Check ingredient availability |
| `/{tenant_id}/recipes/{id}/scaling` | GET | **Viewer** | **Professional** | **💰** Scaling options |

#### Quality Configuration

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/recipes/{id}/quality-config` | GET | **Viewer** | Any | View quality config |
| `/{tenant_id}/recipes/{id}/quality-config` | POST | **Admin** | Any | Create quality config |
| `/{tenant_id}/recipes/{id}/quality-config` | PUT | **Admin** | Any | Update quality config |
| `/{tenant_id}/recipes/{id}/quality-config` | DELETE | **Admin** | Any | Delete quality config |

**🔴 Critical Operations:**
- Recipe deletion (affects production)
- Quality config changes (affects batch quality)
- Cost calculation access (sensitive financial data)

**💰 Premium Features:**
- **Professional Tier:**
  - Advanced recipe scaling
  - Cost optimization recommendations
  - Ingredient substitution suggestions
- **Enterprise Tier:**
  - Multi-location recipe management
  - Recipe version control
  - Batch costing analysis

**Recommendations:**
- 🔧 ADD: Prevent deletion of recipes in active production
- 🔧 ADD: Recipe costing only for Admin+ (sensitive)
- 🔧 ADD: Recipe versioning for audit trail
- 🔧 ADD: Quality config changes require validation
- 🔧 ADD: Subscription tier check on scaling features

---

### 3.10 ORDERS SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 12+

#### Order Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/orders` | GET | **Viewer** | Any | View orders |
| `/{tenant_id}/orders` | POST | **Member** | Any | Create order |
| `/{tenant_id}/orders/{id}` | GET | **Viewer** | Any | View order |
| `/{tenant_id}/orders/{id}` | PUT | **Member** | Any | Update order |
| `/{tenant_id}/orders/{id}/status` | PUT | **Member** | Any | Update order status |
| `/{tenant_id}/orders/{id}/cancel` | POST | **Admin** | Any | **🔴** Cancel order |
| `/{tenant_id}/orders/{id}` | DELETE | **Admin** | Any | **🔴** Delete order |

#### Customer Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/customers` | GET | **Viewer** | Any | View customers |
| `/{tenant_id}/customers` | POST | **Member** | Any | Add customer |
| `/{tenant_id}/customers/{id}` | GET | **Viewer** | Any | View customer |
| `/{tenant_id}/customers/{id}` | PUT | **Member** | Any | Update customer |
| `/{tenant_id}/customers/{id}` | DELETE | **Admin** | Any | **🔴** Delete customer |

#### Procurement Operations

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/procurement/requirements` | GET | **Admin** | **Professional** | **💰** Procurement planning |
| `/{tenant_id}/procurement/schedule` | POST | **Admin** | **Professional** | **💰** Schedule procurement |
| `/test/procurement-scheduler` | POST | **Platform Admin** | Any | **🔴** Manual scheduler test |

**🔴 Critical Operations:**
- Order cancellation (affects production and customer)
- Order deletion (affects reporting and history)
- Customer deletion (GDPR compliance required)
- Procurement scheduling (affects inventory)

**💰 Premium Features:**
- **Professional Tier:**
  - Automated procurement planning
  - Demand-based scheduling
  - Procurement optimization
- **Enterprise Tier:**
  - Multi-location order routing
  - Advanced customer segmentation
  - Priority order handling

**Recommendations:**
- 🔧 ADD: Order cancellation requires reason/notes
- 🔧 ADD: Customer deletion with GDPR-compliant data export
- 🔧 ADD: Soft delete for orders (audit trail)
- 🔧 ADD: Procurement scheduling only for Professional+
- 🔧 ADD: Order approval workflow for large orders

---

### 3.11 POS SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 20+

#### Configuration

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/pos/configurations` | GET | **Admin** | Any | View POS configs |
| `/{tenant_id}/pos/configurations` | POST | **Admin** | Any | Add POS config |
| `/{tenant_id}/pos/configurations/{id}` | GET | **Admin** | Any | View config |
| `/{tenant_id}/pos/configurations/{id}` | PUT | **Admin** | Any | Update config |
| `/{tenant_id}/pos/configurations/{id}` | DELETE | **Admin** | Any | **🔴** Delete config |
| `/{tenant_id}/pos/configurations/active` | GET | **Admin** | Any | View active configs |

#### Transactions

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/pos/transactions` | GET | **Viewer** | Any | View transactions |
| `/{tenant_id}/pos/transactions/{id}` | GET | **Viewer** | Any | View transaction |

#### Operations

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/pos/webhook` | POST | Service | Any | **Internal** Webhook handler |
| `/{tenant_id}/pos/sync-status` | GET | **Admin** | Any | View sync status |
| `/{tenant_id}/pos/products` | GET | **Viewer** | Any | View POS products |
| `/{tenant_id}/pos/sync/full` | POST | **Admin** | Any | **🔴** Full sync |
| `/{tenant_id}/pos/sync/incremental` | POST | **Admin** | Any | Incremental sync |
| `/{tenant_id}/pos/test-connection` | POST | **Admin** | Any | Test connection |
| `/{tenant_id}/pos/mapping/status` | GET | **Admin** | Any | View mapping status |

#### Analytics

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/pos/sales-summary` | GET | **Viewer** | Any | Sales summary |
| `/{tenant_id}/pos/sync-health` | GET | **Admin** | Any | Sync health metrics |

**🔴 Critical Operations:**
- POS configuration changes (affects sales recording)
- Full sync trigger (resource intensive)
- Configuration deletion (breaks integration)

**💰 Premium Features:**
- **Professional Tier:**
  - Multi-POS support
  - Advanced sync options
  - Transaction analytics
- **Enterprise Tier:**
  - Custom webhooks
  - Real-time sync
  - Multi-location POS management

**Recommendations:**
- 🔧 ADD: POS config changes require testing first
- 🔧 ADD: Full sync rate limiting (expensive operation)
- 🔧 ADD: Webhook signature verification
- 🔧 ADD: Transaction data retention policies
- 🔧 ADD: Configuration backup before deletion

---

### 3.12 NOTIFICATION SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 10+

#### Notification Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/notifications` | GET | **Viewer** | Any | Own notifications |
| `/{tenant_id}/notifications/{id}` | GET | **Viewer** | Any | View notification |
| `/{tenant_id}/notifications/{id}/read` | PATCH | **Viewer** | Any | Mark as read |
| `/{tenant_id}/notifications/{id}/unread` | PATCH | **Viewer** | Any | Mark as unread |
| `/{tenant_id}/notifications/preferences` | GET | **Viewer** | Any | Get preferences |
| `/{tenant_id}/notifications/preferences` | PUT | **Viewer** | Any | Update preferences |

#### Operations

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/notifications/send` | POST | Service | Any | **Internal** Send notification |
| `/{tenant_id}/notifications/broadcast` | POST | **Admin** | Any | **🔴** Broadcast to team |

#### Analytics

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/notifications/analytics` | GET | **Admin** | **Professional** | **💰** Notification metrics |
| `/sse-metrics` | GET | **Platform Admin** | Any | **🔴** Platform SSE metrics |

**🔴 Critical Operations:**
- Broadcast notifications (all team members)
- Notification preferences (affects alert delivery)
- SSE metrics (platform monitoring)

**💰 Premium Features:**
- **Professional Tier:**
  - WhatsApp notifications
  - Custom notification channels
  - Notification analytics
- **Enterprise Tier:**
  - SMS notifications
  - Webhook notifications
  - Priority delivery

**Recommendations:**
- 🔧 ADD: Users can only access their own notifications
- 🔧 ADD: Broadcast requires Admin role
- 🔧 ADD: Rate limiting on broadcast (abuse prevention)
- 🔧 ADD: Notification analytics only for Professional+
- 🔧 ADD: Preference validation (at least one channel enabled)

---

### 3.13 ALERT PROCESSOR SERVICE

**Total Endpoints:** 0 (Background Worker)

**Access Control:** This service does not expose HTTP endpoints. It's a background worker that:
- Consumes from RabbitMQ queues
- Processes alerts and recommendations
- Routes to notification service based on severity
- Stores alerts in database

**Security Considerations:**
- 🔧 Service-to-service authentication required
- 🔧 RabbitMQ queue access control
- 🔧 Alert classification validation
- 🔧 Rate limiting on alert generation

**Alert Routing Rules:**
- **Urgent:** All channels (WhatsApp, Email, Push, Dashboard)
- **High:** WhatsApp + Email (daytime), Email only (night)
- **Medium:** Email (business hours only)
- **Low:** Dashboard only
- **Recommendations:** Email (business hours) for medium/high severity

---

### 3.14 DEMO SESSION SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 8+

#### Demo Session Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/demo/sessions` | POST | Public | Any | Create demo session |
| `/demo/sessions/{id}` | GET | Public | Any | View demo session |
| `/demo/sessions/{id}/extend` | POST | Public | Any | Extend demo session |
| `/demo/sessions/{id}/cleanup` | POST | Service | Any | **Internal** Cleanup session |

#### Demo Account Management

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/demo/accounts` | POST | Public | Any | Create demo account |
| `/demo/accounts/{id}` | GET | Public | Any | View demo account |
| `/demo/accounts/{id}/reset` | POST | Public | Any | Reset demo data |

**🔴 Critical Operations:**
- Demo session cleanup (data deletion)
- Demo data seeding (resource intensive)

**Security Considerations:**
- 🔧 Rate limiting on demo creation (abuse prevention)
- 🔧 Automatic cleanup after expiration
- 🔧 Demo data isolation from production
- 🔧 Limited feature access in demo mode
- 🔧 No sensitive operations allowed in demo

**Recommendations:**
- ✅ IMPLEMENTED: Demo session expiration
- 🔧 ADD: CAPTCHA on demo creation
- 🔧 ADD: IP-based rate limiting (max 5 demos per IP per day)
- 🔧 ADD: Demo sessions cannot access paid features
- 🔧 ADD: Clear "DEMO MODE" indicators in UI

---

### 3.15 EXTERNAL SERVICE

**Base Path:** `/api/v1`
**Total Endpoints:** 10+

#### Weather Data

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/weather` | GET | **Viewer** | **Professional** | **💰** Weather data |
| `/{tenant_id}/weather/forecast` | GET | **Viewer** | **Professional** | **💰** Weather forecast |
| `/{tenant_id}/weather/historical` | GET | **Viewer** | **Enterprise** | **💰** Historical weather |

#### Traffic Data

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/{tenant_id}/traffic` | GET | **Viewer** | **Professional** | **💰** Traffic data |
| `/{tenant_id}/traffic/realtime` | GET | **Viewer** | **Professional** | **💰** Real-time traffic |
| `/{tenant_id}/traffic/predictions` | GET | **Viewer** | **Enterprise** | **💰** Traffic predictions |

#### City Operations

| Endpoint | Method | Min Role | Min Tier | Access Control |
|----------|--------|----------|----------|----------------|
| `/city/{city}/weather` | GET | **Viewer** | **Professional** | **💰** City weather |
| `/city/{city}/traffic` | GET | **Viewer** | **Professional** | **💰** City traffic |
| `/city/{city}/events` | GET | **Viewer** | **Enterprise** | **💰** City events |

**🔴 Critical Operations:**
- External API rate limit management
- Data collection scheduling
- API key management

**💰 Premium Features:**
- **Professional Tier:**
  - Basic weather data
  - Real-time traffic data
  - Current day forecasts
- **Enterprise Tier:**
  - Historical weather data
  - Traffic predictions
  - City events calendar
  - Custom data collection schedules

**Recommendations:**
- ✅ REQUIRES: Subscription tier = Professional minimum
- 🔧 ADD: API quota limits per subscription tier
- 🔧 ADD: Rate limiting based on subscription
- 🔧 ADD: Historical data only for Enterprise
- 🔧 ADD: Cache external API responses

---

## 4. Implementation Recommendations

### 4.1 Priority Matrix

**CRITICAL (Implement Immediately):**

1. **Owner-Only Operations**
   - Tenant deletion/deactivation
   - Subscription changes and cancellation
   - Billing information access

2. **Admin Operations**
   - User deletion across all services
   - Financial data access (costs, pricing)
   - POS configuration changes
   - Production schedule modifications
   - Supplier/customer deletion

3. **Service-to-Service Auth**
   - Internal API authentication
   - Webhook signature verification
   - RabbitMQ queue access control

**HIGH PRIORITY (Implement Soon):**

1. **Subscription Tier Enforcement**
   - Forecast horizon limits (7 days Starter, 30+ Professional, unlimited Enterprise)
   - Training job quotas (1/day Starter, 5/day Professional, unlimited Enterprise)
   - Dataset size limits for ML (1k rows Starter, 10k Professional, unlimited Enterprise)
   - Advanced analytics (Professional+)
   - Scenario modeling (Enterprise only)
   - Historical data limits (7 days Starter, 90 days Professional, unlimited Enterprise)
   - Multi-location support (1 Starter, 2 Professional, unlimited Enterprise)

2. **Audit Logging**
   - All deletion operations
   - Subscription changes
   - Role modifications
   - Financial operations

3. **Rate Limiting & Quotas**
   - ML training jobs (per tier: 1/day, 5/day, unlimited)
   - Forecast generation (per tier: 10/day, 100/day, unlimited)
   - Bulk imports
   - POS sync operations
   - Dataset size limits for training

**MEDIUM PRIORITY (Next Sprint):**

1. **Fine-Grained Permissions**
   - Resource-level access control
   - Custom role permissions
   - Department-based access

2. **Approval Workflows**
   - Large purchase orders
   - Production schedule changes
   - Model deployment

3. **Data Retention**
   - Soft delete for critical records
   - Audit trail preservation
   - GDPR compliance

### 4.2 Implementation Steps

#### Step 1: Add Missing Role Decorators

```python
# Example for sales endpoint
@router.delete("/{tenant_id}/sales/{sale_id}")
@require_user_role(['admin', 'owner'])  # ADD THIS
async def delete_sale(
    tenant_id: str,
    sale_id: str,
    current_user: Dict = Depends(get_current_user_dep)
):
    # Existing logic...
```

#### Step 2: Add Subscription Tier Checks

```python
# Example for forecasting endpoint with quota checking
@router.post("/{tenant_id}/forecasts/generate")
@require_user_role(['admin', 'owner'])
async def generate_forecast(
    tenant_id: str,
    horizon_days: int,  # Forecast horizon
    current_user: Dict = Depends(get_current_user_dep)
):
    # Check tier-based limits
    tier = current_user.get('subscription_tier', 'starter')
    max_horizon = {
        'starter': 7,
        'professional': 90,
        'enterprise': 365
    }

    if horizon_days > max_horizon.get(tier, 7):
        raise HTTPException(
            status_code=402,
            detail=f"Forecast horizon limited to {max_horizon[tier]} days for {tier} tier"
        )

    # Check daily quota
    daily_quota = {'starter': 10, 'professional': 100, 'enterprise': None}
    if not await check_quota(tenant_id, 'forecasts', daily_quota[tier]):
        raise HTTPException(
            status_code=429,
            detail=f"Daily forecast quota exceeded for {tier} tier"
        )

    # Existing logic...
```

#### Step 3: Add Audit Logging

```python
# Example audit log utility
from shared.audit import log_audit_event

@router.delete("/{tenant_id}/customers/{customer_id}")
@require_user_role(['admin', 'owner'])
async def delete_customer(
    tenant_id: str,
    customer_id: str,
    current_user: Dict = Depends(get_current_user_dep)
):
    # Existing logic...

    # ADD AUDIT LOG
    await log_audit_event(
        tenant_id=tenant_id,
        user_id=current_user["user_id"],
        action="customer.delete",
        resource_type="customer",
        resource_id=customer_id,
        severity="high"
    )
```

#### Step 4: Implement Rate Limiting

```python
# Example rate limiting for ML operations with tier-based quotas
from shared.rate_limit import check_quota
from shared.ml_limits import check_dataset_size_limit

@router.post("/{tenant_id}/training-jobs")
@require_user_role(['admin', 'owner'])
async def create_training_job(
    tenant_id: str,
    dataset_rows: int,
    current_user: Dict = Depends(get_current_user_dep)
):
    tier = current_user.get('subscription_tier', 'starter')

    # Check daily quota
    daily_limits = {'starter': 1, 'professional': 5, 'enterprise': None}
    if not await check_quota(tenant_id, 'training_jobs', daily_limits[tier], period=86400):
        raise HTTPException(
            status_code=429,
            detail=f"Daily training job limit reached for {tier} tier ({daily_limits[tier]}/day)"
        )

    # Check dataset size limit
    dataset_limits = {'starter': 1000, 'professional': 10000, 'enterprise': None}
    if dataset_limits[tier] and dataset_rows > dataset_limits[tier]:
        raise HTTPException(
            status_code=402,
            detail=f"Dataset size limited to {dataset_limits[tier]} rows for {tier} tier"
        )

    # Existing logic...
```

### 4.3 Security Checklist

**Authentication & Authorization:**
- [ ] JWT validation on all authenticated endpoints
- [ ] Tenant isolation verification
- [ ] Role-based access control on sensitive operations
- [ ] Subscription tier enforcement on premium features
- [ ] Service-to-service authentication

**Data Protection:**
- [ ] Soft delete for audit-critical records
- [ ] Audit logging for all destructive operations
- [ ] GDPR-compliant data deletion
- [ ] Financial data access restricted to Admin+
- [ ] PII access logging

**Rate Limiting & Abuse Prevention:**
- [ ] ML/Training job rate limits
- [ ] Bulk operation throttling
- [ ] Demo session creation limits
- [ ] Login attempt limiting
- [ ] API quota enforcement per subscription tier

**Compliance:**
- [ ] GDPR data export functionality
- [ ] Food safety record retention (cannot delete)
- [ ] Financial record audit trail
- [ ] User consent tracking
- [ ] Data breach notification system

### 4.4 Testing Strategy

**Unit Tests:**
```python
# Test role enforcement
def test_delete_requires_admin_role():
    response = client.delete(
        "/api/v1/tenant123/sales/sale456",
        headers={"Authorization": f"Bearer {member_token}"}
    )
    assert response.status_code == 403
    assert "insufficient_permissions" in response.json()["detail"]["error"]

# Test subscription tier enforcement with horizon limits
def test_forecasting_horizon_limit_starter():
    response = client.post(
        "/api/v1/tenant123/forecasts/generate",
        json={"horizon_days": 30},  # Exceeds 7-day limit for Starter
        headers={"Authorization": f"Bearer {starter_user_token}"}
    )
    assert response.status_code == 402  # Payment Required
    assert "limited to 7 days" in response.json()["detail"]

# Test training job quota
def test_training_job_daily_quota_starter():
    # First training job succeeds
    response1 = client.post(
        "/api/v1/tenant123/training-jobs",
        json={"dataset_rows": 500},
        headers={"Authorization": f"Bearer {starter_admin_token}"}
    )
    assert response1.status_code == 200

    # Second training job on same day fails (1/day limit for Starter)
    response2 = client.post(
        "/api/v1/tenant123/training-jobs",
        json={"dataset_rows": 500},
        headers={"Authorization": f"Bearer {starter_admin_token}"}
    )
    assert response2.status_code == 429  # Too Many Requests
    assert "Daily training job limit reached" in response2.json()["detail"]

# Test dataset size limit
def test_training_dataset_size_limit():
    response = client.post(
        "/api/v1/tenant123/training-jobs",
        json={"dataset_rows": 5000},  # Exceeds 1000-row limit for Starter
        headers={"Authorization": f"Bearer {starter_admin_token}"}
    )
    assert response.status_code == 402  # Payment Required
    assert "Dataset size limited to 1000 rows" in response.json()["detail"]
```

**Integration Tests:**
```python
# Test tenant isolation
def test_user_cannot_access_other_tenant():
    # User belongs to tenant123
    response = client.get(
        "/api/v1/tenant456/sales",  # Trying to access tenant456
        headers={"Authorization": f"Bearer {user_token}"}
    )
    assert response.status_code == 403
```

**Security Tests:**
```python
# Test rate limiting
def test_training_job_rate_limit():
    for i in range(6):
        response = client.post(
            "/api/v1/tenant123/training-jobs",
            headers={"Authorization": f"Bearer {admin_token}"}
        )
    assert response.status_code == 429  # Too Many Requests
```

---

## 5. Access Control Matrix Summary

### By Role

| Role | Read | Create | Update | Delete | Admin Functions | Billing |
|------|------|--------|--------|--------|----------------|---------|
| **Viewer** | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| **Member** | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ |
| **Admin** | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ |
| **Owner** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |

### By Subscription Tier

| Feature Category | Starter | Professional | Enterprise |
|------------------|---------|--------------|------------|
| Basic Operations | ✓ | ✓ | ✓ |
| ML Forecasting (Basic) | ✓ (7-day) | ✓ (30+ day) | ✓ (Unlimited) |
| Production Optimization (Basic) | ✓ | ✓ (Advanced) | ✓ (AI-powered) |
| Model Training (Basic) | ✓ (1/day) | ✓ (5/day) | ✓ (Unlimited) |
| Advanced Analytics | ✗ | ✓ | ✓ |
| Scenario Modeling | ✗ | ✗ | ✓ |
| Multi-location | 1 | 2 | Unlimited |
| API Access | ✗ | ✗ | ✓ |
| Custom ML Parameters | ✗ | ✗ | ✓ |

### Critical Operations (Owner/Admin Only)

**Owner Only:**
- Tenant deletion/deactivation
- Subscription upgrade/downgrade/cancel
- Billing information access
- Final owner cannot be removed

**Admin+ (Admin or Owner):**
- User management (invite, remove, role changes)
- Delete operations (sales, inventory, recipes, etc.)
- Financial data access (costs, margins, pricing)
- System configuration (POS, integrations)
- Production schedule modifications
- Purchase order approvals

**Member:**
- Create and update operational data
- View most reports and dashboards
- Basic CRUD operations

**Viewer:**
- Read-only access to operational data
- View dashboards and reports (non-financial)
- No write permissions

---

## 6. Next Steps

### Phase 1: Critical Security (Week 1-2)
1. Add role decorators to all deletion endpoints
2. Implement owner-only checks for billing/subscription
3. Add service-to-service authentication
4. Implement audit logging for critical operations

### Phase 2: Premium Feature Gating (Week 3-4)
1. Implement forecast horizon limits per tier (7/30/unlimited days)
2. Implement training job quotas per tier (1/5/unlimited per day)
3. Implement dataset size limits for ML training (1k/10k/unlimited rows)
4. Add tier checks to advanced analytics (Professional+)
5. Add tier checks to scenario modeling (Enterprise only)
6. Implement historical data limits (7/90/unlimited days)
7. Implement multi-location limits (1/2/unlimited)
8. Implement usage quota tracking and enforcement

### Phase 3: Rate Limiting & Abuse Prevention (Week 5-6)
1. ML training job rate limits
2. Bulk operation throttling
3. Demo session creation limits
4. Login attempt limiting

### Phase 4: Compliance & Audit (Week 7-8)
1. GDPR data export functionality
2. Audit trail for all destructive operations
3. Data retention policies
4. Compliance reporting

---

## 7. Appendix

### A. Role Hierarchy Code Reference

File: [`shared/auth/access_control.py`](shared/auth/access_control.py:27-51)

```python
class UserRole(Enum):
    VIEWER = "viewer"
    MEMBER = "member"
    ADMIN = "admin"
    OWNER = "owner"

ROLE_HIERARCHY = {
    UserRole.VIEWER: 1,
    UserRole.MEMBER: 2,
    UserRole.ADMIN: 3,
    UserRole.OWNER: 4,
}
```

### B. Subscription Tier Code Reference

File: [`shared/auth/access_control.py`](shared/auth/access_control.py:17-43)

```python
class SubscriptionTier(Enum):
    STARTER = "starter"
    PROFESSIONAL = "professional"
    ENTERPRISE = "enterprise"

TIER_HIERARCHY = {
    SubscriptionTier.STARTER: 1,
    SubscriptionTier.PROFESSIONAL: 2,
    SubscriptionTier.ENTERPRISE: 3,
}
```

### C. Tenant Member Model Reference

File: [`services/tenant/app/models/tenants.py`](services/tenant/app/models/tenants.py:72-98)

```python
class TenantMember(Base):
    tenant_id = Column(UUID(as_uuid=True), ForeignKey("tenants.id"))
    user_id = Column(UUID(as_uuid=True), nullable=False)
    role = Column(String(50), default="member")  # owner, admin, member, viewer
    is_active = Column(Boolean, default=True)
```

### D. Decorator Usage Examples

**Role-Based:**
```python
@router.delete("/{tenant_id}/resource/{id}")
@require_user_role(['admin', 'owner'])
async def delete_resource(...):
    pass
```

**Tier-Based:**
```python
@router.get("/{tenant_id}/analytics/advanced")
@require_subscription_tier(['professional', 'enterprise'])
async def get_advanced_analytics(...):
    pass
```

**Combined:**
```python
@router.post("/{tenant_id}/ml/custom-model")
@require_tier_and_role(['enterprise'], ['admin', 'owner'])
async def train_custom_model(...):
    pass
```

---

## Document Control

**Version:** 1.0
**Status:** Final
**Last Updated:** 2025-10-12
**Next Review:** After Phase 1 implementation
**Owner:** Security & Platform Team

---

**End of Report**
