forked from TetsuakiBaba/receiptable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
915 lines (804 loc) · 34.4 KB
/
index.js
File metadata and controls
915 lines (804 loc) · 34.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
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
/**
* Receiptable - Simple Receipt Generator
* @version 2.2.0
* @author Tetsuaki Baba and Rubens Braz
*/
const receiptApp = (function () {
// ==========================================================================
// 1. CONFIGURATION & STATE
// ==========================================================================
const config = {
defaultColor: "#001c9a",
defaultCurrency: "USD"
};
let state = {
currency: config.defaultCurrency,
lang: "en",
dateFormat: "us",
timeFormat: "24h"
};
let signaturePad = null;
// ==========================================================================
// 2. DATA CONSTANTS
// ==========================================================================
// Currencies
const currencies = [
{ code: 'AUD', symbol: 'A$', name: 'Australian Dollar' },
{ code: 'BRL', symbol: 'R$', name: 'Real Brasileiro' },
{ code: 'CAD', symbol: 'C$', name: 'Canadian Dollar' },
{ code: 'CHF', symbol: 'Fr', name: 'Swiss Franc' },
{ code: 'CNY', symbol: '¥', name: 'Chinese Yuan' },
{ code: 'EUR', symbol: '€', name: 'Euro' },
{ code: 'GBP', symbol: '£', name: 'British Pound' },
{ code: 'HKD', symbol: 'HK$', name: 'Hong Kong Dollar' },
{ code: 'INR', symbol: '₹', name: 'Indian Rupee' },
{ code: 'JPY', symbol: '¥', name: 'Japanese Yen' },
{ code: 'KRW', symbol: '₩', name: 'South Korean Won' },
{ code: 'MXN', symbol: 'Mex$', name: 'Mexican Peso' },
{ code: 'NOK', symbol: 'kr', name: 'Norwegian Krone' },
{ code: 'NZD', symbol: 'NZ$', name: 'New Zealand Dollar' },
{ code: 'RUB', symbol: '₽', name: 'Russian Ruble' },
{ code: 'SEK', symbol: 'kr', name: 'Swedish Krona' },
{ code: 'SGD', symbol: 'S$', name: 'Singapore Dollar' },
{ code: 'TRY', symbol: '₺', name: 'Turkish Lira' },
{ code: 'USD', symbol: '$', name: 'US Dollar' },
{ code: 'ZAR', symbol: 'R', name: 'South African Rand' }
];
const translations = {
en: {
receipt_title: "RECEIPT",
date_label: "Date:",
time_label: "Time:",
receipt_number_label: "Receipt #",
received_from_title: "Received From",
from_title: "Received By",
notes_title: "Notes",
col_description: "Payment For",
total_label: "Amount",
signature_title: "Signature",
received_by_label: "Received By",
sentence_template: "I, {issuer}, received from {payer} the amount of {amount} for payment of {reason}.",
sign_here: "Sign Here",
btn_clear_sign: "Clear signature",
btn_copy_link: "Copy Link",
btn_link_copied: "Copied!",
btn_download_pdf: "Download PDF",
btn_clear: "Clear all inputs",
confirm_clear: "Are you sure you want to clear all data? This action cannot be undone.",
pdf_recreate_link: "Click here to recreate this receipt.",
footer_privacy: "Data is saved locally in your browser. The author assumes no responsibility for any damage or loss caused by this system.",
placeholders: {
received_from_name: "Name",
received_from_address: "Address",
received_from_phone: "Phone",
received_from_email: "Email",
issuer_name: "Name",
issuer_address: "Address",
issuer_phone: "Phone",
issuer_email: "Email",
received_by: "Name",
receipt_notes: "Additional notes...",
item_desc: "Description of service..."
}
},
pt: {
receipt_title: "RECIBO",
date_label: "Data:",
time_label: "Hora:",
receipt_number_label: "Recibo Nº",
received_from_title: "Recebido De",
from_title: "Recebido Por",
notes_title: "Obs.",
col_description: "Referente a",
total_label: "Valor",
signature_title: "Assinatura",
received_by_label: "Recebido Por",
sentence_template: "Eu, {issuer}, recebi de {payer} a quantia de {amount} referente a {reason}.",
sign_here: "Assine Aqui",
btn_clear_sign: "Limpar assinatura",
btn_copy_link: "Copiar Link",
btn_link_copied: "Copiado!",
btn_download_pdf: "Baixar PDF",
btn_clear: "Limpar tudo",
confirm_clear: "Tem certeza que deseja limpar todos os dados? Esta ação não pode ser desfeita.",
pdf_recreate_link: "Clique aqui para recriar essa fatura.",
footer_privacy: "Os dados são salvos localmente no seu navegador. O autor não assume qualquer responsabilidade por danos ou perdas causados por este sistema.",
placeholders: {
received_from_name: "Nome",
received_from_address: "Endereço",
received_from_phone: "Telefone",
received_from_email: "Email",
issuer_name: "Nome",
issuer_address: "Endereço",
issuer_phone: "Telefone",
issuer_email: "Email",
received_by: "Nome",
receipt_notes: "Observações...",
item_desc: "Descrição do serviço..."
}
},
jp: {
receipt_title: "領収書",
date_label: "日付:",
time_label: "時間:",
receipt_number_label: "No.",
received_from_title: "受信元",
from_title: "受領者",
notes_title: "備考",
col_description: "但し書き",
total_label: "金額",
signature_title: "署名",
received_by_label: "受領者",
sentence_template: "私 {issuer} は、{payer} から {reason} として {amount} を受領しました。",
sign_here: "ここに署名",
btn_clear_sign: "明確な署名",
btn_copy_link: "リンク作成",
btn_link_copied: "完了!",
btn_download_pdf: "PDF保存",
btn_clear: "すべて消去",
confirm_clear: "すべてのデータを消去してもよろしいですか?この操作は取り消せません。",
pdf_recreate_link: "この領収書を再発行するためのリンク。",
footer_privacy: "データはブラウザ内にローカルに保存されます。このシステムによって生じたいかなる損害または損失についても、作者は一切責任を負いません。",
placeholders: {
received_from_name: "顧客名",
received_from_address: "住所",
received_from_phone: "電話番号",
received_from_email: "メール",
issuer_name: "自社名",
issuer_address: "自社住所",
issuer_phone: "電話番号",
issuer_email: "メール",
received_by: "担当者名",
receipt_notes: "備考...",
item_desc: "品目内容..."
}
}
};
// ==========================================================================
// 3. INITIALIZATION
// ==========================================================================
/**
* Initializes the application, sets up listeners, and loads data.
*/
function init() {
populateCurrencySelect();
setupSignaturePad();
setupEventListeners();
// PRIORITY: Handle URL parameters first
// If data is found in URL, we use it and SKIP LocalStorage to ensure the link is the source of truth
const loadedFromUrl = handleUrlParameters();
// FALLBACK: Only load from LocalStorage if no URL data was present
if (!loadedFromUrl) {
loadFromLocal();
}
// Sync UI Elements with State
document.getElementById('languageSelect').value = state.lang;
document.getElementById('currencySelect').value = state.currency;
document.getElementById('dateFormatSelect').value = state.dateFormat;
document.getElementById('timeFormatSelect').value = state.timeFormat;
// Apply visual settings
changeLanguage(state.lang);
updateDateDisplay();
updateTimeDisplay();
updateCurrencySymbols();
// Ensure Receipt Number exists
const recNumField = document.querySelector('#receipt_number');
if (!recNumField.innerText.trim()) {
recNumField.innerText = generateReceiptNumber();
}
// Start Auto-save loop (every 5 seconds)
setInterval(() => {
saveToLocal();
updateLiveUrl();
}, 5000);
}
/**
* Init the signature pad.
*/
function setupSignaturePad() {
const canvas = document.querySelector('#signature-pad canvas');
function resizeCanvas() {
const ratio = Math.max(window.devicePixelRatio || 1, 1);
let data = null;
if (signaturePad) data = signaturePad.toDataURL();
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext("2d").scale(ratio, ratio);
if (signaturePad && data) signaturePad.fromDataURL(data);
}
resizeCanvas();
window.addEventListener("resize", resizeCanvas);
signaturePad = new SignaturePad(canvas, {
backgroundColor: 'rgba(255, 255, 255, 0)',
penColor: 'rgb(33, 37, 41)'
});
signaturePad.addEventListener("beginStroke", () => {
document.querySelector('.signature-placeholder').style.display = 'none';
});
signaturePad.addEventListener("endStroke", () => {
saveToLocal();
});
}
/**
* Clear the signature pad.
*/
function clearSignature() {
if (signaturePad) {
signaturePad.clear();
document.querySelector('.signature-placeholder').style.display = 'block';
saveToLocal();
}
}
/**
* Populates the currency dropdown from the sorted array.
*/
function populateCurrencySelect() {
const select = document.getElementById('currencySelect');
select.innerHTML = '';
currencies.forEach(curr => {
const option = document.createElement('option');
option.value = curr.code;
option.text = `${curr.code} (${curr.symbol})`;
select.appendChild(option);
});
}
/**
* Sets up all DOM event listeners.
*/
function setupEventListeners() {
document.getElementById('colorPicker').addEventListener('input', (e) => changeColor(e.target.value));
document.getElementById('languageSelect').addEventListener('change', (e) => changeLanguage(e.target.value));
document.getElementById('currencySelect').addEventListener('change', (e) => {
state.currency = e.target.value;
updateCurrencySymbols();
updateReceiptSentence();
});
document.getElementById('dateFormatSelect').addEventListener('change', (e) => {
state.dateFormat = e.target.value;
updateDateDisplay();
});
document.getElementById('timeFormatSelect').addEventListener('change', (e) => {
state.timeFormat = e.target.value;
updateTimeDisplay();
});
document.getElementById('btn_clear_sign').addEventListener('click', clearSignature);
// Prevents pasting HTML formatting into editable fields
document.querySelectorAll('[contenteditable]').forEach(el => {
el.addEventListener('paste', (e) => {
e.preventDefault();
const text = (e.originalEvent || e).clipboardData.getData('text/plain');
document.execCommand('insertText', false, text);
});
el.addEventListener('blur', (e) => {
if (e.target.innerText.trim() === '') {
e.target.innerHTML = '';
}
});
});
// Listen for input on these specific fields to update the legal sentence in real-time
const sentenceTriggers = [
'issuer_name',
'received_from_name',
'payment_amount',
'payment_description'
];
sentenceTriggers.forEach(id => {
const el = document.getElementById(id);
if (el) {
// 'input' event works for both <input> and contenteditable elements
el.addEventListener('input', updateReceiptSentence);
}
});
}
// ==========================================================================
// 4. CORE LOGIC (Dates, Format, Calc)
// ==========================================================================
/**
* Updates the date INPUT value.
* Note: Inputs type='date' always require YYYY-MM-DD value.
* The visual format (DD/MM or MM/DD) is controlled by the user's browser locale
* until we generate the PDF.
*/
function updateDateDisplay() {
const dateInput = document.getElementById('date');
// If the input already has a value (user selected), don't overwrite it automatically unless it's empty (initial load)
if (!dateInput.value) {
const today = new Date();
// Local date to YYYY-MM-DD
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
dateInput.value = `${year}-${month}-${day}`;
}
}
/**
* Updates the time INPUT value.
*/
function updateTimeDisplay() {
const timeInput = document.getElementById('time');
if (!timeInput.value) {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const mins = String(now.getMinutes()).padStart(2, '0');
timeInput.value = `${hours}:${mins}`;
}
}
/**
* Generates a random Receipt ID.
* @returns {string} The formatted receipt number.
*/
function generateReceiptNumber() {
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const rand = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
return `REC-${year}-${month}-${day}-${rand}`;
}
/**
* Handles Language Switching and Placeholder updates.
* @param {string} langCode - The language code (en, pt, jp).
*/
function changeLanguage(langCode) {
state.lang = translations[langCode] ? langCode : 'en';
const t = translations[langCode];
// Update static text elements
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
if (t[key]) el.innerText = t[key];
});
const mapping = {
'received_from_name': t.placeholders.received_from_name,
'received_from_address': t.placeholders.received_from_address,
'received_from_phone': t.placeholders.received_from_phone,
'received_from_email': t.placeholders.received_from_email,
'issuer_name': t.placeholders.issuer_name,
'issuer_address': t.placeholders.issuer_address,
'issuer_phone': t.placeholders.issuer_phone,
'issuer_email': t.placeholders.issuer_email,
'received_by': t.placeholders.received_by,
'receipt_notes': t.placeholders.receipt_notes
};
for (const [id, text] of Object.entries(mapping)) {
const el = document.getElementById(id);
if (el) el.setAttribute('data-placeholder', text);
}
document.getElementById('payment_description').placeholder = t.placeholders.item_desc;
// Trigger sentence update when language changes
updateReceiptSentence();
}
/**
* Updates CSS variable for the theme color.
* @param {string} color - Hex color code.
*/
function changeColor(color) {
document.documentElement.style.setProperty('--primary-color', color);
}
/**
* Gets symbol for current state currency.
* @returns {string} Currency symbol.
*/
function getSymbol() {
const curr = currencies.find(c => c.code === state.currency);
return curr ? curr.symbol : '$';
}
/**
* Refreshes symbols in the table when currency changes.
*/
function updateCurrencySymbols() {
const symbol = getSymbol();
document.querySelectorAll('.currency-symbol').forEach(el => {
el.innerText = symbol;
});
}
/**
* Helper to prevent XSS by escaping HTML characters.
*/
function escapeHtml(text) {
if (!text) return '';
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
/**
* Generates the dynamic legal sentence based on current input values.
* Replaces placeholders like {issuer} with actual text.
*/
function updateReceiptSentence() {
const t = translations[state.lang];
let template = t.sentence_template;
// Helper to get value from Input or ContentEditable
const getVal = (id) => {
const el = document.getElementById(id);
if (!el) return '___';
// Returns value for inputs, innerText for editable spans
return el.value || el.innerText || '___';
};
// Get current values
const issuer = getVal('issuer_name');
const payer = getVal('received_from_name');
let amount = getVal('payment_amount');
const reason = getVal('payment_description');
// Format amount if it is a number
if (amount !== '___' && !isNaN(parseFloat(amount))) {
const symbol = getSymbol();
amount = `${symbol} ${parseFloat(amount)}`;
}
// Replace placeholders
const text = template
.replace('{issuer}', `<b>${escapeHtml(issuer)}</b>`)
.replace('{payer}', `<b>${escapeHtml(payer)}</b>`)
.replace('{amount}', `<b>${escapeHtml(amount)}</b>`)
.replace('{reason}', `<b>${escapeHtml(reason)}</b>`);
// Update the DOM element
const sentenceEl = document.getElementById('receipt_sentence');
if (sentenceEl) {
sentenceEl.innerHTML = text;
}
}
// ==========================================================================
// 5. PERSISTENCE (LocalStorage)
// ==========================================================================
/**
* Saves current state to LocalStorage.
*/
function saveToLocal() {
const data = collectReceiptData();
// Do not save receipt_number to local storage to ensure a new random number on reload
delete data.receipt_number;
localStorage.setItem('receiptData', JSON.stringify(data));
}
/**
* Loads state from LocalStorage.
*/
function loadFromLocal() {
const raw = localStorage.getItem('receiptData');
if (raw) {
try {
const data = JSON.parse(raw);
restoreData(data);
} catch (e) {
console.error("Failed to load local data", e);
}
}
}
/**
* Generates the shareable URL based on current data.
* @returns {string} Full URL with query parameters.
*/
function generateShareUrl() {
const data = collectReceiptData();
const { signature_data, receipt_number, ...urlData } = data;
// Convert to URL params
const params = new URLSearchParams();
for (const [key, value] of Object.entries(urlData)) {
if (value) params.append(key, value);
}
return `${window.location.origin}${window.location.pathname}?${params.toString()}`;
}
/**
* Updates the input field and the browser URL without reloading.
*/
function updateLiveUrl() {
const link = generateShareUrl();
document.getElementById('share_link').value = link;
window.history.replaceState({}, '', link);
}
/**
* Restores UI from a data object.
* @param {object} data - The receipt data object.
*/
function restoreData(data) {
if (data.lang) state.lang = data.lang;
if (data.currency) state.currency = data.currency;
if (data.dateFormat) state.dateFormat = data.dateFormat;
if (data.timeFormat) state.timeFormat = data.timeFormat;
if (data.color) {
document.getElementById('colorPicker').value = data.color;
changeColor(data.color);
}
const setTxt = (id, val) => {
const el = document.getElementById(id);
if (el && val) el.innerText = val;
};
const setVal = (id, val) => {
const el = document.getElementById(id);
if (el && val) el.value = val;
};
// Restore text fields
['receipt_number', 'issuer_name', 'issuer_address', 'issuer_phone', 'issuer_email',
'received_from_name', 'received_from_address', 'received_from_phone', 'received_from_email',
'received_by', 'receipt_notes'].forEach(id => setTxt(id, data[id]));
// Restore Items
['date', 'time', 'payment_description', 'payment_amount'].forEach(id => setVal(id, data[id]));
if (data.signature_data && signaturePad) {
signaturePad.fromDataURL(data.signature_data);
if (data.signature_data) {
document.querySelector('.signature-placeholder').style.display = 'none';
}
}
}
// ==========================================================================
// 6. EXPORT & SHARE
// ==========================================================================
/**
* Collects all current receipt data into an object.
* @returns {object} Data object.
*/
function collectReceiptData() {
const getTxt = (id) => {
const el = document.getElementById(id);
return el ? el.innerText : '';
};
const getVal = (id) => {
const el = document.getElementById(id);
return el ? el.value : '';
};
return {
receipt_number: getTxt('receipt_number'),
date: getVal('date'),
time: getVal('time'),
issuer_name: getTxt('issuer_name'),
issuer_address: getTxt('issuer_address'),
issuer_phone: getTxt('issuer_phone'),
issuer_email: getTxt('issuer_email'),
received_from_name: getTxt('received_from_name'),
received_from_address: getTxt('received_from_address'),
received_from_phone: getTxt('received_from_phone'),
received_from_email: getTxt('received_from_email'),
payment_description: getVal('payment_description'),
payment_amount: getVal('payment_amount'),
receipt_notes: getTxt('receipt_notes'),
signature_data: signaturePad ? signaturePad.toDataURL() : null,
lang: state.lang,
currency: state.currency,
dateFormat: state.dateFormat,
timeFormat: state.timeFormat,
color: document.getElementById('colorPicker').value
};
}
/**
* Clears content fields but keeps configuration (Lang, Currency, etc).
*/
function clearData() {
const t = translations[state.lang] || translations['en'];
if (confirm(t.confirm_clear)) {
// 1. Clear all editable text fields (except Receipt Number, which we regen)
document.querySelectorAll('.editable-field').forEach(el => {
if (el.id !== 'receipt_number') {
el.innerText = '';
}
});
// Payment Description & Amount
document.getElementById('payment_description').value = '';
document.getElementById('payment_amount').value = '';
// 2. Reset Receipt Number
document.getElementById('receipt_number').innerText = generateReceiptNumber();
// 3. Reset Dates to Today/Now
document.getElementById('date').value = '';
document.getElementById('time').value = '';
updateDateDisplay();
updateTimeDisplay();
// 4. Update Receipt Sentence
updateReceiptSentence();
// 5. Reset Signature
if (signaturePad) {
signaturePad.clear();
const placeholder = document.querySelector('.signature-placeholder');
if (placeholder) {
placeholder.style.display = 'block';
}
}
// 6. Clear URL parameters
window.history.replaceState({}, '', window.location.pathname);
// 7. Force Save to overwrite LocalStorage with the clean state
// Note: This preserves 'state' (lang, currency, etc) because saveToLocal reads from the UI Selects which we didn't touch
saveToLocal();
}
}
/**
* Copies the current state URL to clipboard.
*/
function copyShareLink() {
saveToLocal();
const link = generateShareUrl();
navigator.clipboard.writeText(link).then(() => {
const btn = document.getElementById('btn_copy_link');
const originalContent = btn.innerHTML;
const t = translations[state.lang] || translations['en'];
btn.classList.remove('btn-dark');
btn.classList.add('btn-success');
btn.innerHTML = `<i class="bi bi-check-lg"></i> ${t.btn_link_copied}`;
document.getElementById('share_link').value = link;
setTimeout(() => {
btn.classList.remove('btn-success');
btn.classList.add('btn-dark');
btn.innerHTML = originalContent;
}, 2000);
});
}
/**
* Parses URL parameters on load.
* @returns {boolean} True if data was loaded from URL, False otherwise.
*/
function handleUrlParameters() {
const params = new URLSearchParams(window.location.search);
// We consider it "loaded from URL" if there is at least 1 item below
const keysToCheck = ['payment_description', 'issuer_name', 'received_from_name', 'payment_amount'];
const hasData = keysToCheck.some(key => params.has(key));
if (!hasData) return false;
const data = {};
for (const [key, value] of params.entries()) {
data[key] = value;
}
restoreData(data);
return true;
}
/**
* Generates and downloads the PDF using html2pdf.js.
*/
function downloadPDF() {
const element = document.getElementById('pdf_element');
// Clone DOM to clean up for print without affecting UI
const clone = element.cloneNode(true);
clone.classList.add('pdf-clean-mode');
// Inject the current share URL into the footer link
const currentUrl = generateShareUrl();
const linkElement = clone.querySelector('#pdf_recreate_link');
if (linkElement) linkElement.href = currentUrl;
// Cleanup: Remove UI-only elements
clone.querySelectorAll('.no-print').forEach(el => el.remove());
// Force Notes Wrapping
const notesField = clone.querySelector('#receipt_notes');
if (notesField) {
notesField.style.whiteSpace = "pre-wrap";
notesField.style.wordBreak = "break-word";
notesField.style.overflowWrap = "break-word";
notesField.style.width = "100%";
notesField.style.display = "block";
}
// Signature Handling (Canvas -> Image)
const originalCanvas = document.querySelector('#signature-pad canvas');
const cloneWrapper = clone.querySelector('.signature-wrapper');
// We check if we have the original canvas, the wrapper in the clone, and if a signature has been made
if (originalCanvas && cloneWrapper && signaturePad && !signaturePad.isEmpty()) {
// Converts the original signature into a Base64 image
const imgData = originalCanvas.toDataURL('image/png');
// Create an image element
const img = document.createElement('img');
img.src = imgData;
img.style.width = '100%';
img.style.height = '100%';
img.style.objectFit = 'contain'; // Ensures the signature doesn't get distorted
// Clear the cloned wrapper (remove the empty canvas and the placeholder)
cloneWrapper.innerHTML = '';
// Insert the image
cloneWrapper.appendChild(img);
} else {
// If there is no signature, we can leave it blank
if (cloneWrapper) {
cloneWrapper.innerHTML = '';
cloneWrapper.style.height = '50px';
}
}
// Cleanup: Remove empty Contact Lines (Phone/Email)
clone.querySelectorAll('.contact-line').forEach(line => {
const field = line.querySelector('.editable-field');
if (field && !field.innerText.trim()) {
line.remove();
}
});
// Cleanup: Remove empty Addresses
['issuer_address', 'received_from_address'].forEach(id => {
const field = clone.querySelector(`#${id}`);
if (field && !field.innerText.trim()) {
const parent = field.closest('.d-flex');
if (parent) parent.remove();
}
});
// Remove contenteditable to fix cursor issues
clone.querySelectorAll('[contenteditable]').forEach(el => {
el.removeAttribute('contenteditable');
});
// Handle Inputs: Convert to Text spans
clone.querySelectorAll('input').forEach(input => {
if ((input.type === 'date' || input.type === 'time') && !input.value) {
const wrapper = input.closest('.d-flex');
if (wrapper) wrapper.remove();
return;
}
const span = document.createElement('span');
span.className = input.className;
span.style.border = "none";
span.style.padding = "0";
span.style.backgroundColor = "transparent";
span.style.whiteSpace = "pre-wrap";
span.style.wordBreak = "break-word";
span.style.overflowWrap = "break-word";
span.classList.remove('form-control');
// Alignment & Display Logic
if (input.classList.contains('text-end')) {
span.style.textAlign = 'right';
span.style.display = 'block';
} else if (input.classList.contains('text-center')) {
span.style.textAlign = 'center';
} else {
span.style.textAlign = 'left';
span.style.display = 'block';
}
// Date Formatting
if (input.type === 'date') {
const rawDate = input.value;
let formattedDate = rawDate;
if (rawDate) {
const [y, m, d] = rawDate.split('-');
if (state.dateFormat === 'jp') formattedDate = `${y}-${m}-${d}`;
else if (state.dateFormat === 'us') formattedDate = `${m}/${d}/${y}`;
else if (state.dateFormat === 'br') formattedDate = `${d}/${m}/${y}`;
}
span.innerText = formattedDate;
span.style.textAlign = "right";
}
// Time Formatting
else if (input.type === 'time') {
const rawTime = input.value;
let formattedTime = rawTime;
if (rawTime && state.timeFormat === '12h') {
const [h, m] = rawTime.split(':');
const hours = parseInt(h);
const suffix = hours >= 12 ? 'PM' : 'AM';
const h12 = hours % 12 || 12;
formattedTime = `${h12}:${m} ${suffix}`;
}
span.innerText = formattedTime;
span.style.textAlign = "right";
}
// Standard Inputs
else {
span.innerText = input.value;
span.style.textAlign = input.style.textAlign || "center";
if (input.id === 'payment_description' || input.classList.contains('item-description')) {
span.style.textAlign = "left";
}
}
if (input.parentNode) input.parentNode.replaceChild(span, input);
});
// Styling Overrides for PDF
clone.style.backgroundColor = "#ffffff";
clone.style.padding = "20px";
// Append clone to body so html2canvas can parse computed styles
document.body.appendChild(clone);
// Configuration
const receiptNum = document.getElementById('receipt_number').innerText || 'receipt';
const receivedBy = document.getElementById('issuer_name').innerText.trim() || 'person';
const paymentReason = document.getElementById('payment_description').value.trim() || 'description';
const opt = {
margin: [5, 5, 5, 5],
filename: `receipt_${receiptNum}_${receivedBy}_${paymentReason}.pdf`,
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2, useCORS: true, letterRendering: true, scrollY: 0 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
html2pdf()
.set(opt)
.from(clone)
.save()
.then(() => {
document.body.removeChild(clone);
})
.catch((err) => {
console.error('PDF Generation Error:', err);
// Ensure cleanup happens even on error
if (document.body.contains(clone)) {
document.body.removeChild(clone);
}
});
}
// Public API
return { init, clearData, copyShareLink, downloadPDF };
})();
// Start App
window.addEventListener('DOMContentLoaded', receiptApp.init);