Skip to content

Commit

Permalink
Merge pull request #207 from MikiEremiki/develop
Browse files Browse the repository at this point in the history
Обновление Заказных мероприятий
  • Loading branch information
MikiEremiki authored Oct 27, 2024
2 parents 876b5fa + 7963c7c commit 0648028
Show file tree
Hide file tree
Showing 38 changed files with 1,867 additions and 770 deletions.
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
alembic
black
cachetools
google-api-python-client
google-auth-httplib2
google-auth-oauthlib
Expand All @@ -15,7 +16,7 @@ PyYAML
requests
sqlalchemy
typing_extensions
yookassa~=3.0.1
yookassa
uvicorn
fastapi
faststream[cli]
Expand Down
4 changes: 1 addition & 3 deletions src/api/broker_nats.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from faststream import Logger
from faststream.nats import JStream, NatsMessage, NatsBroker
from faststream.nats import JStream, NatsBroker
from telegram.ext import Application
from yookassa.domain.notification import WebhookNotificationFactory

Expand All @@ -15,11 +15,9 @@ def connect_to_nats(app: Application,
async def nats_handler(
data: dict,
logger: Logger,
nats_message: NatsMessage,
):
logger.info(f'{data=}')
notification = webhook_notification_factory.create(data)
# print(f'{nats_message=}')
await app.update_queue.put(notification)

return broker
200 changes: 89 additions & 111 deletions src/api/googlesheets.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from db import BaseTicket
from db.enum import TicketStatus
from db.models import CustomMadeEvent
from settings.config_loader import parse_settings
from settings.settings import RANGE_NAME

Expand Down Expand Up @@ -228,7 +229,7 @@ def write_client_reserve(
context: ContextTypes.DEFAULT_TYPE,
chat_id: int,
base_ticket: BaseTicket,
ticket_status = TicketStatus.CREATED.value,
ticket_status=TicketStatus.CREATED.value,
) -> Optional[List[int]]:
reserve_user_data = context.user_data['reserve_user_data']
chose_price = reserve_user_data['chose_price']
Expand Down Expand Up @@ -302,8 +303,7 @@ def write_client_reserve(
}

range_sheet = (RANGE_NAME['База клиентов_'] +
f'R1C1:'
f'R1C{end_column_index}')
f'R1C1:R1C{end_column_index}')

execute_append_googlesheet(sheet,
range_sheet,
Expand Down Expand Up @@ -416,66 +416,65 @@ def get_flags_by_ticket_status(ticket_status):
return flag_exclude, flag_exclude_place_sum, flag_transfer


def write_client_bd(
context_data: dict,
def write_client_cme(
custom_made_event: CustomMadeEvent,
) -> None:
try:
values_column = get_values(
SPREADSHEET_ID['Домик'],
RANGE_NAME['База ДР']
)
dict_column_name, len_column = get_column_info('База ДР_')

if not values_column:
googlesheets_logger.info('No data found.')
return
values_column = get_values(
SPREADSHEET_ID['Домик'],
RANGE_NAME['База ДР']
)

first_row_for_write = len(values_column)
last_row_for_write = first_row_for_write
if not values_column:
googlesheets_logger.info('No data found.')
return

sheet = get_service_sacc(SCOPES).spreadsheets()
value_input_option = 'USER_ENTERED'
response_value_render_option = 'FORMATTED_VALUE'
values = [[]]
sheet = get_service_sacc(SCOPES).spreadsheets()
value_input_option = 'USER_ENTERED'
response_value_render_option = 'FORMATTED_VALUE'
values = [[]]

created_at = custom_made_event.created_at.strftime('%y%m%d %H:%M:%S')
cme = custom_made_event.model_dump()
for key, name in dict_column_name.items():
if key in cme:
match key:
case 'created_at':
values[0].append(created_at)
case 'status':
values[0].append(custom_made_event.status.value)
case _:
values[0].append(cme[key])
elif key == 'name_theater':
values[0].append(
'=VLOOKUP('
'INDEX($1:$66;ROW();MATCH("theater_event_id";$2:$2;0));'
'\'Репертуар\'!$A$3:$F;'
'MATCH("name";\'Репертуар\'!$2:$2;0)'
')'
)
else:
values[0].append('')

date = datetime.now().strftime('%y%m%d %H:%M:%S')
values[0][dict_column_name['created_at']] = created_at

bd_data = context_data['birthday_user_data']
values[0].append(bd_data['phone']) # 0
values[0].append(bd_data['place'])
values[0].append(bd_data['address'])
values[0].append(bd_data['date'])
values[0].append(bd_data['time'])
values[0].append(bd_data['theater_event_id'])
values[0].append(bd_data['age'])
values[0].append(bd_data['qty_child'])
values[0].append(bd_data['qty_adult'])
values[0].append(bd_data['format_bd'])
values[0].append(bd_data['name_child'])
values[0].append(bd_data['name'])
values[0].append(date) # 12
values[0].extend(['FALSE', 'FALSE', 'FALSE'])
values[0].append(context_data['user'].id) # 16
googlesheets_logger.info(values)

googlesheets_logger.info(values)
end_column_index = len(values[0])

end_column_index = len(values[0])
value_range_body = {
'values': values,
}

value_range_body = {
'values': values,
}
range_sheet = (RANGE_NAME['База ДР_'] +
f'R1C1:R1C{end_column_index}')

range_sheet = (RANGE_NAME['База ДР_'] +
f'R{first_row_for_write + 1}C1:' +
f'R{last_row_for_write + 1}C{end_column_index}')

execute_update_googlesheet(sheet,
range_sheet,
value_input_option,
response_value_render_option,
value_range_body)

except HttpError as err:
googlesheets_logger.error(err)
execute_append_googlesheet(sheet,
range_sheet,
value_input_option,
response_value_render_option,
value_range_body)


def write_client_list_waiting(context: ContextTypes.DEFAULT_TYPE):
Expand Down Expand Up @@ -534,10 +533,9 @@ def write_client_list_waiting(context: ContextTypes.DEFAULT_TYPE):
}

range_sheet = (RANGE_NAME['Лист ожидания_'] +
f'R{first_row_for_write + 1}C1:'
f'R{last_row_for_write + 1}C{end_column_index}')
f'R1C1:R1C{end_column_index}')

execute_update_googlesheet(sheet,
execute_append_googlesheet(sheet,
range_sheet,
value_input_option,
response_value_render_option,
Expand All @@ -547,65 +545,45 @@ def write_client_list_waiting(context: ContextTypes.DEFAULT_TYPE):
googlesheets_logger.error(err)


def set_approve_order(bd_data, step=0) -> None:
"""
def update_cme_in_gspread(cme_id, status) -> None:
dict_column_name, len_column = get_column_info('База ДР_')
values = get_values(
SPREADSHEET_ID['Домик'],
f'{RANGE_NAME['База ДР']}',
value_render_option='UNFORMATTED_VALUE'
)

:param bd_data:
:type step: 0 - Заявка подтверждена
1 - Предоплата
2 - Предоплата подтверждена
"""
try:
values = get_values(
SPREADSHEET_ID['Домик'],
RANGE_NAME['База ДР_'] + 'A:E'
)
values_header = get_values(
SPREADSHEET_ID['Домик'],
RANGE_NAME['База ДР_'] + '1:1'
)
if not values:
googlesheets_logger.info('No data found')
raise ValueError

if not values:
googlesheets_logger.info('No data found')
return
if not values_header:
googlesheets_logger.info('No data found')
return
row_cme = 0
for i, row in enumerate(values):
if cme_id == row[dict_column_name['id']]:
row_cme = i + 1
if row_cme == 0:
raise ValueError('Билет удален из гугл-таблицы')

colum = 1
for i, item in enumerate(values_header[0]):
if item == 'Заявка подтверждена':
colum += i

for i, item in enumerate(values):
if (item[0] == bd_data['phone'] and
item[2] == bd_data['address'] and
item[3] == bd_data['date'] and
item[4] == bd_data['time']):
sheet = get_service_sacc(SCOPES).spreadsheets()
value_input_option = 'USER_ENTERED'
response_value_render_option = 'FORMATTED_VALUE'

values = [[]]
values[0].append(True)
googlesheets_logger.info(values)

value_range_body = {
'values': values,
}

range_sheet = (RANGE_NAME['База ДР_'] +
f'R{i + 1}C{colum + step}:' +
f'R{i + 2}C{colum + step}')

execute_update_googlesheet(sheet,
range_sheet,
value_input_option,
response_value_render_option,
value_range_body)
sheet = get_service_sacc(SCOPES).spreadsheets()
value_input_option = 'USER_ENTERED'
response_value_render_option = 'FORMATTED_VALUE'

except HttpError as err:
googlesheets_logger.error(err)
values = [[]]
values[0].append(status)
googlesheets_logger.info(values)

value_range_body = {'values': values}

col1 = dict_column_name['status'] + 1
col2 = col1 + 1
range_sheet = (f'{RANGE_NAME['База ДР_']}'
f'R{row_cme}C{col1}:R{row_cme}C{col2}')

execute_update_googlesheet(sheet,
range_sheet,
value_input_option,
response_value_render_option,
value_range_body)


def execute_update_googlesheet(
Expand Down
11 changes: 7 additions & 4 deletions src/bot.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import asyncio
from contextlib import asynccontextmanager

from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import Application, Defaults
from telegram.ext import Application, Defaults, AIORateLimiter
from yookassa import Configuration
from faststream import FastStream
from yookassa.domain.notification import WebhookNotificationFactory

from api.broker_nats import connect_to_nats
from db import pickle_persistence
from handlers.set_handlers import set_handlers
from log.logging_conf import load_log_config
from log.logging_conf import setup_logs
from settings.config_loader import parse_settings
from utilities.utl_post_init import post_init

bot_logger = load_log_config()
bot_logger = setup_logs()
bot_logger.info('Инициализация бота')

config = parse_settings()
Expand All @@ -27,6 +28,7 @@
.get_updates_pool_timeout(3)
.get_updates_write_timeout(7)
.get_updates_connection_pool_size(2)
.rate_limiter(AIORateLimiter())

.build()
)
Expand All @@ -43,8 +45,9 @@ async def lifespan():
set_handlers(application, config)
await application.initialize()
await post_init(application, config)
bot_logger.info('=====Setup Бота произведен, переходим к запуску =====')
await application.start()
await application.updater.start_polling()
await application.updater.start_polling(allowed_updates=Update.ALL_TYPES)

yield

Expand Down
Loading

0 comments on commit 0648028

Please sign in to comment.