Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
347 lines (307 loc) · 12.1 KB
/
Copy pathserver.js
File metadata and controls
347 lines (307 loc) · 12.1 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
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const PORT = 3001;
const DB_PATH = path.join(__dirname, 'budget.db');
// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(__dirname)); // Serve static files (like index.html)
// Database Setup
const db = new sqlite3.Database(DB_PATH, (err) => {
if (err) {
console.error('Error opening database:', err.message);
} else {
console.log('Connected to the SQLite database.');
initDb();
}
});
function initDb() {
// Basic Table: Entries
db.run(`CREATE TABLE IF NOT EXISTS entries (
id TEXT PRIMARY KEY,
group_type TEXT,
name TEXT,
amount INTEGER,
account TEXT,
interval TEXT,
category TEXT,
is_security INTEGER,
savings_type TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`, () => {
// Migration: Add new columns if they don't exist
const columns = [
'ALTER TABLE entries ADD COLUMN owner TEXT DEFAULT "main"',
'ALTER TABLE entries ADD COLUMN paid_by TEXT DEFAULT "main"',
'ALTER TABLE entries ADD COLUMN is_shared INTEGER DEFAULT 0',
'ALTER TABLE entries ADD COLUMN linked_id TEXT'
];
columns.forEach(col => {
db.run(col, (err) => {
if (err && !err.message.includes('duplicate column')) {
console.log('Migration note:', err.message);
}
});
});
});
// Accounts Table
db.run(`CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY,
name TEXT,
owner TEXT,
iban TEXT
)`, () => {
// Seed Default Accounts if empty
db.get("SELECT count(*) as count FROM accounts", [], (err, row) => {
if (err) return console.error(err);
if (row.count === 0) {
console.log("Seeding default accounts...");
const stmt = db.prepare("INSERT INTO accounts (id, name, owner, iban) VALUES (?, ?, ?, ?)");
const defaults = [
['a1', 'N26 (Hauptkonto)', 'main', ''],
['a2', 'N26 (Versicherungen)', 'main', ''],
['a3', 'N26 (Lifestyle)', 'main', ''],
['a4', 'N26 (Abos)', 'main', ''],
['a5', 'N26 (Rücklagen)', 'main', ''],
['a6', 'N26 (Urlaub)', 'main', ''],
['a7', 'N26 (Auto)', 'main', ''],
['a8', 'C24 (Mein Konto)', 'main', ''],
['a9', 'C24 (Gemeinschaftskonto)', 'shared', ''],
['a10', 'C24 (Persönliches Konto)', 'partner', ''],
['a11', 'Postbank Konto', 'partner', '']
];
defaults.forEach(acc => stmt.run(acc));
stmt.finalize();
}
});
});
}
// API Endpoints
// GET all entries
app.get('/api/entries', (req, res) => {
let query = "SELECT * FROM entries";
db.all(query, [], (err, rows) => {
if (err) {
res.status(400).json({ "error": err.message });
return;
}
const state = {
fixkosten: [],
budget: [],
income: [],
savings: []
};
rows.forEach(row => {
const entry = {
id: row.id,
name: row.name,
amount: row.amount,
account: row.account,
owner: row.owner,
paidBy: row.paid_by,
isShared: !!row.is_shared,
linkedId: row.linked_id
};
if (row.group_type === 'fixkosten') {
entry.interval = row.interval;
entry.category = row.category;
entry.isSecurity = !!row.is_security;
state.fixkosten.push(entry);
} else if (row.group_type === 'budget') {
state.budget.push(entry);
} else if (row.group_type === 'income') {
state.income.push(entry);
} else if (row.group_type === 'savings') {
entry.type = row.savings_type;
state.savings.push(entry);
}
});
res.json(state);
});
});
// POST (Create or Update)
app.post('/api/entries', (req, res) => {
const { id, type, data, isSplit } = req.body;
// Determine values
const owner = data.owner || 'main';
const paidBy = data.paidBy || 'main';
let amount = data.amount;
// SQLite Booleans are 0/1
const isSecurity = data.isSecurity ? 1 : 0;
const isShared = (isSplit || data.isShared) ? 1 : 0;
const stmt = db.prepare(`INSERT OR REPLACE INTO entries
(id, group_type, name, amount, account, interval, category, is_security, savings_type, owner, paid_by, is_shared, linked_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
// Special Handling for Shared Account Initial Creation (owner === 'shared')
if (owner === 'shared') {
// 1. Create Master Entry (100% Amount, Owner='shared')
stmt.run(
id, type, data.name, amount, data.account,
data.interval || null, data.category || null,
isSecurity, data.type || null,
'shared', 'main', 1, null, // Owner=shared, PaidBy=main(default), IsShared=1
(err) => {
if (err) {
res.status(400).json({ "error": err.message });
return;
}
// 2. Create Linked Main Entry (50%, Owner='main')
const mainId = id + '_main';
stmt.run(
mainId, type, data.name, Math.round(amount / 2), data.account,
data.interval || null, data.category || null,
isSecurity, data.type || null,
'main', 'main', 1, id, // Linked to Master
(err) => { if (err) console.error("Error creating main split:", err); }
);
// 3. Create Linked Partner Entry (50%, Owner='partner')
const partnerId = id + '_partner';
stmt.run(
partnerId, type, data.name, Math.round(amount / 2), data.account,
data.interval || null, data.category || null,
isSecurity, data.type || null,
'partner', 'main', 1, id, // Linked to Master
(err) => {
if (err) console.error("Error creating partner split:", err);
// Finalize after last insert
stmt.finalize();
res.json({ "message": "success", "id": id });
}
);
}
);
return; // EXIT early, do not run standard logic below
}
// Standard Logic for Normal Entries (Owner = 'main' or 'partner')
// Split Logic: If split, we NO LONGER halve the amount for the main entry.
// The main entry keeps the full amount (for bank reconciliation).
// The partner entry will get half.
if (isSplit) {
// amount remains data.amount
}
// 1. Run Main Insert
stmt.run(
id, type, data.name, amount, data.account,
data.interval || null, data.category || null,
isSecurity, data.type || null,
owner, paidBy, isShared, data.linkedId || null,
function (err) {
if (err) {
res.status(400).json({ "error": err.message });
return;
}
// 2. If Split, create Partner Entry
if (isSplit) {
const partnerId = id + '_partner';
const otherOwner = owner === 'main' ? 'partner' : 'main';
// Partner entry mirrors main entry but with half amount and linked_id
// Note: paid_by remains whoever paid the original amount!
stmt.run(
partnerId, type, data.name, Math.round(amount / 2), data.account,
data.interval || null, data.category || null,
isSecurity, data.type || null,
otherOwner, paidBy, 1, id, // linked to primary
(err) => {
if (err) console.error("Error creating split entry:", err);
stmt.finalize();
res.json({ "message": "success", "id": id });
}
);
} else {
// If NOT split (anymore), ensure any existing partner entry is removed
// and the current entry is marked as not shared
const partnerId = id + '_partner';
db.run("DELETE FROM entries WHERE id = ?", partnerId, (err) => {
if (err) console.error("Error deleting partner entry:", err);
stmt.finalize();
res.json({ "message": "success", "id": id });
});
}
}
);
});
// DELETE entry
app.delete('/api/entries/:id', (req, res) => {
const id = req.params.id;
// Delete the entry AND any entries linked to it (splits)
db.run("DELETE FROM entries WHERE id = ? OR linked_id = ?", [id, id], function (err) {
if (err) {
res.status(400).json({ "error": err.message });
return;
}
res.json({ message: "deleted", changes: this.changes });
});
});
// Accounts API
// GET accounts
app.get('/api/accounts', (req, res) => {
db.all("SELECT * FROM accounts", [], (err, rows) => {
if (err) {
res.status(400).json({ "error": err.message });
return;
}
res.json(rows);
});
});
// POST (Create/Update) account
// POST (Create/Update) account
app.post('/api/accounts', (req, res) => {
const { id, name, owner, iban } = req.body;
// Check for rename scenario
db.get("SELECT name FROM accounts WHERE id = ?", [id], (err, row) => {
if (err) {
res.status(400).json({ "error": err.message });
return;
}
const proceed = () => {
const sql = `INSERT OR REPLACE INTO accounts (id, name, owner, iban) VALUES (?, ?, ?, ?)`;
db.run(sql, [id, name, owner, iban], (err) => {
if (err) {
res.status(400).json({ "error": err.message });
return;
}
res.json({ message: "success", id });
});
};
if (row && row.name !== name) {
// Account exists and name has changed: Update entries
console.log(`Renaming account '${row.name}' to '${name}' in entries...`);
db.run("UPDATE entries SET account = ? WHERE account = ?", [name, row.name], (err) => {
if (err) console.error("Error updating entries for account rename:", err);
proceed();
});
} else {
proceed();
}
});
});
// DELETE account
// DELETE account
app.delete('/api/accounts/:id', (req, res) => {
const id = req.params.id;
// First get the name to migrate entries
db.get("SELECT name FROM accounts WHERE id = ?", [id], (err, row) => {
if (err) return res.status(400).json({ "error": err.message });
if (!row) return res.status(404).json({ "error": "Account not found" });
const accName = row.name;
// Migrate entries to 'Unzugeordnet'
db.run("UPDATE entries SET account = 'Unzugeordnet' WHERE account = ?", [accName], (err) => {
if (err) return res.status(400).json({ "error": err.message });
// Now delete the account
db.run("DELETE FROM accounts WHERE id = ?", [id], function (err) {
if (err) {
res.status(400).json({ "error": err.message });
return;
}
res.json({ message: "deleted", changes: this.changes });
});
});
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});