Merge pull request 'Bestellung' (#30) from Bestellung into develop

Reviewed-on: #30

Funktionen von /bestellformular erweitert und /bestellung gefixed
This commit is contained in:
florianspengler 2025-04-29 07:42:24 +00:00
commit 44d9fe834c
17 changed files with 760 additions and 136 deletions

36
package-lock.json generated
View File

@ -1,11 +1,11 @@
{ {
"name": "sniper", "name": "webshop",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "sniper", "name": "webshop",
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
@ -15,7 +15,9 @@
"express-session": "^1.18.1", "express-session": "^1.18.1",
"mysql": "^2.18.1", "mysql": "^2.18.1",
"mysql2": "^3.12.0", "mysql2": "^3.12.0",
"path": "^0.12.7" "node": "^22.15.0",
"path": "^0.12.7",
"server.js": "^1.0.0"
} }
}, },
"node_modules/accepts": { "node_modules/accepts": {
@ -674,6 +676,28 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/node": {
"version": "22.15.0",
"resolved": "https://registry.npmjs.org/node/-/node-22.15.0.tgz",
"integrity": "sha512-qrOEL83lNt+Jbh9pekl5xQrZK+QRJz51m2IGGCu2NENgbG6Go0D1QUBvjbejP8jB2eokQpX1AorDLbKQ/FxuYA==",
"hasInstallScript": true,
"license": "ISC",
"dependencies": {
"node-bin-setup": "^1.0.0"
},
"bin": {
"node": "bin/node"
},
"engines": {
"npm": ">=5.0.0"
}
},
"node_modules/node-bin-setup": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/node-bin-setup/-/node-bin-setup-1.1.3.tgz",
"integrity": "sha512-opgw9iSCAzT2+6wJOETCpeRYAQxSopqQ2z+N6BXwIMsQQ7Zj5M8MaafQY8JMlolRR6R1UXg2WmhKp0p9lSOivg==",
"license": "ISC"
},
"node_modules/object-inspect": { "node_modules/object-inspect": {
"version": "1.13.2", "version": "1.13.2",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz",
@ -894,6 +918,12 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/server.js": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/server.js/-/server.js-1.0.0.tgz",
"integrity": "sha512-fO4IvzkZ09bBB++XU/gWGuzxJs0OpghSd/34mlW8coMoakLzj/+W5d1pHX+I+7H52GkBKu96UQU0K5vptNjaqg==",
"license": "ISC"
},
"node_modules/set-function-length": { "node_modules/set-function-length": {
"version": "1.2.2", "version": "1.2.2",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",

View File

@ -1,10 +1,10 @@
{ {
"name": "sniper", "name": "webshop",
"version": "1.0.0", "version": "1.0.0",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js" "start": "npm install && node server.js"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
@ -12,13 +12,13 @@
"description": "Webshop Autohändler", "description": "Webshop Autohändler",
"dependencies": { "dependencies": {
"app-root-path": "^3.1.0", "app-root-path": "^3.1.0",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"express": "^4.21.2", "express": "^4.21.2",
"express-session": "^1.18.1", "express-session": "^1.18.1",
"mysql": "^2.18.1", "mysql": "^2.18.1",
"mysql2": "^3.12.0", "mysql2": "^3.12.0",
"path": "^0.12.7" "node": "^22.15.0",
"path": "^0.12.7",
"server.js": "^1.0.0"
} }
} }

View File

@ -15,7 +15,7 @@
<main> <main>
<div class="form-container"> <div class="form-container">
<form action="/submit-bestellung" method="post"> <form method="post" id="bestellform">
<h2>Bestellformular</h2> <h2>Bestellformular</h2>
<label for="vorname">Vorname:</label> <label for="vorname">Vorname:</label>
@ -36,17 +36,222 @@
<label for="ort">Ort:</label> <label for="ort">Ort:</label>
<input type="text" id="ort" name="ort" required placeholder="Ort"> <input type="text" id="ort" name="ort" required placeholder="Ort">
<label for="telefon Nr">Telefon Nr (optional):</label>
<input type="tel" id="telefon Nr" name="telefon" placeholder="Telefon Nr">
<label for="ArtikelNr">Artikel Nr.:</label> <label for="ArtikelNr">Artikel Nr.:</label>
<textarea id="ArtikelNr" name="ArtikelNr" rows="4" required placeholder="Artikel Nr."></textarea> <div class="Artikel">
<button type="button" class="loeschen-button" onclick="loescheArtikel(this)">x</button>
<input type="text" class="ArtikelNrText" id="ArtikelNr" name="ArtikelNr" required placeholder="Artikel Nr.">
<input type="text" class="StueckzahlText" id="Stueckzahl" name="Stueckzahl" required placeholder="Anzahl">
<div class="verfuegbarkeit"></div>
</div>
<input type="submit" value="Bestellung absenden"> <style>
.Artikel{
display: flex;
align-content: center;
}
.ArtikelNrText{
max-width: 50%;
}
.StueckzahlText{
max-width: 15%;
margin-left: 2.5%;
}
.loeschen-button{
background-color: #ff6600;
color: white;
border: none;
border-radius: 5px;
width: 5%;
height: 30px;
cursor: pointer;
margin-right: 5px;
}
.verfuegbarkeit{
display: flex;
align-content: center;
max-width: 20%;
padding-left: 2.5%;
}
</style>
<a class="button-submit" id="sendOrder">Bestellung absenden</a>
</form> </form>
</div> </div>
</main> </main>
<script>
document.addEventListener('DOMContentLoaded', function () {
const formular = document.getElementById('bestellform');
const sendButton = document.getElementById('sendOrder');
let artikelVerfuegbarkeiten = [];
// Bestellung absenden
sendButton.addEventListener('click', async function (event) {
event.preventDefault();
const form = document.getElementById('bestellform');
// Kundendaten einsammeln
const userData = {
vorname: form.Vorname.value.trim(),
nachname: form.Nachname.value.trim(),
kundenNr: form.KundenNr.value.trim(),
strasse: form.strasse.value.trim(),
hausnummer: form.hausnummer.value.trim(),
ort: form.ort.value.trim()
};
// Artikel einsammeln
const artikelInputs = document.querySelectorAll('.Artikel');
const produkte = [];
artikelInputs.forEach(artikel => {
const artikelNrInput = artikel.querySelector('.ArtikelNrText');
const stueckzahlInput = artikel.querySelector('.StueckzahlText');
if (artikelNrInput && artikelNrInput.value.trim() !== '') {
produkte.push({
product_id: parseInt(artikelNrInput.value.trim(), 10),
quantity: parseInt(stueckzahlInput.value.trim(), 10) || 1
});
}
});
if (produkte.length === 0) {
alert('Bitte mindestens ein Produkt angeben!');
return;
}
const payload = {
user_id: parseInt(userData.kundenNr, 10),
produkte: produkte
};
try {
const response = await fetch('/api/bestellung', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
const result = await response.json();
if (response.ok) {
// Bestellung erfolgreich -> Weiterleitung
window.location.href = "/bestellung";
} else {
alert('Fehler: ' + result.message);
}
} catch (error) {
console.error('Fehler beim Abschicken der Bestellung:', error);
alert('Serverfehler beim Abschicken der Bestellung.');
}
});
// Artikelnummer prüfen bei Eingabe
formular.addEventListener('input', async function (event) {
if (event.target.classList.contains('ArtikelNrText')) {
if (event.target.value.trim() !== '') {
await pruefeVerfuegbarkeit(event.target);
fuegeNeuesArtikelFeldHinzu();
}
}
});
});
// Funktion: Verfügbarkeit prüfen
async function pruefeVerfuegbarkeit(inputFeld) {
const artikelnummer = inputFeld.value.trim();
const verfuegbarkeitDiv = inputFeld.parentElement.querySelector('.verfuegbarkeit');
const sendButton = document.getElementById('sendOrder');
if (artikelnummer.length === 0) {
verfuegbarkeitDiv.textContent = "";
return;
}
try {
const response = await fetch(`/api/pruefe-artikel?nummer=${encodeURIComponent(artikelnummer)}`);
const data = await response.json();
const artikelDivs = document.querySelectorAll('.Artikel');
artikelVerfuegbarkeiten = [];
artikelDivs.forEach(div => {
const artikelNrInput = div.querySelector('.ArtikelNrText');
const verfDiv = div.querySelector('.verfuegbarkeit');
if (artikelNrInput.value.trim() !== '') {
if (artikelNrInput === inputFeld) {
if (data.verfuegbar) {
verfDiv.textContent = "Artikel verfügbar.";
verfDiv.style.color = "green";
artikelVerfuegbarkeiten.push(true);
} else {
verfDiv.textContent = "Artikel nicht verfügbar!";
verfDiv.style.color = "red";
artikelVerfuegbarkeiten.push(false);
}
} else {
// Für andere Felder bisherige Anzeige berücksichtigen
if (verfDiv.textContent.includes("nicht verfügbar")) {
artikelVerfuegbarkeiten.push(false);
} else {
artikelVerfuegbarkeiten.push(true);
}
}
}
});
// Button sperren/freigeben
if (artikelVerfuegbarkeiten.every(status => status === true)) {
sendButton.disabled = false;
} else {
sendButton.disabled = true;
}
} catch (error) {
console.error('Fehler bei der Artikelsuche:', error);
verfuegbarkeitDiv.textContent = "Fehler bei der Prüfung.";
verfuegbarkeitDiv.style.color = "orange";
sendButton.disabled = true;
}
}
// Funktion: Neues Artikelfeld hinzufügen
function fuegeNeuesArtikelFeldHinzu() {
const formular = document.getElementById('bestellform');
const artikelnummerFelder = formular.querySelectorAll('.ArtikelNrText');
const letztesFeld = artikelnummerFelder[artikelnummerFelder.length - 1];
if (letztesFeld && letztesFeld.value.trim() !== '') {
const neueArtikelDiv = document.createElement('div');
neueArtikelDiv.className = 'Artikel';
neueArtikelDiv.innerHTML = `
<button type="button" class="loeschen-button" onclick="loescheArtikel(this)">x</button>
<input type="text" class="ArtikelNrText" name="ArtikelNr" required placeholder="Artikel Nr.">
<input type="text" class="StueckzahlText" name="Stueckzahl" required placeholder="Anzahl">
<div class="verfuegbarkeit"></div>
`;
const sendButton = document.getElementById('sendOrder');
formular.insertBefore(neueArtikelDiv, sendButton);
}
}
// Funktion: Artikel löschen
function loescheArtikel(button) {
const artikelDiv = button.parentElement;
artikelDiv.remove();
}
</script>
<!-- Footer wird dynamisch geladen --> <!-- Footer wird dynamisch geladen -->
<div id="footer"></div> <div id="footer"></div>
</div> </div>

View File

@ -0,0 +1,104 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ihre Bestellung</title>
<link rel="stylesheet" href="/Styles/bestellung/bestellung.css">
<link rel="stylesheet" href="/Styles/styles-main.css">
<script src="/header_footer"></script>
</head>
<body>
<!-- Header wird hier dynamisch geladen -->
<div id="header-placeholder"></div>
<main>
<h2>Ihre Bestellung:</h2>
<div id="bestellung">
<!-- Platzhalter für die Bestellinformationen -->
<div class="bestell-info-card">
<p><strong>Kundennummer:</strong> <span id="kundenNr"></span></p>
<p><strong>Produkt-ID:</strong> <span id="produktId"></span></p>
<p><strong>Produktname:</strong> <span id="produktName"></span></p>
<p><strong>Preis:</strong> <span id="preis"></span></p>
</div>
</div>
</main>
<script>
async function ladeBestellung() {
const user_id = sessionStorage.getItem('user_id');
if (!user_id) {
alert('Sie sind nicht eingeloggt! Bitte loggen Sie sich ein.');
window.location.href = '/login';
return;
}
try {
const response = await fetch('/api/bestellung/daten', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ user_id: user_id })
});
if (response.ok) {
const daten = await response.json();
const bestellungContainer = document.getElementById('bestellung');
bestellungContainer.innerHTML = '';
const bestellungen = {};
daten.forEach(item => {
if (!bestellungen[item.order_id]) {
bestellungen[item.order_id] = {
total: item.order_total,
produkte: []
};
}
bestellungen[item.order_id].produkte.push({
name: item.product_name,
preis: item.product_price,
quantity: item.quantity
});
});
for (const orderId in bestellungen) {
const bestellung = bestellungen[orderId];
const bestellCard = document.createElement('div');
bestellCard.className = 'bestell-info-card';
let produkteHTML = '';
bestellung.produkte.forEach(produkt => {
produkteHTML += `
<p>• ${produkt.name} — ${produkt.quantity} Stück — Preis: ${produkt.preis.toFixed(2)} €</p>
`;
});
bestellCard.innerHTML = `
<h3>Bestellnummer: ${orderId}</h3>
${produkteHTML}
<p><strong>Gesamtsumme:</strong> ${bestellung.total.toFixed(2)} €</p>
`;
bestellungContainer.appendChild(bestellCard);
}
} else if (response.status === 404) {
document.getElementById('bestellung').innerHTML = '<p>Keine Bestellungen gefunden.</p>';
} else {
console.error('Fehler beim Laden der Bestellungen.');
}
} catch (error) {
console.error('Fehler: ', error);
}
}
window.addEventListener('DOMContentLoaded', ladeBestellung);
</script>
<!-- Footer wird dynamisch geladen -->
<div id="footer"></div>
</body>
</html>

View File

@ -7,7 +7,7 @@
<div class="header-right"> <div class="header-right">
<a href="/login" class="login-btn">Login</a> <a href="/login" class="login-btn">Login</a>
<div class="header-right"> <div class="header-right">
<a href="/login" class="login-btn">Login</a>
<a href="/warenkorb" class="cart"> <a href="/warenkorb" class="cart">
<i class='bx bx-cart'></i> <i class='bx bx-cart'></i>
<span class="cart-count">0</span> <span class="cart-count">0</span>

View File

@ -15,17 +15,17 @@
<main class="main-content"> <main class="main-content">
<div class="login-container"> <div class="login-container">
<h2 class="title">Login</h2> <h2 class="login-title">Login</h2>
<form class="login-form"> <form class="login-form">
<div class="input-group"> <div class="input-group">
<input type="text" placeholder="Username" required/> <input id="email" type="text" placeholder="E-Mail" required/>
<i class="icon fas fa-user"></i> <i class="icon fas fa-user"></i>
</div> </div>
<div class="input-group"> <div class="input-group">
<input type="password" placeholder="Passwort" required/> <input id="password" type="password" placeholder="Passwort" required/>
<i class="icon fas fa-lock"></i> <i class="icon fas fa-lock"></i>
</div> </div>
<button type="submit" class="login-btn">Login</button> <button id="submit" type="submit" class="login-btn">Login</button>
<p class="register-text"> <p class="register-text">
Noch keinen Account? <a href="/registrieren">Registrieren</a> Noch keinen Account? <a href="/registrieren">Registrieren</a>
</p> </p>
@ -33,7 +33,37 @@
</div> </div>
</main> </main>
<!-- Fußzeiele --> <script>
document.getElementById('submit').addEventListener('click', async (event) => {
event.preventDefault()
const email = document.getElementById('email').value
const password = document.getElementById('password').value
try {
const response = await fetch('/api/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({email, password})
})
if (response.ok) {
const data = await response.json();
sessionStorage.setItem("user_id", data.id)
alert('Login erfolgreich!');
window.location.href = '/'; // Redirect to home page after login
} else {
const errorData = await response.json()
alert('Login fehlgeschlagen: ' + (errorData.message || 'Unbekannter Fehler'))
}
} catch (error) {
console.error('Fehler beim Login: ', error)
alert('Fehler beim Senden des Logins.')
}
})
</script>
<!-- Fußzeile -->
<div id="footer"></div> <div id="footer"></div>
</body> </body>

View File

@ -22,15 +22,15 @@
<h2 class="title">Registrieren</h2> <h2 class="title">Registrieren</h2>
<div class="input-box"> <div class="input-box">
<input type="text" name="vorname" placeholder="Vorname" required> <input type="text" name="vorname" placeholder="Vorname" required id="vorname">
<i class='bx bxs-user'></i> <i class='bx bxs-user'></i>
</div> </div>
<div class="input-box"> <div class="input-box">
<input type="text" name="nachname" placeholder="Nachname" required> <input type="text" name="nachname" placeholder="Nachname" required id="nachname">
<i class='bx bxs-user'></i> <i class='bx bxs-user'></i>
</div> </div>
<div class="input-box"> <div class="input-box">
<input type="email" name="email" placeholder="E-Mail" required> <input type="email" name="email" placeholder="E-Mail" required id="email">
<i class='bx bxs-envelope'></i> <i class='bx bxs-envelope'></i>
</div> </div>
<div class="input-box"> <div class="input-box">
@ -44,7 +44,7 @@
<i class='bx bxs-lock-alt'></i> <i class='bx bxs-lock-alt'></i>
</div> </div>
<button type="submit" class="register-btn">Registrieren</button> <button type="submit" class="btn" id="register">Registrieren</button>
<div class="register-link"> <div class="register-link">
<br> <br>
@ -54,6 +54,40 @@
</div> </div>
</main> </main>
<script>
document.getElementById('register').addEventListener('click', async (event) => {
event.preventDefault();
const formData = {
name: document.getElementById('vorname').value,
lower_name: document.getElementById('nachname').value,
email: document.getElementById('email').value,
passwd: document.getElementById('regPassword').value,
}
try {
const response = await fetch('/api/user/registration', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
if (response.ok) {
const data = await response.json();
sessionStorage.setItem("user_id", data.id)
alert('Nutzer erfolgreich hinzugefügt! Ihre Kundennummer: ' + data.id)
window.location.href= '/'
} else {
alert('Fehler bei der Registrierung.')
}
} catch (error) {
console.error('Fehler: ', error)
alert('Fehler beim Senden des Formulars.')
}
})
</script>
<!-- Fußzeiele --> <!-- Fußzeiele -->
<div id="footer"></div> <div id="footer"></div>

View File

@ -41,6 +41,7 @@
<h3>${product.name}</h3> <h3>${product.name}</h3>
<p>Preis: ${product.price}€</p> <p>Preis: ${product.price}€</p>
<p>${product.description}</p> <p>${product.description}</p>
<p>Artikel Nr: ${product.id}</p>
<button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button> <button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button>
`; `;
container.appendChild(card); container.appendChild(card);

View File

@ -43,8 +43,10 @@
<h3>${product.name}</h3> <h3>${product.name}</h3>
<p>Preis: ${product.price}€</p> <p>Preis: ${product.price}€</p>
<p>${product.description}</p> <p>${product.description}</p>
<p>Artikel Nr: ${product.id}</p>
<button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button> <button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button>
`; `;
container.appendChild(card);
}); });
}) })
.catch(err => { .catch(err => {
@ -60,5 +62,8 @@
}); });
</script> </script>
<!-- Fußzeiele -->
<div id="footer"></div>
</body> </body>
</html> </html>

View File

@ -24,9 +24,6 @@
</section> </section>
</main> </main>
<!-- Fußzeile -->
<div id="footer"></div>
</div>
<script> <script>
fetch('/api/products/motorrad') fetch('/api/products/motorrad')
@ -43,6 +40,7 @@
<h3>${product.name}</h3> <h3>${product.name}</h3>
<p>Preis: ${product.price}€</p> <p>Preis: ${product.price}€</p>
<p>${product.description}</p> <p>${product.description}</p>
<p>Artikel Nr: ${product.id}</p>
<button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button> <button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button>
`; `;
container.appendChild(card); container.appendChild(card);
@ -58,5 +56,9 @@
</div>`; </div>`;
}); });
</script> </script>
<!-- Fußzeiele -->
<div id="footer"></div>
</body> </body>
</html> </html>

View File

@ -33,7 +33,7 @@
.then(res => res.json()) .then(res => res.json())
.then(products => { .then(products => {
const container = document.getElementById('products_oldtimer'); const container = document.getElementById('products_oldtimer');
container.innerHTML = ''; container.innerHTML = ''; // sicherheitshalber leeren
products.forEach(product => { products.forEach(product => {
const card = document.createElement('div'); const card = document.createElement('div');
@ -43,6 +43,7 @@
<h3>${product.name}</h3> <h3>${product.name}</h3>
<p>Preis: ${product.price}€</p> <p>Preis: ${product.price}€</p>
<p>${product.description}</p> <p>${product.description}</p>
<p>Artikel Nr: ${product.id}</p>
<button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button> <button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button>
`; `;
container.appendChild(card); container.appendChild(card);

View File

@ -43,6 +43,7 @@
<h3>${product.name}</h3> <h3>${product.name}</h3>
<p>Preis: ${product.price}€</p> <p>Preis: ${product.price}€</p>
<p>${product.description}</p> <p>${product.description}</p>
<p>Artikel Nr: ${product.id}</p>
<button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button> <button class="add-to-cart" data-id="${product.id}">Zum Warenkorb hinzufügen</button>
`; `;
container.appendChild(card); container.appendChild(card);
@ -60,5 +61,6 @@
</div> `; </div> `;
}); });
</script> </script>
</body> </body>
</html> </html>

View File

@ -70,4 +70,8 @@ router.get('/Warenkorb', (req, res) => {
router.get('/bestellformular', (req, res) => { router.get('/bestellformular', (req, res) => {
res.sendFile(path.join(__dirname, '../../../public/bestellformular/bestellformular.html')); res.sendFile(path.join(__dirname, '../../../public/bestellformular/bestellformular.html'));
}) })
router.get('/bestellung', (req, res) => {
res.sendFile(path.join(__dirname, '../../../public/bestellung/bestellung.html'));
})
module.exports = router; module.exports = router;

155
server.js
View File

@ -127,6 +127,161 @@ app.get('/api/products/sportwagen', async (req, res) => {
}); });
}); });
app.post('/api/user/registration', (req, res) => {
// SQL-Query für Nutzerregistration
const {name, lower_name, email, passwd} = req.body;
const sql = "INSERT INTO webshop.user (name, lower_name, email, passwd, passwd_hash_algo) VALUES (?, ?, ?, ?, 'none')"
// Query abschicken
db.query(sql, [name, lower_name, email, passwd], (err, results) => {
if (err) {
console.error('Fehler beim Schreiben in die Datenbank: ', err);
res.status(500).send('Fehler beim Schreiben in die Datenbank');
return;
}
res.status(201).json({message: 'Nutzer erfolgreich hinzugefügt', id: results.insertId})
})
})
app.post('/api/user/login', (req, res) => {
const {email, password} = req.body
const sql = 'SELECT * FROM user WHERE email = ?'
db.query(sql, [email], (err, results) => {
if (err) {
console.error('Fehler beim Abrufen des Nutzers: ', err)
return res.status(500).json({message: 'Serverfehler'})
}
if (results.length === 0) {
return res.status(401).json({message: 'E-Mail nicht gefunden'})
}
const user = results[0]
if (user.passwd !== password) {
return res.status(401).json({message: 'Falsches Passwort'})
}
req.session.userId = user.id;
req.session.email = user.email;
res.json({message: 'Login erfolgreich', id: user.id})
})
})
app.post('/api/bestellung', (req, res) => {
const { user_id, produkte } = req.body;
// produkte erwartet als Array: [{product_id: 1, quantity: 2}, {product_id: 5, quantity: 1}, ...]
if (!user_id || !Array.isArray(produkte) || produkte.length === 0) {
return res.status(400).json({ message: 'Ungültige Anfrage: user_id oder Produkte fehlen.' });
}
// Preise der Produkte abrufen
const productIds = produkte.map(p => p.product_id);
const priceQuery = 'SELECT id, price FROM webshop.product WHERE id IN (?)';
db.query(priceQuery, [productIds], (err, priceResults) => {
if (err) {
console.error('Fehler beim Abrufen der Produktpreise:', err);
return res.status(500).json({ message: 'Serverfehler beim Abrufen der Produktpreise.' });
}
if (priceResults.length !== productIds.length) {
return res.status(400).json({ message: 'Eines oder mehrere Produkte existieren nicht.' });
}
// Total berechnen
let total = 0;
produkte.forEach(p => {
const dbProduct = priceResults.find(pr => pr.id === p.product_id);
if (dbProduct) {
total += dbProduct.price * p.quantity;
}
});
const payment_id = 1; // Zahlungssystem-ID (z.B. 1 = Rechnung, 2 = PayPal, ...)
const sqlOrder = 'INSERT INTO webshop.order_details (user_id, payment_id, total) VALUES (?, ?, ?)';
db.query(sqlOrder, [user_id, payment_id, total], (err1, result1) => {
if (err1) {
console.error('Fehler beim Erstellen der Bestellung:', err1);
return res.status(500).json({ message: 'Fehler beim Erstellen der Bestellung.' });
}
const orderId = result1.insertId;
const values = produkte.map(p => [user_id, p.product_id, p.quantity, orderId]);
const sqlItems = 'INSERT INTO webshop.order_items (user_id, product_id, quantity, order_id) VALUES ?';
db.query(sqlItems, [values], (err2, result2) => {
if (err2) {
console.error('Fehler beim Einfügen der Order-Items:', err2);
return res.status(500).json({ message: 'Fehler beim Hinzufügen der Produkte zur Bestellung.' });
}
res.status(201).json({ message: 'Bestellung erfolgreich!', order_id: orderId, total: total.toFixed(2) });
});
});
});
});
app.post('/api/bestellung/daten', (req, res) => {
const { user_id } = req.body;
const sql = `
SELECT
od.id AS order_id,
od.total AS order_total,
oi.product_id,
oi.quantity,
p.name AS product_name,
p.price AS product_price
FROM
webshop.order_details od
INNER JOIN
webshop.order_items oi ON od.id = oi.order_id
INNER JOIN
webshop.product p ON oi.product_id = p.id
WHERE
od.user_id = ?
ORDER BY
od.id DESC
`;
db.query(sql, [user_id], (err, results) => {
if (err) {
console.error('Fehler beim Abrufen der Bestellungen: ', err);
return res.status(500).json({ message: 'Fehler beim Abrufen der Bestellungen' });
}
if (results.length === 0) {
return res.status(404).json({ message: 'Keine Bestellungen gefunden.' });
}
res.json(results);
});
});
app.get('/api/pruefe-artikel', (req, res) => {
const artikelnummer = req.query.nummer;
if (!artikelnummer) {
return res.status(400).json({ error: 'Keine Artikelnummer angegeben.' });
}
const query = 'SELECT id FROM product WHERE id = ?';
db.query(query, [artikelnummer], (err, results) => {
if (err) {
console.error('Fehler bei der Artikelsuche:', err);
return res.status(500).json({ error: 'Serverfehler bei der Artikelsuche.' });
}
const verfuegbar = results.length > 0;
res.json({ verfuegbar });
});
});
const getIndexRoute = require('./scripts/routes/other/route-index'); const getIndexRoute = require('./scripts/routes/other/route-index');
app.use('/', getIndexRoute); app.use('/', getIndexRoute);

