Skip to content

Commit

Permalink
Added ses
Browse files Browse the repository at this point in the history
  • Loading branch information
huziibee committed Jan 9, 2024
1 parent 9a65a97 commit 9b3bd7f
Show file tree
Hide file tree
Showing 11 changed files with 256 additions and 100 deletions.
25 changes: 15 additions & 10 deletions AWS-APP/Dashboard/dashboard.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,23 @@
</head>
<body>
<header class="navigation-header">
<h1 class="welcome-message">Welcome back, <span id="username"></span></h1>
<nav class="navbar">
<a href="dashboard.html">Home</a>
<a href="../viewExpenses/view-expenses.html">View Expenses</a>
<button class="formbtn" id="logout-btn">Logout</button>
</nav>
<h1 class="welcome-message">Welcome back, <span id="username"></span></h1>
<nav class="navbar">
<button class="formbtn" onclick="logout()" id="logout-btn">
Logout
</button>
</nav>
</header>

<div class="horizontal_display">
<div class="dashboard-header">
<h2>My Weekly Budget App</h2>
<button class="formbtn" id="set-budget-btn">Set Weekly Budget</button>
<div id="email-btn-container">
<button id="email-btn">View transactions</button>
</div>

<ul id="budget-items">
</ul>
<ul id="budget-items"></ul>
</div>

<section class="dashboard-main">
Expand Down Expand Up @@ -59,7 +61,10 @@ <h2>Add an Expense</h2>
</div>
</section>
</div>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.814.0.min.js"></script>
<script
type="text/javascript"
src="../utils/amazon-cognito-identity.min.js"
></script>
<script src="scripts.js"></script>
</body>
</html>
166 changes: 141 additions & 25 deletions AWS-APP/Dashboard/scripts.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@

let amountSpent =0;
let amountSpent = 0;
let totalBudget = 0;


const userPool = new AmazonCognitoIdentity.CognitoUserPool({
UserPoolId: 'af-south-1_lURIH3IFw',
ClientId: '23hinerifjsno4tbq6bbrcencc', // Generated in the Cognito User Pool settings
});


function logout() {

const cognitoUser = userPool.getCurrentUser();
// console.log(cognitoUser);

if (cognitoUser != null) {
cognitoUser.signOut();
alert("You have been logged out.");
window.location.href = '../index.html';
// Redirect to login page or update UI
}
else {
alert("Error occured while logging you out.");
}
}

