forked from 0xWheatyz/SPARC
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 153eb3b968 |
+1
-56
@@ -9,7 +9,7 @@ from typing import Annotated, List
|
|||||||
|
|
||||||
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Query, Request
|
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Query, Request
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import JSONResponse, StreamingResponse
|
from fastapi.responses import JSONResponse
|
||||||
from pydantic import BaseModel, EmailStr, Field
|
from pydantic import BaseModel, EmailStr, Field
|
||||||
from slowapi import Limiter
|
from slowapi import Limiter
|
||||||
from slowapi.errors import RateLimitExceeded
|
from slowapi.errors import RateLimitExceeded
|
||||||
@@ -389,61 +389,6 @@ async def get_analytics(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# ============== Export Endpoints ==============
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/export/{company_name}", tags=["Export"])
|
|
||||||
async def export_company_csv(
|
|
||||||
company_name: str,
|
|
||||||
_: UserResponse = Depends(get_current_user),
|
|
||||||
):
|
|
||||||
"""Export analysis results for a company as a CSV file.
|
|
||||||
|
|
||||||
Returns all stored analysis records for the given company, including
|
|
||||||
analysis type, model used, response text, and timestamp.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
company_name: Company name to export results for
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
CSV file download
|
|
||||||
"""
|
|
||||||
import csv
|
|
||||||
import io
|
|
||||||
|
|
||||||
db = get_db_client()
|
|
||||||
# Query all non-cached analysis results for this company
|
|
||||||
with db.get_conn() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(
|
|
||||||
"""
|
|
||||||
SELECT company_name, analysis_type, model, response, timestamp
|
|
||||||
FROM llm_messages
|
|
||||||
WHERE LOWER(company_name) = LOWER(%s) AND is_cached = FALSE
|
|
||||||
ORDER BY timestamp DESC
|
|
||||||
""",
|
|
||||||
(company_name,),
|
|
||||||
)
|
|
||||||
rows = cur.fetchall()
|
|
||||||
|
|
||||||
if not rows:
|
|
||||||
raise HTTPException(status_code=404, detail=f"No analysis results found for '{company_name}'")
|
|
||||||
|
|
||||||
output = io.StringIO()
|
|
||||||
writer = csv.writer(output)
|
|
||||||
writer.writerow(["company_name", "analysis_type", "model", "analysis", "timestamp"])
|
|
||||||
for row in rows:
|
|
||||||
writer.writerow(row)
|
|
||||||
|
|
||||||
output.seek(0)
|
|
||||||
safe_name = company_name.replace(" ", "_").lower()
|
|
||||||
return StreamingResponse(
|
|
||||||
iter([output.getvalue()]),
|
|
||||||
media_type="text/csv",
|
|
||||||
headers={"Content-Disposition": f'attachment; filename="sparc_{safe_name}_export.csv"'},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ============== System Endpoints ==============
|
# ============== System Endpoints ==============
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -126,23 +126,6 @@ export const analysisApi = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Export API
|
|
||||||
export const exportApi = {
|
|
||||||
exportCsv: async (companyName: string): Promise<void> => {
|
|
||||||
const response = await api.get(`/export/${encodeURIComponent(companyName)}`, {
|
|
||||||
responseType: 'blob',
|
|
||||||
});
|
|
||||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
|
||||||
const link = document.createElement('a');
|
|
||||||
link.href = url;
|
|
||||||
link.setAttribute('download', `sparc_${companyName.toLowerCase().replace(/\s+/g, '_')}_export.csv`);
|
|
||||||
document.body.appendChild(link);
|
|
||||||
link.click();
|
|
||||||
link.remove();
|
|
||||||
window.URL.revokeObjectURL(url);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// Analytics API
|
// Analytics API
|
||||||
export const analyticsApi = {
|
export const analyticsApi = {
|
||||||
getAnalytics: async (days = 30): Promise<Analytics> => {
|
getAnalytics: async (days = 30): Promise<Analytics> => {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useMutation } from '@tanstack/react-query';
|
import { useMutation } from '@tanstack/react-query';
|
||||||
import { analysisApi, exportApi } from '../api/client';
|
import { analysisApi } from '../api/client';
|
||||||
import { Search, CheckCircle, AlertCircle, Clock, FileText, Download } from 'lucide-react';
|
import { Search, CheckCircle, AlertCircle, Clock, FileText } from 'lucide-react';
|
||||||
import type { CompanyAnalysis } from '../types';
|
import type { CompanyAnalysis } from '../types';
|
||||||
|
|
||||||
export function Analysis() {
|
export function Analysis() {
|
||||||
@@ -106,18 +106,9 @@ export function Analysis() {
|
|||||||
{/* Analysis Content */}
|
{/* Analysis Content */}
|
||||||
{result.success && result.analysis && (
|
{result.success && result.analysis && (
|
||||||
<div className="bg-bg-card/60 backdrop-blur-lg border border-primary/15 rounded-2xl p-6">
|
<div className="bg-bg-card/60 backdrop-blur-lg border border-primary/15 rounded-2xl p-6">
|
||||||
<div className="flex items-center justify-between border-b-2 border-primary/30 pb-2 mb-4">
|
<h3 className="text-lg font-semibold text-text-primary border-b-2 border-primary/30 pb-2 mb-4">
|
||||||
<h3 className="text-lg font-semibold text-text-primary">
|
AI Analysis Results
|
||||||
AI Analysis Results
|
</h3>
|
||||||
</h3>
|
|
||||||
<button
|
|
||||||
onClick={() => exportApi.exportCsv(result.company_name)}
|
|
||||||
className="flex items-center gap-2 text-sm bg-primary/20 hover:bg-primary/30 text-primary font-medium px-3 py-1.5 rounded-lg transition-colors"
|
|
||||||
>
|
|
||||||
<Download size={14} />
|
|
||||||
Export CSV
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="prose prose-invert max-w-none">
|
<div className="prose prose-invert max-w-none">
|
||||||
<div className="text-text-primary whitespace-pre-wrap leading-relaxed">
|
<div className="text-text-primary whitespace-pre-wrap leading-relaxed">
|
||||||
{result.analysis}
|
{result.analysis}
|
||||||
|
|||||||
@@ -9,15 +9,38 @@ const COLORS = ['#6366f1', '#0ea5e9', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'
|
|||||||
export function AnalyticsPage() {
|
export function AnalyticsPage() {
|
||||||
const [days, setDays] = useState(30);
|
const [days, setDays] = useState(30);
|
||||||
|
|
||||||
const { data, isLoading, isError } = useQuery({
|
const { data, isLoading, isError, refetch } = useQuery({
|
||||||
queryKey: ['analytics', days],
|
queryKey: ['analytics', days],
|
||||||
queryFn: () => analyticsApi.getAnalytics(days),
|
queryFn: () => analyticsApi.getAnalytics(days),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center min-h-[400px]">
|
<div className="space-y-6">
|
||||||
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
|
<div>
|
||||||
|
<h2 className="text-xl font-semibold text-text-primary border-b-2 border-primary/30 pb-2 mb-2">
|
||||||
|
Analytics Dashboard
|
||||||
|
</h2>
|
||||||
|
<p className="text-text-secondary">Loading analytics data...</p>
|
||||||
|
</div>
|
||||||
|
{/* Skeleton cards */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
|
{[1, 2, 3].map((i) => (
|
||||||
|
<div key={i} className="bg-gradient-to-br from-primary/10 to-secondary/10 border border-primary/20 rounded-xl p-5 text-center animate-pulse">
|
||||||
|
<div className="h-9 w-16 bg-primary/20 rounded mx-auto mb-2" />
|
||||||
|
<div className="h-4 w-24 bg-primary/10 rounded mx-auto" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{/* Skeleton charts */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
|
{[1, 2].map((i) => (
|
||||||
|
<div key={i} className="bg-bg-card/60 border border-primary/15 rounded-2xl p-6 animate-pulse">
|
||||||
|
<div className="h-5 w-40 bg-primary/20 rounded mb-4" />
|
||||||
|
<div className="h-[300px] bg-primary/5 rounded" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -33,15 +56,18 @@ export function AnalyticsPage() {
|
|||||||
<div className="bg-gradient-to-br from-primary/10 to-secondary/5 border border-primary/20 rounded-xl p-6">
|
<div className="bg-gradient-to-br from-primary/10 to-secondary/5 border border-primary/20 rounded-xl p-6">
|
||||||
<div className="flex items-center gap-3 text-warning mb-2">
|
<div className="flex items-center gap-3 text-warning mb-2">
|
||||||
<Database size={24} />
|
<Database size={24} />
|
||||||
<span className="font-semibold">Database Not Connected</span>
|
<span className="font-semibold">Unable to Load Analytics</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-text-secondary">
|
<p className="text-text-secondary">
|
||||||
Set <code className="bg-bg-card px-2 py-1 rounded">USE_DATABASE=true</code> in your .env file to enable analytics tracking.
|
Could not connect to the analytics database. Ensure PostgreSQL is running and
|
||||||
|
<code className="bg-bg-card px-2 py-1 rounded mx-1">DATABASE_URL</code> is configured correctly.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
<button
|
||||||
<div className="flex items-center gap-2 bg-secondary/10 border border-secondary/20 text-secondary rounded-xl px-4 py-3">
|
onClick={() => refetch()}
|
||||||
<AlertCircle size={18} />
|
className="mt-3 text-sm bg-primary/20 hover:bg-primary/30 text-primary font-medium px-4 py-2 rounded-lg transition-colors"
|
||||||
<span>Analytics features require storing analysis results in PostgreSQL for historical tracking.</span>
|
>
|
||||||
|
Retry
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -114,9 +114,21 @@ export function Batch() {
|
|||||||
|
|
||||||
{/* Error */}
|
{/* Error */}
|
||||||
{mutation.isError && (
|
{mutation.isError && (
|
||||||
<div className="flex items-center gap-2 bg-error/10 border border-error/20 text-error rounded-xl px-4 py-3">
|
<div className="bg-error/10 border border-error/20 rounded-xl px-4 py-3">
|
||||||
<AlertCircle size={18} />
|
<div className="flex items-center gap-2 text-error">
|
||||||
<span>Batch analysis failed. Please try again.</span>
|
<AlertCircle size={18} />
|
||||||
|
<span className="font-semibold">Batch analysis failed</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-text-secondary text-sm mt-1 ml-7">
|
||||||
|
{mutation.error instanceof Error ? mutation.error.message : 'An unexpected error occurred.'}
|
||||||
|
{' '}Check your connection and try again.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onClick={() => mutation.reset()}
|
||||||
|
className="ml-7 mt-2 text-sm text-primary hover:text-primary-dark underline"
|
||||||
|
>
|
||||||
|
Dismiss
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user