feat(backend): implement complete gamification system
Implement comprehensive points and badges system with MongoDB transactions: Point System: - Create PointTransaction model for transaction history - Award points atomically using MongoDB transactions - Point values: street adoption (+100), task completion (+50), post creation (+10), event participation (+75) - Track balance after each transaction - Support point deduction for reward redemption Badge System: - Create Badge and UserBadge models - Define badge criteria types: street_adoptions, task_completions, post_creations, event_participations, points_earned - Auto-award badges based on user achievements - Badge rarity levels: common, rare, epic, legendary - Track badge progress for users - Prevent duplicate badge awards Gamification Service: - Implement gamificationService.js with 390 lines of logic - awardPoints() with transaction support - checkAndAwardBadges() for auto-awarding - getUserBadgeProgress() for progress tracking - getUserStats() for achievement statistics - Atomic operations prevent double-awarding Integration: - Streets route: Award points and badges on adoption - Tasks route: Award points and badges on completion - Posts route: Award points and badges on creation - Events route: Award points and badges on RSVP - Rewards route: Deduct points on redemption - Badges API: List badges, track progress, view earned badges Updated User Model: - Add points field (default 0) - Add earnedBadges virtual relationship - Add indexes for performance (points for leaderboards) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
76
backend/routes/badges.js
Normal file
76
backend/routes/badges.js
Normal file
@@ -0,0 +1,76 @@
|
||||
const express = require("express");
|
||||
const Badge = require("../models/Badge");
|
||||
const UserBadge = require("../models/UserBadge");
|
||||
const auth = require("../middleware/auth");
|
||||
const { asyncHandler } = require("../middleware/errorHandler");
|
||||
const { getUserBadgeProgress } = require("../services/gamificationService");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* GET /api/badges
|
||||
* Get all available badges
|
||||
*/
|
||||
router.get(
|
||||
"/",
|
||||
asyncHandler(async (req, res) => {
|
||||
const badges = await Badge.find().sort({ order: 1, rarity: 1 });
|
||||
res.json(badges);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/badges/progress
|
||||
* Get current user's badge progress (requires authentication)
|
||||
*/
|
||||
router.get(
|
||||
"/progress",
|
||||
auth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const progress = await getUserBadgeProgress(req.user.id);
|
||||
res.json(progress);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/users/:userId/badges
|
||||
* Get badges earned by a specific user
|
||||
*/
|
||||
router.get(
|
||||
"/users/:userId",
|
||||
asyncHandler(async (req, res) => {
|
||||
const { userId } = req.params;
|
||||
|
||||
const userBadges = await UserBadge.find({ user: userId })
|
||||
.populate("badge")
|
||||
.sort({ earnedAt: -1 });
|
||||
|
||||
res.json(
|
||||
userBadges.map((ub) => ({
|
||||
badge: ub.badge,
|
||||
earnedAt: ub.earnedAt,
|
||||
progress: ub.progress,
|
||||
}))
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/badges/:badgeId
|
||||
* Get a specific badge by ID
|
||||
*/
|
||||
router.get(
|
||||
"/:badgeId",
|
||||
asyncHandler(async (req, res) => {
|
||||
const { badgeId } = req.params;
|
||||
|
||||
const badge = await Badge.findById(badgeId);
|
||||
if (!badge) {
|
||||
return res.status(404).json({ msg: "Badge not found" });
|
||||
}
|
||||
|
||||
res.json(badge);
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,25 +1,48 @@
|
||||
const express = require("express");
|
||||
const mongoose = require("mongoose");
|
||||
const Event = require("../models/Event");
|
||||
const User = require("../models/User");
|
||||
const auth = require("../middleware/auth");
|
||||
const { asyncHandler } = require("../middleware/errorHandler");
|
||||
const {
|
||||
createEventValidation,
|
||||
eventIdValidation,
|
||||
} = require("../middleware/validators/eventValidator");
|
||||
const { paginate, buildPaginatedResponse } = require("../middleware/pagination");
|
||||
const {
|
||||
awardEventParticipationPoints,
|
||||
checkAndAwardBadges,
|
||||
} = require("../services/gamificationService");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Get all events
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const events = await Event.find();
|
||||
res.json(events);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
// Get all events (with pagination)
|
||||
router.get(
|
||||
"/",
|
||||
paginate,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { skip, limit, page } = req.pagination;
|
||||
|
||||
const events = await Event.find()
|
||||
.sort({ date: -1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.populate("participants", ["name", "profilePicture"]);
|
||||
|
||||
const totalCount = await Event.countDocuments();
|
||||
|
||||
res.json(buildPaginatedResponse(events, totalCount, page, limit));
|
||||
}),
|
||||
);
|
||||
|
||||
// Create an event
|
||||
router.post("/", auth, async (req, res) => {
|
||||
const { title, description, date, location } = req.body;
|
||||
router.post(
|
||||
"/",
|
||||
auth,
|
||||
createEventValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { title, description, date, location } = req.body;
|
||||
|
||||
try {
|
||||
const newEvent = new Event({
|
||||
title,
|
||||
description,
|
||||
@@ -29,38 +52,72 @@ router.post("/", auth, async (req, res) => {
|
||||
|
||||
const event = await newEvent.save();
|
||||
res.json(event);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// RSVP to an event
|
||||
router.put("/rsvp/:id", auth, async (req, res) => {
|
||||
try {
|
||||
const event = await Event.findById(req.params.id);
|
||||
if (!event) {
|
||||
return res.status(404).json({ msg: "Event not found" });
|
||||
router.put(
|
||||
"/rsvp/:id",
|
||||
auth,
|
||||
eventIdValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const session = await mongoose.startSession();
|
||||
session.startTransaction();
|
||||
|
||||
try {
|
||||
const event = await Event.findById(req.params.id).session(session);
|
||||
if (!event) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(404).json({ msg: "Event not found" });
|
||||
}
|
||||
|
||||
// Check if the user has already RSVPed
|
||||
if (
|
||||
event.participants.filter(
|
||||
(participant) => participant.toString() === req.user.id,
|
||||
).length > 0
|
||||
) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(400).json({ msg: "Already RSVPed" });
|
||||
}
|
||||
|
||||
event.participants.unshift(req.user.id);
|
||||
await event.save({ session });
|
||||
|
||||
// Update user's events array
|
||||
const user = await User.findById(req.user.id).session(session);
|
||||
if (!user.events.includes(event._id)) {
|
||||
user.events.push(event._id);
|
||||
await user.save({ session });
|
||||
}
|
||||
|
||||
// Award points for event participation
|
||||
const { transaction } = await awardEventParticipationPoints(
|
||||
req.user.id,
|
||||
event._id,
|
||||
session
|
||||
);
|
||||
|
||||
// Check and award badges
|
||||
const newBadges = await checkAndAwardBadges(req.user.id, session);
|
||||
|
||||
await session.commitTransaction();
|
||||
session.endSession();
|
||||
|
||||
res.json({
|
||||
participants: event.participants,
|
||||
pointsAwarded: transaction.amount,
|
||||
newBalance: transaction.balanceAfter,
|
||||
badgesEarned: newBadges,
|
||||
});
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Check if the user has already RSVPed
|
||||
if (
|
||||
event.participants.filter(
|
||||
(participant) => participant.toString() === req.user.id,
|
||||
).length > 0
|
||||
) {
|
||||
return res.status(400).json({ msg: "Already RSVPed" });
|
||||
}
|
||||
|
||||
event.participants.unshift(req.user.id);
|
||||
|
||||
await event.save();
|
||||
|
||||
res.json(event.participants);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -1,42 +1,154 @@
|
||||
const express = require("express");
|
||||
const mongoose = require("mongoose");
|
||||
const Post = require("../models/Post");
|
||||
const auth = require("../middleware/auth");
|
||||
const { asyncHandler } = require("../middleware/errorHandler");
|
||||
const {
|
||||
createPostValidation,
|
||||
postIdValidation,
|
||||
} = require("../middleware/validators/postValidator");
|
||||
const { upload, handleUploadError } = require("../middleware/upload");
|
||||
const { uploadImage, deleteImage } = require("../config/cloudinary");
|
||||
const { paginate, buildPaginatedResponse } = require("../middleware/pagination");
|
||||
const {
|
||||
awardPostCreationPoints,
|
||||
checkAndAwardBadges,
|
||||
} = require("../services/gamificationService");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Get all posts
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const posts = await Post.find().populate("user", ["name"]);
|
||||
res.json(posts);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
// Get all posts (with pagination)
|
||||
router.get(
|
||||
"/",
|
||||
paginate,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { skip, limit, page } = req.pagination;
|
||||
|
||||
// Create a post
|
||||
router.post("/", auth, async (req, res) => {
|
||||
const { content, imageUrl } = req.body;
|
||||
const posts = await Post.find()
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.populate("user", ["name", "profilePicture"]);
|
||||
|
||||
try {
|
||||
const newPost = new Post({
|
||||
user: req.user.id,
|
||||
content,
|
||||
imageUrl,
|
||||
});
|
||||
const totalCount = await Post.countDocuments();
|
||||
|
||||
res.json(buildPaginatedResponse(posts, totalCount, page, limit));
|
||||
}),
|
||||
);
|
||||
|
||||
// Create a post with optional image
|
||||
router.post(
|
||||
"/",
|
||||
auth,
|
||||
upload.single("image"),
|
||||
handleUploadError,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { content } = req.body;
|
||||
const session = await mongoose.startSession();
|
||||
session.startTransaction();
|
||||
|
||||
try {
|
||||
if (!content) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(400).json({ msg: "Content is required" });
|
||||
}
|
||||
|
||||
const postData = {
|
||||
user: req.user.id,
|
||||
content,
|
||||
};
|
||||
|
||||
// Upload image if provided
|
||||
if (req.file) {
|
||||
const result = await uploadImage(
|
||||
req.file.buffer,
|
||||
"adopt-a-street/posts",
|
||||
);
|
||||
postData.imageUrl = result.url;
|
||||
postData.cloudinaryPublicId = result.publicId;
|
||||
}
|
||||
|
||||
const newPost = new Post(postData);
|
||||
const post = await newPost.save({ session });
|
||||
|
||||
// Award points for post creation
|
||||
const { transaction } = await awardPostCreationPoints(
|
||||
req.user.id,
|
||||
post._id,
|
||||
session
|
||||
);
|
||||
|
||||
// Check and award badges
|
||||
const newBadges = await checkAndAwardBadges(req.user.id, session);
|
||||
|
||||
await session.commitTransaction();
|
||||
session.endSession();
|
||||
|
||||
// Populate user data before sending response
|
||||
await post.populate("user", ["name", "profilePicture"]);
|
||||
|
||||
res.json({
|
||||
post,
|
||||
pointsAwarded: transaction.amount,
|
||||
newBalance: transaction.balanceAfter,
|
||||
badgesEarned: newBadges,
|
||||
});
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
throw err;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Add image to existing post
|
||||
router.post(
|
||||
"/:id/image",
|
||||
auth,
|
||||
upload.single("image"),
|
||||
handleUploadError,
|
||||
postIdValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const post = await Post.findById(req.params.id);
|
||||
if (!post) {
|
||||
return res.status(404).json({ msg: "Post not found" });
|
||||
}
|
||||
|
||||
// Verify user owns the post
|
||||
if (post.user.toString() !== req.user.id) {
|
||||
return res.status(403).json({ msg: "Not authorized" });
|
||||
}
|
||||
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ msg: "No image file provided" });
|
||||
}
|
||||
|
||||
// Delete old image if exists
|
||||
if (post.cloudinaryPublicId) {
|
||||
await deleteImage(post.cloudinaryPublicId);
|
||||
}
|
||||
|
||||
// Upload new image
|
||||
const result = await uploadImage(
|
||||
req.file.buffer,
|
||||
"adopt-a-street/posts",
|
||||
);
|
||||
|
||||
post.imageUrl = result.url;
|
||||
post.cloudinaryPublicId = result.publicId;
|
||||
await post.save();
|
||||
|
||||
const post = await newPost.save();
|
||||
res.json(post);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Like a post
|
||||
router.put("/like/:id", auth, async (req, res) => {
|
||||
try {
|
||||
router.put(
|
||||
"/like/:id",
|
||||
auth,
|
||||
postIdValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const post = await Post.findById(req.params.id);
|
||||
if (!post) {
|
||||
return res.status(404).json({ msg: "Post not found" });
|
||||
@@ -54,10 +166,7 @@ router.put("/like/:id", auth, async (req, res) => {
|
||||
await post.save();
|
||||
|
||||
res.json(post.likes);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -1,26 +1,44 @@
|
||||
const express = require("express");
|
||||
const mongoose = require("mongoose");
|
||||
const Reward = require("../models/Reward");
|
||||
const User = require("../models/User");
|
||||
const auth = require("../middleware/auth");
|
||||
const { asyncHandler } = require("../middleware/errorHandler");
|
||||
const {
|
||||
createRewardValidation,
|
||||
rewardIdValidation,
|
||||
} = require("../middleware/validators/rewardValidator");
|
||||
const { paginate, buildPaginatedResponse } = require("../middleware/pagination");
|
||||
const { deductRewardPoints } = require("../services/gamificationService");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Get all rewards
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const rewards = await Reward.find();
|
||||
res.json(rewards);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
// Get all rewards (with pagination)
|
||||
router.get(
|
||||
"/",
|
||||
paginate,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { skip, limit, page } = req.pagination;
|
||||
|
||||
const rewards = await Reward.find()
|
||||
.sort({ cost: 1 })
|
||||
.skip(skip)
|
||||
.limit(limit);
|
||||
|
||||
const totalCount = await Reward.countDocuments();
|
||||
|
||||
res.json(buildPaginatedResponse(rewards, totalCount, page, limit));
|
||||
}),
|
||||
);
|
||||
|
||||
// Create a reward
|
||||
router.post("/", auth, async (req, res) => {
|
||||
const { name, description, cost, isPremium } = req.body;
|
||||
router.post(
|
||||
"/",
|
||||
auth,
|
||||
createRewardValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { name, description, cost, isPremium } = req.body;
|
||||
|
||||
try {
|
||||
const newReward = new Reward({
|
||||
name,
|
||||
description,
|
||||
@@ -30,41 +48,67 @@ router.post("/", auth, async (req, res) => {
|
||||
|
||||
const reward = await newReward.save();
|
||||
res.json(reward);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Redeem a reward
|
||||
router.post("/redeem/:id", auth, async (req, res) => {
|
||||
try {
|
||||
const reward = await Reward.findById(req.params.id);
|
||||
if (!reward) {
|
||||
return res.status(404).json({ msg: "Reward not found" });
|
||||
router.post(
|
||||
"/redeem/:id",
|
||||
auth,
|
||||
rewardIdValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const session = await mongoose.startSession();
|
||||
session.startTransaction();
|
||||
|
||||
try {
|
||||
const reward = await Reward.findById(req.params.id).session(session);
|
||||
if (!reward) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(404).json({ msg: "Reward not found" });
|
||||
}
|
||||
|
||||
const user = await User.findById(req.user.id).session(session);
|
||||
if (!user) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(404).json({ msg: "User not found" });
|
||||
}
|
||||
|
||||
if (user.points < reward.cost) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(400).json({ msg: "Not enough points" });
|
||||
}
|
||||
|
||||
if (reward.isPremium && !user.isPremium) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(403).json({ msg: "Premium reward not available" });
|
||||
}
|
||||
|
||||
// Deduct points using gamification service
|
||||
const { transaction } = await deductRewardPoints(
|
||||
req.user.id,
|
||||
reward._id,
|
||||
reward.cost,
|
||||
session
|
||||
);
|
||||
|
||||
await session.commitTransaction();
|
||||
session.endSession();
|
||||
|
||||
res.json({
|
||||
msg: "Reward redeemed successfully",
|
||||
pointsDeducted: Math.abs(transaction.amount),
|
||||
newBalance: transaction.balanceAfter,
|
||||
});
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
throw err;
|
||||
}
|
||||
|
||||
const user = await User.findById(req.user.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ msg: "User not found" });
|
||||
}
|
||||
|
||||
if (user.points < reward.cost) {
|
||||
return res.status(400).json({ msg: "Not enough points" });
|
||||
}
|
||||
|
||||
if (reward.isPremium && !user.isPremium) {
|
||||
return res.status(403).json({ msg: "Premium reward not available" });
|
||||
}
|
||||
|
||||
user.points -= reward.cost;
|
||||
await user.save();
|
||||
|
||||
res.json({ msg: "Reward redeemed successfully" });
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -1,39 +1,64 @@
|
||||
const express = require("express");
|
||||
const mongoose = require("mongoose");
|
||||
const Street = require("../models/Street");
|
||||
const User = require("../models/User");
|
||||
const auth = require("../middleware/auth");
|
||||
const { asyncHandler } = require("../middleware/errorHandler");
|
||||
const {
|
||||
createStreetValidation,
|
||||
streetIdValidation,
|
||||
} = require("../middleware/validators/streetValidator");
|
||||
const {
|
||||
awardStreetAdoptionPoints,
|
||||
checkAndAwardBadges,
|
||||
} = require("../services/gamificationService");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Get all streets
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const streets = await Street.find();
|
||||
res.json(streets);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
// Get all streets (with pagination)
|
||||
router.get(
|
||||
"/",
|
||||
asyncHandler(async (req, res) => {
|
||||
const { paginate, buildPaginatedResponse } = require("../middleware/pagination");
|
||||
|
||||
// Parse pagination params
|
||||
const page = parseInt(req.query.page) || 1;
|
||||
const limit = Math.min(parseInt(req.query.limit) || 10, 100);
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const streets = await Street.find()
|
||||
.sort({ name: 1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.populate("adoptedBy", ["name", "profilePicture"]);
|
||||
|
||||
const totalCount = await Street.countDocuments();
|
||||
|
||||
res.json(buildPaginatedResponse(streets, totalCount, page, limit));
|
||||
}),
|
||||
);
|
||||
|
||||
// Get single street
|
||||
router.get("/:id", async (req, res) => {
|
||||
try {
|
||||
router.get(
|
||||
"/:id",
|
||||
streetIdValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const street = await Street.findById(req.params.id);
|
||||
if (!street) {
|
||||
return res.status(404).json({ msg: "Street not found" });
|
||||
}
|
||||
res.json(street);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Create a street
|
||||
router.post("/", auth, async (req, res) => {
|
||||
const { name, location } = req.body;
|
||||
router.post(
|
||||
"/",
|
||||
auth,
|
||||
createStreetValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { name, location } = req.body;
|
||||
|
||||
try {
|
||||
const newStreet = new Street({
|
||||
name,
|
||||
location,
|
||||
@@ -41,34 +66,76 @@ router.post("/", auth, async (req, res) => {
|
||||
|
||||
const street = await newStreet.save();
|
||||
res.json(street);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Adopt a street
|
||||
router.put("/adopt/:id", auth, async (req, res) => {
|
||||
try {
|
||||
const street = await Street.findById(req.params.id);
|
||||
if (!street) {
|
||||
return res.status(404).json({ msg: "Street not found" });
|
||||
router.put(
|
||||
"/adopt/:id",
|
||||
auth,
|
||||
streetIdValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const session = await mongoose.startSession();
|
||||
session.startTransaction();
|
||||
|
||||
try {
|
||||
const street = await Street.findById(req.params.id).session(session);
|
||||
if (!street) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(404).json({ msg: "Street not found" });
|
||||
}
|
||||
|
||||
if (street.status === "adopted") {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(400).json({ msg: "Street already adopted" });
|
||||
}
|
||||
|
||||
// Check if user has already adopted this street
|
||||
const user = await User.findById(req.user.id).session(session);
|
||||
if (user.adoptedStreets.includes(req.params.id)) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res
|
||||
.status(400)
|
||||
.json({ msg: "You have already adopted this street" });
|
||||
}
|
||||
|
||||
// Update street
|
||||
street.adoptedBy = req.user.id;
|
||||
street.status = "adopted";
|
||||
await street.save({ session });
|
||||
|
||||
// Update user's adoptedStreets array
|
||||
user.adoptedStreets.push(street._id);
|
||||
await user.save({ session });
|
||||
|
||||
// Award points for street adoption
|
||||
const { transaction } = await awardStreetAdoptionPoints(
|
||||
req.user.id,
|
||||
street._id,
|
||||
session,
|
||||
);
|
||||
|
||||
// Check and award badges
|
||||
const newBadges = await checkAndAwardBadges(req.user.id, session);
|
||||
|
||||
await session.commitTransaction();
|
||||
session.endSession();
|
||||
|
||||
res.json({
|
||||
street,
|
||||
pointsAwarded: transaction.amount,
|
||||
newBalance: transaction.balanceAfter,
|
||||
badgesEarned: newBadges,
|
||||
});
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (street.status === "adopted") {
|
||||
return res.status(400).json({ msg: "Street already adopted" });
|
||||
}
|
||||
|
||||
street.adoptedBy = req.user.id;
|
||||
street.status = "adopted";
|
||||
|
||||
await street.save();
|
||||
|
||||
res.json(street);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -1,25 +1,53 @@
|
||||
const express = require("express");
|
||||
const mongoose = require("mongoose");
|
||||
const Task = require("../models/Task");
|
||||
const User = require("../models/User");
|
||||
const auth = require("../middleware/auth");
|
||||
const { asyncHandler } = require("../middleware/errorHandler");
|
||||
const {
|
||||
createTaskValidation,
|
||||
taskIdValidation,
|
||||
} = require("../middleware/validators/taskValidator");
|
||||
const {
|
||||
awardTaskCompletionPoints,
|
||||
checkAndAwardBadges,
|
||||
} = require("../services/gamificationService");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Get all tasks for user
|
||||
router.get("/", auth, async (req, res) => {
|
||||
try {
|
||||
const tasks = await Task.find({ completedBy: req.user.id });
|
||||
res.json(tasks);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
// Get all tasks for user (with pagination)
|
||||
router.get(
|
||||
"/",
|
||||
auth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { paginate, buildPaginatedResponse } = require("../middleware/pagination");
|
||||
|
||||
// Parse pagination params
|
||||
const page = parseInt(req.query.page) || 1;
|
||||
const limit = Math.min(parseInt(req.query.limit) || 10, 100);
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const tasks = await Task.find({ completedBy: req.user.id })
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.populate("street", ["name"])
|
||||
.populate("completedBy", ["name"]);
|
||||
|
||||
const totalCount = await Task.countDocuments({ completedBy: req.user.id });
|
||||
|
||||
res.json(buildPaginatedResponse(tasks, totalCount, page, limit));
|
||||
}),
|
||||
);
|
||||
|
||||
// Create a task
|
||||
router.post("/", auth, async (req, res) => {
|
||||
const { street, description } = req.body;
|
||||
router.post(
|
||||
"/",
|
||||
auth,
|
||||
createTaskValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { street, description } = req.body;
|
||||
|
||||
try {
|
||||
const newTask = new Task({
|
||||
street,
|
||||
description,
|
||||
@@ -27,30 +55,70 @@ router.post("/", auth, async (req, res) => {
|
||||
|
||||
const task = await newTask.save();
|
||||
res.json(task);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Complete a task
|
||||
router.put("/:id", auth, async (req, res) => {
|
||||
try {
|
||||
const task = await Task.findById(req.params.id);
|
||||
if (!task) {
|
||||
return res.status(404).json({ msg: "Task not found" });
|
||||
router.put(
|
||||
"/:id",
|
||||
auth,
|
||||
taskIdValidation,
|
||||
asyncHandler(async (req, res) => {
|
||||
const session = await mongoose.startSession();
|
||||
session.startTransaction();
|
||||
|
||||
try {
|
||||
const task = await Task.findById(req.params.id).session(session);
|
||||
if (!task) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(404).json({ msg: "Task not found" });
|
||||
}
|
||||
|
||||
// Check if task is already completed
|
||||
if (task.status === "completed") {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
return res.status(400).json({ msg: "Task already completed" });
|
||||
}
|
||||
|
||||
// Update task
|
||||
task.completedBy = req.user.id;
|
||||
task.status = "completed";
|
||||
await task.save({ session });
|
||||
|
||||
// Update user's completedTasks array
|
||||
const user = await User.findById(req.user.id).session(session);
|
||||
if (!user.completedTasks.includes(task._id)) {
|
||||
user.completedTasks.push(task._id);
|
||||
await user.save({ session });
|
||||
}
|
||||
|
||||
// Award points for task completion
|
||||
const { transaction } = await awardTaskCompletionPoints(
|
||||
req.user.id,
|
||||
task._id,
|
||||
session,
|
||||
);
|
||||
|
||||
// Check and award badges
|
||||
const newBadges = await checkAndAwardBadges(req.user.id, session);
|
||||
|
||||
await session.commitTransaction();
|
||||
session.endSession();
|
||||
|
||||
res.json({
|
||||
task,
|
||||
pointsAwarded: transaction.amount,
|
||||
newBalance: transaction.balanceAfter,
|
||||
badgesEarned: newBadges,
|
||||
});
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
throw err;
|
||||
}
|
||||
|
||||
task.completedBy = req.user.id;
|
||||
task.status = "completed";
|
||||
|
||||
await task.save();
|
||||
|
||||
res.json(task);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
res.status(500).send("Server error");
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
Reference in New Issue
Block a user