Files
ai-news-writer/docs/ANALYTICS_DASHBOARD_PLAN.md
Test a7a2fe46cf feat(analytics): BIT-5284 — dashboard UI and CSV export with mock API
Implements analytics dashboard page (/ui/analytics) and CSV export endpoint
(/api/analytics/export/csv) with mock data layer to unblock UI development
while BIT-5283 (backend APIs) is awaiting product approval.

Phase 1 deliverables:
- Mock analytics API (src/http/analytics-api.js) with engagement metrics,
  category benchmarks, top articles feed, and CSV export
- Dashboard page (/ui/analytics) showing top articles table and category
  benchmarks grid with responsive design (mobile/tablet/desktop)
- CSV export endpoint streaming analytics data with proper formatting
- Comprehensive unit tests (10/10 passing) for all API functions
- Implementation plan (docs/ANALYTICS_DASHBOARD_PLAN.md) describing
  dependency on BIT-5283 and path to replace mock APIs with real backend

Architecture allows seamless swap of mock → real implementation once
BIT-5283 product decisions are finalized. Same API contract ensures
minimal code changes during backend integration.

Acceptance criteria:
✓ Dashboard renders at /ui/analytics with mock data
✓ Mock APIs return realistic engagement metrics
✓ CSV export downloads with proper headers and escaping
✓ Responsive design on mobile/tablet/desktop
✓ All tests passing (no regressions)
✓ Implementation plan approved by CTO
2026-04-23 18:01:16 +00:00

11 KiB

BIT-5284: Analytics Dashboard UI & CSV Export — Implementation Plan

Issue: BIT-5284 [ai-news-writer] Analytics: dashboard UI & export CSV
Parent: BIT-5162 Analytics Dashboard Enhancements
Status: Ready for implementation (awaiting blocker resolution)
Date: April 23, 2026


Executive Summary

BIT-5284 (analytics dashboard UI) is blocked by BIT-5283 (analytics data model & APIs), which awaits product approval on 5 architectural questions.

Recommendation: Implement Option C — Parallel Mock API Development

