i am asking Every streak of 3 days we give 10 coins So if someone have 6 days in streak then again 10 coins after the first 3 days..
exports.addUserQuestionsAnswer = async (req, res) => {
try {
const { user_id, question_id, options_id } = req.body;
const questionData = await Question.findOne({
where: { id: question_id },
});
if (!questionData) {
return res.status(404).json({
success: false,
message: "Question not found",
});
}
if (questionData.is_lock_Question) {
return res.status(400).json({
success: false,
message: "Cannot submit answer. Question is locked.",
});
}
const user = await User.findByPk(user_id);
if (!user) {
return res.status(404).json({
success: false,
message: "User not found",
});
}
// Check if the answer already exists for the specific question
const existingAnswer = await Answer.findOne({
where: { user_id, question_id },
});
// Check if the user has answered any question before
const hasUserAnsweredAnyQuestion = await Answer.findOne({
where: { user_id },
});
const lastUserAnswer = await Answer.findOne({
where: { user_id },
order: [["updatedAt", "DESC"]],
});
const today = moment().utc().startOf("day");
const lastActiveDate = lastUserAnswer
? moment(lastUserAnswer.updatedAt).utc().startOf("day")
: null;
const isSameDay = lastActiveDate && today.isSame(lastActiveDate, "day");
const isNextDay =
lastActiveDate && today.diff(lastActiveDate, "days") === 1;
console.log("Today's date (UTC):", today.format("YYYY-MM-DD"));
console.log(
"User's last active date (UTC):",
lastActiveDate
? lastActiveDate.format("YYYY-MM-DD")
: "No last active date"
);
console.log("Is same day:", isSameDay);
console.log("Is next day:", isNextDay);
let message = "";
let answerData = existingAnswer;
if (existingAnswer) {
existingAnswer.options_id = options_id;
await existingAnswer.save();
message = "Answer Successfully Updated";
} else {
const newAnswer = await Answer.create({
user_id,
question_id,
options_id,
});
// Increment coins by 10 for the first answer selected, if not already done
if (!hasUserAnsweredAnyQuestion) {
user.larena_coins += 10;
}
message = "New Answer Successfully Submitted";
answerData = newAnswer;
}
// Update streak logic if not the same day
if (!isSameDay) {
user.streak = isNextDay ? user.streak + 1 : 1;
user.last_active = today.toDate();
}
// Add bonus coins every 3-day streak
if (user.streak % 3 === 0) {
user.larena_coins += 10;
}
await user.save();
return res.status(200).json({
success: true,
message: message,
answerData: answerData,
streak: user.streak,
coins: user.larena_coins,
});
} catch (error) {
console.error("Error adding/updating question:", error);
res.status(500).json({ success: false, message: "Internal server error" });
}
};