Skip to content

🔧 AUAF bug fix #1270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Apr 9, 2025
Merged
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
233 changes: 25 additions & 208 deletions backend/api/views/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
from api import socketio
from mongoengine.queryset.visitor import Q
from urllib.parse import unquote
from bson.objectid import ObjectId


messages = Blueprint("messages", __name__)
Expand Down Expand Up @@ -191,11 +190,8 @@ def get_sidebar(user_id):
Q(recipient_id=user_id) | Q(sender_id=user_id)
).order_by("-created_at")

allMessages = [json.loads(message.to_json()) for message in sentMessages]

contacts = []
sidebarContacts = set()

for message in sentMessages:
otherId = message["recipient_id"]
message_read = message["message_read"]
Expand Down Expand Up @@ -223,7 +219,6 @@ def get_sidebar(user_id):
msg = "Could not find mentor or mentee for given ids"
logger.info(msg)
continue

otherUser = json.loads(otherUser.to_json())
if user_type == Account.PARTNER.value:
if "organization" in otherUser:
Expand All @@ -245,38 +240,37 @@ def get_sidebar(user_id):
if "image" in otherUser:
otherUserObj["image"] = otherUser["image"]["url"]

# Count messages for this contact
message_count = len(
[
msg
for msg in sentMessages
if (
msg["recipient_id"] == otherId
or msg["sender_id"] == otherId
)
]
)

# Create the sidebar object
sidebarObject = {
"otherId": str(otherId),
"message_read": message_read,
"numberOfMessages": message_count,
"numberOfMessages": len(
[
messagee
for messagee in sentMessages
if (
messagee["recipient_id"] == otherId
or messagee["sender_id"] == otherId
)
]
),
"otherUser": otherUserObj,
"latestMessage": json.loads(message.to_json()),
}

allMessages = [
json.loads(message.to_json()) for message in sentMessages
]

contacts.append(sidebarObject)
sidebarContacts.add(otherId)

# Return in the exact format expected by frontend
return create_response(
data={
"data": contacts,
"allMessages": allMessages,
},
status=200,
message="success",
message="res",
)
except Exception as e:
logger.info(e)
Expand Down Expand Up @@ -621,134 +615,20 @@ def get_group_messages():
@all_users
def get_direct_messages():
try:
sender_id = request.args.get("sender_id")
recipient_id = request.args.get("recipient_id")

messages = DirectMessage.objects(
Q(sender_id=sender_id) & Q(recipient_id=recipient_id)
| Q(sender_id=recipient_id) & Q(recipient_id=sender_id)
)

if sender_id == request.args.get("viewer_id", sender_id):
DirectMessage.objects(
sender_id=recipient_id, recipient_id=sender_id, message_read=False
).update(message_read=True)

return create_response(
data={"Messages": messages}, status=200, message="Success"
)

except Exception as e:
msg = f"Error retrieving messages: {str(e)}"
logger.info(msg)
return create_response(status=422, message=msg)


@messages.route("/details/", methods=["GET"])
@all_users
def get_message_details():
"""Optimized endpoint for retrieving message details with pagination and filtering"""
try:
page = int(request.args.get("page", 1))
limit = int(request.args.get("limit", 20))
skip = (page - 1) * limit

sender_id = request.args.get("sender_id")
recipient_id = request.args.get("recipient_id")
conversation_id = request.args.get("conversation_id")

match_condition = {}

if conversation_id:
conversation_pipeline = [
{"$match": {"_id": ObjectId(conversation_id)}},
{"$project": {"participants": 1}},
]
conversation = list(DirectMessage.objects.aggregate(*conversation_pipeline))
if conversation:
participants = conversation[0].get("participants", [])
if len(participants) == 2:
user1, user2 = participants
match_condition = {
"$or": [
{"$and": [{"sender_id": user1}, {"recipient_id": user2}]},
{"$and": [{"sender_id": user2}, {"recipient_id": user1}]},
]
}
elif sender_id and recipient_id:
match_condition = {
"$or": [
{
"$and": [
{"sender_id": sender_id},
{"recipient_id": recipient_id},
]
},
{
"$and": [
{"sender_id": recipient_id},
{"recipient_id": sender_id},
]
},
]
}

