浏览代码

add put stikers for auction

DarkGolly 4 年之前
父节点
当前提交
883a6d2f22

+ 3 - 0
CardCollector.sln.DotSettings.user

@@ -1,4 +1,7 @@
 <wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+	<s:String x:Key="/Default/Environment/AssemblyExplorer/XmlDocument/@EntryValue">&lt;AssemblyExplorer&gt;&#xD;
+  &lt;Assembly Path="C:\Users\DarkGolly\.nuget\packages\telegram.bot\17.0.0-alpha.3\lib\netcoreapp3.1\Telegram.Bot.dll" /&gt;&#xD;
+&lt;/AssemblyExplorer&gt;</s:String>
 	
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=CardCollector_002FResources_002FCommand/@EntryIndexedValue">True</s:Boolean>
 	

+ 4 - 1
CardCollector/Commands/CallbackQuery/CallbackQuery.cs

@@ -51,6 +51,8 @@ namespace CardCollector.Commands.CallbackQuery
             new CountQuery(),
             /* Команда для подтверждения покупки */
             new ConfirmBuyingQuery(),
+            /* команда для подтверждения выставления на аукцион */
+            new PutForAuctionQuery(),
             /* Команда для покупки стикера */
             new BuyStickerQuery(),
             /* Команда возврата к стикеру */
@@ -63,7 +65,8 @@ namespace CardCollector.Commands.CallbackQuery
             new DeleteCombine(),
             /* Команда удаления из комбинации */
             new CombineStickers(),
-            
+            //команда подтверждения выставления на аукцион
+            new PutForAuctionPart2Query(),
             /* Отмена в момент выбора "значения фильтра", не в самом меню */
             new BackToFiltersMenu(),
             /* Очистка чата */

+ 23 - 0
CardCollector/Commands/CallbackQuery/PutForAuctionPart2Query.cs

@@ -0,0 +1,23 @@
+using System.Threading.Tasks;
+using CardCollector.Controllers;
+using CardCollector.DataBase.Entity;
+using CardCollector.Resources;
+using Telegram.Bot.Types;
+
+namespace CardCollector.Commands.CallbackQuery
+{
+    public class PutForAuctionPart2Query:CallbackQuery
+    {
+        protected override string CommandText => Command.command_yes_on_auction;
+        public override async Task Execute()
+        {
+            await AuctionController.SellCard(User, User.Session.CoinPrice, User.Session.GemPrice);
+            await MessageController.EditMessage(User, CallbackMessageId, "Товар успешно попал на аукцион");
+
+        }
+        public PutForAuctionPart2Query(){}
+        public PutForAuctionPart2Query(UserEntity user, Update update) : base(user, update){}
+    }
+    
+    
+}

+ 28 - 0
CardCollector/Commands/CallbackQuery/PutForAuctionQuery.cs

@@ -0,0 +1,28 @@
+using System.Threading.Tasks;
+using CardCollector.Commands.Message.TextMessage;
+using CardCollector.Controllers;
+using CardCollector.DataBase.Entity;
+using CardCollector.Resources;
+using Telegram.Bot.Types;
+using Telegram.Bot.Types.ReplyMarkups;
+
+namespace CardCollector.Commands.CallbackQuery
+{
+    public class PutForAuctionQuery:CallbackQuery
+    {
+        protected override string CommandText => Command.sell_on_auction;
+        public override async Task Execute()
+        {
+            await User.ClearChat();
+            var message = await MessageController.SendMessage(User, "Введите монеты", Keyboard.CancelKeyboard);
+            EnterPriceMessage.AddToQueue(User.Id, message.MessageId);
+            
+            
+
+        }
+        
+        
+        public PutForAuctionQuery() {}
+        public PutForAuctionQuery(UserEntity user, Update update) : base(user, update) { }
+    }
+}

+ 5 - 1
CardCollector/Commands/Message/Message.cs

@@ -42,9 +42,13 @@ namespace CardCollector.Commands.Message
                 new AuctionMessage(),
                 // Ожидание ввода эмоджи
                 new EnterEmojiMessage(),
+                //Очередь воода цены на аукцион
+                new EnterPriceMessage(),
                 // Загрузка стикерпака
                 new DownloadStickerPackMessage(),
-
+                //команда ввода цены
+                new EnterPriceMessage(),
+                new EnterPricePart2Message(),
                 // Команда "Показать пример"
                 new ShowSampleMessage(),
                 // Команда "Остановить"

+ 61 - 0
CardCollector/Commands/Message/TextMessage/EnterPriceMessage.cs

@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using CardCollector.Controllers;
+using CardCollector.DataBase.Entity;
+using CardCollector.Resources;
+using Telegram.Bot.Types;
+
+namespace CardCollector.Commands.Message.TextMessage
+{
+    public class EnterPriceMessage : Message
+    {
+        protected override string CommandText => "";
+        private const string pattern = @"^[0-9]+$";
+
+        //Список пользователей, от которых ожидается ввод эмоджи ключ - id пользователя, значение - сообщение с меню #1#
+        private static readonly Dictionary<long, int> Queue = new ();
+
+        public override async Task Execute()
+        {
+            
+            var input = "" + Update.Message!
+                .Text; // это чтоб варн не показывлся, тут никогда не null, так как в Factory все уже проверено
+            /* если пользователь ввел что-то кроме эмодзи */
+            if (!Regex.IsMatch(input, pattern))
+                await MessageController.EditMessage(User, Queue[User.Id], Messages.please_enter_price,
+                    Keyboard.CancelKeyboard);
+            else
+            {
+                User.Session.CoinPrice = Convert.ToInt32(input);
+                /* Редактируем сообщение */
+                await MessageController.EditMessage(User, Queue[User.Id], "Введите алмазы", Keyboard.CancelKeyboard);
+                EnterPricePart2Message.AddToQueue(User.Id,Queue[User.Id]);
+                Queue.Remove(User.Id);
+                
+            }
+        }
+
+        //Добавляем пользователя в очередь #1#
+        public static void AddToQueue(long userId, int messageId)
+        {
+            Queue.TryAdd(userId, messageId);
+        }
+
+        //Удаляем пользователя из очереди #1#
+        public static void RemoveFromQueue(long userId)
+        {
+            Queue.Remove(userId);
+        }
+
+        // Переопределяем метод, так как команда удовлетворяет условию, если пользователь находится в очереди #1#
+        protected internal override bool IsMatches(string command)
+        {
+            return User == null ? base.IsMatches(command) : Queue.ContainsKey(User.Id);
+        }
+
+        public EnterPriceMessage() { }
+        public EnterPriceMessage(UserEntity user, Update update) : base(user, update) { }
+        }
+}

