# CLAUDE.md

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

## Project Overview

CRU World Wine is a fine wine investment and trading e-commerce platform built on **Magento Enterprise Edition** (PHP 8.4). The platform handles wine trading, portfolio management, live market pricing, B2B operations, and integrations with external accounting, payment, and messaging services.

## Development Commands

### JavaScript / Frontend Build
```bash
# Production webpack build
npm run build

# Development webpack build
npm run build-dev

# Webpack dev server
npm start

# Compile SCSS via Grunt/Compass (watches for changes)
grunt

# Clear cache, full-page cache, and compiled CSS
make flush
```

### PHP Dependencies
```bash
composer install
composer update
```

### Docker (local environment)
```bash
docker-compose up -d        # Start all services (PHP, MySQL 8.0, Redis 6, Elasticsearch 5.6)
docker-compose down
docker-compose logs -f web.server
```

### Cache Management
```bash
# Clear all Magento caches (run from web-root/shell/)
php shell/cleanCache.php --all

# Or from project root:
make flush
```

### Magento Shell Scripts
```bash
# Run a shell script (from project root)
php web-root/shell/<script>.php [options]

# Re-index
php web-root/shell/indexer.php --reindex all
```

## Architecture

### Directory Structure
```
/web-root/                        # Magento document root (Apache/Nginx serves this)
├── app/code/local/Cru/           # All custom CRU modules (~78 modules)
├── app/code/community/           # Third-party Magento modules
├── app/etc/                      # Magento configuration (local.xml, config.xml)
├── app/design/                   # Layout XML, admin and frontend templates (.phtml)
├── skin/frontend/cru/            # Frontend themes (CSS/SCSS, JS, images)
├── shell/                        # CLI scripts for background/cron tasks
├── js/                           # Magento core and custom JavaScript
└── media/                        # User-uploaded files (not in git)
/bounce/                          # Ruby-based email bounce handler (Sisimai)
/webpack/                         # Webpack configuration files
/vendor/                          # Composer PHP dependencies
/node_modules/                    # NPM dependencies
/secure-data/                     # Secrets and credentials (not in git)
```

### Custom Modules (`web-root/app/code/local/Cru/`)
Each module follows standard Magento 1 structure:
```
Cru/<ModuleName>/
├── etc/config.xml       # Module registration and class mappings
├── Block/               # View blocks
├── Model/               # Business logic and data models
├── Helper/              # Utility classes (accessed via Mage::helper())
├── controllers/         # HTTP request handlers
├── Resource/            # Database resource models
└── sql/                 # Install/upgrade SQL scripts
```

Key module groups:
- **Trading/Markets**: `LiveMarkets`, `Livex`, `InsideMarket`, `Bids`, `Trade`
- **Commerce**: `Catalog`, `Checkout`, `Payment`, `Sales`, `Shipping`, `Surcharge`, `Inventory`
- **Portfolio/Investment**: `Portfolio`, `PortfolioWatchlist`, `InvestmentFinder`, `Investmentresearch`
- **Customer/CRM**: `Customer`, `CustomerBalance`, `Salesrep`, `B2b`, `Company`, `Personal`
- **Messaging**: `Email`, `EmailCampaign`, `EmailTracker`, `EmailBounce`, `Fcm`, `Whatsapp`, `MessageTracker`
- **Integrations**: `Chatgpt` (OpenAI), `Xero` (accounting), `ThirdParty`, `Otp`
- **Admin/Config**: `Adminhtml`, `Reports`, `Dashboard`, `Bi`, `Menu`, `Layout`

### Frontend
- Theme at `web-root/skin/frontend/cru/default/`
- SCSS source compiled to `web-root/skin/frontend/cru/default/css/styles.css` via Grunt/Compass
- Webpack bundles JS from `web-root/skin/frontend/cru/default/js/src/`
- Multiple theme variants: `default`, `app` (mobile), `no-dutypaid`, `no-inbond`

