Procházet zdrojové kódy

[Telegram] Tried to make item names unique

Slava Barinov před 1 rokem
rodič
revize
0e4bb842eb
1 změnil soubory, kde provedl 80 přidání a 89 odebrání
  1. 80 89
      src/telegram.rs

+ 80 - 89
src/telegram.rs

@@ -316,24 +316,34 @@ fn format_categories(catitems: &HashMap<String, String>) -> String {
 }
  */
 
-/// TODO: Fix the item as unique id. Need to add an identifier
 fn create_categories_keyboard(catitems: &HashMap<String, String>) -> InlineKeyboardMarkup {
     let mut keyboard = InlineKeyboardMarkup::default(); // Use default to initialize
-    let mut buttons = Vec::new();
 
-    for (item, category) in catitems.iter() {
-        let button_text = format!("{}: {}", item, category);
-        let callback_data = format!("edit_{}", item); // Assuming `item` is a unique identifier
+    for (index, (item, category)) in catitems.iter().enumerate() {
+        let parts: Vec<&str> = category.split(':').collect();
+        let shortened_category = if parts.len() > 1 {
+            parts[..parts.len() - 1]
+                .iter()
+                .map(|&part| {
+                    part.chars()
+                        .next()
+                        .unwrap_or_default()
+                        .to_uppercase()
+                        .collect::<String>()
+                })
+                .chain(std::iter::once(parts.last().unwrap().to_string()))
+                .collect::<Vec<String>>()
+                .join(":")
+        } else {
+            category.clone()
+        };
 
-        // Create a button and push it to the row
-        let button = InlineKeyboardButton::callback(button_text, callback_data);
-        buttons.push(button); // Add button to the current row
+        let button_text = format!("{}: {}", item, shortened_category);
+        let callback_data = format!("edit_{}_{}", item, index);
 
-        // Assuming you want each button in its own row for simplicity
-        keyboard = keyboard.append_row(buttons.clone());
-        buttons.clear(); // Clear the vector for the next iteration
+        let button = InlineKeyboardButton::callback(button_text, callback_data);
+        keyboard = keyboard.append_row(vec![button]);
     }
-
     keyboard
 }
 
@@ -693,89 +703,70 @@ async fn handle_qif_ready(
 }
 
 async fn callback_handler(q: CallbackQuery, bot: Bot, dialogue: QIFDialogue) -> HandlerResult {
-    if let Some(version) = q.data {
-        if version.starts_with("edit_") {
-            let item_id = version.strip_prefix("edit_").unwrap(); // Extract the item ID or number
-
-            dialogue
-                .update(State::NewJson {
-                    filename: String::new(),
-                })
-                .await?;
-
-            // Process the selection, e.g., by updating the dialogue state or responding to the user
-            let response_message = format!("Editing item {}", item_id);
-            if let Some(chat_id) = q.message.clone().map(|msg| msg.chat.id) {
-                bot.send_message(chat_id, response_message).await?;
+    if let Some(data) = q.data {
+        if data.starts_with("edit_") {
+            let data = data.strip_prefix("edit_").unwrap();
+            let parts: Vec<&str> = data.split('_').collect();
+
+            if parts.len() == 2 {
+                let item = parts[0].to_string(); // Convert item to String
+                let index = parts[1]; // Index is parsed but not used further in this snippet
+
+                dialogue
+                    .update(State::NewJson {
+                        filename: String::new(),
+                    })
+                    .await?;
+
+                let response_message = format!("Editing item {}: {}", item, index);
+                if let Some(chat_id) = q.message.clone().map(|msg| msg.chat.id) {
+                    bot.send_message(chat_id, response_message).await?;
+                }
             }
         }
 
-        let text = format!("You chose: {}", version);
-
-        match q.message {
-            Some(Message { id, chat, .. }) => {
-                bot.edit_message_text(chat.id, id, text.clone()).await?;
-                let state = dialogue.get().await?;
-                if let Some(data) = state {
-                    log::info!("Data: {}", data);
-                    if let State::SubCategorySelect {
-                        filename,
-                        item,
-                        category: _,
-                        mut items_left,
-                        mut items_processed,
-                    } = data
-                    {
-                        log::info!("SubCategory match!");
-                        bot.send_message(
-                            chat.id,
-                            format!("Item {} is ready for caterogy {}", item, version),
-                        )
+        let text = format!("You chose: {}", data);
+        if let Some(Message { id, chat, .. }) = q.message {
+            bot.edit_message_text(chat.id, id, text.clone()).await?;
+            let state = dialogue.get().await?;
+            if let Some(State::SubCategorySelect {
+                filename,
+                item,
+                category: _,
+                mut items_left,
+                mut items_processed,
+            }) = state
+            {
+                items_processed.insert(item, data.to_string()); // Ensure the correct type is inserted
+                if let Some(newitem) = items_left.pop() {
+                    bot.send_message(chat.id, format!("Input category to search for {}", newitem))
+                        .await?;
+                    dialogue
+                        .update(State::CategorySelect {
+                            filename,
+                            item: newitem,
+                            items_left,
+                            items_processed,
+                        })
+                        .await?;
+                } else {
+                    bot.send_message(chat.id, "This was the last item!").await?;
+                    bot.send_message(chat.id, "Items are categorized and categories are updated")
+                        .await?;
+                    // Assuming create_categories_keyboard is defined elsewhere and correctly processes items_processed
+                    bot.send_message(chat.id, "Enter the memo line").await?;
+                    dialogue
+                        .update(State::Ready {
+                            filename,
+                            item_categories: items_processed,
+                        })
                         .await?;
-                        items_processed.insert(item, version);
-                        if let Some(newitem) = items_left.pop() {
-                            bot.send_message(
-                                chat.id,
-                                format!("Input category to search for {}", newitem),
-                            )
-                            .await?;
-                            dialogue
-                                .update(State::CategorySelect {
-                                    filename,
-                                    item: newitem,
-                                    items_left,
-                                    items_processed,
-                                })
-                                .await?;
-                        } else {
-                            bot.send_message(chat.id, "This was the last item!".to_string())
-                                .await?;
-                            bot.send_message(
-                                chat.id,
-                                "Items are categorized and categories are updated".to_string(),
-                            )
-                            .reply_markup(create_categories_keyboard(&items_processed))
-                            .await?;
-
-                            bot.send_message(chat.id, "Enter the memo line".to_string())
-                                .await?;
-                            dialogue
-                                .update(State::Ready {
-                                    filename,
-                                    item_categories: items_processed,
-                                })
-                                .await?;
-                        }
-                    } else {
-                        log::info!("No SubCategory match!");
-                    }
-                }
-            }
-            None => {
-                if let Some(id) = q.inline_message_id {
-                    bot.edit_message_text_inline(id, text).await?;
                 }
+            } else {
+                log::info!("No SubCategory match!");
             }
+        } else if let Some(id) = q.inline_message_id {
+            bot.edit_message_text_inline(id, text).await?;
         }
     }