# Transfer Rate Implementation Guide

## Overview
This feature allows clients to transfer stock between locations with different valuation prices. Instead of always using the original purchase price, you can now set a separate "transfer price" for valuating transferred stock.

## Changes Made

### 1. Database Migration
**File:** `database/migrations/2025_12_04_add_transfer_price_to_purchase_lines.php`

Added new column to `purchase_lines` table:
- `transfer_price_inc_tax` (DECIMAL 20,4) - Optional field that stores the price used when stock is transferred
  - If NULL: Uses `purchase_price_inc_tax` for valuation
  - If SET: Uses this value for valuation of transferred stock

**To run migration:**
```bash
php artisan migrate
```

### 2. Stock Price Calculation Update
**File:** `app/Utils/ProductUtil.php` (Line 1894)

Updated the stock price calculation query to use transfer price when available:
```php
COALESCE(pl.transfer_price_inc_tax, purchase_price_inc_tax)
```

This means:
- For normal purchases: Uses `purchase_price_inc_tax`
- For transfers with set price: Uses `transfer_price_inc_tax`
- Falls back to purchase price if transfer price not set

### 3. Stock Mismatch Controller Enhancement
**File:** `app/Http/Controllers/StockMismatchController.php`

Enhanced `recalculatePurchaseLines()` to:
- Include `purchase_transfer` transactions in calculations
- Track `transfer_price_inc_tax` and transaction type
- Reset `stock_reset` flag to enable proper valuation

## How to Use

### Setting Transfer Prices When Creating a Stock Transfer

When you create a stock transfer in your system, you can now:

1. **Set at original purchase price** (No change needed)
   - Leave `transfer_price_inc_tax` as NULL
   - Stock will value at original purchase price

2. **Set at custom transfer price** (New feature)
   - Set `transfer_price_inc_tax` to a custom value (e.g., slightly higher)
   - Stock will value at the transfer price instead

### Example Scenario

**Original Purchase:**
- Item purchased at Rs 100 (purchase_price_inc_tax)
- 10 units in Location A

**Transfer to Location B with higher rate:**
- Transfer 10 units from Location A to Location B
- Set transfer_price_inc_tax to Rs 105 (slightly higher)

**Stock Valuation Results:**
- Location A: 0 units × Rs 100 = Rs 0
- Location B: 10 units × Rs 105 = Rs 1,050 (using transfer price)

### Stock Value Report Display

When viewing the Stock Report or Profit & Loss:
- **Closing Stock (By purchase price):** Calculated using transfer prices where set
- **Stock Value:** Will reflect the transfer prices for transferred items
- **Potential Profit:** Will be based on transfer price valuations

## Integration Points

### Stock Transfer Module
When creating/updating stock transfers, populate `transfer_price_inc_tax`:

```php
// Example in StockTransferController (pseudocode)
$purchase_line->update([
    'transfer_price_inc_tax' => $transfer_price // Set custom price
]);
```

### Recalculation Process

After transfer operations:
1. Click "Fix All Mismatches" (corrects qty_available)
2. Click "Recalculate Stock Values" (redistributes quantities and resets stock_reset flag)
3. Stock values will now use transfer prices where applicable

## Backward Compatibility

- **Existing transfers:** transfer_price_inc_tax will be NULL, so original purchase price is used
- **No breaking changes:** System works exactly as before if transfer prices aren't set
- **Gradual adoption:** You can start using transfer prices on new transfers without affecting old ones

## Database Query Example

To view which items have transfer prices set:
```sql
SELECT 
    pl.id,
    p.name,
    pl.quantity,
    pl.purchase_price_inc_tax,
    pl.transfer_price_inc_tax,
    CASE 
        WHEN pl.transfer_price_inc_tax IS NOT NULL THEN pl.transfer_price_inc_tax
        ELSE pl.purchase_price_inc_tax
    END as valuation_price
FROM purchase_lines pl
JOIN products p ON p.id = pl.product_id
WHERE pl.transfer_price_inc_tax IS NOT NULL
ORDER BY pl.created_at DESC;
```

## Troubleshooting

### Stock Value Still Shows 0
1. Check if `variation_location_details.stock_reset` = 1
2. Run "Fix All Mismatches" then "Recalculate Stock Values"
3. Verify migration has been applied: `php artisan migrate:status`

### Transfer Price Not Applied
1. Ensure `transfer_price_inc_tax` is populated in purchase_lines
2. Run "Recalculate Stock Values" button to refresh calculations
3. Check database: `SELECT transfer_price_inc_tax FROM purchase_lines WHERE id = ?`

### Performance Impact
- Minimal: Uses COALESCE which is efficient in MySQL
- No additional joins required
- Column is indexed like purchase_price_inc_tax

## Future Enhancements

Potential improvements:
1. UI form field to input transfer price during stock transfer creation
2. Auto-calculate transfer price based on percentage markup/markdown
3. Transfer price history/audit trail
4. Bulk update transfer prices for multiple items
5. Transfer price approval workflow

## Support

For issues or questions, refer to:
- Database: `purchase_lines` table structure
- Code: `StockMismatchController.php` recalculation logic
- Report: `ProductUtil.php` stock price calculation
