Commit 8f9963d8 authored by mattwire's avatar mattwire
Browse files

Add caching to getAddressIO. Refactor tpl and javascript to improve maintainability.

parent 7964e316
......@@ -18,20 +18,22 @@ class CRM_Civicrmpostcodelookup_Page_GetAddressIo extends CRM_Civicrmpostcodeloo
if (!self::isValidPostcode($postcode)) {
exit;
}
$number = CRM_Utils_Request::retrieve('number', 'String');
$apiUrl = self::getAddressIoApiUrl($postcode, $number);
// get address result from getAddress.io
$addressData = self::addressAPIResult($apiUrl);
$addresslist = [];
if ($addressData['is_error']) {
$addresslist[0]['value'] = '';
$addresslist[0]['label'] = CRM_Utils_Array::value('Message', $addressData, 'Error in fetching address');
} else {
$addresslist = self::getAddressList($addressData, $postcode);
$addressList = \Civi::cache('long')->get("ukpostcodes_{$postcode}") ?? NULL;
if (!isset($addressList)) {
// get address result from getAddress.io
$apiUrl = self::getAddressIoApiUrl($postcode);
$addressData = self::addressAPIResult($apiUrl);
if ($addressData['is_error']) {
$addressList[0]['value'] = '';
$addressList[0]['label'] = CRM_Utils_Array::value('Message', $addressData, 'Error in fetching address');
} else {
$addressList = self::getAddressList($addressData, $postcode);
}
\Civi::cache('long')->set("ukpostcodes_{$postcode}", $addressList);
}
echo json_encode($addresslist);
echo json_encode($addressList);
exit;
}
......@@ -46,27 +48,17 @@ class CRM_Civicrmpostcodelookup_Page_GetAddressIo extends CRM_Civicrmpostcodeloo
// get postcode & address key from selectedId
$selectedResult = explode('_', $selectedId);
$postcode = $selectedResult[0];
$postcode = CRM_Civicrmpostcodelookup_Page_Civipostcode::format($selectedResult[0], FALSE);
$addressKey = $selectedResult[1];
$apiUrl = self::getAddressIoApiUrl(self::format($postcode, FALSE));
// get address result from getAddress.io
$addressData = self::addressAPIResult($apiUrl);
$addressList = \Civi::cache('long')->get("ukpostcodes_{$postcode}") ?? NULL;
$addresslist = [];
if ($addressData['is_error']) {
$address = [];
} else {
$addressItems = $addressData['addresses'];
// selected result from the addressItems
$addressItem = $addressList[$addressKey];
// selected result from the addressItems
$addressItem = $addressItems[$addressKey];
$address = self::formatAddressLines($selectedId, $addressItem);
// Fix me : postcode not returned in the API result, hence using the one from the selected ID
$address['postcode'] = $postcode;
}
$address = $addressItem['lineArray'];
// Fix me : postcode not returned in the API result, hence using the one from the selected ID
$address['postcode'] = $postcode;
$response = [
'address' => $address
......@@ -103,7 +95,7 @@ class CRM_Civicrmpostcodelookup_Page_GetAddressIo extends CRM_Civicrmpostcodeloo
$apiKey = $settingsArray['api_key'];
$querystring = "api-key=$apiKey";
$querystring = "api-key=$apiKey&expand=true";
return $servertarget ."?" . $querystring;
}
......@@ -200,12 +192,13 @@ class CRM_Civicrmpostcodelookup_Page_GetAddressIo extends CRM_Civicrmpostcodeloo
// FIX me : There is no address id found in th API, hence assigning combination of postcode & arrayresultID as rowId inorder to get the selected address later
$addressId = $postcode . '_' . $key;
$addressLineArray = self::formatAddressLines($addressId, $addressItem, TRUE);
$addressLineArray = self::formatAddressLines($addressId, $addressItem);
$addressLineArray['postcode'] = $postcode;
$addressRow["id"] = $addressId;
$addressRow["value"] = $postcode;
$addressRow["label"] = @implode(', ', $addressLineArray);;
$addressRow["label"] = @implode(', ', $addressLineArray);
$addressRow['lineArray'] = $addressLineArray;
array_push($addressList, $addressRow);
}
......@@ -219,49 +212,40 @@ class CRM_Civicrmpostcodelookup_Page_GetAddressIo extends CRM_Civicrmpostcodeloo
return $addressList;
}
private static function formatAddressLines($addressId, $addressItem, $forList = FALSE) {
private static function formatAddressLines($addressId, $addressItem) {
if (empty($addressItem)) {
return;
}
$addressLines = explode(', ', $addressItem);
if ($forList == FALSE) {
$address = ['id' => $addressId];
}
if (!empty($addressLines[0])) {
$address["street_address"] = $addressLines[0];
}
if (!empty($addressLines[1])) {
$address["supplemental_address_1"] = $addressLines[1];
if (!empty($addressItem->line_1)) {
$address['street_address'] = $addressItem->line_1;
}
if (!empty($addressLines[2])) {
$address["supplemental_address_2"] = $addressLines[2];
if (!empty($addressItem->line_2)) {
$address['supplemental_address_1'] = $addressItem->line_2;
};
if (!empty($addressItem->line_3)) {
$address['supplemental_address_2'] = $addressItem->line_2;
}
if (!empty($addressLines[5])) {
$address["town"] = $addressLines[5];
if (!empty($addressItem->town_or_city)) {
$address['city'] = $addressItem->town_or_city;
}
// Get state/county
$states = CRM_Core_PseudoConstant::stateProvince();
$address["state_province_id"] = '';
if (!empty($addressLines[6])) {
$stateId = array_search($addressLines[6], $states);
if ($stateId) {
if ($forList) {
// Display actual state name in selection list
$address['state_province_id'] = $addressLines[6];
}
else {
// Use state ID when returning to fill in details (via a select2)
$address["state_province_id"] = $stateId;
}
if (!isset(\Civi::$statics[__FUNCTION__]['stateprovince'])) {
\Civi::$statics[__FUNCTION__]['stateprovince'] = CRM_Core_PseudoConstant::stateProvince();
}
$address['state_province_id'] = '';
if (!empty($addressItem->county)) {
$stateProvinceID = array_search($addressItem->county, \Civi::$statics[__FUNCTION__]['stateprovince']);
if ($stateProvinceID) {
// Display actual state name in selection list
$address['state_province_id'] = $stateProvinceID;
}
$address['state_province'] = $addressItem->county;
}
$address['country_id'] = 1226;
return $address;
}
......
......@@ -138,7 +138,7 @@ function civicrmpostcodelookup_civicrm_navigationMenu(&$menu) {
function civicrmpostcodelookup_civicrm_buildForm($formName, &$form) {
$postCodeLookupPages = [
'CRM_Contact_Form_Contact'
'CRM_Contact_Form_Contact'
, 'CRM_Contact_Form_Inline_Address'
, 'CRM_Profile_Form_Edit'
, 'CRM_Event_Form_Registration_Register'
......@@ -151,32 +151,42 @@ function civicrmpostcodelookup_civicrm_buildForm($formName, &$form) {
// Assign the postcode lookup provider to form, so that we can call the related function in AJAX
$settingsStr = \Civi::settings()->get('api_details');
$settingsArray = unserialize($settingsStr);
$form->assign('civiPostCodeLookupProvider', $settingsArray['provider']);
$jsVars['lookupProvider'] = $settingsArray['provider'];
$settingsArray['location_type_id'] = $settingsArray['location_type_id'] ?? [];
$settingsArray['location_type_id']['Primary'] = 1;
foreach ($settingsArray['location_type_id'] as $location => $_) {
$addressSelectors[] = [
'id' => $location,
'suffix' => "-{$location}",
'prefix' => '',
'selector' => "#editrow-street_address-{$location}",
'beforeSelector' => ".crm-profile #editrow-street_address-{$location}",
];
// On behalf of address
$addressSelectors[] = [
'id' => $location,
'suffix' => "-{$location}",
'prefix' => 'onbehalf_',
'selector' => "#onbehalf_street_address-{$location}",
'beforeSelector' => "div#on-behalf-block fieldset div#editrow-street_address-{$location}",
];
// Backend addresses
$addressSelectors[] = [
'suffix' => '',
'prefix' => "address_{$location}_",
'selector' => "#address_{$location}_street_address",
'beforeSelector' => "tr#streetAddress_{$location}",
];
}
// Billing address
$addressSelectors[] = [
'id' => '5',
'suffix' => '-5',
'prefix' => 'billing_',
'selector' => '#billing_street_address-5',
'beforeSelector' => '.billing_street_address-5-section',
];
$jsVars['addressSelectors'] = $addressSelectors;
\Civi::resources()->addVars('ukpostcodes', $jsVars);
\Civi::resources()->addScriptFile(E::LONG_NAME, 'js/ukpostcodelookup.js');
$form->assign('ukpostcodesAddressSelectors', json_encode($addressSelectors));
}
}
......
(function($) {
var ukpostcodes = {
load: function() {
var addressSelectors = CRM.vars.ukpostcodes.addressSelectors;
var blockId = '';
var postCodeHtml = '';
// Location Types from settings
if (addressSelectors) {
$.each(addressSelectors, function (id, address) {
if ($(address.selector).length > 0) {
blockId = address.prefix + address.suffix;
var postcodeElement = 'inputPostCode_' + blockId;
postCodeHtml = '' +
'<div class="crm-section addressLookup form-item">' +
'<div class="label">' +
'<label for="addressLookup">Search for an address</label>' +
'</div>' +
'<div class="edit-value content">' +
'<div class="crm-postcodelookup-textbox-wrapper">' +
'<input placeholder="Start typing a postcode" name="' + postcodeElement + '" id="' + postcodeElement + '" class="crm-postcodelookup ui-autocomplete-input" style="width: 25em;">' +
'</div>' +
'</div>' +
'<div class="clear" />' +
'</div>';
if ($('#' + postcodeElement).length === 0) {
$(address.beforeSelector).before(postCodeHtml);
var minCharacters = 4;
var postcodeProvider = CRM.vars.ukpostcodes.lookupProvider;
if (postcodeProvider !== 'civipostcode') {
$(postcodeElement)
.attr("placeholder", "Type full postcode to find addresses");
minCharacters = 5;
}
var sourceUrl = CRM.url('civicrm/' + CRM.vars.ukpostcodes.lookupProvider + '/ajax/search', {"json": 1});
$('#' + postcodeElement).autocomplete({
source: sourceUrl,
minLength: minCharacters,
data: {postcode: $('#' + postcodeElement).val(), mode: '0'},
select: function (event, ui) {
if (ui.item.id !== '') {
findAddressValues(ui.item.id, address.suffix, address.prefix);
}
return false;
},
html: true, // optional (jquery.ui.autocomplete.html.js required)
//optional (if other layers overlap autocomplete list)
open: function (event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
}
}
});
}
function findAddressValues(id, blockSuffix, blockPrefix) {
setAddressFields(false, blockSuffix, blockPrefix);
var sourceUrl = CRM.url('civicrm/' + CRM.vars.ukpostcodes.lookupProvider + '/ajax/get', {"json": 1});
$.ajax({
dataType: 'json',
data: {id: id, mode: '0'},
url: sourceUrl,
success: function (data) {
setAddressFields(data.address, blockSuffix, blockPrefix);
setAddressFields(true, blockSuffix, blockPrefix);
}
});
}
function setAddressFields(address, blockSuffix, blockPrefix) {
var postcodeElement = '#' + blockPrefix + 'postal_code' + blockSuffix;
var streetAddressElement = '#' + blockPrefix + 'street_address' + blockSuffix;
var AddstreetAddressElement = '#' + blockPrefix + 'supplemental_address_1' + blockSuffix;
var AddstreetAddressElement1 = '#' + blockPrefix + 'supplemental_address_2' + blockSuffix;
var cityElement = '#' + blockPrefix + 'city' + blockSuffix;
var countyElement = '#' + blockPrefix + 'state_province_id' + blockSuffix;
if ($(countyElement).length === 0) {
countyElement = '#' + blockPrefix + 'state_province' + blockSuffix;
}
var countryElement = '#' + blockPrefix + 'country_id' + blockSuffix;
if ($(countryElement).length === 0) {
countryElement = '#' + blockPrefix + 'country' + blockSuffix;
}
var allFields = {
postcode: postcodeElement,
line1: streetAddressElement,
line2: AddstreetAddressElement,
line3: AddstreetAddressElement1,
city: cityElement
};
if (address === true) {
for (var field in allFields) {
$(allFields[field]).removeAttr('disabled');
}
}
else
if (address === false) {
for (var field2 in allFields) {
$(allFields[field2]).attr('disabled', 'disabled');
}
}
else {
$(streetAddressElement).val('');
$(AddstreetAddressElement).val('');
$(AddstreetAddressElement1).val('');
$(cityElement).val('');
$(postcodeElement).val('');
$(countryElement).val(address.country_id).trigger('change');
if (($(AddstreetAddressElement1).length === 0) && (typeof address.supplemental_address_2 !== 'undefined')) {
if (typeof address.supplemental_address_1 !== 'undefined') {
address.supplemental_address_1 = address.supplemental_address_1 + ', ';
}
address.supplemental_address_1 = address.supplemental_address_1 + address.supplemental_address_2;
}
if (($(AddstreetAddressElement).length === 0) && (typeof address.supplemental_address_1 !== 'undefined')) {
address.street_address = address.street_address + ', ' + address.supplemental_address_1;
}
$(streetAddressElement).val(address.street_address);
$(AddstreetAddressElement).val(address.supplemental_address_1);
$(AddstreetAddressElement1).val(address.supplemental_address_2);
$(cityElement).val(address.city);
$(postcodeElement).val(address.postcode);
if (typeof (address.state_province_id) !== 'undefined' && address.state_province_id !== null) {
$(countyElement).val(address.state_province_id);
}
// Trigger change on all the elements we touch so that other functions can react
// eg. a checkbox for "My billing address is the same".
$(streetAddressElement).trigger('change');
$(AddstreetAddressElement).trigger('change');
$(AddstreetAddressElement1).trigger('change');
$(cityElement).trigger('change');
$(postcodeElement).trigger('change');
$(countyElement).trigger('change');
}
}
}
};
if (typeof CRM.ukpostcodes === 'undefined') {
CRM.ukpostcodes = ukpostcodes;
}
document.addEventListener('DOMContentLoaded', function() {
CRM.ukpostcodes.load();
});
// Re-prep form when we've loaded a new payproc via ajax or via webform
$(document).ajaxComplete(function(event, xhr, settings) {
// Load postcode lookup on inline address edit (contact summary)
// On wordpress these are urlencoded
if (settings.url.match("civicrm(\/|%2F)ajax(\/|%2F)inline(.*)class_name=CRM_Contact_Form_Inline_Address") !== null) {
CRM.ukpostcodes.load();
}
});
}(CRM.$));
{*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*}
{literal}
<script type="text/javascript">
CRM.$(function($) {
......@@ -41,16 +51,9 @@
source: sourceUrl,
minLength: minCharacters,
data: {postcode: $('#' + postcodeElement).val(), mode: '0'},
search: function(event, ui) {
$('#loaderimage_' + blockNo).show();
},
response: function( event, ui ) {
$('#loaderimage_' + blockNo).hide();
},
select: function(event, ui) {
if (ui.item.id !== '') {
findAddressValues(ui.item.id, address.id, address.prefix);
$('#loaderimage_' + blockNo).show();
}
return false;
},
......@@ -67,7 +70,6 @@
}
function findAddressValues(id , blockNo, blockPrefix) {
$('#loaderimage_'+blockNo).show();
setAddressFields(false, blockNo, blockPrefix);
var sourceUrl = CRM.url('civicrm/{/literal}{$civiPostCodeLookupProvider}{literal}/ajax/get', {"json": 1});
$.ajax({
......@@ -77,9 +79,6 @@
success: function (data) {
setAddressFields(data.address, blockNo, blockPrefix);
setAddressFields(true, blockNo, blockPrefix);
},
complete: function (data) {
$('#loaderimage_'+blockNo).hide();
}
});
}
......@@ -104,8 +103,8 @@
city: cityElement
};
if(address === true) {
for(var field in allFields) {
if (address === true) {
for (var field in allFields) {
$(allFields[field]).removeAttr('disabled');
}
}
......@@ -122,24 +121,35 @@
$(postcodeElement).val('');
$(countyElement).val('');
if (($(AddstreetAddressElement1).length === 0) && (typeof address.supplemental_address_2 !== 'undefined')) {
if (typeof address.supplemental_address_1 !== 'undefined') {
address.supplemental_address_1 = address.supplemental_address_1 + ', ';
}
address.supplemental_address_1 = address.supplemental_address_1 + address.supplemental_address_2;
}
if (($(AddstreetAddressElement).length === 0) && (typeof address.supplemental_address_1 !== 'undefined')) {
address.street_address = address.street_address + ', ' + address.supplemental_address_1;
}
$(streetAddressElement).val(address.street_address);
$(AddstreetAddressElement).val(address.supplemental_address_1);
$(AddstreetAddressElement1).val(address.supplemental_address_2);
$(cityElement).val(address.town);
$(postcodeElement).val(address.postcode);
$(countryElement).val("1226").trigger('change');
$(countryElement).val('1226'); // United Kingdom
if (typeof(address.state_province_id) !== 'undefined' && address.state_province_id !== null) {
$(countyElement).val(address.state_province_id);
}
// Trigger change on all the elements we touch so that other functions can react
// eg. a checkbox for "My billing address is the same".
$(streetAddressElement).trigger("change");
$(AddstreetAddressElement).trigger("change");
$(AddstreetAddressElement1).trigger("change");
$(cityElement).trigger("change");
$(postcodeElement).trigger("change");
$(countyElement).trigger("change");
$(streetAddressElement).trigger('change');
$(AddstreetAddressElement).trigger('change');
$(AddstreetAddressElement1).trigger('change');
$(cityElement).trigger('change');
$(postcodeElement).trigger('change');
$(countryElement).trigger('change')
$(countyElement).trigger('change');
}
}
});
......
{* HEADER *}
{*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*}
<div class="crm-block crm-form-block crm-export-form-block">
{foreach from=$elementNames item=elementName}
......
{* Include file having postcodelookup textbox and JS functions *}
{include file='CRM/Civicrmpostcodelookup/Form/Postcodelookup.tpl'}
{*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2014 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| Copyright CiviCRM LLC. All rights reserved. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*}
......
{* Include file having postcodelookup textbox and JS functions *}
{include file='CRM/Civicrmpostcodelookup/Form/Postcodelookup.tpl'}
{*{include file='CRM/Civicrmpostcodelookup/Form/Postcodelookup.tpl'}*}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment