-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathCode.gs
More file actions
1457 lines (1205 loc) · 46.9 KB
/
Code.gs
File metadata and controls
1457 lines (1205 loc) · 46.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
var token = PropertiesService.getScriptProperties().getProperty('BOT_TOKEN');
var gemini_token = PropertiesService.getScriptProperties().getProperty('GEMINI_TOKEN');
var main_sheet = PropertiesService.getScriptProperties().getProperty('ID_MAINSHEET');
function getApiKeys() {
var keysString = PropertiesService.getScriptProperties().getProperty('GEMINI_LISTKEY');
if (!keysString) return [];
return JSON.parse(keysString);
}
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "CHANGE_YOU_URL_APPSCRIP";
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
}
function formatNumberWithSeparator(number) {
return number
.toString()
}
function addTransactionData(userId, date, description, amount, allocation, type) {
var sheet = getSheet(userId);
sheet.appendRow([date, description, amount, allocation, type]);
}
function sendText(chatId, text, keyBoard) {
var formattedText = formatNumberWithSeparator(text);
var data = {
method: "post",
payload: {
method: "sendMessage",
chat_id: String(chatId),
text: formattedText,
parse_mode: "HTML",
reply_markup: JSON.stringify(keyBoard)
}
};
UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
}
var keyBoard = {
"inline_keyboard": [
[
{
text: 'Xem Tổng Chi Tiêu',
callback_data: 'totalchi'
}
],
[
{
text: 'Xem Tổng Thu Nhập',
callback_data: 'totalthunhap'
}
],
[
{
text: 'Xem Số Tiền Hiện Tại',
callback_data: 'currentbalance'
}
],
[
{
text: 'Xem Chi Tiết Các Hũ',
callback_data: 'getTotalAllocationBalances'
}
],
[
{
text: 'Xem Lịch Sử Thu/Chi',
callback_data: 'history'
}
],
[
{
text: 'Open App',
web_app: {
url: 'https://moneynebot.blogspot.com/?m=1'
}
}
],
[
{
text: 'Connect Email',
callback_data: 'connect_email'
}
]
]
};
var menuchi = {
"inline_keyboard": [
[
{
text: 'Xem Tổng Thu Nhập',
callback_data: 'totalthunhap'
},
{
text: 'Xem Chi Tiết Các Hũ',
callback_data: 'getTotalAllocationBalances'
}
]
]
};
function doPost(e) {
var contents = JSON.parse(e.postData.contents);
var chatId;
var userName;
if (contents.callback_query) {
chatId = contents.callback_query.from.id;
userName = contents.callback_query.from.first_name;
var data = contents.callback_query.data;
if (data === 'connect_email') {
sendText(chatId, "Vui lòng nhập email của bạn:");
return;
} else if (data.startsWith('bank_')) {
var bankName = data.split('_')[1];
saveBankToSheet(chatId, bankName);
sendText(chatId, "Ngân hàng của bạn đã được kết nối thành công: " + bankName);
return;
}
} else if (contents.message) {
chatId = contents.message.chat.id;
userName = contents.message.from.first_name;
var text = contents.message.text;
if (contents.message.voice) {
var fileId = contents.message.voice.file_id;
processVoiceMessage(fileId, chatId);
return;
}
if (isValidEmail(text)) {
var userId = chatId;
saveEmailToSheet(userId, text);
sendBankOptions(chatId);
return;
}
}
var allocations = [
'Thiết yếu',
'Giáo dục',
'Tiết kiệm',
'Đầu tư',
'Tiêu dùng',
'Khác'
];
if (contents.callback_query) {
var id_callback = chatId;
var data = contents.callback_query.data;
if (data === 'totalchi') {
var userId = chatId;
var totalExpenses = getTotalAmountByType(userId, "ChiTieu");
sendText(id_callback, "Tổng chi tiêu của bạn là: " + totalExpenses.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","), menuchi);
} else if (data === 'totalthunhap') {
var userId = chatId;
sendTotalIncomeSummary(id_callback, userId);
} else if (data === 'currentbalance') {
var userId = chatId;
var currentBalance = getCurrentBalance(userId);
sendText(id_callback, "Số tiền hiện tại của bạn là: " + currentBalance.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
} else if (data === 'getTotalAllocationBalances') {
var userId = chatId;
sendTotalPhanboSummary(id_callback, userId);
} else if (data === 'history') {
var userId = chatId;
sendTransactionHistory(id_callback, userId);
}
} else if (contents.message) {
var id_message = chatId;
var text = contents.message.text;
if (text === '/clearthunhap') {
var userId = chatId;
var sheet = getSheet(userId);
var data = sheet
.getDataRange()
.getValues();
var newData = [];
for (var i = 0; i < data.length; i++) {
if (data[i][4] !== "ThuNhap") {
newData.push(data[i]);
}
}
sheet
.getDataRange()
.clearContent();
if (newData.length > 0) {
sheet
.getRange(1, 1, newData.length, newData[0].length)
.setValues(newData);
}
sendText(chatId, "Đã xoá các thu nhập.");
return;
} else if (text === '/clearchitieu') {
var userId = chatId;
var sheet = getSheet(userId);
var data = sheet
.getDataRange()
.getValues();
var newData = [];
for (var i = 0; i < data.length; i++) {
if (data[i][4] !== "ChiTieu") {
newData.push(data[i]);
}
}
sheet
.getDataRange()
.clearContent();
if (newData.length > 0) {
sheet
.getRange(1, 1, newData.length, newData[0].length)
.setValues(newData);
}
sendText(chatId, "Đã xoá các giao dịch chi tiêu.");
return;
} else if (text === '/clearall') {
var userId = chatId;
var sheet = getSheet(userId);
var data = sheet
.getDataRange()
.getValues();
var newData = [];
for (var i = 0; i < data.length; i++) {
if (data[i][4] !== "ChiTieu" && data[i][4] !== "ThuNhap") {
newData.push(data[i]);
}
}
sheet
.getDataRange()
.clearContent();
if (newData.length > 0) {
sheet
.getRange(1, 1, newData.length, newData[0].length)
.setValues(newData);
}
sendText(chatId, "Đã xoá các giao dịch chi tiêu và thu nhập.");
return;
} else if (text.includes("+")) {
var parts = text.split(" + ");
if (parts.length >= 2) {
var itemWithAllocation = parts[0].trim();
var amountWithDate = parts[1].trim();
var allocationAndDate = parts
.slice(2)
.join(" ")
.trim() || "Thiết yếu";
var allocationParts = itemWithAllocation.split("+");
var currentDate = new Date(year, month, day);
var date;
if (allocationParts.length >= 2) {
item = allocationParts[0].trim();
allocationAndDate = allocationParts[1].trim();
} else {
item = itemWithAllocation;
}
var dateRegex = /(\d{1,2}[/-]\d{1,2}[/-]\d{4})/;
var dateMatch = allocationAndDate.match(dateRegex);
if (dateMatch) {
var dateParts = dateMatch[0].split(/[/-]/);
var day = parseInt(dateParts[0]);
var month = parseInt(dateParts[1]) - 1;
var year = parseInt(dateParts[2]);
date = new Date(year, month, day);
allocationAndDate = allocationAndDate
.replace(dateRegex, "")
.trim();
} else {
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth();
var year = currentDate.getFullYear();
date = new Date(year, month, day);
}
var amount = parseFloat(amountWithDate);
var allocation = allocationAndDate || "Thiết yếu";
var type = "ThuNhap";
if (!isNaN(amount) && allocations.includes(allocation)) {
addTransactionData(chatId, date, item, amount, allocation, type);
sendText(
id_message,
"Bạn đã thu nhâp: " + item + " " + amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " vào ngày " + formatDate(date) + " và phân bổ thu nhập của bạn vào hũ " +
allocation + "."
);
return;
} else {
sendText(
id_message,
"Vui lòng cung cấp thông tin thu nhập và số tiền theo cú pháp lệnh sau:\n<b>1. Thêm thông tin Thu nhập:</b>\n - <code>nội dung + số tiền</code>\n\n<b>2. Thêm thông tin Thu nhập vào ngày/tháng/năm cụ thể:</b>\n - <code>nội dung + số tiền + ngày/tháng/năm</code>\n\n<b>3. Thêm thông tin Thu nhập vào ngày/tháng/năm cụ thể và Hũ cụ thể:</b>\n - <code>nội dung + số tiền + ngày/tháng/năm + hũ (Thiết yếu, Giáo dục, Tiết kiệm, Đầu tư, Tiêu dùng, Khác)</code>"
); return;
}
} else {
sendText(
id_message,
"Vui lòng cung cấp thông tin thu nhập và số tiền theo cú pháp lệnh sau:\n<b>1. Thêm thông tin Thu nhập:</b>\n - <code>nội dung + số tiền</code>\n\n<b>2. Thêm thông tin Thu nhập vào ngày/tháng/năm cụ thể:</b>\n - <code>nội dung + số tiền + ngày/tháng/năm</code>\n\n<b>3. Thêm thông tin Thu nhập vào ngày/tháng/năm cụ thể và Hũ cụ thể:</b>\n - <code>nội dung + số tiền + ngày/tháng/năm + hũ (Thiết yếu, Giáo dục, Tiết kiệm, Đầu tư, Tiêu dùng, Khác)</code>"
); return;
}
} else if (text.includes("-")) {
var parts = text.split(" - ");
if (parts.length >= 2) {
var itemWithAllocation = parts[0].trim();
var amountWithDate = parts[1].trim();
var allocationAndDate = parts
.slice(2)
.join(" ")
.trim() || "Thiết yếu";
var allocationParts = itemWithAllocation.split("-");
var currentDate = new Date(year, month, day);
var date;
if (allocationParts.length >= 2) {
item = allocationParts[0].trim();
allocationAndDate = allocationParts[1].trim();
} else {
item = itemWithAllocation;
}
var dateRegex = /(\d{1,2}[/-]\d{1,2}[/-]\d{4})/;
var dateMatch = allocationAndDate.match(dateRegex);
if (dateMatch) {
var dateParts = dateMatch[0].split(/[/-]/);
var day = parseInt(dateParts[0]);
var month = parseInt(dateParts[1]) - 1;
var year = parseInt(dateParts[2]);
date = new Date(year, month, day);
allocationAndDate = allocationAndDate
.replace(dateRegex, "")
.trim();
} else {
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth();
var year = currentDate.getFullYear();
date = new Date(year, month, day);
}
var amount = parseFloat(amountWithDate)
var allocation = allocationAndDate || "Thiết yếu";
var type = "ChiTieu";
if (!isNaN(amount) && allocations.includes(allocation)) {
addTransactionData(chatId, date, item, amount, allocation, type);
sendText(
id_message,
"Bạn đã chi tiêu: " + item + " " + amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " vào ngày " + formatDate(date) + " và phân bổ chi tiêu của bạn vào hũ " +
allocation + "."
);
return;
} else {
sendText(
id_message,
"Vui lòng cung cấp thông tin Chi tiêu và số tiền theo cú pháp lệnh sau:\n<b>1. Thêm thông tin Chi tiêu:</b>\n - <code>nội dung - số tiền</code>\n\n<b>2. Thêm thông tin Chi tiêu vào ngày/tháng/năm cụ thể:</b>\n - <code>nội dung - số tiền - ngày/tháng/năm</code>\n\n<b>3. Thêm thông tin Chi tiêu vào ngày/tháng/năm cụ thể và Hũ cụ thể:</b>\n - <code>nội dung - số tiền - ngày/tháng/năm - hũ (Thiết yếu, Giáo dục, Tiết kiệm, Đầu tư, Tiêu dùng, Khác)</code>"
); return;
}
} else {
sendText(
id_message,
"Vui lòng cung cấp thông tin Chi tiêu và số tiền theo cú pháp lệnh sau:\n<b>1. Thêm thông tin Chi tiêu:</b>\n - <code>nội dung - số tiền</code>\n\n<b>2. Thêm thông tin Chi tiêu vào ngày/tháng/năm cụ thể:</b>\n - <code>nội dung - số tiền - ngày/tháng/năm</code>\n\n<b>3. Thêm thông tin Chi tiêu vào ngày/tháng/năm cụ thể và Hũ cụ thể:</b>\n - <code>nội dung - số tiền - ngày/tháng/năm - hũ (Thiết yếu, Giáo dục, Tiết kiệm, Đầu tư, Tiêu dùng, Khác)</code>"
); return;
}
}
if (text.startsWith("/history")) {
var parts = text.split(" ");
if (parts.length >= 2) {
var historyType = parts[1].toLowerCase();
var userId = chatId;
var startDate;
var endDate;
if (historyType === "today") {
var today = new Date();
startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
} else if (historyType === "week") {
var today = new Date();
var startOfWeek = today.getDate() - today.getDay();
startDate = new Date(today.getFullYear(), today.getMonth(), startOfWeek);
endDate = new Date(today.getFullYear(), today.getMonth(), startOfWeek + 7);
} else if (text.startsWith("/history w")) {
var parts = text.split(" ");
if (parts.length === 3 && parts[1] === "w") {
var weekNumber = parseInt(parts[2]);
if (!isNaN(weekNumber) && weekNumber >= 1 && weekNumber <= 4) {
var currentDate = new Date();
var startDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), (weekNumber - 1) * 7 + 1);
var endDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), weekNumber * 7 + 1);
sendTransactionHistoryByDateRange(chatId, userId, startDate, endDate);
return;
}
}
sendText(id_message, "Vui lòng cung cấp tuần hợp lệ, bạn có thể thử /history w 1, /history w 2, /history w 3, /history w 4.");
} else if (text.startsWith("/history month")) {
var parts = text.split(" ");
if (parts.length === 3 && parts[1] === "month") {
var monthYearStr = parts[2];
var [month, year] = monthYearStr.split("/");
if (month && year) {
month = parseInt(month);
year = parseInt(year);
if (!isNaN(month) && !isNaN(year)) {
var startDate = new Date(year, month - 1, 1);
var endDate = new Date(year, month, 0);
}
} else {
sendText(
id_message,
"Vui lòng cung cấp tháng hợp lệ, ví dụ: /history month MM/YYYY"
);
return;
}
}
} else if (text.startsWith("/history year")) {
var parts = text.split(" ");
if (parts.length === 3 && parts[1] === "year") {
var year = parseInt(parts[2]);
if (!isNaN(year)) {
var startDate = new Date(year, 0, 1);
var endDate = new Date(year + 1, 0, 1);
}
} else {
sendText(
id_message,
"Vui lòng cung cấp năm hợp lệ, ví dụ: /history year YYYY"
);
return;
}
} else if (parts.length >= 3 && parts[1] === 'd') {
var dateParts = parts
.slice(2)
.join(" ")
.split("/");
if (dateParts.length === 3) {
var year = parseInt(dateParts[2]);
var month = parseInt(dateParts[1]) - 1;
var day = parseInt(dateParts[0]);
startDate = new Date(year, month, day);
endDate = new Date(year, month, day + 1);
} else {
sendText(
id_message,
"Vui lòng cung cấp ngày/tháng/năm hợp lệ, ví dụ: /history d DD/MM/YYYY"
);
return;
}
} else {
sendText(
id_message,
'Lệnh không hợp lệ. Hãy sử dụng các lệnh sau:\n <b>1. Lịch sử Thu/Chi hôm nay:</b>\n - <code>/history today</code>\n\n<b>2. Lịch sử Thu/Chi ngày cụ thể:</b>\n - <code>/history d ngày/tháng/năm</code>\n\n<b>3. Lịch sử Thu/Chi trong tuần:</b>\n - <code>/history week</code>\n\n<b>4. Lịch sử Thu/Chi trong tuần cụ thể:</b>\n - <code>/history w 1 (2, 3, 4)</code>\n\n<b>5. Lịch sử Thu/Chi tháng:</b>\n - <code>/history month tháng/năm</code>\n\n<b>6. Lịch sử Thu/Chi năm:</b>\n - <code>/history year năm</code>\n'
); return;
}
sendTransactionHistoryByDateRange(id_message, userId, startDate, endDate);
} else {
sendText(
id_message,
'Hãy sử dụng các lệnh sau:\n <b>1. Lịch sử Thu/Chi hôm nay:</b>\n - <code>/history today</code>\n\n<b>2. Lịch sử Thu/Chi ngày cụ thể:</b>\n - <code>/history d ngày/tháng/năm</code>\n\n<b>3. Lịch sử Thu/Chi trong tuần:</b>\n - <code>/history week</code>\n\n<b>4. Lịch sử Thu/Chi trong tuần cụ thể:</b>\n - <code>/history w 1 (2, 3, 4)</code>\n\n<b>5. Lịch sử Thu/Chi tháng:</b>\n - <code>/history month tháng/năm</code>\n\n<b>6. Lịch sử Thu/Chi năm:</b>\n - <code>/history year năm</code>\n'
); return;
}
} else if (text === '/start') {
sendText(id_message, 'Xin chào ' + userName + '! Money Nè là Bot giúp bạn quản lý Thu/Chi, thu nhập có thể phân bổ ra các hũ và còn các tính năng khác nữa. Để biết thêm chi tiết về các lệnh, bạn có thể sử dụng lệnh /help hoặc cũng có thể xem menu Money Nè tại đây.',
keyBoard
);
}
else if (text === '/menu') {
sendText(id_message, 'Xin chào ' + userName + '! Menu Money Nè tại đây.',
keyBoard
);
} else if (text.startsWith('/del')) {
var userId = chatId;
var transactionId;
var menuthuchi = {
"inline_keyboard": [
[
{
text: 'Xem số thứ tự Thu/Chi',
callback_data: 'history'
}
]
]
};
var parts = text.split(' ');
for (var i = 1; i < parts.length; i++) {
var part = parts[i];
if (!isNaN(parseInt(part))) {
transactionId = parseInt(part);
break;
}
}
if (transactionId !== undefined) {
var success = deleteTransactionByRow(userId, transactionId);
if (success) {
sendText(id_message, 'Đã xoá thành công Thu/Chi có số thứ tự: ' + transactionId);
} else {
sendText(id_message, 'Không tìm thấy thu/chi có số thứ tự ' + transactionId);
}
} else {
sendText(id_message, 'Vui lòng cung cấp số thứ tự của thu/chi cần xoá vào lệnh ví dụ bên dưới.\n Ví dụ: <code>/del số_thứ_tự</code>', menuthuchi);
}
return;
} else if (text === '/help') {
sendText(id_message, `Xin chào ` + userName + `! Dưới đây là cách bạn có thể gửi thông tin về Chi tiêu và Thu nhập của bạn cũng như xem lịch sử chi tiêu:
<b>💳 Chi tiêu:</b>
1. Thêm thông tin Chi tiêu:
\<code>nội dung - số tiền\</code>
2. Thêm thông tin Chi tiêu vào ngày/tháng/năm cụ thể:
\<code>nội dung - số tiền - ngày/tháng/năm\</code>
3. Thêm thông tin Chi tiêu vào ngày/tháng/năm cụ thể và Hũ cụ thể:
\<code>nội dung - số tiền - ngày/tháng/năm - hũ (Thiết yếu, Giáo dục, Tiết kiệm, Đầu tư, Tiêu dùng, Khác)\</code>
<b>💰 Thu nhập:</b>
1. Thêm thông tin Thu nhập:
\<code>nội dung + số tiền\</code>
2. Thêm thông tin Thu nhập vào ngày/tháng/năm cụ thể:
\<code>nội dung + số tiền + ngày/tháng/năm\</code>
3. Thêm thông tin Thu nhập vào ngày/tháng/năm cụ thể và Hũ cụ thể:
\<code>nội dung + số tiền + ngày/tháng/năm + hũ (Thiết yếu, Giáo dục, Tiết kiệm, Đầu tư, Tiêu dùng, Khác)\</code>
<b>📅 Lịch sử Thu/Chi:</b>
1. Lịch sử Thu/Chi hôm nay:
\<code>/history today\</code>
2. Lịch sử Thu/Chi ngày cụ thể:
\<code>/history d ngày/tháng/năm\</code>
3. Lịch sử Thu/Chi trong tuần:
\<code>/history week\</code>
4. Lịch sử Thu/Chi trong tuần cụ thể:
\<code>/history w 1 (2, 3, 4)\</code>
5. Lịch sử Thu/Chi tháng:
\<code>/history month tháng/năm\</code>
6. Lịch sử Thu/Chi năm:
\<code>/history year năm\</code>
<b>🗑️ Clear:</b>
1. Xoá Thu/Chi:
\<code>/del\</code>
2. Xoá tất cả chi tiêu:
\<code>/clearchitieu\</code>
3. Xoá tất cả thu nhập:
\<code>/clearthunhap\</code>
`);
} else {
sendText(
id_message,
"Xin chào " + userName + "! Để biết thêm chi tiết về các lệnh, bạn có thể sử dụng lệnh /help hoặc cũng có thể xem menu Money Nè tại đây."
);
}
}
}
function addTransactionData(
userId,
date,
description,
amount,
allocation,
type
) {
var sheet = getSheet(userId);
sheet.appendRow([date, description, amount, allocation, type]);
}
function addIncomeData(userId, date, content, amount, allocation) {
var sheet = getSheet(userId);
var type = "ThuNhap";
sheet.appendRow([date, content, amount, allocation, type]);
}
function addExpenseData(userId, date, item, amount, allocation) {
var sheet = getSheet(userId);
var type = "ChiTieu";
sheet.appendRow([date, item, amount, allocation, type]);
}
function getTotalIncome(userId) {
var sheet = getSheet(userId);
var data = sheet
.getRange(2, 3, sheet.getLastRow() - 1, 1)
.getValues();
var total = 0;
for (var i = 0; i < data.length; i++) {
total += data[i][0];
}
return total;
}
function getTotalExpenses(userId) {
var sheet = getSheet(userId);
var data = sheet
.getRange(2, 3, sheet.getLastRow() - 1, 1)
.getValues();
var total = 0;
for (var i = 0; i < data.length; i++) {
total += data[i][0];
}
return total;
}
function getCurrentBalance(userId) {
var totalIncome = getTotalAmountByType(userId, "ThuNhap");
var totalExpenses = getTotalAmountByType(userId, "ChiTieu");
return totalIncome - totalExpenses;
}
function getTotalAllocationBalances(userId) {
var allocations = [
'Thiết yếu',
'Giáo dục',
'Tiết kiệm',
'Đầu tư',
'Tiêu dùng',
'Khác'
];
var balances = {};
for (var i = 0; i < allocations.length; i++) {
balances[allocations[i]] = 0;
}
var sheet = getSheet(userId);
var data = sheet
.getRange(2, 3, sheet.getLastRow() - 1, 3)
.getValues();
for (var i = 0; i < data.length; i++) {
var allocation = data[i][1];
var type = data[i][2];
if (allocations.includes(allocation)) {
if (type === "ThuNhap") {
balances[allocation] += data[i][0];
} else if (type === "ChiTieu") {
balances[allocation] -= data[i][0];
}
}
}
return balances;
}
function sendTotalPhanboSummary(chatId, userId) {
var allocations = getTotalAllocationBalances(userId);
var message = "\nSố tiền phân bổ theo hũ:\n";
for (var allocation in allocations) {
message += "- " + allocation + ": " + allocations[allocation].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "\n";
}
var menuphanbo = {
"inline_keyboard": [
[
{
text: 'Xem Tổng Thu Nhập',
callback_data: 'totalthunhap'
},
{
text: 'Xem Tổng Chi Tiêu',
callback_data: 'totalchi'
}
]
]
};
sendText(chatId, message, menuphanbo);
}
function getTransactionHistory(userId, timeframe) {
var sheet = getSheet(userId);
var data = sheet
.getDataRange()
.getValues();
var transactions = [];
var currentDate = new Date();
for (var i = 1; i < data.length; i++) {
var transactionDate = new Date(data[i][0]);
if (transactionDate >= timeframe.startDate && transactionDate < timeframe.endDate) {
var transaction = {
date: data[i][0],
description: data[i][1],
amount: data[i][2],
allocation: data[i][3],
type: data[i][4]
};
transactions.push(transaction);
}
}
return transactions;
}
function getSheet(userId) {
var usersSpreadsheet = SpreadsheetApp.openById(main_sheet);
var usersSheet = usersSpreadsheet.getSheetByName('UserList');
var userData = usersSheet.getDataRange().getValues();
var sheetId = null;
for (var i = 0; i < userData.length; i++) {
if (userData[i][0] === userId) {
sheetId = userData[i][1];
break;
}
}
if (!sheetId) {
var newSpreadsheet = SpreadsheetApp.create('Expense Tracker for ' + userId);
sheetId = newSpreadsheet.getId();
usersSheet.appendRow([userId, sheetId]);
var sheet = newSpreadsheet.getActiveSheet();
sheet.getRange('A1:E1').setValues([
["Date", "Description", "Amount", "Allocation", "Type"]
]);
sheet.deleteColumns(6, 21);
var numRows = sheet.getMaxRows();
if (numRows > 2) {
sheet.deleteRows(3, numRows - 2);
}
}
var sheet = SpreadsheetApp.openById(sheetId).getActiveSheet();
return sheet;
}
function sendTotalIncomeSummary(chatId, userId) {
var totalIncome = getTotalAmountByType(userId, "ThuNhap");
var totalExpenses = getTotalAmountByType(userId, "ChiTieu");
var currentBalance = getCurrentBalance(userId);
var message = "- Tổng thu nhập của bạn là: " + totalIncome.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "\n";
message += "- Số tiền hiện tại của bạn là: " + currentBalance.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "\n";
var menuchithu = {
"inline_keyboard": [
[
{
text: 'Xem Tổng Chi Tiêu',
callback_data: 'totalchi'
},
{
text: 'Xem Chi Tiết Các Hũ',
callback_data: 'getTotalAllocationBalances'
}
]
]
};
sendText(chatId, message, menuchithu);
}
function getTotalAmountByType(userId, type) {
var sheet = getSheet(userId);
var data = sheet
.getDataRange()
.getValues();
var total = 0;
for (var i = 1; i < data.length; i++) {
if (data[i][4] === type) {
total += data[i][2];
}
}
return total;
}
function sendTransactionHistoryPart(chatId, userId, transactions, chunkIndex, chunkSize, totalChunks, totalThuNhap, totalChiTieu) {
var startIndex = chunkIndex * chunkSize;
var endIndex = Math.min((chunkIndex + 1) * chunkSize, transactions.length);
var message = "Lịch sử chi tiêu của bạn (Trang " + (chunkIndex + 1) + " / " + totalChunks + "):\n";
function formatTransaction(transaction, index) {
var formattedDate = new Intl.DateTimeFormat('vi-VN', { day: 'numeric', month: 'numeric', year: 'numeric' }).format(transaction.date);
var formattedAmount = formatNumberWithSeparator(transaction.amount);
var typeLabel = "";
var transactionAmount = transaction.amount;
if (transaction.type === "ChiTieu") {
typeLabel = "Chi tiêu💸";
transactionAmount = "<s>-" + formattedAmount + "</s>";
totalChiTieu += transaction.amount;
} else if (transaction.type === "ThuNhap") {
typeLabel = "Thu nhập💰";
transactionAmount = "<b>+" + formattedAmount + "</b>";
totalThuNhap += transaction.amount;
} else {
typeLabel = transaction.type;
}
var transactionString = `
${index + 1}. Ngày: ${formattedDate}
- Mô tả: ${transaction.description}
- Số tiền: ${transactionAmount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}
- Hũ: ${transaction.allocation}
<i>- Loại:</i> ${typeLabel}
`;
return transactionString;
}
for (var i = startIndex; i < endIndex; i++) {
var transaction = transactions[i];
message += formatTransaction(transaction, i);
}
if (chunkIndex == totalChunks - 1) {
var currentBalance = getCurrentBalance(userId);
message += "<b>💸 Tổng Chi tiêu: <s>" + totalChiTieu.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "</s></b>\n";
message += "<b>💰 Tổng Thu nhập: " + totalThuNhap.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "</b>\n";
message += "<b>💹 Số tiền hiện tại của bạn là: " + currentBalance.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "</b>\n";
}
sendText(chatId, message);
if (chunkIndex < totalChunks - 1) {
Utilities.sleep(3000);
sendTransactionHistoryPart(chatId, userId, transactions, chunkIndex + 1, chunkSize, totalChunks, totalThuNhap, totalChiTieu);
}
}
function sendTransactionHistory(chatId, userId) {
var transactions = getTransactionHistory(userId);
if (transactions.length === 0) {
sendText(chatId, "Bạn chưa có chi tiêu nào.");
return;
}
var chunkSize = 16;
var totalChunks = Math.ceil(transactions.length / chunkSize);
var totalThuNhap = 0;
var totalChiTieu = 0;
sendTransactionHistoryPart(chatId, userId, transactions, 0, chunkSize, totalChunks, totalThuNhap, totalChiTieu);
}
function getTransactionHistory(userId) {
var sheet = getSheet(userId);
var data = sheet
.getDataRange()
.getValues();
var transactions = [];
for (var i = 1; i < data.length; i++) {
var transaction = {
date: data[i][0],
description: data[i][1],
amount: data[i][2],
allocation: data[i][3],
type: data[i][4]
};
transactions.push(transaction);
}
return transactions;
}
function formatDate(dateStr) {
var date = new Date(dateStr);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
return day + "/" + month + "/" + year;
}
function sendTransactionHistoryByDateRange(chatId, userId, startDate, endDate) {
var transactions = getTransactionHistoryByDateRange(userId, startDate, endDate);
var chunkSize = 16;
var totalChunks = Math.ceil(transactions.length / chunkSize);
var totalChiTieu = 0;
var totalThuNhap = 0;
function sendTransactionHistoryPart(chunkIndex) {
var message = "Lịch sử chi tiêu từ " + formatDate(startDate) + " đến " + formatDate(endDate) +
" (Trang " + (chunkIndex + 1) + " / " + totalChunks + "):\n\n";
var startIndex = chunkIndex * chunkSize;
var endIndex = Math.min((chunkIndex + 1) * chunkSize, transactions.length);
for (var i = startIndex; i < endIndex; i++) {
var transaction = transactions[i];
var formattedDate = formatDate(transaction.date);
var typeLabel = "";
var transactionAmount = transaction.amount;
var formatTransactionAmount = new Intl.NumberFormat('vi-VN').format(transactionAmount);
if (transaction.type === "ChiTieu") {
typeLabel = "Chi tiêu💸";
transactionAmount = "<s>-" + formatTransactionAmount + "đ</s>";
totalChiTieu += transaction.amount;
} else if (transaction.type === "ThuNhap") {
typeLabel = "Thu nhập💰";
transactionAmount = "<b>+" + formatTransactionAmount + "đ</b>";
totalThuNhap += transaction.amount;
} else {
typeLabel = transaction.type;
}
message += `${i + 1}. Ngày: ${formattedDate}\n`;
message += "- Mô tả: " + transaction.description + "\n";
message += "- Số tiền: " + transactionAmount + "\n";
message += "- Hũ: " + transaction.allocation + "\n";
message += "<i>- Loại: " + typeLabel + "</i>\n\n";
}
if (chunkIndex === totalChunks - 1) {
var currentBalance = getCurrentBalance(userId);
message += "<b>💸 Tổng Chi tiêu: <s>" + totalChiTieu.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "</s></b>\n";
message += "<b>💰 Tổng Thu nhập: " + totalThuNhap.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "</b>\n";
message += "<b>💹 Số tiền hiện tại: " + currentBalance.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "</b>\n";
}
sendText(chatId, message);
if (chunkIndex < totalChunks - 1) {
Utilities.sleep(3000);
sendTransactionHistoryPart(chunkIndex + 1);
}
}
if (transactions.length === 0) {