← back to Wine Finder Next

public/CLAUDE.md

260 lines

# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

Wine Finder Next.js - A tokenized wine investment platform with DAO governance, secondary marketplace, and comprehensive wine discovery features. Each premium wine bottle is tokenized into 10,000 shares for fractional ownership.

**Production URL:** http://45.61.58.125:7250  
**Process Manager:** PM2 (app name: `wine-finder-next`)  
**Port:** 7250 (fixed for Cloudflare - NEVER change this port)

## Essential Commands

```bash
# Development
npm run dev           # Start development server (localhost:3000)
npm run build         # Build for production
npm run lint          # Run ESLint checks

# Production Deployment
pm2 start ecosystem.config.js  # Start with PM2
pm2 restart wine-finder-next   # Restart application
pm2 logs wine-finder-next      # View logs
pm2 monit                       # Monitor performance
pm2 status                      # Check process status

# Testing (190+ tests)
npm test              # Run tests in watch mode
npm run test:ci       # Run all tests (CI mode, required before deploy)
npm run test:unit     # Unit tests only
npm run test:integration  # Integration tests
npm run test:security     # Security vulnerability tests
npm run test:performance  # Performance benchmarks
npm run test:coverage     # Generate coverage report (target: 70%+)
npm run test:e2e      # Playwright E2E tests
npm run test:all      # Run complete test suite

# Redis Operations
./scripts/setup-redis.sh        # Initialize Redis (run once)
redis-cli -a WineFinder2025SecurePass ping  # Test connection
redis-cli -a WineFinder2025SecurePass monitor  # Monitor commands
redis-cli -a WineFinder2025SecurePass flushdb  # Clear cache

# Data Management
./scripts/run-daily-crawler.sh  # Run wine data crawler
node scripts/seo-validator.js   # Validate SEO metadata
```

## Architecture Overview

### Technology Stack
- **Framework:** Next.js 16.0.3 with React 19.2.0
- **Database:** SQLite (better-sqlite3) at `data/wine_engine.db`
- **Caching:** Redis with 256MB max memory, LRU eviction
- **Authentication:** JWT-based with API key support
- **Process Management:** PM2 with auto-restart
- **Image Optimization:** Next.js Image component with remote patterns for wine images

### Directory Structure

```
app/
├── api/              # API routes organized by feature
│   ├── wines/        # Wine CRUD operations
│   ├── portfolio/    # Portfolio management
│   ├── aff/          # Affiliate tracking
│   ├── ingest/       # Data ingestion endpoints
│   └── membership/   # Membership features (votes, bottles, marketplace)
├── search/           # Search page
├── wines/            # Wine detail pages
└── portfolio/        # Portfolio management UI

lib/
├── db.ts             # Database connection and initialization
├── wines.ts          # Wine data operations
├── portfolio.ts      # Portfolio management logic
├── affiliates.ts     # Affiliate tracking
├── redis.ts          # Redis client configuration
└── membershipDatabase.ts  # Membership system database

components/
├── WineCard.tsx      # Wine display card
├── SearchBar.tsx     # Search interface
├── BestDealHero.tsx  # Deal highlighting
└── PriceChart.tsx    # Price history visualization
```

### API Architecture

All API routes follow RESTful patterns and include:
- Rate limiting via `lib/rateLimit.ts`
- Input validation via `lib/inputValidation.ts`
- JWT authentication for protected endpoints
- CSRF protection for state-changing operations
- Security monitoring and audit logging

### Database Schema

Primary tables in SQLite (`data/wine_engine.db`):
- `wines` - Wine catalog with prices, ratings, and metadata
- `portfolios` - User wine collections and holdings
- `affiliates` - Affiliate link tracking and conversions
- `price_history` - Time-series price data for charts
- `membership_bottles` - Tokenized bottle allocations (10,000 shares each)
- `votes` - DAO governance voting records
- `marketplace_listings` - Secondary market for share trading
- `fulfillment_tracking` - Premium wine shipment tracking
- `sample_requests` - Wine sample program management

### Data Ingestion

The platform aggregates wine data from multiple sources:
- Vivino (via `/api/ingest/vivino`)
- Wine.com (via `/api/ingest/winecom`)
- WineBid (via `/api/ingest/winebid`)
- Drizly (via `/api/ingest/drizly`)

Each ingestion endpoint handles rate limiting, data normalization, and duplicate detection.

### Performance Optimizations

