Skip to content

Commit

Permalink
add allergens on/off support
Browse files Browse the repository at this point in the history
this requires adding a new column to the registrations table since there are no migrations yet
  • Loading branch information
greybaron committed Oct 10, 2024
1 parent 3f8d6e5 commit 747677f
Show file tree
Hide file tree
Showing 11 changed files with 161 additions and 75 deletions.
34 changes: 17 additions & 17 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "stuwe-telegram-rs"
version = "1.8.0"
version = "1.9.0"
edition = "2021"
default-run = "stuwe-telegram-rs"

Expand Down
5 changes: 3 additions & 2 deletions src/bin/mensi-telegram-bin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use stuwe_telegram_rs::data_backend::mm_parser::get_mensen;
use stuwe_telegram_rs::data_types::CampusDualData;

use stuwe_telegram_rs::bot_command_handlers::{
change_mensa, day_cmd, invalid_cmd, reply_time_dialogue, show_different_mensa, start,
start_time_dialogue, subscribe, unsubscribe,
allergene, change_mensa, day_cmd, invalid_cmd, reply_time_dialogue, show_different_mensa,
start, start_time_dialogue, subscribe, unsubscribe,
};
use stuwe_telegram_rs::constants::{
BACKEND, CD_DATA, DB_FILENAME, MENSI_DB, OLLAMA_HOST, OLLAMA_MODEL, USER_REGISTRATIONS,
Expand Down Expand Up @@ -137,6 +137,7 @@ fn schema() -> UpdateHandler<Box<dyn std::error::Error + Send + Sync + 'static>>
.branch(dptree::case![Command::Subscribe].endpoint(subscribe))
.branch(dptree::case![Command::Unsubscribe].endpoint(unsubscribe))
.branch(dptree::case![Command::Mensa].endpoint(change_mensa))
.branch(dptree::case![Command::Allergene].endpoint(allergene))
.branch(dptree::case![Command::Uhrzeit].endpoint(start_time_dialogue));

let message_handler = Update::filter_message()
Expand Down
5 changes: 3 additions & 2 deletions src/bin/stuwe-telegram-bin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
use stuwe_telegram_rs::data_types::CampusDualData;

use stuwe_telegram_rs::bot_command_handlers::{
change_mensa, day_cmd, invalid_cmd, reply_time_dialogue, show_different_mensa, start,
start_time_dialogue, subscribe, unsubscribe,
allergene, change_mensa, day_cmd, invalid_cmd, reply_time_dialogue, show_different_mensa,
start, start_time_dialogue, subscribe, unsubscribe,
};
use stuwe_telegram_rs::constants::{
API_URL, BACKEND, CD_DATA, DB_FILENAME, OLLAMA_HOST, OLLAMA_MODEL, STUWE_DB, USER_REGISTRATIONS,
Expand Down Expand Up @@ -145,6 +145,7 @@ fn schema() -> UpdateHandler<Box<dyn std::error::Error + Send + Sync + 'static>>
.branch(dptree::case![Command::Subscribe].endpoint(subscribe))
.branch(dptree::case![Command::Unsubscribe].endpoint(unsubscribe))
.branch(dptree::case![Command::Mensa].endpoint(change_mensa))
.branch(dptree::case![Command::Allergene].endpoint(allergene))
.branch(dptree::case![Command::Uhrzeit].endpoint(start_time_dialogue));

let message_handler = Update::filter_message()
Expand Down
31 changes: 29 additions & 2 deletions src/bot_command_handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ use crate::data_types::{
UnregisterTask, UpdateRegistrationTask,
};

use crate::db_operations::set_user_allergen_state;
use crate::shared_main::{
build_meal_message_dispatcher, get_user_registration, make_commands_keyrow, make_mensa_keyboard,
build_meal_message_dispatcher, get_user_registration, insert_user_registration,
make_commands_keyrow, make_mensa_keyboard,
};
use rand::Rng;
use std::{collections::BTreeMap, time::Instant};
Expand Down Expand Up @@ -39,7 +41,8 @@ pub async fn day_cmd(bot: Bot, msg: Message, cmd: Command) -> HandlerResult {
};

if let Some(registration) = get_user_registration(msg.chat.id.0) {
let text = build_meal_message_dispatcher(days_forward, registration.mensa_id).await;
let text =
build_meal_message_dispatcher(msg.chat.id.0, days_forward, registration.mensa_id).await;
let now = Instant::now();

bot.send_message(msg.chat.id, text)
Expand Down Expand Up @@ -141,6 +144,30 @@ pub async fn change_mensa(bot: Bot, msg: Message, mensen: BTreeMap<u32, String>)
mensa_disp_or_upd(bot, msg, mensen, MensaKeyboardAction::Update).await
}

pub async fn allergene(bot: Bot, msg: Message) -> HandlerResult {
if let Some(mut registration) = get_user_registration(msg.chat.id.0) {
registration.allergens = !registration.allergens;

set_user_allergen_state(msg.chat.id.0, registration.allergens)?;
insert_user_registration(msg.chat.id.0, registration);

match registration.allergens {
true => {
bot.send_message(msg.chat.id, "✅ Allergene werden jetzt angezeigt.")
.await?;
}
false => {
bot.send_message(msg.chat.id, "❌ Allergene werden nicht mehr angezeigt.")
.await?;
}
}
} else {
bot.send_message(msg.chat.id, NO_DB_MSG).await?;
}

Ok(())
}

pub async fn start_time_dialogue(
bot: Bot,
msg: Message,
Expand Down
11 changes: 7 additions & 4 deletions src/data_backend/mm_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ async fn mm_get_meals_at_mensa_at_day(
Ok(resp.json::<Vec<MensiMeal>>().await?)
}

pub async fn mm_build_meal_msg(days_forward: i64, mensa_location: u32) -> String {
pub async fn mm_build_meal_msg(
days_forward: i64,
mensa_location: u32,
wants_allergens: bool,
) -> String {
let mut msg: String = String::new();

// get requested date
Expand All @@ -69,14 +73,13 @@ pub async fn mm_build_meal_msg(days_forward: i64, mensa_location: u32) -> String
let day_meals = mm_get_meals_at_mensa_at_day(&requested_date, mensa_location).await;

let now = Instant::now();
let german_date = german_date_fmt(requested_date.date_naive());

// start message formatting
let rand_emoji = EMOJIS[rand::thread_rng().gen_range(0..EMOJIS.len())];
msg += &format!(
"{} {} {}\n",
rand_emoji,
markdown::italic(&german_date),
german_date_fmt(requested_date.date_naive()),
rand_emoji,
);

Expand Down Expand Up @@ -137,7 +140,7 @@ pub async fn mm_build_meal_msg(days_forward: i64, mensa_location: u32) -> String
}
}

if meal.allergens != "N/A" {
if wants_allergens && meal.allergens != "N/A" {
msg += &format!(" ⓘ {}\n", meal.allergens);
};

Expand Down
28 changes: 18 additions & 10 deletions src/data_backend/stuwe_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ use rand::Rng;
use teloxide::utils::markdown;

use tokio::time::Instant;
pub async fn stuwe_build_meal_msg(days_forward: i64, mensa_location: u32) -> String {
pub async fn stuwe_build_meal_msg(
days_forward: i64,
mensa_location: u32,
wants_allergens: bool,
) -> String {
// get requested date
let mut requested_date = chrono::Local::now() + Duration::days(days_forward);
let mut date_raised_by_days = 0;
Expand Down Expand Up @@ -57,31 +61,31 @@ pub async fn stuwe_build_meal_msg(days_forward: i64, mensa_location: u32) -> Str
if meal_groups.is_empty() {
msg += &markdown::bold("\nkeine Daten vorhanden.\n");
} else {
msg += &mealgroups_to_msg(&meal_groups);
msg += &mealgroups_to_msg(&meal_groups, wants_allergens);
}
}
};

escape_markdown_v2(&msg)
}

pub async fn stuwe_build_diff_msg(diff: &CanteenMealDiff) -> String {
pub async fn stuwe_build_diff_msg(diff: &CanteenMealDiff, wants_allergens: bool) -> String {
let mut msg = markdown::bold(&markdown::underline("Planänderung")).to_string();
if let Some(new_meals) = diff.new_meals.as_ref() {
msg += &markdown::bold(&markdown::underline(if new_meals.len() == 1 {
"\nNeues Gericht:"
} else {
"\nNeue Gerichte:"
}));
msg += &mealgroups_to_msg(new_meals);
msg += &mealgroups_to_msg(new_meals, wants_allergens);
}
if let Some(modified_meals) = diff.modified_meals.as_ref() {
msg += &markdown::bold(&markdown::underline(if modified_meals.len() == 1 {
"\nGeändertes Gericht:"
} else {
"\nGeänderte Gerichte:"
}));
msg += &mealgroups_to_msg(modified_meals);
msg += &mealgroups_to_msg(modified_meals, wants_allergens);
}

if let Some(removed_meals) = diff.removed_meals.as_ref() {
Expand All @@ -100,7 +104,7 @@ pub async fn stuwe_build_diff_msg(diff: &CanteenMealDiff) -> String {
escape_markdown_v2(msg.trim_end())
}

fn mealgroups_to_msg(meal_groups: &[MealGroup]) -> String {
fn mealgroups_to_msg(meal_groups: &[MealGroup], wants_allergens: bool) -> String {
let mut msg: String = String::new();

// loop over meal groups
Expand Down Expand Up @@ -128,8 +132,10 @@ fn mealgroups_to_msg(meal_groups: &[MealGroup]) -> String {
// appending ingredient to msg
msg += &format!(" + {}\n", markdown::italic(ingredient))
}
if let Some(allergens) = sub_meal.allergens.as_ref() {
msg += &format!(" ⓘ {}\n", allergens)
if wants_allergens {
if let Some(allergens) = sub_meal.allergens.as_ref() {
msg += &format!(" ⓘ {}\n", allergens)
}
}
// appending price
if !price_is_shared {
Expand All @@ -140,8 +146,10 @@ fn mealgroups_to_msg(meal_groups: &[MealGroup]) -> String {
msg += &format!(" → {}\n", markdown::bold("Variationen:"));
for variation in variations {
msg += &format!(" • {}\n", markdown::italic(&variation.name));
if let Some(allergens_and_add) = variation.allergens_and_add.as_ref() {
msg += &format!(" ⓘ {}\n", allergens_and_add)
if wants_allergens {
if let Some(allergens_and_add) = variation.allergens_and_add.as_ref() {
msg += &format!(" ⓘ {}\n", allergens_and_add)
}
}
}
}
Expand Down
15 changes: 9 additions & 6 deletions src/data_types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,20 @@ pub enum Command {
Heute,
#[command(description = "Gerichte für morgen\n")]
Morgen,
#[command(description = "Andere Mensa abrufen\n")]
Andere,
#[command(hide)]
Übermorgen,
#[command(description = "automat. Nachrichten AN")]
#[command(description = "Andere Mensa anzeigen")]
Mensa,
#[command(description = "Mensa wechseln\n")]
Andere,
#[command(description = "autom. Nachrichten aktivieren")]
Subscribe,
#[command(description = "autom. Nachrichten AUS")]
#[command(description = "autom. Nachrichten deaktivieren")]
Unsubscribe,
#[command(hide)]
#[command(description = "Sendezeitpunkt ändern")]
Uhrzeit,
#[command(hide)]
Mensa,
Allergene,
#[command(hide)]
Start,
}
Expand Down Expand Up @@ -157,6 +159,7 @@ pub struct RegistrationEntry {
pub mensa_id: u32,
pub hour: Option<u32>,
pub minute: Option<u32>,
pub allergens: bool,
}

#[derive(Error, Debug, Clone)]
Expand Down
27 changes: 26 additions & 1 deletion src/db_operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ pub fn check_or_create_db_tables() -> rusqlite::Result<()> {
chat_id integer not null unique primary key,
mensa_id integer not null,
hour integer,
minute integer
minute integer,
allergens BOOLEAN
)",
)?
.execute([])?;
Expand Down Expand Up @@ -117,3 +118,27 @@ pub fn init_db_record(job_handler_task: &JobHandlerTask) -> rusqlite::Result<()>

Ok(())
}

pub fn get_user_allergen_state(chat_id: i64) -> rusqlite::Result<bool> {
let conn = Connection::open(DB_FILENAME.get().unwrap()).unwrap();

let mut stmt = conn.prepare_cached(
"select allergens from registrations
where chat_id = ?1",
)?;

let allergens: bool = stmt.query_row(params![chat_id], |row| row.get(0))?;

Ok(allergens)
}

pub fn set_user_allergen_state(chat_id: i64, state: bool) -> rusqlite::Result<()> {
let conn = Connection::open(DB_FILENAME.get().unwrap()).unwrap();

let mut stmt =
conn.prepare_cached("update registrations set allergens = ?2 where chat_id = ?1")?;

stmt.execute(params![chat_id, state])?;

Ok(())
}
Loading

0 comments on commit 747677f

Please sign in to comment.