-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcode.gs
More file actions
1595 lines (1401 loc) · 49.5 KB
/
code.gs
File metadata and controls
1595 lines (1401 loc) · 49.5 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
const SPREADSHEET_ID = '';
const SHEET_HEADERS = {
Items: ['id', 'name', 'category', 'price', 'sku', 'barcode', 'stockQty', 'minStock', 'isActive', 'updatedAt'],
Categories: ['categoryId', 'name', 'isActive', 'updatedAt'],
Transactions: ['timestamp', 'total', 'detail', 'trxId', 'paymentMethod', 'itemCount', 'cashReceived', 'changeAmount', 'status', 'gatewayProvider', 'gatewayOrderId', 'gatewayTransactionId', 'gatewayPaymentType', 'gatewayStatus', 'gatewayToken', 'gatewayRedirectUrl', 'gatewayRaw', 'paidAt'],
TransactionItems: ['trxId', 'itemId', 'nameSnapshot', 'qty', 'price', 'subtotal'],
InventoryMoves: ['moveId', 'createdAt', 'itemId', 'type', 'qtyDelta', 'beforeQty', 'afterQty', 'referenceId', 'note'],
Settings: ['key', 'value']
};
const DEFAULT_SETTINGS = {
storeName: 'Kasira POS',
storeAddress: 'Jl. Contoh No. 1',
storePhone: '0812-0000-0000',
receiptFooter: 'Terima kasih sudah berbelanja.'
};
const PAYMENT_METHODS = ['cash', 'qris', 'transfer', 'ewallet', 'midtrans'];
function doGet() {
return HtmlService.createHtmlOutputFromFile('index')
.setTitle('LitPOS')
.addMetaTag('viewport', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');
}
function getAppBootstrapData() {
return executeSafely_(function () {
const context = ensureSchema_();
const inventory = getInventoryContext_(context);
const dashboard = buildDashboardSummary_(context, inventory.items);
const transactions = buildTransactionsForClient_(context, { range: 'all' });
return buildResponse_(true, 'Data aplikasi berhasil dimuat.', {
store: mapStoreForClient_(getStoreSettings_(context)),
storeInfo: getStoreSettings_(context),
categories: inventory.categories.map(mapCategoryForClient_),
items: inventory.items.map(mapItemForClient_),
transactions: transactions,
dashboard: mapDashboardForClient_(dashboard),
paymentGateway: buildPaymentGatewayBootstrap_()
});
});
}
function saveSale(payload) {
return executeSafely_(function () {
const lock = LockService.getScriptLock();
lock.waitLock(20000);
try {
const context = ensureSchema_();
const sale = validateSalePayload_(context, payload || {});
const result = persistSale_(context, sale);
return buildResponse_(true, 'Transaksi berhasil disimpan.', result);
} finally {
lock.releaseLock();
}
});
}
function createMidtransPayment(payload) {
return executeSafely_(function () {
const lock = LockService.getScriptLock();
lock.waitLock(20000);
try {
const context = ensureSchema_();
const salePayload = payload || {};
salePayload.paymentMethod = 'midtrans';
const sale = validateSalePayload_(context, salePayload);
const trxId = generateId_('TRX');
const storeInfo = getStoreSettings_(context);
const snapPayload = buildMidtransSnapPayload_(sale, storeInfo, trxId);
const snap = KasiraModules.MidtransGateway.createSnapTransaction(snapPayload);
const result = persistSale_(context, sale, {
trxId: trxId,
paymentMethod: 'midtrans',
status: 'Menunggu Pembayaran',
deductStock: true,
inventoryMoveType: 'SALE_PENDING',
inventoryNote: 'Reservasi stok - Midtrans pending',
gateway: {
provider: 'midtrans',
orderId: trxId,
transactionId: '',
paymentType: '',
status: 'pending',
token: snap.token,
redirectUrl: snap.redirectUrl,
raw: snap.raw
},
paidAt: ''
});
result.paymentSession = {
orderId: trxId,
token: snap.token,
redirectUrl: snap.redirectUrl
};
return buildResponse_(true, 'Transaksi Midtrans berhasil dibuat.', result);
} finally {
lock.releaseLock();
}
});
}
function syncMidtransTransactionStatus(payload) {
return executeSafely_(function () {
const lock = LockService.getScriptLock();
lock.waitLock(20000);
try {
const context = ensureSchema_();
const trxId = typeof payload === 'object' && payload !== null
? stringValue_(payload.trxId)
: stringValue_(payload);
if (!trxId) {
throw new Error('trxId wajib diisi.');
}
const transactionRows = readSheetObjects_(context.Transactions.sheet);
const targetRow = transactionRows.find(function (row) {
return stringValue_(row.trxId) === trxId;
});
if (!targetRow) {
throw new Error('Transaksi tidak ditemukan.');
}
const transaction = normalizeTransactionRecord_(targetRow);
if (transaction.paymentMethod !== 'midtrans') {
throw new Error('Transaksi ini bukan transaksi Midtrans.');
}
const orderId = transaction.gateway.orderId || transaction.trxId;
const statusPayload = KasiraModules.MidtransGateway.getTransactionStatus(orderId);
const mapped = KasiraModules.MidtransGateway.mapTransactionState(statusPayload.transaction_status, statusPayload.fraud_status);
const previousStatus = stringValue_(transaction.status);
const isFailure = !!mapped.isFailure;
if (previousStatus === 'Menunggu Pembayaran' && isFailure) {
releaseReservedStockForTransaction_(context, transaction.trxId, 'Midtrans ' + mapped.localStatus);
}
let nextStatus = mapped.localStatus;
if (mapped.isPaid && mapped.localStatus !== 'Refund' && mapped.localStatus !== 'Refund Sebagian') {
nextStatus = 'Selesai';
}
const paidAtValue = mapped.isPaid && nextStatus === 'Selesai'
? (transaction.paidAt || safeIsoString_(new Date()))
: transaction.paidAt;
writeObjectToExistingRow_(context.Transactions.sheet, context.Transactions.headers, targetRow._rowNumber, {
status: nextStatus,
gatewayProvider: 'midtrans',
gatewayOrderId: orderId,
gatewayTransactionId: stringValue_(statusPayload.transaction_id),
gatewayPaymentType: stringValue_(statusPayload.payment_type),
gatewayStatus: stringValue_(statusPayload.transaction_status),
gatewayRaw: JSON.stringify(statusPayload || {}),
paidAt: paidAtValue ? parseDate_(paidAtValue) || paidAtValue : ''
});
const refreshedTransactionRows = readSheetObjects_(context.Transactions.sheet);
const refreshedRaw = refreshedTransactionRows.find(function (row) {
return stringValue_(row.trxId) === trxId;
}) || targetRow;
const refreshed = normalizeTransactionRecord_(refreshedRaw);
const items = readSheetObjects_(context.TransactionItems.sheet)
.filter(function (row) { return stringValue_(row.trxId) === trxId; })
.map(function (row) {
return {
itemId: stringValue_(row.itemId),
name: stringValue_(row.nameSnapshot),
qty: normalizeInteger_(row.qty, 0),
price: normalizeMoney_(row.price),
subtotal: normalizeMoney_(row.subtotal)
};
});
return buildResponse_(true, 'Status Midtrans berhasil diperbarui.', {
trxId: refreshed.trxId,
timestamp: refreshed.timestamp,
total: refreshed.total,
itemCount: refreshed.itemCount,
paymentMethod: refreshed.paymentMethod,
status: refreshed.status,
cashReceived: refreshed.cashReceived,
changeAmount: refreshed.changeAmount,
paidAt: refreshed.paidAt,
items: items,
gateway: refreshed.gateway,
storeInfo: getStoreSettings_(context)
});
} finally {
lock.releaseLock();
}
});
}
function saveItem(payload) {
return executeSafely_(function () {
const context = ensureSchema_();
const itemsSheet = context.Items.sheet;
const rows = readSheetObjects_(itemsSheet);
const headers = context.Items.headers;
const now = new Date();
const itemId = stringValue_(payload && payload.id);
const itemName = stringValue_(payload && payload.name);
const categoryId = stringValue_(payload && (payload.categoryId || payload.category));
const sku = stringValue_(payload && payload.sku);
const barcode = stringValue_(payload && payload.barcode);
const price = normalizeMoney_(payload && payload.price);
const isActive = booleanValue_(payload && payload.isActive, true);
if (!itemName) {
throw new Error('Nama produk wajib diisi.');
}
let targetRow = null;
if (itemId) {
targetRow = rows.find(function (row) {
return stringValue_(row.id) === itemId;
}) || null;
}
const finalId = targetRow ? stringValue_(targetRow.id) : generateId_('ITEM');
const currentStockQty = targetRow ? normalizeInteger_(targetRow.stockQty, 0) : 0;
const currentMinStock = targetRow ? normalizeInteger_(targetRow.minStock, 0) : 0;
const stockQty = Object.prototype.hasOwnProperty.call(payload || {}, 'stockQty')
? normalizeInteger_(payload && payload.stockQty, currentStockQty)
: currentStockQty;
const minStock = Object.prototype.hasOwnProperty.call(payload || {}, 'minStock')
? normalizeInteger_(payload && payload.minStock, currentMinStock)
: currentMinStock;
if (price < 0) {
throw new Error('Harga produk tidak boleh negatif.');
}
if (stockQty < 0 || minStock < 0) {
throw new Error('Stok dan stok minimum tidak boleh negatif.');
}
const rowObject = {
id: finalId,
name: itemName,
category: categoryId,
price: price,
sku: sku,
barcode: barcode,
stockQty: stockQty,
minStock: minStock,
isActive: isActive,
updatedAt: now
};
if (targetRow) {
writeObjectToExistingRow_(itemsSheet, headers, targetRow._rowNumber, rowObject);
} else {
appendObjectRows_(itemsSheet, headers, [rowObject]);
}
const inventory = getInventoryContext_(context);
const savedItem = inventory.items.find(function (item) {
return item.id === finalId;
});
return buildResponse_(true, 'Produk berhasil disimpan.', mapItemForClient_(savedItem || rowObject));
});
}
function saveCategory(payload) {
return executeSafely_(function () {
const context = ensureSchema_();
const categoriesSheet = context.Categories.sheet;
const rows = readSheetObjects_(categoriesSheet);
const headers = context.Categories.headers;
const categoryIdInput = stringValue_(payload && (payload.categoryId || payload.id));
const name = stringValue_(payload && payload.name);
const isActive = booleanValue_(payload && payload.isActive, true);
const now = new Date();
if (!name) {
throw new Error('Nama kategori wajib diisi.');
}
let targetRow = null;
if (categoryIdInput) {
targetRow = rows.find(function (row) {
return stringValue_(row.categoryId) === categoryIdInput;
}) || null;
}
const finalId = targetRow ? stringValue_(targetRow.categoryId) : (categoryIdInput || generateId_('CAT'));
const rowObject = {
categoryId: finalId,
name: name,
isActive: isActive,
updatedAt: now
};
if (targetRow) {
writeObjectToExistingRow_(categoriesSheet, headers, targetRow._rowNumber, rowObject);
} else {
appendObjectRows_(categoriesSheet, headers, [rowObject]);
}
const inventory = getInventoryContext_(context);
const savedCategory = inventory.categories.find(function (category) {
return category.categoryId === finalId;
}) || {
categoryId: finalId,
name: name,
isActive: isActive
};
return buildResponse_(true, 'Kategori berhasil disimpan.', mapCategoryForClient_(savedCategory));
});
}
function adjustStock(payload) {
return executeSafely_(function () {
const lock = LockService.getScriptLock();
lock.waitLock(20000);
try {
const context = ensureSchema_();
const inventory = getInventoryContext_(context);
const itemsSheet = context.Items.sheet;
const headers = context.Items.headers;
const itemId = stringValue_(payload && payload.itemId);
const directionRaw = stringValue_(payload && (payload.direction || payload.type)).toLowerCase();
const direction = directionRaw === 'add' ? 'increase' : directionRaw === 'sub' ? 'decrease' : directionRaw;
const qty = normalizeInteger_(payload && payload.qty, 0);
const note = stringValue_(payload && payload.note);
const item = inventory.itemIndex[itemId];
if (!item) {
throw new Error('Produk tidak ditemukan.');
}
if (qty <= 0) {
throw new Error('Jumlah penyesuaian stok harus lebih dari 0.');
}
if (direction !== 'increase' && direction !== 'decrease') {
throw new Error('Arah penyesuaian stok tidak valid.');
}
const beforeQty = item.stockManaged ? item.stockQty : 0;
const delta = direction === 'increase' ? qty : (qty * -1);
const afterQty = beforeQty + delta;
if (afterQty < 0) {
throw new Error('Stok tidak mencukupi untuk pengurangan.');
}
writeObjectToExistingRow_(itemsSheet, headers, item._rowNumber, {
stockQty: afterQty,
updatedAt: new Date()
});
appendObjectRows_(context.InventoryMoves.sheet, context.InventoryMoves.headers, [{
moveId: generateId_('MOVE'),
createdAt: new Date(),
itemId: item.id,
type: 'ADJUSTMENT',
qtyDelta: delta,
beforeQty: beforeQty,
afterQty: afterQty,
referenceId: '',
note: note || (direction === 'increase' ? 'Tambah stok manual' : 'Kurangi stok manual')
}]);
const refreshedInventory = getInventoryContext_(context);
return buildResponse_(true, 'Stok berhasil disesuaikan.', mapItemForClient_(toPublicItem_(refreshedInventory.itemIndex[itemId])));
} finally {
lock.releaseLock();
}
});
}
function getTransactions(filters) {
return executeSafely_(function () {
const context = ensureSchema_();
const transactions = buildTransactionsForClient_(context, filters || {});
return buildResponse_(true, 'Riwayat transaksi berhasil dimuat.', transactions);
});
}
function getTransactionDetail(trxId) {
return executeSafely_(function () {
const context = ensureSchema_();
const allTransactions = getTransactionsInternal_(context, { range: 'all' });
const targetId = typeof trxId === 'object' && trxId !== null ? stringValue_(trxId.trxId) : stringValue_(trxId);
const transaction = allTransactions.find(function (entry) {
return entry.trxId === targetId;
});
if (!transaction) {
throw new Error('Detail transaksi tidak ditemukan.');
}
const itemRows = readSheetObjects_(context.TransactionItems.sheet);
const items = itemRows
.filter(function (row) {
return stringValue_(row.trxId) === transaction.trxId;
})
.map(function (row) {
return {
itemId: stringValue_(row.itemId),
name: stringValue_(row.nameSnapshot),
qty: normalizeInteger_(row.qty, 0),
price: normalizeMoney_(row.price),
subtotal: normalizeMoney_(row.subtotal)
};
});
const detailItems = items.length > 0 ? items : parseLegacyDetail_(transaction.detail).map(function (entry) {
return {
itemId: '',
name: entry.name,
qty: entry.qty,
price: 0,
subtotal: 0
};
});
return buildResponse_(true, 'Detail transaksi berhasil dimuat.', {
transaction: transaction,
items: detailItems,
storeInfo: getStoreSettings_(context)
});
});
}
function getReportSummary(range) {
return executeSafely_(function () {
const context = ensureSchema_();
const inventory = getInventoryContext_(context);
const rangeValue = typeof range === 'object' && range !== null ? stringValue_(range.range) : stringValue_(range);
const summary = buildReportSummary_(context, inventory.items, rangeValue || 'today');
return buildResponse_(true, 'Laporan berhasil dimuat.', summary);
});
}
function saveStoreSettings(payload) {
return executeSafely_(function () {
const context = ensureSchema_();
const settingsPayload = payload || {};
const nextSettings = {
storeName: stringValue_(settingsPayload.storeName || settingsPayload.name) || DEFAULT_SETTINGS.storeName,
storeAddress: stringValue_(settingsPayload.storeAddress || settingsPayload.address) || DEFAULT_SETTINGS.storeAddress,
storePhone: stringValue_(settingsPayload.storePhone || settingsPayload.phone) || DEFAULT_SETTINGS.storePhone,
receiptFooter: stringValue_(settingsPayload.receiptFooter || settingsPayload.footer) || DEFAULT_SETTINGS.receiptFooter
};
upsertSettings_(context.Settings.sheet, nextSettings);
return buildResponse_(true, 'Pengaturan toko berhasil disimpan.', mapStoreForClient_(nextSettings));
});
}
function getMidtransSettings() {
return executeSafely_(function () {
if (typeof KasiraModules === 'undefined' || !KasiraModules.MidtransGateway) {
throw new Error('Modul Midtrans tidak tersedia.');
}
const settings = KasiraModules.MidtransGateway.getAdminConfig();
return buildResponse_(true, 'Pengaturan Midtrans berhasil dimuat.', settings);
});
}
function saveMidtransSettings(payload) {
return executeSafely_(function () {
if (typeof KasiraModules === 'undefined' || !KasiraModules.MidtransGateway) {
throw new Error('Modul Midtrans tidak tersedia.');
}
const saved = KasiraModules.MidtransGateway.saveAdminConfig(payload || {});
return buildResponse_(true, 'Pengaturan Midtrans berhasil disimpan.', saved);
});
}
function executeSafely_(callback) {
try {
return callback();
} catch (error) {
return buildResponse_(false, error && error.message ? error.message : String(error), null);
}
}
function buildResponse_(success, message, data) {
return {
success: success,
message: message,
data: data
};
}
function ensureSchema_() {
const spreadsheet = SpreadsheetApp.openById(SPREADSHEET_ID);
const context = {};
Object.keys(SHEET_HEADERS).forEach(function (sheetName) {
context[sheetName] = ensureSheet_(spreadsheet, sheetName, SHEET_HEADERS[sheetName]);
});
ensureDefaultSettings_(context.Settings.sheet);
return context;
}
function ensureSheet_(spreadsheet, sheetName, expectedHeaders) {
let sheet = spreadsheet.getSheetByName(sheetName);
if (!sheet) {
sheet = spreadsheet.insertSheet(sheetName);
}
const currentHeaders = getSheetHeaders_(sheet);
if (currentHeaders.length === 0) {
sheet.getRange(1, 1, 1, expectedHeaders.length).setValues([expectedHeaders]);
if (sheet.getFrozenRows() < 1) {
sheet.setFrozenRows(1);
}
return {
sheet: sheet,
headers: expectedHeaders.slice()
};
}
const missingHeaders = expectedHeaders.filter(function (header) {
return currentHeaders.indexOf(header) === -1;
});
if (missingHeaders.length > 0) {
const startColumn = sheet.getLastColumn() + 1;
sheet.getRange(1, startColumn, 1, missingHeaders.length).setValues([missingHeaders]);
}
if (sheet.getFrozenRows() < 1) {
sheet.setFrozenRows(1);
}
return {
sheet: sheet,
headers: getSheetHeaders_(sheet)
};
}
function getSheetHeaders_(sheet) {
const lastColumn = sheet.getLastColumn();
if (lastColumn < 1) {
return [];
}
return sheet.getRange(1, 1, 1, lastColumn).getValues()[0].map(function (value) {
return stringValue_(value);
}).filter(function (value) {
return value !== '';
});
}
function readSheetObjects_(sheet) {
const headers = getSheetHeaders_(sheet);
const lastRow = sheet.getLastRow();
if (headers.length === 0 || lastRow < 2) {
return [];
}
return sheet.getRange(2, 1, lastRow - 1, headers.length).getValues()
.map(function (row, index) {
const object = { _rowNumber: index + 2 };
headers.forEach(function (header, cellIndex) {
object[header] = row[cellIndex];
});
return object;
})
.filter(function (rowObject) {
return headers.some(function (header) {
return rowObject[header] !== '' && rowObject[header] !== null;
});
});
}
function appendObjectRows_(sheet, headers, rows) {
if (!rows || rows.length === 0) {
return;
}
const values = rows.map(function (rowObject) {
return headers.map(function (header) {
return Object.prototype.hasOwnProperty.call(rowObject, header) ? rowObject[header] : '';
});
});
const startRow = sheet.getLastRow() + 1;
sheet.getRange(startRow, 1, values.length, headers.length).setValues(values);
}
function writeObjectToExistingRow_(sheet, headers, rowNumber, partialObject) {
const currentValues = sheet.getRange(rowNumber, 1, 1, headers.length).getValues()[0];
const nextValues = headers.map(function (header, index) {
return Object.prototype.hasOwnProperty.call(partialObject, header) ? partialObject[header] : currentValues[index];
});
sheet.getRange(rowNumber, 1, 1, headers.length).setValues([nextValues]);
}
function ensureDefaultSettings_(settingsSheet) {
const rows = readSheetObjects_(settingsSheet);
const existing = {};
rows.forEach(function (row) {
existing[stringValue_(row.key)] = row;
});
const missingRows = Object.keys(DEFAULT_SETTINGS).filter(function (key) {
return !existing[key];
}).map(function (key) {
return {
key: key,
value: DEFAULT_SETTINGS[key]
};
});
if (missingRows.length > 0) {
appendObjectRows_(settingsSheet, SHEET_HEADERS.Settings, missingRows);
}
}
function upsertSettings_(settingsSheet, settingsObject) {
const rows = readSheetObjects_(settingsSheet);
const rowByKey = {};
rows.forEach(function (row) {
rowByKey[stringValue_(row.key)] = row;
});
Object.keys(settingsObject).forEach(function (key) {
const existingRow = rowByKey[key];
if (existingRow) {
writeObjectToExistingRow_(settingsSheet, SHEET_HEADERS.Settings, existingRow._rowNumber, {
key: key,
value: settingsObject[key]
});
} else {
appendObjectRows_(settingsSheet, SHEET_HEADERS.Settings, [{
key: key,
value: settingsObject[key]
}]);
}
});
}
function getStoreSettings_(context) {
const rows = readSheetObjects_(context.Settings.sheet);
const settings = {};
rows.forEach(function (row) {
settings[stringValue_(row.key)] = stringValue_(row.value);
});
return {
storeName: settings.storeName || DEFAULT_SETTINGS.storeName,
storeAddress: settings.storeAddress || DEFAULT_SETTINGS.storeAddress,
storePhone: settings.storePhone || DEFAULT_SETTINGS.storePhone,
receiptFooter: settings.receiptFooter || DEFAULT_SETTINGS.receiptFooter
};
}
function getInventoryContext_(context) {
const categoryRows = readSheetObjects_(context.Categories.sheet);
const itemRows = readSheetObjects_(context.Items.sheet);
const categories = buildEffectiveCategories_(categoryRows, itemRows);
const categoryMap = {};
const itemIndex = {};
categories.forEach(function (category) {
categoryMap[category.categoryId] = category;
});
itemRows.forEach(function (row) {
const item = normalizeItemRecord_(row, categoryMap);
if (item && item.id && item.name) {
itemIndex[item.id] = item;
}
});
const items = Object.keys(itemIndex).map(function (itemId) {
return toPublicItem_(itemIndex[itemId]);
}).sort(sortByName_);
return {
categories: categories,
categoryMap: categoryMap,
itemIndex: itemIndex,
items: items
};
}
function buildEffectiveCategories_(categoryRows, itemRows) {
const map = {};
categoryRows.forEach(function (row) {
const category = normalizeCategoryRecord_(row);
if (category && category.categoryId) {
map[category.categoryId] = category;
}
});
itemRows.forEach(function (row) {
const legacyCategoryKey = stringValue_(row.category);
if (!legacyCategoryKey || map[legacyCategoryKey]) {
return;
}
map[legacyCategoryKey] = {
categoryId: legacyCategoryKey,
name: legacyCategoryKey,
isActive: true,
legacy: true,
updatedAt: ''
};
});
return Object.keys(map).map(function (key) {
return map[key];
}).sort(function (left, right) {
if (left.isActive !== right.isActive) {
return left.isActive ? -1 : 1;
}
return sortByName_(left, right);
}).map(function (category) {
return {
categoryId: category.categoryId,
name: category.name,
isActive: category.isActive,
legacy: !!category.legacy,
updatedAt: category.updatedAt || ''
};
});
}
function normalizeCategoryRecord_(row) {
const categoryId = stringValue_(row.categoryId);
const name = stringValue_(row.name) || categoryId;
if (!categoryId || !name) {
return null;
}
return {
_rowNumber: row._rowNumber,
categoryId: categoryId,
name: name,
isActive: booleanValue_(row.isActive, true),
legacy: false,
updatedAt: safeIsoString_(row.updatedAt)
};
}
function normalizeItemRecord_(row, categoryMap) {
const itemId = stringValue_(row.id);
const name = stringValue_(row.name);
if (!itemId || !name) {
return null;
}
const categoryId = stringValue_(row.category);
const category = categoryMap[categoryId];
const stockManaged = row.stockQty !== '' && row.stockQty !== null;
return {
_rowNumber: row._rowNumber,
id: itemId,
name: name,
categoryId: categoryId,
categoryName: category ? category.name : (categoryId || 'Tanpa kategori'),
price: normalizeMoney_(row.price),
sku: stringValue_(row.sku),
barcode: stringValue_(row.barcode),
stockQty: normalizeInteger_(row.stockQty, 0),
stockManaged: stockManaged,
minStock: normalizeInteger_(row.minStock, 0),
isActive: booleanValue_(row.isActive, true),
updatedAt: safeIsoString_(row.updatedAt)
};
}
function toPublicItem_(item) {
return {
id: item.id,
name: item.name,
categoryId: item.categoryId,
categoryName: item.categoryName,
price: item.price,
sku: item.sku,
barcode: item.barcode,
stockQty: item.stockQty,
stockManaged: item.stockManaged,
minStock: item.minStock,
isActive: item.isActive,
updatedAt: item.updatedAt
};
}
function mapStoreForClient_(storeInfo) {
const source = storeInfo || {};
return {
name: source.storeName || DEFAULT_SETTINGS.storeName,
address: source.storeAddress || DEFAULT_SETTINGS.storeAddress,
phone: source.storePhone || DEFAULT_SETTINGS.storePhone,
footer: source.receiptFooter || DEFAULT_SETTINGS.receiptFooter,
storeName: source.storeName || DEFAULT_SETTINGS.storeName,
storeAddress: source.storeAddress || DEFAULT_SETTINGS.storeAddress,
storePhone: source.storePhone || DEFAULT_SETTINGS.storePhone,
receiptFooter: source.receiptFooter || DEFAULT_SETTINGS.receiptFooter
};
}
function buildPaymentGatewayBootstrap_() {
const fallback = {
midtrans: {
enabled: false,
mode: 'sandbox',
merchantId: '',
clientKey: '',
clientKeyConfigured: false,
serverKeyConfigured: false
}
};
if (typeof KasiraModules === 'undefined' || !KasiraModules.MidtransGateway) {
return fallback;
}
const midtransConfig = KasiraModules.MidtransGateway.getPublicConfig();
return {
midtrans: {
enabled: !!midtransConfig.enabled,
mode: midtransConfig.mode || 'sandbox',
merchantId: midtransConfig.merchantId || '',
clientKey: midtransConfig.clientKey || '',
clientKeyConfigured: !!midtransConfig.clientKeyConfigured,
serverKeyConfigured: !!midtransConfig.serverKeyConfigured
}
};
}
function mapCategoryForClient_(category) {
if (!category) {
return null;
}
return {
id: category.categoryId || '',
categoryId: category.categoryId || '',
name: category.name || '',
isActive: booleanValue_(category.isActive, true),
legacy: !!category.legacy,
updatedAt: category.updatedAt || ''
};
}
function mapItemForClient_(item) {
if (!item) {
return null;
}
return {
id: item.id || '',
name: item.name || '',
categoryId: item.categoryId || '',
categoryName: item.categoryName || '',
price: normalizeMoney_(item.price),
sku: item.sku || '',
barcode: item.barcode || '',
stockQty: normalizeInteger_(item.stockQty, 0),
stockManaged: booleanValue_(item.stockManaged, false),
minStock: normalizeInteger_(item.minStock, 0),
isActive: booleanValue_(item.isActive, true),
updatedAt: item.updatedAt || ''
};
}
function mapDashboardForClient_(dashboard) {
const source = dashboard || {};
const lowStocks = (source.lowStockItems || []).map(function (item) {
return mapItemForClient_(item);
}).filter(function (item) {
return item !== null;
});
return {
salesToday: normalizeMoney_(source.salesToday),
transactionsToday: normalizeInteger_(source.transactionsToday, 0),
activeItemCount: normalizeInteger_(source.activeItemCount, 0),
lowStockCount: normalizeInteger_(source.lowStockCount, 0),
lowStockItems: lowStocks,
lowStocks: lowStocks,
recentTransactions: source.recentTransactions || [],
trxCount: normalizeInteger_(source.transactionsToday, 0)
};
}
function buildTransactionsForClient_(context, filters) {
const transactions = getTransactionsInternal_(context, filters || {});
const itemRows = readSheetObjects_(context.TransactionItems.sheet);
const itemMap = {};
itemRows.forEach(function (row) {
const trxId = stringValue_(row.trxId);
if (!trxId) {
return;
}
if (!itemMap[trxId]) {
itemMap[trxId] = [];
}
itemMap[trxId].push({
itemId: stringValue_(row.itemId),
name: stringValue_(row.nameSnapshot),
qty: normalizeInteger_(row.qty, 0),
price: normalizeMoney_(row.price),
subtotal: normalizeMoney_(row.subtotal)
});
});
return transactions.map(function (transaction) {
const items = itemMap[transaction.trxId] || parseLegacyDetail_(transaction.detail).map(function (entry) {
return {
itemId: '',
name: entry.name,
qty: entry.qty,
price: 0,
subtotal: 0
};
});
return {
trxId: transaction.trxId,
timestamp: transaction.timestamp,
timestampLabel: transaction.timestampLabel,
total: normalizeMoney_(transaction.total),
detail: transaction.detail,
paymentMethod: transaction.paymentMethod,
itemCount: normalizeInteger_(transaction.itemCount, items.reduce(function (sum, item) {
return sum + normalizeInteger_(item.qty, 0);
}, 0)),
cashReceived: transaction.cashReceived,
changeAmount: transaction.changeAmount,
status: transaction.status,
paidAt: transaction.paidAt || '',
gateway: transaction.gateway || null,
legacy: !!transaction.legacy,
items: items
};
});
}
function validateSalePayload_(context, payload) {
const inventory = getInventoryContext_(context);
const items = Array.isArray(payload.items) ? payload.items : [];
const paymentMethod = stringValue_(payload.paymentMethod).toLowerCase() || 'cash';
const cashReceived = payload.cashReceived === '' || payload.cashReceived === null || typeof payload.cashReceived === 'undefined'
? ''
: normalizeMoney_(payload.cashReceived);
if (items.length === 0) {
throw new Error('Keranjang masih kosong.');
}
if (PAYMENT_METHODS.indexOf(paymentMethod) === -1) {
throw new Error('Metode pembayaran tidak valid.');
}
let total = 0;
let itemCount = 0;
const saleItems = items.map(function (entry) {
const itemId = stringValue_(entry && entry.itemId);
const qty = normalizeInteger_(entry && entry.qty, 0);
const item = inventory.itemIndex[itemId];
if (!item) {
throw new Error('Ada produk pada keranjang yang tidak ditemukan.');
}
if (!item.isActive) {
throw new Error('Ada produk tidak aktif pada keranjang.');
}
if (qty <= 0) {
throw new Error('Jumlah item pada keranjang tidak valid.');
}
const beforeQty = item.stockManaged ? item.stockQty : '';
const afterQty = item.stockManaged ? (item.stockQty - qty) : '';
if (item.stockManaged && afterQty < 0) {
throw new Error('Stok produk "' + item.name + '" tidak mencukupi.');
}
const subtotal = item.price * qty;