Skip to content

Commit

Permalink
update calc_records on archive
Browse files Browse the repository at this point in the history
  • Loading branch information
sspenst committed Oct 3, 2023
1 parent 4699346 commit 06f89c8
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 15 deletions.
32 changes: 29 additions & 3 deletions lib/initializeLocalDb.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import User from '@root/models/db/user';
import { AttemptContext } from '@root/models/schemas/playAttemptSchema';
import { PASSWORD_SALTROUNDS } from '@root/models/schemas/userSchema';
import bcrypt from 'bcryptjs';
Expand Down Expand Up @@ -339,11 +340,18 @@ export default async function initializeLocalDb() {
await Promise.all(promises);
}

// TODO: this should really have the same logic as api/publish so tests are consistent with real use cases
export async function initLevel(userId: string, name: string, obj: Partial<Level> = {}, createReviews = true) {
const ts = TimerUtil.getTs();
const id = new Types.ObjectId();
const user = await UserModel.findById(userId, 'name');
const user = await UserModel.findById<User>(userId, 'name');

if (!user) {
throw new Error(`user ${userId} not found`);
}

const slug = await generateLevelSlug(user.name, name);
const leastMoves = 20;

// based on name length create that many reviews
const lvl = await LevelModel.create({
Expand All @@ -352,14 +360,32 @@ export async function initLevel(userId: string, name: string, obj: Partial<Level
data: '40000\n12000\n05000\n67890\nABCD3',
height: 5,
isDraft: false,
leastMoves: 20,
leastMoves: leastMoves,
name: name,
slug: slug,
ts: ts - name.length * 300,
userId: userId,
userId: user._id,
width: 5,
...obj }) as Level;

await RecordModel.create({
_id: new Types.ObjectId(),
levelId: id,
moves: leastMoves,
ts: ts,
userId: user._id,
});

// await StatModel.create({
// _id: new Types.ObjectId(),
// attempts: 1,
// complete: true,
// levelId: id,
// moves: leastMoves,
// ts: ts,
// userId: user._id,
// });

if (createReviews) {
const revs = [];

Expand Down
23 changes: 20 additions & 3 deletions pages/api/archive/[id].ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Record from '@root/models/db/record';
import mongoose, { Types } from 'mongoose';
import type { NextApiResponse } from 'next';
import Discord from '../../../constants/discord';
Expand All @@ -10,7 +11,7 @@ import isCurator from '../../../helpers/isCurator';
import { logger } from '../../../helpers/logger';
import withAuth, { NextApiRequestWithAuth } from '../../../lib/withAuth';
import Level from '../../../models/db/level';
import { LevelModel } from '../../../models/mongoose';
import { LevelModel, RecordModel, UserModel } from '../../../models/mongoose';
import { queueCalcCreatorCounts } from '../internal-jobs/worker';

export default withAuth({ POST: {
Expand Down Expand Up @@ -39,8 +40,24 @@ export default withAuth({ POST: {

try {
await session.withTransaction(async () => {
// level is over 24hrs old, move to archive
const slug = await generateLevelSlug('archive', level.name, level._id.toString(), { session: session });
const [record, slug] = await Promise.all([
RecordModel.findOne<Record>({ levelId: level._id }, {}, { session: session }).sort({ ts: -1 }),
generateLevelSlug('archive', level.name, level._id.toString(), { session: session }),
]);

if (!record) {
throw new Error(`Record not found for level ${level._id}`);
}

await Promise.all([
LevelModel.findOneAndUpdate({ _id: id }, { $set: {
archivedBy: level.userId,
archivedTs: ts,
slug: slug,
userId: new Types.ObjectId(TestId.ARCHIVE),
} }, { new: true, session: session }),
UserModel.updateOne({ _id: record.userId }, { $inc: { calc_records: -1 } }, { session: session }),
]);

newLevel = await LevelModel.findOneAndUpdate({ _id: id }, { $set: {
archivedBy: level.userId,
Expand Down
11 changes: 2 additions & 9 deletions tests/pages/api/archive/archive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ beforeAll(async () => {
[userACollection, userBCollection, userALevel1] = await Promise.all([
initCollection(TestId.USER, 'user A collection'),
initCollection(TestId.USER_B, 'user B collection'),
initLevel(TestId.USER, 'user A level 1')
initLevel(TestId.USER, 'user A level 1'),
]);
});
enableFetchMocks();
Expand All @@ -50,7 +50,6 @@ describe('Testing archive', () => {
query: {
id: userALevel1._id,
},

headers: {
'content-type': 'application/json',
},
Expand Down Expand Up @@ -82,7 +81,6 @@ describe('Testing archive', () => {
query: {
id: userALevel1._id,
},

headers: {
'content-type': 'application/json',
},
Expand All @@ -97,7 +95,6 @@ describe('Testing archive', () => {
expect(response.error).toBe('Internal server error');
expect(res.status).toBe(500);
},

});
});
test('Archiving one of the levels should remove it from all collections', async () => {
Expand All @@ -111,7 +108,6 @@ describe('Testing archive', () => {
query: {
id: userALevel1._id,
},

headers: {
'content-type': 'application/json',
},
Expand All @@ -131,6 +127,7 @@ describe('Testing archive', () => {
const user = await UserModel.findById(TestId.USER);

expect(user?.calc_levels_created_count).toEqual(2);
expect(user?.calc_records).toBe(1);

const level = await LevelModel.findOne({ _id: userALevel1._id });

Expand Down Expand Up @@ -168,7 +165,6 @@ describe('Testing archive', () => {
query: {
id: new Types.ObjectId(),
},

headers: {
'content-type': 'application/json',
},
Expand All @@ -183,7 +179,6 @@ describe('Testing archive', () => {
expect(response.error).toBe('Level not found');
expect(res.status).toBe(404);
},

});
});
test('Archiving a level that does not belong to you should fail', async () => {
Expand All @@ -197,7 +192,6 @@ describe('Testing archive', () => {
query: {
id: TestId.LEVEL_3,
},

headers: {
'content-type': 'application/json',
},
Expand All @@ -212,7 +206,6 @@ describe('Testing archive', () => {
expect(response.error).toBe('Not authorized to delete this Level');
expect(res.status).toBe(401);
},

});
});
});

0 comments on commit 06f89c8

Please sign in to comment.