← back to Wine Finder Next

claude-md-viewer.html

544 lines

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CLAUDE.md - Wine Finder Documentation</title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.5.1/github-markdown-light.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-bash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 40px 20px;
        }
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
            padding: 30px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
        }
        .header h1 {
            margin: 0;
            font-size: 2.5em;
            font-weight: 700;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
        }
        .header p {
            margin: 10px 0 0 0;
            font-size: 1.2em;
            opacity: 0.95;
        }
        .markdown-body {
            background: white;
            padding: 45px;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            min-height: 500px;
        }
        .markdown-body h1 {
            color: #764ba2;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
        }
        .markdown-body h2 {
            color: #667eea;
            margin-top: 30px;
            border-bottom: 2px solid #e1e4e8;
            padding-bottom: 8px;
        }
        .markdown-body h3 {
            color: #764ba2;
            margin-top: 24px;
        }
        .markdown-body code {
            background: #f6f8fa;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 0.9em;
        }
        .markdown-body pre {
            background: #2d2d2d !important;
            border-radius: 8px;
            padding: 16px !important;
            overflow-x: auto;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .markdown-body pre code {
            background: transparent;
            color: #f8f8f2 !important;
            padding: 0;
        }
        .markdown-body blockquote {
            border-left: 4px solid #667eea;
            padding-left: 16px;
            color: #6a737d;
            margin: 16px 0;
        }
        .markdown-body table {
            border-collapse: collapse;
            width: 100%;
            margin: 16px 0;
        }
        .markdown-body table th {
            background: #667eea;
            color: white;
            font-weight: 600;
            padding: 12px;
            text-align: left;
        }
        .markdown-body table td {
            border: 1px solid #e1e4e8;
            padding: 12px;
        }
        .markdown-body table tr:nth-child(even) {
            background: #f6f8fa;
        }
        .markdown-body ul, .markdown-body ol {
            padding-left: 24px;
            line-height: 1.8;
        }
        .markdown-body li {
            margin: 8px 0;
        }
        .markdown-body strong {
            color: #764ba2;
            font-weight: 600;
        }
        .toc {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }
        .toc h3 {
            margin-top: 0;
            color: #764ba2;
            font-size: 1.3em;
        }
        .toc ul {
            list-style: none;
            padding-left: 0;
        }
        .toc ul ul {
            padding-left: 20px;
        }
        .toc a {
            color: #667eea;
            text-decoration: none;
            display: block;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.3s ease;
        }
        .toc a:hover {
            background: #f0f0f0;
            transform: translateX(4px);
        }
        .loading {
            text-align: center;
            padding: 50px;
            color: white;
            font-size: 1.5em;
        }
        @media (max-width: 768px) {
            .container {
                padding: 20px 10px;
            }
            .markdown-body {
                padding: 20px;
            }
            .header h1 {
                font-size: 1.8em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📚 Wine Finder Next.js Documentation</h1>
            <p>Comprehensive guide for Claude Code instances working with this repository</p>
        </div>
        
        <div id="toc" class="toc" style="display: none;">
            <h3>📑 Table of Contents</h3>
            <div id="toc-content"></div>
        </div>
        
        <div id="content" class="markdown-body">
            <div class="loading">Loading documentation...</div>
        </div>
    </div>

    <script>
        // Read the CLAUDE.md file content
        const claudeMdContent = `# 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)`;

        // Function to generate table of contents
        function generateTOC(content) {
            const lines = content.split('\n');
            const toc = [];
            let currentLevel = 0;
            
            lines.forEach(line => {
                const match = line.match(/^(#{1,3})\s+(.+)$/);
                if (match) {
                    const level = match[1].length;
                    const title = match[2];
                    const id = title.toLowerCase().replace(/[^\w]+/g, '-');
                    
                    if (level <= 3) {
                        toc.push({
                            level: level,
                            title: title,
                            id: id
                        });
                    }
                }
            });
            
            let tocHtml = '<ul>';
            let currentLevel = 0;
            
            toc.forEach(item => {
                if (item.level > currentLevel) {
                    tocHtml += '<ul>'.repeat(item.level - currentLevel);
                } else if (item.level < currentLevel) {
                    tocHtml += '</ul>'.repeat(currentLevel - item.level);
                }
                
                tocHtml += `<li><a href="#${item.id}">${item.title}</a></li>`;
                currentLevel = item.level;
            });
            
            tocHtml += '</ul>'.repeat(currentLevel);
            
            return tocHtml;
        }

        // Function to add IDs to headers
        function addHeaderIds(html) {
            return html.replace(/<h([1-3])>(.+?)<\/h\1>/g, (match, level, content) => {
                const id = content.toLowerCase().replace(/[^\w]+/g, '-');
                return `<h${level} id="${id}">${content}</h${level}>`;
            });
        }

        // Render the markdown
        document.addEventListener('DOMContentLoaded', function() {
            // Configure marked options
            marked.setOptions({
                highlight: function(code, lang) {
                    if (Prism.languages[lang]) {
                        return Prism.highlight(code, Prism.languages[lang], lang);
                    }
                    return code;
                },
                breaks: true,
                gfm: true
            });

            // Generate and display table of contents
            const tocHtml = generateTOC(claudeMdContent);
            document.getElementById('toc-content').innerHTML = tocHtml;
            document.getElementById('toc').style.display = 'block';

            // Render markdown content
            let htmlContent = marked.parse(claudeMdContent);
            htmlContent = addHeaderIds(htmlContent);
            document.getElementById('content').innerHTML = htmlContent;

            // Smooth scroll for TOC links
            document.querySelectorAll('.toc a').forEach(anchor => {
                anchor.addEventListener('click', function(e) {
                    e.preventDefault();
                    const targetId = this.getAttribute('href').substring(1);
                    const targetElement = document.getElementById(targetId);
                    if (targetElement) {
                        targetElement.scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>