Skip to content

Commit

Permalink
Merge pull request #208 from MikiEremiki/develop
Browse files Browse the repository at this point in the history
Улучшение логики хранения данных в контексте + fix в работе approve|reject кнопок
  • Loading branch information
MikiEremiki authored Oct 27, 2024
2 parents 0648028 + 1c14cb2 commit 3fca08f
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 107 deletions.
7 changes: 3 additions & 4 deletions src/db/db_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,15 +623,14 @@ async def get_schedule_events_by_theater_ids_actual(
return result.scalars().all()


async def get_schedule_events_by_theater_and_month_and_types_actual(
async def get_schedule_events_by_ids_and_theater(
session: AsyncSession,
schedule_event_ids: List[int],
theater_event_ids: List[int],
type_event_ids: List[int]
):
query = select(ScheduleEvent).where(
ScheduleEvent.id.in_(schedule_event_ids),
ScheduleEvent.theater_event_id.in_(theater_event_ids),
ScheduleEvent.type_event_id.in_(type_event_ids),
ScheduleEvent.datetime_event >= datetime.now()
).order_by(ScheduleEvent.datetime_event)
result = await session.execute(query)
return result.scalars().all()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def upgrade() -> None:
nullable=False,
),
sa.ForeignKeyConstraint(
["custom_made_format"],
["custom_made_format_id"],
["custom_made_formats.id"],
name=op.f(
"fk__custom_made_events__custom_made_format_id__custom_made_formats"
Expand Down
79 changes: 41 additions & 38 deletions src/handlers/main_hl.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ async def confirm_reserve(update: Update, context: ContextTypes.DEFAULT_TYPE):

await query.edit_message_reply_markup()

text = f'Обновлен статус билета...'
text = f'Обновлен статус билета: {ticket_status}...'
await message.edit_text(text)

chat_id = query.data.split('|')[1].split()[0]
Expand Down Expand Up @@ -336,7 +336,7 @@ async def reject_reserve(update: Update, context: ContextTypes.DEFAULT_TYPE):

await query.edit_message_reply_markup()

text = f'Обновлен статус билета...'
text = f'Обновлен статус билета: {ticket_status}...'
await message.edit_text(text)

message = await message.edit_text(
Expand Down Expand Up @@ -375,6 +375,12 @@ async def confirm_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.effective_chat.send_action(
ChatAction.TYPING, message_thread_id=query.message.message_thread_id)

message = await update.effective_chat.send_message(
text='Начат процесс подтверждения...',
reply_to_message_id=query.message.message_id,
message_thread_id=query.message.message_thread_id
)

chat_id = query.data.split('|')[1].split()[0]
user_data = context.application.user_data.get(int(chat_id))
user = user_data['user']
Expand All @@ -392,10 +398,19 @@ async def confirm_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE):
match data:
case '1':
cme_status = CustomMadeStatus.APPROVED

await query.edit_message_text(
query.message.text + '\n\n Заявка подтверждена, ждём предоплату'
)
case '2':
cme_status = CustomMadeStatus.PREPAID
await query.answer()
update_cme_in_gspread(custom_made_event_id, cme_status.value)
await message.edit_text(f'Обновил статус в гугл-таблице {cme_status.value}')
await db_postgres.update_custom_made_event(context.session,
custom_made_event_id,
status=cme_status)
await query.edit_message_reply_markup()
match data:
case '1':
await message.edit_text(
f'Заявка {custom_made_event_id} подтверждена, ждём предоплату')

text = (f'<b>У нас отличные новости'
f' по вашей заявке: {custom_made_event_id}!</b>\n')
Expand All @@ -405,8 +420,7 @@ async def confirm_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE):
text += '<i>Вам будет отправлено сообщение с информацией об оплате</i>'

case '2':
cme_status = CustomMadeStatus.PREPAID
await query.edit_message_text(
await message.edit_text(
f'Пользователю @{user.username} {user.full_name}\n'
f'подтверждена бронь по заявке {custom_made_event_id}'
)
Expand All @@ -425,13 +439,6 @@ async def confirm_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = (f'Ваша бронь по заявке {custom_made_event_id} подтверждена\n'
'До встречи в Домике')

await query.answer()
update_cme_in_gspread(custom_made_event_id, cme_status.value)
await db_postgres.update_custom_made_event(context.session,
custom_made_event_id,
status=cme_status)
await query.edit_message_reply_markup()

await context.bot.send_message(
text=text,
chat_id=chat_id,
Expand All @@ -447,6 +454,11 @@ async def reject_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE):
return
await update.effective_chat.send_action(
ChatAction.TYPING, message_thread_id=query.message.message_thread_id)
message = await update.effective_chat.send_message(
text='Начат процесс отклонения...',
reply_to_message_id=query.message.message_id,
message_thread_id=query.message.message_thread_id
)

chat_id = query.data.split('|')[1].split()[0]
user_data = context.application.user_data.get(int(chat_id))
Expand All @@ -461,20 +473,26 @@ async def reject_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = ('Возникла ошибка\n'
'Cвяжитесь с администратором:\n'
f'{context.bot_data['admin']['contacts']}')

cme_status = CustomMadeStatus.REJECTED
await query.answer()
update_cme_in_gspread(custom_made_event_id, cme_status.value)
await message.edit_text(f'Обновил статус в гугл-таблице {cme_status.value}')
await db_postgres.update_custom_made_event(context.session,
custom_made_event_id,
status=cme_status)
await query.edit_message_reply_markup()
match data:
case '1':
await message.edit_text('Заявка отклонена')
text = ('Мы рассмотрели Вашу заявку.\n'
'К сожалению, мы не сможем провести день рождения вашего '
'малыша\n\n'
'Для решения данного вопроса, пожалуйста, '
'свяжитесь с Администратором:\n'
f'{context.bot_data['admin']['contacts']}')

await query.edit_message_text(
query.message.text + '\n\n Заявка отклонена'
)
case '2':
await query.edit_message_text(
await message.edit_text(
f'Пользователю @{user.username} {user.full_name}\n'
f'отклонена бронь'
)
Expand All @@ -484,23 +502,14 @@ async def reject_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id=chat_id,
message_id=message_id
)
except BadRequest:
main_handlers_logger.info(
f'Cообщение уже удалено'
)
except BadRequest as e:
main_handlers_logger.error(e)
main_handlers_logger.info(f'Cообщение уже удалено')
text = ('Ваша бронь отклонена.\n'
'Для решения данного вопроса, пожалуйста, '
'свяжитесь с Администратором:\n'
f'{context.bot_data['admin']['contacts']}')

cme_status = CustomMadeStatus.REJECTED
await query.answer()
update_cme_in_gspread(custom_made_event_id, cme_status.value)
await db_postgres.update_custom_made_event(context.session,
custom_made_event_id,
status=cme_status)
await query.edit_message_reply_markup()

await context.bot.send_message(
text=text,
chat_id=chat_id,
Expand All @@ -509,12 +518,6 @@ async def reject_birthday(update: Update, context: ContextTypes.DEFAULT_TYPE):


async def back(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""
:param update:
:param context:
:return:
"""
query = update.callback_query

state = query.data.split('-')[1]
Expand Down
57 changes: 46 additions & 11 deletions src/handlers/reserve_hl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
import pprint
from datetime import datetime

from telegram.error import BadRequest
from telegram.ext import ContextTypes, ConversationHandler, TypeHandler
from telegram import (
Update,
InlineKeyboardMarkup,
Expand All @@ -20,7 +18,7 @@
from handlers.email_hl import check_email_and_update_user
from handlers.sub_hl import (
request_phone_number,
send_breaf_message, send_filtered_schedule_events,
send_breaf_message,
send_message_about_list_waiting,
remove_button_from_last_message,
create_and_send_payment, processing_successful_payment,
Expand All @@ -42,13 +40,16 @@
get_formatted_date_and_time_of_event,
create_event_names_text, get_events_for_time_hl,
get_type_event_ids_by_command, get_emoji, clean_context,
add_clients_data_to_text, add_qty_visitors_to_text
add_clients_data_to_text, add_qty_visitors_to_text,
filter_schedule_event_by_active, get_unique_months,
clean_replay_kb_and_send_typing_action
)
from utilities.utl_kbd import (
create_kbd_schedule_and_date, create_kbd_schedule,
create_kbd_for_time_in_reserve, create_replay_markup,
create_kbd_and_text_tickets_for_choice, create_kbd_for_time_in_studio,
create_kbd_for_date_in_reserve, remove_intent_id
create_kbd_for_date_in_reserve, remove_intent_id, create_kbd_with_months,
adjust_kbd
)
from settings.settings import (
ADMIN_GROUP, COMMAND_DICT, SUPPORT_DATA, RESERVE_TIMEOUT
Expand Down Expand Up @@ -86,11 +87,33 @@ async def choice_month(update: Update, context: ContextTypes.DEFAULT_TYPE):
reserve_hl_logger.info(f'Пользователь начал выбор месяца: {user}')

type_event_ids = await get_type_event_ids_by_command(command)
reply_markup, text = await send_filtered_schedule_events(update,
context,
type_event_ids)
schedule_events = await db_postgres.get_schedule_events_by_type_actual(
context.session, type_event_ids)
schedule_events = await filter_schedule_event_by_active(schedule_events)
months = get_unique_months(schedule_events)
message = await clean_replay_kb_and_send_typing_action(update)
text = 'Выберите месяц'
keyboard = await create_kbd_with_months(months)
keyboard = adjust_kbd(keyboard, 1)
keyboard.append(add_btn_back_and_cancel(
postfix_for_cancel=context.user_data['postfix_for_cancel'],
add_back_btn=False
))
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.delete_message(
chat_id=update.effective_chat.id,
message_id=message.message_id
)
await update.effective_chat.send_message(
text=text,
reply_markup=reply_markup,
message_thread_id=update.effective_message.message_thread_id
)

state = 'MONTH'
schedule_event_ids = [item.id for item in schedule_events]
state_data = context.user_data['reserve_user_data'][state] = {}
state_data['schedule_event_ids'] = schedule_event_ids
await set_back_context(context, state, text, reply_markup)
context.user_data['STATE'] = state
if context.user_data.get('command', False) and query:
Expand All @@ -115,7 +138,8 @@ async def choice_show_or_date(

reserve_hl_logger.info(f'Пользователь выбрал месяц: {number_of_month_str}')
reserve_user_data = context.user_data['reserve_user_data']
schedule_event_ids = reserve_user_data['schedule_event_ids']
state = context.user_data['STATE']
schedule_event_ids = reserve_user_data[state]['schedule_event_ids']
schedule_events = await db_postgres.get_schedule_events_by_ids(
context.session, schedule_event_ids)

Expand Down Expand Up @@ -172,6 +196,9 @@ async def choice_show_or_date(
)

reserve_user_data['number_of_month_str'] = number_of_month_str
schedule_event_ids = [item.id for item in schedule_events_filter_by_month]
state_data = context.user_data['reserve_user_data'][state] = {}
state_data['schedule_event_ids'] = schedule_event_ids

await set_back_context(context, state, text, reply_markup)
context.user_data['STATE'] = state
Expand All @@ -194,10 +221,13 @@ async def choice_date(update: Update, context: ContextTypes.DEFAULT_TYPE):
theater_event_id = int(callback_data)
reserve_user_data = context.user_data['reserve_user_data']
number_of_month_str = reserve_user_data['number_of_month_str']

state = context.user_data['STATE']
schedule_event_ids = reserve_user_data[state]['schedule_event_ids']
theater_event = await db_postgres.get_theater_event(
context.session, theater_event_id)
schedule_events = await db_postgres.get_schedule_events_by_theater_ids_actual(
context.session, [theater_event_id])
schedule_events = await db_postgres.get_schedule_events_by_ids_and_theater(
context.session, schedule_event_ids, [theater_event_id])

keyboard = await create_kbd_for_date_in_reserve(schedule_events)
reply_markup = await create_replay_markup(
Expand Down Expand Up @@ -254,6 +284,11 @@ async def choice_date(update: Update, context: ContextTypes.DEFAULT_TYPE):
state = 'LIST_WAIT'
else:
state = 'DATE'

schedule_event_ids = [item.id for item in schedule_events]
state_data = context.user_data['reserve_user_data'][state] = {}
state_data['schedule_event_ids'] = schedule_event_ids

await set_back_context(context, state, text, reply_markup)
context.user_data['STATE'] = state
return state
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/studio_hl.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ async def choice_show_and_date(update: Update,

studio_hl_logger.info(f'Пользователь выбрал месяц: {number_of_month_str}')
reserve_user_data = context.user_data['reserve_user_data']
schedule_event_ids = reserve_user_data['schedule_event_ids']
state = context.user_data['STATE']
schedule_event_ids = reserve_user_data[state]['schedule_event_ids']
schedule_events = await db_postgres.get_schedule_events_by_ids(
context.session, schedule_event_ids)

Expand Down
41 changes: 2 additions & 39 deletions src/handlers/sub_hl.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@
from utilities import add_btn_back_and_cancel
from utilities.utl_func import (
get_unique_months, get_full_name_event,
filter_schedule_event_by_active, clean_replay_kb_and_send_typing_action,
filter_schedule_event_by_active,
get_formatted_date_and_time_of_event,
create_approve_and_reject_replay, set_back_context
)
from utilities.utl_googlesheets import update_ticket_db_and_gspread
from utilities.utl_kbd import (
adjust_kbd, create_kbd_with_months, create_email_confirm_btn)
from utilities.utl_kbd import create_email_confirm_btn

sub_hl_logger = logging.getLogger('bot.sub_hl')

Expand Down Expand Up @@ -223,15 +222,6 @@ async def get_theater_and_schedule_events_by_month(context, schedule_events,
return tuple(enum_theater_events), schedule_events_filter_by_month


async def get_schedule_events_by_month(schedule_events,
number_of_month_str):
schedule_events_filter_by_month = []
for event in schedule_events:
if event.datetime_event.month == int(number_of_month_str):
schedule_events_filter_by_month.append(event)
return schedule_events_filter_by_month


async def remove_button_from_last_message(update, context):
message_id = context.user_data['common_data']['message_id_buy_info']
try:
Expand Down Expand Up @@ -688,33 +678,6 @@ async def send_agreement(update, context):
return text, inline_markup


async def send_filtered_schedule_events(update, context, type_event_ids):
months, schedule_events = await get_schedule_events_and_month_by_type_event(
context, type_event_ids)
message = await clean_replay_kb_and_send_typing_action(update)
text = 'Выберите месяц'
keyboard = await create_kbd_with_months(months)
keyboard = adjust_kbd(keyboard, 1)
keyboard.append(add_btn_back_and_cancel(
postfix_for_cancel=context.user_data['postfix_for_cancel'],
add_back_btn=False
))
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.delete_message(
chat_id=update.effective_chat.id,
message_id=message.message_id
)
await update.effective_chat.send_message(
text=text,
reply_markup=reply_markup,
message_thread_id=update.effective_message.message_thread_id
)
schedule_event_ids = [item.id for item in schedule_events]
reserve_user_data = context.user_data['reserve_user_data']
reserve_user_data['schedule_event_ids'] = schedule_event_ids
return reply_markup, text


async def send_message_about_list_waiting(update: Update, context):
reserve_user_data = context.user_data['reserve_user_data']
command = context.user_data.get('command', None)
Expand Down
Loading

0 comments on commit 3fca08f

Please sign in to comment.