Skip to main content

Frontend Pages Implementation Guide - M5.3

Overview

This guide documents the four critical frontend pages built for S&OP decision-making workflows. These pages showcase the financial impact and scenario analysis capabilities of ChainAlign.

Status: ✅ Complete Commit: b9a5cba3 Lines of Code: 1700+ Components: 4 major pages + AppRoutes updates


Architecture

All frontend pages follow a consistent pattern:

  1. Data Fetching: Async API calls via apiClient
  2. State Management: React hooks (useState, useEffect)
  3. UI Components: shadcn/ui Card, Button, and custom components
  4. Integration: Guardrails validation, financial calculations
  5. Real-time Updates: WebSocket support via NotificationContext

Component Stack

  • React 18 with hooks
  • Lazy Loading for performance via React.lazy()
  • shadcn/ui design system (Card, Button)
  • Tailwind CSS for styling
  • Chart Recommender for financial visualizations
  • Trust Indicator for AI disclosure

Pages

1. HomePage.jsx (400+ lines)

Location: /frontend/src/components/pages/HomePage.jsx

Purpose: Role-based customized homepage showing personalized action items, news, insights, and collaboration status.

Key Features:

  • Zone A: Action Required

    • AI-driven context (e.g., "$2.3M revenue at risk due to detected bias patterns")
    • Business impact visualization
    • Smart entry point guidance
    • Direct action button
  • Zone B & C: Performance Snapshot & Strategic Alignment

    • Key performance metrics with trend indicators
    • Strategic objectives progress bars
    • External news alerts
    • Objective-to-metric mapping
  • Zone D: Background Intelligence

    • News feed from external sources
    • Recent insights from last visit
    • Impact flagging ("💡 Could affect Q4 margin")
  • Collaboration Status

    • Real-time team member actions
    • Decision approval status
    • Last activity timestamps

Data Sources:

GET /api/dashboard/home
{
actionRequired: {
cycleStatus: string,
aiContext: string, // "$2.3M revenue at risk..."
businessImpact: string, // "$2.3M"
actionButtonText: string,
actionPath: string,
smartEntryPoint: string // "Start with Widget-Pro (highest impact)"
},
performanceSnapshot: { metrics: [] },
strategicAlignment: { objectives: [], externalNews: string },
newsFeed: [],
insights: [],
collaborationStatus: []
}

Key Methods:

  • fetchHomeData() - Retrieves personalized dashboard data
  • Real-time subscription to collaboration updates (WebSocket ready)

Example Usage:

<Button onClick={() => window.location.href = actionRequired.actionPath}>
{actionRequired.actionButtonText}
</Button>

2. DemandPlannerPage.jsx (450+ lines)

Location: /frontend/src/components/pages/DemandPlannerPage.jsx

Purpose: Strategic demand data review workbench implementing the Demand Planner User Flow from FSD.

Key Components:

Panel A: The Data Workbench

  • Intelligent Chart Narratives

    • AI-generated action title summarizing the analysis
    • Multi-line time-series chart with scenario overlays
    • Scenario toggle buttons (Current Plan, AI Bias-Corrected, Conservative, Optimistic)
  • Live Data Validation

    • Real-time quality scoring (Completeness, Consistency, Timeliness)
    • Proactive issue flagging (e.g., "287% above historical seasonal pattern")
    • Visual progress bars for each dimension

Panel B: AI Insights & Decision Hub

  • Priority-Ordered Decisions
    • Each insight card shows:
      • Priority level (1, 2, 3...)
      • Insight title and type
      • Business impact estimate (e.g., "$1.2M WC Optimization")
      • Confidence score
      • AI assistance recommendations
    • Expandable cards with Apply/Customize/Keep actions
    • Max height with scrolling for many insights

Strategic Impact Card

  • Real-time impact cascading visualization
  • Monte Carlo preview showing probabilistic metrics
  • Effects on inventory optimization, service level, forecast accuracy

Workflow Intelligence Card

  • Overall progress percentage (visual bar)
  • Estimated time remaining
  • Next best action recommendation

Data Sources:

GET /api/demand-planner/review
{
actionTitle: string, // "Q4 plan is 12% above baseline..."
chartData: [],
scenarios: [],
selectedScenario: string,
aiInsights: [
{
id: string,
title: string,
type: string, // "BIAS_CORRECTION" | "PROMO_LIFT" | etc.
description: string,
impact: string, // "$1.2M WC Optimization"
confidence: string, // "95%"
}
],
dataQuality: { completeness: 88, consistency: 92, timeliness: 85 },
qualityIssues: [],
strategicImpact: {
metrics: [
{ label, description, change } // change can be % or absolute
],
monteCarloPreview: string
},
workflowStatus: {
percentComplete: number,
estimatedTimeRemaining: string, // "12 min"
nextBestAction: string
}
}

