# Magento 2 GetAddress.io Autocomplete Extension

## Overview

This Magento 2 extension integrates getAddress.io address autocomplete functionality into your checkout process, replacing standard address fields with an intelligent autocomplete form that provides real-time address suggestions.

## Checkout Layout

The autocomplete form appears on the **Shipping Address** step of the checkout process. Here's how it's positioned:

```
Checkout Page (Shipping Step)
├── Email Address Field
├── Shipping Address Section
│   └── 📍 Find Your Address (GetAddress.io Autocomplete Form) ← INSERTED HERE
│       ├── Search Input (Postcode/Address)
│       ├── Loading Indicator (Spinner)
│       ├── Address Results Dropdown
│       └── Selected Address Display
├── Standard Shipping Form Fields (Hidden until address selected)
├── Shipping Method Section
└── Review & Payments Button
```

### Component Placement
- **Parent Element**: `form-shipping-address` (Magento checkout form component)
- **Position**: First element (sort order: 0)
- **Visibility**: Conditional based on admin configuration (enabled flag + API key)

### What You Should See

✅ **When Enabled (with API Key configured)**:
- Blue-bordered form box with "📍 Find Your Address" heading
- Text input field with placeholder "Enter postcode (e.g., SW1A 2AA) or address"
- Loading spinner when searching
- Dropdown list of matching addresses
- Selected address display with "Change Address" button

❌ **When Disabled (without API Key or not configured)**:
- Yellow warning box: "⚠️ Address Autocomplete is disabled. Please enable it in the Magento admin configuration with a valid getAddress.io API key."
- Standard Magento address form fields display below

## Key Features

### Core Functionality
- ✅ **GetAddress.io Integration** - Seamless integration with getAddress.io API
- ✅ **Real-time Address Autocomplete** - Address suggestions as customers type
- ✅ **Address Validation** - Validates addresses using authoritative UK address database
- ✅ **Postcode Search** - Quick address lookup by postcode
- ✅ **Checkout Integration** - Works smoothly with Magento checkout flow
- ✅ **Address Formatting** - Automatically formats addresses correctly

### Technical Features
- ✅ **REST API Endpoints** - API methods for address search and retrieval
- ✅ **Extension Attributes** - Custom address attributes for tracking autocomplete data
- ✅ **Quote Integration** - Stores autocomplete metadata with quote/order
- ✅ **Responsive Design** - Mobile-friendly autocomplete interface
- ✅ **Error Handling** - Graceful error management with user feedback
- ✅ **Logging** - Detailed logging for debugging and monitoring

## Troubleshooting

### Issue: No autocomplete form appears (spinner visible before content loads)

**Symptom**: Page loads and shows a spinner briefly, then displays standard Magento form without the address autocomplete box.

**Solution**:
1. **Check Admin Configuration**:
   - Go to Stores > Configuration > Sales > Checkout > Address Autocomplete
   - Ensure "Enable Address Autocomplete" is set to **Yes**
   - Ensure "API Key" field is populated with a valid getAddress.io API key
   - Click **Save Config**

2. **Flush Cache**:
   ```bash
   php bin/magento cache:clean
   ```

3. **Deploy Static Files**:
   ```bash
   php bin/magento setup:static-content:deploy -f
   ```

4. **Check Console for Debug Messages**:
   - Open browser DevTools (F12)
   - Go to **Console** tab
   - Look for messages starting with "Address Autocomplete Component:"
   - If disabled, check the reason logged

### Issue: Configuration not taking effect

**Solution**:
1. Ensure both conditions are met:
   - ✅ Enable flag is set to **Yes** 
   - ✅ API Key field is **not empty**
2. If only API Key is missing, component is disabled (shows warning)
3. Clear Magento cache and refresh browser

### Issue: Debugging Component Initialization

**Steps**:
1. Open browser **DevTools** (F12 or Right-click > Inspect)
2. Go to **Console** tab
3. Reload the checkout page
4. Look for "Address Autocomplete Component:" messages:
   - ✓ **✓ Address Autocomplete Component Loaded and ENABLED** - Working correctly
   - ✗ **✗ Address Autocomplete Component DISABLED** - Check reasons listed below

5. **Common Disable Reasons**:
   - "window.checkoutConfig not found" - Page configuration not loaded
   - "getaddress_autocomplete config section not found" - ConfigProvider not registered
   - "Module not enabled or API key not configured" - Check admin settings

## Installation

### Step 1: Install via Composer

```bash
composer require portalpeople/magento-addresslookup
```

### Step 2: Enable Module

```bash
php bin/magento module:enable PortalPeople_GetAddressAutocomplete
php bin/magento setup:upgrade
php bin/magento cache:clean
```

### Step 3: Configure API Key

