Initial commit: PriceGhost price tracking application

Full-stack application for tracking product prices:
- Backend: Node.js + Express + TypeScript
- Frontend: React + Vite + TypeScript
- Database: PostgreSQL
- Price scraping with Cheerio
- JWT authentication
- Background price checking with node-cron
- Price history charts with Recharts
- Docker support with docker-compose

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
clucraft 2026-01-20 13:58:13 -05:00
commit 10660e5626
44 changed files with 3662 additions and 0 deletions

106
frontend/src/App.tsx Normal file
View file

@ -0,0 +1,106 @@
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext';
import Login from './pages/Login';
import Register from './pages/Register';
import Dashboard from './pages/Dashboard';
import ProductDetail from './pages/ProductDetail';
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { user, isLoading } = useAuth();
if (isLoading) {
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
}}
>
<span className="spinner" style={{ width: '3rem', height: '3rem' }} />
</div>
);
}
if (!user) {
return <Navigate to="/login" replace />;
}
return <>{children}</>;
}
function PublicRoute({ children }: { children: React.ReactNode }) {
const { user, isLoading } = useAuth();
if (isLoading) {
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
}}
>
<span className="spinner" style={{ width: '3rem', height: '3rem' }} />
</div>
);
}
if (user) {
return <Navigate to="/" replace />;
}
return <>{children}</>;
}
function AppRoutes() {
return (
<Routes>
<Route
path="/login"
element={
<PublicRoute>
<Login />
</PublicRoute>
}
/>
<Route
path="/register"
element={
<PublicRoute>
<Register />
</PublicRoute>
}
/>
<Route
path="/"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
<Route
path="/product/:id"
element={
<ProtectedRoute>
<ProductDetail />
</ProtectedRoute>
}
/>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);
}
export default function App() {
return (
<BrowserRouter>
<AuthProvider>
<AppRoutes />
</AuthProvider>
</BrowserRouter>
);
}

102
frontend/src/api/client.ts Normal file
View file

@ -0,0 +1,102 @@
import axios from 'axios';
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
// Add auth token to requests
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Handle auth errors
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
// Auth API
export const authApi = {
register: (email: string, password: string) =>
api.post('/auth/register', { email, password }),
login: (email: string, password: string) =>
api.post('/auth/login', { email, password }),
};
// Products API
export interface Product {
id: number;
user_id: number;
url: string;
name: string | null;
image_url: string | null;
refresh_interval: number;
last_checked: string | null;
created_at: string;
current_price: number | null;
currency: string | null;
}
export interface ProductWithStats extends Product {
stats: {
min_price: number;
max_price: number;
avg_price: number;
price_count: number;
} | null;
}
export interface PriceHistory {
id: number;
product_id: number;
price: number;
currency: string;
recorded_at: string;
}
export const productsApi = {
getAll: () => api.get<Product[]>('/products'),
getById: (id: number) => api.get<ProductWithStats>(`/products/${id}`),
create: (url: string, refreshInterval?: number) =>
api.post<Product>('/products', { url, refresh_interval: refreshInterval }),
update: (id: number, data: { name?: string; refresh_interval?: number }) =>
api.put<Product>(`/products/${id}`, data),
delete: (id: number) => api.delete(`/products/${id}`),
};
// Prices API
export const pricesApi = {
getHistory: (productId: number, days?: number) =>
api.get<{ product: Product; prices: PriceHistory[] }>(
`/products/${productId}/prices`,
{ params: days ? { days } : undefined }
),
refresh: (productId: number) =>
api.post<{ message: string; price: PriceHistory }>(
`/products/${productId}/refresh`
),
};
export default api;

View file

