mirror of
https://github.com/clucraft/PriceGhost.git
synced 2026-04-25 00:36:32 +02:00
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:
commit
10660e5626
44 changed files with 3662 additions and 0 deletions
34
.gitignore
vendored
Normal file
34
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# Build outputs
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
|
||||||
|
# Environment files
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# OS files
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# Testing
|
||||||
|
coverage/
|
||||||
|
|
||||||
|
# Misc
|
||||||
|
*.tgz
|
||||||
|
.cache/
|
||||||
136
README.md
Normal file
136
README.md
Normal file
|
|
@ -0,0 +1,136 @@
|
||||||
|
# PriceGhost
|
||||||
|
|
||||||
|
A full-stack web application for tracking product prices across any website. Monitor prices over time and visualize price history with interactive charts.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Track prices from any product URL
|
||||||
|
- Automatic price extraction using heuristics and structured data
|
||||||
|
- Configurable refresh intervals (15 min to 24 hours)
|
||||||
|
- Price history visualization with Recharts
|
||||||
|
- User authentication with JWT
|
||||||
|
- Background price checking with node-cron
|
||||||
|
- Docker support for easy deployment
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- **Backend**: Node.js, Express, TypeScript
|
||||||
|
- **Frontend**: React, Vite, TypeScript
|
||||||
|
- **Database**: PostgreSQL
|
||||||
|
- **Scraping**: Cheerio
|
||||||
|
- **Charts**: Recharts
|
||||||
|
- **Auth**: JWT + bcrypt
|
||||||
|
- **Containerization**: Docker
|
||||||
|
|
||||||
|
## Quick Start with Docker
|
||||||
|
|
||||||
|
1. Clone the repository:
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/yourusername/priceghost.git
|
||||||
|
cd priceghost
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Start all services:
|
||||||
|
```bash
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Initialize the database:
|
||||||
|
```bash
|
||||||
|
docker-compose exec backend npm run db:init
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Access the application at http://localhost
|
||||||
|
|
||||||
|
## Development Setup
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Node.js 20+
|
||||||
|
- PostgreSQL 16+
|
||||||
|
|
||||||
|
### Backend Setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# Create .env file
|
||||||
|
cp .env.example .env
|
||||||
|
# Edit .env with your database credentials
|
||||||
|
|
||||||
|
# Initialize database
|
||||||
|
npm run db:init
|
||||||
|
|
||||||
|
# Start development server
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend Setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# Start development server
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
### Backend (.env)
|
||||||
|
|
||||||
|
```
|
||||||
|
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/priceghost
|
||||||
|
JWT_SECRET=your-secret-key
|
||||||
|
PORT=3001
|
||||||
|
NODE_ENV=development
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
- `POST /api/auth/register` - Register new user
|
||||||
|
- `POST /api/auth/login` - Login
|
||||||
|
|
||||||
|
### Products (Protected)
|
||||||
|
- `GET /api/products` - List tracked products
|
||||||
|
- `POST /api/products` - Add product to track
|
||||||
|
- `GET /api/products/:id` - Get product details
|
||||||
|
- `PUT /api/products/:id` - Update product settings
|
||||||
|
- `DELETE /api/products/:id` - Remove product
|
||||||
|
|
||||||
|
### Prices (Protected)
|
||||||
|
- `GET /api/products/:id/prices` - Get price history
|
||||||
|
- `POST /api/products/:id/refresh` - Force price refresh
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
PriceGhost/
|
||||||
|
├── backend/
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── config/ # Database configuration
|
||||||
|
│ │ ├── middleware/ # JWT auth middleware
|
||||||
|
│ │ ├── models/ # Database queries
|
||||||
|
│ │ ├── routes/ # API routes
|
||||||
|
│ │ ├── services/ # Scraper & scheduler
|
||||||
|
│ │ └── utils/ # Price parsing utilities
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ └── package.json
|
||||||
|
├── frontend/
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── api/ # Axios client
|
||||||
|
│ │ ├── components/ # React components
|
||||||
|
│ │ ├── context/ # Auth context
|
||||||
|
│ │ ├── hooks/ # Custom hooks
|
||||||
|
│ │ └── pages/ # Page components
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ └── package.json
|
||||||
|
├── docker-compose.yml
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
10
backend/.dockerignore
Normal file
10
backend/.dockerignore
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
npm-debug.log
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
README.md
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
9
backend/.env.example
Normal file
9
backend/.env.example
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
# Database
|
||||||
|
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/priceghost
|
||||||
|
|
||||||
|
# JWT
|
||||||
|
JWT_SECRET=your-super-secret-jwt-key-change-in-production
|
||||||
|
|
||||||
|
# Server
|
||||||
|
PORT=3001
|
||||||
|
NODE_ENV=development
|
||||||
46
backend/Dockerfile
Normal file
46
backend/Dockerfile
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
# Build stage
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package files
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Build TypeScript
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Production stage
|
||||||
|
FROM node:20-alpine AS production
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package files
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install production dependencies only
|
||||||
|
RUN npm ci --only=production
|
||||||
|
|
||||||
|
# Copy built files from builder
|
||||||
|
COPY --from=builder /app/dist ./dist
|
||||||
|
|
||||||
|
# Create non-root user
|
||||||
|
RUN addgroup -g 1001 -S nodejs && \
|
||||||
|
adduser -S nodejs -u 1001
|
||||||
|
|
||||||
|
USER nodejs
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 3001
|
||||||
|
|
||||||
|
# Set environment variables
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV PORT=3001
|
||||||
|
|
||||||
|
# Start the application
|
||||||
|
CMD ["node", "dist/index.js"]
|
||||||
34
backend/package.json
Normal file
34
backend/package.json
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
{
|
||||||
|
"name": "priceghost-backend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "PriceGhost price tracking API",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/index.ts",
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"db:init": "tsx src/config/init-db.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.6.0",
|
||||||
|
"bcrypt": "^5.1.1",
|
||||||
|
"cheerio": "^1.0.0-rc.12",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.3.1",
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"node-cron": "^3.0.3",
|
||||||
|
"pg": "^8.11.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bcrypt": "^5.0.2",
|
||||||
|
"@types/cors": "^2.8.17",
|
||||||
|
"@types/express": "^4.17.21",
|
||||||
|
"@types/jsonwebtoken": "^9.0.5",
|
||||||
|
"@types/node": "^20.10.0",
|
||||||
|
"@types/node-cron": "^3.0.11",
|
||||||
|
"@types/pg": "^8.10.9",
|
||||||
|
"tsx": "^4.6.0",
|
||||||
|
"typescript": "^5.3.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
19
backend/src/config/database.ts
Normal file
19
backend/src/config/database.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
import { Pool } from 'pg';
|
||||||
|
import dotenv from 'dotenv';
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const pool = new Pool({
|
||||||
|
connectionString: process.env.DATABASE_URL,
|
||||||
|
});
|
||||||
|
|
||||||
|
pool.on('connect', () => {
|
||||||
|
console.log('Connected to PostgreSQL database');
|
||||||
|
});
|
||||||
|
|
||||||
|
pool.on('error', (err) => {
|
||||||
|
console.error('Unexpected error on idle client', err);
|
||||||
|
process.exit(-1);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default pool;
|
||||||
67
backend/src/config/init-db.ts
Normal file
67
backend/src/config/init-db.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
import pool from './database';
|
||||||
|
|
||||||
|
const initDatabase = async () => {
|
||||||
|
const client = await pool.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await client.query('BEGIN');
|
||||||
|
|
||||||
|
// Create users table
|
||||||
|
await client.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
email VARCHAR(255) UNIQUE NOT NULL,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
console.log('Created users table');
|
||||||
|
|
||||||
|
// Create products table
|
||||||
|
await client.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS products (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
name VARCHAR(255),
|
||||||
|
image_url TEXT,
|
||||||
|
refresh_interval INTEGER DEFAULT 3600,
|
||||||
|
last_checked TIMESTAMP,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(user_id, url)
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
console.log('Created products table');
|
||||||
|
|
||||||
|
// Create price_history table
|
||||||
|
await client.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS price_history (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
product_id INTEGER REFERENCES products(id) ON DELETE CASCADE,
|
||||||
|
price DECIMAL(10,2) NOT NULL,
|
||||||
|
currency VARCHAR(10) DEFAULT 'USD',
|
||||||
|
recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
console.log('Created price_history table');
|
||||||
|
|
||||||
|
// Create index for price history queries
|
||||||
|
await client.query(`
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_price_history_product_date
|
||||||
|
ON price_history(product_id, recorded_at);
|
||||||
|
`);
|
||||||
|
console.log('Created price_history index');
|
||||||
|
|
||||||
|
await client.query('COMMIT');
|
||||||
|
console.log('Database initialization complete');
|
||||||
|
} catch (error) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
|
console.error('Error initializing database:', error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
await pool.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
initDatabase().catch(console.error);
|
||||||
53
backend/src/index.ts
Normal file
53
backend/src/index.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
import express from 'express';
|
||||||
|
import cors from 'cors';
|
||||||
|
import dotenv from 'dotenv';
|
||||||
|
|
||||||
|
import authRoutes from './routes/auth';
|
||||||
|
import productRoutes from './routes/products';
|
||||||
|
import priceRoutes from './routes/prices';
|
||||||
|
import { startScheduler } from './services/scheduler';
|
||||||
|
|
||||||
|
// Load environment variables
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const PORT = process.env.PORT || 3001;
|
||||||
|
|
||||||
|
// Middleware
|
||||||
|
app.use(cors());
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
// Health check endpoint
|
||||||
|
app.get('/health', (_, res) => {
|
||||||
|
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||||
|
});
|
||||||
|
|
||||||
|
// API Routes
|
||||||
|
app.use('/api/auth', authRoutes);
|
||||||
|
app.use('/api/products', productRoutes);
|
||||||
|
app.use('/api/products', priceRoutes);
|
||||||
|
|
||||||
|
// Error handling middleware
|
||||||
|
app.use(
|
||||||
|
(
|
||||||
|
err: Error,
|
||||||
|
_req: express.Request,
|
||||||
|
res: express.Response,
|
||||||
|
_next: express.NextFunction
|
||||||
|
) => {
|
||||||
|
console.error('Unhandled error:', err);
|
||||||
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Start server
|
||||||
|
app.listen(PORT, () => {
|
||||||
|
console.log(`PriceGhost API server running on port ${PORT}`);
|
||||||
|
|
||||||
|
// Start the background price checker
|
||||||
|
if (process.env.NODE_ENV !== 'test') {
|
||||||
|
startScheduler();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default app;
|
||||||
61
backend/src/middleware/auth.ts
Normal file
61
backend/src/middleware/auth.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
|
export interface AuthRequest extends Request {
|
||||||
|
userId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface JwtPayload {
|
||||||
|
userId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authMiddleware = (
|
||||||
|
req: AuthRequest,
|
||||||
|
res: Response,
|
||||||
|
next: NextFunction
|
||||||
|
): void => {
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
|
||||||
|
if (!authHeader) {
|
||||||
|
res.status(401).json({ error: 'No authorization header provided' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = authHeader.split(' ');
|
||||||
|
if (parts.length !== 2 || parts[0] !== 'Bearer') {
|
||||||
|
res.status(401).json({ error: 'Invalid authorization header format' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = parts[1];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const secret = process.env.JWT_SECRET;
|
||||||
|
if (!secret) {
|
||||||
|
throw new Error('JWT_SECRET not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
const decoded = jwt.verify(token, secret) as JwtPayload;
|
||||||
|
req.userId = decoded.userId;
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof jwt.TokenExpiredError) {
|
||||||
|
res.status(401).json({ error: 'Token expired' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (error instanceof jwt.JsonWebTokenError) {
|
||||||
|
res.status(401).json({ error: 'Invalid token' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(500).json({ error: 'Authentication failed' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const generateToken = (userId: number): string => {
|
||||||
|
const secret = process.env.JWT_SECRET;
|
||||||
|
if (!secret) {
|
||||||
|
throw new Error('JWT_SECRET not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
return jwt.sign({ userId }, secret, { expiresIn: '7d' });
|
||||||
|
};
|
||||||
233
backend/src/models/index.ts
Normal file
233
backend/src/models/index.ts
Normal file
|
|
@ -0,0 +1,233 @@
|
||||||
|
import pool from '../config/database';
|
||||||
|
|
||||||
|
// User types and queries
|
||||||
|
export interface User {
|
||||||
|
id: number;
|
||||||
|
email: string;
|
||||||
|
password_hash: string;
|
||||||
|
created_at: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const userQueries = {
|
||||||
|
findByEmail: async (email: string): Promise<User | null> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
'SELECT * FROM users WHERE email = $1',
|
||||||
|
[email]
|
||||||
|
);
|
||||||
|
return result.rows[0] || null;
|
||||||
|
},
|
||||||
|
|
||||||
|
findById: async (id: number): Promise<User | null> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
'SELECT * FROM users WHERE id = $1',
|
||||||
|
[id]
|
||||||
|
);
|
||||||
|
return result.rows[0] || null;
|
||||||
|
},
|
||||||
|
|
||||||
|
create: async (email: string, passwordHash: string): Promise<User> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
'INSERT INTO users (email, password_hash) VALUES ($1, $2) RETURNING *',
|
||||||
|
[email, passwordHash]
|
||||||
|
);
|
||||||
|
return result.rows[0];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Product types and queries
|
||||||
|
export interface Product {
|
||||||
|
id: number;
|
||||||
|
user_id: number;
|
||||||
|
url: string;
|
||||||
|
name: string | null;
|
||||||
|
image_url: string | null;
|
||||||
|
refresh_interval: number;
|
||||||
|
last_checked: Date | null;
|
||||||
|
created_at: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProductWithLatestPrice extends Product {
|
||||||
|
current_price: number | null;
|
||||||
|
currency: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const productQueries = {
|
||||||
|
findByUserId: async (userId: number): Promise<ProductWithLatestPrice[]> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
`SELECT p.*, ph.price as current_price, ph.currency
|
||||||
|
FROM products p
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT price, currency FROM price_history
|
||||||
|
WHERE product_id = p.id
|
||||||
|
ORDER BY recorded_at DESC
|
||||||
|
LIMIT 1
|
||||||
|
) ph ON true
|
||||||
|
WHERE p.user_id = $1
|
||||||
|
ORDER BY p.created_at DESC`,
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
return result.rows;
|
||||||
|
},
|
||||||
|
|
||||||
|
findById: async (id: number, userId: number): Promise<ProductWithLatestPrice | null> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
`SELECT p.*, ph.price as current_price, ph.currency
|
||||||
|
FROM products p
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT price, currency FROM price_history
|
||||||
|
WHERE product_id = p.id
|
||||||
|
ORDER BY recorded_at DESC
|
||||||
|
LIMIT 1
|
||||||
|
) ph ON true
|
||||||
|
WHERE p.id = $1 AND p.user_id = $2`,
|
||||||
|
[id, userId]
|
||||||
|
);
|
||||||
|
return result.rows[0] || null;
|
||||||
|
},
|
||||||
|
|
||||||
|
create: async (
|
||||||
|
userId: number,
|
||||||
|
url: string,
|
||||||
|
name: string | null,
|
||||||
|
imageUrl: string | null,
|
||||||
|
refreshInterval: number = 3600
|
||||||
|
): Promise<Product> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
`INSERT INTO products (user_id, url, name, image_url, refresh_interval)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
RETURNING *`,
|
||||||
|
[userId, url, name, imageUrl, refreshInterval]
|
||||||
|
);
|
||||||
|
return result.rows[0];
|
||||||
|
},
|
||||||
|
|
||||||
|
update: async (
|
||||||
|
id: number,
|
||||||
|
userId: number,
|
||||||
|
updates: { name?: string; refresh_interval?: number }
|
||||||
|
): Promise<Product | null> => {
|
||||||
|
const fields: string[] = [];
|
||||||
|
const values: (string | number)[] = [];
|
||||||
|
let paramIndex = 1;
|
||||||
|
|
||||||
|
if (updates.name !== undefined) {
|
||||||
|
fields.push(`name = $${paramIndex++}`);
|
||||||
|
values.push(updates.name);
|
||||||
|
}
|
||||||
|
if (updates.refresh_interval !== undefined) {
|
||||||
|
fields.push(`refresh_interval = $${paramIndex++}`);
|
||||||
|
values.push(updates.refresh_interval);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fields.length === 0) return null;
|
||||||
|
|
||||||
|
values.push(id, userId);
|
||||||
|
const result = await pool.query(
|
||||||
|
`UPDATE products SET ${fields.join(', ')}
|
||||||
|
WHERE id = $${paramIndex++} AND user_id = $${paramIndex}
|
||||||
|
RETURNING *`,
|
||||||
|
values
|
||||||
|
);
|
||||||
|
return result.rows[0] || null;
|
||||||
|
},
|
||||||
|
|
||||||
|
delete: async (id: number, userId: number): Promise<boolean> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
'DELETE FROM products WHERE id = $1 AND user_id = $2',
|
||||||
|
[id, userId]
|
||||||
|
);
|
||||||
|
return (result.rowCount ?? 0) > 0;
|
||||||
|
},
|
||||||
|
|
||||||
|
updateLastChecked: async (id: number): Promise<void> => {
|
||||||
|
await pool.query(
|
||||||
|
'UPDATE products SET last_checked = CURRENT_TIMESTAMP WHERE id = $1',
|
||||||
|
[id]
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
findDueForRefresh: async (): Promise<Product[]> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
`SELECT * FROM products
|
||||||
|
WHERE last_checked IS NULL
|
||||||
|
OR last_checked + (refresh_interval || ' seconds')::interval < CURRENT_TIMESTAMP`
|
||||||
|
);
|
||||||
|
return result.rows;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Price History types and queries
|
||||||
|
export interface PriceHistory {
|
||||||
|
id: number;
|
||||||
|
product_id: number;
|
||||||
|
price: number;
|
||||||
|
currency: string;
|
||||||
|
recorded_at: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const priceHistoryQueries = {
|
||||||
|
findByProductId: async (
|
||||||
|
productId: number,
|
||||||
|
days?: number
|
||||||
|
): Promise<PriceHistory[]> => {
|
||||||
|
let query = `
|
||||||
|
SELECT * FROM price_history
|
||||||
|
WHERE product_id = $1
|
||||||
|
`;
|
||||||
|
const values: (number | string)[] = [productId];
|
||||||
|
|
||||||
|
if (days) {
|
||||||
|
query += ` AND recorded_at >= CURRENT_TIMESTAMP - ($2 || ' days')::interval`;
|
||||||
|
values.push(days.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
query += ' ORDER BY recorded_at ASC';
|
||||||
|
|
||||||
|
const result = await pool.query(query, values);
|
||||||
|
return result.rows;
|
||||||
|
},
|
||||||
|
|
||||||
|
create: async (
|
||||||
|
productId: number,
|
||||||
|
price: number,
|
||||||
|
currency: string = 'USD'
|
||||||
|
): Promise<PriceHistory> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
`INSERT INTO price_history (product_id, price, currency)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
RETURNING *`,
|
||||||
|
[productId, price, currency]
|
||||||
|
);
|
||||||
|
return result.rows[0];
|
||||||
|
},
|
||||||
|
|
||||||
|
getLatest: async (productId: number): Promise<PriceHistory | null> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
`SELECT * FROM price_history
|
||||||
|
WHERE product_id = $1
|
||||||
|
ORDER BY recorded_at DESC
|
||||||
|
LIMIT 1`,
|
||||||
|
[productId]
|
||||||
|
);
|
||||||
|
return result.rows[0] || null;
|
||||||
|
},
|
||||||
|
|
||||||
|
getStats: async (productId: number): Promise<{
|
||||||
|
min_price: number;
|
||||||
|
max_price: number;
|
||||||
|
avg_price: number;
|
||||||
|
price_count: number;
|
||||||
|
} | null> => {
|
||||||
|
const result = await pool.query(
|
||||||
|
`SELECT
|
||||||
|
MIN(price) as min_price,
|
||||||
|
MAX(price) as max_price,
|
||||||
|
AVG(price)::decimal(10,2) as avg_price,
|
||||||
|
COUNT(*) as price_count
|
||||||
|
FROM price_history
|
||||||
|
WHERE product_id = $1`,
|
||||||
|
[productId]
|
||||||
|
);
|
||||||
|
return result.rows[0] || null;
|
||||||
|
},
|
||||||
|
};
|
||||||
93
backend/src/routes/auth.ts
Normal file
93
backend/src/routes/auth.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
import { Router, Request, Response } from 'express';
|
||||||
|
import bcrypt from 'bcrypt';
|
||||||
|
import { userQueries } from '../models';
|
||||||
|
import { generateToken } from '../middleware/auth';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// Register new user
|
||||||
|
router.post('/register', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const { email, password } = req.body;
|
||||||
|
|
||||||
|
if (!email || !password) {
|
||||||
|
res.status(400).json({ error: 'Email and password are required' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (password.length < 8) {
|
||||||
|
res.status(400).json({ error: 'Password must be at least 8 characters' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
if (!emailRegex.test(email)) {
|
||||||
|
res.status(400).json({ error: 'Invalid email format' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingUser = await userQueries.findByEmail(email);
|
||||||
|
if (existingUser) {
|
||||||
|
res.status(409).json({ error: 'Email already registered' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const saltRounds = 12;
|
||||||
|
const passwordHash = await bcrypt.hash(password, saltRounds);
|
||||||
|
|
||||||
|
const user = await userQueries.create(email, passwordHash);
|
||||||
|
const token = generateToken(user.id);
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
message: 'User registered successfully',
|
||||||
|
token,
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Registration error:', error);
|
||||||
|
res.status(500).json({ error: 'Registration failed' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Login
|
||||||
|
router.post('/login', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const { email, password } = req.body;
|
||||||
|
|
||||||
|
if (!email || !password) {
|
||||||
|
res.status(400).json({ error: 'Email and password are required' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await userQueries.findByEmail(email);
|
||||||
|
if (!user) {
|
||||||
|
res.status(401).json({ error: 'Invalid email or password' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValidPassword = await bcrypt.compare(password, user.password_hash);
|
||||||
|
if (!isValidPassword) {
|
||||||
|
res.status(401).json({ error: 'Invalid email or password' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = generateToken(user.id);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
message: 'Login successful',
|
||||||
|
token,
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Login error:', error);
|
||||||
|
res.status(500).json({ error: 'Login failed' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
93
backend/src/routes/prices.ts
Normal file
93
backend/src/routes/prices.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
import { Router, Response } from 'express';
|
||||||
|
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||||
|
import { productQueries, priceHistoryQueries } from '../models';
|
||||||
|
import { scrapePrice } from '../services/scraper';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// All routes require authentication
|
||||||
|
router.use(authMiddleware);
|
||||||
|
|
||||||
|
// Get price history for a product
|
||||||
|
router.get('/:productId/prices', async (req: AuthRequest, res: Response) => {
|
||||||
|
try {
|
||||||
|
const userId = req.userId!;
|
||||||
|
const productId = parseInt(req.params.productId, 10);
|
||||||
|
|
||||||
|
if (isNaN(productId)) {
|
||||||
|
res.status(400).json({ error: 'Invalid product ID' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify product belongs to user
|
||||||
|
const product = await productQueries.findById(productId, userId);
|
||||||
|
if (!product) {
|
||||||
|
res.status(404).json({ error: 'Product not found' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get optional days filter from query
|
||||||
|
const days = req.query.days ? parseInt(req.query.days as string, 10) : undefined;
|
||||||
|
|
||||||
|
const priceHistory = await priceHistoryQueries.findByProductId(
|
||||||
|
productId,
|
||||||
|
days
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
product,
|
||||||
|
prices: priceHistory,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching price history:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch price history' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Force immediate price refresh
|
||||||
|
router.post('/:productId/refresh', async (req: AuthRequest, res: Response) => {
|
||||||
|
try {
|
||||||
|
const userId = req.userId!;
|
||||||
|
const productId = parseInt(req.params.productId, 10);
|
||||||
|
|
||||||
|
if (isNaN(productId)) {
|
||||||
|
res.status(400).json({ error: 'Invalid product ID' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify product belongs to user
|
||||||
|
const product = await productQueries.findById(productId, userId);
|
||||||
|
if (!product) {
|
||||||
|
res.status(404).json({ error: 'Product not found' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scrape new price
|
||||||
|
const priceData = await scrapePrice(product.url);
|
||||||
|
|
||||||
|
if (!priceData) {
|
||||||
|
res.status(400).json({ error: 'Could not extract price from URL' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record new price
|
||||||
|
const newPrice = await priceHistoryQueries.create(
|
||||||
|
productId,
|
||||||
|
priceData.price,
|
||||||
|
priceData.currency
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update last_checked timestamp
|
||||||
|
await productQueries.updateLastChecked(productId);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
message: 'Price refreshed successfully',
|
||||||
|
price: newPrice,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error refreshing price:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to refresh price' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
172
backend/src/routes/products.ts
Normal file
172
backend/src/routes/products.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
import { Router, Response } from 'express';
|
||||||
|
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||||
|
import { productQueries, priceHistoryQueries } from '../models';
|
||||||
|
import { scrapeProduct } from '../services/scraper';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// All routes require authentication
|
||||||
|
router.use(authMiddleware);
|
||||||
|
|
||||||
|
// Get all products for the authenticated user
|
||||||
|
router.get('/', async (req: AuthRequest, res: Response) => {
|
||||||
|
try {
|
||||||
|
const userId = req.userId!;
|
||||||
|
const products = await productQueries.findByUserId(userId);
|
||||||
|
res.json(products);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching products:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch products' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add a new product to track
|
||||||
|
router.post('/', async (req: AuthRequest, res: Response) => {
|
||||||
|
try {
|
||||||
|
const userId = req.userId!;
|
||||||
|
const { url, refresh_interval } = req.body;
|
||||||
|
|
||||||
|
if (!url) {
|
||||||
|
res.status(400).json({ error: 'URL is required' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate URL
|
||||||
|
try {
|
||||||
|
new URL(url);
|
||||||
|
} catch {
|
||||||
|
res.status(400).json({ error: 'Invalid URL format' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scrape product info
|
||||||
|
const scrapedData = await scrapeProduct(url);
|
||||||
|
|
||||||
|
if (!scrapedData.price) {
|
||||||
|
res.status(400).json({
|
||||||
|
error: 'Could not extract price from the provided URL',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create product
|
||||||
|
const product = await productQueries.create(
|
||||||
|
userId,
|
||||||
|
url,
|
||||||
|
scrapedData.name,
|
||||||
|
scrapedData.imageUrl,
|
||||||
|
refresh_interval || 3600
|
||||||
|
);
|
||||||
|
|
||||||
|
// Record initial price
|
||||||
|
await priceHistoryQueries.create(
|
||||||
|
product.id,
|
||||||
|
scrapedData.price.price,
|
||||||
|
scrapedData.price.currency
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update last_checked timestamp
|
||||||
|
await productQueries.updateLastChecked(product.id);
|
||||||
|
|
||||||
|
// Fetch the product with the price
|
||||||
|
const productWithPrice = await productQueries.findById(product.id, userId);
|
||||||
|
|
||||||
|
res.status(201).json(productWithPrice);
|
||||||
|
} catch (error) {
|
||||||
|
// Handle unique constraint violation
|
||||||
|
if (
|
||||||
|
error instanceof Error &&
|
||||||
|
error.message.includes('duplicate key value')
|
||||||
|
) {
|
||||||
|
res.status(409).json({ error: 'You are already tracking this product' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('Error adding product:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to add product' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get a specific product
|
||||||
|
router.get('/:id', async (req: AuthRequest, res: Response) => {
|
||||||
|
try {
|
||||||
|
const userId = req.userId!;
|
||||||
|
const productId = parseInt(req.params.id, 10);
|
||||||
|
|
||||||
|
if (isNaN(productId)) {
|
||||||
|
res.status(400).json({ error: 'Invalid product ID' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const product = await productQueries.findById(productId, userId);
|
||||||
|
|
||||||
|
if (!product) {
|
||||||
|
res.status(404).json({ error: 'Product not found' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get price stats
|
||||||
|
const stats = await priceHistoryQueries.getStats(productId);
|
||||||
|
|
||||||
|
res.json({ ...product, stats });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching product:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch product' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update product settings
|
||||||
|
router.put('/:id', async (req: AuthRequest, res: Response) => {
|
||||||
|
try {
|
||||||
|
const userId = req.userId!;
|
||||||
|
const productId = parseInt(req.params.id, 10);
|
||||||
|
|
||||||
|
if (isNaN(productId)) {
|
||||||
|
res.status(400).json({ error: 'Invalid product ID' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { name, refresh_interval } = req.body;
|
||||||
|
|
||||||
|
const product = await productQueries.update(productId, userId, {
|
||||||
|
name,
|
||||||
|
refresh_interval,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!product) {
|
||||||
|
res.status(404).json({ error: 'Product not found' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(product);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating product:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to update product' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete a product
|
||||||
|
router.delete('/:id', async (req: AuthRequest, res: Response) => {
|
||||||
|
try {
|
||||||
|
const userId = req.userId!;
|
||||||
|
const productId = parseInt(req.params.id, 10);
|
||||||
|
|
||||||
|
if (isNaN(productId)) {
|
||||||
|
res.status(400).json({ error: 'Invalid product ID' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleted = await productQueries.delete(productId, userId);
|
||||||
|
|
||||||
|
if (!deleted) {
|
||||||
|
res.status(404).json({ error: 'Product not found' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ message: 'Product deleted successfully' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting product:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to delete product' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
76
backend/src/services/scheduler.ts
Normal file
76
backend/src/services/scheduler.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
import cron from 'node-cron';
|
||||||
|
import { productQueries, priceHistoryQueries } from '../models';
|
||||||
|
import { scrapePrice } from './scraper';
|
||||||
|
|
||||||
|
let isRunning = false;
|
||||||
|
|
||||||
|
async function checkPrices(): Promise<void> {
|
||||||
|
if (isRunning) {
|
||||||
|
console.log('Price check already in progress, skipping...');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
isRunning = true;
|
||||||
|
console.log('Starting scheduled price check...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Find all products that are due for a refresh
|
||||||
|
const products = await productQueries.findDueForRefresh();
|
||||||
|
console.log(`Found ${products.length} products to check`);
|
||||||
|
|
||||||
|
for (const product of products) {
|
||||||
|
try {
|
||||||
|
console.log(`Checking price for product ${product.id}: ${product.url}`);
|
||||||
|
|
||||||
|
const priceData = await scrapePrice(product.url);
|
||||||
|
|
||||||
|
if (priceData) {
|
||||||
|
// Get the latest recorded price to compare
|
||||||
|
const latestPrice = await priceHistoryQueries.getLatest(product.id);
|
||||||
|
|
||||||
|
// Only record if price has changed or it's the first entry
|
||||||
|
if (!latestPrice || latestPrice.price !== priceData.price) {
|
||||||
|
await priceHistoryQueries.create(
|
||||||
|
product.id,
|
||||||
|
priceData.price,
|
||||||
|
priceData.currency
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`Recorded new price for product ${product.id}: ${priceData.currency} ${priceData.price}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.log(`Price unchanged for product ${product.id}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn(`Could not extract price for product ${product.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update last_checked even if price extraction failed
|
||||||
|
await productQueries.updateLastChecked(product.id);
|
||||||
|
|
||||||
|
// Add a small delay between requests to avoid rate limiting
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error checking product ${product.id}:`, error);
|
||||||
|
// Continue with next product even if one fails
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in scheduled price check:', error);
|
||||||
|
} finally {
|
||||||
|
isRunning = false;
|
||||||
|
console.log('Scheduled price check complete');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startScheduler(): void {
|
||||||
|
// Run every minute
|
||||||
|
cron.schedule('* * * * *', () => {
|
||||||
|
checkPrices().catch(console.error);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Price check scheduler started (runs every minute)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow manual trigger for testing
|
||||||
|
export { checkPrices };
|
||||||
267
backend/src/services/scraper.ts
Normal file
267
backend/src/services/scraper.ts
Normal file
|
|
@ -0,0 +1,267 @@
|
||||||
|
import axios from 'axios';
|
||||||
|
import * as cheerio from 'cheerio';
|
||||||
|
import {
|
||||||
|
parsePrice,
|
||||||
|
ParsedPrice,
|
||||||
|
findMostLikelyPrice,
|
||||||
|
} from '../utils/priceParser';
|
||||||
|
|
||||||
|
export interface ScrapedProduct {
|
||||||
|
name: string | null;
|
||||||
|
price: ParsedPrice | null;
|
||||||
|
imageUrl: string | null;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Common price selectors used across e-commerce sites
|
||||||
|
const priceSelectors = [
|
||||||
|
// Schema.org
|
||||||
|
'[itemprop="price"]',
|
||||||
|
'[data-price]',
|
||||||
|
'[data-product-price]',
|
||||||
|
|
||||||
|
// Common class names
|
||||||
|
'.price',
|
||||||
|
'.product-price',
|
||||||
|
'.current-price',
|
||||||
|
'.sale-price',
|
||||||
|
'.final-price',
|
||||||
|
'.offer-price',
|
||||||
|
'#price',
|
||||||
|
'#priceblock_ourprice',
|
||||||
|
'#priceblock_dealprice',
|
||||||
|
'#priceblock_saleprice',
|
||||||
|
|
||||||
|
// Amazon specific
|
||||||
|
'.a-price .a-offscreen',
|
||||||
|
'.a-price-whole',
|
||||||
|
'#corePrice_feature_div .a-price .a-offscreen',
|
||||||
|
'#corePriceDisplay_desktop_feature_div .a-price .a-offscreen',
|
||||||
|
|
||||||
|
// Generic patterns
|
||||||
|
'[class*="price"]',
|
||||||
|
'[class*="Price"]',
|
||||||
|
'[id*="price"]',
|
||||||
|
'[id*="Price"]',
|
||||||
|
];
|
||||||
|
|
||||||
|
// Selectors for product name
|
||||||
|
const nameSelectors = [
|
||||||
|
'[itemprop="name"]',
|
||||||
|
'h1[class*="product"]',
|
||||||
|
'h1[class*="title"]',
|
||||||
|
'#productTitle',
|
||||||
|
'.product-title',
|
||||||
|
'.product-name',
|
||||||
|
'h1',
|
||||||
|
];
|
||||||
|
|
||||||
|
// Selectors for product image
|
||||||
|
const imageSelectors = [
|
||||||
|
'[itemprop="image"]',
|
||||||
|
'[property="og:image"]',
|
||||||
|
'#landingImage',
|
||||||
|
'#imgBlkFront',
|
||||||
|
'.product-image img',
|
||||||
|
'.main-image img',
|
||||||
|
'[data-zoom-image]',
|
||||||
|
'img[class*="product"]',
|
||||||
|
];
|
||||||
|
|
||||||
|
export async function scrapeProduct(url: string): Promise<ScrapedProduct> {
|
||||||
|
const result: ScrapedProduct = {
|
||||||
|
name: null,
|
||||||
|
price: null,
|
||||||
|
imageUrl: null,
|
||||||
|
url,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await axios.get(url, {
|
||||||
|
headers: {
|
||||||
|
'User-Agent':
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
||||||
|
Accept:
|
||||||
|
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
|
||||||
|
'Accept-Language': 'en-US,en;q=0.5',
|
||||||
|
'Accept-Encoding': 'gzip, deflate, br',
|
||||||
|
Connection: 'keep-alive',
|
||||||
|
'Upgrade-Insecure-Requests': '1',
|
||||||
|
},
|
||||||
|
timeout: 15000,
|
||||||
|
maxRedirects: 5,
|
||||||
|
});
|
||||||
|
|
||||||
|
const $ = cheerio.load(response.data);
|
||||||
|
|
||||||
|
// Try to extract from JSON-LD structured data first
|
||||||
|
const jsonLdData = extractJsonLd($);
|
||||||
|
if (jsonLdData) {
|
||||||
|
if (jsonLdData.name) result.name = jsonLdData.name;
|
||||||
|
if (jsonLdData.price) result.price = jsonLdData.price;
|
||||||
|
if (jsonLdData.image) result.imageUrl = jsonLdData.image;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract product name
|
||||||
|
if (!result.name) {
|
||||||
|
result.name = extractName($);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract price
|
||||||
|
if (!result.price) {
|
||||||
|
result.price = extractPrice($);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract image
|
||||||
|
if (!result.imageUrl) {
|
||||||
|
result.imageUrl = extractImage($, url);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try Open Graph meta tags as fallback
|
||||||
|
if (!result.name) {
|
||||||
|
result.name = $('meta[property="og:title"]').attr('content') || null;
|
||||||
|
}
|
||||||
|
if (!result.imageUrl) {
|
||||||
|
result.imageUrl = $('meta[property="og:image"]').attr('content') || null;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error scraping ${url}:`, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractJsonLd(
|
||||||
|
$: cheerio.CheerioAPI
|
||||||
|
): { name?: string; price?: ParsedPrice; image?: string } | null {
|
||||||
|
try {
|
||||||
|
const scripts = $('script[type="application/ld+json"]');
|
||||||
|
for (let i = 0; i < scripts.length; i++) {
|
||||||
|
const content = $(scripts[i]).html();
|
||||||
|
if (!content) continue;
|
||||||
|
|
||||||
|
const data = JSON.parse(content);
|
||||||
|
const product = findProduct(data);
|
||||||
|
|
||||||
|
if (product) {
|
||||||
|
const result: { name?: string; price?: ParsedPrice; image?: string } =
|
||||||
|
{};
|
||||||
|
|
||||||
|
if (product.name) {
|
||||||
|
result.name = product.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (product.offers) {
|
||||||
|
const offer = Array.isArray(product.offers)
|
||||||
|
? product.offers[0]
|
||||||
|
: product.offers;
|
||||||
|
if (offer.price) {
|
||||||
|
result.price = {
|
||||||
|
price: parseFloat(offer.price),
|
||||||
|
currency: offer.priceCurrency || 'USD',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (product.image) {
|
||||||
|
result.image = Array.isArray(product.image)
|
||||||
|
? product.image[0]
|
||||||
|
: typeof product.image === 'string'
|
||||||
|
? product.image
|
||||||
|
: product.image.url;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// JSON parse error, continue with other methods
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findProduct(data: unknown): Record<string, unknown> | null {
|
||||||
|
if (!data || typeof data !== 'object') return null;
|
||||||
|
|
||||||
|
const obj = data as Record<string, unknown>;
|
||||||
|
|
||||||
|
if (obj['@type'] === 'Product') {
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
for (const item of data) {
|
||||||
|
const found = findProduct(item);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (obj['@graph'] && Array.isArray(obj['@graph'])) {
|
||||||
|
for (const item of obj['@graph']) {
|
||||||
|
const found = findProduct(item);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractPrice($: cheerio.CheerioAPI): ParsedPrice | null {
|
||||||
|
const prices: ParsedPrice[] = [];
|
||||||
|
|
||||||
|
for (const selector of priceSelectors) {
|
||||||
|
const elements = $(selector);
|
||||||
|
elements.each((_, el) => {
|
||||||
|
const text =
|
||||||
|
$(el).attr('content') || $(el).attr('data-price') || $(el).text();
|
||||||
|
const parsed = parsePrice(text);
|
||||||
|
if (parsed) {
|
||||||
|
prices.push(parsed);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (prices.length > 0) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return findMostLikelyPrice(prices);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractName($: cheerio.CheerioAPI): string | null {
|
||||||
|
for (const selector of nameSelectors) {
|
||||||
|
const element = $(selector).first();
|
||||||
|
if (element.length) {
|
||||||
|
const text = element.text().trim();
|
||||||
|
if (text && text.length > 0 && text.length < 500) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractImage($: cheerio.CheerioAPI, baseUrl: string): string | null {
|
||||||
|
for (const selector of imageSelectors) {
|
||||||
|
const element = $(selector).first();
|
||||||
|
if (element.length) {
|
||||||
|
const src =
|
||||||
|
element.attr('src') ||
|
||||||
|
element.attr('content') ||
|
||||||
|
element.attr('data-zoom-image') ||
|
||||||
|
element.attr('data-src');
|
||||||
|
if (src) {
|
||||||
|
// Handle relative URLs
|
||||||
|
try {
|
||||||
|
return new URL(src, baseUrl).href;
|
||||||
|
} catch {
|
||||||
|
return src;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function scrapePrice(url: string): Promise<ParsedPrice | null> {
|
||||||
|
const product = await scrapeProduct(url);
|
||||||
|
return product.price;
|
||||||
|
}
|
||||||
121
backend/src/utils/priceParser.ts
Normal file
121
backend/src/utils/priceParser.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
||||||
|
export interface ParsedPrice {
|
||||||
|
price: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Currency symbols and their codes
|
||||||
|
const currencyMap: Record<string, string> = {
|
||||||
|
'$': 'USD',
|
||||||
|
'€': 'EUR',
|
||||||
|
'£': 'GBP',
|
||||||
|
'¥': 'JPY',
|
||||||
|
'₹': 'INR',
|
||||||
|
'CAD': 'CAD',
|
||||||
|
'AUD': 'AUD',
|
||||||
|
'USD': 'USD',
|
||||||
|
'EUR': 'EUR',
|
||||||
|
'GBP': 'GBP',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Patterns to match prices in text
|
||||||
|
const pricePatterns = [
|
||||||
|
// $29.99 or $29,99 or $ 29.99
|
||||||
|
/(?<currency>[$€£¥₹])\s*(?<price>[\d,]+\.?\d*)/,
|
||||||
|
// 29.99 USD or 29,99 EUR
|
||||||
|
/(?<price>[\d,]+\.?\d*)\s*(?<currency>USD|EUR|GBP|CAD|AUD|JPY|INR)/i,
|
||||||
|
// Plain number with optional decimal (fallback)
|
||||||
|
/(?<price>\d{1,3}(?:[,.\s]?\d{3})*(?:[.,]\d{2})?)/,
|
||||||
|
];
|
||||||
|
|
||||||
|
export function parsePrice(text: string): ParsedPrice | null {
|
||||||
|
if (!text) return null;
|
||||||
|
|
||||||
|
// Clean up the text
|
||||||
|
const cleanText = text.trim().replace(/\s+/g, ' ');
|
||||||
|
|
||||||
|
for (const pattern of pricePatterns) {
|
||||||
|
const match = cleanText.match(pattern);
|
||||||
|
if (match && match.groups) {
|
||||||
|
const priceStr = match.groups.price || match[1];
|
||||||
|
const currencySymbol = match.groups.currency || '$';
|
||||||
|
|
||||||
|
if (priceStr) {
|
||||||
|
const price = normalizePrice(priceStr);
|
||||||
|
if (price !== null && price > 0) {
|
||||||
|
const currency = currencyMap[currencySymbol] || 'USD';
|
||||||
|
return { price, currency };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to extract just a number as fallback
|
||||||
|
const numberMatch = cleanText.match(/[\d,]+\.?\d*/);
|
||||||
|
if (numberMatch) {
|
||||||
|
const price = normalizePrice(numberMatch[0]);
|
||||||
|
if (price !== null && price > 0) {
|
||||||
|
return { price, currency: 'USD' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePrice(priceStr: string): number | null {
|
||||||
|
if (!priceStr) return null;
|
||||||
|
|
||||||
|
// Remove spaces
|
||||||
|
let normalized = priceStr.replace(/\s/g, '');
|
||||||
|
|
||||||
|
// Handle European format (1.234,56) vs US format (1,234.56)
|
||||||
|
const hasCommaDecimal = /,\d{2}$/.test(normalized);
|
||||||
|
const hasDotDecimal = /\.\d{2}$/.test(normalized);
|
||||||
|
|
||||||
|
if (hasCommaDecimal && !hasDotDecimal) {
|
||||||
|
// European format: 1.234,56 -> 1234.56
|
||||||
|
normalized = normalized.replace(/\./g, '').replace(',', '.');
|
||||||
|
} else {
|
||||||
|
// US format or plain number: remove commas
|
||||||
|
normalized = normalized.replace(/,/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
const price = parseFloat(normalized);
|
||||||
|
return isNaN(price) ? null : Math.round(price * 100) / 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extractPricesFromText(html: string): ParsedPrice[] {
|
||||||
|
const prices: ParsedPrice[] = [];
|
||||||
|
const seen = new Set<number>();
|
||||||
|
|
||||||
|
// Match all price-like patterns in the HTML
|
||||||
|
const allMatches = html.matchAll(
|
||||||
|
/(?:[$€£¥₹])\s*[\d,]+\.?\d*|[\d,]+\.?\d*\s*(?:USD|EUR|GBP|CAD|AUD)/gi
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const match of allMatches) {
|
||||||
|
const parsed = parsePrice(match[0]);
|
||||||
|
if (parsed && !seen.has(parsed.price)) {
|
||||||
|
seen.add(parsed.price);
|
||||||
|
prices.push(parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return prices;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findMostLikelyPrice(prices: ParsedPrice[]): ParsedPrice | null {
|
||||||
|
if (prices.length === 0) return null;
|
||||||
|
if (prices.length === 1) return prices[0];
|
||||||
|
|
||||||
|
// Filter out very small prices (likely not product prices)
|
||||||
|
const validPrices = prices.filter((p) => p.price >= 0.99);
|
||||||
|
|
||||||
|
if (validPrices.length === 0) return prices[0];
|
||||||
|
|
||||||
|
// Sort by price and pick the middle one (often the actual price)
|
||||||
|
// This helps avoid picking shipping costs or discounts
|
||||||
|
validPrices.sort((a, b) => a.price - b.price);
|
||||||
|
|
||||||
|
// Return the first (lowest) valid price - often the current/sale price
|
||||||
|
return validPrices[0];
|
||||||
|
}
|
||||||
19
backend/tsconfig.json
Normal file
19
backend/tsconfig.json
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ES2022"],
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"declaration": true,
|
||||||
|
"declarationMap": true,
|
||||||
|
"sourceMap": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist"]
|
||||||
|
}
|
||||||
54
docker-compose.yml
Normal file
54
docker-compose.yml
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
# PostgreSQL Database
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
container_name: priceghost-db
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: priceghost
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
# Backend API
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: ./backend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: priceghost-backend
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql://postgres:postgres@postgres:5432/priceghost
|
||||||
|
JWT_SECRET: ${JWT_SECRET:-change-this-in-production-use-strong-secret}
|
||||||
|
PORT: 3001
|
||||||
|
NODE_ENV: production
|
||||||
|
ports:
|
||||||
|
- "3001:3001"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
# Frontend
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: priceghost-frontend
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
10
frontend/.dockerignore
Normal file
10
frontend/.dockerignore
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
npm-debug.log
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
README.md
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
31
frontend/Dockerfile
Normal file
31
frontend/Dockerfile
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
# Build stage
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package files
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Build the application
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Production stage - serve with nginx
|
||||||
|
FROM nginx:alpine AS production
|
||||||
|
|
||||||
|
# Copy built files to nginx
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
# Copy nginx configuration
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
# Start nginx
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/ghost.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>PriceGhost - Track Product Prices</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
34
frontend/nginx.conf
Normal file
34
frontend/nginx.conf
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# Gzip compression
|
||||||
|
gzip on;
|
||||||
|
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
|
||||||
|
|
||||||
|
# Proxy API requests to backend
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://backend:3001;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Serve static files and handle SPA routing
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Cache static assets
|
||||||
|
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
}
|
||||||
25
frontend/package.json
Normal file
25
frontend/package.json
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
{
|
||||||
|
"name": "priceghost-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.6.0",
|
||||||
|
"react": "^18.2.0",
|
||||||
|
"react-dom": "^18.2.0",
|
||||||
|
"react-router-dom": "^6.20.0",
|
||||||
|
"recharts": "^2.10.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "^18.2.37",
|
||||||
|
"@types/react-dom": "^18.2.15",
|
||||||
|
"@vitejs/plugin-react": "^4.2.0",
|
||||||
|
"typescript": "^5.3.2",
|
||||||
|
"vite": "^5.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
5
frontend/public/ghost.svg
Normal file
5
frontend/public/ghost.svg
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#6366f1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M9 10h.01"/>
|
||||||
|
<path d="M15 10h.01"/>
|
||||||
|
<path d="M12 2a8 8 0 0 0-8 8v12l3-3 2.5 2.5L12 19l2.5 2.5L17 19l3 3V10a8 8 0 0 0-8-8z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 301 B |
106
frontend/src/App.tsx
Normal file
106
frontend/src/App.tsx
Normal 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
102
frontend/src/api/client.ts
Normal 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;
|
||||||
184
frontend/src/components/AuthForm.tsx
Normal file
184
frontend/src/components/AuthForm.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
115
frontend/src/components/Layout.tsx
Normal file
115
frontend/src/components/Layout.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
262
frontend/src/components/PriceChart.tsx
Normal file
262
frontend/src/components/PriceChart.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
155
frontend/src/components/ProductCard.tsx
Normal file
155
frontend/src/components/ProductCard.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
130
frontend/src/components/ProductForm.tsx
Normal file
130
frontend/src/components/ProductForm.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
82
frontend/src/context/AuthContext.tsx
Normal file
82
frontend/src/context/AuthContext.tsx
Normal 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;
|
||||||
|
}
|
||||||
1
frontend/src/hooks/useAuth.ts
Normal file
1
frontend/src/hooks/useAuth.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export { useAuth } from '../context/AuthContext';
|
||||||
225
frontend/src/index.css
Normal file
225
frontend/src/index.css
Normal 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
10
frontend/src/main.tsx
Normal 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>
|
||||||
|
);
|
||||||
136
frontend/src/pages/Dashboard.tsx
Normal file
136
frontend/src/pages/Dashboard.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
15
frontend/src/pages/Login.tsx
Normal file
15
frontend/src/pages/Login.tsx
Normal 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} />;
|
||||||
|
}
|
||||||
353
frontend/src/pages/ProductDetail.tsx
Normal file
353
frontend/src/pages/ProductDetail.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
15
frontend/src/pages/Register.tsx
Normal file
15
frontend/src/pages/Register.tsx
Normal 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
9
frontend/src/vite-env.d.ts
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
/// <reference types="vite/client" />
|
||||||
|
|
||||||
|
interface ImportMetaEnv {
|
||||||
|
readonly VITE_API_URL: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImportMeta {
|
||||||
|
readonly env: ImportMetaEnv;
|
||||||
|
}
|
||||||
21
frontend/tsconfig.json
Normal file
21
frontend/tsconfig.json
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true
|
||||||
|
},
|
||||||
|
"include": ["src"],
|
||||||
|
"references": [{ "path": "./tsconfig.node.json" }]
|
||||||
|
}
|
||||||
11
frontend/tsconfig.node.json
Normal file
11
frontend/tsconfig.node.json
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"composite": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"strict": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
15
frontend/vite.config.ts
Normal file
15
frontend/vite.config.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:3001',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue