Files
igny8/docs/plans/IMPLEMENTATION-PLAN-PHASES-1-5-6.md
IGNY8 VPS (Salman) 0526553c9b Phase 1: Code cleanup - remove unused pages, components, and console.logs
- Deleted 6 empty folders (pages/Admin, pages/admin, pages/settings, components/debug, components/widgets, components/metrics)
- Removed unused template components:
  - ecommerce/ (7 files)
  - sample-componeents/ (2 HTML files)
  - charts/bar/ and charts/line/
  - tables/BasicTables/
- Deleted deprecated file: CurrentProcessingCard.old.tsx
- Removed console.log statements from:
  - UserProfile components (UserMetaCard, UserAddressCard, UserInfoCard)
  - Automation/ConfigModal
  - ImageQueueModal (8 statements)
  - ImageGenerationCard (7 statements)
- Applied ESLint auto-fixes (9 errors fixed)
- All builds pass ✓
- TypeScript compiles without errors ✓
2026-01-09 15:22:23 +00:00

24 KiB

Implementation Plan: Phases 1, 5, and 6

Created: January 9, 2026
Target: Safe, verified execution of cleanup, UX improvements, and data backup


Table of Contents

  1. Phase 1: Code Cleanup & Technical Debt
  2. Phase 5: UX Improvements
  3. Phase 6: Data Backup & Cleanup
  4. Execution Checklist

Phase 1: Code Cleanup & Technical Debt

1.1 Pre-Cleanup Verification

1.1.1 Create Safety Branch

# BEFORE ANY CHANGES - Create a safety branch
cd /data/app/igny8
git checkout -b cleanup/phase-1-$(date +%Y%m%d)
git push origin cleanup/phase-1-$(date +%Y%m%d)

1.1.2 Run Full Test Suite (Baseline)

# Backend tests
cd /data/app/igny8/backend
python manage.py test --verbosity=2 > /tmp/test-baseline-backend.log 2>&1
echo "Exit code: $?"

# Frontend build check
cd /data/app/igny8/frontend
npm run build > /tmp/test-baseline-frontend.log 2>&1
echo "Exit code: $?"

# Frontend lint check
npm run lint > /tmp/test-baseline-lint.log 2>&1

CHECKPOINT: All tests must pass before proceeding.


1.2 Frontend Cleanup - Empty/Unused Folders

Files to Delete (Verified Empty/Unused)

Path Reason Verified
frontend/src/pages/Admin/ Empty folder
frontend/src/pages/admin/ Empty folder (duplicate lowercase)
frontend/src/pages/settings/ Empty folder (lowercase duplicate)
frontend/src/components/debug/ Empty debug folder
frontend/src/components/widgets/ Empty folder
frontend/src/components/metrics/ Empty folder

Execution Steps:

# Step 1: Verify folders are empty
cd /data/app/igny8/frontend/src

# Check each folder before deletion
ls -la pages/Admin/ 2>/dev/null || echo "Admin/ doesn't exist or empty"
ls -la pages/admin/ 2>/dev/null || echo "admin/ doesn't exist or empty"
ls -la pages/settings/ 2>/dev/null || echo "settings/ doesn't exist or empty"
ls -la components/debug/ 2>/dev/null || echo "debug/ doesn't exist or empty"
ls -la components/widgets/ 2>/dev/null || echo "widgets/ doesn't exist or empty"
ls -la components/metrics/ 2>/dev/null || echo "metrics/ doesn't exist or empty"

# Step 2: Remove empty folders (only if confirmed empty)
rmdir pages/Admin 2>/dev/null
rmdir pages/admin 2>/dev/null
rmdir pages/settings 2>/dev/null
rmdir components/debug 2>/dev/null
rmdir components/widgets 2>/dev/null
rmdir components/metrics 2>/dev/null

CHECKPOINT: Run npm run build - must succeed.


1.3 Frontend Cleanup - Template/Sample Components

Components to Delete (Never Used - Template/Demo Code)

