-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1867 lines (1610 loc) · 74.5 KB
/
Copy pathserver.js
File metadata and controls
1867 lines (1610 loc) · 74.5 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
const express = require('express');
const { Pool } = require('pg');
const cors = require('cors');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
// Load environment variables
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// Serve static files from public directory
app.use(express.static('public'));
// Serve the consolidated template file
app.get('/consolidated_import_template.csv', (req, res) => {
res.sendFile(__dirname + '/consolidated_import_template.csv');
});
// PostgreSQL connection
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});
// Test database connection
const testConnection = async () => {
try {
const client = await pool.connect();
console.log('PostgreSQL Connected successfully');
client.release();
} catch (error) {
console.error('Database connection failed:', error.message);
console.log('Starting without database connection for demo purposes');
}
};
// Test connection
testConnection();
// Database helper functions
const db = {
// Execute a query with error handling
async query(text, params) {
try {
const result = await pool.query(text, params);
return result;
} catch (error) {
console.error('Database query error:', error);
throw error;
}
},
// Get a client for transactions
async getClient() {
return await pool.connect();
}
};
// PostgreSQL schema is handled by database tables created above
// JWT Middleware for protected routes
const authMiddleware = (req, res, next) => {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ message: 'No token, authorization denied' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'seas-financial-secret');
req.user = decoded;
next();
} catch (error) {
res.status(401).json({ message: 'Token is not valid' });
}
};
// Routes
// GET /api/employees - Fetch all employees with filters
app.get('/api/employees', authMiddleware, async (req, res) => {
try {
// Try to fetch from PostgreSQL database
const result = await db.query('SELECT * FROM employees ORDER BY created_at DESC');
const employees = result.rows;
// If no employees found, return demo data
if (employees.length === 0) {
const demoEmployees = [
{
_id: '1',
employee_id: 'EMP-LZ9X2M4K-DEMO1',
employee_name: 'John Smith',
department: 'Engineering',
lcat: 'Solution Architect/Engineering Lead (SA/Eng Lead)',
education_level: "Master's Degree",
priced_salary: 140000,
current_salary: 145000,
hours_per_month: 160,
bill_rate: 95,
hourly_rate: 56.64,
start_date: '2023-01-15',
status: 'Active',
role: 'Manager',
monthly_data: [
{ month: '2024-01', hours: 168, revenue: 15960, actual_hours: 165, actual_revenue: 15675 },
{ month: '2024-02', hours: 160, revenue: 15200, actual_hours: 158, actual_revenue: 15010 }
],
notes: 'Team lead for core platform'
},
{
_id: '2',
employee_id: 'EMP-MN8V3L7P-DEMO2',
employee_name: 'Sarah Johnson',
department: 'SEAS IT',
lcat: 'AI Engineering Lead (AI Lead)',
education_level: 'PhD',
priced_salary: 130000,
current_salary: 135000,
hours_per_month: 160,
bill_rate: 85,
hourly_rate: 52.73,
start_date: '2023-03-01',
status: 'Active',
role: 'Employee',
monthly_data: [
{ month: '2024-01', hours: 160, revenue: 13600, actual_hours: 162, actual_revenue: 13770 },
{ month: '2024-02', hours: 160, revenue: 13600, actual_hours: 155, actual_revenue: 13175 }
],
notes: 'ML model development specialist'
}
];
return res.json(demoEmployees);
}
// Handle query filters for PostgreSQL
const { department, lcat, active_only } = req.query;
let whereClause = 'WHERE 1=1';
const queryParams = [];
if (department && department !== 'all') {
queryParams.push(department);
whereClause += ` AND department = $${queryParams.length}`;
}
if (lcat && lcat !== 'all') {
queryParams.push(lcat);
whereClause += ` AND lcat = $${queryParams.length}`;
}
if (active_only === 'true') {
whereClause += ` AND status = 'Active' AND (end_date IS NULL OR end_date >= CURRENT_DATE)`;
}
const query = `SELECT * FROM employees ${whereClause} ORDER BY employee_name`;
const filteredResult = await db.query(query, queryParams);
res.json(filteredResult.rows);
} catch (error) {
console.error('Error fetching employees:', error);
res.status(500).json({ message: 'Server error', error: error.message });
}
});
// GET /api/employees/:id - Fetch single employee
app.get('/api/employees/:id', authMiddleware, async (req, res) => {
try {
const result = await db.query('SELECT * FROM employees WHERE id = $1', [req.params.id]);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Employee not found' });
}
res.json(result.rows[0]);
} catch (error) {
console.error('Error fetching employee:', error);
res.status(500).json({ message: 'Server error', error: error.message });
}
});
// POST /api/employees - Create new employee
app.post('/api/employees', authMiddleware, async (req, res) => {
try {
const {
employee_name, department, role = 'Employee', status = 'Active', lcat,
education_level, years_experience = 0, priced_salary = 0, current_salary = 0,
bill_rate = 0, start_date, end_date, notes = '', employee_type = 'Employee',
subcontractor_company
} = req.body;
// Generate unique employee ID
const employee_id = Math.floor(Math.random() * 90000 + 10000).toString();
const query = `
INSERT INTO employees (
employee_id, employee_name, department, role, status, lcat,
education_level, years_experience, priced_salary, current_salary,
bill_rate, start_date, end_date, notes, employee_type, subcontractor_company
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
RETURNING *
`;
const values = [
employee_id, employee_name, department, role, status, lcat,
education_level, years_experience, priced_salary, current_salary,
bill_rate, start_date || null, end_date || null, notes, employee_type, subcontractor_company || null
];
const result = await db.query(query, values);
res.status(201).json(result.rows[0]);
} catch (error) {
console.error('Error creating employee:', error);
res.status(400).json({ message: 'Error creating employee', error: error.message });
}
});
// PUT /api/employees/:id - Update employee
app.put('/api/employees/:id', authMiddleware, async (req, res) => {
try {
const {
employee_name, department, role, status, lcat, education_level,
years_experience, priced_salary, current_salary, bill_rate,
start_date, end_date, notes, employee_type, subcontractor_company
} = req.body;
const query = `
UPDATE employees SET
employee_name = $2, department = $3, role = $4, status = $5, lcat = $6,
education_level = $7, years_experience = $8, priced_salary = $9,
current_salary = $10, bill_rate = $11, start_date = $12, end_date = $13,
notes = $14, employee_type = $15, subcontractor_company = $16,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING *
`;
const values = [
req.params.id, employee_name, department, role, status, lcat,
education_level, years_experience, priced_salary, current_salary,
bill_rate, start_date || null, end_date || null, notes,
employee_type, subcontractor_company || null
];
const result = await db.query(query, values);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Employee not found' });
}
res.json(employee);
} catch (error) {
console.error('Error updating employee:', error);
res.status(400).json({ message: 'Error updating employee', error: error.message });
}
});
// DELETE /api/employees/:id - Delete employee
app.delete('/api/employees/:id', authMiddleware, async (req, res) => {
try {
const employee = await Employee.findByIdAndDelete(req.params.id);
if (!employee) {
return res.status(404).json({ message: 'Employee not found' });
}
res.json({ message: 'Employee deleted successfully' });
} catch (error) {
console.error('Error deleting employee:', error);
res.status(500).json({ message: 'Server error', error: error.message });
}
});
// POST /api/import - Import employees from CSV
const papa = require('papaparse');
const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() });
// POST /api/import/consolidated - Import employees with monthly data and indirect costs
app.post('/api/import/consolidated', authMiddleware, upload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ message: 'No file uploaded' });
}
const csvData = req.file.buffer.toString('utf8');
const parsed = papa.parse(csvData, {
header: true,
skipEmptyLines: true,
transformHeader: (header) => header.trim(),
transform: (value) => value.trim()
});
if (parsed.errors.length > 0) {
console.error('CSV parsing errors:', parsed.errors);
return res.status(400).json({
message: 'CSV parse error - please check your file format',
errors: parsed.errors.map(err => ({
row: err.row,
type: err.type,
code: err.code,
message: err.message
}))
});
}
const results = {
employees_imported: 0,
monthly_data_imported: 0,
indirect_costs_imported: 0,
errors: []
};
const processedIndirectCosts = new Set(); // Track processed indirect cost months
console.log('Parsed CSV data:', {
dataLength: parsed.data.length,
headers: Object.keys(parsed.data[0] || {}),
firstRow: parsed.data[0]
});
for (let i = 0; i < parsed.data.length; i++) {
const row = parsed.data[i];
// Skip empty rows
if (!row.Employee_Name) continue;
try {
// Generate 5-digit employee ID
const employee_id = Math.floor(10000 + Math.random() * 90000);
// Insert employee data
const employeeQuery = `
INSERT INTO employees (
employee_id, employee_name, department, role, status, lcat,
education_level, priced_salary, current_salary, bill_rate,
start_date, end_date, notes
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
`;
await db.query(employeeQuery, [
employee_id,
row.Employee_Name,
row.Department || 'Engineering',
row.Role || 'Employee',
row.Status || 'Active',
row.LCAT || 'Software Engineer (SWE)',
row.Education_Level || "Bachelor's Degree",
parseFloat(row.Priced_Salary) || 0,
parseFloat(row.Current_Salary) || 0,
parseFloat(row.Bill_Rate) || 0,
row.Start_Date || new Date().toISOString().split('T')[0],
row.End_Date || null,
row.Notes || ''
]);
results.employees_imported++;
// Process monthly data for each month (revenue only, calculate hours from bill rate)
const months = [
'JAN_2024', 'FEB_2024', 'MAR_2024', 'APR_2024', 'MAY_2024', 'JUN_2024',
'JUL_2024', 'AUG_2024', 'SEP_2024', 'OCT_2024', 'NOV_2024', 'DEC_2024',
'JAN_2025', 'FEB_2025', 'MAR_2025', 'APR_2025', 'MAY_2025', 'JUN_2025'
];
const billRate = parseFloat(row.Bill_Rate) || 75; // Default bill rate
for (const month of months) {
const revenueField = `${month}_Revenue`;
if (row[revenueField] && parseFloat(row[revenueField]) > 0) {
const monthValue = month.replace('_', '-').toLowerCase().substring(0, 7); // Ensure max 7 chars like "jan-2024"
const revenue = parseFloat(row[revenueField]);
const hours = Math.round(revenue / billRate); // Calculate hours from revenue and bill rate
const monthlyQuery = `
INSERT INTO monthly_data (
employee_id, month, hours, revenue
) VALUES ($1, $2, $3, $4)
ON CONFLICT (employee_id, month)
DO UPDATE SET hours = $3, revenue = $4
`;
await db.query(monthlyQuery, [
employee_id,
monthValue,
hours,
revenue
]);
results.monthly_data_imported++;
}
}
// Process indirect costs (only once per month to avoid duplicates)
if (row.Indirect_Costs_Month && !processedIndirectCosts.has(row.Indirect_Costs_Month)) {
const indirectQuery = `
INSERT INTO monthly_indirect_costs (
month, fringe_amount, overhead_amount, ga_amount, profit_amount, notes
) VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (month)
DO UPDATE SET
fringe_amount = $2,
overhead_amount = $3,
ga_amount = $4,
profit_amount = $5,
notes = $6
`;
await db.query(indirectQuery, [
row.Indirect_Costs_Month,
parseFloat(row.Fringe_Amount) || 0,
parseFloat(row.Overhead_Amount) || 0,
parseFloat(row.GA_Amount) || 0,
parseFloat(row.Profit_Amount) || 0,
row.Indirect_Notes || ''
]);
processedIndirectCosts.add(row.Indirect_Costs_Month);
results.indirect_costs_imported++;
}
} catch (error) {
results.errors.push({
row: i + 2,
employee: row.Employee_Name,
error: error.message
});
}
}
res.json({
message: `Successfully imported ${results.employees_imported} employees, ${results.monthly_data_imported} monthly records, and ${results.indirect_costs_imported} indirect cost months`,
results: results
});
} catch (error) {
console.error('Error in consolidated import:', error);
res.status(500).json({ message: 'Import failed', error: error.message });
}
});
// Legacy employee import endpoint (keep for backward compatibility)
app.post('/api/import', authMiddleware, upload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ message: 'No file uploaded' });
}
const csvData = req.file.buffer.toString('utf8');
const parsed = papa.parse(csvData, { header: true, skipEmptyLines: true });
if (parsed.errors.length > 0) {
return res.status(400).json({ message: 'CSV parse error', errors: parsed.errors });
}
const results = {
employees_imported: 0,
monthly_data_imported: 0,
errors: []
};
for (let i = 0; i < parsed.data.length; i++) {
const row = parsed.data[i];
if (!row.Employee_Name) continue;
try {
// Generate 5-digit employee ID
const employee_id = Math.floor(10000 + Math.random() * 90000);
// Insert employee data using PostgreSQL
const employeeQuery = `
INSERT INTO employees (
employee_id, employee_name, department, role, status, lcat,
education_level, priced_salary, current_salary, bill_rate,
start_date, end_date, notes
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
`;
await db.query(employeeQuery, [
employee_id,
row.Employee_Name,
row.Department || 'Engineering',
row.Role || 'Employee',
row.Status || 'Active',
row.LCAT || 'Software Engineer (SWE)',
row.Education_Level || "Bachelor's Degree",
parseFloat(row.Priced_Salary) || 0,
parseFloat(row.Current_Salary) || 0,
parseFloat(row.Bill_Rate) || 0,
row.Start_Date || new Date().toISOString().split('T')[0],
row.End_Date || null,
row.Notes || ''
]);
results.employees_imported++;
// Process monthly billing data if present
const monthlyFields = [
'JAN_FEB_2024_Revenue', 'FEB_MAR_2024_Revenue', 'MAR_APR_2024_Revenue',
'APR_MAY_2024_Revenue', 'MAY_JUN_2024_Revenue', 'JUN_JUL_2024_Revenue',
'JUL_AUG_2024_Revenue', 'AUG_SEP_2024_Revenue', 'SEP_OCT_2024_Revenue',
'OCT_NOV_2024_Revenue', 'NOV_DEC_2024_Revenue', 'DEC_JAN_2024_Revenue'
];
for (let j = 0; j < monthlyFields.length; j++) {
const field = monthlyFields[j];
if (row[field]) {
const month = `2024-${String(j + 1).padStart(2, '0')}`;
const revenue = parseFloat(row[field]) || 0;
const hours = revenue > 0 ? Math.round(revenue / (parseFloat(row.Bill_Rate) || 75)) : 0;
const monthlyQuery = `
INSERT INTO monthly_data (employee_id, month, hours, revenue)
VALUES ($1, $2, $3, $4)
ON CONFLICT (employee_id, month)
DO UPDATE SET hours = $3, revenue = $4
`;
await db.query(monthlyQuery, [employee_id, month, hours, revenue]);
results.monthly_data_imported++;
}
}
} catch (error) {
results.errors.push({ row: i + 2, error: error.message });
}
}
res.json({
message: `Successfully imported ${results.employees_imported} employees with ${results.monthly_data_imported} monthly records`,
results: results
});
} catch (error) {
console.error('Error importing employees:', error);
res.status(500).json({ message: 'Import failed', error: error.message });
}
});
// POST /api/projections - Generate financial projections
app.post('/api/projections', authMiddleware, async (req, res) => {
try {
const {
months = 12,
salary_increase = 3,
attrition_rate = 10,
new_hires = 0
} = req.body;
const employees = await Employee.find({
$or: [
{ end_date: { $exists: false } },
{ end_date: null },
{ end_date: { $gte: new Date() } }
]
});
const projections = [];
const currentDate = new Date();
for (let i = 0; i < months; i++) {
const projectionDate = new Date(currentDate);
projectionDate.setMonth(projectionDate.getMonth() + i);
let totalHours = 0;
let totalRevenue = 0;
let activeEmployees = employees.length;
// Calculate attrition impact
if (i > 0) {
const monthlyAttritionRate = attrition_rate / 12 / 100;
activeEmployees = Math.max(1, activeEmployees * (1 - monthlyAttritionRate));
}
// Add new hires
if (i > 0 && new_hires > 0) {
const monthlyNewHires = new_hires / 12;
activeEmployees += monthlyNewHires;
}
employees.forEach(employee => {
// Calculate average hours from historical data
const avgHours = employee.monthly_data.length > 0
? employee.monthly_data.reduce((sum, data) => sum + (data.actual_hours || data.hours), 0) / employee.monthly_data.length
: employee.hours_per_month;
// Apply salary increase
const adjustedSalary = employee.current_salary * Math.pow(1 + salary_increase / 100, i / 12);
const hourlyRate = adjustedSalary / 12 / avgHours;
totalHours += avgHours;
totalRevenue += avgHours * hourlyRate;
});
// Adjust for attrition and new hires
totalHours = totalHours * (activeEmployees / employees.length);
totalRevenue = totalRevenue * (activeEmployees / employees.length);
projections.push({
month: projectionDate.toISOString().slice(0, 7),
total_hours: Math.round(totalHours),
total_revenue: Math.round(totalRevenue),
active_employees: Math.round(activeEmployees),
avg_hourly_rate: totalHours > 0 ? totalRevenue / totalHours : 0
});
}
res.json(projections);
} catch (error) {
console.error('Error generating projections:', error);
res.status(500).json({ message: 'Projection generation failed', error: error.message });
}
});
// GET /api/validation-options - Get validation options for dropdowns
app.get('/api/validation-options', async (req, res) => {
try {
// Always return demo data for now since we just converted to PostgreSQL
// Once employees are added, this can be enhanced to use real data
res.json({
departments: ['Engineering', 'Data Science', 'Product Management', 'Operations', 'SEAS IT'],
lcats: [
'Program Manager (PM)',
'Solution Architect/Engineering Lead (SA/Eng Lead)',
'AI Engineering Lead (AI Lead)',
'Senior Software Engineer (Sr. SWE)',
'Software Engineer (SWE)',
'Junior Software Engineer (Jr. SWE)'
],
education_levels: ['High School', "Bachelor's Degree", "Master's Degree", 'PhD'],
roles: ['Employee', 'Manager'],
statuses: ['Active', 'Inactive']
});
} catch (error) {
console.error('Error fetching validation options:', error);
res.status(500).json({ message: 'Server error', error: error.message });
}
});
// Basic auth endpoint for development
app.post('/api/auth/login', async (req, res) => {
try {
const { username, password } = req.body;
console.log('Login attempt:', {
username: JSON.stringify(username),
password: JSON.stringify(password),
usernameLength: username?.length,
passwordLength: password?.length
});
// Simple auth for development - in production, use proper authentication
if (username === 'admin' && password === 'admin123') {
const token = jwt.sign(
{ username: 'admin', role: 'admin' },
process.env.JWT_SECRET || 'seas-financial-secret',
{ expiresIn: '24h' }
);
res.json({ token, user: { username: 'admin', role: 'admin' } });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ message: 'Server error', error: error.message });
}
});
// Utility functions for billing periods
function getMonthlyBillingPeriod(year, month) {
// Validate input parameters
if (!year || !month || month < 1 || month > 12) {
throw new Error(`Invalid year or month: year=${year}, month=${month}`);
}
// Billing period starts on 12th of month unless it's a weekend
let startDate = new Date(year, month - 1, 12); // month is 1-indexed
// Validate the created date
if (isNaN(startDate.getTime())) {
throw new Error(`Invalid start date created: year=${year}, month=${month}`);
}
// If 12th is Saturday (6) or Sunday (0), move to next Monday
const dayOfWeek = startDate.getDay();
if (dayOfWeek === 6) { // Saturday
startDate.setDate(startDate.getDate() + 2); // Move to Monday
} else if (dayOfWeek === 0) { // Sunday
startDate.setDate(startDate.getDate() + 1); // Move to Monday
}
// End date is 11th of next month (or previous working day)
let endDate = new Date(year, month, 11); // Next month's 11th
// Validate the end date
if (isNaN(endDate.getTime())) {
throw new Error(`Invalid end date created: year=${year}, month=${month}`);
}
const endDayOfWeek = endDate.getDay();
if (endDayOfWeek === 6) { // Saturday
endDate.setDate(endDate.getDate() - 1); // Move to Friday
} else if (endDayOfWeek === 0) { // Sunday
endDate.setDate(endDate.getDate() - 2); // Move to Friday
}
return { startDate, endDate };
}
function getFederalHolidays(year) {
const holidays = [];
// Fixed date holidays
holidays.push(new Date(year, 0, 1)); // New Year's Day
holidays.push(new Date(year, 6, 4)); // Independence Day
holidays.push(new Date(year, 10, 11)); // Veterans Day
holidays.push(new Date(year, 11, 25)); // Christmas Day
// MLK Day - 3rd Monday in January
const mlkDay = new Date(year, 0, 1);
mlkDay.setDate(1 + (7 - mlkDay.getDay() + 1) % 7 + 14); // 3rd Monday
holidays.push(mlkDay);
// Presidents Day - 3rd Monday in February
const presidentsDay = new Date(year, 1, 1);
presidentsDay.setDate(1 + (7 - presidentsDay.getDay() + 1) % 7 + 14);
holidays.push(presidentsDay);
// Memorial Day - Last Monday in May
const memorialDay = new Date(year, 4, 31);
memorialDay.setDate(31 - (memorialDay.getDay() + 6) % 7);
holidays.push(memorialDay);
// Labor Day - First Monday in September
const laborDay = new Date(year, 8, 1);
laborDay.setDate(1 + (7 - laborDay.getDay() + 1) % 7);
holidays.push(laborDay);
// Columbus Day - 2nd Monday in October
const columbusDay = new Date(year, 9, 1);
columbusDay.setDate(1 + (7 - columbusDay.getDay() + 1) % 7 + 7);
holidays.push(columbusDay);
// Thanksgiving - 4th Thursday in November
const thanksgiving = new Date(year, 10, 1);
thanksgiving.setDate(1 + (7 - thanksgiving.getDay() + 4) % 7 + 21);
holidays.push(thanksgiving);
return holidays;
}
function calculateWorkingDays(startDate, endDate) {
const holidays = getFederalHolidays(startDate.getFullYear());
let workingDays = 0;
const currentDate = new Date(startDate);
while (currentDate <= endDate) {
const dayOfWeek = currentDate.getDay();
const isWeekend = dayOfWeek === 0 || dayOfWeek === 6; // Sunday or Saturday
const isHoliday = holidays.some(holiday =>
holiday.getTime() === currentDate.getTime()
);
if (!isWeekend && !isHoliday) {
workingDays++;
}
currentDate.setDate(currentDate.getDate() + 1);
}
return workingDays;
}
// Function to convert period name to month number
function periodToMonth(period) {
const periodMap = {
'JAN-FEB': 1,
'FEB-MAR': 2,
'MAR-APR': 3,
'APR-MAY': 4,
'MAY-JUN': 5,
'JUN-JUL': 6,
'JUL-AUG': 7,
'AUG-SEP': 8,
'SEP-OCT': 9,
'OCT-NOV': 10,
'NOV-DEC': 11,
'DEC-JAN': 12
};
return periodMap[period] || null;
}
// GET /api/billing-period/:year/:period - Get billing period info
app.get('/api/billing-period/:year/:period', authMiddleware, async (req, res) => {
try {
const year = parseInt(req.params.year);
const periodParam = req.params.period;
// Convert period to month number
let month;
if (isNaN(parseInt(periodParam))) {
// It's a period name like "JAN-FEB"
month = periodToMonth(periodParam);
if (!month) {
return res.status(400).json({
message: 'Invalid period name',
period: periodParam,
validPeriods: ['JAN-FEB', 'FEB-MAR', 'MAR-APR', 'APR-MAY', 'MAY-JUN', 'JUN-JUL', 'JUL-AUG', 'AUG-SEP', 'SEP-OCT', 'OCT-NOV', 'NOV-DEC', 'DEC-JAN']
});
}
} else {
// It's a numeric month
month = parseInt(periodParam);
}
// Validate input parameters
if (isNaN(year) || isNaN(month) || month < 1 || month > 12) {
return res.status(400).json({
message: 'Invalid year or month parameters',
year: req.params.year,
period: periodParam,
month: month
});
}
const { startDate, endDate } = getMonthlyBillingPeriod(year, month);
const workingDays = calculateWorkingDays(startDate, endDate);
const maxHours = workingDays * 8; // 8 hours per working day
res.json({
period: periodParam,
month: month,
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
workingDays,
maxHours,
holidays: getFederalHolidays(year).map(h => h.toISOString().split('T')[0])
});
} catch (error) {
console.error('Error calculating billing period:', error);
res.status(500).json({ message: 'Server error', error: error.message });
}
});
// GET /api/profit-loss - Calculate current month profit/loss
app.get('/api/profit-loss', authMiddleware, async (req, res) => {
try {
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1;
// Try to calculate profit/loss from PostgreSQL data
try {
// Calculate from employees and costs
const empResult = await db.query('SELECT SUM(current_salary) as total_salaries FROM employees WHERE status = $1', ['Active']);
const totalSalaries = empResult.rows[0]?.total_salaries || 0;
// Simple calculation - use actual data or fallback to demo
const revenue = totalSalaries * 1.3; // Rough estimate
const costs = totalSalaries * 1.1; // Rough estimate
const profit = revenue - costs;
const profitMargin = revenue > 0 ? ((profit / revenue) * 100).toFixed(2) : '0.00';
return res.json({
revenue: Math.round(revenue),
costs: Math.round(costs),
profit: Math.round(profit),
profitMargin: parseFloat(profitMargin)
});
} catch (dbError) {
// If database query fails, return demo data
const revenue = 125000;
const costs = 98500;
const profit = revenue - costs;
const profitMargin = revenue > 0 ? (profit / revenue) * 100 : 0;
return res.json({
revenue,
costs,
profit,
profitMargin: profitMargin.toFixed(1),
month: `${year}-${month.toString().padStart(2, '0')}`
});
}
const monthKey = `${year}-${month.toString().padStart(2, '0')}`;
// Calculate total revenue from employee billing
const employees = await Employee.find({
$or: [
{ end_date: { $exists: false } },
{ end_date: null },
{ end_date: { $gte: new Date(year, month - 1, 1) } }
]
});
let totalRevenue = 0;
employees.forEach(employee => {
const monthlyData = employee.monthly_data.find(data => data.month === monthKey);
const actualHours = monthlyData?.actual_hours || employee.hours_per_month || 160;
const billRate = employee.bill_rate || 85; // Default bill rate
totalRevenue += actualHours * billRate;
});
// Calculate total costs using existing project costs calculation
const projectCosts = await calculateProjectCosts(year, month);
// Get ODC costs for the month
const odcItems = await ODCItem.find({ month: monthKey });
const totalOdcCost = odcItems.reduce((sum, item) => sum + (item.amount || 0), 0);
const totalCosts = projectCosts.total_cost + totalOdcCost;
const profit = totalRevenue - totalCosts;
const profitMargin = totalRevenue > 0 ? (profit / totalRevenue) * 100 : 0;
res.json({
revenue: totalRevenue,
costs: totalCosts,
profit,
profitMargin: profitMargin.toFixed(1),
month: monthKey
});
} catch (error) {
console.error('Error calculating profit/loss:', error);
res.status(500).json({ message: 'Server error', error: error.message });
}
});
// POST /api/employees/:id/monthly-billing - Add/update monthly billing data
app.post('/api/employees/:id/monthly-billing', authMiddleware, async (req, res) => {
try {
const { month, actual_hours, notes } = req.body;
const employeeId = req.params.id;
// For demo mode, simulate updating employee data
if (false) {
return res.json({
message: 'Monthly billing updated successfully (demo mode)',
month,
actual_hours,
actual_revenue: actual_hours * 85 // Demo bill rate
});
}
const employee = await Employee.findById(employeeId);
if (!employee) {
return res.status(404).json({ message: 'Employee not found' });
}
// Calculate actual revenue based on bill rate
const actual_revenue = actual_hours * employee.bill_rate;
// Find existing monthly data or create new
const existingIndex = employee.monthly_data.findIndex(data => data.month === month);
const monthlyData = {
month,
hours: employee.hours_per_month,
revenue: employee.hours_per_month * employee.bill_rate,
actual_hours,
actual_revenue,
notes
};
if (existingIndex >= 0) {
employee.monthly_data[existingIndex] = monthlyData;
} else {
employee.monthly_data.push(monthlyData);
}
await employee.save();
res.json({ message: 'Monthly billing updated successfully', data: monthlyData });
} catch (error) {
console.error('Error updating monthly billing:', error);
res.status(500).json({ message: 'Server error', error: error.message });
}
});
// GET /api/all-indirect-costs - Get all indirect costs
app.get('/api/all-indirect-costs', authMiddleware, async (req, res) => {
try {
// Demo data for when MongoDB is not connected
if (false) {
const demoIndirectCosts = [
{ month: '2024-01', type: 'fringe', amount: 7500, notes: 'January fringe costs' },
{ month: '2024-01', type: 'overhead', amount: 12000, notes: 'January overhead costs' },
{ month: '2024-01', type: 'ga', amount: 2500, notes: 'January G&A costs' },
{ month: '2024-01', type: 'profit', amount: 1500, notes: 'January profit' },
{ month: '2024-02', type: 'fringe', amount: 8000, notes: 'February fringe costs' },
{ month: '2024-02', type: 'overhead', amount: 12500, notes: 'February overhead costs' },
{ month: '2024-02', type: 'ga', amount: 2700, notes: 'February G&A costs' },