### Infrastructure
- **Database**: MySQL 8.0 — primary DB `cruworldwine1`, log DB `cruworldwine_log`
- **Cache / Sessions**: Redis 6 (cache on DB 0, sessions on DB 2)
- **Search**: Elasticsearch 5.6
- **PHP**: 8.4

## Environment Configuration

Environment-specific configs live alongside each other:
```
web-root/app/etc/local.xml         # Active config (symlinked or copied)
web-root/app/etc/local.xml.DEV
web-root/app/etc/local.xml.STAGING
web-root/app/etc/local.xml.LIVE
web-root/web-root/.htaccess.DEV / .STAGING / .LIVE
```

The active environment is determined by which `local.xml` is in place. Secrets (DB credentials, API keys) live in `local.xml` and `/secure-data/` — never commit these.

## Background Jobs / Shell Scripts

`web-root/shell/` contains PHP CLI scripts organized by domain:
- `customer/` — sales rep assignment, email chasing, exports
- `email/` — bounce handling, campaigns
- `livex/` — Livex trading platform sync (last trade, cellar sync)
- `liveMarkets/` — live market data tasks
- `dailyTasks/` — routine maintenance
- `bids/`, `shipping/`, `category/`, `fix/` — domain-specific tasks
- `ai/`, `chatgpt/` — OpenAI integration tasks

Scripts typically extend `Mage_Shell_Abstract` and accept `--` prefixed arguments.

## Deployment

- **Staging**: Auto-deployed via GitHub Actions on push to `staging` branch — SSH pull + cache clear on `crustaging.com` (34.90.141.227)
- **Production**: Manual deploy via git pull to production server
- There is no automated test suite; test manually after changes

## Partner Trading API (`Cru_Api`)

Before touching `web-root/app/code/local/Cru/Api/`, read
`web-root/app/code/local/Cru/Api/docs/` — it maps the bid/offer domain model, the module
internals, the tables, and the Liv-ex / Bordeaux Index reference integrations, so this work does
not need a codebase-wide scan. Partner-facing docs stay in `web-root/docs/api/`.

## Key Third-Party Integrations

| Service | Module / Package |
|---|---|
| Nuvei (payment) | `Cru_Payment`, `lib/nuvei-server-php/` |
| Checkout.com (payment) | `Cru_Payment/Model/Ckopayment`, `checkout/checkout-sdk-php` |
| Xero (accounting) | `Cru_Xero`-like, `xeroapi/xero-php-oauth2` |
| OpenAI / ChatGPT | `Cru_Chatgpt`, `orhanerday/open-ai` |
| Firebase FCM | `Cru_Fcm`, `firebase/php-jwt` |
| Google APIs | `google/apiclient`, `google/auth` |
| Livex (wine market) | `Cru_Livex` |
| mPDF | `mpdf/mpdf` (PDF generation) |
| MongoDB | `mongodb/mongodb` (optional sessions) |

## Magento Patterns Used Throughout

- **Mage::getModel('module/classname')** — instantiate models
- **Mage::helper('module')** — get helper instances
- **Mage::getSingleton('...')** — singleton models
- **Mage::app()->getStore()** — store/scope context
- **Observer pattern** via `config.xml` `<events>` nodes
- **Rewrites** in `config.xml` to override core classes
- Database schema changes go in `sql/<module_setup>/` upgrade scripts

## Coding Conventions

- PHP classes follow Magento 1 PSR-0-like naming: `Cru_ModuleName_Block_Foo` → `app/code/local/Cru/ModuleName/Block/Foo.php`
- New modules must be registered in `app/etc/modules/Cru_ModuleName.xml`
- Admin grid/form work lives under `Block/Adminhtml/` and controllers in `controllers/Adminhtml/`
- Frontend CSS changes: edit SCSS in `skin/frontend/cru/default/scss/`, then run `grunt`
- JS changes: edit source in `skin/frontend/cru/default/js/src/`, then run `npm run build`
