/** * Knowledge Base - manage Q&A pairs and WP content indexing. */ import { useState, useEffect, useCallback } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; import { Button, SelectControl, SearchControl, TextControl, TextareaControl, Spinner } from '@aime/wp-components'; import { edit, trash } from '@wordpress/icons'; import useApi from '../../../../hooks/useApi'; import useSlowWarning from '../../../../hooks/useSlowWarning'; import Card from '../../../common/Card'; import LoadingBtn from '../../../common/LoadingBtn'; import Loader from '../../../common/Loader'; import Notice from '../../../common/Notice'; import ConfirmModal from '../../../common/ConfirmModal'; import { toast } from '../../../common/Toast'; import { PER_PAGE } from '../../../../utils/constants'; const TYPE_OPTIONS = [ { label: 'All Types', value: '' }, { label: 'Q&A Pair', value: 'qa_pair' }, { label: 'WP Content', value: 'wp_content' }, { label: 'WooCommerce Product', value: 'woo_product' }, { label: 'Document', value: 'document' }, { label: 'URL', value: 'url' }, ]; const TYPE_LABELS = { qa_pair: 'Q&A', wp_content: 'WordPress', woo_product: 'WooCommerce', document: 'Document', url: 'URL', }; const TYPE_COLORS = { qa_pair: '#2196f3', wp_content: '#4caf50', woo_product: '#9c27b0', document: '#ff9800', url: '#607d8b', }; const DEFAULT_ENTRY = { bot_id: '', source_type: 'qa_pair', title: '', content: '', }; const KnowledgeBase = ( { onNavigate } ) => { const { get, post, put, del, loading } = useApi(); const slowWarning = useSlowWarning(); const [ items, setItems ] = useState( [] ); const [ total, setTotal ] = useState( 0 ); const [ page, setPage ] = useState( 1 ); const [ search, setSearch ] = useState( '' ); const [ typeFilter, setTypeFilter ] = useState( '' ); const [ bots, setBots ] = useState( [] ); const [ botFilter, setBotFilter ] = useState( '' ); const [ editEntry, setEditEntry ] = useState( null ); const [ confirmDelete, setConfirmDelete ] = useState( null ); const [ indexStatus, setIndexStatus ] = useState( null ); const [ indexing, setIndexing ] = useState( false ); /* Load bots for filter + forms */ useEffect( () => { const loadBots = async () => { try { const res = await get( '/chatbot/bots' ); const arr = Array.isArray( res ) ? res : res.items || []; const list = arr.map( ( b ) => ( { label: b.name, value: String( b.id ) } ) ); setBots( list ); if ( list.length > 0 ) setBotFilter( list[ 0 ].value ); } catch ( e ) { // silent } }; loadBots(); }, [ get ] ); const fetchItems = useCallback( async () => { if ( ! botFilter ) { setItems( [] ); setTotal( 0 ); return; } try { const params = { page, per_page: PER_PAGE }; if ( search ) params.search = search; if ( typeFilter ) params.type = typeFilter; const res = await get( `/chatbot/bots/${ botFilter }/knowledge`, params ); setItems( res.items || res.data || [] ); setTotal( res.total || 0 ); } catch ( e ) { // silent } }, [ get, page, search, typeFilter, botFilter ] ); const fetchIndexStatus = useCallback( async () => { if ( ! botFilter ) return; try { const res = await get( `/chatbot/bots/${ botFilter }/knowledge/status` ); // API returns a flat array of stats, not wrapped in { types: [] }. setIndexStatus( Array.isArray( res ) ? res : res.types || null ); } catch ( e ) { // silent } }, [ get, botFilter ] ); useEffect( () => { fetchItems(); }, [ fetchItems ] ); useEffect( () => { fetchIndexStatus(); }, [ fetchIndexStatus ] ); const handleSave = async () => { if ( ! editEntry.title?.trim() ) { toast( __( 'Title is required.', 'ai-marketing-expert' ), 'error' ); return; } if ( ! editEntry.bot_id ) { toast( __( 'Please select a bot.', 'ai-marketing-expert' ), 'error' ); return; } // Map UI fields to PHP fields: question+answer for qa_pair. const payload = { ...editEntry, type: editEntry.source_type || 'qa_pair', question: editEntry.title, answer: editEntry.content || '', }; try { if ( editEntry.id ) { await put( `/chatbot/knowledge/${ editEntry.id }`, payload ); toast( __( 'Knowledge entry updated.', 'ai-marketing-expert' ) ); } else { await post( `/chatbot/bots/${ editEntry.bot_id }/knowledge`, payload ); toast( __( 'Knowledge entry created.', 'ai-marketing-expert' ) ); } setEditEntry( null ); fetchItems(); fetchIndexStatus(); } catch ( e ) { toast( e.message, 'error' ); } }; const handleDelete = async ( id ) => { try { await del( `/chatbot/knowledge/${ id }` ); toast( __( 'Knowledge entry deleted.', 'ai-marketing-expert' ) ); setConfirmDelete( null ); fetchItems(); fetchIndexStatus(); } catch ( e ) { toast( e.message, 'error' ); } }; const handleTriggerIndex = async ( type ) => { if ( ! botFilter ) { toast( __( 'Please select a bot first.', 'ai-marketing-expert' ), 'error' ); return; } setIndexing( true ); slowWarning.start(); try { const res = await post( `/chatbot/bots/${ botFilter }/knowledge/index`, { type } ); toast( `${ __( 'Indexed', 'ai-marketing-expert' ) } ${ res.result?.indexed || res.indexed || 0 } ${ __( 'items.', 'ai-marketing-expert' ) }` ); fetchItems(); fetchIndexStatus(); } catch ( e ) { toast( e.message, 'error' ); } finally { slowWarning.stop(); setIndexing( false ); } }; const totalPages = Math.ceil( total / PER_PAGE ); const botOptions = [ { label: __( 'Select Bot', 'ai-marketing-expert' ), value: '' }, ...bots, ]; return (

{ __( 'Knowledge Base', 'ai-marketing-expert' ) } ({ total })

{ /* Index actions */ }

{ __( 'Index your WordPress content and WooCommerce products so the chatbot can answer questions about your site.', 'ai-marketing-expert' ) }

{ ! botFilter && ( ) }
{ botFilter && indexStatus && (
{ indexStatus.map( ( s ) => (
{ TYPE_LABELS[ s.type ] || s.type } { s.total } { __( 'entries', 'ai-marketing-expert' ) }
) ) }
) } { botFilter && (
{ indexing ? ( { __( 'Indexing...', 'ai-marketing-expert' ) } ) : ( ) } { indexing ? ( { __( 'Indexing...', 'ai-marketing-expert' ) } ) : ( ) } { indexing ? ( { __( 'Indexing...', 'ai-marketing-expert' ) } ) : ( ) }
) }
{ /* Knowledge entries list */ }
{ setSearch( v ); setPage( 1 ); } } placeholder={ __( 'Search knowledge...', 'ai-marketing-expert' ) } className="aime-search" /> { setTypeFilter( v ); setPage( 1 ); } } __nextHasNoMarginBottom />
{ loading && ! items.length ? ( ) : items.length === 0 ? (

{ __( 'No knowledge entries found. Add Q&A pairs or index your content.', 'ai-marketing-expert' ) }

) : ( <> { items.map( ( entry ) => { // Derive display title: Q&A uses question, wp_content uses metadata.title, fallback to question. const meta = typeof entry.metadata === 'string' ? JSON.parse( entry.metadata || '{}' ) : ( entry.metadata || {} ); const displayTitle = entry.question || meta.title || __( 'Untitled', 'ai-marketing-expert' ); const entryType = entry.type || entry.source_type || ''; return ( ); } ) }
{ __( 'Title', 'ai-marketing-expert' ) } { __( 'Type', 'ai-marketing-expert' ) } { __( 'Content Preview', 'ai-marketing-expert' ) } { __( 'Updated', 'ai-marketing-expert' ) } { __( 'Actions', 'ai-marketing-expert' ) }
{ displayTitle } { TYPE_LABELS[ entryType ] || entryType || '\u2014' } { entry.content?.substring( 0, 80 ) || entry.answer?.substring( 0, 80 ) || '\u2014' } { entry.updated_at?.split( ' ' )[ 0 ] }
{ entryType === 'qa_pair' && (
{ totalPages > 1 && (
{ page } / { totalPages } ({ total } { __( 'total', 'ai-marketing-expert' ) })
) } ) }
{ /* Create / Edit Q&A modal */ } { editEntry && (
{ if ( e.target === e.currentTarget ) setEditEntry( null ); } }>

{ editEntry.id ? __( 'Edit Q&A Entry', 'ai-marketing-expert' ) : __( 'New Q&A Entry', 'ai-marketing-expert' ) }

setEditEntry( ( prev ) => ( { ...prev, bot_id: v } ) ) } __nextHasNoMarginBottom />
setEditEntry( ( prev ) => ( { ...prev, title: v } ) ) } placeholder={ __( 'e.g. What are your business hours?', 'ai-marketing-expert' ) } __nextHasNoMarginBottom />
setEditEntry( ( prev ) => ( { ...prev, content: v } ) ) } rows={ 5 } placeholder={ __( 'e.g. We are open Monday-Friday 9am-5pm.', 'ai-marketing-expert' ) } />
) } { confirmDelete && ( handleDelete( confirmDelete ) } onCancel={ () => setConfirmDelete( null ) } /> ) }
); }; export default KnowledgeBase;