public async Task ExecuteLoadItems()
        {
            TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

            if (tokenExpManger.IsExpired())
            {
                await tokenExpManger.CloseSession();
            }
            else
            {
                if (StorePresenters.Count > 0)
                {
                    StorePresenters.Clear();
                }

                var yourStores = StoreDataStore.GetStoresFromUser(App.LogUser.UserId);

                foreach (var item in yourStores)
                {
                    var storePresenter = new StorePresenters(item);

                    StorePresenters.Add(storePresenter);
                }
            }
        }
        public ProductPresenter(OrderProduct product)
        {
            ProductName  = product.ProductName;
            ProductImg   = product.ProductImage;
            ProductId    = product.OrderProductId;
            ProductPrice = product.Price;
            Quantity     = product.Quantity;

            //ProductDescription = product.ProductDescription;


            RemoveFromCartCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    var orderProductRemovedResult = await orderProductDataStore.DeleteItemAsync(ProductId.ToString());

                    if (orderProductRemovedResult)
                    {
                        await Shell.Current.DisplayAlert("Notification", "Product Removed succefully.", "OK");

                        MessagingCenter.Send <ProductPresenter>(this, "RemoveOrderProduct");
                    }
                }
            });
        }
        async Task GoStoreControlPanel(Guid StoreId)
        {
            TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

            if (tokenExpManger.IsExpired())
            {
                await tokenExpManger.CloseSession();
            }
            else
            {
                await Shell.Current.GoToAsync($"StoreControlPanelRoute?Id={StoreId.ToString()}", animate : true);
            }
        }
Esempio n. 4
0
        async Task ExecuteLoadItems()
        {
            TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

            if (tokenExpManger.IsExpired())
            {
                await tokenExpManger.CloseSession();
            }
            else
            {
                var tokenData = new  JwtSecurityTokenHandler().ReadJwtToken(App.TokenDto.Token);
                var cardData  = await CardDataStore.GetCardDTOFromUser(App.LogUser.UserId, App.TokenDto.Token);

                foreach (var item in cardData)
                {
                    var cardPresenter = new PaymentCardPresenter(item);

                    PaymentCardPresenters.Add(cardPresenter);
                }
            }
        }
