Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 27 additions & 30 deletions src/database/queries/mentorExtension.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,38 +153,35 @@ module.exports = class MentorExtensionQueries {
}
static async removeMentorDetails(userId, tenantCode) {
try {
const modelAttributes = MentorExtension.rawAttributes

const fieldsToNullify = {}

for (const [key, attribute] of Object.entries(modelAttributes)) {
// Skip primary key or explicitly excluded fields
if (
attribute.primaryKey ||
key === 'user_id' ||
key === 'organization_id' || // required field
key === 'created_at' ||
key === 'updated_at' ||
key === 'is_mentor' // has default value
) {
continue
}

// Set types accordingly
if (attribute.type.constructor.name === 'ARRAY') {
fieldsToNullify[key] = []
} else if (attribute.type.key === 'JSON' || attribute.type.key === 'JSONB') {
fieldsToNullify[key] = {} // Or `{}` if you prefer default object
} else if (key === 'deleted_at') {
fieldsToNullify[key] = new Date() // Timestamp field
} else if (key === 'name') {
fieldsToNullify[key] = common.USER_NOT_FOUND
} else {
fieldsToNullify[key] = null
}
const fieldsToClear = {
designation: [],
area_of_expertise: [],
education_qualification: null,
rating: {},
meta: {},
stats: {},
tags: [],
configs: {},
visible_to_organizations: [],
external_session_visibility: null,
custom_entity_text: {},
experience: null,
external_mentee_visibility: null,
mentee_visibility: null,
external_mentor_visibility: null,
mentor_visibility: null,
name: common.USER_NOT_FOUND,
email: null,
phone: null,
settings: {},
image: null,
gender: null,
status: null,
username: null,
deleted_at: new Date(),
}

return await MentorExtension.update(fieldsToNullify, {
return await MentorExtension.update(fieldsToClear, {
where: {
user_id: userId,
tenant_code: tenantCode,
Expand Down
7 changes: 5 additions & 2 deletions src/database/queries/sessions.js
Original file line number Diff line number Diff line change
Expand Up @@ -1099,22 +1099,25 @@ exports.getSessionsAssignedToMentor = async (mentorUserId, tenantCode) => {
}
}

exports.getSessionsAssignedToMentor = async (mentorUserId) => {
exports.getSessionsAssignedToMentor = async (mentorUserId, tenantCode) => {
try {
const query = `
SELECT s.*, sa.mentee_id
FROM ${Session.tableName} s
LEFT JOIN session_attendees sa ON s.id = sa.session_id
WHERE s.mentor_id = :mentorUserId
AND s.tenant_code = sa.tenant_code
WHERE s.mentor_id = :mentorUserId
AND s.start_date > :currentTime
AND s.deleted_at IS NULL
AND s.tenant_code = :tenantCode
`

const sessionsToDelete = await Sequelize.query(query, {
type: QueryTypes.SELECT,
replacements: {
mentorUserId,
currentTime: Math.floor(Date.now() / 1000),
tenantCode,
},
})

Expand Down
61 changes: 29 additions & 32 deletions src/database/queries/userExtension.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,38 +238,35 @@ module.exports = class MenteeExtensionQueries {

static async removeMenteeDetails(userId, tenantCode) {
try {
const modelAttributes = MenteeExtension.rawAttributes

const fieldsToNullify = {}

for (const [key, attribute] of Object.entries(modelAttributes)) {
// Skip primary key or explicitly excluded fields
if (
attribute.primaryKey ||
key === 'user_id' ||
key === 'organization_id' || // required field
key === 'created_at' ||
key === 'updated_at' ||
key === 'is_mentor' // has default value
) {
continue
}

// Set types accordingly
if (attribute.type.constructor.name === 'ARRAY') {
fieldsToNullify[key] = []
} else if (attribute.type.key === 'JSON' || attribute.type.key === 'JSONB') {
fieldsToNullify[key] = {} // Or `{}` if you prefer default object
} else if (key === 'deleted_at') {
fieldsToNullify[key] = new Date() // Timestamp field
} else if (key === 'name') {
fieldsToNullify[key] = common.USER_NOT_FOUND
} else {
fieldsToNullify[key] = null
}
}

return await MenteeExtension.update(fieldsToNullify, {
const fieldsToClear = {
designation: [],
area_of_expertise: [],
education_qualification: null,
rating: {},
meta: {},
stats: {},
tags: [],
configs: {},
visible_to_organizations: [],
external_session_visibility: null,
custom_entity_text: {},
experience: null,
external_mentee_visibility: null,
mentee_visibility: null,
external_mentor_visibility: null,
mentor_visibility: null,
name: common.USER_NOT_FOUND,
email: null,
phone: null,
settings: {},
image: null,
gender: null,
status: null,
username: null,
deleted_at: new Date(),
}

return await MenteeExtension.update(fieldsToClear, {
where: {
user_id: userId,
tenant_code: tenantCode,
Expand Down
12 changes: 0 additions & 12 deletions src/helpers/getDefaultOrgId.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
'use strict'

const userRequests = require('@requests/user')

/**
* Retrieves the default organization code.
* @returns {Promise<string|null>} Default organization code or null if not found.
Expand All @@ -15,16 +13,6 @@ exports.getDefaults = async () => {
tenantCode: DEFAULT_TENANT_CODE,
}
}

const { success, data } = await userRequests.fetchOrgDetails({
organizationCode: DEFAULT_ORGANISATION_CODE,
tenantCode: DEFAULT_TENANT_CODE,
})

return {
orgCode: success && data?.result?.code,
tenantCode: data?.result?.tenant_code,
}
} catch (err) {
console.error('Error in getDefaults:', err)
return null
Expand Down
3 changes: 1 addition & 2 deletions src/requests/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@ const httpStatusCode = require('@generics/http-status')
const responses = require('@helpers/responses')
const common = require('@constants/common')
const { Op } = require('sequelize')
const cacheHelper = require('@generics/cacheHelper')
const usersHelper = require('@helpers/users')
const cacheHelper = require('@generics/cacheHelper')

const menteeQueries = require('@database/queries/userExtension')
const organisationExtensionQueries = require('@database/queries/organisationExtension')
// Removed cacheHelper to break circular dependency with getDefaultOrgId

const emailEncryption = require('@utils/emailEncryption')
const _ = require('lodash')
Expand Down
43 changes: 22 additions & 21 deletions src/services/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ module.exports = class AdminService {
let result = {}

// Step 1: Fetch user details
let getUserDetails = []
let userInfo = null
let userTenantCode = tenantCode

// Optimization: If admin, query directly without tenant restriction (1 query)
Expand All @@ -182,18 +182,17 @@ module.exports = class AdminService {
getUserDetails = userDetail ? [userDetail] : []
} else {
// Regular user deleting themselves - use tenant code from token (optimized path)
getUserDetails = await menteeQueries.getUsersByUserIds([userId], {}, tenantCode)
const getUserDetails = await menteeQueries.getUsersByUserIds([userId], {}, tenantCode)
userInfo = getUserDetails?.[0]
}

if (!getUserDetails || getUserDetails.length === 0) {
if (!userInfo) {
return responses.failureResponse({
statusCode: httpStatusCode.bad_request,
message: 'USER_NOT_FOUND',
result,
})
}

const userInfo = getUserDetails[0]
const isMentor = userInfo.is_mentor === true

// Step 2: Check if user is a session manager
Expand Down Expand Up @@ -763,7 +762,11 @@ module.exports = class AdminService {
const sentRequestsData = sentRequests.rows || []

// Get requests where user is requestee (received requests)
const sessionRequestMapping = await sessionRequestMappingQueries.getSessionsMapping(userId, tenantCode)
const sessionRequestMapping = await sessionRequestMappingQueries.getSessionsMapping(
userId,
common.CONNECTIONS_STATUS.REQUESTED,
tenantCode
)
const sessionRequestIds = Array.isArray(sessionRequestMapping)
? sessionRequestMapping.map((s) => s.request_session_id)
: []
Expand Down Expand Up @@ -1133,7 +1136,7 @@ module.exports = class AdminService {
orgCode: orgCodes,
templateData: { menteeName },
subjectData: { menteeName },
tenantCodes,
tenantCode: tenantCodes,
})
}

Expand Down Expand Up @@ -1190,7 +1193,7 @@ module.exports = class AdminService {
sessionTime: sessionDateTime.format('hh:mm A'),
},
subjectData: { sessionName: sessionDetails.title },
tenantCodes,
tenantCode: tenantCodes,
})
} catch (error) {
console.error('Error notifying mentor about private session cancellation:', error)
Expand Down Expand Up @@ -1415,21 +1418,19 @@ module.exports = class AdminService {
orgCode: orgCodes,
templateData: { mentorName },
subjectData: { mentorName },
tenantCodes,
tenantCode: tenantCodes,
})
}

static async getPendingSessionRequestsForMentor(mentorUserId, tenantCode) {
try {
const query = `
SELECT rs.*, rm.requestee_id
FROM ${RequestSession.tableName} rs
INNER JOIN request_session_mapping rm ON rs.id = rm.request_session_id
WHERE rm.requestee_id = :mentorUserId
AND rs.status = :requestedStatus
AND rs.deleted_at IS NULL
AND rs.tenant_code = :tenantCode
AND rm.tenant_code = :tenantCode
SELECT *
FROM ${RequestSession.tableName}
WHERE requestee_id = :mentorUserId
AND status = :requestedStatus
AND deleted_at IS NULL
AND tenant_code = :tenantCode
`

const pendingRequests = await sequelize.query(query, {
Expand Down Expand Up @@ -1476,7 +1477,7 @@ module.exports = class AdminService {
orgCode: orgCodes,
templateData: { sessionName: request.title },
subjectData: { sessionName: request.title },
tenantCodes,
tenantCode: tenantCodes,
})
}
}
Expand Down Expand Up @@ -1532,7 +1533,7 @@ module.exports = class AdminService {
orgCode: orgCodes,
templateData: { mentorName, sessionList },
subjectData: { mentorName },
tenantCodes,
tenantCode: tenantCodes,
})
}
})
Expand Down Expand Up @@ -1589,7 +1590,7 @@ module.exports = class AdminService {
orgCode: orgCodes,
templateData: { menteeName: menteeName, sessionList: sessionList },
subjectData: { menteeName: menteeName },
tenantCodes,
tenantCode: tenantCodes,
})
}
})
Expand Down Expand Up @@ -1643,7 +1644,7 @@ module.exports = class AdminService {
orgCode: orgCodes,
templateData: { sessionName: session.title },
subjectData: { sessionName: session.title },
tenantCodes,
tenantCode: tenantCodes,
})
}
}
Expand Down