Browse Source

Chat methods for front

zinab_elgendy 1 month ago
parent
commit
700f32593b

+ 46 - 17
MTWorkHR.Application/Chat/ChatHub.cs

@@ -1,6 +1,7 @@
 using Microsoft.AspNetCore.Identity;
 using Microsoft.AspNetCore.SignalR;
 using Microsoft.EntityFrameworkCore;
+using MimeKit;
 using MTWorkHR.Application.Filters;
 using MTWorkHR.Application.Identity;
 using MTWorkHR.Application.Mapper;
@@ -12,6 +13,7 @@ using MTWorkHR.Core.Global;
 using MTWorkHR.Core.UnitOfWork;
 using MTWorkHR.Infrastructure.Entities;
 using System;
+using System.ComponentModel.Design;
 using System.Linq.Dynamic.Core.Tokenizer;
 using System.Security.Claims;
 using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
@@ -34,33 +36,43 @@ namespace MTWorkHR.API.Chat
             _userManager = userManager;
         }
 
-
-       
-        public async Task getCompanyUsersList()
+        public async Task GetUsers()
         {
-            var companyUsers = await GetAllCompanyEmployees();
+            var myCompanyUsers = await GetAllCompanyEmployees();
 
-            await Clients.Caller.SendAsync("getCompanyUsersList", companyUsers);
+            await Clients.Caller.SendAsync("UpdateUserList", myCompanyUsers);
         }
 
+      
+      
         public async Task<List<UserAllDto>> GetAllCompanyEmployees()
         {
             var employees = await _userManager.GetUsersInRoleAsync("Employee");
-            var companyId = Context.User.Identities.FirstOrDefault().FindFirst("companyId")?.Value;
-            var CompanyId = long.Parse(companyId);
+            var CompanyId = GetAuthenticatedCompanyId();
             var res = employees.Where(e => e.CompanyId == CompanyId).ToList();
             var response = MapperObject.Mapper.Map<List<UserAllDto>>(res);
 
             return response;
         }
 
-
-        //Simple Test Method
-        public async Task SendMessageAll(string user, string message)
+        private long GetAuthenticatedCompanyId()
         {
-            await Clients.All.SendAsync("ReceiveMessage", user, message);
+            long CompanyIdLong = 0;
+            var identity = Context.User?.Identities.FirstOrDefault();
+            var CompanyId = identity!=null ? identity.FindFirst("companyId")?.Value : "0";
+            
+            if(CompanyId != null)
+            {
+                CompanyIdLong = long.Parse(CompanyId);
+            }
+            return CompanyIdLong;
         }
 
+      
+
+      
+        // Send a message from one user to another
+       
         public async Task sendMsg(string receiverUserId, string msg)
         {
             try
@@ -71,23 +83,40 @@ namespace MTWorkHR.API.Chat
                 var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
                 var receiverUser = allConnections.Item1.FirstOrDefault(c => c.UserId == receiverUserId);
                 var receiverconnIdDB = receiverUser != null ? receiverUser.SignalrId : "0";
-                ChatMessage messag = new ChatMessage { Content = msg, ReceiverId = receiverUserId, ReceiverName = receiverUser.UserName ?? "", SenderId = userId, SenderName = userName, IsSeen = false };
+                ChatMessage messag = new ChatMessage { 
+                    Content = msg, 
+                    ReceiverId = receiverUserId, 
+                    ReceiverName = receiverUser.UserName ?? "", 
+                    SenderId = userId, 
+                    SenderName = userName, 
+                    IsSeen = false 
+                };
                 await _unitOfWork.ChatMessage.AddAsync(messag);
                 await _unitOfWork.CompleteAsync();
-                await Clients.Client(receiverconnIdDB).SendAsync("sendMsgResponse", Context.ConnectionId, msg);
+                await Clients.Client(receiverconnIdDB).SendAsync("ReceiveMessage", messag);
+                await Clients.Caller.SendAsync("ReceiveMessage", messag);
             }
             catch (Exception e) { }
         }
 
-
-        public async Task getAllMessagesByUser(string senderId)
+        // Get previous messages between two users
+        public async Task GetPreviousMessages(string contactId)
         {
             var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
-            var allmessages = await _unitOfWork.ChatMessage.GetAllWithChildrenAsync(senderId, userId);
+            var allmessages = await _unitOfWork.ChatMessage.GetAllWithChildrenAsync(userId, contactId);
             // Ensure the query is fully materialized before passing it to SignalR
             var messagesList = await allmessages.Item1.ToListAsync();
 
-            await Clients.Caller.SendAsync("getAllMessagesByUserResponse", messagesList);
+            await Clients.Caller.SendAsync("PreviousMessages", messagesList);
+        }
+        //----------------------------------------------------------------------
+        //----------------------------------------------------------------------
+        //----------------------------------------------------------------------
+
+        //Simple Test Method
+        public async Task SendMessageAll(string user, string message)
+        {
+            await Clients.All.SendAsync("ReceiveMessage", user, message);
         }
 
         public async override Task OnDisconnectedAsync(Exception exception)

+ 1 - 1
MTWorkHR.Core/IRepositories/Chat/IChatMessageRepository.cs

@@ -11,6 +11,6 @@ namespace MTWorkHR.Core.IRepositories
     public interface IChatMessageRepository : IRepository<ChatMessage>
     {
         Task<ChatMessage> GetByIdWithAllChildren(long id);
-        Task<Tuple<IQueryable<ChatMessage>, int>> GetAllWithChildrenAsync(string senderId, string receiverId);
+        Task<Tuple<IQueryable<ChatMessage>, int>> GetAllWithChildrenAsync(string userId, string contactId);
     }
 }

+ 2 - 2
MTWorkHR.Infrastructure/Repositories/Chat/ChatMessageRepository.cs

@@ -22,9 +22,9 @@ namespace MTWorkHR.Infrastructure.Repositories
                 .Include(x => x.ChatAttachments)
                 .FirstOrDefaultAsync(x => x.Id == id);
         }
-        public async Task<Tuple<IQueryable<ChatMessage>, int>> GetAllWithChildrenAsync(string senderId, string receiverId)
+        public async Task<Tuple<IQueryable<ChatMessage>, int>> GetAllWithChildrenAsync(string userId, string contactId)
         {
-            var query = dbSet.Include(x => x.ChatAttachments).Where(m=> m.ReceiverId == receiverId && m.SenderId == senderId).AsQueryable();
+            var query = dbSet.Include(x => x.ChatAttachments).Where(m=> (m.ReceiverId == contactId && m.SenderId == userId) || (m.ReceiverId == userId && m.SenderId == contactId)).AsQueryable();
             var total = await query.CountAsync();
 
             return new Tuple<IQueryable<ChatMessage>, int>(query, total);