AI Viewpoint Generation

Description

The AI Viewpoint Generation feature utilizes OpenAI's powerful language models to automatically generate category details and specific viewpoints for temporary wishlist categories. This module enables the creation of AI-powered analysis perspectives within the temporary wishlist system, allowing users to experiment with different category descriptions and viewpoint approaches before converting to production.

Key characteristics of the temporary viewpoint system:

  • AI-powered content generation through OpenAI integration
  • User experimentation and iteration capabilities
  • Convertible to production system via ViewpointService
  • Three-tier hierarchy: Category Viewpoints → Category Details → Specific Viewpoints
  • Tables: temp_wl_cat_vps, temp_wl_cat_vp_details, temp_wl_spec_vps

Note: This documentation covers temporary wishlist viewpoints only. For production wishlist viewpoint analysis, see Viewpoint Analysis.

Recent Updates (2025-07-24)

Enhanced Category Detail Generation

  • Short Detail Support: OpenAI now generates both detail and short_detail fields
  • DS Analyzer Integration: Short details are pushed to analyzer during conversion
  • Improved DTO: CategoryDetailResultData includes both detailed and brief descriptions

Specific Viewpoint Changes

  • Delete-Before-Generate: New behavior automatically removes existing viewpoints before generating new ones
  • Ordinal Number Support: Production conversion assigns ordinal numbers for analysis
  • DS Analyzer Push: Specific viewpoints are automatically pushed to analyzer database

API Enhancements

  • Delete Endpoint: Added DELETE /temp-viewpoint/specific-viewpoint/{id} for individual removal
  • Enhanced Error Handling: Improved transaction management and rollback logic

Activity Diagram

---
config:
  theme: base
  layout: dagre
  flowchart:
    curve: linear
    htmlLabels: true
  themeVariables:
    edgeLabelBackground: "transparent"
---
flowchart TB
    %% Main components
    UserRequest[User Request]
    OpenAI((OpenAI API))
    TempDatabase[(Temp Database)]
    
    subgraph Controllers
        TempViewpointController[TempViewpointController]
    end
    
    subgraph Services
        TempViewpointService(TempViewpointService)
        OpenAIService(OpenAIService)
    end
    
    subgraph Models
        TempCategoryViewpoint[[TempWishlistCategoryViewpoint]]
        TempCategoryDetail[[TempWishlistCategoryViewpointDetail]]
        TempSpecificViewpoint[[TempWishlistSpecificViewpoint]]
    end
    
    subgraph Middleware
        GroupMiddleware{GroupMiddleware}
    end
    
    UserRequest --- Step1[
        <div style='text-align: center'>
            <span style='display: inline-block; background-color: #6699cc !important; color:white; width: 28px; height: 28px; line-height: 28px; border-radius: 50%; font-weight: bold'>1</span>
            <p style='margin-top: 8px'>Authentication & Group Validation</p>
        </div>
    ]
    Step1 --> GroupMiddleware

    TempViewpointController --- Step2[
        <div style='text-align: center'>
            <span style='display: inline-block; background-color: #6699cc !important; color:white; width: 28px; height: 28px; line-height: 28px; border-radius: 50%; font-weight: bold'>2</span>
            <p style='margin-top: 8px'>Generate Category Detail</p>
        </div>
    ]
    Step2 --> TempViewpointService

    TempViewpointService --- Step3[
        <div style='text-align: center'>
            <span style='display: inline-block; background-color: #6699cc !important; color:white; width: 28px; height: 28px; line-height: 28px; border-radius: 50%; font-weight: bold'>3</span>
            <p style='margin-top: 8px'>OpenAI Generation</p>
        </div>
    ]
    Step3 --> OpenAIService

    OpenAIService --- Step4[
        <div style='text-align: center'>
            <span style='display: inline-block; background-color: #6699cc !important; color:white; width: 28px; height: 28px; line-height: 28px; border-radius: 50%; font-weight: bold'>4</span>
            <p style='margin-top: 8px'>Store Temp Data</p>
        </div>
    ]
    Step4 --> TempDatabase

    TempViewpointController --- Step5[
        <div style='text-align: center'>
            <span style='display: inline-block; background-color: #99cc66 !important; color:white; width: 28px; height: 28px; line-height: 28px; border-radius: 50%; font-weight: bold'>5</span>
            <p style='margin-top: 8px'>Generate Specific Viewpoints</p>
        </div>
    ]
    Step5 --> TempViewpointService

    TempViewpointService --- Step6[
        <div style='text-align: center'>
            <span style='display: inline-block; background-color: #99cc66 !important; color:white; width: 28px; height: 28px; line-height: 28px; border-radius: 50%; font-weight: bold'>6</span>
            <p style='margin-top: 8px'>Delete Existing Viewpoints</p>
        </div>
    ]
    Step6 --> TempDatabase

    TempViewpointController --- Step7[
        <div style='text-align: center'>
            <span style='display: inline-block; background-color: #cc66cc !important; color:white; width: 28px; height: 28px; line-height: 28px; border-radius: 50%; font-weight: bold'>7</span>
            <p style='margin-top: 8px'>Delete Individual Viewpoint</p>
        </div>
    ]
    Step7 --> TempViewpointService

    %% Service to Model relationships
    TempViewpointService -.-> TempCategoryViewpoint
    TempViewpointService -.-> TempCategoryDetail
    TempViewpointService -.-> TempSpecificViewpoint
    
    %% Model to Database relationships
    TempCategoryViewpoint -.-> TempDatabase
    TempCategoryDetail -.-> TempDatabase
    TempSpecificViewpoint -.-> TempDatabase
    
    %% OpenAI relationships
    OpenAIService -.-> OpenAI
    
    %% Styling
    style TempDatabase fill:#ffe6cc,stroke:#ff9900,stroke-width:2px
    style OpenAI fill:#fcd9d9,stroke:#cc3333,stroke-width:2px
    style Controllers fill:#e6f3ff
    style Services fill:#f0f8e6
    style Models fill:#fff0f5
    style Middleware fill:#f5f0ff
    style Step1 fill:transparent,stroke:transparent,stroke-width:1px
    style Step2 fill:transparent,stroke:transparent,stroke-width:1px
    style Step3 fill:transparent,stroke:transparent,stroke-width:1px
    style Step4 fill:transparent,stroke:transparent,stroke-width:1px
    style Step5 fill:transparent,stroke:transparent,stroke-width:1px
    style Step6 fill:transparent,stroke:transparent,stroke-width:1px
    style Step7 fill:transparent,stroke:transparent,stroke-width:1px

