diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 2f91b204951039347cbd0672ce069b140c562c3f..2159b23a170a7e8cc3c93babb63ac7c688fcf63a 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -326,21 +326,36 @@ export class UsersService { structureName: string, validate: boolean ): Promise<PendingStructureDto[]> { - const users = await this.findOne(userEmail); + const user = await this.findOne(userEmail); + // Get other users who have made the demand on the same structure + const otherUsers = await this.userModel + .find({ pendingStructuresLink: structureId, email: { $ne: userEmail } }) + .exec(); + let status = false; - if (!users) { + if (!user) { throw new HttpException('User not found', HttpStatus.NOT_FOUND); } - if (users.pendingStructuresLink.includes(structureId)) { - users.pendingStructuresLink = users.pendingStructuresLink.filter((item) => item !== structureId); + if (user.pendingStructuresLink.includes(structureId)) { + user.pendingStructuresLink = user.pendingStructuresLink.filter((item) => item !== structureId); // If it's a validation case, push structureId into validated user structures if (validate) { - users.structuresLink.push(structureId); + user.structuresLink.push(structureId); // Send validation email status = true; + // For other users who have made the demand on the same structure + if (otherUsers) { + otherUsers.forEach((user) => { + // Remove the structure id from their demand + user.pendingStructuresLink = user.pendingStructuresLink.filter((item) => item !== structureId); + // Send a rejection email + this.sendStructureClaimApproval(user.email, structureName, false); + user.save(); + }); + } } this.sendStructureClaimApproval(userEmail, structureName, status); - await users.save(); + await user.save(); return this.getPendingStructures(); } else { throw new HttpException(