async function fetchData() {
const requestBody = {
username: sessionStorage.getItem('username')
};

try {
const response = await fetch('https://94u93wm33m.execute-api.af-south-1.amazonaws.com/test/budget-app-get', {
const response = await fetch('https://j0hy1rsjrj.execute-api.af-south-1.amazonaws.com/test/budget-app-get', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
Expand All @@ -28,23 +51,83 @@ async function fetchData() {
}
}



async function sendTransactions(transactions) {
const email = '[email protected]'; // Replace with the email you want to send to

const lambdaEndpoint = 'https://j0hy1rsjrj.execute-api.af-south-1.amazonaws.com/test/lala'; // Replace with your Lambda endpoint

console.log(JSON.stringify({ transactions, email }));
try {
const response = await fetch(lambdaEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ transactions, email })
});

if (!response.ok) {
throw new Error('Network response was not ok');
}

const data = await response.json();
console.log(data);

} catch (error) {
console.error('There was an error sending the transactions:', error);
}
}

// Add a button to your HTML with id 'send-transactions-btn'
// <button id="send-transactions-btn">Send Transactions</button>

document.getElementById('email-btn').addEventListener('click', () => {
console.log('Collecting budget items data...');
const budgetItems = document.getElementById('budget-items');
// Initialize an array to hold the transactions
const transactions = [];

// Iterate over each child div of budgetItems
budgetItems.querySelectorAll('div').forEach((div) => {
// Extract the text content of each div
const titleText = div.querySelector('strong:nth-of-type(1)').nextSibling.textContent.trim();
const amountText = div.querySelector('strong:nth-of-type(2)').nextSibling.textContent.trim();
const dateText = div.querySelector('strong:nth-of-type(3)').nextSibling.textContent.trim();


// Add a transaction object to the transactions array
transactions.push({
title: titleText,
amount: amountText,
date: dateText
});
});

// console.log('Transactions:', transactions);
sendTransactions(transactions);

});


async function postData(name, amount) {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');

const formattedDate = `${year}${month}${day}`;
console.log(formattedDate,name, amount);
console.log(formattedDate, name, amount);
const requestBody = {
"username": sessionStorage.getItem('username'),
"name": name,
"amount": amount.toString(),
"created_at": formattedDate
"username": sessionStorage.getItem('username'),
"name": name,
"amount": amount.toString(),
"created_at": formattedDate
};

try {
const response = await fetch('https://94u93wm33m.execute-api.af-south-1.amazonaws.com/test/budgets-app-resource', {
const response = await fetch('https://j0hy1rsjrj.execute-api.af-south-1.amazonaws.com/test/budget-app-post', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
Expand All @@ -58,42 +141,74 @@ async function postData(name, amount) {

const data = await response.json();
console.log(data);

} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
function formatDate(dateString) {
// Create a date object from the input format 'YYYYMMDD'
const year = dateString.substring(0, 4);
const month = dateString.substring(4, 6);
const day = parseInt(dateString.substring(6, 8), 10); // Convert day to number to remove leading 0

// Define an array of month names
const months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
const monthIndex = parseInt(month, 10) - 1; // Convert month to number and get the index (0-based)
const monthName = months[monthIndex];

// Function to get ordinal indicator for a given day
function getOrdinalIndicator(day) {
if (day > 3 && day < 21) return 'th';
switch (day % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}

// Combine the parts to create the final string
return `${day}${getOrdinalIndicator(day)} ${monthName} ${year}`;
}

function displayIds(items, count) {
const responseArea = document.getElementById('budget-items');
responseArea.innerHTML = ''; // Clear previous results

if (count === 0) {
document.getElementById('budget-items').style.display = 'none';

document.getElementById('email-btn-container').style.display = 'none';

} else {
document.getElementById('budget-items').style.display = 'block';

document.getElementById('email-btn-container').style.display = 'flex';




// Reset amountSpent to 0 before calculating the total from fetched items
amountSpent = 0;

items.forEach(item => {
// Create a new div element
const div = document.createElement('div');

// Set the content of the div
div.innerHTML = `<strong>Title:</strong> ${item.name.S} <br> <strong>Amount:</strong> ${item.amount.N}`;
div.innerHTML = `<strong>Title:</strong> ${item.name.S} <br> <strong>Amount:</strong> R${item.amount.N}<br> <strong>Date:</strong> ${formatDate(item.created_at.S)}`;

// Add the item's amount to the total amountSpent
amountSpent += parseFloat(item.amount.N);

// Apply styles to the div
div.style.padding = '20px';
div.style.borderRadius = '5px';
div.style.marginTop = '10px';
div.style.marginBottom = '10px';
div.style.backgroundColor = '#ccc';

// Append the div to the responseArea
responseArea.appendChild(div);
});
Expand Down Expand Up @@ -123,7 +238,7 @@ function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('DOMContentLoaded', function () {


if (!sessionStorage.getItem('username')) {
Expand All @@ -134,32 +249,33 @@ document.addEventListener('DOMContentLoaded', function() {

document.getElementById('username').textContent = sessionStorage.getItem('username') || 'User';

document.getElementById('set-budget-btn').addEventListener('click', function() {
document.getElementById('set-budget-btn').addEventListener('click', function () {
const budget = prompt("What's your budget for this week?");
totalBudget = parseFloat(budget);
if (isNaN(totalBudget)) {alert('Please enter a valid number'); return;}
if (isNaN(totalBudget)) { alert('Please enter a valid number'); return; }
document.getElementById('total-budget').textContent = totalBudget.toFixed(2);
if (totalBudget) {
document.getElementById('set-budget-btn').style.display = 'none';
fetchData();
updateBudgetDisplay();}

updateBudgetDisplay();
}

});

document.getElementById('add-expense-btn').addEventListener('click', function() {
document.getElementById('add-expense-btn').addEventListener('click', function () {
const name = capitalizeFirstLetter(document.getElementById('expense-name').value);
const amount = parseFloat(document.getElementById('expense-amount').value);
if (totalBudget===0) {alert('Please set a budget first'); return;}
else if (name && amount ) {
if (totalBudget === 0) { alert('Please set a budget first'); return; }
else if (name && amount) {
amountSpent += amount;
const div = document.createElement('div');

// Set the content of the div
div.innerHTML = `<strong>Title:</strong> ${name} <br> <strong>Amount:</strong> ${amount}`;

// Add the item's amount to the total amountSpent
// amountSpent += parseFloat(item.amount);

// Apply styles to the div
div.style.padding = '20px';
div.style.borderRadius = '5px';
Expand Down
18 changes: 18 additions & 0 deletions AWS-APP/Dashboard/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,25 @@ s
background-color: #5c94de;
border-radius: 20px;
}
#email-btn {
background: none;
border: none;
color: black;
cursor: pointer;
font-size: 16px;
}

#email-btn:hover {
text-decoration: underline;
background: none;
}

#email-btn-container{
display: none;
width: 100%;
justify-content: end;
align-items: center;
}
#budget-amount, #amount-spent, #remaining-budget {
font-weight: bold;
}
Expand Down
8 changes: 4 additions & 4 deletions AWS-APP/Register/register.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ const userPool = new AmazonCognitoIdentity.CognitoUserPool({



function registerUser(name,email,phone_number, password) {
function registerUser(name, email, phone_number, password) {
const attributeList = [
new AmazonCognitoIdentity.CognitoUserAttribute({
Name: 'email',
Value: email,
}),
new AmazonCognitoIdentity.CognitoUserAttribute({
Name: 'phone_number',
Value: phone_number,
Value: phone_number,
}),
];

Expand All @@ -34,13 +34,13 @@ function registerUser(name,email,phone_number, password) {
}


document.getElementById('signup-form').addEventListener('submit', function(event){
document.getElementById('signup-form').addEventListener('submit', function (event) {
event.preventDefault();
const email = document.getElementById('signup-email').value;
const password = document.getElementById('signup-password').value;
const name = document.getElementById('signup-name').value;
const phone_number = document.getElementById('signup-phone-number').value;
registerUser(name,email, phone_number, password);
registerUser(name, email, phone_number, password);
// window.location.href = 'login.html';
});

Expand Down
Loading

0 comments on commit 9b3bd7f

Please sign in to comment.