Files
ai-mail-server/web/script.js

86 lines
3.0 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
const editor = document.getElementById('rules-editor');
const saveButton = document.getElementById('save-button');
const runButton = document.getElementById('run-button');
const statusMessage = document.getElementById('status-message');
// Function to display status messages
const showStatus = (message, isError = false) => {
statusMessage.textContent = message;
statusMessage.className = isError ? 'error' : 'success';
};
// 1. Fetch initial rules on page load
fetch('/api/rules')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.error) {
showStatus(`Error loading rules: ${data.error}`, true);
} else {
// Pretty-print the JSON with 2 spaces
editor.value = JSON.stringify(data, null, 2);
}
})
.catch(error => {
showStatus('Failed to fetch rules. Is the server running?', true);
console.error('Fetch error:', error);
});
// 2. Add event listener for the Save button
saveButton.addEventListener('click', () => {
let rulesContent;
try {
// We parse it first to ensure it's valid JSON before sending
rulesContent = JSON.parse(editor.value);
} catch (error) {
showStatus('Invalid JSON format. Please correct it before saving.', true);
return;
}
fetch('/api/rules', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(rulesContent),
})
.then(response => response.json())
.then(data => {
if (data.error) {
showStatus(`Error saving rules: ${data.error}`, true);
} else {
showStatus(data.message || 'Rules saved successfully!', false);
}
})
.catch(error => {
showStatus('Failed to save rules. An unknown error occurred.', true);
console.error('Save error:', error);
});
});
// 3. Add event listener for the Run button
runButton.addEventListener('click', () => {
showStatus('Requesting to start email processing...', false);
fetch('/api/run-processing', {
method: 'POST',
})
.then(response => response.json())
.then(data => {
if (data.error) {
showStatus(`Error starting process: ${data.error}`, true);
} else {
showStatus(data.message || 'Processing started in the background.', false);
}
})
.catch(error => {
showStatus('Failed to start processing. An unknown error occurred.', true);
console.error('Run error:', error);
});
});
});