Example #1
0
        public static bool UpdateUserLocation(userLocationModel requestModel)
        {
            DbGeography   userLoc = null;
            List <string> latlng  = new List <string>();

            if (!string.IsNullOrEmpty(requestModel.Cords) && requestModel.Cords != "")
            {
                latlng = requestModel.Cords.Split('_').ToList();
                if (latlng.Count == 2)
                {
                    userLoc = CommonService.ConvertLatLonToDbGeography(latlng[1], latlng[0]); // lat _ lng
                    using (var dbContext = new DeliversEntities())
                    {
                        var userlocmap = dbContext.Rider_Location_Map.FirstOrDefault(l => l.UserId == requestModel.UserId);
                        if (userlocmap == null)
                        {
                            var obj = new Rider_Location_Map
                            {
                                UserId      = requestModel.UserId,
                                Location    = userLoc,
                                LastUpdated = CommonService.GetSystemTime()
                            };
                            dbContext.Rider_Location_Map.Add(obj);
                        }
                        else
                        {
                            userlocmap.Location    = userLoc;
                            userlocmap.LastUpdated = DateTime.Now;
                        }
                        dbContext.SaveChanges();
                        return(true);
                    }
                }
            }
            return(false);
        }
        public static List <SendNotiResponseModel> SendNotification(NotificationSendModel model)
        {
            var response = new List <SendNotiResponseModel>();


            using (var dbContext = new DeliversEntities())
            {
                //#region Confirmed
                //if (model.Action == NotificationEnum.confirmed)
                //{
                //    var allDevliveryBoyes = dbContext.AspNetUsers.Where(o => o.Type == 0 && (o.Status ?? false) && (o.IsApproved ?? false)).ToList();
                //    if (allDevliveryBoyes != null && allDevliveryBoyes.Any())
                //    {
                //        model.UserIds = new List<string>();
                //        model.UserIds = allDevliveryBoyes.Select(o => o.Id.ToString()).ToList();
                //    }
                //}

                //if(model.UserIds==null || !model.UserIds.Any())
                //{
                //    var tempoRes = new SendNotiResponseModel
                //    {
                //        UserId = "0",
                //        AppId = 0000,
                //        Token = new List<string> { "NOTHING"},
                //        Response = "No active delivery boy found"
                //    };
                //    response.Add(tempoRes);
                //    return response;
                //}

                //#endregion

                foreach (var u in model.UserIds)
                {
                    var tempoRes = new SendNotiResponseModel
                    {
                        UserId   = u,
                        AppId    = model.AppId,
                        Token    = new List <string>(),
                        Response = ""
                    };

                    var tokens = new List <Token>();

                    var user = dbContext.AspNetUsers.FirstOrDefault(obj => obj.Id == u);
                    if (user != null)
                    {
                        var toks = dbContext.Tokens.Where(t => t.UserId == user.Id && t.AppId == model.AppId);
                        if (toks != null && toks.Any())
                        {
                            tokens.AddRange(toks);

                            foreach (var tok in tokens)
                            {
                                tempoRes.Token.Add(tok.Token1);
                                tempoRes.Response = SendNotiInner(model.AppId, tok.Token1, model.Text, "Testing");

                                var tempoNoti = new Notification
                                {
                                    AppId    = model.AppId,
                                    DateTime = CommonService.GetSystemTime(),
                                    Text     = model.Text + " at " + CommonService.GetSystemTime().ToLongTimeString(),
                                    UserId   = user.Id
                                };
                                dbContext.Notifications.Add(tempoNoti);
                                dbContext.SaveChanges();
                            }
                        }
                        else
                        {
                            tempoRes.Token.Add("User is valid but No Token Found for this user");
                        }
                    }
                    else
                    {
                        tempoRes.Token.Add("User is not valid");
                    }
                    response.Add(tempoRes);
                }
            }

            return(response);
        }
        private static string SendNotiInner(long appId, string token, string message, string title)
        {
            var    mId      = CommonService.GetSystemTime().Millisecond;
            var    jGcmData = new JObject();
            var    jData    = new JObject();
            var    url      = new Uri("https://fcm.googleapis.com/fcm/send");
            string auth     = null;

            if (appId == 1)  // order app
            {
                auth = "AAAA3LphIJw:APA91bGkmGxenbS_Tlli1fHbNJuYhJvhnsRf2zH1u9pa3zvAQ3mNuewN69G8MtLz6PJkJ6Ksmklo4WpBV5tGyGvue6LNMPNc9mjYv10g90Jdq8HvesE1XJP-lQNeoDIQYb__-b4oczE1";
            }
            else if (appId == 0)// delivery/rider app
            {
                auth = "AAAAZhLRgQw:APA91bGav1qNIlqd3Q7VJUZ6vjzECSqVsoB0-xBxJljlkyrTP_mq5DdwjPIUjvGMslJEKZ6NmsgqXdkJLuoejtV8oMngLA7AJ2WmCZwLPL_8uNh7r50lkdyg1Pds2yO9JriSldXqOyWo";
            }
            else if (appId == 2)// restaurant app
            {
                auth = "AAAAM2X6b1M:APA91bHxOTofAgdrqoSjXDiKnT7eHZaE5fSBLegkAKcrr8TZ4gyURyCBp3Wt2Qx4Tmd8lbaTa8JZksmDwyz6yWP7VO-Wl-5l9BDDbVw395piZ3-sWoGPC4EVV7J5BWtzwRfWQrdjptWm";
            }


            jData.Add("message", message);
            jData.Add("mid", mId);
            jData.Add("title", title);
            jGcmData.Add("to", token);

            jGcmData.Add("data", jData);
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    client.DefaultRequestHeaders.TryAddWithoutValidation(
                        "Authorization", "key=" + auth);

                    Task.WaitAll(client.PostAsync(url,
                                                  new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                                 .ContinueWith(response =>
                    {
                        var xxx = response.Result.Content.ReadAsStringAsync();
                        using (var dbContext = new DeliversEntities())
                        {
                            try
                            {
                                dbContext.Notifications.Add(new Notification
                                {
                                    AppId    = appId,
                                    DateTime = CommonService.GetSystemTime(),
                                    Text     = message,
                                    UserId   = "0beab117-d8ef-4a8e-9978-b66b35a56be5"
                                });
                                dbContext.SaveChanges();
                            }
                            catch (Exception dfd)
                            {
                            }
                        }
                        return(xxx);
                    }));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Unable to send GCM message:");
                Console.Error.WriteLine(e.StackTrace);
                return("Exception while sending notification");
            }
            return("Processing...");
        }
