-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction-codes.js
More file actions
1164 lines (1031 loc) · 36.9 KB
/
action-codes.js
File metadata and controls
1164 lines (1031 loc) · 36.9 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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function () {
const helpers = window.dbWalletHelpers || null;
if (
!helpers ||
typeof helpers.base64UrlEncode !== "function" ||
typeof helpers.base64UrlDecode !== "function" ||
typeof helpers.safeParse !== "function" ||
typeof helpers.randomToken !== "function"
) {
return;
}
const SOFT_LIMIT = 6;
const HARD_LIMIT = 10;
const { base64UrlEncode, base64UrlDecode, safeParse, randomToken } = helpers;
function normalizeAmount(value) {
const n = typeof value === "number" ? value : parseInt(value, 10);
if (!Number.isFinite(n)) return 1;
return Math.max(1, Math.round(n));
}
function normalizeType(value) {
const t = typeof value === "string" ? value.trim() : "";
return t === "d" ? "d" : "g";
}
function normalizeScope(value) {
return value === "global" ? "global" : "local";
}
const GLOBAL_ACTION_VERSION = 1;
const GLOBAL_ACTION_MAX_AMOUNT = 100;
function clampGlobalAmount(value) {
const n = typeof value === "number" ? value : parseInt(value, 10);
if (!Number.isFinite(n)) return null;
const rounded = Math.round(n);
const clamped = Math.min(GLOBAL_ACTION_MAX_AMOUNT, Math.max(1, rounded));
return clamped;
}
function normalizeGlobalAmount(value) {
const n = typeof value === "number" ? value : parseInt(value, 10);
if (!Number.isFinite(n)) return null;
const rounded = Math.round(n);
if (typeof value === "number" && rounded !== n) return null;
if (rounded < 1 || rounded > GLOBAL_ACTION_MAX_AMOUNT) return null;
return rounded;
}
function normalizeGlobalPayload(input) {
if (!input || typeof input !== "object") return null;
const vRaw = typeof input.v === "number" ? Math.floor(input.v) : null;
const v =
vRaw === null || !Number.isFinite(vRaw) ? GLOBAL_ACTION_VERSION : vRaw;
if (v !== GLOBAL_ACTION_VERSION) return null;
const t = input.t === "d" || input.t === "g" ? input.t : "";
if (!t) return null;
const n = normalizeGlobalAmount(input.n);
if (n === null) return null;
const label =
typeof input.l === "string" && input.l.trim() !== ""
? input.l.trim()
: "";
const out = { v, t, n };
if (label) out.l = label;
return out;
}
function defaultLabelForType(type, amount) {
const amountValue = normalizeAmount(amount);
const normalizedType = normalizeType(type);
return normalizedType === "d"
? `Drink +${amountValue}`
: `Guthaben +${amountValue}`;
}
function amountPromptForType(type) {
return normalizeType(type) === "d"
? "Wie viele Getränke soll der neue Code trinken?"
: "Wie viele Getränke soll der neue Code gutschreiben?";
}
function rotateActionCodeKey(code, now = Date.now()) {
if (!code || typeof code !== "object") return;
code.key = randomToken(18);
code.updatedAt = now;
if (!code.createdAt) code.createdAt = code.updatedAt;
}
function buildActionCode(data, now = Date.now()) {
const type = normalizeType(data && data.type);
const amount = normalizeAmount(data && data.amount);
const labelRaw = data && typeof data.label === "string" ? data.label : "";
const label =
String(labelRaw || "").trim() || defaultLabelForType(type, amount);
return {
id: randomToken(10),
label,
amount,
type,
key: randomToken(18),
createdAt: now,
updatedAt: now,
};
}
function buildGlobalCode(data, now = Date.now()) {
const type = normalizeType(data && data.type);
const amountRaw = clampGlobalAmount(data && data.amount);
const amount = amountRaw === null ? 1 : amountRaw;
const labelRaw = data && typeof data.label === "string" ? data.label : "";
const label =
String(labelRaw || "").trim() || defaultLabelForType(type, amount);
return {
id: `global:${randomToken(10)}`,
label,
amount,
type,
scope: "global",
createdAt: now,
updatedAt: now,
};
}
function applyActionCodeEdits(code, updates, now = Date.now()) {
if (!code || typeof code !== "object") return false;
const nextAmount = normalizeAmount(updates && updates.amount);
const nextType = normalizeType(updates && updates.type);
const nextLabelRaw =
updates && typeof updates.label === "string" ? updates.label : "";
const nextLabel = String(nextLabelRaw || "").trim() || `+${nextAmount}`;
const prevLabel = code.label || "";
const changed =
nextAmount !== code.amount ||
nextType !== code.type ||
nextLabel !== prevLabel;
code.amount = nextAmount;
code.type = nextType;
code.label = nextLabel;
if (changed) {
rotateActionCodeKey(code, now);
} else {
code.updatedAt = now;
if (!code.createdAt) code.createdAt = code.updatedAt;
}
return true;
}
function normalizeActionCode(raw) {
if (!raw || typeof raw !== "object") return null;
const id = typeof raw.id === "string" && raw.id.trim() ? raw.id.trim() : "";
const label = typeof raw.label === "string" ? raw.label.trim() : "";
const amount = normalizeAmount(raw.amount);
const type = normalizeType(raw.type);
const key =
typeof raw.key === "string" && raw.key.trim() ? raw.key.trim() : "";
const createdAt =
typeof raw.createdAt === "number" && Number.isFinite(raw.createdAt)
? raw.createdAt
: 0;
const updatedAt =
typeof raw.updatedAt === "number" && Number.isFinite(raw.updatedAt)
? raw.updatedAt
: 0;
return {
id,
label,
amount,
type,
key,
createdAt,
updatedAt,
};
}
function compareActionCodes(a, b) {
const au = a && typeof a.updatedAt === "number" ? a.updatedAt : 0;
const bu = b && typeof b.updatedAt === "number" ? b.updatedAt : 0;
if (au !== bu) return bu - au;
const ac = a && typeof a.createdAt === "number" ? a.createdAt : 0;
const bc = b && typeof b.createdAt === "number" ? b.createdAt : 0;
if (ac !== bc) return bc - ac;
const aid = a && typeof a.id === "string" ? a.id : "";
const bid = b && typeof b.id === "string" ? b.id : "";
return aid.localeCompare(bid);
}
function normalizeActionCodes(list, now = Date.now()) {
const arr = Array.isArray(list) ? list : [];
const out = [];
const seen = new Set();
for (const raw of arr) {
const code = normalizeActionCode(raw);
if (!code) continue;
if (!code.id) code.id = randomToken(10);
if (!code.key) code.key = randomToken(18);
if (!code.updatedAt && !code.createdAt) {
code.updatedAt = now;
code.createdAt = now;
} else if (!code.updatedAt) {
code.updatedAt = code.createdAt;
} else if (!code.createdAt) {
code.createdAt = code.updatedAt;
}
if (!code.label) {
const typeLabel = code.type === "d" ? "Drink" : "Guthaben";
code.label = `${typeLabel} +${code.amount}`;
}
let id = code.id;
while (seen.has(id)) {
id = randomToken(10);
}
code.id = id;
seen.add(id);
out.push(code);
}
out.sort(compareActionCodes);
const trimmedCount = Math.max(0, out.length - HARD_LIMIT);
const trimmed = out.slice(0, HARD_LIMIT);
if (trimmedCount > 0) {
trimmed._dbwTrimmed = trimmedCount;
}
return trimmed;
}
function mergeActionCodes(localList, remoteList) {
const now = Date.now();
const local = normalizeActionCodes(localList, now);
const remote = normalizeActionCodes(remoteList, now);
const byId = new Map();
for (const c of local) byId.set(c.id, c);
for (const c of remote) {
const existing = byId.get(c.id);
if (!existing) {
local.push(c);
byId.set(c.id, c);
continue;
}
const localUpdated = existing.updatedAt || 0;
const remoteUpdated = c.updatedAt || 0;
if (remoteUpdated >= localUpdated) {
existing.label = c.label;
existing.amount = c.amount;
existing.type = c.type;
existing.key = c.key;
existing.createdAt = c.createdAt;
existing.updatedAt = c.updatedAt;
}
}
const merged = normalizeActionCodes(local, now);
const remoteTrimmed =
remote && typeof remote._dbwTrimmed === "number" ? remote._dbwTrimmed : 0;
const mergedTrimmed =
merged && typeof merged._dbwTrimmed === "number" ? merged._dbwTrimmed : 0;
if (remoteTrimmed > 0 || mergedTrimmed > 0) {
merged._dbwTrimmed = Math.max(remoteTrimmed, mergedTrimmed);
}
return merged;
}
function buildActionPayload(wallet, code) {
const payload = {
v: 2,
walletId:
wallet && typeof wallet.walletId === "string" ? wallet.walletId : "",
codeId: code.id,
key: code.key,
};
return payload;
}
function encodeGlobalActionHash(input) {
const payload = normalizeGlobalPayload(input);
if (!payload) return "";
const json = JSON.stringify(payload);
return "acg:" + base64UrlEncode(json);
}
function decodeGlobalActionHash(hash) {
const raw = String(hash || "");
if (!raw.startsWith("acg:")) return null;
const token = raw.slice(4);
if (!token) return null;
try {
const json = base64UrlDecode(token);
const payload = safeParse(json);
return normalizeGlobalPayload(payload);
} catch (e) {
return null;
}
}
function encodeActionHash(payload) {
const json = JSON.stringify(payload || {});
return "ac:" + base64UrlEncode(json);
}
function decodeActionHash(hash) {
const raw = String(hash || "");
if (!raw.startsWith("ac:")) return null;
const token = raw.slice(3);
if (!token) return null;
const json = base64UrlDecode(token);
const payload = safeParse(json);
if (!payload || typeof payload !== "object") return null;
const walletId =
typeof payload.walletId === "string" ? payload.walletId : "";
const codeId = typeof payload.codeId === "string" ? payload.codeId : "";
const key = typeof payload.key === "string" ? payload.key : "";
const v =
typeof payload.v === "number" && Number.isFinite(payload.v)
? payload.v
: 1;
const out = { v, walletId, codeId, key };
const type = typeof payload.type === "string" ? payload.type.trim() : "";
if (type === "d" || type === "g") out.type = type;
return out;
}
function canvasToPngDownload(canvas, filename) {
if (!canvas) return;
const saveBlob = (blob) => {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(a.href);
};
if (canvas.toBlob) {
canvas.toBlob((blob) => {
if (blob) saveBlob(blob);
}, "image/png");
return;
}
const a = document.createElement("a");
a.href = canvas.toDataURL("image/png");
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function renderQrToCanvas(canvas, url) {
if (!canvas) return;
if (!window.qrcodegen || !window.qrcodegen.QrCode) {
throw new Error("QR library missing");
}
const ecc = window.qrcodegen.QrCode.Ecc.LOW;
const qr = window.qrcodegen.QrCode.encodeText(String(url || ""), ecc);
const border = 4;
const scale = 6;
const size = qr.size;
const dim = (size + border * 2) * scale;
canvas.width = dim;
canvas.height = dim;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.imageSmoothingEnabled = false;
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, dim, dim);
ctx.fillStyle = "#000000";
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
if (qr.getModule(x, y)) {
ctx.fillRect(
(x + border) * scale,
(y + border) * scale,
scale,
scale,
);
}
}
}
}
function ensureWalletActionCodes(wallet) {
if (!wallet || typeof wallet !== "object") return false;
const now = Date.now();
const current = Array.isArray(wallet.actionCodes) ? wallet.actionCodes : [];
const normalized = normalizeActionCodes(current, now);
const prevTrimmed =
typeof current._dbwTrimmed === "number" ? current._dbwTrimmed : 0;
const nextTrimmed =
typeof normalized._dbwTrimmed === "number" ? normalized._dbwTrimmed : 0;
const trimmedCount = Math.max(prevTrimmed, nextTrimmed);
if (trimmedCount > 0) {
normalized._dbwTrimmed = trimmedCount;
}
const changed = JSON.stringify(current) !== JSON.stringify(normalized);
wallet.actionCodes = normalized;
return {
changed,
trimmedCount,
};
}
function persistIfChanged(ctx, wallet) {
const current = Array.isArray(wallet && wallet.actionCodes)
? wallet.actionCodes
: [];
if (current.length > HARD_LIMIT) ctx.showTrimNotice = true;
const res = ensureWalletActionCodes(wallet);
if (res && res.trimmedCount > 0) ctx.showTrimNotice = true;
if (res && res.changed) ctx.persistWallet(wallet);
}
function actionUrlFor(ctx, code) {
const wallet = ctx.getWallet();
const scope = normalizeScope(code && code.scope);
if (scope === "global") {
const label =
code && typeof code.label === "string" ? code.label.trim() : "";
const amountRaw = clampGlobalAmount(code && code.amount);
const amount = amountRaw === null ? 1 : amountRaw;
const payload = {
v: GLOBAL_ACTION_VERSION,
t: normalizeType(code && code.type),
n: amount,
};
if (label) payload.l = label;
const hash = encodeGlobalActionHash(payload);
return hash ? ctx.getBaseUrl() + "#" + hash : "";
}
const payload = buildActionPayload(wallet, code);
return ctx.getBaseUrl() + "#" + encodeActionHash(payload);
}
function buildTypeToggle(initialType, onChange) {
let currentType = normalizeType(initialType);
const wrapper = document.createElement("div");
wrapper.className = "action-code-type-toggle";
const btnTypeDrink = document.createElement("button");
btnTypeDrink.type = "button";
btnTypeDrink.textContent = "🥤 Trinken";
btnTypeDrink.className = "mode-btn";
btnTypeDrink.setAttribute("aria-pressed", "false");
const btnTypeCredit = document.createElement("button");
btnTypeCredit.type = "button";
btnTypeCredit.textContent = "💰 Guthaben";
btnTypeCredit.className = "mode-btn";
btnTypeCredit.setAttribute("aria-pressed", "false");
function sync() {
currentType = currentType === "g" ? "g" : "d";
const isDrink = currentType === "d";
btnTypeDrink.classList.toggle("active", isDrink);
btnTypeCredit.classList.toggle("active", !isDrink);
btnTypeDrink.setAttribute("aria-pressed", isDrink ? "true" : "false");
btnTypeCredit.setAttribute("aria-pressed", isDrink ? "false" : "true");
}
btnTypeDrink.addEventListener("click", () => {
currentType = "d";
sync();
if (onChange) onChange(currentType);
});
btnTypeCredit.addEventListener("click", () => {
currentType = "g";
sync();
if (onChange) onChange(currentType);
});
sync();
wrapper.appendChild(btnTypeDrink);
wrapper.appendChild(btnTypeCredit);
return {
el: wrapper,
getType: () => currentType,
setType: (type) => {
currentType = normalizeType(type);
sync();
},
};
}
function buildScopeToggle(initialScope, onChange) {
let currentScope = normalizeScope(initialScope);
const wrapper = document.createElement("div");
wrapper.className = "action-code-scope-toggle";
const btnLocal = document.createElement("button");
btnLocal.type = "button";
btnLocal.textContent = "🔒 Lokal";
btnLocal.className = "mode-btn";
btnLocal.setAttribute("aria-pressed", "false");
const btnGlobal = document.createElement("button");
btnGlobal.type = "button";
btnGlobal.textContent = "🌍 Global";
btnGlobal.className = "mode-btn";
btnGlobal.setAttribute("aria-pressed", "false");
function sync() {
currentScope = normalizeScope(currentScope);
const isLocal = currentScope === "local";
btnLocal.classList.toggle("active", isLocal);
btnGlobal.classList.toggle("active", !isLocal);
btnLocal.setAttribute("aria-pressed", isLocal ? "true" : "false");
btnGlobal.setAttribute("aria-pressed", isLocal ? "false" : "true");
}
btnLocal.addEventListener("click", () => {
currentScope = "local";
sync();
if (onChange) onChange(currentScope);
});
btnGlobal.addEventListener("click", () => {
currentScope = "global";
sync();
if (onChange) onChange(currentScope);
});
sync();
wrapper.appendChild(btnLocal);
wrapper.appendChild(btnGlobal);
return {
el: wrapper,
getScope: () => currentScope,
setScope: (scope) => {
currentScope = normalizeScope(scope);
sync();
},
};
}
function buildCreateForm(ctx) {
const form = document.createElement("div");
form.className = "action-code-form";
const amountInput = document.createElement("input");
amountInput.type = "number";
amountInput.min = "1";
amountInput.value = "10";
const labelInput = document.createElement("input");
labelInput.type = "text";
let autoLabel = defaultLabelForType(ctx.selectedType, amountInput.value);
labelInput.value = autoLabel;
const amountField = document.createElement("label");
amountField.className = "action-code-form-field";
const amountText = document.createElement("span");
amountText.textContent = amountPromptForType(ctx.selectedType);
amountField.appendChild(amountText);
amountField.appendChild(amountInput);
const labelField = document.createElement("label");
labelField.className = "action-code-form-field";
const labelText = document.createElement("span");
labelText.textContent = "Name für den Action Code:";
labelField.appendChild(labelText);
labelField.appendChild(labelInput);
const scopeToggle = buildScopeToggle(ctx.selectedScope, (nextScope) => {
ctx.selectedScope = nextScope;
updateAmountLimit();
});
const typeToggle = buildTypeToggle(ctx.selectedType, (nextType) => {
ctx.selectedType = nextType;
updateDefaults();
amountText.textContent = amountPromptForType(nextType);
});
function updateDefaults() {
const nextDefault = defaultLabelForType(
typeToggle.getType(),
amountInput.value,
);
const current = labelInput.value.trim();
if (!current || current === autoLabel) {
labelInput.value = nextDefault;
}
autoLabel = nextDefault;
}
function updateAmountLimit() {
const scope = scopeToggle.getScope();
if (scope === "global") {
amountInput.max = String(GLOBAL_ACTION_MAX_AMOUNT);
const normalized = clampGlobalAmount(amountInput.value);
if (normalized !== null) {
amountInput.value = String(normalized);
}
} else {
amountInput.removeAttribute("max");
}
}
amountInput.addEventListener("input", () => {
updateDefaults();
updateAmountLimit();
});
const fields = document.createElement("div");
fields.className = "action-code-form-fields";
fields.appendChild(amountField);
fields.appendChild(labelField);
const actions = document.createElement("div");
actions.className = "action-code-form-actions";
const btnSave = document.createElement("button");
btnSave.type = "button";
btnSave.textContent = "Speichern";
btnSave.addEventListener("click", () => {
const walletNow = ctx.getWallet();
if (!walletNow) return;
const scope = scopeToggle.getScope();
if (scope === "global") {
const created = buildGlobalCode({
type: typeToggle.getType(),
amount: amountInput.value,
label: labelInput.value,
});
ctx.globalCodes.push(created);
} else {
persistIfChanged(ctx, walletNow);
const currentCodes = Array.isArray(walletNow.actionCodes)
? walletNow.actionCodes
: [];
const hadNoCodes = currentCodes.length === 0;
const created = buildActionCode({
type: typeToggle.getType(),
amount: amountInput.value,
label: labelInput.value,
});
if (!Array.isArray(walletNow.actionCodes))
walletNow.actionCodes = [];
walletNow.actionCodes.push(created);
const res = ensureWalletActionCodes(walletNow);
if (res && res.trimmedCount > 0) ctx.showTrimNotice = true;
ctx.persistWallet(walletNow);
if (hadNoCodes) {
const details =
typeof ctx.container.closest === "function"
? ctx.container.closest("details")
: null;
if (details) details.open = true;
}
}
ctx.createOpen = false;
ctx.refresh();
});
const btnCancel = document.createElement("button");
btnCancel.type = "button";
btnCancel.textContent = "Abbrechen";
btnCancel.addEventListener("click", () => {
ctx.createOpen = false;
ctx.refresh();
});
actions.appendChild(btnSave);
actions.appendChild(btnCancel);
updateAmountLimit();
form.appendChild(scopeToggle.el);
form.appendChild(typeToggle.el);
form.appendChild(fields);
form.appendChild(actions);
return form;
}
function buildEditForm(ctx, code, isGlobal) {
const editForm = document.createElement("div");
editForm.className = "action-code-form";
const amountInput = document.createElement("input");
amountInput.type = "number";
amountInput.min = "1";
amountInput.value = String(code.amount || 1);
const labelInput = document.createElement("input");
labelInput.type = "text";
labelInput.value =
code.label ||
defaultLabelForType(code.type, normalizeAmount(code.amount));
const amountField = document.createElement("label");
amountField.className = "action-code-form-field";
const amountLabel = document.createElement("span");
amountLabel.textContent = amountPromptForType(code.type);
amountField.appendChild(amountLabel);
amountField.appendChild(amountInput);
const labelField = document.createElement("label");
labelField.className = "action-code-form-field";
const labelText = document.createElement("span");
labelText.textContent = "Name für den Action Code:";
labelField.appendChild(labelText);
labelField.appendChild(labelInput);
const scopeToggle = buildScopeToggle(
isGlobal ? "global" : "local",
() => updateAmountLimit(),
);
const typeToggle = buildTypeToggle(code.type, (nextType) => {
amountLabel.textContent = amountPromptForType(nextType);
});
amountInput.addEventListener("input", () => updateAmountLimit());
function updateAmountLimit() {
const scope = scopeToggle.getScope();
if (scope === "global") {
amountInput.max = String(GLOBAL_ACTION_MAX_AMOUNT);
const normalized = clampGlobalAmount(amountInput.value);
if (normalized !== null) amountInput.value = String(normalized);
} else {
amountInput.removeAttribute("max");
}
}
const fields = document.createElement("div");
fields.className = "action-code-form-fields";
fields.appendChild(amountField);
fields.appendChild(labelField);
const actions = document.createElement("div");
actions.className = "action-code-form-actions";
const btnSave = document.createElement("button");
btnSave.type = "button";
btnSave.textContent = "Speichern";
btnSave.addEventListener("click", () => {
const walletNow = ctx.getWallet();
if (!walletNow) return;
const scope = scopeToggle.getScope();
if (scope === "global") {
if (!isGlobal) {
const codesNow = Array.isArray(walletNow.actionCodes)
? walletNow.actionCodes
: [];
walletNow.actionCodes = codesNow.filter(
(c) => c && c.id !== code.id,
);
const res = ensureWalletActionCodes(walletNow);
if (res && res.trimmedCount > 0) ctx.showTrimNotice = true;
ctx.persistWallet(walletNow);
const created = buildGlobalCode({
type: typeToggle.getType(),
amount: amountInput.value,
label: labelInput.value,
});
ctx.globalCodes.push(created);
} else {
code.type = normalizeType(typeToggle.getType());
const amountRaw = clampGlobalAmount(amountInput.value);
code.amount = amountRaw === null ? 1 : amountRaw;
const labelRaw = String(labelInput.value || "").trim();
code.label =
labelRaw || defaultLabelForType(code.type, code.amount);
code.updatedAt = Date.now();
}
} else {
if (isGlobal) {
ctx.globalCodes = ctx.globalCodes.filter((c) => c.id !== code.id);
const created = buildActionCode({
type: typeToggle.getType(),
amount: amountInput.value,
label: labelInput.value,
});
if (!Array.isArray(walletNow.actionCodes))
walletNow.actionCodes = [];
walletNow.actionCodes.push(created);
} else {
const codesNow = Array.isArray(walletNow.actionCodes)
? walletNow.actionCodes
: [];
const target = codesNow.find((c) => c && c.id === code.id);
if (!target) return;
applyActionCodeEdits(target, {
label: labelInput.value,
amount: amountInput.value,
type: typeToggle.getType(),
});
}
const res = ensureWalletActionCodes(walletNow);
if (res && res.trimmedCount > 0) ctx.showTrimNotice = true;
ctx.persistWallet(walletNow);
}
ctx.editingId = "";
ctx.refresh();
});
const btnCancel = document.createElement("button");
btnCancel.type = "button";
btnCancel.textContent = "Abbrechen";
btnCancel.addEventListener("click", () => {
ctx.editingId = "";
ctx.refresh();
});
actions.appendChild(btnSave);
actions.appendChild(btnCancel);
updateAmountLimit();
editForm.appendChild(scopeToggle.el);
editForm.appendChild(typeToggle.el);
editForm.appendChild(fields);
editForm.appendChild(actions);
return editForm;
}
function buildDeleteConfirm(ctx, code, isGlobal) {
const deleteBox = document.createElement("div");
deleteBox.className = "action-code-confirm";
const deleteText = document.createElement("div");
deleteText.textContent = `Action Code "${code.label || `+${code.amount}`}" löschen?`;
const deleteActions = document.createElement("div");
deleteActions.className = "action-code-form-actions";
const btnConfirm = document.createElement("button");
btnConfirm.type = "button";
btnConfirm.textContent = "Löschen";
btnConfirm.addEventListener("click", () => {
const walletNow = ctx.getWallet();
if (!walletNow) return;
if (isGlobal) {
ctx.globalCodes = ctx.globalCodes.filter((c) => c.id !== code.id);
} else {
const codesNow = Array.isArray(walletNow.actionCodes)
? walletNow.actionCodes
: [];
walletNow.actionCodes = codesNow.filter(
(c) => c && c.id !== code.id,
);
const res = ensureWalletActionCodes(walletNow);
if (res && res.trimmedCount > 0) ctx.showTrimNotice = true;
ctx.persistWallet(walletNow);
}
ctx.pendingDeleteId = "";
ctx.refresh();
});
const btnCancel = document.createElement("button");
btnCancel.type = "button";
btnCancel.textContent = "Abbrechen";
btnCancel.addEventListener("click", () => {
ctx.pendingDeleteId = "";
ctx.refresh();
});
deleteActions.appendChild(btnConfirm);
deleteActions.appendChild(btnCancel);
deleteBox.appendChild(deleteText);
deleteBox.appendChild(deleteActions);
return deleteBox;
}
function buildQrCard(ctx, code) {
const canvas = document.createElement("canvas");
canvas.className = "action-code-canvas";
const urlInput = document.createElement("input");
urlInput.type = "text";
urlInput.readOnly = true;
urlInput.inputMode = "none";
urlInput.className = "action-code-url";
urlInput.setAttribute("aria-label", "Action Code Link");
let url = "";
try {
url = actionUrlFor(ctx, code);
urlInput.value = url;
renderQrToCanvas(canvas, url);
} catch (e) {
const msg = String(e && e.message ? e.message : e || "");
const fallback = document.createElement("div");
fallback.className = "action-code-error";
fallback.textContent = msg.includes("QR library missing")
? "QR-Code-Generator fehlt (qrcodegen.js)."
: "QR-Code konnte nicht erzeugt werden.";
return { error: fallback };
}
function selectUrl() {
try {
urlInput.focus({ preventScroll: true });
} catch (e) {
urlInput.focus();
}
urlInput.select();
try {
urlInput.setSelectionRange(0, urlInput.value.length);
} catch (e) {}
}
urlInput.addEventListener("focus", selectUrl);
urlInput.addEventListener("click", selectUrl);
const wallet = ctx.getWallet();
const safeUserId = String((wallet && wallet.userId) || "user").replace(
/[^a-zA-Z0-9_-]/g,
"_",
);
canvas.addEventListener("click", () => {
if (!url) return;
const safeCode = String(code.label || `+${code.amount}`)
.replace(/[^a-zA-Z0-9_-]/g, "_")
.slice(0, 20);
const filename = `db-wallet-${safeUserId}-action-${safeCode}.png`;
canvasToPngDownload(canvas, filename);
});
return { canvas, urlInput };
}
function buildActionCard(ctx, code, isSingle) {
const isGlobal = normalizeScope(code && code.scope) === "global";
const card = document.createElement("div");
card.className = "action-code-card";
if (isSingle) card.classList.add("action-code-card--featured");
const head = document.createElement("div");
head.className = "action-code-head";
const meta = document.createElement("div");
meta.className = "action-code-meta";
const badge = document.createElement("span");
badge.className = "action-code-badge";
badge.textContent = isGlobal ? "🌍 Global" : "🔒 Lokal";
const label = document.createElement("div");
label.className = "action-code-label";
label.textContent = code.label || `+${code.amount}`;
const amount = document.createElement("div");
amount.className = "action-code-amount";
const typeLabel = code.type === "d" ? "Drink" : "Guthaben";
amount.textContent = `+${normalizeAmount(code.amount)} Getränke (${typeLabel})`;
const labelRow = document.createElement("div");
labelRow.className = "action-code-label-row";
labelRow.appendChild(label);
labelRow.appendChild(badge);
meta.appendChild(labelRow);
meta.appendChild(amount);
const btns = document.createElement("div");
btns.className = "action-code-buttons";
const btnEdit = document.createElement("button");
btnEdit.type = "button";
btnEdit.textContent = "Bearbeiten";
btnEdit.addEventListener("click", () => {
ctx.editingId = code.id;
ctx.pendingDeleteId = "";
ctx.createOpen = false;
ctx.refresh();
});
const btnDelete = document.createElement("button");
btnDelete.type = "button";
btnDelete.textContent = "Löschen";
btnDelete.addEventListener("click", () => {
ctx.pendingDeleteId = ctx.pendingDeleteId === code.id ? "" : code.id;
ctx.editingId = "";
ctx.createOpen = false;
ctx.refresh();
});
btns.appendChild(btnEdit);
btns.appendChild(btnDelete);
head.appendChild(meta);
head.appendChild(btns);
card.appendChild(head);
if (ctx.editingId === code.id) {
card.appendChild(buildEditForm(ctx, code, isGlobal));
} else if (ctx.pendingDeleteId === code.id) {