Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Loyalty and rewards APIs #997

Merged
merged 3 commits into from
Nov 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions backend/controllers/rent/RewardsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
const User = require('../../model/user');
const Reward = require('../../model/rent/reward');

exports.accumulatePoints = async (req, res) => {
try {
const user = await User.findById(req.user.id); // Assume user is authenticated
if (!user) {
const errorMessage = "User not found.";
console.error(`Error in accumulatePoints: ${errorMessage} User ID: ${req.user.id}`);
return res.status(404).json({ error: errorMessage });
}

const rentalCost = req.body.rentalCost; // Assume rental cost is sent in request
if (isNaN(rentalCost) || rentalCost <= 0) {
const errorMessage = "Invalid rental cost.";
console.error(`Error in accumulatePoints: ${errorMessage} Rental cost: ${rentalCost}`);
return res.status(400).json({ error: errorMessage });
}

await user.addPoints(rentalCost);
res.status(200).json({ message: "Points added successfully" });
} catch (error) {
console.error(`Error in accumulatePoints: ${error.message}`, error);
res.status(500).json({ error: "An error occurred while accumulating points. Please try again." });
}
};

exports.redeem = async (req, res) => {
try {
const { points, rewardType } = req.body;
if (!points || points <= 0) {
const errorMessage = "Invalid points value.";
console.error(`Error in redeem: ${errorMessage} Points: ${points}`);
return res.status(400).json({ error: errorMessage });
}

const user = await User.findById(req.user.id);
if (!user) {
const errorMessage = "User not found.";
console.error(`Error in redeem: ${errorMessage} User ID: ${req.user.id}`);
return res.status(404).json({ error: errorMessage });
}

const reward = await user.redeemPoints(points, rewardType);
res.status(200).json({ message: "Reward redeemed successfully", reward });
} catch (error) {
console.error(`Error in redeem: ${error.message}`, error);
res.status(500).json({ error: "An error occurred while redeeming points. Please try again." });
}
};

exports.referral = async (req, res) => {
try {
const { referralCode } = req.body;
if (!referralCode) {
const errorMessage = "Referral code is required.";
console.error(`Error in referral: ${errorMessage} Referral Code: ${referralCode}`);
return res.status(400).json({ error: errorMessage });
}

const referrer = await User.findOne({ referralCode });
if (!referrer) {
const errorMessage = "Referral code not found.";
console.error(`Error in referral: ${errorMessage} Referral Code: ${referralCode}`);
return res.status(404).json({ error: errorMessage });
}

const user = await User.findById(req.user.id);
if (!user) {
const errorMessage = "User not found.";
console.error(`Error in referral: ${errorMessage} User ID: ${req.user.id}`);
return res.status(404).json({ error: errorMessage });
}

user.referredBy = referrer._id;
referrer.points += 50; // Give referrer points
await referrer.save();
await user.save();

res.status(200).json({ message: "Referral recorded successfully" });
} catch (error) {
console.error(`Error in referral: ${error.message}`, error);
res.status(500).json({ error: "An error occurred while processing the referral. Please try again." });
}
};

exports.pointRewards = async (req, res) => {
try {
const user = await User.findById(req.user.id).populate("rewards");
if (!user) {
const errorMessage = "User not found.";
console.error(`Error in pointRewards: ${errorMessage} User ID: ${req.user.id}`);
return res.status(404).json({ error: errorMessage });
}

res.status(200).json({ points: user.points, rewards: user.rewards });
} catch (error) {
console.error(`Error in pointRewards: ${error.message}`, error);
res.status(500).json({ error: "An error occurred while retrieving points and rewards. Please try again." });
}
};
2 changes: 2 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const adminOrderRoutes = require('./routes/rent/adminOrderRoutes');
const adminUserControlRoutes = require('./routes/rent/adminUserControlRoutes');
const analyticsRoutes = require('./routes/rent/analyticsRoutes');
const reviewRoutes = require('./routes/rent/reviewRoutes');
const rewardsRoutes = require('./routes/rent/rewardsRoutes');

