]> git repositories - simple-cash-register.git/commitdiff
lot of functions added, I don't know what commit message I'll put here.
authorbochard <mail@tenkyuu.dev>
Sun, 2 Mar 2025 09:37:05 +0000 (17:37 +0800)
committerbochard <mail@tenkyuu.dev>
Sun, 2 Mar 2025 09:37:05 +0000 (17:37 +0800)
index.css [deleted file]
index.html
index.js [deleted file]
script.js [new file with mode: 0644]
styles.css [new file with mode: 0644]

diff --git a/index.css b/index.css
deleted file mode 100644 (file)
index 79d3918..0000000
--- a/index.css
+++ /dev/null
@@ -1,37 +0,0 @@
-*,
-::before,
-::after {
-  box-sizing: border-box;
-  margin: 0;
-  padding: 0;
-}
-html {
-  font-size: 62.5%;
-}
-body {
-  font-size: 2rem;
-}
-.cash-register-screen {
-  padding: 1rem;
-  border: 1px solid black;
-}
-.product-list {
-  display: flex;
-  flex-direction: column;
-  gap: 1rem;
-  padding: 1rem;
-  border: 1px solid black;
-}
-.product-wrapper {
-  display: flex;
-  justify-content: space-between;
-  align-items: center;
-  padding: 1rem;
-  border: 1px solid black;
-}
-.quantity-controls {
-  display: flex;
-  align-items: center;
-  gap: 1rem;
-  padding: 0.5rem;
-}
\ No newline at end of file
index 124690bf2a46a8cd1bb607317a18d895d0936c0e..3d3cfdb6efda19be395d07523dc770e80237e6cd 100644 (file)
@@ -4,7 +4,7 @@
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Digital Cash Register</title>
-    <link rel="stylesheet" href="./index.css">
+    <link rel="stylesheet" href="./styles.css">
   </head>
   <body>
     <div class="customer-input-ctn">
@@ -49,6 +49,6 @@
       <div id="change-drawer"></div>
     </div>
 
-    <script src="./index.js"></script>
+    <script src="./script.js"></script>
   </body>
 </html>
