Files
PriceUpdaterAppv2/.kiro/specs/shopify-tui/design.md

13 KiB

Design Document

Overview

The Shopify Price Updater TUI will be built as a Node.js terminal user interface that provides an interactive, menu-driven experience for all existing functionality. The design leverages the blessed library for robust terminal UI components and maintains complete integration with the existing service layer architecture. The TUI will serve as an alternative interface to the CLI while preserving all existing functionality and logging behavior.

Architecture

High-Level Architecture

graph TB
    A[TUI Entry Point] --> B[TUI Application Controller]
    B --> C[Screen Manager]
    C --> D[Main Menu Screen]
    C --> E[Configuration Screen]
    C --> F[Operations Screen]
    C --> G[Scheduling Screen]
    C --> H[Logs Screen]
    C --> I[Tag Analysis Screen]

    B --> J[State Manager]
    B --> K[Existing Services Layer]

    K --> L[ProductService]
    K --> M[ShopifyService]
    K --> N[ProgressService]
    K --> O[ScheduleService]

    J --> P[Configuration State]
    J --> Q[Operation State]
    J --> R[UI State]

Component Layers

  1. TUI Layer: User interface components and screen management
  2. State Management Layer: Application state and configuration management
  3. Integration Layer: Bridges TUI with existing services
  4. Service Layer: Existing business logic (unchanged)

Components and Interfaces

Core TUI Components

TUIApplication

class TUIApplication {
    constructor()
    initialize()
    run()
    shutdown()
    handleGlobalKeypress(key)
}

Responsibilities:

  • Application lifecycle management
  • Global keyboard shortcuts
  • Screen routing and navigation
  • Integration with existing services

ScreenManager

class ScreenManager {
    constructor(blessed, stateManager)
    registerScreen(name, screenClass)
    showScreen(name, params)
    getCurrentScreen()
    goBack()
    showModal(content, options)
}

Responsibilities:

  • Screen lifecycle management
  • Navigation history
  • Modal dialog management
  • Screen transitions

StateManager

class StateManager {
    constructor()
    getConfiguration()
    updateConfiguration(key, value)
    validateConfiguration()
    saveConfiguration()
    getOperationState()
    updateOperationState(state)
    subscribe(event, callback)
}

Responsibilities:

  • Centralized state management
  • Configuration persistence
  • State change notifications
  • Validation coordination

Screen Components

MainMenuScreen

  • Purpose: Primary navigation hub
  • Features: Menu options, status indicators, quick actions
  • Navigation: Routes to all other screens

ConfigurationScreen

  • Purpose: Environment variable management
  • Features: Form inputs, validation, API testing
  • Components: Input fields, validation messages, save/cancel buttons

OperationsScreen

  • Purpose: Price update and rollback execution
  • Features: Operation selection, progress tracking, results display
  • Components: Progress bars, product lists, error panels

SchedulingScreen

  • Purpose: Scheduled operation management
  • Features: Date/time picker, countdown display, cancellation
  • Components: Calendar widget, time input, countdown timer

LogsScreen

  • Purpose: Operation history and log viewing
  • Features: Log filtering, search, pagination
  • Components: Log list, search bar, filter controls

TagAnalysisScreen

  • Purpose: Product tag debugging and analysis
  • Features: Tag listing, product counts, sample display
  • Components: Tag tree, product preview, statistics panel

UI Component Library

Common Components

  • FormField: Reusable input component with validation
  • ProgressBar: Animated progress indicator
  • StatusBar: Global status and connection indicator
  • ErrorPanel: Error display with retry options
  • ConfirmDialog: Modal confirmation dialogs
  • HelpOverlay: Context-sensitive help system

Data Models

Configuration Model

{
    shopifyShopDomain: string,
    shopifyAccessToken: string,
    targetTag: string,
    priceAdjustmentPercentage: number,
    operationMode: 'update' | 'rollback',
    isScheduled: boolean,
    scheduledExecutionTime: Date,
    isValid: boolean,
    validationErrors: string[]
}

Operation State Model

{
    currentOperation: 'idle' | 'fetching' | 'updating' | 'rollback' | 'scheduled',
    progress: {
        current: number,
        total: number,
        percentage: number,
        currentProduct: string
    },
    results: {
        totalProducts: number,
        totalVariants: number,
        successfulUpdates: number,
        failedUpdates: number,
        errors: Array
    },
    canCancel: boolean
}

UI State Model

{
    currentScreen: string,
    navigationHistory: string[],
    modalStack: Array,
    globalMessages: Array,
    keyboardShortcuts: Object,
    theme: Object
}

Error Handling

Error Categories

  1. Configuration Errors: Invalid environment variables, API credentials
  2. Network Errors: Shopify API connectivity issues
  3. Operation Errors: Price update failures, validation errors
  4. UI Errors: Screen rendering issues, input validation

Error Handling Strategy

  • Graceful Degradation: UI remains functional during errors
  • User-Friendly Messages: Technical errors translated to user language
  • Recovery Options: Retry mechanisms and alternative actions
  • Error Logging: All errors logged to existing progress system