Path File Count Reason
frontend/src/components/ecommerce/ 7 files E-commerce template components - not used in app
frontend/src/components/sample-componeents/ 2 files Sample HTML files with typo in folder name
frontend/src/components/charts/bar/ - Unused bar chart template
frontend/src/components/charts/line/ - Unused line chart template
frontend/src/components/tables/BasicTables/ - Unused basic table template

Pre-Delete Verification:

# Search for any imports of these components
cd /data/app/igny8/frontend

# Check ecommerce imports
grep -r "ecommerce" src/ --include="*.ts" --include="*.tsx" | grep -v "node_modules"

# Check sample imports
grep -r "sample-componeents" src/ --include="*.ts" --include="*.tsx"

# Check charts/bar imports
grep -r "charts/bar" src/ --include="*.ts" --include="*.tsx"

# Check charts/line imports
grep -r "charts/line" src/ --include="*.ts" --include="*.tsx"

# Check BasicTables imports
grep -r "BasicTables" src/ --include="*.ts" --include="*.tsx"

Execution (Only if no imports found):

cd /data/app/igny8/frontend/src

# Delete unused template folders
rm -rf components/ecommerce/
rm -rf components/sample-componeents/
rm -rf components/charts/bar/
rm -rf components/charts/line/
rm -rf components/tables/BasicTables/

# If charts folder is now empty, remove it
rmdir components/charts 2>/dev/null || true
# If tables folder is now empty, remove it
rmdir components/tables 2>/dev/null || true

CHECKPOINT: Run npm run build - must succeed.


1.4 Frontend Cleanup - Deprecated Files

Individual Files to Delete

File Reason
frontend/src/components/Automation/CurrentProcessingCard.old.tsx Old deprecated version

Execution:

# Verify no imports exist
cd /data/app/igny8/frontend
grep -r "CurrentProcessingCard.old" src/

# If no results, safe to delete
rm src/components/Automation/CurrentProcessingCard.old.tsx

CHECKPOINT: Run npm run build - must succeed.


1.5 Console.log Cleanup

Files with console.log statements to review:

File Line(s) Action
src/services/api.ts 2010, 2015 Review - may need for debugging
src/components/UserProfile/UserMetaCard.tsx 11 Remove
src/components/UserProfile/UserAddressCard.tsx 11 Remove
src/components/UserProfile/UserInfoCard.tsx 11 Remove
src/components/Automation/ConfigModal.tsx 42 Remove
src/components/common/ImageQueueModal.tsx 227, 229, 239, 242, 247, 251, 259, 262 Remove all
src/components/common/ImageGenerationCard.tsx 107, 125, 129, 141, 142, 151, 178 Remove all

Execution Strategy:

Option A: Manual removal (safer) Edit each file and remove console.log statements manually.

Option B: Automated with review

cd /data/app/igny8/frontend

# Find all console.log in src (excluding node_modules)
grep -rn "console.log" src/ --include="*.ts" --include="*.tsx" > /tmp/console-logs.txt

# Review the file before any automated removal
cat /tmp/console-logs.txt

Per-File Actions:

// In UserMetaCard.tsx, UserAddressCard.tsx, UserInfoCard.tsx - REMOVE:
console.log("Saving changes...");

// In ConfigModal.tsx - REMOVE:
console.log('Saving config with delays:', dataToSave);

// In ImageQueueModal.tsx - REMOVE ALL console.log statements

// In ImageGenerationCard.tsx - REMOVE ALL console.log statements

// In api.ts - KEEP or convert to proper logging (these may be useful)

CHECKPOINT: Run npm run build && npm run lint - must succeed.


1.6 ESLint Verification

cd /data/app/igny8/frontend

# Run full lint check
npm run lint

# If errors exist, fix them:
npm run lint -- --fix

CHECKPOINT: Zero lint errors.


1.7 Post-Cleanup Verification

# 1. Full build
cd /data/app/igny8/frontend
npm run build

# 2. Type check
npx tsc --noEmit

# 3. Start dev server and manually verify app loads
npm run dev
# Open http://localhost:5173 and verify:
# - Dashboard loads
# - All sidebar navigation works
# - No console errors in browser

