toddler_shop_frontend/static/scripts/main.js
2024-09-04 10:08:06 +02:00

92 lines
No EOL
3 KiB
JavaScript

var all_products
let barcodeForm
const api_url = "http://192.168.1.3:8000"
var to_fill_product_index = 0
var total_price = 0
async function makeAPIRequest(request) {
try {
const response = await fetch(request);
const result = await response.json();
return result
} catch (error) {
console.error("Error:", error);
}
}
async function loadCash(price) {
const cashAmountRequest = new Request(api_url + '/price_to_cash/' + price)
const cashAmount = await makeAPIRequest(cashAmountRequest)
const cash_bills_row = document.getElementById('cash_bills')
for (var bill_type in cashAmount){
bill_amount = cashAmount[bill_type]
console.log(bill_type, bill_amount)
for (var x = 0; x < bill_amount; x++){
const new_column = document.createElement('div')
new_column.classList.add('col')
const bill_image = document.createElement('img')
bill_image.src = api_url + '/icons/' + bill_type
new_column.appendChild(bill_image)
cash_bills_row.appendChild(new_column)
}
}
}
async function loadProducts() {
const loadProductRequest = new Request(api_url + "/products")
all_products = await makeAPIRequest(loadProductRequest)
console.log("Loaded products:", all_products)
barcodeForm = document.getElementById("barcode_form");
barcodeForm.addEventListener("submit", (e) => {
e.preventDefault();
if (to_fill_product_index < 5) {
const barcode = document.getElementById('barcode_input').value
var chosen_product
for (index = 0; index < all_products.length; index++) {
if (all_products[index].barcode == barcode) {
chosen_product = all_products[index]
}
}
barcode_input.value = ""
const product_placeholders = document.getElementsByClassName('product_col')
const chosen_product_placeholder = product_placeholders[to_fill_product_index]
const image_product = chosen_product_placeholder.getElementsByClassName('product_image')[0]
const price_product = chosen_product_placeholder.getElementsByClassName('product_price')[0]
const total_price_holder = document.getElementById("totalprice")
total_price += chosen_product.price
image_product.setAttribute('src', api_url + "/icons/" + chosen_product.image_filename);
price_product.textContent = "\u20AC " + chosen_product.price
total_price_holder.textContent = "\u20AC " + total_price
to_fill_product_index += 1
}else{
barcode_input.value = ""
}
});
}
async function payCash() {
const total_cost = document.getElementById('totalprice').innerHTML.replace('€ ','')
window.location.replace("/pay_cash/" + total_cost);
}
async function toMain() {
window.location.replace("/");
}