Files
projectmycelium/docs/dev/design/archive/plan_refactor.md
2025-09-01 21:37:01 -04:00

334 lines
11 KiB
Markdown

# OpenRouter-Inspired Marketplace Enhancement Plan
## Overview
This document outlines the implementation plan for enhancing the Project Mycelium with OpenRouter-inspired payment features while maintaining all existing functionality. The goal is to add streamlined "buy now" capabilities and improved wallet management alongside the current cart-based shopping experience.
## Current System Analysis
### Architecture Patterns
- **Builder Pattern**: Services use `ServiceName::builder().build()` pattern
- **Service Layer**: Clean separation with dedicated services (CurrencyService, WalletController, etc.)
- **Controller Pattern**: RESTful endpoints with JSON responses
- **Template Engine**: Tera templating with context-based rendering
- **Session Management**: Actix-web sessions for user state
- **Persistence**: UserPersistence service for data management
### Current Currency System
- **Base Currency**: TFP (ThreeFold Points)
- **Exchange Rate**: 1 TFP = 0.1 USD (configurable)
- **Display Options**: Currently supports multiple currencies (USD, EUR, TFT, PEAQ)
- **User Preferences**: Currency preferences stored per user
### Current Purchase Flow
1. Browse marketplace → Add to cart → Checkout → Purchase
2. TFP purchase via wallet page or TFP pools
3. TFP pools support trading: TFP/Fiat, TFP/TFT, TFP/PEAQ
## Enhancement Goals
### 1. Currency Display Improvements
- **Default Currency**: Set USD as default display currency for new users
- **TFP Display Option**: Add TFP as a display currency choice alongside fiat currencies
- **User Choice**: Users can choose any supported currency (TFP, USD, CAD, EUR, etc.) for price display
- **Internal Processing**: All transactions remain TFP-based internally
### 2. OpenRouter-Style Navbar
Replace simple "Hello, USERNAME" with dropdown menu containing:
- User name/email
- Current wallet balance in user's preferred display currency
- "Top Up Wallet" / "Buy Credits" quick action
- Settings link
- Logout option
### 3. Enhanced Wallet Top-Up
- **Direct Currency Input**: "Add $20" converts to TFP automatically
- **Quick Amount Buttons**: Preset amounts ($10, $20, $50, $100)
- **Real-time Conversion**: Show TFP equivalent during input
- **Streamlined Flow**: Fewer steps from intent to completion
### 4. Buy Now Functionality
- **Instant Purchase**: "Buy Now" buttons alongside "Add to Cart"
- **Direct Deduction**: Skip cart, deduct TFP immediately
- **Balance Check**: Automatic fallback to top-up if insufficient funds
- **Immediate Deployment**: For applicable services/products
## Technical Implementation Plan
### Phase 1: Currency Service Enhancement
#### 1.1 Extend CurrencyService
```rust
// File: src/services/currency.rs
impl CurrencyService {
pub fn builder() -> CurrencyServiceBuilder {
CurrencyServiceBuilder::new()
.with_default_display_currency("USD")
.with_tfp_display_option(true)
}
}
```
#### 1.2 Update Currency Models
```rust
// File: src/models/currency.rs
// Add TFP as display currency option
// Ensure USD is default for new users
// Maintain configurable TFP exchange rate
```
#### 1.3 Currency Preference Storage
```rust
// File: src/services/user_persistence.rs
// Extend UserPersistentData to include display_currency preference
// Default to "USD" for new users
// Support "TFP", "USD", "CAD", "EUR", etc.
```
### Phase 2: Navbar Enhancement
#### 2.1 Create NavbarService
```rust
// File: src/services/navbar.rs
pub struct NavbarService;
impl NavbarService {
pub fn builder() -> NavbarServiceBuilder {
NavbarServiceBuilder::new()
}
pub fn get_user_dropdown_data(&self, session: &Session) -> NavbarDropdownData {
// Get user info, wallet balance in preferred currency, etc.
}
}
```
#### 2.2 Update Base Template
```html
<!-- File: src/views/base.html -->
<!-- Replace simple greeting with dropdown menu -->
<!-- Include wallet balance, top-up button, settings link -->
```
### Phase 3: Instant Purchase System
#### 3.1 Create InstantPurchaseService
```rust
// File: src/services/instant_purchase.rs
pub struct InstantPurchaseService;
impl InstantPurchaseService {
pub fn builder() -> InstantPurchaseServiceBuilder {
InstantPurchaseServiceBuilder::new()
}
pub async fn execute_instant_purchase(&self, request: InstantPurchaseRequest) -> InstantPurchaseResult {
// Check TFP balance
// Deduct amount
// Create transaction
// Trigger deployment/fulfillment
}
}
```
#### 3.2 Extend WalletController
```rust
// File: src/controllers/wallet.rs
impl WalletController {
pub async fn instant_purchase(
request: web::Json<InstantPurchaseRequest>,
session: Session,
) -> Result<impl Responder> {
// Handle buy-now requests
}
pub async fn quick_topup(
request: web::Json<QuickTopupRequest>,
session: Session,
) -> Result<impl Responder> {
// Handle streamlined top-up
}
}
```
#### 3.3 Update Marketplace Templates
```html
<!-- Add buy-now buttons to all product listings -->
<!-- Maintain existing add-to-cart functionality -->
<!-- Include balance check and top-up prompts -->
```
### Phase 4: Enhanced Wallet Interface
#### 4.1 Wallet Page Improvements
```html
<!-- File: src/views/wallet/index.html -->
<!-- Prominent display of balance in user's preferred currency -->
<!-- Quick top-up with currency input -->
<!-- Preset amount buttons -->
<!-- Real-time conversion display -->
```
#### 4.2 Currency Settings
```html
<!-- File: src/views/dashboard/settings.html -->
<!-- Add currency preference selection -->
<!-- Include TFP and all supported fiat currencies -->
<!-- Real-time preview of balance in selected currency -->
```
## API Endpoints
### New Endpoints
- `POST /api/wallet/instant-purchase` - Execute buy-now purchase
- `POST /api/wallet/quick-topup` - Streamlined wallet top-up
- `PUT /api/currency/set-display` - Update user's display currency preference
- `GET /api/navbar/dropdown-data` - Get navbar dropdown information
### Enhanced Endpoints
- `GET /api/wallet/info` - Include balance in user's preferred display currency
- `GET /api/currency/user-preference` - Return current display currency setting
## Database Schema Changes
### UserPersistentData Extensions
```rust
pub struct UserPersistentData {
// ... existing fields ...
pub display_currency: Option<String>, // "USD", "TFP", "CAD", etc.
pub quick_topup_amounts: Option<Vec<Decimal>>, // Customizable preset amounts
}
```
### Transaction Model Extensions
```rust
pub struct Transaction {
// ... existing fields ...
pub purchase_type: PurchaseType, // Cart, Instant, TopUp
pub display_currency_used: Option<String>,
pub display_amount: Option<Decimal>,
}
pub enum PurchaseType {
CartPurchase,
InstantPurchase,
WalletTopUp,
PoolExchange,
}
```
## User Experience Flow
### Buy Now Flow
1. User browses marketplace in their preferred display currency
2. Clicks "Buy Now" on a product
3. System checks TFP balance
4. If sufficient: Immediate purchase and deployment
5. If insufficient: Prompt for top-up with exact amount needed
6. Top-up in user's preferred currency, convert to TFP
7. Complete purchase automatically
### Top-Up Flow
1. User clicks "Top Up" in navbar dropdown or wallet page
2. Enter amount in preferred currency (e.g., "$20")
3. System shows TFP conversion (e.g., "= 200 TFP")
4. Select payment method
5. Process payment and add TFP to wallet
6. Update balance display across all interfaces
## Backward Compatibility
### Preserved Functionality
- **Cart System**: Remains fully functional
- **TFP Pools**: All existing pool trading continues to work
- **Existing APIs**: No breaking changes to current endpoints
- **User Data**: Existing users retain all data and preferences
- **Payment Methods**: All current payment options remain available
### Migration Strategy
- New users default to USD display currency
- Existing users keep current preferences
- TFP display option added to all currency selectors
- Gradual rollout of buy-now buttons alongside existing cart buttons
## Testing Strategy
### Integration Tests
- Cart and buy-now flows work together
- Currency conversion accuracy
- Session management with new features
- Backward compatibility with existing data
### User Experience Tests
- Navbar dropdown functionality
- Wallet top-up flow
- Buy-now purchase flow
- Currency preference changes
### Performance Tests
- Real-time currency conversion
- Balance checks for instant purchases
- Template rendering with new data
## Implementation Timeline
### Phase 1: Foundation (Week 1)
- Currency service enhancements
- TFP display option
- USD default for new users
### Phase 2: UI/UX (Week 2)
- Navbar dropdown implementation
- Wallet page improvements
- Settings page currency selection
### Phase 3: Buy Now (Week 3)
- Instant purchase service
- Buy-now buttons in marketplace
- Balance check and top-up integration
### Phase 4: Polish & Testing (Week 4)
- Integration testing
- UI/UX refinements
- Performance optimization
- Documentation updates
## Success Metrics
### User Experience
- Reduced time from product discovery to purchase
- Increased wallet top-up frequency
- Higher conversion rates on marketplace items
### Technical
- No regression in existing cart functionality
- Successful currency conversion accuracy
- Stable session management with new features
### Business
- Maintained compatibility with TFP pools
- Seamless integration with existing payment systems
- Clear audit trail for all transaction types
## Risk Mitigation
### Technical Risks
- **Currency Conversion Errors**: Extensive testing of conversion logic
- **Session Management**: Careful handling of user state across new features
- **Performance Impact**: Optimize database queries for balance checks
### User Experience Risks
- **Confusion Between Flows**: Clear UI distinction between cart and buy-now
- **Currency Display Issues**: Thorough testing of all currency combinations
- **Balance Synchronization**: Ensure real-time balance updates across interfaces
### Business Risks
- **Backward Compatibility**: Comprehensive testing with existing user data
- **TFP Pool Integration**: Ensure no conflicts with existing pool functionality
- **Payment Processing**: Maintain all existing payment method support
## Conclusion
This enhancement plan adds OpenRouter-inspired streamlined purchasing while preserving the robust existing marketplace functionality. The modular approach ensures clean integration with the current architecture and provides a foundation for future enhancements.
The key innovation is offering users choice: they can continue using the familiar cart-based shopping experience or opt for the new instant purchase flow, all while viewing prices in their preferred currency (including TFP itself).