-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
342 lines (287 loc) · 10.4 KB
/
script.js
File metadata and controls
342 lines (287 loc) · 10.4 KB
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
document.addEventListener("DOMContentLoaded", initializePage);
const HIDDEN_CATEGORIES_DEFAULT = ["Fleisch & Wurst", "Drogerie", "Tiernahrung", "Fisch & Meeresfrüchte"];
async function initializePage() {
const dropdown = document.getElementById("file-dropdown");
const copyProductsButton = document.getElementById("copy-products");
try {
const files = await fetchFolderStructure();
files.reverse(); // Neueste Dateien zuerst
populateDropdown(dropdown, files);
dropdown.addEventListener("change", () => {
const selectedFile = dropdown.value;
if (selectedFile) {
fetchOffers(selectedFile);
}
});
if (files.length > 0) {
dropdown.value = files[0];
await fetchOffers(files[0]);
}
copyProductsButton.addEventListener("click", copyVisibleProducts);
attachSearchFunctionality();
setupToggleImages();
} catch (error) {
console.error("Error initializing page:", error);
}
}
async function fetchFolderStructure() {
try {
const response = await fetch("data/folder-structure.json");
if (!response.ok) {
throw new Error(`Failed to fetch folder structure: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error fetching folder structure:", error);
alert("Fehler: Die Ordnerstruktur konnte nicht geladen werden.");
return [];
}
}
function populateDropdown(dropdown, files) {
dropdown.innerHTML = "";
files.forEach((file) => {
const option = document.createElement("option");
option.value = file;
// "2026/KW11/2026-03-09.json" → "KW11 — 09.03.2026"
const match = file.match(/(\d{4})\/(KW\d+)\/(\d{4})-(\d{2})-(\d{2})\.json/);
if (match) {
option.textContent = `${match[2]} — ${match[5]}.${match[4]}.${match[1]}`;
} else {
option.textContent = file;
}
dropdown.appendChild(option);
});
}
async function fetchOffers(filePath) {
const fullPath = `data/${filePath}`;
const tableBody = document.getElementById("offer-table");
const offerInfo = document.getElementById("offer-info");
try {
const response = await fetch(fullPath);
if (!response.ok) {
throw new Error(`Failed to fetch file: ${response.status}`);
}
const data = await response.json();
const { validFrom, validTill, totalCount, offers } = data;
offerInfo.textContent = `${totalCount} Angebote vom ${formatDate(validFrom)} bis ${formatDate(validTill)}`;
tableBody.innerHTML = "";
const fragment = document.createDocumentFragment();
offers.forEach((offer) => {
const row = document.createElement("tr");
row.dataset.category = offer.category.name;
const cells = [
offer.id,
offer.title,
offer.category.name,
`${offer.price.value} €`,
offer.description,
];
cells.forEach((text) => {
const td = document.createElement("td");
td.textContent = text;
row.appendChild(td);
});
// Image cell with data attributes
const imgCell = document.createElement("td");
imgCell.className = "image-cell hidden";
imgCell.dataset.imageUrl = offer.images.app || "";
imgCell.dataset.originalUrl = offer.images.original || "";
row.appendChild(imgCell);
fragment.appendChild(row);
});
tableBody.appendChild(fragment);
populateCategoryCheckboxes(offers);
} catch (error) {
console.error("Error fetching offers:", error);
offerInfo.textContent = "Fehler beim Laden der Angebote.";
tableBody.innerHTML = "";
}
}
function formatDate(dateStr) {
// "2026-03-09" → "09.03.2026"
const parts = dateStr.split("-");
if (parts.length === 3) return `${parts[2]}.${parts[1]}.${parts[0]}`;
return dateStr;
}
function populateCategoryCheckboxes(offers) {
const activeContainer = document.getElementById("category-filters");
const hiddenContainer = document.getElementById("hidden-category-filters");
if (!activeContainer) return;
activeContainer.innerHTML = "";
if (hiddenContainer) hiddenContainer.innerHTML = "";
const categoryCounts = offers.reduce((counts, offer) => {
counts[offer.category.name] = (counts[offer.category.name] || 0) + 1;
return counts;
}, {});
Object.entries(categoryCounts).forEach(([category, count]) => {
const label = document.createElement("label");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = category;
const isVisible = !HIDDEN_CATEGORIES_DEFAULT.includes(category);
checkbox.checked = isVisible;
if (isVisible) label.classList.add("checked");
checkbox.addEventListener("change", () => {
label.classList.toggle("checked", checkbox.checked);
distributeCategoryLabels();
applyCategoryFilter();
});
label.appendChild(checkbox);
label.appendChild(document.createTextNode(` ${category} (${count})`));
if (isVisible) {
activeContainer.appendChild(label);
} else if (hiddenContainer) {
hiddenContainer.appendChild(label);
}
});
distributeCategoryLabels();
applyCategoryFilter();
}
function distributeCategoryLabels() {
const activeContainer = document.getElementById("category-filters");
const hiddenContainer = document.getElementById("hidden-category-filters");
if (!activeContainer || !hiddenContainer) return;
const allLabels = [...document.querySelectorAll("#category-filters label, #hidden-category-filters label")];
allLabels.forEach((label) => {
const cb = label.querySelector("input[type='checkbox']");
if (!cb) return;
const target = cb.checked ? activeContainer : hiddenContainer;
target.appendChild(label);
});
hiddenContainer.style.display = hiddenContainer.querySelectorAll("label").length > 0 ? "" : "none";
}
function applyCategoryFilter() {
const checkboxes = document.querySelectorAll("#category-filters input[type='checkbox'], #hidden-category-filters input[type='checkbox']");
const visibleCategories = [];
checkboxes.forEach((cb) => {
if (cb.checked) visibleCategories.push(cb.value);
});
const rows = document.querySelectorAll("#offer-table tr");
rows.forEach((row) => {
if (visibleCategories.includes(row.dataset.category)) {
row.classList.remove("hidden");
} else {
row.classList.add("hidden");
}
});
}
function attachSearchFunctionality() {
const searchInput = document.getElementById("search-input");
if (searchInput) {
searchInput.addEventListener("input", () => {
const searchTerm = searchInput.value.toLowerCase();
const rows = document.querySelectorAll("#offer-table tr");
if (!searchTerm) {
// Reset to category filter state
applyCategoryFilter();
return;
}
rows.forEach((row) => {
const cells = Array.from(row.querySelectorAll("td"));
const matches = cells.some((cell) =>
cell.textContent.toLowerCase().includes(searchTerm)
);
if (matches) {
row.classList.remove("hidden");
} else {
row.classList.add("hidden");
}
});
});
}
}
function copyVisibleProducts() {
const rows = document.querySelectorAll("#offer-table tr:not(.hidden)");
const products = [];
rows.forEach((row) => {
const cells = row.querySelectorAll("td");
if (cells.length) {
const product = {
id: cells[0].textContent.trim(),
title: cells[1].textContent.trim(),
category: cells[2].textContent.trim(),
price: cells[3].textContent.trim(),
description: cells[4].textContent.trim(),
};
products.push(product);
}
});
const jsonString = JSON.stringify(products, null, 2);
// Add LLM-friendly instructions and formatting
const promptString = `
[LLM PROMPT START]
Below is a JSON list of filtered products. Use this data to answer questions, generate summaries, or provide insights based on the product information.
\`\`\`json
${jsonString}
\`\`\`
Please follow the steps below in your response:
1. Reference product data by 'id' or 'title'.
2. If you need to provide reasoning, consider the context of 'category', 'price', and 'description'.
3. Keep answers factual and based on the provided data.
[LLM PROMPT END]
`;
navigator.clipboard
.writeText(promptString)
.then(() => {
alert("Sichtbare Produkte wurden als strukturierte LLM-Prompt kopiert!");
})
.catch((err) => {
console.error("Fehler beim Kopieren der Daten:", err);
});
}
function setupToggleImages() {
const toggleImagesButton = document.getElementById("toggle-images");
const imageHeader = document.getElementById("image-column-header");
if (!toggleImagesButton || !imageHeader) return;
toggleImagesButton.addEventListener("click", () => {
const imageCells = document.querySelectorAll(".image-cell");
const isHidden = imageHeader.classList.contains("hidden");
imageCells.forEach((cell) => {
if (isHidden) {
// Show images
const imgUrl = cell.getAttribute("data-image-url");
if (imgUrl && !cell.querySelector("img")) {
const img = document.createElement("img");
img.src = imgUrl;
img.alt = "Produktbild";
img.style.cursor = "zoom-in";
cell.appendChild(img);
}
cell.classList.remove("hidden");
} else {
// Hide images
if (cell.querySelector("img")) {
cell.querySelector("img").remove();
}
cell.classList.add("hidden");
}
});
imageHeader.classList.toggle("hidden", !isHidden);
toggleImagesButton.textContent = isHidden
? "Bilder ausblenden"
: "Bilder laden";
// Attach hover preview if images are shown
if (isHidden) attachImageHoverPreview();
});
}
function attachImageHoverPreview() {
const table = document.getElementById("offer-table");
const imagePreview = document.getElementById("image-preview");
if (!table || !imagePreview) return;
table.addEventListener("mouseover", (event) => {
const imgCell = event.target.closest(".image-cell img");
if (!imgCell) return;
const originalUrl =
imgCell.closest(".image-cell").dataset.originalUrl || "";
if (originalUrl) {
imagePreview.innerHTML = `<img src="${originalUrl}" alt="Vorschau" loading="lazy">`;
imagePreview.classList.add("visible");
}
});
table.addEventListener("mouseout", (event) => {
if (event.target.closest(".image-cell img")) {
imagePreview.innerHTML = "";
imagePreview.classList.remove("visible");
}
});
}