-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathserver.js
More file actions
1550 lines (1393 loc) · 58.8 KB
/
server.js
File metadata and controls
1550 lines (1393 loc) · 58.8 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
/**
* DumbAssets - Asset Tracking Application
* Server implementation for handling API requests and file operations
*/
// --- SECURITY & CONFIG IMPORTS ---
require('dotenv').config();
// console.log('process.env:', process.env);
const express = require('express');
const session = require('express-session');
const helmet = require('helmet');
const crypto = require('crypto');
const path = require('path');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const fs = require('fs');
const multer = require('multer');
const { v4: uuidv4 } = require('uuid');
const XLSX = require('xlsx');
const { sendNotification } = require('./src/services/notifications/appriseNotifier');
const { startWarrantyCron } = require('./src/services/notifications/warrantyCron');
const { generatePWAManifest } = require("./scripts/pwa-manifest-generator");
const { originValidationMiddleware, getCorsOptions } = require('./middleware/cors');
const { demoModeMiddleware } = require('./middleware/demo');
const { sanitizeFileName } = require('./src/services/fileUpload/utils');
const packageJson = require('./package.json');
const app = express();
const PORT = process.env.PORT || 3000;
const DEBUG = process.env.DEBUG === 'TRUE';
const NODE_ENV = process.env.NODE_ENV || 'production';
const BASE_URL = process.env.BASE_URL || `http://localhost:${PORT}`;
const DEMO_MODE = process.env.DEMO_MODE === 'true';
const SITE_TITLE = DEMO_MODE ? `${process.env.SITE_TITLE || 'DumbAssets'} (DEMO)` : (process.env.SITE_TITLE || 'DumbAssets');
const PUBLIC_DIR = path.join(__dirname, 'public');
const PUBLIC_ASSETS_DIR = path.join(PUBLIC_DIR, 'assets');
const DATA_DIR = path.join(__dirname, 'data');
const VERSION = packageJson.version;
const DEFAULT_SETTINGS = {
notificationSettings: {
notifyAdd: true,
notifyDelete: false,
notifyEdit: true,
notify1Month: true,
notify2Week: false,
notify7Day: true,
notify3Day: false,
notifyMaintenance: false
},
interfaceSettings: {
dashboardOrder: ["analytics", "totals", "warranties", "events"],
dashboardVisibility: { analytics: true, totals: true, warranties: true, events: true },
cardVisibility: {
assets: true,
components: true,
value: true,
warranties: true,
within60: true,
within30: true,
expired: true,
active: true
}
},
};
// Currency configuration from environment variables
const CURRENCY_CODE = process.env.CURRENCY_CODE || 'USD';
const CURRENCY_LOCALE = process.env.CURRENCY_LOCALE || 'en-US';
generatePWAManifest(SITE_TITLE);
// Set timezone from environment variable or default to America/Chicago
process.env.TZ = process.env.TZ || 'America/Chicago';
function debugLog(...args) {
if (DEBUG) {
console.log('[DEBUG]', ...args);
}
}
// --- BASE PATH & PIN CONFIG ---
const BASE_PATH = (() => {
if (!BASE_URL) {
debugLog('No BASE_URL set, using empty base path');
return '';
}
try {
const url = new URL(BASE_URL);
const path = url.pathname.replace(/\/$/, '');
debugLog('Base URL Configuration:', {
originalUrl: BASE_URL,
extractedPath: path,
protocol: url.protocol,
hostname: url.hostname
});
return path;
} catch {
const path = BASE_URL.replace(/\/$/, '');
debugLog('Using direct path as BASE_URL:', path);
return path;
}
})();
const projectName = packageJson.name.toUpperCase().replace(/-/g, '_');
const PIN = process.env.DUMBASSETS_PIN;
console.log('PIN:', PIN);
if (!PIN || PIN.trim() === '') {
debugLog('PIN protection is disabled');
} else {
debugLog('PIN protection is enabled, PIN length:', PIN.length);
}
// --- BRUTE FORCE PROTECTION ---
const loginAttempts = new Map();
const MAX_ATTEMPTS = 5;
const LOCKOUT_TIME = 15 * 60 * 1000;
function resetAttempts(ip) { loginAttempts.delete(ip); }
function isLockedOut(ip) {
const attempts = loginAttempts.get(ip);
if (!attempts) return false;
if (attempts.count >= MAX_ATTEMPTS) {
const timeElapsed = Date.now() - attempts.lastAttempt;
if (timeElapsed < LOCKOUT_TIME) return true;
resetAttempts(ip);
}
return false;
}
function recordAttempt(ip) {
const attempts = loginAttempts.get(ip) || { count: 0, lastAttempt: 0 };
attempts.count += 1;
attempts.lastAttempt = Date.now();
loginAttempts.set(ip, attempts);
}
// --- SECURITY MIDDLEWARE ---
app.use(helmet({
noSniff: true, // Prevent MIME type sniffing
frameguard: { action: 'deny' }, // Prevent clickjacking
hsts: { maxAge: 31536000, includeSubDomains: true }, // Enforce HTTPS for one year
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: { policy: 'same-origin-allow-popups' },
crossOriginResourcePolicy: { policy: 'same-origin' },
referrerPolicy: { policy: 'no-referrer-when-downgrade' }, // Set referrer policy
ieNoOpen: true, // Prevent IE from executing downloads
// Disabled Helmet middlewares:
contentSecurityPolicy: false, // Disable CSP for now
dnsPrefetchControl: true, // Disable DNS prefetching
permittedCrossDomainPolicies: false,
originAgentCluster: false,
xssFilter: false,
}));
app.use(express.json());
app.set('trust proxy', 1);
app.use(cors(getCorsOptions(BASE_URL)));
app.use(cookieParser());
app.use(session({
secret: process.env.SESSION_SECRET || 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: (BASE_URL.startsWith('https') && NODE_ENV === 'production'),
sameSite: 'strict',
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
// Add helper function to get base URL for notifications
function getBaseUrl(req) {
// Try to get from environment variable first
if (process.env.BASE_URL) {
return process.env.BASE_URL;
}
// Try to construct from request headers
if (req) {
const protocol = req.secure || req.get('X-Forwarded-Proto') === 'https' ? 'https' : 'http';
const host = req.get('Host') || req.get('X-Forwarded-Host');
if (host) {
return `${protocol}://${host}`;
}
}
// Fallback to localhost with default port
return 'http://localhost:3000';
}
// --- AUTHENTICATION MIDDLEWARE FOR ALL PROTECTED ROUTES ---
app.use(BASE_PATH, (req, res, next) => {
// List of paths that should be publicly accessible
const publicPaths = [
'/login',
'/pin-length',
'/verify-pin',
'/config.js',
'/assets/',
'/styles.css',
'/manifest.json',
'/asset-manifest.json',
];
// Check if the current path matches any of the public paths
if (publicPaths.some(path => req.path.startsWith(path))) {
return next();
}
// For all other paths, apply both origin validation and auth middleware
originValidationMiddleware(req, res, () => {
authMiddleware(req, res, () => {
demoModeMiddleware(req, res, next);
});
});
});
// --- PIN VERIFICATION ---
function verifyPin(storedPin, providedPin) {
if (!storedPin || !providedPin) return false;
if (storedPin.length !== providedPin.length) return false;
try {
return crypto.timingSafeEqual(Buffer.from(storedPin), Buffer.from(providedPin));
} catch { return false; }
}
// --- AUTH MIDDLEWARE ---
function authMiddleware(req, res, next) {
debugLog('Auth check for path:', req.path, 'Method:', req.method);
if (!PIN || PIN.trim() === '') return next();
const pinCookie = req.cookies[`${projectName}_PIN`];
if (req.session.authenticated || verifyPin(PIN, pinCookie)) {
debugLog('Auth successful - Valid cookie found');
req.session.authenticated = true;
return next();
}
if (req.path.startsWith('/api/') || req.xhr) {
req.session.authenticated = false;
// Return JSON error for API requests
return res.status(401).json({
error: 'Authentication required',
redirectTo: BASE_PATH + '/login'
});
} else {
req.session.authenticated = false;
// Preserve the original URL with query parameters for post-login redirect
const originalUrl = req.originalUrl;
const loginUrl = `${BASE_PATH}/login${originalUrl ? `?returnTo=${encodeURIComponent(originalUrl)}` : ''}`;
debugLog('Redirecting to login with return URL:', loginUrl);
return res.redirect(loginUrl);
}
};
// --- STATIC FILES & CONFIG ---
app.get(BASE_PATH + '/config.js', async (req, res) => {
debugLog('Serving config.js with basePath:', BASE_PATH);
// Set proper MIME type
res.setHeader('Content-Type', 'application/javascript');
const currency = JSON.stringify({
code: CURRENCY_CODE,
locale: CURRENCY_LOCALE
});
// First send the dynamic config
res.write(`
window.appConfig = {
basePath: '${BASE_PATH}',
debug: ${DEBUG},
siteTitle: '${SITE_TITLE}',
version: '${VERSION}',
defaultSettings: ${JSON.stringify(DEFAULT_SETTINGS)},
demoMode: ${DEMO_MODE},
currency: ${currency},
};
`);
// Then append the static config.js content
try {
const staticConfig = await fs.promises.readFile(path.join(PUBLIC_DIR, 'config.js'), 'utf8');
res.write('\n\n' + staticConfig);
} catch (error) {
console.error('Error reading static config.js:', error);
}
res.end();
});
// Dynamic service worker with correct version
app.get(BASE_PATH + '/service-worker.js', async (req, res) => {
debugLog('Serving service-worker.js with version:', VERSION);
// Set proper MIME type and cache headers to prevent caching
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
try {
let swContent = await fs.promises.readFile(path.join(PUBLIC_DIR, 'service-worker.js'), 'utf8');
// Replace the version initialization with the actual version from package.json
swContent = swContent.replace(
/let APP_VERSION = ".*?";/,
`let APP_VERSION = "${VERSION}";`
);
res.write(swContent);
res.end();
} catch (error) {
console.error('Error reading service-worker.js:', error);
res.status(500).send('Error loading service worker');
}
});
// Serve static files for public assets
app.use(BASE_PATH + '/', express.static(path.join(PUBLIC_DIR)));
app.get(BASE_PATH + "/manifest.json", (req, res) => {
res.sendFile(path.join(PUBLIC_ASSETS_DIR, "manifest.json"));
});
app.get(BASE_PATH + "/asset-manifest.json", (req, res) => {
res.sendFile(path.join(PUBLIC_ASSETS_DIR, "asset-manifest.json"));
});
// Unprotected routes and files (accessible without login)
app.get(BASE_PATH + '/login', (req, res) => {
// If no PIN is set, redirect to return URL or main page (preserving any asset parameters)
if (!PIN || PIN.trim() === '') {
const returnTo = req.query.returnTo || (BASE_PATH + '/');
debugLog('No PIN set, redirecting to:', returnTo);
return res.redirect(returnTo);
}
// If already authenticated, redirect to return URL or main page
if (req.session.authenticated) {
const returnTo = req.query.returnTo || (BASE_PATH + '/');
debugLog('Already authenticated, redirecting to:', returnTo);
return res.redirect(returnTo);
}
// Store the return URL in the session if provided
if (req.query.returnTo) {
req.session.returnTo = req.query.returnTo;
debugLog('Stored return URL in session:', req.query.returnTo);
}
res.sendFile(path.join(PUBLIC_DIR, 'login.html'));
});
app.get(BASE_PATH + '/pin-length', (req, res) => {
if (!PIN || PIN.trim() === '') return res.json({ length: 0 });
res.json({ length: PIN.length });
});
app.post(BASE_PATH + '/verify-pin', (req, res) => {
debugLog('PIN verification attempt from IP:', req.ip);
// If no PIN is set, authentication is successful
if (!PIN || PIN.trim() === '') {
debugLog('PIN verification bypassed - No PIN configured');
req.session.authenticated = true;
// Get the return URL from session, or default to main page
const returnTo = req.session.returnTo || (BASE_PATH + '/');
// Clear the return URL from session
delete req.session.returnTo;
debugLog('No PIN set, redirecting to:', returnTo);
// Redirect to the intended destination
return res.redirect(returnTo);
}
// Check if IP is locked out
const ip = req.ip;
if (isLockedOut(ip)) {
const attempts = loginAttempts.get(ip);
const timeLeft = Math.ceil((LOCKOUT_TIME - (Date.now() - attempts.lastAttempt)) / 1000 / 60);
debugLog('PIN verification blocked - IP is locked out:', ip);
return res.status(429).json({
error: `Too many attempts. Please try again in ${timeLeft} minutes.`
});
}
const { pin } = req.body;
if (!pin || typeof pin !== 'string') {
debugLog('PIN verification failed - Invalid PIN format');
return res.status(400).json({ error: 'Invalid PIN format' });
}
// Verify PIN first
const isPinValid = verifyPin(PIN, pin);
if (isPinValid) {
debugLog('PIN verification successful');
// Reset attempts on successful login
resetAttempts(ip);
// Set authentication in session immediately
req.session.authenticated = true;
// Set secure cookie
res.cookie(`${projectName}_PIN`, pin, {
httpOnly: true,
secure: req.secure || (BASE_URL.startsWith('https') && NODE_ENV === 'production'),
sameSite: 'strict',
maxAge: 24 * 60 * 60 * 1000
});
// Get the return URL from session, or default to main page
const returnTo = req.session.returnTo || (BASE_PATH + '/');
// Clear the return URL from session
delete req.session.returnTo;
debugLog('Redirecting after successful login to:', returnTo);
// Redirect to the intended destination
res.redirect(returnTo);
} else {
debugLog('PIN verification failed - Invalid PIN');
// Record failed attempt
recordAttempt(ip);
const attempts = loginAttempts.get(ip);
const attemptsLeft = MAX_ATTEMPTS - attempts.count;
res.status(401).json({
error: 'Invalid PIN',
attemptsLeft: Math.max(0, attemptsLeft)
});
}
});
// Login page static assets (need to be accessible without authentication)
app.use(BASE_PATH + '/styles.css', express.static('public/styles.css'));
app.use(BASE_PATH + '/script.js', express.static('public/script.js'));
// Module files (need to be accessible for imports)
app.use(BASE_PATH + '/src/services/fileUpload', express.static('src/services/fileUpload'));
app.use(BASE_PATH + '/src/services/render', express.static('src/services/render'));
// Serve Chart.js from node_modules
app.use(BASE_PATH + '/js/chart.js', express.static('node_modules/chart.js/dist/chart.umd.js'));
// Serve uploaded files
app.use(BASE_PATH + '/Images', express.static('data/Images'));
app.use(BASE_PATH + '/Receipts', express.static('data/Receipts'));
app.use(BASE_PATH + '/Manuals', express.static('data/Manuals'));
// Protected API routes
app.use('/api', (req, res, next) => {
console.log(`API Request: ${req.method} ${req.path}`);
next();
});
// --- ASSET MANAGEMENT (existing code preserved) ---
// File paths
const assetsFilePath = path.join(DATA_DIR, 'Assets.json');
const subAssetsFilePath = path.join(DATA_DIR, 'SubAssets.json');
// Helper Functions
function ensureDirectoryExists(directory) {
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true });
}
}
function readJsonFile(filePath) {
try {
if (!fs.existsSync(filePath)) {
return [];
}
const data = fs.readFileSync(filePath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error(`Error reading ${filePath}:`, error);
return [];
}
}
function writeJsonFile(filePath, data) {
try {
const dirPath = path.dirname(filePath);
ensureDirectoryExists(dirPath);
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
return true;
} catch (error) {
console.error(`Error writing to ${filePath}:`, error);
return false;
}
}
function generateId() {
// Generate a 10-digit ID
return Math.floor(1000000000 + Math.random() * 9000000000).toString();
}
function deleteAssetFileAsync(filePath) {
return new Promise((resolve, reject) => {
if (!filePath) {
console.log('[DEBUG] Skipping empty filePath');
return resolve();
}
// File paths are stored as '/Images/filename.jpg', so we need to join with DATA_DIR
// and remove the leading slash to avoid double slashes
const cleanPath = filePath.startsWith('/') ? filePath.substring(1) : filePath;
const fullPath = path.join(DATA_DIR, cleanPath);
console.log(`[DEBUG] Attempting to delete file: ${fullPath}`);
fs.unlink(fullPath, (err) => {
if (err && err.code !== 'ENOENT') {
console.error(`[DEBUG] Error deleting file ${fullPath}:`, err);
return reject(err);
}
if (!err) {
console.log(`[DEBUG] Successfully deleted file: ${fullPath}`);
} else {
console.log(`[DEBUG] File not found (already deleted?): ${fullPath}`);
}
resolve();
});
});
}
/**
* Recursively finds all sub-assets (including nested ones) for a given parent.
* @param {string} parentId - The parent asset ID
* @param {string} parentSubId - The parent sub-asset ID (for nested sub-assets)
* @param {Array} allSubAssets - Array of all sub-assets to search through
* @returns {Array} Array of all child sub-assets (direct and nested)
*/
function findAllChildSubAssets(parentId, parentSubId, allSubAssets) {
const directChildren = allSubAssets.filter(sa => {
if (parentSubId) {
// Looking for sub-assets of a sub-asset
return sa.parentSubId === parentSubId;
} else {
// Looking for sub-assets of an asset
return sa.parentId === parentId && !sa.parentSubId;
}
});
let allChildren = [...directChildren];
// Recursively find children of each direct child
for (const child of directChildren) {
const nestedChildren = findAllChildSubAssets(parentId, child.id, allSubAssets);
allChildren.push(...nestedChildren);
}
return allChildren;
}
/**
* Deletes files associated with assets or sub-assets.
* @param {string|string[]|Object|Object[]} input - File paths, asset objects, or arrays of either.
*/
async function deleteAssetFiles(input) {
if (!input) return;
// Normalize input to an array
const items = Array.isArray(input) ? input : [input];
const pathsToDelete = [];
// Extract file paths from assets/sub-assets or use direct paths
for (const item of items) {
if (typeof item === 'string') {
// Direct file path
console.log('[DEBUG] Will delete file path:', item);
pathsToDelete.push(item);
} else if (typeof item === 'object' && item !== null) {
// Asset or sub-asset object - extract all file paths
const asset = item;
console.log('[DEBUG] Processing asset/sub-asset for deletion:', asset.id || asset.name || asset);
// Photos
if (asset.photoPaths && Array.isArray(asset.photoPaths)) {
asset.photoPaths.forEach(p => console.log('[DEBUG] Will delete photo:', p));
pathsToDelete.push(...asset.photoPaths);
} else if (asset.photoPath) {
console.log('[DEBUG] Will delete photo:', asset.photoPath);
pathsToDelete.push(asset.photoPath);
}
// Receipts
if (asset.receiptPaths && Array.isArray(asset.receiptPaths)) {
asset.receiptPaths.forEach(p => console.log('[DEBUG] Will delete receipt:', p));
pathsToDelete.push(...asset.receiptPaths);
} else if (asset.receiptPath) {
console.log('[DEBUG] Will delete receipt:', asset.receiptPath);
pathsToDelete.push(asset.receiptPath);
}
// Manuals
if (asset.manualPaths && Array.isArray(asset.manualPaths)) {
asset.manualPaths.forEach(p => console.log('[DEBUG] Will delete manual:', p));
pathsToDelete.push(...asset.manualPaths);
} else if (asset.manualPath) {
console.log('[DEBUG] Will delete manual:', asset.manualPath);
pathsToDelete.push(asset.manualPath);
}
}
}
// Delete all collected file paths
for (const filePath of pathsToDelete) {
if (filePath) {
try {
await deleteAssetFileAsync(filePath);
} catch (error) {
// Log error but continue trying to delete other files
console.error(`[DEBUG] Failed to delete ${filePath}, continuing...`);
}
}
}
}
// Initialize data directories
ensureDirectoryExists(path.join(DATA_DIR, 'Images'));
ensureDirectoryExists(path.join(DATA_DIR, 'Receipts'));
ensureDirectoryExists(path.join(DATA_DIR, 'Manuals'));
// Initialize empty files if they don't exist
if (!fs.existsSync(assetsFilePath)) {
writeJsonFile(assetsFilePath, []);
}
if (!fs.existsSync(subAssetsFilePath)) {
writeJsonFile(subAssetsFilePath, []);
}
// API Routes
// Get all assets
app.get('/api/assets', (req, res) => {
const assets = readJsonFile(assetsFilePath);
// Ensure backwards compatibility for quantity field
const assetsWithQuantity = assets.map(asset => ({
...asset,
quantity: asset.quantity || 1
}));
res.json(assetsWithQuantity);
});
// Get all sub-assets
app.get('/api/subassets', (req, res) => {
const subAssets = readJsonFile(subAssetsFilePath);
// Ensure backwards compatibility for quantity field
const subAssetsWithQuantity = subAssets.map(subAsset => ({
...subAsset,
quantity: subAsset.quantity || 1
}));
res.json(subAssetsWithQuantity);
});
// Create a new asset
app.post('/api/asset', async (req, res) => {
const assets = readJsonFile(assetsFilePath);
const newAsset = req.body;
// Ensure maintenanceEvents is always present (even if empty)
newAsset.maintenanceEvents = newAsset.maintenanceEvents || [];
// Ensure quantity is present for backwards compatibility
if (typeof newAsset.quantity === 'undefined' || newAsset.quantity === null) {
newAsset.quantity = 1;
}
// Ensure required fields
if (!newAsset.name) {
return res.status(400).json({ error: 'Asset name is required' });
}
// Generate ID if not provided
if (!newAsset.id) {
newAsset.id = generateId();
}
// Set timestamps
newAsset.createdAt = new Date().toISOString();
newAsset.updatedAt = new Date().toISOString();
assets.push(newAsset);
let success = writeJsonFile(assetsFilePath, assets);
if (success) {
if (DEBUG) {
console.log('[DEBUG] Asset added:', { name: newAsset.name, modelNumber: newAsset.modelNumber, description: newAsset.description });
}
// Notification logic
try {
const configPath = path.join(DATA_DIR, 'config.json');
let config = {};
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
}
const notificationSettings = config.notificationSettings || {};
const appriseUrl = process.env.APPRISE_URL || (config.appriseUrl || null);
if (DEBUG) {
console.log('[DEBUG] Notification settings (add):', notificationSettings, 'Apprise URL:', appriseUrl);
}
if (notificationSettings.notifyAdd && appriseUrl) {
await sendNotification('asset_added', {
id: newAsset.id,
name: newAsset.name,
modelNumber: newAsset.modelNumber,
description: newAsset.description
}, {
appriseUrl,
baseUrl: getBaseUrl(req)
});
if (DEBUG) {
console.log('[DEBUG] Asset added notification sent.');
}
}
} catch (err) {
console.error('Failed to send asset added notification:', err.message);
}
res.status(201).json(newAsset);
} else {
res.status(500).json({ error: 'Failed to create asset' });
}
});
// Update an existing asset
app.put('/api/assets/:id', async (req, res) => {
try {
const assetId = req.params.id;
const updatedAssetData = req.body;
const assets = readJsonFile(path.join(DATA_DIR, 'Assets.json'));
const assetIndex = assets.findIndex(a => a.id === assetId);
if (assetIndex === -1) {
return res.status(404).json({ message: 'Asset not found' });
}
// Validate required fields
if (!updatedAssetData.name) {
return res.status(400).json({ error: 'Asset name is required' });
}
const existingAsset = assets[assetIndex];
// Ensure quantity is present for backwards compatibility
if (typeof updatedAssetData.quantity === 'undefined' || updatedAssetData.quantity === null) {
updatedAssetData.quantity = existingAsset.quantity || 1;
}
if (updatedAssetData.filesToDelete && updatedAssetData.filesToDelete.length > 0) {
await deleteAssetFiles(updatedAssetData.filesToDelete);
}
const finalAsset = {
...existingAsset,
...updatedAssetData,
updatedAt: new Date().toISOString()
};
delete finalAsset.filesToDelete;
assets[assetIndex] = finalAsset;
writeJsonFile(path.join(DATA_DIR, 'Assets.json'), assets);
if (DEBUG) {
console.log('[DEBUG] Asset updated:', { id: finalAsset.id, name: finalAsset.name, modelNumber: finalAsset.modelNumber });
}
// Notification logic for asset edit
try {
const configPath = path.join(DATA_DIR, 'config.json');
let config = {};
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
}
const notificationSettings = config.notificationSettings || {};
const appriseUrl = process.env.APPRISE_URL || (config.appriseUrl || null);
if (DEBUG) {
console.log('[DEBUG] Notification settings (edit):', notificationSettings, 'Apprise URL:', appriseUrl);
}
if (notificationSettings.notifyEdit && appriseUrl) {
await sendNotification('asset_edited', {
id: finalAsset.id,
name: finalAsset.name,
modelNumber: finalAsset.modelNumber,
description: finalAsset.description
}, {
appriseUrl,
baseUrl: getBaseUrl(req)
});
if (DEBUG) {
console.log('[DEBUG] Asset edited notification sent.');
}
}
} catch (err) {
console.error('Failed to send asset edited notification:', err.message);
}
res.json(finalAsset);
} catch (error) {
console.error(`Error updating asset ${req.params.id}:`, error);
res.status(500).json({ message: 'Error updating asset' });
}
});
// Delete an asset
app.delete('/api/asset/:id', async (req, res) => {
const assetId = req.params.id;
const assets = readJsonFile(assetsFilePath);
const subAssets = readJsonFile(subAssetsFilePath);
// Find the asset to delete
const assetIndex = assets.findIndex(a => a.id === assetId);
if (assetIndex === -1) {
return res.status(404).json({ error: 'Asset not found' });
}
// Get the asset to delete
const deletedAsset = assets.splice(assetIndex, 1)[0];
console.log(`[DEBUG] Deleting asset: ${deletedAsset.id} (${deletedAsset.name})`);
// Find all sub-assets (including nested ones) that belong to this asset
const allChildSubAssets = findAllChildSubAssets(assetId, null, subAssets);
console.log(`[DEBUG] Found ${allChildSubAssets.length} sub-assets to delete for asset ${assetId}`);
// Remove all related sub-assets from the array
const updatedSubAssets = subAssets.filter(sa => {
return sa.parentId !== assetId && !allChildSubAssets.some(child => child.id === sa.id);
});
// Delete all associated files
try {
await deleteAssetFiles(deletedAsset);
if (allChildSubAssets.length > 0) {
await deleteAssetFiles(allChildSubAssets);
}
console.log(`[DEBUG] Deleted asset ${deletedAsset.id} and ${allChildSubAssets.length} sub-assets with their files`);
} catch (error) {
console.error('[DEBUG] Error deleting asset files:', error);
}
// Write updated assets
if (writeJsonFile(assetsFilePath, assets) && writeJsonFile(subAssetsFilePath, updatedSubAssets)) {
// Notification logic for asset delete
try {
const configPath = path.join(DATA_DIR, 'config.json');
let config = {};
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
}
const notificationSettings = config.notificationSettings || {};
const appriseUrl = process.env.APPRISE_URL || (config.appriseUrl || null);
if (DEBUG) {
console.log('[DEBUG] Notification settings (delete):', notificationSettings, 'Apprise URL:', appriseUrl);
}
if (notificationSettings.notifyDelete && appriseUrl) {
await sendNotification('asset_deleted', {
id: deletedAsset.id,
name: deletedAsset.name,
modelNumber: deletedAsset.modelNumber,
description: deletedAsset.description
}, {
appriseUrl,
baseUrl: getBaseUrl(req)
});
if (DEBUG) {
console.log('[DEBUG] Asset deleted notification sent.');
}
}
} catch (err) {
console.error('Failed to send asset deleted notification:', err.message);
}
res.json({ message: 'Asset deleted successfully' });
} else {
res.status(500).json({ error: 'Failed to delete asset' });
}
});
// Create a new sub-asset
app.post('/api/subasset', async (req, res) => {
const subAssets = readJsonFile(subAssetsFilePath);
const newSubAsset = req.body;
// Remove legacy maintenanceReminder if present
if (newSubAsset.maintenanceReminder) delete newSubAsset.maintenanceReminder;
// Ensure maintenanceEvents is always present (even if empty)
newSubAsset.maintenanceEvents = newSubAsset.maintenanceEvents || [];
// Ensure quantity is present for backwards compatibility
if (typeof newSubAsset.quantity === 'undefined' || newSubAsset.quantity === null) {
newSubAsset.quantity = 1;
}
// Ensure required fields
if (!newSubAsset.name || !newSubAsset.parentId) {
return res.status(400).json({ error: 'Sub-asset name and parent ID are required' });
}
// Generate ID if not provided
if (!newSubAsset.id) {
newSubAsset.id = generateId();
}
// Set timestamps
newSubAsset.createdAt = new Date().toISOString();
newSubAsset.updatedAt = new Date().toISOString();
subAssets.push(newSubAsset);
if (writeJsonFile(subAssetsFilePath, subAssets)) {
if (DEBUG) {
console.log('[DEBUG] Sub-asset added:', { id: newSubAsset.id, name: newSubAsset.name, parentId: newSubAsset.parentId });
}
// Notification logic for sub-asset creation
try {
const configPath = path.join(DATA_DIR, 'config.json');
let config = {};
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
}
const notificationSettings = config.notificationSettings || {};
const appriseUrl = process.env.APPRISE_URL || (config.appriseUrl || null);
if (DEBUG) {
console.log('[DEBUG] Sub-asset notification settings (add):', notificationSettings, 'Apprise URL:', appriseUrl);
}
if (notificationSettings.notifyAdd && appriseUrl) {
await sendNotification('asset_added', {
id: newSubAsset.id,
parentId: newSubAsset.parentId,
name: `${newSubAsset.name} (Component)`,
modelNumber: newSubAsset.modelNumber,
description: newSubAsset.description || newSubAsset.notes
}, {
appriseUrl,
baseUrl: getBaseUrl(req)
});
if (DEBUG) {
console.log('[DEBUG] Sub-asset added notification sent.');
}
}
} catch (err) {
console.error('Failed to send sub-asset added notification:', err.message);
}
res.status(201).json(newSubAsset);
} else {
res.status(500).json({ error: 'Failed to create sub-asset' });
}
});
// Update an existing sub-asset
app.put('/api/subassets/:id', async (req, res) => {
try {
const subAssetId = req.params.id;
const updatedSubAssetData = req.body;
const subAssets = readJsonFile(path.join(DATA_DIR, 'SubAssets.json'));
const subAssetIndex = subAssets.findIndex(sa => sa.id === subAssetId);
if (subAssetIndex === -1) {
return res.status(404).json({ message: 'Sub-asset not found' });
}
// Validate required fields
if (!updatedSubAssetData.name) {
return res.status(400).json({ error: 'Sub-asset name is required' });
}
const existingSubAsset = subAssets[subAssetIndex];
// Ensure quantity is present for backwards compatibility
if (typeof updatedSubAssetData.quantity === 'undefined' || updatedSubAssetData.quantity === null) {
updatedSubAssetData.quantity = existingSubAsset.quantity || 1;
}
if (updatedSubAssetData.filesToDelete && updatedSubAssetData.filesToDelete.length > 0) {
await deleteAssetFiles(updatedSubAssetData.filesToDelete);
}
const finalSubAsset = {
...existingSubAsset,
...updatedSubAssetData,
updatedAt: new Date().toISOString()
};
delete finalSubAsset.filesToDelete;
subAssets[subAssetIndex] = finalSubAsset;
writeJsonFile(path.join(DATA_DIR, 'SubAssets.json'), subAssets);
if (DEBUG) {
console.log('[DEBUG] Sub-asset updated:', { id: finalSubAsset.id, name: finalSubAsset.name, parentId: finalSubAsset.parentId });
}
// Notification logic for sub-asset edit
try {
const configPath = path.join(DATA_DIR, 'config.json');
let config = {};
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
}
const notificationSettings = config.notificationSettings || {};
const appriseUrl = process.env.APPRISE_URL || (config.appriseUrl || null);
if (DEBUG) {
console.log('[DEBUG] Sub-asset notification settings (edit):', notificationSettings, 'Apprise URL:', appriseUrl);
}
if (notificationSettings.notifyEdit && appriseUrl) {
await sendNotification('asset_edited', {
id: finalSubAsset.id,
parentId: finalSubAsset.parentId,
name: `${finalSubAsset.name} (Component)`,
modelNumber: finalSubAsset.modelNumber,
description: finalSubAsset.description || finalSubAsset.notes
}, {
appriseUrl,
baseUrl: getBaseUrl(req)
});