public void Create(EducationSecurityPrincipal user, ServiceRequestModel viewModel)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (viewModel == null)
            {
                throw new ArgumentNullException("viewModel");
            }
            IPermission permission = PermissionFactory.Current.Create("CreateServiceRequest", StudentRepository.Items.Include(s => s.School.UserRoles).Where(s => viewModel.StudentIds.Contains(s.Id)));

            permission.GrantAccess(user);
            List <int> studentIds = viewModel.StudentIds.ToList();

            foreach (int studentId in studentIds)
            {
                ServiceRequest request = new ServiceRequest();
                viewModel.CopyTo(request);
                request.StudentId      = studentId;
                request.CreatingUser   = user.Identity.User;
                request.CreatingUserId = user.Identity.User.Id;
                CreateFulfillmentDetail(request, user, viewModel);
                ServiceRequestRepository.Add(request);
            }
            RepositoryContainer.Save();
        }
        public IHttpActionResult Save([FromBody] RequestQuotationViewModel model)
        {
            try
            {
                if (model == null)
                {
                    return(NotFound());
                }
                var quotation = new RequestQuotation
                {
                    Id = model.Id,
                    ServiceRequestId    = model.ServiceRequestId,
                    AgentId             = model.AgentId,
                    QuotationTemplateId = model.QuotationTemplateId,
                    QuotationText       = model.QuotationText,
                    Premimum            = Convert.ToDecimal(model.Premimum.Replace(",", String.Empty)),
                    Status = (int)Constant.QuotationStatus.Initial,
                    Cover  = Convert.ToDecimal(model.Cover.Replace(",", String.Empty))
                };

                using (AppDBContext context = new AppDBContext())
                {
                    long quoteId = new RequestQuotationRepository(context).Save(quotation);
                    new AgentServiceRequestRepository(context).UpdateResponseTime(model.ServiceRequestId, model.AgentId);
                    var userRepo     = new UserRepository(context);
                    var request      = new ServiceRequestRepository(context).GetById(model.ServiceRequestId);
                    var agentProfile = new UserProfileRepository(context).GetByUserId(model.AgentId);
                    var agent        = userRepo.GetByUserId(model.AgentId);
                    var agentName    = agent.Name;
                    var company      = agent.Company.Name;
                    if (agentProfile != null)
                    {
                        agentName = agentProfile.FirstName + " " + agentProfile.LastName;
                    }

                    MessageModel message = new MessageModel
                    {
                        MessageText = "Quotation Sent by: " + agentName + "\n" + company,
                        RequestId   = model.ServiceRequestId,
                        SenderId    = model.AgentId,
                        RecieverId  = request.UserId,
                        QuotationId = quoteId
                    };
                    AddMessage(message, context);
                    new NotificationRepository(context).Add(
                        message.RecieverId,
                        (int)Constant.NotificationType.Quotation,
                        message.QuotationId,
                        ConfigurationHelper.NOTIFICATION_TITLE,
                        Constant.Notification.NEW_QUOTATION_TEXT);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(QuotationController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError());
            }

            return(Ok());
        }
        public IHttpActionResult GetFollowUpByBuyerCount(long BuyerId)
        {
            var count = 0;

            using (AppDBContext context = new AppDBContext())
            {
                count = new ServiceRequestRepository(context).GetFollowUpByBuyerId(BuyerId).Count();
            }
            return(Json(count));
        }
        public IHttpActionResult Save(ServiceRequestModel Model)
        {
            ServiceRequest SR = new ServiceRequest();

            SR.Id = Model.Id;
            SR.InsuranceTypeId      = Model.InsuranceTypeId;
            SR.Code                 = Model.Code;
            SR.UserId               = Model.UserId;
            SR.TimeOccured          = DateTime.Now.ToUniversalTime();
            SR.ClaimType            = Model.ClaimType;
            SR.UsageType            = Model.UsageType;
            SR.RegistrationCategory = Model.RegistrationCategory;
            SR.VehicleNo            = Model.VehicleNo;
            SR.VehicleValue         = Model.VehicleValue;
            SR.VehicleYear          = Model.VehicleYear;
            SR.IsFinanced           = Model.IsFinanced;
            SR.Location             = Model.Location;
            SR.ClientType           = Model.ClientType;
            SR.FuelType             = Model.FuelType;
            //SR.Images = Model.Images;

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    var repo = new ServiceRequestRepository(context);
                    if (SR.Id == 0)
                    {
                        SR.Id = repo.Add(SR);
                        AssignRequestToAgents(SR.Id);

                        //Added temporary
                        Utility.SendEmail("Request " + SR.Code + " Raised", SR.Code);
                    }
                    else
                    {
                        repo.Update(SR);
                    }

                    if (SR.Images != null)
                    {
                        var imageRepo = new VehicleImageRepository(context);
                        imageRepo.Update(SR.Id, SR.Images);
                    }
                }

                return(Json(SR));
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(ServiceRequestController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError());
            }
        }
        public IHttpActionResult GetByBuyerId(long BuyerId, int Status, int Page)
        {
            var requests = new List <ServiceRequestModel>();

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    var serviceReqRepo = new ServiceRequestRepository(context);
                    if (!(Status == (int)Constant.ServiceRequestStatus.Closed || Status == (int)Constant.ServiceRequestStatus.Expired))
                    {
                        Status = 0;
                    }
                    var result = serviceReqRepo.GetByBuyerId(BuyerId, Status, Page).ToList();

                    requests = result.Select(i => new ServiceRequestModel
                    {
                        Id                   = i.Id,
                        Code                 = i.Code,
                        InsuranceTypeId      = i.InsuranceTypeId,
                        UserId               = i.UserId,
                        CreatedDate          = i.TimeOccured.GetAdjustedTime().ToString("yyyy-MM-dd"),
                        ClaimType            = i.ClaimType,
                        UsageType            = i.UsageType,
                        RegistrationCategory = i.RegistrationCategory,
                        VehicleNo            = i.VehicleNo,
                        VehicleValue         = i.VehicleValue,
                        VehicleYear          = i.VehicleYear,
                        IsFinanced           = i.IsFinanced,
                        Status               = i.Status,
                        FuelType             = i.FuelType ?? 0,
                        ExpiryDate           = i.TimeOccured.GetAdjustedTime().AddDays(ConfigurationHelper.DAYS_TO_EXPIRE_REQUEST).ToString("yyyy-MM-dd"),
                        QuotationList        = GetServiceQuotations(i.Id)
                    }).ToList();

                    var followUp = serviceReqRepo.GetFollowUpByBuyerId(BuyerId);
                    foreach (var sr in followUp)
                    {
                        var req = requests.Where(r => r.Id == sr.Id).FirstOrDefault();
                        if (req != null)
                        {
                            req.IsFollowUp = true;
                        }
                    }
                }
                return(Json(requests));
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(ServiceRequestController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError());
            }
        }
        public IHttpActionResult Accept(long QuotationId)
        {
            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    var repo  = new RequestQuotationRepository(context);
                    var quote = repo.GetById(QuotationId);
                    quote.Status = (int)Constant.QuotationStatus.Accepted;
                    repo.Update(quote);
                    var otherQuotes = repo.GetByRequest(quote.ServiceRequestId)?.Where(q => q.Id != quote.Id);
                    if (otherQuotes != null)
                    {
                        foreach (var q in otherQuotes)
                        {
                            q.Status = (int)Constant.QuotationStatus.Closed;
                            repo.Update(q);
                        }
                    }

                    var reqRepo   = new ServiceRequestRepository(context);
                    var userRepo  = new UserRepository(context);
                    var request   = quote.ServiceRequest;
                    var buyerName = userRepo.GetName(request.UserId);
                    reqRepo.UpdateSRStatus(request.Id, (int)Constant.ServiceRequestStatus.Closed);

                    MessageModel message = new MessageModel
                    {
                        MessageText = "Quotation accepted by: " + buyerName,
                        RequestId   = request.Id,
                        SenderId    = request.UserId,
                        RecieverId  = quote.AgentId,
                        QuotationId = 0
                    };
                    AddMessage(message, context);

                    new NotificationRepository(context).Add(
                        quote.AgentId,
                        (int)Constant.NotificationType.Accept,
                        quote.Id,
                        ConfigurationHelper.NOTIFICATION_TITLE,
                        Constant.Notification.ACCCEPTED_TEXT);
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(QuotationController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError());
            }
        }
        public IHttpActionResult GetFollowUpByAgentCount(long AgentId)
        {
            var count = 0;

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    count = new ServiceRequestRepository(context).GetFollowUpByAgentId(AgentId).Count();
                }
                return(Json(count));
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(ServiceRequestController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError());
            }
        }
        public IHttpActionResult GetByAgentId(long AgentId, int Page)
        {
            var requests = new List <ServiceRequestModel>();

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    requests = new ServiceRequestRepository(context).GetByAgentId(AgentId).
                               OrderByDescending(r => r.TimeOccured).
                               Select(
                        i => new ServiceRequestModel
                    {
                        Id                   = i.Id,
                        Code                 = i.Code,
                        InsuranceTypeId      = i.InsuranceTypeId,
                        UserId               = i.UserId,
                        CreatedDate          = i.TimeOccured.GetAdjustedTime().ToString("yyyy-MM-dd"),
                        ClaimType            = i.ClaimType,
                        UsageType            = i.UsageType,
                        RegistrationCategory = i.RegistrationCategory,
                        VehicleNo            = i.VehicleNo,
                        VehicleValue         = i.VehicleValue,
                        VehicleYear          = i.VehicleYear,
                        IsFinanced           = i.IsFinanced,
                        Status               = i.Status,
                        FuelType             = i.FuelType ?? 0,
                        Location             = i.Location == null ? String.Empty : i.Location,
                        ExpiryDate           = i.TimeOccured.GetAdjustedTime().AddDays(ConfigurationHelper.DAYS_TO_EXPIRE_REQUEST).ToString("yyyy-MM-dd"),
                        QuotationList        = GetServiceQuotations(i.Id)
                    }).ToList();
                }
                requests = requests.Skip((Page - 1) * Constant.Paging.AGENT_REQUESTS_PER_PAGE).
                           Take(Constant.Paging.AGENT_REQUESTS_PER_PAGE).ToList();
                return(Json(requests));
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(ServiceRequestController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError());
            }
        }
        public void Edit(EducationSecurityPrincipal user, ServiceRequestModel viewModel)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (viewModel == null)
            {
                throw new ArgumentNullException("viewModel");
            }
            var updatedServiceRequest = ServiceRequestRepository.Items.Include(s => s.ServiceType).
                                        Include(s => s.FulfillmentDetails).
                                        Include(s => s.Student.ApprovedProviders).
                                        Include(s => s.Student.School.UserRoles).
                                        Include("Student.StudentAssignedOfferings.ServiceOffering.Provider").
                                        SingleOrDefault(s => s.Id == viewModel.Id);

            if (updatedServiceRequest == null)
            {
                throw new EntityNotFoundException("Cannot find specified service request.");
            }
            IPermission permission = PermissionFactory.Current.Create("EditRequest", updatedServiceRequest);

            permission.GrantAccess(user);
            var currentServiceRequestFulfillment = updatedServiceRequest.FulfillmentDetails.OrderByDescending(f => f.CreateTime).FirstOrDefault();
            int currentStatusId   = currentServiceRequestFulfillment.FulfillmentStatusId;
            int?currentOfferingId = currentServiceRequestFulfillment.FulfilledById;

            viewModel.CopyTo(updatedServiceRequest);
            if (currentStatusId != viewModel.SelectedStatusId)
            {
                CreateFulfillmentDetail(updatedServiceRequest, user, viewModel);
            }
            else if (currentOfferingId != viewModel.SelectedAssignedOfferingId)
            {
                UpdateCurrentFulfillmentDetail(updatedServiceRequest, viewModel);
            }
            updatedServiceRequest.LastModifyingUser = user.Identity.User;
            updatedServiceRequest.LastModifyTime    = DateTime.Now;
            ServiceRequestRepository.Update(updatedServiceRequest);
            RepositoryContainer.Save();
        }
        public void Delete(EducationSecurityPrincipal user, int requestId)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            var serviceRequestToDelete = ServiceRequestRepository.Items.
                                         Include(s => s.ServiceType).
                                         Include(s => s.FulfillmentDetails).
                                         Include(s => s.Student.ApprovedProviders).
                                         Include(s => s.Student.School.UserRoles).
                                         SingleOrDefault(s => s.Id == requestId);

            if (serviceRequestToDelete == null)
            {
                throw new EntityNotFoundException("Service Request not found");
            }
            IPermission permission = PermissionFactory.Current.Create("DeleteRequest", serviceRequestToDelete);

            permission.GrantAccess(user);
            ServiceRequestRepository.Remove(serviceRequestToDelete);
            RepositoryContainer.Save();
        }
        public IHttpActionResult GetThreadById(long ThreadId, long UserId)
        {
            MessageThreadModel thread = null;

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    var t = new MessageThreadRepository(context).GetById(ThreadId);
                    if (t != null)
                    {
                        thread = new MessageThreadModel
                        {
                            Id        = t.Id,
                            AgentId   = t.AgentId,
                            BuyerId   = t.BuyerId,
                            RequestId = t.RequestId,
                            Date      = t.CreatedTime.GetAdjustedTime().ToString("dd/MMM"),
                            Time      = t.CreatedTime.GetAdjustedTime().ToString("HH:mm"),
                            Messages  = t.Messages.OrderBy(
                                m => m.Time).Select(m => new MessageModel
                            {
                                Id          = m.Id,
                                ThreadId    = m.ThreadId,
                                RecieverId  = m.RecieverId,
                                SenderId    = m.SenderId,
                                MessageText = m.MessageText,
                                Status      = m.Status,
                                QuotationId = m.QuotationId ?? 0,
                                Time        = m.Time.GetAdjustedTime().ToString("yyyy-MM-dd hh:mm tt")
                            }).ToList()
                        };

                        var userRepo        = new UserRepository(context);
                        var userProfileRepo = new UserProfileRepository(context);
                        var buyer           = userRepo.GetByUserId(thread.BuyerId);
                        var agent           = userRepo.GetByUserId(thread.AgentId);
                        var buyerProfile    = userProfileRepo.GetByUserId(thread.BuyerId);
                        var agentProfile    = userProfileRepo.GetByUserId(thread.AgentId);
                        var request         = new ServiceRequestRepository(context).GetById(thread.RequestId);

                        thread.AgentName = agent.Name;
                        if (agentProfile != null)
                        {
                            thread.AgentName = agentProfile.FirstName + " " + agentProfile.LastName;
                        }
                        thread.CompanyName = agent.Company.Name;
                        thread.BuyerName   = buyer.Name;
                        if (buyerProfile != null)
                        {
                            thread.BuyerName = buyerProfile.FirstName + " " + buyerProfile.LastName;
                        }

                        thread.Description   = "Vehicle No: " + request.VehicleNo + " / Request: " + request.Code;
                        thread.RequestStatus = request.Status;

                        var latestMessageWithQuote = thread.Messages.Where(
                            m => m.QuotationId > 0).OrderByDescending(m => m.Id).FirstOrDefault()?.Id;

                        thread.UnreadMessageCount = thread.Messages.Count(
                            m => m.Status == (int)Constant.MessageStatus.Initial && m.RecieverId == UserId);

                        foreach (var message in thread.Messages)
                        {
                            var sender = userRepo.GetByUserId(message.SenderId);
                            message.SenderName = sender.Name;
                            var senderProfile = userProfileRepo.GetByUserId(message.SenderId);
                            if (senderProfile != null)
                            {
                                message.SenderName = senderProfile.FirstName + " " + senderProfile.LastName;
                            }
                            if (message.QuotationId > 0)
                            {
                                thread.HasQuotation = true;
                            }

                            if (message.Id != latestMessageWithQuote)
                            {
                                message.QuotationId = 0;
                            }
                            else
                            {
                                message.MessageText = "New " + message.MessageText;
                            }
                        }

                        new MessageRepository(context).UpdateMessgesToRead(UserId, ThreadId);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(MessageController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError(ex));
            }

            return(Ok(thread));
        }
        public IHttpActionResult GetById(long Id)
        {
            ServiceRequest      request = null;
            ServiceRequestModel model   = null;
            IUser        buyer          = null;
            IUserProfile buyerProfile   = null;

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    request      = new ServiceRequestRepository(context).GetById(Id);
                    buyer        = new UserRepository(context).GetByUserId(request.UserId);
                    buyerProfile = new UserProfileRepository(context).GetByUserId(request.UserId);
                }

                if (request != null)
                {
                    model = new ServiceRequestModel
                    {
                        Id                   = request.Id,
                        Code                 = request.Code,
                        InsuranceTypeId      = request.InsuranceTypeId,
                        UserId               = request.UserId,
                        CreatedDate          = request.TimeOccured.GetAdjustedTime().ToString("yyyy-MM-dd"),
                        ClaimType            = request.ClaimType,
                        UsageType            = request.UsageType,
                        RegistrationCategory = request.RegistrationCategory,
                        VehicleNo            = request.VehicleNo,
                        VehicleValue         = request.VehicleValue,
                        VehicleYear          = request.VehicleYear,
                        IsFinanced           = request.IsFinanced,
                        Status               = request.Status,
                        FuelType             = request.FuelType ?? 0,
                        Location             = request.Location == null ? String.Empty : request.Location,
                        ExpiryDate           = request.TimeOccured.GetAdjustedTime().AddDays(ConfigurationHelper.DAYS_TO_EXPIRE_REQUEST).ToString("yyyy-MM-dd"),
                        QuotationList        = GetServiceQuotations(request.Id)
                    };

                    if (buyer != null)
                    {
                        model.BuyerName    = buyer.Name;
                        model.BuyerMobile  = buyer.UserName;
                        model.IsAllowPhone = false;

                        if (buyerProfile != null)
                        {
                            model.BuyerName  = buyerProfile.FirstName + " " + buyerProfile.LastName;
                            model.BuyerPhone = buyerProfile.Phone;
                            if (String.IsNullOrEmpty(model.Location))
                            {
                                model.Location = buyerProfile.City;
                            }
                            if (buyerProfile.ContactMethod != (int)Constant.ContactMethod.Message)
                            {
                                model.IsAllowPhone = true;
                            }
                        }
                    }
                }
                return(Json(model));
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(ServiceRequestController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError());
            }
        }
        public IHttpActionResult GetBuyerThreads(long UserId, int Page)
        {
            List <MessageThreadModel> threads = null;

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    var userThreads = new MessageThreadRepository(context).GetByBuyerId(UserId);
                    userThreads = userThreads.Skip((Page - 1) * Constant.Paging.MESSAGE_THREADS_PER_PAGE).
                                  Take(Constant.Paging.MESSAGE_THREADS_PER_PAGE).ToList();
                    threads = userThreads.Select(t => new MessageThreadModel
                    {
                        Id        = t.Id,
                        AgentId   = t.AgentId,
                        BuyerId   = t.BuyerId,
                        RequestId = t.RequestId,
                        Date      = t.CreatedTime.GetAdjustedTime().ToString("dd/MMM"),
                        Time      = t.CreatedTime.GetAdjustedTime().ToString("HH:mm"),
                        Messages  = t.Messages.OrderBy(
                            m => m.Time).Select(m => new MessageModel
                        {
                            Id          = m.Id,
                            ThreadId    = m.ThreadId,
                            RecieverId  = m.RecieverId,
                            SenderId    = m.SenderId,
                            MessageText = m.MessageText,
                            Status      = m.Status,
                            QuotationId = m.QuotationId ?? 0,
                            Time        = m.Time.GetAdjustedTime().ToString("yyyy-MM-dd HH:mm")
                        }).ToList()
                    }).ToList();

                    foreach (var thread in threads)
                    {
                        var userRepo        = new UserRepository(context);
                        var userProfileRepo = new UserProfileRepository(context);
                        var buyer           = userRepo.GetByUserId(thread.BuyerId);
                        var agent           = userRepo.GetByUserId(thread.AgentId);
                        var buyerProfile    = userProfileRepo.GetByUserId(thread.BuyerId);
                        var agentProfile    = userProfileRepo.GetByUserId(thread.AgentId);
                        var request         = new ServiceRequestRepository(context).GetById(thread.RequestId);
                        thread.AgentName = agent.Name;
                        if (agentProfile != null)
                        {
                            thread.AgentName = agentProfile.FirstName + " " + agentProfile.LastName;
                        }
                        thread.CompanyName = agent.Company.Name;
                        thread.BuyerName   = buyer.Name;
                        if (buyerProfile != null)
                        {
                            thread.BuyerName = buyerProfile.FirstName + " " + buyerProfile.LastName;
                        }

                        thread.Description        = "Vehicle No: " + request.VehicleNo + " / Request: " + request.Code;
                        thread.VehicleNo          = request.VehicleNo;
                        thread.UnreadMessageCount = thread.Messages.Count(
                            m => m.Status == (int)Constant.MessageStatus.Initial && m.RecieverId == UserId);

                        foreach (var message in thread.Messages)
                        {
                            var sender = userRepo.GetByUserId(message.SenderId);
                            message.SenderName = sender.Name;
                            var senderProfile = userProfileRepo.GetByUserId(message.SenderId);
                            if (senderProfile != null)
                            {
                                message.SenderName = senderProfile.FirstName + " " + senderProfile.LastName;
                            }
                        }
                    }

                    if (Page == 1)
                    {
                        var            promotion = new PromotionRepository(context).GetLatestPromotion(1); //TODO change the type to param
                        PromotionModel promModel = null;

                        if (promotion != null)
                        {
                            promModel = new PromotionModel
                            {
                                Id          = promotion.Id,
                                Title       = promotion.Title,
                                Header      = promotion.Header,
                                Description = promotion.Description,
                                CreatedDate = promotion.CreatedDate?.ToString(Constant.DateFormatType.YYYYMMDD),
                                Status      = promotion.Status ?? 0,
                                Type        = ((promotion.Type ?? 0) == Constant.PromotionType.OFFER) ? "Offers" : "Promotions"
                            };
                            MessageThreadModel promotionEntry = new MessageThreadModel();
                            promotionEntry.Description = promModel.Type;
                            promotionEntry.Promotion   = promModel;
                            if (threads == null)
                            {
                                threads = new List <MessageThreadModel>();
                            }
                            threads.Insert(0, promotionEntry);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(MessageController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError(ex));
            }

            return(Ok(threads));
        }
        public IHttpActionResult Test()
        {
            //ServiceRequestController.AssignRequestToAgents(5);
            //NotificationHelper.GCMNotification("ejV8j1Ife04:APA91bGctCxqnIX3xJmsWrOqnO8b_H8h8L9LFpfXQ_-Eigk-SYQko2h5E6sUge0AHSzPraQzBdQIy7UyH_I90YGB0hnB2E_6h1au_bp0OIrd6fGytuXsPWTnZCjbFDc3-pio7BkpNGbn", "Test Message");

            long ServiceRequestId = 1;

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    var companies        = new CompanyRepository(context).GetAll();
                    var request          = new ServiceRequestRepository(context).GetById(ServiceRequestId);
                    var agentServiceRepo = new AgentServiceRequestRepository(context);

                    foreach (var company in companies)
                    {
                        //Check vehicle number is recently serviced
                        var agentId          = agentServiceRepo.GetAgentIdIfServicedRecently(request.VehicleNo, company.Id);
                        var lastRequestAgent = agentServiceRepo.GetLastOpenServiceAgentIdByCompany(company.Id);

                        if (agentId == 0)
                        {
                            //get agents for each company
                            var agents = new UserRepository(context).GetAgentsByCompany(company.Id);

                            if (agents == null || agents.Count == 0)
                            {
                                continue;
                            }

                            Dictionary <long, int> counts = new Dictionary <long, int>();

                            foreach (var agent in agents)
                            {
                                //get open requests for each agent
                                var agentRequests = agentServiceRepo.GetByAgentIdForAssign(agent.Id)?.Where(
                                    r => (r.Status ?? 0) != (int)Constant.ServiceRequestStatus.Closed ||
                                    (r.Status ?? 0) != (int)Constant.ServiceRequestStatus.Expired);
                                var weight = 0;
                                if (agent.Id == lastRequestAgent)
                                {
                                    weight = 100;
                                }

                                if (agentRequests != null)
                                {
                                    counts.Add(agent.Id, agentRequests.Count() + weight);
                                }
                                else
                                {
                                    counts.Add(agent.Id, 0 + weight);
                                }
                            }

                            //find agent with min no of requests
                            //order by id asc and get top 1 agent
                            var item = counts.OrderBy(i => i.Value).ThenBy(i => i.Key).First();
                            agentId = item.Key;
                        }

                        //assign the request to agent
                        AgentServiceRequest asr = new AgentServiceRequest
                        {
                            AgentId          = agentId,
                            ServiceRequestId = ServiceRequestId,
                            Status           = (int)Constant.ServiceRequestStatus.Initial,
                            CreatedTime      = DateTime.Now.ToUniversalTime()
                        };

                        agentServiceRepo.Add(asr);

                        new NotificationRepository(context).Add(
                            asr.AgentId,
                            (int)Constant.NotificationType.Request,
                            asr.ServiceRequestId,
                            ConfigurationHelper.NOTIFICATION_TITLE,
                            Constant.Notification.NEW_REQUEST_TEXT);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(DefaultController), ex.Message, LogType.ERROR);
            }

            return(Ok());
        }
 public ServiceRequestBusiness()
 {
     serviceRequestRepository = new ServiceRequestRepository();
 }
        public IHttpActionResult GetAgentThreads(long UserId, int Page)
        {
            List <MessageThreadModel> threads = null;

            try
            {
                using (AppDBContext context = new AppDBContext())
                {
                    var userThreads = new MessageThreadRepository(context).GetByAgentId(UserId);
                    userThreads = userThreads.Skip((Page - 1) * Constant.Paging.MESSAGE_THREADS_PER_PAGE).
                                  Take(Constant.Paging.MESSAGE_THREADS_PER_PAGE).ToList();
                    threads = userThreads.Select(t => new MessageThreadModel
                    {
                        Id        = t.Id,
                        AgentId   = t.AgentId,
                        BuyerId   = t.BuyerId,
                        RequestId = t.RequestId,
                        Date      = t.CreatedTime.GetAdjustedTime().ToString("dd/MMM"),
                        Time      = t.CreatedTime.GetAdjustedTime().ToString("HH:mm"),
                        Messages  = t.Messages.OrderBy(
                            m => m.Time).Select(m => new MessageModel
                        {
                            Id          = m.Id,
                            ThreadId    = m.ThreadId,
                            RecieverId  = m.RecieverId,
                            SenderId    = m.SenderId,
                            MessageText = m.MessageText,
                            Status      = m.Status,
                            QuotationId = m.QuotationId ?? 0,
                            Time        = m.Time.GetAdjustedTime().ToString("yyyy-MM-dd HH:mm")
                        }).ToList()
                    }).ToList();

                    foreach (var thread in threads)
                    {
                        var userRepo        = new UserRepository(context);
                        var userProfileRepo = new UserProfileRepository(context);
                        var buyer           = userRepo.GetByUserId(thread.BuyerId);
                        var agent           = userRepo.GetByUserId(thread.AgentId);
                        var buyerProfile    = userProfileRepo.GetByUserId(thread.BuyerId);
                        var agentProfile    = userProfileRepo.GetByUserId(thread.AgentId);
                        var request         = new ServiceRequestRepository(context).GetById(thread.RequestId);
                        thread.AgentName = agent.Name;
                        if (agentProfile != null)
                        {
                            thread.AgentName = agentProfile.FirstName + " " + agentProfile.LastName;
                        }
                        thread.CompanyName = agent.Company.Name;
                        thread.BuyerName   = buyer.Name;
                        if (buyerProfile != null)
                        {
                            thread.BuyerName = buyerProfile.FirstName + " " + buyerProfile.LastName;
                        }

                        thread.Description        = "Vehicle No: " + request.VehicleNo + " / Request: " + request.Code;
                        thread.VehicleNo          = request.VehicleNo;
                        thread.UnreadMessageCount = thread.Messages.Count(
                            m => m.Status == (int)Constant.MessageStatus.Initial && m.RecieverId == UserId);

                        foreach (var message in thread.Messages)
                        {
                            var sender = userRepo.GetByUserId(message.SenderId);
                            message.SenderName = sender.Name;
                            var senderProfile = userProfileRepo.GetByUserId(message.SenderId);
                            if (senderProfile != null)
                            {
                                message.SenderName = senderProfile.FirstName + " " + senderProfile.LastName;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(MessageController), ex.Message + ex.StackTrace, LogType.ERROR);
                return(InternalServerError(ex));
            }

            return(Ok(threads));
        }
        private void AssignRequestToAgents(long ServiceRequestId)
        {
            try
            {
                //get all companies
                using (AppDBContext context = new AppDBContext())
                {
                    var companies        = new CompanyRepository(context).GetAll();
                    var request          = new ServiceRequestRepository(context).GetById(ServiceRequestId);
                    var agentServiceRepo = new AgentServiceRequestRepository(context);

                    foreach (var company in companies)
                    {
                        //Check vehicle number is recently serviced
                        var agentId          = agentServiceRepo.GetAgentIdIfServicedRecently(request.VehicleNo, company.Id);
                        var lastRequestAgent = agentServiceRepo.GetLastOpenServiceAgentIdByCompany(company.Id);

                        if (agentId == 0)
                        {
                            //get agents for each company
                            var agents = new UserRepository(context).GetAgentsByCompany(company.Id);

                            if (agents == null || agents.Count == 0)
                            {
                                continue;
                            }

                            Dictionary <long, int> counts = new Dictionary <long, int>();

                            foreach (var agent in agents)
                            {
                                //get open requests for each agent
                                var agentRequests = agentServiceRepo.GetByAgentIdForAssign(agent.Id)?.Where(
                                    r => (r.Status ?? 0) != (int)Constant.ServiceRequestStatus.Closed ||
                                    (r.Status ?? 0) != (int)Constant.ServiceRequestStatus.Expired);
                                var weight = 0;
                                if (agent.Id == lastRequestAgent)
                                {
                                    weight = 100;
                                }

                                if (agentRequests != null)
                                {
                                    counts.Add(agent.Id, agentRequests.Count() + weight);
                                }
                                else
                                {
                                    counts.Add(agent.Id, 0 + weight);
                                }
                            }

                            //find agent with min no of requests
                            //order by id asc and get top 1 agent
                            var item = counts.OrderBy(i => i.Value).ThenBy(i => i.Key).First();
                            agentId = item.Key;
                        }

                        //assign the request to agent
                        AgentServiceRequest asr = new AgentServiceRequest
                        {
                            AgentId          = agentId,
                            ServiceRequestId = ServiceRequestId,
                            Status           = (int)Constant.ServiceRequestStatus.Initial,
                            CreatedTime      = DateTime.Now.ToUniversalTime()
                        };

                        agentServiceRepo.Add(asr);

                        new NotificationRepository(context).Add(
                            asr.AgentId,
                            (int)Constant.NotificationType.Request,
                            asr.ServiceRequestId,
                            ConfigurationHelper.NOTIFICATION_TITLE,
                            Constant.Notification.NEW_REQUEST_TEXT);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(typeof(ServiceRequestController), ex.Message + ex.StackTrace, LogType.ERROR);
            }
        }