{"slug":"developers/FRONTEND_SERVICE_INTEGRATION","title":"Frontend-to-Backend Service Integration","section":"developers","sectionLabel":"Developers","status":"unclassified","type":"document","path":"developers/FRONTEND_SERVICE_INTEGRATION.mdx","bytes":9606,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n**Complete & Production-Ready**\n**3 Profiles × 31 Services = Full Cloudflare Control from UI**\n\n---\n\n## Architecture Overview\n\n```\napps/platform (Next.js Frontend)\n    ↓\nProfileProvider (Context)\n    ↓\nuseServices() Hook\n    ↓\n12 Service Clients (Tenants, Connectors, MCP, etc.)\n    ↓\nGateway API → /api/v1/*\n    ↓\n31 Cloudflare Workers Services\n    ↓\nNeon (Control Plane) + D1 (Runtime)\n```\n\n---\n\n## What Was Built\n\n### 1. Profile Context & Providers\n\n**File**: `lib/contexts/profile-context.tsx`\n\nManages deployment profile switching:\n\n- Dev (95% SLA, TLS 1.2 + JWT)\n- Customer Zero (99.5% SLA, TLS 1.3 + mTLS)\n- External Users (99.9% SLA, TLS 1.3 + mTLS + pinning)\n\nEach profile has:\n\n- Isolated data\n- Separate configuration\n- Own Cloudflare Worker deployments\n- Profile-specific MCP pools\n\n```typescript\nconst { activeProfile, setProfile } = useProfile();\n\n// Switch profiles\nawait setProfile(\"customer-zero\");\n```\n\n### 2. Tenant Schema Allocation\n\n**File**: `lib/services/tenant-schema.ts`\n\nHandles schema assignment during onboarding:\n\n**Core 10 Base Tenants** (Dev & Customer Zero):\n\n- System, Admin, Support, Analytics, Compliance\n- Monitoring, Audit, Billing, Onboarding, Testing\n\n**Profile-Specific Tenants** (External Users):\n\n- Custom per customer\n\nSchema allocation:\n\n```typescript\nawait allocateTenantSchema({\n  tenantId: \"tenant-123\",\n  profile: \"customer-zero\",\n  tenantName: \"Acme Corp\",\n  tier: \"enterprise\",\n  region: \"us-east\",\n});\n// Creates: schema_customer_zero_tenant_123_abc123\n```\n\n### 3. Tenant Onboarding Workflow\n\n**File**: `lib/services/tenant-onboarding.ts`\n\n5-step automated onboarding:\n\n1. **Create Tenant** — Register in tenants service\n2. **Allocate Schema** — Reserve database schema\n3. **Create Admin User** — Initialize tenant admin\n4. **Setup Core Services** — Deploy 10 base services\n5. **Configure Profile Settings** — Apply profile-specific config\n\nProgress tracking with error recovery.\n\n### 4. useServices() Hook\n\n**File**: `lib/hooks/useServices.ts`\n\nSingle entry point for all backend operations:\n\n```typescript\nconst services = useServices();\n\n// Tenants\nawait services.tenants.list();\nawait services.tenants.create(\"Acme Corp\", \"enterprise\");\nawait services.tenants.update(id, { tier: \"growth\" });\n\n// Connectors\nawait services.connectors.list();\nawait services.connectors.sync(connectorId);\n\n// Admin\nawait services.admin.users.create(tenantId, \"admin@example.com\", \"admin\");\nawait services.admin.audit.list(tenantId);\n\n// Governance\nawait services.governance.policies.list();\nawait services.governance.approvals.list();\n\n// Observability\nawait services.observability.health();\nawait services.observability.metrics(\"request_count\");\n```\n\nAll calls automatically scoped to active profile.\n\n### 5. Platform Pages Wired to Services\n\n#### Tenants Page (`app/(shell)/tenants/page.tsx`)\n\n- Lists all tenants in profile\n- Profile-specific data isolation\n- Tier, status, creation date visible\n\n#### Connectors Page (`app/(shell)/connectors/page.tsx`)\n\n- Shows integration connectors\n- Last sync timestamp\n- Connection status\n\n#### Environment Page (`app/(shell)/environment/page.tsx`)\n\n- **Cloudflare Workers Status** — All 31 services\n- **TLS Configuration** — Shows active profile settings\n- **Infrastructure Info** — Data centers, backup regions\n- **Metrics** — Uptime, latency, worker count, Durable Objects\n\n#### Onboarding Page (`app/(shell)/onboarding/page.tsx`)\n\n- Form to create new tenants\n- Region selection (us-east, eu-west, ap-south)\n- Tier selection (starter, growth, enterprise)\n- Real-time progress tracking\n\n### 6. Profile Switcher Component\n\n**File**: `components/profile-switcher.tsx`\n\nUI to switch deployment profiles with:\n\n- Current profile indicator\n- SLA information\n- TLS/mTLS status\n- Live configuration display\n\n---\n\n## Data Isolation Per Profile\n\n### Dev Profile\n\n- 10 core tenants (shared base)\n- 95% SLA guarantee\n- TLS 1.2 + JWT auth\n- Single region (us-east)\n- Internal only\n\n### Customer Zero Profile\n\n- 10 core tenants (same as dev)\n- 99.5% SLA guarantee\n- TLS 1.3 + mTLS certificates\n- Primary region + backup\n- First paying customer\n\n### External Users Profile\n\n- Variable custom tenants\n- 99.9% SLA guarantee\n- TLS 1.3 + mTLS + certificate pinning\n- 5 regions (multi-region failover)\n- Public production\n\n---\n\n## How Frontend Controls Cloudflare\n\n### 1. Profile Selection\n\n```typescript\n// UI switches profile\nawait setProfile(\"external-users\");\n// All subsequent service calls route to external-users workers\n```\n\n### 2. Service Operations\n\n```typescript\n// Create connector → integration-management-mcp worker\nawait services.connectors.create(\"Salesforce\", config);\n\n// Execute capability → iw-agent-runtime worker\nawait services.capabilities.execute(capabilityId, params);\n\n// Update governance → twin-orchestrator worker\nawait services.governance.policies.create(\"rate-limit\", rules);\n```\n\n### 3. Environment Control\n\n```typescript\n// Check all 31 workers' health\nconst health = await services.observability.health();\n// Returns: status of gateway, tenants, admin, connectors, mcp-pool,\n//          spine, knowledge, continuity, agents, etc.\n```\n\n### 4. Tenant Onboarding\n\n```typescript\n// Complete workflow with schema allocation\nconst result = await onboardTenant({\n  tenantName: \"Acme Corp\",\n  adminEmail: \"admin@acme.com\",\n  profile: \"customer-zero\",\n  region: \"eu-west\",\n  tier: \"enterprise\",\n});\n// Allocates schema: schema_customer_zero_acmecorp_abc123\n// Creates all 10 base tenants automatically\n```\n\n---\n\n## File Structure\n\n```\napps/platform/\n├── lib/\n│   ├── services/\n│   │   ├── index.ts                    # Service client exports\n│   │   ├── types.ts                    # BaseServiceClient\n│   │   ├── gateway.ts                  # Gateway routing\n│   │   ├── tenants.ts                  # Tenant lifecycle\n│   │   ├── admin.ts                    # Users & roles\n│   │   ├── connectors.ts               # Integrations\n│   │   ├── mcp.ts                      # MCP registry\n│   │   ├── capabilities.ts             # Agent workflows\n│   │   ├── knowledge.ts                # Docs & search\n│   │   ├── memory.ts                   # Session continuity\n│   │   ├── governance.ts               # Policies & approvals\n│   │   ├── observability.ts            # Health & metrics\n│   │   ├── spine.ts                    # Entity management\n│   │   ├── agents.ts                   # Agent deployment\n│   │   ├── tenant-schema.ts            # Schema allocation\n│   │   └── tenant-onboarding.ts        # Onboarding workflow\n│   ├── contexts/\n│   │   └── profile-context.tsx         # Profile provider\n│   └── hooks/\n│       └── useServices.ts              # Main service hook\n├── components/\n│   └── profile-switcher.tsx            # Profile UI\n└── app/(shell)/\n    ├── tenants/page.tsx                # Tenant management\n    ├── connectors/page.tsx             # Connector control\n    ├── environment/page.tsx            # CF environment dashboard\n    └── onboarding/page.tsx             # Tenant onboarding\n```\n\n---\n\n## Usage Example: End-to-End Flow\n\n```typescript\n'use client'\n\n\n  const { activeProfile, setProfile } = useProfile()\n  const services = useServices()\n\n  // 1. Switch to customer-zero profile\n  const handleSwitchProfile = async () => {\n    await setProfile('customer-zero')\n  }\n\n  // 2. List all tenants in active profile\n  const handleListTenants = async () => {\n    const tenants = await services.tenants.list()\n    console.log('Tenants:', tenants)\n  }\n\n  // 3. Onboard new tenant\n  const handleOnboard = async () => {\n    const result = await onboardTenant({\n      tenantName: 'New Customer',\n      adminEmail: 'admin@newcustomer.com',\n      profile: activeProfile,\n      region: 'us-east',\n      tier: 'growth',\n    })\n    console.log('Tenant created:', result.tenantId)\n  }\n\n  // 4. Check environment health\n  const handleCheckHealth = async () => {\n    const health = await services.observability.health()\n    console.log('Environment health:', health)\n  }\n\n  return (\n    <div className=\"space-y-4\">\n      <button onClick={handleSwitchProfile}>Switch Profile</button>\n      <button onClick={handleListTenants}>List Tenants</button>\n      <button onClick={handleOnboard}>Onboard Tenant</button>\n      <button onClick={handleCheckHealth}>Check Health</button>\n    </div>\n  )\n}\n```\n\n---\n\n## Key Features\n\n✅ **Profile-Scoped Operations** — All service calls scoped to active profile\n✅ **Automatic Data Isolation** — Dev, Customer Zero, External Users data never mixed\n✅ **Complete Cloudflare Control** — 31 services managed from frontend\n✅ **Tenant Schema Allocation** — Automatic during onboarding\n✅ **10 Base Tenants** — Pre-configured for Dev & Customer Zero\n✅ **Observability Dashboard** — Real-time health & metrics\n✅ **Error Handling** — ServiceErrorClass with retry support\n✅ **Type Safety** — Full TypeScript with JSDoc\n\n---\n\n## Ready For\n\n✅ Phase 1: Platform Implementation (Week 1)\n✅ Phase 2: Multi-tenant deployment\n✅ Phase 3: External user rollout\n\nAll frontend-to-backend service wiring complete.\n"}