-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature/add_message_history #336
base: develop
Are you sure you want to change the base?
Changes from 18 commits
d5ca066
6ee2768
984714b
42e13b8
9e70f53
b037146
19f2ead
4860b76
2f84ec0
b59430b
e139cad
77df88b
4ccd67c
8b99676
018ac55
0cdcde0
cc8711a
65baead
cff6ebd
a996312
8195063
e204f35
25f163c
c4f2094
c753006
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,23 +5,30 @@ | |
from telegram.ext import CallbackContext | ||
|
||
from src.bot.api_services import ( | ||
get_history_service, | ||
get_member_service_callback, | ||
get_report_service_callback, | ||
get_shift_service_callback, | ||
) | ||
from src.bot.services import BotService | ||
from src.bot.ui import DAILY_TASK_BUTTONS | ||
from src.core.db.db import get_session | ||
from src.core.db.models import Report | ||
from src.core.db.models import MessageHistory, Report | ||
from src.core.settings import settings | ||
|
||
|
||
async def send_no_report_reminder_job(context: CallbackContext) -> None: | ||
"""Отправить напоминание об отчёте.""" | ||
member_session_generator = get_session() | ||
history_session = get_session() | ||
history_service = await get_history_service(history_session) | ||
member_service = await get_member_service_callback(member_session_generator) | ||
bot_service = BotService(context) | ||
bot_service = BotService(context, history_service) | ||
members = await member_service.get_members_with_no_reports() | ||
if members: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Поле shift_id обязательное у модели Member, поэтому эта проверка не имеет смысла. Можно ниже просто подставлять member.shift_id. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Поле у Member обязательное, а если список пустой будет то ошибка вылетит. Как раз и проверяю, что список не пустой такое наверно маловероятно, но наверное возможно There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Всё просто. Если в members придёт пустой список, то генератор списка также вернёт пустой список. А если не пустой, то смену возьмёт из member, как я написал выше.
Так точно ошибки не будет. |
||
shift_id = members[0].shift_id | ||
else: | ||
shift_id = None | ||
send_message_tasks = [ | ||
bot_service.send_message( | ||
member.user, | ||
|
@@ -31,6 +38,8 @@ async def send_no_report_reminder_job(context: CallbackContext) -> None: | |
f"Напоминаем, что за каждое выполненное задание ты получаешь виртуальные " | ||
f"\"ломбарьерчики\", которые можешь обменять на призы и подарки!" | ||
), | ||
MessageHistory.Event.REPORT_MENTION, | ||
shift_id, | ||
) | ||
for member in members | ||
] | ||
|
@@ -42,18 +51,24 @@ async def send_daily_task_job(context: CallbackContext) -> None: | |
shift_session = get_session() | ||
report_session = get_session() | ||
member_session = get_session() | ||
history_session = get_session() | ||
shift_service = await get_shift_service_callback(shift_session) | ||
report_service = await get_report_service_callback(report_session) | ||
member_service = await get_member_service_callback(member_session) | ||
history_service = await get_history_service(history_session) | ||
|
||
await shift_service.start_prepared_shift() | ||
|
||
bot_service = BotService(context) | ||
bot_service = BotService(context, history_service) | ||
await report_service.set_status_to_waiting_reports(Report.Status.SKIPPED) | ||
await member_service.exclude_lagging_members(context.application) | ||
task, members = await report_service.get_today_task_and_active_members(date.today().day) | ||
await report_service.create_daily_reports(members, task) | ||
task_photo = urljoin(settings.APPLICATION_URL, task.url) | ||
if members: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Здесь так же. |
||
shift_id = members[0].shift_id | ||
else: | ||
shift_id = None | ||
send_message_tasks = [ | ||
bot_service.send_photo( | ||
member.user, | ||
|
@@ -71,6 +86,8 @@ async def send_daily_task_job(context: CallbackContext) -> None: | |
f"Не забудь сделать фотографию, как ты выполняешь задание, и отправить на проверку." | ||
), | ||
DAILY_TASK_BUTTONS, | ||
MessageHistory.Event.GET_TASK, | ||
shift_id, | ||
) | ||
for member in members | ||
] | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
"""add model MessageHistory | ||
|
||
Revision ID: 5163a5140a0a | ||
Revises: 5a1ecb2d17c4 | ||
Create Date: 2023-05-13 16:34:39.932886 | ||
|
||
""" | ||
import sqlalchemy as sa | ||
from alembic import op | ||
from sqlalchemy.dialects import postgresql | ||
|
||
# revision identifiers, used by Alembic. | ||
revision = '5163a5140a0a' | ||
down_revision = '5a1ecb2d17c4' | ||
branch_labels = None | ||
depends_on = None | ||
|
||
|
||
STATUS_ENUM_POSTGRES = postgresql.ENUM( | ||
'registration', | ||
'get_task', | ||
'report_mention', | ||
'request_accepted', | ||
'request_canceled', | ||
'task_accepted', | ||
'task_not_accepted', | ||
'exclude_from_shift', | ||
'shift_ended', | ||
'shift_canceled', | ||
'start_shift_changed', | ||
name='message_history_event', | ||
create_type=False | ||
) | ||
STATUS_ENUM = sa.Enum( | ||
'registration', | ||
'get_task', | ||
'report_mention', | ||
'request_accepted', | ||
'request_canceled', | ||
'task_accepted', | ||
'task_not_accepted', | ||
'exclude_from_shift', | ||
'shift_ended', | ||
'shift_canceled', | ||
'start_shift_changed', | ||
name='message_history_event' | ||
) | ||
STATUS_ENUM.with_variant(STATUS_ENUM_POSTGRES, 'postgresql') | ||
|
||
def upgrade(): | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.create_table('message_history', | ||
sa.Column('user_id', sa.UUID(), nullable=True), | ||
sa.Column('message', sa.String(length=400), nullable=False), | ||
sa.Column('message_id', sa.BigInteger(), nullable=False), | ||
sa.Column('event', STATUS_ENUM, nullable=False), | ||
sa.Column('shift_id', sa.UUID(), nullable=True), | ||
sa.Column('id', sa.UUID(), nullable=False), | ||
sa.Column('created_at', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False), | ||
sa.Column('updated_at', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False), | ||
sa.ForeignKeyConstraint(['shift_id'], ['shifts.id'], ), | ||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), | ||
sa.PrimaryKeyConstraint('id') | ||
) | ||
# ### end Alembic commands ### | ||
|
||
|
||
def downgrade(): | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.drop_table('message_history') | ||
STATUS_ENUM.drop(op.get_bind(), checkfirst=True) | ||
# ### end Alembic commands ### |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -302,3 +302,36 @@ class AdministratorInvitation(Base): | |
|
||
def __repr__(self) -> str: | ||
return f"<AdministratorInvitation: {self.id}, email: {self.email}, surname: {self.surname}, name: {self.name}>" | ||
|
||
|
||
class MessageHistory(Base): | ||
"""Хрениние истории отправленных сообщений.""" | ||
|
||
class Event(str, enum.Enum): | ||
"""Статус отправленного сообщения.""" | ||
|
||
REGISTRATION = "registration" | ||
GET_TASK = "get_task" | ||
REPORT_MENTION = "report_mention" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Именование статусов потом нужно будет пересмотреть. Не все удачные. |
||
REQUEST_ACCEPTED = "request_accepted" | ||
REQUEST_CANCELED = "request_canceled" | ||
TASK_ACCEPTED = "task_accepted" | ||
TASK_NOT_ACCEPTED = "task_not_accepted" | ||
EXCLUDE_FROM_SHIFT = "exclude_from_shift" | ||
SHIFT_ENDED = "shift_ended" | ||
SHIFT_CANCELED = "shift_canceled" | ||
START_SHIFT_CHANGED = "start_shift_changed" | ||
|
||
__tablename__ = 'message_history' | ||
|
||
user_id = Column(UUID(as_uuid=True), ForeignKey(User.id)) | ||
message = Column(String(400), nullable=False) | ||
message_id = Column(BigInteger, nullable=False) | ||
event = Column( | ||
Enum(Event, name="message_history_event", values_callable=lambda obj: [e.value for e in obj]), | ||
nullable=False, | ||
) | ||
shift_id = Column(UUID(as_uuid=True), ForeignKey(Shift.id)) | ||
|
||
def __repr__(self) -> str: | ||
return f"<MessageHistory: {self.user_id} - {self.status}" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь точно user = None
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это я знаю поэтому и написал user, а не user.id или как-то по другому надо, немного не понял если честно. Сделать как со сменой если не передать юзера то по умолчанию None ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если пользователя нет, то и сообщения сохранять нет смысла.
Здесь, после регистрации пользователь уже есть. Его надо получить и использовать при сохранении.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут получается что функция register только форму с регистрацией кидает, но еще пользователя в базу не сохраняет, это как-то пометить надо будет в event? событие перед формой регистрации?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
я убрал и после update и после register, я написал вызов в функцию web_app_data там как я понял и обновление данных обрабатывается и регистрация