Skip to content

This PR is the solution to the '4-bank-project' #4 #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
247 changes: 247 additions & 0 deletions 4-bank-project/bank-solution/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
const routes = {
'/login': { templateId: 'login' },
'/dashboard': { templateId: 'dashboard' , init:refresh},
'/credits':{templateId:'credits'}
};
let state = Object.freeze({
account: null
});

const storageKey = 'savedAccount';

function updateRoute() {

const path = window.location.pathname;
console.log(path);
const route = routes[path];

document.title=route.templateId;



const template = document.getElementById(route.templateId);
if(template.content){
const view = template.content.cloneNode(true);
const app = document.getElementById('app');
app.innerHTML = '';
app.appendChild(view);
}
if(path==='/dashboard') {
console.log('Dashboard is Shown')
if(!state.account){
return logout();

}
updateDashboard();

}
if (!route) {
return navigate('/dashboard');
}
if (typeof route.init === 'function') {
route.init();
}
}
function navigate(path) {
window.history.pushState({}, path, path);
console.log('navigate');
updateRoute();
}
function onLinkClick(event) {
event.preventDefault();
navigate(event.target.href);
}
window.onpopstate = () => {console.log('popstate');updateRoute();}



async function register() {
const registerForm = document.getElementById('registerForm');
const formData = new FormData(registerForm);
const jsonData = JSON.stringify(Object.fromEntries(formData));
const result = await createAccount(jsonData);


if (result.error) {
alert(result.error);
console.log(result.erroe)

}
updateState('account', result);

console.log('Account created!', result);
navigate('/dashboard');
}




async function createAccount(account) {
try {
const response = await fetch('//localhost:5000/api/accounts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: account
});
return await response.json();
} catch (error) {
return { error: error.message || 'Unknown error' };
}
}


async function login() {
const loginForm = document.getElementById('loginForm')
const user = loginForm.user.value;
const data = await getAccount(user);

if (data.error) {
return updateElement('loginError', data.error);
}

updateState('account', data);
navigate('/dashboard');
}
async function getAccount(user) {
try {
const response = await fetch('//localhost:5000/api/accounts/' + encodeURIComponent(user));
return await response.json();
} catch (error) {
return { error: error.message || 'Unknown error' };
}
}

function updateElement(id, textOrNode) {
const element = document.getElementById(id);
element.textContent = '';
element.append(textOrNode);
}

function updateDashboard() {
const account = state.account;
if (!account) {
console.log('updatedashboard no account');
}
console.log('updated')
updateElement('description', account.description);
updateElement('balance', account.balance.toFixed(2));
updateElement('currency', account.currency);

const transactionsRows = document.createDocumentFragment();
for (const transaction of account.transactions) {
const transactionRow = createTransactionRow(transaction);
transactionsRows.appendChild(transactionRow);
}
updateElement('transactions', transactionsRows);

}

function createTransactionRow(transaction) {
const template = document.getElementById('transaction');
const transactionRow = template.content.cloneNode(true);
const tr = transactionRow.querySelector('tr');
console.log(transaction.date)
tr.children[0].textContent = transaction.date;
tr.children[1].textContent = transaction.object;
tr.children[2].textContent = transaction.amount;
console.log(transactionRow)
return transactionRow;
}

function updateState(property, newData) {
console.log("called",newData)
state = Object.freeze({
...state,
[property]: newData
});
localStorage.setItem(storageKey, JSON.stringify(state.account));
}


async function addTransaction(){
const account = state.account;
const form=document.getElementById('transactionForm');
const formData = new FormData(form);
const jsonData = JSON.stringify(Object.fromEntries(formData));


try {

const response = await fetch('//localhost:5000/api/accounts/'+encodeURIComponent(account.user)+'/transactions', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: jsonData
});
console.log('out');
//updateDashboard();
refresh()
return await response.json();
} catch (error) {
return { error: error.message || 'Unknown error' };
}

}

function logout() {

updateState('account', null);
navigate('/login');
console.log('logged out')
}

function init() {
// Restore state
const savedState = localStorage.getItem(storageKey);
if (savedState) {
updateState('account', JSON.parse(savedState));
}

// Update route for browser back/next buttons
window.onpopstate = () => updateRoute();
updateRoute();
}

init();

async function updateAccountData() {
const account = state.account;
if (!account) {
console.log('updateAppData no account');
return logout();
}

const data = await getAccount(account.user);
if (data.error) {
console.log('updateAppData data error');

return logout();
}

updateState('account', data);
}

async function refresh() {
await updateAccountData();
updateDashboard();
}

function pop(){
const pop=document.getElementById("popup");
pop.style.display='flex';
console.log('yes');
}

function popc(){
const pop=document.getElementById("popup");
const form=document.getElementById('transactionForm');
form.reset();
pop.style.display='none';
console.log('no');
}







113 changes: 113 additions & 0 deletions 4-bank-project/bank-solution/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bank App</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1 style="text-align: center; font-weight: 800;">Bank App</h1>

<div id="app">Loading...</div>



<template id="login">
<section>
<h2>Login</h2>
<form id="loginForm" action="javascript:login()">
<label for="username">Username</label>
<input id="username" name="user" type="text" required>
<div id="loginError" role="alert"></div>
<button type="submit" class="bn" id='login' >Login</button>
</form>
<hr/>
<h2>Register</h2>
<form id="registerForm" action="javascript:register();">
<label for="user">Username (required)</label>
<input id="user" name="user" type="text" maxlength="20" required>

<label for="currency">Currency (required)</label>
<input id="currency" name="currency" type="text" value="$" maxlength="5" required>

<label for="description">Description</label>
<input id="description" name="description" type="text" maxlength="100">

<label for="balance">Current balance</label>
<input id="balance" name="balance" type="number" value="0">
<button class="bn">Register</button>
</form>
</section>
</template>

<template id="dashboard">
<header>
<a href="/credits" onclick="onLinkClick(event)">Credits</a>

</header>
<section style="padding: 15px;font-size: 20px;font-weight: 800;">

Balance: <span id="balance"></span><span id="currency"></span>
</section>
<section>
<h2 id="description"></h2>
</section>

<section >
<h2>Transactions</h2>
<table id="customers">
<thead>
<tr>
<th>Date</th>
<th>Object</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="transactions"></tbody>
</table>
<div id="popup" class="popup">
<div class="popup-content">

<form id='transactionForm' action="javascript:popc();">
<br>
<label>Date</label>
<input type="date" name='date' required>
<label>Object</label>
<input type="text" name="object" required>
<label>Amount</label>
<input type="number" name="amount" required>

<button class="bn" type="submit" onclick="addTransaction();">Add Transaction</button>
<button class="bn" onclick="popc();">Cancel</button>
</form>

</div>
</div>
</section>
<button style="margin: auto;" class="bn" onclick="pop();">Add Transaction</button>
<button style="margin: auto;" class="bn" onclick="navigate('/login')">Logout</button>




</template>
<template id="credits">
<h1>Credits</h1>
<h3>This app is built by amFOSS club members of Amritapuri campus</h3>

</template>


<template id="transaction">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</template>


<script src="app.js" defer></script>
</body>
</html>
1 change: 1 addition & 0 deletions 4-bank-project/bank-solution/node_modules/.bin/mime

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading