Skip to content

Commit

Permalink
Merge branch 'develop' into feature/realize_service_for_stage_and_prod
Browse files Browse the repository at this point in the history
  • Loading branch information
KonstantinRaikhert authored Sep 3, 2023
2 parents 4b80ed8 + 22ab47e commit 03bb06b
Show file tree
Hide file tree
Showing 97 changed files with 478 additions and 154 deletions.
2 changes: 1 addition & 1 deletion .flake8
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[flake8]
ignore = E501, E265, F811, PT001, DJ05, D100, D105, D104, W504, W292, D106, D107
ignore = E501, E265, F811, PT001, DJ05, D100, D105, D104, W504, W292, D106, D107, W503
max-line-length = 79
exclude =
*/migrations/
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ coverage.xml
local_settings.py
db.sqlite3
db.sqlite3-journal
static/
staticfiles/
media/
logs/

Expand Down
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ help: # Show help


.PHONY: runbot-init
runbot-init: deletedb rundb migrate filldb runbot-db # Build and run Database Docker-image
runbot-init: deletedb rundb migrate filldb collectstatic createsuperuser runbot-db # Build and run Database Docker-image
@echo -e "$(COLOR_YELLOW)Starting initialization...$(COLOR_RESET)"
@source $$(poetry env info -p)/bin/activate

Expand Down Expand Up @@ -90,6 +90,10 @@ migrate: # Commit migrations to Database
@sleep 3;
@echo -e "$(COLOR_GREEN)Migrated$(COLOR_RESET)"

.PHONY: createsuperuser
createsuperuser:
@echo -e "$(COLOR_YELLOW)Creating Django superuser...$(COLOR_RESET)"
@poetry run python src/manage.py createsuperuser

.PHONY: run_tests
run_tests: run_unit_tests # Run all tests
Expand Down
2 changes: 1 addition & 1 deletion infra/dev/docker-compose.stage.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ services:
- redis
- db
volumes:
- ../../static:/app/src/static
- ../../static:/app/src/staticfiles
- ../../media:/app/src/media
- ./logs/bot/:/app/src/logs
restart: always
Expand Down
4 changes: 0 additions & 4 deletions infra/init.sh

This file was deleted.

2 changes: 1 addition & 1 deletion infra/prod/docker-compose.prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ services:
- redis
- db
volumes:
- ../../static:/app/src/static
- ../../static:/app/src/staticfiles
- ../../media:/app/src/media
- ./logs/bot/:/app/src/logs
restart: always
Expand Down
19 changes: 2 additions & 17 deletions src/bot/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class QuestionAdmin(RegionForAdmin):
form = QuestionAdminForm
list_display = (
"get_question",
"get_short_description",
"get_question_type",
"short_description",
"question_type",
"get_answer",
"get_regions",
)
Expand All @@ -41,16 +41,6 @@ def get_question(self, obj):
"""Display questions in admin panel."""
return obj.question[:100]

@admin.display(description="Короткое описание")
def get_short_description(self, obj):
"""Display short_descriptions in admin panel."""
return obj.short_description[:100]

@admin.display(description="Тип вопроса")
def get_question_type(self, obj):
"""Display question_type in admin panel."""
return obj.question_type[:100]

@admin.display(description="Ответ")
def get_answer(self, obj):
"""Display answer in admin panel."""
Expand Down Expand Up @@ -95,11 +85,6 @@ def get_title(self, obj):
"""Display title in admin panel."""
return obj.title[:100]

@admin.display(description="Короткое описание")
def get_short_description(self, obj):
"""Display short_description in admin panel."""
return obj.short_description[:100]