Example #4
0
        public static ApplyRiderResponse ApplyToOrder_ByRider(ApplyByRiderRequestmodel model)
        {
            string newStatus = "";

            using (var dbContext = new DeliversEntities())
            {
                var order = dbContext.Orders.FirstOrDefault(o => o.Id.ToString() == model.OrderId);
                if (order != null)
                {
                    //  var combinedOrders = dbContext.Orders.Where(o => o.SerialNo == order.SerialNo).ToList();
                    //  var ifSomeoneAppliedAlready = combinedOrders.Any(o => o.Status != OrderHistoryEnu.ConfirmedByRestaurant.Value);
                    var ifSomeoneAppliedAlready = order.Status != OrderHistoryEnu.ConfirmedByRestaurant.Value;
                    if (ifSomeoneAppliedAlready)
                    {
                        return(new ApplyRiderResponse
                        {
                            isSuccesss = false,
                            Message = "Order has been assigned to some other rider."
                        });
                    }

                    var notAvaialbeORders = 0;

                    var combinedOrders = new List <Order> {
                        order
                    };                                               // this one

                    foreach (var dbO in combinedOrders)
                    {
                        newStatus = OrderHistoryEnu.ConfirmedByRider.Value;
                        if (dbO.Status != OrderHistoryEnu.ConfirmedByRestaurant.Value)
                        {
                            notAvaialbeORders++;
                            continue;
                        }

                        dbO.Status    = newStatus;
                        dbO.PickedBy  = model.UserId;
                        dbO.UpdatedAt = CommonService.GetSystemTime();

                        var currentHis = dbContext.OrderHistories.FirstOrDefault(d => d.OrderId.ToString() == dbO.Id.ToString() && d.IsCurrent);
                        if (currentHis != null)
                        {
                            currentHis.IsCurrent = false;
                        }

                        dbContext.OrderHistories.Add(new OrderHistory
                        {
                            OrderId   = dbO.Id,
                            DateTime  = CommonService.GetSystemTime(),
                            Status    = newStatus,
                            IsCurrent = true
                        });
                    }
                    if (notAvaialbeORders == 0)
                    {
                        dbContext.SaveChanges();
                        notAvaialbeORders = 0;
                        // generate notifications
                        NotificationService.ProcessNotificationRequest(newStatus, order.Id);
                        return(new ApplyRiderResponse
                        {
                            isSuccesss = true,
                            Message = "Order has been assigned to you."
                        });
                    }
                    else
                    {
                        return(new ApplyRiderResponse
                        {
                            isSuccesss = false,
                            Message = "Order/part of order has been assigned to some other rider."
                        });
                    }
                }
                return(new ApplyRiderResponse
                {
                    isSuccesss = false,
                    Message = "Order does not exist."
                });
            }
        }