@ -0,0 +1,184 @@
import { useState, FormEvent } from 'react';
import { Link } from 'react-router-dom';
interface AuthFormProps {
mode: 'login' | 'register';
onSubmit: (email: string, password: string) => Promise<void>;
}
export default function AuthForm({ mode, onSubmit }: AuthFormProps) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
setError('');
if (mode === 'register' && password !== confirmPassword) {
setError('Passwords do not match');
return;
}
if (password.length < 8) {
setError('Password must be at least 8 characters');
return;
}
setIsLoading(true);
try {
await onSubmit(email, password);
} catch (err) {
if (err instanceof Error) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const axiosError = err as any;
setError(axiosError.response?.data?.error || 'An error occurred');
} else {
setError('An error occurred');
}
} finally {
setIsLoading(false);
}
};
return (
<div className="auth-form-container">
<style>{`
.auth-form-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
.auth-form-card {
width: 100%;
max-width: 400px;
background: var(--surface);
border-radius: 1rem;
box-shadow: var(--shadow-lg);
padding: 2rem;
}
.auth-form-header {
text-align: center;
margin-bottom: 2rem;
}
.auth-form-logo {
font-size: 2.5rem;
margin-bottom: 0.5rem;
}
.auth-form-title {
font-size: 1.5rem;
font-weight: 600;
color: var(--text);
}
.auth-form-subtitle {
color: var(--text-muted);
margin-top: 0.25rem;
}
.auth-form-footer {
text-align: center;
margin-top: 1.5rem;
color: var(--text-muted);
}
.auth-form-footer a {
font-weight: 500;
}
`}</style>
<div className="auth-form-card">
<div className="auth-form-header">
<div className="auth-form-logo">👻</div>
<h1 className="auth-form-title">PriceGhost</h1>
<p className="auth-form-subtitle">
{mode === 'login'
? 'Sign in to track prices'
: 'Create your account'}
</p>
</div>
{error && <div className="alert alert-error">{error}</div>}
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
required
autoComplete="email"
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
required
autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
/>
</div>
{mode === 'register' && (
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
type="password"
id="confirmPassword"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="••••••••"
required
autoComplete="new-password"
/>
</div>
)}
<button
type="submit"
className="btn btn-primary"
style={{ width: '100%', marginTop: '0.5rem' }}
disabled={isLoading}
>
{isLoading ? (
<span className="spinner" />
) : mode === 'login' ? (
'Sign In'
) : (
'Create Account'
)}
</button>
</form>
<div className="auth-form-footer">
{mode === 'login' ? (
<>
Don't have an account? <Link to="/register">Sign up</Link>
</>
) : (
<>
Already have an account? <Link to="/login">Sign in</Link>
</>
)}
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,115 @@
import { ReactNode } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
interface LayoutProps {
children: ReactNode;
}
export default function Layout({ children }: LayoutProps) {
const { user, logout } = useAuth();
const navigate = useNavigate();
const handleLogout = () => {
logout();
navigate('/login');
};
return (
<div className="layout">
<style>{`
.layout {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.navbar {
background: var(--surface);
border-bottom: 1px solid var(--border);
padding: 0 1rem;
position: sticky;
top: 0;
z-index: 100;
}
.navbar-content {
max-width: 1200px;
margin: 0 auto;
height: 64px;
display: flex;
align-items: center;
justify-content: space-between;
}
.navbar-brand {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1.25rem;
font-weight: 600;
color: var(--text);
text-decoration: none;
}
.navbar-brand:hover {
text-decoration: none;
color: var(--primary);
}
.navbar-brand-icon {
font-size: 1.5rem;
}
.navbar-user {
display: flex;
align-items: center;
gap: 1rem;
}
.navbar-email {
color: var(--text-muted);
font-size: 0.875rem;
}
.main-content {
flex: 1;
padding: 2rem 1rem;
}
.main-content-inner {
max-width: 1200px;
margin: 0 auto;
}
@media (max-width: 640px) {
.navbar-email {
display: none;
}
}
`}</style>
<nav className="navbar">
<div className="navbar-content">
<Link to="/" className="navbar-brand">
<span className="navbar-brand-icon">👻</span>
<span>PriceGhost</span>
</Link>
{user && (
<div className="navbar-user">
<span className="navbar-email">{user.email}</span>
<button className="btn btn-secondary" onClick={handleLogout}>
Logout
</button>
</div>
)}
</div>
</nav>
<main className="main-content">
<div className="main-content-inner">{children}</div>
</main>
</div>
);
}

View file

@ -0,0 +1,262 @@
import { useState } from 'react';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
ReferenceLine,
} from 'recharts';
import { PriceHistory } from '../api/client';
interface PriceChartProps {
prices: PriceHistory[];
currency: string;
onRangeChange?: (days: number | undefined) => void;
}
const DATE_RANGES = [
{ value: 7, label: '7 days' },
{ value: 30, label: '30 days' },
{ value: 90, label: '90 days' },
{ value: undefined, label: 'All time' },
];
export default function PriceChart({
prices,
currency,
onRangeChange,
}: PriceChartProps) {
const [selectedRange, setSelectedRange] = useState<number | undefined>(30);
const handleRangeChange = (days: number | undefined) => {
setSelectedRange(days);
onRangeChange?.(days);
};
const currencySymbol =
currency === 'EUR' ? '€' : currency === 'GBP' ? '£' : '$';
const chartData = prices.map((p) => ({
date: new Date(p.recorded_at).getTime(),
price: parseFloat(p.price.toString()),
}));
const minPrice = Math.min(...chartData.map((d) => d.price));
const maxPrice = Math.max(...chartData.map((d) => d.price));
const avgPrice =
chartData.reduce((sum, d) => sum + d.price, 0) / chartData.length;
const formatDate = (timestamp: number) => {
const date = new Date(timestamp);
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
};
const formatPrice = (value: number) => {
return `${currencySymbol}${value.toFixed(2)}`;
};
if (prices.length === 0) {
return (
<div className="price-chart-empty">
<style>{`
.price-chart-empty {
background: var(--surface);
border-radius: 0.75rem;
padding: 3rem;
text-align: center;
color: var(--text-muted);
}
`}</style>
<p>No price history available yet.</p>
</div>
);
}
return (
<div className="price-chart">
<style>{`
.price-chart {
background: var(--surface);
border-radius: 0.75rem;
padding: 1.5rem;
box-shadow: var(--shadow);
}
.price-chart-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
flex-wrap: wrap;
gap: 1rem;
}
.price-chart-title {
font-size: 1.125rem;
font-weight: 600;
color: var(--text);
}
.price-chart-range {
display: flex;
gap: 0.5rem;
}
.price-chart-range button {
padding: 0.375rem 0.75rem;
border: 1px solid var(--border);
background: var(--surface);
border-radius: 0.375rem;
font-size: 0.875rem;
color: var(--text-muted);
cursor: pointer;
transition: all 0.2s;
}
.price-chart-range button:hover {
border-color: var(--primary);
color: var(--primary);
}
.price-chart-range button.active {
background: var(--primary);
border-color: var(--primary);
color: white;
}
.price-chart-container {
height: 300px;
}
.price-chart-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border);
}
.price-stat {
text-align: center;
}
.price-stat-label {
font-size: 0.75rem;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.price-stat-value {
font-size: 1.25rem;
font-weight: 600;
margin-top: 0.25rem;
}
.price-stat-value.min {
color: var(--secondary);
}
.price-stat-value.max {
color: var(--danger);
}
.price-stat-value.avg {
color: var(--primary);
}
@media (max-width: 640px) {
.price-chart-stats {
grid-template-columns: 1fr;
}
}
`}</style>
<div className="price-chart-header">
<h3 className="price-chart-title">Price History</h3>
<div className="price-chart-range">
{DATE_RANGES.map((range) => (
<button
key={range.label}
className={selectedRange === range.value ? 'active' : ''}
onClick={() => handleRangeChange(range.value)}
>
{range.label}
</button>
))}
</div>
</div>
<div className="price-chart-container">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={chartData}>
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
<XAxis
dataKey="date"
tickFormatter={formatDate}
stroke="#94a3b8"
fontSize={12}
/>
<YAxis
tickFormatter={formatPrice}
stroke="#94a3b8"
fontSize={12}
domain={['auto', 'auto']}
/>
<Tooltip
formatter={(value: number) => [formatPrice(value), 'Price']}
labelFormatter={(label) =>
new Date(label).toLocaleDateString('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
contentStyle={{
background: 'white',
border: '1px solid #e2e8f0',
borderRadius: '0.5rem',
boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)',
}}
/>
<ReferenceLine
y={avgPrice}
stroke="#6366f1"
strokeDasharray="5 5"
label=""
/>
<Line
type="monotone"
dataKey="price"
stroke="#6366f1"
strokeWidth={2}
dot={{ fill: '#6366f1', strokeWidth: 0, r: 3 }}
activeDot={{ r: 5, stroke: '#6366f1', strokeWidth: 2, fill: 'white' }}
/>
</LineChart>
</ResponsiveContainer>
</div>
<div className="price-chart-stats">
<div className="price-stat">
<div className="price-stat-label">Lowest</div>
<div className="price-stat-value min">{formatPrice(minPrice)}</div>
</div>
<div className="price-stat">
<div className="price-stat-label">Average</div>
<div className="price-stat-value avg">{formatPrice(avgPrice)}</div>
</div>
<div className="price-stat">
<div className="price-stat-label">Highest</div>
<div className="price-stat-value max">{formatPrice(maxPrice)}</div>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,155 @@
import { Link } from 'react-router-dom';
import { Product } from '../api/client';
interface ProductCardProps {
product: Product;
onDelete: (id: number) => void;
}
export default function ProductCard({ product, onDelete }: ProductCardProps) {
const formatPrice = (price: number | null, currency: string | null) => {
if (price === null) return 'N/A';
const currencySymbol =
currency === 'EUR' ? '€' : currency === 'GBP' ? '£' : '$';
return `${currencySymbol}${price.toFixed(2)}`;
};
const formatDate = (dateStr: string | null) => {
if (!dateStr) return 'Never';
const date = new Date(dateStr);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};
const truncateUrl = (url: string, maxLength: number = 50) => {
try {
const parsed = new URL(url);
const display = parsed.hostname + parsed.pathname;
return display.length > maxLength
? display.slice(0, maxLength) + '...'
: display;
} catch {
return url.length > maxLength ? url.slice(0, maxLength) + '...' : url;
}
};
return (
<div className="product-card">
<style>{`
.product-card {
background: var(--surface);
border-radius: 0.75rem;
box-shadow: var(--shadow);
overflow: hidden;
display: flex;
flex-direction: column;
transition: box-shadow 0.2s;
}
.product-card:hover {
box-shadow: var(--shadow-lg);
}
.product-image {
width: 100%;
height: 160px;
object-fit: contain;
background: #f8fafc;
padding: 1rem;
}
.product-image-placeholder {
width: 100%;
height: 160px;
background: linear-gradient(135deg, #e2e8f0 0%, #f1f5f9 100%);
display: flex;
align-items: center;
justify-content: center;
color: var(--text-muted);
font-size: 2rem;
}
.product-content {
padding: 1rem;
flex: 1;
display: flex;
flex-direction: column;
}
.product-name {
font-weight: 600;
color: var(--text);
margin-bottom: 0.25rem;
line-height: 1.3;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.product-url {
font-size: 0.75rem;
color: var(--text-muted);
margin-bottom: 0.75rem;
}
.product-price {
font-size: 1.5rem;
font-weight: 700;
color: var(--primary);
margin-bottom: 0.5rem;
}
.product-meta {
font-size: 0.75rem;
color: var(--text-muted);
margin-bottom: 1rem;
}
.product-actions {
display: flex;
gap: 0.5rem;
margin-top: auto;
}
.product-actions .btn {
flex: 1;
padding: 0.5rem;
font-size: 0.875rem;
}
`}</style>
{product.image_url ? (
<img
src={product.image_url}
alt={product.name || 'Product'}
className="product-image"
/>
) : (
<div className="product-image-placeholder">📦</div>
)}
<div className="product-content">
<h3 className="product-name">{product.name || 'Unknown Product'}</h3>
<p className="product-url">{truncateUrl(product.url)}</p>
<div className="product-price">
{formatPrice(product.current_price, product.currency)}
</div>
<p className="product-meta">
Last checked: {formatDate(product.last_checked)}
</p>
<div className="product-actions">
<Link to={`/product/${product.id}`} className="btn btn-primary">
View Details
</Link>
<button
className="btn btn-danger"
onClick={() => onDelete(product.id)}
>
Delete
</button>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,130 @@
import { useState, FormEvent } from 'react';
interface ProductFormProps {
onSubmit: (url: string, refreshInterval: number) => Promise<void>;
}
const REFRESH_INTERVALS = [
{ value: 900, label: '15 minutes' },
{ value: 1800, label: '30 minutes' },
{ value: 3600, label: '1 hour' },
{ value: 7200, label: '2 hours' },
{ value: 21600, label: '6 hours' },
{ value: 43200, label: '12 hours' },
{ value: 86400, label: '24 hours' },
];
export default function ProductForm({ onSubmit }: ProductFormProps) {
const [url, setUrl] = useState('');
const [refreshInterval, setRefreshInterval] = useState(3600);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
setError('');
// Validate URL
try {
new URL(url);
} catch {
setError('Please enter a valid URL');
return;
}
setIsLoading(true);
try {
await onSubmit(url, refreshInterval);
setUrl('');
setRefreshInterval(3600);
} catch (err) {
if (err instanceof Error) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const axiosError = err as any;
setError(axiosError.response?.data?.error || 'Failed to add product');
} else {
setError('Failed to add product');
}
} finally {
setIsLoading(false);
}
};
return (
<div className="product-form">
<style>{`
.product-form {
background: var(--surface);
border-radius: 0.75rem;
padding: 1.5rem;
box-shadow: var(--shadow);
margin-bottom: 2rem;
}
.product-form h2 {
font-size: 1.25rem;
margin-bottom: 1rem;
color: var(--text);
}
.product-form-row {
display: grid;
gap: 1rem;
grid-template-columns: 1fr auto auto;
align-items: end;
}
@media (max-width: 768px) {
.product-form-row {
grid-template-columns: 1fr;
}
}
`}</style>
<h2>Track a New Product</h2>
{error && <div className="alert alert-error mb-3">{error}</div>}
<form onSubmit={handleSubmit}>
<div className="product-form-row">
<div className="form-group" style={{ margin: 0 }}>
<label htmlFor="product-url">Product URL</label>
<input
type="url"
id="product-url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://www.example.com/product"
required
/>
</div>
<div className="form-group" style={{ margin: 0 }}>
<label htmlFor="refresh-interval">Check Every</label>
<select
id="refresh-interval"
value={refreshInterval}
onChange={(e) => setRefreshInterval(parseInt(e.target.value, 10))}
>
{REFRESH_INTERVALS.map((interval) => (
<option key={interval.value} value={interval.value}>
{interval.label}
</option>
))}
</select>
</div>
<button
type="submit"
className="btn btn-primary"
disabled={isLoading}
style={{ height: '46px' }}
>
{isLoading ? <span className="spinner" /> : 'Add Product'}
</button>
</div>
</form>
</div>
);
}

View file

@ -0,0 +1,82 @@
import {
createContext,
useContext,
useState,
useEffect,
ReactNode,
} from 'react';
import { authApi } from '../api/client';
interface User {
id: number;
email: string;
}
interface AuthContextType {
user: User | null;
isLoading: boolean;
login: (email: string, password: string) => Promise<void>;
register: (email: string, password: string) => Promise<void>;
logout: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Check for existing session on mount
const storedUser = localStorage.getItem('user');
const token = localStorage.getItem('token');
if (storedUser && token) {
try {
setUser(JSON.parse(storedUser));
} catch {
localStorage.removeItem('user');
localStorage.removeItem('token');
}
}
setIsLoading(false);
}, []);
const login = async (email: string, password: string) => {
const response = await authApi.login(email, password);
const { token, user: userData } = response.data;
localStorage.setItem('token', token);
localStorage.setItem('user', JSON.stringify(userData));
setUser(userData);
};
const register = async (email: string, password: string) => {
const response = await authApi.register(email, password);
const { token, user: userData } = response.data;
localStorage.setItem('token', token);
localStorage.setItem('user', JSON.stringify(userData));
setUser(userData);
};
const logout = () => {
localStorage.removeItem('token');
localStorage.removeItem('user');
setUser(null);
};
return (
<AuthContext.Provider value={{ user, isLoading, login, register, logout }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}

View file

@ -0,0 +1 @@
export { useAuth } from '../context/AuthContext';

225
frontend/src/index.css Normal file
View file

@ -0,0 +1,225 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--primary: #6366f1;
--primary-dark: #4f46e5;
--secondary: #10b981;
--danger: #ef4444;
--background: #f8fafc;
--surface: #ffffff;
--text: #1e293b;
--text-muted: #64748b;
--border: #e2e8f0;
--shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
Ubuntu, Cantarell, sans-serif;
background-color: var(--background);
color: var(--text);
line-height: 1.6;
}
a {
color: var(--primary);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
button {
cursor: pointer;
font-family: inherit;
}
input, button {
font-size: 1rem;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
}
/* Form styles */
.form-group {
margin-bottom: 1rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: var(--text);
}
.form-group input,
.form-group select {
width: 100%;
padding: 0.75rem;
border: 1px solid var(--border);
border-radius: 0.5rem;
font-size: 1rem;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}
/* Button styles */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.75rem 1.5rem;
border: none;
border-radius: 0.5rem;
font-weight: 500;
transition: all 0.2s;
}
.btn-primary {
background-color: var(--primary);
color: white;
}
.btn-primary:hover {
background-color: var(--primary-dark);
}
.btn-secondary {
background-color: var(--surface);
color: var(--text);
border: 1px solid var(--border);
}
.btn-secondary:hover {
background-color: var(--background);
}
.btn-danger {
background-color: var(--danger);
color: white;
}
.btn-danger:hover {
background-color: #dc2626;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
/* Card styles */
.card {
background: var(--surface);
border-radius: 0.75rem;
box-shadow: var(--shadow);
overflow: hidden;
}
.card-header {
padding: 1rem 1.5rem;
border-bottom: 1px solid var(--border);
}
.card-body {
padding: 1.5rem;
}
/* Alert styles */
.alert {
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
.alert-error {
background-color: #fef2f2;
color: #991b1b;
border: 1px solid #fecaca;
}
.alert-success {
background-color: #f0fdf4;
color: #166534;
border: 1px solid #bbf7d0;
}
/* Loading spinner */
.spinner {
display: inline-block;
width: 1.5rem;
height: 1.5rem;
border: 2px solid var(--border);
border-top-color: var(--primary);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Utility classes */
.text-center {
text-align: center;
}
.text-muted {
color: var(--text-muted);
}
.mt-1 { margin-top: 0.25rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.mt-4 { margin-top: 1.5rem; }
.mb-1 { margin-bottom: 0.25rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mb-4 { margin-bottom: 1.5rem; }
.flex {
display: flex;
}
.flex-col {
flex-direction: column;
}
.items-center {
align-items: center;
}
.justify-between {
justify-content: space-between;
}
.gap-2 {
gap: 0.5rem;
}
.gap-3 {
gap: 1rem;
}
.gap-4 {
gap: 1.5rem;
}

10
frontend/src/main.tsx Normal file
View file

@ -0,0 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View file

@ -0,0 +1,136 @@
import { useState, useEffect } from 'react';
import Layout from '../components/Layout';
import ProductCard from '../components/ProductCard';
import ProductForm from '../components/ProductForm';
import { productsApi, Product } from '../api/client';
export default function Dashboard() {
const [products, setProducts] = useState<Product[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState('');
const fetchProducts = async () => {
try {
const response = await productsApi.getAll();
setProducts(response.data);
} catch {
setError('Failed to load products');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchProducts();
}, []);
const handleAddProduct = async (url: string, refreshInterval: number) => {
const response = await productsApi.create(url, refreshInterval);
setProducts((prev) => [response.data, ...prev]);
};
const handleDeleteProduct = async (id: number) => {
if (!confirm('Are you sure you want to stop tracking this product?')) {
return;
}
try {
await productsApi.delete(id);
setProducts((prev) => prev.filter((p) => p.id !== id));
} catch {
alert('Failed to delete product');
}
};
return (
<Layout>
<style>{`
.dashboard-header {
margin-bottom: 2rem;
}
.dashboard-title {
font-size: 1.75rem;
font-weight: 700;
color: var(--text);
}
.dashboard-subtitle {
color: var(--text-muted);
margin-top: 0.25rem;
}
.products-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1.5rem;
}
.empty-state {
text-align: center;
padding: 4rem 2rem;
background: var(--surface);
border-radius: 0.75rem;
box-shadow: var(--shadow);
}
.empty-state-icon {
font-size: 4rem;
margin-bottom: 1rem;
}
.empty-state-title {
font-size: 1.25rem;
font-weight: 600;
color: var(--text);
margin-bottom: 0.5rem;
}
.empty-state-text {
color: var(--text-muted);
}
.loading-state {
display: flex;
justify-content: center;
padding: 4rem;
}
`}</style>
<div className="dashboard-header">
<h1 className="dashboard-title">Your Tracked Products</h1>
<p className="dashboard-subtitle">
Monitor prices and get notified when they drop
</p>
</div>
<ProductForm onSubmit={handleAddProduct} />
{error && <div className="alert alert-error">{error}</div>}
{isLoading ? (
<div className="loading-state">
<span className="spinner" style={{ width: '3rem', height: '3rem' }} />
</div>
) : products.length === 0 ? (
<div className="empty-state">
<div className="empty-state-icon">📦</div>
<h2 className="empty-state-title">No products yet</h2>
<p className="empty-state-text">
Add your first product URL above to start tracking prices!
</p>
</div>
) : (
<div className="products-grid">
{products.map((product) => (
<ProductCard
key={product.id}
product={product}
onDelete={handleDeleteProduct}
/>
))}
</div>
)}
</Layout>
);
}

View file

@ -0,0 +1,15 @@
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import AuthForm from '../components/AuthForm';
export default function Login() {
const { login } = useAuth();
const navigate = useNavigate();
const handleLogin = async (email: string, password: string) => {
await login(email, password);
navigate('/');
};
return <AuthForm mode="login" onSubmit={handleLogin} />;
}

View file

@ -0,0 +1,353 @@
import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import Layout from '../components/Layout';
import PriceChart from '../components/PriceChart';
import {
productsApi,
pricesApi,
ProductWithStats,
PriceHistory,
} from '../api/client';
export default function ProductDetail() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [product, setProduct] = useState<ProductWithStats | null>(null);
const [prices, setPrices] = useState<PriceHistory[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const [error, setError] = useState('');
const productId = parseInt(id || '0', 10);
const fetchData = async (days?: number) => {
try {
const [productRes, pricesRes] = await Promise.all([
productsApi.getById(productId),
pricesApi.getHistory(productId, days),
]);
setProduct(productRes.data);
setPrices(pricesRes.data.prices);
} catch {
setError('Failed to load product details');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
if (productId) {
fetchData(30);
}
}, [productId]);
const handleRefresh = async () => {
setIsRefreshing(true);
try {
await pricesApi.refresh(productId);
await fetchData(30);
} catch {
alert('Failed to refresh price');
} finally {
setIsRefreshing(false);
}
};
const handleDelete = async () => {
if (!confirm('Are you sure you want to stop tracking this product?')) {
return;
}
try {
await productsApi.delete(productId);
navigate('/');
} catch {
alert('Failed to delete product');
}
};
const handleRangeChange = (days: number | undefined) => {
fetchData(days);
};
const formatPrice = (price: number | null, currency: string | null) => {
if (price === null) return 'N/A';
const currencySymbol =
currency === 'EUR' ? '€' : currency === 'GBP' ? '£' : '$';
return `${currencySymbol}${price.toFixed(2)}`;
};
if (isLoading) {
return (
<Layout>
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '4rem',
}}
>
<span className="spinner" style={{ width: '3rem', height: '3rem' }} />
</div>
</Layout>
);
}
if (error || !product) {
return (
<Layout>
<div className="alert alert-error">{error || 'Product not found'}</div>
<Link to="/" className="btn btn-secondary mt-3">
Back to Dashboard
</Link>
</Layout>
);
}
const priceChange =
product.stats && prices.length > 1
? ((product.current_price || 0) - prices[0].price) / prices[0].price
: null;
return (
<Layout>
<style>{`
.product-detail-header {
margin-bottom: 2rem;
}
.product-detail-back {
display: inline-flex;
align-items: center;
gap: 0.5rem;
color: var(--text-muted);
margin-bottom: 1rem;
font-size: 0.875rem;
}
.product-detail-back:hover {
color: var(--primary);
text-decoration: none;
}
.product-detail-card {
background: var(--surface);
border-radius: 0.75rem;
box-shadow: var(--shadow);
padding: 1.5rem;
margin-bottom: 2rem;
}
.product-detail-content {
display: grid;
grid-template-columns: 200px 1fr;
gap: 2rem;
}
@media (max-width: 768px) {
.product-detail-content {
grid-template-columns: 1fr;
}
}
.product-detail-image {
width: 200px;
height: 200px;
object-fit: contain;
background: #f8fafc;
border-radius: 0.5rem;
}
.product-detail-image-placeholder {
width: 200px;
height: 200px;
background: linear-gradient(135deg, #e2e8f0 0%, #f1f5f9 100%);
border-radius: 0.5rem;
display: flex;
align-items: center;
justify-content: center;
font-size: 4rem;
}
.product-detail-info {
flex: 1;
}
.product-detail-name {
font-size: 1.5rem;
font-weight: 600;
color: var(--text);
margin-bottom: 0.5rem;
}
.product-detail-url {
font-size: 0.875rem;
color: var(--text-muted);
word-break: break-all;
margin-bottom: 1.5rem;
}
.product-detail-price {
font-size: 2.5rem;
font-weight: 700;
color: var(--primary);
margin-bottom: 0.5rem;
}
.product-detail-change {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-size: 0.875rem;
font-weight: 500;
}
.product-detail-change.up {
background: #fef2f2;
color: #dc2626;
}
.product-detail-change.down {
background: #f0fdf4;
color: #16a34a;
}
.product-detail-meta {
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border);
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
font-size: 0.875rem;
}
.product-detail-meta-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.product-detail-meta-label {
color: var(--text-muted);
}
.product-detail-meta-value {
font-weight: 500;
color: var(--text);
}
.product-detail-actions {
display: flex;
gap: 0.75rem;
margin-top: 1.5rem;
}
`}</style>
<div className="product-detail-header">
<Link to="/" className="product-detail-back">
Back to Dashboard
</Link>
</div>
<div className="product-detail-card">
<div className="product-detail-content">
{product.image_url ? (
<img
src={product.image_url}
alt={product.name || 'Product'}
className="product-detail-image"
/>
) : (
<div className="product-detail-image-placeholder">📦</div>
)}
<div className="product-detail-info">
<h1 className="product-detail-name">
{product.name || 'Unknown Product'}
</h1>
<p className="product-detail-url">
<a
href={product.url}
target="_blank"
rel="noopener noreferrer"
>
{product.url}
</a>
</p>
<div className="product-detail-price">
{formatPrice(product.current_price, product.currency)}
</div>
{priceChange !== null && priceChange !== 0 && (
<span
className={`product-detail-change ${priceChange > 0 ? 'up' : 'down'}`}
>
{priceChange > 0 ? '↑' : '↓'}{' '}
{Math.abs(priceChange * 100).toFixed(1)}% since tracking started
</span>
)}
<div className="product-detail-meta">
<div className="product-detail-meta-item">
<span className="product-detail-meta-label">Last Checked</span>
<span className="product-detail-meta-value">
{product.last_checked
? new Date(product.last_checked).toLocaleString()
: 'Never'}
</span>
</div>
<div className="product-detail-meta-item">
<span className="product-detail-meta-label">Check Interval</span>
<span className="product-detail-meta-value">
{product.refresh_interval < 3600
? `${product.refresh_interval / 60} minutes`
: `${product.refresh_interval / 3600} hour(s)`}
</span>
</div>
<div className="product-detail-meta-item">
<span className="product-detail-meta-label">Tracking Since</span>
<span className="product-detail-meta-value">
{new Date(product.created_at).toLocaleDateString()}
</span>
</div>
<div className="product-detail-meta-item">
<span className="product-detail-meta-label">Price Records</span>
<span className="product-detail-meta-value">
{product.stats?.price_count || 0}
</span>
</div>
</div>
<div className="product-detail-actions">
<button
className="btn btn-primary"
onClick={handleRefresh}
disabled={isRefreshing}
>
{isRefreshing ? (
<span className="spinner" />
) : (
'Refresh Price Now'
)}
</button>
<button className="btn btn-danger" onClick={handleDelete}>
Stop Tracking
</button>
</div>
</div>
</div>
</div>
<PriceChart
prices={prices}
currency={product.currency || 'USD'}
onRangeChange={handleRangeChange}
/>
</Layout>
);
}

View file

@ -0,0 +1,15 @@
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import AuthForm from '../components/AuthForm';
export default function Register() {
const { register } = useAuth();
const navigate = useNavigate();
const handleRegister = async (email: string, password: string) => {
await register(email, password);
navigate('/');
};
return <AuthForm mode="register" onSubmit={handleRegister} />;
}

9
frontend/src/vite-env.d.ts vendored Normal file
View file

@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}