Skip to content

Commit

Permalink
update set ranked script
Browse files Browse the repository at this point in the history
  • Loading branch information
sspenst committed Sep 23, 2024
1 parent 164a672 commit d595698
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 36 deletions.
60 changes: 35 additions & 25 deletions pages/api/admin/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import AchievementCategory from '@root/constants/achievements/achievementCategory';
import AdminCommand from '@root/constants/adminCommand';
import { GameId } from '@root/constants/GameId';
import NotificationType from '@root/constants/notificationType';
import Role from '@root/constants/role';
import { ValidEnum, ValidObjectId, ValidType } from '@root/helpers/apiWrapper';
Expand All @@ -17,6 +18,38 @@ import { NextApiResponse } from 'next';
import { runEmailDigest } from '../internal-jobs/email-digest';
import { bulkQueueCalcPlayAttempts, processQueueMessages } from '../internal-jobs/worker';

export async function switchIsRanked(levelId: Types.ObjectId, gameId: GameId, isRanked?: boolean): Promise<boolean> {
const session = await mongoose.startSession();

try {
await session.withTransaction(async () => {
const level = await LevelModel.findById<Level>(levelId, { isRanked: 1 }, { session: session });

if (!level) {
throw new Error('Level not found');
}

const newIsRanked = isRanked !== undefined ? isRanked : !level.isRanked;

await LevelModel.updateOne({ _id: levelId }, { isRanked: newIsRanked }, { session: session });

const stats = await StatModel.find({ levelId: levelId, complete: true }, 'userId', { session: session });
const userIds = stats.map(stat => stat.userId);

await UserConfigModel.updateMany({ userId: { $in: userIds }, gameId: gameId }, { $inc: { calcRankedSolves: newIsRanked ? 1 : -1 } }, { session: session });
});

session.endSession();
} catch (err) {
logger.error(err);
session.endSession();

return false;
}

return true;
}

interface AdminBodyProps {
targetId: string;
command: AdminCommand;
Expand Down Expand Up @@ -97,32 +130,9 @@ export default withAuth({ POST: {
}

case AdminCommand.SwitchIsRanked: {
const levelId = new Types.ObjectId(targetId as string);
const session = await mongoose.startSession();

try {
await session.withTransaction(async () => {
const level = await LevelModel.findById<Level>(levelId, { isRanked: 1 }, { session: session });

if (!level) {
throw new Error('Level not found');
}

const newIsRanked = !level.isRanked;

await LevelModel.updateOne({ _id: levelId }, { isRanked: newIsRanked }, { session: session });

const stats = await StatModel.find({ levelId: levelId, complete: true }, 'userId', { session: session });
const userIds = stats.map(stat => stat.userId);

await UserConfigModel.updateMany({ userId: { $in: userIds }, gameId: req.gameId }, { $inc: { calcRankedSolves: newIsRanked ? 1 : -1 } }, { session: session });
});

session.endSession();
} catch (err) {
logger.error(err);
session.endSession();
const success = await switchIsRanked(new Types.ObjectId(targetId as string), req.gameId);

if (!success) {
return res.status(500).json({ error: 'Error switching isRanked' });
}

Expand Down
19 changes: 8 additions & 11 deletions server/scripts/set-is-ranked.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// ts-node -r tsconfig-paths/register --files server/scripts/set-is-ranked.ts

import Level from '@root/models/db/level';
import { LevelModel } from '@root/models/mongoose';
import { GameId } from '@root/constants/GameId';
import { switchIsRanked } from '@root/pages/api/admin';
import cliProgress from 'cli-progress';
import dotenv from 'dotenv';
import * as fs from 'fs';
import { Types } from 'mongoose';
import dbConnect from '../../lib/dbConnect';

'use strict';
Expand All @@ -14,7 +15,7 @@ console.log('loaded env vars');
const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);

async function setIsRanked() {
const filePath = './server/scripts/ranked_level_ids';
const filePath = './server/scripts/ranked-level-ids';

fs.readFile(filePath, 'utf8', async (err: NodeJS.ErrnoException | null, data: string) => {
if (err) {
Expand All @@ -23,16 +24,12 @@ async function setIsRanked() {
process.exit(0);
}

const rankedLevelIds = new Set(data.split('\n'));
const levelIds = data.split('\n');

const totalLevels = await LevelModel.countDocuments();
progressBar.start(levelIds.length, 0);

progressBar.start(totalLevels, 0);

for await (const level of LevelModel.find<Level>()) {
const isRanked = rankedLevelIds.has(level._id.toString());

await LevelModel.updateOne({ _id: level._id }, { $set: { isRanked } });
for (const levelId of levelIds) {
await switchIsRanked(new Types.ObjectId(levelId as string), GameId.PATHOLOGY, true);
progressBar.increment();
}

Expand Down

0 comments on commit d595698

Please sign in to comment.