\ No newline at end of file
diff --git a/index.js b/index.js
deleted file mode 100644 (file)
index eba34c7..0000000
--- a/index.js
+++ /dev/null
@@ -1,160 +0,0 @@
-const cash = document.getElementById('cash');
-const purchaseBtn = document.getElementById('purchase-btn');
-const totalPriceIndicator = document.getElementById('total-price');
-const changeDue = document.getElementById('change-due');
-const productList = document.getElementById('product-list');
-const productQuantity = document.querySelectorAll('.product-quantity');
-const changeDrawer = document.getElementById('change-drawer');
-
-let totalChangeToReturn = 0;
-let price = 19.5; // 1.87 - original
-let cart = {};
-let totalPriceOnCart = 0;
-let cid = [
-  ['PENNY', 1.01],        // 101 pennies
-  ['NICKEL', 2.05],       // 41 nickels
-  ['DIME', 3.1],          // 31 dimes
-  ['QUARTER', 4.25],      // 17 quarters
-  ['ONE', 90],            // 90 one-dollar bills
-  ['FIVE', 55],           // 11 five-dollar bills
-  ['TEN', 20],            // 2 ten-dollar bills
-  ['TWENTY', 60],         // 3 twenty-dollar bills
-  ['ONE HUNDRED', 100]    // 1 hundred-dollar bill
-];
-const currency = {
-  'PENNY': 0.01,
-  'NICKEL': 0.05,
-  'DIME': 0.10,
-  'QUARTER': 0.25,
-  'ONE': 1,
-  'FIVE': 5,
-  'TEN': 10,
-  'TWENTY': 20,
-  'ONE HUNDRED': 100
-}
-const productsPrice = {
-  'water bottle': 1,
-  'bread': 2.5,
-  'coffee': 1.5
-}
-
-// ===== TODO: CALCULATE THE CHANGE =====
-function calculateChange(amount) {
-  let reversedCid = [...cid].reverse();
-  let changeToReturn = [];
-
-  while (amount < currencyValue) {
-      
-  }
-  
-  reversedCid.forEach((arr) => {
-    const cashName = arr[0];
-    const cashValue = arr[1];
-
-    while (currency[cashName] < amount) {
-      changeToReturn += amount - cashValue;
-    }
-  })
-  totalChangeToReturn = changeToReturn;
-}
-
-// ===== CHECK IF CASH IS GREATER THAN THE TOTAL PRICE IN CART =====
-function checkCashAmount(cash) {
-  if (cash < totalPriceOnCart || !cash) {
-    alert('Customer does not have enough money to purchase the item');
-    return;
-  } else if (cash === totalPriceOnCart) {
-    changeDue.textContent = 'No change due - customer paid with exact cash';
-    return; // remove this soon
-  } else if (cash > totalPriceOnCart) {
-    const difference = cash - totalPriceOnCart;
-    alert('proceeded to calculate change');
-    calculateChange(difference);
-  }
-}
-
-// ===== REMOVE INPUT =====
-function removeInput() {
-  cash.value = '';
-}
-
-// ===== RESET LIST QUANTITY =====
-function resetProductListQuantity() {
-  productQuantity.forEach((item) => {
-    item.textContent = '0';
-  })
-}
-
-// ===== RESET TOTAL PRICE INDICATOR =====
-function resetPriceIndicator() {
-  totalPriceIndicator.textContent = '$0.00';
-}
-
-// ===== UPDATE THE TOTAL ON PRICE INDICATOR =====
-function updatePriceIndicator() {
-  totalPriceIndicator.textContent = `$${totalPriceOnCart.toFixed(2)}`;
-}
-
-// ===== CALCULATE THE TOTAL OF PRODUCTS ADDED =====
-function calculateCartItems() {
-  let temporaryPrice = 0;
-  Object.entries(cart).forEach(([product, price]) => {
-    temporaryPrice += price * productsPrice[product];
-  })
-  totalPriceOnCart = temporaryPrice;
-}
-
-// ===== WHEN PLUS BTN OR MINUS BTN IS CLICKED =====
-function plusOrMinusBtnIsClicked(event) {
-  const plusBtn = event.target.classList.contains('plus-btn');
-  const minusBtn = event.target.classList.contains('minus-btn');
-
-  if (plusBtn) { // plus btn is clicked
-    const quantity = event.target.previousElementSibling;
-    let quantityInt = parseInt(quantity.textContent);
-    const productName = event.target.parentElement.previousElementSibling.childNodes[0].textContent.trim().toLowerCase();
-
-    quantityInt += 1;
-    quantity.textContent = quantityInt;
-
-    if (cart[productName]) {
-      cart[productName] += 1;
-    } else {
-      cart[productName] = 1;
-    }
-  }
-  
-  if (minusBtn) { // minus btn is clicked
-    const quantity = event.target.nextElementSibling;
-    let quantityInt = parseInt(quantity.textContent);
-    const productName = event.target.parentElement.previousElementSibling.childNodes[0].textContent.trim().toLowerCase();
-
-    if (quantityInt > 0) {
-      quantityInt -= 1;
-      quantity.textContent = quantityInt;
-    }
-
-    if (cart[productName]) {
-      cart[productName] -= 1;
-      if (cart[productName] === 0) {
-        delete cart[productName];
-      }
-    }
-  }
-}
-
-// ===== LISTEN FOR UPDATE QUANTITY =====
-productList.addEventListener('click', (e) => {
-  plusOrMinusBtnIsClicked(e);
-  calculateCartItems();
-  updatePriceIndicator();
-})
-
-// ===== LISTEN FOR PURCHASE CLICK =====
-purchaseBtn.addEventListener('click', () => {
-  const cashValue = Number(cash.value);
-  checkCashAmount(cashValue);
-  removeInput();
-  resetProductListQuantity()
-  resetPriceIndicator()
-})
\ No newline at end of file
diff --git a/script.js b/script.js
new file mode 100644 (file)
index 0000000..4aa3c02
--- /dev/null
+++ b/script.js
@@ -0,0 +1,212 @@
+const cash = document.getElementById('cash');
+const purchaseBtn = document.getElementById('purchase-btn');
+const totalPriceIndicator = document.getElementById('total-price');
+const changeDue = document.getElementById('change-due');
+const productList = document.getElementById('product-list');
+const productQuantity = document.querySelectorAll('.product-quantity');
+const changeDrawer = document.getElementById('change-drawer');
+
+let totalChangeToReturn = 0;
+let price = 0;
+let cart = {};
+let cid = [
+  ['PENNY', 1.01],        // 101 pennies
+  ['NICKEL', 2.05],       // 41 nickels
+  ['DIME', 3.1],          // 31 dimes
+  ['QUARTER', 4.25],      // 17 quarters
+  ['ONE', 90],            // 90 one-dollar bills
+  ['FIVE', 55],           // 11 five-dollar bills
+  ['TEN', 20],            // 2 ten-dollar bills
+  ['TWENTY', 60],         // 3 twenty-dollar bills
+  ['ONE HUNDRED', 100]    // 1 hundred-dollar bill
+];
+const currency = {
+  'PENNY': 0.01,
+  'NICKEL': 0.05,
+  'DIME': 0.10,
+  'QUARTER': 0.25,
+  'ONE': 1,
+  'FIVE': 5,
+  'TEN': 10,
+  'TWENTY': 20,
+  'ONE HUNDRED': 100
+}
+const productsPrice = {
+  'water bottle': 1,
+  'bread': 2.5,
+  'coffee': 1.5
+}
+
+// ===== CALCULATE THE CHANGE =====
+function calculateChange(amount) {
+  console.log('CID Before:', JSON.stringify(cid));
+  let reversedCid = [...cid].reverse();
+  let changeToReturn = [];
+  let remainingAmount = Math.round(amount * 100);
+  let tempCid = [];
+  let status = '';
+  let totalCashAvailable = Math.round(cid.reduce((sum, [, value]) => sum + value, 0) * 100);
+  let cashUsed = 0;
+  
+  reversedCid.forEach(([cashName, cashAvailable]) => {
+    let amountFromThisCurrency = 0;
+    let cashAvailableInCents = Math.round(cashAvailable * 100);
+    let unitValueInCents = Math.round(currency[cashName] * 100);
+
+    while (remainingAmount >= unitValueInCents && cashAvailableInCents >= unitValueInCents) {
+      amountFromThisCurrency += unitValueInCents;
+      remainingAmount -= unitValueInCents;
+      cashAvailableInCents -= unitValueInCents;
+    }
+
+    if (amountFromThisCurrency > 0) {
+      changeToReturn.push([cashName, amountFromThisCurrency / 100]);
+    }
+
+    cashUsed += amountFromThisCurrency;
+    tempCid.push([cashName, cashAvailableInCents / 100]);
+  })
+
+  if (remainingAmount > 0) {
+    status = 'INSUFFICIENT_FUNDS';
+    changeToReturn = [];
+  } else if (remainingAmount === 0 && cashUsed === totalCashAvailable) {
+    status = 'CLOSED';
+    changeToReturn = [...cid];
+  } else {
+    status = 'OPEN';
+  }
+
+  cid = tempCid.reverse();
+  updateChangeDue(status, changeToReturn);
+
+  console.log('Total Price:', price);
+  console.log('Cash Given:', cash.value);
+
+  console.log('Remaining Amount:', remainingAmount);
+  console.log('Change to Return:', changeToReturn);
+  console.log('Total Cash Available:', totalCashAvailable);
+  console.log('Cash Used:', cashUsed);
+  console.log('CID After:', JSON.stringify(tempCid));
+}
+
+// ===== CHECK IF CASH IS GREATER THAN THE TOTAL PRICE IN CART =====
+function checkCashAmount(cash) {
+  if (cash < price || !cash) {
+    alert('Customer does not have enough money to purchase the item');
+    return;
+  } else if (cash === price) {
+    changeDue.textContent = 'No change due - customer paid with exact cash';
+    return; // remove this soon
+  } else if (cash > price) {
+    const difference = cash - price;
+    calculateChange(difference);
+  }
+}
+
+// ===== RESET CART OBJECT =====
+function resetCart() {
+  cart = {};
+}
+
+// ===== REMOVE INPUT =====
+function removeInput() {
+  cash.value = '';
+}
+
+// ===== RESET LIST QUANTITY =====
+function resetProductListQuantity() {
+  productQuantity.forEach((item) => {
+    item.textContent = '0';
+  })
+}
+
+// ===== RESET TOTAL PRICE INDICATOR =====
+function resetPriceIndicator() {
+  totalPriceIndicator.textContent = '$0.00';
+}
+
+// ===== UPDATE CHANGE DUE TEXT CONTENT =====
+function updateChangeDue(status, arr) {
+  let output = `Status: ${status}<br>`;
+
+  arr.forEach((arr) => {
+    const name = arr[0];
+    const value = arr[1];
+
+    output += `${name}: $${value}<br>`;
+  })
+
+  changeDue.innerHTML = output;
+  console.log(cid);
+}
+
+// ===== UPDATE THE TOTAL ON PRICE INDICATOR =====
+function updatePriceIndicator() {
+  totalPriceIndicator.textContent = `$${price.toFixed(2)}`;
+}
+
+// ===== CALCULATE THE TOTAL OF PRODUCTS ADDED =====
+function calculateCartItems() {
+  let temporaryPrice = 0;
+  Object.entries(cart).forEach(([product, price]) => {
+    temporaryPrice += price * productsPrice[product];
+  })
+  price = temporaryPrice;
+}
+
+// ===== WHEN PLUS BTN OR MINUS BTN IS CLICKED =====
+function plusOrMinusBtnIsClicked(event) {
+  const plusBtn = event.target.classList.contains('plus-btn');
+  const minusBtn = event.target.classList.contains('minus-btn');
+
+  if (plusBtn) { // plus btn is clicked
+    const quantity = event.target.previousElementSibling;
+    let quantityInt = parseInt(quantity.textContent);
+    const productName = event.target.parentElement.previousElementSibling.childNodes[0].textContent.trim().toLowerCase();
+
+    quantityInt += 1;
+    quantity.textContent = quantityInt;
+
+    if (cart[productName]) {
+      cart[productName] += 1;
+    } else {
+      cart[productName] = 1;
+    }
+  }
+  
+  if (minusBtn) { // minus btn is clicked
+    const quantity = event.target.nextElementSibling;
+    let quantityInt = parseInt(quantity.textContent);
+    const productName = event.target.parentElement.previousElementSibling.childNodes[0].textContent.trim().toLowerCase();
+
+    if (quantityInt > 0) {
+      quantityInt -= 1;
+      quantity.textContent = quantityInt;
+    }
+
+    if (cart[productName]) {
+      cart[productName] -= 1;
+      if (cart[productName] === 0) {
+        delete cart[productName];
+      }
+    }
+  }
+}
+
+// ===== LISTEN FOR UPDATE QUANTITY =====
+productList.addEventListener('click', (e) => {
+  plusOrMinusBtnIsClicked(e);
+  calculateCartItems();
+  updatePriceIndicator();
+})
+
+// ===== LISTEN FOR PURCHASE CLICK =====
+purchaseBtn.addEventListener('click', () => {
+  const cashValue = parseFloat(cash.value);
+  checkCashAmount(cashValue);
+  removeInput();
+  resetCart();
+  resetProductListQuantity()
+  resetPriceIndicator()
+})
\ No newline at end of file
diff --git a/styles.css b/styles.css
new file mode 100644 (file)
index 0000000..79d3918
--- /dev/null
@@ -0,0 +1,37 @@
+*,
+::before,
+::after {
+  box-sizing: border-box;
+  margin: 0;
+  padding: 0;
+}
+html {
+  font-size: 62.5%;
+}
+body {
+  font-size: 2rem;
+}
+.cash-register-screen {
+  padding: 1rem;
+  border: 1px solid black;
+}
+.product-list {
+  display: flex;
+  flex-direction: column;
+  gap: 1rem;
+  padding: 1rem;
+  border: 1px solid black;
+}
+.product-wrapper {
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  padding: 1rem;
+  border: 1px solid black;
+}
+.quantity-controls {
+  display: flex;
+  align-items: center;
+  gap: 1rem;
+  padding: 0.5rem;
+}
\ No newline at end of file