Skip to content

Commit

Permalink
Merge pull request #2211 from Real-Dev-Squad/develop
Browse files Browse the repository at this point in the history
Dev to Main Sync
  • Loading branch information
iamitprakash authored Oct 13, 2024
2 parents 722b0ea + 37aea6e commit 46f5d4f
Show file tree
Hide file tree
Showing 3 changed files with 257 additions and 21 deletions.
6 changes: 5 additions & 1 deletion services/dataAccessLayer.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,13 @@ const retrieveUsers = async ({
} else if (discordId !== null) {
result = await userQuery.fetchUser({ discordId });
return levelSpecificAccess(result, level, role);
} else {
} else if (userdata) {
const result = await userQuery.fetchUser({ userId: userdata.id });
return levelSpecificAccess(result.user, level, role);
} else {
return {
userExists: false,
};
}
};

Expand Down
246 changes: 246 additions & 0 deletions test/unit/models/discordactions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ const {
groupUpdateLastJoinDate,
updateIdleUsersOnDiscord,
updateIdle7dUsersOnDiscord,
updateUsersWith31DaysPlusOnboarding,
updateGroupRole,
removeMemberGroup,
getGroupRoleByName,
getGroupRolesForUser,
} = require("../../../models/discordactions");
const {
groupData,
Expand All @@ -41,6 +46,7 @@ const {
memberGroupData,
groupIdle,
groupIdle7d,
groupOnboarding31dPlus,
} = require("../../fixtures/discordactions/discordactions");
const cleanDb = require("../../utils/cleanDb");
const { userPhotoVerificationData } = require("../../fixtures/user/photo-verification");
Expand All @@ -54,6 +60,7 @@ const { createProgressDocument } = require("../../../models/progresses");
const { stubbedModelTaskProgressData } = require("../../fixtures/progress/progresses");
const { convertDaysToMilliseconds } = require("../../../utils/time");
const { generateUserStatusData } = require("../../fixtures/userStatus/userStatus");
const { userState } = require("../../../constants/userStatus");

chai.should();

Expand Down Expand Up @@ -993,4 +1000,243 @@ describe("discordactions", function () {
expect(res.totalArchivedUsers).to.be.equal(1);
});
});

describe("updateUsersWith31DaysPlusOnboarding", function () {
let fetchStub;

beforeEach(async function () {
fetchStub = sinon.stub(global, "fetch");

userData[0] = {
...userData[0],
discordId: "2131234453456545656765767876",
discordJoinedAt: "2023-07-31T16:57:53.894000+00:00",
roles: { archived: false, in_discord: true },
};
userData[1] = {
...userData[1],
discordId: "12345678909867666",
discordJoinedAt: "2023-07-31T16:57:53.894000+00:00",
roles: { archived: false, in_discord: true },
};
userData[2] = {
...userData[2],
discordId: "1234567",
discordJoinedAt: "2023-07-31T16:57:53.894000+00:00",
roles: { archived: false, in_discord: true },
};

const userId0 = await addUser(userData[0]);
const userId1 = await addUser(userData[1]);
const userId2 = await addUser(userData[2]);

await userStatusModel.updateUserStatus(
userId0,
generateUserStatusData(userState.ONBOARDING, 1690829925336, 1690829925336)
);
await userStatusModel.updateUserStatus(
userId1,
generateUserStatusData(userState.ONBOARDING, 1690829925336, 1690829925336)
);
await userStatusModel.updateUserStatus(
userId2,
generateUserStatusData(userState.IDLE, 1690829925336, 1690829925336)
);

const addRolesPromises = [discordRoleModel.add(groupOnboarding31dPlus)];
await Promise.all(addRolesPromises);

getDiscordMembers[1] = {
...getDiscordMembers[1],
roles: ["9876543210"],
};
getDiscordMembers[3] = {
...getDiscordMembers[3],
roles: ["9876543210", "11334336"],
};
getDiscordMembers[4] = {
...getDiscordMembers[4],
roles: ["9876543210", "11334336"],
};

fetchStub.returns(
Promise.resolve({
status: 200,
json: () => Promise.resolve(getDiscordMembers),
})
);
});

afterEach(async function () {
sinon.restore();
await cleanDb();
});

it("apply, or remove grouponboarding31D", async function () {
const res = await updateUsersWith31DaysPlusOnboarding();

expect(res.usersAlreadyHavingOnboaring31DaysRole.count).to.be.equal(2);
expect(res.totalOnboardingUsers31DaysCompleted.count).to.be.equal(2);
expect(res.totalOnboarding31dPlusRoleApplied.count).to.be.equal(1);
expect(res.totalOnboarding31dPlusRoleRemoved.count).to.be.equal(1);
});

it("should throw an error if Database error occurs", async function () {
fetchStub.rejects(new Error("Database error"));

try {
await updateUsersWith31DaysPlusOnboarding();
} catch (err) {
expect(err).to.be.an.instanceOf(Error);
expect(err.message).to.equal("Error while fetching onboarding users who have completed 31 days");
}
});
});

