Repository navigation
Expand file tree
/
Copy pathCode.js
More file actions
2979 lines (2521 loc) · 111 KB
/
Copy pathCode.js
File metadata and controls
2979 lines (2521 loc) · 111 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
/**
* DONATION HELPER - backend (Code.gs)
*
* This script must be bound to a Google Sheet (Extensions > Apps Script).
* Run setup() once from the Apps Script editor before deploying.
*
* Sheets used (auto-created by setup()):
* - Settings : Key | Value
* - Members : Name | WhatsApp | Status | AddedBy | AddedAt | Role
* - Tokens : TokenID | Role | Status | LinkedCampaignID | CreatedBy | CreatedAt
* - Campaigns: CampaignID | TargetName | Reason | GiftAmount | Status | StartDate |
* Deadline | BankName | BankAccount | AccountHolder | RoundingUsed |
* RoundTo | CreatedAt | FinalizedAt
* - Donors : CampaignID | Name | WhatsApp | JoinedAt | DonorStatus | AmountDue |
* Paid | ProofLink | PaidAt | CustomAmount | AmountPaid | Verified | Refunded
*/
const SHEETS = {
SETTINGS: 'Settings',
MEMBERS: 'Members',
TOKENS: 'Tokens',
CAMPAIGNS: 'Campaigns',
DONORS: 'Donors',
LATE_REQUESTS: 'LateRequests'
};
const HEADERS = {
Settings: ['Key', 'Value'],
Members: ['Name', 'WhatsApp', 'Status', 'AddedBy', 'AddedAt', 'Role', 'ModifiedBy', 'ModifiedAt', 'Email'],
Tokens: ['TokenID', 'Role', 'Status', 'LinkedCampaignID', 'CreatedBy', 'CreatedAt', 'Alias'],
Campaigns: ['CampaignID', 'TargetName', 'Reason', 'GiftAmount', 'Status', 'StartDate',
'Deadline', 'BankName', 'BankAccount', 'AccountHolder', 'RoundingUsed',
'RoundTo', 'CreatedAt', 'FinalizedAt', 'GiftLink', 'GiftImage', 'ModifiedBy', 'ModifiedAt'],
Donors: ['CampaignID', 'Name', 'WhatsApp', 'JoinedAt', 'DonorStatus', 'AmountDue',
'Paid', 'ProofLink', 'PaidAt', 'CustomAmount', 'AmountPaid', 'Verified', 'Refunded', 'Alias', 'ModifiedBy', 'ModifiedAt', 'LastReminderSentAt'],
LateRequests: ['RequestID', 'CampaignID', 'PIC_Alias', 'DonorName', 'DonorWhatsApp', 'IsCustom', 'CustomAmount', 'Reason', 'Status', 'CreatedAt', 'DonorAlias']
};
const DEFAULT_SETTINGS = {
EnableRounding: 'FALSE',
RoundToNearest: '500',
RequireMemberValidation: 'FALSE',
ProofsFolderId: '',
AppUrl: ''
};
// ====================== SETUP ======================
/**
* Run this ONCE manually from the Apps Script editor (select "setup" and click Run).
* Creates all sheets, default settings, a Drive folder for payment proofs, and a
* Super Admin token. The token is written to the execution log (View > Logs / Executions).
*/
function setupDatabase() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
Object.keys(HEADERS).forEach(name => {
let sh = ss.getSheetByName(name);
if (!sh) sh = ss.insertSheet(name);
const expectedHeaders = HEADERS[name];
if (sh.getLastRow() === 0) {
sh.appendRow(expectedHeaders);
sh.setFrozenRows(1);
} else {
const existingHeaders = sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0].map(h => String(h).trim());
expectedHeaders.forEach(header => {
if (existingHeaders.indexOf(header) === -1) {
sh.getRange(1, sh.getLastColumn() + 1).setValue(header);
}
});
}
});
const settingsSheet = ss.getSheetByName(SHEETS.SETTINGS);
const existingKeys = settingsSheet.getDataRange().getValues().slice(1).map(r => r[0]);
Object.keys(DEFAULT_SETTINGS).forEach(key => {
if (existingKeys.indexOf(key) === -1) {
settingsSheet.appendRow([key, DEFAULT_SETTINGS[key]]);
}
});
if (!getSetting('ProofsFolderId')) {
const folder = DriveApp.createFolder('Donation Proofs - ' + ss.getName());
setSetting('ProofsFolderId', folder.getId());
Logger.log('Created proofs folder: ' + folder.getUrl());
}
const props = PropertiesService.getScriptProperties();
if (!props.getProperty('SUPER_ADMIN_TOKEN')) {
const token = 'SA-' + Utilities.getUuid().split('-')[0].toUpperCase();
props.setProperty('SUPER_ADMIN_TOKEN', token);
}
Logger.log('Setup complete.');
Logger.log('SUPER ADMIN TOKEN: ' + props.getProperty('SUPER_ADMIN_TOKEN'));
Logger.log('Keep this token private. Use it to log in as Super Admin in the web app.');
}
/**
* Optional helper: run from the editor to print the current Super Admin token
* (e.g. after rotation) without re-running the whole setup.
*/
function showSuperAdminToken() {
Logger.log('SUPER ADMIN TOKEN: ' + PropertiesService.getScriptProperties().getProperty('SUPER_ADMIN_TOKEN'));
}
/**
* Optional: rotate (regenerate) the Super Admin token. Run manually from the editor.
*/
function rotateSuperAdminToken() {
const token = 'SA-' + Utilities.getUuid().split('-')[0].toUpperCase();
PropertiesService.getScriptProperties().setProperty('SUPER_ADMIN_TOKEN', token);
Logger.log('NEW SUPER ADMIN TOKEN: ' + token);
}
// ====================== WEB APP ENTRY ======================
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index')
.setTitle('Donatur Helper')
.addMetaTag('viewport', 'width=device-width, initial-scale=1');
}
function doPost(e) {
var data;
try {
data = JSON.parse(e.postData.contents);
} catch (err) {
return ContentService.createTextOutput(JSON.stringify({
status: 'error',
message: 'Invalid JSON payload'
})).setMimeType(ContentService.MimeType.JSON);
}
var action = data.action;
var params = data.params || [];
if (!Array.isArray(params)) {
params = [params];
}
try {
if (typeof this[action] !== 'function') {
throw new Error('Backend function "' + action + '" is missing or private.');
}
var result = this[action].apply(this, params);
return ContentService.createTextOutput(JSON.stringify({
status: 'success',
data: result
})).setMimeType(ContentService.MimeType.JSON);
} catch (err) {
return ContentService.createTextOutput(JSON.stringify({
status: 'error',
message: err.message || String(err)
})).setMimeType(ContentService.MimeType.JSON);
}
}
function doOptions(e) {
return ContentService.createTextOutput("")
.setMimeType(ContentService.MimeType.TEXT);
}
// ====================== GENERIC HELPERS ======================
function sheet_(name) {
return SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
}
function headerIndex_(sheetName, header) {
const sh = sheet_(sheetName);
const headers = sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
// Trim both sides to make it bulletproof against manual sheet edits
return headers.findIndex(h => String(h).trim() === String(header).trim());
}
/** Returns all data rows as objects, each carrying its 1-based sheet row in _row. */
function getRows_(sheetName) {
const sh = sheet_(sheetName);
const range = sh.getDataRange();
const data = range.getValues();
if (data.length < 2) return [];
const startRow = range.getRow(); // Accurately grabs the physical starting row
const headers = data[0].map(h => String(h).trim());
const rows = [];
for (let i = 1; i < data.length; i++) {
const obj = { _row: startRow + i }; // Bulletproof physical row mapping
headers.forEach((h, idx) => obj[h] = data[i][idx]);
rows.push(obj);
}
return rows;
}
function stripRow_(obj) {
const copy = Object.assign({}, obj);
delete copy._row;
// BUG FIX: google.script.run silently converts objects containing Dates to NULL.
// We must sanitize all Date objects into Strings before sending them to the frontend.
Object.keys(copy).forEach(key => {
if (copy[key] instanceof Date) {
if (key === 'Deadline' || key === 'StartDate') {
// Keep UI clean: Format deadlines as YYYY-MM-DD
copy[key] = copy[key].toISOString().split('T')[0];
} else {
// Keep precise time for CreatedAt / FinalizedAt for sorting
copy[key] = copy[key].toISOString();
}
}
});
return copy;
}
function getSetting(key) {
const rows = getRows_(SHEETS.SETTINGS);
const row = rows.find(r => r.Key === key);
return row ? row.Value : null;
}
function setSetting(key, value) {
const sh = sheet_(SHEETS.SETTINGS);
const rows = getRows_(SHEETS.SETTINGS);
const row = rows.find(r => r.Key === key);
if (row) {
sh.getRange(row._row, 2).setValue(value);
} else {
sh.appendRow([key, value]);
}
}
function normalizePhone_(phone) {
let p = String(phone || '').replace(/[^0-9]/g, '');
if (p.indexOf('0') === 0) p = '62' + p.slice(1);
else if (p.indexOf('62') !== 0 && p.indexOf('8') === 0) p = '62' + p;
return p;
}
function formatNumber_(n) {
return Number(n || 0).toLocaleString('id-ID');
}
function deleteRowsWhere_(sheetName, field, value) {
const sh = sheet_(sheetName);
const col = headerIndex_(sheetName, field);
const data = sh.getDataRange().getValues();
for (let i = data.length - 1; i >= 1; i--) {
if (data[i][col] === value) sh.deleteRow(i + 1);
}
}
function getOrCreateSheet_(name, headers) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
let sh = ss.getSheetByName(name);
if (!sh) {
sh = ss.insertSheet(name);
sh.appendRow(headers);
sh.setFrozenRows(1);
}
return sh;
}
// ====================== AUTH ======================
function checkSuperAdmin_(token) {
token = String(token || '').replace(/\s+/g, '').toUpperCase();
const real = String(PropertiesService.getScriptProperties().getProperty('SUPER_ADMIN_TOKEN') || '').replace(/\s+/g, '').toUpperCase();
return !!token && token === real;
}
function findToken_(token, role) {
const clean = String(token || '').replace(/\s+/g, '').toUpperCase();
return getRows_(SHEETS.TOKENS).find(t =>
String(t.TokenID || '').replace(/\s+/g, '').toUpperCase() === clean &&
String(t.Role || '').trim() === role
);
}
function checkAdmin_(token) {
if (checkSuperAdmin_(token)) return true;
const t = findToken_(token, 'Admin');
return !!t && t.Status === 'Active';
}
/**
* Used by the landing page to figure out which dashboard to show for a given token.
*/
function loginWithToken(token) {
// 1. Strip absolutely all whitespace (including hidden characters) and force uppercase
token = String(token || '').replace(/\s+/g, '').toUpperCase();
if (checkSuperAdmin_(token)) return { role: 'SuperAdmin', alias: 'SuperAdmin' };
const allTokens = getRows_(SHEETS.TOKENS);
// 2. Search the database with the same strict cleaning
const match = allTokens.find(t => {
const rowToken = String(t.TokenID || '').replace(/\s+/g, '').toUpperCase();
return rowToken === token;
});
if (!match) {
throw new Error('DEBUG: Token [' + token + '] sama sekali tidak ditemukan di Google Sheet.');
}
const role = String(match.Role || '').trim().toLowerCase();
const status = String(match.Status || '').trim().toLowerCase();
const alias = match.Alias ? String(match.Alias).trim() : '';
if (role === 'admin') {
if (status === 'active') return { role: 'Admin', alias: alias };
throw new Error('DEBUG: Token Admin ditemukan, tapi statusnya tercatat sebagai [' + status + '].');
}
if (role === 'pic') {
if (status !== 'expired') return { role: 'PIC', alias: alias };
throw new Error('DEBUG: Token PIC ditemukan, tapi statusnya sudah Expired.');
}
throw new Error('DEBUG: Token ditemukan, tapi Role tidak dikenali [' + role + '].');
}
// ====================== TOKEN MANAGEMENT ======================
function generatePicToken(callerToken) {
if (!checkAdmin_(callerToken)) throw new Error('Not authorized');
const id = 'PIC-' + Utilities.getUuid().split('-')[0].toUpperCase();
sheet_(SHEETS.TOKENS).appendRow([id, 'PIC', 'Unused', '', callerToken, new Date()]);
return id;
}
function revokeToken(callerToken, tokenId) {
if (!checkAdmin_(callerToken)) throw new Error('Not authorized');
const tok = getRows_(SHEETS.TOKENS).find(t => t.TokenID === tokenId);
if (!tok) throw new Error('Token not found');
sheet_(SHEETS.TOKENS).getRange(tok._row, headerIndex_(SHEETS.TOKENS, 'Status') + 1).setValue('Expired');
return true;
}
function listTokens(callerToken) {
if (!checkAdmin_(callerToken)) throw new Error('Not authorized');
return getRows_(SHEETS.TOKENS).map(stripRow_);
}
// ====================== CAMPAIGN COMPUTATION ======================
/**
* Splits `total` among `n` donors.
* - If rounding disabled: integer division, remainder distributed (first donors pay +1)
* so the sum always equals `total` exactly.
* - If rounding enabled: every donor pays ceil((total/n)/roundTo)*roundTo. This may
* collect slightly more than `total` (the small overage acts as a buffer/fees).
*/
function computeAmounts_(total, n, enableRounding, roundTo) {
total = Number(total);
n = Number(n);
if (n <= 0) return [];
if (enableRounding) {
const per = Math.ceil((total / n) / roundTo) * roundTo;
return new Array(n).fill(per);
}
const base = Math.floor(total / n);
const remainder = total - base * n;
const arr = [];
for (let i = 0; i < n; i++) arr.push(i < remainder ? base + 1 : base);
return arr;
}
function getPublicSettings() {
return {
enableRounding: String(getSetting('EnableRounding')).toUpperCase() === 'TRUE',
roundTo: Number(getSetting('RoundToNearest')) || 500
};
}
// ====================== PIC FUNCTIONS ======================
function createCampaign(picToken, data) {
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
const tok = findToken_(picToken, 'PIC');
if (!tok) throw new Error('Token PIC tidak valid.');
if (tok.Status === 'Expired') throw new Error('Token PIC sudah tidak aktif.');
if (tok.Status === 'Active' && tok.LinkedCampaignID) {
throw new Error('Token ini sudah dipakai untuk campaign ' + tok.LinkedCampaignID + '.');
}
if (!data.targetName || !data.deadline) {
throw new Error('Nama target dan deadline wajib diisi.');
}
const id = 'C-' + Utilities.getUuid().split('-')[0].toUpperCase();
const now = new Date();
const finalAmount = Number(data.giftAmount) || 0;
// 1. Write the new campaign to the database
sheet_(SHEETS.CAMPAIGNS).appendRow([
id, String(data.targetName), String(data.reason || ''), finalAmount, 'Open',
String(data.startDate || ''), String(data.deadline), '', '', '', '', '', now, '', '', '', '', ''
]);
// 2. BULLETPROOF TOKEN UPDATE: Link the campaign ID to the PIC token
const tSheet = sheet_(SHEETS.TOKENS);
// Grab the headers to dynamically find the correct columns
const headers = tSheet.getRange(1, 1, 1, tSheet.getLastColumn()).getValues()[0].map(h => String(h).trim());
const statusCol = headers.indexOf('Status') + 1;
const linkCol = headers.indexOf('LinkedCampaignID') + 1;
// Use Google's native text finder to locate the exact row containing the Token ID
const cell = tSheet.createTextFinder(tok.TokenID).matchEntireCell(true).findNext();
if (cell) {
const physicalRow = cell.getRow();
// Safely update the exact row and columns without offset errors
tSheet.getRange(physicalRow, statusCol).setValue('Active');
tSheet.getRange(physicalRow, linkCol).setValue(id);
} else {
throw new Error('Gagal mengupdate Token: TokenID tidak ditemukan secara fisik di database.');
}
SpreadsheetApp.flush();
// 3. Return the sanitized data to the frontend
return {
campaign: {
CampaignID: id,
TargetName: String(data.targetName),
Reason: String(data.reason || ''),
GiftAmount: finalAmount,
Status: 'Open',
StartDate: String(data.startDate || ''),
Deadline: String(data.deadline),
BankName: '',
BankAccount: '',
AccountHolder: '',
RoundingUsed: '',
RoundTo: '',
CreatedAt: now.toISOString(),
FinalizedAt: ''
},
donors: []
};
} finally {
lock.releaseLock();
}
}
function getCampaignDetail_(campaignId) {
// 1. Aggressively clean the ID we are looking for
campaignId = String(campaignId || '').trim();
// 2. Aggressively clean the ID in the database while searching
const campaign = getRows_(SHEETS.CAMPAIGNS).find(c => String(c.CampaignID || '').trim() === campaignId);
if (!campaign) return null; // If it still fails, it genuinely doesn't exist
// 3. Clean the IDs when pulling the donor list
const donors = getRows_(SHEETS.DONORS)
.filter(d => String(d.CampaignID || '').trim() === campaignId && String(d.DonorStatus || '').trim() === 'Pledged')
.map(stripRow_);
return { campaign: stripRow_(campaign), donors: donors };
}
function getCampaignForPic(picToken) {
const tok = findToken_(picToken, 'PIC');
if (!tok) throw new Error('Token PIC tidak valid.');
const status = String(tok.Status || '').trim().toLowerCase();
if (status === 'expired') throw new Error('Token PIC sudah tidak aktif.');
const linkedId = String(tok.LinkedCampaignID || '').trim();
// If the token has no Linked Campaign ID...
if (!linkedId) {
// PREVENT DUPLICATES: If they are already active, block the create form!
if (status === 'active') {
throw new Error('Token ini tercatat sudah aktif tapi kehilangan link ke Campaign. Silakan hubungi Admin untuk mengecek database.');
}
// Genuinely new token, safe to show the create form
return null;
}
// If we have an ID, we MUST find it.
const detail = getCampaignDetail_(linkedId);
if (!detail) {
throw new Error('Campaign dengan ID [' + linkedId + '] tidak ditemukan di database.');
}
return detail;
}
function setCampaignField_(campaignId, field, value) {
const sh = sheet_(SHEETS.CAMPAIGNS);
const col = headerIndex_(SHEETS.CAMPAIGNS, field) + 1;
const idCol = headerIndex_(SHEETS.CAMPAIGNS, 'CampaignID');
const data = sh.getDataRange().getValues();
for (let i = 1; i < data.length; i++) {
if (data[i][idCol] === campaignId) { sh.getRange(i + 1, col).setValue(value); return; }
}
}
function setCampaignTextField_(campaignId, field, value) {
const sh = sheet_(SHEETS.CAMPAIGNS);
const col = headerIndex_(SHEETS.CAMPAIGNS, field) + 1;
const idCol = headerIndex_(SHEETS.CAMPAIGNS, 'CampaignID');
const data = sh.getDataRange().getValues();
for (let i = 1; i < data.length; i++) {
if (data[i][idCol] === campaignId) {
sh.getRange(i + 1, col).setNumberFormat('@').setValue(String(value));
return;
}
}
}
function closeCampaignList(picToken) {
const tok = requirePicCampaign_(picToken);
const detail = getCampaignDetail_(tok.LinkedCampaignID);
if (detail.campaign.Status !== 'Open') throw new Error('Campaign sedang tidak dalam status Open.');
setCampaignField_(tok.LinkedCampaignID, 'Status', 'Closed');
return getCampaignDetail_(tok.LinkedCampaignID);
}
function reopenCampaignList(picToken) {
const tok = requirePicCampaign_(picToken);
const detail = getCampaignDetail_(tok.LinkedCampaignID);
if (detail.campaign.Status !== 'Closed' && detail.campaign.Status !== 'Finalized') throw new Error('Campaign sedang tidak dalam status Closed atau Finalized.');
setCampaignField_(tok.LinkedCampaignID, 'Status', 'Open');
return getCampaignDetail_(tok.LinkedCampaignID);
}
function requirePicCampaign_(picToken) {
const tok = findToken_(picToken, 'PIC');
if (!tok) throw new Error('Token PIC tidak valid.');
if (!tok.LinkedCampaignID) throw new Error('Token ini belum punya campaign.');
return tok;
}
function finalizeCampaign(picToken, bankInfo, finalGiftAmount, fileData) {
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
const tok = requirePicCampaign_(picToken);
const detail = getCampaignDetail_(tok.LinkedCampaignID);
const campaign = detail.campaign;
const donors = detail.donors;
if (campaign.Status === 'Archived') {
throw new Error('Campaign sudah diarsipkan.');
}
if (donors.length === 0) throw new Error('Belum ada yang join, tidak bisa difinalisasi.');
if (!bankInfo.bankName || !bankInfo.bankAccount || !bankInfo.accountHolder) {
throw new Error('Info rekening bank wajib diisi.');
}
// NEW: Ensure the PIC input a valid amount before dividing
finalGiftAmount = Number(finalGiftAmount);
if (!finalGiftAmount || finalGiftAmount <= 0) {
throw new Error('Total nilai hadiah akhir wajib diisi sebelum finalisasi.');
}
const enableRounding = String(getSetting('EnableRounding')).toUpperCase() === 'TRUE';
const roundTo = Number(getSetting('RoundToNearest')) || 500;
// Compute the split using the NEW final amount
const donorSheet = sheet_(SHEETS.DONORS);
const amtCol = headerIndex_(SHEETS.DONORS, 'AmountDue') + 1;
const allDonorRows = getRows_(SHEETS.DONORS).filter(d => d.CampaignID === campaign.CampaignID && d.DonorStatus === 'Pledged');
let customSum = 0;
let regularCount = 0;
allDonorRows.forEach(d => {
let customVal = Number(d.CustomAmount) || 0;
if (customVal > 0) {
customSum += customVal;
} else {
regularCount++;
}
});
let remainingGoal = finalGiftAmount - customSum;
if (remainingGoal < 0) remainingGoal = 0;
const regularAmounts = computeAmounts_(remainingGoal, regularCount, enableRounding, roundTo);
let regularIdx = 0;
const finalAmounts = [];
allDonorRows.forEach(d => {
let customVal = Number(d.CustomAmount) || 0;
if (customVal > 0) {
finalAmounts.push(customVal);
} else {
finalAmounts.push(regularAmounts[regularIdx]);
regularIdx++;
}
});
allDonorRows.forEach((d, idx) => donorSheet.getRange(d._row, amtCol).setValue(finalAmounts[idx]));
let imageUrl = '';
if (fileData) {
const folderId = getSetting('ProofsFolderId');
if (!folderId) throw new Error('Folder penyimpanan belum disetup oleh Super Admin.');
const folder = DriveApp.getFolderById(folderId);
const blob = Utilities.newBlob(Utilities.base64Decode(fileData.data), fileData.type, 'Price_' + campaign.CampaignID + '_' + fileData.name);
const file = folder.createFile(blob);
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
imageUrl = file.getUrl();
}
setCampaignField_(campaign.CampaignID, 'Status', 'Finalized');
setCampaignField_(campaign.CampaignID, 'GiftAmount', finalGiftAmount); // Update the master record
setCampaignField_(campaign.CampaignID, 'BankName', bankInfo.bankName);
setCampaignTextField_(campaign.CampaignID, 'BankAccount', bankInfo.bankAccount);
setCampaignField_(campaign.CampaignID, 'AccountHolder', bankInfo.accountHolder);
setCampaignField_(campaign.CampaignID, 'RoundingUsed', enableRounding);
setCampaignField_(campaign.CampaignID, 'RoundTo', roundTo);
setCampaignField_(campaign.CampaignID, 'FinalizedAt', new Date());
setCampaignField_(campaign.CampaignID, 'GiftLink', bankInfo.giftLink || '');
if (imageUrl) setCampaignField_(campaign.CampaignID, 'GiftImage', imageUrl);
// Send billing reminder emails to all pledged donors
const emailsSent = sendFinalizationEmails_(campaign, allDonorRows);
console.log(`Finalization complete. ${emailsSent} billing reminder emails sent.`);
return getCampaignDetail_(campaign.CampaignID);
} finally {
lock.releaseLock();
}
}
function updateGiftProof(picToken, link, fileData) {
const tok = requirePicCampaign_(picToken);
const campaignId = tok.LinkedCampaignID;
const detail = getCampaignDetail_(campaignId);
if (detail.campaign.Status !== 'Finalized') throw new Error('Hanya bisa diupload jika campaign sudah Finalized.');
if (link !== undefined && link !== null) {
setCampaignField_(campaignId, 'GiftLink', link);
}
if (fileData) {
const folderId = getSetting('ProofsFolderId');
if (!folderId) throw new Error('Folder penyimpanan belum disetup oleh Super Admin.');
const folder = DriveApp.getFolderById(folderId);
const blob = Utilities.newBlob(Utilities.base64Decode(fileData.data), fileData.type, 'Gift_' + campaignId + '_' + fileData.name);
const file = folder.createFile(blob);
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
setCampaignField_(campaignId, 'GiftImage', file.getUrl());
}
return true;
}
function archiveCampaign(picToken) {
const tok = requirePicCampaign_(picToken);
setCampaignField_(tok.LinkedCampaignID, 'Status', 'Archived');
sheet_(SHEETS.TOKENS).getRange(tok._row, headerIndex_(SHEETS.TOKENS, 'Status') + 1).setValue('Expired');
return true;
}
/**
* Deletes a campaign (PIC only). Only allowed for Open or Closed campaigns.
* Finalized and Archived campaigns cannot be deleted by PIC.
*/
function deleteCampaign(picToken) {
const lock = LockService.getScriptLock();
lock.waitLock(15000);
try {
const tok = requirePicCampaign_(picToken);
const campaignId = tok.LinkedCampaignID;
const campaign = getRows_(SHEETS.CAMPAIGNS).find(c => String(c.CampaignID || '').trim() === campaignId);
if (!campaign) {
throw new Error('Campaign tidak ditemukan.');
}
const status = String(campaign.Status || '').trim();
if (status === 'Finalized') {
throw new Error('Campaign yang sudah Finalized tidak bisa dihapus. Silakan arsipkan saja.');
}
if (status === 'Archived') {
throw new Error('Campaign yang sudah diarsipkan tidak bisa dihapus.');
}
// Delete campaign and related data
deleteRowsWhere_(SHEETS.CAMPAIGNS, 'CampaignID', campaignId);
deleteRowsWhere_(SHEETS.DONORS, 'CampaignID', campaignId);
deleteRowsWhere_(SHEETS.LATE_REQUESTS, 'CampaignID', campaignId);
// Clear and expire the PIC token
const sh = sheet_(SHEETS.TOKENS);
sh.getRange(tok._row, headerIndex_(SHEETS.TOKENS, 'LinkedCampaignID') + 1).setValue('');
sh.getRange(tok._row, headerIndex_(SHEETS.TOKENS, 'Status') + 1).setValue('Expired');
return true;
} finally {
lock.releaseLock();
}
}
/**
* Deletes a Draft PIC token (token with no linked campaign).
* Used when a user wants to remove a draft campaign from their list.
*/
function deleteDraftPicToken(picToken) {
const lock = LockService.getScriptLock();
lock.waitLock(15000);
try {
const tokens = getRows_(SHEETS.TOKENS);
const tok = tokens.find(t => t.TokenID === picToken);
if (!tok) {
throw new Error('Token tidak ditemukan.');
}
// Verify this is a Draft (no LinkedCampaignID)
if (String(tok.LinkedCampaignID || '').trim()) {
throw new Error('Token ini sudah terhubung ke campaign. Gunakan fitur hapus campaign.');
}
// Delete the token row
sheet_(SHEETS.TOKENS).deleteRow(tok._row);
return true;
} finally {
lock.releaseLock();
}
}
/**
* Returns a ready-to-copy bulk reminder message for the WhatsApp group, plus
* per-person wa.me deep links for unpaid donors only.
*/
function getReminderInfo(picToken, baseUrl) {
const tok = requirePicCampaign_(picToken);
const detail = getCampaignDetail_(tok.LinkedCampaignID);
const campaign = detail.campaign;
if (!baseUrl) {
try {
baseUrl = ScriptApp.getService().getUrl();
} catch(e) {
baseUrl = "https://script.google.com/macros/s/AKfycbzt4dyTtpTZhAXYleHJ6bC0na7jAfJpJft_sIfN0nReNtC9751ltMGKE07zMqAr-9rQZA/exec";
}
}
// Ensure Campaign URL contains campaign query param
const shareUrl = baseUrl.indexOf('?') === -1
? baseUrl + '?c=' + campaign.CampaignID
: baseUrl + '&c=' + campaign.CampaignID;
let bulkMessage = '';
if (campaign.Status === 'Open' || campaign.Status === 'Closed') {
bulkMessage = generatePreRegistrationMessage_(campaign, detail.donors, shareUrl);
} else if (campaign.Status === 'Finalized') {
const unpaid = detail.donors.filter(d => String(d.Paid).toUpperCase() !== 'TRUE');
if (unpaid.length > 0) {
bulkMessage = generateGroupBillingReminder_(campaign, detail.donors, shareUrl);
} else {
bulkMessage = generateGratitudeMessage_(campaign, detail.donors);
}
} else {
throw new Error('Status campaign tidak didukung untuk membuat reminder.');
}
const unpaid = detail.donors.filter(d => String(d.Paid).toUpperCase() !== 'TRUE');
const personal = unpaid.map(d => ({
name: d.Name,
whatsapp: d.WhatsApp,
amount: d.AmountDue,
waLink: 'https://wa.me/' + normalizePhone_(d.WhatsApp) + '?text=' + encodeURIComponent(
`Hi ${d.Name}, reminder ya untuk donasi "${campaign.TargetName}". ` +
`Mohon transfer Rp${formatNumber_(d.AmountDue)} ke ${campaign.BankName} ${campaign.BankAccount} ` +
`a.n. ${campaign.AccountHolder}, lalu konfirmasi di web. Makasih!`
)
}));
return { bulkMessage: bulkMessage, personal: personal, unpaidCount: unpaid.length, totalDonors: detail.donors.length };
}
function generatePreRegistrationMessage_(campaign, donors, webUrl) {
const donorNames = donors.map(d => d.Alias ? d.Alias : d.Name);
const deadlineText = campaign.Deadline || '-';
const lines = [
`🎁 *Yuk Patungan Donasi!*`,
``,
`👤 Untuk: *${campaign.TargetName}*` + (campaign.Reason ? `\n💬 Alasan: ${campaign.Reason}` : ''),
`📅 Batas akhir pendaftaran: ${deadlineText}`,
``,
`Yuk, segera gabung dan klik "Count me in" melalui link dashboard ini:`,
webUrl,
``,
`Rekan-rekan yang sudah gabung (${donors.length} orang):`
];
if (donorNames.length) {
donorNames.forEach(name => lines.push(`- ${name}`));
} else {
lines.push(`(belum ada, yuk jadi yang pertama!)`);
}
return lines.join('\n');
}
function generateGroupBillingReminder_(campaign, donors, webUrl) {
const unpaid = donors.filter(d => String(d.Paid).toUpperCase() !== 'TRUE');
const unpaidLines = unpaid.map(d => {
const displayName = d.Alias ? d.Alias : d.Name;
return `* ${displayName}`;
});
const totalGift = Number(campaign.GiftAmount) || 0;
const totalDonors = donors.length;
// Math breakdowns for Custom vs Standard
let customDonors = donors.filter(d => Number(d.CustomAmount) > 0);
let customSum = customDonors.reduce((sum, d) => sum + Number(d.CustomAmount), 0);
let customCount = customDonors.length;
let standardCount = totalDonors - customCount;
let standardAmount = 0;
// Prioritize unpaid standard donors to find the live standard amount
let firstStandard = donors.find(d => String(d.Paid).toUpperCase() !== 'TRUE' && (!d.CustomAmount || Number(d.CustomAmount) <= 0));
if (firstStandard) {
standardAmount = Number(firstStandard.AmountDue) || 0;
} else {
// Fallback if all standard donors are paid
let anyStandard = donors.find(d => !d.CustomAmount || Number(d.CustomAmount) <= 0);
if (anyStandard) {
standardAmount = Number(anyStandard.AmountDue) || 0;
}
}
const detailLines = [
`Detail Patungan:`,
`* Total Nilai Hadiah: Rp${formatNumber_(totalGift)}`,
`* Total Donatur: ${totalDonors} orang`
];
if (customCount > 0) {
const remainingGoal = Math.max(0, totalGift - customSum);
detailLines.push(` (Terdapat ${customCount} donatur nominal bebas dengan total Rp${formatNumber_(customSum)})`);
detailLines.push(`* Sisa target patungan: Rp${formatNumber_(remainingGoal)}`);
detailLines.push(`* Tagihan per orang standard (untuk ${standardCount} orang): Rp${formatNumber_(standardAmount)}`);
} else {
detailLines.push(`* Tagihan per orang: Rp${formatNumber_(standardAmount)}`);
}
const lines = [
`Halo semua, reminder transfer donasi untuk "${campaign.TargetName}"` + (campaign.Reason ? ` (${campaign.Reason})` : '') + `.`,
``,
`Rekan-rekan yang belum konfirmasi transfer (${unpaid.length} orang):`,
unpaidLines.length ? unpaidLines.join('\n') : '(semua sudah konfirmasi transfer, terima kasih!)',
``,
detailLines.join('\n'),
``,
`Silakan transfer ke rekening target:`,
`👉 ${campaign.BankName} ${campaign.BankAccount} a.n. ${campaign.AccountHolder}`,
``,
`Setelah transfer, mohon unggah bukti di web:`,
webUrl,
``,
`Terima kasih!`
];
return lines.join('\n');
}
function generateGratitudeMessage_(campaign, donors) {
const totalGift = Number(campaign.GiftAmount) || 0;
const donorNames = donors.map(d => d.Alias ? d.Alias : d.Name);
const customDonors = donors.filter(d => Number(d.CustomAmount) > 0);
const customSum = customDonors.reduce((sum, d) => sum + Number(d.CustomAmount), 0);
const customCount = customDonors.length;
const lines = [
`Alhamdulillah! Kegiatan donasi untuk "${campaign.TargetName}"` + (campaign.Reason ? ` (${campaign.Reason})` : '') + ` dengan total nilai hadiah Rp${formatNumber_(totalGift)} telah selesai dan semua pembayaran telah diverifikasi.`,
``
];
if (customCount > 0) {
lines.push(`*Catatan: Termasuk total donasi nominal bebas sebesar Rp${formatNumber_(customSum)} dari ${customCount} donatur.*`);
lines.push(``);
}
lines.push(`Terima kasih banyak atas ketulusan dan partisipasi dari ${donors.length} rekan-rekan donatur:`);
if (donorNames.length) {
donorNames.forEach(name => lines.push(`- ${name}`));
} else {
lines.push(`- (tidak ada donatur)`);
}
lines.push(``);
lines.push(`Semoga kebaikan rekan-rekan dibalas dengan kelimpahan. Hadiah akan segera diserahkan oleh PIC.`);
return lines.join('\n');
}
function runReminderTests() {
const mockCampaign = {
CampaignID: "C-TEST1",
TargetName: "Test Target",
Reason: "Resign",
GiftAmount: 1000000,
Deadline: "2026-07-01",
Status: "Open",
BankName: "BCA",
BankAccount: "123456",
AccountHolder: "Test Holder"
};
const mockDonors = [
{ Name: "Donor A", WhatsApp: "6281", DonorStatus: "Pledged", Paid: "FALSE", AmountDue: 400000 },
{ Name: "Donor B", WhatsApp: "6282", DonorStatus: "Pledged", Paid: "TRUE", AmountDue: 200000, CustomAmount: 200000 },
{ Name: "Donor C", WhatsApp: "6283", DonorStatus: "Pledged", Paid: "FALSE", AmountDue: 400000, Alias: "Hamba Allah" }
];
// Test Pre-Registration Message
const invite = generatePreRegistrationMessage_(mockCampaign, mockDonors, "http://mock?c=C-TEST1");
if (!invite.includes("Test Target") || !invite.includes("Donor A") || !invite.includes("Hamba Allah")) {
throw new Error("Pre-Registration template generation failed");
}
// Test Billing Reminder Message (with Custom Pledge)
mockCampaign.Status = "Finalized";
const bill = generateGroupBillingReminder_(mockCampaign, mockDonors, "http://mock?c=C-TEST1");
if (!bill.includes("Hamba Allah") || !bill.toLowerCase().includes("nominal bebas") || !bill.includes("BCA 123456")) {
throw new Error("Group Billing template generation failed");
}
// Test Gratitude Message
const mockAllPaid = mockDonors.map(d => ({ ...d, Paid: "TRUE" }));
const thanks = generateGratitudeMessage_(mockCampaign, mockAllPaid);
if (!thanks.includes("Test Target") || !thanks.includes("Hamba Allah") || !thanks.includes("Rp200.000")) {
throw new Error("Gratitude template generation failed");
}
console.log("ALL REMINDER TEST CASES PASSED!");
return "ALL REMINDER TEST CASES PASSED!";
}
// ====================== USER FUNCTIONS ======================
function checkDonorWhatsApp(whatsapp) {
whatsapp = normalizePhone_(whatsapp);
if (!whatsapp) throw new Error('Nomor WhatsApp wajib diisi.');
const members = getRows_(SHEETS.MEMBERS);
const existingMember = members.find(m => normalizePhone_(m.WhatsApp) === whatsapp);
const requireValidation = String(getSetting('RequireMemberValidation')).toUpperCase() === 'TRUE';
if (existingMember) {
if (requireValidation) {
const currentStatus = String(existingMember.Status).toLowerCase();
if (currentStatus === 'pending') {
return { exists: true, pending: true, message: 'Pendaftaran Anda sedang diproses. Mohon tunggu persetujuan Admin agar dapat masuk.' };
}
if (currentStatus !== 'active' && currentStatus !== 'ex') {
throw new Error('Akun Anda tidak aktif. Hubungi Admin.');
}
}
// Successfully verified / logged in
return { exists: true, name: existingMember.Name, email: existingMember.Email || '', whatsapp: whatsapp, verified: true, status: existingMember.Status };
}
return { exists: false };
}
function updateMemberProfile(whatsapp, name, email) {
const lock = LockService.getScriptLock();
lock.waitLock(10000);
try {
whatsapp = normalizePhone_(whatsapp);
name = String(name || '').trim();
email = String(email || '').trim();
if (!whatsapp) throw new Error('WhatsApp identifier missing.');
if (!name) throw new Error('Nama tidak boleh kosong.');
const sh = sheet_(SHEETS.MEMBERS);
const members = getRows_(SHEETS.MEMBERS);
const memberRow = members.find(m => normalizePhone_(m.WhatsApp) === whatsapp);
if (!memberRow) {