# Add Purchase Error Analysis & Fix Report

## Main root cause
The Add Purchase screen, controller, and item-saving flow are using an **advanced purchase schema**, but the project still carries clear signs of a **legacy database structure**. That means the form submits fields and the controller writes columns that may not exist yet in older/live databases.

This is the most likely reason the Add Purchase page crashes on submit.

## Why this happens
The purchase workflow now depends on these newer columns/tables:

### purchases table
- branch_id
- purchase_type
- po_no
- supplier_id
- subtotal
- discount_total
- transport_cost
- landed_cost
- batch_no
- expiry_date
- received_status
- paid_amount
- due_amount
- payment_method
- approval_status
- approved_by
- approved_at

### purchase_items table
- batch_no
- expiry_date
- landed_unit_cost
- entered_unit
- unit_factor
- qty_in_base

### supporting table
- purchase_payments

If the live DB is missing any of the above, the PurchaseController store() flow can fail when saving purchase headers or line items.

## Additional issues found
1. **Quantity mismatch**
   - Frontend allowed decimal quantity (`step=0.01`)
   - Backend finally cast quantity to integer
   - This can create rounding/truncation issues and inconsistent stock

2. **Supplier name dependency**
   - Supplier Name was auto-filled mainly on select change
   - In some cases old/selected supplier state could still leave supplier_name unreliable during submit

3. **Payment method select was weakly defined**
   - Several option tags relied on implicit text values instead of explicit `value="..."`

## Files updated
1. `database/migrations/2026_03_30_160000_fix_purchase_workflow_schema_and_form.php`
   - Safely normalizes purchase-related schema for legacy/live DBs
   - Adds missing purchase columns if absent
   - Adds missing purchase item columns if absent
   - Creates `purchase_payments` table if missing

2. `app/Http/Controllers/Admin/PurchaseController.php`
   - Forces purchase row quantity validation to integer minimum 1
   - Rounds quantity safely before stock/item processing

3. `resources/views/admin/purchases/form.blade.php`
   - Quantity input changed to whole-number purchase flow
   - Payment method options now use explicit values
   - Supplier name sync improved on initial load and change event

## What you need to do after upload
Run migration on live/local project:

```bash
php artisan migrate
```

Then test:
- Add Purchase
- Add multiple rows
- Select supplier and save
- Verify stock increases correctly
- Verify purchase list and purchase details still load

## Final conclusion
This looked less like a simple controller typo and more like a **schema drift issue** caused by new purchase code being used on an older/partially migrated DB. The patch fixes that mismatch and also hardens the form so the same error is less likely to happen again.