API: Temp Viewpoint APIs

Database Schema

Database Related Tables & Fields

Database: gb_console

erDiagram
    temp_wl_cat_vps {
        bigint id PK
        bigint temp_wishlist_to_group_id "Link to specific temp wishlist (nullable)"
        bigint user_id "User who created the viewpoint"
        bigint group_id "Group ownership for access control"
        string name "Category name for AI generation"
        string slug "Auto-generated unique identifier with twcv- prefix"
        timestamp created_at
        timestamp updated_at
    }
    
    temp_wl_cat_vp_details {
        bigint id PK
        bigint temp_wl_cat_vp_id FK "Reference to temp_wl_cat_vps"
        text detail "AI-generated detailed category description (max 500 chars)"
        text short_detail "AI-generated brief category summary (Added 2025-07-24)"
        timestamp created_at
        timestamp updated_at
    }
    
    temp_wl_spec_vps {
        bigint id PK
        bigint temp_wl_cat_vp_detail_id FK "Reference to temp_wl_cat_vp_details"
        string name "Specific viewpoint name from AI generation"
        text description "Specific viewpoint description (max 100 chars)"
        timestamp created_at
        timestamp updated_at
    }

    temp_wl_cat_vps ||--o{ temp_wl_cat_vp_details : has
    temp_wl_cat_vp_details ||--o{ temp_wl_spec_vps : has

Case Documentation

Case 1: Successful Category Detail Generation

Description

User generates AI-powered category detail with both detailed description and short summary for temporary wishlist categories.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Controller as TempViewpointController
    participant Service as TempViewpointService
    participant OpenAIService
    participant OpenAI as OpenAI API
    participant TempDB as Temp Database
    
    Note over Client,TempDB: POST /api/v1/temp-viewpoint/category/generate
    
    rect rgb(200, 255, 200)
    Note right of Client: Happy Case - Category Detail Generation
    
    Client->>Controller: POST /category/generate (category_name, temp_wishlist_to_group_id)
    
    rect rgb(200, 230, 255)
    Note right of Controller: Input Validation
    Controller->>Controller: Validate input data (category_name required, max 200 chars)
    end
    
    rect rgb(200, 255, 255)
    Note right of Controller: Business Logic Processing
    Controller->>Service: generateCategoryDetail(validatedData)
    Service->>Service: transactionBegin()
    Service->>Service: createOrUpdateTempWishlistCategoryViewpoint(user, category_name, temp_wishlist_to_group_id)
    end
    
    rect rgb(255, 230, 200)
    Note right of Service: OpenAI API Call
    Service->>OpenAIService: generateCategoryDetail(category_name)
    OpenAIService->>OpenAI: Send prompt with category name
    OpenAI-->>OpenAIService: Return CategoryDetailResultData {detail, short_detail}
    OpenAIService-->>Service: Return generated content
    end
    
    rect rgb(230, 200, 255)
    Note right of Service: Database Operations
    Service->>Service: createOrUpdateTempWishlistCategoryViewpointDetail(detail, short_detail)
    Service->>TempDB: INSERT/UPDATE temp_wl_cat_vp_details
    Service->>Service: Log user action (GptGenerateCategoryDetail)
    Service->>Service: transactionCommit()
    end
    
    Service-->>Controller: Return TempWishlistCategoryViewpointDetailResource
    Controller-->>Client: 201 Created (category detail with short_detail)
    end
    
    rect rgb(255, 200, 200)
    Note right of Client: Error Handling
    
    alt Validation Error
        rect rgb(255, 230, 230)
        Controller-->>Client: 422 Unprocessable Entity (validation errors)
        end
    else OpenAI API Error
        rect rgb(255, 230, 230)
        OpenAI-->>OpenAIService: API timeout/rate limit
        OpenAIService-->>Service: OpenAI error
        Service->>Service: transactionRollback()
        Service-->>Controller: API error result
        Controller-->>Client: 500 Internal Server Error (OpenAI timeout)
        end
    else Authorization Error
        rect rgb(255, 230, 230)
        Controller-->>Client: 401 Unauthorized (user not in group)
        end
    end
    end

Steps

Step 1: Category Generation Request

  • Description: User submits category name for AI-powered detail generation
  • Request: POST /api/v1/temp-viewpoint/category/generate
  • Required Fields: category_name (string, max 200 chars)
  • Optional Fields: temp_wishlist_to_group_id (integer, links to specific temp wishlist)
  • Authorization: User must be member of a group

Step 2: Input Validation

  • Description: System validates request parameters
  • Validation Rules:
    • category_name: Required, string, maximum 200 characters
    • temp_wishlist_to_group_id: Optional, integer, must exist in temp_wishlist_to_groups table
  • Potential Errors: Validation failure returns 422 Unprocessable Entity

Step 3: Business Logic Processing

  • Description: Create or update category viewpoint structure
  • Action:
    • Begin database transaction
    • Create/update temp_wl_cat_vps record
    • Link to temp wishlist if temp_wishlist_to_group_id provided

Step 4: OpenAI Generation

  • Description: Generate AI-powered category descriptions
  • Action: Call OpenAI API with category name and structured prompt
  • Output: CategoryDetailResultData containing both detail and short_detail
  • Error Handling: Timeout and rate limiting managed with proper error responses

Step 5: Database Storage

  • Description: Store generated content in temporary tables
  • Action:
    • Create/update temp_wl_cat_vp_details record
    • Store both detail (max 500 chars) and short_detail
    • Log user action for analytics
    • Commit transaction

Step 6: Success Response

  • Description: Return generated category detail to client
  • Response: 201 Created with TempWishlistCategoryViewpointDetailResource
  • Includes: Generated detail, short_detail, timestamps, and relationships

Error Handling

  • Log: Generation failures logged to application log
  • Error Detail:
Status Code Error Message Description
401 "User not authorized to generate viewpoints" User not member of group
422 "Validation failed" Invalid input parameters
500 "OpenAI API timeout occurred" OpenAI service unavailable

Case 2: Successful Specific Viewpoint Generation

Description

User generates multiple AI-powered specific viewpoints based on category detail. Important: This process deletes all existing specific viewpoints before creating new ones.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Controller as TempViewpointController
    participant Service as TempViewpointService
    participant OpenAIService
    participant OpenAI as OpenAI API
    participant TempDB as Temp Database
    
    Note over Client,TempDB: POST /api/v1/temp-viewpoint/specific-viewpoint/generate
    
    rect rgb(200, 255, 200)
    Note right of Client: Happy Case - Specific Viewpoint Generation
    
    Client->>Controller: POST /specific-viewpoint/generate (category_name, category_detail, temp_wishlist_to_group_id)
    
    rect rgb(200, 230, 255)
    Note right of Controller: Input Validation
    Controller->>Controller: Validate input (category_name, category_detail required)
    end
    
    rect rgb(200, 255, 255)
    Note right of Controller: Setup & Cleanup
    Controller->>Service: generateSpecificViewpoints(validatedData)
    Service->>Service: transactionBegin()
    Service->>Service: createOrUpdateTempWishlistCategoryViewpoint()
    Service->>Service: createOrUpdateTempWishlistCategoryViewpointDetail()
    
    Service->>TempDB: DELETE existing specific viewpoints
    Note over Service,TempDB: ⚠️ All existing viewpoints for this category detail are deleted!
    end
    
    rect rgb(255, 230, 200)
    Note right of Service: OpenAI Generation
    Service->>OpenAIService: generateSpecificViewpoints(category_name, category_detail, quantity)
    OpenAIService->>OpenAI: Send structured prompt with category info
    OpenAI-->>OpenAIService: Return SPVPResultData {viewpoints[]}
    OpenAIService-->>Service: Array of ViewpointItemData
    end
    
    rect rgb(230, 200, 255)
    Note right of Service: Database Storage
    Service->>TempDB: INSERT multiple temp_wl_spec_vps records
    Service->>Service: Log user action (GptGenerateSpecificViewpoint)
    Service->>Service: transactionCommit()
    end
    
    Service-->>Controller: Return TempWishlistSpecificViewpointResource collection
    Controller-->>Client: 201 Created (generated viewpoints array)
    end
    
    rect rgb(255, 200, 200)
    Note right of Client: Error Handling
    
    alt Validation Error
        rect rgb(255, 230, 230)
        Controller-->>Client: 422 Unprocessable Entity
        end
    else OpenAI API Error
        rect rgb(255, 230, 230)
        OpenAI-->>OpenAIService: Generation failure
        OpenAIService-->>Service: API error
        Service->>Service: transactionRollback()
        Service-->>Controller: Error result
        Controller-->>Client: 500 Internal Server Error
        end
    end
    end

Steps

Step 1: Specific Viewpoint Generation Request

  • Description: User requests AI generation of specific viewpoints
  • Request: POST /api/v1/temp-viewpoint/specific-viewpoint/generate
  • Required Fields: category_name, category_detail
  • Optional Fields: temp_wishlist_to_group_id

Step 2: Data Cleanup (Important Behavior)

  • Description: Delete all existing specific viewpoints for the category detail
  • Action: DELETE FROM temp_wl_spec_vps WHERE temp_wl_cat_vp_detail_id = ?
  • Impact: Previous viewpoints are permanently lost
  • Reason: Ensures clean slate for new generation

Step 3: OpenAI Generation

  • Description: Generate multiple specific viewpoints based on category
  • Configuration: Uses config('viewpoint.default_quantity') (typically 5 viewpoints)
  • Output: Array of viewpoints with name and description

Step 4: Bulk Database Storage

  • Description: Store all generated viewpoints in single operation
  • Action: Bulk INSERT into temp_wl_spec_vps table
  • Transaction: All operations wrapped in database transaction

Case 3: Individual Viewpoint Deletion

Description

User deletes a specific viewpoint by ID with proper ownership validation.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Controller as TempViewpointController
    participant Repository as TempWishlistSpecificViewpointRepository
    participant TempDB as Temp Database
    
    Note over Client,TempDB: DELETE /api/v1/temp-viewpoint/specific-viewpoint/{id}
    
    Client->>Controller: DELETE /specific-viewpoint/{id}
    
    rect rgb(200, 230, 255)
    Note right of Controller: Ownership Validation
    Controller->>Repository: findByIdAndCurrentUser(id, user_id)
    Repository->>TempDB: SELECT with user validation
    end
    
    alt Viewpoint Found and Owned
        rect rgb(200, 255, 200)
        Note right of Repository: Delete Operation
        TempDB-->>Repository: Return viewpoint record
        Repository-->>Controller: Viewpoint object
        Controller->>Repository: deleteById(id)
        Repository->>TempDB: DELETE FROM temp_wl_spec_vps WHERE id = ?
        TempDB-->>Repository: Deletion confirmed
        Repository-->>Controller: Success
        Controller-->>Client: 200 OK "Specific viewpoint deleted successfully"
        end
    else Viewpoint Not Found or Access Denied
        rect rgb(255, 230, 230)
        TempDB-->>Repository: NULL result
        Repository-->>Controller: NULL
        Controller-->>Client: 404 Not Found "Specific viewpoint not found"
        end
    end

Steps

Step 1: Delete Request

  • Description: User requests deletion of specific viewpoint
  • Request: DELETE /api/v1/temp-viewpoint/specific-viewpoint/{id}
  • Authorization: User can only delete own viewpoints

Step 2: Ownership Validation

  • Description: Verify user owns the viewpoint
  • Action: Query with user_id filter to ensure ownership
  • Security: Prevents unauthorized deletion of other users' viewpoints

Step 3: Deletion Operation

  • Description: Remove viewpoint from database
  • Action: DELETE single record from temp_wl_spec_vps
  • Response: Success confirmation or error message

Production Conversion & DS Analyzer Integration

Conversion to Production Viewpoints

When temporary wishlists are converted to production, the ViewpointService::create() method handles the transfer of viewpoint data and integration with DS Analyzer:

Key Conversion Process

  1. Copy Viewpoint Data: Transfer from temp tables to production tables (wl_cat_vps, wl_cat_vp_details, wl_spec_vps)
  2. Assign Ordinal Numbers: Production viewpoints receive ordinal numbers for analysis ordering
  3. DS Analyzer Push: Automatic push of category and specific viewpoint data to analyzer database
  4. Short Detail Integration: short_detail from temp data is passed to DS Analyzer for quick category overviews

ViewpointService Integration Points

// Extract short_detail from temp data during conversion
if ($tempWishlistCategoryViewpointDetail) {
    $categoryShortDetail = $tempWishlistCategoryViewpointDetail->short_detail;
} else {
    // Fallback: Generate via OpenAI if no temp data
    $categoryShortDetail = $this->tempViewpointService->generateCategoryDetailUsingChatGPT($categoryName)->short_detail;
}

// Push to DS Analyzer
$this->viewpointCategoryRepository->create([
    'viewpoint_category_id' => $wishlistCategoryViewpoint->id,
    'name' => $categoryName,
    'short_detail' => $categoryShortDetail,
]);

Important Behavior Changes (2025-07-24)

1. Delete-Before-Generate Pattern

Current Behavior: When generating specific viewpoints, ALL existing viewpoints for the category detail are deleted first.

Impact:

  • No incremental addition of viewpoints
  • Users lose previous viewpoints when regenerating
  • Ensures clean slate for each generation

Recommendation: Inform users about this behavior in the UI with confirmation dialogs.

2. Short Detail Integration

New Feature: Category details now include both detailed and brief descriptions.

Benefits:

  • Quick category overviews for DS Analyzer dashboards
  • Better user experience with summary information
  • Enhanced data for production conversion

3. Enhanced Error Handling

Improvements:

  • Better transaction management with proper rollback
  • More specific error messages for OpenAI failures
  • Improved logging for debugging and monitoring

Additional Notes

OpenAI Integration Considerations

  • Rate Limiting: Generation requests may hit OpenAI rate limits during peak usage
  • Token Usage: Both detail and short_detail generation increases token consumption
  • Retry Logic: Built-in retry mechanisms handle temporary API failures
  • Prompt Versioning: Prompt templates are versioned for consistent generation quality

Performance Considerations

  • Transaction Safety: All generation operations are wrapped in database transactions
  • Bulk Operations: Specific viewpoints are inserted using bulk operations for efficiency
  • Caching: Consider implementing caching for frequently requested categories
  • Database Indexing: Proper indexes on foreign keys improve query performance

Security & Authorization

  • Group Membership: Users must be group members to generate viewpoints
  • Ownership Validation: Individual deletion requires ownership verification
  • Data Isolation: Users can only access viewpoints within their group context
  • API Rate Limiting: Consider implementing rate limiting for generation endpoints

Future Enhancements

  • Backup/Restore: Implement backup functionality before generation to prevent data loss
  • Generation Modes: Consider "add mode" vs "replace mode" for specific viewpoints
  • Batch Operations: Support for generating multiple categories simultaneously
  • Improved UI Warnings: Better user notifications about delete-before-generate behavior