points added; rating still isn't fixed

This commit is contained in:
DmitryGantimurov 2023-08-08 19:00:06 +03:00
parent 5bdad31dae
commit bd863bc911
6 changed files with 69 additions and 20 deletions

View File

@ -135,7 +135,7 @@ def create_user(nickname: Annotated[str, Form()], password: Annotated[str, Form(
if database.query(models.User).filter(models.User.nickname == nickname).first() == None: if database.query(models.User).filter(models.User.nickname == nickname).first() == None:
new_user = models.User(nickname=nickname, hashed_password=utils.get_password_hash(password), new_user = models.User(nickname=nickname, hashed_password=utils.get_password_hash(password),
name=name, surname=surname) name=name, surname=surname, reg_date=datetime.date.today())
database.add(new_user) database.add(new_user)
database.commit() database.commit()
database.refresh(new_user) # обновляем состояние объекта database.refresh(new_user) # обновляем состояние объекта
@ -173,26 +173,27 @@ async def read_own_items(
return [{"Current user name": current_user.name, "Current user surname": current_user.surname}] return [{"Current user name": current_user.name, "Current user surname": current_user.surname}]
# начисляем баллы пользователю # изменяем рейтинг пользователя
@app.post("/api/user/rating") @app.post("/api/user/rating")
def add_points(data: schemas.AddPoints, current_user: Annotated[schemas.User, Depends(utils.get_current_user)]): def add_points(data: schemas.AddRating, current_user: Annotated[schemas.User, Depends(utils.get_current_user)]):
if current_user.id != data.user_id: if current_user.id != data.user_id:
user = utils.get_user(data.user_id) user = utils.get_user_by_id(db=database, user_id=data.user_id)
if not user: if not user:
raise HTTPException(status_code=404, detail="Item not found") raise HTTPException(status_code=404, detail="Item not found")
user.rating = (user.rating*user.num_of_ratings + data.rate)/(user.num_of_ratings + 1)
user.num_of_ratings += 1 user.num_of_ratings += 1
user.rating = (user.rating + data.rate)/user.num_of_ratings
return {"Success": True} return {"Success": True}
# получаем данные о баллах пользователя # получаем рейтинг пользователя
@app.get("/api/user/rating") @app.get("/api/user/rating")
def add_points(user_id: int): def add_points(user_id: int):
user = utils.get_user(user_id) user = utils.get_user_by_id(db=database, user_id=user_id)
if not user: if not user:
raise HTTPException(status_code=404, detail="Item not found") raise HTTPException(status_code=404, detail="Item not found")
return {"rating": user.rating} return {"rating": user.rating}
# Отправляем стихи # Отправляем стихи
@app.get("/api/user/poem") # пока не работает @app.get("/api/user/poem") # пока не работает
def poems_to_front(): # db: Annotated[Session, Depends(utils.get_db)] def poems_to_front(): # db: Annotated[Session, Depends(utils.get_db)]
@ -244,5 +245,11 @@ async def react_app(req: Request, rest_of_path: str):
@app.post("api/announcement/dispose") @app.post("api/announcement/dispose")
def dispose(despose_data: schemas.DisposeData, current_user: Annotated[schemas.User, Depends(utils.get_current_user)]): def dispose(data: schemas.TrashboxResponse, current_user: Annotated[schemas.User, Depends(utils.get_current_user)]):
current_user.rating += 60 current_user.points += 60
new_trashox = models.Trashbox(user_id=current_user.id, date_of_chose=datetime.date.today(), name=data.Name,
latitude=data.Lat, longtitude=data.Lng, address=data.Address, category=data.Categories)
database.add(new_trashox)
database.commit()
database.refresh(new_trashox) # обновляем состояние объекта

View File

@ -13,7 +13,8 @@ class User(Base):#класс пользователя
name = Column(String, nullable=True)#имя пользователя name = Column(String, nullable=True)#имя пользователя
surname = Column(String)#фамилия пользователя surname = Column(String)#фамилия пользователя
disabled = Column(Boolean, default=False) disabled = Column(Boolean, default=False)
rating = Column(Integer, default=0) #баллы пользователя rating = Column(Integer, default=0) # рейтинг пользователя (показатель надежности)
points = Column(Integer, default=0) # баллы пользователя (заслуги перед платформой)
num_of_ratings = Column(Integer, default=0) # количество оценок (т.е. то, сколько раз другие пользователи оценили текущего) num_of_ratings = Column(Integer, default=0) # количество оценок (т.е. то, сколько раз другие пользователи оценили текущего)
reg_date = Column(Date) # дата регистрации reg_date = Column(Date) # дата регистрации
@ -47,11 +48,11 @@ class Trashbox(Base): #класс мусорных баков
id = Column(Integer, primary_key=True, index=True)#айди id = Column(Integer, primary_key=True, index=True)#айди
user_id = Column(Integer, ForeignKey("users.id")) # айди выбравшего мусорку user_id = Column(Integer, ForeignKey("users.id")) # айди выбравшего мусорку
name = Column(String, nullable=True)#имя пользователя name = Column(String, nullable=True)#название мусорки
address = Column(String) address = Column(String)
latitude = Column(Integer) latitude = Column(Integer)
longtitude = Column(Integer) longtitude = Column(Integer)
category = Column(String) #категория продукта из объявления category = Column(String) #типы мусора (из тех, что возвращает API мусорки)
date_of_chose = Column(Date) # Дата выбора мусорки пользователем date_of_chose = Column(Date) # Дата выбора мусорки пользователем
user = relationship("User", back_populates="trashboxes_chosen") user = relationship("User", back_populates="trashboxes_chosen")

View File

@ -33,6 +33,7 @@ class Announcement(BaseModel):
arbitrary_types_allowed=True arbitrary_types_allowed=True
# Не используется
class PutAnnInDB(BaseModel): class PutAnnInDB(BaseModel):
name: Annotated[str, Form()] name: Annotated[str, Form()]
category: Annotated[str, Form()] category: Annotated[str, Form()]
@ -59,6 +60,7 @@ class User(BaseModel):
nickname: str nickname: str
name: Union[str, None] = None name: Union[str, None] = None
surname: Union[str, None] = None surname: Union[str, None] = None
reg_date: date
disabled: Union[bool, None] = False disabled: Union[bool, None] = False
items: list[Announcement] = [] items: list[Announcement] = []
@ -97,13 +99,7 @@ class SortAnnouncements(BaseModel):
category: Union[str, None] = None category: Union[str, None] = None
# booked_by: Union[int, None] = None # booked_by: Union[int, None] = None
class DisposeData(BaseModel):
ann_id: int # id объявления
trash_id: int # id мусорки
trash_category: str # категория мусора
# схема для начисления баллов # схема для начисления баллов
class AddPoints(BaseModel): class AddRating(BaseModel):
user_id: int user_id: int
rate: int rate: int

View File

@ -87,7 +87,8 @@ async def get_current_user(db: Annotated[Session, Depends(get_db)], token: Annot
user = get_user_by_id(db, user_id=token_data.user_id) user = get_user_by_id(db, user_id=token_data.user_id)
if user is None: if user is None:
raise credentials_exception raise credentials_exception
return schemas.User(id=user.id, nickname=user.nickname, name=user.name, surname=user.surname, disabled=user.disabled, items=user.announcements) return schemas.User(id=user.id, nickname=user.nickname, name=user.name, surname=user.surname,
disabled=user.disabled, items=user.announcements, reg_date=user.reg_date)
async def get_current_active_user( async def get_current_active_user(

View File

@ -0,0 +1,38 @@
"""points field added to User model
Revision ID: a991606e0a35
Revises: ee035dd94fbb
Create Date: 2023-08-08 17:55:21.011642
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a991606e0a35'
down_revision = 'ee035dd94fbb'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
# with op.batch_alter_table('trashboxes', schema=None) as batch_op:
# batch_op.create_foreign_key(None, 'users', ['user_id'], ['id'])
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('points', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('points')
# with op.batch_alter_table('trashboxes', schema=None) as batch_op:
# batch_op.drop_constraint(None, type_='foreignkey')
# ### end Alembic commands ###

6
package-lock.json generated Normal file
View File

@ -0,0 +1,6 @@
{
"name": "porridger",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}