public async Task <ProgrammableServiceResponse> MenuProcessor()
        {
            var json = await DataBag.Get(MenuProcessorDataKey);

            var      menu = JsonConvert.DeserializeObject <Menu>(json);
            MenuItem item;

            try
            {
                var choice = Convert.ToInt16(Request.TrimmedMessage);
                if (choice == 0 && menu.ZeroItem != null)
                {
                    return(Redirect(menu.ZeroItem.Action, menu.ZeroItem.Controller));
                }

                item = menu.Items[choice - 1];
            }
            catch (Exception ex)
            {
                return(Render(string.Format("Menu choice {0} does not exist.",
                                            Request.TrimmedMessage), null, null));
            }

            await DataBag.Delete(MenuProcessorDataKey);

            return(Redirect(item.Action, item.Controller));
        }
        internal async Task <Form> GetForm()
        {
            var json = await DataBag.Get(FormProcessorDataKey);

            var form = JsonConvert.DeserializeObject <Form>(json);

            return(form);
        }
Exemple #3
0
        public async Task <ProgrammableServiceResponse> Confirmation()
        {
            try
            {
                var mobileNumber = await DataBag.Get("mobileNumber");

                var amountStr = FormData["amount"]; // you may want to validate amount

                if (!decimal.TryParse(amountStr, out var amount))
                {
                    return(await RenderResponse("Amount is not valid"));
                }

                if (amount <= decimal.Zero)
                {
                    return(await RenderResponse($"Amount is not valid"));
                }


                if (amount < 1)
                {
                    return(await RenderResponse($"Sorry, minimum amount is GHS 1.00"));
                }

                if (amount > 100)
                {
                    return(await RenderResponse($"Sorry, maximum amount is GHS 100.00"));
                }


                await DataBag.Set("amount", amount.ToString());

                var header = $"Confirmation\nService: MTN Airtime for {mobileNumber}\nAmount: {amount}";

                var menu = Menu.New(header)
                           .AddItem("Confirm", $"{nameof(ProcessAddToCart)}")
                           .AddZeroItem("Cancel", $"{nameof(Exit)}");

                var dataItems = new List <ProgrammableServicesResponseData>
                {
                    new ProgrammableServicesResponseData("Confirm", "1")
                    ,
                    new ProgrammableServicesResponseData("Cancel", "0")
                };

                if (Request.IsUssd())
                {
                    return(await RenderMenu(menu, dataItems, null, header, ProgrammableServiceDataTypes.Confirm));
                }

                return(await ProcessAddToCart());
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(await Error());
            }
        }
        /// <summary>
        /// Get Form's response data.
        /// </summary>
        /// <returns></returns>
        internal async Task <Dictionary <string, string> > GetFormData()
        {
            var json = await DataBag.Get(FormDataKey);

            try
            {
                var data = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                return(data);
            }
            catch (Exception ex)
            {
                return(new Dictionary <string, string>());
            }
        }
