Skip to content

Commit

Permalink
Merge pull request #26 from End-rey/backend
Browse files Browse the repository at this point in the history
make more functionals
  • Loading branch information
End-rey authored Feb 25, 2024
2 parents 0f83a2f + 4d05f1f commit af733e0
Show file tree
Hide file tree
Showing 15 changed files with 387 additions and 103 deletions.
13 changes: 13 additions & 0 deletions backend/app/common/AuthUser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@

from typing import Optional, Self


class AuthUser(object):
def __init__(self, user_id: Optional[int] = None):
self.user_id = user_id
self.city_id = None

def __new__(cls) -> Self:
if not hasattr(cls, 'instance'):
cls.instance = super(AuthUser, cls).__new__(cls)
return cls.instance
29 changes: 29 additions & 0 deletions backend/app/common/keyboards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from app.keyboards.reply import get_reply_keyboard
from aiogram import types


web_app_auth = types.WebAppInfo(
url="https://end-rey.github.io/DonorSearch-Module/auth")


web_up_profile = types.WebAppInfo(
url="https://end-rey.github.io/DonorSearch-Module/profile"
)
web_up_donation = types.WebAppInfo(
url="https://end-rey.github.io/DonorSearch-Module/"
)

keyboard_profile = get_reply_keyboard("Профиль",
"Запланировать донацию",
"Список центров сдачи крови",
"Мои донации",
"Выйти",
web_app={
0: web_up_profile,
1: web_up_donation
}, sizes=(2,2))


keyboard_login_register = get_reply_keyboard(
"Вход / Регистрация", web_app={0: web_app_auth}, sizes=(1,))

24 changes: 18 additions & 6 deletions backend/app/database/bloodcentre/Bloodcentre.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from sqlalchemy import Integer, String, Boolean
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import Float, Integer, String, Boolean, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database.models import Base

Expand All @@ -8,32 +8,44 @@ class City(Base):

id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String, nullable=False)
region_id: Mapped[int] = mapped_column(Integer, nullable=False)
latitude: Mapped[float] = mapped_column(Float, nullable=False)
longitude: Mapped[float] = mapped_column(Float, nullable=False)
region_id: Mapped[int] = mapped_column(Integer, ForeignKey("region.id"), nullable=False)

region = relationship("Region", back_populates="cities")
bloodcentres = relationship("BloodCentre", back_populates="city")

class Region(Base):
__tablename__ = "region"

id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String, nullable=False)
country_id: Mapped[int] = mapped_column(Integer, nullable=False)
country_id: Mapped[int] = mapped_column(Integer, ForeignKey("country.id"), nullable=False)

cities = relationship("City", back_populates="region")
country = relationship("Country", back_populates="regions")

class Country(Base):
__tablename__ = "country"

id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String, nullable=False)

regions = relationship("Region", back_populates="country")

class BloodCentre(Base):
__tablename__ = "bloodcentre"

id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String, nullable=False)
address: Mapped[str] = mapped_column(String, nullable=False)
city_id: Mapped[int] = mapped_column(Integer, nullable=False)
city_id: Mapped[int] = mapped_column(Integer, ForeignKey("city.id"), nullable=False)
is_no_registration: Mapped[bool] = mapped_column(Boolean, nullable=False)
is_typing: Mapped[bool] = mapped_column(Boolean, nullable=False)
is_work_on_sat: Mapped[bool] = mapped_column(Boolean, nullable=False)
is_work_on_sun: Mapped[bool] = mapped_column(Boolean, nullable=False)
schedule: Mapped[str] = mapped_column(String, nullable=False)
phone_numbers: Mapped[str] = mapped_column(String, nullable=False)
is_closed: Mapped[bool] = mapped_column(Boolean, nullable=False)
is_closed: Mapped[bool] = mapped_column(Boolean, nullable=False)

city = relationship("City", back_populates="bloodcentres")
71 changes: 71 additions & 0 deletions backend/app/database/bloodcentre/bloodcentre_orm_handlres.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
from datetime import datetime
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.bloodcentre.Bloodcentre import BloodCentre, Country, City, Region
from app.logger import get_logger
logger = get_logger()

async def create_blood_centre(session: AsyncSession, dict: dict):
new_centre = BloodCentre(
name=dict['name'],
address=dict['address'],
city_id=dict['city_id'],
is_no_registration=dict['is_no_registration'],
is_typing=dict['is_typing'],
is_work_on_sat=dict['is_work_on_sat'],
is_work_on_sun=dict['is_work_on_sun'],
schedule=dict['schedule'],
phone_numbers=dict['phone_numbers'],
is_closed=dict['is_closed']
)
session.add(new_centre)
await session.commit()

async def get_blood_centre_by_id(session: AsyncSession, centre_id: int):
stmt = select(BloodCentre).filter(BloodCentre.id == centre_id)
result = await session.execute(stmt)
return result.scalars().first()