Error Display Components

  • Inline Validation: Real-time input validation feedback
  • Error Panels: Dedicated error display areas
  • Toast Notifications: Temporary error messages
  • Modal Dialogs: Critical error handling

Testing Strategy

Unit Testing

  • Component Testing: Individual screen and component functionality
  • State Management Testing: Configuration and state transitions
  • Integration Testing: TUI-to-service layer integration
  • Mock Testing: Shopify API interactions

Test Structure

tests/
├── tui/
│   ├── components/
│   │   ├── screens/
│   │   └── common/
│   ├── state/
│   └── integration/
└── fixtures/
    └── tui-test-data.js

Testing Approach

  • Blessed Testing: Use blessed's testing utilities for UI components
  • State Testing: Verify state transitions and persistence
  • Service Integration: Ensure existing services work unchanged
  • User Journey Testing: End-to-end workflow validation

Implementation Details

Technology Stack

  • UI Framework: blessed - Mature, feature-rich terminal UI library
  • State Management: Custom implementation using EventEmitter pattern
  • Configuration: Extend existing environment.js configuration system
  • Logging: Integrate with existing ProgressService for consistent logging

Key Design Decisions

Choice of Blessed Library

  • Rationale: Mature, well-documented, extensive widget library
  • Benefits: Rich component set, event handling, layout management
  • Alternatives Considered: Ink (React-based), terminal-kit, raw ANSI

State Management Pattern

  • Rationale: Centralized state with event-driven updates
  • Benefits: Predictable state changes, easy debugging, component isolation
  • Implementation: Custom StateManager with EventEmitter for notifications

Service Integration Strategy

  • Rationale: Preserve existing service layer without modifications
  • Benefits: Maintains existing functionality, easier testing, reduced risk
  • Implementation: TUI acts as alternative controller layer

Screen Layout Design

Main Menu Layout

┌─ Shopify Price Updater TUI ─────────────────────────────────┐
│ Status: Connected ✓ | Config: Valid ✓ | Last Run: 2h ago    │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. Configure Settings                                      │
│  2. Update Prices                                          │
│  3. Rollback Prices                                        │
│  4. Schedule Operation                                     │
│  5. View Logs                                              │
│  6. Analyze Tags                                           │
│  7. Help                                                   │
│  8. Exit                                                   │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│ Press number key or use arrows + Enter | F1: Help | Q: Quit │
└─────────────────────────────────────────────────────────────┘

Operations Screen Layout

┌─ Price Update Operation ────────────────────────────────────┐
│ Target Tag: sale-items | Adjustment: +15% | Mode: Update    │
├─────────────────────────────────────────────────────────────┤
│ Progress: [████████████████████████████████████████] 85%    │
│ Products: 127/150 | Variants: 342/400 | Errors: 3          │
├─────────────────────────────────────────────────────────────┤
│ Current Product: "Premium Widget Set"                       │
│ Status: Updating variant prices...                          │
│                                                             │
│ Recent Errors:                                              │
│ • Product "Basic Kit": Invalid price format                │
│ • Product "Deluxe Set": API rate limit (retrying...)       │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│ ESC: Cancel (if safe) | F1: Help | Space: Pause/Resume     │
└─────────────────────────────────────────────────────────────┘

Keyboard Navigation Design

  • Global Shortcuts: F1 (Help), ESC (Back/Cancel), Q (Quit)
  • Menu Navigation: Arrow keys, Tab, Enter, Number keys
  • Form Navigation: Tab/Shift+Tab, Enter (submit), ESC (cancel)
  • List Navigation: Arrow keys, Page Up/Down, Home/End

Theme and Styling

  • Color Scheme: Terminal-friendly colors with fallbacks
  • Status Indicators: Unicode symbols with text alternatives
  • Progress Indicators: ASCII progress bars with percentage
  • Responsive Design: Adapts to different terminal sizes

Integration Points

Existing Service Integration

  • ProductService: Direct integration for all product operations
  • ShopifyService: API connectivity and authentication
  • ProgressService: Logging integration for audit trail
  • ScheduleService: Scheduling functionality integration

Configuration Integration

  • Environment Variables: Read/write to existing .env system
  • Validation: Use existing configuration validation logic
  • Persistence: Maintain compatibility with CLI configuration

Logging Integration

  • Progress.md: Continue writing to existing log file
  • Console Output: Maintain existing log format for compatibility
  • Error Tracking: Use existing error categorization and handling

Performance Considerations

Memory Management

  • Screen Caching: Cache frequently used screens
  • Event Cleanup: Proper event listener cleanup on screen changes
  • Large Data Sets: Pagination for large product lists and logs

Responsiveness

  • Async Operations: Non-blocking UI during API calls
  • Progress Feedback: Real-time progress updates
  • Cancellation: Safe operation cancellation where possible

Terminal Compatibility

  • Size Adaptation: Responsive layout for different terminal sizes
  • Color Support: Graceful fallback for terminals without color
  • Unicode Support: ASCII alternatives for Unicode characters