-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactor.html
More file actions
1109 lines (944 loc) · 39 KB
/
Copy pathfactor.html
File metadata and controls
1109 lines (944 loc) · 39 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
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ماشین حساب خرید</title>
<style>
:root {
direction: rtl;
}
body {
font-family: sans-serif;
margin: 0;
padding: 0;
background-color: #f5f5f5;
direction: rtl; /* اضافه کردن جهت راست به چپ */
text-align: right; /* اضافه کردن تراز راست */
}
header {
background-color: #007bff;
color: white;
padding: 1rem;
text-align: center;
font-size: 1.5rem;
position: relative; /* برای پوزیشن absolute ساعت */
}
#clock {
position: absolute;
top: 10px;
right: 40px; /* افزایش مجدد فاصله از لبه راست برای ایجاد فاصله با متن وسط */
font-size: 0.8rem;
}
header::after {
content: "ماشین حساب خرید";
display: block;
margin-top: 20px; /* فاصله بالا */
font-size: 1.3rem; /* اندازه فونت */
text-align: center;
}
main {
padding: 1rem;
}
/* استایل برای ناحیه نمایش پیام شناور */
#floatingMessageArea {
position: fixed; /* نمایش شناور بالای همه عناصر */
top: 20px; /* فاصله از بالای صفحه */
left: 50%; /* قرارگیری در وسط افقی */
transform: translateX(-50%); /* تراز کردن دقیق در وسط */
background-color: #e9ecef; /* رنگ پیشفرض */
color: #333;
padding: 0.75rem 1.5rem; /* پدینگ داخلی */
border-radius: 5px;
text-align: center;
z-index: 1010; /* بالاتر از confirm-overlay و history-overlay */
display: none; /* ابتدا مخفی است */
opacity: 0;
transition: opacity 0.5s ease-in-out; /* انیمیشن محو شدن */
max-width: 90%; /* حداکثر عرض برای موبایل */
box-shadow: 0 2px 10px rgba(0,0,0,0.1); /* سایه برای برجستگی */
}
/* استایل برای Overlay تایید سفارشی */
.confirm-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.6);
display: none; /* ابتدا مخفی است */
justify-content: center;
align-items: center;
z-index: 1000; /* بالاتر از تاریخچه */
}
.confirm-container {
background: white;
padding: 1.5rem;
border-radius: 10px;
text-align: center;
direction: rtl;
max-width: 300px; /* عرض محدود برای دیالوگ */
}
.confirm-container p {
margin-bottom: 1.5rem;
font-size: 1.1rem;
}
.confirm-buttons {
display: flex;
justify-content: space-around;
gap: 10px;
}
.confirm-buttons button {
/* استفاده از استایل دکمههای پیشفرض یا تعریف استایل جدید */
flex-grow: 1; /* دکمهها فضای موجود را پر کنند */
margin-top: 0; /* دکمههای داخل دیالوگ فاصله بالا نداشته باشند */
}
.confirm-buttons button.confirm-yes {
background-color: #dc3545; /* رنگ قرمز برای تایید حذف */
}
.confirm-buttons button.confirm-yes:hover {
background-color: #c82333;
}
.confirm-buttons button.confirm-no {
background-color: #6c757d; /* رنگ خاکستری برای انصراف */
}
.confirm-buttons button.confirm-no:hover {
background-color: #5a6268;
}
.form-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1rem;
}
input[type="text"] {
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 5px;
/* ورودیهای عددی بهتر است چپ چین و چپ به راست باشند */
}
/* استایل خاص برای ورودیهای قیمت - حالا هم راست چین هم فارسی */
input[type="text"].price-input {
direction: ltr; /* برای ورودی قیمت، راست به چپ مناسبتر است */
text-align: left; /* متن اعداد در ورودی راست به چپ، بهتر است چپ چین باشد */
}
button {
padding: 0.5rem;
border: none;
border-radius: 5px;
background-color: #007bff;
color: white;
cursor: pointer;
margin-top: 0.2rem; /* کمی فاصله بین دکمهها */
}
button:first-of-type {
margin-top: 0; /* دکمه اول فاصله بالا نداشته باشد */
}
button:hover {
background-color: #0056b3;
}
.item-list {
margin-top: 1rem;
}
.item {
display: flex;
justify-content: space-between;
background-color: white;
padding: 0.1rem;
margin-bottom: 0.1rem;
border-radius: 5px;
align-items: center;
flex-wrap: nowrap; /* قابلیت شکستن خطوط */
gap: 0.05rem; /* فاصله بین ردیفهای المانها */
overflow-x: hidden;
}
/*... سایر استایلها ...*/
/* Media Query برای صفحات با عرض کمتر از 200 پیکسل */
@media (max-width: 200px) {
.item {
flex-direction: column; /* تغییر جهت به ستونی برای نمایش در دو خط */
align-items: stretch; /* کشیدن عناصر به عرض کامل */
}
.item input[type="text"],
.item input[type="text"].price-input,
.item button {
width: 100%; /* عرض 100% برای عناصر در حالت ستونی */
margin: 0.1rem 0; /* کمی فاصله از بالا و پایین */
box-sizing: border-box; /* Padding و border جزو عرض محاسبه شوند */
}
}
/* Media Query برای صفحات با عرض بیشتر از 200 پیکسل */
@media (min-width: 201px) {
.item input[type="text"] {
flex-grow: 2;
max-width: calc(50% - 5px);
font-size: 0.8rem;
padding-left: 0;
padding-right: 0;
margin-left: 0;
margin-right: 0;
margin-top: 5px; /* اضافه کردن margin بالا */
margin-bottom: 5px; /* اضافه کردن margin پایین */
}
.item input[type="text"].price-input {
flex-grow: 1;
min-width: 60px;
max-width: calc(30% - 5px);
font-size: 0.8rem;
padding-left: 0;
padding-right: 0;
margin-left: 0;
margin-right: 0;
margin-top: 5px; /* اضافه کردن margin بالا */
margin-bottom: 5px; /* اضافه کردن margin پایین */
}
.item button {
flex-shrink: 0;
min-width: 25px;
font-size: 0.7rem;
padding: 0.15rem 0.3rem;
margin-left: 2px;
}
}
@media (min-width: 251px) {
.item input[type="text"] {
flex-grow: 1; /* اجازه رشد */
flex-basis: 50%; /* عرض پایه 50% */
max-width: none; /* حذف محدودیت حداکثر عرض */
font-size: 0.8rem;
padding-left: 0;
padding-right: 0;
margin-left: 0;
margin-right: 0;
margin-top: 5px;
margin-bottom: 5px;
}
.item input[type="text"].price-input {
flex-grow: 1; /* اجازه رشد */
flex-basis: 50%; /* عرض پایه 50% */
max-width: none; /* حذف محدودیت حداکثر عرض */
min-width: 0; /* حذف حداقل عرض */
font-size: 0.8rem;
padding-left: 0;
padding-right: 0;
margin-left: 0;
margin-right: 0;
margin-top: 5px;
margin-bottom: 5px;
}
.item button {
flex-shrink: 0;
min-width: 25px;
font-size: 0.7rem;
padding: 0.15rem 0.3rem;
margin-left: 2px;
}
}
.item input[type="text"] {
flex-grow: 1; /* اجازه رشد به ورودی نام */
margin: 0 5px;
}
.item input[type="text"]:first-child {
flex-grow: 2; /* ورودی نام کمی بزرگتر باشد */
}
.item input[type="text"]:nth-child(2) {
flex-grow: 1; /* ورودی قیمت */
min-width: 100px; /* حداقل عرض برای ورودی قیمت */
}
.item button {
flex-shrink: 1; /* دکمه حذف کوچک نشود */
margin-top: 0; /* دکمه حذف در لیست فاصله بالا نداشته باشد */
font-size: 0.5rem; /* اندازه فونت کوچکتر */
padding: 0.05rem 0.5rem; /* پدینگ کمتر */
min-width: auto;
}
@media (min-width: 200px) and (max-width: 250px) {
.item input[type="text"] {
flex-grow: 2;
max-width: 40%; /* حداکثر عرض برای نام */
font-size: 0.8rem;
padding-left: 0;
padding-right: 0;
margin-left: 0;
margin-right: 0;
margin-top: 5px;
margin-bottom: 5px;
}
.item input[type="text"].price-input {
flex-grow: 1;
max-width: 30%; /* حداکثر عرض برای قیمت */
min-width: 0;
font-size: 0.8rem;
padding-left: 0;
padding-right: 0;
margin-left: 0;
margin-right: 0;
margin-top: 5px;
margin-bottom: 5px;
}
.item button {
flex-shrink: 0;
min-width: 25px;
font-size: 0.7rem;
padding: 0.15rem 0.3rem;
margin-left: 2px;
}
}
.total {
font-weight: bold;
margin-top: 1rem;
text-align: center;
}
footer {
background-color: #007bff;
color: white;
text-align: center;
padding: 1rem;
margin-top: 2rem;
}
.history-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.6);
display: none;
justify-content: center;
align-items: center;
z-index: 999; /* کمتر از confirm-overlay */
}
.history-container {
background: white;
padding: 1rem;
border-radius: 10px;
max-height: 80vh;
overflow-y: auto;
width: 90vw;
max-width: 600px; /* محدود کردن عرض تاریخچه در صفحات بزرگتر */
direction: rtl; /* محتوای تاریخچه فارسی است */
text-align: right;
}
.history-container > button { /* دکمههای مستقیم در history-container */
margin-bottom: 1rem;
margin-left: 0.5rem; /* کمی فاصله بین دکمههای کنترل تاریخچه */
}
.history-container > button:last-of-type { /* دکمه آخر (خروجی) */
margin-left: 0;
}
.history-entry {
background: #e9ecef;
padding: 0.5rem;
margin-bottom: 0.5rem;
border-radius: 5px;
display: flex; /* برای قرار دادن دکمه حذف کنار اطلاعات */
justify-content: space-between;
align-items: center;
}
.history-entry > div { /* محتوای متنی فاکتور در یک div داخلی */
flex-grow: 1;
margin-left: 10px; /* فاصله از دکمه حذف */
}
.history-entry button { /* دکمه حذف فاکتور */
flex-shrink: 0;
background-color: #dc3545; /* رنگ قرمز برای حذف */
padding: 0.25rem 0.5rem; /* پدینگ کوچکتر برای دکمههای حذف کوچک */
}
.history-entry button:hover {
background-color: #c82333;
}
.history-entry ul {
padding-right: 20px; /* فاصله از راست برای لیست آیتمها */
text-align: right;
margin-top: 0.5rem; /* کمی فاصله از عنوان فاکتور */
margin-bottom: 0.5rem;
}
.history-entry li {
text-align: right;
}
.button-row {
display: flex;
justify-content: center; /* دکمهها در وسط */
gap: 0.1rem; /* فاصله بین دکمهها */
margin-bottom: 0.1rem; /* فاصله بین دو ردیف */
}
.button-row button {
flex: 0 0 48%; /* عرض کمی کمتر از 50% */
max-width: 48%;
box-sizing: border-box;
}
/* رنگ دکمه افزودن */
.btn-add {
background-color: #28a745; /* سبز */
}
/* رنگ دکمه حذف */
.btn-clear {
background-color: #dc3545; /* قرمز */
}
/* رنگ دکمه ایجاد فاکتور */
.btn-invoice {
background-color: #483D8B;
}
/* رنگ دکمه نمایش تاریخچه */
.btn-history {
background-color: #ffc107; /* زرد */
}
/* hover برای تمام دکمهها */
button:hover {
opacity: 0.9;
}
</style>
</head>
<body>
<header>
<div id="clock"></div>
</header>
<main>
<!-- ناحیه نمایش پیام شناور جدید -->
<div id="floatingMessageArea"></div>
<div class="form-group">
<input type="text" id="itemName" placeholder="نام جنس">
<!-- اضافه کردن کلاس price-input برای استایلدهی -->
<input type="text" id="itemPrice" class="price-input" placeholder="قیمت" oninput="liveFormatPrice(this)" inputmode="numeric">
<div class="button-row">
<button onclick="addItem()" class="btn-add">افزودن</button>
<button onclick="clearItems()" class="btn-clear">حذف لیست</button>
</div>
<div class="button-row">
<button onclick="createNewInvoice()" class="btn-invoice">فاکتور جدید</button>
<button onclick="toggleHistory()" class="btn-history">تاریخچه</button>
</div>
<!-- دکمه خروجی از اینجا به داخل history-container منتقل شده است -->
</div>
<div class="item-list" id="itemList"></div>
<div class="total" id="totalPrice">جمع کل: ۰ تومان</div>
</main>
<!-- Overlay و محتوای تایید سفارشی -->
<div class="confirm-overlay" id="customConfirmOverlay">
<div class="confirm-container" onclick="event.stopPropagation()">
<p id="customConfirmMessage"></p>
<div class="confirm-buttons">
<button id="customConfirmYes" class="confirm-yes">بله</button>
<button id="customConfirmNo" class="confirm-no">خیر</button>
</div>
</div>
</div>
<div class="history-overlay" id="historyOverlay" onclick="toggleHistory(event)">
<div class="history-container" onclick="event.stopPropagation()">
<!-- دکمه بستن -->
<button onclick="toggleHistory()">بستن ❌</button>
<!-- دکمه خروجی به اینجا منتقل شده است -->
<button onclick="exportHistory()">خروجی تاریخچه (CSV)</button>
<h3>تاریخچه فاکتورها</h3>
<div id="invoiceHistory">
<!-- فاکتورهای تاریخچه اینجا رندر میشوند -->
</div>
</div>
</div>
<footer>
برنامۀ فاکتور!
</footer>
<script>
let items = [];
let messageTimeout;
let confirmCallbacks = {
yes: null,
no: null
};
const englishDigits = '0123456789';
const persianDigits = '۰۱۲۳۴۵۶۷۸۹';
function toPersianDigits(num) {
const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return num.toString().replace(/\d/g, digit => persianDigits[digit]);
}
// تابع نمایش پیام شناور سفارشی
function displayMessage(message, duration = 1000) { // زمان نمایش پیشفرض 1 ثانیه
const messageArea = document.getElementById('floatingMessageArea');
// پاک کردن تایم اوت قبلی اگر وجود دارد
if (messageTimeout) {
clearTimeout(messageTimeout);
}
// اگر پیام خالی و زمان 0 است، بلافاصله مخفی کن (برای پاک کردن پیام هنگام بستن تاریخچه)
if (message === '' && duration === 0) {
messageArea.style.display = 'none';
messageArea.style.opacity = '0';
messageArea.innerText = '';
return;
}
messageArea.innerText = message;
messageArea.style.display = 'block'; // نمایش ناحیه پیام
// استفاده از setTimeout کوتاه برای اجازه اعمال 'display: block' قبل از تغییر opacity
setTimeout(() => {
messageArea.style.opacity = '1'; // نمایش با انیمیشن محو شونده
}, 10); // کمی تأخیر
// تنظیم تایم اوت برای مخفی کردن پیام (فقط اگر duration > 0 است)
if (duration > 0) {
messageTimeout = setTimeout(() => {
messageArea.style.opacity = '0'; // شروع انیمیشن مخفی شدن
// بعد از اتمام انیمیشن، display را به none تغییر دهید
setTimeout(() => {
messageArea.style.display = 'none';
messageArea.innerText = ''; // پاک کردن متن
}, 500); // مدت زمان باید با transition-duration در CSS همخوانی داشته باشد (0.5s)
}, duration);
}
}
// تابع نمایش دیالوگ تایید سفارشی
function showConfirmDialog(message, onYes, onNo) {
const overlay = document.getElementById('customConfirmOverlay');
const messageElement = document.getElementById('customConfirmMessage');
const yesBtn = document.getElementById('customConfirmYes');
const noBtn = document.getElementById('customConfirmNo');
messageElement.innerText = message;
// تنظیم رویدادها مستقیم
yesBtn.onclick = () => {
hideConfirmDialog();
if (onYes && typeof onYes === 'function') {
onYes(); // ← اجرا مستقیم callback
}
};
noBtn.onclick = () => {
hideConfirmDialog();
if (onNo && typeof onNo === 'function') {
onNo(); // ← اجرا مستقیم callback
}
};
// بستن با کلیک روی Overlay (اگر روی Container کلیک نشود)
overlay.onclick = (event) => {
if (event.target === overlay) {
hideConfirmDialog();
if (onNo && typeof onNo === 'function') {
onNo();
}
}
};
overlay.style.display = 'flex';
}
// تابع مخفی کردن دیالوگ تایید سفارشی
function hideConfirmDialog() {
const overlay = document.getElementById('customConfirmOverlay');
overlay.style.display = 'none';
// پاک کردن callback ها
confirmCallbacks.yes = null;
confirmCallbacks.no = null;
// پاک کردن شنوندهها برای جلوگیری از رفرنسهای رها شده
document.getElementById('customConfirmYes').onclick = null;
document.getElementById('customConfirmNo').onclick = null;
document.getElementById('customConfirmOverlay').onclick = null; // پاک کردن شنونده overlay
}
function formatNumberForInput(num) {
if (num === 0) return '0';
return num.toLocaleString('en-US');
}
function formatNumberForDisplay(num) {
return num.toLocaleString('en-US', { useGrouping: true });
}
function parseFormattedNumber(str) {
const raw = str.replace(/[^\d]/g, '');
return parseInt(raw) || 0;
}
function addItem() {
const nameInput = document.getElementById('itemName');
const priceInput = document.getElementById('itemPrice');
const name = nameInput.value.trim();
const price = parseFormattedNumber(priceInput.value);
const errors = validateInput(name, price);
if (errors.length > 0) {
displayMessage(errors.join(' و '), 2000);
priceInput.focus(); // Focus on price since that's the only required field
return;
}
// Use default name if empty
items.push({ name: name || 'کالا', price, quantity: 1 });
nameInput.value = '';
priceInput.value = '';
nameInput.focus();
renderItems();
displayMessage("کالا به لیست اضافه شد.", 1000);
}
// تابع حذف آیتم
function removeItem(index) {
// نیازی به تایید برای حذف یک آیتم نیست
items.splice(index, 1);
renderItems();
displayMessage("کالا از لیست حذف شد.", 1000); // پیام شناور 1 ثانیهای
}
function updateItemName(index, value) {
items[index].name = value || '—';
}
function validateInput(name, price) {
const errors = [];
// Remove name validation - name is now optional
// if (!name || name.trim() === '') {
// errors.push('نام کالا الزامی است');
// }
if (!price || price <= 0) {
errors.push('قیمت باید بزرگتر از صفر باشد');
}
return errors;
}
// تابع اصلاح شده updateItemPrice برای مدیریت تبدیل و فرمت فارسی
function updateItemPrice(index, input) {
const currentValue = input.value;
const rawDigitsOnly = currentValue.replace(/[^\d]/g, '');
// اگر هیچ عددی وجود نداشته باشد، قیمت را صفر قرار نده، بلکه خالی کن
let price = rawDigitsOnly === '' ? 0 : parseInt(rawDigitsOnly);
items[index].price = price;
// فقط در صورت وجود رقم، فرمت کن، در غیر این صورت خالی کن
if (rawDigitsOnly === '') {
input.value = '';
} else {
const formattedValue = formatNumberForInput(price);
const cursorPosition = input.selectionStart;
const lengthDiff = formattedValue.length - currentValue.length;
input.value = formattedValue;
input.setSelectionRange(cursorPosition + lengthDiff, cursorPosition + lengthDiff);
}
updateTotal();
}
function liveFormatPrice(input) {
const currentValue = input.value;
const rawDigitsOnly = currentValue.replace(/[^\d]/g, '');
if (rawDigitsOnly === '') {
input.value = '';
return;
}
const price = parseInt(rawDigitsOnly);
if (!isNaN(price)) {
const formattedValue = formatNumberForInput(price);
const cursorPosition = input.selectionStart;
const lengthDiff = formattedValue.length - currentValue.length;
input.value = formattedValue;
input.setSelectionRange(cursorPosition + lengthDiff, cursorPosition + lengthDiff);
}
}
function updateQuantity(index, delta) {
const newQuantity = (items[index].quantity || 1) + delta;
if (newQuantity > 0) {
items[index].quantity = newQuantity;
renderItems();
displayMessage(`تعداد به ${toPersianDigits(newQuantity)} تغییر کرد.`, 1000);
}
}
function updateTotal() {
const total = items.reduce((sum, item) => sum + (item.price * (item.quantity || 1)), 0);
document.getElementById('totalPrice').innerText = `جمع کل: ${formatNumberForDisplay(total)} تومان`;
}
function renderItems() {
const list = document.getElementById('itemList');
list.innerHTML = ''; // **اطمینان از پاک شدن کامل لیست قبل از رندر مجدد**
items.forEach((item, index) => {
const div = document.createElement('div');
div.className = 'item';
div.innerHTML = `
<input type="text" value="${item.name}" onchange="updateItemName(${index}, this.value)" style="flex: 2; font-size: 0.9rem; padding: 0.05rem;">
<input type="text" class="price-input" value="${formatNumberForInput(item.price)}" oninput="updateItemPrice(${index}, this)" inputmode="numeric" style="flex: 1; min-width: 80px; font-size: 0.9rem; padding: 0.05rem;">
<div style="display: flex; align-items: center; gap: 2px; margin: 0 4px;">
<button onclick="updateQuantity(${index}, -1)" style="padding: 0.05rem 0.3rem; font-size: 0.8rem;">-</button>
<span style="min-width: 20px; text-align: center; font-size: 0.8rem;">${toPersianDigits(item.quantity || 1)}</span>
<button onclick="updateQuantity(${index}, 1)" style="padding: 0.05rem 0.3rem; font-size: 0.8rem;">+</button>
</div>
<button onclick="removeItem(${index})" style="flex-shrink: 0; min-width: 30px; font-size: 0.9rem; padding: 0.05rem 0.1rem;">❌</button>
`;
list.appendChild(div);
});
updateTotal();
}
// تابع اصلاح شده clearItems با استفاده از دیالوگ تایید سفارشی
function clearItems() {
if (items.length === 0) {
displayMessage("لیست خالی است.", 2000);
return;
}
showConfirmDialog("آیا مطمئنید که میخواهید همه آیتمهای فعلی را حذف کنید؟", () => {
items = [];
renderItems(); // ← فراخوانی renderItems برای نمایش لیست خالی
displayMessage("لیست اجناس حذف شد.", 2000);
});
}
// تابع createNewInvoice: ذخیره فاکتور فعلی و شروع فاکتور جدید (بدون تایید)
function createNewInvoice() {
if (items.length === 0) {
displayMessage("لیست خالیه، برای فاکتور جدید، جنس ها را اضافه کنید.", 2000);
return;
}
const now = new Date();
const history = JSON.parse(localStorage.getItem('invoiceHistory') || '[]');
const currentTotal = items.reduce((sum, i) => sum + (i.price * (i.quantity || 1)), 0);
// Save items with both unit price and total price
const itemsWithPrices = items.map(item => ({
name: item.name,
unitPrice: item.price, // قیمت واحد
quantity: item.quantity || 1,
totalPrice: item.price * (item.quantity || 1) // قیمت کل
}));
history.push({
date: now.toLocaleDateString('fa-IR'),
time: now.toLocaleTimeString('fa-IR'),
items: itemsWithPrices,
total: currentTotal
});
localStorage.setItem('invoiceHistory', JSON.stringify(history));
items = [];
renderItems();
displayMessage(`فاکتور ذخیره شد.`, 3000);
}
// تابع حذف یک فاکتور از تاریخچه (با استفاده از دیالوگ تایید سفارشی)
function deleteHistoryEntry(index) {
// تاریخچه را داخل تابع callback بخوانید تا همیشه آخرین نسخه را داشته باشید
showConfirmDialog("آیا مطمئنید که میخواهید این فاکتور را از تاریخچه حذف کنید؟", () => {
// تابع callback برای 'بله'
const history = JSON.parse(localStorage.getItem('invoiceHistory') || '[]'); // **خواندن مجدد تاریخچه**
if (index < 0 || index >= history.length) {
displayMessage("خطا در حذف فاکتور: شاخص نامعتبر است.", 3000);
renderHistory(); // رندر مجدد احتیاطی در صورت خطا
return;
}
history.splice(index, 1); // حذف فاکتور در شاخص مشخص شده
localStorage.setItem('invoiceHistory', JSON.stringify(history)); // بهروزرسانی localStorage
renderHistory(); // **فراخوانی renderHistory برای بهروزرسانی نمایش**
displayMessage("فاکتور از تاریخچه حذف شد.", 2000);
});
}
// تابع برای خروجی گرفتن از تاریخچه به صورت CSV
function exportHistory() {
const history = JSON.parse(localStorage.getItem('invoiceHistory') || '[]');
if (history.length === 0) {
displayMessage("تاریخچهای برای خروجی گرفتن وجود ندارد.", 2000);
return;
}
// سربرگ CSV - ستونها باید سازگار با نرمافزارهای صفحه گسترده باشند (اعداد انگلیسی)
let csvContent = "تاریخ,زمان,جمع کل فاکتور (تومان),نام کالا,قیمت کالا (تومان)\n";
history.forEach(entry => {
// تاریخ و زمان را برای CSV شاید بهتر باشد به فرمت انگلیسی درآورد
const invoiceDate = entry.date;
// زمان را هم به فرمت 24 ساعته و انگلیسی
const invoiceTime = new Date('1970/01/01 ' + entry.time.replace(/ص|ق.ظ|ب.ظ/g, '') // حذف عبارات فارسی زمان
.replace(':', ':')).toLocaleTimeString('en-US', { hour12: false }).replace(/:/g, '-'); // HH-MM-SS
const invoiceTotal = entry.total; // عدد خام (انگلیسی) برای CSV
entry.items.forEach(item => {
// برای اطمینان از اینکه نام کالا اگر شامل کاما یا کوتیشن بود مشکلی ایجاد نکند
const itemName = `"${item.name.replace(/"/g, '""')}"`; // Double quotes inside field are escaped by double double quotes
const itemPrice = item.price; // عدد خام (انگلیسی) برای CSV
csvContent += `${invoiceDate},${invoiceTime},${invoiceTotal},${itemName},${itemPrice}\n`;
});
});
// BOM برای اطمینان از نمایش صحیح کاراکترهای فارسی در اکسل
const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
// نام فایل CSV شامل تاریخ و زمان فعلی باشد (با ارقام انگلیسی)
const now = new Date();
const fileNameDate = now.toISOString().slice(0,10); // YYYY-MM-DD
const fileNameTime = now.toLocaleTimeString('en-US', { hour12: false }).replace(/:/g, '-'); // HH-MM-SS
link.setAttribute('download', `invoice_history_${fileNameDate}_${fileNameTime}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
// پیام موفقیت در دانلود نیازی نیست، مرورگر خودش پیام میدهد یا فایل را نمایش میدهد.
} else {
// فالبک برای مرورگرهای قدیمیتر
displayMessage("مرورگر شما از دانلود مستقیم فایل پشتیبانی نمیکند. محتوا را کپی کنید:\n\n" + csvContent, 10000); // پیام با مدت زمان طولانیتر
}
}
// تابع رندر کردن تاریخچه با دکمه حذف برای هر آیتم
function renderHistory() {
const historyDiv = document.getElementById('invoiceHistory');
historyDiv.innerHTML = '';
const history = JSON.parse(localStorage.getItem('invoiceHistory') || '[]');
if (history.length === 0) {
historyDiv.innerHTML = '<p style="text-align: center;">تاریخچهای وجود ندارد.</p>';
return;
}
// نمایش تاریخچه از جدیدترین به قدیمیترین
// توجه: هنگام رندر کردن معکوس، باید شاخص اصلی را برای تابع حذف ذخیره کنیم
history.slice().reverse().forEach((entry, reversedIndex) => {
// محاسبه شاخص اصلی در آرایه history قبل از معکوس شدن
const originalIndex = history.length - 1 - reversedIndex;
const div = document.createElement('div');
div.className = 'history-entry';
div.innerHTML = `
<div> <!-- محتوای متنی فاکتور در یک div داخلی -->
<strong>${entry.date} - ${entry.time}</strong><br>
<ul>
${entry.items.map(i =>
`<li>${i.name} (${toPersianDigits(i.quantity)} عدد × ${formatNumberForDisplay(i.unitPrice)} = ${formatNumberForDisplay(i.totalPrice)} تومان)</li>`
).join('')}
</ul>
جمع کل: ${formatNumberForDisplay(entry.total)} تومان
</div>
<!-- دکمه حذف با ارسال شاخص اصلی -->
<button onclick="deleteHistoryEntry(${originalIndex})">حذف</button>
`;
historyDiv.appendChild(div);
});
}
function toggleHistory(event) {
const overlay = document.getElementById('historyOverlay');
// جلوگیری از بسته شدن با کلیک داخل محتوا
if (event && event.target !== overlay && event.target.parentNode !== document.getElementById('historyOverlay')) {
return;
}
// مطمئن میشویم که دیالوگ تایید سفارشی باز نیست
if (document.getElementById('customConfirmOverlay').style.display === 'flex') {
return;
}
if (overlay.style.display === 'flex') {
overlay.style.display = 'none';
// هنگام بسته شدن تاریخچه، پیامهای شناور را پاک کنید
displayMessage('', 0); // پیام خالی با زمان 0 برای پاک کردن فوری
} else {
overlay.style.display = 'flex';
renderHistory(); // فقط هنگام باز شدن، تاریخچه را رندر کن
}
}
function getLocalizedDate(date) {
if (isPersianLocaleSupported()) {
return date.toLocaleDateString('fa-IR');
} else {
const pDate = toPersianDate(date);
return formatPersianDate(pDate);
}
}
function updateClock() {
const now = new Date();
const daysOfWeek = ["یکشنبه", "دوشنبه", "سهشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"]; // آرایه نام روزهای هفته
const dayOfWeek = daysOfWeek[now.getDay()]; // بدست آوردن نام روز هفته
const time = now.toLocaleTimeString('fa-IR');
const date = now.toLocaleDateString('fa-IR');
document.getElementById('clock').innerText = `${dayOfWeek}، ${date} - ${time}`; // اضافه کردن نام روز هفته به خروجی
}
// رویداد DOMContentLoaded برای اجرای کد پس از بارگذاری کامل DOM
document.addEventListener('DOMContentLoaded', () => {
renderItems();
updateClock();
setInterval(updateClock, 1000);
// افزودن شنونده رویداد برای کلید Escape برای بستن overlay ها
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
// اگر دیالوگ تایید باز است، آن را ببند
if (document.getElementById('customConfirmOverlay').style.display === 'flex') {
hideConfirmDialog();
// اگر callback برای No وجود دارد، آن را اجرا کن (رفتار پیشفرض Esc مانند No است)
// این بخش نیازمند اصلاح در منطق callback ها است یا باید آن را نادیده گرفت
// برای سادگی فعلا فقط دیالوگ را میبندیم.
}
// اگر تاریخچه باز است، آن را ببند
else if (document.getElementById('historyOverlay').style.display === 'flex') {
toggleHistory();
}
}
});
});
function toPersianDate(date) {
// Simplified and more accurate Persian date conversion
const jalaali = require('jalaali-js'); // You might want to include this library or use a simpler conversion
// For now, using a basic conversion approach
const gregorian = new Date(date);
const year = gregorian.getFullYear();
const month = gregorian.getMonth() + 1;
const day = gregorian.getDate();
// Basic Gregorian to Persian conversion (approximate)
const persianYear = year - 621;
return {
year: persianYear,
month: month,
day: day
};
}
function formatPersianDate(pDate) {