async def get_blood_centres_by_city(session: AsyncSession, city_id: int):
stmt = select(BloodCentre).filter(BloodCentre.city_id == city_id)
result = await session.execute(stmt)
return result.scalars().all()

async def update_blood_centre(session: AsyncSession, centre_id: int, **kwargs):
stmt = select(BloodCentre).filter(BloodCentre.id == centre_id)
result = await session.execute(stmt)
centre = result.scalars().first()
if centre:
for attr, value in kwargs.items():
setattr(centre, attr, value)
await session.commit()
else:
raise ValueError("Blood Centre not found")

async def delete_blood_centre(session: AsyncSession, centre_id: int):
stmt = select(BloodCentre).filter(BloodCentre.id == centre_id)
result = await session.execute(stmt)
centre = result.scalars().first()
if centre:
session.delete(centre)
await session.commit()
else:
raise ValueError("Blood Centre not found")

async def get_city_by_name(session: AsyncSession, city_name: str):
stmt = select(City).filter(City.name == city_name)
result = await session.execute(stmt)
return result.scalars().first()

async def get_city_by_coordinates(session: AsyncSession, latitude: float, longitude: float):
stmt = select(
City,
func.sqrt(
func.pow(func.radians(latitude) - func.radians(City.latitude), 2) +
func.pow(func.radians(longitude) - func.radians(City.longitude), 2)
).label("distance")
).order_by("distance")
result = await session.execute(stmt)
nearest_city = result.scalars().first()
return nearest_city
21 changes: 12 additions & 9 deletions backend/app/database/donation/Donation.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
from sqlalchemy import Column, Enum, Integer, String, DateTime, Boolean, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from enum import Enum
from sqlalchemy import Column, Enum as PgEnum, Integer, String, DateTime, Boolean, func, ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

from app.database.models import Base

class DonationType(Enum):
blood: "кровь"
plasma: "плазма"
platelets: "тромбоциты"
erythrocytes: "эритроциты"
leukocytes: "гранулоциты"
blood = "blood"
plasma = "plasma"
trombs = "trombs"
erits = "erits"
granuls = "granuls"

class Donation(Base):
__tablename__ = "donation"

id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
date: Mapped[DateTime] = mapped_column(DateTime, nullable=False)
user_id: Mapped[int] = mapped_column(Integer, nullable=False)
donation_type_id: Mapped[DonationType] = mapped_column(DonationType, nullable=False)
user_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id"), nullable=False)
donation_type_id: Mapped[DonationType] = mapped_column(PgEnum(DonationType, name="donation_type"), nullable=False)
is_commerce: Mapped[bool] = mapped_column(Boolean, nullable=False)
is_confirmed: Mapped[bool] = mapped_column(Boolean, nullable=False)
is_in_stationary_point: Mapped[bool] = mapped_column(Boolean, nullable=False)
blood_centre_id: Mapped[int] = mapped_column(Integer, nullable=False)

user = relationship("User", back_populates="donations")
50 changes: 50 additions & 0 deletions backend/app/database/donation/donation_orm_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from datetime import datetime
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.donation.Donation import Donation, DonationType
from app.logger import get_logger
logger = get_logger()


async def get_all_donations(session: AsyncSession):
return await session.execute(select(Donation))


async def get_donation_by_id(session: AsyncSession, donation_id: int):
result = await session.execute(select(Donation).filter(Donation.id == donation_id))
donation = result.scalars().first()
return donation


async def get_donations_by_user_id(session: AsyncSession, user_id: int) -> list[Donation]:
result = await session.execute(select(Donation).filter(Donation.user_id == user_id))
donation = result.scalars().all()
return donation


async def add_donation(session: AsyncSession, dict: dict):
try:
date = datetime.strptime(dict['donationData'], '%Y-%m-%dT%H:%M:%S.%fZ').date()
new_donation = Donation(
date = date,
user_id = dict['user_id'],
donation_type_id = DonationType(dict['donationType']),
is_commerce = dict['donationPrice'] == 'money',
is_confirmed = dict['donationCertificateDate'] == 'today',
is_in_stationary_point = dict['donationPlace'] == 'station',
blood_centre_id = 0
)
session.add(new_donation)
await session.commit()
return new_donation.id
except Exception as e:
logger.error(e)
await session.rollback()
return None


async def update_Donation(session: AsyncSession, donation_id, **kwargs):
stmt = update(Donation).where(Donation.id == donation_id).values(**kwargs)
await session.execute(stmt)
await session.commit()
67 changes: 34 additions & 33 deletions backend/app/database/users/User.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,48 @@
from sqlalchemy import Enum, Integer, String, DateTime, Boolean
from enum import Enum
from sqlalchemy import Enum as PgEnum, Integer, String, DateTime, Boolean
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from app.database.models import Base
from sqlalchemy.orm import relationship

