Search code examples
c#botframeworkverificationformflow

Adding verification step in formFlow - Check if topping is in stock


I am working on using the form flow example found Here

The example uses formFlow to help the user pick out the toppings they want on their sandwich.

I'm trying to add a verification step that checks if each of the toppings they add is in stock and if it isn't send an apology message and prompt the user to enter a different topping instead. A code example is seen below:

public static IForm<SandwichOrder> BuildForm()
{

return new FormBuilder<SandwichOrder>()
    .Message("Welcome to the sandwich order bot!")
    .Field(nameof(Sandwich))
    .Field(nameof(Length))
    .Field(nameof(Bread))
    .Field(nameof(Cheese))
    .Field(nameof(Topping),
        validate: async (state, value) =>
        {
            foreach(var t in Topping)
            {
                if (!isToppinginStock)
                {
                    // Apology message
                    //Code to ask topping question again
                }
            }


        })
    .Message("For sandwich toppings you have selected {Toppings}.")

    .Build();
   }

If anyone can help or point me in the right direction I would really appreciate it.


Solution

  • Something like the following should work for your scenerio:

    .Field(nameof(Toppings),
        validate: async (state, value) =>
        {
            var values = ((List<object>)value).OfType<ToppingOptions>();
            var notInStock = GetOutOfStockToppings(values);
    
            if(notInStock.Any())
                return new ValidateResult { IsValid = false, Value = null, Feedback = $"These are not in stock: {string.Join(",", notInStock.ToArray())} Please choose again." };
    
            return new ValidateResult { IsValid = true, Value = values};
        })
    
    static IEnumerable<ToppingOptions> NotInStock = new[] { ToppingOptions.Lettuce, ToppingOptions.Pickles };
    private static IEnumerable<ToppingOptions> GetOutOfStockToppings(IEnumerable<ToppingOptions> toppings)
    {
        List<ToppingOptions> result = new List<ToppingOptions>();
        foreach(var topping in toppings)
        {
            if (NotInStock.Contains(topping))
                result.Add(topping);
        }
        return result;
    }