{"slug":"architecture/WORKBENCH_IMPLEMENTATION_GUIDE","title":"12 Department Workbenches - Implementation Guide","section":"architecture","sectionLabel":"Architecture","status":"unclassified","type":"document","path":"architecture/WORKBENCH_IMPLEMENTATION_GUIDE.mdx","bytes":13067,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n\n> **Tier C — Historical.** This document is a point-in-time snapshot preserved for reference. For current architecture, see [CANONICAL_PLATFORM_ARCHITECTURE.md](../architecture/CANONICAL_PLATFORM_ARCHITECTURE.md).\n\n## Overview\n\nThis is a **Spine-First, V0-Style** dashboard architecture. Each workbench renders domain-specific Spine EntityTypes with real metrics computed from CANONICAL_FIELDS. The system is adaptive—as users connect tools, the Spine hydrates and metrics activate automatically.\n\n---\n\n## Architecture\n\n```\nConnectors (28+)\n    ↓\nLoader (maps raw → CANONICAL_FIELDS)\n    ↓\nNormalizer (EntityType routing)\n    ↓\nSPINE (974 canonical fields across 12 domains)\n    ↓\nMetricEngine (computes from Spine rows)\n    ↓\nWorkbench (renders metrics + data gaps)\n```\n\n**Key principle:** A workbench never displays broken data. If Spine fields are null, it shows \"Connect [tool] to unlock\" instead.\n\n---\n\n## What You Have Now\n\n### Foundation Layer\n\n**`spine-types.ts`** (202 lines)\n- 18 EntityTypes (DEAL, ACCOUNT, INVOICE, INCIDENT, PATIENT, STUDENT, etc.)\n- 5 Null Policies (BLOCK, DERIVE, DEFAULT, ENRICH, SIGNAL)\n- 12 Domain Configs with phase assignments (P1-P4)\n- Complete TypeScript interfaces\n\n**`metric-engine.ts`** (286 lines)\n- `MetricEngine.computeMetric()` — evaluates formulas from Spine rows\n- Formula support: SUM, AVG, COUNT, RATE, RATIO, arbitrary arithmetic\n- Trend calculation with confidence scoring\n- Data quality assessment with actionable gap reporting\n- Null-policy-aware: returns \"insufficient_data\" when fields missing\n\n**`metrics-definitions.ts`** (351 lines)\n- **Phase 1 Metrics:** 25 live metric definitions across Sales/Finance/CSM/Engineering/Marketing\n- Each metric tied to Spine fields via `field_refs` and goals via `goal_refs`\n- Real-world thresholds (e.g., NRR > 110 is good, 100-110 is warning)\n- Organized by domain for easy discovery\n\n### Component Layer\n\n**`SpineCard.tsx`** (150 lines)\n- V0-style metric card with 5 status states (good/warning/critical/unknown/insufficient_data)\n- Trend indicators with direction arrows and percentage change\n- Data completeness progress bar\n- Recommendations for missing connectors\n- Fully dark mode compatible\n\n**`DataGapPrompt.tsx`** (134 lines)\n- Compact + full modes for flexible deployment\n- Shows critical missing fields with connector suggestions\n- Lists currently connected tools\n- Data quality score with visual breakdown\n- One-click \"Connect data sources\" CTA\n\n### Workbench Layer\n\n**`SalesRevOpsWorkbench.tsx`** (264 lines)\n- V0-style dashboard with command bar, filters, search\n- Real-time metric grid (3-column responsive layout)\n- Category tabs (All, Deals, Pipeline, Forecast)\n- Summary cards (Health Score, Total Metrics, Critical Count, Warnings)\n- Data gap prompt integration\n- Refresh + download controls\n\n---\n\n## Phase 1 Metrics (Ready Now)\n\n### Sales/RevOps (5 metrics)\n\n| Metric ID | Metric Name | Formula | Good | Spine Fields |\n|-----------|-------------|---------|------|--------------|\n| M-SALES-01 | Pipeline Value | SUM(deal_amount) | $1M+ | deal_amount |\n| M-SALES-02 | Win Rate | RATE(won, total) | 35%+ | deal_status, close_date |\n| M-SALES-03 | Sales Cycle | AVG(days_to_close) | <45d | created_at, close_date |\n| M-SALES-04 | Pipeline Coverage | (forecast / quota) * 100 | 300%+ | deal_amount, forecast_category, quota_target |\n| M-SALES-05 | Deal Velocity | COUNT(closed) / 30 | 5+/mo | deal_status, close_date |\n\n### Finance (5 metrics)\n\n| Metric ID | Metric Name | Formula | Good | Spine Fields |\n|-----------|-------------|---------|------|--------------|\n| M-FIN-01 | Monthly Recurring Revenue | SUM(monthly_contract_value) | $500k+ | monthly_contract_value |\n| M-FIN-02 | Days Sales Outstanding | AVG(days_outstanding) | <30d | invoice_date, payment_date |\n| M-FIN-03 | Collections Rate | (collected / invoiced) * 100 | 95%+ | invoice_amount, collected_amount |\n| M-FIN-04 | Revenue Recognition | (recognized / invoiced) * 100 | 98%+ | invoice_amount, revenue_recognized |\n| M-FIN-05 | Overdue Invoices | COUNT(overdue) | 0 | invoice_status, due_date |\n\n### CSM (5 metrics)\n\n| Metric ID | Metric Name | Formula | Good | Spine Fields |\n|-----------|-------------|---------|------|--------------|\n| M-CSM-01 | Net Revenue Retention | ((current - churn + expansion) / prior) * 100 | 110%+ | current_month_arr, churned_arr |\n| M-CSM-02 | Health Score | AVG(health_score) | 80+ | health_score, engagement_score |\n| M-CSM-03 | Churn Risk | COUNT(at_risk) | 0 | churn_probability, health_score |\n| M-CSM-04 | Expansion Opps | COUNT(expansion) | 25+ | usage_growth, feature_adoption |\n| M-CSM-05 | Feature Adoption | AVG(adoption_rate) | 75%+ | feature_adoption_count |\n\n### Engineering (3 metrics)\n\n| Metric ID | Metric Name | Formula | Good | Spine Fields |\n|-----------|-------------|---------|------|--------------|\n| M-ENG-01 | Mean Time To Resolve | AVG(time_to_resolution) | <4d | incident_created_at, resolved_at |\n| M-ENG-02 | Critical Incidents | COUNT(critical) | 0 | severity, incident_created_at |\n| M-ENG-03 | Deployment Frequency | COUNT(deployments) / 30 | 5+/mo | change_deployed_date |\n\n### Marketing (3 metrics)\n\n| Metric ID | Metric Name | Formula | Good | Spine Fields |\n|-----------|-------------|---------|------|--------------|\n| M-MKT-01 | Cost Per Acquisition | SUM(spend) / COUNT(customers) | <$2k | campaign_spend, customer_count |\n| M-MKT-02 | Marketing Qualified Leads | COUNT(mql) | 500+ | lead_score, engagement_score |\n| M-MKT-03 | Campaign ROI | ((revenue - spend) / spend) * 100 | 300%+ | campaign_spend, attributed_revenue |\n\n**Total:** 21 live metrics ready to compute from Spine data\n\n---\n\n## How to Use\n\n### 1. Render a Workbench\n\n```tsx\n\n  const spineRows = useSpineRows('sales_revops');\n  \n  const metrics = METRICS_BY_DOMAIN.sales_revops.map(metricDef =>\n    MetricEngine.computeMetric(metricDef, spineRows)\n  );\n\n  const dataQuality = MetricEngine.assessDataQuality(\n    'sales_revops',\n    spineRows,\n    CANONICAL_FIELDS // from Loader config\n  );\n\n  return (\n    <SalesRevOpsWorkbench\n      metrics={metrics}\n      dataQuality={dataQuality}\n      onRefresh={() => revalidateSpineCache()}\n      onConnectTools={() => router.push('/settings/connectors')}\n    />\n  );\n}\n```\n\n### 2. Compute a Single Metric\n\n```tsx\n\nconst pipelineMetric = MetricEngine.computeMetric(\n  SALES_REVOPS_METRICS[0],\n  spineRows,\n  historicalMetrics\n);\n\nconsole.log(pipelineMetric);\n// {\n//   metric_id: 'M-SALES-01',\n//   metric_name: 'Total Pipeline Value',\n//   value: 2500000,\n//   status: 'good',\n//   trend: { direction: 'up', percentage: 15, period: '30d' },\n//   confidence_score: 0.95,\n//   ...\n// }\n```\n\n### 3. Handle Data Gaps\n\n```tsx\n\nconst dataQuality = MetricEngine.assessDataQuality(\n  'sales_revops',\n  spineRows,\n  canonicalFields\n);\n\n// If Spine is shallow, render gap prompt instead of broken cards\n<DataGapPrompt \n  status={dataQuality}\n  onConnectClick={() => showConnectorModal()}\n/>\n```\n\n### 4. Build a New Workbench (Template)\n\n```tsx\n'use client';\n\n\ninterface MyWorkbenchProps {\n  metrics: ComputedMetric[];\n  dataQuality: DataQityStatus;\n  onRefresh?: () => void;\n}\n\n  return (\n    <div className=\"min-h-screen bg-slate-50 dark:bg-slate-950\">\n      \n      {dataQuality.overall_score < 80 && (\n        <DataGapPrompt status={dataQuality} />\n      )}\n\n      \n      <div className=\"max-w-7xl mx-auto px-6 py-8\">\n        <div className=\"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4\">\n          {metrics.map(metric => (\n            <SpineCard key={metric.metric_id} metric={metric} />\n          ))}\n        </div>\n      </div>\n    </div>\n  );\n}\n```\n\n---\n\n## Phase Roadmap\n\n### Phase 1 (Weeks 1-4) ✅ READY NOW\n- Sales/RevOps: Deal, Account, Opportunity pipeline visibility\n- Finance: Invoice, Revenue, Collections tracking\n- CSM: Account Health, NRR, Churn Risk\n- **Deliverable:** 3 live workbenches with real P1 metrics\n\n### Phase 2 (Weeks 5-8)\n- Engineering: Incident, Change, Deploy metrics\n- Marketing: Campaign, Lead, ROI tracking\n- Legal: Contract, Compliance, Risk management\n- **Deliverable:** 3 additional workbenches\n\n### Phase 3 (Weeks 9-12)\n- HR/People: Employee, Engagement, Attrition\n- Supply Chain: Supplier, Shipment, Inventory\n- Support: Ticket, Resolution, CSAT\n- **Deliverable:** 3 more workbenches\n\n### Phase 4 (Weeks 13-20)\n- Healthcare: Patient outcomes, Compliance, Quality\n- Education: Student, Course, Assessment outcomes\n- Freelancers: Contract, Performance, Payment\n- BizOps/Console: Cross-org analytics and governance\n\n---\n\n## Key Design Decisions\n\n1. **Spine-First Always** — Every metric reads from Spine, never connector-specific APIs\n2. **Graceful Degradation** — Null fields show prompts, not errors\n3. **Adaptive UX** — Metrics activate as Spine fields hydrate\n4. **V0 Aesthetic** — Minimal design, card grids, soft colors, professional typography\n5. **Reusable Components** — SpineCard, DataGapPrompt, MetricRenderer used everywhere\n6. **Type Safety** — Full TypeScript, no `any` types in critical paths\n7. **Real Thresholds** — All metrics use actual business benchmarks, not placeholder numbers\n\n---\n\n## Integration Points\n\n### With Loader\n```\nCANONICAL_FIELDS → Loader knows which connector field → maps to → Spine column\n```\n\n### With MCP\n```\nMCP reads Spine rows → passes to AI → AI reasons over fields → Workspace context is coherent\n```\n\n### With Goals/Metrics\n```\nMetric references Spine fields via field_refs → Metric formula computes → Goal_refs link to outcomes\n```\n\n### With Intelligence Layer\n```\nMetricEngine outputs → signal_type (positive/negative) → triggers alerts/recommendations\n```\n\n---\n\n## Files Structure\n\n```\npackages/domain-shells/workbenches/\n├── foundation/\n│   ├── spine-types.ts (202 lines)\n│   ├── metric-engine.ts (286 lines)\n│   └── metrics-definitions.ts (351 lines)\n├── components/\n│   ├── spine-card.tsx (150 lines)\n│   └── data-gap-prompt.tsx (134 lines)\n├── sales-revops-workbench.tsx (264 lines)\n├── finance-workbench.tsx (planned)\n├── csm-workbench.tsx (planned)\n├── engineering-workbench.tsx (planned)\n├── marketing-workbench.tsx (planned)\n├── legal-workbench.tsx (planned)\n├── hr-people-workbench.tsx (planned)\n├── supply-chain-workbench.tsx (planned)\n├── support-workbench.tsx (planned)\n├── healthcare-workbench.tsx (planned)\n├── education-workbench.tsx (planned)\n├── freelancers-workbench.tsx (planned)\n└── index.ts (56 lines)\n```\n\n**Total lines:** ~2,000 core + ~5,000 when all 12 workbenches built\n\n---\n\n## Next Steps\n\n1. ✅ Foundation layer complete (spine-types, metric-engine, metrics-definitions)\n2. ✅ Component layer complete (SpineCard, DataGapPrompt)\n3. ✅ Phase 1 Sales workbench complete and exported\n4. ⏭️ Build Finance workbench (same pattern as Sales)\n5. ⏭️ Build CSM workbench with NRR focus\n6. ⏭️ Continue with Engineering, Marketing, Legal, etc.\n\n---\n\n## Testing Guide\n\n### Unit Test: MetricEngine\n\n```tsx\n\nconst metric = MetricEngine.computeMetric(\n  { formula: 'SUM(amount)', field_refs: ['amount'] },\n  [{ data: { amount: 100 } }, { data: { amount: 200 } }]\n);\nexpect(metric.value).toBe(300);\n```\n\n### Component Test: SpineCard\n\n```tsx\n\nrender(\n  <SpineCard\n    metric={{\n      metric_id: 'M-TEST-01',\n      value: 2500000,\n      status: 'good',\n      ...\n    }}\n  />\n);\n\nexpect(screen.getByText('$2.5m')).toBeInTheDocument();\n```\n\n### E2E: Full Workbench\n\n```tsx\n// Navigate to /sales workbench\n// Verify all P1 metrics render\n// Click \"Connect [tool]\"\n// Verify data gap prompt shows correct fields\n```\n\n---\n\n## Color Reference\n\n- **Good**: emerald (#059669)\n- **Warning**: amber (#d97706)\n- **Critical**: red (#dc2626)\n- **Unknown**: slate (#64748b)\n- **Insufficient Data**: gray (#6b7280)\n\n---\n\n## Questions?\n\nRefer to:\n- `BRANDING_GUIDE.md` — Theme system\n- `BRANDING_INTEGRATION_COMPLETE.md` — Design tokens\n- `V0_DASHBOARD_STYLE_GUIDE.md` — V0 aesthetic rules\n- `V0_SHELL_DEPLOYMENT.md` — Deployment patterns\n"}