Commit 1a740823 authored by shahriar's avatar shahriar
Browse files

return 404 if user not found

parent a128cea4
...@@ -37,8 +37,6 @@ export class LotteryController { ...@@ -37,8 +37,6 @@ export class LotteryController {
@ApiTags('Lottery/weekly') @ApiTags('Lottery/weekly')
@Post('weekly/change-status') @Post('weekly/change-status')
async changeStatus(@Body() changeStatusDto: ChangeStatusDto) { async changeStatus(@Body() changeStatusDto: ChangeStatusDto) {
console.log('here');
return await this.lotteryService.changeStatus(changeStatusDto) return await this.lotteryService.changeStatus(changeStatusDto)
} }
} }
import { HttpException, Injectable } from '@nestjs/common' import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose' import { InjectModel } from '@nestjs/mongoose';
import { Model, ObjectId, Types } from 'mongoose' import { Model, Types } from 'mongoose';
import { of } from 'rxjs' import { CommentDocument } from 'src/instagram/models/comment.schema';
import { CommentDocument } from 'src/instagram/models/comment.schema' import { FollowerDocument } from 'src/instagram/models/follower.schema';
import { FollowerDocument } from 'src/instagram/models/follower.schema' import { LikeDocument } from 'src/instagram/models/like.schema';
import { LikeDocument } from 'src/instagram/models/like.schema' import { LottoryResultDocument } from 'src/instagram/models/LottoryResult.schema';
import { LottoryResultDocument } from 'src/instagram/models/LottoryResult.schema' import { UserDocument } from 'src/instagram/models/user.schema';
import { UserDocument } from 'src/instagram/models/user.schema' import addToStoryData from '../instagram/values/add-to-story-data';
import addToStoryData from '../instagram/values/add-to-story-data' import { ChangeStatusDto } from './dto/change-status-dto';
import { ChangeStatusDto } from './dto/change-status-dto' import { ScoreService } from './score.service';
import { ScoreService } from './score.service' import { StoryMentionDocument } from 'src/instagram/models/storyMention.schema';
import * as _ from "lodash"
import { StoryMentionDocument } from 'src/instagram/models/storyMention.schema'
@Injectable() @Injectable()
export class LotteryService { export class LotteryService {
constructor( constructor(
private scoreService: ScoreService, private scoreService: ScoreService,
@InjectModel('User') @InjectModel('User')
private userModel: Model<UserDocument>, private userModel: Model<UserDocument>,
@InjectModel('Follower') @InjectModel('Follower')
private followerModel: Model<FollowerDocument>, private followerModel: Model<FollowerDocument>,
@InjectModel('Like') @InjectModel('Like')
private likeModel: Model<LikeDocument>, private likeModel: Model<LikeDocument>,
@InjectModel('Comment') @InjectModel('Comment')
private commentModel: Model<CommentDocument>, private commentModel: Model<CommentDocument>,
@InjectModel('LottryResult') @InjectModel('LottryResult')
private lotteryResultModel: Model<LottoryResultDocument>, private lotteryResultModel: Model<LottoryResultDocument>,
@InjectModel('StoryMention') @InjectModel('StoryMention')
private storyMentionModel: Model<StoryMentionDocument>, private storyMentionModel: Model<StoryMentionDocument>,
) { } ) {}
async getUserScore(username: string, profileUsername: string, postArray: string[]) { async getUserScore(
let foundUser = await this.userModel.findOne({ username }) username: string,
let likesScore = await this.scoreService.getUserLikesScore(foundUser._id, profileUsername, postArray) profileUsername: string,
let commentScore = await this.scoreService.getUserCommentsScore(foundUser._id, profileUsername, postArray) postArray: string[],
let addToStoryScore = await this.scoreService.getTagsScore(username) ) {
const foundUser = await this.userModel.findOne({ username });
const likesScore = await this.scoreService.getUserLikesScore(
foundUser._id,
profileUsername,
postArray,
);
const commentScore = await this.scoreService.getUserCommentsScore(
foundUser._id,
profileUsername,
postArray,
);
const addToStoryScore = await this.scoreService.getTagsScore(username);
return { likesScore, commentScore, addToStoryScore, totalScore: likesScore + commentScore + addToStoryScore } return {
likesScore,
commentScore,
addToStoryScore,
totalScore: likesScore + commentScore + addToStoryScore,
};
}
async addResultsToDB(profileUsername: string, postArray: string[]) {
const foundUser_idsList = await this.getUserList();
let index = 0;
for await (const user_id of foundUser_idsList) {
const userScore = await this.scoreService.calculateUserScore(
user_id.toString(),
profileUsername,
postArray,
);
if (userScore > 0) {
console.log(userScore, user_id.toString());
}
const foundUserLastCount = await this.lotteryResultModel.countDocuments({
user_id: new Types.ObjectId(user_id),
});
const newChances = userScore - foundUserLastCount;
for (let u = 0; u < newChances; u++) {
await this.lotteryResultModel.create({
_id: new Types.ObjectId(),
index: await this.codeGenerator(),
user_id: new Types.ObjectId(user_id),
status: 'valid',
});
}
console.log(`${index}/${foundUser_idsList.length}`);
index++;
} }
async addResultsToDB(profileUsername: string, postArray: string[]) { console.log('end');
let foundUser_idsList = await this.getUserList() return 'successfull';
let index = 0 }
for await (const user_id of foundUser_idsList) {
let userScore = await this.scoreService.calculateUserScore(user_id.toString(), profileUsername, postArray) async getResultDb() {
if (userScore > 0) { return await this.lotteryResultModel
console.log(userScore, user_id.toString()); .find({ status: 'online' })
} .populate('user_id', { username: 1 }, 'User')
let foundUserLastCount = await this.lotteryResultModel.countDocuments({ .sort({ status: 1 })
user_id: new Types.ObjectId(user_id) .select({ username: 1, index: 1, status: 1 });
}) }
let newChances = userScore - foundUserLastCount
for (let u = 0; u < newChances; u++) { async changeStatus(changeStatus: ChangeStatusDto) {
await this.lotteryResultModel.create({ const foundUser = await this.userModel.findOne({
_id: new Types.ObjectId(), username: changeStatus.username,
index: await this.codeGenerator(), });
user_id: new Types.ObjectId(user_id), if (!foundUser) {
status: 'valid', throw new NotFoundException(
}) `user with username : ${changeStatus.username} not found`,
} );
console.log(`${index}/${foundUser_idsList.length}`)
index++
}
console.log('end')
return 'successfull'
} }
async getResultDb() { const foundLottryResults = await this.lotteryResultModel.find({
return await this.lotteryResultModel user_id: foundUser._id,
.find({ status: "online" }).populate("user_id", { "username": 1 }, "User").sort({ "status": 1 }) });
.select({ username: 1, index: 1, status: 1 }) for await (const result of foundLottryResults) {
result.status = 'online';
await result.save();
} }
await this.userModel.findOneAndUpdate(
{ username: changeStatus.username },
{ mobile: changeStatus.mobile },
);
return {
message: 'status changed to online successfully',
};
}
async changeStatus(changeStatus: ChangeStatusDto) { async codeGenerator() {
let foundUser = await this.userModel.findOne({ username: changeStatus.username }) const lastIndex = await this.lotteryResultModel
let foundLottryResults = await this.lotteryResultModel.find({ .find()
user_id: foundUser._id .sort({ createdAt: -1 });
})
for await (const result of foundLottryResults) {
result.status = "online"
await result.save()
}
await this.userModel.findOneAndUpdate({ username: changeStatus.username }, { mobile: changeStatus.mobile })
return {
message: "status changed to online successfully"
}
}
async codeGenerator() {
let lastIndex = await this.lotteryResultModel.find().sort({ createdAt: -1 })
if (lastIndex[0]) { if (lastIndex[0]) {
let lastChanceIndex = lastIndex[0].index const lastChanceIndex = lastIndex[0].index;
let code = lastChanceIndex.split('LT_')[1] const code = lastChanceIndex.split('LT_')[1];
let res = `LT_${(Number(code) + 1)}` const res = `LT_${Number(code) + 1}`;
return res return res;
} } else {
else { return `LT_${1000}`;
return `LT_${1000}`
}
} }
}
async getUserList() { async getUserList() {
let foundUsernameInComment = await this.commentModel.distinct('user_id') const foundUsernameInComment = await this.commentModel.distinct('user_id');
let foundUsernameInLike = await this.likeModel.distinct('user_id') const foundUsernameInLike = await this.likeModel.distinct('user_id');
let foundUsernamesInStoryData = new Array<any>() const foundUsernamesInStoryData = new Array<any>();
for await (const iterator of addToStoryData.addToStoryData) { for await (const iterator of addToStoryData.addToStoryData) {
let foundUser = await this.userModel.findOne({ username: iterator.username }) const foundUser = await this.userModel.findOne({
if (!foundUser) { username: iterator.username,
let createdUser = await this.userModel.create({ });
_id: new Types.ObjectId(), if (!foundUser) {
username: iterator.username const createdUser = await this.userModel.create({
}) _id: new Types.ObjectId(),
foundUsernamesInStoryData.push(createdUser._id.toString()) username: iterator.username,
} });
else { foundUsernamesInStoryData.push(createdUser._id.toString());
foundUsernamesInStoryData.push(foundUser._id.toString()) } else {
} foundUsernamesInStoryData.push(foundUser._id.toString());
} }
let userListTemp = foundUsernameInComment.concat(foundUsernameInLike)
let array = new Array<string>()
userListTemp.forEach(user => {
array.push(user.toString())
})
let userListTemp2 = array.concat(foundUsernamesInStoryData)
let userList = [...new Set(userListTemp2)]
return userList
} }
const userListTemp = foundUsernameInComment.concat(foundUsernameInLike);
const array = new Array<string>();
userListTemp.forEach((user) => {
array.push(user.toString());
});
const userListTemp2 = array.concat(foundUsernamesInStoryData);
const userList = [...new Set(userListTemp2)];
return userList;
}
} }
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment