-
Notifications
You must be signed in to change notification settings - Fork 2
/
shop.html
522 lines (470 loc) · 23.6 KB
/
shop.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!--
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
-->
<title>Preisrechner</title>
<style>
html {
font-family: sans-serif;
}
.lastResult {
color: white;
padding: 3px;
}
tr:nth-child(odd){
background:#eee;
}
tr:nth-child(even){
background:#fcfcfc;
}
tr.inCart:nth-child(odd) {
background:#76d576;
}
tr.inCart:nth-child(even) {
background:#b2f4b2;
}
h2 {
padding-top:2em;
}
div#categoriesBar > h2 {
padding-top: 0em;;
}
td>p{
margin: auto;
}
td {
padding: 1em 0.2em;
}
.product_location, .product_details {
font-size: 70%;
}
.cartTotal {
font-weight: bold; font-size: 130%; background: white;
}
div#loading{
display:block; line-height:50em; background-color:lightgray;
}
#search{
line-height:2em; padding:.5em; margin-bottom:1em;
}
div#categoriesBar {
position:fixed;
width:20em;
z-index: 1;
top: 0;
left:0;
overflow-x: hidden;
padding-top:1em;
padding-left:1em;
}
div#main {
margin-left: 25em; /* leave space for category sidebar */
max-width: 60em;
}
a {
text-decoration:none;
color:navy;
}
</style>
</head>
<body>
<div id="main">
<h1>Preisrechner</h1>
<p>Lege Produkte in den Warenkorb, um den Preis zu berechnen. Neu laden, rückgängig, usw. löscht den Warenkorb!</p>
<p style="font-size:80%; color:gray;">Hinweis: Wir sind kein Onlineshop. Nicht alle Artikel sind vorrätig oder bestellbar. Diese Seite ist lediglich eine Rechenhilfe um vor Ort im Lab auszurechnen wieviel du zahlen musst.</p>
<div id="loading"> Produkte werden geladen. Bitte warten.... </div>
<h2 id="productsAnchor">Produkte</h2>
<input id="search" type="search" placeholder="Suchbegriff oder Artikelnummer" size="40"> <input type="button" id="clearSearch" value="❌ Suche leeren">
<table id="products">
</table>
<h2 id="cartAnchor">Warenkorb</h2>
<table id="cart">
<tr><td>ist leer</td></tr>
</table>
<p><a href="https://fablab.fau.de/impressum"> Impressum </a> | <a href="https://github.com/fau-fablab/oerp-pricelist/blob/master/shop.html">Source code on GitHub</a></p>
<p style="margin-bottom:99%"></p>
</div>
<div id="categoriesBar">
<input type="button" onClick="javascript:document.getElementById('productsAnchor').scrollIntoView()" value="🔎 Produkte">
<input type="button" onClick="javascript:document.getElementById('cartAnchor').scrollIntoView()" value="🛒 Warenkorb">
<h2>Kategorien</h2>
<ul id="categories">
</ul>
</div>
<script>
async function loadJson(url) {
let obj = await (await fetch(url)).json();
return obj;
}
// =========
// Global (state) variables
// =========
var products = { "42": {"price": 412.12, "name": "Produkte werden geladen. Bitte warten...", "description": "Infotext", "unit": "g", "category": ["Bitte", "warten", "..."], "location": "Schublade XY"},
"43": {"price": 0.1337, "name": "Produkte werden geladen. Bitte warten...", "description": "Infotext", "unit": "kg", "category": ["Bitte warten", ". . ."] , "location": "Schublade XY"},
"productId": {"price": 0.1337, "name": "name", "description": "Infotext", "unit": "Stück", "category": ["top", "second", "third"], "location": "Schublade XY"}
};
var cart = []; // [{"id": productKey, "qty": quantity}, ...]
var searchString = "";
var selectedCategory = [];
var OERPProducts = {}; // not needed globally, but helpful for debugging
// GUI-specific variables
var timerWhileUserIsTyping = null;
// =========
// Functions
// =========
// Load products from oerp-pricelist JSON output, convert that to the above "products" format
function loadOERPProducts() {
// dummy content:
// d = {"0834": {"_price_str": "0.15\u202f\u20ac", "code": "0834", "lst_price": 0.15, "_supplier_name": "MEW", "uom_id": 1, "_location_str": "Elektrowerkstatt / Regal / Schublade S6 (S6)", "default_code": "0834", "property_stock_location": false, "id": 693, "description": false, "sale_ok": true, "categ_id": [195, "Alle Produkte / Mechanik / Beilagscheiben"], "_supplier_name_code": "MEW: 82.230.130", "_code_str": "0834", "_categ_list": ["Mechanik", "Beilagscheiben"], "manufacturer_pname": false, "_uom_str": "St\u00fcck", "_categ_str": "Mechanik / Beilagscheiben", "active": true, "manufacturer_pref": false, "manufacturer": false, "_supplier_all_infos": "MEW: 82.230.130", "name": "Karosseriescheibe\u00a0DIN\u00a09021\u00a0\u2010 13\u00a0\u2010\u00a0St. ", "_supplierinfo": {"pricelist_ids": [563], "name": [49, "MEW"], "product_uom": [1, "St\u00fcck"], "sequence": 1, "product_name": false, "company_id": [1, "FAU FabLab"], "qty": 0.0, "delay": 7, "min_qty": 0.0, "product_code": "82.230.130", "id": 578, "product_id": [693, "False"]}, "_name_and_description": "Karosseriescheibe\u00a0DIN\u00a09021\u00a0\u2010 13\u00a0\u2010\u00a0St. ", "_supplier_code": "82.230.130", "seller_ids": [578]}, "0836": {"_price_str": "0.18\u202f\u20ac", "code": "0836", "lst_price": 0.18, "_supplier_name": "Amazon (Sammellieferant f\u00fcr Auslagen/Vorkassebestellungen)", "uom_id": 1, "_location_str": "Elektrowerkstatt / Regal / Schublade S3 (S3)", "default_code": "0836", "property_stock_location": [121, "tats\u00e4chliche Lagerorte / FAU FabLab / Elektrowerkstatt / Regal / Schublade S3"], "id": 3657, "description": false, "sale_ok": true, "categ_id": [32, "Alle Produkte / Elektronik / Geh\u00e4usebau"], "_supplier_name_code": "Amazon (Sammellieferant f\u00fcr Auslagen/Vorkassebestellungen): ", "_code_str": "0836", "_categ_list": ["Elektronik", "Geh\u00e4usebau"], "manufacturer_pname": false, "_uom_str": "St\u00fcck", "_categ_str": "Elektronik / Geh\u00e4usebau", "active": true, "manufacturer_pref": false, "manufacturer": false, "_supplier_all_infos": "Amazon (Sammellieferant f\u00fcr Auslagen/Vorkassebestellungen): ", "name": "Antirutsch Pads selbstklebend \u00d8 10 mm", "_supplierinfo": {"pricelist_ids": [1889], "name": [175, "Amazon (Sammellieferant f\u00fcr Auslagen/Vorkassebestellungen)"], "product_uom": [1, "St\u00fcck"], "sequence": 1, "product_name": "108 x Antirutsch Pads aus EPDM/Zellkautschuk | rund | \u00d8 10 mm | Schwarz | selbstklebend | Rutschhemmende Pads inTop-Qualit\u00e4t", "company_id": [1, "FAU FabLab"], "qty": 108.0, "delay": 1, "min_qty": 108.0, "product_code": false, "id": 2293, "product_id": [2495, "False"]}, "_name_and_description": "Antirutsch Pads selbstklebend \u00d8 10 mm", "_supplier_code": "", "seller_ids": [2293]}};
const url ="price_list-Alle_Produkte.html.json";
d = loadJson(url);
d.then(function(d) {
OERPProducts = d;
products = {};
for (const prodKey in d) {
const oerpProduct = d[prodKey];
// console.log(oerpProduct);
product = {"price": oerpProduct.lst_price, "name": oerpProduct.name, "description": (oerpProduct.description || ""), "unit": oerpProduct._uom_str, "category": oerpProduct._categ_list, "location": oerpProduct._location_str};
if (product.location == "FAU FabLab" || product.location == "kein Ort eingetragen") {
product.location = "";
}
if (oerpProduct._supplier_all_infos != "") {
product.description += "\n Lieferant: " + oerpProduct._supplier_all_infos;
}
products[oerpProduct.code] = product;
}
updateProducts();
updateCategories();
document.getElementById("loading").remove();
}
);
}
function formatPrice(price) {
return price.toFixed(2) + " €"
}
// add to cart
function addToCart(productKey, quantity) {
cart.push({"id": productKey, "qty": quantity});
cartChanged();
}
// how many of a given product are in the cart?
function getCartQty(productKey) {
qty = 0;
for (const entryId in cart) {
entry = cart[entryId];
if (entry.id == productKey) {
qty += entry.qty;
}
}
return qty;
}
function clearElement(el) {
// purge all contents of DOM element
while (el.firstChild){
el.removeChild(el.firstChild);
}
}
function cartChanged() {
updateCart();
// also update the products list because it highlights which products are in the cart.
// Do not limit the maximum number of products, because the user could have clicked on "show all" before.
updateProducts(Infinity);
}
// regenerate the cart view
function updateCart() {
const cartTable = document.getElementById("cart");
clearElement(cartTable);
// create the new cart table
const cartTBody = cartTable.createTBody();
total = 0;
for (const entryId in cart) {
entry = cart[entryId];
// console.log(`c ${entry}`);
// add one product row
const row = cartTBody.insertRow();
const product = products[entry.id];
row.insertCell().textContent = entry.qty;
row.insertCell().textContent = product.unit;
row.insertCell().textContent = product.name;
row.insertCell().textContent = " x ";
row.insertCell().textContent = formatPrice(product.price);
linePrice = entry.qty * product.price;
row.insertCell().textContent = " = " + formatPrice(linePrice);
removeBtn = document.createElement("input");
removeBtn.type="submit";
removeBtn.value="❌";
removeBtn.onclick=removeThis;
function removeThis(event) {
// remove the current cart element
cart.splice(entryId, 1);
cartChanged();
event.preventDefault();
}
row.insertCell().append(removeBtn);
total += linePrice;
}
totalCell = cartTBody.insertRow().insertCell();
totalCell.textContent="Gesamt " + formatPrice(total);
totalCell.className = "cartTotal";
totalCell.colSpan = "4";
}
// Sorting order of products
function productToSortString(productKey) {
product = products[productKey];
if (product.name.startsWith("Spende")) {
return "0 Spende immer zuerst";
}
if (product.name.startsWith("Kommentar")) {
return "1 Kommentar immer als zweites";
}
return product.category.join(" ") + " 000 " + product.name + productKey;
}
// compare() function for products
function productSortOrder(keyA, keyB) {
if (productToSortString(keyA) > productToSortString(keyB)) {
return 1;
} else {
return -1;
};
}
// Does the given product match the search string?
function productMatchesSearch(productKey, searchString) {
searchString = searchString.trim().toLowerCase();
if (searchString == "") {
// search not active
return true;
}
product = products[productKey];
// searching within category
// note: searchString is already lowercased
if (searchString.startsWith("kategorie: \"")) {
searchParts = searchString.split("\"");
chosenCategory = searchParts[1];
// strip away 'Kategorie: "..."' from search string
if (searchParts.length >= 2) {
searchString = searchParts[2];
}
if (!product.category.join(" / ").toLowerCase().startsWith(chosenCategory)) {
return false;
}
}
for (searchWord of searchString.split(" ")) {
if (searchWord == "") {
continue
}
searchWord = searchWord.replace("\"", "");
if (!(product.category.join(" ").toLowerCase().includes(searchWord) || product.name.toLowerCase().includes(searchWord) || Number(productKey) == Number(searchString))) {
return false;
}
}
return true;
}
// regenerate products view
// parameter: limitNumber: only show the first N results to increase speed
function updateProducts(limitNumber = 100) {
console.log(searchString);
const productsTable = document.getElementById("products");
clearElement(productsTable);
const productsTBody = productsTable.createTBody();
let sortedProductsList = Object.keys(products);
sortedProductsList.sort(productSortOrder);
let productsShown = 0;
for (const productKey of sortedProductsList) {
if (!productMatchesSearch(productKey, searchString)) {
continue;
}
productsShown++;
if (productsShown > limitNumber) {
const notAllShown = productsTBody.insertRow().insertCell();
notAllShown.textContent = "Es werden nur die ersten 50 Ergebnisse angezeigt."
notAllShown.style = "background:white; font-weight:bold;";
const showAll = document.createElement("input");
showAll.type="button";
showAll.value="mehr anzeigen";
showAll.onclick = function(ev) {updateProducts(Infinity);}
notAllShown.append(showAll);
break;
}
const product = products[productKey];
// console.log(`${productKey}: ${product}`);
// add one product row
const row = productsTBody.insertRow();
// product infos
row.insertCell().textContent = product.category.join(" / ");
row.insertCell().textContent = productKey;
const details = row.insertCell();
const detailsName = document.createElement("p");
detailsName.textContent = product.name;
details.append(detailsName);
const detailsDescription = document.createElement("p");
detailsDescription.textContent = product.description;
detailsDescription.className = "product_details";
details.append(detailsDescription);
const detailsLocation = document.createElement("p");
detailsLocation.className = "product_location";
detailsLocation.textContent = product.location;
details.append(detailsLocation);
const price = row.insertCell();
price.textContent = formatPrice(product.price) + " pro " + product.unit;
const addToCartCell = row.insertCell();
// "Add to cart"
const addToCartBtn = document.createElement("input");
addToCartBtn.type="submit";
addToCartBtn.value="🛒";
// x pieces in cart
inCartCell = row.insertCell();
if (getCartQty(productKey) > 0) {
row.className = "inCart";
inCartCell.textContent = getCartQty(productKey) + " " + product.unit + " im ";
linkToCart = document.createElement("a");
linkToCart.href="#cartAnchor";
linkToCart.textContent="Warenkorb"
inCartCell.append(linkToCart);
}
function addThisToCart(event) {
let qty = null;
while (true) {
qty = window.prompt("Menge in " + product.unit, "1");
if (qty == null || qty == 0) {
return;
}
qty = parseFloat(qty.replace(",","."));
if (isNaN(qty)) {
continue;
}
addToCart(productKey, qty);
break;
}
// don't actually submit the form
event.preventDefault();
}
addToCartBtn.onclick = addThisToCart;
addToCartBtn.onkeydown = addThisToCart;
addToCartCell.append(addToCartBtn);
if (product.price == 0) {
price.textContent = "gegen Spende";
clearElement(addToCartCell);
clearElement(inCartCell);
}
}
}
// show the list of categories
function updateCategories() {
// build the list of categories that are currently shown
let categories = {}; // {"category sort string": ["category", "array", "from", "top", "to", "bottom"], ...}
for (p of Object.values(products)) {
// go through the category path of every product
for (let i = 0; i < p.category.length; i++) {
category = p.category.slice(0, i+1);
// only show a category if it is a top category or if it matches the currently selected category
let showThisCategory = true;
if (i == 0) {
// always show root categories.
} else if (i > selectedCategory.length) {
// do not show more than 1 level below the selected level
showThisCategory = false;
}
if (showThisCategory) {
categories[category.join(" Z ") + " 0"] = category;
}
if (selectedCategory.length >= i + 1 && p.category[i] != selectedCategory[i]) {
// this category does not match the selected path
break; // do not go further down
}
}
}
const categoriesList = document.getElementById("categories");
clearElement(categoriesList);
categories["0"] = [];
for (const [catString, catAsList] of Object.entries(categories).sort()) {
function clickedOnThisCategory(event) {
// Event handler: User clicked on the category.
// Rebuild the tree
selectedCategory = catAsList;
updateCategories();
// and update the product search
let searchBarString = "Kategorie: \"" + catAsList.join(" / ") + "\" ";
if (selectedCategory.length == 0) {
searchBarString = "";
}
document.getElementById("search").value = searchBarString;
updateSearch();
document.getElementById("productsAnchor").scrollIntoView();
}
const listItem = document.createElement("li");
categoriesList.append(listItem);
const listItemLink = document.createElement("a");
listItem.append(listItemLink);
listItemLink.href="javascript:;";
if (catAsList.length == 0) {
listItemLink.textContent = "Alle Produkte";
} else {
listItemLink.textContent = catAsList[catAsList.length - 1];
}
listItem.style="margin-left:" + 2 * (catAsList.length - 1) + "em;" // TODO: this is ugly, better create a nested list
listItemLink.onclick = clickedOnThisCategory;
}
// document.getElementById("search").value = cat.join(" ");
}
// search box changed
// call updateSearch() some time after the user has stopped typing
function searchBoxChanged(event) {
if (timerWhileUserIsTyping != null) {
// cancel previous timers
clearTimeout(timerWhileUserIsTyping);
}
timerWhileUserIsTyping = setTimeout(updateSearch, 300);
}
// update search immediately
function updateSearch(event=null) {
newSearchString = document.getElementById("search").value;
document.getElementById("clearSearch").disabled = (newSearchString == "");
newSearchString = newSearchString.trim();
if (searchString != newSearchString) {
searchString = newSearchString;
updateProducts();
}
}
function clearSearch(event = null) {
document.getElementById("search").value = "";
selectedCategory=[];
updateSearch();
updateCategories();
}
function startup() {
document.getElementById("search").value = "";
document.getElementById("search").oninput = searchBoxChanged;
document.getElementById("clearSearch").onclick = clearSearch;
updateSearch();
// load the list of dummy products so one can develop even if the JSON file is not found
updateProducts();
updateCategories();
// load the real products
loadOERPProducts();
}
startup();
</script>
</body>
</html>