# User Dashboard - Focused Implementation Plan ## Complete User Experience Lifecycle ### 🎯 **User Dashboard Workflow** The user dashboard must follow this specific user journey: 1. **Registration & Onboarding** → User creates account and sets preferences 2. **Marketplace Discovery** → Browse, search, and discover services/apps 3. **Purchase & Deployment** → Buy services, deploy apps, track orders 4. **Active Management** → Monitor deployments, manage services 5. **Profile & Preferences** → Customize experience, manage settings 6. **Analytics & Insights** → Track spending, usage patterns, optimization --- ## 🏗️ **Implementation Strategy - User Lifecycle** ### **Phase 1: User Activity Tracking** 🔄 **Foundation** **Target**: Track all user actions for comprehensive activity timeline #### **1.1 Enhanced UserActivity Model** ```rust // src/models/user.rs - Comprehensive activity tracking #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UserActivity { pub id: String, pub user_email: String, pub activity_type: ActivityType, pub description: String, pub timestamp: DateTime, pub metadata: HashMap, pub related_entity_id: Option, // Product ID, Service ID, etc. pub related_entity_type: Option, // "product", "service", "app" pub impact_level: ActivityImpact, pub session_id: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ActivityType { Login, Logout, MarketplaceBrowse, ProductView, CartAdd, CartRemove, Purchase, ServiceDeploy, AppDeploy, ProfileUpdate, PreferencesUpdate, WalletTransaction, PoolInvestment, ServiceRating, SupportRequest, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ActivityImpact { Low, // Browsing, viewing Medium, // Profile updates, cart actions High, // Purchases, deployments, transactions } ``` #### **1.2 Activity Tracking Service** ```rust // src/services/user_service.rs - Activity management impl UserService { pub fn track_activity(&self, user_email: &str, activity: UserActivity) -> Result<(), String> { let mut persistent_data = UserPersistence::load_user_data(user_email) .unwrap_or_else(|| UserPersistence::create_default_user_data(user_email)); persistent_data.user_activities.push(activity); // Keep only last 1000 activities to prevent data bloat if persistent_data.user_activities.len() > 1000 { persistent_data.user_activities.drain(0..persistent_data.user_activities.len() - 1000); } UserPersistence::save_user_data(user_email, &persistent_data) } pub fn get_user_activities(&self, user_email: &str, limit: Option, filter: Option) -> Vec { if let Some(data) = UserPersistence::load_user_data(user_email) { let mut activities = data.user_activities; // Filter by activity type if specified if let Some(filter_type) = filter { activities.retain(|a| std::mem::discriminant(&a.activity_type) == std::mem::discriminant(&filter_type)); } // Sort by timestamp (most recent first) activities.sort_by(|a, b| b.timestamp.cmp(&a.timestamp)); // Apply limit if let Some(limit) = limit { activities.truncate(limit); } activities } else { Vec::new() } } pub fn get_activity_summary(&self, user_email: &str, days: i32) -> HashMap { let activities = self.get_user_activities(user_email, None, None); let cutoff_date = Utc::now() - chrono::Duration::days(days as i64); let recent_activities: Vec<&UserActivity> = activities.iter() .filter(|a| a.timestamp > cutoff_date) .collect(); let mut summary = HashMap::new(); for activity in recent_activities { let activity_name = format!("{:?}", activity.activity_type); *summary.entry(activity_name).or_insert(0) += 1; } summary } } ``` ### **Phase 2: Purchase & Deployment Management** 🔄 **Core Feature** **Target**: Comprehensive purchase tracking and deployment monitoring #### **2.1 Enhanced Purchase Models** ```rust // src/models/user.rs - Purchase and deployment tracking #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PurchaseRecord { pub id: String, pub transaction_id: String, pub product_id: String, pub product_name: String, pub product_type: ProductType, pub provider_id: String, pub provider_name: String, pub amount: Decimal, pub currency: String, pub purchase_date: DateTime, pub status: PurchaseStatus, pub deployment_info: Option, pub service_period: Option, pub rating: Option, pub review: Option, pub support_tickets: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ProductType { Service, Application, ComputeSlice, Storage, Network, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PurchaseStatus { Pending, Active, Completed, Cancelled, Refunded, Expired, Suspended, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DeploymentInfo { pub deployment_id: String, pub status: DeploymentStatus, pub region: String, pub node_id: Option, pub resources_allocated: ResourceAllocation, pub uptime_percentage: f32, pub last_health_check: DateTime, pub deployment_url: Option, pub access_credentials: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum DeploymentStatus { Deploying, Running, Stopped, Error, Maintenance, Scaling, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ResourceAllocation { pub cpu_cores: f32, pub memory_gb: f32, pub storage_gb: f32, pub bandwidth_mbps: f32, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ServicePeriod { pub start_date: DateTime, pub end_date: Option>, pub auto_renewal: bool, pub hours_used: f32, pub sessions_completed: i32, pub next_billing_date: Option>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AccessCredentials { pub username: Option, pub password: Option, pub api_key: Option, pub ssh_key: Option, } ``` #### **2.2 Purchase Management Service** ```rust // src/services/user_service.rs - Purchase management impl UserService { pub fn get_purchase_history(&self, user_email: &str, limit: Option) -> Vec { if let Some(data) = UserPersistence::load_user_data(user_email) { // Convert transactions to purchase records let mut purchases: Vec = data.transactions.iter() .filter(|t| matches!(t.transaction_type, crate::models::user::TransactionType::Purchase { .. })) .map(|t| self.transaction_to_purchase_record(t)) .collect(); purchases.sort_by(|a, b| b.purchase_date.cmp(&a.purchase_date)); if let Some(limit) = limit { purchases.truncate(limit); } purchases } else { Vec::new() } } pub fn get_active_deployments(&self, user_email: &str) -> Vec { self.get_purchase_history(user_email, None).into_iter() .filter(|p| matches!(p.status, PurchaseStatus::Active) && p.deployment_info.is_some()) .collect() } pub fn get_purchase_by_id(&self, user_email: &str, purchase_id: &str) -> Option { self.get_purchase_history(user_email, None).into_iter() .find(|p| p.id == purchase_id) } pub fn update_purchase_rating(&self, user_email: &str, purchase_id: &str, rating: f32, review: Option) -> Result<(), String> { // Update purchase record with rating and review // Track rating activity let activity = UserActivity::builder() .activity_type(ActivityType::ServiceRating) .description(format!("Rated purchase: {} stars", rating)) .related_entity_id(purchase_id.to_string()) .impact_level(ActivityImpact::Medium) .build()?; self.track_activity(user_email, activity)?; // Save updated purchase record Ok(()) } pub fn get_deployment_status(&self, user_email: &str, deployment_id: &str) -> Option { self.get_active_deployments(user_email).into_iter() .find_map(|p| p.deployment_info) .filter(|d| d.deployment_id == deployment_id) } } ``` ### **Phase 3: Profile & Preferences Management** 🔄 **Personalization** **Target**: Complete user profile and preference management #### **3.1 Enhanced User Profile Models** ```rust // src/models/user.rs - Profile and preferences #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UserProfile { pub user_email: String, pub display_name: String, pub first_name: Option, pub last_name: Option, pub avatar_url: Option, pub bio: Option, pub company: Option, pub job_title: Option, pub country: Option, pub timezone: String, pub phone: Option, pub website: Option, pub social_links: HashMap, pub profile_visibility: ProfileVisibility, pub created_at: DateTime, pub updated_at: DateTime, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ProfileVisibility { Public, Limited, Private, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UserPreferences { // Display preferences pub preferred_currency: String, pub language: String, pub theme: Theme, pub dashboard_layout: DashboardLayout, pub items_per_page: i32, // Notification preferences pub email_notifications: bool, pub push_notifications: bool, pub marketing_emails: bool, pub security_alerts: bool, pub deployment_alerts: bool, pub billing_alerts: bool, // Marketplace preferences pub default_category_filter: Option, pub price_range_filter: Option<(Decimal, Decimal)>, pub preferred_providers: Vec, pub blocked_providers: Vec, pub auto_renewal_default: bool, // Privacy preferences pub activity_tracking: bool, pub analytics_participation: bool, pub data_sharing: bool, pub cookie_preferences: CookiePreferences, pub updated_at: DateTime, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Theme { Light, Dark, Auto, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum DashboardLayout { Compact, Detailed, Cards, List, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CookiePreferences { pub essential: bool, // Always true pub analytics: bool, pub marketing: bool, pub personalization: bool, } ``` #### **3.2 Profile Management Service** ```rust // src/services/user_service.rs - Profile management impl UserService { pub fn get_user_profile(&self, user_email: &str) -> Option { if let Some(data) = UserPersistence::load_user_data(user_email) { // Convert persistent data to profile Some(UserProfile { user_email: data.user_email.clone(), display_name: data.name.clone().unwrap_or_else(|| user_email.split('@').next().unwrap_or("User").to_string()), country: data.country.clone(), timezone: data.timezone.clone().unwrap_or_else(|| "UTC".to_string()), // ... map other fields created_at: Utc::now(), // Would be stored in real implementation updated_at: Utc::now(), }) } else { None } } pub fn update_user_profile(&self, user_email: &str, profile: UserProfile) -> Result<(), String> { let mut persistent_data = UserPersistence::load_user_data(user_email) .unwrap_or_else(|| UserPersistence::create_default_user_data(user_email)); // Update persistent data fields persistent_data.name = Some(profile.display_name.clone()); persistent_data.country = profile.country.clone(); persistent_data.timezone = profile.timezone.clone().into(); // Track profile update activity let activity = UserActivity::builder() .activity_type(ActivityType::ProfileUpdate) .description("Updated profile information".to_string()) .impact_level(ActivityImpact::Medium) .build()?; persistent_data.user_activities.push(activity); UserPersistence::save_user_data(user_email, &persistent_data) } pub fn get_user_preferences(&self, user_email: &str) -> Option { if let Some(data) = UserPersistence::load_user_data(user_email) { data.user_preferences } else { None } } pub fn update_user_preferences(&self, user_email: &str, preferences: UserPreferences) -> Result<(), String> { let mut persistent_data = UserPersistence::load_user_data(user_email) .unwrap_or_else(|| UserPersistence::create_default_user_data(user_email)); persistent_data.user_preferences = Some(preferences); // Track preferences update activity let activity = UserActivity::builder() .activity_type(ActivityType::PreferencesUpdate) .description("Updated preferences".to_string()) .impact_level(ActivityImpact::Medium) .build()?; persistent_data.user_activities.push(activity); UserPersistence::save_user_data(user_email, &persistent_data) } } ``` ### **Phase 4: Analytics & Insights** 🔄 **Intelligence** **Target**: Provide meaningful insights about user behavior and spending #### **4.1 Usage Analytics Models** ```rust // src/models/user.rs - Analytics and insights #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UsageStatistics { pub user_email: String, pub total_purchases: i32, pub total_spent: Decimal, pub average_monthly_spending: Decimal, pub favorite_categories: Vec, pub preferred_providers: Vec, pub spending_trends: Vec, pub deployment_stats: DeploymentStatistics, pub activity_patterns: ActivityPatterns, pub last_calculated: DateTime, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CategoryUsage { pub category: String, pub purchase_count: i32, pub total_spent: Decimal, pub percentage_of_total: f32, pub last_purchase: DateTime, pub average_rating: f32, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProviderUsage { pub provider_id: String, pub provider_name: String, pub purchase_count: i32, pub total_spent: Decimal, pub average_rating: f32, pub last_purchase: DateTime, pub satisfaction_score: f32, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MonthlySpending { pub month: String, // "2025-06" pub total_spent: Decimal, pub purchase_count: i32, pub categories: HashMap, pub providers: HashMap, pub average_per_purchase: Decimal, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DeploymentStatistics { pub total_deployments: i32, pub active_deployments: i32, pub average_uptime: f32, pub total_resource_hours: f32, pub monthly_costs: Decimal, pub cost_efficiency_score: f32, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ActivityPatterns { pub most_active_hours: Vec, // Hours of day (0-23) pub most_active_days: Vec, // Days of week pub session_frequency: f32, // Sessions per week pub average_session_duration: i32, // Minutes pub peak_usage_times: Vec, } ``` #### **4.2 Analytics Service** ```rust // src/services/user_service.rs - Analytics and insights impl UserService { pub fn calculate_usage_statistics(&self, user_email: &str) -> UsageStatistics { let purchases = self.get_purchase_history(user_email, None); let activities = self.get_user_activities(user_email, None, None); let total_spent = purchases.iter().map(|p| p.amount).sum(); let total_purchases = purchases.len() as i32; // Calculate favorite categories let mut category_stats: HashMap = HashMap::new(); for purchase in &purchases { let category = format!("{:?}", purchase.product_type); let entry = category_stats.entry(category).or_insert((0, Decimal::from(0))); entry.0 += 1; entry.1 += purchase.amount; } let favorite_categories: Vec = category_stats.into_iter() .map(|(category, (count, spent))| CategoryUsage { category, purchase_count: count, total_spent: spent, percentage_of_total: if total_spent > Decimal::from(0) { (spent / total_spent * Decimal::from(100)).to_f32().unwrap_or(0.0) } else { 0.0 }, last_purchase: purchases.iter() .filter(|p| format!("{:?}", p.product_type) == category) .map(|p| p.purchase_date) .max() .unwrap_or(Utc::now()), average_rating: 4.5, // Calculate from actual ratings }) .collect(); // Calculate monthly spending trends let spending_trends = self.calculate_monthly_spending_trends(&purchases); // Calculate activity patterns let activity_patterns = self.calculate_activity_patterns(&activities); UsageStatistics { user_email: user_email.to_string(), total_purchases, total_spent, average_monthly_spending: if spending_trends.len() > 0 { spending_trends.iter().map(|m| m.total_spent).sum::() / Decimal::from(spending_trends.len()) } else { Decimal::from(0) }, favorite_categories, preferred_providers: Vec::new(), // Calculate similar to categories spending_trends, deployment_stats: self.calculate_deployment_stats(user_email), activity_patterns, last_calculated: Utc::now(), } } pub fn get_spending_recommendations(&self, user_email: &str) -> Vec { let stats = self.calculate_usage_statistics(user_email); let mut recommendations = Vec::new(); // Analyze spending patterns and generate recommendations if stats.average_monthly_spending > Decimal::from(100) { recommendations.push(SpendingRecommendation { type_: "cost_optimization".to_string(), title: "Consider annual subscriptions".to_string(), description: "You could save 15% by switching to annual billing".to_string(), potential_savings: stats.average_monthly_spending * Decimal::from(12) * Decimal::from(0.15), confidence: 0.8, }); } recommendations } pub fn get_product_recommendations(&self, user_email: &str) -> Vec { let stats = self.calculate_usage_statistics(user_email); // Get products from favorite categories that user hasn't purchased // This would integrate with the existing ProductService Vec::new() // Placeholder } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SpendingRecommendation { pub type_: String, pub title: String, pub description: String, pub potential_savings: Decimal, pub confidence: f32, } ``` --- ## 🎨 **UI Implementation - Complete User Experience** ### **Dashboard Navigation** ``` /dashboard/user/ ├── overview # Main dashboard with personalized insights ├── activity # Complete activity timeline and analytics ├── purchases # Purchase history and active deployments ├── deployments # Active service and app management ├── profile # Personal information and account settings ├── preferences # Customization and notification settings ├── analytics # Spending insights and usage patterns ├── wallet # TFP balance, transactions, pool positions └── recommendations # Personalized product and optimization suggestions ``` ### **Main User Dashboard** (`/dashboard/user`) ```html

