diff --git a/docs/plans/COMPREHENSIVE-SYSTEM-FIX-PLAN-JAN-10-2026.md b/docs/plans/COMPREHENSIVE-SYSTEM-FIX-PLAN-JAN-10-2026.md index 629cca4a..2c6d63fd 100644 --- a/docs/plans/COMPREHENSIVE-SYSTEM-FIX-PLAN-JAN-10-2026.md +++ b/docs/plans/COMPREHENSIVE-SYSTEM-FIX-PLAN-JAN-10-2026.md @@ -1,17 +1,29 @@ # COMPREHENSIVE SYSTEM FIX PLAN **Date:** January 10, 2026 +**Last Updated:** January 10, 2026 **Priority:** CRITICAL -**Status:** Analysis Complete - Ready for Implementation +**Status:** Phase 1 Complete - Phase 2 In Progress --- ## EXECUTIVE SUMMARY -After comprehensive system analysis, I've identified **7 critical issues** with clear root causes and detailed fixes. These issues fall into **3 categories**: +This plan tracks all identified system issues, their status, and implementation details. Issues are categorized by priority and module. -1. **Backend Data Model Inconsistencies** (2 issues) -2. **Missing Credit Tracking & Logging** (1 major issue) -3. **Frontend Issues** (4 issues) +**Issue Categories:** +1. **Backend Data Model & Credits** (2 issues - ✅ COMPLETED) +2. **Frontend - Automation** (3 issues) +3. **Frontend - Publishing & Calendar** (3 issues) +4. **Frontend - Planner/Writer Pages** (2 issues) +5. **Frontend - Sites & Settings** (3 issues) +6. **Branding & Terminology** (2 issues) +7. **New Features** (2 issues) + +**Completion Status:** +- ✅ Phase 1 (Backend Credit System): COMPLETED +- 🔄 Phase 2 (Frontend Critical): IN PROGRESS +- ⏳ Phase 3 (UX Improvements): PENDING +- ⏳ Phase 4 (New Features): PENDING **Impact:** These fixes will ensure: - ✅ All AI functions log consistently to AI tasks, notifications, and usage logs @@ -19,12 +31,15 @@ After comprehensive system analysis, I've identified **7 critical issues** with - ✅ No attribute errors in AI model configuration - ✅ Consistent data display across all pages - ✅ Improved UX with proper button styling and working features +- ✅ Proper terminology throughout the app (site vs wordpress) +- ✅ Auto-approve and auto-publish working correctly +- ✅ Content calendar showing published content --- ## ISSUE 1: AIModelConfig AttributeError - `input_cost_per_1m` -### 🔴 CRITICAL - System Breaking +### ✅ COMPLETED - v1.7.1 **Error Message:** ``` @@ -32,72 +47,41 @@ Failed to cluster keywords: Unexpected error: 'AIModelConfig' object has no attr ``` **Root Cause:** -The `AIModelConfig` model uses field names `cost_per_1k_input` and `cost_per_1k_output`, but `model_registry.py` is trying to access `input_cost_per_1m` and `output_cost_per_1m` (old field names). +The `AIModelConfig` model uses field names `cost_per_1k_input` and `cost_per_1k_output`, but `model_registry.py` was trying to access `input_cost_per_1m` and `output_cost_per_1m` (old field names). -**Location:** -- File: `/backend/igny8_core/ai/model_registry.py` line 121 -- File: `/backend/igny8_core/modules/billing/serializers.py` line 290 +**Fix Applied in v1.7.1:** +- Updated field references in `model_registry.py` to use correct field names +- Updated field references in `serializers.py` to match -**Current Code (WRONG):** -```python -# model_registry.py line 121 -if rate_type == 'input': - return model.input_cost_per_1m or Decimal('0') # ❌ WRONG FIELD NAME -elif rate_type == 'output': - return model.output_cost_per_1m or Decimal('0') # ❌ WRONG FIELD NAME -``` - -**Model Definition (CORRECT):** -```python -# business/billing/models.py line 785-797 -cost_per_1k_input = models.DecimalField(...) # ✅ ACTUAL FIELD NAME -cost_per_1k_output = models.DecimalField(...) # ✅ ACTUAL FIELD NAME -``` - -**Fix Strategy:** -Update field references in `model_registry.py` and `serializers.py` to match actual model field names. - -**Files to Change:** -1. `backend/igny8_core/ai/model_registry.py` (1 fix) -2. `backend/igny8_core/modules/billing/serializers.py` (1 fix) - -**Impact:** -- Fixes: Clustering errors, all AI function cost calculations -- Affects: All AI operations that use ModelRegistry for cost calculation +**Files Changed:** +1. `backend/igny8_core/ai/model_registry.py` +2. `backend/igny8_core/modules/billing/serializers.py` --- ## ISSUE 2: Image Generation - Missing Credit Tracking & Logging -### 🔴 CRITICAL - Business Logic Gap +### ✅ COMPLETED - v1.7.1 **Problem:** -Image generation does NOT: -- ❌ Log to AI tasks table (AITaskLog) -- ❌ Log to notifications -- ❌ Log to usage logs with cost calculations -- ❌ Deduct credits properly based on model configuration +Image generation was not: +- ❌ Logging to AI tasks table (AITaskLog) +- ❌ Logging to notifications +- ❌ Logging to usage logs with cost calculations +- ❌ Deducting credits properly based on model configuration -All other AI functions (clustering, content generation, idea generation) properly log to all 3 locations, but image generation is missing. +**Fix Applied in v1.7.1:** +- Added `CreditService.check_credits_for_image()` method +- Pre-generation credit verification in `tasks.py` +- Credit deduction after each successful image +- AITaskLog creation for image generation +- Notification integration -**Root Cause Analysis:** +**Files Changed:** +1. `backend/igny8_core/business/billing/services/credit_service.py` +2. `backend/igny8_core/ai/tasks.py` -**Current Image Generation Flow:** -``` -generate_images() - → ai_core.generate_image() - → _generate_image_openai()/_generate_image_runware() - → Returns {'url': ..., 'cost': ...} - → ❌ NO credit deduction - → ❌ NO AITaskLog creation - → ❌ NO notification - → ❌ NO usage log -``` - -**Expected Flow (like other AI functions):** -``` -generate_images() - → Check credits (CreditService.check_credits) +**See CHANGELOG v1.7.1 for full details.** → ai_core.generate_image() → Returns result → Deduct credits (CreditService.deduct_credits_for_image) @@ -338,198 +322,108 @@ If not, add them to the notification type choices. ## ISSUE 3: Pause/Cancel Button Colors in Automation -### 🟡 MEDIUM - UX Issue +### ✅ COMPLETED **Problem:** -Pause/Cancel buttons in automation in-progress panel need better button colors for clarity. +Pause/Cancel buttons in automation in-progress panel needed better button colors for clarity. -**Current Implementation:** -File: `frontend/src/components/Automation/CurrentProcessingCardV2.tsx` lines 268-294 +**Fix Applied:** +Updated button variants from `outline` to `primary` for better visibility. +**File:** `frontend/src/components/Automation/CurrentProcessingCardV2.tsx` + +**Current Implementation (CORRECT):** ```tsx -{currentRun.status === 'running' ? ( - -) : currentRun.status === 'paused' ? ( - -)} - + + + ``` -**Recommended Fix:** - -```tsx -{currentRun.status === 'running' ? ( - -) : currentRun.status === 'paused' ? ( - -)} - -``` - -**Rationale:** -- Pause: Solid warning (yellow) button - more visible, important action -- Resume: Already solid success (green) - GOOD -- Cancel: Solid danger (red) button - critical destructive action needs prominence - -**Files to Change:** -1. `frontend/src/components/Automation/CurrentProcessingCardV2.tsx` -2. `frontend/src/components/Automation/CurrentProcessingCard.tsx` (if still used) - --- -## ISSUE 4: Credits Not Updating in Automation In-Progress Panel +## ISSUE 4: Automation Stage Cards - Credits Not Showing During Processing + +### 🔴 CRITICAL - UI Gap + +**Problem:** +Credits are not showing in Stage 1, 2, 4, and 5 stage cards when processing, but they DO show in Stage 6 card. Need consistency across all stages. + +**Root Cause:** +The `StageCard.tsx` component doesn't have a mechanism to display credits during processing. Only Stage 6 (Image Generation) shows credits because the `CurrentProcessingCardV2.tsx` displays `currentRun.total_credits_used`. + +**Files to Investigate:** +1. `frontend/src/components/Automation/StageCard.tsx` - Individual stage cards +2. `frontend/src/components/Automation/CurrentProcessingCardV2.tsx` - In-progress panel + +**Fix Strategy:** +1. Pass credits information to StageCard when stage is active +2. Display credits consumed during that stage's processing +3. Fetch real-time credit updates from backend + +**Implementation:** + +```tsx +// In StageCard.tsx - Add credits display +interface StageCardProps { + // ... existing props + creditsUsed?: number; // Credits used by this stage + creditsPerItem?: number; // Credit cost per item processed +} + +// Display in active state: +{isActive && ( +
+
+ Credits Used: + {creditsUsed || 0} +
+
+)} +``` + +--- + +## ISSUE 5: Automation In-Progress Panel - Credits Badge Not Incrementing ### 🔴 CRITICAL - Real-time UX Issue **Problem:** -When images are being generated one by one in automation, the credits count doesn't update in the in-progress panel. +The credits badge in the automation in-progress panel shows `0` and doesn't increment after each stage completes. It should show cumulative credits used during the entire run. **Root Cause:** -The in-progress panel doesn't have real-time updates for credit balance. It only updates when the page refreshes or when the run status is polled. +Looking at `CurrentProcessingCardV2.tsx`, it displays `currentRun.total_credits_used` but this value isn't being updated in real-time from the backend during processing. -**Current Implementation:** -File: `frontend/src/components/Automation/CurrentProcessingCardV2.tsx` - -The component displays credits from `currentRun` object but doesn't subscribe to credit balance updates. +**Current Code (Line 297):** +```tsx +{currentRun.total_credits_used} +``` **Fix Strategy:** -### Option 1: Poll Credit Balance (Simpler) - -Add credit balance polling to the automation progress polling: - +### Option 1: Poll Credit Updates More Frequently ```tsx -// In CurrentProcessingCardV2.tsx -import { useCreditBalance } from '../../hooks/useCreditBalance'; - -export default function CurrentProcessingCardV2({ ... }) { - const { balance, loading: balanceLoading, refresh: refreshBalance } = useCreditBalance(); +// Add dedicated credit polling +useEffect(() => { + const pollCredits = async () => { + try { + const response = await fetchAPI(`/v1/automation/runs/${runId}/credits/`); + setCreditsUsed(response.total_credits_used); + } catch (err) {} + }; - // Refresh balance when run updates - useEffect(() => { - if (currentRun) { - refreshBalance(); - } - }, [currentRun.credits_used, currentRun.credits_remaining]); - - // Display live balance - return ( -
- {/* ... existing UI ... */} -
- Credits: {balance?.credits || 0} -
-
- ); -} + if (currentRun.status === 'running') { + const interval = setInterval(pollCredits, 2000); // Every 2 seconds + return () => clearInterval(interval); + } +}, [currentRun.status, runId]); ``` -### Option 2: WebSocket Updates (Better - Future) - -Implement WebSocket for real-time credit updates: -- Backend: Send credit update events via WebSocket -- Frontend: Subscribe to credit updates in credit balance context - -**Recommended: Option 1 for now** (simpler, works immediately) +### Option 2: Include Credits in Processing State Response +Backend should return `credits_used_so_far` in the processing state endpoint. **Files to Change:** 1. `frontend/src/components/Automation/CurrentProcessingCardV2.tsx` -2. `frontend/src/hooks/useCreditBalance.ts` (ensure it has refresh method) - ---- - -## ISSUE 5: Console Error - value prop without onChange in WordPress Integration Form - -### 🟡 MEDIUM - React Warning - -**Error:** -``` -You provided a `value` prop to a form field without an `onChange` handler. -This will render a read-only field. If the field should be mutable use `defaultValue`. -Otherwise, set either `onChange` or `readOnly`. -``` - -**Location:** -`frontend/src/components/sites/WordPressIntegrationForm.tsx` - -**Root Cause:** -Input fields are using `value` prop without corresponding `onChange` handlers. - -**Fix:** -Find all `` without `onChange` and either: -1. Add `onChange` handler, or -2. Change to `defaultValue` if read-only, or -3. Add `readOnly` prop - -**Example Fix:** -```tsx -// BEFORE (WRONG) - - -// AFTER (OPTION 1 - if editable) - setApiKey(e.target.value)} /> - -// AFTER (OPTION 2 - if read-only) - - -// AFTER (OPTION 3 - if should use initial value only) - -``` - -**Files to Change:** -1. `frontend/src/components/sites/WordPressIntegrationForm.tsx` +2. `backend/igny8_core/business/automation/services/automation_service.py` (if needed) --- @@ -538,333 +432,599 @@ Find all `` without `onChange` and either: ### 🔴 CRITICAL - Data Integrity Issue **Problem:** -The WorkflowCompletionWidget shows different counts on different pages, even though it's the same widget using the same data source. +The WorkflowCompletionWidget shows different counts on different pages because it filters by active sector. -**Root Cause Analysis:** - -**Current Implementation:** -- Widget uses `useWorkflowStats()` hook -- Hook fetches data with site_id and optional sector_id filters -- **BUG:** Different pages may have different active sector, causing different counts +**Root Cause:** +The `useWorkflowStats()` hook uses `activeSector` from store, which changes per page. **File:** `frontend/src/hooks/useWorkflowStats.ts` +**Current Code (Line 151):** ```typescript -const { activeSite } = useSiteStore(); -const { activeSector } = useSectorStore(); // ❌ PROBLEM: sector changes per page - -// Fetch with sector filter +const { activeSector } = useSectorStore(); const sectorParam = activeSector?.id ? `§or_id=${activeSector.id}` : ''; ``` -**The Issue:** -- Keywords page: Shows sector X → Widget shows stats for sector X -- Writer page: Shows sector Y → Widget shows stats for sector Y -- Different sectors = different counts = confusing UX - -**Fix Strategy:** - -### Option 1: Remove Sector Filter from Widget (Recommended) - -The widget should always show **site-wide stats**, not sector-specific. +**Fix:** +Remove sector filter - widget should always show site-wide stats. ```typescript -// In useWorkflowStats.ts -export function useWorkflowStats(timeFilter: TimeFilter = 'all') { - const { activeSite } = useSiteStore(); - // ✅ REMOVE: Don't use sector filter for widget - // const { activeSector } = useSectorStore(); - - const loadStats = useCallback(async () => { - if (!activeSite?.id) return; - - // Build params WITHOUT sector - const siteParam = `&site_id=${activeSite.id}`; - // ✅ REMOVED: const sectorParam = activeSector?.id ? `§or_id=${activeSector.id}` : ''; - const baseParams = siteParam; // No sector filter - - // ... rest of logic ... - }, [activeSite?.id]); // ✅ Remove activeSector from dependencies -} +// Remove sector dependency +const loadStats = useCallback(async () => { + const siteParam = `&site_id=${activeSite.id}`; + // NO sector filter for consistent widget display + const baseParams = siteParam; + // ... +}, [activeSite?.id]); // Remove activeSector from dependencies ``` -**Rationale:** -- Widget is in the footer = global context -- Should show site-wide completion, not sector-specific -- Keeps counts consistent across all pages - -### Option 2: Add Toggle for Site-wide vs Sector Stats - -Add a toggle in the widget to switch between site-wide and sector-specific stats. More complex, may not be needed. - -**Recommended: Option 1** - -**Files to Change:** -1. `frontend/src/hooks/useWorkflowStats.ts` - -**Testing:** -- [ ] Navigate between different pages -- [ ] Verify widget shows same counts on all pages -- [ ] Verify counts match actual site-wide totals - --- -## ISSUE 7: Published Items Calendar Disappeared +## ISSUE 7: Content Calendar and List Not Showing ### 🔴 CRITICAL - Feature Broken **Problem:** -The published items calendar view that was showing earlier has disappeared. Both calendar and list views are not working. +Content calendar and content list at `/publisher/content-calendar` not showing. Calendar missing completely and list also not showing any past published content. -**Investigation Needed:** +**Investigation:** **File:** `frontend/src/pages/Publisher/ContentCalendar.tsx` -**Current Status:** -- Component exists and is implemented -- Has calendar and list view modes -- Default view mode is 'calendar' -- Uses `viewMode` state to switch between views +**Current Implementation Analysis:** +- Component fetches ALL content for the site (line 134-145) +- `publishedItems` filters for items with `external_id` (line 110-112) +- Calendar uses `getPublishedItemsForDate()` and `getScheduledItemsForDate()` **Possible Issues:** -1. Route not working -2. Component not rendering due to data fetch error -3. CSS/visibility issue -4. Auth/permission issue +1. `external_id` might not be set on published content +2. `updated_at` used as publish date might not be correct +3. Data fetch might be failing silently **Debug Steps:** -```typescript -// In ContentCalendar.tsx, add logging -useEffect(() => { - console.log('[DEBUG] ContentCalendar mounted'); - console.log('[DEBUG] activeSite:', activeSite); - console.log('[DEBUG] viewMode:', viewMode); - console.log('[DEBUG] allContent:', allContent); -}, []); +```tsx +console.log('[ContentCalendar] publishedItems:', publishedItems); +console.log('[ContentCalendar] Sample with external_id:', + allContent.filter(c => c.external_id)); ``` -**Fix will depend on findings:** -- If data fetch error → Fix API call -- If route issue → Check App.tsx routes -- If rendering issue → Fix component logic -- If auth issue → Fix permissions - -**Files to Investigate:** -1. `frontend/src/pages/Publisher/ContentCalendar.tsx` -2. `frontend/src/App.tsx` (check route) -3. Browser console (check errors) - ---- - -## ISSUE 8: Auto-Approve and Scheduling System - -### 🟡 MEDIUM - Feature Incomplete - -**Problem:** -Auto-approve and scheduling feature needs to be properly planned and implemented, or fixed if already configured. - -**Current State (Need to Verify):** -- Auto-approve setting exists in site configuration? -- Scheduling feature exists for content? -- Integration with automation? - -**Investigation Needed:** - -1. **Check if feature exists:** - ```bash - grep -r "auto.approve" backend/ - grep -r "auto_approve" backend/ - ``` - -2. **Check scheduling:** - ```bash - grep -r "scheduled_publish" backend/ - ``` - -3. **Check automation integration:** - - Does automation respect auto-approve setting? - - Does it schedule content automatically? - -**Potential Implementation (if missing):** - -### Auto-Approve Feature - -**Backend:** -- Add `auto_approve_content` field to Site model or AutomationConfig -- When content is generated, check this setting -- If true, set status to 'approved' instead of 'review' - -**Frontend:** -- Add toggle in site settings -- Show in automation configuration -- Display in content workflow - -### Scheduling Feature - -**Backend:** -- Add `auto_schedule` field to Site model or AutomationConfig -- Add `schedule_interval` (daily, every 2 days, weekly, etc.) -- When content is approved (or auto-approved), calculate next schedule date -- Set `scheduled_publish_at` field - -**Frontend:** -- Add scheduling configuration in site settings -- Show schedule preview -- Display scheduled items in calendar - -**Files to Investigate:** -1. `backend/igny8_core/business/automation/models.py` (AutomationConfig) -2. `backend/igny8_core/modules/integration/models.py` (Site model) -3. `frontend/src/pages/Sites/Settings.tsx` - ---- - -## ISSUE 9: 404 Page Redesign - -### 🟢 LOW - Visual Enhancement - -**Problem:** -404 page needs to be branded as igny8 own. - -**Current State:** -- Default React 404 page or basic error page -- Not branded with igny8 design system - **Fix Strategy:** - -Create a custom 404 page component: - -```tsx -// frontend/src/pages/NotFound.tsx -import React from 'react'; -import { Link } from 'react-router-dom'; -import Button from '../components/ui/button/Button'; -import { HomeIcon, ArrowLeftIcon } from '../icons'; - -export default function NotFound() { - return ( -
-
- {/* Logo */} -
- igny8 -
- - {/* 404 */} -

- 404 -

- - {/* Message */} -

- Page Not Found -

-

- The page you're looking for doesn't exist or has been moved. -

- - {/* Actions */} -
- - - - -
- - {/* Help text */} -

- Need help? Contact Support -

-
-
- ); -} -``` - -**Integration:** -```tsx -// In App.tsx -} /> -``` - -**Files to Create/Change:** -1. `frontend/src/pages/NotFound.tsx` (new file) -2. `frontend/src/App.tsx` (add route) +1. Verify that published content has `external_id` set +2. Check if backend is returning published content correctly +3. May need to use `site_status === 'published'` instead of checking `external_id` --- -## IMPLEMENTATION PRIORITY & ORDER +## ISSUE 8: Auto-Approve and Auto-Publish on Site Settings -### Phase 1: Critical Backend Fixes (MUST FIX FIRST) -**Estimated Time: 2-3 hours** +### 🔴 CRITICAL - Feature Not Functional -1. ✅ **Issue 1: AIModelConfig AttributeError** (30 min) - - Fix field name references - - Test all AI functions +**Problem:** +Auto-approve and auto-publish toggles on Site Settings → Publishing tab need to be made functional. -2. ✅ **Issue 2: Image Generation Credit Tracking** (2 hours) - - Integrate credit service - - Add AITaskLog creation - - Add notification creation - - Add usage log with cost - - Test thoroughly +**Current State (from code analysis):** -### Phase 2: Critical Frontend Fixes -**Estimated Time: 2-3 hours** +**Backend Models Exist:** +- `PublishingSettings.auto_approval_enabled` - in `business/integration/models.py:265` +- `PublishingSettings.auto_publish_enabled` - in `business/integration/models.py:271` -3. ✅ **Issue 6: WorkflowCompletionWidget Data Consistency** (30 min) - - Remove sector filter from widget - - Test across all pages +**Backend Service Integration Exists:** +- `automation_service.py:1491` - Checks `auto_approval_enabled` +- `automation_service.py:1632` - Checks `auto_publish_enabled` and triggers publish -4. ✅ **Issue 4: Credits Not Updating in Automation** (1 hour) - - Add credit balance polling - - Test real-time updates +**Frontend Implementation Exists:** +- Site Settings Publishing tab has toggles +- Saves via `savePublishingSettings()` on toggle change -5. ✅ **Issue 7: Published Items Calendar** (1 hour) - - Debug and identify issue - - Implement fix - - Test both views +**Issues to Fix:** +1. ✅ Backend models exist +2. ✅ Backend service checks the flags +3. ❓ Need to verify data flow is working +4. ❓ Need to verify settings are being loaded correctly -### Phase 3: UX Improvements -**Estimated Time: 1-2 hours** +**Testing Required:** +1. Toggle auto-approval ON → Run automation → Content should go to 'approved' not 'review' +2. Toggle auto-publish ON → Content approved → Should trigger publish to WordPress -6. ✅ **Issue 3: Automation Button Colors** (15 min) - - Update button variants - - Test visual appearance +--- -7. ✅ **Issue 5: Console Error - WordPress Form** (30 min) - - Fix input onChange handlers - - Test form +## ISSUE 9: Publishing Settings Save Button -8. ✅ **Issue 9: 404 Page Redesign** (30 min) - - Create branded 404 page - - Test routing +### 🟡 MEDIUM - UX Improvement -### Phase 4: Feature Implementation (If Time Permits) +**Problem:** +Limits and Schedule settings in Publishing tab save immediately on change. They should require a Save button click instead. Only the automation toggles should save on toggle. + +**Current Implementation:** +File: `frontend/src/pages/Sites/Settings.tsx` (lines 1025-1100) + +```tsx +// Limits Card - saves on every change (WRONG) + { + const value = ...; + setPublishingSettings({ ...publishingSettings, daily_publish_limit: value }); + // Missing: Should NOT auto-save here + }} +/> + +// Automation Card - saves on toggle (CORRECT for toggles) + { + setPublishingSettings(newSettings); + savePublishingSettings({ auto_approval_enabled: checked }); // ✅ OK for toggles + }} +/> +``` + +**Fix Strategy:** +1. Remove immediate save from Limits and Schedule cards +2. Add a "Save Settings" button at bottom of Publishing tab +3. Keep toggle-based save for Automation card only + +**New Code:** +```tsx +// Limits Card - no auto-save +onChange={(e) => { + setPublishingSettings({ ...publishingSettings, daily_publish_limit: value }); + // Don't call savePublishingSettings here +}} + +// Add Save button at bottom +
+ +
+``` + +--- + +## ISSUE 10: Planner and Writer Pagination + +### 🟡 MEDIUM - Navigation Issue + +**Problem:** +Pagination not working properly on all Planner and Writer pages. + +**Pages Affected:** +- `/planner/keywords` +- `/planner/clusters` +- `/planner/ideas` +- `/writer/tasks` +- `/writer/drafts` +- `/writer/images` + +**Current Implementation:** +All pages use similar pagination pattern via `TablePageTemplate`: +- `currentPage` state +- `pageSize` state +- `setCurrentPage` passed to Pagination component + +**Possible Issues:** +1. Page doesn't reset when filters change +2. Total count not being calculated correctly +3. Backend not respecting page parameter + +**Debug Steps:** +1. Check network tab - verify `page` param sent correctly +2. Check response - verify `count` and `results` correct +3. Check `setCurrentPage` - verify it triggers data reload + +**Files to Check:** +1. `frontend/src/pages/Planner/Keywords.tsx` +2. `frontend/src/pages/Planner/Clusters.tsx` +3. `frontend/src/pages/Writer/Tasks.tsx` +4. `frontend/src/templates/TablePageTemplate.tsx` + +--- + +## ISSUE 11: Footer Widgets Data Audit + +### 🟡 MEDIUM - Data Accuracy + +**Problem:** +Need to audit footer widgets on all Planner and Writer pages to ensure counts are accurate. + +**Widgets to Audit:** +1. **Credits Widget** - Shows credit balance +2. **Quick Stats Widget** - Shows items pending/processed +3. **Workflow Completion Widget** - Shows pipeline progress + +**Audit Table Required:** + +| Page | Widget | Model/API | Field | Filter/Criteria | Status | +|------|--------|-----------|-------|-----------------|--------| +| Keywords | Quick Stats | Keyword | count | site_id, status | TBD | +| Clusters | Quick Stats | Cluster | count | site_id | TBD | +| Ideas | Quick Stats | ContentIdea | count | site_id | TBD | +| Tasks | Quick Stats | Task | count | site_id | TBD | +| ... | ... | ... | ... | ... | ... | + +**Investigation Required:** +1. List all widgets shown on each page +2. Document API endpoint each widget calls +3. Document filter criteria used +4. Verify counts match backend reality + +--- + +## ISSUE 12: Usage Logs Cost Calculation Formula + +### 🟡 MEDIUM - Documentation/Clarity + +**Problem:** +Need to document the formula/criteria used for cost calculation in Usage Logs page. + +**Page:** `/account/usage/logs` + +**Current Implementation:** +File: `frontend/src/pages/account/UsageLogsPage.tsx` + +The page displays `cost_usd` from the `CreditUsageLog` model. + +**Backend Cost Calculation:** +File: `backend/igny8_core/business/billing/services/credit_service.py` + +```python +# For text operations (clustering, content, ideas): +credits = tokens_used / tokens_per_credit +cost_usd = credits * credit_price_usd # From BillingConfiguration + +# For image operations: +credits = num_images * credits_per_image # From AIModelConfig +cost_usd = credits * credit_price_usd +``` + +**Top Metrics Calculation:** +The summary stats on the usage page are calculated client-side from loaded logs: +```typescript +const totalCredits = logs.reduce((sum, log) => sum + log.credits_used, 0); +const totalCost = logs.reduce((sum, log) => sum + parseFloat(log.cost_usd || '0'), 0); +``` + +**Documentation to Add:** +- Add tooltip/help text explaining cost calculation +- Show formula in UI: "Cost = Credits Used × Credit Price ($0.XX per credit)" + +--- + +## ISSUE 13: Sites Page - Add Site Button Not Working + +### 🔴 CRITICAL - Core Feature Broken + +**Problem:** +Neither the top "Add New Website" button nor the empty state button works on the Sites page. + +**Investigation Results:** + +**File:** `frontend/src/pages/Sites/List.tsx` + +**Current Implementation:** +```tsx +// Line 71: State +const [showWelcomeGuide, setShowWelcomeGuide] = useState(false); + +// Line 481: Button + + +// Line 527-534: Conditional render +{showWelcomeGuide && ( +
+ { + loadSites(); + setShowWelcomeGuide(false); + }} /> +
+)} +``` + +**Root Cause Analysis:** +The button toggles `showWelcomeGuide` which should show the `WorkflowGuide` component. If it's not working: +1. State toggle might not be working +2. `WorkflowGuide` component might not be rendering +3. Component might have internal errors + +**Debug Steps:** +1. Add console.log to onClick handler +2. Check if WorkflowGuide component exists +3. Check for any JS errors in console + +**Fix Strategy:** +If WorkflowGuide isn't appropriate for Sites page: +- Create dedicated AddSiteModal or AddSiteForm +- Use similar flow to homepage setup wizard + +--- + +## ISSUE 14: AI Model Names - Branding Update + +### 🟡 MEDIUM - Branding Consistency + +**Problem:** +AI model names like "GPT-4", "DALL-E", "Claude" should be replaced with "IGNY8 AI" in user-facing areas (Help page, docs, etc.). + +**Areas to Update:** + +**Help Page (`frontend/src/pages/Help/Help.tsx`):** +- Line 263: "Images are generated using AI (DALL-E 3 for premium, Runware for basic)" +- Should be: "Images are generated using IGNY8 AI (Premium quality or Basic quality)" + +**Other Locations to Check:** +- `/frontend/src/pages/Settings/Publishing.tsx` +- `/frontend/src/pages/Billing/Credits.tsx` +- Any tooltip or help text mentioning specific AI models + +**Guideline:** +- Backend/Admin: Keep technical model names (for configuration) +- Frontend/User-facing: Use "IGNY8 AI" or quality tier names (Basic, Quality, Premium) + +**Search Pattern:** +```bash +grep -r "GPT-4\|DALL-E\|Claude\|OpenAI\|Anthropic" frontend/src/pages/ +``` + +--- + +## ISSUE 15: WordPress to Site Terminology + +### 🟡 MEDIUM - Terminology Consistency + +**Problem:** +System says "WordPress" in many places where "site" should be used, especially since Shopify and Custom Site integrations are coming. + +**Context:** +- Integration section: Keep "WordPress" where it refers to WordPress-specific features +- Global/help text: Use "site" or "your website" instead of "WordPress" + +**Examples to Fix:** + +**Keep "WordPress":** +- "Connect WordPress" button (integration-specific) +- "WordPress Integration" settings tab +- "IGNY8 WP Bridge Plugin" references + +**Change to "site":** +- "Publish to WordPress" → "Publish to your site" +- "WordPress sync" → "Site sync" (in general contexts) +- Help text mentioning WordPress as the only option + +**Search Pattern:** +```bash +grep -ri "wordpress" frontend/src/pages/ --include="*.tsx" | grep -v "WordPressIntegration" +``` + +**Files to Review:** +1. `frontend/src/pages/Help/Help.tsx` +2. `frontend/src/pages/Settings/Publishing.tsx` +3. `frontend/src/pages/legal/Terms.tsx` +4. `frontend/src/pages/Billing/Credits.tsx` + +--- + +## ISSUE 16: Content View - Image Regeneration + +### 🟢 NEW FEATURE - Enhancement + +**Problem:** +Need ability to regenerate images from the content view with: +- Custom prompt input +- Option to regenerate from original prompt +- Option to generate at higher quality tier + +**Current State:** +- Backend: API endpoint documented but NOT implemented +- Frontend: No regenerate buttons exist + +**Implementation Plan:** + +### Backend: +Add `regenerate` action to `ImageViewSet`: +```python +# In modules/writer/views.py - ImageViewSet +@action(detail=True, methods=['post']) +def regenerate(self, request, pk=None): + image = self.get_object() + custom_prompt = request.data.get('custom_prompt', '') + quality_tier = request.data.get('quality_tier', image.quality_tier) + + # Append custom prompt to original if provided + prompt = image.prompt + if custom_prompt: + prompt = f"{prompt}. {custom_prompt}" + + # Check credits for quality tier + # Generate new image + # Update image record + # Return result +``` + +### Frontend: +Add regenerate button to content view: +```tsx +// In ContentViewTemplate or similar + + +// Modal with options: +// - Custom prompt textarea +// - Quality tier selector (Basic/Quality/Premium) +// - "Use original prompt" checkbox +``` + +**Credit Calculation:** +- Show credit cost before regeneration +- Different costs for different quality tiers + +--- + +## ISSUE 17: Auto-Publish After Stage 7 Approval + +### 🟢 NEW FEATURE - Enhancement + +**Problem:** +After Stage 7 (Review) completes and content is approved, need to automatically schedule content for publishing based on auto-publish settings. + +**Current Flow:** +Stage 7 → Content status = 'approved' → STOPS + +**Desired Flow:** +Stage 7 → Content status = 'approved' → IF auto_publish_enabled → Schedule for next available slot → Publish + +**Implementation:** + +### Backend (automation_service.py): +After stage 7 completion, add: +```python +# After approving content +if publishing_settings.auto_publish_enabled: + # Get next available publish slot based on schedule + next_slot = get_next_publish_slot(site) + + # Schedule content + for content in approved_content: + content.site_status = 'scheduled' + content.scheduled_publish_at = next_slot + content.save() + next_slot = get_next_slot_after(next_slot, publishing_settings) +``` + +### Publishing Scheduler: +The existing `publishing_scheduler.py` task should pick up scheduled content and publish at the scheduled time. + +**Files to Modify:** +1. `backend/igny8_core/business/automation/services/automation_service.py` +2. `backend/igny8_core/tasks/publishing_scheduler.py` (if needed) + +--- +## UPDATED IMPLEMENTATION PRIORITY & ORDER + +### ✅ Phase 1: Backend Critical (COMPLETED in v1.7.1) +1. ✅ Issue 1: AIModelConfig AttributeError +2. ✅ Issue 2: Image Generation Credit Tracking +3. ✅ Issue 3: Button Colors (already fixed) + +### 🔄 Phase 2: Automation & Credits (IN PROGRESS) **Estimated Time: 3-4 hours** -9. ✅ **Issue 8: Auto-Approve & Scheduling** (3-4 hours) - - Investigate current state - - Plan implementation - - Implement if missing - - Test workflow +4. 🔴 **Issue 4: Stage Cards Credits Display** (1 hour) + - Add credits display to all stage cards during processing + - Match Stage 6 behavior + +5. 🔴 **Issue 5: Credits Badge Not Incrementing** (1 hour) + - Poll credits more frequently during automation + - Update display in real-time + +6. 🔴 **Issue 8: Auto-Approve/Auto-Publish** (2 hours) + - Verify backend logic is working + - Test frontend toggles save correctly + - Run end-to-end test + +### 🔄 Phase 3: Calendar & Content (IN PROGRESS) +**Estimated Time: 2-3 hours** + +7. 🔴 **Issue 7: Content Calendar Not Showing** (1.5 hours) + - Debug data loading + - Fix published content display + - Test both calendar and list views + +8. 🟡 **Issue 9: Publishing Settings Save Button** (30 min) + - Separate auto-save for toggles + - Add Save button for limits/schedule + +### Phase 4: Widget & Data Consistency +**Estimated Time: 2 hours** + +9. 🔴 **Issue 6: WorkflowWidget Consistency** (30 min) + - Remove sector filter + - Test across all pages + +10. 🟡 **Issue 10: Pagination Issues** (1 hour) + - Debug planner/writer pagination + - Fix page reset on filter change + +11. 🟡 **Issue 11: Footer Widgets Audit** (30 min) + - Document all widgets + - Verify data accuracy + +### Phase 5: Sites & Settings +**Estimated Time: 1-2 hours** + +12. 🔴 **Issue 13: Add Site Button** (1 hour) + - Debug WorkflowGuide toggle + - Fix or replace component + +13. 🟡 **Issue 12: Usage Logs Documentation** (30 min) + - Add help text/tooltips + - Document cost formula + +### Phase 6: Branding & Terminology +**Estimated Time: 1-2 hours** + +14. 🟡 **Issue 14: AI Model Names** (30 min) + - Replace GPT/DALL-E with IGNY8 AI + - Update Help page + +15. 🟡 **Issue 15: WordPress to Site** (1 hour) + - Audit all "WordPress" text + - Replace with "site" where appropriate + +### Phase 7: New Features (If Time Permits) +**Estimated Time: 4-6 hours** + +16. 🟢 **Issue 16: Image Regeneration** (3 hours) + - Backend API implementation + - Frontend modal with options + +17. 🟢 **Issue 17: Auto-Publish After Stage 7** (2 hours) + - Integrate with automation + - Use publishing scheduler + +--- + +## ISSUE SUMMARY TABLE + +| # | Issue | Priority | Status | Est. Time | +|---|-------|----------|--------|-----------| +| 1 | AIModelConfig AttributeError | ✅ | DONE | - | +| 2 | Image Credit Tracking | ✅ | DONE | - | +| 3 | Button Colors | ✅ | DONE | - | +| 4 | Stage Cards Credits | 🔴 | TODO | 1h | +| 5 | Credits Badge Increment | 🔴 | TODO | 1h | +| 6 | Widget Consistency | 🔴 | TODO | 30m | +| 7 | Content Calendar | 🔴 | TODO | 1.5h | +| 8 | Auto-Approve/Publish | 🔴 | TODO | 2h | +| 9 | Publishing Save Button | 🟡 | TODO | 30m | +| 10 | Pagination Issues | 🟡 | TODO | 1h | +| 11 | Footer Widgets Audit | 🟡 | TODO | 30m | +| 12 | Usage Logs Docs | 🟡 | TODO | 30m | +| 13 | Add Site Button | 🔴 | TODO | 1h | +| 14 | AI Model Names | 🟡 | TODO | 30m | +| 15 | WordPress → Site | 🟡 | TODO | 1h | +| 16 | Image Regeneration | 🟢 | NEW | 3h | +| 17 | Auto-Publish Stage 7 | 🟢 | NEW | 2h | + +**Legend:** +- 🔴 CRITICAL - Must fix +- 🟡 MEDIUM - Should fix +- 🟢 LOW/NEW - Nice to have +- ✅ COMPLETED --- @@ -876,141 +1036,56 @@ export default function NotFound() { - [ ] Check browser console for errors - [ ] Verify no regression in related features -### After All Fixes -- [ ] **AI Functions Test Suite** - - [ ] Clustering: Credits deducted, logged to all 3 locations - - [ ] Idea Generation: Credits deducted, logged to all 3 locations - - [ ] Content Generation: Credits deducted, logged to all 3 locations - - [ ] Image Generation: Credits deducted, logged to all 3 locations ✨ NEW - -- [ ] **Credit System Verification** - - [ ] Check AITaskLog table has entries for all AI functions - - [ ] Check Notifications table has entries for all AI functions - - [ ] Check CreditUsageLog has entries for all AI functions with costs - - [ ] Verify cost calculations match formula: credits × credit_price_usd - -- [ ] **Frontend Verification** - - [ ] Navigate all pages, verify widget shows same counts - - [ ] Run automation, verify credits update in real-time - - [ ] Test pause/cancel buttons, verify clear visual feedback - - [ ] Check no console errors on any page - - [ ] Test 404 page routing +### Phase 2 Verification +- [ ] Run automation and verify credits show on all stage cards +- [ ] Verify credits badge increments after each stage +- [ ] Toggle auto-approve ON → Content goes to 'approved' +- [ ] Toggle auto-publish ON → Approved content gets scheduled -- [ ] **Integration Test** - - [ ] Run full automation cycle - - [ ] Verify all stages work - - [ ] Verify all credits deducted correctly - - [ ] Verify all logs created properly +### Phase 3 Verification +- [ ] Content calendar shows scheduled items +- [ ] Content calendar shows published items +- [ ] Calendar view renders correctly +- [ ] List view shows all content +- [ ] Save button works for limits/schedule ---- +### Phase 4-5 Verification +- [ ] Widget shows same counts on all pages +- [ ] Pagination works on all tables +- [ ] Add Site button opens wizard +- [ ] New site can be created -## DATABASE VERIFICATION QUERIES - -After implementing fixes, run these SQL queries to verify: - -```sql --- 1. Verify AIModelConfig field names -SELECT model_name, cost_per_1k_input, cost_per_1k_output, credits_per_image -FROM igny8_billing_aimodelconfig -WHERE is_active = true; - --- 2. Verify image generation logs in AITaskLog -SELECT function_name, COUNT(*) as count, SUM(cost) as total_cost -FROM igny8_ai_task_logs -WHERE function_name = 'generate_images' -GROUP BY function_name; - --- 3. Verify credit usage logs have image_generation -SELECT operation_type, COUNT(*) as count, SUM(credits_used) as total_credits, SUM(cost_usd) as total_cost -FROM igny8_billing_creditusagelog -WHERE operation_type = 'image_generation' -GROUP BY operation_type; - --- 4. Verify notifications have image generation -SELECT notification_type, COUNT(*) as count -FROM igny8_notifications_notification -WHERE notification_type IN ('ai_image_success', 'ai_image_failed') -GROUP BY notification_type; - --- 5. Compare credit deductions for all operations -SELECT operation_type, COUNT(*) as transactions, SUM(amount) as total_credits -FROM igny8_billing_credittransaction -WHERE transaction_type = 'deduction' -GROUP BY operation_type -ORDER BY total_credits DESC; -``` +### Phase 6 Verification +- [ ] No GPT/DALL-E references in user-facing text +- [ ] "Site" used instead of "WordPress" in generic contexts --- ## SUCCESS CRITERIA -✅ **Fix is successful when:** +✅ **All fixes successful when:** -1. **No attribute errors** in AI functions -2. **All AI functions** log to AITaskLog, Notifications, and CreditUsageLog -3. **Image generation** properly deducts credits based on model config -4. **Cost calculations** appear in usage logs for all operations -5. **Widget shows consistent data** across all pages -6. **Credits update in real-time** during automation -7. **Button colors** provide clear visual feedback -8. **No console errors** on any page -9. **404 page** is branded and functional -10. **Auto-approve/scheduling** works as configured (TBD after investigation) +1. ✅ No attribute errors in AI functions +2. ✅ All AI functions log to all 3 locations +3. ✅ Image generation deducts credits correctly +4. **Credits display on all stage cards during processing** +5. **Credits badge increments in real-time** +6. **Widget shows consistent data across all pages** +7. **Content calendar displays scheduled and published content** +8. **Auto-approve and auto-publish work correctly** +9. **Add Site button works on Sites page** +10. **Consistent IGNY8 AI branding throughout** +11. **Generic "site" terminology where appropriate** --- -## ROLLBACK PLAN +## END OF COMPREHENSIVE FIX PLAN v2 -If issues occur during implementation: +**Last Updated:** January 10, 2026 +**Total Issues:** 17 (3 completed, 14 pending) +**Critical Issues:** 7 pending +**Estimated Total Time:** 15-20 hours -1. **Database Changes:** None expected (only code changes) -2. **Code Rollback:** `git revert ` for each fix -3. **Individual Fix Rollback:** Each fix is independent, can be reverted separately -4. **Testing Database:** Use development environment first, verify thoroughly before production +This plan is based on actual codebase analysis and reflects the true state of the system. ---- - -## MONITORING POST-DEPLOYMENT - -After deployment, monitor: - -1. **Error Logs:** Check for AttributeError or other exceptions -2. **Credit Balance:** Monitor for incorrect deductions -3. **AITaskLog Table:** Verify entries being created -4. **Notification Table:** Verify notifications being created -5. **User Reports:** Check for any user-reported issues -6. **Performance:** Monitor API response times (should not degrade) - ---- - -## NOTES FOR IMPLEMENTATION - -**CRITICAL REMINDERS:** - -1. **Test EVERY change** before moving to next fix -2. **Don't break existing functionality** - regression test after each fix -3. **Follow the PRIORITY ORDER** - backend fixes first, then frontend -4. **Verify with database queries** - don't just trust logs -5. **Use git branches** - one branch per major fix for easy rollback -6. **Document any deviations** from this plan with reasons - -**CODE QUALITY:** -- Follow existing code style -- Add comments for complex logic -- Include error handling -- Add logging for debugging -- Write clean, maintainable code - -**Communication:** -- Update this document if you find additional issues -- Document any assumptions made -- Note any blockers encountered -- Report completion status for each phase - ---- - -## END OF COMPREHENSIVE FIX PLAN - -This plan provides **100% accuracy** in identifying issues, root causes, and fixes. All analysis is based on actual code inspection and understanding of the system architecture. - -**Ready for implementation.** 🚀 +**Ready for implementation.** 🚀 \ No newline at end of file diff --git a/docs/90-REFERENCE/IMAGE-GENERATION-GAPS.md b/docs/plans/IMAGE-GENERATION-GAPS.md similarity index 100% rename from docs/90-REFERENCE/IMAGE-GENERATION-GAPS.md rename to docs/plans/IMAGE-GENERATION-GAPS.md diff --git a/docs/plans/FINAL-PRELAUNCH-Completed.md b/docs/plans/implemented/FINAL-PRELAUNCH-Completed.md similarity index 100% rename from docs/plans/FINAL-PRELAUNCH-Completed.md rename to docs/plans/implemented/FINAL-PRELAUNCH-Completed.md diff --git a/docs/plans/phase3-content-template-redesign.md b/docs/plans/phase3-content-template-redesign.md index 1608dc0d..920dc0d1 100644 --- a/docs/plans/phase3-content-template-redesign.md +++ b/docs/plans/phase3-content-template-redesign.md @@ -792,15 +792,14 @@ $igny8_plugin_settings = [ - ✅ Implement keyword badge matching logic ### Phase 2: Advanced Features (Week 2) -- ⏳ Table of contents component -- ⏳ Widget placeholder system -- ⏳ Table detection and image positioning -- ⏳ Image reuse logic (sections 5+) +- ✅ Table of contents component +- ✅ Table detection and image positioning +- ✅ Image reuse logic (sections 5+) ### Phase 3: App Sync (Week 3) -- ⏳ Update ContentViewTemplate.tsx to match WordPress -- ⏳ Add TOC component to React app -- ⏳ Sync image layouts and sizing +- ✅ Update ContentViewTemplate.tsx to match WordPress +- ✅ Add TOC component to React app +- ✅ Sync image layouts and sizing ### Phase 4: Settings & Configuration (Week 4) - ⏳ Plugin settings page