public async Task <ActionResult <List <LeadViewModel> > > ListLeads(bool allLeads, string status, string sortBy, CancellationToken ct)
        {
            var  loggedUserQuery = new LoggedUserQuery();
            User user            = await Mediator.Send(loggedUserQuery);

            var listLeadsData = new ListLeadsQuery(user.Id, user.Level, allLeads, status, sortBy);
            var list          = await Mediator.Send(listLeadsData);

            return(Mapper.Map <List <Lead>, List <LeadViewModel> >(list));
        }
        public async Task <List <Lead> > Handle(ListLeadsQuery request, CancellationToken cancellationToken)
        {
            IQueryable <UserContact> userContacts = null;
            IQueryable <Order>       orders       = null;
            List <Lead> data = new List <Lead>();

            //query for leads (contacts with other than inactive status) which belong to logged user if user is not an admin, otherwise query all contacts
            if (request.UserLevel != "top")
            {
                userContacts = _context.UserContacts.Where(x => x.User.Id == request.UserId && x.Contact.Status != "Inactive");
            }
            else
            {
                userContacts = _context.UserContacts.Where(x => x.Contact.Status != "Inactive");
            }

            //don't proceed and return empty list if there are no leads
            if (userContacts == null)
            {
                return(new List <Lead>());
            }

            orders = _context.Orders.Where(x => x.Closed == false);

            if (request.AllLeads == false)
            {
                userContacts = filterLeads(userContacts, request.Status);
            }

            foreach (UserContact userContact in userContacts)
            {
                if (userContact.Contact.CurrentSale.Count() > 0)
                {
                    Order order = null;

                    if (userContact.Contact.CurrentSale.Last().OrderId != null)
                    {
                        order = await _context.Orders.FindAsync(new Guid(userContact.Contact.CurrentSale.Last().OrderId));
                    }

                    data.Add(new Lead
                    {
                        Contact           = userContact.Contact,
                        Order             = order,
                        LastOperationDate = userContact.Contact.CurrentSale.Last().Operation.Date
                    });
                }
                else
                {
                    data.Add(new Lead
                    {
                        Contact = userContact.Contact,
                        Order   = null,
                    });
                }
            }

            data = sortLeads(data, request.SortBy);

            return(data);
        }