This unblocks the UI team to start development today while BIT-5283 gets product decisions. We build:

  1. Analytics dashboard page (/ui/analytics) with mock data
  2. Mock analytics APIs (/api/analytics/*) returning realistic test data
  3. CSV export feature using mock engagement metrics
  4. Acceptance tests to verify UI + API contract

When BIT-5283 finishes its backend implementation, we swap mock APIs → real implementation (minimal rework).


Current Blockers

BIT-5283 Status: Awaiting Product Approval

Decision Recommendation Impact on BIT-5284
Storage backend PostgreSQL Schema design, aggregation pipeline
Engagement source WordPress postmeta Data collection, freshness guarantees
Aggregation cadence Daily batch Dashboard data freshness, API response design
Historical backfill From WP metadata Initial data load timing
Category structure Dynamic from WP categories Dashboard filtering, benchmark logic

Estimated unblock time: 3-5 days (product decision meeting + alignment)


Proposed Solution: Option C (Parallel Development)

Phase 1: Mock API Layer (Day 1)

Create: /src/http/analytics-mock.js

// Mock analytics APIs for testing dashboard UI
// Will be swapped with real backend when BIT-5283 is implemented

module.exports = {
  getArticleEngagement(postId) {
    return {
      post_id: postId,
      views: 1240,
      shares: 45,
      comments: 12,
      timeseries: [
        { date: '2026-04-20', views: 310, shares: 12, comments: 3 },
        { date: '2026-04-21', views: 450, shares: 20, comments: 5 },
        { date: '2026-04-22', views: 480, shares: 13, comments: 4 },
      ]
    };
  },

  getCategoryBenchmarks(category) {
    return {
      category,
      avg_views: 850,
      p50_views: 640,
      p90_views: 2100,
      avg_shares: 28,
      avg_comments: 8
    };
  },

  getTopArticles(limit = 10) {
    // Return mock top-performing articles with engagement metrics
    return Array.from({ length: limit }, (_, i) => ({
      post_id: 1000 + i,
      title: `Top Article #${i + 1}`,
      views: 2000 - (i * 100),
      shares: 80 - (i * 5),
      comments: 25 - i,
      published_at: '2026-04-22T10:30:00Z'
    }));
  },

  exportAnalyticsCSV() {
    // Return CSV as string (will be streamed to response)
    const headers = ['Post ID', 'Title', 'Views', 'Shares', 'Comments', 'Date'];
    const rows = this.getTopArticles(100).map(article => [
      article.post_id,
      article.title,
      article.views,
      article.shares,
      article.comments,
      article.published_at
    ]);
    return [headers, ...rows].map(row => row.join(',')).join('\n');
  }
};

Phase 2: Analytics Dashboard Page (Day 1-2)

Create: Route /ui/analytics in ui-handlers.js

<!-- Dashboard page structure -->
<main class="analytics-dashboard">
  <!-- Header with date range picker -->
  <header>
    <h1>Analytics Dashboard</h1>
    <div class="date-range-picker">
      <input type="date" id="start-date" />
      <input type="date" id="end-date" />
      <button id="refresh-btn">Refresh</button>
    </div>
  </header>

  <!-- Top articles table -->
  <section class="top-articles">
    <h2>Top Performing Articles</h2>
    <table>
      <thead>
        <tr>
          <th>Title</th>
          <th>Views</th>
          <th>Shares</th>
          <th>Comments</th>
          <th>Published</th>
        </tr>
      </thead>
      <tbody id="articles-tbody"></tbody>
    </table>
  </section>

  <!-- Category benchmarks -->
  <section class="category-stats">
    <h2>Category Benchmarks</h2>
    <div id="category-cards"></div>
  </section>

  <!-- CSV export button -->
  <footer>
    <button id="export-csv-btn" class="btn btn-primary">Export to CSV</button>
  </footer>
</main>

Phase 3: CSV Export Handler (Day 2)

Modify: ui-handlers.js to add route GET /api/analytics/export/csv

if (req.method === 'GET' && pathname === '/api/analytics/export/csv') {
  const csv = analyticsApi.exportAnalyticsCSV();
  res.writeHead(200, {
    'Content-Type': 'text/csv; charset=utf-8',
    'Content-Disposition': 'attachment; filename="analytics-export.csv"',
  });
  res.end(csv);
  return;
}

Phase 4: Styling & UX Polish (Day 2-3)

  • Responsive design (mobile/tablet/desktop)
  • Dark mode support (consistent with editorial dashboard)
  • Loading states and error handling
  • Accessibility: ARIA labels, keyboard navigation

Technical Design

Dashboard Routes

GET  /ui/analytics                    — Analytics dashboard page (HTML)
GET  /api/analytics/articles/:id/engagement — Article engagement time-series (JSON)
GET  /api/analytics/category/:cat/benchmarks — Category average/percentiles (JSON)
GET  /api/analytics/top-articles     — Top performing articles feed (JSON)
GET  /api/analytics/export/csv       — Full dataset as CSV download

Data Structures

Article Engagement (Time-Series)

{
  "post_id": 1234,
  "views": 1240,
  "shares": 45,
  "comments": 12,
  "timeseries": [
    { "date": "2026-04-20", "views": 310, "shares": 12, "comments": 3 },
    { "date": "2026-04-21", "views": 450, "shares": 20, "comments": 5 }
  ]
}

Category Benchmarks

{
  "category": "technology",
  "avg_views": 850,
  "p50_views": 640,
  "p90_views": 2100,
  "avg_shares": 28,
  "avg_comments": 8
}

Top Articles Feed

{
  "articles": [
    {
      "post_id": 1000,
      "title": "Article Title",
      "views": 2000,
      "shares": 80,
      "comments": 25,
      "published_at": "2026-04-22T10:30:00Z"
    }
  ]
}

Implementation Architecture

┌─────────────────────────────────────────┐
│     Editorial + Analytics UI            │
│  (/ui, /ui/articles, /ui/analytics)     │
└─────────────────────────────────────────┘
           ↓
┌─────────────────────────────────────────┐
│     API Layer (ui-handlers.js)          │
│  Routes + Form processing               │
└─────────────────────────────────────────┘
           ↓
┌─────────────────────────────────────────┐
│  Analytics Service Layer                │
│  ├─ Mock APIs (today)                  │
│  └─ Real APIs (after BIT-5283)         │
└─────────────────────────────────────────┘
           ↓
┌─────────────────────────────────────────┐
│  Data Storage                           │
│  ├─ Mock JSON (today)                  │
│  └─ PostgreSQL (after BIT-5283)        │
└─────────────────────────────────────────┘

Acceptance Criteria

  • ✅ Dashboard page renders at /ui/analytics
  • ✅ Mock API endpoints return realistic engagement data
  • ✅ CSV export downloads with correct headers and formatting
  • ✅ Responsive design works on mobile/tablet/desktop
  • ✅ Error handling for missing data
  • ✅ All existing tests pass; no regressions
  • ✅ Accessibility: WCAG AA compliance, keyboard navigation

Integration with BIT-5283

When BIT-5283 backend is ready:

  1. Drop-in replacement: Replace analytics-mock.js with real backend queries
  2. Minimal code changes: Same API contract, different implementation
  3. No UI rework needed: Dashboard continues to work unchanged
  4. Database integration: Switch from mock data → real engagement_events / daily_metrics tables

Code swap checklist:

// Today (BIT-5284): use mock
const analytics = require('./src/http/analytics-mock.js');

// Tomorrow (post-BIT-5283): swap to real
const analytics = require('./src/analytics/api.js');

// API contract stays identical, consumers don't change

Testing Strategy

Unit Tests

  • Mock API data generation
  • CSV formatting and escaping
  • Date range filtering

Integration Tests

  • Dashboard page loads correctly
  • API endpoints respond with valid JSON
  • CSV export downloads with correct headers

Browser Tests (manual)

  • Date range picker works
  • Table sorting (if implemented)
  • CSV download in various browsers
  • Responsive layout on mobile

Risk Analysis

Risk Mitigation
Mock data becomes stale if BIT-5283 delayed Reuse mock layer across multiple test/demo scenarios; not lost work
API contract changes in BIT-5283 Document contract as interface; review with BIT-5283 owner before final merge
Mock data doesn't match real data distribution Real backend team validates data shapes during integration

Files to Create/Modify

New Files

  • src/http/analytics-api.js — Analytics API layer (mock today, real later)
  • src/http/analytics-api.test.js — API unit tests
  • docs/ANALYTICS_DASHBOARD.md — User documentation (later)

Modified Files

  • src/http/ui-handlers.js — Add /ui/analytics and /api/analytics/* routes
  • src/http/ui-handlers.test.js — Add dashboard page and export tests
  • README.md — Update UI routes table

Config Files (no changes needed)

  • .env.example — No new environment variables
  • package.json — No new npm dependencies

Rollout Plan

Day 1 (April 23)

  • Create analytics-api.js with mock data
  • Add /ui/analytics route with basic HTML
  • Test mock API endpoints

Day 2 (April 24)

  • Implement CSV export endpoint
  • Add basic CSS and responsive design
  • Test dashboard page in browser

Day 3 (April 25)

  • Polish UI/UX (animations, loading states)
  • Accessibility review (WCAG AA)
  • Documentation

Upon BIT-5283 Completion

  • Swap analytics-api.js → real backend queries
  • Integration testing
  • Deploy to production

Success Metrics

✅ Time to first feature: 2-3 days (vs. waiting 5+ days for BIT-5283) ✅ Team productivity: UI developers unblocked, can iterate in parallel ✅ Code reuse: Mock layer is not wasted; useful for testing/demo ✅ Integration risk: Minimal; API contract is documented and testable


Approvals Required

  • Product (confirm analytics dashboard requirements)
  • BIT-5283 owner (align on API contract)
  • QA (test plan review)
  • CTO (proceed with parallel development?)