1. **Redis Caching:** 
   - Search results cached for 5 minutes
   - Featured wines cached for 1 hour
   - Price history cached for 24 hours

2. **Database Optimizations:**
   - Connection pooling with 10 concurrent connections
   - Prepared statement caching
   - Index optimization on frequently queried columns

3. **Next.js Optimizations:**
   - Image optimization with remote patterns
   - Static generation where possible
   - Turbopack for faster builds
   - Standalone output mode for smaller deployments

### Security Features

- JWT-based authentication with refresh tokens
- API key authentication for service-to-service calls
- Rate limiting (100 requests/minute per IP)
- CSRF protection on all state-changing operations
- Input validation and sanitization
- SQL injection prevention via parameterized queries
- XSS protection headers
- Security monitoring dashboard at `/api/security/dashboard`

### External Integrations

1. **Google Sheets:** Wine inventory management
   - Sheet ID: `1jCvQbOT9vRXrT7bHN9DiCBqPRJ9jG0sJLRr5Wvf3FuI`
   - Credentials: `/google-credentials.json`

2. **Slack Notifications:** Price alerts and system notifications
   - Webhook configured in `.env`

3. **Roboflow:** Wine label detection API
   - API key in environment variables

### Environment Variables

Required in `.env`:
- `PORT` - Application port (7250)
- `NODE_ENV` - Environment (production/development)
- `ADMIN_USER/ADMIN_PASS` - Admin credentials
- `SESSION_SECRET` - Session encryption key
- `GOOGLE_SHEET_ID` - Google Sheets integration
- `SLACK_WEBHOOK_URL` - Slack notifications
- `ROBOFLOW_API_KEY` - Wine label detection

### Deployment Notes

- **Server:** 45.61.58.125 (Kamatera VPS Ubuntu)
- **Port:** 7250 (fixed for Cloudflare, do not change)
- **Firewall:** Port must be open via `sudo ufw allow 7250/tcp`
- **Process Manager:** PM2 with auto-restart on failure
- **Memory Limit:** 1GB max per process
- **Redis Password:** WineFinder2025SecurePass

### Key Business Features

1. **Wine Tokenization System**
   - Each bottle = 10,000 tradeable shares
   - Fractional ownership via `/api/membership/bottles`
   - Share trading on secondary marketplace
   - Automated fulfillment when holding threshold reached

2. **DAO Governance**
   - Community voting on wine selections
   - Vote weight based on share holdings
   - Proposal system at `/api/membership/votes`
   - Automatic execution of passed proposals

3. **Data Aggregation Sources**
   - **Vivino:** Ratings and user reviews
   - **Wine.com:** Inventory and pricing
   - **WineBid:** Auction prices
   - **Drizly:** Local availability
   - Real-time price tracking across all sources

### Testing Strategy

The codebase includes 190+ tests across multiple categories:

```javascript
// Run specific test suites
jest --testPathPattern=__tests__/unit/wines.test.ts  // Single file
jest --testNamePattern="should create wine"          // Single test
jest --coverage --coveragePathIgnorePatterns=node_modules
```

Test coverage requirements:
- Statements: 70%
- Branches: 65%
- Functions: 70%
- Lines: 70%

### Common Troubleshooting

1. **Port 7250 issues:** 
   ```bash
   lsof -ti:7250 | xargs kill -9  # Force kill process
   sudo ufw allow 7250/tcp         # Open firewall
   ```

2. **Database locks:** 
   ```bash
   rm data/wine_engine.db-wal      # Remove WAL file
   rm data/wine_engine.db-shm      # Remove shared memory
   ```

3. **Redis issues:**
   ```bash
   sudo systemctl restart redis-wine-finder
   redis-cli -a WineFinder2025SecurePass ping
   ```

4. **Memory issues:** PM2 auto-restarts at 1GB limit
   ```bash
   pm2 restart wine-finder-next --max-memory-restart 2G
   ```

5. **Build failures:** 
   ```bash
   rm -rf .next node_modules
   npm install
   npm run build
   ```

### Performance Benchmarks

Current production metrics:
- **API Response Time:** 60-90% faster after optimizations
- **Database Queries:** 100-1000x faster with proper indexing
- **Cache Hit Rate:** 85% with Redis
- **Payload Size:** 98% smaller with pagination
- **Concurrent Users:** 10x improvement with connection pooling
- **Security Score:** 92/100 (OWASP compliance)