if not match_condition:
return create_response(
data={
"Messages": [],
"pagination": {
"total": 0,
"page": page,
"limit": limit,
"pages": 0,
},
},
status=200,
message="No valid filter provided",
)

pipeline = [
{"$match": match_condition},
{"$sort": {"created_at": 1}},
{"$skip": skip},
{"$limit": limit},
]

messages = list(DirectMessage.objects.aggregate(*pipeline))

# Get total count for pagination
count_pipeline = [{"$match": match_condition}, {"$count": "total"}]

count_result = list(DirectMessage.objects.aggregate(*count_pipeline))
total_count = count_result[0]["total"] if count_result else 0

# Convert ObjectIds to strings for JSON serialization
for msg in messages:
if "_id" in msg:
msg["_id"] = str(msg["_id"])
if "sender_id" in msg:
msg["sender_id"] = str(msg["sender_id"])
if "recipient_id" in msg:
msg["recipient_id"] = str(msg["recipient_id"])

return create_response(
data={
"Messages": messages,
"pagination": {
"total": total_count,
"page": page,
"limit": limit,
"pages": (total_count + limit - 1) // limit,
},
},
status=200,
message="Success",
Q(sender_id=request.args.get("sender_id"))
& Q(recipient_id=request.args.get("recipient_id"))
| Q(sender_id=request.args.get("recipient_id"))
& Q(recipient_id=request.args.get("sender_id"))
)
except Exception as e:
msg = f"Error retrieving message details: {str(e)}"
except:
msg = "Invalid parameters provided"
logger.info(msg)
return create_response(status=422, message=msg)
msg = "Success"
if not messages:
msg = request.args
return create_response(data={"Messages": messages}, status=200, message=msg)


@socketio.on("editGroupMessage")
Expand Down Expand Up @@ -887,66 +767,3 @@ def invite(msg, methods=["POST"]):
return create_response(status=422, message=msg)

return create_response(status=200, message="successfully sent invite")


@messages.route("/partners/", methods=["GET"])
@all_users
def get_partners():
"""Optimized endpoint for retrieving partner data with caching support"""
try:
# Get filter parameters
restricted = request.args.get("restricted")
hub_user_id = request.args.get("hub_user_id")

# Build query based on filters
query = {}
if restricted == "true":
query["restricted"] = True
elif restricted == "false":
query["restricted"] = False

if hub_user_id:
query["hub_id"] = hub_user_id # Using hub_id field instead of hub_user_id

# Use projection to limit fields returned (optimization)
partners = PartnerProfile.objects(**query).only(
"id", "organization", "image", "restricted", "hub_id", "hub_user", "email"
)

# Convert to list of dictionaries with minimal required data
partner_data = []
for partner in partners:
partner_dict = {
"id": str(partner.id),
"organization": partner.organization,
"email": partner.email,
"role": Account.PARTNER.value,
}

if partner.image and hasattr(partner.image, "url"):
partner_dict["image"] = {"url": partner.image.url}

if hasattr(partner, "restricted"):
partner_dict["restricted"] = partner.restricted

# Check for both hub_id and hub_user_id to maintain compatibility
if hasattr(partner, "hub_id"):
partner_dict[
"hub_user_id"
] = (
partner.hub_id
) # Map hub_id to hub_user_id for frontend compatibility
elif hasattr(partner, "hub_user_id"):
partner_dict["hub_user_id"] = partner.hub_user_id

partner_data.append(partner_dict)

return create_response(
data={"accounts": partner_data}, # Match the structure of fetchAccounts
status=200,
message="Success",
)
except Exception as e:
msg = f"Error retrieving partners: {str(e)}"
logger.info(msg)
return create_response(status=422, message=msg)
2 changes: 1 addition & 1 deletion frontend/src/components/EventCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function EventCard(props) {
}

function getCreaterData(user_id) {
return props.users.find((x) => x._id.$oid === user_id.$oid);
return props.users.find((x) => (x.id ? x.id : x._id.$oid === user_id.$oid));
}

const event_item = props.event_item;
Expand Down
Loading