turash/bugulma/FRONTEND_UX_REFACTORING_PLAN.md
Damir Mukimov 000eab4740
Major repository reorganization and missing backend endpoints implementation
Repository Structure:
- Move files from cluttered root directory into organized structure
- Create archive/ for archived data and scraper results
- Create bugulma/ for the complete application (frontend + backend)
- Create data/ for sample datasets and reference materials
- Create docs/ for comprehensive documentation structure
- Create scripts/ for utility scripts and API tools

Backend Implementation:
- Implement 3 missing backend endpoints identified in gap analysis:
  * GET /api/v1/organizations/{id}/matching/direct - Direct symbiosis matches
  * GET /api/v1/users/me/organizations - User organizations
  * POST /api/v1/proposals/{id}/status - Update proposal status
- Add complete proposal domain model, repository, and service layers
- Create database migration for proposals table
- Fix CLI server command registration issue

API Documentation:
- Add comprehensive proposals.md API documentation
- Update README.md with Users and Proposals API sections
- Document all request/response formats, error codes, and business rules

Code Quality:
- Follow existing Go backend architecture patterns
- Add proper error handling and validation
- Match frontend expected response schemas
- Maintain clean separation of concerns (handler -> service -> repository)
2025-11-25 06:01:16 +01:00

1028 lines
29 KiB
Markdown