# 4. Commit changes
cd /data/app/igny8
git add -A
git status  # Review all changes
git commit -m "Phase 1: Code cleanup - remove unused pages, components, and console.logs"

Phase 5: UX Improvements

5.1 Pre-Implementation Setup

5.1.1 Create Feature Branch

cd /data/app/igny8
git checkout main  # or your main branch
git pull
git checkout -b feature/phase-5-ux-improvements

5.2 Search Modal Enhancement

5.2.1 Current State Analysis

Location: Search functionality likely in header/navigation components

Research Required:

cd /data/app/igny8/frontend

# Find existing search component
grep -rn "search" src/components/header/ --include="*.tsx"
grep -rn "Search" src/components/ --include="*.tsx" | head -20

# Find search-related stores
grep -rn "search" src/store/ --include="*.ts"

5.2.2 Implementation Tasks

Task File(s) Details
Add keyboard shortcut src/components/header/Search*.tsx Cmd/Ctrl+K to open
Add search filters Search component Filter by type (keyword, content, site)
Add recent searches Search component + localStorage Store last 5 searches
Improve results display Search results component Show context snippets
Add quick actions Search results Quick action buttons

5.2.3 Keyboard Shortcut Implementation

// Add to App.tsx or a global hook
useEffect(() => {
  const handleKeyDown = (e: KeyboardEvent) => {
    if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
      e.preventDefault();
      // Open search modal
      setSearchOpen(true);
    }
  };
  
  window.addEventListener('keydown', handleKeyDown);
  return () => window.removeEventListener('keydown', handleKeyDown);
}, []);

5.2.4 Verification

  • Cmd/Ctrl+K opens search modal
  • Search filters work correctly
  • Recent searches persist across sessions
  • Results show relevant context
  • Quick actions function properly

5.3 Image Regeneration Feature

5.3.1 Backend Requirements

Check existing endpoint:

cd /data/app/igny8/backend

# Find image generation endpoints
grep -rn "image" igny8_core/modules/writer/ --include="*.py" | head -20
grep -rn "regenerate" igny8_core/ --include="*.py"

Required API endpoint (if not exists):

POST /api/v1/writer/images/{id}/regenerate/
Body: { reason?: string, prompt_adjustment?: string }
Response: { task_id: string, status: "queued" }

5.3.2 Frontend Implementation

File: frontend/src/pages/Writer/Images.tsx

Add regenerate button to each image card:

// Add to image card actions
const handleRegenerate = async (imageId: number) => {
  const reason = await showRegenerateModal();
  if (reason !== null) {
    await api.post(`/v1/writer/images/${imageId}/regenerate/`, { reason });
    // Refresh list or show status
  }
};

// Button in image card
<Button 
  variant="outline" 
  size="sm" 
  onClick={() => handleRegenerate(image.id)}
>
  <RefreshIcon /> Regenerate
</Button>

File: frontend/src/pages/Writer/ContentView.tsx

Add regenerate for featured image:

// In featured image section (admin/editor only)
{(user.role === 'admin' || user.role === 'editor') && (
  <Button onClick={() => handleRegenerateFeaturedImage(content.id)}>
    Regenerate Featured Image
  </Button>
)}

5.3.3 Verification

  • Regenerate button appears on /writer/images page
  • Regenerate modal prompts for reason
  • API call succeeds and image regenerates
  • Status updates correctly
  • Featured image regenerate works in content view
  • Role-based visibility works (admin/editor only)

5.4 User Flow Polish

5.4.1 Signup to First Content Flow Testing

Test Checklist:

Step URL Verify
1. Signup /signup Form submits, verification email sent
2. Verify Email /verify-email?token=... Email verified, redirect to app
3. Onboarding /setup/wizard All steps complete without errors
4. Add Site Sites → Add Site WordPress connection successful
5. Add Keywords /planner/keywords Import works, keywords appear
6. Clustering /planner/clusters AI clustering completes
7. Generate Content /writer/tasks Content generates successfully
8. Publish Content → Publish Content appears on WordPress

5.4.2 Issue Documentation Template

