quantum-ai/weather_reporter/templates/weather_reporter/detail.html
Claude 82fc051370 Fix Weather Reporter network errors for API-based agent
Fix data format and processing pattern for Weather Reporter:
- Change backend from json.loads() to request.POST.dict() for FormData handling
- Update frontend URL from window.location.href to /process/ endpoint
- Implement immediate response pattern for API-based agent (no polling needed)
- Return complete weather data directly in POST response
- Weather Reporter uses OpenWeatherMap API directly, unlike webhook agents

Key difference: API agents process immediately, webhook agents use async polling

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-11 22:37:14 +05:30

670 lines
23 KiB
HTML

{% extends 'base.html' %}
{% load static %}
{% block title %}Weather Reporter Agent - NetCop AI Hub{% endblock %}
{% block extra_css %}
<style>
.weather-page {
background: linear-gradient(135deg, #f6f8ff 0%, #e8f0fe 50%, #f0f7ff 100%);
min-height: calc(100vh - 80px);
padding: clamp(20px, 5vw, 40px);
width: 100vw;
margin-left: calc(-50vw + 50%);
}
.weather-container {
max-width: 1280px;
margin: 0 auto;
display: grid;
grid-template-columns: 1fr 400px;
gap: 24px;
align-items: start;
}
.card {
background: rgba(255, 255, 255, 0.9);
border-radius: 16px;
padding: 24px;
border: 1px solid rgba(255, 255, 255, 0.3);
backdrop-filter: blur(20px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
margin-bottom: 24px;
}
.section-title {
font-size: 18px;
font-weight: 600;
color: #1f2937;
margin-bottom: 16px;
}
.form-input {
width: 100%;
padding: 12px 16px;
border: 2px solid #e5e7eb;
border-radius: 12px;
font-size: 16px;
transition: border-color 0.2s ease;
min-height: 48px;
margin-bottom: 16px;
font-family: inherit;
background: #f9fafb;
}
.form-input:focus {
outline: none;
border-color: #3b82f6;
background: white;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.help-text {
font-size: 12px;
color: #6b7280;
margin-top: 6px;
}
.radio-grid {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
}
.radio-option {
display: flex;
align-items: center;
gap: 12px;
padding: 16px;
border: 2px solid #e5e7eb;
border-radius: 12px;
cursor: pointer;
background: white;
transition: all 0.2s ease;
min-height: 60px;
}
.radio-option.selected {
border-color: #3b82f6;
background: #eff6ff;
}
.radio-option input[type="radio"] {
margin: 0;
width: 18px;
height: 18px;
}
.processing-status {
padding: 20px;
background: rgba(59, 130, 246, 0.1);
border: 2px solid #3b82f6;
border-radius: 12px;
color: #1d4ed8;
font-weight: 600;
text-align: center;
margin-bottom: 24px;
display: none;
}
.processing-status .status-icon {
font-size: 32px;
margin-bottom: 12px;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
.results-card {
background: rgba(255, 255, 255, 0.9);
border-radius: 16px;
padding: 24px;
border: 1px solid rgba(255, 255, 255, 0.3);
backdrop-filter: blur(20px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
margin-top: 24px;
display: none;
}
.results-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 20px;
padding-bottom: 16px;
border-bottom: 1px solid #e5e7eb;
}
.results-content {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 24px;
margin-bottom: 20px;
white-space: pre-line;
line-height: 1.7;
color: #374151;
font-size: 15px;
}
.action-buttons {
display: flex;
gap: 12px;
margin-top: 20px;
flex-wrap: wrap;
}
.btn {
padding: 16px 32px;
border: none;
border-radius: 12px;
font-weight: 600;
cursor: pointer;
font-size: 16px;
min-height: 48px;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
transition: transform 0.1s ease;
text-decoration: none;
}
.btn-primary {
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
color: white;
flex: 1;
min-width: 120px;
}
.btn-secondary {
background: white;
color: #374151;
border: 2px solid #e5e7eb;
flex: 1;
min-width: 120px;
}
.btn:hover:not(:disabled) {
transform: translateY(-1px);
}
.btn:disabled {
background: #9ca3af;
cursor: not-allowed;
transform: none;
}
.wallet-section {
position: sticky;
top: 20px;
}
.wallet-balance {
font-size: 28px;
font-weight: 700;
color: #1f2937;
margin-bottom: 8px;
}
.balance-label {
font-size: 16px;
color: #6b7280;
margin-bottom: 20px;
}
.process-btn {
width: 100%;
margin-bottom: 12px;
}
.insufficient-balance {
background: #fef2f2;
border: 1px solid #fca5a5;
color: #dc2626;
padding: 12px;
border-radius: 8px;
text-align: center;
font-size: 14px;
margin-bottom: 12px;
}
.usage-info {
padding: 16px;
background: rgba(59, 130, 246, 0.1);
border-radius: 12px;
border: 1px solid rgba(59, 130, 246, 0.2);
}
.usage-info h4 {
margin: 0 0 8px 0;
font-size: 14px;
font-weight: 600;
color: #1d4ed8;
}
.usage-info ul {
margin: 0;
font-size: 12px;
color: #374151;
line-height: 1.4;
list-style: none;
padding-left: 0;
}
.usage-info li {
margin: 4px 0;
padding-left: 16px;
position: relative;
}
.usage-info li::before {
content: "•";
position: absolute;
left: 0;
color: #3b82f6;
}
/* Mobile optimizations */
@media (max-width: 768px) {
.weather-container {
grid-template-columns: 1fr;
}
.action-buttons {
flex-direction: column;
}
.btn {
width: 100%;
}
}
</style>
{% endblock %}
{% block content %}
<div class="weather-page">
<div class="weather-container">
<!-- Messages -->
{% if messages %}
{% for message in messages %}
<div class="{% if message.tags == 'error' %}error-message{% else %}success-message{% endif %}" style="grid-column: 1 / -1;">
{{ message }}
</div>
{% endfor %}
{% endif %}
<!-- Main Content -->
<div>
<div class="card">
<h3 class="section-title">🌤️ Weather Reporter</h3>
<form method="POST" id="weatherForm">
{% csrf_token %}
<!-- Location Input -->
<div style="margin-bottom: 24px;">
<label for="location" style="display: block; margin-bottom: 8px; font-size: 14px; font-weight: 600; color: #374151;">📍 Enter Location *</label>
<input type="text" name="location" id="location" class="form-input" placeholder="Enter city name, address, or coordinates..." required>
<div class="help-text">Examples: "New York", "London, UK", "Tokyo, Japan", "37.7749,-122.4194"</div>
</div>
<!-- Report Type Selection -->
<div>
<label style="display: block; margin-bottom: 12px; font-size: 14px; font-weight: 600; color: #374151;">📊 Report Type *</label>
<div class="radio-grid">
<label class="radio-option selected" onclick="selectReportType('current')">
<input type="radio" name="report_type" value="current" checked>
<div style="font-size: 20px;">🌡️</div>
<div>
<div style="font-weight: 600; margin-bottom: 4px; font-size: 16px;">Current Weather</div>
<div style="font-size: 14px; color: #6b7280;">Real-time conditions</div>
</div>
</label>
<label class="radio-option" onclick="selectReportType('forecast')">
<input type="radio" name="report_type" value="forecast">
<div style="font-size: 20px;">📅</div>
<div>
<div style="font-weight: 600; margin-bottom: 4px; font-size: 16px;">5-Day Forecast</div>
<div style="font-size: 14px; color: #6b7280;">Extended weather outlook</div>
</div>
</label>
<label class="radio-option" onclick="selectReportType('detailed')">
<input type="radio" name="report_type" value="detailed">
<div style="font-size: 20px;">📋</div>
<div>
<div style="font-weight: 600; margin-bottom: 4px; font-size: 16px;">Detailed Report</div>
<div style="font-size: 14px; color: #6b7280;">Current + forecast combined</div>
</div>
</label>
</div>
</div>
</form>
</div>
<!-- Processing Status -->
<div id="processingStatus" class="processing-status">
<div class="status-icon"></div>
<div style="font-weight: 600; color: #1d4ed8;">Getting Weather Data...</div>
<div style="font-size: 14px; color: #2563eb; margin-top: 8px;" id="statusText">Fetching latest weather information for your location</div>
</div>
<!-- Results -->
<div id="weatherResults" class="results-card">
<div class="results-header">
<div style="font-size: 24px;"></div>
<h3 style="font-size: 20px; font-weight: 600; color: #1f2937; margin: 0;">Weather Report</h3>
<div style="background: #3b82f6; color: white; padding: 6px 12px; border-radius: 6px; font-size: 14px; font-weight: 600; margin-left: auto;">✅ Complete</div>
</div>
<div class="results-content" id="weatherContent">
<!-- Weather data will be displayed here -->
</div>
<div class="action-buttons">
<button onclick="copyWeatherReport()" class="btn btn-primary">📋 Copy Report</button>
<button onclick="downloadWeatherReport()" class="btn btn-secondary">💾 Download Report</button>
<button onclick="resetForm()" class="btn" style="background: #3b82f6; color: white;">🔄 Get Another</button>
</div>
</div>
</div>
<!-- Wallet Sidebar -->
<div class="wallet-section">
<div class="card">
<h3 class="section-title">💳 Your Wallet</h3>
<div class="wallet-balance" data-wallet-balance>
{% if user.is_authenticated %}
{{ user.wallet_balance|floatformat:2 }} AED
{% else %}
0.00 AED
{% endif %}
</div>
<div class="balance-label">Available Balance</div>
{% if user.is_authenticated %}
{% if user.wallet_balance >= 2.00 %}
<button type="submit" form="weatherForm" class="btn btn-primary process-btn" id="processButton">
🌤️ Get Weather Report (2.00 AED)
</button>
{% else %}
<div class="insufficient-balance">
Insufficient balance! You need 2.00 AED.
</div>
<a href="{% url 'core:wallet' %}" class="btn btn-primary process-btn" style="text-decoration: none;">
💰 Top Up Wallet
</a>
{% endif %}
{% else %}
<a href="{% url 'authentication:login' %}" class="btn btn-primary process-btn" style="text-decoration: none;">
🔑 Login to Continue
</a>
{% endif %}
</div>
<div class="usage-info">
<h4>💡 How it works</h4>
<ul>
<li>Enter any city name worldwide</li>
<li>Choose your preferred report type</li>
<li>Get real-time weather data</li>
<li>Copy or download detailed reports</li>
</ul>
</div>
</div>
</div>
</div>
{% endblock %}
{% block extra_js %}
<script>
// Report type selection
function selectReportType(type) {
document.querySelectorAll('.radio-option').forEach(option => {
option.classList.remove('selected');
});
event.currentTarget.classList.add('selected');
document.querySelector(`input[value="${type}"]`).checked = true;
}
// Form validation
function isFormValid() {
const location = document.getElementById('location').value.trim();
const reportType = document.querySelector('input[name="report_type"]:checked');
return location && reportType;
}
// Copy weather report to clipboard
function copyWeatherReport() {
const reportText = generateReportText();
navigator.clipboard.writeText(reportText).then(() => {
showToast('📋 Weather report copied to clipboard!', 'success');
}).catch(() => {
showToast('Failed to copy report', 'error');
});
}
// Download weather report as text file
function downloadWeatherReport() {
const reportText = generateReportText();
const blob = new Blob([reportText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'weather-report-' + Date.now() + '.txt';
a.click();
URL.revokeObjectURL(url);
showToast('💾 Weather report downloaded!', 'success');
}
// Generate report text for copy/download
function generateReportText() {
const content = document.querySelector('#weatherContent');
if (content) {
return content.textContent || content.innerText || '';
}
return 'No weather data available';
}
// Reset form for creating another report
function resetForm() {
document.getElementById('weatherForm').reset();
document.getElementById('weatherResults').style.display = 'none';
document.getElementById('processingStatus').style.display = 'none';
document.getElementById('processButton').disabled = false;
document.getElementById('processButton').innerHTML = '🌤️ Get Weather Report (2.00 AED)';
// Reset to default selection
document.querySelectorAll('.radio-option').forEach(option => {
option.classList.remove('selected');
});
document.querySelector('.radio-option').classList.add('selected');
document.querySelector('input[value="current"]').checked = true;
showToast('Form reset! Ready for another weather report.', 'success');
}
// Simple toast notification
function showToast(message, type = 'info') {
const toast = document.createElement('div');
toast.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 12px 20px;
border-radius: 8px;
color: white;
font-weight: 600;
z-index: 1000;
${type === 'success' ? 'background: #10b981;' : 'background: #ef4444;'}
`;
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.remove();
}, 3000);
}
// Update wallet balance display
function updateWalletBalance(newBalance) {
const balanceElements = document.querySelectorAll('[data-wallet-balance]');
balanceElements.forEach(element => {
element.textContent = `${newBalance.toFixed(2)} AED`;
});
window.currentWalletBalance = newBalance;
}
// Display weather results
function displayResults(result) {
const resultsContainer = document.getElementById('weatherResults');
const contentContainer = document.getElementById('weatherContent');
if (result.success && result.status === 'completed') {
contentContainer.textContent = result.content || result.weather_data || result.formatted_report || 'Weather report generated successfully!';
resultsContainer.style.display = 'block';
// Update wallet balance if provided
if (result.wallet_balance !== undefined) {
updateWalletBalance(result.wallet_balance);
}
showToast('✅ Weather report completed and payment processed!', 'success');
} else {
showToast('❌ Failed to generate weather report - no charge applied', 'error');
}
}
// Poll for results
function pollForResults(requestId) {
let pollCount = 0;
const maxPolls = 30; // 30 seconds maximum
const pollInterval = setInterval(() => {
pollCount++;
fetch(`/agents/weather-reporter/status/${requestId}/`)
.then(response => response.json())
.then(result => {
if (result.status === 'completed' || result.status === 'failed') {
clearInterval(pollInterval);
document.getElementById('processingStatus').style.display = 'none';
document.getElementById('processButton').disabled = false;
document.getElementById('processButton').innerHTML = '🌤️ Get Weather Report (2.00 AED)';
displayResults(result);
} else if (pollCount >= maxPolls) {
clearInterval(pollInterval);
document.getElementById('processingStatus').style.display = 'none';
document.getElementById('processButton').disabled = false;
document.getElementById('processButton').innerHTML = '🌤️ Get Weather Report (2.00 AED)';
showToast('❌ Processing timeout - please try again', 'error');
}
})
.catch(error => {
console.error('Error polling results:', error);
if (pollCount >= maxPolls) {
clearInterval(pollInterval);
document.getElementById('processingStatus').style.display = 'none';
document.getElementById('processButton').disabled = false;
document.getElementById('processButton').innerHTML = '🌤️ Get Weather Report (2.00 AED)';
showToast('❌ Network error - please try again', 'error');
}
});
}, 1000);
}
// Handle form submission
document.getElementById('weatherForm').addEventListener('submit', function(e) {
e.preventDefault();
if (!isFormValid()) {
showToast('Please fill in all required fields', 'error');
return;
}
// Check user authentication
{% if not user.is_authenticated %}
window.location.href = "{% url 'authentication:login' %}";
return;
{% endif %}
// Check wallet balance
const balance = {{ user.wallet_balance|default:0 }};
if (balance < 2.00) {
showToast('Insufficient balance! You need 2.00 AED.', 'error');
setTimeout(() => {
window.location.href = "{% url 'core:wallet' %}";
}, 2000);
return;
}
// Show processing status with steps
document.getElementById('processingStatus').style.display = 'block';
document.getElementById('processButton').disabled = true;
document.getElementById('processButton').innerHTML = '⏳ Processing...';
document.getElementById('weatherResults').style.display = 'none';
const steps = [
'Connecting to weather service...',
'Fetching location data...',
'Getting current conditions...',
'Processing weather information...',
'Generating report...'
];
let currentStep = 0;
const stepInterval = setInterval(() => {
if (currentStep < steps.length) {
document.getElementById('statusText').textContent = steps[currentStep];
currentStep++;
} else {
clearInterval(stepInterval);
}
}, 800);
// Submit form via AJAX
const formData = new FormData(this);
fetch('/agents/weather-reporter/process/', {
method: 'POST',
body: formData,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(response => response.json())
.then(result => {
clearInterval(stepInterval);
// Handle immediate response (API-based agent)
document.getElementById('processingStatus').style.display = 'none';
document.getElementById('processButton').disabled = false;
document.getElementById('processButton').innerHTML = '🌤️ Get Weather Report (2.00 AED)';
if (result.error) {
showToast(`${result.error}`, 'error');
} else if (result.success) {
displayResults(result);
} else {
showToast('❌ Failed to generate weather report', 'error');
}
})
.catch(error => {
clearInterval(stepInterval);
console.error('Error:', error);
document.getElementById('processingStatus').style.display = 'none';
document.getElementById('processButton').disabled = false;
document.getElementById('processButton').innerHTML = '🌤️ Get Weather Report (2.00 AED)';
showToast('❌ Network error - please try again', 'error');
});
});
</script>
{% endblock %}