-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
378 lines (336 loc) · 11.6 KB
/
Copy pathdatabase.js
File metadata and controls
378 lines (336 loc) · 11.6 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
const Database = require('better-sqlite3');
const path = require('path');
const DB_PATH = process.env.DB_PATH || path.join(__dirname, 'givstack.db');
let db;
function getDb() {
if (!db) {
db = new Database(DB_PATH);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
}
return db;
}
function initDb() {
const db = getDb();
db.exec(`
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
);
CREATE TABLE IF NOT EXISTS amount_buttons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
label TEXT NOT NULL,
amount INTEGER NOT NULL,
sort_order INTEGER DEFAULT 0,
active INTEGER DEFAULT 1
);
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price INTEGER DEFAULT 0,
quantity_total INTEGER DEFAULT 1,
quantity_remaining INTEGER DEFAULT 1,
active INTEGER DEFAULT 1,
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS ambassadors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
code TEXT UNIQUE NOT NULL,
goal INTEGER DEFAULT 0,
active INTEGER DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS donations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source TEXT DEFAULT 'nedarim',
payment_method TEXT,
donor_name TEXT,
amount INTEGER NOT NULL,
currency INTEGER DEFAULT 1,
comment TEXT,
item_id INTEGER,
ambassador_id INTEGER,
transaction_id TEXT,
param2 TEXT,
show_in_wall INTEGER DEFAULT 1,
donation_date DATETIME DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
raw_webhook TEXT,
FOREIGN KEY (item_id) REFERENCES items(id),
FOREIGN KEY (ambassador_id) REFERENCES ambassadors(id)
);
CREATE TABLE IF NOT EXISTS updates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
content TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
`);
// Migrations: add new columns to existing DBs without breaking them
const tryAdd = (table, col, type) => {
try { db.exec(`ALTER TABLE ${table} ADD COLUMN ${col} ${type}`); } catch (_) {}
};
tryAdd('donations', 'donor_phone', 'TEXT');
tryAdd('donations', 'donor_email', 'TEXT');
tryAdd('donations', 'donor_taz', 'TEXT');
tryAdd('donations', 'notes', 'TEXT');
seedData(db);
}
function seedData(db) {
// Default settings — all configurable via admin panel after setup
const defaultSettings = {
campaign_name: 'My Campaign',
subtitle: '',
banner_text: '',
goal: '10000',
contact_phone: '',
contact_email: '',
is_active: '1',
show_progress: '1',
show_wall: '1',
start_date: '',
end_date: '',
video_url: '',
matching_text: '',
admin_phone: '',
notify_donor: '0',
bank_details: '',
};
const insertSetting = db.prepare('INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)');
for (const [key, value] of Object.entries(defaultSettings)) {
insertSetting.run(key, value);
}
// Default donation amount buttons
const buttonCount = db.prepare('SELECT COUNT(*) as cnt FROM amount_buttons').get();
if (buttonCount.cnt === 0) {
const insertButton = db.prepare('INSERT INTO amount_buttons (label, amount, sort_order, active) VALUES (?, ?, ?, 1)');
const buttons = [
['$18', 18, 1],
['$36', 36, 2],
['$54', 54, 3],
['$100', 100, 4],
['Custom', 0, 5],
];
for (const [label, amount, sort_order] of buttons) {
insertButton.run(label, amount, sort_order);
}
}
// No default items — add your own via admin panel
}
// ===== SETTINGS =====
function getSetting(key) {
const row = getDb().prepare('SELECT value FROM settings WHERE key = ?').get(key);
return row ? row.value : null;
}
function getAllSettings() {
const rows = getDb().prepare('SELECT key, value FROM settings').all();
const result = {};
for (const row of rows) result[row.key] = row.value;
return result;
}
function setSetting(key, value) {
getDb().prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)').run(key, String(value));
}
function setSettings(obj) {
const stmt = getDb().prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)');
const tx = getDb().transaction((entries) => {
for (const [k, v] of entries) stmt.run(k, String(v));
});
tx(Object.entries(obj));
}
// ===== BUTTONS =====
function getButtons(activeOnly = false) {
// Sort: specific amounts ascending, custom/free (amount=0) buttons last
const order = 'ORDER BY CASE WHEN amount = 0 THEN 999999 ELSE amount END ASC';
const sql = activeOnly
? `SELECT * FROM amount_buttons WHERE active = 1 ${order}`
: `SELECT * FROM amount_buttons ${order}`;
return getDb().prepare(sql).all();
}
function upsertButton(data) {
if (data.id) {
getDb().prepare(`
UPDATE amount_buttons SET label=?, amount=?, sort_order=?, active=? WHERE id=?
`).run(data.label, data.amount, data.sort_order ?? 0, data.active ?? 1, data.id);
return data.id;
} else {
const info = getDb().prepare(`
INSERT INTO amount_buttons (label, amount, sort_order, active) VALUES (?, ?, ?, ?)
`).run(data.label, data.amount, data.sort_order ?? 0, data.active ?? 1);
return info.lastInsertRowid;
}
}
function deleteButton(id) {
getDb().prepare('DELETE FROM amount_buttons WHERE id = ?').run(id);
}
// ===== ITEMS =====
function getItems(activeOnly = false) {
const sql = activeOnly
? 'SELECT * FROM items WHERE active = 1 AND price > 0 ORDER BY sort_order'
: 'SELECT * FROM items ORDER BY sort_order';
return getDb().prepare(sql).all();
}
function getItem(id) {
return getDb().prepare('SELECT * FROM items WHERE id = ?').get(id);
}
function upsertItem(data) {
if (data.id) {
getDb().prepare(`
UPDATE items SET name=?, price=?, quantity_total=?, quantity_remaining=?, active=?, sort_order=? WHERE id=?
`).run(data.name, data.price ?? 0, data.quantity_total ?? 1, data.quantity_remaining ?? 1, data.active ?? 1, data.sort_order ?? 0, data.id);
return data.id;
} else {
const qty = data.quantity_total ?? 1;
const info = getDb().prepare(`
INSERT INTO items (name, price, quantity_total, quantity_remaining, active, sort_order)
VALUES (?, ?, ?, ?, ?, ?)
`).run(data.name, data.price ?? 0, qty, qty, data.active ?? 1, data.sort_order ?? 0);
return info.lastInsertRowid;
}
}
function decrementItem(itemId) {
getDb().prepare(`
UPDATE items SET quantity_remaining = MAX(0, quantity_remaining - 1) WHERE id = ?
`).run(itemId);
}
// ===== AMBASSADORS =====
function getAmbassadors(activeOnly = false) {
const sql = `
SELECT a.*,
COALESCE(SUM(d.amount), 0) as raised,
COUNT(d.id) as donor_count
FROM ambassadors a
LEFT JOIN donations d ON d.ambassador_id = a.id
${activeOnly ? 'WHERE a.active = 1' : ''}
GROUP BY a.id
ORDER BY raised DESC
`;
return getDb().prepare(sql).all();
}
function getAmbassadorByCode(code) {
return getDb().prepare('SELECT * FROM ambassadors WHERE code = ?').get(code);
}
function upsertAmbassador(data) {
if (data.id) {
getDb().prepare(`
UPDATE ambassadors SET name=?, code=?, goal=?, active=? WHERE id=?
`).run(data.name, data.code, data.goal ?? 0, data.active ?? 1, data.id);
return data.id;
} else {
const info = getDb().prepare(`
INSERT INTO ambassadors (name, code, goal, active) VALUES (?, ?, ?, ?)
`).run(data.name, data.code, data.goal ?? 0, data.active ?? 1);
return info.lastInsertRowid;
}
}
function deleteAmbassador(id) {
getDb().prepare('DELETE FROM ambassadors WHERE id = ?').run(id);
}
// ===== DONATIONS =====
function getDonations({ limit = 20, offset = 0, wallOnly = true } = {}) {
const sql = `
SELECT d.*, i.name as item_name
FROM donations d
LEFT JOIN items i ON i.id = d.item_id
${wallOnly ? 'WHERE d.show_in_wall = 1' : ''}
ORDER BY d.donation_date DESC
LIMIT ? OFFSET ?
`;
return getDb().prepare(sql).all(limit, offset);
}
function getAllDonationsForExport() {
return getDb().prepare(`
SELECT d.*, i.name as item_name, a.name as ambassador_name
FROM donations d
LEFT JOIN items i ON i.id = d.item_id
LEFT JOIN ambassadors a ON a.id = d.ambassador_id
ORDER BY d.donation_date DESC
`).all();
}
function getAdminDonations({ limit = 50, offset = 0 } = {}) {
return getDb().prepare(`
SELECT d.*, i.name as item_name, a.name as ambassador_name
FROM donations d
LEFT JOIN items i ON i.id = d.item_id
LEFT JOIN ambassadors a ON a.id = d.ambassador_id
ORDER BY d.donation_date DESC
LIMIT ? OFFSET ?
`).all(limit, offset);
}
function updateDonation(id, data) {
getDb().prepare(`
UPDATE donations SET donor_name=?, amount=?, comment=?, show_in_wall=? WHERE id=?
`).run(data.donor_name ?? null, data.amount, data.comment ?? null, data.show_in_wall ?? 1, id);
}
function getStats() {
const db = getDb();
const totals = db.prepare(`
SELECT COALESCE(SUM(amount), 0) as total_raised, COUNT(*) as donor_count,
MAX(donation_date) as last_donation_at
FROM donations
`).get();
const goal = parseInt(getSetting('goal') || '120750', 10);
const percentage = goal > 0 ? Math.min(100, Math.round((totals.total_raised / goal) * 100)) : 0;
return { ...totals, goal, percentage };
}
function isDuplicateWebhook(param2) {
const row = getDb().prepare('SELECT id FROM donations WHERE param2 = ?').get(param2);
return !!row;
}
function insertDonation(data) {
const info = getDb().prepare(`
INSERT INTO donations
(source, payment_method, donor_name, donor_phone, donor_email, donor_taz,
amount, currency, comment, notes,
item_id, ambassador_id, transaction_id, param2, show_in_wall,
donation_date, raw_webhook)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
data.source ?? 'nedarim',
data.payment_method ?? null,
data.donor_name ?? null,
data.donor_phone ?? null,
data.donor_email ?? null,
data.donor_taz ?? null,
data.amount,
data.currency ?? 1,
data.comment ?? null,
data.notes ?? null,
data.item_id ?? null,
data.ambassador_id ?? null,
data.transaction_id ?? null,
data.param2 ?? null,
data.show_in_wall ?? 1,
data.donation_date ?? new Date().toISOString(),
data.raw_webhook ?? null
);
return info.lastInsertRowid;
}
// ===== UPDATES =====
function getUpdates() {
return getDb().prepare('SELECT * FROM updates ORDER BY created_at DESC').all();
}
function upsertUpdate(data) {
if (data.id) {
getDb().prepare('UPDATE updates SET title=?, content=?, created_at=? WHERE id=?')
.run(data.title ?? null, data.content, data.created_at ?? new Date().toISOString(), data.id);
return data.id;
} else {
const info = getDb().prepare('INSERT INTO updates (title, content, created_at) VALUES (?, ?, ?)')
.run(data.title ?? null, data.content, data.created_at ?? new Date().toISOString());
return info.lastInsertRowid;
}
}
function deleteUpdate(id) {
getDb().prepare('DELETE FROM updates WHERE id = ?').run(id);
}
module.exports = {
initDb,
getSetting, getAllSettings, setSetting, setSettings,
getButtons, upsertButton, deleteButton,
getItems, getItem, upsertItem, decrementItem,
getAmbassadors, getAmbassadorByCode, upsertAmbassador, deleteAmbassador,
getDonations, getAdminDonations, getAllDonationsForExport, getStats, isDuplicateWebhook, insertDonation, updateDonation,
getUpdates, upsertUpdate, deleteUpdate,
};