codenuk_backend_mine/services/ai-mockup-service/WIREFRAME_SAVING_GUIDE.md
2025-10-10 08:56:39 +05:30

7.1 KiB

AI Mockup Service - Wireframe Saving Implementation Guide

🎯 Overview

This guide explains the complete implementation of wireframe saving functionality with user authentication in the CodeNuk AI Mockup Service.

🔧 Problem Solved

  • Issue: AI mockup service was failing to connect to user-auth service for JWT verification
  • Root Cause: Service communication issues and JWT secret mismatches
  • Solution: Implemented robust authentication with fallback mechanisms and proper service coordination

🏗️ Architecture

Services Involved:

  1. AI Mockup Service (Port 8021) - Handles wireframe generation and storage
  2. User Auth Service (Port 8011) - Manages user authentication and JWT tokens
  3. PostgreSQL Database (Port 5433) - Stores wireframes and user data
  4. Frontend (Port 3001) - React application with wireframe canvas

Data Flow:

Frontend → User Auth Service → AI Mockup Service → PostgreSQL
    ↓           ↓                    ↓              ↓
  Canvas    JWT Token         Wireframe Data    Persistent Storage

🔐 Authentication Implementation

JWT Configuration:

  • Secret: access-secret-key-2024-tech4biz-${POSTGRES_PASSWORD}
  • Algorithm: HS256
  • Expiry: 15 minutes (access), 7 days (refresh)

Verification Strategy:

  1. Local Verification: Try to verify JWT with local secret first
  2. Remote Verification: If local fails, call user-auth service
  3. Fallback: Continue with local verification if remote service unavailable

User ID Extraction:

def extract_user_id_from_token(user_data):
    """Extract user ID from various possible token formats"""
    return (user_data.get('id') or 
            user_data.get('userId') or 
            user_data.get('user_id') or
            user_data.get('sub') or
            user_data.get('user', {}).get('id'))

💾 Database Schema

Wireframes Table:

CREATE TABLE wireframes (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  project_id UUID REFERENCES user_projects(id) ON DELETE SET NULL,
  name VARCHAR(200) NOT NULL,
  description TEXT,
  device_type VARCHAR(20) DEFAULT 'desktop',
  dimensions JSONB NOT NULL,
  metadata JSONB,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

Wireframe Elements Table:

CREATE TABLE wireframe_elements (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  wireframe_id UUID REFERENCES wireframes(id) ON DELETE CASCADE,
  element_type VARCHAR(50) NOT NULL,
  element_data JSONB NOT NULL,
  position JSONB NOT NULL,
  size JSONB,
  style JSONB,
  parent_id UUID REFERENCES wireframe_elements(id) ON DELETE CASCADE,
  z_index INTEGER DEFAULT 0,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

🚀 Deployment Steps

1. Update Docker Compose:

ai-mockup-service:
  environment:
    - JWT_ACCESS_SECRET=access-secret-key-2024-tech4biz-${POSTGRES_PASSWORD}
    - USER_AUTH_SERVICE_URL=http://user-auth:8011
  depends_on:
    user-auth:
      condition: service_healthy

2. Start Services:

cd automated-dev-pipeline
docker compose up -d user-auth ai-mockup-service

3. Verify Health:

curl http://localhost:8011/health  # User Auth Service
curl http://localhost:8021/health   # AI Mockup Service

4. Test Integration:

cd services/ai-mockup-service/src
python test_integration.py

🎨 Frontend Integration

Wireframe Canvas Component:

  • Auto-save: Automatically saves wireframes every 30 seconds
  • Authentication: Uses JWT tokens from auth context
  • Error Handling: Graceful fallback for authentication failures

Key Features:

  • Real-time Saving: Wireframes saved as user creates them
  • User Isolation: Each user only sees their own wireframes
  • Version Control: Automatic versioning of wireframe changes
  • Multi-device Support: Desktop, tablet, and mobile wireframes

🔍 Testing

Manual Testing:

  1. Register/Login: Create account at http://localhost:3001/signup
  2. Create Wireframe: Go to project builder → AI Mockup step
  3. Generate Wireframe: Use AI prompt to generate wireframe
  4. Save Wireframe: Canvas automatically saves to database
  5. Verify Storage: Check database for saved wireframe data

Automated Testing:

# Run integration tests
python test_integration.py

# Expected output:
# ✅ AI Mockup Service is healthy
# ✅ User Auth Service is healthy
# ✅ User registration successful
# ✅ Wireframe generation successful
# ✅ Wireframe saved successfully
# ✅ Wireframe retrieved successfully

🛠️ Troubleshooting

Common Issues:

  1. Connection Refused (Port 8011):

    # Check if user-auth service is running
    docker compose ps user-auth
    
    # Restart if needed
    docker compose restart user-auth
    
  2. JWT Verification Failed:

    # Check JWT secrets match
    docker compose exec user-auth env | grep JWT_ACCESS_SECRET
    docker compose exec ai-mockup-service env | grep JWT_ACCESS_SECRET
    
  3. Database Connection Failed:

    # Check PostgreSQL is running
    docker compose ps postgres
    
    # Run database setup
    docker compose exec ai-mockup-service python src/setup_database.py
    

Debug Commands:

# View service logs
docker compose logs -f ai-mockup-service
docker compose logs -f user-auth

# Check database tables
docker compose exec postgres psql -U pipeline_admin -d dev_pipeline -c "\dt"

# Test authentication endpoint
curl -H "Authorization: Bearer YOUR_TOKEN" http://localhost:8011/api/auth/verify

📊 Monitoring

Health Endpoints:

  • AI Mockup Service: http://localhost:8021/health
  • User Auth Service: http://localhost:8011/health

Key Metrics:

  • Database Connection: Status of PostgreSQL connection
  • Auth Service: Status of user-auth service communication
  • Wireframe Count: Number of wireframes saved per user
  • Generation Success Rate: Percentage of successful wireframe generations

🎯 Success Criteria

Authentication: Users can register/login and receive valid JWT tokens
Wireframe Generation: AI generates wireframes based on user prompts
Wireframe Saving: Wireframes are saved to database with user association
Wireframe Retrieval: Users can load their previously saved wireframes
User Isolation: Users only see their own wireframes
Error Handling: Graceful handling of service failures
Real-time Updates: Frontend updates reflect saved state

🔮 Future Enhancements

  1. Collaborative Editing: Multiple users editing same wireframe
  2. Version History: Detailed version control with diff views
  3. Export Options: Export wireframes as PNG, PDF, or code
  4. Templates: Pre-built wireframe templates
  5. Analytics: Usage analytics and performance metrics

Implementation Status: COMPLETE
Last Updated: $(date)
Version: 1.0.0