-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
345 lines (314 loc) · 8.78 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
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const passport = require("passport");
const http = require("http");
const flash = require("connect-flash");
const session = require("express-session");
const multer = require("multer");
const Users = require("./api/models/users.js");
const Shops = require("./api/models/shops.js");
const Invoices = require("./api/models/invoices.js");
const fs = require("fs");
const pdf = require("pdf-creator-node");
const path = require("path");
const app = express();
try {
mongoose.connect(`mongodb://localhost:27017/invoiceCentral`, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("connected");
} catch (err) {
console.log(err);
}
const server = http.createServer(app);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(flash());
const users = [];
const initializePassport = require("./passport_config.js");
initializePassport(
passport,
async (username) =>
// getUserByUsername
await Users.find({ username }).exec(),
// getUserById
async (id) => await Users.findById(id).exec()
);
app.use(
session({
// key to encrpt
secret: "secret",
// resave existing sesson id
resave: false,
// save empty session id
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views/"));
var upload = multer({ dest: "uploads/" });
// localhosh:3000/login
app.get("/", checkAuth, async (req, res) => {
console.log("index");
const shop = await Invoices.find({ shop: req.user.username });
const client = await Invoices.find({
client: [{ type: "invoiceCentral", username: req.user.username }],
});
console.log(shop);
console.log(client);
await res.render("index.ejs", { user: req.user, shop, client });
});
app.get("/login", checkNotAuth, (req, res) => {
res.sendFile("/views/html/login.html", { root: __dirname });
});
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true,
}),
(req, res) => {
const user = { name: username };
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN);
res.json({ accessToken });
}
);
app.get("/signup", checkNotAuth, (req, res) => {
res.sendFile("/views/html/signup.html", { root: __dirname });
});
app.post("/signup", checkNotAuth, upload.single("avatar"), async (req, res) => {
try {
const hashedPasswd = await bcrypt.hash(req.body.password, 10);
let image = "";
if (req.hasOwnProperty("file")) {
image = fs.readFileSync(
path.join(__dirname + "/uploads/" + req.file.filename)
);
}
var data = { ...req.body, password: hashedPasswd };
delete data["signup"];
data["images"] = {};
data["images"]["data"] = image;
var user = await Users.create(data);
res.redirect("/login");
} catch (err) {
console.log(err);
res.redirect("/signup");
}
});
app.get("/products/add", checkAuth, async (req, res) => {
res.sendFile("/views/html/add_products.html", { root: __dirname });
});
app.post("/products/add", checkAuth, async (req, res) => {
const data = req.body;
try {
var shop = await Shops.Shop.find({ username: data.username }).exec();
if (Object.keys(shop).length > 0) {
var product = await Shops.Product.create(data);
await Shops.Shop.updateOne(
{ username: data.username },
{ $push: { products: product._id } }
);
res.status(200).send({ status: "success" });
} else {
res.status(302).send({ status: "error" });
}
} catch (err) {
console.log(err);
res.status(302).send({ status: "error" });
}
});
app.get("/shop/register", checkAuth, async (req, res) => {
res.sendFile("/views/html/register_shop.html", { root: __dirname });
});
app.post("/shop/register", checkAuth, async (req, res) => {
const data = req.body;
try {
var shop = await Shops.Shop.create(data);
await Users.updateOne(
{ username: data.username },
{ $set: { shop: "registered" } }
);
console.log(shop);
res.status(200).send({ status: "success" });
} catch (err) {
console.log(err);
res.status(302).send({ status: "error" });
}
});
app.get("/shop/register", checkAuth, async (req, res) => {
res.sendFile("/views/html/shop_details.html", { root: __dirname });
});
app.post("/shop/register", checkAuth, async (req, res) => {
const data = req.body;
try {
var shop = await Shops.Shop.create(data);
await Users.updateOne(
{ username: data.username },
{ $set: { shop: "registered" } }
);
console.log(shop);
res.status(200).send({ status: "success" });
} catch (err) {
console.log(err);
res.status(302).send({ status: "error" });
}
});
app.get("/invoice", checkAuth, async (req, res) => {
res.sendFile("/views/html/invoice.html", { root: __dirname });
});
app.post("/invoice", checkAuth, async (req, res) => {
try {
var invoice = await Invoices.create(req.body);
console.log(invoice);
for (i of req.body.items) {
var p = await Shops.Product.find({ productId: i });
var quantity = parseInt(p[0].quantity) - parseInt(invoice.quantity[i]);
await Shops.Product.updateOne(
{ productId: i },
{ $set: { quantity: quantity } }
);
}
const data = await generatePdf(invoice);
res.send(data);
} catch (err) {
console.log(err);
res.status(302).send({ status: "error" });
}
});
app.get("/invoice/:invoiceId", checkAuth, (req, res) => {
const { invoiceId } = req.params;
res.sendFile(`/uploads/invoices/${invoiceId}.pdf`, { root: __dirname });
});
app.get("/products/search/:shopId", checkAuth, async (req, res) => {
try {
const { shopId } = req.params;
const key = Object.keys(req.query)[0];
const queryVal = "^" + req.query[key] + ".*";
console.log(shopId);
const pipeline1 = [{ $match: { username: shopId } }];
var getProductsId = await Shops.Shop.aggregate(pipeline1);
const pipeline2 = [
{ $match: { _id: { $in: [...getProductsId[0].products] } } },
{ $match: { [key]: { $regex: queryVal, $options: "i" } } },
];
var getProducts = await Shops.Product.aggregate(pipeline2);
res.send(getProducts);
} catch (err) {
console.log(err);
res.status(302).send({ status: "error" });
}
});
app.delete("/login", (req, res) => {
req.logOut();
res.redirect("/login");
});
async function generatePdf(invoice) {
const pipeShop = [
{ $match: { _id: invoice._id } },
{
$lookup: {
from: "shops",
localField: "shop",
foreignField: "username",
as: "shop",
},
},
];
var pipeClient = [];
if (invoice.client[0].type !== "local") {
pipeClient = [
{
$lookup: {
from: "users",
localField: "client.username",
foreignField: "username",
as: "client",
},
},
];
}
const pipeProduct = [
{
$lookup: {
from: "products",
localField: "items",
foreignField: "productId",
as: "items",
},
},
];
const [data] = await Invoices.aggregate([
...pipeShop,
...pipeClient,
...pipeProduct,
]);
var grandTotal = 0;
data.items.forEach((x, i) => {
data.items[i].quantity = data.quantity[x.productId];
data.items[i].sellingPrice = Math.floor(
(parseFloat(x.mrp) *
parseFloat(data.items[i].quantity) *
(100 - parseFloat(x.discount))) /
100
);
grandTotal += data.items[i].sellingPrice;
});
data.grandTotal = grandTotal;
delete data.quantity;
console.log(data.client);
var html = fs.readFileSync("./views/html/template.html", "utf8");
var options = {
format: "A3",
orientation: "portrait",
border: "10mm",
footer: {
height: "28mm",
contents: {
first: "Cover page",
2: "Second page", // Any page number is working. 1-based index
default:
'<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value
last: "Last Page",
},
},
};
var document = {
html: html,
data: {
invoice: data,
},
path: `./uploads/invoices/${data._id}.pdf`,
};
await pdf
.create(document, options)
.then((res) => {
console.log(res);
})
.catch((error) => {
console.error(error);
});
return { invoiceId: data._id };
}
function checkAuth(req, res, next) {
if (req.isAuthenticated()) {
console.log("check Auth");
next();
} else {
return res.redirect("/login");
}
}
function checkNotAuth(req, res, next) {
if (req.isAuthenticated()) {
return res.redirect("/");
}
next();
}
server.listen(3000);