Key Actions:

POST /api/demand-planner/apply-insight
{ insightId, action: 'apply' | 'custom' | 'keep' }

POST /api/guardrails/validate-content
// Validates data quality via guardrails framework

POST /api/demand-planner/submit-plan
{ scenarioId, rationale }

Key Methods:

  • handleScenarioChange() - Switch between scenario views
  • handleValidateData() - Trigger guardrails validation
  • handleApplyInsight() - Apply AI recommendation
  • handleSubmitPlan() - Lock and submit plan

Example Insight Card:

<div className="border rounded-lg p-3">
<span className="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-bold rounded">
Priority 1
</span>
<p className="text-sm font-semibold text-gray-900 mt-2">
EMEA Bias Correction
</p>
<p className="text-xs text-green-700 font-medium">
💰 $1.2M WC Optimization
</p>
<p className="text-xs text-gray-600">
Confidence: 95%
</p>
</div>

3. DemandConsensusPage.jsx (400+ lines)

Location: /frontend/src/components/pages/DemandConsensusPage.jsx

Purpose: Interactive, collaborative workspace for Demand Review meetings. Implements the Demand Consensus Workbench from FSD.

Key Components:

Main Interactive Graph

  • Four Data Lines:

    1. Historical Sales (solid line, historical data)
    2. Statistical Baseline (dotted line, reference)
    3. Sales Forecast (dashed line, reference)
    4. Consensus Unconstrained Plan (solid, user-adjustable)
  • Editable Consensus Line (when unlocked)

    • Team can drag/adjust to build agreement
    • Real-time financial impact updates

Variance Analysis Pane

  • Top 5 Disagreements

    • Product family & region breakdown
    • Gap percentage highlighting
    • Statistical vs. Sales comparison
    • AI context explaining variance (e.g., "Planned promotion in Q4")
    • Quick-select buttons: "Use Stat" / "Use Sales"
  • Expandable Cards with decision guidance

Financial Impact Summary (Real-time)

  • Three Key KPIs:
    1. Projected Revenue
    2. Projected Gross Margin
    3. Service Level Impact
  • Updates live as consensus line adjusts
  • Change summary vs. statistical baseline

Data Sources:

GET /api/demand-consensus/data
{
historical: [], // historical sales data
statistical: [], // statistical forecast
sales: [], // sales/commercial forecast
consensus: [], // editable consensus plan
variances: [
{
id: string,
productFamily: string,
region: string,
period: string,
variancePercent: number,
statistical: number,
sales: number,
aiContext: string // explains the variance
}
],
financialImpact: {
projectedRevenue: string, // "$2.3M"
projectedMargin: string, // "24.5%"
serviceLevel: string, // "97%"
changes: { vsStatistical: string }
},
locked: boolean
}

Lock Consensus Modal:

  • Summary of plan KPIs
  • Key Assumptions & Rationale textarea (required)
  • Lock & Approve button (validates rationale before locking)
  • Plan becomes non-editable after locking
  • Generates audit trail entry

Key Actions:

POST /api/demand-consensus/adjust
{ period, adjustment: 'statistical' | 'sales' }
// Updates consensus line based on user choice

POST /api/demand-consensus/lock
{ consensusPlan, rationale }
// Locks the plan and logs decision

Key Methods:

  • handleAdjustConsensus() - Update consensus for period
  • handleLockConsensus() - Submit rationale and lock plan
  • Updates KPIs in real-time as adjustments are made

Meeting Flow:

  1. Facilitator directs discussion: "Team, largest gap is Widget-Pro Q4"
  2. Team adjusts consensus line upward to 20% above baseline
  3. Financial Impact Summary shows +$1.5M revenue, +2% margin impact
  4. Team agrees, facilitator clicks "Lock Consensus"
  5. Modal captures: "Consensus 15% above baseline due to Q4 marketing campaign with 95% confidence based on historical promo data"
  6. Plan locked, becomes input for Supply Review

4. EnhancedWhatIfWorkbenchPage.jsx (500+ lines)

Location: /frontend/src/components/pages/EnhancedWhatIfWorkbenchPage.jsx

Purpose: Strategic scenario analysis tool implementing the What-If Scenario Workbench v2.0 from FSD.

Key Design Principles:

  • Lead with the conclusion
  • Minimize cognitive load
  • Model outcomes, not tactics
  • Quantify risk clearly

Component States:

State 1: Scenario Selection

  • Shows existing scenarios with quick metrics
  • "Create New Scenario" button to enter builder

