# Zhik_Portal Module

## Overview
B2B dealer portal with comprehensive order creation system for Zhik's wholesale trade network.

## Version
**Current Version**: 0.0.1
*Note: Despite the version number, this is a production-ready module with mature features*

## Documentation

| Document | Purpose | Location |
|----------|---------|----------|
| **Order Creation Architecture** | Complete technical documentation of order creation system | [`docs/portal-order-architecture.md`](../../../../docs/portal-order-architecture.md) |
| **Platform Architecture Integration** | How Portal fits into overall platform | [`docs/platform-architecture.md#4.3.2`](../../../../docs/platform-architecture.md#432-zhik_portal-v001) |
| **Forward Order Extension** | Enhancement module that extends Portal | [`docs/forward-order-architecture.md`](../../../../docs/forward-order-architecture.md) |

## Key Features

### Order Management
- **Supergrid Interface**: Advanced product grid with real-time inventory
- **Category Item Counts**: Headers show product counts (e.g., "OFS900 RANGE [04]")
- **Saved Orders**: Draft order functionality for dealers
- **Draft Persistence**: localStorage auto-save with 24-hour expiry
- **Floating Summary Bar**: Real-time item count and total display
- **Bulk Operations**: CSV import/export for large orders
- **Multi-User Support**: Dealers, teams, and sales representatives

### Pricing & Inventory
- **MYOB Integration**: Real-time pricing from ERP
- **Customer-Specific Pricing**: Price lists per customer group
- **Backorder Management**: Configurable per customer
- **Multi-Warehouse**: Support for multiple stock locations

### Payment Processing
- **Gateway Abstraction**: `GatewayInterface` pattern supporting Braintree and eWay, switchable per website via admin config (`zhik_portal/payments/gateway`)
- **Invoice Payments** (`portal/payment`): Pay outstanding MYOB invoices with credit card
- **Order Payments** (`portal/orderpayment`): Pay MYOB sales orders to trigger shipment
- **Multi-Merchant Routing**: `BraintreeCredentialSwitcher` routes transactions to the correct Braintree merchant ID and merchant account based on the order's currency/website (not the session store)
- **Braintree Hosted Fields**: PCI SAQ-A compliant card entry with optional 3D Secure
- **MYOB Integration**: Payments auto-submitted to MYOB as AR Payment or Prepayment records

### Customer Features
- **Sales Rep Impersonation**: Order on behalf of dealers
- **Custom Categories**: Per-customer product visibility
- **Payment Terms**: Prepaid and postpaid support
- **Address Management**: Multiple shipping addresses

## Module Structure

```
Portal/
├── Block/
│   ├── Invoice/
│   │   └── Payment.php             # Invoice payment form block
│   ├── Order/
│   │   ├── Supergrid.php           # Main order creation interface
│   │   └── Supergrid/              # Supporting blocks
│   └── OrderPayment/
│       └── Form.php                # Order payment form block
├── Controller/
│   ├── Order/
│   │   ├── Index.php               # Order form display
│   │   ├── Submit.php              # Order processing
│   │   ├── Save.php                # Draft order saving
│   │   └── View.php                # Order viewing
│   ├── Payment/
│   │   ├── Submit.php              # Invoice payment processing
│   │   └── GetClientToken.php      # Braintree client token AJAX endpoint
│   └── OrderPayment/
│       ├── Lookup.php              # Order lookup
│       └── Submit.php              # Order payment processing
├── Helper/
│   └── Data.php                    # Portal utilities and authorization
├── Model/
│   ├── Payment/
│   │   ├── BraintreeCredentialSwitcher.php  # Per-website Braintree credential routing
│   │   └── Gateway/
│   │       ├── GatewayInterface.php         # Payment gateway contract
│   │       ├── GatewayResultInterface.php   # Payment result contract
│   │       ├── GatewayResult.php            # Result implementation
│   │       ├── GatewayFactory.php           # Website-based gateway selection
│   │       ├── BraintreeGateway.php         # Braintree implementation
│   │       └── EwayGateway.php              # eWay implementation
│   ├── SavedOrder.php              # Draft order management
│   └── Config/Source/
│       └── PaymentGateway.php      # Admin gateway dropdown source
├── Plugin/                         # Core functionality extensions
├── view/
│   └── frontend/
│       ├── layout/                 # Page layouts
│       ├── templates/
│       │   ├── invoice/            # Invoice payment templates
│       │   └── orderpayment/       # Order payment templates
│       └── web/
│           ├── js/
│           │   └── braintree-payment.js  # Braintree Hosted Fields
│           └── css/
└── etc/
    ├── module.xml                  # Module declaration
    ├── di.xml                      # Dependency injection
    ├── adminhtml/
    │   └── system.xml              # Admin config (gateway selection)
    └── frontend/
        └── routes.xml              # Frontend routing

```

## Dependencies

### Required Modules
- `Magento_Sales`
- `Magento_Quote`
- `Magento_Customer`
- `Magento_Catalog`
- `Zhik_Myoba` - For ERP integration
- `Zhik_Misc` - Utility functions
- `PayPal_Braintree` - Braintree payment gateway SDK and adapter

### PHP Requirements
- PHP 8.2+
- Magento 2.4.8+

## Configuration

### Admin Settings
Navigate to: **Stores > Configuration > Zhik Extensions > Dealer Portal**

Key configuration areas:
- Portal Category selection
- Prepayment settings
- MYOB integration options
- Allowed countries for shipping
- Payment processing options

### Customer Attributes
Per-customer settings available in customer edit form:
- `allow_backorders` - Team accounts only
- `dealer_categories` - Additional visible categories
- `hide_dealer_categories` - Hide default categories

## API Endpoints

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/portal/order` | GET | Display order form |
| `/portal/order/submit` | POST | Process order |
| `/portal/order/save` | POST | Save draft order |
| `/portal/order/view/{id}` | GET | View order details |
| `/portal/payment` | GET | Invoice payment form |
| `/portal/payment/submit` | POST | Process invoice payment |
| `/portal/payment/getClientToken` | GET | Braintree client token (AJAX, accepts `?website_id=X`) |
| `/portal/orderpayment/lookup` | GET | Order payment lookup |
| `/portal/orderpayment/submit` | POST | Process order payment |

## Development

### Testing
```bash
# Run unit tests
php bin/magento dev:tests:run unit Zhik_Portal

# Run integration tests
php bin/magento dev:tests:run integration Zhik_Portal
```

### Common Customizations

#### Extending Supergrid
```php
// Create a plugin for Supergrid block
class SupergridPlugin
{
    public function afterGetProducts(
        \Zhik\Portal\Block\Order\Supergrid $subject,
        $result
    ) {
        // Modify product collection
        return $result;
    }
}
```

#### Adding Order Attributes
Use the order submission plugin points to add custom attributes during order creation.

## Performance

Block caching with 24-hour lifetime:
- First load: 3.90s | Revisit: **562ms** (98.7% improvement from 42s)
- Category counts rendered server-side and cached with block
- Trade prices load fresh via JavaScript (not cached)

Key optimizations:
- N+1 query fixes (Myoba tax, color attribute)
- O(1) attribute lookups, batch tax calculations
- Title rendering moved into cached Category block

## Troubleshooting

### Common Issues

1. **Products not showing in Portal**
   - Check Portal Category configuration
   - Verify customer's dealer_categories attribute
   - Ensure products are enabled and in stock

2. **Pricing not loading**
   - Verify MYOB connection settings
   - Check customer's price class in MYOB
   - Review MYOB sync logs

3. **Order submission fails**
   - Check customer credit limits
   - Verify shipping address validity
   - Review order validation rules

## Support

For technical issues or questions:
- Review comprehensive documentation in [`docs/portal-order-architecture.md`](../../../../docs/portal-order-architecture.md)
- Check MYOB integration status in admin panel
- Review system logs in `var/log/portal.log`

## License

Proprietary - Zhik Pty Ltd

---

*This module is a core component of the ZhikTrade2 B2B platform. Handle with care during updates.*