Example #5
0
        public static UpdateOrderResponse EditOrder_Admin(OrderLocal source)
        {
            var response = new UpdateOrderResponse {
            };

            using (var dbContext = new DeliversEntities())
            {
                var dbOrder = dbContext.Orders.FirstOrDefault(o => o.Id == source.Id);
                if (dbOrder != null)
                {
                    var canEditOrder = true;
                    #region EDIT
                    if (dbOrder.Status == OrderHistoryEnu.Deliverd.Value || dbOrder.Status == OrderHistoryEnu.PickedUp.Value)
                    {
                        canEditOrder = false;
                    }

                    #region STATUS
                    if (dbOrder.Status != source.Status)
                    {
                        var dbOrderStatus      = OrderService.GetOrderCurrentStatus(source.Id.ToString());
                        var updatedOrderStatus = OrderHistoryEnu.GetOrderStatus(source.Status);

                        if (updatedOrderStatus.Order - dbOrderStatus.Order > 1)
                        {
                            response.Status = false;
                            response.Error  = "Invalid order status";
                            return(response);
                        }

                        // UPDATE STATUS
                        ChangeOrderStatus(new ChangeOrderStatusRequesrModel {
                            OrderId   = source.Id.ToString(),
                            NewStatus = source.Status,
                            UserId    = null,
                            Comments  = source.Comments
                        });
                    }

                    #endregion

                    var newHist = new OrderHistory
                    {
                        OrderId   = dbOrder.Id,
                        DateTime  = CommonService.GetSystemTime(),
                        IsCurrent = false,
                        Status    = OrderHistoryEnu.OrderEdited.Value,
                        Comments  = source.Comments
                    };
                    var isAddHis = false;
                    var comm     = "";


                    if (!string.IsNullOrEmpty(source.Address) && source.Address.ToLower() != dbOrder.Address.ToLower())
                    {
                        if (canEditOrder)
                        {
                            comm            = "address changed from '" + dbOrder.Address + "' TO '" + source.Address + "' & ";
                            dbOrder.Address = source.Address;
                            isAddHis        = true;
                        }
                        else
                        {
                            response.Status = false;
                            response.Error  = "Can not change address in current status: " + dbOrder.Status;
                            return(response);
                        }
                    }
                    if (!string.IsNullOrEmpty(source.Instructions) && source.Instructions.ToLower() != dbOrder.Instructions.ToLower())
                    {
                        dbOrder.Instructions = source.Instructions;
                    }
                    if (!string.IsNullOrEmpty(source.PickedBy) && source.PickedBy.ToLower() != dbOrder.PickedBy.ToLower())
                    {
                        dbOrder.PickedBy = source.PickedBy;
                    }
                    if (source.DeliveryCost != dbOrder.DeliveryCost)
                    {
                        if (canEditOrder)
                        {
                            comm                 = comm + "delivery cost changed from " + dbOrder.DeliveryCost + " TO " + source.DeliveryCost + ".";
                            isAddHis             = true;
                            dbOrder.DeliveryCost = source.DeliveryCost;
                        }
                        else
                        {
                            response.Status = false;
                            response.Error  = "Can not change delivery cost in current status: " + dbOrder.Status;
                            return(response);
                        }
                    }

                    if (isAddHis)
                    {
                        newHist.Comments = comm;
                        dbContext.OrderHistories.Add(newHist);
                    }

                    dbContext.SaveChanges();
                    response.Status = true;
                    response.Error  = "";
                    return(response);

                    #endregion
                }
                else
                {
                    response.Status = false;
                    response.Error  = "Invalid order Id";
                    return(response);
                }
            }
        }
Example #6
0
        public static PlaceOrderResponseModel Place(PlaceOrderRequestModel request, string orderBy)
        {
            DbGeography userLoc       = null;
            var         orderstatus   = OrderHistoryEnu.Placed.Value;
            var         estimatedTime = "45 minutes away";
            var         orderIds      = new List <string>();

            if (!string.IsNullOrEmpty(request.Cords) && request.Cords != "")
            {
                var latlng = request.Cords.Split('_').ToList();
                if (latlng.Count == 2)
                {
                    userLoc = CommonService.ConvertLatLonToDbGeography(latlng[1], latlng[0]); // lat _ lng
                }
            }


            using (var dbContext = new DeliversEntities())
            {
                foreach (var item in request.Items)
                {
                    var dbItem = dbContext.ItemDetails.FirstOrDefault(i => i.Id == item.ItemId);
                    if (dbItem != null)
                    {
                        item.RestId = dbItem.ListItemId;
                    }
                }
            }


            var rest_groups = request.Items.GroupBy(item => item.RestId).ToList();
            var serial      = Guid.NewGuid().ToString().Substring(0, 6).ToUpper();

            using (var dbContext = new DeliversEntities())
            {
                foreach (var localG in rest_groups)
                {
                    var localList   = localG.ToList();
                    var totalAmount = localList.Sum(i => ItemDetailsService.GetItemDetailLocalById(i.ItemId).Price *i.Quantity);
                    var order       = new Order
                    {
                        Address       = request.Address,
                        Instructions  = request.Instructions,
                        Status        = orderstatus,
                        OrderBy       = orderBy,
                        Amount        = totalAmount,
                        DateTime      = CommonService.GetSystemTime(),
                        Cords         = userLoc,
                        EstimatedTime = estimatedTime,
                        SerialNo      = serial,
                        PickedBy      = Guid.Empty.ToString(),
                        UpdatedAt     = CommonService.GetSystemTime(),
                        DeliveryCost  = CommonService.GetDeliveryAmount()
                    };
                    dbContext.Orders.Add(order);

                    dbContext.OrderHistories.Add(new OrderHistory
                    {
                        OrderId   = order.Id,
                        DateTime  = CommonService.GetSystemTime(),
                        Status    = orderstatus,
                        IsCurrent = true
                    });
                    foreach (var item in localList)
                    {
                        var itmObj = new OrderDetail
                        {
                            OrderId  = order.Id,
                            ItemId   = item.ItemId,
                            Quantity = item.Quantity,
                            RestId   = item.RestId
                        };
                        dbContext.OrderDetails.Add(itmObj);
                    }
                    dbContext.SaveChanges();

                    // generate notification
                    NotificationService.ProcessNotificationRequest(orderstatus, order.Id);
                    orderIds.Add(order.Id.ToString());
                }

                return(new PlaceOrderResponseModel {
                    EstimatedTime = estimatedTime, OrderIds = orderIds, SerailNo = serial
                });
            }
        }
