Skip to content

Commit

Permalink
making actionItemCategory name unique for a given Organization
Browse files Browse the repository at this point in the history
  • Loading branch information
meetulr committed Jan 22, 2024
1 parent 9298ace commit a74d184
Show file tree
Hide file tree
Showing 30 changed files with 258 additions and 163 deletions.
3 changes: 2 additions & 1 deletion codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ const config: CodegenConfig = {
mappers: {
ActionItem: "../models/ActionItem#InterfaceActionItem",

ActionItemCategory: "../models/ActionItemCategory#InterfaceActionItemCategory",
ActionItemCategory:
"../models/ActionItemCategory#InterfaceActionItemCategory",

CheckIn: "../models/CheckIn#InterfaceCheckIn",

Expand Down
3 changes: 2 additions & 1 deletion locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"user.notFound": "User not found",
"user.alreadyMember": "User is already a member",
"user.profileImage.notFound": "User profile image not found",
"actionItemCategory.notFound": "ActionItemCategory not found",
"actionItemCategory.notFound": "Action Item Category not found",
"actionItemCategory.alreadyExists": "Action Item Category already exists",
"actionItem.notFound": "Action Item not found",
"advertisement.notFound": "Advertisement not found",
"event.notFound": "Event not found",
Expand Down
3 changes: 2 additions & 1 deletion locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"user.notFound": "Utilisateur introuvable",
"user.alreadyMember": "L'utilisateur est déjà membre",
"user.profileImage.notFound": "Image du profil utilisateur introuvable",
"actionItemCategory.notFound": "Catégorie non trouvée",
"actionItemCategory.notFound": "Catégorie d’élément d’action introuvable",
"actionItemCategory.alreadyExists": "La catégorie d’élément d’action existe déjà",
"actionItem.notFound": "Élément d\\’action non trouvé",
"event.notFound": "Événement non trouvé",
"organization.notFound": "Organisation introuvable",
Expand Down
1 change: 1 addition & 0 deletions locales/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"user.alreadyMember": "उपयोगकर्ता पहले से ही एक सदस्य है",
"user.profileImage.notFound": "उपयोगकर्ता प्रोफ़ाइल छवि नहीं मिली",
"actionItemCategory.notFound": "श्रेणी नहीं मिली",
"actionItemCategory.alreadyExists": "यह श्रेणी पहले से मौजूद है",
"actionItem.notFound": "कार्रवाई का मद नहीं मिला",
"advertisement.notFound": "विज्ञापन नहीं मिला",
"event.notFound": "घटना नहीं मिली",
Expand Down
3 changes: 2 additions & 1 deletion locales/sp.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"user.notFound": "Usuario no encontrado",
"user.alreadyMember": "El usuario ya es miembro",
"user.profileImage.notFound": "No se encontró la imagen de perfil de usuario",
"actionItemCategory.notFound": "Categoría no encontrada",
"actionItemCategory.notFound": "No se encontró la categoría de elemento de acción",
"actionItemCategory.alreadyExists": "Ya existe una categoría de elemento de acción",
"actionItem.notFound": "Elemento de acción no encontrado",
"event.notFound": "Evento no encontrado",
"organization.notFound": "Organización no encontrada",
Expand Down
3 changes: 2 additions & 1 deletion locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"user.notFound": "找不到用戶",
"user.alreadyMember": "用戶已經是會員",
"user.profileImage.notFound": "未找到用戶個人資料圖像",
"actionItemCategory.notFound": "找不到类别",
"actionItemCategory.notFound": "未找到措施项类别",
"actionItemCategory.alreadyExists": "措施项类别已存在",
"actionItem.notFound": "找不到操作项",
"event.notFound": "未找到事件",
"organization.notFound": "未找到組織",
Expand Down
7 changes: 7 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ export const ACTION_ITEM_CATEGORY_NOT_FOUND_ERROR = {
PARAM: "actionItemCategory",
};

export const ACTION_ITEM_CATEGORY_ALREADY_EXISTS = {
DESC: "Action Item Category already exists",
CODE: "actionItemCategory.alreadyExists",
MESSAGE: "actionItemCategory.alreadyExists",
PARAM: "actionItemCategory",
};

export const CHAT_NOT_FOUND_ERROR = {
DESC: "Chat not found",
CODE: "chat.notFound",
Expand Down
15 changes: 11 additions & 4 deletions src/models/ActionItemCategory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,17 @@ const actionItemCategorySchema = new Schema(
{ timestamps: true }
);

actionItemCategorySchema.index(
{ organizationId: 1, name: 1 },
{ unique: true }
);

const actionItemCategoryModel = (): Model<InterfaceActionItemCategory> =>
model<InterfaceActionItemCategory>("ActionItemCategory", actionItemCategorySchema);
model<InterfaceActionItemCategory>(
"ActionItemCategory",
actionItemCategorySchema
);

// This syntax is needed to prevent Mongoose OverwriteModelError while running tests.
export const ActionItemCategory = (models.ActionItemCategory || actionItemCategoryModel()) as ReturnType<
typeof actionItemCategoryModel
>;
export const ActionItemCategory = (models.ActionItemCategory ||
actionItemCategoryModel()) as ReturnType<typeof actionItemCategoryModel>;
11 changes: 6 additions & 5 deletions src/resolvers/ActionItem/actionItemCategory.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { ActionItemResolvers } from "../../types/generatedGraphQLTypes";
import { ActionItemCategory } from "../../models";

export const actionItemCategory: ActionItemResolvers["actionItemCategory"] = async (parent) => {
return ActionItemCategory.findOne({
_id: parent.actionItemCategoryId,
}).lean();
};
export const actionItemCategory: ActionItemResolvers["actionItemCategory"] =
async (parent) => {
return ActionItemCategory.findOne({
_id: parent.actionItemCategoryId,
}).lean();
};
4 changes: 3 additions & 1 deletion src/resolvers/ActionItemCategory/creator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { ActionItemCategoryResolvers } from "../../types/generatedGraphQLTypes";
import { User } from "../../models";

export const creator: ActionItemCategoryResolvers["creator"] = async (parent) => {
export const creator: ActionItemCategoryResolvers["creator"] = async (
parent
) => {
return User.findOne({
_id: parent.creatorId,
}).lean();
Expand Down
4 changes: 3 additions & 1 deletion src/resolvers/ActionItemCategory/organization.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { ActionItemCategoryResolvers } from "../../types/generatedGraphQLTypes";
import { Organization } from "../../models";

export const organization: ActionItemCategoryResolvers["organization"] = async (parent) => {
export const organization: ActionItemCategoryResolvers["organization"] = async (
parent
) => {
return Organization.findOne({
_id: parent.organizationId,
}).lean();
Expand Down
2 changes: 1 addition & 1 deletion src/resolvers/Event/actionItems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ import type { EventResolvers } from "../../types/generatedGraphQLTypes";
*/
export const actionItems: EventResolvers["actionItems"] = async (parent) => {
return await ActionItem.find({
eventId: parent._id
eventId: parent._id,
}).lean();
};
124 changes: 70 additions & 54 deletions src/resolvers/Mutation/createActionItemCategory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { errors, requestContext } from "../../libraries";
import {
USER_NOT_FOUND_ERROR,
ORGANIZATION_NOT_FOUND_ERROR,
ACTION_ITEM_CATEGORY_ALREADY_EXISTS,
} from "../../constants";

import { adminCheck } from "../../utilities";
Expand All @@ -22,57 +23,72 @@ import { cacheOrganizations } from "../../services/OrganizationCache/cacheOrgani
* @returns Created ActionItemCategory
*/

export const createActionItemCategory: MutationResolvers["createActionItemCategory"] = async (
_parent,
args,
context
) => {
const currentUser = await User.findOne({
_id: context.userId,
});

// Checks whether currentUser with _id == context.userId exists.
if (currentUser === null) {
throw new errors.NotFoundError(
requestContext.translate(USER_NOT_FOUND_ERROR.MESSAGE),
USER_NOT_FOUND_ERROR.CODE,
USER_NOT_FOUND_ERROR.PARAM
);
}

let organization;

const organizationFoundInCache = await findOrganizationsInCache([args.organizationId]);

organization = organizationFoundInCache[0];

if (organizationFoundInCache[0] == null) {
organization = await Organization.findOne({
_id: args.organizationId,
}).lean();

await cacheOrganizations([organization!]);
}

// Checks whether the organization with _id === args.organizationId exists.
if (!organization) {
throw new errors.NotFoundError(
requestContext.translate(ORGANIZATION_NOT_FOUND_ERROR.MESSAGE),
ORGANIZATION_NOT_FOUND_ERROR.CODE,
ORGANIZATION_NOT_FOUND_ERROR.PARAM
);
}

// Checks whether the user is authorized to perform the operation
await adminCheck(context.userId, organization);

// Creates new actionItemCategory.
const createdActionItemCategory = await ActionItemCategory.create({
name: args.name,
organizationId: args.organizationId,
creatorId: context.userId,
});

// Returns created actionItemCategory.
return createdActionItemCategory.toObject();
};
export const createActionItemCategory: MutationResolvers["createActionItemCategory"] =
async (_parent, args, context) => {
const currentUser = await User.findOne({
_id: context.userId,
});

// Checks whether currentUser with _id == context.userId exists.
if (currentUser === null) {
throw new errors.NotFoundError(
requestContext.translate(USER_NOT_FOUND_ERROR.MESSAGE),
USER_NOT_FOUND_ERROR.CODE,
USER_NOT_FOUND_ERROR.PARAM
);
}

let organization;

const organizationFoundInCache = await findOrganizationsInCache([
args.organizationId,
]);

organization = organizationFoundInCache[0];

if (organizationFoundInCache[0] == null) {
organization = await Organization.findOne({
_id: args.organizationId,
}).lean();

await cacheOrganizations([organization!]);
}

// Checks whether

// Checks whether the organization with _id === args.organizationId exists.
if (!organization) {
throw new errors.NotFoundError(
requestContext.translate(ORGANIZATION_NOT_FOUND_ERROR.MESSAGE),
ORGANIZATION_NOT_FOUND_ERROR.CODE,
ORGANIZATION_NOT_FOUND_ERROR.PARAM
);
}

// Checks whether the user is authorized to perform the operation
await adminCheck(context.userId, organization);

// Checks whether an actionItemCategory with given name already exists for the current organization
const existingActionItemCategory = await ActionItemCategory.findOne({
organizationId: organization?._id,
name: args.name,
});

if (existingActionItemCategory) {
throw new errors.ConflictError(
requestContext.translate(ACTION_ITEM_CATEGORY_ALREADY_EXISTS.MESSAGE),
ACTION_ITEM_CATEGORY_ALREADY_EXISTS.CODE,
ACTION_ITEM_CATEGORY_ALREADY_EXISTS.PARAM
);
}

// Creates new actionItemCategory.
const createdActionItemCategory = await ActionItemCategory.create({
name: args.name,
organizationId: args.organizationId,
creatorId: context.userId,
});

// Returns created actionItemCategory.
return createdActionItemCategory.toObject();
};
8 changes: 4 additions & 4 deletions src/resolvers/Mutation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { createPlugin } from "./createPlugin";
import { createAdvertisement } from "./createAdvertisement";
import { createPost } from "./createPost";
import { createSampleOrganization } from "./createSampleOrganization";
import { createCategory } from "./createActionItemCategory";
import { createActionItemCategory } from "./createActionItemCategory";
import { createUserTag } from "./createUserTag";
import { deleteDonationById } from "./deleteDonationById";
import { forgotPassword } from "./forgotPassword";
Expand Down Expand Up @@ -78,7 +78,7 @@ import { unlikeComment } from "./unlikeComment";
import { unlikePost } from "./unlikePost";
import { unregisterForEventByUser } from "./unregisterForEventByUser";
import { updateActionItem } from "./updateActionItem";
import { updateCategory } from "./updateActionItemCategory";
import { updateActionItemCategory } from "./updateActionItemCategory";
import { updateEvent } from "./updateEvent";
import { updateLanguage } from "./updateLanguage";
import { updateOrganization } from "./updateOrganization";
Expand Down Expand Up @@ -124,7 +124,7 @@ export const Mutation: MutationResolvers = {
createPlugin,
createPost,
createSampleOrganization,
createCategory,
createActionItemCategory,
createUserTag,
deleteDonationById,
deleteAdvertisementById,
Expand Down Expand Up @@ -172,7 +172,7 @@ export const Mutation: MutationResolvers = {
unlikePost,
unregisterForEventByUser,
updateActionItem,
updateCategory,
updateActionItemCategory,
updateEvent,
updateLanguage,
updateOrganization,
Expand Down
4 changes: 3 additions & 1 deletion src/resolvers/Mutation/removeActionItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ export const removeActionItem: MutationResolvers["removeActionItem"] = async (
const currentUserIsOrgAdmin = currentUser.adminFor.some(
(ogranizationId) =>
ogranizationId === actionItem.actionItemCategoryId.organizationId ||
Types.ObjectId(ogranizationId).equals(actionItem.actionItemCategoryId.organizationId)
Types.ObjectId(ogranizationId).equals(
actionItem.actionItemCategoryId.organizationId
)
);

let currentUserIsEventAdmin = false;
Expand Down
12 changes: 9 additions & 3 deletions src/resolvers/Mutation/removeOrganization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,17 @@ export const removeOrganization: MutationResolvers["removeOrganization"] =
);

// Get the ids of all ActionItemCategories associated with the organization
const actionItemCategories = await ActionItemCategory.find({ organizationId: organization?._id });
const actionItemCategoriesIds = actionItemCategories.map(category => category._id);
const actionItemCategories = await ActionItemCategory.find({
organizationId: organization?._id,
});
const actionItemCategoriesIds = actionItemCategories.map(
(category) => category._id
);

// Remove all ActionItemCategory documents whose id is in the actionItemCategories array
await ActionItemCategory.deleteMany({ _id: { $in: actionItemCategoriesIds } });
await ActionItemCategory.deleteMany({
_id: { $in: actionItemCategoriesIds },
});

// Remove all ActionItem documents whose actionItemCategory is in the actionItemCategories array
await ActionItem.deleteMany({
Expand Down
4 changes: 3 additions & 1 deletion src/resolvers/Mutation/updateActionItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ export const updateActionItem: MutationResolvers["updateActionItem"] = async (
const currentUserIsOrgAdmin = currentUser.adminFor.some(
(ogranizationId) =>
ogranizationId === actionItem.actionItemCategoryId.organizationId ||
Types.ObjectId(ogranizationId).equals(actionItem.actionItemCategoryId.organizationId)
Types.ObjectId(ogranizationId).equals(
actionItem.actionItemCategoryId.organizationId
)
);

let currentUserIsEventAdmin = false;
Expand Down
Loading

0 comments on commit a74d184

Please sign in to comment.