Esempio n. 5
0
        public StorePresenters(Store store)
        {
            StoreName        = store.StoreName;
            StoreId          = store.StoreId;
            StoreImg         = store.StoreImage;
            StoreDescription = store.StoreDescription;
            StoreType        = store.StoreType.ToString();

            GoHomeStoreCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    App.CurrentStore = store;
                    await GoStoreHome();
                }
            });
        }
        public async Task ExecuteLoadItemsCommand()
        {
            TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

            if (tokenExpManger.IsExpired())
            {
                await tokenExpManger.CloseSession();
            }
            else
            {
                IsBusy = true;

                try
                {
                    UserRequests.Clear();

                    var requestData = await requestDataStore.GetRequestOfUser(App.LogUser.UserId);

                    foreach (var item in requestData)
                    {
                        if (item.RequestAnswer == Answer.None)
                        {
                            var presenter = new RequestPresenter(item);

                            UserRequests.Add(presenter);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                finally
                {
                    IsBusy = false;
                }
            }
        }
        public async Task LoadItems()
        {
            LoadingManager.OnLoading();

            TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

            if (tokenExpManger.IsExpired())
            {
                await tokenExpManger.CloseSession();

                LoadingManager.OffLoading();
            }
            else
            {
                var storeData = await StoreDataStore.GetAvailableStore();

                if (!KeyValues.ContainsKey("storeAdded"))
                {
                    KeyValues.Add("storeAdded", storeData);
                }

                if (Stores.Count > 0)
                {
                    Stores.Clear();
                }

                foreach (var store in storeData)
                {
                    var storepresenter = new StorePresenters(store);

                    Stores.Add(storepresenter);
                }

                LoadingManager.OffLoading();
            }
        }
Esempio n. 8
0
        public static async Task <bool> OrderManger(ProductPresenter product)
        {
            TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

            if (tokenExpManger.IsExpired())
            {
                await tokenExpManger.CloseSession();

                return(false);
            }
            else
            {
                var ordersOfuser = orderDataStore.GetUserOrdersOfStore(App.LogUser.UserId, App.CurrentStore.StoreId);


                Order orderOfuser = ordersOfuser.Where(o => o.OrderStatus == Status.NotSubmited && o.IsDisisble == false).FirstOrDefault();


                //Crear por primera vez la orden
                if (orderOfuser == null)
                {
                    //Create a new order
                    Order order = new Order()
                    {
                        OrderId     = Guid.NewGuid(),
                        BuyerId     = App.LogUser.UserId,
                        StoreId     = App.CurrentStore.StoreId,
                        OrderType   = Library.Models.Type.None,
                        OrderDate   = DateTime.Now,
                        OrderStatus = Status.NotSubmited,
                    };

                    //Add order to DB
                    var orderadded = await orderDataStore.AddItemAsync(order);

                    //Create a new order product to the order that was created
                    OrderProduct orderProduct = new OrderProduct()
                    {
                        OrderProductId     = Guid.NewGuid(),
                        Price              = product.ProductPrice,
                        ProductName        = product.ProductName,
                        Quantity           = (int)product.Quantity,
                        BuyerId            = App.LogUser.UserId,
                        StoreId            = App.CurrentStore.StoreId,
                        OrderId            = order.OrderId,
                        ProductImage       = product.ProductImg,
                        ProductIdReference = product.ProductId
                    };

                    //Check id orderproduct exist in the order
                    var _productoExisteEnOrden = orderProductDataStore.OrderProductOfUserExistInOrder(App.LogUser.UserId, orderProduct.ProductIdReference, order.OrderId);
                    if (!_productoExisteEnOrden)
                    {
                        //Add orderproduct to order
                        var orderProductAdded = await orderProductDataStore.AddItemAsync(orderProduct);

                        if (orderProductAdded)
                        {
                            Cart.OrderProducts.Add(orderProduct);
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        var orderProducttoUpdate = orderProductDataStore.OrderProductOfUserExistOnOrder(orderProduct.ProductIdReference, order.OrderId);

                        if (orderProducttoUpdate.Quantity != orderProduct.Quantity)
                        {
                            orderProducttoUpdate.Quantity = orderProduct.Quantity;
                            var uptedResult = await orderProductDataStore.UpdateItemAsync(orderProducttoUpdate);

                            return(uptedResult);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
                else
                {
                    OrderProduct orderProduct = new OrderProduct()
                    {
                        OrderProductId     = Guid.NewGuid(),
                        Price              = product.ProductPrice,
                        ProductName        = product.ProductName,
                        Quantity           = (int)product.Quantity,
                        BuyerId            = App.LogUser.UserId,
                        StoreId            = App.CurrentStore.StoreId,
                        OrderId            = orderOfuser.OrderId,
                        ProductImage       = product.ProductImg,
                        ProductIdReference = product.ProductId
                    };

                    var _productoExisteEnOrden = orderProductDataStore.OrderProductOfUserExistInOrder(App.LogUser.UserId, orderProduct.ProductIdReference, orderOfuser.OrderId);
                    if (!_productoExisteEnOrden)
                    {
                        var orderProductAdded = await orderProductDataStore.AddItemAsync(orderProduct);

                        if (orderProductAdded)
                        {
                            Cart.OrderProducts.Add(orderProduct);
                            Cart.Total += Cart.OrderProducts.Sum(o => o.Price * o.Quantity);
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        var orderProducttoUpdate = orderProductDataStore.OrderProductOfUserExistOnOrder(orderProduct.ProductIdReference, orderOfuser.OrderId);

                        if (orderProducttoUpdate.Quantity != orderProduct.Quantity)
                        {
                            if (orderOfuser.OrderStatus == Status.NotSubmited)
                            {
                                orderProducttoUpdate.Quantity = orderProduct.Quantity;
                                var updateResult = await orderProductDataStore.UpdateItemAsync(orderProducttoUpdate);

                                if (updateResult)
                                {
                                    MessagingCenter.Send <OrderProduct>(orderProducttoUpdate, "OrderProductUpdate");
                                }
                                return(updateResult);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        public RegisterStoreViewModel()
        {
            ValidatorInitializer();
            StoreImage = ImageSource.FromFile("imgPlaceholder.jpg");
            StoreTypes = new List <string>(Enum.GetNames(typeof(StoreType)).ToList());
            #region WorkHourPresenter Initialize
            WorkHourPresenters = new ObservableCollection <WorkHourPresenter>();

            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Monday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Tuesday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Wednesday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Thursday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Friday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Saturday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Sunday.ToString()));
            #endregion

            PickPhotoCommand = new Command(async() =>
            {
                //Stream stream = await DependencyService.Get<IPickPhotoService>().GetImageStreamAsync();
                //if (stream != null)
                //{
                //    ImgArray = ConvertToByteArray(stream);
                //    StoreImage = ImageSource.FromStream(() => stream);
                //}

                try
                {
                    await CrossMedia.Current.Initialize();

                    files.Clear();

                    if (!CrossMedia.Current.IsPickPhotoSupported)
                    {
                        await Shell.Current.DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
                        return;
                    }

                    var mediOptions = new PickMediaOptions()
                    {
                        PhotoSize = PhotoSize.Full,
                    };

                    var selectedImgFile = await CrossMedia.Current.PickPhotoAsync(mediOptions);



                    if (selectedImgFile == null)
                    {
                        return;
                    }



                    ImgArray = ConvertToByteArray(selectedImgFile.GetStream());

                    StoreImage = ImageSource.FromStream(() => selectedImgFile.GetStream());
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });

            CompleteRegisterCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    List <string> valuesToCheck = new List <string>();

                    valuesToCheck.Add(StoreName);
                    valuesToCheck.Add(LicenseCode);
                    valuesToCheck.Add(StripeSecretKey);
                    valuesToCheck.Add(StripePublicKey);


                    StoreNameValidator        = ValidatorRules.EmptyOrNullValueRule(StoreName);
                    StoreDescriptionValidator = ValidatorRules.EmptyOrNullValueRule(StoreDescription);
                    LicenseCodeValidator      = ValidatorRules.EmptyOrNullValueRule(LicenseCode);

                    SkStripeValidator   = ValidatorRules.EmptyOrNullValueRule(StripeSecretKey);
                    PKeyStripeValidator = ValidatorRules.EmptyOrNullValueRule(StripePublicKey);



                    if (!StoreNameValidator.HasError && !StoreDescriptionValidator.HasError && !LicenseCodeValidator.HasError && !SkStripeValidator.HasError && !PKeyStripeValidator.HasError && GlobalValidator.CheckNullOrEmptyImage(StoreImage))
                    {
                        bool isSKKeyCorrect = StripeSecretKey.StartsWith("sk");
                        bool isPBkeyCorrect = StripePublicKey.StartsWith("pk");
                        if (isSKKeyCorrect || isSKKeyCorrect)
                        {
                            Guid licenseCodeGuid = Guid.Parse(LicenseCode);
                            var licenseResult    = storeLicenseDataStore.StoreLicenseExists(licenseCodeGuid);

                            if (licenseResult)
                            {
                                var licenseIsInUsed = await storeLicenseDataStore.IsLicenseInUsed(LicenseCode);
                                if (!licenseIsInUsed)
                                {
                                    StoreType value;
                                    Enum.TryParse(StoreTypeSelected, out value);

                                    var newStoreRegister = new Store()
                                    {
                                        StoreId                = Guid.NewGuid(),
                                        StoreName              = StoreName,
                                        UserId                 = App.LogUser.UserId,
                                        StoreImage             = ImgArray,
                                        StoreType              = value,
                                        StoreRegisterLicenseId = licenseCodeGuid,
                                        StoreDescription       = StoreDescription,
                                        SKKey = StripeSecretKey,
                                        PBKey = StripePublicKey,
                                    };

                                    List <WorkHour> workHours = new List <WorkHour>();

                                    foreach (var item in WorkHourPresenters)
                                    {
                                        var workHour = new WorkHour()
                                        {
                                            CloseTime  = Convert.ToDateTime(item.Close.ToString()),
                                            Day        = item.Day,
                                            OpenTime   = Convert.ToDateTime(item.Open.ToString()),
                                            WorkHourId = Guid.NewGuid(),
                                            StoreId    = newStoreRegister.StoreId
                                        };

                                        workHours.Add(workHour);
                                    }

                                    newStoreRegister.WorkHours = workHours;

                                    var storeaddedResult = await StoreDataStore.AddItemAsync(newStoreRegister);

                                    if (storeaddedResult)
                                    {
                                        var licenceUpdateResult = await storeLicenseDataStore.UpdateLicenceInCode(licenseCodeGuid);

                                        if (licenceUpdateResult)
                                        {
                                            await Shell.Current.DisplayAlert("Notification", "Store Added...!", "OK");
                                        }
                                    }
                                }
                                else
                                {
                                    await Shell.Current.DisplayAlert("Notification", "This License is in used.", "OK");
                                }
                            }
                            else
                            {
                                await Shell.Current.DisplayAlert("Notification", "License Code Incorrect", "OK");
                            }
                        }
                        else
                        {
                            await Shell.Current.DisplayAlert("Notification", "Srtipe Secret Key or Public Key are set in incorrect entry check again.", "OK");
                        }
                    }
                    else
                    {
                        await Shell.Current.DisplayAlert("Notification", "Some fields are empty", "OK");
                    }
                }
            });
        }
        public async Task LoadDifferentItems()
        {
            LoadingManager.OnLoading();

            TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

            if (tokenExpManger.IsExpired())
            {
                await tokenExpManger.CloseSession();

                LoadingManager.OffLoading();
            }
            else
            {
                if (!KeyValues.ContainsKey("storeAdded"))
                {
                    await LoadItems();
                }
                else
                {
                    var storeData = await StoreDataStore.GetDifferentStore(KeyValues["storeAdded"]);

                    if (storeData != null)
                    {
                        var tempData = new List <Store>();


                        foreach (var item in KeyValues["storeAdded"])
                        {
                            if (!tempData.Any(s => s.StoreId == item.StoreId))
                            {
                                tempData.Add(item);
                            }
                        }

                        foreach (var item in storeData)
                        {
                            if (!tempData.Any(s => s.StoreId == item.StoreId))
                            {
                                tempData.Add(item);
                            }
                        }


                        KeyValues.Clear();
                        KeyValues.Add("storeAdded", tempData);

                        foreach (var item in KeyValues["storeAdded"])
                        {
                            if (!Stores.Any(s => s.StoreId == item.StoreId))
                            {
                                var storepresenter = new StorePresenters(item);


                                Stores.Add(storepresenter);
                            }
                        }
                    }
                }



                LoadingManager.OffLoading();
            }
        }
        public RegisterCardViewModel()
        {
            PropertiesInitializer();


            CompleteRegisterCardCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    HolderNameValidator = ValidatorRules.EmptyOrNullValueRule(HolderName);
                    CardNumberValidator = ValidatorRules.EmptyOrNullValueRule(CardNumber);
                    YearValidator       = ValidatorRules.EmptyOrNullValueRule(Year);
                    MonthVaidator       = ValidatorRules.EmptyOrNullValueRule(Month);
                    CVCValidator        = ValidatorRules.EmptyOrNullValueRule(CVC);


                    if (!HolderNameValidator.HasError && !CardNumberValidator.HasError && !YearValidator.HasError && !MonthVaidator.HasError && !CVCValidator.HasError)
                    {
                        try
                        {
                            var cardData = new PaymentCard()
                            {
                                CardNumber    = CardNumber,
                                Cvc           = CVC,
                                HolderName    = HolderName,
                                Month         = Month,
                                Year          = Year,
                                PaymentCardId = Guid.NewGuid(),
                                UserId        = App.LogUser.UserId
                            };

                            var cardserviceResult = await stripeServiceDS.InsertStripeCardToStripeUser(cardData, App.LogUser.StripeUserId);

                            if (!cardserviceResult.HasError)
                            {
                                cardData.StripeCardId = cardserviceResult.TokenId;
                                var result            = await CardDataStore.AddItemAsync(cardData);

                                if (result)
                                {
                                    await Shell.Current.DisplayAlert("Notification", "Card succefully added.", "OK");
                                }
                            }
                            else
                            {
                                await Shell.Current.DisplayAlert("Notification", cardserviceResult.ErrorMsg, "OK");
                            }
                        }
                        catch (Exception e)
                        {
                            await Shell.Current.DisplayAlert("Notification", e.Message, "OK");
                        }
                    }
                }
            });
        }
        public GetLicenceViewModel()
        {
            GetLicenseCommand = new Command <string>(async(arg) =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    var result = await Shell.Current.DisplayAlert("Notification", "Your are going to get a store license.For the cost $100 by month. Are you OK with that?", "Yes", "No");

                    if (result)
                    {
                        var cardResult = await CardDataStore.GetCardFromUser(App.LogUser.UserId, App.TokenDto.Token);

                        if (cardResult != null && cardResult.Count() > 0)
                        {
                            //Make the Payment transation here...

                            //Check that the payment was submited.

                            //Send Lincese Code

                            var subcriptionToken = await stripeServiceDS.CreateACustomerSubcription(App.LogUser.StripeUserId);

                            if (!string.IsNullOrEmpty(subcriptionToken))
                            {
                                var subcription = new Library.Models.Subcription()
                                {
                                    StripeCustomerId    = App.LogUser.StripeUserId,
                                    StripeSubCriptionID = subcriptionToken,
                                    //StoreLicense = StoreControlPanelViewModel.YourSelectedStore.StoreLicenceId
                                };

                                var subcriptionResult = await SubcriptionDataStore.AddItemAsync(subcription);

                                if (subcriptionResult)
                                {
                                    var licenseReuslt = await storeLicenseDataStore.PostStoreLicense(App.LogUser.Email, App.LogUser.Name);

                                    if (licenseReuslt)
                                    {
                                        await App.Current.MainPage.DisplayAlert("Notification", "License added succefully.", "OK");
                                    }
                                }
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Notification", "The subcription could not be made. Try again.", "OK");
                            }
                        }
                        else
                        {
                            await App.Current.MainPage.DisplayAlert("Notification", "You dont have a card register, register a card first.", "OK");
                        }
                    }
                }
            });
        }
        public ProductPresenter(Product product)
        {
            ProductName        = product.ProductName;
            ProductImg         = product.ProductImage;
            ProductId          = product.ProductId;
            ProductPrice       = product.Price;
            ItemLeft           = product.InventoryQuantity;
            ProductType        = product.Type.ToString();
            ProductDescription = product.ProductDescription;

            Quantity = 0;

            AddToCartCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    if (ItemLeft > 0)
                    {
                        if (Quantity > 0)
                        {
                            int left = ItemLeft - (int)Quantity;

                            if (Quantity <= ItemLeft)
                            {
                                await Cart.OrderManger(this);
                            }
                            else
                            {
                                await Shell.Current.DisplayAlert("Notification", "Item dont have to many in stock selecte a less quantity.", "OK");
                            }



                            #region OrderManger
                            //               var userhaveorder =  orderDataStore.HaveOrder(App.LogUser.UserId, App.CurrentStore.StoreId);

                            //if (userhaveorder == null)
                            //{
                            //	Order order = new Order()
                            //	{
                            //		OrderId = Guid.NewGuid(),
                            //		BuyerId = App.LogUser.UserId,
                            //		StoreId = App.CurrentStore.StoreId,
                            //		OrderType = Library.Models.Type.None,
                            //		OrderDate = DateTime.Today,
                            //		OrderStatus = Status.NotSubmited,


                            //	};

                            //	var orderadded = await orderDataStore.AddItemAsync(order);

                            //	OrderProduct orderProduct = new OrderProduct()
                            //	{
                            //		OrderProductId = Guid.NewGuid(),
                            //		Price = ProductPrice,
                            //		ProductName = ProductName,
                            //		Quantity = (int)Quantity,
                            //		BuyerId = App.LogUser.UserId,
                            //		StoreId = App.CurrentStore.StoreId,
                            //		OrderId = order.OrderId,
                            //		ProductImage = ProductImg
                            //	};

                            //	var result = orderProductDataStore.OrderProductOfUserExist(App.LogUser.UserId, orderProduct.ProductName);
                            //	if (result == false)
                            //	{

                            //		var orderProductAdded = await orderProductDataStore.AddItemAsync(orderProduct);

                            //		if (orderProductAdded)
                            //		{
                            //			Cart.OrderProducts.Add(orderProduct);
                            //		}
                            //	}
                            //	else
                            //	{

                            //		var toupdate = orderProductDataStore.OrderProductOfUserExistWith(ProductName);

                            //		if (toupdate.Quantity != orderProduct.Quantity)
                            //		{

                            //			toupdate.Quantity = orderProduct.Quantity;
                            //			var uptedResult = await orderProductDataStore.UpdateItemAsync(toupdate);
                            //		}
                            //	}

                            //}
                            //else
                            //{

                            //	OrderProduct orderProduct = new OrderProduct()
                            //	{
                            //		OrderProductId = Guid.NewGuid(),
                            //		Price = ProductPrice,
                            //		ProductName = ProductName,
                            //		Quantity = (int)Quantity,
                            //		BuyerId = App.LogUser.UserId,
                            //		StoreId = App.CurrentStore.StoreId,
                            //		 OrderId = userhaveorder.OrderId,
                            //		ProductImage = ProductImg
                            //	};

                            //	var result = orderProductDataStore.OrderProductOfUserExist(App.LogUser.UserId, orderProduct.ProductName);
                            //	if (result == false)
                            //	{

                            //		var orderProductAdded = await orderProductDataStore.AddItemAsync(orderProduct);

                            //		if (orderProductAdded)
                            //		{
                            //			Cart.OrderProducts.Add(orderProduct);
                            //			Cart.Total += Cart.OrderProducts.Sum(o => o.Price * o.Quantity);
                            //		}
                            //	}
                            //	else
                            //	{

                            //		var toupdate = orderProductDataStore.OrderProductOfUserExistWith(ProductName);

                            //		if (toupdate.Quantity != orderProduct.Quantity)
                            //		{

                            //			toupdate.Quantity = orderProduct.Quantity;
                            //			var uptedResult = await orderProductDataStore.UpdateItemAsync(toupdate);
                            //		}
                            //	}
                            //}
                            #endregion
                        }
                        else
                        {
                            await Shell.Current.DisplayAlert("Notification", "Quantiy selected is 0.", "OK");
                        }
                    }
                    else
                    {
                        await Shell.Current.DisplayAlert("Notification", "There are no products.", "OK");
                    }
                }
            });



            DeleteCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    var answer = await Shell.Current.DisplayAlert("Notification", "Are you sure that you want to delete this item?", "Yes", "No");

                    if (answer)
                    {
                        var result = await productDataStore.DeleteItemAsync(this.ProductId.ToString());

                        if (result)
                        {
                            MessagingCenter.Send <ProductPresenter>(this, "DeleteProductInventory");
                        }
                    }
                }
            });

            EditCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync($"{EditProductPage.Route}?pId={ProductId.ToString()}", animate: true);
                }
            });
        }
        public UserDetailOrderViewModel()
        {
            ProductPresenters = new ObservableCollection <ProductPresenter>();

            OrderDetail        = SelectedOrder.CurrentOrder;
            OrderStatus        = OrderDetail.OrderStatus.ToString();
            OrderQuantity      = OrderDetail.OrderProducts.Count();
            isDeliveryFeeAdded = false;

            if (OrderDetail.OrderStatus == Status.Submited || OrderDetail.OrderStatus == Status.Completed)
            {
                AreVisible = false;
            }
            else
            {
                AreVisible = true;
            }

            SetProducts();

            IspickUp        = true;
            CheckoutCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);

                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    var cardofUser = await CardDataStore.GetCardFromUser(App.LogUser.UserId, App.TokenDto.Token);

                    App.LogUser.PaymentCards = new List <PaymentCard>(cardofUser);

                    if (App.LogUser.PaymentCards.Count() > 0)
                    {
                        if (OrderDetail.OrderStatus == Status.NotSubmited)
                        {
                            if (IsDelivery)
                            {
                                OrderDetail.OrderType = Library.Models.Type.Delivery;
                            }
                            if (IspickUp)
                            {
                                OrderDetail.OrderType = Library.Models.Type.PickUp;
                            }

                            if (!IsDelivery && !IspickUp)
                            {
                                OrderDetail.OrderType = Library.Models.Type.PickUp;
                            }

                            OrderDetail.OrderStatus = Status.Submited;

                            //List<PaymentCard> paymentCards = new List<PaymentCard>(App.LogUser.PaymentCards);

                            var customercardId = await stripeServiceDS.GetCustomerCardId(App.LogUser.StripeUserId, App.LogUser.PaymentCards.FirstOrDefault().StripeCardId);

                            var isTransactionSuccess = await stripeServiceDS.MakePaymentWithCard(OrderDetail.StoreId, Total, App.LogUser.PaymentCards.FirstOrDefault().PaymentCardId, OrderDetail.OrderId.ToString());

                            if (isTransactionSuccess)
                            {
                                var orderUpdate = await orderDataStore.UpdateItemAsync(OrderDetail);

                                OrderStatus = OrderDetail.OrderStatus.ToString();

                                if (orderUpdate)
                                {
                                    var orderNotificationToEmployees = await userConnectedDataStore.SendOrdersToEmployees(OrderDetail.StoreId.ToString(), OrderDetail.OrderId.ToString());

                                    //await App.ComunicationService.OrderToPrepare(OrderDetail);

                                    await App.Current.MainPage.DisplayAlert("Notification", "Order was submited...!", "OK");

                                    MessagingCenter.Send <Library.Models.Order>(OrderDetail, "RemoveOrderSubtmitedMsg");
                                }
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Notification", "Bad Transaction.", "OK");
                            }
                        }
                        else
                        {
                            await App.Current.MainPage.DisplayAlert("Notification", "Order was submited.", "OK");
                        }
                    }
                    else
                    {
                        await App.Current.MainPage.DisplayAlert("Notification", "You dont have a card register, register a card first.", "OK");
                    }
                }
            });

            CalculateTotal();

            MessagingCenter.Subscribe <ProductPresenter>(this, "RemoveOrderProduct", async(obj) =>
            {
                ProductPresenters.Remove(obj);

                var _orderProductToRemove = OrderDetail.OrderProducts.Where(o => o.OrderProductId == obj.ProductId).FirstOrDefault();

                OrderDetail.OrderProducts.Remove(_orderProductToRemove);

                OrderQuantity = OrderDetail.OrderProducts.Count();

                if (OrderDetail.OrderProducts.Count() == 0)
                {
                    var result = await orderDataStore.DeleteItemAsync(OrderDetail.OrderId.ToString());

                    if (result)
                    {
                        await Shell.Current.GoToAsync($"../StoreOrderRoute");
                    }
                }
                CalculateTotal();
            });
            MessagingCenter.Subscribe <OrderProduct>(this, "OrderProductUpdate", async(obj) =>
            {
                var oproductToRemove = ProductPresenters.Where(op => op.ProductId == obj.OrderProductId).FirstOrDefault();

                ProductPresenters.Remove(oproductToRemove);

                var updatedOrderProductPrensenter = new ProductPresenter(obj);

                if (OrderDetail.OrderStatus == Status.Submited || OrderDetail.OrderStatus == Status.Completed)
                {
                    updatedOrderProductPrensenter.AreVisible = false;
                }
                else
                {
                    updatedOrderProductPrensenter.AreVisible = true;
                }
                ProductPresenters.Add(updatedOrderProductPrensenter);

                CalculateTotal();
            });
        }