State 2: Strategic Scenario Builder

  • Predefined Strategic Options (radio buttons):

    1. "Eliminate Q1 Stockout Risk" - Accept $1.5M cost
    2. "Maximize Gross Margin" - Accept 12% stockout risk
    3. "Maintain Current Service Level" - Minimize cost
  • Custom Targets (for power users):

    • Target Service Level: [99]%
    • Working Capital Limit: $[25]M
    • Margin Target: [25]%
  • Generate Impact Analysis button (triggers analysis)

State 3: Decision-Focused Layout (Main View)

  • AI-Generated "Primary Insight" Headline (McKinsey-style)

    • Example: "Trading $1.5M in working capital for a 14-point stockout risk reduction delivers a net $2.8M benefit."
    • Prominently displayed in blue gradient card
  • Key Impact Table

    | KPI              | Baseline  | Scenario      | Impact      |
    |------------------|-----------|---------------|-------------|
    | Revenue at Risk | $4.2M | $1.4M | -$2.8M ✓ |
    | Working Capital | $22M | $23.5M | +$1.5M ↑ |
    | Service Level | 95% | 98% | +3% ↑ |
  • Interactive chart showing baseline vs. scenario projections

  • Action buttons: "Run Monte Carlo Simulation", "Promote to Plan"

  • Expandable "View All Scenarios Matrix" for deeper analysis

State 4: Enhanced Probabilistic Results

  • Headline Conclusion

    • Plain-language risk summary
    • Example: "78% probability of achieving service targets with 15% chance of exceeding cost estimates"
  • Confidence Levels (P10/P50/P90 translated)

    • 90% certain: Revenue protection > $2.1M
    • 50% likely: Total cost < $1.8M
    • 10% risk: Cost overrun could exceed $2.5M
  • Distribution chart (detailed view button)

  • Accept Risk Profile button

Data Sources:

GET /api/scenarios
{
scenarios: [
{
id: string,
name: string,
description: string,
projectedRevenue: string,
projectedMargin: string
}
],
baseline: { /* baseline scenario */ }
}

POST /api/scenarios/analyze
// Input: { strategyId } or { customTargets }
// Output:
{
name: string,
primaryInsight: string, // McKinsey-style headline
keyImpacts: [
{ label, baseline, scenario, delta }
],
confidenceScore: number,
chartData: []
}

POST /api/scenarios/monte-carlo
// Input: { scenarioId }
// Output:
{
headlineConclusion: string,
confidenceLevels: [
{ confidence: 90, value: string, description: string }
]
}

Key Methods:

  • handleGenerateAnalysis() - Generate scenario analysis
  • handleRunMonteCarloSimulation() - Run probabilistic analysis
  • handlePromoteScenario() - Promote to recommended plan

State Flow:

Scenario Selection

Strategic Builder (modal)

Decision-Focused Layout (main view)

[Optional] Monte Carlo Results

Promote to Plan → Consensus Lock-In

Integration with Guardrails:

// Scenario validation before promotion
POST /api/guardrails/validate-scenario
{
scenario: { id, name, predicted_impact },
projections: { period_1, period_2, ... }
}
// Returns: { status, riskLevel, requiresApproval }

API Integration

Endpoint Summary

Dashboard Endpoints:

GET /api/dashboard/home                    // HomePage data
GET /api/demand-planner/review // DemandPlannerPage data
GET /api/demand-consensus/data // DemandConsensusPage data
GET /api/scenarios // EnhancedWhatIfWorkbenchPage scenarios

Action Endpoints:

POST /api/demand-planner/apply-insight     // Apply AI recommendation
POST /api/demand-planner/submit-plan // Lock and submit plan
POST /api/demand-consensus/adjust // Adjust consensus line
POST /api/demand-consensus/lock // Lock and approve consensus
POST /api/scenarios/analyze // Generate scenario analysis
POST /api/scenarios/monte-carlo // Run probabilistic simulation
POST /api/scenarios/promote // Promote scenario to plan

Guardrails Integration:

POST /api/guardrails/validate-content      // Validate language/tone
POST /api/guardrails/validate-scenario // Validate financial assumptions
POST /api/guardrails/validate-financial // Validate financial data

Routing Configuration

All pages are registered in AppRoutes.jsx:

// Lazy-loaded imports
const HomePage = lazy(() => import('./components/pages/HomePage'));
const DemandPlannerPage = lazy(() => import('./components/pages/DemandPlannerPage'));
const DemandConsensusPage = lazy(() => import('./components/pages/DemandConsensusPage'));
const EnhancedWhatIfWorkbenchPage = lazy(() => import('./components/pages/EnhancedWhatIfWorkbenchPage'));

