# Chocolate Ordering System - Architecture

## Overview
Node.js/Express backend with SQLite database, serving static HTML/JS frontend with JWT authentication.

## Directory Structure

```
chocolate-ordering-system/
├── server.js                 # Express server entry point
├── database.js              # SQLite database initialization and schema
├── routes/                  # API route handlers
│   ├── auth.js             # Authentication endpoints
│   ├── products.js         # Product CRUD operations
│   ├── orders.js           # Order management
│   ├── bulk-import.js      # Invoice parsing and bulk operations
│   └── currency.js         # Currency conversion (BNR API)
├── public/                  # Static frontend assets
│   ├── js/
│   │   ├── admin.js        # Admin panel logic
│   │   ├── customer.js     # Customer portal logic
│   │   └── image-gallery.js# Product image gallery
│   └── uploads/            # Product images
├── views/                   # HTML templates
│   ├── admin-dashboard.html
│   ├── customer-portal.html
│   └── login.html
└── Reference documents/     # Invoice templates and samples

```

## Architecture Layers

### 1. Backend (Node.js/Express)
- **server.js**: Express server initialization, middleware setup, static file serving
- **database.js**: SQLite database connection, table creation, initial data seeding
- **routes/**: RESTful API endpoints

### 2. Database (SQLite)
Schema:
- **users**: Authentication (admin/customer roles)
- **products**: Product catalog with pricing, weights, codes
- **orders**: Customer orders with line items
- **import_batches**: Track invoice import history
- **exchange_rates**: Historical EUR-RON rates from BNR

### 3. Frontend (Vanilla JavaScript)
- **admin.js**: Admin dashboard for product management, invoice processing, bulk editing
- **customer.js**: Customer portal for browsing and ordering products
- **image-gallery.js**: Product image viewer

## Key Features & Their Modules

### Invoice Processing
**Files**: `routes/bulk-import.js`, `public/js/admin.js`
- PDF parsing (pdf-parse library)
- Pattern matching for LAURENCE invoices
- Product matching (by producer code or name similarity)
- Cost calculation with transport and processing costs
- VAT and markup calculations

### Product Management
**Files**: `routes/products.js`, `public/js/admin.js`
- CRUD operations
- Bulk editor with Excel-like editing
- Product code management (cod_produs, cod_producator)

### Currency Exchange
**Files**: `routes/currency.js`, `public/js/admin.js`
- BNR (Romanian Central Bank) API integration
- Historical rate tracking
- EUR to RON conversion with localStorage persistence

### Authentication
**Files**: `routes/auth.js`, JWT middleware in route files
- JWT-based authentication
- Role-based access control (admin/customer)

## Data Flow

### Invoice Upload Flow
1. User uploads PDF invoice (admin-dashboard.html)
2. POST /api/bulk/upload-invoice → routes/bulk-import.js
3. pdf-parse extracts text from PDF
4. Regex patterns match product lines
5. Product matching against database (code → name similarity)
6. Return matched products to frontend
7. User reviews matches, adjusts prices
8. POST /api/bulk/process-invoice-costs
9. Backend calculates transport allocation, processing costs, markup, VAT
10. User approves and saves to products
11. POST /api/bulk/save-invoice-costs updates product table

### Order Flow
1. Customer browses products (customer-portal.html)
2. Adds to cart (localStorage)
3. POST /api/orders/create → routes/orders.js
4. Creates order and line items in database
5. Admin views orders in admin dashboard

## API Endpoints

### Authentication
- POST /api/auth/login
- POST /api/auth/register

### Products
- GET /api/products
- POST /api/products
- PUT /api/products/:id
- DELETE /api/products/:id
- POST /api/products/bulk-update

### Invoice Processing
- POST /api/bulk/upload-invoice
- POST /api/bulk/process-invoice-costs
- POST /api/bulk/save-invoice-costs

### Currency
- GET /api/currency/fetch-bnr-rate
- GET /api/currency/latest

### Orders
- GET /api/orders
- POST /api/orders/create
- PUT /api/orders/:id/status

## Design Patterns

### Frontend
- **Module Pattern**: Separate concerns (admin.js, customer.js)
- **Event-Driven**: ContentEditable tables with blur events for live editing
- **LocalStorage Persistence**: Cart, settings, exchange rates

### Backend
- **Middleware Chain**: JWT auth → role check → route handler
- **Route Separation**: Feature-based route modules
- **Error Handling**: Try-catch with JSON error responses

## Third-Party Dependencies

### Backend
- **express**: Web server framework
- **sqlite3**: Database
- **jsonwebtoken**: Authentication
- **bcrypt**: Password hashing
- **pdf-parse**: PDF text extraction
- **axios**: HTTP requests to BNR API
- **multer**: File upload handling

### Frontend
- **Vanilla JavaScript**: No framework (performance, simplicity)
- **Fetch API**: AJAX requests
- **localStorage**: Client-side persistence

## Security
- JWT tokens with expiration
- Password hashing with bcrypt
- Role-based access control
- SQL parameterized queries (prevents SQL injection)
- File upload validation (PDF only, size limits)

## Performance Considerations
- SQLite for simplicity (single-user admin, low concurrent writes)
- Client-side table editing (no server round-trip per cell edit)
- Image optimization (user responsibility)
- LocalStorage caching (exchange rates, settings)

## Deployment Architecture

### Production Environment (cPanel/CloudLinux)
**Hosting**: reseller.methexis.eu
**Server**: CloudLinux with Passenger for Node.js
**Node Version**: 22.x
**Database**: SQLite (64KB, auto-created on first run)

### Passenger Configuration
The production server uses **Passenger (CloudLinux)**, not PM2:

**`.htaccess` Configuration**:
```apache
PassengerAppRoot "/home/username/reseller.methexis.eu"
PassengerBaseURI "/"
PassengerNodejs "/home/username/nodevenv/reseller.methexis.eu/22/bin/node"
PassengerAppType node
PassengerStartupFile server.js
```

**Key Characteristics**:
- Starts Node.js app automatically when first HTTP request arrives
- Idle timeout: Stops app after no requests for ~5 minutes
- Restart mechanism: `touch tmp/restart.txt` triggers reload
- Startup timeout: ~20 seconds (important for database initialization)
- No need for PM2 or other process managers

### Deployment Process
1. **Clone repository** to subdomain directory
2. **Activate Node.js environment**: `source /home/username/nodevenv/.../bin/activate`
3. **Install dependencies**: `npm install` (takes 20-30 minutes on shared hosting)
4. **Pre-initialize database**: Run `node server.js` briefly to create `database.db`
5. **Restart Passenger**: `touch tmp/restart.txt`
6. **Verify**: Check site returns HTTP 200

### Performance Characteristics
- **First request (cold start)**: 5-20 seconds (Passenger starts Node.js process)
- **Subsequent requests**: <100ms (app already running)
- **Database queries**: <10ms (SQLite, local file)
- **Invoice parsing**: 2-5 seconds (PDF processing)
- **npm install**: 20-30 minutes (254 packages on shared hosting)

### File Structure in Production
```
/home/username/reseller.methexis.eu/
├── server.js                    # Entry point
├── database.js                  # Schema definition
├── database.db                  # SQLite database (64KB, auto-created)
├── .htaccess                    # Passenger configuration
├── node_modules/                # 254 packages (symlinked to nodevenv)
├── routes/                      # API handlers
├── public/                      # Static assets
├── views/                       # HTML templates
├── uploads/                     # User-uploaded files
└── tmp/
    └── restart.txt              # Touch to restart Passenger
```

### Monitoring & Logs
- **Application logs**: Check Passenger error pages (Error ID shown on 500 errors)
- **Access logs**: `/home/username/logs/reseller.methexis.eu.access_log`
- **Error logs**: `/home/username/logs/reseller.methexis.eu.error_log`
- **Database integrity**: Run `node check-db.js` to verify schema

### Backup Strategy
- **Database**: `cp database.db database-backup-$(date +%Y%m%d).db`
- **Images**: `tar -czf uploads-backup.tar.gz uploads/`
- **Frequency**: Daily via cron job recommended
- **Storage**: Keep 7 days of backups

## Future Scalability
To scale beyond single-user:
- Replace SQLite with PostgreSQL/MySQL
- Add Redis for session management
- Implement WebSocket for real-time updates
- Add file storage service (S3) for product images
- Implement proper CI/CD pipeline
- Move from Passenger to dedicated Node.js hosting (PM2 + Nginx)