Exemple #5
0
        public async Task <ProgrammableServiceResponse> ProcessAddToCart()
        {
            try
            {
                var mobileNumber = await DataBag.Get("mobileNumber");

                var accountId = await DataBag.Get("mobileNumber");

                var rawAmount = await DataBag.Get("amount");

                var     rawQuantity = "1";
                var     country     = "GH";
                decimal amount      = decimal.Parse(rawAmount);
                int     quantity    = int.Parse(rawQuantity);

                //save your data into Storage so that when you get callback from Hubtel, you can
                //compare and render service
                var cartItem = new ProgrammableServicesResponseCartData($"MTN Airtime Topup for {mobileNumber}", quantity, amount, Guid.NewGuid().ToString("N"))
                {
                    ServiceData = { ["destination"] = mobileNumber, ["amount"] = $"{2m}" }
                };
                cartItem.ServiceData["destination"] = mobileNumber;
                cartItem.ServiceData["amount"]      = rawAmount;

                var checkoutMsg =
                    $"Please authorize payment for GHs {amount} as MTN Airtime Topup to {mobileNumber}";


                //any of these methods can work for redirecting a user to another controller

                //return Redirect(nameof(TestController.Index), nameof(TestController));
                // return Redirect("Index", nameof(TestController));
                //return Redirect("Index", "Test");
                // return Redirect("Index", nameof(TestController));


                return(AddToCart(checkoutMsg, cartItem));
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(await Error());
            }
        }
        public async Task <ProgrammableServiceResponse> ProcessNextPreviousPaginationActions()
        {
            var value = FormData[OnPaginationItemSelectedValue];

            var service           = JsonConvert.DeserializeObject <Dictionary <string, string> >(await DataBag.Get(PaginationCollectionKey));
            var paginationOptions = JsonConvert.DeserializeObject <PaginationOptions>(await DataBag.Get(PaginationOptionsKey));

            int page;

            if (value.StartsWith("more"))
            {
                int.TryParse(value.Substring(value.IndexOf("e",
                                                           StringComparison.Ordinal) + 1), out page);


                var form = (await PaginateCollection(service, paginationOptions))[page + 1];
                form.Data = FormData;
                return(await RenderForm(form));
            }

            if (!value.StartsWith("back"))
            {
                return(await OnPaginatedItemSelected(value));
            }

            int.TryParse(value.Substring(
                             value.IndexOf("k", StringComparison.Ordinal) + 1), out page);

            var form1 = (await PaginateCollection(service, paginationOptions))[page - 1];

            form1.Data = FormData;
            return(await RenderForm(form1));
        }
        private async Task <Form[]> PaginateCollection(Dictionary <string, string> collection, PaginationOptions paginationOptions)
        {
            var key = await DataBag.Get(OnPaginationItemSelectedName);


            var arrayTotal      = Math.Floor((decimal)collection.Count / paginationOptions.PageCount);
            var arrayTotalTopup = collection.Count % paginationOptions.PageCount; //just because we want to show 3 items at a time...


            var formarray = new Form[(int)arrayTotal + arrayTotalTopup];

            for (var i = 0; i < formarray.Length; i++)
            {
                formarray[i] = Form.New(paginationOptions.Title,
                                        nameof(ProcessNextPreviousPaginationActions));

                formarray[i].AddInput(new Input
                {
                    DisplayName = string.Empty,
                    Name        = OnPaginationItemSelectedValue
                });
            }

            for (var i = 0; i < formarray.Length; i++)
            {
                formarray[i].Inputs.Find(x => x.Name == key).Options.AddRange(
                    collection.Skip(((i * paginationOptions.PageCount)))
                    .Take(paginationOptions.PageCount).Select(x => new InputOption
                {
                    DisplayValue = x.Key,
                    Value        = x.Value,
                    Index        = paginationOptions.UseDefaultNumberListing? (collection.Keys.ToList().IndexOf(x.Key) + 1).ToString() : x.Value
                }));
            }

            for (var i = 0; i <= paginationOptions.PageCount; i++)
            {
                try
                {
                    if (formarray[i + 1].Inputs.Find(x => x.Name == key).Options.Any())
                    {
                        formarray[i].Inputs.Find(x => x.Name == key).Options.AddRange(
                            new List <InputOption> {
                            new InputOption {
                                DisplayValue = paginationOptions.NextPageDisplayText, Value = "more" + i,
                                Index        = paginationOptions.NextPageKey
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                }
            }

            for (var i = 1; i < formarray.Length; i++)
            {
                if (!formarray[i].Inputs.Find(x => x.Name == key).Options.Any())
                {
                    break;
                }

                formarray[i].Inputs.Find(x => x.Name == key).Options.AddRange(
                    new List <InputOption>
                {
                    new InputOption {
                        DisplayValue = paginationOptions.PreviousPageDisplayText, Value = "back" + i, Index = paginationOptions.PreviousPageKey
                    }
                });
            }


            return(formarray);
        }