1. Log in to Magento Admin
2. Navigate to: **Stores** > **Configuration** > **Sales** > **Checkout** > **Address Autocomplete**
3. Enable the extension
4. Enter your getAddress.io API key (obtained from https://getaddress.io)
5. Save configuration

## Configuration

### GetAddress.io API Key

To use this extension, you need a getAddress.io API key:

1. Visit https://getaddress.io
2. Sign up for an account (free tier available)
3. Generate an API key
4. Copy the key to Magento admin configuration

### Module Settings

The module provides the following configuration options in the Magento Admin:

- **Enable Address Autocomplete** - Toggle the extension on/off
- **API Key** - Your getAddress.io API key
- **Default Country** - Default country for address lookups (default: GB)

## Usage

### For Customers

1. During checkout, customers will see the address autocomplete field
2. They can search by:
   - **Postcode** (e.g., "SW1A 2AA")
   - **Address text** (e.g., "10 Downing Street")
3. Matching addresses appear in a dropdown list
4. Select the correct address to auto-populate the form
5. Continue with checkout

### For Developers

#### API Endpoints

The module provides the following REST API endpoints:

##### Search Addresses
```
POST /V1/getaddress/address/search
```

Request:
```json
{
    "search_term": "SW1A 2AA"
}
```

Response:
```json
{
    "success": true,
    "addresses": [
        {
            "address": "10 Downing Street, London",
            "postcode": "SW1A 2AA",
            "AddressId": 12345
        }
    ]
}
```

##### Get Address Details
```
GET /V1/getaddress/address/details
```

Request:
```json
{
    "address_id": "12345"
}
```

##### Save Address to Quote
```
POST /V1/getaddress/address/save
```

Request:
```json
{
    "postcode": "SW1A 2AA",
    "udprn": 12345,
    "organisation": "",
    "building": "10 Downing Street",
    "street": "Street Name",
    "city": "London",
    "county": ""
}
```

## Architecture

### Directory Structure

```
magento-getaddress-autocomplete/
├── src/
│   ├── Api/
│   │   └── AddressAutocompleteInterface.php    # API contracts
│   ├── Model/
│   │   └── AddressAutocompleteManagement.php   # Business logic
│   ├── view/
│   │   └── frontend/
│   │       ├── layout/
│   │       │   └── checkout_index_index.xml    # Layout updates
│   │       ├── requirejs-config.js             # RequireJS config
│   │       └── web/
│   │           ├── js/
│   │           │   ├── action/
│   │           │   │   └── set-shipping-information-mixin.js
│   │           │   ├── view/
│   │           │   │   └── address-autocomplete.js
│   │           │   └── model/
│   │           ├── css/
│   │           │   └── address-autocomplete.css
│   │           └── template/
│   │               └── address-autocomplete.html
│   └── etc/
│       ├── module.xml                          # Module config
│       ├── di.xml                              # Dependency injection
│       ├── extension_attributes.xml            # Extension attributes
│       └── frontend/
│           └── di.xml                          # Frontend DI config
├── composer.json
└── README.md
```

### Key Components

#### AddressAutocompleteInterface
API contract defining address autocomplete operations:
- `searchAddresses($searchTerm)` - Search for addresses
- `getAddressDetails($addressId)` - Get full address details
- `saveAddress(...)` - Save address to quote

#### AddressAutocompleteManagement
Implements the API interface with:
- getAddress.io API integration
- Quote address management
- Error handling and logging

#### JavaScript Component (address-autocomplete.js)
- Handles frontend autocomplete UI
- Communicates with backend API
- Manages address selection and population

## Customization

### Modifying Templates

Edit `src/view/frontend/web/template/address-autocomplete.html` to customize the autocomplete form HTML.

### Styling

Modify `src/view/frontend/web/css/address-autocomplete.css` to change the look and feel.

### JavaScript Logic

Edit `src/view/frontend/web/js/view/address-autocomplete.js` to customize the autocomplete behavior.

## Troubleshooting

### Extension Not Showing

1. Verify module is enabled: `php bin/magento module:status | grep GetAddress`
2. Clear cache: `php bin/magento cache:clean`
3. Check that API key is configured

### API Key Invalid

- Verify key is correct in admin configuration
- Check getAddress.io account is active
- Ensure key has API access enabled

### Address Not Found

- Try searching by postcode instead of address
- Verify the address exists in UK address database
- Check network connectivity to getAddress.io API

### JavaScript Errors

- Check browser console for errors
- Ensure RequireJS is properly configured
- Clear browser cache and reload

## Support

For issues, questions, or feature requests:

- **Email**: support@portalpeople.uk
- **Website**: https://portalpeople.uk
- **Repository**: https://dev.azure.com/PortalPeopleUK/ngauge_modules/_git/magento-getaddress-autocomplete

## License

This extension is released under the MIT License. See the LICENSE file for details.

## Changelog

### Version 1.0.0 (Initial Release)
- Initial release with core autocomplete functionality
- getAddress.io API integration
- Checkout flow integration
- REST API endpoints
- Mobile-responsive design
