import React, { useCallback, useEffect, useState, useRef } from 'react'; import { Loader2Icon } from 'lucide-react'; import { Link } from 'react-router-dom'; import { recomaze_ai_personalization_env } from '../env'; import { Button } from '../components/ui/button'; import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell, } from '../components/ui/table'; import { ErrorCallout } from '../components/ui/callout'; const JOB_STORAGE_KEY = 'recomaze_bulk_update_job_id'; const formatEstimatedTime = (count: number) => { const requests = Math.ceil(count / 250); const seconds = requests * 2; if (seconds < 60) { return `~${seconds} seconds`; } const minutes = Math.ceil(seconds / 60); return `~${minutes} minute${minutes > 1 ? 's' : ''}`; }; type ParsedProduct = { product_id: string; improved_title: string | null; improved_description: string | null; improved_tags: string | null; }; type Result = { product_id: string; status: 'ok' | 'error' | 'skipped'; message: string; }; const parseCSV = (text: string): ParsedProduct[] => { const rows: string[][] = []; let currentRow: string[] = []; let currentField = ''; let inQuotes = false; for (let i = 0; i < text.length; i++) { const char = text[i]; const nextChar = text[i + 1]; if (char === '"') { if (inQuotes && nextChar === '"') { currentField += '"'; i++; } else { inQuotes = !inQuotes; } } else if (char === ',' && !inQuotes) { currentRow.push(currentField.trim()); currentField = ''; } else if ( (char === '\n' || (char === '\r' && nextChar === '\n')) && !inQuotes ) { if (char === '\r') i++; currentRow.push(currentField.trim()); if (currentRow.some(field => field)) { rows.push(currentRow); } currentRow = []; currentField = ''; } else { currentField += char; } } if (currentField || currentRow.length > 0) { currentRow.push(currentField.trim()); if (currentRow.some(field => field)) { rows.push(currentRow); } } if (rows.length < 2) { return []; } const header = rows[0].map(h => h.toLowerCase().replace(/[^a-z0-9_]/g, '_')); const find = (needles: string[]): number => header.findIndex(h => needles.some(n => h.includes(n))); const pidIdx = find(['product_id', 'product_id']); const skuIdx = find(['sku']); const impTitleIdx = find(['improved_title']); const nameIdx = find(['name']); const origNameIdx = find(['original_name', 'original_title']); const impDescIdx = find(['improved_description', 'improved_desc']); const descIdx = find(['description']); const origDescIdx = find(['original_description', 'original_desc']); const impTagsIdx = find(['improved_tags']); const tagsIdx = find(['tags', 'tag']); const hasAnyKnownHeader = pidIdx >= 0 || skuIdx >= 0 || impTitleIdx >= 0 || nameIdx >= 0; const products: ParsedProduct[] = []; for (let i = 1; i < rows.length; i++) { const values = rows[i]; if (!hasAnyKnownHeader) { if (values.length < 5) continue; const productId = values[0]?.split('|')[0]?.trim(); if (!productId || !/^\d+$/.test(productId)) continue; products.push({ product_id: productId, improved_title: values[2]?.trim() || null, improved_description: values[4]?.trim() || null, improved_tags: null, }); } else { const productId = pidIdx >= 0 ? values[pidIdx]?.trim() || '' : skuIdx >= 0 ? values[skuIdx]?.trim() || '' : ''; if (!productId) continue; let title: string | null = null; if (impTitleIdx >= 0) { title = values[impTitleIdx]?.trim() || null; } else if (nameIdx >= 0) { const newName = values[nameIdx]?.trim() || ''; const origName = origNameIdx >= 0 ? values[origNameIdx]?.trim() || '' : ''; title = newName && newName !== origName ? newName : newName || null; } let desc: string | null = null; if (impDescIdx >= 0) { desc = values[impDescIdx]?.trim() || null; } else if (descIdx >= 0) { const newDesc = values[descIdx]?.trim() || ''; const origDesc = origDescIdx >= 0 ? values[origDescIdx]?.trim() || '' : ''; desc = newDesc && newDesc !== origDesc ? newDesc : newDesc || null; } let tags: string | null = null; if (impTagsIdx >= 0) { tags = values[impTagsIdx]?.trim() || null; } else if (tagsIdx >= 0) { tags = values[tagsIdx]?.trim() || null; } products.push({ product_id: productId, improved_title: title, improved_description: desc, improved_tags: tags, }); } } return products; }; const ProductImprovementsPage = (): JSX.Element => { const [products, setProducts] = useState([]); const [updateTitle, setUpdateTitle] = useState(true); const [updateDescription, setUpdateDescription] = useState(true); const [updateSummaryField, setUpdateSummaryField] = useState(false); const [updateTags, setUpdateTags] = useState(false); const [fileName, setFileName] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [results, setResults] = useState([]); const [summary, setSummary] = useState<{ total: number; success: number; failed: number; skipped: number; } | null>(null); const [currentStats, setCurrentStats] = useState<{ loaded: number; titleUpdates: number; descriptionUpdates: number; tagUpdates: number; }>({ loaded: 0, titleUpdates: 0, descriptionUpdates: 0, tagUpdates: 0 }); const [backupLoading, setBackupLoading] = useState(false); const [backupError, setBackupError] = useState(null); const [showBackupModal, setShowBackupModal] = useState(false); const [progress, setProgress] = useState<{ processed: number; total: number; success: number; failed: number; skipped: number; current: string | null; state: 'idle' | 'pending' | 'running' | 'done' | 'failed'; error?: string | null; }>({ processed: 0, total: 0, success: 0, failed: 0, skipped: 0, current: null, state: 'idle', error: null, }); const [activeJobId, setActiveJobId] = useState(() => { try { return sessionStorage.getItem(JOB_STORAGE_KEY) || null; } catch { return null; } }); const pollTimerRef = useRef(null); const fileInputRef = useRef(null); const apiBase = recomaze_ai_personalization_env?.wp_api_url; const nonce = recomaze_ai_personalization_env?.nonce; const clearStoredJob = useCallback(() => { setActiveJobId(null); try { sessionStorage.removeItem(JOB_STORAGE_KEY); } catch { console.log('error'); } }, []); const saveJobToStorage = useCallback((id: string) => { setActiveJobId(id); try { sessionStorage.setItem(JOB_STORAGE_KEY, id); } catch { console.log('error'); } }, []); const stopPolling = useCallback(() => { if (pollTimerRef.current) { clearInterval(pollTimerRef.current); pollTimerRef.current = null; } }, []); const handleFile = useCallback(async (file: File) => { setError(null); let text = await file.text(); try { const jsonParsed = JSON.parse(text); if (typeof jsonParsed === 'string') text = jsonParsed; } catch (e) { console.log('error:', e); } const parsed = parseCSV(text); if (!parsed.length) { setError('No valid products found in CSV.'); setProducts([]); return; } setProducts(parsed); setFileName(file.name); const tagCount = parsed.filter(p => p.improved_tags).length; setCurrentStats({ loaded: parsed.length, titleUpdates: parsed.filter(p => p.improved_title).length, descriptionUpdates: parsed.filter(p => p.improved_description).length, tagUpdates: tagCount, }); if (tagCount > 0) setUpdateTags(true); }, []); const pollStatus = useCallback( async (id: string) => { if (!apiBase || !nonce) return; try { const resp = await fetch( `${apiBase}recomaze/v1/product-improvements/status/${id}`, { headers: { 'X-WP-Nonce': nonce } } ); if (!resp.ok) { throw new Error('Failed to fetch job status.'); } const data = await resp.json(); setProgress(prev => { const statusRaw = data.status || prev.state || 'running'; const nextState = statusRaw === 'done' ? 'done' : statusRaw === 'failed' ? 'failed' : statusRaw === 'pending' ? 'pending' : 'running'; return { processed: typeof data.processed === 'number' ? data.processed : prev.processed, total: typeof data.total === 'number' ? data.total : prev.total || products.length || 0, success: typeof data.success === 'number' ? data.success : prev.success, failed: typeof data.failed === 'number' ? data.failed : prev.failed, skipped: typeof data.skipped === 'number' ? data.skipped : prev.skipped, current: data.current || prev.current, state: nextState, error: data.error || null, }; }); if (Array.isArray(data.results)) { setResults(data.results); } const isDone = data.status === 'done' || data.status === 'failed' || data.status === 'complete'; if (isDone) { setSummary({ total: data.total || products.length || 0, success: data.success || 0, failed: data.failed || 0, skipped: data.skipped || 0, }); setLoading(false); stopPolling(); clearStoredJob(); } } catch (err: any) { console.error(err); setError(err?.message || 'Failed to fetch job status.'); setLoading(false); stopPolling(); clearStoredJob(); } }, [apiBase, nonce, products.length, stopPolling, clearStoredJob] ); const startPolling = useCallback( (id: string) => { stopPolling(); pollStatus(id); pollTimerRef.current = setInterval(() => pollStatus(id), 3000); }, [stopPolling, pollStatus] ); useEffect(() => { if (activeJobId && apiBase && nonce) { setLoading(true); setProgress(prev => ({ ...prev, state: prev.state === 'idle' ? 'running' : prev.state, })); startPolling(activeJobId); } return () => { stopPolling(); }; }, []); const onFileChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) { return; } handleFile(file); }; const onSubmit = async () => { if (!products.length) { setError('Upload a CSV with products first.'); return; } if (!apiBase || !nonce) { setError('Missing WordPress API configuration.'); return; } setLoading(true); setError(null); setResults([]); setSummary(null); setProgress({ processed: 0, total: products.length, success: 0, failed: 0, skipped: 0, current: null, state: 'pending', error: null, }); stopPolling(); clearStoredJob(); try { const resp = await fetch(`${apiBase}recomaze/v1/product-improvements`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce, }, body: JSON.stringify({ products, updateTitle, updateDescription, updateSummaryField, updateTags, }), }); const data = await resp.json(); if (!resp.ok || !data?.job_id) { throw new Error(data?.error || 'Failed to start bulk update.'); } saveJobToStorage(data.job_id); setProgress(prev => ({ ...prev, total: data.total || products.length, current: products[0]?.product_id || null, state: 'pending', })); startPolling(data.job_id); } catch (err: any) { setError(err?.message || 'Failed to apply improvements.'); setLoading(false); setProgress(prev => ({ ...prev, state: 'failed' })); clearStoredJob(); } }; const downloadBackup = async () => { if (!apiBase || !nonce) { setBackupError('Missing WordPress API configuration.'); return; } try { setBackupLoading(true); setBackupError(null); const resp = await fetch( `${apiBase}recomaze/v1/product-improvements/backup`, { headers: { 'X-WP-Nonce': nonce } } ); if (!resp.ok) { const data = await resp.json().catch(() => ({})); throw new Error(data?.error || 'Failed to download backup.'); } const raw = await resp.text(); let csv: string; try { const parsed = JSON.parse(raw); csv = typeof parsed === 'string' ? parsed : raw; } catch { csv = raw; } const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'product_backup.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); setShowBackupModal(false); } catch (err: any) { setBackupError(err?.message || 'Failed to download backup.'); } finally { setBackupLoading(false); } }; return (

Bulk Catalog Update

Update your product titles and descriptions with AI-generated improvements. Upload the CSV provided in your AI Discoverability Report.

Products can only be updated with the CSV received by email from your Recomaze AI report.

Important: Submitting this form will permanently update your live WooCommerce catalog. Please verify the CSV contents first.

Data Backup

Highly recommended before applying bulk changes ( {formatEstimatedTime(1000)} per 1000 products).

1. Upload Improvement CSV

Required columns: product_id, original_title, improved_title, original_description, improved_description

{fileName && (

{fileName}

Loaded {products.length} products

Titles:{' '} {currentStats.titleUpdates} Descriptions:{' '} {currentStats.descriptionUpdates} {currentStats.tagUpdates > 0 && ( Tags:{' '} {currentStats.tagUpdates} )}
)}
{products.length > 0 && (

2. Select Fields to Update

{currentStats.tagUpdates > 0 && ( )}
)}
Back to Agent Analytics
{error && (
)} {progress.state !== 'idle' && (

Update Progress

{progress.state.toUpperCase()}
Processed {progress.processed} of {progress.total}
Success: {progress.success} Skipped: {progress.skipped} Failed: {progress.failed}
0 ? `${Math.round((progress.processed / progress.total) * 100)}%` : '0%', }} />
{progress.current && (

Current ID: {progress.current}

)}
)} {summary && (

Update Complete

Successfully processed {summary.total} products. ({summary.success}{' '} updated, {summary.skipped} skipped, {summary.failed} failed).

)} {results.length > 0 && (
Product ID Status Message {results.map((row, idx) => ( {row.product_id} {row.status.toUpperCase()} {row.message} ))}
)} {showBackupModal && (
!backupLoading && setShowBackupModal(false)} />

Download Backup CSV

This exports your current product titles and descriptions. We highly recommend keeping a backup before running bulk updates. Active products only (Drafts are skipped).

{backupError && (
{backupError}
)}
)}
); }; export default ProductImprovementsPage;