@admin.display(description="Описание программы")
def get_fund_text(self, obj):
"""Display fund_text in admin panel."""
Expand Down
4 changes: 2 additions & 2 deletions src/bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ async def build_app() -> Application:
states={
States.GET_ASSISTANCE: [
CallbackQueryHandler(get_assistance, pattern=GET_ASSISTANCE),
],
States.REGION: [
]
+ [
CallbackQueryHandler(
select_type_of_assistance,
pattern=PATTERN.format(state=key),
Expand Down
12 changes: 0 additions & 12 deletions src/bot/constants/messages.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
START_MESSAGE = 'Здравствуйте! Это бот фонда "Расправь крылья".'
HELP_MESSAGE = (
"[Заглушка]Здесь выводится краткое описание возможностей бота (/help)"
)
ASSISTANCE_MESSAGE = (
'[Заглушка]Сообщение после нажатия на кнопку "Получить помощь" '
"(Выбор региона)"
)
CHOOSE_REGION_MESSAGE = "Выберите, пожалуйста, регион"
ASSISTANCE_TYPE_MESSAGE = (
"[Заглушка]Сообщение в момент выбора юр., соц., психол., помощи и т.д."
)
HOW_CAN_WE_HELP = "Чем мы можем помочь?"
MENU_MESSAGE = "Команды и меню обновлены"
CONTACT_US_MESSAGE = "[Заглушка] Задать вопрос."

SELECT_FUND_PROGRAM = "Выбор программы из списка"
SELECT_QUESTION = "Выбор вопроса из списка"
Expand Down
4 changes: 3 additions & 1 deletion src/bot/constants/patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
state="".join(f"{h_type}|" for h_type in HelpTypes.names)
)
HELP_TYPE = rf"({POSSIBLE_TYPE_OF_ASSISTANCE})(?:{PAGE_SEP_SYMBOL}(\d+))?"
GET_ASSISTANCE = PATTERN.format(
state=rf"({States.GET_ASSISTANCE.value})(?:{PAGE_SEP_SYMBOL}(\d+))?"
)
SEND_EMAIL = PATTERN.format(state=States.SEND_EMAIL.value)
GET_USER_QUESTION = PATTERN.format(state=States.GET_USER_QUESTION.value)
GET_ASSISTANCE = PATTERN.format(state=States.GET_ASSISTANCE.value)
FUND_PROGRAMS = PATTERN.format(
state=rf"({States.FUND_PROGRAMS.value})(?:{PAGE_SEP_SYMBOL}(\d+))?"
)
Expand Down
2 changes: 2 additions & 0 deletions src/bot/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class Meta:

model = Question
widgets = {
"question": forms.Textarea(attrs={"rows": 3, "cols": 50}),
"answer": forms.Textarea(attrs={"rows": 10, "cols": 80}),
"regions": forms.CheckboxSelectMultiple,
}
Expand All @@ -25,6 +26,7 @@ class Meta:

models = FundProgram
widgets = {
"title": forms.Textarea(attrs={"rows": 3, "cols": 50}),
"regions": forms.CheckboxSelectMultiple,
}
fields = "__all__"
27 changes: 17 additions & 10 deletions src/bot/handlers/assistance.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
SELECT_FUND_PROGRAM,
SELECT_QUESTION,
)
from bot.constants.patterns import FUND_PROGRAMS, HELP_TYPE
from bot.constants.patterns import FUND_PROGRAMS, GET_ASSISTANCE, HELP_TYPE
from bot.constants.states import States
from bot.handlers.debug_handlers import debug_logger
from bot.keyboards.assistance import (
Expand All @@ -20,27 +20,34 @@
)
from bot.keyboards.assistance_types import assistance_types_keyboard_markup
from bot.keyboards.utils.callback_data_parse import parse_callback_data
from bot.models import HelpTypes
from bot_settings.models import BotSettings

DEFAULT_PAGE = 1


@debug_logger(state=States.REGION, run_functions_debug_loger="get_assistance")
@debug_logger(
state=States.GET_ASSISTANCE, run_functions_debug_loger="get_assistance"
)
async def get_assistance(
update: Update,
context: ContextTypes.DEFAULT_TYPE,
) -> States:
"""Select a region of assistance."""
await update.callback_query.answer()
keyboard = await build_region_keyboard()
query = update.callback_query
callback_data = query.data.replace("back_to_", "")
_, page_number = parse_callback_data(callback_data, GET_ASSISTANCE)
page_number = page_number or DEFAULT_PAGE
await query.answer()
keyboard = await build_region_keyboard(page_number)
assistance_message = await BotSettings.objects.aget(
key="assistance_message"
)
await update.callback_query.edit_message_text(
text=assistance_message.value, reply_markup=keyboard
)
return States.REGION
if query.message.reply_markup.to_json() != keyboard.markup:
await query.edit_message_text(
text=assistance_message.value,
reply_markup=keyboard.markup,
)
return States.GET_ASSISTANCE


@debug_logger(
Expand Down Expand Up @@ -139,7 +146,7 @@ async def contact_with_us(
) -> States:
"""Ask question and show contacts."""
query = update.callback_query
context.user_data[States.QUESTION_TYPE] = HelpTypes.COMMON_QUESTION.value
context.user_data[States.QUESTION_TYPE] = "COMMON_QUESTION"
await query.answer()
await query.edit_message_text(
text=CONTACT_SHOW_MESSAGE,
Expand Down
4 changes: 2 additions & 2 deletions src/bot/handlers/service_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ async def answer_all_messages(


FUNCTIONS: dict[str, Callable[[Any, Any], Awaitable[States]]] = {
States.GET_ASSISTANCE.value: start,
States.START: start,
States.ASSISTANCE_TYPE: select_type_of_assistance,
States.CONTACT_US: contact_with_us,
States.FUND_PROGRAMS: fund_programs,
States.REGION: get_assistance,
States.REGION.value: get_assistance,
States.SHOW_CONTACT: show_contact,
States.GET_USERNAME: get_user_question,
States.USERNAME_AFTER_RETURNING: get_username_after_returning_back,
Expand Down
59 changes: 37 additions & 22 deletions src/bot/keyboards/assistance.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@
from bot_settings.models import BotSettings
from core.models import Region

PROGRAMS_PER_PAGE = 6
QUESTIONS_PER_PAGE = 6


async def build_assistance_keyboard() -> InlineKeyboardMarkup:
"""
Expand All @@ -43,30 +40,42 @@ async def build_assistance_keyboard() -> InlineKeyboardMarkup:
)


async def build_region_keyboard() -> InlineKeyboardMarkup:
async def build_region_keyboard(
page: int,
) -> InlineKeyboardPaginator:
"""
Build telegram assistance type keyboard async.
After building cache it.
"""
keyboard = [
[
InlineKeyboardButton(
text=region.region_name,
callback_data=region.region_key,
)
]
async for region in Region.objects.all()
]
back_button = [
[
queryset = await sync_to_async(list)(
Region.objects.all().values("region_name", "region_key")
)
region_per_page = await BotSettings.objects.aget(
key="regions_pagination_setting"
)
data_paginator = Paginator(queryset, int(region_per_page.value))
telegram_paginator = InlineKeyboardPaginator(
data_paginator.num_pages,
current_page=page,
data_pattern="".join(
[States.GET_ASSISTANCE.value, PAGE_SEP_SYMBOL, "{page}"]
),
)
for region in data_paginator.page(page):
telegram_paginator.add_before(
InlineKeyboardButton(
text=BACK_BUTTON,
callback_data=f"back_to_{States.GET_ASSISTANCE.value}",
text=region.get("region_name"),
callback_data=region.get("region_key"),
)
]
]
return InlineKeyboardMarkup(keyboard + back_button)
)
telegram_paginator.add_after(
InlineKeyboardButton(
text=BACK_BUTTON,
callback_data=f"back_to_{States.START.value}",
),
)
return telegram_paginator


async def build_question_keyboard(
Expand All @@ -85,7 +94,10 @@ async def build_question_keyboard(
question_type=question_type,
).values("id", "short_description")
)
data_paginator = Paginator(queryset, QUESTIONS_PER_PAGE)
questions_per_page = await BotSettings.objects.aget(
key="questions_pagination_setting"
)
data_paginator = Paginator(queryset, int(questions_per_page.value))
telegram_paginator = InlineKeyboardPaginator(
data_paginator.num_pages,
current_page=page,
Expand Down Expand Up @@ -131,7 +143,10 @@ async def build_fund_program_keyboard(
regions__region_key=region,
).values("id", "short_description")
)
data_paginator = Paginator(queryset, PROGRAMS_PER_PAGE)
programs_per_page = await BotSettings.objects.aget(
key="programs_pagination_setting"
)
data_paginator = Paginator(queryset, int(programs_per_page.value))
telegram_paginator = InlineKeyboardPaginator(
data_paginator.num_pages,
current_page=page,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Generated by Django 4.2.4 on 2023-08-31 21:06

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):
"""Migrations for bot."""

dependencies = [
("core", "0002_alter_region_region_name"),
("bot", "0004_alter_coordinator_options_coordinator_is_chief"),
]

operations = [
migrations.AlterField(
model_name="coordinator",
name="email_address",
field=models.EmailField(
help_text="Введите адрес электронной почты",
max_length=254,
unique=True,
verbose_name="Email",
),
),
migrations.AlterField(
model_name="coordinator",
name="region",
field=models.OneToOneField(
help_text="Выберите регион из списка",
on_delete=django.db.models.deletion.PROTECT,
primary_key=True,
related_name="coordinators",
serialize=False,
to="core.region",
verbose_name="Регион",
),
),
migrations.AlterField(
model_name="fundprogram",
name="regions",
field=models.ManyToManyField(
blank=True,
help_text="Выберите регион(ы) для программы",
related_name="programs",
to="core.region",
verbose_name="Регионы",
),
),
]
Loading

0 comments on commit 03bb06b

Please sign in to comment.