adision de bases para trabajo completo de back-v1.0.0

This commit is contained in:
2026-04-08 15:05:29 -07:00
parent 290a32364d
commit 75ecb00a94
89 changed files with 1630 additions and 2350 deletions

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,116 @@
from fastapi import APIRouter, Depends, HTTPException, Query, Header, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from typing import Optional, List
#
from database import get_db
from app.core.auth import get_current_user
from app.modules.users.models import Users # Modelo base de usuario
from app.modules.coments.models import Coments
from app.modules.coments.schema import Commentupdate, CommentCreate, CommentResponse, MessageResponse
from app.modules.coments.services import ComentsService
router = APIRouter(prefix="/coments", tags=["coments"])
security = HTTPBearer()
#================ Create ====================
@router.post("/create", response_model=CommentResponse, status_code=status.HTTP_201_CREATED)
async def create_coments(
data: CommentCreate,
db: Session = Depends(get_db),
current_user: Users = Depends(get_current_user)
):
"""Create a coments - Requires authentication"""
if not current_user:
raise HTTPException(status_code=401, detail="User not found - invalid token")
if current_user.tipo_usuario not in ["root", "admin"]:
raise HTTPException(status_code=403, detail="You don't have permission to create coments")
try:
result = ComentsService.create_coments(db=db, data=data)
return result
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
#================ Get ====================
@router.get("/", response_model=List[CommentResponse])
def get_comentss(
db: Session = Depends(get_db),
current_user: Users = Depends(get_current_user),
skip: int = Query(0, ge=0, description="Number of records to skip"),
limit: int = Query(100, ge=1, le=1000, description="Max number of records to return")
):
"""Get list with pagination - requires authentication"""
if not current_user:
raise HTTPException(status_code=401, detail="Authentication required")
return ComentsService.get_coments(db=db, skip=skip, limit=limit)
#================ Get by ID ====================
@router.get("/{{{entity_name}}_id}", response_model=CommentResponse)
def get_coments_by_id(
coments_id: int,
db: Session = Depends(get_db),
current_user: Users = Depends(get_current_user)
):
"""Get coments by ID - requires authentication"""
if not current_user:
raise HTTPException(status_code=401, detail="Authentication required")
try:
result = ComentsService.get_coments(db=db, coments_id=coments_id, current_user=current_user)
return result
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
#================ Update ====================
@router.patch("/update/{{{entity_name}}_id}", response_model=CommentResponse)
async def update_coments(
coments_id: int,
data: Commentupdate ,
db: Session = Depends(get_db),
current_user: Users = Depends(get_current_user)
):
"""Update existing coments - requires authentication"""
if not current_user:
raise HTTPException(status_code=401, detail="Authentication required")
if current_user.tipo_usuario not in ["root", "admin"]:
raise HTTPException(status_code=403, detail="You don't have permission to update coments")
try:
result = ComentsService.update_coments(
db=db,
coments_id=coments_id,
data=data,
current_user=current_user
)
return result
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
#================ Delete ====================
@router.delete("/delete/{{{entity_name}}_id}", response_model=MessageResponse, status_code=status.HTTP_200_OK)
async def delete_coments(
coments_id: int,
db: Session = Depends(get_db),
current_user: Users = Depends(get_current_user)
):
"""Delete coments by ID - requires authentication"""
if not current_user:
raise HTTPException(status_code=401, detail="Authentication required")
if current_user.tipo_usuario not in ["root", "admin"]:
raise HTTPException(status_code=403, detail="You don't have permission to delete coments")
try:
result = ComentsService.delete_coments(db=db, coments_id=coments_id, current_user=current_user)
return {"message": "coments deleted successfully"}
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))

View File

@@ -6,7 +6,7 @@ import re
from enum import Enum
class CommentCreate(BaseModel):
texto: str = Field(..., max(380), min(30))
texto: str
user_id: Optional[int]
feed_id: Optional[int]
is_active: bool = True

View File

@@ -0,0 +1,63 @@
from sqlalchemy.orm import Session
from datetime import datetime
from typing import Optional
from fastapi import HTTPException
from app.modules.coments.models import Coments
from app.modules.coments.schema import CommentCreate, CommentResponse, Commentupdate, MessageResponse
class ComentsService:
@staticmethod
def create_coments(db: Session, data: CommentCreate):
new_coments = Coments(**data.dict())
db.add(new_coments)
db.commit()
db.refresh(new_coments)
return new_coments
@staticmethod
def get_coments(db: Session, coments_id: int, current_user):
coments = db.query(Coments).filter(Coments.id == coments_id).first()
if not coments:
raise ValueError("coments no encontrado")
return coments
@staticmethod
def update_coments(db: Session, coments_id: int, data:Commentupdate , current_user):
coments = db.query(Coments).filter(Coments.id == coments_id).first()
if not coments:
raise ValueError("coments no encontrado")
if current_user.role not in ["ROOT", "ADMIN"]:
raise ValueError("No tienes permisos para actualizar este coments")
update_data = data.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(coments, key, value)
db.commit()
db.refresh(coments)
return coments
@staticmethod
def delete_coments(db: Session, coments_id: int, current_user):
coments = db.query(Coments).filter(Coments.id == coments_id).first()
if not coments:
raise ValueError("coments no encontrado")
if current_user.role not in ["ROOT", "ADMIN"]:
raise ValueError("No tienes permisos para eliminar este coments")
try:
coments.is_active = False
coments.deleted_at = datetime.utcnow()
coments.deleted_by = current_user.id
db.commit()
db.refresh(coments)
except Exception as e:
db.rollback()
raise ValueError(f"Error al eliminar el coments: {e}")
return {"message": "coments eliminado correctamente"}