-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
1410 lines (1218 loc) · 49.1 KB
/
index.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require("express");
const cors = require("cors");
require("dotenv").config();
const moment = require("moment");
const SSLCommerzPayment = require("sslcommerz-lts");
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const app = express();
const port = process.env.PORT || 5000;
// middleware
app.use(cors());
app.use(express.json());
const orderDate = moment().format("Do MMM YY, h:mm a");
const dateAndTime = moment().format("MMMM Do YYYY, h:mm:ss a");
// mongodb code start
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@team-gladiators.2x9sw5e.mongodb.net/?retryWrites=true&w=majority`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
// const client = new MongoClient(uri, { useUnifiedTopology: true }, { useNewUrlParser: true }, { connectTimeoutMS: 30000 }, { keepAlive: 1 });
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
useNewUrlParser: true,
useUnifiedTopology: true,
maxPoolSize: 10,
});
// ssl config
const store_id = process.env.PAYMENT_STORE_ID;
const store_passwd = process.env.PAYMENT_STORE_PASSWD;
const is_live = false; //true for live, false for sandbox
async function run() {
try {
client.connect((err) => {
if (err) {
console.error(err);
return;
}
});
// database collection
const database = client.db("medicareDB");
// medicine
const medicineCollection = database.collection("medicines");
const mediCartCollection = database.collection("medicinesCart");
const orderedMedicinesCollection = database.collection("orderedMedicines");
const reqToStockMedicineCollection = database.collection("requestToStockMedi");
const reqNewMedicineCollection = database.collection("reqNewMedi");
// lab test
const labCategoryCollection = database.collection("labCategories");
const labItemsCollection = database.collection("labItems");
const labCartCollection = database.collection("labsCart");
const bookedLabTestCollection = database.collection("bookedLabTest");
// users
const userCollection = database.collection("users");
const pharmacyRegistrationApplication = database.collection("P.R. Applications");
const pharmacistCollection = database.collection("pharmacists");
// health tips & blog
const healthTipsCollection = database.collection("healthTips");
const blogCollection = database.collection("blogs");
// general
const imagesCollection = database.collection("images");
const imagesNotifications = database.collection("notifications");
const prescriptionCollection = database.collection("prescription");
const dashboardDataCollection = database.collection("dashboardData");
const discountCodesCollection = database.collection("discountCodes");
const feedbackCollection = database.collection("feedback");
// =========== Medicines Related apis ===========
app.get("/all-medicines", async (req, res) => {
const needData = { _id: 1, medicine_name: 1, image: 1, available_quantity: 1, sellQuantity: 1, pharmacist_name: 1, pharmacist_email: 1, status: 1 };
const result = await medicineCollection.find({}, { projection: needData }).toArray();
res.send(result);
});
// home page search medicines
app.get("/searchMedicinesByName", async (req, res) => {
const needData = { _id: 1, medicine_name: 1, image: 1, price: 1, discount: 1, category: 1, available_quantity: 1, sellQuantity: 1 };
const sbn = req.query?.name;
let query = { status: "approved" };
if (sbn) {
query = { ...query, medicine_name: { $regex: sbn, $options: "i" } };
}
const result = await medicineCollection.find(query, { projection: needData }).toArray();
res.send(result);
});
// status approved;
app.get("/medicines", async (req, res) => {
const query = { status: "approved" };
let sortObject = {};
const needData = { _id: 1, medicine_name: 1, image: 1, price: 1, discount: 1, category: 1, available_quantity: 1, sellQuantity: 1, pharmacist_email: 1, rating: 1, order_quantity: 1 };
switch (req.query.sort) {
case "phtl":
sortObject = { price: 1 };
break;
case "plth":
sortObject = { price: -1 };
break;
case "byRating":
sortObject = { rating: -1 };
break;
case "fNew":
sortObject = { date: -1 };
break;
case "fOld":
sortObject = { date: 1 };
break;
default:
break;
}
// FOR FINDING DATA WITHOUT SPECIFIC FIELD (IMPORTANT)
// const result = await medicineCollection
// .find(query, { projection: { feature_with_details: 0, medicine_description: 0 } })
// .sort(sortObject)
// .toArray();
// FOR FINDING DATA WITH SPECIFIC FIELD
const result = await medicineCollection.find(query, { projection: needData }).sort(sortObject).toArray();
res.send(result);
});
// highest selling medicines
app.get("/highestSelling-medicines", async (req, res) => {
const query = { status: "approved" };
const needData = { _id: 1, medicine_name: 1, image: 1, price: 1, discount: 1, category: 1, available_quantity: 1, sellQuantity: 1, pharmacist_email: 1, rating: 1, order_quantity: 1 };
const sorting = {
sort: { sellQuantity: -1 },
limit: 10,
};
const result = await medicineCollection.find(query, { projection: needData, ...sorting }).toArray();
res.send(result);
});
// top rated medicines
app.get("/topRated-medicines", async (req, res) => {
const query = { status: "approved" };
const needData = { _id: 1, medicine_name: 1, image: 1, price: 1, discount: 1, rating: 1 };
const sorting = {
sort: { rating: -1 },
limit: 5,
};
const result = await medicineCollection.find(query, { projection: needData, ...sorting }).toArray();
res.send(result);
});
app.get("/medicinesc", async (req, res) => {
const needData = { _id: 1, medicine_name: 1, image: 1, price: 1, discount: 1, category: 1, available_quantity: 1, sellQuantity: 1, pharmacist_email: 1, rating: 1, order_quantity: 1 };
const category = req.query.category;
const query = {
"category.value": category,
status: "approved",
};
const result = await medicineCollection.find(query, { projection: needData }).toArray();
res.send(result);
});
app.get("/medicines/details/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await medicineCollection.findOne(query);
res.send(result);
});
app.get("/pharmacistMedicines", async (req, res) => {
const needData = { _id: 1, medicine_name: 1, image: 1, available_quantity: 1, sellQuantity: 1, status: 1 };
const email = req.query.email;
if (!email) {
res.send([]);
}
const query = { pharmacist_email: email };
const result = await medicineCollection.find(query, { projection: needData }).toArray();
res.send(result);
});
app.post("/medicines", async (req, res) => {
const newMedicine = req.body;
const result = await medicineCollection.insertOne(newMedicine);
res.send(result);
});
// Adding reviews
app.post("/reviews/:id", async (req, res) => {
const id = req.params.id;
const review = req.body;
const filter = { _id: new ObjectId(id) };
const existingItem = await medicineCollection.findOne(filter);
const newReview = [...existingItem.allRatings, review];
let count = 0.0;
newReview.forEach((r) => {
count += r.rating;
});
const options = { upsert: true };
const updatedRating = {
$set: {
rating: parseFloat((count / newReview.length).toFixed(2)),
},
};
const updatedRatings = {
$set: {
allRatings: newReview,
},
};
const result1 = await medicineCollection.updateOne(filter, updatedRating, options);
const result2 = await medicineCollection.updateOne(filter, updatedRatings, options);
res.send(result2);
});
app.put("/update-medicine/:id", async (req, res) => {
const id = req.params.id;
const updatedData = req.body;
// Remove the _id field from the updatedData
delete updatedData._id;
const filter = { _id: new ObjectId(id) };
const options = { upsert: true };
const updatedMedicine = {
$set: { ...updatedData },
};
const result = await medicineCollection.updateOne(filter, updatedMedicine, options);
res.send(result);
});
app.patch("/medicine-status/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const updateStatus = {
$set: req.body,
};
const result = medicineCollection.updateOne(query, updateStatus);
res.send(result);
});
app.delete("/medicines/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await medicineCollection.deleteOne(query);
res.send(result);
});
app.put("/medicine-feedback/:id", async (req, res) => {
const id = req.params.id;
const updatedFeedback = req.body;
const query = { _id: new ObjectId(id) };
const newFeedback = {
$set: { feedback: updatedFeedback.feedback },
};
const result = await medicineCollection.updateOne(query, newFeedback, { upsert: true });
res.send(result);
});
// =========== Medicines Cart Related apis ===========
app.get("/medicineCarts", async (req, res) => {
const email = req.query.email;
if (!email) {
res.send({ message: "Empty Cart" });
}
const query = { email: email };
const result = await mediCartCollection.find(query).toArray();
res.send(result);
});
app.post("/medicineCarts", async (req, res) => {
const medicine = req.body;
const filterMedicine = { medicine_Id: medicine.medicine_Id, email: medicine.email };
const singleMedicine = await mediCartCollection.findOne(filterMedicine);
if (singleMedicine) {
const updateDoc = {
$set: {
quantity: singleMedicine.quantity + medicine.quantity,
},
};
const updateQuantity = await mediCartCollection.updateOne(filterMedicine, updateDoc);
res.send(updateQuantity);
} else {
const result = await mediCartCollection.insertOne(medicine);
res.send(result);
}
});
app.delete("/medicineCarts/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await mediCartCollection.deleteOne(query);
res.send(result);
});
app.delete("/medicineCarts", async (req, res) => {
const email = req.query.email;
const query = { email: email };
const result = await mediCartCollection.deleteMany(query);
res.send(result);
});
app.patch("/update-quantity/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const updateQuantity = {
$set: req.body,
};
const result = await mediCartCollection.updateOne(query, updateQuantity);
res.send(result);
});
// =========== Medicine Order related apis ===========
// for customer order history
app.get("/medicinesOrder", async (req, res) => {
const email = req.query.email;
if (!email) {
res.send({ message: "Email Not Found" });
}
const query = { email: email, status: "success" };
const result = await orderedMedicinesCollection.find(query).toArray();
res.send(result);
});
// medicine ordered conformation apis for pharmacist dashboard (pharmacist)
app.get("/medicinesOrderByPharmacistWithResponse", async (req, res) => {
const email = req.query.email;
if (!email) {
res.send({ message: "Email Not Found" });
}
const query = { pharmacist_email: email, status: "success", pharmacist_response: false };
const result = await orderedMedicinesCollection.find(query).toArray();
res.send(result);
});
// for all medicine order history (pharmacist)
app.get("/medicinesOrderByPharmacist", async (req, res) => {
const email = req.query.email;
if (!email) {
res.send({ message: "Email Not Found" });
}
const query = { pharmacist_email: email, status: "success" };
const result = await orderedMedicinesCollection.find(query).toArray();
res.send(result);
});
// order conformation (pharmacist) and update delivery status (pharmacist/admin/user)
app.patch("/deliveryStatus/:id", async (req, res) => {
const id = req.params.id;
const updateResponse = {
$set: req.body,
};
const result = await orderedMedicinesCollection.updateOne({ _id: new ObjectId(id) }, updateResponse);
res.send(result);
});
// all medicine for admin
app.get("/medicinesOrderByAdmin", async (req, res) => {
const result = await orderedMedicinesCollection.find().toArray();
res.send(result);
});
// medicine details for admin
app.get("/medicinesOrderByAdmin/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await orderedMedicinesCollection.findOne(query);
res.send(result);
});
app.delete("/medicinesOrderByAdmin/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await orderedMedicinesCollection.deleteOne(query);
res.send(result);
});
// =========== Request to stock & request new medicines related apis ===========
// request to stock
app.get("/requestToStock/:email", async (req, res) => {
const email = req.params.email;
const query = { pharmacist_email: email };
if (!email) {
res.send({ message: "No Request Medicine found Found" });
}
const result = await reqToStockMedicineCollection.find(query).toArray();
res.send(result);
});
app.post("/requestToStock", async (req, res) => {
const medicineRequest = req.body;
const filterMediReq = { reqByMedicine_Id: medicineRequest.reqByMedicine_Id };
const existRequest = await reqToStockMedicineCollection.findOne(filterMediReq);
if (existRequest) {
const updateCountDate = {
$set: {
request_count: existRequest.request_count + 1,
date: existRequest.date,
},
};
const rquestUpdate = await reqToStockMedicineCollection.updateOne(filterMediReq, updateCountDate);
res.send(rquestUpdate);
} else {
const result = await reqToStockMedicineCollection.insertOne(medicineRequest);
res.send(result);
}
});
app.delete("/requestToStock/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await reqToStockMedicineCollection.deleteOne(query);
res.send(result);
});
// request for new medicine
app.get("/requestNewMedicine", async (req, res) => {
const result = await reqNewMedicineCollection.find().toArray();
res.send(result);
});
app.post("/requestNewMedicine", async (req, res) => {
const newMediReq = req.body;
const result = await reqNewMedicineCollection.insertOne(newMediReq);
res.send(result);
});
app.delete("/requestNewMedicine/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await reqNewMedicineCollection.deleteOne(query);
res.send(result);
});
// =========== Lab Test related apis ===========
app.get("/labCategories", async (req, res) => {
const result = await labCategoryCollection.find().toArray();
res.send(result);
});
app.get("/adminLabBooking", async (req, res) => {
const result = await bookedLabTestCollection.find().toArray();
res.send(result);
});
app.post("/labDeliveryStatus", async (req, res) => {
const id = req.body?.id;
const updatedStatus = {
$set: {
status: "success",
},
};
const result = await bookedLabTestCollection.updateOne({ _id: new ObjectId(id) }, updatedStatus, { upsert: true });
res.send(result);
});
app.delete("/deleteLabTest/:id", async (req, res) => {
const id = req.params?.id;
const result = await bookedLabTestCollection.deleteOne({ _id: new ObjectId(id) });
res.send(result);
});
app.get("/labBooking", async (req, res) => {
const email = req.query.email;
if (!email) {
res.send([]);
}
const query = { email: email };
const result = await bookedLabTestCollection.find(query).toArray();
res.send(result);
});
app.get("/labCategory/:id", async (req, res) => {
const id = req.params.id;
const result = await labCategoryCollection.find({ _id: new ObjectId(id) }).toArray();
res.send(result);
});
app.get("/labAllItems", async (req, res) => {
const sbn = req.query?.name;
let query = {};
if (sbn != "undefined") {
//it is made for lab search
query = { test_name: { $regex: sbn, $options: "i" } };
}
const result = await labItemsCollection
.find(query, { projection: { labTestDetails: 0 } })
.sort({ report: 1 })
.toArray();
res.send(result);
});
app.get("/labAllItems/:id", async (req, res) => {
const id = req.params.id;
if (id) {
const result = await labItemsCollection.findOne({ _id: new ObjectId(id) });
res.send(result);
}
});
app.get("/labPopularItems", async (req, res) => {
const result = await labItemsCollection
.find({}, { projection: { labTestDetails: 0 } })
.sort({
totalBooked: -1,
})
.toArray();
res.send(result);
});
app.get("/labItems/:category", async (req, res) => {
const result = await labItemsCollection.find({ category_name: req.params.category }).toArray();
res.send(result);
});
app.post("/labItems", async (req, res) => {
const lab = req.body;
const result = await labItemsCollection.insertOne(lab);
res.send(result);
});
app.delete("/labItems/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await labItemsCollection.deleteOne(query);
res.send(result);
});
app.put("/labItems/:id", async (req, res) => {
// const id = req.params.id;
const { data, _id } = req.body;
delete data._id;
// const { image_url, PhoneNumber, labNames, labTestDetails, popularCategory, category, price, test_name, discount, city } = body;
const filter = { _id: new ObjectId(_id) };
const options = { upsert: true };
const updatedLabTest = {
// $set: { image_url, PhoneNumber, labNames, labTestDetails, popularCategory, category, price, test_name, discount, city, remaining }
$set: { ...data },
};
const result = await labItemsCollection.updateOne(filter, updatedLabTest, options);
res.send(result);
});
// =========== Lab Test Cart Related apis ===========
app.get("/labsCart", async (req, res) => {
const email = req.query.email;
if (!email) {
res.send([]);
}
const query = { email: email };
const result = await labCartCollection.find(query).toArray();
res.send(result);
});
app.post("/labsCart", async (req, res) => {
const labCart = req.body;
const result = await labCartCollection.insertOne(labCart);
res.send(result);
});
app.delete("/labCart/:id", async (req, res) => {
const id = req.params.id;
const result = await labCartCollection.deleteOne({ _id: new ObjectId(id) });
res.send(result);
});
// =========== Health Tips Related apis ===========
app.get("/allHealthTips", async (req, res) => {
const unnecessaryData = { prevention: 0, cure: 0, doctorDepartment: 0, date: 0, doctorName: 0 };
const result = await healthTipsCollection.find({}, { projection: unnecessaryData }).toArray();
res.send(result);
});
app.post("/addHealthTips", async (req, res) => {
const tips = req.body;
const result = await healthTipsCollection.insertOne(tips);
res.send(result);
});
app.get("/allHealthTips/:id", async (req, res) => {
const id = req.params.id;
const result = await healthTipsCollection.findOne({ _id: new ObjectId(id) });
res.send(result);
});
app.delete("/allHealthTips/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await healthTipsCollection.deleteOne(query);
res.send(result);
});
app.put("/allHealthTips/:id", async (req, res) => {
const id = req.params.id;
// const { body } = req.body;
console.log(id, req.body);
const { category, name, image, type, cause, cure, prevention, doctorDepartment, doctorName, date } = req.body;
const filter = { _id: new ObjectId(id) };
const options = { upsert: true };
const updatedHealthTips = {
$set: { category, name, image, type, cause, cure, prevention, doctorDepartment, doctorName, date },
};
const result = await healthTipsCollection.updateOne(filter, updatedHealthTips, options);
res.send(result);
});
// =========== Blog Related apis ===========
app.get("/blogs", async (req, res) => {
const unnecessaryData = { content_details: 0, author: 0 };
const result = await blogCollection.find({}, { projection: unnecessaryData }).toArray();
res.send(result);
});
app.post("/blogs", async (req, res) => {
const newBlog = req.body;
const result = await blogCollection.insertOne(newBlog);
res.send(result);
});
app.get("/blogs/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await blogCollection.findOne(query);
res.send(result);
});
app.put("/blogs/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const updatedData = {
$set: req.body,
};
const result = await blogCollection.updateOne(query, updatedData);
res.send(result);
});
app.delete("/blogs/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await blogCollection.deleteOne(query);
res.send(result);
});
// =========== Pharmacist Related apis ===========
app.post("/pharmacyRegistrationApplication", async (req, res) => {
const newApplication = req.body;
const result = await pharmacyRegistrationApplication.insertOne(newApplication);
res.send(result);
});
app.get("/pharmacyRegistrationApplications", async (req, res) => {
const result = await pharmacyRegistrationApplication.find().toArray();
res.send(result);
});
app.get("/pharmacyRegistrationApl/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await pharmacyRegistrationApplication.findOne(query);
res.send(result);
});
app.patch("/pharmacyRApprove/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const email = req.body.email;
// const body = req.body
const newApplication = {
$set: {
applicationType: req?.body?.applicationType,
},
};
const result = await pharmacyRegistrationApplication.updateOne(query, newApplication);
const updateUser = {
$set: {
role: req?.body?.role,
pharmacistDetail: req?.body?.pharmacistDetail,
},
};
const result2 = await userCollection.updateOne({ email: email }, updateUser, { upsert: true });
res.send({ result, result2 });
});
app.delete("/deleteRApplication/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await pharmacyRegistrationApplication.deleteOne(query);
res.send(result);
});
// =========== Users Related apis ===========
app.post("/users", async (req, res) => {
const user = req.body;
const query = { email: user.email };
const existingUser = await userCollection.findOne(query);
if (existingUser) {
return res.send({ message: "User Already has been Create" });
}
const result = await userCollection.insertOne(user);
res.send(result);
});
app.put("/users/:email", async (req, res) => {
const userEmail = req.params.email; // Get the user's email from the URL parameter
const updatedUserData = req.body; // User data to update
// Create a query to find the user by their email
const query = { email: userEmail };
// Check if the user with the specified email exists
const existingUser = await userCollection.findOne(query);
if (!existingUser) {
return res.status(404).json({ message: "User not found" });
}
// Update the user's profile data
const updateResult = await userCollection.updateOne(query, { $set: updatedUserData });
if (updateResult.modifiedCount === 0) {
return res.status(500).json({ message: "Failed to update user profile" });
}
res.status(200).json({ message: "User profile updated successfully" });
});
app.get("/users/:email", async (req, res) => {
const userEmail = req.params.email; // Get the user's email from the URL parameter
// Create a query to find the user by their email
const query = { email: userEmail };
// Find the user based on the email
const user = await userCollection.findOne(query);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
// Return the user's profile data as a JSON response
res.status(200).json(user);
});
app.get("/users", async (req, res) => {
const result = await userCollection.find().toArray();
res.send(result);
});
// update user Role
app.patch("/updateUserRole/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const newRole = {
$set: req.body,
};
const result = await userCollection.updateOne(query, newRole);
res.send(result);
});
app.get("/all-pharmacist/:role", async (req, res) => {
const role = req.params.role;
const query = { role: role };
const result = await userCollection.find(query).toArray();
res.send(result);
});
app.delete("/delete-user/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await userCollection.deleteOne(query);
res.send(result);
});
// =========== Feedback apis ===========
app.get("/feedback", async (req, res) => {
const result = await feedbackCollection.find().toArray();
res.send(result);
});
app.post("/feedback", async (req, res) => {
const feedback = req.body;
const result = await feedbackCollection.insertOne(feedback);
res.send(result);
});
// =========== Payment getwey ===========
app.post("/payment", async (req, res) => {
const paymentData = req.body;
const cart = paymentData.cart;
const discountCode = paymentData?.discountCode;
const transId = new ObjectId().toString();
const { name, email, division, district, location, number, totalPayment } = paymentData.paymentDetails;
const points = ((10 * totalPayment) / 100).toFixed(2);
const data = {
total_amount: totalPayment,
currency: "BDT",
tran_id: transId, // use unique tran_id for each api call
success_url: `http://localhost:5000/payment/success/${transId}?discountCode=${discountCode}&email=${email}&points=${points}`,
fail_url: `http://localhost:5000/payment/fail/${transId}`,
cancel_url: `http://localhost:5000/payment/fail/${transId}`,
ipn_url: "http://localhost:3030/ipn",
shipping_method: "Courier",
product_name: "Computer.",
product_category: "Electronic",
product_profile: "general",
cus_name: name,
cus_email: email,
cus_add1: location,
cus_add2: "Dhaka",
cus_city: "Dhaka",
cus_state: "Dhaka",
cus_postcode: "1000",
cus_country: "Bangladesh",
cus_phone: number,
cus_fax: "01711111111",
ship_name: "Customer Name",
ship_add1: "Dhaka",
ship_add2: "Dhaka",
ship_city: "Dhaka",
ship_state: "Dhaka",
ship_postcode: 1000,
ship_country: "Bangladesh",
};
const currentDate = moment();
// Add 1-3 days to the current date
const oneDaysAhead = currentDate.add(1, "days").format("DD MMM");
const threeDaysAhead = currentDate.add(3, "days").format("DD MMM YYYY");
const sslcz = new SSLCommerzPayment(store_id, store_passwd, is_live);
sslcz.init(data).then((apiResponse) => {
const a = cart.map(async (cp) => {
const { _id, medicine_Id, medicine_name, price, quantity, discount, email, category, image } = cp;
const singleProduct = {
dateAndTime,
expectedDate: [oneDaysAhead, threeDaysAhead],
dateAndTime,
transId,
cartId: _id,
medicine_Id,
status: "pending",
delivery_status: "pending",
pharmacist_response: false,
medicine_name,
price,
quantity,
discount,
email,
category,
image,
name,
division,
district,
location,
number,
};
const createOrder = await orderedMedicinesCollection.insertOne(singleProduct);
});
// Redirect the user to payment gateway
let GatewayPageURL = apiResponse.GatewayPageURL;
res.send({ url: GatewayPageURL, transId });
// console.log('Redirecting to: ', GatewayPageURL)
});
app.post("/payment/success/:id", async (req, res) => {
const transId = req.params.id;
const discountCode = req.query.discountCode;
const email = req.query.email;
const points = req.query.points;
const userInfo = await userCollection.findOne({ email: email }, { projection: { rewardPoints: 1, promoCodes: 1 } });
console.log(userInfo);
if (!userInfo?.rewardPoints) {
const updateInfo = {
$set: {
rewardPoints: parseFloat(points).toFixed(2),
},
};
const addedReward = await userCollection.updateOne({ email: email }, updateInfo, { upsert: true });
} else {
const newPoint = (parseFloat(points) + parseFloat(userInfo.rewardPoints)).toFixed(2);
const updateInfo = {
$set: {
rewardPoints: newPoint,
},
};
const addedReward = await userCollection.updateOne({ email: email }, updateInfo, { upsert: true });
}
if (!userInfo?.promoCodes && discountCode === "WELCOME50") {
const updateInfo = {
$set: {
promoCodes: [discountCode],
},
};
const updatePromo = await userCollection.updateOne({ email: email }, updateInfo, { upsert: true });
}
if (discountCode === "REWARD50") {
const updateInfo = {
$set: {
rewardToDiscount: "",
},
};
const updatePromo = await userCollection.updateOne({ email: email }, updateInfo, { upsert: true });
}
// return;
orderedItems = await orderedMedicinesCollection.find({ transId }).toArray();
orderedItems.forEach(async (item) => {
const query = { _id: new ObjectId(item.medicine_Id) };
const result1 = await medicineCollection.findOne(query);
const url = "dashboard/order-history";
const deliveryTime = "Your order is being processing";
const notificationData = {
name: `New order: ${item.medicine_name}`,
read: "no",
email: item.email,
date: orderDate,
photoURL: item.image,
url,
deliveryTime,
pharmacist_email: result1.pharmacist_email,
};
const newStatus = {
$set: {
status: "success",
pharmacist_email: result1.pharmacist_email,
},
};
const options = { upsert: true };
const updateQuantity = {
$set: {
sellQuantity: result1.sellQuantity + item.quantity,
},
};
const result2 = await orderedMedicinesCollection.updateOne({ _id: new ObjectId(item._id.toString()) }, newStatus, options);
const result3 = await medicineCollection.updateOne({ _id: new ObjectId(item.medicine_Id) }, updateQuantity);
const result4 = await mediCartCollection.deleteOne({ _id: new ObjectId(item.cartId) });
const storeNotification = await imagesNotifications.insertOne(notificationData);
// console.log("a", result2, result3, result4)
});
res.redirect(`http://localhost:5173/paymentSuccess/${req.params.id}`);
});
app.post("/payment/fail/:id", async (req, res) => {
const transId = req.params.id;
orderedItems = await orderedMedicinesCollection.find({ transId }).toArray();
orderedItems.forEach(async (item) => {
const result = await orderedMedicinesCollection.deleteOne({ _id: new ObjectId(item._id.toString()) });
});
res.redirect(`http://localhost:5173/paymentFailed/${req.params.id}`);
});
});
// Lab payment api
app.post("/labPayment", async (req, res) => {
const paymentData = req.body;
const cart = paymentData.cart;
const transId = new ObjectId().toString();
const { name, mobile, email, address, dateTime, age, note, area } = paymentData.personalInfo;
let totalPayment = 0.0 + 50.0; // or report
cart.forEach((singleItem) => {
totalPayment += singleItem.remaining;
});
const points = ((5 * totalPayment) / 100).toFixed(2);
const data = {
total_amount: totalPayment,
currency: "BDT",
tran_id: transId, // use unique tran_id for each api call
success_url: `http://localhost:5000/payment/success/${transId}?email=${email}&points=${points}`,
fail_url: `http://localhost:5000/payment/fail/${transId}`,
cancel_url: `http://localhost:5000/payment/fail/${transId}`,
ipn_url: "http://localhost:3030/ipn",
product_name: "Lab test.",
product_category: "lab test",
product_profile: "general",