Skip to content

Commit

Permalink
Merge pull request #220 from souravbhowmik1999/Fetch_Learner_Lists_To…
Browse files Browse the repository at this point in the history
…_add_in_Center_new

Task #PS-1028 User Management: Fetch Learner Lists To add in Center
  • Loading branch information
vaivk369 authored Jun 20, 2024
2 parents 917c26a + 284d8b1 commit 7a59d3e
Show file tree
Hide file tree
Showing 3 changed files with 164 additions and 86 deletions.
96 changes: 48 additions & 48 deletions src/adapters/postgres/fields-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,28 +105,28 @@ export class PostgresFieldsService implements IServicelocatorfields {


try {
let result = await this.findAndSaveFieldValues(fieldValuesDto);
if(!result){
APIResponse.error(
res,
apiId,
`Fields not found or already exist`,
`Fields not found or already exist`,
(HttpStatus.NOT_FOUND)
)
let result = await this.findAndSaveFieldValues(fieldValuesDto);
if (!result) {
APIResponse.error(
res,
apiId,
`Fields not found or already exist`,
`Fields not found or already exist`,
(HttpStatus.NOT_FOUND)
)

}
return APIResponse.success(res, apiId, result, (HttpStatus.CREATED), "Field Values created successfully");
}
return APIResponse.success(res, apiId, result, (HttpStatus.CREATED), "Field Values created successfully");


} catch (error) {
const errorMessage = error.message || 'Something went wrong';
return APIResponse.error(res, apiId, "Internal Server Error",errorMessage, (HttpStatus.INTERNAL_SERVER_ERROR));
return APIResponse.error(res, apiId, "Internal Server Error", errorMessage, (HttpStatus.INTERNAL_SERVER_ERROR));

}
}

