Admin/Chatbot Admin: Difference between revisions

From Bodhicitta
((by SublimeText.Mediawiker))
Tag: Reverted
((by SublimeText.Mediawiker))
Tags: Replaced Reverted
Line 1: Line 1:
<div id="chatbot-kb-editor">
{{#widget:ChatBotAdminPage}}
    <div class="kb-header">
        <h2>Chatbot Knowledge Base Editor</h2>
        <div class="kb-toolbar">
            <button onclick="ChatbotAdmin.loadKB()" style="padding:8px 16px; background:#6c757d; color:white; border:none; border-radius:4px; cursor:pointer;">Load Current KB</button>
            <button onclick="ChatbotAdmin.saveKB()" style="padding:8px 16px; background:#28a745; color:white; border:none; border-radius:4px; cursor:pointer;">Save Changes</button>
        </div>
    </div>
   
    <div id="kb-status" style="padding:10px; margin:10px 0; background:#f8f9fa; border-radius:4px;"></div>
   
    <div style="margin:20px 0;">
        <h3>Edit Knowledge Base JSON</h3>
        <textarea id="kb-json-editor" style="width:100%; height:500px; font-family:monospace; font-size:12px; padding:10px; border:1px solid #ddd;"></textarea>
    </div>
   
    <div style="margin:20px 0;">
        <h3>Quick Add Response</h3>
        <div style="background:#f8f9fa; padding:15px; border-radius:4px;">
            <div style="margin-bottom:10px;">
                <label style="display:block; margin-bottom:5px;">Patterns (comma-separated):</label>
                <input type="text" id="quick-patterns" style="width:100%; padding:5px;" placeholder="login, sign in, account">
            </div>
            <div style="margin-bottom:10px;">
                <label style="display:block; margin-bottom:5px;">Response:</label>
                <textarea id="quick-response" style="width:100%; padding:5px; height:60px;" placeholder="Enter the response text..."></textarea>
            </div>
            <div style="margin-bottom:10px;">
                <label style="display:block; margin-bottom:5px;">Category:</label>
                <select id="quick-category" style="width:100%; padding:5px;">
                    <option value="access">Access & Permissions</option>
                    <option value="navigation">Navigation</option>
                    <option value="search">Search</option>
                    <option value="general">General</option>
                </select>
            </div>
            <button onclick="ChatbotAdmin.quickAdd()" style="padding:8px 16px; background:#8B4513; color:white; border:none; border-radius:4px; cursor:pointer;">Add Response</button>
        </div>
    </div>
</div>
 
<script>
var ChatbotAdmin = {
    currentData: null,
   
    loadKB: function() {
        var self = this;
        var apiUrl = mw.config.get('wgScriptPath') + '/api.php';
       
        // Show loading message
        document.getElementById('kb-status').innerHTML = 'Loading knowledge base...';
       
        // Try to load the current KB
        $.ajax({
            url: apiUrl,
            data: {
                action: 'query',
                prop: 'revisions',
                titles: 'MediaWiki:Chatbot-KnowledgeBase.json',
                rvprop: 'content',
                format: 'json'
            },
            success: function(data) {
                var pages = data.query.pages;
                var content = null;
               
                for (var pageId in pages) {
                    if (pages[pageId].revisions) {
                        content = pages[pageId].revisions[0]['*'];
                        break;
                    }
                }
               
                if (content) {
                    try {
                        self.currentData = JSON.parse(content);
                        document.getElementById('kb-json-editor').value = JSON.stringify(self.currentData, null, 2);
                        document.getElementById('kb-status').innerHTML = '<span style="color:green;">✓ Knowledge base loaded successfully</span>';
                    } catch(e) {
                        document.getElementById('kb-status').innerHTML = '<span style="color:red;">Error parsing knowledge base: ' + e.message + '</span>';
                    }
                } else {
                    // Create default structure
                    self.currentData = {
                        version: "1.0",
                        lastUpdated: new Date().toISOString().split('T')[0],
                        categories: {
                            access: {
                                name: "Access & Permissions",
                                enabled: true,
                                items: []
                            },
                            navigation: {
                                name: "Navigation",
                                enabled: true,
                                items: []
                            },
                            search: {
                                name: "Search",
                                enabled: true,
                                items: []
                            },
                            general: {
                                name: "General",
                                enabled: true,
                                items: []
                            }
                        }
                    };
                    document.getElementById('kb-json-editor').value = JSON.stringify(self.currentData, null, 2);
                    document.getElementById('kb-status').innerHTML = '<span style="color:orange;">Knowledge base not found. Created new structure.</span>';
                }
            },
            error: function(xhr, status, error) {
                document.getElementById('kb-status').innerHTML = '<span style="color:red;">Error loading: ' + error + '</span>';
            }
        });
    },
   
    saveKB: function() {
        var self = this;
        var apiUrl = mw.config.get('wgScriptPath') + '/api.php';
       
        // Parse the JSON from the editor
        try {
            this.currentData = JSON.parse(document.getElementById('kb-json-editor').value);
        } catch(e) {
            alert('Invalid JSON: ' + e.message);
            return;
        }
       
        // Update metadata
        this.currentData.lastUpdated = new Date().toISOString().split('T')[0];
       
        document.getElementById('kb-status').innerHTML = 'Saving...';
       
        // Get edit token
        $.ajax({
            url: apiUrl,
            data: {
                action: 'query',
                meta: 'tokens',
                type: 'csrf',
                format: 'json'
            },
            success: function(data) {
                var token = data.query.tokens.csrftoken;
               
                // Save the page
                $.ajax({
                    url: apiUrl,
                    type: 'POST',
                    data: {
                        action: 'edit',
                        title: 'MediaWiki:Chatbot-KnowledgeBase.json',
                        text: JSON.stringify(self.currentData, null, 2),
                        summary: 'Updated chatbot knowledge base',
                        token: token,
                        format: 'json'
                    },
                    success: function() {
                        document.getElementById('kb-status').innerHTML = '<span style="color:green;">✓ Saved successfully!</span>';
                        // Clear cache
                        try {
                            localStorage.removeItem('tsadra-chatbot-kb');
                        } catch(e) {}
                        // Update editor
                        document.getElementById('kb-json-editor').value = JSON.stringify(self.currentData, null, 2);
                    },
                    error: function(xhr, status, error) {
                        document.getElementById('kb-status').innerHTML = '<span style="color:red;">Error saving: ' + error + '</span>';
                    }
                });
            }
        });
    },
   
    quickAdd: function() {
        var patterns = document.getElementById('quick-patterns').value;
        var response = document.getElementById('quick-response').value;
        var category = document.getElementById('quick-category').value;
       
        if (!patterns || !response) {
            alert('Please enter patterns and response');
            return;
        }
       
        // Parse current data
        try {
            this.currentData = JSON.parse(document.getElementById('kb-json-editor').value);
        } catch(e) {
            alert('Please load the knowledge base first');
            return;
        }
       
        // Create new entry
        var newEntry = {
            patterns: patterns.split(',').map(function(p) { return p.trim().toLowerCase(); }),
            response: response,
            priority: 5
        };
       
        // Add to category
        if (!this.currentData.categories[category]) {
            this.currentData.categories[category] = {
                name: category,
                enabled: true,
                items: []
            };
        }
       
        this.currentData.categories[category].items.push(newEntry);
       
        // Update editor
        document.getElementById('kb-json-editor').value = JSON.stringify(this.currentData, null, 2);
       
        // Clear form
        document.getElementById('quick-patterns').value = '';
        document.getElementById('quick-response').value = '';
       
        document.getElementById('kb-status').innerHTML = '<span style="color:orange;">Entry added. Don\'t forget to save!</span>';
    }
};
 
// Load on page ready
$(document).ready(function() {
    ChatbotAdmin.loadKB();
});
</script>

Revision as of 19:47, 6 October 2025