Repository navigation
Expand file tree
/
Copy pathdata.js
More file actions
294 lines (258 loc) · 12.2 KB
/
Copy pathdata.js
File metadata and controls
294 lines (258 loc) · 12.2 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
// ============================================================
// Bank Sampah Digital Sekolah - Data Layer & localStorage
// ============================================================
const BSD_KEYS = {
USERS: 'bsd_users',
CATEGORIES: 'bsd_categories',
TRANSACTIONS: 'bsd_transactions',
TRANSACTION_ITEMS: 'bsd_transaction_items',
REWARDS: 'bsd_rewards',
REDEMPTIONS: 'bsd_redemptions',
INITIALIZED: 'bsd_initialized_v2' // bumped version to force re-initialization if needed
};
const SEED_DATA = {
users: [
{ id: 'u1', nis: '10001', password: 'siswa123', nama: 'Muhamad Haikal Setiawan', kelas: '10 RPL', role: 'siswa', totalPoin: 45 },
{ id: 'u2', nis: '10002', password: 'siswa123', nama: 'Siti Rahayu', kelas: '10 AK', role: 'siswa', totalPoin: 82 },
{ id: 'u3', nis: '10003', password: 'siswa123', nama: 'Budi Santoso', kelas: '10 RPL', role: 'siswa', totalPoin: 31 },
{ id: 'u4', nis: '10004', password: 'siswa123', nama: 'Dewi Lestari', kelas: '10 MP', role: 'siswa', totalPoin: 99 },
{ id: 'u5', nis: '10005', password: 'siswa123', nama: 'Rizky Pratama', kelas: '10 DKV 1', role: 'siswa', totalPoin: 120 },
{ id: 'u6', nis: '10006', password: 'siswa123', nama: 'Nur Aisyah', kelas: '10 DKV 2', role: 'siswa', totalPoin: 75 },
{ id: 'u7', nis: '11001', password: 'siswa123', nama: 'Eko Widodo', kelas: '11 BR', role: 'siswa', totalPoin: 58 },
{ id: 'u8', nis: '11002', password: 'siswa123', nama: 'Fitri Handayani', kelas: '11 AK', role: 'siswa', totalPoin: 145 },
{ id: 'u9', nis: '11003', password: 'siswa123', nama: 'Galih Permana', kelas: '11 RPL', role: 'siswa', totalPoin: 92 },
{ id: 'u10', nis: '11004', password: 'siswa123', nama: 'Hana Pertiwi', kelas: '11 MP', role: 'siswa', totalPoin: 67 },
{ id: 'u11', nis: '11005', password: 'siswa123', nama: 'Iqbal Ramadhan', kelas: '11 DKV 1', role: 'siswa', totalPoin: 110 },
{ id: 'u12', nis: '11006', password: 'siswa123', nama: 'Jihan Nabila', kelas: '11 DKV 2', role: 'siswa', totalPoin: 88 },
{ id: 'p1', nis: '99001', password: 'petugas123', nama: 'Pak Joko (OSIS)', kelas: '-', role: 'petugas', totalPoin: 0 },
{ id: 'a1', nis: '00001', password: 'admin123', nama: 'Bu Rini (Admin)', kelas: '-', role: 'admin', totalPoin: 0 }
],
categories: [
{ id: 'k1', nama: 'Kardus', satuan: 'box', poinPerSatuan: 2, icon: '📦', color: '#f59e0b', description: 'Kardus/box bekas' },
{ id: 'k2', nama: 'Botol', satuan: 'pcs', poinPerSatuan: 3, icon: '♻️', color: '#3b82f6', description: 'Botol plastik/kaca' },
{ id: 'k3', nama: 'Kaleng', satuan: 'pcs', poinPerSatuan: 4, icon: '🥫', color: '#ef4444', description: 'Kaleng minuman/makanan' },
{ id: 'k4', nama: 'Kertas', satuan: 'pcs', poinPerSatuan: 1, icon: '📄', color: '#8b5cf6', description: 'Kertas bekas' },
{ id: 'k5', nama: 'Plastik', satuan: 'pcs', poinPerSatuan: 1, icon: '🛍️', color: '#10b981', description: 'Kantong/kemasan plastik' }
],
rewards: [
{ id: 'r1', nama: 'Permen / Yupi', deskripsi: 'Snack manis', poinDibutuhkan: 10, stok: 100, icon: '🍬' },
{ id: 'r2', nama: 'Pensil / Penghapus', deskripsi: 'Alat tulis dasar', poinDibutuhkan: 15, stok: 50, icon: '✏️' },
{ id: 'r3', nama: 'Snack Taro / Chiki', deskripsi: 'Snack ringan kemasan', poinDibutuhkan: 20, stok: 30, icon: '🥔' },
{ id: 'r4', nama: 'Teh Kotak / Susu', deskripsi: 'Minuman kotak segar', poinDibutuhkan: 25, stok: 20, icon: '🧃' },
{ id: 'r5', nama: 'Buku Tulis', deskripsi: 'Buku tulis sekolah', poinDibutuhkan: 30, stok: 15, icon: '📓' }
],
transactions: [],
transactionItems: [],
redemptions: []
};
// ============================================================
// Database Helpers
// ============================================================
const DB = {
_get: (key) => JSON.parse(localStorage.getItem(key) || '[]'),
_set: (key, data) => localStorage.setItem(key, JSON.stringify(data)),
init() {
if (!localStorage.getItem(BSD_KEYS.INITIALIZED)) {
this._set(BSD_KEYS.USERS, SEED_DATA.users);
this._set(BSD_KEYS.CATEGORIES, SEED_DATA.categories);
this._set(BSD_KEYS.TRANSACTIONS, SEED_DATA.transactions);
this._set(BSD_KEYS.TRANSACTION_ITEMS, SEED_DATA.transactionItems);
this._set(BSD_KEYS.REWARDS, SEED_DATA.rewards);
this._set(BSD_KEYS.REDEMPTIONS, SEED_DATA.redemptions);
localStorage.setItem(BSD_KEYS.INITIALIZED, 'true');
}
},
reset() {
Object.values(BSD_KEYS).forEach(k => localStorage.removeItem(k));
this.init();
},
// Getters
getUsers: () => DB._get(BSD_KEYS.USERS),
getCategories: () => DB._get(BSD_KEYS.CATEGORIES),
getTransactions: () => DB._get(BSD_KEYS.TRANSACTIONS),
getTransactionItems: () => DB._get(BSD_KEYS.TRANSACTION_ITEMS),
getRewards: () => DB._get(BSD_KEYS.REWARDS),
getRedemptions: () => DB._get(BSD_KEYS.REDEMPTIONS),
// Setters
saveUsers: (d) => DB._set(BSD_KEYS.USERS, d),
saveCategories: (d) => DB._set(BSD_KEYS.CATEGORIES, d),
saveTransactions: (d) => DB._set(BSD_KEYS.TRANSACTIONS, d),
saveTransactionItems: (d) => DB._set(BSD_KEYS.TRANSACTION_ITEMS, d),
saveRewards: (d) => DB._set(BSD_KEYS.REWARDS, d),
saveRedemptions: (d) => DB._set(BSD_KEYS.REDEMPTIONS, d),
// Finders
getUserByNIS: (nis) => DB.getUsers().find(u => u.nis === nis),
getUserById: (id) => DB.getUsers().find(u => u.id === id),
getCategoryById: (id) => DB.getCategories().find(c => c.id === id),
getTransactionById: (id) => DB.getTransactions().find(t => t.id === id),
getRewardById: (id) => DB.getRewards().find(r => r.id === id),
getUserTransactions: (uid) => DB.getTransactions().filter(t => t.userId === uid).sort((a, b) => new Date(b.dibuatPada) - new Date(a.dibuatPada)),
getItemsByTransaction: (tid) => DB.getTransactionItems().filter(i => i.transaksiId === tid),
getPendingTransactions: () => DB.getTransactions().filter(t => t.status === 'menunggu').sort((a, b) => new Date(b.dibuatPada) - new Date(a.dibuatPada)),
getUserRedemptions: (uid) => DB.getRedemptions().filter(r => r.userId === uid).sort((a, b) => new Date(b.tanggal) - new Date(a.tanggal)),
// ID Generator
genId: (prefix) => `${prefix}${Date.now()}${Math.random().toString(36).substr(2, 6)}`,
// User points update
updateUserPoints(userId, delta) {
const users = DB.getUsers();
const idx = users.findIndex(u => u.id === userId);
if (idx !== -1) {
users[idx].totalPoin = Math.max(0, users[idx].totalPoin + delta);
DB.saveUsers(users);
// Update session if this is the current user
const session = sessionStorage.getItem('bsd_session');
if (session) {
const s = JSON.parse(session);
if (s.id === userId) {
s.totalPoin = users[idx].totalPoin;
sessionStorage.setItem('bsd_session', JSON.stringify(s));
}
}
}
},
// Create transaction
createTransaction(userId, items) {
const categories = DB.getCategories();
let totalEstimasi = 0;
items.forEach(item => {
const cat = categories.find(c => c.id === item.kategoriId);
if (cat) totalEstimasi += cat.poinPerSatuan * parseFloat(item.jumlah);
});
const tx = {
id: DB.genId('tr'),
userId,
status: 'menunggu',
totalPoinEstimasi: Math.round(totalEstimasi),
totalPoinAktual: null,
diverifikasiOleh: null,
dibuatPada: new Date().toISOString(),
diverifikasiPada: null
};
const txs = DB.getTransactions();
txs.unshift(tx);
DB.saveTransactions(txs);
const allItems = DB.getTransactionItems();
items.forEach(item => {
allItems.push({
id: DB.genId('ti'),
transaksiId: tx.id,
kategoriId: item.kategoriId,
jumlahEstimasi: parseFloat(item.jumlah),
jumlahAktual: null
});
});
DB.saveTransactionItems(allItems);
return tx;
},
// Verify transaction
verifyTransaction(transactionId, petugasId, corrections, approve) {
const txs = DB.getTransactions();
const items = DB.getTransactionItems();
const categories = DB.getCategories();
const txIdx = txs.findIndex(t => t.id === transactionId);
if (txIdx === -1) return null;
if (!approve) {
txs[txIdx].status = 'ditolak';
txs[txIdx].diverifikasiOleh = petugasId;
txs[txIdx].diverifikasiPada = new Date().toISOString();
txs[txIdx].totalPoinAktual = 0;
DB.saveTransactions(txs);
return txs[txIdx];
}
let totalAktual = 0;
corrections.forEach(c => {
const iIdx = items.findIndex(i => i.id === c.itemId);
if (iIdx !== -1) {
items[iIdx].jumlahAktual = parseFloat(c.jumlahAktual);
const cat = categories.find(cat => cat.id === items[iIdx].kategoriId);
if (cat) totalAktual += cat.poinPerSatuan * parseFloat(c.jumlahAktual);
}
});
txs[txIdx].status = 'terverifikasi';
txs[txIdx].diverifikasiOleh = petugasId;
txs[txIdx].diverifikasiPada = new Date().toISOString();
txs[txIdx].totalPoinAktual = Math.round(totalAktual);
DB.saveTransactions(txs);
DB.saveTransactionItems(items);
DB.updateUserPoints(txs[txIdx].userId, Math.round(totalAktual));
return txs[txIdx];
},
// Redeem reward
redeemReward(userId, rewardId) {
const rewards = DB.getRewards();
const users = DB.getUsers();
const rIdx = rewards.findIndex(r => r.id === rewardId);
const uIdx = users.findIndex(u => u.id === userId);
if (rIdx === -1 || uIdx === -1) return { success: false, msg: 'Data tidak ditemukan.' };
const reward = rewards[rIdx];
const user = users[uIdx];
if (user.totalPoin < reward.poinDibutuhkan) return { success: false, msg: 'Poin tidak cukup.' };
if (reward.stok <= 0) return { success: false, msg: 'Stok habis.' };
rewards[rIdx].stok -= 1;
DB.saveRewards(rewards);
const redemptions = DB.getRedemptions();
redemptions.unshift({
id: DB.genId('rd'),
userId,
rewardId,
rewardNama: reward.nama,
rewardIcon: reward.icon,
poinDigunakan: reward.poinDibutuhkan,
tanggal: new Date().toISOString()
});
DB.saveRedemptions(redemptions);
// updateUserPoints handles save + session update
DB.updateUserPoints(userId, -reward.poinDibutuhkan);
return { success: true, msg: `Berhasil menukar poin dengan ${reward.nama}! 🎉` };
},
// Leaderboard
getLeaderboardIndividu() {
return DB.getUsers()
.filter(u => u.role === 'siswa')
.sort((a, b) => b.totalPoin - a.totalPoin)
.map((u, i) => ({ ...u, rank: i + 1 }));
},
getLeaderboardKelas() {
const students = DB.getUsers().filter(u => u.role === 'siswa');
const kelasMap = {};
students.forEach(s => {
if (!kelasMap[s.kelas]) kelasMap[s.kelas] = { kelas: s.kelas, totalPoin: 0, anggota: 0 };
kelasMap[s.kelas].totalPoin += s.totalPoin;
kelasMap[s.kelas].anggota++;
});
return Object.values(kelasMap)
.sort((a, b) => b.totalPoin - a.totalPoin)
.map((k, i) => ({ ...k, rank: i + 1 }));
},
// Admin stats
getAdminStats() {
const verifiedTxs = DB.getTransactions().filter(t => t.status === 'terverifikasi');
const allTxs = DB.getTransactions();
const items = DB.getTransactionItems();
const categories = DB.getCategories();
const byCat = {};
categories.forEach(c => {
byCat[c.id] = { nama: c.nama, totalKg: 0, totalPoin: 0, icon: c.icon, color: c.color };
});
verifiedTxs.forEach(tx => {
const txItems = items.filter(i => i.transaksiId === tx.id && i.jumlahAktual != null);
txItems.forEach(item => {
if (byCat[item.kategoriId]) {
const cat = categories.find(c => c.id === item.kategoriId);
byCat[item.kategoriId].totalKg += item.jumlahAktual;
if (cat) byCat[item.kategoriId].totalPoin += cat.poinPerSatuan * item.jumlahAktual;
}
});
});
const totalSampah = Object.values(byCat).reduce((a, c) => a + c.totalKg, 0);
return {
totalTransaksi: verifiedTxs.length,
totalMenunggu: allTxs.filter(t => t.status === 'menunggu').length,
totalDitolak: allTxs.filter(t => t.status === 'ditolak').length,
totalSampahKg: totalSampah.toFixed(1),
totalSiswaAktif: DB.getUsers().filter(u => u.role === 'siswa' && u.totalPoin > 0).length,
byCat: Object.values(byCat),
recentTxs: verifiedTxs.slice(-5).reverse()
};
}
};