forked from experiandataquality/GlobalIntuitive
-
Notifications
You must be signed in to change notification settings - Fork 17
/
address-search.ts
2109 lines (1859 loc) · 89.5 KB
/
address-search.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import EventFactory from './event-factory';
import Request from './request';
import {
AddAddressesOptions,
AddressSearchOptions,
AddressValidationConfidenceType,
AddressValidationLookupKeywords,
AddressValidationMode,
AddressValidationSearchType,
defaults
} from './search-options';
import {datasetCodes} from './datasets-codes';
import {predefinedFormats} from './predefined-formats';
import {translations} from './translations';
import {
AddressValidationResult,
DatasetsResponse,
EnrichmentDetails,
EnrichmentResponse,
LookupAddress, LookupSuggestion,
LookupV2Response,
LookupW3WResponse,
Picklist,
PicklistItem,
PoweredByLogo,
PredefinedFormats,
SearchResponse,
What3WordsPickList
} from './class-types';
import {enrichmentOutput} from "./enrichment-output";
import {consumerViewDescriptions} from "./consumer-view-description";
import {regionalGeocodeDescriptions} from "./regional-geocodes-description";
export default class AddressValidation {
public options: AddressSearchOptions;
public searchType: AddressValidationSearchType;
public avMode: AddressValidationMode;
public events;
public request: Request;
public countryDropdown: {country: string, iso3Code: string, iso2Code: string, datasetCodes: string[], searchTypes: string[]}[] = [];
public componentsCollectionMap = new Map<string, string>();
public metadataCollectionMap = new Map<string, string>();
public geocodes: EnrichmentDetails = new EnrichmentDetails();
public cvHousehold: EnrichmentDetails = new EnrichmentDetails();
public tooltipDescriptionMap = new Map<string, string>();
public premiumLocationInsightMap = new Map<string, string>();
private baseUrl = 'https://api.experianaperture.io/';
private datasetsEndpoint = 'address/datasets/v1';
private searchEndpoint = 'address/search/v1';
private lookupV2Endpoint = 'address/lookup/v2';
private validateEndpoint = 'address/validate/v1';
private promptsetEndpoint = 'address/promptsets/v1';
private stepInEndpoint = 'address/suggestions/stepin/v1';
private refineEndpoint = 'address/suggestions/refine/v1';
private enrichmentEndpoint = 'enrichment/v2';
private picklist: Picklist;
private inputs: HTMLInputElement[];
private lastSearchTerm: string;
private currentSearchTerm: string;
private lookupType: string;
private returnAddresses: boolean;
private currentCountryCode: string;
private currentCountryName: string;
private currentDataSet: string[];
private hasSearchInputBeenReset: boolean;
private countryCodeMapping;
private lookupFn;
private keyUpFn;
private checkTabFn;
constructor(options: AddressSearchOptions) {
this.options = this.mergeDefaultOptions(options);
this.events = new EventFactory();
this.setup();
}
public setToken(token: string): void {
this.options.token = token;
this.setup();
}
public setSearchType(searchType: AddressValidationSearchType): void {
this.searchType = searchType;
this.globalReset();
this.setInputs();
this.events.trigger('post-search-type-change', searchType);
}
public getLookupEnrichmentData(key: string) {
if (key) {
let regionalAttributes = {
geocodes: Object.keys(enrichmentOutput.GLOBAL.geocodes),
premium_location_insight: {} = [
"geocodes",
"geocodes_building_xy",
"geocodes_access",
"time"
]
}
this.callEnrichment(key, regionalAttributes);
}
}
public getEnrichmentData(data: EnrichmentResponse) {
this.events.trigger('pre-enrichment');
this.result.handleEnrichmentResponse(data);
}
private getEnrichmentAttributes(globalAddressKey: string) {
if (globalAddressKey) {
let regionalAttributes: {};
let premium_location_insight: {} = [
"geocodes",
"geocodes_building_xy",
"geocodes_access",
"time"
]
if (this.currentCountryCode == "NZL") {
regionalAttributes = {
nzl_regional_geocodes: Object.keys(enrichmentOutput.NZL.nzl_regional_geocodes),
nzl_cv_household: Object.keys(enrichmentOutput.NZL.nzl_cv_household),
premium_location_insight
}
} else if (this.currentCountryCode == "AUS") {
regionalAttributes = {
aus_regional_geocodes: Object.keys(enrichmentOutput.AUS.aus_regional_geocodes),
aus_cv_household: Object.keys(enrichmentOutput.AUS.aus_cv_household),
premium_location_insight
}
} else if (this.currentCountryCode == "USA") {
regionalAttributes = {
usa_regional_geocodes: Object.keys(enrichmentOutput.USA.usa_regional_geocodes),
premium_location_insight
}
} else if (this.currentCountryCode == "GBR") {
regionalAttributes = {
uk_location_essential: Object.keys(enrichmentOutput.GBR.uk_location_essential),
what3words: Object.keys(enrichmentOutput.GBR.what3words),
premium_location_insight
}
} else {
regionalAttributes = {
geocodes: Object.keys(enrichmentOutput.GLOBAL.geocodes),
premium_location_insight
}
}
return regionalAttributes;
}
}
private callEnrichment(key: string, regionalAttributes) : void {
let data = {
country_iso: this.currentCountryCode,
keys: {
global_address_key: key
},
attributes: regionalAttributes
}
this.events.trigger('pre-enrichment');
this.request.send(this.baseUrl + this.enrichmentEndpoint, 'POST', this.result.handleEnrichmentResponse, JSON.stringify(data));
}
private setup(): void {
// Get token and proceed if it's present
if (this.token) {
this.hasSearchInputBeenReset = true;
// Instantiate a new Request class for use when making API calls
this.request = new Request(this);
// Set the country list
this.setCountryList();
// Set the input fields for this search type
this.setInputs();
// Setup a picklist object
this.createPicklist();
// Set the default search mode
this.searchType = AddressValidationSearchType.COMBINED;
this.avMode = AddressValidationMode.SEARCH;
} else {
// Trigger a 401 Unauthorized event if a token does not exist
setTimeout(() => this.events.trigger('request-error-401'));
}
}
private getParameter(name): string {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
// Try and get token from the query string if it's not already provided
private get token(): string {
if (!this.options.token) {
this.options.token = this.getParameter('token');
}
return this.options.token;
}
private mergeDefaultOptions(customOptions): AddressSearchOptions {
const instance: AddressSearchOptions = customOptions || {};
instance.enabled = true;
this.searchType = instance.searchType || defaults.searchType;
instance.searchType = instance.searchType || defaults.searchType;
instance.language = instance.language || defaults.language;
instance.useSpinner = instance.useSpinner || defaults.useSpinner;
instance.applyFocus = (typeof instance.applyFocus !== 'undefined') ? instance.applyFocus : defaults.input.applyFocus;
instance.placeholderText = instance.placeholderText || defaults.input.placeholderText;
instance.searchAgain = instance.searchAgain || {};
instance.searchAgain.visible = (typeof instance.searchAgain.visible !== 'undefined') ? instance.searchAgain.visible : defaults.searchAgain.visible;
instance.searchAgain.text = instance.searchAgain.text || defaults.searchAgain.text;
instance.formattedAddressContainer = instance.formattedAddressContainer || defaults.formattedAddressContainer;
instance.formattedAddressContainer.showHeading = (typeof instance.formattedAddressContainer.showHeading !== 'undefined') ? instance.formattedAddressContainer.showHeading : defaults.formattedAddressContainer.showHeading;
instance.formattedAddressContainer.headingType = instance.formattedAddressContainer.headingType || defaults.formattedAddressContainer.headingType;
instance.formattedAddressContainer.validatedHeadingText = instance.formattedAddressContainer.validatedHeadingText || defaults.formattedAddressContainer.validatedHeadingText;
instance.formattedAddressContainer.manualHeadingText = instance.formattedAddressContainer.manualHeadingText || defaults.formattedAddressContainer.manualHeadingText;
instance.useAddressEnteredText = instance.useAddressEnteredText || defaults.useAddressEnteredText;
instance.elements = instance.elements || {};
return instance;
}
private getPromptset(): void {
if (this.currentCountryCode) {
// Using the country code and the search type, lookup what the relevant dataset code should be
this.currentDataSet = this.lookupDatasetCodes();
if (this.currentDataSet) {
/// Temporary measure until the promptset endpoint supports Autocomplete and Validate
if (this.searchType === AddressValidationSearchType.AUTOCOMPLETE || this.searchType === AddressValidationSearchType.COMBINED) {
setTimeout(() => this.handlePromptsetResult({ result: { lines: [{ example: this.options.placeholderText, prompt: 'Address', suggested_input_length: 160 }] } }));
return;
} else if (this.searchType === AddressValidationSearchType.VALIDATE) {
const lines = [
{ prompt: 'Address line 1', suggested_input_length: 160 },
{ prompt: 'Address line 2', suggested_input_length: 160 },
{ prompt: 'Address line 3', suggested_input_length: 160 },
{ prompt: this.result.createAddressLine.label('locality'), suggested_input_length: 160 },
{ prompt: this.result.createAddressLine.label('region'), suggested_input_length: 160 },
{ prompt: this.result.createAddressLine.label('postal_code'), suggested_input_length: 160 }
];
setTimeout(() => this.handlePromptsetResult({ result: { lines } }));
return;
} else if (this.searchType === AddressValidationSearchType.LOOKUPV2) {
const tempDatasets = JSON.stringify(this.currentDataSet.map(x => x.toUpperCase()).sort());
const lines = [
{prompt: 'Lookup type', suggested_input_length: 160,
dropdown_options: Object.values(AddressValidationLookupKeywords)
.filter(type => type.dataset.length == 0 || type.dataset.map(x => JSON.stringify(x.map(y => y.toUpperCase()).sort())).some(x => x == tempDatasets))},
{prompt: 'Return addresses - if "true" addresses are returned in the response',
suggested_input_length: 160, dropdown_options: Object.values(AddAddressesOptions)},
{prompt: 'Lookup value', suggested_input_length: 160}
];
setTimeout(() => this.handlePromptsetResult({result: { lines } }));
return;
}
const data = {
country_iso: this.currentCountryCode,
datasets: Array.isArray(this.currentDataSet) ? this.currentDataSet : [this.currentDataSet],
search_type: this.searchType,
prompt_set: 'optimal'
};
this.events.trigger('pre-promptset-check');
this.request.send(this.baseUrl + this.promptsetEndpoint, 'POST', this.handlePromptsetResult.bind(this), JSON.stringify(data));
return;
}
this.events.trigger('error-display', "Unsupported search type '" + this.searchType + "' for country dataset '" + this.currentCountryName + "'.");
}
}
private lookupDatasetCodes(): string[] {
const item = datasetCodes.find(dataset =>
dataset.iso3Code === this.currentCountryCode
&& dataset.country === this.currentCountryName
&& dataset.searchTypes.includes(this.searchType));
if (item) {
return item.datasetCodes;
}
}
private lookupSearchTypes(countryCode: string, countryName: string): string[] {
const items = datasetCodes.filter(dataset =>
dataset.iso3Code === countryCode
&& dataset.country === countryName);
if (items.length > 0) {
const searchTypePriorityOrder = Object.values(AddressValidationSearchType);
return items.flatMap(x => x.searchTypes)
.map(y => AddressValidationSearchType[y.toUpperCase()])
.sort((a, b) => searchTypePriorityOrder.indexOf(a) - searchTypePriorityOrder.indexOf(b));
}
}
private readPredefinedFormats(): PredefinedFormats[] {
const item = predefinedFormats.filter(format =>
format.countryIso === this.currentCountryCode);
if (item) {
return item;
}
}
private handlePromptsetResult(response): void {
// Remove any currently displayed picklist when the promptset changes
this.picklist.hide();
// Trigger a new event to notify subscribers
this.events.trigger('post-promptset-check', response);
}
public setInputs(inputs = this.options.elements.inputs): void {
// If address inputs exist then register these with event listeners, otherwise call the promptset endpoint to retrieve them
if (inputs) {
this.registerInputs(inputs);
} else {
// Make an API call to get the promptset for this country/dataset/engine
this.getPromptset();
}
if (this.searchType !== AddressValidationSearchType.AUTOCOMPLETE && this.searchType !== AddressValidationSearchType.COMBINED) {
// Bind an event listener on the lookup button
if (this.options.elements.lookupButton) {
this.lookupFn = this.search.bind(this);
this.options.elements.lookupButton.addEventListener('click', this.lookupFn);
}
}
}
private registerInputs(inputs: HTMLInputElement[]) {
// If new inputs have been provided, ensure we update the elements array to capture them
this.inputs = Array.from(inputs);
this.inputs.forEach(input => {
// Disable autocomplete on the form fields
input.setAttribute(AddressValidationSearchType.AUTOCOMPLETE, 'new-password');
input.setAttribute(AddressValidationSearchType.COMBINED, 'new-password');
if (this.searchType === AddressValidationSearchType.AUTOCOMPLETE || this.searchType === AddressValidationSearchType.COMBINED) {
// Bind an event listener on the input
this.keyUpFn = this.search.bind(this);
input.addEventListener('keyup', this.keyUpFn);
this.checkTabFn = this.checkTab.bind(this);
input.addEventListener('keydown', this.checkTabFn);
// Set a placeholder for the input
input.setAttribute('placeholder', this.options.placeholderText);
}
// Bind an event listener on the input to allow users to traverse up and down the picklist using the keyboard
input.addEventListener('keyup', this.handleKeyboardEvent.bind(this));
});
this.countryCodeMapping = this.options.countryCodeMapping || {};
// Apply focus to the first input
if (this.options.applyFocus) {
this.inputs[0].focus();
}
}
private setCountryList(): void {
let url = this.baseUrl + this.datasetsEndpoint;
this.request.send(url, 'GET', this.handleDatasetsResponse.bind(this));
// Set the initial country code from either the value of a country list HTML element or a static country code
if (this.options.elements.countryList) {
this.currentCountryCode = this.options.elements.countryList.value;
this.currentCountryName = this.options.elements.countryList[this.options.elements.countryList.selectedIndex].label;
// Listen for when a country is changed and call the promptset endpoint
this.options.elements.countryList.addEventListener('change', this.handleCountryListChange.bind(this));
} else if (this.options.countryCode) {
this.currentCountryCode = this.options.countryCode;
} else {
throw new Error('Please provide a country code or a country list element');
}
}
private handleDatasetsResponse(response: DatasetsResponse): void {
let countries = response.result;
this.countryDropdown = [];
if (countries && countries.length > 0) {
for (const country of countries) {
for (const countryDataset of Object.values(country.datasets)) {
const item = datasetCodes.find(dataset => dataset.datasetCodes.length == 1 && dataset.datasetCodes[0] === countryDataset.id);
if (item && !this.countryDropdown.find(o => o.country === item.country)) {
this.countryDropdown.push(item);
}
}
if (country.valid_combinations) {
country.valid_combinations.forEach(countryDatasetCombination => {
let sorted = countryDatasetCombination.slice().sort()
const item = datasetCodes.find(dataset => Array.isArray(dataset.datasetCodes)
&& dataset.datasetCodes.length === sorted.length
&& dataset.datasetCodes.slice().sort().every(function(value, index) { return value === sorted[index]; }))
if (item && !this.countryDropdown.find(o => o.country === item.country)) {
this.countryDropdown.push(item);
}
});
}
}
this.countryDropdown.sort((a, b) => a.country.localeCompare(b.country))
this.events.trigger('post-datasets-update');
}
}
// When a country from the list is changed, update the current country code, call the promptset endpoint again
private handleCountryListChange(): void {
let countryList = this.options.elements.countryList;
this.currentCountryCode = countryList.value;
this.currentCountryName = countryList[countryList.selectedIndex].label;
this.getPromptset();
// If supported, keep the same search type as previous search, otherwise select the first one from the array
// of available search types
let availableSearchTypes = this.lookupSearchTypes(this.currentCountryCode, this.currentCountryName);
let isCurrentSearchTypeSupported: boolean = false;
if (this.searchType !== null){
isCurrentSearchTypeSupported = availableSearchTypes.indexOf(this.searchType) >= 0 ? true : false;
}
if (!isCurrentSearchTypeSupported){
this.searchType = AddressValidationSearchType[availableSearchTypes[0].toUpperCase()];
this.setInputs();
this.events.trigger('post-search-type-change', this.searchType);
}
// Set to default search mode
this.avMode = AddressValidationMode.SEARCH;
// Trigger a new event to notify subscribers
this.events.trigger('post-country-list-change', availableSearchTypes, this.searchType);
}
private generateSearchDataForApiCall(): string {
// If a dataset code hasn't been set yet, try and look it up
if (!this.currentDataSet) {
this.currentDataSet = this.lookupDatasetCodes();
}
const data = {
country_iso: this.currentCountryCode,
components: { unspecified: [this.currentSearchTerm] },
datasets: Array.isArray(this.currentDataSet) ? this.currentDataSet : [this.currentDataSet],
max_suggestions: (this.options.maxSuggestions || this.picklist.maxSuggestions)
};
if (this.searchType === AddressValidationSearchType.SINGLELINE || this.searchType === AddressValidationSearchType.VALIDATE) {
data['attributes'] = {};
data['options'] = [
{
name: 'flatten',
Value: 'true'
},
{
name: 'intensity',
Value: 'close'
},
{
name: 'prompt_set',
Value: 'default'
}
];
if (this.currentDataSet.includes("gb-address")
|| this.currentDataSet.includes("gb-additional-multipleresidence")
|| this.currentDataSet.includes("gb-additional-notyetbuilt")
|| this.currentDataSet.includes("gb-address-addressbase")
|| this.currentDataSet.includes("gb-additional-addressbaseislands")
|| this.currentDataSet.includes("gb-additional-business")
|| this.currentDataSet.includes("gb-additional-electricity")
|| this.currentDataSet.includes("gb-additional-gas")
|| this.currentDataSet.includes("gb-address-streetlevel")
|| this.currentDataSet.includes("gb-additional-businessextended")
|| this.currentDataSet.includes("gb-address-wales")){
data['attributes'] = {
"uk_location_essential":[
"latitude",
"longitude",
"match_level",
"uprn",
"x_coordinate",
"y_coordinate",
"udprn"
]
};
}
else if(this.currentDataSet.includes("us-address")){
data['attributes'] = {
"usa_location_insight":[
"delivery_point_barcode",
"dpc",
"check_digit",
"congressional_district_code",
"county_code",
"record_type",
"latitude",
"longitude",
"match_level",
"carrier_route",
"census_tract_number"
]
};
}
else if (this.currentDataSet.includes("au-address")
|| this.currentDataSet.includes("au-address-gnaf")
|| this.currentDataSet.includes("au-address-datafusion")){
data['attributes']['AUS_CV_Household'] = [
"address",
"adults_at_address_code",
"adults_at_address_description",
"affluence_code",
"affluence_description",
"channel_preference",
"channel_preference_description",
"children_at_address_code_0_10_years",
"children_at_address_code_11_18_years",
"children_at_address_description_0_10_years",
"children_at_address_description_11_18_years",
"credit_demand_code",
"credit_demand_description",
"gnaf_latitude",
"gnaf_longitude",
"gnaf_pid",
"head_of_household_age_code",
"head_of_household_age_description",
"hin",
"household_composition_code",
"household_composition_description",
"household_income_code",
"household_income_description",
"length_of_residence_code",
"length_of_residence_description",
"lifestage_code",
"lifestage_description",
"local_government_area_code",
"local_government_area_name",
"meshblock",
"mosaic_group",
"mosaic_segment",
"mosaic_type",
"postcode",
"residential_flag",
"risk_insight_code",
"risk_insight_description",
"sa1",
"state",
"suburb",
"mosaic_factor1_percentile",
"mosaic_factor1_score",
"mosaic_factor2_percentile",
"mosaic_factor2_score",
"mosaic_factor3_percentile",
"mosaic_factor3_score",
"mosaic_factor4_percentile",
"mosaic_factor4_score",
"mosaic_factor5_percentile",
"mosaic_factor5_score"
];
data['attributes']['aus_regional_geocodes'] = [
"latitude",
"longitude",
"match_level",
"sa1",
"meshblock",
"lga_code",
"lga_name",
"street_pid",
"locality_pid",
"geocode_level_code",
"geocode_level_description",
"geocode_type_code",
"geocode_type_description",
"highest_level_longitude",
"highest_level_latitude",
"highest_level_elevation",
"highest_level_planimetric_accuracy",
"highest_level_boundary_extent",
"highest_level_geocode_reliability_code",
"highest_level_geocode_reliability_description",
"confidence_level_code",
"confidence_level_description",
"2021_meshblock_id",
"2021_meshblock_code",
"2021_meshblock_match_code",
"2021_meshblock_match_description",
"2016_meshblock_id",
"2016_meshblock_code",
"2016_meshblock_match_code",
"2016_meshblock_match_description",
"address_type_code",
"primary_address_pid",
"address_join_type",
"collector_district_id",
"collector_district_code",
"commonwealth_electoral_boundary_id",
"commonwealth_electoral_boundary_name",
"statistical_local_area_id",
"statistical_local_area_code",
"statistical_local_area_name",
"state_electoral_boundary_id",
"state_electoral_boundary_name",
"state_electoral_effective_start",
"state_electoral_effective_end",
"state_electoral_new_pid",
"state_electoral_new_name",
"state_electoral_new_effective_start",
"state_electoral_new_effective_end",
"address_level_longitude",
"address_level_latitude",
"address_level_elevation",
"address_level_planimetric_accuracy",
"address_level_boundary_extent",
"address_level_geocode_reliability_code",
"address_level_geocode_reliability_description",
"street_level_longitude",
"street_level_latitude",
"street_level_planimetric_accuracy",
"street_level_boundary_extent",
"street_level_geocode_reliability_code",
"street_level_geocode_reliability_description",
"locality_level_longitude",
"locality_level_latitude",
"locality_level_planimetric_accuracy",
"locality_level_geocode_reliability_code",
"locality_level_geocode_reliability_description",
"gnaf_legal_parcel_identifier",
"locality_class_code"
];
}
data['attributes']['premium_location_insight'] = [
"geocodes",
"geocodes_access",
"geocodes_building_xy",
"time"
];
if (this.searchType === AddressValidationSearchType.SINGLELINE) {
data['options'].push({
name: 'search_type',
Value: 'singleline'
});
}
if (this.searchType === AddressValidationSearchType.VALIDATE) {
data['layouts'] = ['default'];
data['layout_format'] = 'default';
}
}
if (this.options.location) {
data['location'] = this.options.location;
}
return JSON.stringify(data);
}
private generateLookupDataForApiCall(input: string, avMode: AddressValidationMode): string {
// If a dataset code hasn't been set yet, try and look it up
if (!this.currentDataSet) {
this.currentDataSet = this.lookupDatasetCodes();
}
// Set the dataset and layout for the Utilities Proposition. The default country drop down combines gas and electricity.
// Lookup by MPAN or MPRN requires a single dataset to be targeted instead.
let datasets = [];
let layouts = [];
switch (avMode) {
case AddressValidationMode.MPAN:
if (this.currentDataSet.includes('gb-additional-electricity')) {
datasets.push('gb-additional-electricity');
}
layouts.push('ElectricityUtilityLookup');
break;
case AddressValidationMode.MPRN:
if (this.currentDataSet.includes('gb-additional-gas')) {
datasets.push('gb-additional-gas');
}
layouts.push('GasUtilityLookup');
break;
default:
datasets = Array.isArray(this.currentDataSet) ? this.currentDataSet : [ this.currentDataSet ];
}
const data = {
country_iso: this.currentCountryCode,
datasets: datasets,
max_suggestions: (this.options.maxSuggestionsForLookup || this.picklist.maxSuggestions),
key: {
type: this.generateLookupType(avMode),
value: input,
},
layouts: layouts,
};
return JSON.stringify(data);
}
private getWhat3WordsLookupValue(input: string, shouldGetSuggestions: boolean): string {
if (input.startsWith('///') && shouldGetSuggestions) {
input = input.slice(3);
}
return input;
}
// Allow the keyboard to be used to either traverse up and down the picklist and select an item, or trigger a new search
private handleKeyboardEvent(event: KeyboardEvent): void {
event.preventDefault();
// Handle keyboard navigation
const key = this.getKey(event);
// If a picklist is populated then trigger its keyup event to select an item
if (this.picklist.size) {
if (key === 'ArrowUp' || key === 'ArrowDown' || key === 'Enter') {
this.picklist.keyup(event);
return;
}
} else {
// Otherwise, enable pressing 'enter' to trigger a new search
if (key === 'Enter') {
this.search(event);
return;
}
}
}
// Main function to search for an address from an input string
private search(event: KeyboardEvent): void {
event.preventDefault();
// Reset the search mode to default value
this.avMode = AddressValidationMode.SEARCH;
// Grab the country ISO code and (if it is present) the dataset name from the current value of the countryList (format: {countryIsoCode};{dataset})
const currentCountryInfo = this.countryCodeMapping[this.currentCountryCode] || this.currentCountryCode;
const countryCodeAndDataset = currentCountryInfo.split(';');
this.currentCountryCode = countryCodeAndDataset[0];
if (countryCodeAndDataset[1]) {
this.currentDataSet = countryCodeAndDataset[1];
}
// (Re-)set the property stating whether the search input has been reset.
// This is needed for instances when the search input is also an address
// output field. After an address has been returned, you don't want a new
// search being triggered until the field has been cleared.
if (this.currentSearchTerm === '') {
this.hasSearchInputBeenReset = true;
}
// Concatenating the input components depending on search type and dataset to maximize match results
const delimiter = this.isInternationalValidation() ? "|": ",";
this.currentSearchTerm = this.inputs.map(input => input.value).join(delimiter);
// Check if searching is permitted
if (this.canSearch()) {
// Abort any outstanding requests
if (this.request.currentRequest) {
this.request.currentRequest.abort();
}
// Determine the search mode from the supplied input when in combined mode.
if (this.searchType == AddressValidationSearchType.COMBINED) {
let predefinedFormats = this.readPredefinedFormats();
predefinedFormats.find(predefinedItem => {
if (predefinedItem.format.test(this.currentSearchTerm.trim())) {
this.avMode = predefinedItem.mode;
this.currentSearchTerm = this.currentSearchTerm.trim();
}
});
}
// Fire an event before a search takes place
this.events.trigger('pre-search', this.currentSearchTerm);
// Store the last search term
this.lastSearchTerm = this.currentSearchTerm;
// Hide and show an inline spinner whilst searching. Hide it first so we don't show 2 spinners by accident.
this.searchSpinner.hide();
this.searchSpinner.show();
let url, headers, callback, data;
// Determine search mode and search term for key lookups
if (this.searchType === AddressValidationSearchType.LOOKUPV2) {
const lookupSearchTerm = this.currentSearchTerm.split(',');
this.avMode = AddressValidationMode[lookupSearchTerm[0].toUpperCase() as keyof typeof AddressValidationMode];
this.returnAddresses = lookupSearchTerm[1] === "true";
this.currentSearchTerm = lookupSearchTerm[2].trim();
}
// Construct the new Search URL and data
switch(this.avMode as any) {
case AddressValidationMode.WHAT3WORDS: {
data = this.generateLookupDataForApiCall(this.getWhat3WordsLookupValue(this.currentSearchTerm, true), this.avMode);
url = this.baseUrl + this.lookupV2Endpoint;
headers = [];
callback = this.picklist.showWhat3Words;
break;
}
case AddressValidationMode.MPAN:
case AddressValidationMode.MPRN: {
this.returnAddresses = true;
data = this.generateLookupDataForApiCall(this.currentSearchTerm, this.avMode);
url = this.baseUrl + this.lookupV2Endpoint;
headers = [{ key: 'Add-FinalAddress', value: true }];
callback = this.result.handleUtilitiesLookupResponse;
break;
}
case AddressValidationMode.UDPRN:
case AddressValidationMode.POSTAL_CODE:
case AddressValidationMode.LOCALITY: {
// Always return addresses if the combined search type is selected. The form has no toggle to turn this on or off.
if (this.searchType === AddressValidationSearchType.COMBINED) {
this.returnAddresses = true;
}
data = this.generateLookupDataForApiCall(this.currentSearchTerm, this.avMode);
url = this.baseUrl + this.lookupV2Endpoint;
headers = [{ key: 'Add-Addresses', value: true }];
callback = this.picklist.showLookup;
break;
}
default: {
data = this.generateSearchDataForApiCall();
url = this.baseUrl + (this.searchType === AddressValidationSearchType.VALIDATE ? this.validateEndpoint : this.searchEndpoint);
headers = this.searchType === AddressValidationSearchType.VALIDATE ? [{ key: 'Add-Components', value: true }, { key: 'Add-Metadata', value: true }, { key: 'Add-Enrichment', value: true }] : [];
callback = this.searchType === AddressValidationSearchType.VALIDATE ? this.result.handleValidateResponse : this.picklist.show;
break;
}
};
// Initiate new Search request
this.request.send(url, 'POST', callback, data, headers);
} else if (this.lastSearchTerm !== this.currentSearchTerm) {
// Clear the picklist if the search term is cleared/empty
this.picklist.hide();
}
}
// Helper method to return a consistent key name
private getKey({ key }): string {
switch (key) {
case 'Down':
case 'ArrowDown':
return 'ArrowDown';
case 'Up':
case 'ArrowUp':
return 'ArrowUp';
case 'Spacebar':
case ' ':
return ' ';
case 'Escape':
case 'Esc':
return 'Escape';
default:
return key;
}
}
private canSearch(): boolean {
// If searching on this instance is enabled, and
return (this.options.enabled &&
// If search term is not empty, and
this.currentSearchTerm !== '' &&
// If the search term is at least 4 characters
this.currentSearchTerm.length > 3 &&
// If search term is not the same as previous search term, and
this.lastSearchTerm !== this.currentSearchTerm &&
// If the country is not empty, and
this.currentCountryCode &&
// If search input has been reset (if applicable)
this.hasSearchInputBeenReset === true);
}
private poweredByLogo: PoweredByLogo = {
element: null,
// Create a "Powered by Experian" footer
create(picklist) {
const item = {
text: `${this.svg} <em>Powered by Experian</em>`,
format: ''
};
const listItem = picklist.createListItem(item);
listItem.classList.add('powered-by-experian');
picklist.list.parentNode.appendChild(listItem);
return listItem;
},
// Destroy the "Powered by Experian" footer
destroy(picklist) {
if (this.element) {
picklist.list.parentNode.removeChild(this.element);
this.element = undefined;
}
},
svg: `<svg class="experian-logo" version="1.1" width="18" height="18" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 120 120" style="" xml:space="preserve" role="img" aria-label="Powered by Experian">
<title>Experian logo</title>
<g>
<path style="fill: #0E6EB6" d="M56.1,27h-13c-3.9,0-7-3.1-7-7V7c0-3.9,3.1-7,7-7h13c3.9,0,7,3.1,7,7v13C63.1,23.8,60,27,56.1,27"></path>
<path style="fill: #72217B" d="M22.5,56.1H7.9c-4.3,0-7.9-3.5-7.9-7.9V33.6c0-4.3,3.5-7.9,7.9-7.9h14.6c4.3,0,7.9,3.5,7.9,7.9v14.6C30.4,52.6,26.8,56.1,22.5,56.1"></path>
<path style="fill: #B12384" d="M21.1,86.4h-8.9c-2.7,0-4.8-2.1-4.8-4.8v-8.9c0-2.7,2.2-4.8,4.8-4.8h8.9c2.7,0,4.8,2.2,4.8,4.8v8.9C25.9,84.3,23.7,86.4,21.1,86.4"></path>
<path style="fill: #E72887" d="M45.1,114.7H34.5c-3.1,0-5.7-2.5-5.7-5.7V98.4c0-3.1,2.5-5.7,5.7-5.7h10.6c3.1,0,5.7,2.5,5.7,5.7V109C50.7,112.1,48.2,114.7,45.1,114.7"></path>
<path style="fill: #E72887" d="M83.8,32.3h-7.3c-2.2,0-3.9-1.8-3.9-3.9v-7.3c0-2.2,1.8-3.9,3.9-3.9h7.3c2.2,0,3.9,1.8,3.9,3.9v7.3C87.7,30.5,85.9,32.3,83.8,32.3"></path>
<path style="fill: #004691" d="M81.7,61.8C81.5,51.1,72,42,60.7,42C49,42,39.6,51.3,39.6,62.9C39.6,74.6,49,84,60.7,84c5.6,0,10.8-2.2,14.6-5.9c0.7-0.7,1.2-1.6,1.2-2.6c0-1.9-1.6-3.5-3.5-3.5c-1.1,0-2,0.7-2.8,1.4c-2.4,2.5-5.9,3.7-9.5,3.7c-7,0-12.7-4.8-13.9-11.5h31.5c0,0,0,0,0.1,0h0.1c0.1,0,0.1,0,0.2,0c0.1,0,0.2,0,0.4-0.1C80.4,65,81.7,63.6,81.7,61.8z M60.7,48.9c6.3,0,11.6,4.1,13.4,9.7H47.3C49.1,53,54.3,48.9,60.7,48.9z"></path>
</g>
</svg>`
};
private createPicklist() {
// Instantiate a new Picklist class and set the properties below
this.picklist = new Picklist();
// Set initial max size
this.picklist.maxSuggestions = 25;
// Tab count used for keyboard navigation
this.picklist.tabCount = -1;
// Render a picklist of search results
this.picklist.show = (items: SearchResponse) => {
// Store the picklist items
this.picklist.items = items?.result.suggestions;
this.picklist.handleCommonShowPicklistLogic();
if (this.picklist.items?.length > 0) {
// If a picklist needs "refining" then prepend a textbox to allow the user to enter their selection
if (this.picklist.refine.isNeeded(items)) {
this.picklist.refine.createInput(items.result.suggestions_prompt, items.result.suggestions_key);
}
if (this.searchType === AddressValidationSearchType.VALIDATE) {
this.picklist.displaySuggestionsHeader();
}
// Iterate over and show results
this.picklist.items.forEach(item => {
// Create a new item/row in the picklist
const listItem = this.picklist.createListItem(item);
this.picklist.list.appendChild(listItem);
// Listen for selection on this item
this.picklist.listen(listItem);
});
if (this.searchType === AddressValidationSearchType.VALIDATE) {
this.picklist.displayUseAddressEnteredFooter();
}
this.picklist.scrollIntoViewIfNeeded();
} else {
this.picklist.handleEmptyPicklist(items);
}
// Add a "Powered by Experian" logo to the picklist footer
this.poweredByLogo.element = this.poweredByLogo.element || this.poweredByLogo.create(this.picklist);
// Fire an event after picklist is created
this.events.trigger('post-picklist-create', this.picklist.items);
};
this.picklist.showWhat3Words = (items: LookupW3WResponse) => {
// Store the picklist items
this.picklist.what3wordsItems = items?.result.suggestions;
this.picklist.handleCommonShowPicklistLogic();
if (this.picklist.what3wordsItems?.length > 0) {
// Iterate over and show results
this.picklist.what3wordsItems.forEach(item => {
// Create a new item/row in the picklist
const listItem = this.picklist.createWhat3WordsListItem(item);
this.picklist.list.appendChild(listItem);
// Listen for selection on this item
this.picklist.listen(listItem);
});
this.picklist.scrollIntoViewIfNeeded();
} else {
this.picklist.handleEmptyPicklist(items);
}
// Add a "Powered by Experian" logo to the picklist footer
this.poweredByLogo.element = this.poweredByLogo.element || this.poweredByLogo.create(this.picklist);
// Fire an event after picklist is created