+ 62 - 0
CardCollector/Commands/Message/TextMessage/EnterPricePart2Message.cs

@@ -0,0 +1,62 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using CardCollector.Controllers;
+using CardCollector.DataBase.Entity;
+using CardCollector.Resources;
+using Telegram.Bot.Types;
+
+namespace CardCollector.Commands.Message.TextMessage
+{
+    public class EnterPricePart2Message : Message
+    {
+        private const string pattern = @"^[0-9]+$";
+        protected override string CommandText => "";
+        
+        private static readonly Dictionary<long, int> Queue = new ();
+        public override async Task Execute()
+        {
+            var input = "" + Update.Message!.Text;
+            /* если пользователь ввел что-то кроме эмодзи */
+            if (!Regex.IsMatch(input, pattern))
+                await MessageController.EditMessage(User, Queue[User.Id], Messages.please_enter_price,
+                    Keyboard.CancelKeyboard);
+            else
+            {
+                User.Session.GemPrice = Convert.ToInt32(input);
+                await MessageController.EditMessage(User, Queue[User.Id],
+                    "Подтвердите сумму" + $"{User.Session.CoinPrice}" +
+                    " Монет и" + $"{User.Session.GemPrice}" + "Алмазов",Keyboard.GetConfirmationKeyboard(Command.command_yes_on_auction));
+                Queue.Remove(User.Id);
+            }
+        }
+
+        //Добавляем пользователя в очередь #1#
+        public static void AddToQueue(long userId, int messageId)
+        {
+            Queue.TryAdd(userId, messageId);
+        }
+
+        //Удаляем пользователя из очереди #1#
+        public static void RemoveFromQueue(long userId)
+        {
+            Queue.Remove(userId);
+        }
+
+        // Переопределяем метод, так как команда удовлетворяет условию, если пользователь находится в очереди #1#
+        protected internal override bool IsMatches(string command)
+        {
+            return User == null ? base.IsMatches(command) : Queue.ContainsKey(User.Id);
+        }
+
+        public EnterPricePart2Message()
+        {
+        }
+
+        public EnterPricePart2Message(UserEntity user, Update update) : base(user, update)
+        {
+        }
+    }
+}

+ 1 - 1
CardCollector/Controllers/AuctionController.cs

@@ -18,7 +18,7 @@ namespace CardCollector.Controllers
         stickerShortHashCode - MD5 хеш представляющий собой сумму id стикера и id пользователя, используется в словаре как ключ
         price - цена за штуку
         count - количество продаваемых стикеров*/
-        private static async Task SellCard(UserEntity user, int priceCoins, int priceGems)
+        public static async Task SellCard(UserEntity user, int priceCoins, int priceGems)
         {
             /* Учитывая, что мы будем управлять кнопками + и -, то сюда никогда не поступят ложные данные
              решил метод упростить и задачу проверки переложил на взаимодействие с ботом 

+ 3 - 0
CardCollector/Others/Session.cs

@@ -71,6 +71,9 @@ namespace CardCollector.Others
         public int CombineCoinsPrice;
         public int CombineGemsPrice;
 
+        public int CoinPrice;
+        public int GemPrice;
+
         public void CalculateCombinePrice()
         {
             var coinsSum = CombineList.Values.Sum(i => 1440 / i.IncomeTime * i.IncomeCoins * i.Count);

+ 9 - 0
CardCollector/Resources/Command.Designer.cs

@@ -150,6 +150,15 @@ namespace CardCollector.Resources {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to sell_product.
+        /// </summary>
+        internal static string command_yes_on_auction {
+            get {
+                return ResourceManager.GetString("command_yes_on_auction", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to confirm_buying.
         /// </summary>

+ 3 - 0
CardCollector/Resources/Command.resx

@@ -105,4 +105,7 @@
     <data name="stop_bot" xml:space="preserve">
         <value>Остановить</value>
     </data>
+    <data name="command_yes_on_auction" xml:space="preserve">
+        <value>sell_product</value>
+    </data>
 </root>

+ 9 - 0
CardCollector/Resources/Messages.Designer.cs

@@ -294,6 +294,15 @@ namespace CardCollector.Resources {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to Пожалуйста, введите положительное целое число.
+        /// </summary>
+        internal static string please_enter_price {
+            get {
+                return ResourceManager.GetString("please_enter_price", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to Стоимость:.
         /// </summary>

+ 3 - 0
CardCollector/Resources/Messages.resx

@@ -138,4 +138,7 @@
     <data name="combined_sticker" xml:space="preserve">
         <value>Поздравляем! Вы получили стикер</value>
     </data>
+    <data name="please_enter_price" xml:space="preserve">
+        <value>Пожалуйста, введите положительное целое число</value>
+    </data>
 </root>