mirror of
https://github.com/thecyberlearn/quantum-ai-v3.git
synced 2026-08-18 22:12:57 +00:00
Fix Data Analyzer wallet balance persistence issue
Replace demo JavaScript implementation with real backend processing: - Remove fake analyzeData() function that only updated frontend - Add real AJAX submission to /agents/data-analyzer/process/ endpoint - Implement proper polling for results using request ID - Add displayResults() function to handle backend responses - Update wallet balance from server response to ensure persistence - Remove generateSampleAnalysis() demo function - Fix wallet balance to persist across page navigation This resolves the issue where wallet deduction would revert when navigating to other pages, as the frontend was using demo mode instead of actual database transactions. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
2d793dfbae
commit
07d61dbf63
@ -577,14 +577,31 @@
|
|||||||
return;
|
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 < 5.00) {
|
||||||
|
showToast('Insufficient balance! You need 5.00 AED.', 'error');
|
||||||
|
setTimeout(() => {
|
||||||
|
window.location.href = "{% url 'core:wallet' %}";
|
||||||
|
}, 2000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const analysisType = document.querySelector('input[name="analysisType"]:checked').value;
|
const analysisType = document.querySelector('input[name="analysisType"]:checked').value;
|
||||||
|
|
||||||
// Show processing status
|
// Show processing status
|
||||||
document.getElementById('processingStatus').style.display = 'block';
|
document.getElementById('processingStatus').style.display = 'block';
|
||||||
document.getElementById('processButton').disabled = true;
|
document.getElementById('processButton').disabled = true;
|
||||||
document.getElementById('processButton').innerHTML = '⏳ Processing...';
|
document.getElementById('processButton').innerHTML = '⏳ Processing...';
|
||||||
|
document.getElementById('analysisResults').style.display = 'none';
|
||||||
|
|
||||||
// Simulate analysis steps
|
// Processing steps for user feedback
|
||||||
const steps = [
|
const steps = [
|
||||||
'Reading file structure...',
|
'Reading file structure...',
|
||||||
'Extracting data patterns...',
|
'Extracting data patterns...',
|
||||||
@ -600,142 +617,120 @@
|
|||||||
currentStep++;
|
currentStep++;
|
||||||
} else {
|
} else {
|
||||||
clearInterval(stepInterval);
|
clearInterval(stepInterval);
|
||||||
completeAnalysis(analysisType);
|
|
||||||
}
|
}
|
||||||
}, 1000);
|
}, 1000);
|
||||||
|
|
||||||
|
// Submit form data to backend
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', selectedFile);
|
||||||
|
formData.append('analysis_type', analysisType);
|
||||||
|
formData.append('csrfmiddlewaretoken', document.querySelector('[name=csrfmiddlewaretoken]').value);
|
||||||
|
|
||||||
|
fetch('/agents/data-analyzer/process/', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData,
|
||||||
|
headers: {
|
||||||
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
}
|
}
|
||||||
|
})
|
||||||
function completeAnalysis(analysisType) {
|
.then(response => response.json())
|
||||||
// Generate sample analysis report
|
.then(result => {
|
||||||
const analysisReport = generateSampleAnalysis(analysisType);
|
clearInterval(stepInterval);
|
||||||
|
if (result.success && result.request_id) {
|
||||||
// Display results
|
// Start polling for results
|
||||||
document.getElementById('analysisContent').textContent = analysisReport;
|
pollForResults(result.request_id);
|
||||||
|
} else {
|
||||||
|
// Handle immediate response
|
||||||
document.getElementById('processingStatus').style.display = 'none';
|
document.getElementById('processingStatus').style.display = 'none';
|
||||||
document.getElementById('analysisResults').style.display = 'block';
|
|
||||||
|
|
||||||
// Reset button
|
|
||||||
document.getElementById('processButton').disabled = false;
|
document.getElementById('processButton').disabled = false;
|
||||||
document.getElementById('processButton').innerHTML = '📊 Analyze Data (5.00 AED)';
|
document.getElementById('processButton').innerHTML = '📊 Analyze Data (5.00 AED)';
|
||||||
|
|
||||||
// Update wallet balance (demo)
|
if (result.error) {
|
||||||
const currentBalance = parseFloat('{{ user.wallet_balance|floatformat:2 }}');
|
showToast(`❌ ${result.error}`, 'error');
|
||||||
updateWalletBalance(currentBalance - 5.00);
|
} else {
|
||||||
|
displayResults(result);
|
||||||
showToast('Data analysis complete! 5.00 AED used.', 'success');
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
clearInterval(stepInterval);
|
||||||
|
console.error('Error:', error);
|
||||||
|
document.getElementById('processingStatus').style.display = 'none';
|
||||||
|
document.getElementById('processButton').disabled = false;
|
||||||
|
document.getElementById('processButton').innerHTML = '📊 Analyze Data (5.00 AED)';
|
||||||
|
showToast('❌ Network error - please try again', 'error');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateSampleAnalysis(type) {
|
// Display analysis results
|
||||||
const fileName = selectedFile.name;
|
function displayResults(result) {
|
||||||
const baseReport = `📊 Data Analysis Report - ${fileName}
|
const resultsContainer = document.getElementById('analysisResults');
|
||||||
|
const contentContainer = document.getElementById('analysisContent');
|
||||||
|
|
||||||
File Information:
|
if (result.success && result.status === 'completed') {
|
||||||
- Name: ${fileName}
|
// Use the analysis content from backend
|
||||||
- Size: ${formatFileSize(selectedFile.size)}
|
const content = result.report_text || result.analysis_results || result.insights_summary || 'Data analysis completed successfully!';
|
||||||
- Type: ${selectedFile.type || 'Unknown'}
|
contentContainer.textContent = content;
|
||||||
- Processed: ${new Date().toLocaleString()}
|
resultsContainer.style.display = 'block';
|
||||||
|
|
||||||
`;
|
// Update wallet balance if provided
|
||||||
|
if (result.wallet_balance !== undefined) {
|
||||||
if (type === 'summary') {
|
updateWalletBalance(result.wallet_balance);
|
||||||
return baseReport + `Summary Analysis Results:
|
|
||||||
|
|
||||||
Key Findings:
|
|
||||||
• Data contains 1,247 records across 8 columns
|
|
||||||
• 94% data completeness rate
|
|
||||||
• 3 potential outliers identified
|
|
||||||
• Strong correlation (0.83) between variables A and B
|
|
||||||
• Trending pattern shows 15% increase over time period
|
|
||||||
|
|
||||||
Recommendations:
|
|
||||||
• Clean missing data in columns 3 and 7
|
|
||||||
• Investigate outlier values for data quality
|
|
||||||
• Consider seasonal adjustments for trend analysis
|
|
||||||
|
|
||||||
Generated by NetCop AI Data Analyzer Agent`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type === 'detailed') {
|
showToast('✅ Data analysis completed and payment processed!', 'success');
|
||||||
return baseReport + `Detailed Analysis Results:
|
} else {
|
||||||
|
showToast('❌ Failed to analyze data - no charge applied', 'error');
|
||||||
Data Quality Assessment:
|
}
|
||||||
• Missing Values: 6% (73 records)
|
|
||||||
• Duplicate Records: 2% (25 records)
|
|
||||||
• Outliers Detected: 3 records beyond 3σ threshold
|
|
||||||
• Data Types: 5 numeric, 2 categorical, 1 datetime
|
|
||||||
|
|
||||||
Statistical Summary:
|
|
||||||
• Mean: 45.67 ± 12.34
|
|
||||||
• Median: 43.21
|
|
||||||
• Mode: 42.00
|
|
||||||
• Range: 15.5 - 89.3
|
|
||||||
• Skewness: 0.23 (slight right skew)
|
|
||||||
• Kurtosis: -0.45 (platykurtic distribution)
|
|
||||||
|
|
||||||
Correlation Analysis:
|
|
||||||
• Variable A ↔ Variable B: 0.83 (strong positive)
|
|
||||||
• Variable C ↔ Variable D: -0.67 (moderate negative)
|
|
||||||
• Variable E ↔ Variable F: 0.12 (weak positive)
|
|
||||||
|
|
||||||
Trend Analysis:
|
|
||||||
• Linear trend: y = 2.3x + 18.5 (R² = 0.76)
|
|
||||||
• Seasonal component detected (quarterly pattern)
|
|
||||||
• 15% overall growth trend identified
|
|
||||||
|
|
||||||
Generated by NetCop AI Data Analyzer Agent`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type === 'statistical') {
|
// Poll for results
|
||||||
return baseReport + `Advanced Statistical Analysis:
|
function pollForResults(requestId) {
|
||||||
|
let pollCount = 0;
|
||||||
|
const maxPolls = 60; // 60 seconds maximum for data analysis
|
||||||
|
|
||||||
Descriptive Statistics:
|
const pollInterval = setInterval(() => {
|
||||||
• Count: 1,247 observations
|
pollCount++;
|
||||||
• Mean: 45.67 ± 12.34 (95% CI: 44.98 - 46.36)
|
|
||||||
• Median: 43.21
|
|
||||||
• Standard Deviation: 12.34
|
|
||||||
• Variance: 152.48
|
|
||||||
• Coefficient of Variation: 27.02%
|
|
||||||
|
|
||||||
Distribution Analysis:
|
fetch(`/agents/data-analyzer/result/${requestId}/`)
|
||||||
• Normality Test (Shapiro-Wilk): W = 0.987, p = 0.043
|
.then(response => response.json())
|
||||||
• Distribution appears approximately normal with slight skew
|
.then(result => {
|
||||||
• Outliers: 3 values > 3σ (flagged for review)
|
if (result.status === 'completed' || result.status === 'failed') {
|
||||||
|
clearInterval(pollInterval);
|
||||||
|
document.getElementById('processingStatus').style.display = 'none';
|
||||||
|
document.getElementById('processButton').disabled = false;
|
||||||
|
document.getElementById('processButton').innerHTML = '📊 Analyze Data (5.00 AED)';
|
||||||
|
|
||||||
Hypothesis Testing:
|
displayResults(result);
|
||||||
• T-test vs. baseline: t = 3.45, p = 0.0006 (significant)
|
} else if (pollCount >= maxPolls) {
|
||||||
• ANOVA across groups: F = 12.67, p < 0.001 (significant)
|
clearInterval(pollInterval);
|
||||||
• Chi-square test: χ² = 23.45, p = 0.012 (significant)
|
document.getElementById('processingStatus').style.display = 'none';
|
||||||
|
document.getElementById('processButton').disabled = false;
|
||||||
Regression Analysis:
|
document.getElementById('processButton').innerHTML = '📊 Analyze Data (5.00 AED)';
|
||||||
• R-squared: 0.762 (76.2% variance explained)
|
showToast('❌ Processing timeout - please try again', 'error');
|
||||||
• Adjusted R-squared: 0.758
|
}
|
||||||
• F-statistic: 234.67, p < 0.001
|
})
|
||||||
• Durbin-Watson: 1.98 (no autocorrelation)
|
.catch(error => {
|
||||||
|
console.error('Error polling results:', error);
|
||||||
Model Coefficients:
|
if (pollCount >= maxPolls) {
|
||||||
• Intercept: 18.5 ± 2.1 (p < 0.001)
|
clearInterval(pollInterval);
|
||||||
• Slope: 2.3 ± 0.3 (p < 0.001)
|
document.getElementById('processingStatus').style.display = 'none';
|
||||||
• Residual Standard Error: 4.67
|
document.getElementById('processButton').disabled = false;
|
||||||
|
document.getElementById('processButton').innerHTML = '📊 Analyze Data (5.00 AED)';
|
||||||
Time Series Analysis:
|
showToast('❌ Network error - please try again', 'error');
|
||||||
• Trend: Increasing (slope = 0.023/month)
|
}
|
||||||
• Seasonality: Quarterly pattern detected
|
});
|
||||||
• Autocorrelation: Significant at lags 1, 4, 12
|
}, 1000);
|
||||||
• Forecast accuracy: MAPE = 8.3%
|
|
||||||
|
|
||||||
Generated by NetCop AI Data Analyzer Agent`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return baseReport + 'Analysis complete.';
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateWalletBalance(newBalance) {
|
function updateWalletBalance(newBalance) {
|
||||||
document.getElementById('walletBalance').textContent = newBalance.toFixed(2) + ' AED';
|
// Update wallet balance display
|
||||||
// Update header balance if exists
|
const balanceElements = document.querySelectorAll('[data-wallet-balance]');
|
||||||
const headerBalance = document.querySelector('[data-wallet-balance]');
|
balanceElements.forEach(element => {
|
||||||
if (headerBalance) {
|
element.textContent = `${newBalance.toFixed(2)} AED`;
|
||||||
headerBalance.textContent = `💰 ${newBalance.toFixed(2)} AED`;
|
});
|
||||||
}
|
window.currentWalletBalance = newBalance;
|
||||||
}
|
}
|
||||||
|
|
||||||
function copyAnalysisReport() {
|
function copyAnalysisReport() {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user