forked from 0xWheatyz/SPARC
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a4aa968434 |
@@ -40,9 +40,3 @@ JWT_SECRET=your-secure-jwt-secret-change-in-production
|
|||||||
# When USE_CACHE=true: check database for cached responses before making API calls
|
# When USE_CACHE=true: check database for cached responses before making API calls
|
||||||
# When USE_CACHE=false: always make fresh API calls (still stores results in database)
|
# When USE_CACHE=false: always make fresh API calls (still stores results in database)
|
||||||
USE_CACHE=true
|
USE_CACHE=true
|
||||||
|
|
||||||
# ---- Webhooks ----
|
|
||||||
|
|
||||||
# Comma-separated list of webhook URLs for job completion and alert notifications
|
|
||||||
# Supports generic HTTP POST and Slack/Discord incoming webhooks
|
|
||||||
# WEBHOOK_URLS=https://hooks.slack.com/services/XXX,https://example.com/webhook
|
|
||||||
|
|||||||
@@ -519,25 +519,8 @@ def _run_batch_job(job_id: str, companies: list[str], max_workers: int):
|
|||||||
progress=100,
|
progress=100,
|
||||||
result_json=_json.dumps(batch_response.model_dump(), default=str),
|
result_json=_json.dumps(batch_response.model_dump(), default=str),
|
||||||
)
|
)
|
||||||
# Fire webhook notification
|
|
||||||
from SPARC.webhooks import notify_job_completed
|
|
||||||
notify_job_completed(
|
|
||||||
job_id=job_id,
|
|
||||||
status="completed",
|
|
||||||
total_companies=result.total_companies,
|
|
||||||
successful=result.successful,
|
|
||||||
failed=result.failed,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.update_job(job_id, status="failed", error=str(e))
|
db.update_job(job_id, status="failed", error=str(e))
|
||||||
from SPARC.webhooks import notify_job_completed
|
|
||||||
notify_job_completed(
|
|
||||||
job_id=job_id,
|
|
||||||
status="failed",
|
|
||||||
total_companies=len(companies),
|
|
||||||
successful=0,
|
|
||||||
failed=len(companies),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/analyze/batch/async", response_model=JobStatus, tags=["Analysis"])
|
@app.post("/analyze/batch/async", response_model=JobStatus, tags=["Analysis"])
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
"""Webhook notifications for job completion and alert events.
|
|
||||||
|
|
||||||
Sends JSON payloads to configured webhook URLs with retry logic.
|
|
||||||
Supports generic HTTP POST and Slack-compatible text payloads.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
from datetime import datetime
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import requests
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# Comma-separated list of webhook URLs (env var based config)
|
|
||||||
_WEBHOOK_URLS_RAW = os.getenv("WEBHOOK_URLS", "")
|
|
||||||
WEBHOOK_URLS: list[str] = [
|
|
||||||
url.strip() for url in _WEBHOOK_URLS_RAW.split(",") if url.strip()
|
|
||||||
]
|
|
||||||
|
|
||||||
MAX_RETRIES = 3
|
|
||||||
BACKOFF_BASE = 2 # seconds
|
|
||||||
|
|
||||||
|
|
||||||
def _is_slack_url(url: str) -> bool:
|
|
||||||
"""Check if a URL looks like a Slack incoming webhook."""
|
|
||||||
return "hooks.slack.com" in url or "discord.com/api/webhooks" in url
|
|
||||||
|
|
||||||
|
|
||||||
def _build_payload(event_type: str, data: dict[str, Any], slack: bool = False) -> dict:
|
|
||||||
"""Build the webhook payload.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
event_type: Type of event (e.g., "job_completed", "alert")
|
|
||||||
data: Event-specific data
|
|
||||||
slack: If True, wrap in Slack-compatible ``text`` format
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON-serializable payload dict
|
|
||||||
"""
|
|
||||||
payload = {
|
|
||||||
"event": event_type,
|
|
||||||
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
||||||
**data,
|
|
||||||
}
|
|
||||||
|
|
||||||
if slack:
|
|
||||||
# Build a human-readable summary for Slack/Discord
|
|
||||||
lines = [f"*[SPARC] {event_type}*"]
|
|
||||||
for key, value in data.items():
|
|
||||||
lines.append(f" {key}: {value}")
|
|
||||||
return {"text": "\n".join(lines)}
|
|
||||||
|
|
||||||
return payload
|
|
||||||
|
|
||||||
|
|
||||||
def _send_with_retry(url: str, payload: dict) -> bool:
|
|
||||||
"""Send a POST request with exponential backoff retry.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
url: Webhook URL
|
|
||||||
payload: JSON payload to send
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
True if delivered successfully, False after all retries exhausted
|
|
||||||
"""
|
|
||||||
for attempt in range(1, MAX_RETRIES + 1):
|
|
||||||
try:
|
|
||||||
response = requests.post(url, json=payload, timeout=10)
|
|
||||||
if response.status_code < 300:
|
|
||||||
logger.debug("Webhook delivered to %s (attempt %d)", url, attempt)
|
|
||||||
return True
|
|
||||||
logger.warning(
|
|
||||||
"Webhook %s returned %d (attempt %d/%d)",
|
|
||||||
url, response.status_code, attempt, MAX_RETRIES,
|
|
||||||
)
|
|
||||||
except requests.RequestException as e:
|
|
||||||
logger.warning(
|
|
||||||
"Webhook delivery failed for %s (attempt %d/%d): %s",
|
|
||||||
url, attempt, MAX_RETRIES, e,
|
|
||||||
)
|
|
||||||
|
|
||||||
if attempt < MAX_RETRIES:
|
|
||||||
wait = BACKOFF_BASE ** attempt
|
|
||||||
time.sleep(wait)
|
|
||||||
|
|
||||||
logger.error("Webhook permanently failed for %s after %d attempts", url, MAX_RETRIES)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def notify(event_type: str, data: dict[str, Any]) -> None:
|
|
||||||
"""Fire all configured webhooks for an event.
|
|
||||||
|
|
||||||
Safe to call even when no webhooks are configured (returns immediately).
|
|
||||||
|
|
||||||
Args:
|
|
||||||
event_type: Event identifier (e.g., "job_completed", "patent_alert")
|
|
||||||
data: Event data to include in the payload
|
|
||||||
"""
|
|
||||||
if not WEBHOOK_URLS:
|
|
||||||
return
|
|
||||||
|
|
||||||
for url in WEBHOOK_URLS:
|
|
||||||
slack = _is_slack_url(url)
|
|
||||||
payload = _build_payload(event_type, data, slack=slack)
|
|
||||||
_send_with_retry(url, payload)
|
|
||||||
|
|
||||||
|
|
||||||
def notify_job_completed(
|
|
||||||
job_id: str,
|
|
||||||
status: str,
|
|
||||||
total_companies: int,
|
|
||||||
successful: int,
|
|
||||||
failed: int,
|
|
||||||
) -> None:
|
|
||||||
"""Send notification when a batch job completes."""
|
|
||||||
notify("job_completed", {
|
|
||||||
"job_id": job_id,
|
|
||||||
"status": status,
|
|
||||||
"total_companies": total_companies,
|
|
||||||
"successful": successful,
|
|
||||||
"failed": failed,
|
|
||||||
"summary": f"Batch job {job_id}: {successful}/{total_companies} succeeded",
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
def notify_alert(
|
|
||||||
company_name: str,
|
|
||||||
alert_type: str,
|
|
||||||
message: str,
|
|
||||||
) -> None:
|
|
||||||
"""Send notification for a tracked company alert."""
|
|
||||||
notify("patent_alert", {
|
|
||||||
"company_name": company_name,
|
|
||||||
"alert_type": alert_type,
|
|
||||||
"message": message,
|
|
||||||
})
|
|
||||||
@@ -7,6 +7,15 @@
|
|||||||
<title>SPARC Dashboard</title>
|
<title>SPARC Dashboard</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<script>
|
||||||
|
// Prevent FOUC: apply saved theme before first render
|
||||||
|
(function() {
|
||||||
|
var theme = localStorage.getItem('theme');
|
||||||
|
if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
|
||||||
|
document.documentElement.classList.add('dark');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
||||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
import { AuthProvider } from './context/AuthContext';
|
import { AuthProvider } from './context/AuthContext';
|
||||||
|
import { ThemeProvider } from './context/ThemeContext';
|
||||||
import { Layout } from './components/Layout';
|
import { Layout } from './components/Layout';
|
||||||
import { ProtectedRoute } from './components/ProtectedRoute';
|
import { ProtectedRoute } from './components/ProtectedRoute';
|
||||||
import { Login } from './pages/Login';
|
import { Login } from './pages/Login';
|
||||||
@@ -22,6 +23,7 @@ const queryClient = new QueryClient({
|
|||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
|
<ThemeProvider>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
@@ -61,6 +63,7 @@ function App() {
|
|||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
</ThemeProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { Outlet, NavLink, useNavigate } from 'react-router-dom';
|
import { Outlet, NavLink, useNavigate } from 'react-router-dom';
|
||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
import { Search, Layers, BarChart3, Info, Users, LogOut } from 'lucide-react';
|
import { useTheme } from '../context/ThemeContext';
|
||||||
|
import { Search, Layers, BarChart3, Info, Users, LogOut, Sun, Moon } from 'lucide-react';
|
||||||
|
|
||||||
export function Layout() {
|
export function Layout() {
|
||||||
const { user, isAdmin, logout } = useAuth();
|
const { user, isAdmin, logout } = useAuth();
|
||||||
|
const { theme, toggleTheme } = useTheme();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
@@ -23,7 +25,7 @@ export function Layout() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gradient-to-br from-bg-dark to-indigo-950">
|
<div className="min-h-screen bg-gradient-to-br from-bg-dark to-slate-100 dark:to-indigo-950">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<header className="bg-bg-card/80 backdrop-blur-lg border-b border-primary/20">
|
<header className="bg-bg-card/80 backdrop-blur-lg border-b border-primary/20">
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
@@ -63,6 +65,13 @@ export function Layout() {
|
|||||||
|
|
||||||
{/* User menu */}
|
{/* User menu */}
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
|
<button
|
||||||
|
onClick={toggleTheme}
|
||||||
|
className="p-2 rounded-lg text-text-secondary hover:text-text-primary hover:bg-bg-card-hover transition-all"
|
||||||
|
aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
|
||||||
|
>
|
||||||
|
{theme === 'dark' ? <Sun size={18} /> : <Moon size={18} />}
|
||||||
|
</button>
|
||||||
<div className="text-right hidden sm:block">
|
<div className="text-right hidden sm:block">
|
||||||
<div className="text-sm font-medium text-text-primary">{user?.email}</div>
|
<div className="text-sm font-medium text-text-primary">{user?.email}</div>
|
||||||
<div className="text-xs text-text-secondary capitalize">{user?.role}</div>
|
<div className="text-xs text-text-secondary capitalize">{user?.role}</div>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRout
|
|||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gradient-to-br from-bg-dark to-indigo-950 flex items-center justify-center">
|
<div className="min-h-screen bg-gradient-to-br from-bg-dark to-slate-100 dark:to-indigo-950 flex items-center justify-center">
|
||||||
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
|
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { createContext, useContext, useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
type Theme = 'light' | 'dark';
|
||||||
|
|
||||||
|
interface ThemeContextType {
|
||||||
|
theme: Theme;
|
||||||
|
toggleTheme: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
function getInitialTheme(): Theme {
|
||||||
|
const stored = localStorage.getItem('theme');
|
||||||
|
if (stored === 'light' || stored === 'dark') return stored;
|
||||||
|
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const [theme, setTheme] = useState<Theme>(getInitialTheme);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const root = document.documentElement;
|
||||||
|
if (theme === 'dark') {
|
||||||
|
root.classList.add('dark');
|
||||||
|
} else {
|
||||||
|
root.classList.remove('dark');
|
||||||
|
}
|
||||||
|
localStorage.setItem('theme', theme);
|
||||||
|
}, [theme]);
|
||||||
|
|
||||||
|
const toggleTheme = () => {
|
||||||
|
setTheme((prev) => (prev === 'dark' ? 'light' : 'dark'));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
||||||
|
{children}
|
||||||
|
</ThemeContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTheme() {
|
||||||
|
const context = useContext(ThemeContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useTheme must be used within a ThemeProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
+22
-2
@@ -2,6 +2,26 @@
|
|||||||
@tailwind components;
|
@tailwind components;
|
||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
|
||||||
|
/* Light mode (default) */
|
||||||
|
:root {
|
||||||
|
--color-bg-dark: #f1f5f9;
|
||||||
|
--color-bg-card: #ffffff;
|
||||||
|
--color-bg-card-hover: #e2e8f0;
|
||||||
|
--color-text-primary: #0f172a;
|
||||||
|
--color-text-secondary: #475569;
|
||||||
|
--color-border: #cbd5e1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dark mode */
|
||||||
|
.dark {
|
||||||
|
--color-bg-dark: #0f172a;
|
||||||
|
--color-bg-card: #1e293b;
|
||||||
|
--color-bg-card-hover: #334155;
|
||||||
|
--color-text-primary: #f8fafc;
|
||||||
|
--color-text-secondary: #94a3b8;
|
||||||
|
--color-border: #334155;
|
||||||
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
@@ -15,7 +35,7 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
::-webkit-scrollbar-track {
|
::-webkit-scrollbar-track {
|
||||||
background: #1e293b;
|
background: var(--color-bg-card);
|
||||||
}
|
}
|
||||||
|
|
||||||
::-webkit-scrollbar-thumb {
|
::-webkit-scrollbar-thumb {
|
||||||
@@ -30,5 +50,5 @@ body {
|
|||||||
/* Selection */
|
/* Selection */
|
||||||
::selection {
|
::selection {
|
||||||
background: rgba(99, 102, 241, 0.3);
|
background: rgba(99, 102, 241, 0.3);
|
||||||
color: #f8fafc;
|
color: var(--color-text-primary);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export function Login() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gradient-to-br from-bg-dark to-indigo-950 flex items-center justify-center px-4">
|
<div className="min-h-screen bg-gradient-to-br from-bg-dark to-slate-100 dark:to-indigo-950 flex items-center justify-center px-4">
|
||||||
<div className="w-full max-w-md">
|
<div className="w-full max-w-md">
|
||||||
{/* Brand */}
|
{/* Brand */}
|
||||||
<div className="text-center mb-8">
|
<div className="text-center mb-8">
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ export function Register() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gradient-to-br from-bg-dark to-indigo-950 flex items-center justify-center px-4">
|
<div className="min-h-screen bg-gradient-to-br from-bg-dark to-slate-100 dark:to-indigo-950 flex items-center justify-center px-4">
|
||||||
<div className="w-full max-w-md">
|
<div className="w-full max-w-md">
|
||||||
{/* Brand */}
|
{/* Brand */}
|
||||||
<div className="text-center mb-8">
|
<div className="text-center mb-8">
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ export default {
|
|||||||
"./index.html",
|
"./index.html",
|
||||||
"./src/**/*.{js,ts,jsx,tsx}",
|
"./src/**/*.{js,ts,jsx,tsx}",
|
||||||
],
|
],
|
||||||
|
darkMode: 'class',
|
||||||
theme: {
|
theme: {
|
||||||
extend: {
|
extend: {
|
||||||
colors: {
|
colors: {
|
||||||
@@ -16,15 +17,15 @@ export default {
|
|||||||
warning: '#f59e0b',
|
warning: '#f59e0b',
|
||||||
error: '#ef4444',
|
error: '#ef4444',
|
||||||
bg: {
|
bg: {
|
||||||
dark: '#0f172a',
|
dark: 'var(--color-bg-dark)',
|
||||||
card: '#1e293b',
|
card: 'var(--color-bg-card)',
|
||||||
'card-hover': '#334155',
|
'card-hover': 'var(--color-bg-card-hover)',
|
||||||
},
|
},
|
||||||
text: {
|
text: {
|
||||||
primary: '#f8fafc',
|
primary: 'var(--color-text-primary)',
|
||||||
secondary: '#94a3b8',
|
secondary: 'var(--color-text-secondary)',
|
||||||
},
|
},
|
||||||
border: '#334155',
|
border: 'var(--color-border)',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user