Skip to content

Commit

Permalink
Merge pull request #131 from souravbhowmik1999/deleteCohot
Browse files Browse the repository at this point in the history
COHORT: Delete API changes
  • Loading branch information
vaivk369 authored Apr 26, 2024
2 parents 086ec75 + 09abc3f commit abb8076
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 37 deletions.
62 changes: 42 additions & 20 deletions src/adapters/postgres/cohort-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export class PostgresCohortService {
private cohortRepository: Repository<Cohort>,
@InjectRepository(CohortMembers)
private cohortMembersRepository: Repository<CohortMembers>,
@InjectRepository(FieldValues)
private fieldValuesRepository: Repository<FieldValues>,
@InjectRepository(Fields)
private fieldsRepository: Repository<Fields>,
private fieldsService: PostgresFieldsService,
Expand Down Expand Up @@ -230,7 +232,7 @@ export class PostgresCohortService {
} else {
return new SuccessResponse({
statusCode: HttpStatus.CONFLICT,
message: "Cohort Name already exists.",
message: "Cohort name already exists.",
data: existData,
});
}
Expand Down Expand Up @@ -284,6 +286,8 @@ export class PostgresCohortService {
try {
const decoded: any = jwt_decode(request.headers.authorization);
cohortUpdateDto.updatedBy = decoded?.sub
cohortUpdateDto.createdBy = decoded?.sub
cohortUpdateDto.status = true;


if (!isUUID(cohortId)) {
Expand All @@ -296,32 +300,34 @@ export class PostgresCohortService {
const checkData = await this.checkAuthAndValidData(cohortId);

if (checkData === true) {
const filteredDto = Object.entries(cohortUpdateDto)
.filter(([_, value]) => value !== undefined && value !== '')
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});

if (Object.keys(filteredDto).length === 0) {
// If there are no properties to update, return success
return new SuccessResponse({
statusCode: HttpStatus.OK,
message: "No fields to update.",
data: {
rowCount: 0,
let updateData = {};
let fieldValueData = {};

// Iterate over all keys in cohortUpdateDto
for (let key in cohortUpdateDto) {
if (cohortUpdateDto.hasOwnProperty(key) && cohortUpdateDto[key] !== null) {
if (key !== 'fieldValues') {
updateData[key] = cohortUpdateDto[key];
} else {
fieldValueData[key] = cohortUpdateDto[key];
}
});
}
}

const response = await this.cohortRepository.update(cohortId, cohortUpdateDto);
const response = await this.cohortRepository.update(cohortId, updateData);


if (fieldValueData['fieldValues']) {

if (cohortUpdateDto.fieldValues) {
let field_value_array = cohortUpdateDto.fieldValues.split("|");
if (field_value_array.length > 0) {
let field_values = [];
for (let i = 0; i < field_value_array.length; i++) {

for (let i = 0; i < field_value_array.length; i++) {
let fieldValues = field_value_array[i].split(":");
let fieldId = fieldValues[0] ? fieldValues[0].trim() : "";
try {
console.log("hii");

const fieldVauesRowId = await this.fieldsService.searchFieldValueId(cohortId, fieldId)
const rowid = fieldVauesRowId.fieldValuesId;

Expand All @@ -331,6 +337,8 @@ export class PostgresCohortService {
};
await this.fieldsService.updateFieldValues(rowid, fieldValueUpdateDto);
} catch {
console.log("hii1");

let fieldValueDto: FieldValuesDto = {
value: fieldValues[1] ? fieldValues[1].trim() : "",
itemId: cohortId,
Expand All @@ -340,6 +348,8 @@ export class PostgresCohortService {
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
// console.log(fieldValueDto);

await this.fieldsService.createFieldValues(request, fieldValueDto);
}
}
Expand All @@ -348,7 +358,7 @@ export class PostgresCohortService {

return new SuccessResponse({
statusCode: HttpStatus.OK,
message: "Ok.",
message: "Cohort updated successfully.",
data: {
rowCount: response.affected,
}
Expand Down Expand Up @@ -488,21 +498,33 @@ export class PostgresCohortService {
request: any
) {
try {
const decoded: any = jwt_decode(request.headers.authorization);
// const createdBy = decoded?.sub;
const updatedBy = decoded?.sub

if (!isUUID(cohortId)) {
return new ErrorResponseTypeOrm({
statusCode: HttpStatus.BAD_REQUEST,
errorMessage: "Please Enter valid (UUID)",
});
}
const checkData = await this.checkAuthAndValidData(cohortId);
const updatedBy = request.user.userId;

if (checkData === true) {
let query = `UPDATE public."Cohort"
SET "status" = false,
"updatedBy" = '${updatedBy}'
WHERE "cohortId" = $1`;
await this.cohortRepository.query(query, [cohortId]);

await this.cohortMembersRepository.delete(
{cohortId:cohortId}
);
await this.fieldValuesRepository.delete(
{itemId:cohortId}
);


const results = await this.cohortRepository.query(query, [cohortId]);
return new SuccessResponse({
statusCode: HttpStatus.OK,
message: "Cohort Deleted Successfully.",
Expand Down
20 changes: 3 additions & 17 deletions src/cohort/cohort.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import { QueryParamsDto } from "./dto/query-params.dto";

@ApiTags("Cohort")
@Controller("cohorts")
// @UseGuards(JwtAuthGuard)
@UseGuards(JwtAuthGuard)
export class CohortController {
constructor(private readonly cohortAdapter: CohortAdapter) { }

Expand All @@ -57,7 +57,7 @@ export class CohortController {
@ApiOkResponse({ description: "Cohort detais Fetched Succcessfully" })
@ApiNotFoundResponse({ description: "Cohort Not Found" })
@ApiInternalServerErrorResponse({ description: "Internal Server Error." })
@ApiBadRequestResponse({description:"Bad Request"})
@ApiBadRequestResponse({ description: "Bad Request" })
@SerializeOptions({ strategy: "excludeAll", })
@ApiHeader({ name: "tenantid", })
public async getCohortsDetails(
Expand All @@ -78,7 +78,7 @@ export class CohortController {
@ApiCreatedResponse({ description: "Cohort has been created successfully." })
@ApiBadRequestResponse({ description: "Bad request." })
@ApiInternalServerErrorResponse({ description: "Internal Server Error." })
@ApiConflictResponse({description:"Cohort already exists."})
@ApiConflictResponse({ description: "Cohort already exists." })

@UseInterceptors(
FileInterceptor("image", {
Expand All @@ -101,15 +101,6 @@ export class CohortController {
@UploadedFile() image,
@Res() response: Response
) {
// Define expected fields
const expectedFields = ['programId', 'parentId', 'name', 'type', 'fieldValues' ];

// Check if any unexpected fields are present in the request body
const unexpectedFields = Object.keys(cohortCreateDto).filter(field => !expectedFields.includes(field));
if (unexpectedFields.length > 0) {
throw new BadRequestException(`Unexpected fields found: ${unexpectedFields.join(', ')}`);
}

let tenantid = headers["tenantid"];
const payload = {
image: image?.filename,
Expand Down Expand Up @@ -180,11 +171,6 @@ export class CohortController {
@UploadedFile() image,
@Res() response: Response
) {
const imgresponse = {
image: image?.filename,
};
Object.assign(cohortUpdateDto, imgresponse);

const result = await this.cohortAdapter.buildCohortAdapter().updateCohort(
cohortId,
request,
Expand Down

0 comments on commit abb8076

Please sign in to comment.