## Issue: [Brief Description]

**Step:** [Which step in flow]
**URL:** [Page URL]
**Expected:** [What should happen]
**Actual:** [What happened]
**Steps to Reproduce:**
1. ...
2. ...

**Screenshots/Logs:** [Attach if applicable]
**Severity:** [Blocking/Major/Minor]

5.4.3 Post-Implementation Verification

# Build and test
cd /data/app/igny8/frontend
npm run build
npm run lint

# Commit
git add -A
git commit -m "Phase 5: UX improvements - search modal, image regeneration, flow polish"

Phase 6: Data Backup & Cleanup

6.1 Pre-Backup Safety Steps

6.1.1 Create Backup Branch

cd /data/app/igny8
git checkout main
git checkout -b backup/pre-v1-cleanup-$(date +%Y%m%d)

6.1.2 Full Database Backup

# Create backup directory
mkdir -p /data/app/igny8/backups/$(date +%Y%m%d)

# PostgreSQL full backup
pg_dump -h localhost -U your_user -d igny8_db > /data/app/igny8/backups/$(date +%Y%m%d)/full_backup.sql

# Verify backup
ls -la /data/app/igny8/backups/$(date +%Y%m%d)/
head -50 /data/app/igny8/backups/$(date +%Y%m%d)/full_backup.sql

CHECKPOINT: Backup file exists and has content.


6.2 System Configuration Export

6.2.1 Create Export Directory Structure

mkdir -p /data/app/igny8/backups/config

6.2.2 Export Django Models (System Config)

Create management command:

# File: backend/igny8_core/management/commands/export_system_config.py
# backend/igny8_core/management/commands/export_system_config.py
from django.core.management.base import BaseCommand
from django.core import serializers
import json
import os
from datetime import datetime

class Command(BaseCommand):
    help = 'Export system configuration data to JSON files'

    def add_arguments(self, parser):
        parser.add_argument(
            '--output-dir',
            default='backups/config',
            help='Output directory for config files'
        )

    def handle(self, *args, **options):
        output_dir = options['output_dir']
        os.makedirs(output_dir, exist_ok=True)
        
        # Import models here to avoid circular imports
        from igny8_core.modules.billing.models import Plan, CreditCostConfig
        from igny8_core.modules.system.models import (
            AIModelConfig, GlobalIntegrationSettings, SystemSettings
        )
        from igny8_core.auth.models import Industry, Sector, SeedKeyword
        # Add other system models as needed
        
        exports = {
            'plans': Plan.objects.all(),
            'credit_costs': CreditCostConfig.objects.all(),
            'ai_models': AIModelConfig.objects.all(),
            # 'global_integrations': GlobalIntegrationSettings.objects.all(),
            # 'system_settings': SystemSettings.objects.all(),
            'industries': Industry.objects.all(),
            'sectors': Sector.objects.all(),
            'seed_keywords': SeedKeyword.objects.all(),
        }
        
        for name, queryset in exports.items():
            try:
                data = serializers.serialize('json', queryset, indent=2)
                filepath = os.path.join(output_dir, f'{name}.json')
                with open(filepath, 'w') as f:
                    f.write(data)
                self.stdout.write(
                    self.style.SUCCESS(f'Exported {queryset.count()} {name} to {filepath}')
                )
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'Failed to export {name}: {str(e)}')
                )
        
        # Export timestamp
        with open(os.path.join(output_dir, 'export_metadata.json'), 'w') as f:
            json.dump({
                'exported_at': datetime.now().isoformat(),
                'exports': list(exports.keys())
            }, f, indent=2)
        
        self.stdout.write(self.style.SUCCESS('System config export complete!'))

6.2.3 Run Export

cd /data/app/igny8/backend

# Run the export command
python manage.py export_system_config --output-dir=../backups/config

# Verify exports
ls -la ../backups/config/

CHECKPOINT: All config JSON files exist and contain data.


6.3 User Data Cleanup

⚠️ DANGER ZONE - READ CAREFULLY ⚠️