View File

@ -9,7 +9,7 @@ body {
} }
.wrapper { .wrapper {
flex: 1; /* Der Hauptinhalt (Formular) nimmt den verfügbaren Platz ein */ flex: 1; /* Der Hauptinhalt nimmt den verfügbaren Platz ein */
} }
.form-container { .form-container {
@ -43,20 +43,22 @@ textarea {
box-sizing: border-box; box-sizing: border-box;
} }
input[type="submit"] { /* NEU: Styling für den Absende-Link */
.button-submit {
display: inline-block;
margin-top: 20px; margin-top: 20px;
background-color: #ff6600; background-color: #ff6600;
color: white; color: white;
border: none; text-decoration: none;
padding: 12px; padding: 12px;
border-radius: 5px; border-radius: 5px;
font-size: 16px; font-size: 16px;
cursor: pointer; cursor: pointer;
width: 100%; width: 100%;
text-align: center;
box-sizing: border-box; /* Damit Breite + Padding sauber passen */
} }
input[type="submit"]:hover { .button-submit:hover {
background-color: #ff5500; /* Ein leicht dunklerer Farbton beim Hover */ background-color: #ff6600;
} }

View File

@ -0,0 +1,49 @@
/* Allgemeine Layout-Stile */
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
padding: 20px;
margin: 0;
display: flex;
flex-direction: column;
min-height: 100vh;
}
/* Container für die Bestellinformationen */
#bestellung {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
margin-top: 20px;
}
/* Titel */
h2 {
text-align: center;
margin-bottom: 30px;
margin-top: 20px;
}
/* Karte für Bestellinformationen */
.bestell-info-card {
background-color: #fafafa;
padding: 15px;
border-radius: 8px;
margin-bottom: 15px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
/* Bestellinformationen formatieren */
.bestell-info-card p {
font-size: 16px;
margin: 10px 0;
}
/* Stile für die Label und Platzhalter */
.bestell-info-card span {
font-weight: bold;
color: #333;
}