class Gender(Enum):
male = "мужчина"
female = "женщина"

class User(Base):
__tablename__ = "users"

date_joined: Mapped[DateTime] = mapped_column(DateTime, nullable=False)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
username: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
first_name: Mapped[str] = mapped_column(String(255), nullable=False)
email: Mapped[str] = mapped_column(String, unique=True, nullable=False)
phone: Mapped[str] = mapped_column(String, nullable=False)
password: Mapped[str] = mapped_column(String, nullable=False)
last_name: Mapped[str] = mapped_column(String(255), nullable=True)
middle_name: Mapped[str] = mapped_column(String(255), nullable=True)
maiden_name: Mapped[str] = mapped_column(String(255), nullable=True)
birth_date: Mapped[DateTime] = mapped_column(DateTime, nullable=True)
gender: Mapped[Gender] = mapped_column(PgEnum(Gender, name="gender"), nullable=True)
login_via_phone: Mapped[bool] = mapped_column(Boolean, nullable=True)
about: Mapped[str] = mapped_column(String(130), nullable=True)
city_id: Mapped[int] = mapped_column(Integer, nullable=False)
is_in_top_20: Mapped[bool] = mapped_column(Boolean, nullable=True)
is_in_top_100: Mapped[bool] = mapped_column(Boolean, nullable=True)
photo: Mapped[str] = mapped_column(String, nullable=True)
blood_group: Mapped[str] = mapped_column(String, nullable=False)
is_email_verified: Mapped[str] = mapped_column(String, nullable=False)
is_phone_verified: Mapped[str] = mapped_column(String, nullable=False)
email_reconfirmed_at: Mapped[str] = mapped_column(String, nullable=True)
phone_reconfirmed_at: Mapped[str] = mapped_column(String, nullable=True)
legacy_avatar: Mapped[str] = mapped_column(String, nullable=True)
start_donor_year: Mapped[int] = mapped_column(Integer, nullable=False)
referal_code: Mapped[str] = mapped_column(String, nullable=True)
parent_user_id: Mapped[int] = mapped_column(Integer, nullable=True)
donor_status: Mapped[str] = mapped_column(String, nullable=False)
managed_organizations: Mapped[str] = mapped_column(String, nullable=True)
joined_events: Mapped[str] = mapped_column(String, nullable=True)
joined_organizations: Mapped[str] = mapped_column(String, nullable=True)
donor_certificate: Mapped[bool] = mapped_column(Boolean, nullable=True)

# id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# date_joined: Mapped[DateTime] = mapped_column(DateTime, nullable=False)
# username: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
# first_name: Mapped[str] = mapped_column(String(255), nullable=False)
# last_name: Mapped[str] = mapped_column(String(255))
# middle_name: Mapped[str] = mapped_column(String(255))
# maiden_name: Mapped[str] = mapped_column(String(255))
# birth_date: Mapped[DateTime] = mapped_column(DateTime)
# gender: Mapped[Gender] = mapped_column(Gender)
# email: Mapped[str] = mapped_column(String, unique=True, nullable=False)
# phone: Mapped[str] = mapped_column(String, unique=True, nullable=False)
# password: Mapped[str] = mapped_column(String, nullable=False)
# login_via_phone: Mapped[bool] = mapped_column(Boolean)
# about: Mapped[str] = mapped_column(String(130))
# city_id: Mapped[int] = mapped_column(Integer, nullable=False)
# is_in_top_20: Mapped[bool] = mapped_column(Boolean)
# is_in_top_100: Mapped[bool] = mapped_column(Boolean)
# photo: Mapped[str] = mapped_column(String, nullable=False)
# blood_group: Mapped[str] = mapped_column(String, nullable=False)
# is_email_verified: Mapped[str] = mapped_column(String, nullable=False)
# is_phone_verified: Mapped[str] = mapped_column(String, nullable=False)
# email_reconfirmed_at: Mapped[str] = mapped_column(String)
# phone_reconfirmed_at: Mapped[str] = mapped_column(String)
# legacy_avatar: Mapped[str] = mapped_column(String, nullable=False)
# start_donor_year: Mapped[int] = mapped_column(Integer, nullable=False)
# referal_code: Mapped[str] = mapped_column(String, nullable=False)
# parent_user_id: Mapped[int] = mapped_column(Integer, nullable=False)
# donor_status: Mapped[str] = mapped_column(String, nullable=False)
# managed_organizations: Mapped[str] = mapped_column(String, nullable=False)
# joined_events: Mapped[str] = mapped_column(String, nullable=False)
# joined_organizations: Mapped[str] = mapped_column(String, nullable=False)
# donor_certificate: Mapped[bool] = mapped_column(Boolean)
donations = relationship("Donation", back_populates="user")

Loading

0 comments on commit af733e0

Please sign in to comment.