54 lines
1.4 KiB
Python
54 lines
1.4 KiB
Python
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from models.family import Comments
|
|
from schemas.comment import CommentCreate, CommentUpdate
|
|
from service.record_service import get_record_by_id
|
|
|
|
|
|
def get_comment_by_id(db: Session, comment_id: int) -> Comments | None:
|
|
result = db.execute(select(Comments).where(Comments.id == comment_id))
|
|
return result.scalar_one_or_none()
|
|
|
|
|
|
def create_comment(db: Session, comment_dto: CommentCreate) -> bool:
|
|
comment = Comments(**comment_dto.model_dump())
|
|
db.add(comment)
|
|
|
|
record = get_record_by_id(db, comment_dto.record_id)
|
|
if record:
|
|
record.comment_count = (record.comment_count or 0) + 1
|
|
|
|
db.commit()
|
|
db.refresh(comment)
|
|
|
|
return True
|
|
|
|
|
|
def update_comment(db: Session, comment_id: int, comment_dto: CommentUpdate) -> bool:
|
|
comment = get_comment_by_id(db, comment_id)
|
|
if not comment:
|
|
return False
|
|
|
|
comment.content = comment_dto.content
|
|
db.commit()
|
|
db.refresh(comment)
|
|
return True
|
|
|
|
|
|
def delete_comment(db: Session, comment_id: int, current_user_id: int) -> bool:
|
|
comment = get_comment_by_id(db, comment_id)
|
|
if not comment:
|
|
return False
|
|
if comment.user_id != current_user_id:
|
|
return False
|
|
|
|
record = get_record_by_id(db, comment.record_id)
|
|
if record and record.comment_count and record.comment_count > 0:
|
|
record.comment_count -= 1
|
|
|
|
db.delete(comment)
|
|
db.commit()
|
|
|
|
return True
|