-
Notifications
You must be signed in to change notification settings - Fork 0
/
loginScript.js
385 lines (338 loc) · 11.5 KB
/
loginScript.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
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
'use strict';
// Data
const account1 = {
owner: 'Mazen Zain',
movements: [200, 455.23, -306.5, 25000, -642.21, -133.9, 79.97, 1300],
interestRate: 1.2, // %
pin: 1111,
movementsDates: [
'2019-11-18T21:31:17.178Z',
'2019-12-23T07:42:02.383Z',
'2022-01-28T09:15:04.904Z',
'2022-01-01T10:17:24.185Z',
'2022-02-08T14:11:59.604Z',
'2022-05-12T17:01:17.194Z',
'2022-05-14T23:36:17.929Z',
'2022-05-20T10:51:36.790Z',
],
currency: 'EUR',
locale: 'pt-PT', // de-DE
};
const account2 = {
owner: 'Ahmed Fathy',
movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
interestRate: 1.5,
pin: 2222,
movementsDates: [
'2019-11-01T13:15:33.035Z',
'2019-11-30T09:48:16.867Z',
'2019-12-25T06:04:23.907Z',
'2022-01-25T14:18:46.235Z',
'2022-02-05T16:33:06.386Z',
'2022-03-10T14:43:26.374Z',
'2022-05-25T18:49:59.371Z',
'2022-04-26T12:01:20.894Z',
],
currency: 'USD',
locale: 'en-US',
};
const accounts = [account1, account2];
// Elements
const labelWelcome = document.querySelector('.welcome');
const labelDate = document.querySelector('.date');
const labelBalance = document.querySelector('.balance__value');
const labelSumIn = document.querySelector('.summary__value--in');
const labelSumOut = document.querySelector('.summary__value--out');
const labelSumInterest = document.querySelector('.summary__value--interest');
const labelTimer = document.querySelector('.timer');
const warningText = document.querySelector('.warning-text');
const containerApp = document.querySelector('.app');
const containerMovements = document.querySelector('.movements');
const loginForm = document.querySelector('.login');
const navContainer = document.querySelector('.login-nav');
const loginTooltip = document.querySelector('.tooltip');
const btnLogin = document.querySelector('.login__btn');
const btnTransfer = document.querySelector('.form__btn--transfer');
const btnLoan = document.querySelector('.form__btn--loan');
const btnClose = document.querySelector('.form__btn--close');
const btnSort = document.querySelector('.btn--sort');
const btnLogout = document.querySelector('.logout');
const inputLoginUsername = document.querySelector('.login__input--user');
const inputLoginPin = document.querySelector('.login__input--password');
const inputTransferTo = document.querySelector('.form__input--to');
const inputTransferAmount = document.querySelector('.form__input--amount');
const inputLoanAmount = document.querySelector('.form__input--loan-amount');
const inputCloseUsername = document.querySelector('.form__input--user');
const inputClosePin = document.querySelector('.form__input--pin');
// Funtions
const formatMovementDate = function (date) {
const calcDaysPassed = (date1, date2) =>
Math.round(Math.abs(date2 - date1) / (1000 * 60 * 60 * 24));
const daysPassed = calcDaysPassed(new Date(), date);
if (daysPassed === 0) return 'Today';
if (daysPassed === 1) return 'Yesterday';
if (daysPassed <= 7) return '${daysPassed} days ago';
else {
const day = `${date.getDate()}`.padStart(2, 0);
const month = `${date.getMonth() + 1}`.padStart(2, 0);
const year = date.getFullYear();
return `${day}/${month}/${year}`;
}
};
const formatCurrency = function (value, locale, currency) {
//Format currency
return new Intl.NumberFormat(locale, {
style: 'currency',
currency,
}).format(value);
};
const displayMovements = function (acc, sort = false) {
containerMovements.innerHTML = '';
//sort movemenets
const movs = sort
? acc.movements.slice().sort((a, b) => a - b)
: acc.movements;
movs.forEach(function (mov, i) {
const type = mov > 0 ? 'deposit' : 'withdrawal';
//Display dates
const date = new Date(acc.movementsDates[i]);
const displayDate = formatMovementDate(date);
const formattedMov = formatCurrency(mov, acc.locale, acc.currency);
const html = ` <div class="movements__row">
<div class="movements__type movements__type--${type}">${i + 1} ${type}</div>
<div class="movements__date">${displayDate}</div>
<div class="movements__value">${formattedMov}</div>
</div>`;
containerMovements.insertAdjacentHTML('afterbegin', html);
});
};
const createUsernames = function (accs) {
accs.forEach(function (acc) {
acc.username = acc.owner
.toLowerCase()
.split(' ')
.map(name => name[0])
.join('');
});
};
createUsernames(accounts);
const updateUI = function (currentAccount) {
// calculate nums
displayMovements(currentAccount);
calcPrintBalance(currentAccount);
calcDisplaySum(currentAccount);
};
// display Balance
const calcPrintBalance = function (acc) {
acc.balance = acc.movements.reduce((acc, mov) => acc + mov, 0);
const formattedMov = formatCurrency(acc.balance, acc.locale, acc.currency);
labelBalance.textContent = `${formattedMov}`;
};
const calcDisplaySum = function (acc) {
const incomes = acc.movements
.filter(mov => mov > 0)
.reduce((acc, mov) => acc + mov, 0);
labelSumIn.textContent = formatCurrency(incomes, acc.locale, acc.currency);
const out = acc.movements
.filter(mov => mov < 0)
.reduce((acc, mov) => acc + mov, 0);
labelSumOut.textContent = formatCurrency(
Math.abs(out),
acc.locale,
acc.currency
);
const interest = acc.movements
.filter(mov => mov > 0)
.map(deposit => (deposit * acc.interestRate) / 100)
.filter((int, i, arr) => {
return int >= 1;
})
.reduce((acc, int) => acc + int, 0);
labelSumInterest.textContent = formatCurrency(
interest,
acc.locale,
acc.currency
);
};
// logout timer
const startLogoutTimer = function () {
const tick = function () {
const mins = String(Math.trunc(timer / 60)).padStart(2, 0);
const secs = String(timer % 60).padStart(2, 0);
labelTimer.textContent = `${mins}:${secs}`;
// logout when reaching 0
if (timer === 0) {
clearInterval(timing);
labelWelcome.textContent = 'Log in to get started';
containerApp.style.display = 'none';
loginTooltip.style.display = 'block';
loginForm.style.display = 'flex';
navContainer.style.marginTop = '10%';
}
timer--;
};
// setting time to 5 min
let timer = 300;
tick();
const timing = setInterval(tick, 1000);
return timing;
};
// logout with button
btnLogout.addEventListener('click', function () {
labelWelcome.textContent = 'Log in to get started';
containerApp.style.display = 'none';
loginForm.style.display = 'flex';
loginTooltip.style.display = 'block';
navContainer.style.marginTop = '10%';
});
// implementing Login
let currentAccount, timing;
btnLogin.addEventListener('click', function (e) {
// prevent the form from submiting
e.preventDefault();
currentAccount = accounts.find(
acc => acc.username === inputLoginUsername.value
);
/// login validation
let bothInputsEmpty =
inputLoginUsername.value.length === 0 && inputLoginPin.value.length === 0;
let usernameEmpty = inputLoginUsername.value.length === 0;
let passwordEmpty = inputLoginPin.value.length === 0;
if (bothInputsEmpty) {
inputLoginUsername.classList.add('warning');
inputLoginPin.classList.add('warning');
warningText.textContent = 'Empty Username and Password!';
console.log('empty both');
} else if (usernameEmpty && !passwordEmpty) {
inputLoginUsername.classList.add('warning');
inputLoginPin.classList.remove('warning');
warningText.textContent = 'Empty Username!';
console.log('empty username');
} else if (passwordEmpty && !usernameEmpty) {
inputLoginUsername.classList.remove('warning');
inputLoginPin.classList.add('warning');
warningText.textContent = 'Empty Password!';
console.log('empty password');
} else if (!currentAccount && !bothInputsEmpty) {
inputLoginUsername.classList.add('warning');
inputLoginPin.classList.add('warning');
warningText.textContent = "Account with such username doesn't exist!";
console.log('no such acc');
}
/// if validation passed
else {
inputLoginUsername.classList.remove('warning');
inputLoginPin.classList.remove('warning');
warningText.textContent = ' ';
if (currentAccount?.pin === Number(inputLoginPin.value)) {
labelWelcome.textContent = `Welcome back, ${
currentAccount.owner.split(' ')[0]
}!`;
//Show hidden container
loginForm.style.display = 'none';
containerApp.style.display = 'grid';
loginTooltip.style.display = 'none';
navContainer.style.marginTop = '5%';
//Create current date
const now = new Date();
const options = {
hour: 'numeric',
minute: 'numeric',
day: 'numeric',
month: 'numeric',
year: 'numeric',
};
// const now = new Date();
// const day = `${now.getDate()}`.padStart(2, 0);
// const month = `${now.getMonth() + 1}`.padStart(2, 0);
// const year = now.getFullYear();
// const hour = `${now.getHours()}`.padStart(2, 0);
// const min = `${now.getMinutes()}`.padStart(2, 0);
// labelDate.textContent = `${day}/${month}/${year}, ${hour}:${min}`;
// updateUI(currentAccount);
labelDate.textContent = new Intl.DateTimeFormat(
currentAccount.locale,
options
).format(now);
//Clear input
inputLoginUsername.value = inputLoginPin.value = '';
inputLoginPin.blur();
//clear time if it started on another acc
if (timing) clearInterval(timing);
//Start logout
timing = startLogoutTimer();
// Update UI
updateUI(currentAccount);
}
}
});
// tranfer money
btnTransfer.addEventListener('click', function (e) {
e.preventDefault();
const amount = Number(inputTransferAmount.value);
const recieverAcc = accounts.find(
acc => acc.username === inputTransferTo.value
);
inputTransferAmount.value = inputTransferTo.value = '';
if (
amount > 0 &&
recieverAcc &&
currentAccount.balance >= amount &&
recieverAcc.username !== currentAccount.username
) {
//Transfer
currentAccount.movements.push(-amount);
recieverAcc.movements.push(amount);
//Add transfer date
currentAccount.movementsDates.push(new Date().toISOString());
recieverAcc.movementsDates.push(new Date().toISOString());
updateUI(currentAccount);
//Reset timer on action
clearInterval(timing);
timing = startLogoutTimer();
}
});
btnClose.addEventListener('click', function (e) {
e.preventDefault();
if (
inputCloseUsername.value === currentAccount.username &&
Number(inputClosePin.value) === currentAccount.pin
) {
const index = accounts.findIndex(
acc => acc.username === currentAccount.username
);
console.log(index);
accounts.splice(index, 1);
loginForm.style.display = 'flex';
containerApp.style.display = 'none';
navContainer.style.marginTop = '10%';
}
inputCloseUsername.value = inputClosePin.value = '';
});
//Loan
btnLoan.addEventListener('click', function (e) {
e.preventDefault();
const amount = Math.floor(inputLoanAmount.value);
if (amount > 0 && currentAccount.movements.some(mov => mov >= amount / 10)) {
// set timer for loan
setTimeout(function () {
// add movement
currentAccount.movements.push(amount);
// add loan date
currentAccount.movementsDates.push(new Date().toISOString());
// update UI
updateUI(currentAccount);
// reset the timer
clearInterval(timing);
timing = startLogoutTimer();
}, 2500);
}
inputLoanAmount.value = '';
});
// sort movements
let sorted = false;
btnSort.addEventListener('click', function (e) {
e.preventDefault();
displayMovements(currentAccount, !sorted);
sorted = !sorted;
});