diff --git a/src/db/models.py b/src/db/models.py index b4ac707..5ada838 100644 --- a/src/db/models.py +++ b/src/db/models.py @@ -1,7 +1,7 @@ from __future__ import annotations from datetime import datetime from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship -from sqlalchemy import String, ForeignKey +from sqlalchemy import String, ForeignKey, BigInteger from sqlalchemy.dialects.postgresql import UUID, ARRAY import uuid from typing import List, Optional @@ -60,7 +60,7 @@ class Admins(Base): __tablename__ = "admins" id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) - telegram_id: Mapped[int] = mapped_column(unique=True, nullable=False) + telegram_id: Mapped[int] = mapped_column(BigInteger, unique=True, nullable=False) created_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) available_payment_methods: Mapped[Optional[List[str]]] = mapped_column( ARRAY(String), nullable=True) @@ -70,7 +70,7 @@ class Patients(Base): __tablename__ = "patients" id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) - telegram_id: Mapped[int] = mapped_column(unique=True, nullable=False) + telegram_id: Mapped[int] = mapped_column(BigInteger, unique=True, nullable=False) phone: Mapped[Optional[str]] = mapped_column(nullable=True) created_at: Mapped[datetime] = mapped_column(nullable=False) updated_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) @@ -85,7 +85,7 @@ class Doctors(Base): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) code: Mapped[str] = mapped_column(unique=True, nullable=True) time_zone: Mapped[Optional[str]] = mapped_column(nullable=True) - telegram_id: Mapped[int] = mapped_column(unique=True, nullable=False) + telegram_id: Mapped[int] = mapped_column(BigInteger, unique=True, nullable=False) name: Mapped[str] = mapped_column(nullable=False) available_formats: Mapped[Optional[List[str]] ] = mapped_column(ARRAY(String), nullable=True) diff --git a/src/docbot/handlers/patients/consultation_handler.py b/src/docbot/handlers/patients/consultation_handler.py index 8d965aa..d259c0a 100644 --- a/src/docbot/handlers/patients/consultation_handler.py +++ b/src/docbot/handlers/patients/consultation_handler.py @@ -17,7 +17,9 @@ from docbot.services.patients_service import ( create_patient, update_patient_phone, get_patient_by_telegram_id, is_user_has_phone ) -from docbot.services.doctors_service import get_doctors_payment_link +from docbot.services.doctors_service import ( + get_doctors_payment_link, get_doctor_by_code +) from docbot.services.session_service import create_session from core.logging import logger @@ -68,14 +70,15 @@ async def accept_personal_data_agreement(update: Update, context: ContextTypes.D ] ] - user_id = update.effective_user.id user_data = context.user_data - user_data['telegram_id'] = user_id + user_data['telegram_id'] = user_id = update.effective_user.id + + registered = await get_patient_by_telegram_id(user_id) logger.info(f"User {user_id} initiated consultation process.") - logger.info(f"User exists? {await get_patient_by_telegram_id(user_id)}") + logger.info(f"User exists? {registered}") - if await get_patient_by_telegram_id(user_id): + if registered: await update.message.reply_text( "Вы уже зарегистрированы как пациент. Пожалуйста, продолжайте с записью на консультацию.", parse_mode="Markdown", @@ -92,6 +95,7 @@ async def accept_personal_data_agreement(update: Update, context: ContextTypes.D async def receive_patient_aceptance(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: + logger.info(f"Next function receive_patient_aceptance") user_data = context.user_data await update.callback_query.answer() @@ -276,16 +280,26 @@ async def pay_consultation(update: Update, context: ContextTypes.DEFAULT_TYPE) - user_id = context.user_data['telegram_id'] consultation_date_time = context.user_data['consultation_date_time'] patient = await get_patient_by_telegram_id(user_id) + doctor = await get_doctor_by_code(context.user_data['doctor_number']) await create_session( telegram_id=user_id, phone=patient.phone, consultation_date_time=consultation_date_time, - patient=patient + patient=patient, + doctor_id=doctor.id if doctor else None ) link = await get_doctors_payment_link(context.user_data['doctor_number']) + if not link: + await update.callback_query.answer() + await update.callback_query.message.reply_text( + "❌ Извините, но по введённому серийному номеру врача не найдено ссылки на оплату. Пожалуйста, проверьте правильность введённого номера и попробуйте снова.", + parse_mode="Markdown" + ) + return ConversationHandler.END + await update.callback_query.answer() await update.callback_query.message.reply_text( f"Чтобы оплатить консультацию перейдите по ссылке {link}.", @@ -307,7 +321,7 @@ def get_consultation_handler() -> ConversationHandler: entry_points=[consultation_handler()], states={ SEND_ACKNOWLEDGEMENT_INFO: [CallbackQueryHandler(receive_patient_aceptance, pattern=r"^consult:(accepted|declined)$")], - PROCEED_WITH_CONSULTATION: [CallbackQueryHandler(choose_consultation_type, pattern=r"^consult:proceed$")], + PROCEED_WITH_CONSULTATION: [CallbackQueryHandler(choose_consultation_type, pattern=r"^consult:(proceed_with_consultation|frequent_questions)$")], SELECT_CONSULTATION_TYPE: [CallbackQueryHandler(enter_patient_phone, pattern=r"^consult:(initial_reception|readmission)$")], ENTER_PATIENT_PHONE: [MessageHandler(filters=filters.TEXT & ~filters.COMMAND, callback=receive_patient_phone)], ENTER_DOCTOR_NUMBER: [ diff --git a/src/docbot/services/doctors_service.py b/src/docbot/services/doctors_service.py index 974510f..ec5e7f1 100644 --- a/src/docbot/services/doctors_service.py +++ b/src/docbot/services/doctors_service.py @@ -21,6 +21,15 @@ async def get_doctor(telegram_id: int) -> Doctors | None: return result.scalar_one_or_none() +async def get_doctor_by_code(code: str) -> Doctors | None: + async with AsyncSessionLocal() as session: + result = await session.execute( + select(Doctors) + .where(Doctors.code == code) + ) + return result.scalar_one_or_none() + + async def get_doctors_names() -> Doctors | None: async with AsyncSessionLocal() as session: result = await session.execute( diff --git a/src/docbot/services/session_service.py b/src/docbot/services/session_service.py index 5ec0d6b..1ded613 100644 --- a/src/docbot/services/session_service.py +++ b/src/docbot/services/session_service.py @@ -10,7 +10,7 @@ from core.utils import (generate_session_code, date_time_formatter) from core.logging import logger -async def create_session(telegram_id: int, phone: str, consultation_date_time: str, patient: Patients) -> str: +async def create_session(telegram_id: int, phone: str, consultation_date_time: str, patient: Patients, doctor_id: str) -> str: """ Генерирует уникальный код, сохраняет его вместе с Telegram ID. Возвращает этот код. @@ -22,7 +22,8 @@ async def create_session(telegram_id: int, phone: str, consultation_date_time: s sessions = Sessions( code=code, patient=patient, - sent_at=datetime.utcnow() + sent_at=datetime.utcnow(), + doctor_id=doctor_id ) sessions_code_history = SessionStatusHistory(