-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
317 lines (270 loc) · 11 KB
/
app.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
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
function CurrencyItem() {
let baseCur = "";
let targetCur = "";
let excRate = 1.0;
let baseAmt = 0.0;
let baseAmtText = "";
let targetAmt = 0.0;
let targetAmtText = "";
}
function CurrencyCode() {
let code = "";
let countryName = "";
}
function UserOptions() {
let baseCurrency = "";
let targetCurrency = "";
let totalItemsPerPage = 10;
let baseNumber = 1;
let baseDecimalPoint = 2;
let targetDecimalPoint = 2;
}
let UserPrefs = {
// Initialize default values if no data is available.
initialize() {
SC_UserOpt.baseCurrency = "SGD";
SC_UserOpt.targetCurrency = "MYR";
SC_UserOpt.totalItemsPerPage = 10;
SC_UserOpt.baseNumber = 1;
SC_UserOpt.baseDecimalPoint = 2;
SC_UserOpt.targetDecimalPoint = 2;
this.save();
},
// Load user local storage.
load() {
SC_UserOpt = JSON.parse(localStorage.UserPreferences);
},
// Save user local storage.
save() {
localStorage.UserPreferences = JSON.stringify(SC_UserOpt);
},
}
//////////////////////////////////////////////////////////////////////
let SC_XChangeRate = {};
let SC_CurrencyList = [];
let SC_UserOpt = new UserOptions();
if (localStorage.UserPreferences) {
UserPrefs.load();
if (SC_UserOpt.baseNumber === undefined || SC_UserOpt.totalItemsPerPage === undefined)
UserPrefs.initialize();
}
else {
UserPrefs.initialize();
}
console.log(SC_UserOpt);
Vue.component('v-select', VueSelect.VueSelect);
//////////////////////////////////////////////////////////////////////
const app_id = "330efd1b3dda49ecab74a654f7e436fd";
window.onload = () => {
new Vue({
el: "#app",
data() {
return {
totalItemsPerPage: SC_UserOpt.totalItemsPerPage,
baseCurrency: SC_UserOpt.baseCurrency,
targetCurrency: SC_UserOpt.targetCurrency,
currentBaseNumber: SC_UserOpt.baseNumber,
currencyItems: [],
currencyList: [],
xchangeRate: 0.0,
rateLastUpdated: "",
isLoading: true,
GlobalErrorMessage: "",
isAlertVisible: false
};
},
// Vue2 created - Called synchronously after the instance is created.
// Initialization code.
// - Init and parse currency list
// - Check localstorage exchange rates data
// - Retrieve exchange rate if required
created: function () {
GetCurrencyList();
if (localStorage.XRates) {
console.log("LocalStorage is NOT empty");
SC_XChangeRate = JSON.parse(localStorage.XRates);
let differentInMinutes = this.getDifferentInMinutes();
if (differentInMinutes > 120) {
this.triggerUpdateExchangeRate();
}
else{
this.initialize();
}
this.isLoading = false;
}
else {
console.log("LocalStorage is empty");
this.refreshExchangeRate()
.finally(() => {
this.isLoading = false;
this.initialize();
});
}
},
methods: {
// Initialize component data.
initialize: function() {
console.log("initialize this.currentBaseNumber", this.currentBaseNumber)
this.currencyList = SC_CurrencyList;
this.refreshLastUpdatedDate();
this.setXchangeRate();
this.buildItemList(this.currentBaseNumber);
},
// Refresh exchange rate via openexchangerates
refreshExchangeRate: function() {
const rateUrl = `https://openexchangerates.org/api/latest.json?app_id=${app_id}`;
return axios
.get(rateUrl)
.then(response => {
SC_XChangeRate = response.data;
localStorage.XRates = JSON.stringify(SC_XChangeRate);
console.log("RetrieveLatestXchangeRate", response);
})
.catch(error => {
console.error("RetrieveLatestXchangeRate", error);
this.showErrorMessage("Unexpected error when retrieving latest exchange rates. Please try again later. " + error);
// this.errored = true;
});
},
// Calculate and set exchange rate
setXchangeRate: function() {
let xrates = SC_XChangeRate.rates;
let baseXRate = parseFloat(xrates[this.targetCurrency]) / parseFloat(xrates[this.baseCurrency]);
console.log("xchange rates", baseXRate, parseFloat(xrates[this.targetCurrency]), parseFloat(xrates[this.baseCurrency]));
this.xchangeRate = baseXRate;
},
// Update base number
updateBaseNumber: function(baseNumber) {
this.currentBaseNumber = baseNumber;
SC_UserOpt.baseNumber = this.currentBaseNumber;
UserPrefs.save();
this.buildItemList();
},
// Multiple 10
showNext10: function (event) {
let multiplier = this.currentBaseNumber * 10;
this.updateBaseNumber(multiplier);
},
// Divide by 10
showPrev10: function (event) {
if (this.currentBaseNumber > 1) {
let multiplier = this.currentBaseNumber / 10;
this.updateBaseNumber(multiplier);
}
else {
this.makeToast("danger", "Lowest base number is 1");
}
},
// Refresh last updated text label
refreshLastUpdatedDate: function() {
let epochTime = SC_XChangeRate.timestamp * 1000;
this.rateLastUpdated = new Date(epochTime);
},
// Toggle Switch Currency modal dialog
switchCurrency() {
this.$bvModal.show("modal-switch-currency");
},
//
getDifferentInMinutes() {
let lastUpdateTime = SC_XChangeRate.timestamp * 1000;
let currentTime = Date.now();
let differentInMinutes = (currentTime - lastUpdateTime) / 1000 / 60;
return differentInMinutes;
},
// Trigger update exchange rate on click
triggerUpdateExchangeRate() {
// Check last updated time
let differentInMinutes = this.getDifferentInMinutes();
if (differentInMinutes > 60) {
// If more than 60 minutes, get the latest exchange rates
this.makeToast("info", "Updating exchange rate...");
this.refreshExchangeRate()
.finally(() => {
this.initialize();
this.makeToast("success", "Exchange rate has been updated. Exchange rate is ONLY updated every 1-hour.");
});
}
else {
this.makeToast("info", "Exchange rate is already the latest available rate. Exchange rate is ONLY updated every 1-hour.");
}
},
// For swap-currency clicked event from option modal page.
onCurrencyChangeEvent(updatedCurrency) {
this.setCurrency(updatedCurrency);
},
// For swap-currency clicked event.
swapCurrencyClicked() {
this.setCurrency({ base: this.targetCurrency, target: this.baseCurrency });
},
// Set currency event handler.
setCurrency(updatedCurrency) {
// console.log("setTargetCurrency", updatedCurrency);
this.targetCurrency = updatedCurrency.target;
this.baseCurrency = updatedCurrency.base;
SC_UserOpt.baseCurrency = this.baseCurrency;
SC_UserOpt.targetCurrency = this.targetCurrency;
UserPrefs.save();
this.initialize();
},
// Build and generate item list.
buildItemList() {
this.currencyItems = [];
let multiplier = this.currentBaseNumber;
for (let i = this.currentBaseNumber; i <= this.totalItemsPerPage * multiplier; i += multiplier) {
let item = new CurrencyItem();
item.baseCur = this.baseCurrency;
item.targetCur = this.targetCurrency;
item.excRate = this.xchangeRate;
item.baseAmt = i;
item.baseAmtText = FormatMoney(item.baseAmt, SC_UserOpt.baseDecimalPoint);
item.targetAmt = (i * item.excRate);
item.targetAmtText = FormatMoney(item.targetAmt, SC_UserOpt.targetDecimalPoint);
this.currencyItems.push(item);
}
},
// Create toast message.
makeToast(variant = null, message = "", isAutoHide = false) {
this.$bvToast.toast(message, {
title: `Donkey App`,
variant: variant,
solid: true,
noAutoHide: isAutoHide
})
},
// Show toast error message.
showErrorMessage(errorMsg) {
this.makeToast("danger", errorMsg, true);
}
}
});
};
//////////////////////////////////////////////////////////////////////
function GetCurrencyList() {
SC_CurrencyList = [];
for(curCode in tempCurrencyList) {
let ccode = new CurrencyCode();
ccode.code = curCode;
ccode.countryName = tempCurrencyList[curCode] + ' (' + curCode + ')';
SC_CurrencyList.push(ccode);
}
}
// Create our number formatter.
let formatter = new Intl.NumberFormat('en-SG', {
style: 'currency',
currency: 'SGD',
});
// formatter.format(2500); /* $2,500.00 */
//
function FormatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
try {
decimalCount = Math.abs(decimalCount);
decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
const negativeSign = amount < 0 ? "-" : "";
let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
let j = (i.length > 3) ? i.length % 3 : 0;
return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
} catch (e) {
console.error(e)
}
};
//////////////////////////////////////////////////////////////////////