This repository has been archived by the owner on Feb 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zipcheck-results.js
253 lines (220 loc) · 9.36 KB
/
zipcheck-results.js
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
const HARDCODED_MAPPINGS = {
22000: '22 Mb',
50000: '50 Mb',
512000: '500 Mb',
524000: '500 Mb',
};
const SORT_LIST = ["KPNWBAFIBER", "KPNWBAFTTH/FTTO", "KPNWBAVPLUS", "KPNWBAVVDSL", "KPNWBAVDSL", "KPNWBAADSL", "KPNWBABVDSL",
"TELE2FIBER", "ZIGGOFIBER", "KPNWEASFIBER", "EUROFIBERFIBER", "TELE2COPPER", "KPNWEASCOPPER"]
// See https://github.com/Nextpertise/imp_portal/blob/master/src/filters/bandwidth.js for details.
function createSpeedDisplayValue(_value) {
const value = Number(_value);
const isLessThanAMb = value < 1024;
const isLessThan3Mb = value < 3000;
const isGreaterThan95Mb = value > 95000 && value < 1000000;
const isLessThan1Gb = value < 1000000;
if (HARDCODED_MAPPINGS[value]) {
return HARDCODED_MAPPINGS[value];
}
if (isLessThanAMb) {
return `${value} Kb`;
}
if (isLessThan3Mb) {
const mbValue = parseFloat((value / 1024).toFixed(2));
return `${mbValue} Mb`;
}
if (isGreaterThan95Mb) {
const mbValue = Math.round(value / 1024);
const roundedMbValue = Math.ceil(mbValue / 10) * 10;
return `${roundedMbValue} Mb`;
}
if (isLessThan1Gb) {
return `${Math.round(value / 1024)} Mb`;
}
return `${Math.round(value / 1024 / 1024)} Gb`;
}
jQuery(document).ready(function($) {
// Used to check if all the calls have been completed.
let necessaryProviderCalls;
let completedProvidercalls = 0;
// Stores all the results and is sorted after every call.
let resultsList = [];
// Extract params from URL.
// Not using native functionality because it is not supported in all browsers.
function getParameters() {
query = window.location.search.substring(1);
let vars = query.split("&");
let results = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
// If first entry with this name
if (typeof results[key] === "undefined") {
results[key] = decodeURIComponent(value);
// If second entry with this name
} else if (typeof results[key] === "string") {
var arr = [results[key], decodeURIComponent(value)];
results[key] = arr;
// If third or later entry with this name
} else {
results[key].push(decodeURIComponent(value));
}
}
return results;
}
function hideLoader(){
$(".postcode-result-box.spinner-box").hide(300);
}
// Sorts the list that has all the different options.
function sortAllResults(){
function buildString(result){
if(result['provider'].toUpperCase() === "KPNWBA"){
return (result['provider'] + result['header']).toUpperCase();
}else{
return (result['provider'] + result['carrier']).toUpperCase();
}
}
// Sorts the list based on SORT_LIST
resultsList.sort(function(a, b){
let aString = buildString(a);
let bString = buildString(b);
try{
if(SORT_LIST.indexOf(aString) > SORT_LIST.indexOf(bString)){
return -1;
}else{
return 1
}
}catch (error) {
return 0;
}
});
}
// Renders the list. Should be called after sortAllResults()
function renderAllResults(){
$(".result-item").remove();
$.each(resultsList, function(index, result){
$(".postcode-result").prepend(createResultBox(result));
});
}
// Adds the address to the header.
function updateHeaderContent(address){
let subtitle = "<p>Beschikbare producten op</p>";
let title_housenrext = address['housenrext'] === "" ? "" : "-" + address['housenrext'];
let title = "<h2>" + address["street"] + " " + address['housenr'].toString() + title_housenrext + " in " + address['municipality'] + "</h2>";
$(".postcode-text-part").html(subtitle + title);
}
// Show message if no results are found
function updateHeaderNoResults(zipcode, housenr, ext){
ext = ext === "" ? "" : "-" + ext;
let title = "<h2>Geen resultaten gevonden voor " + zipcode.toUpperCase() + " " + housenr + ext + ".</h2>";
$(".postcode-text-part").html(title);
}
// Gets a list of all the available providers.
// Uses a callback for browser compatiblity.
function listProviders(callback){
$.ajax(zipcheck_ajax.ajax_url, {
method: 'POST',
data: {'action': 'nextzipcheck_get_all_providers'},
success: function(data){
callback(JSON.parse(data));
}
})
}
// Gets the actual data from the provider.
function getProviderAvailableData(callback, provider, zipcode, housenr, ext=""){
$.ajax(zipcheck_ajax.ajax_url, {
method: 'POST',
data: {
'action': 'nextzipcheck_get_available_per_provider',
'zipcode': zipcode,
'housenr': housenr,
'housenrext': ext,
'provider': provider
},
success: function(data){
callback(JSON.parse(data));
}
})
}
// Gets data for each provider, loops over the data, adds data to resultlist, calls the sort and render functions.
function getAndInsertDataFromProviders(providerList){
let params = getParameters();
params['zipcheck-ext'] = params['zipcheck-ext'] !== "undefined" ? params['zipcheck-ext'] : ""
necessaryProviderCalls = providerList.length;
$.each(providerList, function(index, val){
// Gets data from API for each provider.
getProviderAvailableData(
function(data){
// Handles loader card
completedProvidercalls++;
if(completedProvidercalls >= necessaryProviderCalls){
hideLoader();
}
// Check if provider actually has data.
if (data !== null && data !== "null"){
// Updates header with address.
updateHeaderContent(data['address'])
// Loops over data and sorts and renders cards.
$.each(data['available'], function(providerName, provider){
$.each(provider, function(header, result){
result['header'] = header;
result['provider'] = providerName;
resultsList.push(result);
});
});
sortAllResults();
renderAllResults();
}
// Check if there are any results
if(completedProvidercalls >= necessaryProviderCalls && resultsList.length === 0){
// Show error message if there are no results
updateHeaderNoResults(params['zipcheck-zipcode'], params['zipcheck-housenr'], params['zipcheck-ext']);
}
},
val,
params['zipcheck-zipcode'],
params['zipcheck-housenr'],
params['zipcheck-ext'],
)
});
}
// Create the HTML within JavaScript. Using normal `+` instead of template literals for IE 11 support.
function createResultBox(result){
let title = "<h3>" + result['header'].replace('Fiber', 'Glasvezel') + "</h3>";
let subtitle = "<p> via " + result['network'] + "</p>";
let speedup = '<h3><img src="https://nextpertise.nl/wp-content/uploads/2018/10/arrow-up.svg" alt="down">' + createSpeedDisplayValue(result['max_upload']) + '</h3>';
let speeddown = '<h3><img src="https://nextpertise.nl/wp-content/uploads/2018/10/arrow-down.svg" alt="down">' + createSpeedDisplayValue(result['max_download']) + '</h3>';
let shouldAddDivider = (result['area'] !== undefined && result['area'] != "" && result['distance'] !== undefined && result['distance'] != "")
let area = result['area'] + (shouldAddDivider ? ", " : "") + result['distance'].replace(";", ", ");
let smallSubText = (result['carrier'].toUpperCase() === "COPPER" && result['provider'].toUpperCase() === "KPNWBA") ? "Verwachte snelheid" : "";
let html = '\
<div class="postcode-result-box result-item">\
<div class="postcode-left-part">\
' + title + subtitle + '\
</div>\
<div class="postcode-right-part">\
<div class="speed-part">\
' + speeddown + speedup + '\
</div>\
<p>' + area + smallSubText + '</p>\
</div>\
<p><p>\
</div>\
';
return html;
}
// Sets the inputs to the inputs submitted.
function populateState(params){
params['zipcheck-ext'] = params['zipcheck-ext'] !== "undefined" ? params['zipcheck-ext'] : ""
global_zipcode = params['zipcheck-zipcode'];
global_housenr_zipcode = global_zipcode;
global_housenr = params['zipcheck-housenr'];
$(".results .zipcheck-zipcode").val(global_zipcode);
$(".results .zipcheck-housenr").val(global_housenr);
$(".results .zipcheck-ext").val(params['zipcheck-ext']);
$(document).trigger("zipcheck-results-init");
}
listProviders(getAndInsertDataFromProviders);
populateState(getParameters());
});