-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
791 lines (714 loc) · 23.9 KB
/
index.js
File metadata and controls
791 lines (714 loc) · 23.9 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
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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 3000;
const Stripe = require("stripe");
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
var admin = require("firebase-admin");
//var serviceAccount = require("./cointasker-ed5ad-firebase-adminsdk.json");
const decoded = Buffer.from(process.env.FB_SERVICE_KEY, "base64").toString(
"utf8"
);
const serviceAccount = JSON.parse(decoded);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
//middlewares
app.use(express.json());
app.use(cors());
const verifyFirebaseToken = async (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).send({ message: "Unauthorized access" });
}
//verify firebase token here
try {
const idToken = token.split(" ")[1];
const decoded = await admin.auth().verifyIdToken(idToken);
req.decoded_email = decoded.email;
next();
} catch (error) {
res.status(401).send({ message: "unauthorized access" });
}
};
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const { getAuth } = require("firebase-admin/auth");
const uri = process.env.MONGODB_URI;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
//collections names
const collections = {
USERS: "users",
TASKS: "tasks",
SUBMISSIONS: "submissions",
PAYMENTS: "payments",
WITHDRAWALS: "withdrawals",
};
const database = client.db("CoinTaskerDB");
const usersCollection = database.collection(collections.USERS);
const tasksCollection = database.collection(collections.TASKS);
const submissionsCollection = database.collection(collections.SUBMISSIONS);
const paymentsCollection = database.collection(collections.PAYMENTS);
const withdrawalsCollection = database.collection(collections.WITHDRAWALS);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Send a ping to confirm a successful connection
// await client.db("admin").command({ ping: 1 });
// console.log(
// "Pinged your deployment. You successfully connected to MongoDB!"
// );
app.get("/", (req, res) => {
res.send("Server is up and running");
});
//verify admin middleware
const verifyAdmin = async (req, res, next) => {
const requesterEmail = req.decoded_email;
const requesterAccount = await usersCollection.findOne({
email: requesterEmail,
});
if (requesterAccount && requesterAccount.role === "admin") {
next();
} else {
res.status(403).send({ message: "forbidden access" });
}
};
//verify buyer middleware
const verifyBuyer = async (req, res, next) => {
const requesterEmail = req.decoded_email;
const requesterAccount = await usersCollection.findOne({
email: requesterEmail,
});
if (requesterAccount && requesterAccount.role === "buyer") {
next();
} else {
res.status(403).send({ message: "forbidden access" });
}
};
//verify worker middleware
const verifyWorker = async (req, res, next) => {
const requesterEmail = req.decoded_email;
const requesterAccount = await usersCollection.findOne({
email: requesterEmail,
});
if (requesterAccount && requesterAccount.role === "worker") {
next();
} else {
res.status(403).send({ message: "forbidden access" });
}
};
//USERS RELATED APIS
//get users
app.get("/users", verifyFirebaseToken, async (req, res) => {
const cursor = usersCollection.find();
const users = await cursor.toArray();
res.send(users);
});
//get single user
app.get("/users/:email", verifyFirebaseToken, async (req, res) => {
const email = req.params.email;
const query = { email: email };
const user = await usersCollection.findOne(query);
res.send(user);
});
//get user role
app.get("/users/:email/role", verifyFirebaseToken, async (req, res) => {
const email = req.params.email;
const query = { email: email };
const user = await usersCollection.findOne(query);
res.send(user);
});
//update user role by admin
app.patch(
"/users/role/:id",
verifyFirebaseToken,
verifyAdmin,
async (req, res) => {
const id = req.params.id;
const { role } = req.body;
const filter = { _id: new ObjectId(id) };
const updateDoc = {
$set: { role: role },
};
const result = await usersCollection.updateOne(filter, updateDoc);
res.send(result);
}
);
//get user coins
app.get("/users/:email/coin", verifyFirebaseToken, async (req, res) => {
const email = req.params.email;
const query = { email: email };
const user = await usersCollection.findOne(query);
res.send(user);
});
//get top 6 workers based on coins
app.get("/workers/top", async (req, res) => {
const query = { role: "worker" };
const options = {
sort: { coin: -1 },
limit: 6,
};
const cursor = usersCollection.find(query, options);
const workers = await cursor.toArray();
res.send(workers);
});
//create user
app.post("/users", async (req, res) => {
const user = req.body;
const existingUser = await usersCollection.findOne({ email: user.email });
if (existingUser) {
return res.send({ message: "User already exists" });
}
if (user.role === "buyer") {
//do something
user.coin = 50;
} else if (user.role === "worker") {
user.task_completed = 0;
user.coin = 10;
}
user.createdAt = new Date();
const result = await usersCollection.insertOne(user);
res.send(result);
});
//delete user by admin
app.delete(
"/users/:id",
verifyFirebaseToken,
verifyAdmin,
async (req, res) => {
const id = req.params.id;
const filter = { _id: new ObjectId(id) };
try {
// 1️Get user from MongoDB
const dbUser = await usersCollection.findOne(filter);
if (dbUser?.email) {
// 2 Get Firebase user using email
const firebaseUser = await admin
.auth()
.getUserByEmail(dbUser.email);
// 3️Delete from Firebase Auth
await admin.auth().deleteUser(firebaseUser.uid);
}
//check the user role and delete related data
if (dbUser.role === "buyer") {
//delete all tasks created by this buyer
await tasksCollection.deleteMany({ buyer_email: dbUser.email });
//delete all submissions related to this buyer
await submissionsCollection.deleteMany({
buyer_email: dbUser.email,
});
} else if (dbUser.role === "worker") {
//delete all submissions made by this worker
await submissionsCollection.deleteMany({
worker_email: dbUser.email,
});
}
// 4️ Delete from MongoDB
const result = await usersCollection.deleteOne(filter);
res.send(result);
} catch (error) {
console.error("Error deleting user:", error);
res.status(500).send({
success: false,
message: error.message,
});
}
}
);
//TASKS RELATED APIs
//create a task
app.post("/tasks", verifyFirebaseToken, verifyBuyer, async (req, res) => {
const task = req.body;
task.createdAt = new Date();
//deduct coins from user
const buyerEmail = task.buyer_email;
const buyer = await usersCollection.findOne({ email: buyerEmail });
if (!buyer) {
return res.status(404).send({ message: "Buyer not found" });
}
if (buyer.coin < task.total_payable_amount) {
return res
.status(400)
.send({ message: "Insufficient coins to create task" });
}
const updatedCoin = buyer.coin - task.total_payable_amount;
await usersCollection.updateOne(
{ email: buyerEmail },
{ $set: { coin: updatedCoin } }
);
const result = await tasksCollection.insertOne(task);
res.send(result);
});
//get tasks
app.get("/tasks", verifyFirebaseToken, async (req, res) => {
const email = req.query.email;
let query = {};
if (email) {
query = { buyer_email: email };
}
const cursor = tasksCollection.find(query);
const tasks = await cursor.toArray();
res.send(tasks);
});
//get task based on required workers greater than 0
app.get("/tasks/available", verifyFirebaseToken, async (req, res) => {
const query = { required_workers: { $gt: 0 } };
const cursor = tasksCollection.find(query);
const tasks = await cursor.toArray();
res.send(tasks);
});
//get single task by id
app.get("/tasks/:id", verifyFirebaseToken, async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const task = await tasksCollection.findOne(query);
res.send(task);
});
//update a task
app.patch(
"/tasks/:id",
verifyFirebaseToken,
verifyBuyer,
async (req, res) => {
const id = req.params.id;
const updates = req.body;
const filter = { _id: new ObjectId(id) };
const updateDoc = {
$set: updates,
};
const result = await tasksCollection.updateOne(filter, updateDoc);
res.send(result);
}
);
//delete a task
app.delete("/tasks/:id", verifyFirebaseToken, async (req, res) => {
const id = req.params.id;
//get the task to refund coins to buyer
const task = await tasksCollection.findOne({ _id: new ObjectId(id) });
if (task) {
const buyerEmail = task.buyer_email;
const buyer = await usersCollection.findOne({ email: buyerEmail });
if (buyer) {
const updatedCoin = buyer.coin + task.total_payable_amount;
await usersCollection.updateOne(
{ email: buyerEmail },
{ $set: { coin: updatedCoin } }
);
}
}
const filter = { _id: new ObjectId(id) };
const result = await tasksCollection.deleteOne(filter);
res.send(result);
});
//SUBMISSIONS RELATED APIS
//create a submission
app.post(
"/submissions",
verifyFirebaseToken,
verifyWorker,
async (req, res) => {
const submission = req.body;
submission.createdAt = new Date();
const workerEmail = submission.worker_email;
const worker = await usersCollection.findOne({ email: workerEmail });
if (!worker) {
return res.status(404).send({ message: "Worker not found" });
}
//check duplicate submission for the same task by the same worker
const existingSubmission = await submissionsCollection.findOne({
task_id: submission.task_id,
worker_email: workerEmail,
});
if (existingSubmission) {
return res
.status(400)
.send({ message: "You have already submitted for this task" });
}
//decresese required_workers in task
const taskId = submission.task_id;
const task = await tasksCollection.findOne({
_id: new ObjectId(taskId),
});
if (!task) {
return res.status(404).send({ message: "Task not found" });
}
if (task.required_workers <= 0) {
return res
.status(400)
.send({ message: "No more workers required for this task" });
}
const updatedRequiredWorkers = task.required_workers - 1;
await tasksCollection.updateOne(
{ _id: new ObjectId(taskId) },
{ $set: { required_workers: updatedRequiredWorkers } }
);
const result = await submissionsCollection.insertOne(submission);
res.send(result);
}
);
//get my submissions
app.get("/submissions/my", verifyFirebaseToken, async (req, res) => {
const workerEmail = req.query.worker_email;
const status = req.query.status;
let query = { worker_email: workerEmail };
if (status) {
query.status = status;
}
const cursor = submissionsCollection.find(query);
const submissions = await cursor.toArray();
res.send(submissions);
});
// Fetch Pending Submissions
app.get(
"/submissions/buyer-pending",
verifyFirebaseToken,
async (req, res) => {
const email = req.query.email;
const query = { buyer_email: email, status: "pending" };
const cursor = submissionsCollection.find(query);
const submissions = await cursor.toArray();
res.send(submissions);
}
);
///submissions/approve/:id
app.patch(
"/submissions/approve/:id",
verifyFirebaseToken,
verifyBuyer,
async (req, res) => {
const id = req.params.id;
const filter = { _id: new ObjectId(id) };
const submission = await submissionsCollection.findOne(filter);
if (!submission) {
return res.status(404).send({ message: "Submission not found" });
}
//update submission status to approved
const updateDoc = {
$set: { status: "approved" },
};
const result = await submissionsCollection.updateOne(filter, updateDoc);
//update worker's coin and task_completed
const workerEmail = submission.worker_email;
const worker = await usersCollection.findOne({ email: workerEmail });
if (worker) {
const updatedCoin = worker.coin + submission.payable_amount;
const updatedTasksCompleted = worker.task_completed + 1;
await usersCollection.updateOne(
{ email: workerEmail },
{
$set: {
coin: updatedCoin,
task_completed: updatedTasksCompleted,
},
}
);
}
res.send(result);
}
);
//reject a submission
app.patch(
"/submissions/reject/:id",
verifyFirebaseToken,
verifyBuyer,
async (req, res) => {
const id = req.params.id;
const { taskId } = req.body;
const filter = { _id: new ObjectId(id) };
const submission = await submissionsCollection.findOne(filter);
if (!submission) {
return res.status(404).send({ message: "Submission not found" });
}
//update submission status to rejected
const updateDoc = {
$set: { status: "rejected" },
};
const result = await submissionsCollection.updateOne(filter, updateDoc);
//increment required_workers in task
const task = await tasksCollection.findOne({
_id: new ObjectId(taskId),
});
if (task) {
const updatedRequiredWorkers = task.required_workers + 1;
await tasksCollection.updateOne(
{ _id: new ObjectId(taskId) },
{ $set: { required_workers: updatedRequiredWorkers } }
);
}
res.send(result);
}
);
//WITHDRAWALS APIs
//create a withdrawal request
app.post(
"/withdrawals",
verifyFirebaseToken,
verifyWorker,
async (req, res) => {
const withdrawal = req.body;
withdrawal.createdAt = new Date();
withdrawal.status = "pending";
const workerEmail = withdrawal.worker_email;
const worker = await usersCollection.findOne({ email: workerEmail });
console.log("Withdrawal request received:", withdrawal);
if (!worker) {
return res.status(404).send({ message: "Worker not found" });
}
if (worker.coin < withdrawal.withdrawal_coin) {
return res
.status(400)
.send({ message: "Insufficient coins for withdrawal" });
}
const updatedCoin = worker.coin - withdrawal.withdrawal_coin;
await usersCollection.updateOne(
{ email: workerEmail },
{ $set: { coin: updatedCoin } }
);
const result = await withdrawalsCollection.insertOne(withdrawal);
res.send(result);
}
);
//get withdrawals
app.get("/withdrawals", verifyFirebaseToken, async (req, res) => {
const email = req.query.email;
const status = req.query.status;
let query = {};
if (email) {
query = { worker_email: email };
}
if (status) {
query.status = status;
}
const cursor = withdrawalsCollection.find(query);
const withdrawals = await cursor.toArray();
res.send(withdrawals);
});
//update withdrawal status by admin
app.patch(
"/withdrawals/:id",
verifyFirebaseToken,
verifyAdmin,
async (req, res) => {
const id = req.params.id;
const { status } = req.body;
const filter = { _id: new ObjectId(id) };
const updateDoc = {
$set: { status: status },
};
const result = await withdrawalsCollection.updateOne(filter, updateDoc);
res.send(result);
}
);
//PAYMENTS RELATED APIS
//create checkout session
app.post("/create-checkout-session", async (req, res) => {
const { cost, packageName, buyerEmail, coinAmount } = req.body;
if (!cost || !buyerEmail || !coinAmount) {
return res.status(400).send({ message: "Invalid payment data" });
}
const amount = Number(cost) * 100; // cents
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
mode: "payment",
customer_email: buyerEmail,
line_items: [
{
price_data: {
currency: "usd",
unit_amount: amount,
product_data: { name: packageName },
},
quantity: 1,
},
],
metadata: {
buyerEmail,
packageName,
coinAmount,
},
success_url: `${process.env.SITE_DOMAIN}/dashboard/payment-success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.SITE_DOMAIN}/dashboard/payment-cancelled`,
});
res.send({ url: session.url });
});
//payment success api
app.patch("/payment-success", async (req, res) => {
const { session_id } = req.query;
if (!session_id)
return res.status(400).send({ message: "Session ID missing" });
const session = await stripe.checkout.sessions.retrieve(session_id);
if (session.payment_status !== "paid") {
return res.status(400).send({ message: "Payment not completed" });
}
const transactionId = session.payment_intent;
const buyerEmail = session.metadata.buyerEmail;
const coinAmount = Number(session.metadata.coinAmount);
try {
const result = await paymentsCollection.updateOne(
{ transactionId },
{
$setOnInsert: {
buyerEmail,
packageName: session.metadata.packageName,
coinAmount,
amount: session.amount_total / 100,
currency: session.currency,
transactionId,
paymentStatus: session.payment_status,
paidAt: new Date(),
},
},
{ upsert: true }
);
if (result.upsertedCount === 1) {
await usersCollection.updateOne(
{ email: buyerEmail },
{ $inc: { coin: coinAmount } }
);
}
return res.send({
success: true,
transactionId,
});
} catch (err) {
if (err.code === 11000) {
return res.send({
success: true,
message: "Payment already processed",
transactionId,
});
}
throw err;
}
});
//get payments
app.get("/payments", verifyFirebaseToken, async (req, res) => {
const email = req.query.email;
const query = {};
if (email) {
query.buyerEmail = email;
//check email address
if (email != req.decoded_email) {
res.status(403).send({ message: "forbidden access" });
}
}
const cursor = paymentsCollection.find(query).sort({ paidAt: -1 });
const result = await cursor.toArray();
res.send(result);
});
//STATS RELATED APIS
//get workeer stats
app.get(
"/worker/stats",
verifyFirebaseToken,
verifyWorker,
async (req, res) => {
const email = req.query.email;
const worker = await usersCollection.findOne({ email: email });
if (!worker) {
return res.status(404).send({ message: "Worker not found" });
}
const totalSubmissions = await submissionsCollection.countDocuments({
worker_email: email,
});
const pendingSubmissions = await submissionsCollection.countDocuments({
worker_email: email,
status: "pending",
});
const earnings = await submissionsCollection
.aggregate([
{ $match: { worker_email: email, status: "approved" } },
{ $group: { _id: null, total: { $sum: "$payable_amount" } } },
])
.toArray();
res.send({
task_completed: worker.task_completed,
totalSubmissions,
pendingSubmissions,
totalEarnings: earnings[0]?.total || 0,
});
}
);
//get admin stats
app.get(
"/admin-stats",
verifyFirebaseToken,
verifyAdmin,
async (req, res) => {
try {
const [totalWorkers, totalBuyers] = await Promise.all([
usersCollection.countDocuments({ role: "worker" }),
usersCollection.countDocuments({ role: "buyer" }),
]);
const coinsAggregation = await usersCollection
.aggregate([
{ $group: { _id: null, totalCoins: { $sum: "$coin" } } },
])
.toArray();
const paymentsAggregation = await withdrawalsCollection
.aggregate([
{ $match: { status: "approved" } },
{
$group: {
_id: null,
totalPayments: { $sum: "$withdrawal_amount" },
},
},
])
.toArray();
res.send({
totalWorkers,
totalBuyers,
totalAvailableCoins: coinsAggregation[0]?.totalCoins || 0,
totalPayments: paymentsAggregation[0]?.totalPayments || 0,
});
} catch (error) {
console.error("Admin stats error:", error);
res.status(500).send({ message: "Failed to load admin stats" });
}
}
);
//get buyer stats
app.get(
"/buyer/stats",
verifyFirebaseToken,
verifyBuyer,
async (req, res) => {
const email = req.query.email;
const totalTasks = await tasksCollection.countDocuments({
buyer_email: email,
});
const pendingTasks = await submissionsCollection.countDocuments({
buyer_email: email,
status: "pending",
});
const payments = await submissionsCollection
.aggregate([
{ $match: { buyer_email: email, status: "approved" } },
{ $group: { _id: null, total: { $sum: "$payable_amount" } } },
])
.toArray();
res.send({
totalTasks,
pendingTasks,
totalPaymentPaid: payments[0]?.total || 0,
});
}
);
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
} finally {
// Ensures that the client will close when you finish/error
//await client.close();
}
}
run().catch(console.dir);