-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
368 lines (315 loc) · 11 KB
/
server.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
var express = require('express');
var path = require('path');
var pg = require('pg');
var bcrypt = require('bcrypt-nodejs');
var bodyParser = require('body-parser');
var routes = require('./routes');
var nodemailer = require('nodemailer');
exports.nodemailer = nodemailer;
var validator = require('validator');
var jwt = require('jsonwebtoken');
var secret = 'menyourocks';
var url = require('url');
// var helper = require('sendgrid').mail;
// var sg = require('sendgrid')(process.env.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);
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/menyoudb';
var app = express();
var client = new pg.Client(connectionString);
client.connect(function (err) {
if (err) throw err;
});
app.use(bodyParser.json());
app.set('port', (process.env.PORT || 5000));
app.use(express.static(path.join(__dirname, '/client')));
app.use(function(req, res, next){
console.log(req.method, req.url);
next();
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port ' + this.address().port);
});
app.get('/', function(req, res, next) {
res.sendfile('index.html');
});
app.get('/kitchen', function(req, res, next) {
res.redirect('/#/kitchen');
});
app.get('/admin', function(req, res, next) {
res.redirect('/#/admin');
});
app.get('/confirmation', function(req, res, next) {
res.redirect('/#/confirmation');
});
app.get('/login', function(req, res, next) {
res.redirect('/#/login');
});
app.get('/categories', function(req, res, next) {
console.log('get categories test');
client.query("SELECT * FROM categories", function(err, result) {
res.send(result.rows);
});
});
app.get('/menuitems', function(req, res, next) {
client.query("SELECT * FROM menuitems", function(err, result) {
res.send(result.rows);
});
});
app.get('/orders', function(req, res, next) {
client.query("SELECT * FROM orders", function(err, result) {
res.send(result.rows);
});
});
app.post('/valid', function(req, res, next) {
var email = req.body.email;
res.send(validator.isEmail(email));
});
app.post('/email', function(req, res, next) {
var orderid = req.body.orderid;
var add = req.body.email;
var name = req.body.name;
if(name.length) {
client.query(`UPDATE orders SET customer = ($1) WHERE id = ($2)`, [name, orderid],
function(err, result) {
if(err) {console.log("ERROR! ", err) }
console.log('UPDATING customer name');
res.send("Name updated");
}
);
}
console.log(add + ' ' + typeof add)
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'Verizon7'
}
});
let mailOptions = {
from: '"MenYou" <[email protected]>', // sender address
to: add, // list of receivers
subject: "Hey " + name + "! Here's your first coupon! ✔", // Subject line
text: 'Whatever we want to tell the client', // plain text body
html: '<b>Enjoy your savings!</b>' // html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
});
app.get('/userorders', function(req, res, next) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log('userorders query: ', query)
var ids = JSON.parse(query.orders_ids);
var userOrders = [];
ids.forEach(function(id) {
client.query("SELECT * FROM orders WHERE id = ($1)", [id], function(err, result) {
userOrders.push(result.rows[0]);
if(userOrders.length === ids.length) {
res.send(userOrders);
}
});
});
});
app.get('/deeporders', function(req, res, next) {
var deeporder = [];
client.query("SELECT * FROM orders", function(err, result) {
var orders = result.rows;
orders.forEach(function(order, ind, coll){
client.query("SELECT * FROM suborders WHERE id_orders = ($1)", [order.id], function(err, result){
if(err) { console.log(err) }
order.menuitems = result.rows;
deeporder.push(order);
if(deeporder.length === coll.length) {
//console.log(deeporder);
res.send(deeporder);
};
});
});
});
});
app.get('/getMax', function(req, response, next) {
client.query("SELECT * FROM orders WHERE id = (SELECT MAX(id) FROM orders)", function(err, res) {
var data = [];
if (res.rows[0] === undefined) {
response.status(204);
response.send();
} else {
var maxId = res.rows[0].id;
data.push(res.rows[0].id);
data.push(res.rows[0].customer);
data.push(res.rows[0].totalprice);
client.query("SELECT * FROM suborders WHERE id_orders = ($1)",[maxId], function(err, res) {
data.push(res.rows);
response.send(data);
});
};
});
});
app.get('/kitchenorders', function(req, res, next) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var lastIdFromClient = query.last_id;
var deeporder = [];
var lastOrderId;
client.query("SELECT * FROM orders ORDER BY id DESC LIMIT 1", function(err, lastRecord) {
lastOrderId = lastRecord.rows[0].id;
if (lastIdFromClient < lastOrderId) {
var offset = lastOrderId - lastIdFromClient;
client.query("SELECT * FROM orders ORDER BY id DESC LIMIT ($1)", [offset], function(err, offsetRecords) {
if(err) {console.log(err)};
var orders = offsetRecords.rows;
orders.forEach(function(order, index, array){
client.query("SELECT * FROM suborders WHERE id_orders = ($1)", [order.id], function(err, subOrders){
if(err) { console.log(err) }
order.menuitems = subOrders.rows;
deeporder.push(order);
if(deeporder.length === offset) {
res.send(deeporder);
};
});
});
});
} else {
res.status(204);
res.send();
}
})
});
var orderCount = 0;
app.post('/orders', function(req, res, next) {
console.log('order post request', req.body);
var menuitems = req.body.menuitems;
client.query("INSERT INTO \
orders(customer, totalprice) VALUES($1, $2) RETURNING id", [req.body.customer, req.body.totalprice],
function(err, result) {
if(err) {
console.log(err);
res.send('FAIL POST');
}
menuitems.forEach(function(suborder) {
client.query("INSERT INTO \
suborders(description, subtotalprice, quantity, id_orders, id_menuitems) VALUES($1, $2, $3, $4, $5)",
[suborder.name, suborder.price, suborder.quantity, result.rows[0].id, suborder.category_id],
function(err, menuResults) {
if(err) {
console.log(err);
}
});
});
res.send(result.rows[0]);
});
});
app.post('/complete', function(req, res, next) {
client.query("UPDATE orders SET complete = true WHERE id = ($1)", [req.body.id],
function(err, result) {
if(err) {console.log("ERROR! ", err) }
console.log('UPDATING! ', req.customer,"'s order is complete!");
res.send("Order complete");
}
);
});
app.post('/incomplete', function(req, res, next) {
client.query("UPDATE orders SET complete = false WHERE id = ($1)", [req.body.id],
function(err, result) {
if(err) {console.log("ERROR! ", err) }
console.log('UPDATING! ', req.customer,"'s order is incomplete!");
res.send("Order re-added");
}
);
});
app.post('/createCategory', function(req, res, next) {
//access the database....
//add a new category to table categories
var newCat = req.body.name;
console.log('NEW CAT', newCat);
client.query("INSERT INTO \
categories(name) VALUES($1) RETURNING name",[newCat],
function(err, results) {
if(err) { res.send("POST FAILED") }
console.log(results.rows);
res.send(results.rows);
});
});
app.post('/createMenuItem', function(req, res, next) {
//add a new menue item to the database table, 'menueites'
//each item needs (name, description, price, category_id)
var newItem = req.body;
console.log(newItem);
client.query("INSERT INTO \
menuitems(name, description, price, category_id) \
VALUES ($1, $2, $3, $4) RETURNING name", [newItem.name, newItem.description, newItem.price, newItem.category_id],
function(err, results) {
if(err) { res.send("POST FAILED") }
console.log(results.rows);
res.send(results.rows);
});
});
app.post('/authenticate', function(req, res, next) {
var body = req.body;
var user = {};
if(req.body.token) {
jwt.verify(req.body.token, secret, function(err, decoded){
if(err) {
res.status(401).send('Invalid credentials');
} else {
res.send(decoded);
}
});
} else if (body.username === 'admin' && body.password === 'admin') {
user.type = 'admin';
res.send({user: user, token: jwt.sign(user, secret)});
} else if (body.username === 'kitchen' && body.password === 'kitchen') {
user.type = 'kitchen';
res.send({user: user, token: jwt.sign(user, secret)});
} else {
res.status(401).send('Invalid credentials');
}
});
app.get('/newGetCurrentData', function(req, res, next) {
var initialCategory;
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var current_time = query.current_time;
var initialCategory;
if(current_time < 12) {
initialCategory = 'Breakfast';
} else if (current_time < 16) {
initialCategory = 'Lunch';
} else if (current_time < 24) {
initialCategory = 'Dinner';
} else {
initialCategory = 'Lunch';
}
client.query('SELECT * FROM categories WHERE name = ($1)', [initialCategory], function(err, currentCategory) {
if(err) {console.log(err)}
console.log(initialCategory)
var categoryId = currentCategory.rows[0].id;
client.query('SELECT * FROM menuitems WHERE category_id = ($1)', [categoryId], function(err, currentMenuItems) {
if(err) {console.log(err)}
console.log('server menu items ', currentMenuItems.rows)
res.send({
menuItems: currentMenuItems.rows,
categoryName: {name: initialCategory, id: categoryId}
});
})
})
});
app.get('/menuByCategory', function(req, res, next) {
var menuByCategory = {};
client.query('SELECT * FROM categories', function(err, categories) {
categories.rows.forEach(function(category, index) {
client.query('SELECT * FROM menuitems WHERE category_id = ($1)', [category.id], function(err, menuitems) {
menuByCategory[category.name] = menuitems.rows;
if(index === categories.rows.length - 1) {
res.send(menuByCategory);
}
});
})
})
});
app.get('/*', function(req, res, next) {
res.redirect('/');
});