This section PERMANENTLY DELETES user data. Ensure:

  1. Full backup completed (6.1.2)
  2. Config exported (6.2)
  3. You are in the correct environment (NOT PRODUCTION until ready)

6.3.1 Create Cleanup Management Command

# backend/igny8_core/management/commands/cleanup_user_data.py
from django.core.management.base import BaseCommand
from django.db import transaction

class Command(BaseCommand):
    help = 'Clean up all user-generated data (DESTRUCTIVE)'

    def add_arguments(self, parser):
        parser.add_argument(
            '--confirm',
            action='store_true',
            help='Confirm you want to delete all user data'
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be deleted without deleting'
        )

    def handle(self, *args, **options):
        if not options['confirm'] and not options['dry_run']:
            self.stdout.write(
                self.style.ERROR('Must use --confirm or --dry-run flag')
            )
            return
        
        # Import models
        from igny8_core.auth.models import Site
        from igny8_core.business.planning.models import Keywords, Clusters
        from igny8_core.modules.writer.models import (
            ContentIdea, Task, Content, ContentImage
        )
        from igny8_core.modules.publisher.models import PublishingRecord, SyncEvent
        from igny8_core.modules.billing.models import CreditTransaction, CreditUsageLog
        # Add other models
        
        models_to_clear = [
            ('Keywords', Keywords),
            ('Clusters', Clusters),
            ('ContentIdeas', ContentIdea),
            ('Tasks', Task),
            ('Content', Content),
            ('ContentImages', ContentImage),
            ('PublishingRecords', PublishingRecord),
            ('SyncEvents', SyncEvent),
            ('CreditTransactions', CreditTransaction),
            ('CreditUsageLogs', CreditUsageLog),
            # Sites should be last (foreign keys)
            ('Sites', Site),
        ]
        
        if options['dry_run']:
            self.stdout.write(self.style.WARNING('DRY RUN - No data will be deleted'))
            for name, model in models_to_clear:
                count = model.objects.count()
                self.stdout.write(f'  Would delete {count} {name}')
            return
        
        # Actual deletion
        with transaction.atomic():
            for name, model in models_to_clear:
                count = model.objects.count()
                model.objects.all().delete()
                self.stdout.write(
                    self.style.SUCCESS(f'Deleted {count} {name}')
                )
        
        self.stdout.write(self.style.SUCCESS('User data cleanup complete!'))

6.3.2 Execute Cleanup (Step by Step)

cd /data/app/igny8/backend

# Step 1: DRY RUN - See what will be deleted
python manage.py cleanup_user_data --dry-run

# Step 2: Review output carefully
# - Are the counts expected?
# - Is this the right environment?

# Step 3: ONLY if absolutely sure, run actual cleanup
python manage.py cleanup_user_data --confirm

6.3.3 Clear Media Storage

# List media files first
ls -la /data/app/igny8/backend/media/

# Backup media if needed
cp -r /data/app/igny8/backend/media/ /data/app/igny8/backups/$(date +%Y%m%d)/media/

# Clear generated images (be specific about paths)
rm -rf /data/app/igny8/backend/media/generated_images/*
rm -rf /data/app/igny8/backend/media/content_images/*

# Verify
ls -la /data/app/igny8/backend/media/

6.3.4 Clear Logs

# Backup logs first
cp -r /data/app/igny8/backend/logs/ /data/app/igny8/backups/$(date +%Y%m%d)/logs/

# Clear log files (keep empty files for app to write)
> /data/app/igny8/backend/logs/publish-sync-logs/*.log
> /data/app/igny8/backend/celerybeat-schedule

# Or remove all logs
rm -f /data/app/igny8/backend/logs/**/*.log

6.4 Configuration Lock (V1.0)

6.4.1 Document Final Configuration

Create documentation file:

mkdir -p /data/app/igny8/docs/90-REFERENCE/
# V1.0 Configuration Reference

**Locked:** [DATE]
**Version:** 1.0.0

## Plans Configuration

| Plan | Credits | Sites | Price | Interval |
|------|---------|-------|-------|----------|
| Starter | X | 1 | $X/mo | monthly |
| Growth | X | 3 | $X/mo | monthly |
| Scale | X | 10 | $X/mo | monthly |