const ratingRoutes = require('./routes/rent/ratingRoutes');

Expand Down Expand Up @@ -61,6 +62,7 @@ app.use('/api', adminOrderRoutes);
app.use('/api/admin', adminUserControlRoutes);
app.use('/api', analyticsRoutes);
app.use('/api', reviewRoutes);
app.use('/api', rewardsRoutes);

app.use('/api', ratingRoutes);

Expand Down
18 changes: 18 additions & 0 deletions backend/middleware/rent/loyaltyMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Middleware to apply loyalty discount
const applyLoyaltyDiscount = async (req, res, next) => {
try {
const user = await User.findById(req.user.id);
const loyaltyDiscount = {
bronze: 0,
silver: 5,
gold: 10,
platinum: 15,
};
const discount = loyaltyDiscount[user.loyaltyTier];
req.body.rentalCost = req.body.rentalCost * ((100 - discount) / 100);
next();
} catch (error) {
res.status(400).json({ error: error.message });
}
};

22 changes: 22 additions & 0 deletions backend/model/rent/reward.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require('mongoose');
const rewardSchema = new mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
pointsUsed: { type: Number, required: true },
rewardType: {
type: String,
enum: ["discount", "freeRental", "voucher"],
required: true,
},
details: { type: String },
redeemedAt: { type: Date, default: Date.now },
},
{ timestamps: true }
);

const Reward = mongoose.models.Reward || mongoose.model("Reward", rewardSchema);
module.exports = Reward;
50 changes: 50 additions & 0 deletions backend/model/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,60 @@ const userSchema = new mongoose.Schema(
quantity: { type: Number, default: 1 },
},
],
points: { type: Number, default: 0 }, // Points for rewards
referralCode: { type: String, unique: true }, // Referral code unique to each user
referredBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, // Referral tracking
loyaltyTier: {
type: String,
enum: ["bronze", "silver", "gold", "platinum"],
default: "bronze",
},
},
{ timestamps: true } // Timestamps automatically add createdAt and updatedAt
);


// Generate a referral code on user creation
userSchema.pre("save", function (next) {
if (this.isNew) {
this.referralCode = generateReferralCode(this._id);
}
next();
});

// Utility function to generate a referral code
function generateReferralCode(userId) {
return `REF${userId.toString().slice(-4).toUpperCase()}`;
}


userSchema.methods.addPoints = async function (rentalCost) {
const pointsEarned = Math.floor(rentalCost / 10); // 10% of rental cost as points
this.points += pointsEarned;

// Update loyalty tier based on accumulated points
if (this.points >= 1000) this.loyaltyTier = "platinum";
else if (this.points >= 500) this.loyaltyTier = "gold";
else if (this.points >= 200) this.loyaltyTier = "silver";

await this.save();
};

userSchema.methods.redeemPoints = async function (points, rewardType) {
if (this.points < points) throw new Error("Insufficient points");
this.points -= points;

const reward = await Reward.create({
userId: this._id,
pointsUsed: points,
rewardType,
});

await this.save();
return reward;
};


// Hash the password before saving
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next(); // Only hash if the password is modified
Expand Down
19 changes: 19 additions & 0 deletions backend/routes/rent/rewardsRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const express = require("express");

const { accumulatePoints, redeem, referral, pointRewards } = require("../../controllers/rent/RewardsController");

const router = express.Router();

// 1. Accumulate Points on Rental
router.post("/rentals/:rentalId/complete", accumulatePoints);

// 2. Redeem Points for Rewards
router.post("/redeem", redeem);

// 3. Referral Tracking and Points Award
router.post("/referral", referral);

// 4. Get User Points and Rewards
router.get("/points-rewards", pointRewards );

module.exports = router;
Loading