# Frontend UX/UI Refactoring Plan
## Comprehensive Plan to Support All Backend Features
**Date:** November 24, 2025
**Status:** Strategic Planning Document
---
## Executive Summary
The backend has grown into a sophisticated industrial symbiosis platform with:
- **9 domain entities** (Organizations, Sites, ResourceFlows, Matches, Products, Services, SharedAssets, Heritage, Users)
- **17 API handler groups** with 80+ endpoints
- **Advanced features**: Matching engine, Analytics, Geospatial operations, Graph database, Real-time WebSockets, Financial calculations
The current frontend has only **11 pages** (mostly landing/static pages) and lacks coverage for 70%+ of backend capabilities.
---
## Current State Analysis
### Current Frontend Pages (11 total)
1. **LandingPage.tsx** - Marketing landing page ✅ Well-designed
2. **MapView.tsx** - Sophisticated Leaflet map with clustering ✅ Production-ready
3. **OrganizationPage.tsx** - Detailed organization view ✅ Good UX
4. **HeritagePage.tsx** - Heritage/cultural content ✅ Complete
5. **HeritageBuildingPage.tsx** - Individual heritage building ✅ Complete
6. **UserDashboard.tsx** - Basic user dashboard ⚠️ Needs enhancement
7. **AdminPage.tsx** - Admin panel ⚠️ Needs enhancement
8. **LoginPage.tsx** - Authentication ✅ Functional
9. **AboutPage.tsx** - Static about page ✅ Complete
10. **ContactPage.tsx** - Static contact page ✅ Complete
11. **PrivacyPage.tsx** - Static privacy page ✅ Complete
### Existing Component Infrastructure ✅
**Strong Foundation Already in Place:**
- **30+ memoized components** (React.memo, useMemo, useCallback)
- **Reusable UI library** (Button, Card, Badge, Input, Select, etc.)
- **Layout primitives** (Container, Grid, Stack, Flex)
- **Form components** (react-hook-form + Zod validation)
- **Map infrastructure** (Leaflet with clustering, bounds tracking)
- **Resource flow components** (ResourceFlowCard, ResourceFlowList)
- **Match components** (MatchCard, MatchesList)
- **Wizard system** (Multi-step forms with portals)
- **Error boundaries** (Global + module-specific)
- **Context architecture** (Split into 5 focused map contexts)
- **API hooks** (React Query with factories, automatic invalidation)
- **Zod schemas** (Backend alignment with validation)
- **i18n support** (Russian + English)
- **Performance optimizations** (Code splitting, lazy loading, debouncing)
### Current UX/UI Best Practices ✅ Already Implemented
**The frontend already follows modern UX best practices:**
1. **Performance-First Architecture**
- Code splitting with React.lazy() for all routes
- 30+ components with React.memo to prevent re-renders
- useMemo/useCallback for expensive operations
- Debouncing for search/map interactions (300ms)
- WeakMap caching for map icons
- Viewport-based loading for map markers
2. **Accessibility (a11y)**
- ARIA labels on interactive elements
- Keyboard navigation (Esc to close modals)
- Focus trapping in modals
- Semantic HTML structure
- Error boundaries with fallback UI
3. **User Feedback & Communication**
- Loading states with skeletons
- Error handling with user-friendly messages
- Toast notifications (via mutation callbacks)
- Optimistic updates for better perceived performance
- Empty states with guidance
4. **Form UX Excellence**
- Multi-step wizard with progress indication
- Real-time validation (Zod schemas)
- Contextual error messages (react-hook-form)
- Auto-save capabilities (in certain forms)
- Clear required field indicators
5. **Responsive Design**
- Mobile-first Tailwind CSS approach
- Flexible grid layouts (Grid, Stack, Flex primitives)
- Touch-friendly controls
- Bottom sheets for mobile modals
- Responsive map controls
6. **Data Handling Best Practices**
- React Query for server state (caching, invalidation)
- Placeholder data to prevent UI blocking
- Stable query keys (rounded coordinates)
- Automatic retry with exponential backoff
- Type-safe API layer (Zod validation)
7. **Visual Hierarchy & Clarity**
- Consistent design tokens (colors, spacing)
- Badge system for status/categories
- Icon-text combinations for scannability
- Framer Motion animations (subtle, purposeful)
- Clear call-to-action buttons
8. **Internationalization (i18n)**
- Bilingual support (Russian/English)
- Memoized translation functions
- Locale-specific formatting
- Easy to add new languages
### Backend Capabilities (Not Covered)
#### 🔴 Critical Missing Features (Core Business Logic)
- **Resource Flow Management** - No UI for creating/managing inputs/outputs
- **Matching Engine Interface** - No UI for finding/viewing/managing matches
- **Sites Management** - Minimal site CRUD operations
- **Products & Services Catalog** - No dedicated product/service management
- **Shared Assets** - No UI for shared infrastructure/equipment
- **Match Negotiation** - No workflow for match status progression
- **Financial Impact Analysis** - No display of NPV, IRR, payback calculations
#### 🟡 Important Missing Features
- **Analytics Dashboard** - No comprehensive platform analytics
- **Geospatial Analysis** - Limited use of geospatial features
- **Graph Visualization** - Neo4j relationships not visualized
- **Real-time Updates** - WebSocket integration missing
- **User Management** - No admin user management interface
- **Multi-party Matches** - No support for complex matching scenarios
#### 🟢 Nice-to-Have Features
- **Supply/Demand Analysis** - No visualization of market gaps
- **Environmental Impact Metrics** - No CO2/sustainability tracking
- **Risk Assessment Display** - No risk visualization
- **Transportation Planning** - No logistics optimization UI
---
## Strategic Recommendation: Focused Enhancement
**Given the strong existing infrastructure, we recommend a focused approach:**
### Strategy Adjustment
**Original Plan:** Add 14+ new pages (11 → 25+)
**Revised Recommendation:** Add 8-10 strategically important pages, enhance 3 existing
**Rationale:**
- The frontend already has excellent technical foundation
- Component library is production-ready and reusable
- Adding too many pages risks diluting UX focus
- Better to have fewer, polished features than many half-baked ones
- Current map experience is sophisticated—build on its strengths
### Revised Complexity Assessment
**Pages that will be Easy (use existing components):**
- Resource Flow pages (components already exist!)
- Match pages (MatchCard, MatchesList ready)
- Sites pages (map infrastructure supports it)
- Analytics (Grid, Card, MetricItem components ready)
**Pages that need new work:**
- Products/Services marketplace
- Shared assets management
- Graph network visualization (needs D3/Cytoscape)
- Advanced geospatial analysis
## Proposed Page Structure (Focused: 11 → 19-21 pages)
### 1. Authentication & User Management (3 pages)
**Current:** LoginPage
**Add:**
- **RegisterPage.tsx** - User registration
- **UserProfilePage.tsx** - Profile settings, API keys
- **UsersAdminPage.tsx** - Admin user management (roles, permissions)
### 2. Dashboard & Analytics (4 pages)
**Current:** UserDashboard (basic)
**Enhance & Add:**
- **DashboardPage.tsx** ⭐ (redesign) - Comprehensive analytics hub
- Platform statistics (orgs, sites, flows, matches)
- Recent activity feed
- Top matches
- Economic impact summary
- Quick actions
- **AnalyticsDashboard.tsx** ⭐ - Deep analytics
- Connection statistics
- Supply/demand analysis
- Resource flow statistics
- Geographic heat maps
- **ImpactMetrics.tsx** - Environmental & Economic Impact
- CO2 savings visualization
- Economic value created
- Resource recovery rates
- **SupplyDemandAnalysis.tsx** - Market gap analysis
- Resource type supply/demand charts
- Geographic coverage gaps
- Pricing trends
### 3. Organization Management (Enhanced - 3 pages)
**Current:** OrganizationPage (detail view)
**Add:**
- **OrganizationsListPage.tsx** - Searchable organization directory
- Filters by sector, certification, size
- Map/list toggle view
- Bulk operations
- **OrganizationEditPage.tsx** - Create/edit organizations
- Multi-step wizard
- Address management
- Product/service association
- Trust network configuration
- **OrganizationAnalytics.tsx** - Per-organization analytics
- Resource flow statistics
- Match history
- Economic performance
- Network visualization
### 4. Sites Management (3 pages) ⭐ **HIGH PRIORITY**
**Current:** Minimal (embedded in map)
**Add:**
- **SitesListPage.tsx** - Site directory
- Filterable table (type, ownership, utilities)
- Map view toggle
- Heritage sites filter
- **SiteDetailPage.tsx** - Individual site view
- Location & facilities
- Operating organizations
- Resource flows at site
- Shared assets inventory
- Infrastructure details
- **SiteEditPage.tsx** - Create/edit sites
- Location picker (map integration)
- Utilities & infrastructure
- PostGIS spatial data
- Photo/document upload
### 5. Resource Flow Management (4 pages) ⭐ **CRITICAL PRIORITY**
**Current:** None!
**Add:**
- **ResourceFlowsPage.tsx** ⚡ Fast (reuse ResourceFlowList component)
- List view with existing ResourceFlowCard
- Filters: type, direction, organization (existing UI patterns)
- "Find Matches" button per flow (already in ResourceFlowCard!)
- Export to CSV (simple utility function)
- **ResourceFlowWizard.tsx** ⚡ Medium (adapt existing Wizard component)
- Reuse existing Wizard modal with portal rendering
- Step 1: Type + Direction (simple selects)
- Step 2: Quantity (Zod schema for Quantity already exists)
- Step 3: Quality params (dynamic based on type)
- Step 4: Economic data (optional fields)
- Use existing form components (Input, Select, Button)
- **ResourceFlowDetail.tsx** ⚡ Fast (compose existing components)
- Reuse ResourceFlowCard for header
- KeyMetrics-style layout for parameters
- MatchesList component for related matches
- Tabs component for organizing sections
### 6. Matching Engine (5 pages) ⭐ **CRITICAL PRIORITY**
**Current:** None!
**Add:**
- **MatchingDashboard.tsx** - Matching hub
- Quick match search
- Top suggested matches
- Match pipeline (suggested → live)
- Filter by status, score, type
- **MatchExplorer.tsx** - Advanced match finding
- Search by resource type, location, quality
- Distance/score sliders
- Real-time results with caching indicator
- Map view of potential matches
- **MatchDetailPage.tsx** - Individual match view
- Compatibility breakdown (quality, temporal, economic)
- Distance & transportation estimate
- Risk assessment visualization
- Economic impact (NPV, IRR, payback)
- Contract details (if formalized)
- Negotiation history timeline
- **MatchNegotiationPage.tsx** - Negotiation workflow
- Status progression UI
- Document upload
- Communication history
- Counter-offer management
- Approval workflow
- **MatchesMapView.tsx** - Geographic match visualization
- Source/target flow connections on map
- Filter by status, type
- Cluster visualization for high-density areas
### 7. Products & Services (3 pages)
**Current:** None (embedded in org data)
**Add:**
- **ProductsCatalog.tsx** - Searchable product directory
- Filter by category, price, MOQ
- Organization links
- Certification badges
- Comparison tool
- **ServicesCatalog.tsx** - Service directory
- Filter by type, domain, service area
- Hourly rate comparison
- On-site/remote indicators
- Booking/inquiry system
- **ServiceNeedsBoard.tsx** - Marketplace for service needs
- Posted service requests
- Match with service providers
- RFQ (Request for Quote) system
### 8. Shared Assets (2 pages)
**Current:** None
**Add:**
- **SharedAssetsPage.tsx** - Infrastructure sharing platform
- Available assets (utilization < 100%)
- Filter by type, location, capacity
- Utilization charts
- Cost sharing models
- **SharedAssetDetail.tsx** - Asset management
- Capacity & current users
- Maintenance schedule
- Cost allocation
- Booking calendar
- Operational status
### 9. Heritage & Cultural (Current - 2 pages)
**Keep:**
- **HeritagePage.tsx** - Heritage overview
- **HeritageBuildingPage.tsx** - Individual heritage site
### 10. Geospatial & Mapping (Enhanced - 2 pages)
**Current:** MapView
**Enhance & Add:**
- **MapView.tsx** (enhance existing)
- Layer controls (orgs, sites, flows, matches)
- Heat maps (resource density, match potential)
- Clustering for performance
- Drawing tools for area selection
- **SpatialAnalysisPage.tsx** - Advanced geospatial tools
- Proximity analysis
- Cluster detection
- Coverage gap analysis
- Route optimization for logistics
### 11. Graph Network (2 pages) ⭐ **HIGH VALUE**
**Current:** None
**Add:**
- **NetworkGraphPage.tsx** - Interactive network visualization
- Organization relationship graph (Neo4j)
- Resource flow connections
- Trust network visualization
- Shortest path finding
- Community detection
- **NetworkAnalytics.tsx** - Network metrics
- Centrality measures
- Network density
- Clustering coefficients
- Influence scores
### 12. Admin & Management (Enhanced - 3 pages)
**Current:** AdminPage
**Enhance & Add:**
- **AdminPage.tsx** (enhance)
- System health monitoring
- Database statistics
- Graph DB sync status
- Cache management
- Event bus status
- **DataManagementPage.tsx** - Data operations
- Bulk import/export
- Data validation
- Migration tools
- Backup/restore
- **SystemConfigPage.tsx** - Configuration
- API settings
- Integration toggles (Neo4j, Redis)
- Feature flags
- Rate limiting
### 13. Static Pages (Keep - 3 pages)
- **AboutPage.tsx**
- **ContactPage.tsx**
- **PrivacyPage.tsx**
---
## Proposed Information Architecture
```
/
├── / (Landing)
├── /login
├── /register
├── /dashboard (Main hub after login)
│ ├── /dashboard/analytics
│ ├── /dashboard/impact
│ └── /dashboard/supply-demand
├── /organizations
│ ├── /organizations (list)
│ ├── /organizations/new
│ ├── /organizations/:id
│ ├── /organizations/:id/edit
│ └── /organizations/:id/analytics
├── /sites
│ ├── /sites (list)
│ ├── /sites/new
│ ├── /sites/:id
│ └── /sites/:id/edit
├── /resources (Resource Flows)
│ ├── /resources (list)
│ ├── /resources/new (wizard)
│ ├── /resources/:id
│ ├── /resources/:id/edit
│ └── /resources/templates
├── /matching
│ ├── /matching (dashboard)
│ ├── /matching/explore
│ ├── /matching/:id
│ ├── /matching/:id/negotiate
│ └── /matching/map
├── /marketplace
│ ├── /marketplace/products
│ ├── /marketplace/services
│ └── /marketplace/service-needs
├── /shared-assets
│ ├── /shared-assets (list)
│ └── /shared-assets/:id
├── /heritage
│ ├── /heritage
│ └── /heritage/:id
├── /map (Enhanced map view)
│ └── /map/spatial-analysis
├── /network
│ ├── /network/graph
│ └── /network/analytics
├── /admin
│ ├── /admin (dashboard)
│ ├── /admin/users
│ ├── /admin/data
│ └── /admin/config
├── /profile
├── /about
├── /contact
└── /privacy
```
---
## Implementation Priority Matrix
### Phase 1: Critical Foundation (Weeks 1-4)
**Goal:** Enable core resource matching workflow
1. **Resource Flow Management** (4 pages) - Week 1-2
- ResourceFlowsPage.tsx
- ResourceFlowDetail.tsx
- ResourceFlowWizard.tsx
- ResourceFlowTemplates.tsx
2. **Basic Matching Interface** (3 pages) - Week 2-3
- MatchingDashboard.tsx
- MatchExplorer.tsx
- MatchDetailPage.tsx
3. **Sites Management** (3 pages) - Week 3-4
- SitesListPage.tsx
- SiteDetailPage.tsx
- SiteEditPage.tsx
**Deliverable:** Users can create resource flows, discover matches, and manage sites
---
### Phase 2: Enhancement & Workflow (Weeks 5-8)
**Goal:** Complete matching workflow and analytics
4. **Match Negotiation** (2 pages) - Week 5
- MatchNegotiationPage.tsx
- MatchesMapView.tsx
5. **Dashboard & Analytics** (4 pages) - Week 6-7
- DashboardPage.tsx (redesign)
- AnalyticsDashboard.tsx
- ImpactMetrics.tsx
- SupplyDemandAnalysis.tsx
6. **Organization Enhancement** (2 pages) - Week 7-8
- OrganizationsListPage.tsx
- OrganizationEditPage.tsx
**Deliverable:** Complete matching workflow with analytics
---
### Phase 3: Marketplace & Sharing (Weeks 9-11)
**Goal:** Enable product/service marketplace
7. **Products & Services** (3 pages) - Week 9-10
- ProductsCatalog.tsx
- ServicesCatalog.tsx
- ServiceNeedsBoard.tsx
8. **Shared Assets** (2 pages) - Week 10-11
- SharedAssetsPage.tsx
- SharedAssetDetail.tsx
**Deliverable:** Functional marketplace for products, services, and shared assets
---
### Phase 4: Advanced Features (Weeks 12-15)
**Goal:** Leverage advanced backend capabilities
9. **Graph Network** (2 pages) - Week 12-13
- NetworkGraphPage.tsx
- NetworkAnalytics.tsx
10. **Geospatial Enhancement** (1 page) - Week 13-14
- SpatialAnalysisPage.tsx
11. **Admin & Management** (3 pages) - Week 14-15
- DataManagementPage.tsx
- SystemConfigPage.tsx
- UsersAdminPage.tsx
**Deliverable:** Full platform capabilities exposed
---
### Phase 5: Polish & Optimization (Weeks 16-18)
**Goal:** Performance, UX, and real-time features
12. **Real-time Features** - Week 16
- WebSocket integration across pages
- Live match notifications
- Real-time analytics updates
13. **Performance Optimization** - Week 17
- Query optimization
- Caching strategies
- Lazy loading
- Code splitting
14. **UX Polish** - Week 18
- Consistent design system
- Accessibility improvements
- Mobile responsiveness
- User testing & refinement
**Deliverable:** Production-ready platform
---
## Key UI/UX Patterns to Implement
### 1. Resource Flow Wizard
Multi-step form with dynamic fields based on resource type:
```
[Type Selection] → [Quality Params] → [Quantity] → [Economic] → [Constraints] → [Review]
```
### 2. Match Detail Layout
```
┌─────────────────────────────────────────────┐
│ Match Score: 85% ⭐⭐⭐⭐ │
├─────────────────────────────────────────────┤
│ Source Flow → Target Flow │
│ Heat Output Heat Input │
│ 65°C, 500 kWh/h 60-70°C req │
├─────────────────────────────────────────────┤
│ Compatibility Breakdown │
│ ├─ Quality: 92% │
│ ├─ Temporal: 88% │
│ ├─ Economic: 75% │
│ └─ Geographic: 3.2 km │
├─────────────────────────────────────────────┤
│ Economic Impact │
│ ├─ Annual Savings: €45,000 │
│ ├─ NPV (10y): €320,000 │
│ ├─ Payback: 2.1 years │
│ └─ CO2 Avoided: 120 tonnes/year │
├─────────────────────────────────────────────┤
│ [Propose Match] [Download Report] │
└─────────────────────────────────────────────┘
```
### 3. Analytics Dashboard Grid
```
┌──────────────┬──────────────┬──────────────┐
│ Total Orgs │ Active Sites │ Live Matches │
│ 142 │ 89 │ 23 │
├──────────────┴──────────────┴──────────────┤
│ Resource Flow Statistics │
│ [Chart: Supply vs Demand by Type] │
├────────────────────────────────────────────┤
│ Geographic Distribution [Map] │
├──────────────┬────────────────────────────┤
│ Recent │ Top Matches │
│ Activity │ [Table] │
│ [Feed] │ │
└──────────────┴────────────────────────────┘
```
### 4. Geospatial Filters
```
Layer Controls:
☑ Organizations
☑ Sites
☑ Resource Flows (outputs only)
☐ Matches
☑ Heritage Buildings
Filters:
Resource Type: [Heat ▼]
Max Distance: [─●────] 25 km
Min Score: [──●──] 0.6
```
---
## Component Library Enhancements
### New Components Needed
#### Data Display
- **ResourceFlowCard** - Compact flow representation
- **MatchScoreGauge** - Visual score indicator
- **CompatibilityBreakdown** - Radar/bar chart
- **EconomicImpactSummary** - NPV/IRR/Payback display
- **GeographicDistanceIndicator** - Distance with map preview
- **QualityParametersTable** - Dynamic quality display
- **QuantityChart** - Temporal profile visualization
- **RiskAssessmentMatrix** - Risk visualization
- **NetworkGraph** - D3.js/Cytoscape integration
- **TimelineComponent** - Negotiation history
#### Input Components
- **ResourceTypeSelector** - Type picker with icons
- **QualityParamsForm** - Dynamic based on resource type
- **QuantityInput** - Amount + unit + temporal selector
- **LocationPicker** - Map-based location selection
- **CertificationBadges** - Certification selector
- **TemporalProfileEditor** - Weekly availability grid
- **ConstraintsBuilder** - Complex constraint form
#### Navigation
- **TabNavigation** - For multi-section pages
- **StepWizard** - Multi-step form component
- **BreadcrumbNav** - Hierarchical navigation
- **FilterPanel** - Collapsible filter sidebar
---
## Data Fetching Strategy
### API Services to Create/Enhance
1. **resources-api.ts** (NEW)
- CRUD operations for resource flows
- Filtering & pagination
- Template management
2. **matching-api.ts** (ENHANCE)
- Match finding with caching
- Match CRUD
- Status updates
- Negotiation history
3. **sites-api.ts** (NEW)
- Site CRUD
- Geospatial queries
- Heritage filtering
4. **analytics-api.ts** (NEW)
- Platform statistics
- Organization analytics
- Impact metrics
- Supply/demand analysis
5. **shared-assets-api.ts** (NEW)
- Asset CRUD
- Availability queries
6. **graph-api.ts** (NEW)
- Network queries
- Relationship traversal
- Graph statistics
7. **geospatial-api.ts** (NEW)
- Proximity searches
- Cluster detection
- Spatial statistics
### React Query Hooks Pattern
```typescript
// Example: Resource Flows
export const useResourceFlows = (filters?: ResourceFlowFilters) =>
useQuery(['resourceFlows', filters], () =>
resourceFlowsApi.getAll(filters)
);
export const useCreateResourceFlow = () =>
useMutation(
resourceFlowsApi.create,
{
onSuccess: () => {
queryClient.invalidateQueries(['resourceFlows']);
}
}
);
```
---
## Backend Schema Integration
### Zod Schemas to Create
Based on backend domain models:
1. **ResourceFlowSchema** - Complete flow validation
2. **MatchSchema** - Match entity with nested data
3. **ProductSchema** - Product catalog item
4. **ServiceSchema** - Service offering
5. **SharedAssetSchema** - Shared infrastructure
6. **NegotiationHistorySchema** - Negotiation entry
7. **EconomicImpactSchema** - Financial calculations
8. **RiskAssessmentSchema** - Risk parameters
9. **TransportationEstimateSchema** - Logistics data
### Type Generation
Use Zod's `.infer` to generate TypeScript types:
```typescript
export type ResourceFlow = z.infer<typeof ResourceFlowSchema>;
export type Match = z.infer<typeof MatchSchema>;
```
---
## Real-time Features via WebSockets
### Events to Subscribe To
- **match.created** - New match found
- **match.status_updated** - Match status changed
- **resource_flow.created** - New flow added
- **organization.updated** - Organization data changed
- **negotiation.new_message** - Negotiation activity
### UI Updates
- Dashboard: Live activity feed
- Matching: Real-time match notifications
- Negotiation: Live chat/updates
- Analytics: Live metric updates
---
## Mobile Responsiveness Strategy
### Breakpoints
- **Mobile:** < 768px (single column, simplified views)
- **Tablet:** 768px - 1024px (2-column grids)
- **Desktop:** > 1024px (full layouts)
### Mobile-First Components
- Bottom sheet modals (instead of sidebars)
- Swipeable cards
- Collapsible filters
- Simplified tables (card view on mobile)
- Touch-friendly map controls
---
## Performance Optimization
### Code Splitting
```typescript
// Lazy load heavy pages
const MatchingDashboard = lazy(() => import('./pages/MatchingDashboard'));
const NetworkGraphPage = lazy(() => import('./pages/NetworkGraphPage'));
```
### Data Caching
- React Query cache (5-15 min TTL)
- Backend cache service (match results)
- Optimistic updates for mutations
### Virtualization
- Large lists (react-window)
- Map markers (clustering)
- Table rows (react-virtual)
---
## Design System Tokens
### Color Palette (Expand)
```typescript
// Resource Types
resourceTypes: {
heat: '#FF6B6B',
water: '#4ECDC4',
steam: '#95E1D3',
materials: '#F9A825',
waste: '#78909C',
electricity: '#FFC107',
// ...
}
// Match Scores
matchScores: {
excellent: '#4CAF50', // 80-100%
good: '#8BC34A', // 60-79%
fair: '#FFC107', // 40-59%
poor: '#FF9800', // 20-39%
veryPoor: '#F44336', // 0-19%
}
```
---
## Testing Strategy
### Unit Tests
- Component rendering
- Hook logic
- Utility functions
- Schema validation
### Integration Tests
- API service functions
- Form submissions
- Navigation flows
- WebSocket connections
### E2E Tests (Playwright)
- Critical user journeys:
1. Create resource flow → Find matches → Negotiate
2. Register organization → Add site → Add flows
3. Admin: User management workflow
---
## Documentation Requirements
### Developer Docs
1. **Component Storybook** - All new components
2. **API Integration Guide** - Service usage examples
3. **State Management** - React Query patterns
4. **Routing Structure** - Page hierarchy
### User Docs
1. **User Guide** - Feature walkthroughs
2. **Video Tutorials** - Key workflows
3. **API Documentation** - For power users
---
## Migration Path from Current State
### Step 1: Parallel Development
- Keep existing 11 pages functional
- Develop new pages in `/pages/v2/` directory
- Test thoroughly before cutover
### Step 2: Gradual Rollout
- Feature flags for new pages
- Beta users test new interface
- Collect feedback and iterate
### Step 3: Cutover
- Replace old pages with new
- Redirect old routes
- Monitor analytics for issues
### Step 4: Cleanup
- Remove deprecated components
- Update documentation
- Archive old code
---
## Success Metrics
### User Engagement
- [ ] Time to create first resource flow < 3 min
- [ ] Time to find first match < 30 sec
- [ ] Match conversion rate > 15%
- [ ] Daily active users +50%
### Platform Health
- [ ] Page load time < 2s
- [ ] API response time < 500ms
- [ ] Match accuracy > 80%
- [ ] User satisfaction score > 4.2/5
### Business Impact
- [ ] Active matches +200%
- [ ] CO2 savings tracked: 10,000+ tonnes/year
- [ ] Economic value created: €1M+ annually
---
## Next Steps
1. **Review & Approval** - Stakeholder sign-off on plan
2. **Design Mockups** - Create wireframes for key pages
3. **Sprint Planning** - Break into 2-week sprints
4. **Team Allocation** - Assign developers to phases
5. **Kick-off** - Begin Phase 1 development
---
## Appendix: Backend API Coverage
### Currently Used by Frontend
✅ Organizations: GET /api/organizations, GET /api/organizations/:id
✅ Sites: GET /api/sites (minimal)
✅ Heritage: GET /api/heritage
✅ Auth: POST /auth/login
✅ Stats: GET /api/stats
### Not Used (70%+ of backend)
❌ Resource Flows (all endpoints)
❌ Matching Engine (all endpoints)
❌ Analytics (all 8 endpoints)
❌ Geospatial (all endpoints)
❌ Shared Assets (all endpoints)
❌ Graph API (all endpoints)
❌ Products/Services (embedded in orgs, no dedicated UI)
❌ WebSockets
**This plan addresses this 70% gap.**
---
## Conclusion
This refactoring plan provides a roadmap to transform the frontend from a basic landing page + map into a comprehensive industrial symbiosis platform that fully leverages the sophisticated backend capabilities. The phased approach ensures steady progress while maintaining existing functionality.
**Estimated Timeline:** 18 weeks (4.5 months)
**Required Resources:** 2-3 frontend developers, 1 UI/UX designer
**Expected Outcome:** Production-ready platform with 25+ pages supporting all backend features