async searchFieldValues(request: any, fieldValuesSearchDto: FieldValuesSearchDto, response: Response) {
async searchFieldValues(request: any, fieldValuesSearchDto: FieldValuesSearchDto, response: Response) {
const apiId = APIID.FIELDVALUES_SEARCH;
try {
const getConditionalData = await this.search(fieldValuesSearchDto)
Expand Down Expand Up @@ -384,7 +384,9 @@ export class PostgresFieldsService implements IServicelocatorfields {
context: context,
};

if (contextType.length) {

const validContextTypes = contextType.filter(item => item);
if (validContextTypes.length > 0) {
condition.contextType = In(contextType);
}

Expand All @@ -396,12 +398,12 @@ export class PostgresFieldsService implements IServicelocatorfields {

async findFieldValues(contextId: string, context: string) {
let query = "";
if(context === "COHORT") {
query = `SELECT C."cohortId",F."fieldId",F."value" FROM public."Cohort" C
if (context === "COHORT") {
query = `SELECT C."cohortId",F."fieldId",F."value" FROM public."Cohort" C
LEFT JOIN public."FieldValues" F
ON C."cohortId" = F."itemId" where C."cohortId" =$1`;
} else if (context === "USERS") {
query = `SELECT U."userId",F."fieldId",F."value" FROM public."Users" U
query = `SELECT U."userId",F."fieldId",F."value" FROM public."Users" U
LEFT JOIN public."FieldValues" F
ON U."userId" = F."itemId" where U."userId" =$1`;
}
Expand All @@ -414,7 +416,7 @@ export class PostgresFieldsService implements IServicelocatorfields {
let customField;
let fieldsArr = [];
const [filledValues, customFields] = await Promise.all([
this.findFieldValues(id,context),
this.findFieldValues(id, context),
this.findCustomFields(context, [contextType])
]);

Expand Down Expand Up @@ -471,43 +473,41 @@ export class PostgresFieldsService implements IServicelocatorfields {
}

async updateCustomFields(itemId, data, fieldAttributesAndParams) {
console.log(fieldAttributesAndParams,"fiuouooijhjh")
const fieldOptions = fieldAttributesAndParams?.fieldParams?.options.map(({value}) => value);
const fieldOptions = fieldAttributesAndParams?.fieldParams?.options.map(({ value }) => value);
if (Array.isArray(data.value) === true) {
let dataArray = [];
for (let value of data.value) {
// check against options
console.log(fieldOptions ,"Foo")
if(!fieldOptions.includes(value)) {
let dataArray = [];
for (let value of data.value) {
// check against options
if (!fieldOptions.includes(value)) {
return {
correctValue: false,
fieldName: fieldAttributesAndParams.fieldName,
valueIssue: "Value not a part of given options"
};
}
else {
dataArray.push(value);
}
}
if (fieldAttributesAndParams?.fieldAttributes?.isMultiSelect && parseInt(fieldAttributesAndParams?.fieldAttributes?.maxSelections) >= dataArray.length) {
data.value = dataArray.join(',');
} else {
return {
correctValue : false,
correctValue: false,
fieldName: fieldAttributesAndParams.fieldName,
valueIssue: "Value not a part of given options"
};
}
else {
dataArray.push(value);
valueIssue: "Multiselect max selections exceeded"
};
}
}
if(fieldAttributesAndParams?.fieldAttributes?.isMultiSelect && parseInt(fieldAttributesAndParams?.fieldAttributes?.maxSelections) >= dataArray.length ) {
data.value = dataArray.join(',');
} else {
return {
correctValue : false,
fieldName : fieldAttributesAndParams.fieldName,
valueIssue: "Multiselect max selections exceeded"
};
}
}
let result : any = await this.fieldsValuesRepository.update({ itemId, fieldId: data.fieldId }, { value: data.value });

let result: any = await this.fieldsValuesRepository.update({ itemId, fieldId: data.fieldId }, { value: data.value });
let newResult;
if (result.affected === 0) {
newResult = await this.fieldsValuesRepository.save({
itemId,
fieldId: data.fieldId,
value: data.value
});
newResult = await this.fieldsValuesRepository.save({
itemId,
fieldId: data.fieldId,
value: data.value
});
}
Object.assign(result, newResult);
result["correctValue"] = true;
Expand Down
103 changes: 65 additions & 38 deletions src/adapters/postgres/user-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,10 @@ export class PostgresUserService implements IServicelocator {


async findAllUserDetails(userSearchDto) {
let { limit, page, filters } = userSearchDto;
let { limit, page, filters, exclude } = userSearchDto;
let offset = 0;
let excludeCohortIdes;
let excludeUserIdes;
if (page > 1) {
offset = parseInt(limit) * (page - 1);
}
Expand All @@ -102,15 +104,42 @@ export class PostgresUserService implements IServicelocator {
});
}

if (exclude && Object.keys(exclude).length > 0) {
Object.entries(exclude).forEach(([key, value]) => {
if (key == 'cohortIds') {
excludeCohortIdes = (value);
}
if (key == 'userIds') {
excludeUserIdes = (value);
}
});
}

const userIds = excludeUserIdes?.length > 0 ? excludeUserIdes.map(userId => `'${userId}'`).join(',') : null;

const cohortIds = excludeCohortIdes?.length > 0 ? excludeCohortIdes.map(cohortId => `'${cohortId}'`).join(',') : null;

if (userIds || cohortIds) {
const userCondition = userIds ? `U."userId" NOT IN (${userIds})` : '';
const cohortCondition = cohortIds ? `CM."cohortId" NOT IN (${cohortIds})` : '';
const combinedCondition = [userCondition, cohortCondition].filter(String).join(' AND ');

whereCondition += (index > 0 ? ' AND ' : '') + combinedCondition;
} else if (index === 0) {
whereCondition = '';
}

let query = `SELECT U."userId", U.username, U.name, R.name AS role, U.district, U.state,U.mobile
FROM public."Users" U
INNER JOIN public."CohortMembers" CM
ON CM."userId" = U."userId"
INNER JOIN public."UserRolesMapping" UR
ON UR."userId" = U."userId"
INNER JOIN public."Roles" R
ON R."roleId" = UR."roleId" ${whereCondition} AND U."status"='true'`
let results = await this.usersRepository.query(query);

if (!Query) {
if (!query) {
return false;
}
return results;
Expand Down Expand Up @@ -206,7 +235,7 @@ export class PostgresUserService implements IServicelocator {
where: {
roleId: getRole.roleId,
},
select: ["title",'code']
select: ["title", 'code']
})
return role;
}
Expand All @@ -228,45 +257,45 @@ export class PostgresUserService implements IServicelocator {
userDetails['tenantData'] = tenentDetails;
return userDetails;
}

async userTenantRoleData(userId: string) {
const query = `SELECT T.name AS tenantName, T."tenantId", UTM."Id" AS userTenantMappingId
FROM public."UserTenantMapping" UTM
LEFT JOIN public."Tenants" T
ON T."tenantId" = UTM."tenantId"
WHERE UTM."userId" = $1;`;

const result = await this.usersRepository.query(query, [userId]);

const combinedResult = [];
let roleArray = []
for (let data of result) {
const roleData = await this.postgresRoleService.findUserRoleData(userId, data.tenantId);
if (roleData.length > 0) {
roleArray.push(roleData[0].roleid)
const roleId = roleData[0].roleid;
const roleName = roleData[0].title;

const privilegeData = await this.postgresRoleService.findPrivilegeByRoleId(roleArray);
const privileges = privilegeData.map(priv => priv.name);

combinedResult.push({
tenantName: data.tenantname,
tenantId: data.tenantId,
userTenantMappingId: data.usertenantmappingid,
roleId: roleId,
roleName: roleName,
privileges: privileges
});
}
const roleData = await this.postgresRoleService.findUserRoleData(userId, data.tenantId);
if (roleData.length > 0) {
roleArray.push(roleData[0].roleid)
const roleId = roleData[0].roleid;
const roleName = roleData[0].title;

const privilegeData = await this.postgresRoleService.findPrivilegeByRoleId(roleArray);
const privileges = privilegeData.map(priv => priv.name);

combinedResult.push({
tenantName: data.tenantname,
tenantId: data.tenantId,
userTenantMappingId: data.usertenantmappingid,
roleId: roleId,
roleName: roleName,
privileges: privileges
});
}
}

return combinedResult;
}
}






async updateUser(userDto, response: Response) {
const apiId = APIID.USER_UPDATE;
try {
Expand All @@ -285,7 +314,7 @@ export class PostgresUserService implements IServicelocator {
const fieldIdAndAttributes = {};
for (let fieldDetails of getFieldsAttributes) {
isEditableFieldId.push(fieldDetails.fieldId);
fieldIdAndAttributes[`${fieldDetails.fieldId}`] = {fieldAttributes :fieldDetails.fieldAttributes, fieldParams :fieldDetails.fieldParams, fieldName: fieldDetails.name};
fieldIdAndAttributes[`${fieldDetails.fieldId}`] = { fieldAttributes: fieldDetails.fieldAttributes, fieldParams: fieldDetails.fieldParams, fieldName: fieldDetails.name };
}

let unEditableIdes = [];
Expand All @@ -305,15 +334,13 @@ export class PostgresUserService implements IServicelocator {
}
}
if (unEditableIdes.length > 0) {
// editIssues = `Uneditable fields: ${unEditableIdes.join(', ')}`
editIssues["uneditableFields"] = unEditableIdes
}
if (editFailures.length > 0) {
// editIssues += ` Edit Failures: ${editFailures.join(', ')}`
editIssues["editFieldsFailure"] = editFailures
editIssues["uneditableFields"] = unEditableIdes
}
if (editFailures.length > 0) {
editIssues["editFieldsFailure"] = editFailures
}
}
return await APIResponse.success(response, apiId, { ...updatedData, editIssues},
return await APIResponse.success(response, apiId, { ...updatedData, editIssues },
HttpStatus.OK, "User has been updated successfully.")
} catch (e) {
return APIResponse.error(response, apiId, "Internal Server Error", "Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR);
Expand Down Expand Up @@ -380,12 +407,12 @@ export class PostgresUserService implements IServicelocator {

if (result && userCreateDto.fieldValues?.length > 0) {
let userId = result?.userId;
const roles = validatedRoles.map(({code}) => code.toUpperCase())
const roles = validatedRoles.map(({ code }) => code.toUpperCase())

const customFields = await this.fieldsService.findCustomFields("USERS", roles)

const customFieldAttributes = customFields.reduce((fieldDetail ,{fieldId,fieldAttributes,fieldParams,name}) => fieldDetail[`${fieldId}`] ? fieldDetail : {...fieldDetail, [`${fieldId}`] : {fieldAttributes,fieldParams,name}},{});
const customFieldAttributes = customFields.reduce((fieldDetail, { fieldId, fieldAttributes, fieldParams, name }) => fieldDetail[`${fieldId}`] ? fieldDetail : { ...fieldDetail, [`${fieldId}`]: { fieldAttributes, fieldParams, name } }, {});

for (let fieldValues of userCreateDto.fieldValues) {

const fieldData = {
Expand All @@ -404,7 +431,7 @@ export class PostgresUserService implements IServicelocator {
}
}

APIResponse.success(response, apiId, { userData: {...result, createFailures } },
APIResponse.success(response, apiId, { userData: { ...result, createFailures } },
HttpStatus.CREATED, "User has been created successfully.")
}
} catch (e) {
Expand Down
Loading

0 comments on commit 7a59d3e

Please sign in to comment.