-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
351 lines (314 loc) · 9.45 KB
/
index.js
File metadata and controls
351 lines (314 loc) · 9.45 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
import express from 'express';
import pg from 'pg';
import fs from 'fs';
import fastcsv from 'fast-csv';
import methodOverride from 'method-override';
import cookieParser from 'cookie-parser';
import multer from 'multer';
import { sessionAuth } from './hashing.js';
import {
signUpForm, signUpFormResults, loginForm, loginFormResults, logout,
} from './account-route-callbacks.js';
const { Pool } = pg;
let pgConnectionConfigs;
if (process.env.ENV === 'DATABASE_URL') {
// determine how we connect to the remote Postgres server
pgConnectionConfigs = {
user: 'postgres',
// set DB_PASSWORD as an environment variable for security.
password: process.env.DB_PASSWORD,
host: 'localhost',
database: 'p65',
port: 5432,
};
} else {
// determine how we connect to the local Postgres server
pgConnectionConfigs = {
user: 'neo',
host: 'localhost',
database: 'p65',
port: 5432,
};
}
const pool = new Pool(pgConnectionConfigs);
const app = express();
// set the name of the upload directory here
const multerUpload = multer({ dest: 'uploads/' });
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride('_method'));
app.use(cookieParser());
app.use(sessionAuth);
// #################### Helper Functions ####################
// Return a promise to an invoice
function getInvoiceById(id) {
const query = `SELECT
invoices.delivery_number,
items.species,
invoices.status,
invoices.mode_delivery,
invoices.pmt_date,
invoices.delivery_date,
items.size,
items.qual,
items.weight,
items.price_kg,
items.price_total,
customers.cust_name,
customers.cust_contact
FROM invoices
JOIN items USING (delivery_number)
JOIN customers USING (cust_code)
WHERE invoices.delivery_number = '${id}'`;
return pool.query(query);
}
function getItemsSum(id) {
const query = `SELECT sum(price_total) as tot_invoice
FROM items
WHERE delivery_number = '${id}'`;
return pool.query(query);
}
function getPendingInvoices() {
// query for list of invoiceId which are pending
const query = `SELECT
invoices.delivery_number
FROM invoices
WHERE status = 'Pending'`;
return pool.query(query);
}
function getInvoiceAndSum(invoiceId) {
return Promise.all([
getInvoiceById(invoiceId),
getItemsSum(invoiceId),
]);
}
// #################### App Routes ####################
// renders login page
app.get('/', (req, res) => {
res.render('welcome');
});
// displays single invoice
app.get('/invoice/:id', (req, res) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
const invoiceId = req.params.id;
return Promise.all([
getInvoiceById(invoiceId),
getItemsSum(invoiceId),
])
.then((results) => {
const [invoice, invoiceSum] = results;
const singleInvoice = invoice.rows;
const invoiceTotal = invoiceSum.rows[0];
console.log(invoiceTotal);
const invoiceID = invoice.rows[0].delivery_number;
res.render('single-invoice', { singleInvoice, invoiceTotal, invoiceID });
});
}
});
// renders delivery tracking page
app.get('/delivery', (req, res) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
const deliveryQuery = `SELECT
invoices.delivery_number,
invoices.status,
invoices.mode_delivery,
invoices.pmt_date,
invoices.delivery_date,
customers.cust_name,
customers.cust_contact
FROM invoices
JOIN customers USING (cust_code)`;
pool.query(deliveryQuery).then((deliveryQueryResult) => {
const deliveryNotes = deliveryQueryResult.rows;
res.render('delivery-page', { deliveryNotes });
});
}
});
// render edit page with details filled
app.get('/invoice/:id/edit', (req, res) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
const invoiceId = req.params.id;
const editQuery = `SELECT
invoices.delivery_number,
items.species,
invoices.status,
invoices.mode_delivery,
invoices.pmt_date,
invoices.delivery_date,
items.size,
items.qual,
items.weight,
items.price_kg,
items.price_total,
customers.cust_name,
customers.cust_contact
FROM invoices
JOIN items USING (delivery_number)
JOIN customers USING (cust_code)
WHERE invoices.delivery_number = '${invoiceId}'`;
pool.query(editQuery).then((editQueryResult) => {
const editFormInput = editQueryResult.rows;
const invoiceID = editFormInput[0].delivery_number;
res.render('edit-invoice', { editFormInput, invoiceID });
});
}
});
// update invoice field in database
app.put('/invoice/:id/edit', (req, res) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
const invoiceId = req.params.id;
const editEntryQuery = `UPDATE invoices
SET delivery_date = '${req.body.delivery_date}',
mode_delivery = '${req.body.mode_delivery}'
WHERE delivery_number = '${invoiceId}'
RETURNING *`;
pool.query(editEntryQuery, (editEntryQueryError, editEntryQueryResult) => {
if (editEntryQueryError) {
console.log('error', editEntryQueryError);
} else {
console.log(editEntryQueryResult.rows);
res.redirect('/delivery');
}
});
}
});
// for admin: delete invoice
app.delete('/invoice/:id/delete', (req, res) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
const invoiceId = req.params.id;
pool.query('DELETE FROM invoices WHERE delivery_number = $1', [invoiceId]).then((deleteResult) => {
res.redirect('/admin-page1');
});
}
});
// renders admin page1
app.get('/admin-page1', (req, res) => getPendingInvoices()
// eslint-disable-next-line max-len
.then((pendingInvoices) => Promise.all(pendingInvoices.rows.map((invoice) => getInvoiceAndSum(invoice.delivery_number))))
.then((results) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
const invoices = results.map((result) => {
const [pendingInvoices, invoiceSum] = result;
const invoiceList = pendingInvoices.rows;
console.log(invoiceList);
const invoiceTotal = invoiceSum.rows;
console.log(invoiceTotal);
return { invoiceList, invoiceTotal };
});
console.table(invoices);
console.table(invoices[2]);
console.table(invoices[3]);
res.render('admin-page1', { invoices });
}
}));
// renders admin page2
app.get('/admin-page2', (req, res) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
res.render('admin-page2');
}
});
// post data from admin page2
app.post('/admin-page2', multerUpload.single('file'), (req, res) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
console.log('request came in');
console.log(req.file.filename);
const fileID = req.file.filename;
const stream = fs.createReadStream(`uploads/${fileID}`);
const csvData = [];
const csvStream = fastcsv
.parse()
.on('data', (data) => {
csvData.push(data);
})
.on('end', () => {
// remove the first line: header
csvData.shift();
const query = `INSERT INTO auction_list (
id,
vessel_name,
species,
size,
qual,
weight,
box_size,
price_box,
created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`;
pool.connect((err, client, done) => {
if (err) throw err;
try {
csvData.forEach((row) => {
client.query(query, row, (err, res) => {
if (err) {
console.log(err.stack);
} else {
console.log(`inserted ${res.rowCount} row:`, row);
}
});
});
} finally {
done();
}
});
});
stream.pipe(csvStream);
res.redirect('/admin-page3');
}
});
// renders admin page3
app.get('/admin-page3', (req, res) => {
if (req.isUserLoggedIn === false) {
res.redirect('/login');
} else {
const auctionQuery = 'SELECT * FROM auction_list';
pool.query(auctionQuery).then((auctionQueryResult) => {
const auctionList = auctionQueryResult.rows;
const sortQuery = req.query.sorter;
if (sortQuery === 'species') {
auctionList.sort((a, b) => ((a.species > b.species) ? 1 : -1));
}
if (sortQuery === 'size') {
auctionList.sort((a, b) => ((a.size > b.size) ? 1 : -1));
}
if (sortQuery === 'qual') {
auctionList.sort((a, b) => ((a.qual > b.qual) ? 1 : -1));
}
if (sortQuery === 'vessel_name') {
auctionList.sort((a, b) => ((a.vessel_name > b.vessel_name) ? 1 : -1));
}
res.render('admin-page3', { auctionList });
});
}
});
// renders admin page2
app.get('/invalid', (req, res) => {
res.render('invalid');
});
// #################### Auth Routes ####################
// Signup
app.get('/signup', signUpForm);
app.post('/signup', signUpFormResults);
// Login
app.get('/login', loginForm);
app.post('/login', loginFormResults);
// Logout
app.get('/logout', logout);
app.listen(3005);