## Credit Costs

| Operation | Cost |
|-----------|------|
| Basic Image | 1 credit |
| Quality Image | 5 credits |
| Premium Image | 15 credits |
| Clustering | Token-based |
| Content Generation | Token-based |

## AI Model Configurations

[Document all AI model settings]

---

**CHANGE POLICY:** Any changes require version bump and documented release.

6.4.2 Git Tag for V1.0

cd /data/app/igny8

# Ensure all changes committed
git status
git add -A
git commit -m "Phase 6: Pre-launch cleanup complete"

# Create annotated tag
git tag -a v1.0.0 -m "IGNY8 V1.0.0 - Production Release"

# Push tag
git push origin v1.0.0

6.5 Post-Cleanup Verification

6.5.1 Database Verification

cd /data/app/igny8/backend

# Run Django check
python manage.py check

# Verify system config still exists
python manage.py shell << 'EOF'
from igny8_core.modules.billing.models import Plan
from igny8_core.auth.models import Industry, Sector
print(f"Plans: {Plan.objects.count()}")
print(f"Industries: {Industry.objects.count()}")
print(f"Sectors: {Sector.objects.count()}")
EOF

# Verify user data cleared
python manage.py shell << 'EOF'
from igny8_core.auth.models import Site
from igny8_core.business.planning.models import Keywords
print(f"Sites: {Site.objects.count()}")
print(f"Keywords: {Keywords.objects.count()}")
EOF

6.5.2 Application Verification

# Start backend
cd /data/app/igny8/backend
python manage.py runserver &

# Start frontend
cd /data/app/igny8/frontend
npm run dev &

# Manual checks:
# 1. Can login as admin
# 2. Dashboard loads (empty state)
# 3. Plans visible in settings
# 4. Can create new user account
# 5. Onboarding flow works

Execution Checklist

Phase 1 Checklist

  • Created safety branch
  • Ran baseline tests (all pass)
  • Deleted empty folders (6 folders)
  • Build succeeds after empty folder deletion
  • Deleted template/sample components (ecommerce, sample-componeents, charts, tables)
  • Build succeeds after template deletion
  • Deleted CurrentProcessingCard.old.tsx
  • Removed console.log statements (reviewed each)
  • ESLint passes with zero errors
  • TypeScript compiles without errors
  • Manual app verification complete
  • Changes committed

Phase 5 Checklist

  • Created feature branch
  • Researched existing search implementation
  • Implemented keyboard shortcut (Cmd/Ctrl+K)
  • Added search filters
  • Added recent searches
  • Improved results display
  • Added image regenerate to /writer/images
  • Added featured image regenerate to content view
  • Backend endpoint created/verified
  • Role-based visibility works
  • Tested full signup-to-publish flow
  • Documented any issues found
  • Changes committed

Phase 6 Checklist

  • Created backup branch
  • Full database backup created
  • Backup file verified (has content)
  • Created export_system_config command
  • Exported all system config (plans, industries, etc.)
  • Config files verified (JSON valid)
  • Created cleanup_user_data command
  • Ran dry-run cleanup (reviewed counts)
  • CONFIRMED correct environment
  • Executed user data cleanup
  • Cleared media storage
  • Backed up and cleared logs
  • Created V1.0 config documentation
  • Created git tag v1.0.0
  • Verified system config still exists
  • Verified user data cleared
  • Application starts and functions

Rollback Procedures

Phase 1 Rollback

git checkout main
git branch -D cleanup/phase-1-*

Phase 5 Rollback

git checkout main
git branch -D feature/phase-5-ux-improvements

Phase 6 Rollback (Database)

# Restore from backup
psql -h localhost -U your_user -d igny8_db < /data/app/igny8/backups/YYYYMMDD/full_backup.sql

# Restore media
cp -r /data/app/igny8/backups/YYYYMMDD/media/* /data/app/igny8/backend/media/

Document Owner: IGNY8 Team
Review: Before each phase execution
Approval Required: Phase 6 cleanup requires explicit approval