describe("removeMemberGroup", function () {
let deleteStub;

beforeEach(async function () {
await discordRoleModel.add({ roleid: "1234566777777", rolename: "xyz" });
await memberRoleModel.add({ roleid: "1234566777777", userid: "2131234453456545656765767876" });

deleteStub = sinon.stub();
sinon.stub(memberRoleModel, "doc").returns({
delete: deleteStub.resolves(),
});
});

afterEach(async function () {
sinon.restore();
await cleanDb();
});

it("should remove role from user", async function () {
const res = await removeMemberGroup("1234566777777", "2131234453456545656765767876");

expect(res.roleId).to.be.equal("1234566777777");
expect(res.wasSuccess).to.be.equal(true);
});

it("should return wasSuccess as false if role does not exist", async function () {
const res = await removeMemberGroup("123", "2131234453456545656765767876");

expect(res.roleId).to.be.equal("123");
expect(res.wasSuccess).to.be.equal(false);
});

it("return error if something goes while deleting the role", async function () {
deleteStub.rejects(new Error("Database error"));

try {
await removeMemberGroup("1243", "2131234453456545656765767876");
} catch (err) {
expect(err).to.be.an.instanceOf(Error);
expect(err.message).to.equal("Database error");
}
});
});

describe("getGroupRolesForUser", function () {
let whereStub;

beforeEach(async function () {
whereStub = sinon.stub(memberRoleModel, "where").resolves();

await discordRoleModel.add({ roleid: "1234566777777", rolename: "xyz" });
await memberRoleModel.add({ roleid: "1234566777777", userid: "2131234453456545656765767876" });
});

afterEach(async function () {
sinon.restore();
await cleanDb();
});

it("should return group role for a given user", async function () {
const res = await getGroupRolesForUser("2131234453456545656765767876");

expect(res.userId).to.be.equal("2131234453456545656765767876");
expect(res.groups[0].roleId).to.be.equal("1234566777777");
});

it("should throw error if something goes wrong while fetching the roles", async function () {
whereStub.rejects(new Error("Something went wrong while fetching"));

try {
await getGroupRolesForUser("2131234453456545656765767876");
} catch (err) {
expect(err).to.be.an.instanceOf(Error);
expect(err.message).to.equal("Something went wrong while fetching");
}
});
});

describe("getGroupRoleByName", function () {
let whereStub;

beforeEach(async function () {
await discordRoleModel.add({ roleid: "1234566777777", rolename: "xyz" });
whereStub = sinon.stub(discordRoleModel, "where").resolves();
});

afterEach(async function () {
sinon.restore();
await cleanDb();
});

it("should return the role, if given the name", async function () {
const res = await getGroupRoleByName("xyz");

expect(res.data).to.be.an.instanceOf(Object);
});

it("should thrown an error, if something goes wrong", async function () {
whereStub.rejects(new Error("Database Error"));

try {
await getGroupRoleByName("xyz");
} catch (err) {
expect(err).to.be.an.instanceOf(Error);
expect(err.message).to.equal("Database error");
}
});
});

describe("updateGroupRole", function () {
let setStub;
let addStub;

beforeEach(async function () {
addStub = sinon.stub(discordRoleModel, "add");

addStub.resolves({ id: "test-id" });

setStub = sinon.stub();
sinon.stub(discordRoleModel, "where").returns({
set: setStub.resolves(),
});
});

afterEach(async function () {
sinon.restore();
await cleanDb();
});

it("should update the group role data", async function () {
const res = await updateGroupRole({ roleid: "2312", rolename: "fmk" }, "test-id");

expect(res.data).to.be.an.instanceOf(Object);
});

it("should throw an error if something goes wrong", async function () {
setStub.rejects(new Error("Database error"));

try {
await updateGroupRole({ roleid: "2312", rolename: "fmk" }, "test-id");
} catch (err) {
expect(err).to.be.an.instanceOf(Error);
expect(err.message).to.equal("Database error");
}
});
});
});
26 changes: 6 additions & 20 deletions utils/users.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const { fetchUser } = require("../models/users");
const firestore = require("../utils/firestore");
const userModel = firestore.collection("users");
const { months, discordNicknameLength } = require("../constants/users");
Expand All @@ -21,8 +20,7 @@ const getUserId = async (username) => {
const {
userExists,
user: { id },
} = await fetchUser({ username });

} = await dataAccessLayer.retrieveUsers({ username });
return userExists ? id : false;
} catch (error) {
logger.error("Something went wrong", error);
Expand All @@ -37,10 +35,8 @@ const getUserId = async (username) => {
*/
const getUsername = async (userId) => {
try {
const {
user: { username },
} = await fetchUser({ userId });
return username;
const { userExists, user } = await dataAccessLayer.retrieveUsers({ id: userId });
return userExists ? user.username : undefined;
} catch (error) {
logger.error("Something went wrong", error);
throw error;
Expand All @@ -58,7 +54,7 @@ const getFullName = async (userId) => {
const {
// eslint-disable-next-line camelcase
user: { first_name, last_name },
} = await fetchUser({ userId });
} = await dataAccessLayer.retrieveUsers({ id: userId });
// eslint-disable-next-line camelcase
return { first_name, last_name };
} catch (error) {
Expand All @@ -76,7 +72,7 @@ const getUsernameElseUndefined = async (userId) => {
try {
const {
user: { username },
} = await fetchUser({ userId });
} = await dataAccessLayer.retrieveUsers({ id: userId });
return username;
} catch (error) {
logger.error("Something went wrong", error);
Expand All @@ -92,17 +88,7 @@ const getUsernameElseUndefined = async (userId) => {
*/

const getUserIdElseUndefined = async (username) => {
try {
const {
userExists,
user: { id },
} = await fetchUser({ username });

return userExists ? id : false;
} catch (error) {
logger.error("Something went wrong", error);
return undefined;
}
return await getUserId(username);
};

/**
Expand Down

0 comments on commit 46f5d4f

Please sign in to comment.