Skip to content

Commit

Permalink
Merge pull request #16 from guivaloz:guivaloz/folio-seguimiento
Browse files Browse the repository at this point in the history
Consulta de exhortos
  • Loading branch information
guivaloz authored May 22, 2024
2 parents 3bef415 + 4b5bf01 commit 616d0ca
Show file tree
Hide file tree
Showing 12 changed files with 117 additions and 66 deletions.
2 changes: 1 addition & 1 deletion carina/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def create_app() -> FastAPI:
# Rutas
app.include_router(autoridades, include_in_schema=False)
app.include_router(bitacoras, include_in_schema=False)
app.include_router(distritos)
app.include_router(distritos, include_in_schema=False)
app.include_router(entradas_salidas, include_in_schema=False)
app.include_router(estados)
app.include_router(exh_areas)
Expand Down
4 changes: 4 additions & 0 deletions carina/core/autoridades/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Autoridades, modelos
"""

from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

Expand All @@ -20,6 +21,8 @@ class Autoridad(Base, UniversalMixin):
# Claves foráneas
distrito_id = Column(Integer, ForeignKey("distritos.id"), index=True, nullable=False)
distrito = relationship("Distrito", back_populates="autoridades")
municipio_id = Column(Integer, ForeignKey("municipios.id"), index=True, nullable=False)
municipio = relationship("Municipio", back_populates="autoridades")

# Columnas
clave = Column(String(16), nullable=False, unique=True)
Expand All @@ -28,6 +31,7 @@ class Autoridad(Base, UniversalMixin):
es_extinto = Column(Boolean, nullable=False, default=False)

# Hijos
exh_exhortos = relationship("ExhExhorto", back_populates="autoridad")
usuarios = relationship("Usuario", back_populates="autoridad")

def __repr__(self):
Expand Down
7 changes: 7 additions & 0 deletions carina/core/exh_exhortos/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ class ExhExhorto(Base, UniversalMixin):
# Campo para saber si es un proceso interno o extorno
remitente = Column(Enum(*REMITENTES, name="exh_exhortos_remitentes", native_enum=False), nullable=True)

# Juzgado/Área al que se turna el Exhorto y hará el correspondiente proceso de este
autoridad_id = Column(Integer, ForeignKey("autoridades.id"), index=True, nullable=False)
autoridad = relationship("Autoridad", back_populates="exh_exhortos")

# Número de Exhorto con el que se radica en el Juzgado/Área que se turnó el exhorto. Este número sirve para que el usuario pueda indentificar su exhorto dentro del Juzgado/Área donde se turnó.
numero_exhorto = Column(String(256))

def __repr__(self):
"""Representación"""
return f"<ExhExhorto {self.id}>"
1 change: 1 addition & 0 deletions carina/core/municipios/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class Municipio(Base, UniversalMixin):
nombre = Column(String(256), nullable=False)

# Hijos
autoridades = relationship("Autoridad", back_populates="municipio")
exh_exhortos_origenes = relationship("ExhExhorto", back_populates="municipio_origen")

def __repr__(self):
Expand Down
22 changes: 3 additions & 19 deletions carina/v4/exh_areas/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@

from ...core.permisos.models import Permiso
from ..usuarios.authentications import UsuarioInDB, get_current_active_user
from .crud import get_exh_areas, get_exh_area_with_clave
from .schemas import ExhAreaOut, OneExhAreaOut
from .crud import get_exh_areas
from .schemas import ExhAreaOut

exh_areas = APIRouter(prefix="/v4/exh_areas", tags=["categoria"])
exh_areas = APIRouter(prefix="/v4/exh_areas", tags=["areas"])


@exh_areas.get("", response_model=CustomPage[ExhAreaOut])
Expand All @@ -32,19 +32,3 @@ async def paginado_exh_areas(
except MyAnyError as error:
return CustomPage(success=False, errors=[str(error)])
return paginate(resultados)


@exh_areas.get("/{materia_clave}", response_model=OneExhAreaOut)
async def detalle_exh_area(
current_user: Annotated[UsuarioInDB, Depends(get_current_active_user)],
database: Annotated[Session, Depends(get_db)],
materia_clave: str,
):
"""Detalle de una singular a partir de su clave"""
if current_user.permissions.get("MODULO", 0) < Permiso.VER:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
try:
exh_area = get_exh_area_with_clave(database, materia_clave)
except MyAnyError as error:
return OneExhAreaOut(success=False, errors=[str(error)])
return OneExhAreaOut.model_validate(exh_area)
34 changes: 31 additions & 3 deletions carina/v4/exh_exhortos/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

from sqlalchemy.orm import Session

from carina.core.autoridades.models import Autoridad
from carina.core.exh_areas.models import ExhArea
from lib.exceptions import MyIsDeletedError, MyNotExistsError, MyNotValidParamError
from ...core.estados.models import Estado
from ...core.exh_exhortos.models import ExhExhorto
Expand All @@ -26,8 +28,8 @@ def get_exh_exhortos(database: Session) -> Any:
return consulta.filter_by(estatus="A").order_by(ExhExhorto.id)


def get_exh_exhorto(database: Session, exhorto_origen_id: str) -> ExhExhorto:
"""Consultar un exhorto por su id"""
def get_exh_exhorto_by_exhorto_origen_id(database: Session, exhorto_origen_id: str) -> ExhExhorto:
"""Consultar un exhorto por su exhorto_origen_id"""
try:
uuid.UUID(exhorto_origen_id)
except ValueError as error:
Expand All @@ -40,6 +42,20 @@ def get_exh_exhorto(database: Session, exhorto_origen_id: str) -> ExhExhorto:
return exh_exhorto


def get_exh_exhorto_by_folio_seguimiento(database: Session, folio_seguimiento: str) -> ExhExhorto:
"""Consultar un exhorto por su folio de seguimiento"""
try:
uuid.UUID(folio_seguimiento)
except ValueError as error:
raise MyNotValidParamError("No es un UUID válido") from error
exh_exhorto = database.query(ExhExhorto).filter_by(folio_seguimiento=folio_seguimiento).first()
if exh_exhorto is None:
raise MyNotExistsError("No existe ese exhorto")
if exh_exhorto.estatus != "A":
raise MyIsDeletedError("No es activo ese exhorto, está eliminado")
return exh_exhorto


def create_exh_exhorto(database: Session, exh_exhorto_in: ExhExhortoIn) -> ExhExhorto:
"""Crear un exhorto"""

Expand Down Expand Up @@ -113,7 +129,19 @@ def create_exh_exhorto(database: Session, exh_exhorto_in: ExhExhortoIn) -> ExhEx
exh_exhorto.folio_seguimiento = str(random_uuid)

# Área de recepción, 1 = NO DEFINIDO
exh_exhorto.exh_area_id = 1
exh_exhorto.exh_area = database.query(ExhArea).filter_by(clave="ND").first()

# Juzgado/Área al que se turna el Exhorto, por defecto ND
exh_exhorto.autoridad = database.query(Autoridad).filter_by(clave="ND").first()

# Número de Exhorto con el que se radica en el Juzgado/Área que se turnó el exhorto, por defecto ''
exh_exhorto.numero_exhorto = ""

# Remitente es EXTERNO
exh_exhorto.remitente = "EXTERNO"

# Estado es PENDIENTE
exh_exhorto.estado = "PENDIENTE"

# Iniciar la transaccion, agregar el exhorto
database.add(exh_exhorto)
Expand Down
76 changes: 50 additions & 26 deletions carina/v4/exh_exhortos/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi_pagination.ext.sqlalchemy import paginate

from lib.database import Session, get_db
from lib.exceptions import MyAnyError
from lib.fastapi_pagination_custom_page import CustomPage

from ...core.permisos.models import Permiso
from ..municipios.crud import get_municipio
from ..usuarios.authentications import UsuarioInDB, get_current_active_user
from .crud import create_exh_exhorto, get_exh_exhortos, get_exh_exhorto
from .crud import create_exh_exhorto, get_exh_exhorto_by_folio_seguimiento
from .schemas import (
ExhExhortoConfirmacionDatosExhortoRecibidoOut,
ExhExhortoIn,
Expand All @@ -28,34 +27,19 @@
exh_exhortos = APIRouter(prefix="/v4/exh_exhortos", tags=["exhortos"])


@exh_exhortos.get("", response_model=CustomPage[ExhExhortoOut])
async def paginado_exh_exhortos(
@exh_exhortos.get("/{folio_seguimiento}", response_model=OneExhExhortoOut)
async def detalle_exh_exhorto_con_folio_seguimiento(
current_user: Annotated[UsuarioInDB, Depends(get_current_active_user)],
database: Annotated[Session, Depends(get_db)],
folio_seguimiento: str,
):
"""Paginado de exhortos"""
if current_user.permissions.get("EXH EXHORTOS", 0) < Permiso.VER:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
try:
resultados = get_exh_exhortos(database)
except MyAnyError as error:
return CustomPage(success=False, errors=[str(error)])
return paginate(resultados)


@exh_exhortos.get("/{exhorto_origen_id}", response_model=OneExhExhortoOut)
async def detalle_exh_exhorto(
current_user: Annotated[UsuarioInDB, Depends(get_current_active_user)],
database: Annotated[Session, Depends(get_db)],
exhorto_origen_id: str,
):
"""Detalle de una exhorto a partir de su id"""
"""Detalle de un exhorto a partir de su folio de seguimiento"""
if current_user.permissions.get("EXH EXHORTOS", 0) < Permiso.VER:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")

# Consultar el exhorto
try:
exh_exhorto = get_exh_exhorto(database, exhorto_origen_id)
exh_exhorto = get_exh_exhorto_by_folio_seguimiento(database, folio_seguimiento)
except MyAnyError as error:
return OneExhExhortoOut(success=False, errors=[str(error)])

Expand All @@ -73,7 +57,6 @@ async def detalle_exh_exhorto(
tipoParteNombre=exh_exhorto_parte.tipo_parte_nombre,
)
)
exh_exhorto.partes = partes

# Copiar los archivos del exhorto a instancias de ExhExhortoArchivoOut
archivos = []
Expand All @@ -86,10 +69,51 @@ async def detalle_exh_exhorto(
tipoDocumento=exh_exhorto_archivo.tipo_documento,
)
)
exh_exhorto.archivos = archivos

# Definir la clave INEGI del municipio de destino
municipio_destino = get_municipio(database, exh_exhorto.municipio_destino_id)

# Definir la clave INEGI del estado de destino
estado_destino = municipio_destino.estado

# Definir datos del exhorto a entregar
ext_extorto_data = ExhExhortoOut(
exhortoOrigenId=exh_exhorto.exhorto_origen_id,
folioSeguimiento=exh_exhorto.folio_seguimiento,
estadoDestinoId=estado_destino.clave,
estadoDestinoNombre=estado_destino.nombre,
municipioDestinoId=municipio_destino.clave,
municipioDestinoNombre=municipio_destino.nombre,
materiaClave=exh_exhorto.materia.clave,
materiaNombre=exh_exhorto.materia.nombre,
estadoOrigenId=exh_exhorto.municipio_origen.estado.clave,
estadoOrigenNombre=exh_exhorto.municipio_origen.estado.nombre,
municipioOrigenId=exh_exhorto.municipio_origen.clave,
municipioOrigenNombre=exh_exhorto.municipio_origen.nombre,
juzgadoOrigenId=exh_exhorto.juzgado_origen_id,
juzgadoOrigenNombre=exh_exhorto.juzgado_origen_nombre,
numeroExpedienteOrigen=exh_exhorto.numero_expediente_origen,
numeroOficioOrigen=exh_exhorto.numero_oficio_origen,
tipoJuicioAsuntoDelitos=exh_exhorto.tipo_juicio_asunto_delitos,
juezExhortante=exh_exhorto.juez_exhortante,
partes=partes,
fojas=exh_exhorto.fojas,
diasResponder=exh_exhorto.dias_responder,
tipoDiligenciacionNombre=exh_exhorto.tipo_diligenciacion_nombre,
fechaOrigen=exh_exhorto.fecha_origen,
observaciones=exh_exhorto.observaciones,
archivos=archivos,
fechaHoraRecepcion=exh_exhorto.creado,
municipioTurnadoId=exh_exhorto.autoridad.municipio.clave,
municipioTurnadoNombre=exh_exhorto.autoridad.municipio.nombre,
areaTurnadoId=exh_exhorto.exh_area.clave,
areaTurnadoNombre=exh_exhorto.exh_area.nombre,
numeroExhorto=exh_exhorto.numero_exhorto,
urlInfo="https://carina.justiciadigital.gob.mx/",
)

# Entregar
return OneExhExhortoOut(success=True, data=exh_exhorto)
return OneExhExhortoOut(success=True, data=ext_extorto_data)


@exh_exhortos.post("", response_model=OneExhExhortoConfirmacionDatosExhortoRecibidoOut)
Expand Down
16 changes: 14 additions & 2 deletions carina/v4/exh_exhortos/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,20 @@ class ExhExhortoIn(BaseModel):
class ExhExhortoOut(ExhExhortoIn):
"""Esquema para entregar exhortos"""

id: int | None = None
model_config = ConfigDict(from_attributes=True)
folioSeguimiento: str | None = None
estadoDestinoId: int | None = None
estadoDestinoNombre: str | None = None
municipioDestinoNombre: str | None = None
materiaNombre: str | None = None
estadoOrigenNombre: str | None = None
municipioOrigenNombre: str | None = None
fechaHoraRecepcion: datetime | None = None
municipioTurnadoId: int | None = None
municipioTurnadoNombre: str | None = None
areaTurnadoId: str | None = None
areaTurnadoNombre: str | None = None
numeroExhorto: str | None = None
urlInfo: str | None = None


class OneExhExhortoOut(OneBaseOut):
Expand Down
4 changes: 2 additions & 2 deletions carina/v4/exh_exhortos_archivos/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@

from lib.exceptions import MyIsDeletedError, MyNotExistsError

from ..exh_exhortos.crud import get_exh_exhorto
from ..exh_exhortos.crud import get_exh_exhorto_by_exhorto_origen_id
from ...core.exh_exhortos_archivos.models import ExhExhortoArchivo


def get_exh_exhortos_archivos(database: Session, exhorto_origen_id: str = None) -> Any:
"""Consultar los archivos activos"""
consulta = database.query(ExhExhortoArchivo)
if exhorto_origen_id is not None:
exh_exhorto = get_exh_exhorto(database, exhorto_origen_id)
exh_exhorto = get_exh_exhorto_by_exhorto_origen_id(database, exhorto_origen_id)
consulta = consulta.filter_by(exh_exhorto_id=exh_exhorto.id)
return consulta.filter_by(estatus="A").order_by(ExhExhortoArchivo.id)

Expand Down
4 changes: 2 additions & 2 deletions carina/v4/exh_exhortos_archivos/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from lib.google_cloud_storage import upload_file_to_gcs

from carina.core.permisos.models import Permiso
from carina.v4.exh_exhortos.crud import get_exh_exhorto, update_set_exhorto
from carina.v4.exh_exhortos.crud import get_exh_exhorto_by_exhorto_origen_id, update_set_exhorto
from carina.v4.exh_exhortos_archivos.crud import get_exh_exhortos_archivos, get_exh_exhorto_archivo, update_set_exhorto_archivo
from carina.v4.exh_exhortos_archivos.schemas import (
ExhExhortoArchivoFileDataAcuseOut,
Expand Down Expand Up @@ -79,7 +79,7 @@ async def upload_exh_exhorto_archivo(

# Consultar y validar el exhorto a partir del exhortoOrigenId
try:
exh_exhorto = get_exh_exhorto(database, exhortoOrigenId)
exh_exhorto = get_exh_exhorto_by_exhorto_origen_id(database, exhortoOrigenId)
except MyAnyError as error:
return ExhExhortoArchivoFileOut(success=False, errors=[str(error)])

Expand Down
4 changes: 2 additions & 2 deletions carina/v4/exh_exhortos_partes/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from lib.exceptions import MyIsDeletedError, MyNotExistsError

from ..exh_exhortos.crud import get_exh_exhorto
from ..exh_exhortos.crud import get_exh_exhorto_by_exhorto_origen_id
from ...core.exh_exhortos_partes.models import ExhExhortoParte


Expand All @@ -19,7 +19,7 @@ def get_exh_exhortos_partes(
"""Consultar los partes activos"""
consulta = database.query(ExhExhortoParte)
if exh_exhorto_id is not None:
exh_exhorto = get_exh_exhorto(database, exh_exhorto_id)
exh_exhorto = get_exh_exhorto_by_exhorto_origen_id(database, exh_exhorto_id)
consulta = consulta.filter_by(exh_exhorto_id=exh_exhorto.id)
return consulta.filter_by(estatus="A").order_by(ExhExhortoParte.id)

Expand Down
9 changes: 0 additions & 9 deletions tests/test_exh_exhortos.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,6 @@
class TestExhExhortos(unittest.TestCase):
"""Tests for exh_exhortos category"""

def test_get_exh_exhortos(self):
"""Test GET method for exh_exhortos"""
response = requests.get(
f"{config['api_base_url']}/exh_exhortos",
headers={"X-Api-Key": config["api_key"]},
timeout=config["timeout"],
)
self.assertEqual(response.status_code, 200)

def test_post_exh_exhorto(self):
"""Test POST method for exh_exhorto"""

Expand Down

0 comments on commit 616d0ca

Please sign in to comment.