Welcome back, {{ user_profile.display_name }}!

Active Services

{{ active_deployments|length }}
{{ deployment_change }}

This Month

{{ monthly_spending }} TFP
{{ spending_change }}

Wallet Balance

{{ wallet_balance }} TFP
{{ balance_change }}

Recent Activity

{% for activity in recent_activities %}
{{ activity.description }}
{{ activity.timestamp | timeago }}
{% if activity.metadata %} {% endif %}
{% endfor %}
View All Activity

Active Deployments

{% for deployment in active_deployments %}

{{ deployment.product_name }}

{{ deployment.deployment_info.status }}
Provider: {{ deployment.provider_name }}
Region: {{ deployment.deployment_info.region }}
Uptime: {{ deployment.deployment_info.uptime_percentage }}%
Monthly Cost: {{ deployment.monthly_cost }} TFP
{% if deployment.deployment_info.deployment_url %} Access {% endif %}
{% endfor %}

Insights & Recommendations

Spending Pattern

You spend most on {{ top_category }} services

Cost Optimization

Switch to annual billing to save {{ potential_savings }} TFP/year

Recommended for You

{% for product in recommended_products %}
{{ product.name }} {{ product.price }} TFP
{% endfor %}
``` ### **Purchase Management** (`/dashboard/user/purchases`) ```html
{% for purchase in purchases %}

{{ purchase.product_name }}

{{ purchase.status }}
Provider: {{ purchase.provider_name }}
Purchase Date: {{ purchase.purchase_date | date }}
Amount: {{ purchase.amount }} {{ purchase.currency }}
{% if purchase.deployment_info %}
Deployment: {{ purchase.deployment_info.status }}
{% endif %}
{% if purchase.status == "Active" %} {% endif %} {% if not purchase.rating %} {% endif %}
{% endfor %}
``` --- ## 📋 **Implementation Checklist --- ## 📋 **Implementation Checklist - User Lifecycle** ### **Phase 1: Activity Tracking Foundation** - [ ] Create enhanced `UserActivity` model with activity types and impact levels - [ ] Implement `ActivityType` enum with all user action types - [ ] Add activity tracking methods to `UserService` - [ ] Create activity timeline UI with filtering and search - [ ] Add automatic activity tracking hooks throughout the application ### **Phase 2: Purchase & Deployment Management** - [ ] Create comprehensive `PurchaseRecord` model with deployment info - [ ] Implement `DeploymentInfo` model with status and resource tracking - [ ] Add purchase management methods to `UserService` - [ ] Create purchase history UI with advanced filtering - [ ] Implement deployment monitoring and management interface - [ ] Add purchase rating and review system ### **Phase 3: Profile & Preferences Management** - [ ] Create detailed `UserProfile` model with all personal information - [ ] Implement comprehensive `UserPreferences` model - [ ] Add profile management methods to `UserService` - [ ] Create profile editing UI with validation - [ ] Implement preferences management with real-time updates - [ ] Add privacy controls and visibility settings ### **Phase 4: Analytics & Insights** - [ ] Create `UsageStatistics` model with spending and usage analytics - [ ] Implement analytics calculation methods in `UserService` - [ ] Add spending trend analysis and forecasting - [ ] Create analytics dashboard with charts and insights - [ ] Implement recommendation engine for products and optimizations - [ ] Add comparative analytics and benchmarking ### **Phase 5: Controller Implementation** - [ ] Add user dashboard controller methods to `DashboardController` - [ ] Implement activity tracking API endpoints - [ ] Add purchase management API endpoints - [ ] Create profile and preferences API endpoints - [ ] Implement analytics and insights API endpoints - [ ] Add proper authentication and authorization ### **Phase 6: UI Templates** - [ ] Create main user dashboard template with personalized overview - [ ] Implement activity timeline template with filtering - [ ] Create purchase history template with deployment tracking - [ ] Build profile management template with comprehensive forms - [ ] Implement preferences template with all user controls - [ ] Create analytics dashboard template with charts and insights ### **Phase 7: Routes & Integration** - [ ] Add all user dashboard routes to routing configuration - [ ] Implement RESTful API endpoints for user data management - [ ] Add proper middleware for authentication and validation - [ ] Integrate with existing wallet and transaction systems - [ ] Connect with marketplace for purchase tracking - [ ] Add real-time updates and notifications ### **Phase 8: Data Migration & Enhancement** - [ ] Extend `UserPersistentData` with new user models - [ ] Create migration helpers for existing user data - [ ] Add builder patterns for all new models - [ ] Implement data validation and sanitization - [ ] Add data export and import functionality --- ## 🎯 **Success Criteria - Complete User Experience** ### **Functional Requirements** - User can view comprehensive dashboard with personalized insights - User can track complete activity history with detailed timeline - User can manage all purchases with deployment monitoring - User can update profile and preferences with full control - User can view detailed analytics and spending insights - User can receive personalized recommendations and optimizations ### **User Experience Requirements** - Dashboard loads quickly with real-time data - Activity tracking works automatically across all user actions - Purchase history accurately reflects all marketplace transactions - Profile management provides intuitive and comprehensive controls - Analytics provide meaningful insights and actionable recommendations - Navigation between sections is smooth and consistent ### **Technical Requirements** - All new code follows established builder patterns - All services use proper error handling with Result types - All templates use ContextBuilder for consistency - All data loading uses UserPersistence for real data - Performance optimized for large datasets and frequent updates - Security controls protect user privacy and data ### **Data Integration Requirements** - Activity tracking integrates with all existing user actions - Purchase history connects with existing transaction system - Profile data syncs with existing user authentication - Analytics calculations use real transaction and activity data - Recommendations based on actual user behavior patterns - Wallet integration shows real TFP balances and transactions ### **Testing Requirements** - Complete user workflow testing from registration to analytics - Activity tracking verification across all user actions - Purchase and deployment management testing - Profile and preferences functionality testing - Analytics accuracy and recommendation quality testing - Performance testing with large datasets --- ## 🚀 **Implementation Priority** ### **High Priority (Essential)** 1. **Activity Tracking** - Foundation for all user insights 2. **Purchase Management** - Core user functionality 3. **Profile Management** - Essential user control ### **Medium Priority (Important)** 1. **Analytics & Insights** - Value-added intelligence 2. **Deployment Monitoring** - Advanced management features 3. **Recommendations** - Personalization features ### **Low Priority (Enhancement)** 1. **Advanced Analytics** - Detailed reporting and forecasting 2. **Social Features** - Profile sharing and community 3. **Export/Import** - Data portability features --- ## 💡 **Implementation Tips** ### **Start Simple, Build Complex** - Begin with basic activity tracking and purchase history - Add analytics and insights once foundation is solid - Implement advanced features after core functionality works ### **Leverage Existing Patterns** - Copy controller patterns from existing dashboard sections - Use established service builder patterns throughout - Follow existing template structures and CSS classes ### **Focus on Real Data** - Always use `UserPersistence::load_user_data()` for data access - Convert existing transactions to purchase records - Build analytics from real user activity and transaction data ### **Maintain Performance** - Limit activity history to prevent data bloat - Use pagination for large datasets - Cache analytics calculations when possible This comprehensive plan provides everything needed to create a complete user dashboard that matches the quality and functionality of modern SaaS platforms while maintaining the excellent architectural patterns established in the Project Mycelium.