From 063cabb557453b6b347db4ddc15c8b19dc8496ba Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mikl=C3=B3s=20T=C3=B3th?= <tothmiklostibor@gmail.com>
Date: Thu, 31 Aug 2023 17:36:38 +0200
Subject: [PATCH] Add submission from UI

---
 homepage/header.template.html   |   1 -
 pultosch/pultosch.template.html | 166 ++++++++++++++++++++++++++------
 static/js/cart.js               |  68 -------------
 3 files changed, 138 insertions(+), 97 deletions(-)
 delete mode 100644 static/js/cart.js

diff --git a/homepage/header.template.html b/homepage/header.template.html
index 1cb50c0..54c54d0 100644
--- a/homepage/header.template.html
+++ b/homepage/header.template.html
@@ -17,7 +17,6 @@
         <link rel="stylesheet" href="/static/style.css">
 
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
-        <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:">
 
         <title>BecskasszáSCH</title>
 
diff --git a/pultosch/pultosch.template.html b/pultosch/pultosch.template.html
index 0cdc871..a946898 100644
--- a/pultosch/pultosch.template.html
+++ b/pultosch/pultosch.template.html
@@ -2,33 +2,143 @@
 
 {{ template "navbar" . }}
 
-{{- if .User.IsPultosch }}
-
-    <form method="post" action="/api/v1/cart">
-            <label for="userSelect">Choose a user:</label><br>
-            <select id="userSelect" name="userId">
-                {{ range .Users }}
-                    <option value="{{ .SchAcc }}">{{ .SchAcc }} - {{ .Name }}</option>
-                {{ end }}
-            </select><br><br>
-
-            <div id="cart">
-                <label>Choose products:</label><br>
-                <select id="productSelect" name="productId">
-                    {{ range .Products }}
-                        <option value="{{ .ID }}">{{ .Name }}</option>
-                    {{ end }}
-                </select>
-                <label for="amount">Amount:</label>
-                <input type="number" id="amount" min="1" value="1" name="amount">
-                <input type="button" id="addToCart" value="Add to  cart"><br>
-            </div>
-
-            <input type="submit" value="Sell">
-        </form>
-
-        <script src="/static/js/cart.js"></script>
-
-{{- end }}
+<style>
+    .prodline {
+        display: flex;
+        flex-direction: row;
+        gap: 1em;
+        align-items: baseline;
+    }
+</style>
+
+<form>
+    <label for="userSelect">Choose a user:</label><br>
+    <select id="userSelect" name="userId">
+        {{ range .Users }}
+        <option value="{{ .SchAcc }}">{{ .SchAcc }} - {{ .Name }}</option>
+        {{ end }}
+    </select><br><br>
+
+    <div id="products">
+        <label>Products</label>
+    </div>
+
+    <input type="button" value="More rows1!!1!" onclick="addLine()"><br><br>
+
+    <p id="sum">Sum: 0 JMF</p>
+
+    <input type="button" value="Let teh moneh rain!$" onclick="submitData()">
+</form>
+
+<script>
+    const products = {{ .Products | toJson }};
+
+    const productsDiv = document.getElementById("products");
+    const sum = document.getElementById("sum");
+
+    function updateSum() {
+        let sum = 0;
+        const sums = document.querySelectorAll("[data-purpose=sum]");
+        sums.forEach(s => {
+            sum += parseInt(s.dataset["sum"]);
+        });
+        document.getElementById("sum").innerText = `Sum: ${sum} JMF`;
+    }
+
+    function addLine() {
+        const line = document.createElement("div");
+        line.className = "prodline";
+
+        const select = document.createElement("select");
+        products.map(p => {
+            const option = document.createElement("option");
+            option.value = p.ID;
+            option.innerHTML = p.Name;
+            option.dataset["price"] = p.Price;
+            select.appendChild(option);
+        });
+        line.appendChild(select);
+
+        const id = Math.random().toString()
+        const lab = document.createElement("label");
+        lab.innerText = "Amount:";
+        lab.htmlFor = id;
+        line.appendChild(lab);
+
+        const amount = document.createElement("input");
+        amount.id = id;
+        amount.type = "number";
+        amount.min = "0";
+        amount.value = "1";
+        amount.name = "amount";
+        line.appendChild(amount);
+
+        const sum = document.createElement("p");
+        sum.dataset["purpose"] = "sum";
+        line.appendChild(sum);
+
+        const br = document.createElement("br");
+        line.appendChild(br);
+
+        onchange = () => {
+            let price = amount.value * select.options[select.selectedIndex].dataset["price"];
+            sum.innerText = `${price} JMF`;
+            sum.dataset["sum"] = price.toString();
+            updateSum();
+        }
+
+        amount.onchange = onchange;
+        select.onchange = onchange;
+        setInterval(onchange, 10);
+
+        productsDiv.appendChild(line);
+    }
+
+    addLine()
+
+    function getPurchaseData() {
+        const data = [];
+        const lines = document.querySelectorAll(".prodline");
+        lines.forEach(l => {
+            const select = l.querySelector("select");
+            const amount = l.querySelector("input");
+            data.push({
+                productId: select.value,
+                amount: amount.value-0
+            });
+        });
+        return data;
+    }
+
+    function getPageData() {
+        return {
+            userId: document.getElementById("userSelect").value,
+            purchases: getPurchaseData()
+        };
+    }
+
+    const endpoint = "/api/v1/cart";
+
+    function submitData() {
+        const data = getPageData();
+        fetch(endpoint, {
+            method: "POST",
+            headers: {
+                "Content-Type": "application/json"
+            },
+            body: JSON.stringify(data)
+        }).then(r => {
+            if (r.ok) {
+                alert("Success!");
+                window.location.reload()
+            } else {
+                // read error from response body
+                r.text().then(err => {
+                    alert(`Something went wrong!\n${err}`);
+                });
+            }
+        });
+    }
+</script>
 
 {{ template "footer" . }}