Esempio n. 15
0
        public SettingViewModel()
        {
            #region UserInformaation Initialize
            Fullname        = App.LogUser.Name;
            Email           = App.LogUser.Email;
            Address         = App.LogUser.Address;
            Phone           = App.LogUser.Phone;
            GenderSelected  = App.LogUser.Gender.ToString();
            UserInformation = App.LogUser;
            #endregion

            Genders = new List <string>(Enum.GetNames(typeof(Gender)).ToList());

            GoUserInformationCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync("UserInformationRoute", true);
                }
            });

            UpdateProfileCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync("UpdateProfileRoute", true);
                    MessagingCenter.Send <User>(App.LogUser, "UserInformation");
                }
            });

            GoPaymentCardCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync($"{YourCardsPage.Route}", true);
                }
            });


            RegisterStoreCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync("GetLicensenStoreRoute", true);
                }
            });

            AlreadyHaveLicenseCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync("RegisterStoreRoute", true);
                }
            });



            LogOutCommand = new Command(async() =>
            {
                await App.ComunicationService.Disconnect();


                if (App.UsersConnected != null)
                {
                    App.UsersConnected.IsDisable = true;
                    var result = await userConnectedDataStore.UpdateItemAsync(App.UsersConnected);

                    if (result)
                    {
                        App.UsersConnected = null;
                    }
                }
                await Shell.Current.GoToAsync("../LoginRoute");
            });

            GoRegisterCardCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync("RegisterCardRoute");
                }
            });

            GoGetLicenseCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync("StoreLicenseRoute");
                }
            });

            GoCheckYourStores = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    await Shell.Current.GoToAsync($"{YourStoresPage.Route}");
                }
            });
        }