# Alphabetical Sorting Update

## Changes Made

### Company Model (`models/Company.php`)
Updated default sorting to alphabetically order customers/companies by name:

1. **`getAll()` method** (line 85):
   - Changed from: `ORDER BY created_at DESC`
   - Changed to: `ORDER BY COALESCE(NULLIF(company_name, ''), CONCAT(first_name, ' ', last_name)) ASC`
   - This sorts by company_name if present, otherwise by full name (first + last)

2. **`getAllWithContextualStats()` method** (line 265):
   - Changed from: `ORDER BY c.created_at DESC`
   - Changed to: `ORDER BY COALESCE(NULLIF(c.company_name, ''), CONCAT(c.first_name, ' ', c.last_name)) ASC`
   - Ensures consistent alphabetical sorting with rich stats

## Impact

### All forms now show customers alphabetically in dropdowns:
- ✅ Invoices (create/edit)
- ✅ Sales Orders (create/edit)
- ✅ Quotes (create/edit)
- ✅ Payments (create)
- ✅ Customer Payments (create)
- ✅ Projects (create/edit)
- ✅ Battery Quotes (create)
- ✅ Sales Returns (create)
- ✅ Shipments (create)
- ✅ CRM Contacts (create)
- ✅ Recurring Transactions (create/edit)
- ✅ Sales Delivery Notes (create)
- ✅ Sales Pricing (create)
- ✅ All other customer selection forms

### Browse Modal (Entity Browser)
- ✅ API endpoint `/api/customers` returns alphabetically sorted results
- ✅ Search results maintain alphabetical order

### Views with Manual Sorting
These views already had `usort()` sorting and will continue to work:
- `views/sales/delivery-notes/create.php`
- `views/sales/returns/create.php`
- `views/shipments/create.php`

## Technical Details

**Sorting Logic:**
```sql
ORDER BY COALESCE(NULLIF(company_name, ''), CONCAT(first_name, ' ', last_name)) ASC
```

This ensures:
1. Companies with a company_name sort by that name
2. Individuals without a company_name sort by "FirstName LastName"
3. Empty company names are treated as NULL and fall back to full name
4. Case-insensitive alphabetical ordering (MySQL default)

## Testing

Test by checking any customer dropdown - customers should appear in alphabetical order:
1. Navigate to any form with customer selection
2. Open the dropdown
3. Verify customers are sorted A-Z by company name or full name