// Routes
{ index: true, element: <HomePage /> }, // Home
{ path: 'home', element: <HomePage /> }, // Explicit home
{ path: 'demand-planner', element: <DemandPlannerPage /> }, // Demand review
{ path: 'demand-consensus', element: <DemandConsensusPage /> }, // Consensus
{ path: 'what-if-workbench', element: <EnhancedWhatIfWorkbenchPage /> }, // Scenarios

Data Flow Example

Complete Demand Review Workflow

1. User visits HomePage (/)

2. Sees "Action Required" card: "$2.3M revenue at risk"

3. Clicks "Start Review (Focus on Widget-Pro)"

4. Navigates to DemandPlannerPage (/demand-planner)

5. Reviews demand data with AI insights

6. Applies bias corrections from AI recommendations

7. Submits demand plan

8. Navigates to DemandConsensusPage (/demand-consensus) for meeting

9. Team discusses and adjusts consensus line

10. Locks plan with rationale: "Consensus 15% above baseline due to Q4 marketing"

11. Consensus feeds into supply review

12. Team creates scenarios in EnhancedWhatIfWorkbenchPage (/what-if-workbench)

13. Reviews "Trading $1.5M WC for 14-point stockout reduction"

14. Promotes recommended scenario

15. Executive S&OP makes final decision

Performance Considerations

Lazy Loading

All pages use React.lazy() for code splitting:

const HomePage = lazy(() => import('./components/pages/HomePage'));

Data Fetching

  • Single API call per page mount
  • No cascading requests
  • Error boundaries for graceful degradation

Real-time Updates (Future)

  • WebSocket ready via NotificationContext
  • Collaboration status updates
  • Decision approval notifications

Streaming Architecture (Ready)

1. Load page shell instantly
2. Stream headline first (fastest)
3. Stream KPIs progressively
4. Stream charts last (heaviest)

Design System

Color Coding

  • Blue (#0B5ED7): Primary actions, insights
  • Green (#00D084, #00B74A): Positive impacts, approvals
  • Amber (#F59E0B): Warnings, risks
  • Red (#E84C3D): Errors, critical issues
  • Purple (#8B5CF6): Probabilistic results, Monte Carlo

Spacing & Typography

  • Tailwind CSS utility classes
  • Max-width constraints (max-w-7xl) for readability
  • Responsive grid layouts (grid-cols-1 md:grid-cols-2 lg:grid-cols-3)

Components Used

  • Card (CardHeader, CardTitle, CardContent) from shadcn/ui
  • Button (primary, secondary variants) from shadcn/ui
  • TrustIndicator for AI disclosure badges
  • ChartRecommender for financial visualizations

Testing

Unit Tests (TODO)

npm test -- HomePage.test.js
npm test -- DemandPlannerPage.test.js
npm test -- DemandConsensusPage.test.js
npm test -- EnhancedWhatIfWorkbenchPage.test.js

Integration Tests (TODO)

  • Full demand workflow from home to consensus lock
  • Scenario generation and Monte Carlo simulation
  • Guardrails validation integration
  • WebSocket collaboration updates

Manual Testing

  • Test each scenario path independently
  • Verify API error handling
  • Test with different user roles
  • Validate responsive design on mobile

Future Enhancements

Phase 2

  1. Streaming Implementation

    • Progressive headline rendering for scenarios
    • KPI table progressive population
    • Chart lazy-loading
  2. Collaboration Features

    • Real-time multi-user consensus editing
    • Inline comments on variance analysis
    • Approval workflows with notifications
  3. Advanced Analytics

    • Sensitivity analysis UI
    • What-if parameter exploration
    • Historical comparison (plan vs. actual)
  4. Mobile Optimization

    • Touch-friendly controls
    • Simplified layouts for small screens
    • Offline capability via PWA
  5. Accessibility

    • WCAG 2.1 AA compliance
    • Keyboard navigation
    • Screen reader support

Summary

These four frontend pages provide a complete S&OP decision-making experience:

HomePage - Personalized entry point with AI-driven priorities ✅ DemandPlannerPage - Strategic demand review with live insights ✅ DemandConsensusPage - Collaborative consensus building ✅ EnhancedWhatIfWorkbenchPage - Executive scenario analysis

Together with the backend guardrails, financial services, and evaluation framework, ChainAlign now provides an end-to-end platform for data-driven, AI-amplified S&OP decision-making.

Total Implementation: 1700+ lines of frontend code across 4 pages + routing updates Integration: Complete with guardrails, financial calculations, and decision logging Status: Ready for demo and user testing