-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
162 lines (145 loc) · 4.94 KB
/
utils.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
const os = require('os');
var db = require("./database.js")
const csv = require('csv-parser');
const fs = require('fs');
const csvWriter = require('csv-writer').createObjectCsvWriter;
const {createAndEmail} = require('./emailer');
// returns todays date in correct format
function formatted_date() {
var date_today = new Date();
var dd = date_today.getDate();
var mm = date_today.getMonth()+1;
var yyyy = date_today.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
}
var today = yyyy+'-'+mm+'-'+dd;
return today;
}
function log(update) {
const sql = "INSERT INTO console_logs (timestamp, user, log_message) VALUES (datetime('now'), ?, ?)";
const computerName = os.hostname();
const data = [computerName, update];
db.run(sql, data, err => {
if (err) {
console.error(err.message);
return;
}
});
}
function readCSVAndProcess(csvFilePath, req, res, next) {
if (!csvFilePath.toLowerCase().endsWith('.csv')) {
log("File is not a CSV. Process aborted.");
req.flash('error', 'File is not a CSV');
fs.unlinkSync(csvFilePath);
return res.redirect('/admin');
}
if (!fs.existsSync(csvFilePath)) {
log("CSV file not found. Process aborted.");
req.flash('error', 'CSV file not found');
return res.redirect('/admin');
}
const results = [];
fs.createReadStream(csvFilePath)
.pipe(csv())
.on('data', (data) => {
data.Date = convertDateFormat(data.Date);
results.push(data);
})
.on('end', () => {
results.forEach(row => {
const sql = "INSERT INTO transactions (date, transaction_type, type, description, paid_out, paid_in, balance, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
const params = [row.Date, row.Type, null, row.Description, row['Paid Out'], row['Paid In'], row.Balance, null];
db.run(sql, params, (err) => {
if (err) {
log("Error inserting row into the database: " + row.Description + " " + err.message);
} else {
log("Row inserted successfully: " + row.Description);
}});
});
fs.unlinkSync(csvFilePath);
});
}
function convertDateFormat(dateString) {
const months = {
"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06",
"Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"
};
const dateParts = dateString.split(' ');
const day = dateParts[0];
const month = months[dateParts[1]];
const year = dateParts[2];
return `${year}-${month}-${day}`;
}
function requireLogin(req, res, next) {
if (req.session && req.session.email) {
next();
} else {
res.redirect('/login');
}}
function checkUserRole(req, res, next) {
if (req.session.role === 'admin') {
next();
} else if (req.session.role === 'super admin') {
next();
} else {
req.flash('error', 'Only Admins are allowed to use this functionality.');
res.redirect('/claimants/:page');
}};
function checkSuperAdmin(req, res, next) {
if (req.session.role === 'super admin') {
next();
} else {
req.flash('error', 'Only Super Admins are allowed to use this functionality.');
res.redirect('/admin');
}};
function checkApprovedUser(req, res, next) {
if (req.session.approval === 'approved') {
next();
} else {
req.flash('error', 'Only approved users are allowed to access the software.');
res.redirect('/login');
}};
async function exportDonationsCsv(req, res) {
const tableName = 'donations';
db.all(`SELECT * FROM ${tableName}`, function(err, rows) {
if (err) {
req.flash('error', 'Error retrieving data to export donations.');
log('Error retrieving data to export donations.')
}
const csvWrite = csvWriter({
path: 'donations.csv',
header: Object.keys(rows[0]).map(key => ({ id: key, title: key }))
});
csvWrite.writeRecords(rows)
.then(() => {
res.download('donations.csv');
req.flash('success', 'Donations successfully exported.');
log('Donations successfully exported')
})
.catch(() => {
req.flash('error', 'Error generating CSV file for donations.');
log('Error generating CSV file for donations.')
});
});
try {
await createAndEmail('donations', 'ProBooks Accounting - Donations Export CSV File', 'donations export csv file');
log('Donations sent via email!');
} catch (error) {
log("Error sending donations email")
}
}
module.exports = {
formatted_date,
log,
readCSVAndProcess,
convertDateFormat,
requireLogin,
checkUserRole,
exportDonationsCsv,
checkSuperAdmin,
checkApprovedUser
}