-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1511 lines (1277 loc) · 51.8 KB
/
index.js
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 express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const cookieParser = require('cookie-parser');
const multer = require('multer');
const { parse } = require('fast-csv');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const axiosRetry = require('axios-retry').default;
const { body, validationResult } = require('express-validator');
const winston = require('winston');
dotenv.config();
// Initialize Express
const app = express();
const port = 3000;
// Configure multer for file uploads
const upload = multer({
dest: 'uploads/',
limits: { fileSize: 5 * 1024 * 1024 } // 5 MB limit
});
// Logger setup using Winston
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Configure Axios with retry logic
axiosRetry(axios, { retries: 3, retryDelay: axiosRetry.exponentialDelay });
const cache = {
goldPrice: null,
timestamp: null
};
// Middleware to parse JSON
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(cookieParser());
// Create a MariaDB connection pool
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// Middleware to check if user is logged in
function checkLoginStatus(req, res, next) {
const token = req.cookies.token;
if (!token) {
req.loggedIn = false;
return next();
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.loggedIn = true;
req.userId = decoded.id;
req.username = decoded.username;
} catch (error) {
logger.error('JWT verification failed', { error });
req.loggedIn = false;
}
next();
}
// Helper function to validate user inputs
function validateInputs(validations) {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
};
}
// Routes
app.set('view engine', 'ejs');
// Basic routes
app.get('/', checkLoginStatus, (req, res) => {
res.render('index', { loggedIn: req.loggedIn, username: req.username });
});
// Get the value of 2.25 troy ounces of gold
app.get('/api/gold-price', async (req, res) => {
try {
const now = Date.now();
const oneDay = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
const today = new Date().toISOString().slice(0, 10).replace(/-/g, ''); // Format: YYYYMMDD for GoldAPI
const { date = today } = req.query; // Default to today's date
const formattedGoldApiDate = date; // GoldAPI format: YYYYMMDD
const formattedMetalPriceDate = `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6)}`; // MetalPriceAPI format: YYYY-MM-DD
// Check cache
if (cache.goldPrice && cache.timestamp && cache.date === date && now - cache.timestamp < oneDay) {
logger.info(`Serving cached gold price for date: ${date}`);
return res.json({ value: cache.goldPrice });
}
let goldPrice;
// Primary API: MetalPriceAPI
try {
const apiKeyMetalPriceApi = process.env.METAL_PRICE_API_KEY;
const apiUrlMetalPriceApi = date === today
? `https://api.metalpriceapi.com/v1/latest?api_key=${apiKeyMetalPriceApi}&base=USD¤cies=XAU`
: `https://api.metalpriceapi.com/v1/${formattedMetalPriceDate}?api_key=${apiKeyMetalPriceApi}&base=USD¤cies=XAU`;
const responseMetalPriceApi = await axios.get(apiUrlMetalPriceApi);
// Extract gold price from MetalPriceAPI response
goldPrice = responseMetalPriceApi.data.rates?.USDXAU;
if (!goldPrice) {
throw new Error('Gold price is missing in MetalPriceAPI response.');
}
logger.info(`Fetched gold price from MetalPriceAPI for date: ${date}`);
} catch (metalPriceApiError) {
logger.error('MetalPriceAPI failed, switching to GoldAPI', { error: metalPriceApiError.message });
// Fallback API: GoldAPI
try {
const apiKeyGoldApi = process.env.GOLD_API_KEY;
const apiUrlGoldApi = date === today
? `https://www.goldapi.io/api/XAU/USD` // Current price endpoint
: `https://www.goldapi.io/api/XAU/USD/${formattedGoldApiDate}`; // Historical price endpoint
const responseGoldApi = await axios.get(apiUrlGoldApi, {
headers: {
'x-access-token': apiKeyGoldApi,
'Content-Type': 'application/json',
},
});
// Extract gold price from GoldAPI response
goldPrice = responseGoldApi.data.price;
if (!goldPrice) {
throw new Error('Gold price is missing in GoldAPI response.');
}
logger.info(`Fetched gold price from GoldAPI for date: ${date}`);
} catch (goldApiError) {
logger.error('Both MetalPriceAPI and GoldAPI failed', {
metalPriceApiError: metalPriceApiError.message,
goldApiError: goldApiError.message,
});
return res.status(500).json({ value: null, error: 'Gold price unavailable' });
}
}
// Calculate mithqal price
const mithqalPrice = goldPrice * 2.22456;
// Update cache
cache.goldPrice = mithqalPrice;
cache.timestamp = now;
cache.date = date;
logger.info(`Fetched and cached gold price for date: ${date}`);
return res.json({ value: mithqalPrice });
} catch (error) {
logger.error('Unexpected error fetching gold price', { error });
res.status(500).json({ value: null, error: 'Gold price unavailable' });
}
});
app.get('/help', checkLoginStatus, (req, res) => {
res.render('help', { loggedIn: req.loggedIn, username: req.username });
});
app.get('/public-dashboard', checkLoginStatus, (req, res) => {
const labels = [
// Example placeholder labels for demonstration
{ id: 1, category: 'Assets', label: 'Total' },
{ id: 2, category: 'Debts', label: 'Total' },
{ id: 3, category: 'Expenses', label: 'Total' },
];
const summaries = [];
const entries = [];
const entryMap = labels.map(label => ({
id: label.id,
category: label.category,
label: label.label,
values: [], // Start with no values
}));
res.render('public-dashboard', {
loggedIn: false,
username: null,
summaries,
labels,
entries,
entryMap,
});
});
app.get('/register', (req, res) => {
res.render('register', { loggedIn: false });
});
app.get('/login', (req, res) => {
res.render('login', { loggedIn: false });
});
app.get('/logout', (req, res) => {
res.clearCookie('token');
res.redirect('/');
});
// User Registration Endpoint
app.post(
'/register',
[
body('username').isAlphanumeric().withMessage('Username must be alphanumeric'),
body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters'),
body('email').isEmail().withMessage('Must be a valid email')
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('register', { errors: errors.array(), loggedIn: false });
}
const { username, password, email } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
await pool.query('INSERT INTO users (username, password, email) VALUES (?, ?, ?)', [username, hashedPassword, email]);
res.redirect('/login');
} catch (error) {
logger.error('Error during registration', { error });
res.status(500).render('register', {
errorMessage: 'An error occurred during registration. Please try again.',
loggedIn: false
});
}
}
);
// User Login Endpoint
app.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
const [rows] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
if (rows.length === 0) {
return res.status(401).render('login', { errorMessage: 'User not found', loggedIn: false });
}
const user = rows[0];
const isPasswordMatch = await bcrypt.compare(password, user.password);
if (!isPasswordMatch) {
return res.status(401).render('login', { errorMessage: 'Incorrect password', loggedIn: false });
}
const token = jwt.sign({ id: user.id, username: user.username }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'Strict' });
res.redirect('/');
} catch (error) {
logger.error('Error during login', { error });
res.status(500).render('login', { errorMessage: 'An error occurred during login.', loggedIn: false });
}
});
// Dashboard route
app.get('/dashboard', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.redirect('/login');
}
try {
const userId = req.userId;
// Fetch all labels for the user
const [labels] = await pool.query(
`
SELECT
id,
user_id,
category,
label
FROM financial_labels
WHERE user_id = ?
ORDER BY category ASC, label ASC
`,
[userId]
);
// Fetch all financial entries with normalized reporting_date
const [entries] = await pool.query(
`
SELECT
fv.id,
fv.user_id,
fv.label_id,
DATE_FORMAT(fv.reporting_date, '%Y-%m-%d') AS reporting_date, -- Normalize date format
fv.value,
fl.category,
fl.label
FROM financial_entries fv
JOIN financial_labels fl ON fv.label_id = fl.id
WHERE fv.user_id = ?
ORDER BY fv.reporting_date ASC, fl.category ASC, fl.label ASC
`,
[userId]
);
// Check if entries exist
if (entries.length === 0) {
const entryMap = labels.map(label => ({
id: label.id,
category: label.category,
label: label.label,
values: [], // No financial entries, so values are empty
}));
return res.render('dashboard', {
loggedIn: req.loggedIn,
username: req.username,
summaries: [], // No summaries because no entries exist
labels,
entries: [], // No entries
entryMap, // Labels-only entryMap
});
}
// Fetch financial summaries only if entries exist
const [summaries] = await pool.query(
`
SELECT
id,
user_id,
DATE_FORMAT(start_date, '%Y-%m-%d') AS start_date,
DATE_FORMAT(end_date, '%Y-%m-%d') AS end_date,
total_assets,
total_debts,
unnecessary_expenses,
wealth_already_taxed,
gold_rate,
huquq_payments_made
FROM financial_summary
WHERE user_id = ?
ORDER BY end_date ASC
`,
[userId]
);
// Transform the data for easier rendering
const entryMap = labels.map(label => {
const labelEntries = entries.filter(entry => entry.label_id === label.id);
return {
id: label.id,
category: label.category,
label: label.label,
values: summaries.map(summary => {
const match = labelEntries.find(entry => entry.reporting_date === summary.end_date);
return match
? { value: parseFloat(match.value).toFixed(2), reportingDate: summary.end_date }
: { value: '0.00', reportingDate: summary.end_date };
}),
};
});
// Render the dashboard page with the fetched data
res.render('dashboard', {
loggedIn: req.loggedIn,
username: req.username,
summaries,
labels,
entries,
entryMap,
});
} catch (error) {
logger.error('Error loading dashboard:', error);
res.status(500).send('Server Error');
}
});
app.post('/api/labels', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { category, label } = req.body;
const userId = req.userId;
// Check if the label already exists
let [labelResult] = await pool.query(
`
SELECT id
FROM financial_labels
WHERE user_id = ? AND category = ? AND label = ?
`,
[userId, category, label]
);
let labelId;
if (labelResult.length === 0) {
// Insert the new label
const insertLabelQuery = `
INSERT INTO financial_labels (user_id, category, label)
VALUES (?, ?, ?)
`;
const result = await pool.query(insertLabelQuery, [userId, category, label]);
labelId = result[0].insertId; // Get the inserted label's ID
} else {
labelId = labelResult[0].id; // Use existing label's ID
}
// Get all existing reporting_dates for the user
const [datesResult] = await pool.query(
`
SELECT DISTINCT reporting_date
FROM financial_entries
WHERE user_id = ?
`,
[userId]
);
// Insert entries for the new label for all existing reporting_dates
if (datesResult.length > 0) {
const insertEntryQuery = `
INSERT INTO financial_entries (user_id, label_id, reporting_date, value)
VALUES ${datesResult.map(() => '(?, ?, ?, ?)').join(', ')}
`;
// Flatten entries array
const entries = datesResult.flatMap(date => [
userId,
labelId,
date.reporting_date,
0.00, // Default value
]);
try {
await pool.query(insertEntryQuery, entries);
} catch (err) {
logger.error('Error inserting financial entries:', err);
}
}
// Return the labelId to the client
res.status(201).json({ labelId });
} catch (error) {
logger.error('Error adding financial label:', error);
res.status(500).send('Server Error');
}
});
app.put('/api/labels/:id', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { id } = req.params;
const { value } = req.body;
// Step 1: Update the value in financial_entries
const updateValueQuery = `
UPDATE financial_entries
SET value = ?
WHERE id = ? AND label_id IN (
SELECT id FROM financial_labels WHERE user_id = ?
)
`;
const [updateResult] = await pool.query(updateValueQuery, [value, id, req.userId]);
if (updateResult.affectedRows === 0) {
return res.status(404).json({ error: 'Entry not found or unauthorized' });
}
// Step 2: Retrieve reporting_date and label_id for the updated entry
const [entry] = await pool.query(`
SELECT reporting_date, label_id
FROM financial_entries
WHERE id = ? AND label_id IN (
SELECT id FROM financial_labels WHERE user_id = ?
)
`, [id, req.userId]);
if (entry.length === 0) {
return res.status(404).json({ error: 'Entry not found' });
}
const { reporting_date } = entry[0];
// Step 3: Aggregate totals for the reporting_date
const [totals] = await pool.query(`
SELECT
SUM(CASE WHEN l.category = 'Assets' THEN v.value ELSE 0 END) AS total_assets,
SUM(CASE WHEN l.category = 'Debts' THEN v.value ELSE 0 END) AS total_debts,
SUM(CASE WHEN l.category = 'Expenses' THEN v.value ELSE 0 END) AS unnecessary_expenses
FROM financial_entries v
JOIN financial_labels l ON v.label_id = l.id
WHERE l.user_id = ? AND v.reporting_date = ?
`, [req.userId, reporting_date]);
if (totals.length === 0) {
return res.status(404).json({ error: 'No data available for aggregation' });
}
const { total_assets, total_debts, unnecessary_expenses } = totals[0];
// Step 4: Update the financial_summary table
const updateSummaryQuery = `
UPDATE financial_summary
SET total_assets = ?, total_debts = ?, unnecessary_expenses = ?
WHERE user_id = ? AND end_date = ?
`;
await pool.query(updateSummaryQuery, [total_assets, total_debts, unnecessary_expenses, req.userId, reporting_date]);
res.status(200).json({ message: 'Entry updated and summary recalculated successfully' });
} catch (error) {
console.error('Error updating entry and recalculating summary:', error);
res.status(500).send('Server Error');
}
});
app.delete('/api/labels/:id', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { id } = req.params;
const userId = req.userId;
// Delete associated entries from financial_entries
const [entriesResult] = await pool.query(
`
DELETE FROM financial_entries
WHERE label_id = ? AND EXISTS (
SELECT 1 FROM financial_labels WHERE id = ? AND user_id = ?
)
`,
[id, id, userId]
);
// Delete the label itself
const [labelResult] = await pool.query(
`
DELETE FROM financial_labels
WHERE id = ? AND user_id = ?
`,
[id, userId]
);
if (labelResult.affectedRows === 0) {
logger.warn('Label not found or not authorized to delete:', { labelId: id, userId });
return res.status(404).json({ error: 'Label not found or not authorized to delete' });
}
res.status(200).json({ message: 'Label and associated entries deleted successfully' });
} catch (error) {
logger.error('Error deleting label:', error);
res.status(500).send('Server Error');
}
});
// Route to get all entries for a user
app.get('/api/entries', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const userId = req.userId;
// Fetch financial entries for the current user, including their labels and categories
const [entries] = await pool.query(
`
SELECT fl.id AS label_id, fl.label, COALESCE(fv.value, 0) AS value, fv.reporting_date, fl.category
FROM financial_labels fl
LEFT JOIN financial_entries fv ON fl.id = fv.label_id AND fv.user_id = ?
WHERE fl.user_id = ?
`,
[userId, userId]
);
res.status(200).json({ entries });
} catch (error) {
console.error('Error fetching entries:', error);
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/entries', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { reporting_date } = req.body; // Expected format: YYYY-MM-DD
const userId = req.userId;
// Step 1: Validate the reporting_date
if (!reporting_date) {
logger.warn('Reporting date is missing in request body', { userId });
return res.status(400).json({ error: 'Reporting date is required' });
}
// Step 2: Fetch all labels for the user
const [labels] = await pool.query(
'SELECT id FROM financial_labels WHERE user_id = ?',
[userId]
);
if (labels.length === 0) {
logger.warn('No financial labels found for user:', { userId });
return res.status(400).json({ error: 'No financial labels found for the user' });
}
// Step 3: Construct batch insert values
const insertValues = [];
for (const label of labels) {
insertValues.push(userId, label.id, reporting_date, 0.00); // Default value: 0.00
}
// Step 4: Perform batch insertion
const placeholders = labels.map(() => '(?, ?, ?, ?)').join(', ');
const insertQuery = `
INSERT INTO financial_entries (user_id, label_id, reporting_date, value)
VALUES ${placeholders}
`;
await pool.query(insertQuery, insertValues);
// Step 5: Send success response
res.status(201).json({ message: 'New financial entries added for the reporting period successfully!' });
} catch (error) {
// Step 6: Log and handle errors
logger.error('Error adding financial entries:', {
message: error.message,
stack: error.stack,
});
res.status(500).json({ error: 'Server Error' });
}
});
// Route used by dashboard.js "Automatically save input values on blur"
app.put('/api/entries/:labelId', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { labelId } = req.params;
let { value, reporting_date } = req.body;
const userId = req.userId;
// Convert value to positive
value = Math.abs(parseFloat(value));
// Update the financial entry
const updateEntryQuery = `
UPDATE financial_entries
SET value = ?
WHERE label_id = ? AND reporting_date = ? AND user_id = ?
`;
const [entryResult] = await pool.query(updateEntryQuery, [value, labelId, reporting_date, userId]);
if (entryResult.affectedRows === 0) {
return res.status(404).json({ error: 'Financial entry not found or not authorized to update' });
}
// Aggregate totals for the reporting_date
const aggregateQuery = `
SELECT
SUM(CASE WHEN fl.category = 'Assets' THEN fe.value ELSE 0 END) AS total_assets,
SUM(CASE WHEN fl.category = 'Debts' THEN fe.value ELSE 0 END) AS total_debts,
SUM(CASE WHEN fl.category = 'Expenses' THEN fe.value ELSE 0 END) AS unnecessary_expenses
FROM financial_entries fe
JOIN financial_labels fl ON fe.label_id = fl.id
WHERE fe.user_id = ? AND fe.reporting_date = ?
`;
const [totals] = await pool.query(aggregateQuery, [userId, reporting_date]);
const { total_assets, total_debts, unnecessary_expenses } = totals[0];
// Update the financial_summary table
const updateSummaryQuery = `
UPDATE financial_summary
SET total_assets = ?, total_debts = ?, unnecessary_expenses = ?
WHERE user_id = ? AND end_date = ?
`;
const [summaryResult] = await pool.query(updateSummaryQuery, [
total_assets || 0.00,
total_debts || 0.00,
unnecessary_expenses || 0.00,
userId,
reporting_date,
]);
if (summaryResult.affectedRows === 0) {
return res.status(404).json({ error: 'Summary not found or not authorized to update' });
}
res.status(200).json({ message: 'Value and summary updated successfully' });
} catch (error) {
console.error('Error updating financial entry and summary:', error);
res.status(500).json({ error: 'Server Error' });
}
});
app.delete('/api/entries/:id', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { id } = req.params;
const userId = req.userId;
// Fetch the end_date for the reporting period being deleted
const [summary] = await pool.query(
'SELECT end_date FROM financial_summary WHERE id = ? AND user_id = ?',
[id, userId]
);
if (summary.length === 0) {
return res.status(404).json({ error: 'Year not found or not authorized to delete.' });
}
const { end_date } = summary[0];
// Delete associated entries from financial_entries for the given end_date
await pool.query(
`
DELETE fv
FROM financial_entries fv
JOIN financial_labels fl ON fv.label_id = fl.id
WHERE fl.user_id = ? AND fv.reporting_date = ?
`,
[userId, end_date]
);
// Delete the reporting period from financial_summary
const result = await pool.query(
'DELETE FROM financial_summary WHERE id = ? AND user_id = ?',
[id, userId]
);
if (result.affectedRows === 0) {
return res.status(404).json({ error: 'Year not found or not authorized to delete.' });
}
res.status(200).json({ message: 'Year and associated entries deleted successfully.' });
} catch (error) {
console.error('Error deleting entries and summary:', error);
res.status(500).json({ error: 'Server error' });
}
});
app.get('/api/summary', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const userId = req.userId;
// Fetch summary data for the user
const [summaries] = await pool.query(
`SELECT * FROM financial_summary WHERE user_id = ?`,
[userId]
);
res.status(200).json({ summaries });
} catch (error) {
console.error('Error fetching summary:', error);
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/summary', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { end_date } = req.body; // Expected format: YYYY-MM-DD
const userId = req.userId;
// Check if the date is in the future
const today = new Date().toISOString().split('T')[0];
const isFutureDate = end_date > today;
let goldRate = 0.00;
if (!isFutureDate) {
// Fetch the gold rate for valid past/current dates
const formattedDate = end_date.replace(/-/g, '');
const goldResponse = await axios.get(`http://localhost:3000/api/gold-price?date=${formattedDate}`);
goldRate = goldResponse.data.value;
if (!goldRate) {
throw new Error('Failed to fetch gold rate.');
}
}
// Fetch the previous reporting period's end_date
const [previousPeriod] = await pool.query(
'SELECT end_date FROM financial_summary WHERE user_id = ? ORDER BY end_date DESC LIMIT 1',
[userId]
);
const lastEndDate = previousPeriod.length > 0
? new Date(previousPeriod[0].end_date)
: null;
// Calculate the start_date for the new period
const startDate = lastEndDate
? new Date(lastEndDate.getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0]
: null;
// Fetch the previous reporting period's wealth_already_taxed and huquq_payments_made
const [previousSummary] = await pool.query(
'SELECT wealth_already_taxed, huquq_payments_made FROM financial_summary WHERE user_id = ? ORDER BY end_date DESC LIMIT 1',
[userId]
);
const wealthAlreadyTaxed = previousSummary.length > 0
? parseFloat(previousSummary[0].wealth_already_taxed) || 0
: 0;
const huquqPaymentsMade = previousSummary.length > 0
? parseFloat(previousSummary[0].huquq_payments_made) || 0
: 0;
// Calculate the new wealth_already_taxed by adding the payment adjustment
const updatedWealthAlreadyTaxed = wealthAlreadyTaxed + (huquqPaymentsMade * (100 / 19));
// Insert a new reporting period with placeholder totals
const insertQuery = `
INSERT INTO financial_summary (user_id, start_date, end_date, wealth_already_taxed, gold_rate)
VALUES (?, ?, ?, ?, ?)
`;
await pool.query(insertQuery, [userId, startDate, end_date, updatedWealthAlreadyTaxed, goldRate]);
// Aggregate totals for the new reporting date
const [totals] = await pool.query(`
SELECT
SUM(CASE WHEN fl.category = 'Assets' THEN fv.value ELSE 0 END) AS total_assets,
SUM(CASE WHEN fl.category = 'Debts' THEN fv.value ELSE 0 END) AS total_debts,
SUM(CASE WHEN fl.category = 'Expenses' THEN fv.value ELSE 0 END) AS unnecessary_expenses
FROM financial_entries fv
JOIN financial_labels fl ON fv.label_id = fl.id
WHERE fl.user_id = ? AND fv.reporting_date = ?
`, [userId, end_date]);
const { total_assets, total_debts, unnecessary_expenses } = totals[0];
// Update the new reporting period with calculated totals
const updateQuery = `
UPDATE financial_summary
SET total_assets = ?, total_debts = ?, unnecessary_expenses = ?
WHERE user_id = ? AND end_date = ?
`;
await pool.query(updateQuery, [total_assets, total_debts, unnecessary_expenses, userId, end_date]);
res.status(201).json({ message: 'New reporting period added successfully!' });
} catch (error) {
console.error('Error adding reporting period:', error.message, error.stack);
res.status(500).json({ error: 'Server Error' });
}
});
// Route used for when the user updates their wealth previously paid on
app.put('/api/summary/update', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { value, end_date } = req.body; // Value and reporting period
const userId = req.userId;
// Validate input
if (!value || !end_date) {
logger.warn('Missing value or end_date in request:', { value, end_date });
return res.status(400).json({ error: 'Value and end_date are required.' });
}
const parsedValue = parseFloat(value);
const updateQuery = `
UPDATE financial_summary
SET wealth_already_taxed = ?
WHERE user_id = ? AND end_date = ?
`;
// Execute query
const [result] = await pool.query(updateQuery, [parsedValue, userId, end_date]);
if (result.affectedRows === 0) {
logger.warn('No matching summary found to update:', { userId, end_date });
return res.status(404).json({ error: 'No matching summary found to update.' });
}
res.status(200).json({ message: 'Wealth already taxed updated successfully.' });
} catch (error) {
logger.error('Error updating wealth already taxed:', { error: error.message, stack: error.stack });
res.status(500).send('Server Error');
}
});
// Route used for when the user updates their payments to Huquq
app.put('/api/summary/update-huquq', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.status(403).send('Unauthorized');
}
try {
const { value, end_date } = req.body; // Value and reporting period
const userId = req.userId;
// Validate input
if (!value || !end_date) {
logger.warn('Missing value or end_date in request:', { value, end_date });
return res.status(400).json({ error: 'Value and end_date are required.' });
}
const parsedValue = parseFloat(value);
const updateQuery = `
UPDATE financial_summary
SET huquq_payments_made = ?
WHERE user_id = ? AND end_date = ?
`;
// Execute query
const [result] = await pool.query(updateQuery, [parsedValue, userId, end_date]);
if (result.affectedRows === 0) {
logger.warn('No matching summary found to update:', { userId, end_date });
return res.status(404).json({ error: 'No matching summary found to update.' });
}
res.status(200).json({ message: 'Huquq payments made updated successfully.' });
} catch (error) {
logger.error('Error updating Huquq payments made:', { error: error.message, stack: error.stack });
res.status(500).send('Server Error');
}
});
app.get('/upload', checkLoginStatus, async (req, res) => {
if (!req.loggedIn) {
return res.redirect('/login');
}
const statusLabels = {
ne: 'Necessary',
un: 'Unnecessary', // Will not appear in upload rules
hi: 'Hidden'
};
try {
const [uploadHistory] = await pool.query(
'SELECT * FROM upload_history WHERE user_id = ? ORDER BY upload_date DESC',
[req.userId]
);
const safeUploadHistory = uploadHistory || [];
const [rules] = await pool.query(
'SELECT * FROM filter_rules WHERE user_id = ? ORDER BY created_at DESC',
[req.userId]
);
res.render('upload', {
uploadHistory: safeUploadHistory,
rules: rules || [],
statusLabels,
loggedIn: req.loggedIn
});