Example #7
0
        public static GetListResponseModel GetItemsForList(GetListRequestModel requestModel)
        {
            var   distanceFrom = 0;
            var   distanceTo   = 1000000;
            float rating       = 0;

            if (!string.IsNullOrEmpty(requestModel.DistanceFrom))
            {
                distanceFrom = Convert.ToInt16(requestModel.DistanceFrom);
            }
            if (!string.IsNullOrEmpty(requestModel.DistanceTo))
            {
                distanceTo = Convert.ToInt16(requestModel.DistanceTo);
            }
            if (!string.IsNullOrEmpty(requestModel.Rating))
            {
                rating = (float)Convert.ToDouble(requestModel.Rating);
            }

            DbGeography   userLoc = null;
            List <string> latlng  = new List <string>();

            if (!string.IsNullOrEmpty(requestModel.Cords) && requestModel.Cords != "")
            {
                latlng = requestModel.Cords.Split('_').ToList();
                if (latlng.Count == 2)
                {
                    userLoc = CommonService.ConvertLatLonToDbGeography(latlng[1], latlng[0]); // lat _ lng
                }
            }
            using (var dbContext = new DeliversEntities())
            {
                var allCats = GetCategories(true);
                if ((requestModel.IsWeb && (requestModel.TypeList == null || requestModel.TypeList.Count() == 0)) ||
                    (!requestModel.IsWeb && (requestModel.Type == -1)))
                {
                    requestModel.TypeList = new List <int>();
                    requestModel.TypeList = allCats.Select(c => (int)c.CatId).ToList();
                }
                requestModel.CurrentPage--;
                var response = new GetListResponseModel();
                var newList  = new List <ListItemLocal>();

                string searchText = null;
                if (!string.IsNullOrEmpty(requestModel.SearchTerm))
                {
                    searchText = requestModel.SearchTerm.ToLower();
                }

                var list = dbContext.ListItems.Where(item => item.Status &&
                                                     ((requestModel.IsWeb && requestModel.TypeList.Any(o => o == item.Type)) ||
                                                      (!requestModel.IsWeb && requestModel.Type == -1 && requestModel.TypeList.Any(o => o == item.Type)) ||
                                                      (item.Type == requestModel.Type && !requestModel.IsWeb))

                                                     &&
                                                     (string.IsNullOrEmpty(searchText) ||
                                                      item.Name.ToLower().Contains(searchText) ||
                                                      item.Address.ToLower().Contains(searchText) ||
                                                      item.Description.ToLower().Contains(searchText) ||
                                                      (item.ItemDetails.Any(det => det.Name.ToLower().Contains(searchText)))
                                                     )).ToList();
                if (list.Any())
                {
                    var finals = list.Select(obj => obj.MapListItem()).ToList();
                    foreach (var rest in finals)
                    {
                        var restRate = (float)Convert.ToDouble(rest.Rating);
                        var dist     = CommonService.GetDistance((double)userLoc.Latitude, (double)userLoc.Longitude, Convert.ToDouble(rest.LocationObj.Latitude), Convert.ToDouble(rest.LocationObj.Longitude));
                        if ((int)dist >= distanceFrom && (int)dist <= distanceTo && restRate >= rating)
                        {
                            var disst = Math.Round((double)dist, 2);
                            rest.LocationObj = null;
                            rest.Distance    = disst;
                            rest.Name        = rest.Name;
                            rest.TypeName    = allCats.FirstOrDefault(c => c.CatId == rest.Type).Name;
                            newList.Add(rest);
                        }
                    }
                    newList = newList.OrderBy(obj => obj.Distance).ToList();
                    var take = newList.Skip(requestModel.CurrentPage * requestModel.ItemsPerPage).
                               Take(requestModel.ItemsPerPage).ToList();
                    response.Items = take;
                }
                requestModel.CurrentPage++;
                response.ItemsPerPage = requestModel.ItemsPerPage;
                response.CurrentPage  = requestModel.CurrentPage;
                response.TotalItems   = newList.Count;
                return(response);
            }
        }