# Shipment Feature Work State
Last Updated: 2025-08-21

## Current Status
Working on fixing the "Best Carrier" column in the shipment page that shows "N/A" instead of actual carrier rates.

## Completed Tasks
1. ✅ Reverted all Finale inventory implementation changes
2. ✅ Moved test files to subdirectories for organization
3. ✅ Implemented supplier auto-selection in Order Items section
   - Best supplier logic: `is_cheapest && in_stock`
   - Auto-selects cheapest in-stock supplier in dropdown
4. ✅ Moved Shipping Method section to top (3-column layout with Billing/Shipping addresses)
5. ✅ Fixed warehouse list to match old central system
   - Added dynamic warehouses (WSP_UPS, WSP_DHL, FBA) based on order conditions
6. ✅ Copied ShipStation API credentials from old central's config.php
   - Created `/config/shipstation.php` with all warehouse credentials
7. ✅ Added CSRF token meta tag to layout
8. ✅ Fixed JavaScript AJAX implementation with proper error handling

## Current Issue: Best Carrier Shows "N/A"

### Problem
The Best Carrier column shows "N/A" even though:
- Suppliers exist with stock (verified in database)
- Order 839751 has item 965311 with partslink GM1236108
- 6 suppliers in stock, cheapest is supplier 8 at $9.00

### Debugging Done
1. Added extensive logging to `calculateBestRate()` method
2. Temporarily disabled status=1 check for testing
3. Fixed AJAX URL issues (removed duplicate `/public`)
4. Added proper CSRF token handling
5. Added error handling and "Calculating..." state

### Files Modified

#### Primary Files
- `/resources/views/shipment/ship.blade.php` - Main shipment view
- `/app/Http/Controllers/ShipmentController.php` - Controller with getDelivery() and calculateBestRate()
- `/app/Services/CarrierRateService.php` - Service for fetching carrier rates
- `/app/Services/ShipStationService.php` - ShipStation API integration
- `/config/shipstation.php` - API credentials for each warehouse
- `/resources/views/layouts/app.blade.php` - Added CSRF token meta tag

#### Key Code Sections

**Supplier Auto-Selection (ship.blade.php)**
```php
@php
    $bestSupplierId = null;
    if ($item->product && $item->product->partslink) {
        $bestSupplier = \DB::table('parts_suppliers')
            ->join('suppliers', 'parts_suppliers.supplier_id', '=', 'suppliers.supplier_id')
            ->where('parts_suppliers.partslink', $item->product->partslink)
            ->where('parts_suppliers.qty', '>', 0)
            ->where('suppliers.is_active', true)
            ->orderBy('parts_suppliers.price')
            ->first();
        if ($bestSupplier) {
            $bestSupplierId = $bestSupplier->supplier_id;
        }
    }
@endphp
```

**AJAX Delivery Info Update (ship.blade.php)**
```javascript
function updateDeliveryInfo() {
    const warehouse = warehouseSelect.value;
    const itemRows = document.querySelectorAll('tr[data-item-id]');
    const allItems = Array.from(itemRows).map(row => row.getAttribute('data-item-id'));
    
    fetch(APP_URL + '/shipment/get-delivery', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': csrfToken || '',
            'Accept': 'application/json'
        },
        credentials: 'same-origin',
        body: JSON.stringify({
            warehouse: warehouse,
            items: allItems
        })
    })
    // ... response handling
}
```

**calculateBestRate Method (ShipmentController.php)**
```php
private function calculateBestRate($item, $warehouse) {
    // Get supplier ID from item or find cheapest
    // Get order for shipping address
    // Get dimensions from product
    // Call CarrierRateService->getShippingHandlingCost()
    // Format response: "[WH] Carrier $X.XX + Y.YY"
}
```

## Next Steps
1. Check browser console for JavaScript errors when selecting warehouse
2. Monitor Laravel logs when warehouse is selected: `tail -f storage/logs/laravel.log`
3. Verify getDelivery() endpoint is being called successfully
4. Check if CarrierRateService is returning rates properly
5. Test with different warehouses to see if any return rates

## Important Notes
- Old system uses ShipStation API with warehouse-specific credentials
- Suppliers have `ss_accounts` field mapping to warehouses
- Best carrier logic requires status=1 (Needs Order) - currently disabled for testing
- System should show rates like "[WH] Carrier $X.XX + Y.YY"
- AJAX calls all item IDs, not just selected ones (matches old system behavior)

## URL Structure
- Base URL: `https://opstest.go-parts.com/central-new/public`
- Shipment page: `/shipment/ship/{orderId}`
- AJAX endpoint: `/shipment/get-delivery`

## Database Tables Involved
- `orders` - Main order data
- `order_items` - Individual items in orders
- `products` - Product information
- `parts_suppliers` - Supplier inventory and pricing
- `suppliers` - Supplier information including ss_accounts
- `shipments` - Shipment records

## Testing Orders
- Order 839751 - Has item with suppliers in stock
- Order 839746 - Another test order

## Git Status
Last commit: "Implement supplier auto-selection and fix warehouse list"
- Added supplier auto-selection logic
- Fixed warehouse list to match old central
- Moved Shipping Method section to top