adision de bases para trabajo completo de back-v1.0.0
This commit is contained in:
7
.env
7
.env
@@ -2,3 +2,10 @@
|
||||
|
||||
|
||||
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres
|
||||
|
||||
|
||||
|
||||
CSV_DOWNLOAD_TIMEOUT=30
|
||||
CSV_MAX_SIZE_MB=10
|
||||
API_VERSION=v1
|
||||
LOG_LEVEL=INFO
|
||||
|
||||
@@ -24,3 +24,9 @@ una vez importado el model, lo lee, lo pasa por la logica en la que se descratan
|
||||
|
||||
- puntos no claros de uso Diot
|
||||
- se pidio que no se agregara multiempresas o multitenant, aunque hay la posibilida de hacerlo, asi como el que se pudiera facilitar la actualizacion de las listas de efos, edos.
|
||||
|
||||
`notas de Gerardo`
|
||||
se quedaron implementadas los servicios crud de las funciones que seran publicos, ajustados a el tipo de usuario ('Root', 'Admin')
|
||||
lo mas dificil de implementar para el back va a ser, implementar las funciones de ajuste "automatico" de cargado de files, con un url, desde las listas, del sat y las publicaciones del diario.
|
||||
|
||||
si el tiempo nos cae encima (que es lo mas seguro, voy a concentrarme en trabajar en las listas de el sat(edos, efos y creditos), para tratar de dejar enpoints funcionales).
|
||||
BIN
app/helpers/__pycache__/csv_mapper.cpython-311.pyc
Normal file
BIN
app/helpers/__pycache__/csv_mapper.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/helpers/__pycache__/db_adapter.cpython-311.pyc
Normal file
BIN
app/helpers/__pycache__/db_adapter.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/helpers/__pycache__/extractCsv.cpython-311.pyc
Normal file
BIN
app/helpers/__pycache__/extractCsv.cpython-311.pyc
Normal file
Binary file not shown.
56
app/helpers/csv_mapper.py
Normal file
56
app/helpers/csv_mapper.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from typing import List, Dict, Any
|
||||
from app.modules.edos.schema import EdosUpload
|
||||
|
||||
class CSVMapper:
|
||||
""" Mapper: filter and mapping only necesary data, based on a schema"""
|
||||
|
||||
FIELD_MAPPING = {
|
||||
'csv_column_name': 'schema_field',
|
||||
'No.' : 'publicacion_sat',
|
||||
'RFC' : 'numero',
|
||||
'Nombre del Contribuyente' : 'razon_social',
|
||||
'Situación del contribuyente' : 'situacion',
|
||||
'Número y fecha de oficio global definitivo SAT' : 'numero_definitivo',
|
||||
'Publicación página SAT definitivo' : 'fecha_definitivo',
|
||||
'Número y fecha de oficio global definitivo DOF' : 'numero_def_dof',
|
||||
'Publicación DOF definitivo' : 'fecha_def_dof',
|
||||
'Número y fecha de oficio global de sentencia favorable SAT' : 'publicacion_dof',
|
||||
'Publicación página SAT sentencia favorable' : 'numero_fav_sat',
|
||||
}
|
||||
|
||||
REQUIRED_FIELD = [ 'publicacion_sat', 'numero', 'razon_social', 'situacion'] #Campos obligatorios
|
||||
|
||||
@staticmethod
|
||||
def filter_by_schema(raw_rows: List[Dict]) -> List[Dict]:
|
||||
""" Filter only fields defined on schema"""
|
||||
filtered = []
|
||||
|
||||
for row in raw_rows:
|
||||
mapped_row = {}
|
||||
for csv_field, schema_field in CSVMapper.FIELD_MAPPING.items():
|
||||
if csv_field in row and row[csv_field]:
|
||||
mapped_row[schema_field] = CSVMapper._clean_value(
|
||||
row[csv_field], schema_field
|
||||
)
|
||||
if all(field in mapped_row for field in CSVMapper.REQUIRED_FIELD):
|
||||
filtered.append(mapped_row)
|
||||
else:
|
||||
print(f"omited fields: {mapped_row}")
|
||||
return filtered
|
||||
|
||||
@staticmethod
|
||||
def _clean_value(value: str, field_type: str) -> Any:
|
||||
""" Cleanen and typified values"""
|
||||
if not value or value.strip() == '':
|
||||
return None
|
||||
|
||||
if 'date' in field_type:
|
||||
from datetime import datetime
|
||||
return datetime.strptime(value.strip(), '%Y-%m-%d')
|
||||
elif 'amount' in field_type or 'price' in field_type:
|
||||
return float(value.strip().replace(',','.'))
|
||||
elif 'int' in field_type.lower():
|
||||
return int(value.strip())
|
||||
else:
|
||||
return value.strip()
|
||||
|
||||
42
app/helpers/db_adapter.py
Normal file
42
app/helpers/db_adapter.py
Normal file
@@ -0,0 +1,42 @@
|
||||
from typing import List, Dict
|
||||
from database import sessionLocal
|
||||
from app.modules.edos.models import EDOS
|
||||
|
||||
class DBAdapter:
|
||||
""" Adapter: insert cleen data on a db"""
|
||||
|
||||
def __inti__(self):
|
||||
self.db = sessionLocal()
|
||||
|
||||
def insert_filtered_data(self, mapped_rows: List[Dict]) -> Dict:
|
||||
""" Insert only data filtered and mapped"""
|
||||
results = {
|
||||
'total_processed': len(mapped_rows),
|
||||
'inserted': 0,
|
||||
'errors': [],
|
||||
'duplicates_skiped': 0
|
||||
}
|
||||
for row in mapped_rows:
|
||||
try:
|
||||
#verified dupled data
|
||||
existing = self.db.query(EDOS).filter_by(
|
||||
unique_field=row.get('unique_field')
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
results['duplicates_skiped'] += 1
|
||||
continue
|
||||
|
||||
instance = EDOS(**row)
|
||||
self.db.add(instance)
|
||||
self.db.commit()
|
||||
results['inserted'] += 1
|
||||
except Exception as e:
|
||||
self.db.rollback()
|
||||
results['errors'].append({
|
||||
'row': row,
|
||||
'error': str(e)
|
||||
})
|
||||
self.db.close()
|
||||
return results
|
||||
|
||||
81
app/helpers/extractCsv.py
Normal file
81
app/helpers/extractCsv.py
Normal file
@@ -0,0 +1,81 @@
|
||||
import csv
|
||||
import requests
|
||||
from io import StringIO
|
||||
#
|
||||
from typing import List, Dict, Any
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class Settings:
|
||||
"""configuration"""
|
||||
CSV_DOWNLOAD_TIMEOUT = int(os.getenv('CSV_DOWNLOAD_TIMEOUT', 30))
|
||||
CSV_MAX_SIZE_MB = int(os.getenv('CSV_MAX_SIZE_MB', 10))
|
||||
|
||||
settings = Settings()
|
||||
|
||||
|
||||
class CSVExtractor:
|
||||
"""Extract raw data of CSV"""
|
||||
|
||||
@staticmethod
|
||||
def download_csv(url: str) -> str:
|
||||
""" Download CSV of URL"""
|
||||
try:
|
||||
|
||||
response = requests.get(url, timeout=30)
|
||||
response.raise_for_status()
|
||||
|
||||
encoding = response.encoding or 'utf-8'
|
||||
content = response.text
|
||||
return content, encoding
|
||||
except Exception as e:
|
||||
raise Exception(f"Error Download CSV: {str(e)}")
|
||||
|
||||
|
||||
@staticmethod
|
||||
def read_csv(content: str) -> List[Dict[str, Any]]:
|
||||
""" Converts CSV to list of dictionary"""
|
||||
csv_file = StringIO(content)
|
||||
#detect delimiter auto
|
||||
sample = csv_file.read(1024)
|
||||
csv_file.seek(0)
|
||||
try:
|
||||
dialect = csv.Sniffer().sniff(sample)
|
||||
reader =csv.DictReader(csv_file, dialect=dialect)
|
||||
except:
|
||||
csv_file.seek(0)
|
||||
reader = csv.DictReader(csv_file)
|
||||
|
||||
rows = [row for row in reader]
|
||||
|
||||
if rows:
|
||||
clean_row = {}
|
||||
|
||||
for key, value in rows[0].items():
|
||||
|
||||
if key is not None:
|
||||
clean_key = key.strip().replace('"', '').replace("'", "").replace('\ufeff', '')
|
||||
else:
|
||||
clean_key = ''
|
||||
|
||||
clean_row[clean_key] = value
|
||||
|
||||
for i, row in enumerate(rows):
|
||||
new_row = {}
|
||||
for old_key, value in row.items():
|
||||
if old_key is not None:
|
||||
new_key = old_key.strip().replace('"', '').replace("'", "").replace('\ufeff', '')
|
||||
else:
|
||||
new_key = ''
|
||||
#FIX: manage value None for avoid error strip
|
||||
if value is not None and isinstance(value, str):
|
||||
new_value = value.strip()
|
||||
else:
|
||||
new_value = value
|
||||
|
||||
new_row[new_key] = value
|
||||
rows[i] = new_row
|
||||
return rows
|
||||
BIN
app/modules/coments/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/coments/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/coments/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/coments/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/coments/__pycache__/services.cpython-311.pyc
Normal file
BIN
app/modules/coments/__pycache__/services.cpython-311.pyc
Normal file
Binary file not shown.
@@ -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))
|
||||
@@ -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
|
||||
|
||||
@@ -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"}
|
||||
|
||||
|
||||
BIN
app/modules/configuration/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/configuration/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/configuration/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/configuration/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/configuration/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/configuration/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -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.configuration.models import Configuration
|
||||
from app.modules.configuration.schema import Configupdate, ConfigResponse, ConfigCreate, MessageResponse
|
||||
from app.modules.configuration.service import ConfigurationService
|
||||
|
||||
router = APIRouter(prefix="/configuration", tags=["configuration"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=ConfigResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_configuration(
|
||||
data: ConfigCreate ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a configuration - 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.create_configuration(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[ConfigResponse])
|
||||
def get_configurations(
|
||||
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 ConfigurationService.get_configuration(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=ConfigResponse)
|
||||
def get_configuration_by_id(
|
||||
configuration_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get configuration by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.get_configuration(db=db, configuration_id=configuration_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=ConfigResponse)
|
||||
async def update_configuration(
|
||||
configuration_id: int,
|
||||
data: Configupdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing configuration - 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.update_configuration(
|
||||
db=db,
|
||||
configuration_id=configuration_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_configuration(
|
||||
configuration_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete configuration 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.delete_configuration(db=db, configuration_id=configuration_id, current_user=current_user)
|
||||
return {"message": "configuration deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -12,7 +12,7 @@ class ConfigCreate(BaseModel):
|
||||
smtp_user: Optional[str] = None
|
||||
smtp_password: Optional[str] = None
|
||||
is_active: bool = True
|
||||
class Commentupdate(ConfigCreate):
|
||||
class Configupdate(ConfigCreate):
|
||||
pass
|
||||
class ConfigResponse(ConfigCreate):
|
||||
created_at: datetime
|
||||
|
||||
@@ -3,15 +3,12 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.configuration.models import Configuration
|
||||
from app.modules.configuration.schema import
|
||||
from app.modules.configuration.schema import ConfigCreate, ConfigResponse, Configupdate, MessageResponse
|
||||
|
||||
|
||||
class ConfigurationService:
|
||||
@staticmethod
|
||||
def create_configuration(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
def create_configuration(db: Session, data: ConfigCreate):
|
||||
|
||||
new_configuration = Configuration(**data.dict())
|
||||
db.add(new_configuration)
|
||||
@@ -27,7 +24,7 @@ class ConfigurationService:
|
||||
return configuration
|
||||
|
||||
@staticmethod
|
||||
def update_configuration(db: Session, configuration_id: int, data: , current_user):
|
||||
def update_configuration(db: Session, configuration_id: int, data: Configupdate , current_user):
|
||||
configuration = db.query(Configuration).filter(Configuration.id == configuration_id).first()
|
||||
if not configuration:
|
||||
raise ValueError("configuration no encontrado")
|
||||
Binary file not shown.
@@ -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.credits.models import Credits
|
||||
from app.modules.credits.schema import CreditsCreate, CreditsResponse, CreditsUpdate, MessageResponse
|
||||
from app.modules.credits.service import CreditsService
|
||||
|
||||
router = APIRouter(prefix="/credits", tags=["credits"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=CreditsResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_credits(
|
||||
data: CreditsCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a credits - 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.create_credits(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[CreditsResponse])
|
||||
def get_creditss(
|
||||
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 CreditsService.get_creditss(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=CreditsResponse)
|
||||
def get_credits_by_id(
|
||||
credits_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get credits by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = CreditsService.get_credits(db=db, credits_id=credits_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=CreditsResponse)
|
||||
async def update_credits(
|
||||
credits_id: int,
|
||||
data: CreditsUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing credits - 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.update_credits(
|
||||
db=db,
|
||||
credits_id=credits_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_credits(
|
||||
credits_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete credits 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.delete_credits(db=db, credits_id=credits_id, current_user=current_user)
|
||||
return {"message": "credits deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -4,3 +4,41 @@ from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
class Supuestos(Enum):
|
||||
CANCELADOS ="cancelados"
|
||||
CONDONADOS ="condonados"
|
||||
FIRMES ="firmes"
|
||||
SENTENCIAS ="sentencias"
|
||||
EXIGIBLES ="exigibles"
|
||||
RETORNO_INVERSIONES ="retorno_inversiones"
|
||||
FRACCION_X ="fraccion_x"
|
||||
FRACCION_VII ="fraccion_vii"
|
||||
NO_LOCALIZADOS ="no_localizados"
|
||||
|
||||
class CreditsCreate(BaseModel):
|
||||
title:str
|
||||
rfc : str
|
||||
razon_social : str
|
||||
tipo_persona : str
|
||||
supuesto : Supuestos
|
||||
fecha_prim_publicacion : datetime
|
||||
fecha_ley : datetime
|
||||
fecha_cancelacion : datetime
|
||||
fecha_csd : datetime
|
||||
entidad_federativa : str
|
||||
monto : Optional[int] = None
|
||||
motivo : Optional[str] = None
|
||||
location_id : int
|
||||
|
||||
|
||||
class CreditsUpdate(CreditsCreate):
|
||||
pass
|
||||
|
||||
class CreditsResponse(CreditsCreate):
|
||||
creted_at: datetime
|
||||
updated_at: Optional[datetime]
|
||||
uploader_at : Optional[datetime]
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
message: str
|
||||
@@ -3,16 +3,12 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.credits.models import Credits
|
||||
from app.modules.credits.schema import
|
||||
from app.modules.credits.schema import CreditsCreate, CreditsUpdate, CerditsResponse, MessageResponse
|
||||
|
||||
|
||||
class CreditsService:
|
||||
@staticmethod
|
||||
def create_credits(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
def create_credits(db: Session, data:CreditsCreate ):
|
||||
new_credits = Credits(**data.dict())
|
||||
db.add(new_credits)
|
||||
db.commit()
|
||||
@@ -27,7 +23,7 @@ class CreditsService:
|
||||
return credits
|
||||
|
||||
@staticmethod
|
||||
def update_credits(db: Session, credits_id: int, data: , current_user):
|
||||
def update_credits(db: Session, credits_id: int, data:CreditsUpdate , current_user):
|
||||
credits = db.query(Credits).filter(Credits.id == credits_id).first()
|
||||
if not credits:
|
||||
raise ValueError("credits no encontrado")
|
||||
Binary file not shown.
BIN
app/modules/edos/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/edos/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/edos/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/edos/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/edos/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/edos/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -20,7 +20,7 @@ class EDOS(Base):
|
||||
razon_social = Column(String(100), nullable=False)
|
||||
situacion = Column(SQLEnum(Situacion, name="situcion", create_type=False), nullable=False)
|
||||
numero_definitivo = Column(String(60), nullable=False)
|
||||
fecha_definitivo = Column(Date, nullable=False )
|
||||
fecha_definitivo = Column(Date, nullable=True )
|
||||
publicaccion_sat = Column(Date, nullable=True)
|
||||
numero_def_dof = Column(String(100), nullable=True)
|
||||
fecha_def_dof = Column(Date, nullable=True)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Body
|
||||
from app.modules.edos.service import XMACSVService
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from app.helpers.extractCsv import CSVExtractor
|
||||
|
||||
router = APIRouter(prefix='/api/csv', tags=['CSV Import'])
|
||||
|
||||
@router.post('/import-from-url')
|
||||
async def import_csv(data: Dict[str, Any] = Body(..., example={"url": "http://example.com/data.csv"})):
|
||||
"""Endpoint to download CSV and process, write and see on DB"""
|
||||
|
||||
|
||||
csv_url = data.get('url')
|
||||
dry_run = data.get('dry_run', True)
|
||||
max_rows = data.get('max_rows')
|
||||
|
||||
if not csv_url:
|
||||
raise HTTPException(400, "url del CSV requerida")
|
||||
|
||||
if not isinstance(csv_url, str):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="la URL debe ser un texto valido"
|
||||
)
|
||||
|
||||
try:
|
||||
result = XMACSVService.process_csv_from_url(
|
||||
csv_url= csv_url,
|
||||
dry_run=dry_run,
|
||||
max_rows=max_rows,
|
||||
)
|
||||
|
||||
return {
|
||||
'status' : 'success',
|
||||
'message': 'Procesamiento completado',
|
||||
'data': result
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error on endpoint: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Procesing CSV error: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
@router.post('/import-from-url/v2')
|
||||
async def import_csv(data: dict):
|
||||
"""Endpoint simple para probar el extractor"""
|
||||
csv_url = data.get('url')
|
||||
|
||||
if not csv_url:
|
||||
raise HTTPException(400, "url del CSV requerida")
|
||||
|
||||
try:
|
||||
# Probar extractor
|
||||
content = CSVExtractor.download_csv(csv_url)
|
||||
rows = CSVExtractor.read_csv(content)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': 'CSV procesado correctamente',
|
||||
'data': {
|
||||
'url': csv_url,
|
||||
'total_filas': len(rows),
|
||||
'primeras_filas': rows[:3] if rows else [],
|
||||
'columnas': list(rows[0].keys()) if rows else []
|
||||
}
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(500, detail=str(e))
|
||||
@@ -1,6 +1,33 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
class Situacion(Enum):
|
||||
SENTENCIA_FAVORABLE ="sentencia_favorable"
|
||||
DEFINITIVO="definitivo"
|
||||
|
||||
|
||||
class EdosUpload(BaseModel):
|
||||
numero : str
|
||||
razon_social : str
|
||||
situacion : Situacion
|
||||
numero_definitivo : str
|
||||
fecha_definitivo : date
|
||||
publicaccion_sat : date
|
||||
numero_def_dof : str
|
||||
fecha_def_dof : date
|
||||
publicacion_dof : date
|
||||
numero_fav_sat : str
|
||||
|
||||
|
||||
class EdosResponse(EdosUpload):
|
||||
pass
|
||||
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
|
||||
74
app/modules/edos/service.py
Normal file
74
app/modules/edos/service.py
Normal file
@@ -0,0 +1,74 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.edos.models import EDOS
|
||||
from app.modules.edos.schema import EdosResponse, EdosUpload, messageResponse
|
||||
|
||||
|
||||
from app.helpers.csv_mapper import CSVMapper
|
||||
from app.helpers.db_adapter import DBAdapter
|
||||
from app.helpers.extractCsv import CSVExtractor
|
||||
|
||||
class XMACSVService:
|
||||
""" Orquester"""
|
||||
|
||||
@staticmethod
|
||||
def process_csv_from_url(
|
||||
csv_url: str,
|
||||
dry_run: bool = False,
|
||||
max_rows: int = None
|
||||
) -> dict:
|
||||
""" flow download and parsing, filter and adapt"""
|
||||
|
||||
|
||||
try:
|
||||
# X - EXTRACT
|
||||
print(f"📥 Descargando CSV: {csv_url}")
|
||||
|
||||
# ✅ Ahora download_csv retorna (content, encoding)
|
||||
content, encoding = CSVExtractor.download_csv(csv_url)
|
||||
print(f" ✅ Descargado {len(content)} bytes, encoding: {encoding}")
|
||||
|
||||
# Parsear CSV
|
||||
raw_rows = CSVExtractor.read_csv(content)
|
||||
print(f" ✅ Parseadas {len(raw_rows)} filas")
|
||||
|
||||
if not raw_rows:
|
||||
return {
|
||||
'total_extracted': 0,
|
||||
'total_mapped': 0,
|
||||
'inserted': 0,
|
||||
'errors': ['No se encontraron datos en el CSV']
|
||||
}
|
||||
|
||||
# Mostrar columnas encontradas
|
||||
print(f" 📋 Columnas: {list(raw_rows[0].keys())}")
|
||||
|
||||
# M - MAP (si tienes mapper)
|
||||
# Por ahora, usar datos crudos
|
||||
mapped_rows = raw_rows
|
||||
|
||||
if max_rows:
|
||||
mapped_rows = mapped_rows[:max_rows]
|
||||
print(f" 🔒 Limitado a {max_rows} filas")
|
||||
|
||||
# A - ADAPT
|
||||
if not dry_run:
|
||||
print(f" 💾 Insertando {len(mapped_rows)} filas en BD")
|
||||
# Aquí iría la inserción en BD
|
||||
|
||||
return {
|
||||
'total_extracted': len(raw_rows),
|
||||
'total_mapped': len(mapped_rows),
|
||||
'inserted': len(mapped_rows) if not dry_run else 0,
|
||||
'dry_run': dry_run,
|
||||
'columns': list(raw_rows[0].keys()) if raw_rows else [],
|
||||
'sample': raw_rows[:2] if raw_rows else []
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
raise
|
||||
@@ -1,6 +1,32 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
class Situacion(Enum):
|
||||
DEFINITIVO ="definitivo"
|
||||
DESVIRTUADO ="desvituado"
|
||||
PRESUNTO ="presunto"
|
||||
SENTENCIA_FAVORABLE ="sentencia_favorable"
|
||||
|
||||
class EfosBase(BaseModel):
|
||||
numero: int
|
||||
rfc : str
|
||||
nombre_contribuyente: str
|
||||
situacion: Situacion
|
||||
publi_presuntos_sat: str
|
||||
publi_desvirtuados_sat: date
|
||||
publi_definitivos_sat: date
|
||||
publi_favorable_sat: date
|
||||
|
||||
class EfosResponse(EfosBase):
|
||||
cretaed_at : datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
loader_by: int
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
@@ -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.feed.models import Feed
|
||||
from app.modules.feed.schema import FeedUpdate, FeedCreate, FeedResponse, messageResponse
|
||||
from app.modules.feed.service import FeedService
|
||||
|
||||
router = APIRouter(prefix="/feed", tags=["feed"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=FeedResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_feed(
|
||||
data: FeedCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a feed - 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.create_feed(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[FeedResponse])
|
||||
def get_feeds(
|
||||
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 FeedService.get_feeds(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=FeedResponse)
|
||||
def get_feed_by_id(
|
||||
feed_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get feed by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = FeedService.get_feed(db=db, feed_id=feed_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=FeedResponse)
|
||||
async def update_feed(
|
||||
feed_id: int,
|
||||
data: FeedUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing feed - 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.update_feed(
|
||||
db=db,
|
||||
feed_id=feed_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_feed(
|
||||
feed_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete feed 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.delete_feed(db=db, feed_id=feed_id, current_user=current_user)
|
||||
return {"message": "feed deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,6 +1,31 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
class FeedBase(BaseModel):
|
||||
title: str
|
||||
body: Optional[str] = None
|
||||
document_url: str
|
||||
publication_date: date
|
||||
is_important : bool = False
|
||||
|
||||
class FeedCreate(FeedBase):
|
||||
user_id: int
|
||||
file_id: Optional[int] = None
|
||||
|
||||
class FeedUpdate(BaseModel):
|
||||
body: str
|
||||
|
||||
class FeedResponse(FeedBase):
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] =None
|
||||
created_by : Optional[int] = None
|
||||
updated_by : Optional[int] = None
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
|
||||
@@ -3,16 +3,12 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.feed.models import Feed
|
||||
from app.modules.feed.schema import
|
||||
from app.modules.feed.schema import FeedCreate, FeedResponse, FeedUpdate, messageResponse
|
||||
|
||||
|
||||
class FeedService:
|
||||
@staticmethod
|
||||
def create_feed(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
def create_feed(db: Session, data: FeedCreate ):
|
||||
new_feed = Feed(**data.dict())
|
||||
db.add(new_feed)
|
||||
db.commit()
|
||||
@@ -27,7 +23,7 @@ class FeedService:
|
||||
return feed
|
||||
|
||||
@staticmethod
|
||||
def update_feed(db: Session, feed_id: int, data: , current_user):
|
||||
def update_feed(db: Session, feed_id: int, data: FeedUpdate , current_user):
|
||||
feed = db.query(Feed).filter(Feed.id == feed_id).first()
|
||||
if not feed:
|
||||
raise ValueError("feed no encontrado")
|
||||
@@ -1,6 +1,27 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
class FileBase(BaseModel):
|
||||
title: str
|
||||
summary: str
|
||||
document_url : str
|
||||
file_type : str
|
||||
file_size : str
|
||||
feed_id: str
|
||||
|
||||
class FileCreate(FileBase):
|
||||
feed_id: int
|
||||
|
||||
class FileResponse(FileBase):
|
||||
cretaed_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
uploader_by: int
|
||||
updated_by: Optional[int] = None
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
0
app/modules/files/service.py
Normal file
0
app/modules/files/service.py
Normal file
@@ -1,6 +1,26 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Interacction(Enum):
|
||||
LIKE = "like"
|
||||
DONT_LIKE = "dont_like"
|
||||
APPROVED = "approved"
|
||||
DISAPRROVE = "disapproved"
|
||||
NONE = "none"
|
||||
|
||||
|
||||
class InteractionBase(BaseModel):
|
||||
type_interactions: Interacction = "none"
|
||||
|
||||
class InteractionCreate(InteractionBase):
|
||||
feed_id: int
|
||||
user_id: int
|
||||
|
||||
class InteractionResponse(InteractionBase):
|
||||
pass
|
||||
|
||||
|
||||
@@ -4,3 +4,21 @@ from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class InvoceRecept(BaseModel):
|
||||
emisor: str
|
||||
receptor: str
|
||||
uuid: str
|
||||
total: int
|
||||
tipo: str
|
||||
date: Optional[datetime]
|
||||
|
||||
class InvoceResponse(InvoceRecept):
|
||||
verified_at: datetime
|
||||
verified_by: Optional[int]
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
message : str
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
@@ -25,7 +25,7 @@ class License(Base):
|
||||
#timestamsp
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now(), nullable=True)
|
||||
deleted_at = Column(DateTime(timezone=True), nullable=False)
|
||||
deleted_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
#trace
|
||||
created_by = Column(Integer, nullable=True)
|
||||
|
||||
@@ -4,3 +4,24 @@ from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
class LicenseBase(BaseModel):
|
||||
titular : int
|
||||
begins_at : datetime
|
||||
ends_at: datetime
|
||||
token_license: str
|
||||
location_id : int
|
||||
client_id: int
|
||||
|
||||
class LicenseResponse(LicenseBase):
|
||||
cretaed_at: datetime
|
||||
updated_at: Optional[datetime]
|
||||
deleted_at: Optional[datetime]
|
||||
|
||||
created_by: Optional[int]
|
||||
updated_by: Optional[int]
|
||||
deleted_by: Optional[int]
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
message : str
|
||||
@@ -3,16 +3,12 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.license.models import License
|
||||
from app.modules.license.schema import
|
||||
from app.modules.license.schema import LicenseResponse, LicenseBase
|
||||
|
||||
|
||||
class LicenseService:
|
||||
@staticmethod
|
||||
def create_license(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_license = License(**data.dict())
|
||||
db.add(new_license)
|
||||
db.commit()
|
||||
Binary file not shown.
BIN
app/modules/location/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/location/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/location/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/location/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/location/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/location/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -10,11 +10,8 @@ class Locations(Base):
|
||||
id = Column(Integer, primary_key=True, nullable=False)
|
||||
|
||||
country = Column(String(120), nullable=False)
|
||||
country_id = Column(Integer, nullable=False)
|
||||
state = Column(String(100), nullable=False)
|
||||
state_id = Column(Integer, nullable=False)
|
||||
city = Column(String(100), nullable=False)
|
||||
city_id = Column(Integer, nullable=False)
|
||||
cp_zp = Column(Integer, nullable=True)
|
||||
street = Column(String(120), nullable=True)
|
||||
is_department = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
@@ -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.location.models import Locations
|
||||
from app.modules.location.schema import LocationBase, LocationUpdate, LocationResponse, messageResponse
|
||||
from app.modules.location.service import LocationsService
|
||||
|
||||
router = APIRouter(prefix="/locations", tags=["locations"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=LocationResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_locations(
|
||||
data: LocationBase,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a locations - 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.create_locations(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[LocationResponse])
|
||||
def get_locationss(
|
||||
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 LocationsService.get_locations(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=LocationResponse)
|
||||
def get_locations_by_id(
|
||||
locations_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get locations by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = LocationsService.get_locations(db=db, locations_id=locations_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=LocationResponse)
|
||||
async def update_locations(
|
||||
locations_id: int,
|
||||
data: LocationUpdate ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing locations - 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.update_locations(
|
||||
db=db,
|
||||
locations_id=locations_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_locations(
|
||||
locations_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete locations 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.delete_locations(db=db, locations_id=locations_id, current_user=current_user)
|
||||
return {"message": "locations deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -0,0 +1,34 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class LocationBase(BaseModel):
|
||||
country: str
|
||||
state: str
|
||||
city: str
|
||||
cp_zp: int
|
||||
street: str
|
||||
is_department: bool
|
||||
number_ext: int
|
||||
number_int: int
|
||||
is_active: bool
|
||||
|
||||
class LocationResponse(LocationBase):
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime]
|
||||
deleted_at: Optional[datetime]
|
||||
created_by: Optional[int]
|
||||
updated_by: Optional[int]
|
||||
deleted_by: Optional[int]
|
||||
|
||||
class LocationUpdate(LocationBase):
|
||||
pass
|
||||
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message : str
|
||||
|
||||
|
||||
@@ -4,3 +4,66 @@ from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.location.models import Locations
|
||||
from app.modules.location.schema import LocationBase, LocationUpdate
|
||||
|
||||
class LocationsService:
|
||||
@staticmethod
|
||||
def create_locations(db: Session, data:LocationBase ):
|
||||
new_locations = Locations(**data.dict())
|
||||
db.add(new_locations)
|
||||
db.commit()
|
||||
db.refresh(new_locations)
|
||||
return new_locations
|
||||
|
||||
@staticmethod
|
||||
def get_locations(db: Session, locations_id: int, current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
return locations
|
||||
|
||||
@staticmethod
|
||||
def update_locations(db: Session, locations_id: int, data: LocationUpdate, current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este locations")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(locations, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(locations)
|
||||
return locations
|
||||
|
||||
@staticmethod
|
||||
def delete_locations(db: Session, locations_id: int, current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este locations")
|
||||
|
||||
try:
|
||||
locations.is_active = False
|
||||
locations.deleted_at = datetime.utcnow()
|
||||
locations.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(locations)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el locations: {e}")
|
||||
|
||||
return {"message": "locations eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,6 +1,56 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from pydantic import BaseModel, EmailStr, Field, validator, ConfigDict
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from typing import Optional, Dict, Any
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
#
|
||||
|
||||
class Action(Enum):
|
||||
UPLOAD = "upload"
|
||||
MATCH = "match"
|
||||
QUERY = "query"
|
||||
CONSUMPTION = "consumption"
|
||||
CREATE = "create"
|
||||
DELETE = "delete"
|
||||
SOLD = "sold"
|
||||
INTERACTION = "interaction"
|
||||
COMMENT = "comment"
|
||||
CONFIG = "config"
|
||||
EMAIL = "email"
|
||||
|
||||
|
||||
class Target(Enum):
|
||||
CLIENT = "client"
|
||||
INVOICES = "invoices"
|
||||
FEED = "feed"
|
||||
EFOS = "efos"
|
||||
CREDITS = "credits"
|
||||
USERS = "users"
|
||||
EMAIL = "email"
|
||||
|
||||
class MovesBase(BaseModel):
|
||||
action_type: Action
|
||||
target_type : Target
|
||||
description: Optional[str]
|
||||
move_metadata: Optional[Dict[str, Any]] = None
|
||||
ip_address: Optional[str]
|
||||
user_agent: Optional[str]
|
||||
is_active: bool = True
|
||||
|
||||
class MoveCreate(MovesBase):
|
||||
client_id: int
|
||||
user_id: int
|
||||
|
||||
class MoveUpdate(MoveCreate):
|
||||
pass
|
||||
|
||||
class MovesResponse(MoveCreate):
|
||||
id: int
|
||||
created_at: datetime
|
||||
created_by: Optional[int]
|
||||
|
||||
updated_at: Optional[datetime]
|
||||
deleted_by: Optional[int]
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
Binary file not shown.
BIN
app/modules/suppliers/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/suppliers/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/suppliers/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/suppliers/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/suppliers/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/suppliers/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -7,7 +7,7 @@ import enum
|
||||
|
||||
class SupplierType(str, enum.Enum):
|
||||
NACIONAL = "nacional"
|
||||
EXTRANJERO = "exttranjero"
|
||||
EXTRANJERO = "extranjero"
|
||||
GLOBAL = "global"
|
||||
|
||||
|
||||
|
||||
@@ -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.suppliers.models import Suppliers
|
||||
from app.modules.suppliers.schema import SupplierCreate, SupplierResponse, SupplierUpdate, messageResponse
|
||||
from app.modules.suppliers.service import SuppliersService
|
||||
|
||||
router = APIRouter(prefix="/suppliers", tags=["suppliers"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=SupplierResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_suppliers(
|
||||
data: SupplierCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a suppliers - 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.create_suppliers(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[SupplierResponse])
|
||||
def get_supplierss(
|
||||
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 SuppliersService.get_suppliers(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=SupplierResponse)
|
||||
def get_suppliers_by_id(
|
||||
suppliers_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get suppliers by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = SuppliersService.get_suppliers(db=db, suppliers_id=suppliers_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=SupplierResponse)
|
||||
async def update_suppliers(
|
||||
suppliers_id: int,
|
||||
data: SupplierUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing suppliers - 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.update_suppliers(
|
||||
db=db,
|
||||
suppliers_id=suppliers_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_suppliers(
|
||||
suppliers_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete suppliers 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.delete_suppliers(db=db, suppliers_id=suppliers_id, current_user=current_user)
|
||||
return {"message": "suppliers deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -0,0 +1,42 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator, ConfigDict
|
||||
from datetime import datetime
|
||||
from typing import Optional, Dict, Any
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
#
|
||||
|
||||
|
||||
|
||||
class SupplierType(Enum):
|
||||
NACIONAL = "nacional"
|
||||
EXTRANJERO = "extranjero"
|
||||
GLOBAL = "global"
|
||||
|
||||
class SuppliersBase(BaseModel):
|
||||
rfc: str
|
||||
email : EmailStr
|
||||
short_name : str
|
||||
razon_social : str
|
||||
fiscal_number : str
|
||||
cellphone: str
|
||||
supplier_type : SupplierType
|
||||
is_active : bool = True
|
||||
|
||||
class SupplierCreate(SuppliersBase):
|
||||
location_id: int
|
||||
client_id: int
|
||||
|
||||
class SupplierUpdate(SuppliersBase):
|
||||
pass
|
||||
|
||||
class SupplierResponse(SupplierCreate):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime]
|
||||
deleted_at: Optional[datetime]
|
||||
created_by: int
|
||||
updated_by: Optional[int]
|
||||
deleted_by: Optional[int]
|
||||
class messageResponse(BaseModel):
|
||||
message : str
|
||||
@@ -4,3 +4,67 @@ from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.suppliers.models import Suppliers
|
||||
from app.modules.suppliers.schema import SupplierCreate, SupplierUpdate
|
||||
|
||||
|
||||
class SuppliersService:
|
||||
@staticmethod
|
||||
def create_suppliers(db: Session, data:SupplierCreate ):
|
||||
new_suppliers = Suppliers(**data.dict())
|
||||
db.add(new_suppliers)
|
||||
db.commit()
|
||||
db.refresh(new_suppliers)
|
||||
return new_suppliers
|
||||
|
||||
@staticmethod
|
||||
def get_suppliers(db: Session, suppliers_id: int, current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
return suppliers
|
||||
|
||||
@staticmethod
|
||||
def update_suppliers(db: Session, suppliers_id: int, data:SupplierUpdate , current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este suppliers")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(suppliers, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(suppliers)
|
||||
return suppliers
|
||||
|
||||
@staticmethod
|
||||
def delete_suppliers(db: Session, suppliers_id: int, current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este suppliers")
|
||||
|
||||
try:
|
||||
suppliers.is_active = False
|
||||
suppliers.deleted_at = datetime.utcnow()
|
||||
suppliers.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(suppliers)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el suppliers: {e}")
|
||||
|
||||
return {"message": "suppliers eliminado correctamente"}
|
||||
|
||||
|
||||
16
main.py
16
main.py
@@ -9,6 +9,17 @@ from database import test_connection
|
||||
from app.modules.users.route import router as user_router
|
||||
from app.modules.clients.route import router as client_router
|
||||
from app.modules.branches.route import router as branches_router
|
||||
#
|
||||
from app.modules.coments.route import router as comments_router
|
||||
from app.modules.configuration.route import router as configuration_router
|
||||
#
|
||||
from app.modules.suppliers.route import router as suppliers_router
|
||||
from app.modules.location.route import router as location_router
|
||||
from app.modules.edos.route import router as Edos_router
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.INFO,
|
||||
@@ -61,3 +72,8 @@ async def root():
|
||||
app.include_router(user_router)
|
||||
app.include_router(client_router)
|
||||
app.include_router(branches_router)
|
||||
app.include_router(comments_router)
|
||||
app.include_router(configuration_router)
|
||||
app.include_router(suppliers_router)
|
||||
app.include_router(location_router)
|
||||
app.include_router(Edos_router)
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.branches.models import Branches
|
||||
from app.modules.branches.schema import , Response
|
||||
from app.modules.branches.services import BranchesService
|
||||
|
||||
router = APIRouter(prefix="/branches", tags=["branches"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_branches(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a branches - 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 branches")
|
||||
|
||||
try:
|
||||
result = BranchesService.create_branches(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_branchess(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 BranchesService.get_branchess(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_branches_by_id(
|
||||
branches_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get branches by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = BranchesService.get_branches(db=db, branches_id=branches_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=Response)
|
||||
async def update_branches(
|
||||
branches_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing branches - 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 branches")
|
||||
|
||||
try:
|
||||
result = BranchesService.update_branches(
|
||||
db=db,
|
||||
branches_id=branches_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_branches(
|
||||
branches_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete branches 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 branches")
|
||||
|
||||
try:
|
||||
result = BranchesService.delete_branches(db=db, branches_id=branches_id, current_user=current_user)
|
||||
return {"message": "branches deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,117 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.client.models import Client
|
||||
from app.modules.client.schema import , Response
|
||||
from app.modules.client.services import ClientService
|
||||
|
||||
router = APIRouter(prefix="/client", tags=["client"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_client(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a client - 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 client")
|
||||
|
||||
try:
|
||||
result = ClientService.create_client(db=db, data=data)
|
||||
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_clients(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 ClientService.get_clients(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/client_id}", response_model=Response)
|
||||
def get_client_by_id(
|
||||
client_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get client by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = ClientService.get_client(db=db, client_id=client_id, current_user=current_user)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
|
||||
#================ Update ====================
|
||||
@router.patch("/update/client_id}", response_model=Response)
|
||||
async def update_client(
|
||||
client_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing client - 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 client")
|
||||
|
||||
try:
|
||||
result = ClientService.update_client(
|
||||
db=db,
|
||||
client_id=client_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/client_id}", status_code=status.HTTP_200_OK)
|
||||
async def delete_client(
|
||||
client_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete client 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 client")
|
||||
|
||||
try:
|
||||
result = ClientService.delete_client(db=db, client_id=client_id, current_user=current_user)
|
||||
return {"message": "client deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.coments.models import Coments
|
||||
from app.modules.coments.schema import , Response
|
||||
from app.modules.coments.services import ComentsService
|
||||
|
||||
router = APIRouter(prefix="/coments", tags=["coments"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_coments(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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[Response])
|
||||
def get_comentss(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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_comentss(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_coments_by_id(
|
||||
coments_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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=Response)
|
||||
async def update_coments(
|
||||
coments_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_coments(
|
||||
coments_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.configuration.models import Configuration
|
||||
from app.modules.configuration.schema import , Response
|
||||
from app.modules.configuration.services import ConfigurationService
|
||||
|
||||
router = APIRouter(prefix="/configuration", tags=["configuration"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_configuration(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a configuration - 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.create_configuration(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_configurations(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 ConfigurationService.get_configurations(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_configuration_by_id(
|
||||
configuration_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get configuration by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.get_configuration(db=db, configuration_id=configuration_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=Response)
|
||||
async def update_configuration(
|
||||
configuration_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing configuration - 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.update_configuration(
|
||||
db=db,
|
||||
configuration_id=configuration_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_configuration(
|
||||
configuration_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete configuration 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.delete_configuration(db=db, configuration_id=configuration_id, current_user=current_user)
|
||||
return {"message": "configuration deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.credits.models import Credits
|
||||
from app.modules.credits.schema import , Response
|
||||
from app.modules.credits.services import CreditsService
|
||||
|
||||
router = APIRouter(prefix="/credits", tags=["credits"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_credits(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a credits - 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.create_credits(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_creditss(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 CreditsService.get_creditss(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_credits_by_id(
|
||||
credits_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get credits by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = CreditsService.get_credits(db=db, credits_id=credits_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=Response)
|
||||
async def update_credits(
|
||||
credits_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing credits - 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.update_credits(
|
||||
db=db,
|
||||
credits_id=credits_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_credits(
|
||||
credits_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete credits 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.delete_credits(db=db, credits_id=credits_id, current_user=current_user)
|
||||
return {"message": "credits deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.edos.models import EDOS
|
||||
from app.modules.edos.schema import , Response
|
||||
from app.modules.edos.services import EDOSService
|
||||
|
||||
router = APIRouter(prefix="/edos", tags=["edos"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_edos(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a edos - 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 edos")
|
||||
|
||||
try:
|
||||
result = EDOSService.create_edos(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_edoss(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 EDOSService.get_edoss(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_edos_by_id(
|
||||
edos_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get edos by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = EDOSService.get_edos(db=db, edos_id=edos_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=Response)
|
||||
async def update_edos(
|
||||
edos_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing edos - 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 edos")
|
||||
|
||||
try:
|
||||
result = EDOSService.update_edos(
|
||||
db=db,
|
||||
edos_id=edos_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_edos(
|
||||
edos_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete edos 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 edos")
|
||||
|
||||
try:
|
||||
result = EDOSService.delete_edos(db=db, edos_id=edos_id, current_user=current_user)
|
||||
return {"message": "edos deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.efos.models import EFOS
|
||||
from app.modules.efos.schema import , Response
|
||||
from app.modules.efos.services import EFOSService
|
||||
|
||||
router = APIRouter(prefix="/efos", tags=["efos"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_efos(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a efos - 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 efos")
|
||||
|
||||
try:
|
||||
result = EFOSService.create_efos(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_efoss(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 EFOSService.get_efoss(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_efos_by_id(
|
||||
efos_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get efos by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = EFOSService.get_efos(db=db, efos_id=efos_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=Response)
|
||||
async def update_efos(
|
||||
efos_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing efos - 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 efos")
|
||||
|
||||
try:
|
||||
result = EFOSService.update_efos(
|
||||
db=db,
|
||||
efos_id=efos_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_efos(
|
||||
efos_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete efos 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 efos")
|
||||
|
||||
try:
|
||||
result = EFOSService.delete_efos(db=db, efos_id=efos_id, current_user=current_user)
|
||||
return {"message": "efos deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.feed.models import Feed
|
||||
from app.modules.feed.schema import , Response
|
||||
from app.modules.feed.services import FeedService
|
||||
|
||||
router = APIRouter(prefix="/feed", tags=["feed"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_feed(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a feed - 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.create_feed(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_feeds(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 FeedService.get_feeds(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_feed_by_id(
|
||||
feed_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get feed by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = FeedService.get_feed(db=db, feed_id=feed_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=Response)
|
||||
async def update_feed(
|
||||
feed_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing feed - 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.update_feed(
|
||||
db=db,
|
||||
feed_id=feed_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_feed(
|
||||
feed_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete feed 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.delete_feed(db=db, feed_id=feed_id, current_user=current_user)
|
||||
return {"message": "feed deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.files.models import Files
|
||||
from app.modules.files.schema import , Response
|
||||
from app.modules.files.services import FilesService
|
||||
|
||||
router = APIRouter(prefix="/files", tags=["files"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_files(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a files - 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 files")
|
||||
|
||||
try:
|
||||
result = FilesService.create_files(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_filess(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 FilesService.get_filess(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_files_by_id(
|
||||
files_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get files by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = FilesService.get_files(db=db, files_id=files_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=Response)
|
||||
async def update_files(
|
||||
files_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing files - 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 files")
|
||||
|
||||
try:
|
||||
result = FilesService.update_files(
|
||||
db=db,
|
||||
files_id=files_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_files(
|
||||
files_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete files 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 files")
|
||||
|
||||
try:
|
||||
result = FilesService.delete_files(db=db, files_id=files_id, current_user=current_user)
|
||||
return {"message": "files deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.invoices.models import Invoices
|
||||
from app.modules.invoices.schema import , Response
|
||||
from app.modules.invoices.services import InvoicesService
|
||||
|
||||
router = APIRouter(prefix="/invoices", tags=["invoices"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_invoices(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a invoices - 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 invoices")
|
||||
|
||||
try:
|
||||
result = InvoicesService.create_invoices(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_invoicess(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 InvoicesService.get_invoicess(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_invoices_by_id(
|
||||
invoices_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get invoices by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = InvoicesService.get_invoices(db=db, invoices_id=invoices_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=Response)
|
||||
async def update_invoices(
|
||||
invoices_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing invoices - 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 invoices")
|
||||
|
||||
try:
|
||||
result = InvoicesService.update_invoices(
|
||||
db=db,
|
||||
invoices_id=invoices_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_invoices(
|
||||
invoices_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete invoices 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 invoices")
|
||||
|
||||
try:
|
||||
result = InvoicesService.delete_invoices(db=db, invoices_id=invoices_id, current_user=current_user)
|
||||
return {"message": "invoices deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.license.models import License
|
||||
from app.modules.license.schema import , Response
|
||||
from app.modules.license.services import LicenseService
|
||||
|
||||
router = APIRouter(prefix="/license", tags=["license"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_license(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a license - 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 license")
|
||||
|
||||
try:
|
||||
result = LicenseService.create_license(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_licenses(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 LicenseService.get_licenses(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_license_by_id(
|
||||
license_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get license by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = LicenseService.get_license(db=db, license_id=license_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=Response)
|
||||
async def update_license(
|
||||
license_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing license - 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 license")
|
||||
|
||||
try:
|
||||
result = LicenseService.update_license(
|
||||
db=db,
|
||||
license_id=license_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_license(
|
||||
license_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete license 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 license")
|
||||
|
||||
try:
|
||||
result = LicenseService.delete_license(db=db, license_id=license_id, current_user=current_user)
|
||||
return {"message": "license deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.locations.models import Locations
|
||||
from app.modules.locations.schema import , Response
|
||||
from app.modules.locations.services import LocationsService
|
||||
|
||||
router = APIRouter(prefix="/locations", tags=["locations"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_locations(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a locations - 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.create_locations(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_locationss(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 LocationsService.get_locationss(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_locations_by_id(
|
||||
locations_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get locations by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = LocationsService.get_locations(db=db, locations_id=locations_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=Response)
|
||||
async def update_locations(
|
||||
locations_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing locations - 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.update_locations(
|
||||
db=db,
|
||||
locations_id=locations_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_locations(
|
||||
locations_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete locations 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.delete_locations(db=db, locations_id=locations_id, current_user=current_user)
|
||||
return {"message": "locations deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.moves.models import Moves
|
||||
from app.modules.moves.schema import , Response
|
||||
from app.modules.moves.services import MovesService
|
||||
|
||||
router = APIRouter(prefix="/moves", tags=["moves"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_moves(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a moves - 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 moves")
|
||||
|
||||
try:
|
||||
result = MovesService.create_moves(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_movess(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 MovesService.get_movess(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_moves_by_id(
|
||||
moves_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get moves by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = MovesService.get_moves(db=db, moves_id=moves_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=Response)
|
||||
async def update_moves(
|
||||
moves_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing moves - 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 moves")
|
||||
|
||||
try:
|
||||
result = MovesService.update_moves(
|
||||
db=db,
|
||||
moves_id=moves_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_moves(
|
||||
moves_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete moves 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 moves")
|
||||
|
||||
try:
|
||||
result = MovesService.delete_moves(db=db, moves_id=moves_id, current_user=current_user)
|
||||
return {"message": "moves deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,116 +0,0 @@
|
||||
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.models.user import User # Modelo base de usuario
|
||||
from app.modules.suppliers.models import Suppliers
|
||||
from app.modules.suppliers.schema import , Response
|
||||
from app.modules.suppliers.services import SuppliersService
|
||||
|
||||
router = APIRouter(prefix="/suppliers", tags=["suppliers"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=Response, status_code=status.HTTP_201_CREATED)
|
||||
async def create_suppliers(
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Create a suppliers - 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.create_suppliers(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[Response])
|
||||
def get_supplierss(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = 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 SuppliersService.get_supplierss(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=Response)
|
||||
def get_suppliers_by_id(
|
||||
suppliers_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get suppliers by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = SuppliersService.get_suppliers(db=db, suppliers_id=suppliers_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=Response)
|
||||
async def update_suppliers(
|
||||
suppliers_id: int,
|
||||
data: ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing suppliers - 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.update_suppliers(
|
||||
db=db,
|
||||
suppliers_id=suppliers_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}", status_code=status.HTTP_200_OK)
|
||||
async def delete_suppliers(
|
||||
suppliers_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Delete suppliers 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.delete_suppliers(db=db, suppliers_id=suppliers_id, current_user=current_user)
|
||||
return {"message": "suppliers deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.branches.models import Branches
|
||||
from app.modules.branches.schema import
|
||||
|
||||
|
||||
class BranchesService:
|
||||
@staticmethod
|
||||
def create_branches(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_branches = Branches(**data.dict())
|
||||
db.add(new_branches)
|
||||
db.commit()
|
||||
db.refresh(new_branches)
|
||||
return new_branches
|
||||
|
||||
@staticmethod
|
||||
def get_branches(db: Session, branches_id: int, current_user):
|
||||
branches = db.query(Branches).filter(Branches.id == branches_id).first()
|
||||
if not branches:
|
||||
raise ValueError("branches no encontrado")
|
||||
return branches
|
||||
|
||||
@staticmethod
|
||||
def update_branches(db: Session, branches_id: int, data: , current_user):
|
||||
branches = db.query(Branches).filter(Branches.id == branches_id).first()
|
||||
if not branches:
|
||||
raise ValueError("branches no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este branches")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(branches, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(branches)
|
||||
return branches
|
||||
|
||||
@staticmethod
|
||||
def delete_branches(db: Session, branches_id: int, current_user):
|
||||
branches = db.query(Branches).filter(Branches.id == branches_id).first()
|
||||
if not branches:
|
||||
raise ValueError("branches no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este branches")
|
||||
|
||||
try:
|
||||
branches.is_active = False
|
||||
branches.deleted_at = datetime.utcnow()
|
||||
branches.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(branches)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el branches: {e}")
|
||||
|
||||
return {"message": "branches eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.client.models import Client
|
||||
from app.modules.client.schema import
|
||||
|
||||
|
||||
class ClientService:
|
||||
@staticmethod
|
||||
def create_client(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_client = Client(**data.dict())
|
||||
db.add(new_client)
|
||||
db.commit()
|
||||
db.refresh(new_client)
|
||||
return new_client
|
||||
|
||||
@staticmethod
|
||||
def get_client(db: Session, client_id: int, current_user):
|
||||
client = db.query(Client).filter(Client.id == client_id).first()
|
||||
if not client:
|
||||
raise ValueError("client no encontrado")
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def update_client(db: Session, client_id: int, data: , current_user):
|
||||
client = db.query(Client).filter(Client.id == client_id).first()
|
||||
if not client:
|
||||
raise ValueError("client no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este client")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(client, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(client)
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def delete_client(db: Session, client_id: int, current_user):
|
||||
client = db.query(Client).filter(Client.id == client_id).first()
|
||||
if not client:
|
||||
raise ValueError("client no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este client")
|
||||
|
||||
try:
|
||||
client.is_active = False
|
||||
client.deleted_at = datetime.utcnow()
|
||||
client.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(client)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el client: {e}")
|
||||
|
||||
return {"message": "client eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
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
|
||||
|
||||
|
||||
class ComentsService:
|
||||
@staticmethod
|
||||
def create_coments(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
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: , 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"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.edos.models import EDOS
|
||||
from app.modules.edos.schema import
|
||||
|
||||
|
||||
class EDOSService:
|
||||
@staticmethod
|
||||
def create_edos(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_edos = EDOS(**data.dict())
|
||||
db.add(new_edos)
|
||||
db.commit()
|
||||
db.refresh(new_edos)
|
||||
return new_edos
|
||||
|
||||
@staticmethod
|
||||
def get_edos(db: Session, edos_id: int, current_user):
|
||||
edos = db.query(EDOS).filter(EDOS.id == edos_id).first()
|
||||
if not edos:
|
||||
raise ValueError("edos no encontrado")
|
||||
return edos
|
||||
|
||||
@staticmethod
|
||||
def update_edos(db: Session, edos_id: int, data: , current_user):
|
||||
edos = db.query(EDOS).filter(EDOS.id == edos_id).first()
|
||||
if not edos:
|
||||
raise ValueError("edos no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este edos")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(edos, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(edos)
|
||||
return edos
|
||||
|
||||
@staticmethod
|
||||
def delete_edos(db: Session, edos_id: int, current_user):
|
||||
edos = db.query(EDOS).filter(EDOS.id == edos_id).first()
|
||||
if not edos:
|
||||
raise ValueError("edos no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este edos")
|
||||
|
||||
try:
|
||||
edos.is_active = False
|
||||
edos.deleted_at = datetime.utcnow()
|
||||
edos.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(edos)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el edos: {e}")
|
||||
|
||||
return {"message": "edos eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.efos.models import EFOS
|
||||
from app.modules.efos.schema import
|
||||
|
||||
|
||||
class EFOSService:
|
||||
@staticmethod
|
||||
def create_efos(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_efos = EFOS(**data.dict())
|
||||
db.add(new_efos)
|
||||
db.commit()
|
||||
db.refresh(new_efos)
|
||||
return new_efos
|
||||
|
||||
@staticmethod
|
||||
def get_efos(db: Session, efos_id: int, current_user):
|
||||
efos = db.query(EFOS).filter(EFOS.id == efos_id).first()
|
||||
if not efos:
|
||||
raise ValueError("efos no encontrado")
|
||||
return efos
|
||||
|
||||
@staticmethod
|
||||
def update_efos(db: Session, efos_id: int, data: , current_user):
|
||||
efos = db.query(EFOS).filter(EFOS.id == efos_id).first()
|
||||
if not efos:
|
||||
raise ValueError("efos no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este efos")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(efos, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(efos)
|
||||
return efos
|
||||
|
||||
@staticmethod
|
||||
def delete_efos(db: Session, efos_id: int, current_user):
|
||||
efos = db.query(EFOS).filter(EFOS.id == efos_id).first()
|
||||
if not efos:
|
||||
raise ValueError("efos no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este efos")
|
||||
|
||||
try:
|
||||
efos.is_active = False
|
||||
efos.deleted_at = datetime.utcnow()
|
||||
efos.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(efos)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el efos: {e}")
|
||||
|
||||
return {"message": "efos eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.files.models import Files
|
||||
from app.modules.files.schema import
|
||||
|
||||
|
||||
class FilesService:
|
||||
@staticmethod
|
||||
def create_files(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_files = Files(**data.dict())
|
||||
db.add(new_files)
|
||||
db.commit()
|
||||
db.refresh(new_files)
|
||||
return new_files
|
||||
|
||||
@staticmethod
|
||||
def get_files(db: Session, files_id: int, current_user):
|
||||
files = db.query(Files).filter(Files.id == files_id).first()
|
||||
if not files:
|
||||
raise ValueError("files no encontrado")
|
||||
return files
|
||||
|
||||
@staticmethod
|
||||
def update_files(db: Session, files_id: int, data: , current_user):
|
||||
files = db.query(Files).filter(Files.id == files_id).first()
|
||||
if not files:
|
||||
raise ValueError("files no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este files")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(files, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(files)
|
||||
return files
|
||||
|
||||
@staticmethod
|
||||
def delete_files(db: Session, files_id: int, current_user):
|
||||
files = db.query(Files).filter(Files.id == files_id).first()
|
||||
if not files:
|
||||
raise ValueError("files no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este files")
|
||||
|
||||
try:
|
||||
files.is_active = False
|
||||
files.deleted_at = datetime.utcnow()
|
||||
files.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(files)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el files: {e}")
|
||||
|
||||
return {"message": "files eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.invoices.models import Invoices
|
||||
from app.modules.invoices.schema import
|
||||
|
||||
|
||||
class InvoicesService:
|
||||
@staticmethod
|
||||
def create_invoices(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_invoices = Invoices(**data.dict())
|
||||
db.add(new_invoices)
|
||||
db.commit()
|
||||
db.refresh(new_invoices)
|
||||
return new_invoices
|
||||
|
||||
@staticmethod
|
||||
def get_invoices(db: Session, invoices_id: int, current_user):
|
||||
invoices = db.query(Invoices).filter(Invoices.id == invoices_id).first()
|
||||
if not invoices:
|
||||
raise ValueError("invoices no encontrado")
|
||||
return invoices
|
||||
|
||||
@staticmethod
|
||||
def update_invoices(db: Session, invoices_id: int, data: , current_user):
|
||||
invoices = db.query(Invoices).filter(Invoices.id == invoices_id).first()
|
||||
if not invoices:
|
||||
raise ValueError("invoices no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este invoices")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(invoices, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(invoices)
|
||||
return invoices
|
||||
|
||||
@staticmethod
|
||||
def delete_invoices(db: Session, invoices_id: int, current_user):
|
||||
invoices = db.query(Invoices).filter(Invoices.id == invoices_id).first()
|
||||
if not invoices:
|
||||
raise ValueError("invoices no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este invoices")
|
||||
|
||||
try:
|
||||
invoices.is_active = False
|
||||
invoices.deleted_at = datetime.utcnow()
|
||||
invoices.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(invoices)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el invoices: {e}")
|
||||
|
||||
return {"message": "invoices eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.locations.models import Locations
|
||||
from app.modules.locations.schema import
|
||||
|
||||
|
||||
class LocationsService:
|
||||
@staticmethod
|
||||
def create_locations(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_locations = Locations(**data.dict())
|
||||
db.add(new_locations)
|
||||
db.commit()
|
||||
db.refresh(new_locations)
|
||||
return new_locations
|
||||
|
||||
@staticmethod
|
||||
def get_locations(db: Session, locations_id: int, current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
return locations
|
||||
|
||||
@staticmethod
|
||||
def update_locations(db: Session, locations_id: int, data: , current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este locations")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(locations, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(locations)
|
||||
return locations
|
||||
|
||||
@staticmethod
|
||||
def delete_locations(db: Session, locations_id: int, current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este locations")
|
||||
|
||||
try:
|
||||
locations.is_active = False
|
||||
locations.deleted_at = datetime.utcnow()
|
||||
locations.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(locations)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el locations: {e}")
|
||||
|
||||
return {"message": "locations eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.moves.models import Moves
|
||||
from app.modules.moves.schema import
|
||||
|
||||
|
||||
class MovesService:
|
||||
@staticmethod
|
||||
def create_moves(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_moves = Moves(**data.dict())
|
||||
db.add(new_moves)
|
||||
db.commit()
|
||||
db.refresh(new_moves)
|
||||
return new_moves
|
||||
|
||||
@staticmethod
|
||||
def get_moves(db: Session, moves_id: int, current_user):
|
||||
moves = db.query(Moves).filter(Moves.id == moves_id).first()
|
||||
if not moves:
|
||||
raise ValueError("moves no encontrado")
|
||||
return moves
|
||||
|
||||
@staticmethod
|
||||
def update_moves(db: Session, moves_id: int, data: , current_user):
|
||||
moves = db.query(Moves).filter(Moves.id == moves_id).first()
|
||||
if not moves:
|
||||
raise ValueError("moves no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este moves")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(moves, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(moves)
|
||||
return moves
|
||||
|
||||
@staticmethod
|
||||
def delete_moves(db: Session, moves_id: int, current_user):
|
||||
moves = db.query(Moves).filter(Moves.id == moves_id).first()
|
||||
if not moves:
|
||||
raise ValueError("moves no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este moves")
|
||||
|
||||
try:
|
||||
moves.is_active = False
|
||||
moves.deleted_at = datetime.utcnow()
|
||||
moves.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(moves)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el moves: {e}")
|
||||
|
||||
return {"message": "moves eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.suppliers.models import Suppliers
|
||||
from app.modules.suppliers.schema import
|
||||
|
||||
|
||||
class SuppliersService:
|
||||
@staticmethod
|
||||
def create_suppliers(db: Session, data: ):
|
||||
|
||||
|
||||
|
||||
|
||||
new_suppliers = Suppliers(**data.dict())
|
||||
db.add(new_suppliers)
|
||||
db.commit()
|
||||
db.refresh(new_suppliers)
|
||||
return new_suppliers
|
||||
|
||||
@staticmethod
|
||||
def get_suppliers(db: Session, suppliers_id: int, current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
return suppliers
|
||||
|
||||
@staticmethod
|
||||
def update_suppliers(db: Session, suppliers_id: int, data: , current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este suppliers")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(suppliers, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(suppliers)
|
||||
return suppliers
|
||||
|
||||
@staticmethod
|
||||
def delete_suppliers(db: Session, suppliers_id: int, current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este suppliers")
|
||||
|
||||
try:
|
||||
suppliers.is_active = False
|
||||
suppliers.deleted_at = datetime.utcnow()
|
||||
suppliers.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(suppliers)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el suppliers: {e}")
|
||||
|
||||
return {"message": "suppliers eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
qeuitar condenados_contenados
|
||||
quitar condenados_contenados
|
||||
|
||||
ajustar el envio de notificacions
|
||||
ajustar los matchs de visualizacion
|
||||
|
||||
@@ -5,6 +5,7 @@ sqlalchemy==2.0.23
|
||||
alembic==1.12.1
|
||||
psycopg2-binary==2.9.9
|
||||
python-dotenv==1.0.0
|
||||
pandas>=2.0.0
|
||||
pydantic==2.5.0
|
||||
python-jose[cryptography]==3.3.0
|
||||
passlib[bcrypt]==1.7.4
|
||||
@@ -13,3 +14,4 @@ pyjwt==2.8.0
|
||||
email-validator==2.1.0
|
||||
python-dateutil==2.8.2
|
||||
bcrypt==4.0.1
|
||||
requests==2.31.0
|
||||
24
test_csv_extractor.py
Normal file
24
test_csv_extractor.py
Normal file
@@ -0,0 +1,24 @@
|
||||
# test_csv_extractor.py
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Añadir el directorio raíz al path
|
||||
sys.path.append(str(Path(__file__).parent))
|
||||
|
||||
from app.helpers.extractCsv import CSVExtractor
|
||||
|
||||
# Prueba con un CSV público
|
||||
test_url = "https://people.sc.fsu.edu/~jburkardt/data/csv/hw_200.csv"
|
||||
|
||||
try:
|
||||
print("📥 Descargando CSV...")
|
||||
content = CSVExtractor.download_csv(test_url)
|
||||
print(f"✅ Descargado: {len(content)} caracteres")
|
||||
|
||||
print("📖 Leyendo CSV...")
|
||||
rows = CSVExtractor.read_csv(content)
|
||||
print(f"✅ Leídas {len(rows)} filas")
|
||||
print(f"📋 Columnas: {list(rows[0].keys()) if rows else 'Ninguna'}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
Reference in New Issue
Block a user