\ No newline at end of file
diff --git a/static/js/cart.js b/static/js/cart.js
deleted file mode 100644
index e98a537..0000000
--- a/static/js/cart.js
+++ /dev/null
@@ -1,68 +0,0 @@
-function addToCartClickHandler() {
-    const cartEl = document.getElementById('cart');
-
-    // creating a div for each line
-    const lineDiv = document.createElement('div');
-
-    const selectClone = document.getElementById('productSelect').cloneNode(true);
-    const amountLabel = document.createElement('label');
-    amountLabel.setAttribute('for', 'amount');
-    amountLabel.textContent = 'Amount:';
-    const amountInput = document.createElement('input');
-    amountInput.setAttribute('type', 'number');
-    amountInput.setAttribute('value', '1');
-    amountInput.setAttribute('min', '1');
-    amountInput.setAttribute('name', 'amount');
-
-    // creation of the delete button
-    const deleteBtn = document.createElement('input');
-    deleteBtn.setAttribute('type', 'button');
-    deleteBtn.setAttribute('value', 'Delete');
-
-    lineDiv.appendChild(selectClone);
-    lineDiv.appendChild(amountLabel);
-    lineDiv.appendChild(amountInput);
-    lineDiv.appendChild(deleteBtn);
-
-    cartEl.appendChild(lineDiv);
-
-    // Move "Add to Cart" button to the new line
-    const addToCartBtn = document.getElementById('addToCart');
-    lineDiv.appendChild(addToCartBtn);
-
-    // On delete button click
-    deleteBtn.addEventListener('click', () => {
-        lineDiv.remove();
-
-        if (!document.getElementById('addToCart')) { // If there are no lines left,
-            const lastLine = cartEl.lastElementChild;  // Get last line
-            if (lastLine) { // if last line exists
-                lastLine.appendChild(addToCartBtn); // Re-append the 'Add to Cart' button to the last line
-            }
-        }
-    });
-}
-
-document.getElementById('addToCart').addEventListener('click', addToCartClickHandler);
-
-document.querySelector("form").addEventListener("submit", function(event){
-    event.preventDefault();
-
-    let formData = new FormData();
-    formData.append("userId", document.querySelector("#userSelect").value);
-
-    document.querySelectorAll("#cart div").forEach(function(div){
-        let product = div.querySelector("select").value;
-        let amount = div.querySelector("input[name='amount']").value;
-
-        formData.append(product, amount);
-        // formData.append("amounts[]", amount);
-    });
-
-    // use fetch API to send async POST request
-    fetch('/api/v1/cart', {
-        method: 'POST',
-        body: formData
-    }).then(response => console.log(response))
-        .catch(error => console.error(error))
-});
\ No newline at end of file
-- 
GitLab