-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
549 lines (486 loc) · 18.4 KB
/
index.html
File metadata and controls
549 lines (486 loc) · 18.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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Scanner für Speditionspakete mit Barcode-Verifizierung">
<meta name="theme-color" content="#93c01f">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-title" content="SpedScan">
<title>Speditions Scanner</title>
<link rel="manifest" href="./manifest.json">
<link rel="icon" type="image/png" sizes="192x192" href="./icons/icon-192x192.png">
<link rel="apple-touch-icon" href="./icons/icon-192x192.png">
<style>
body {
background-color: #f5f5f7;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
max-width: 960px;
margin: 0 auto;
padding: 20px;
}
h1 {
text-align: center;
margin-bottom: 20px;
}
.error {
background: #fee;
color: #900;
padding: 10px;
border-radius: 8px;
text-align: center;
margin-bottom: 10px;
}
label {
font-weight: bold;
display: block;
margin: 10px 0 5px;
}
input[type=file],
.scan-input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 8px;
font-size: 14px;
}
.scan-status {
text-align: center;
margin-top: 15px;
font-size: 14px;
}
.scan-status .accent {
color: #2a7a1f;
font-weight: bold;
}
.table-container {
background: white;
border-radius: 8px;
margin-top: 20px;
overflow-x: auto;
border: 1px solid #ccc;
box-shadow: 0 2px 8px rgba(0, 0, 0, .08);
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 10px;
border-bottom: 1px solid #ccc;
text-align: left;
}
th {
background: #f0f0f0;
}
tr.matched {
background: #d4f7d4;
}
.no-data {
text-align: center;
padding: 20px;
}
.status-panel {
background: #f1f3f5;
border: 1px solid #d2d2d7;
border-radius: 12px;
padding: 16px;
margin-top: 12px;
}
.file-input::file-selector-button {
background-color: #93c01f;
color: #fff;
border: none;
padding: 8px 16px;
border-radius: 9999px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
margin-right: 12px;
}
.file-input::file-selector-button:hover {
filter: brightness(0.95);
}
</style>
</head>
<body>
<div id="root" class="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/papaparse@latest/papaparse.min.js"></script>
<script>
const { createRoot } = ReactDOM;
const root = createRoot(document.getElementById('root'));
// Web Audio API für bessere Android-Kompatibilität
// Web Audio API für bessere Android-Kompatibilität
let audioContext = null;
let audioBuffers = {};
let audioEnabled = false;
let useFallbackAudio = false;
let fallbackSounds = {};
const soundFiles = {
positive: 'sounds/positive.mp3',
negative: 'sounds/negative.mp3',
confirm: 'sounds/confirm.mp3'
};
// Initialisiere AudioContext (muss durch User-Interaktion ausgelöst werden)
async function initAudio() {
if (audioEnabled) return true;
try {
// Versuch 1: Web Audio API
audioContext = new (window.AudioContext || window.webkitAudioContext)();
if (audioContext.state === 'suspended') {
await audioContext.resume();
}
const loadPromises = Object.entries(soundFiles).map(async ([name, url]) => {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
audioBuffers[name] = audioBuffer;
return true;
});
await Promise.all(loadPromises);
audioEnabled = true;
useFallbackAudio = false;
console.log('Web Audio API initialized successfully');
return true;
} catch (error) {
console.warn('Web Audio API initialization failed, falling back to HTML5 Audio:', error);
// Versuch 2: Fallback auf HTML5 Audio (für file:// Protokoll oder wenn fetch fehlschlägt)
try {
const warmupPromises = Object.entries(soundFiles).map(async ([name, url]) => {
const audio = new Audio(url);
audio.preload = 'auto';
audio.volume = 1.0;
fallbackSounds[name] = audio;
// Warmup/Unlock: Kurz anspielen während der User-Interaktion
try {
audio.muted = true;
await audio.play();
audio.pause();
audio.currentTime = 0;
audio.muted = false;
} catch (e) {
console.warn('Audio warmup failed for', name, e);
}
return true;
});
await Promise.all(warmupPromises);
audioEnabled = true;
useFallbackAudio = true;
console.log('HTML5 Audio fallback initialized successfully');
return true;
} catch (fallbackError) {
console.error('HTML5 Audio fallback failed:', fallbackError);
return false;
}
}
}
// Audio abspielen
function playSound(name) {
if (!audioEnabled) return;
if (useFallbackAudio) {
// Fallback: HTML5 Audio
const sound = fallbackSounds[name];
if (sound) {
try {
sound.currentTime = 0;
sound.play().catch(e => console.warn('HTML5 Audio play error:', e));
} catch (e) {
console.warn('HTML5 Audio error:', e);
}
}
} else {
// Web Audio API
if (!audioContext || !audioBuffers[name]) return;
try {
const source = audioContext.createBufferSource();
source.buffer = audioBuffers[name];
const gainNode = audioContext.createGain();
gainNode.gain.value = 1.0;
source.connect(gainNode);
gainNode.connect(audioContext.destination);
source.start(0);
} catch (error) {
console.error(`Web Audio API play error for ${name}:`, error);
}
}
}
function toStringSafe(v) {
if (v === null || v === undefined) return '';
if (typeof v === 'number') return String(Math.trunc(v));
return String(v).trim();
}
function normalizePackageNumber(packageNumber, fileName) {
const pkgStr = toStringSafe(packageNumber);
if (!fileName) return pkgStr;
const isGeis = fileName.toLowerCase().includes('geis');
if (isGeis && pkgStr.length > 3) {
return pkgStr.slice(0, -3);
}
return pkgStr;
}
function App() {
const [data, setData] = React.useState([]);
const [currentScan, setCurrentScan] = React.useState(null);
const [scanMode, setScanMode] = React.useState('package');
const [matchedRows, setMatchedRows] = React.useState(new Set());
const [error, setError] = React.useState(null);
const [scanInput, setScanInput] = React.useState('');
const [uploadedFileName, setUploadedFileName] = React.useState('');
const [audioReady, setAudioReady] = React.useState(false);
const inputRef = React.useRef(null);
// Auto-unlock Audio bei erster User-Interaktion
React.useEffect(() => {
const tryUnlockAudio = async () => {
if (audioEnabled) return; // Bereits aktiviert
const success = await initAudio();
if (success) {
setAudioReady(true);
console.log('Audio auto-unlocked');
}
};
// Event-Listener für verschiedene Interaktionen
const events = ['click', 'touchstart', 'keydown'];
events.forEach(event => {
document.addEventListener(event, tryUnlockAudio, { once: true });
});
// Cleanup
return () => {
events.forEach(event => {
document.removeEventListener(event, tryUnlockAudio);
});
};
}, []);
const handleFileUpload = (event) => {
const file = event.target.files[0];
if (file) {
setUploadedFileName(file.name);
Papa.parse(file, {
header: true,
skipEmptyLines: true,
transformHeader: (header) => header.trim().replace(/^"|"$/g, ''),
transform: (value) => (value ?? '').toString().trim().replace(/^"|"$/g, ''),
complete: (results) => {
const filteredData = results.data.filter(row => row['OrderItem.orderItemName'] !== 'Versandkosten');
setData(filteredData);
},
error: (err) => {
setError('Fehler beim Parsen der CSV-Datei: ' + err.message);
},
});
}
};
const handleScanInput = (e) => {
if (e.key === 'Enter' && scanInput) {
handleScan(scanInput.trim());
setScanInput('');
} else {
setScanInput(e.target.value);
}
};
const handleScan = (scannedValue) => {
setError(null);
const code = toStringSafe(scannedValue);
const normalizedScannedCode = normalizePackageNumber(code, uploadedFileName);
if (scanMode === 'package') {
const groupIndexes = data
.map((row, idx) => ({ idx, row }))
.filter(({ row }) => {
const csvPackageNumber = toStringSafe(row['ShippingPackages.packageNumber']);
return csvPackageNumber === normalizedScannedCode;
})
.map(({ idx }) => idx);
if (groupIndexes.length === 0) {
playSound('negative');
setError('Paketnummer nicht gefunden!');
setCurrentScan(null);
setScanMode('package');
} else {
const items = groupIndexes.map(i => {
const r = data[i];
const qty = Math.max(1, parseInt(r['OrderItem.quantity'], 10) || 1);
return {
rowIndex: i,
expectedBarcode: toStringSafe(r['VariationBarcode.code']),
qtyRequired: qty,
qtyRemaining: qty,
name: `${r['DeliveryAddress.firstName']} ${r['DeliveryAddress.lastName']}`,
itemName: r['OrderItem.orderItemName']
};
});
const byBarcode = {};
for (const it of items) {
const key = it.expectedBarcode;
if (!key) continue;
byBarcode[key] = (byBarcode[key] || 0) + it.qtyRequired;
}
const totalRequired = items.reduce((s, it) => s + it.qtyRequired, 0);
setCurrentScan({
packageNumber: code,
items,
byBarcode,
totalRequired,
totalRemaining: totalRequired,
});
setScanMode('barcode');
playSound('positive');
}
} else {
if (!currentScan) return;
const groups = { ...currentScan.byBarcode };
const remainingForCode = groups[code] || 0;
if (remainingForCode > 0) {
groups[code] = remainingForCode - 1;
const items = currentScan.items.map(it => {
if (it.expectedBarcode === code && it.qtyRemaining > 0) {
return { ...it, qtyRemaining: it.qtyRemaining - 1 };
}
return it;
});
const totalRemaining = currentScan.totalRemaining - 1;
if (totalRemaining > 0) {
setCurrentScan({ ...currentScan, byBarcode: groups, items, totalRemaining });
playSound('positive');
} else {
const allIdx = items.map(it => it.rowIndex);
setMatchedRows(prev => new Set([...prev, ...allIdx]));
playSound('confirm');
setCurrentScan(null);
setScanMode('package');
}
} else {
playSound('negative');
setError('Falscher Barcode. Bitte erneut die Paketnummer scannen.');
setCurrentScan(null);
setScanMode('package');
}
}
if (inputRef.current) inputRef.current.focus();
};
React.useEffect(() => { if (inputRef.current) inputRef.current.focus(); }, []);
const renderTable = () => {
if (data.length === 0) {
return React.createElement('p', { className: 'no-data' }, 'Keine Daten hochgeladen.');
}
return React.createElement('div', { className: 'table-container' }, [
React.createElement('table', null, [
React.createElement('thead', null, [
React.createElement('tr', null, [
React.createElement('th', null, 'BESTELL-ID'),
React.createElement('th', null, 'BARCODE'),
React.createElement('th', null, 'PAKETNUMMER'),
React.createElement('th', null, 'NAME'),
React.createElement('th', null, 'ARTIKELNAME'),
React.createElement('th', null, 'MENGE'),
]),
]),
React.createElement('tbody', null, data.map((row, index) =>
React.createElement('tr', { key: index, className: matchedRows.has(index) ? 'matched' : '' }, [
React.createElement('td', null, row['Order.id']),
React.createElement('td', null, toStringSafe(row['VariationBarcode.code'])),
React.createElement('td', null, toStringSafe(row['ShippingPackages.packageNumber'])),
React.createElement('td', null, `${row['DeliveryAddress.firstName']} ${row['DeliveryAddress.lastName']}`),
React.createElement('td', null, row['OrderItem.orderItemName']),
React.createElement('td', null, parseInt(row['OrderItem.quantity'], 10) || 1),
])
))
])
]);
};
const renderCurrentScan = () => {
if (!currentScan) {
return React.createElement(
'p',
{ className: 'scan-status' },
[
'Scannen Sie eine ',
React.createElement('span', { className: 'accent' }, 'Paketnummer'),
]
);
}
const barcodeList = Object.entries(currentScan.byBarcode)
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([ean, count]) =>
React.createElement('li', { key: ean }, `${ean || 'N/A'} – noch ${count}`)
);
const itemLines = currentScan.items.map((it, idx) =>
React.createElement(
'li',
{ key: idx },
`${it.itemName} (${it.expectedBarcode || 'N/A'}): ${it.qtyRequired - it.qtyRemaining}/${it.qtyRequired} gescannt`
)
);
// NEU: Empfängername aus dem ersten Eintrag
const recipientName =
currentScan.items && currentScan.items.length > 0
? currentScan.items[0].name
: 'N/A';
return React.createElement('div', { className: 'status-panel' }, [
React.createElement('div', { className: 'scan-status' }, [
React.createElement('p', null, [
'Gescannte Paketnummer: ',
React.createElement('span', { className: 'accent' }, currentScan.packageNumber),
]),
React.createElement('p', null, [
'Empfänger: ',
React.createElement('span', { className: 'accent' }, recipientName),
]),
React.createElement(
'p',
null,
`Gesamt noch: ${currentScan.totalRemaining} von ${currentScan.totalRequired}`
),
React.createElement('p', null, 'Benötigte EANs:'),
React.createElement('ul', null, barcodeList),
React.createElement('p', null, 'Positionen:'),
React.createElement('ul', null, itemLines),
React.createElement(
'p',
{ className: 'mt-2' },
[
'Bitte scannen Sie die ',
React.createElement('span', { className: 'accent' }, 'zugehörigen EANs'),
' der Positionen.',
]
),
]),
]);
};
return React.createElement('div', null, [
React.createElement('h1', { style: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '10px' } }, [
'Speditions Scanner',
React.createElement('span', {
style: { fontSize: '20px', opacity: audioReady ? 1 : 0.3 },
title: audioReady ? 'Audio aktiviert' : 'Audio wird beim ersten Klick aktiviert'
}, audioReady ? '🔊' : '🔇')
]),
error && React.createElement('div', { className: 'error' }, error),
React.createElement('div', null, [React.createElement('label', null, 'CSV-Datei hochladen'), React.createElement('input', { type: 'file', accept: '.csv', onChange: handleFileUpload, className: 'file-input' })]),
React.createElement('div', null, [React.createElement('label', null, uploadedFileName.toLowerCase().includes('geis') ? 'Geis Barcode scannen' : 'Barcode scannen'), React.createElement('input', { type: 'text', value: scanInput, onChange: (e) => setScanInput(e.target.value), onKeyDown: handleScanInput, ref: inputRef, placeholder: scanMode === 'package' ? 'Paketnummer scannen' : (uploadedFileName.toLowerCase().includes('geis') ? 'Geis Barcode scannen' : 'Barcode scannen'), className: 'scan-input' }), renderCurrentScan()]),
renderTable()
]);
}
root.render(React.createElement(App));
// Register Service Worker for PWA
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./service-worker.js')
.then(registration => {
console.log('Service Worker registered successfully:', registration.scope);
})
.catch(error => {
console.log('Service Worker registration failed:', error);
});
});
}
</script>
</body>
</html>