Skip to content

Commit

Permalink
Merge pull request #238 from poojakarma/notification_integration_onAf…
Browse files Browse the repository at this point in the history
…terCohortMemberAdd

Notification integration on after cohort member added and learner added
  • Loading branch information
vaivk369 authored Jul 5, 2024
2 parents 901aba3 + 1d02c1f commit caa7ad4
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 17 deletions.
1 change: 1 addition & 0 deletions src/adapters/cohortMembersservicelocator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface IServicelocatorcohortMembers {
cohortMembersDto: CohortMembersDto,
response: any,
tenantId: string,
deviceId: string
);
getCohortMembers(cohortMemberId: string, tenantId: string, fieldvalue: string, response: Response);
searchCohortMembers(cohortMembersSearchDto: CohortMembersSearchDto, tenantId: string, response: Response);
Expand Down
40 changes: 28 additions & 12 deletions src/adapters/postgres/cohortMembers-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import APIResponse from "src/common/responses/response";
import { Response } from "express";
import { APIID } from 'src/common/utils/api-id.config';
import { MemberStatus } from "src/cohortMembers/entities/cohort-member.entity";
import { NotificationRequest } from "@utils/notification.axios";


@Injectable()
export class PostgresCohortMembersService {
Expand All @@ -34,7 +36,9 @@ export class PostgresCohortMembersService {
@InjectRepository(User)
private usersRepository: Repository<User>,
@InjectRepository(Cohort)
private cohortRepository: Repository<Cohort>
private cohortRepository: Repository<Cohort>,
private readonly notificationRequest: NotificationRequest

) { }

async getCohortMembers(cohortId: any, tenantId: any, fieldvalue: any, res: Response) {
Expand Down Expand Up @@ -289,7 +293,8 @@ export class PostgresCohortMembersService {
loginUser: any,
cohortMembers: CohortMembersDto,
res: Response,
tenantId: string
tenantId: string,
deviceId: string
) {
const apiId = APIID.COHORT_MEMBER_CREATE;
try {
Expand Down Expand Up @@ -328,6 +333,19 @@ export class PostgresCohortMembersService {
cohortMembers
);

if (deviceId) {
// Prepare the notification payload
const notificationPayload = {
isQueue: false,
context: 'COHORT',
replacements: [cohortMembers.cohortId],
push: {
receipients: [deviceId],
// to: deviceId,
},
};
await this.notificationRequest.sendNotification(notificationPayload);
}
return APIResponse.success(res, apiId, savedCohortMember, HttpStatus.OK, "Cohort member has been successfully assigned.");

} catch (e) {
Expand Down Expand Up @@ -507,14 +525,14 @@ export class PostgresCohortMembersService {
updatedBy: loginUser,
tenantId: tenantId
};

for (let userId of cohortMembersDto.userId) {
const userExists = await this.checkUserExist(userId);
if (!userExists) {
errors.push(`User with userId ${userId} does not exist.`);
continue;
}

// Handling of Removing Cohort from user
if (cohortMembersDto.removeCohortId && cohortMembersDto.removeCohortId.length > 0) {
for (let removeCohortId of cohortMembersDto.removeCohortId) {
Expand All @@ -525,10 +543,10 @@ export class PostgresCohortMembersService {
continue;
}
const updateCohort = await this.cohortMembersRepository.update({ userId, cohortId: removeCohortId }, { status: MemberStatus.ARCHIVED });
if(updateCohort.affected === 0){
results.push({message:`Cohort Id ${removeCohortId} is not mapped to user Id${userId}} `});
}else{
results.push({message:`Cohort Id ${removeCohortId} status updated for This user Id${userId}} `});
if (updateCohort.affected === 0) {
results.push({ message: `Cohort Id ${removeCohortId} is not mapped to user Id${userId}} ` });
} else {
results.push({ message: `Cohort Id ${removeCohortId} status updated for This user Id${userId}} ` });
}
} catch (error) {
errors.push(`Error updating cohort member with userId ${userId} and cohortId ${removeCohortId}: ${error.message}`);
Expand Down Expand Up @@ -567,13 +585,11 @@ export class PostgresCohortMembersService {
}
}
}

if (errors.length > 0) {
return APIResponse.success(response, APIID.COHORT_MEMBER_CREATE, { results, errors }, HttpStatus.CREATED, "Cohort Members Created with some errors");
}

return APIResponse.success(response, APIID.COHORT_MEMBER_CREATE, results, HttpStatus.CREATED, "Cohort Members Created Successfully");
}


}
7 changes: 5 additions & 2 deletions src/adapters/postgres/postgres-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { UserRoleMapping } from "src/rbac/assign-role/entities/assign-role.entit
import { Role } from "src/rbac/role/entities/role.entity";
import { PostgresRoleService } from "./rbac/role-adapter";
import { RolePrivilegeMapping } from "src/rbac/assign-privilege/entities/assign-privilege.entity";
import { NotificationRequest } from "@utils/notification.axios";


@Module({
Expand All @@ -33,19 +34,21 @@ import { RolePrivilegeMapping } from "src/rbac/assign-privilege/entities/assign-
Tenants,
UserRoleMapping,
Role,
RolePrivilegeMapping
RolePrivilegeMapping,
])
],
providers: [
PostgresUserService,
PostgresAttendanceService,
PostgresFieldsService,
PostgresRoleService,
NotificationRequest
],
exports: [
PostgresUserService,
PostgresAttendanceService,
PostgresFieldsService
PostgresFieldsService,
NotificationRequest
],
})
export class PostgresModule { }
25 changes: 25 additions & 0 deletions src/adapters/postgres/user-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { IServicelocator } from '../userservicelocator';
import { PostgresFieldsService } from "./fields-adapter"
import { PostgresRoleService } from './rbac/role-adapter';
import { CustomFieldsValidation } from '@utils/custom-field-validation';
import { NotificationRequest } from '@utils/notification.axios';


@Injectable()
export class PostgresUserService implements IServicelocator {
Expand All @@ -55,6 +57,7 @@ export class PostgresUserService implements IServicelocator {
private roleRepository: Repository<Role>,
private fieldsService: PostgresFieldsService,
private readonly postgresRoleService: PostgresRoleService,
private readonly notificationRequest: NotificationRequest
// private cohortMemberService: PostgresCohortMembersService,
) { }

Expand Down Expand Up @@ -421,6 +424,15 @@ export class PostgresUserService implements IServicelocator {
const decoded: any = jwt_decode(request.headers.authorization);
userCreateDto.createdBy = decoded?.sub
userCreateDto.updatedBy = decoded?.sub
// const emailId = decoded?.email;
console.log(userCreateDto.createdBy, "cfeatbby");

let email = await this.usersRepository.findOne({
where: { userId: userCreateDto.createdBy }, select
: ['email']
})
console.log(email, "email");


// Check duplicate field entry
if (userCreateDto.fieldValues) {
Expand Down Expand Up @@ -493,6 +505,19 @@ export class PostgresUserService implements IServicelocator {

}
}
// Send Notification if user added as cohort Member
if (result && userCreateDto.tenantCohortRoleMapping[0].cohortId &&
userCreateDto.tenantCohortRoleMapping[0].cohortId.length > 0 && email.email) {
const notificationPayload = {
isQueue: false,
context: 'USER',
replacements: [userCreateDto.name, userCreateDto.username, userCreateDto.password],
email: {
receipients: [email.email]
}
};
await this.notificationRequest.sendNotification(notificationPayload);
}

APIResponse.success(response, apiId, { userData: { ...result, createFailures } },
HttpStatus.CREATED, "User has been created successfully.")
Expand Down
10 changes: 7 additions & 3 deletions src/cohortMembers/cohortMembers.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import { BulkCohortMember } from "./dto/bulkMember-create.dto";
export class CohortMembersController {
constructor(
private readonly cohortMemberAdapter: CohortMembersAdapter
) {}
) { }

//create cohort members
@UseFilters(new AllExceptionsFilter(APIID.COHORT_MEMBER_CREATE))
Expand All @@ -59,6 +59,9 @@ export class CohortMembersController {
@ApiHeader({
name: "tenantid",
})
@ApiHeader({
name: "deviceid",
})
public async createCohortMembers(
@Headers() headers,
@Req() request,
Expand All @@ -67,9 +70,10 @@ export class CohortMembersController {
) {
const loginUser = request.user.userId;
const tenantId = headers["tenantid"];
const deviceId = headers["deviceid"];
const result = await this.cohortMemberAdapter
.buildCohortMembersAdapter()
.createCohortMembers(loginUser, cohortMembersDto, response, tenantId);
.createCohortMembers(loginUser, cohortMembersDto, response, tenantId, deviceId);
return response.status(result.statusCode).json(result);
}

Expand Down Expand Up @@ -202,7 +206,7 @@ export class CohortMembersController {
const tenantId = headers["tenantid"];
const result = await this.cohortMemberAdapter
.buildCohortMembersAdapter()
.createBulkCohortMembers(loginUser,bulkcohortMembersDto, response, tenantId);
.createBulkCohortMembers(loginUser, bulkcohortMembersDto, response, tenantId);
return result;
}
}
35 changes: 35 additions & 0 deletions src/common/utils/notification.axios.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { HttpService } from "@nestjs/axios";
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";

import axios, { AxiosRequestConfig } from "axios";

@Injectable()
export class NotificationRequest {
private readonly url: string;
constructor(private readonly configService: ConfigService,
private readonly httpService: HttpService) {
this.url = this.configService.get('NOTIFICATION_URL');
}

async sendNotification(body) {
const data = JSON.stringify(body);
const config: AxiosRequestConfig<any> = {
method: 'POST',
maxBodyLength: Infinity,
url: this.url,
headers: {
'Content-Type': 'application/json'
},
data: data,
};
try {
const response = await axios.request(config)
console.log(response.data);
return response.data;
} catch (error) {
// throw error;
return null
}
}
}

0 comments on commit caa7ad4

Please sign in to comment.