-
Notifications
You must be signed in to change notification settings - Fork 11
/
server.js
266 lines (236 loc) · 7.97 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
require("dotenv").config();
var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
const flash = require('express-flash');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var bcrypt = require('bcrypt');
const passport = require("passport");
const cors = require("cors");
const {
getAllDataFromTarget,
getOrdersById,
getClientById,
getOrdersByClientId,
getProductsBySingleOrderId,
getProductsByMultipleOrderId,
deleteProductsById,
addMultipleProducts,
updateOrderById,
updateClientById,
getAllClientsWithOrdersCount,
addNewClient,
getDasboardData,
addNewEvent,
addNewOrder,
deleteUserById,
getUsersForAdminPanel,
createNewUser
} = require("./queries.js");
var connection = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DATABASE,
multipleStatements: true,
timezone: 'utc'
});
// CONFIGURING OPTIONS
const corsOptions = {
origin: "http://localhost:3000",
credentials: true,
optionSuccessStatus: 200
};
const initializePassport = require('./passport-config');
initializePassport(connection, passport);
app.use(cors(corsOptions));
app.use(flash());
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// END OF CONFIGURING OPTIONS
app.post('/login', passport.authenticate('local'), (req, res) => {
res.send("success")
});
app.get('/logout', (req, res) => {
req.logout();
res.send("success");
});
app.get('/user', (req, res) => {
res.send(req.user)
});
// ALL ORDERS SECTION *
app.get("/orders", async (req, res) => {
const queryAllOrders = await getAllDataFromTarget("orders");
const queryAllClients = await getAllDataFromTarget("clients");
const mergedQueries = queryAllOrders.map(order => ({
...order,
...queryAllClients.find(client => client.client_id === order.client_id)
}));
res.send(mergedQueries)
});
// END OF ALL ORDERS SECTION *
// ORDER BY ID SECTION *
app.get("/order_by_id", async (req, res) => {
const orderId = req.query.id;
const queryOrderById = await getOrdersById(orderId);
const queryProductsByOrderID = await getProductsBySingleOrderId(orderId);
const queryClientById = await getClientById(queryOrderById.client_id);
Promise.all([queryOrderById, queryProductsByOrderID, queryClientById]).then((results) => {
res.send(results)
})
});
// END OF ORDER BY ID SECTION *
// CREATE NEW ORDER *
app.post("/neworder", async (req, res) => {
let newOrderData = req.body.clientDetails;
// if new client was selected
let isNewClient = req.body.isNewClient;
// if existing client was selected
let oldClientId = req.body.oldClientId;
let dataDetails = newOrderData;
let productsData = newOrderData.products;
let totalCostOfProducts = productsData.reduce(
(accumulator, product) =>
accumulator + (product.itemPrice * product.amount || 0),
0
);
let currentDate = new Date();
// if new client is being created
if(isNewClient) {
const queryAddNewClient = await addNewClient(dataDetails);
const queryAddNewOrder = await addNewOrder(dataDetails, queryAddNewClient, totalCostOfProducts, currentDate);
const queryAddMultipleProducts = await addMultipleProducts(queryAddNewOrder, productsData);
Promise.all([queryAddNewClient, queryAddNewOrder, queryAddMultipleProducts]).then(() => {
res.send("success");
})
} else {
const queryAddNewOrder = await addNewOrder(dataDetails, oldClientId, totalCostOfProducts, currentDate);
const queryAddMultipleProducts = await addMultipleProducts(queryAddNewOrder, productsData);
Promise.all([queryAddNewOrder, queryAddMultipleProducts]).then(() => {
res.send("success");
})
}
})
// END OF CREATING NEW ORDER *
// UPDATING ORDER SECTION *
app.post("/updateorder", async (req, res) => {
let orderId = req.body.orderId;
let clientData = req.body.clientDetails.client;
let orderData = req.body.clientDetails.order;
let productsData = req.body.clientDetails.products;
let deletedIds = req.body.deletedItems.ids;
let totalCostOfProducts = productsData.reduce(
(accumulator, product) =>
accumulator + (product.itemPrice * product.amount || 0),
0
);
let currentDate = new Date();
const queryUpdateClientById = await updateClientById(clientData, orderData.client_id);
const queryUpdateOrderById = await updateOrderById(totalCostOfProducts, orderData.status, orderId);
const queryAddMultipleProducts = await addMultipleProducts(orderId, productsData);
// if user is deleteing some products from order
if(deletedIds.length > 0) {
const queryDeleteProductsById = await deleteProductsById(deletedIds);
Promise.all([queryUpdateClientById, queryUpdateOrderById, queryAddMultipleProducts, queryDeleteProductsById]).then(() => {
res.send("success");
});
} else {
Promise.all([queryUpdateClientById, queryUpdateOrderById, queryAddMultipleProducts]).then(() => {
res.send("success");
});
}
})
// END OF UPDATING ORDER SECTION *
// ALL CLIENTS SECTION *
app.get("/clients", async (req, res) => {
const queryAllClientsWithOrdersCount = await getAllClientsWithOrdersCount();
Promise.resolve(queryAllClientsWithOrdersCount).then((results) => {
res.send(results);
})
})
// END OF ALL CLIENTS SECTION *
// ADD NEW CLIENT SECTION *
app.post("/newclient", async (req, res) => {
const clientDetails = req.body.clientDetails;
const queryAddingNewClient = await addNewClient(clientDetails);
Promise.resolve(queryAddingNewClient).then(() => {
res.send("success");
})
})
// END OF ADDING NEW CLIENT SECTION *
// CLIENT BY ID SECTION *
app.get("/client_by_id", async (req, res) => {
const clientId = req.query.id;
const queryClientById = await getClientById(clientId);
const queryOrdersByClientId = await getOrdersByClientId(clientId);
const queryProductsByOrderId = await getProductsByMultipleOrderId(queryOrdersByClientId);
Promise.all([queryClientById, queryOrdersByClientId, queryProductsByOrderId]).then((results) => {
res.send(results);
});
});
// END OF CLIENT BY ID SECTION *
// DASHBOARD DATA SECTION *
app.get("/dashboard_data", async (req,res) => {
const queryDashboardData = await getDasboardData();
Promise.resolve(queryDashboardData).then((results) => {
res.send(results);
})
})
// END OF DASHBOARD DATA SECTION *
// ADD NEW EVENT SECTION *
app.post("/newevent", async (req, res) => {
const eventData = req.body.eventData;
const queryAddNewEvent = await addNewEvent(eventData);
Promise.resolve(queryAddNewEvent).then(() => {
res.send("success");
})
})
// END OF NEW EVENT SECTION *
// GET ALL EVENTS *
app.get("/events", async (req, res) => {
const queryAllEvents = await getAllDataFromTarget("calendar");
Promise.resolve(queryAllEvents).then((results) => {
res.send(results);
})
})
// END OF ALL EVENTS *
// GET USERS FOR ADMIN PANEL SECTION *
app.get("/getusers", async (req, res) => {
const queryGetUsersForAdminPanel = await getUsersForAdminPanel();
Promise.resolve(queryGetUsersForAdminPanel).then((results) => {
res.send(results);
})
})
// END OF GET USERS FOR ADMIN PANEL SECTION *
// DELETE USER BY ID SECTION *
app.post("/deleteuser", async (req, res) => {
let userId = req.body.userId;
const queryDeleteUser = await deleteUserById(userId);
Promise.resolve(queryDeleteUser).then(() => {
res.send("success");
})
});
// DELETE USER BY ID SECTION *
// CREATE NEW USER SECTION *
app.post("/newuser", async (req, res) => {
const userDetails = req.body.userDetails;
const hashedPassword = await bcrypt.hash(userDetails.password, 10);
const queryCreateNewUser = await createNewUser(userDetails, hashedPassword);
Promise.resolve(queryCreateNewUser).then(() => {
res.send("success");
})
})
// END OF CREATE NEW USER SECTION *
const port = 5000;
app.listen(port, () => `Server running on port ${port}`);