Arch/services/schema_service.py

170 lines
4.9 KiB
Python
Raw Permalink Normal View History

2025-03-03 15:35:24 -03:00
import os
2025-03-03 17:50:11 -03:00
import json
2025-03-03 15:35:24 -03:00
from datetime import datetime
import pytz
from flask import current_app
from utils.file_utils import load_json_file, save_json_file
2025-03-03 17:50:11 -03:00
def get_schema_file_path():
"""Get path to the schema storage file."""
2025-03-03 17:50:11 -03:00
storage_path = current_app.config["STORAGE_PATH"]
return os.path.join(storage_path, "schemas", "schema.json")
def load_schemas():
"""Load all schemas from storage."""
file_path = get_schema_file_path()
if os.path.exists(file_path):
with open(file_path, "r", encoding="utf-8") as f:
return json.load(f)
return {}
2025-03-03 15:35:24 -03:00
2025-03-03 17:50:11 -03:00
def save_schemas(schemas):
"""Save schemas to storage."""
file_path = get_schema_file_path()
with open(file_path, "w", encoding="utf-8") as f:
json.dump(schemas, f, ensure_ascii=False, indent=2)
return True
2025-03-03 17:50:11 -03:00
def get_all_schemas():
"""Get all schemas as a list."""
schemas_dict = load_schemas()
return [
{**schema_data, "id": schema_id}
for schema_id, schema_data in schemas_dict.items()
]
def get_schema_by_id(schema_id):
"""Get a specific schema by ID."""
schemas = load_schemas()
if schema_id in schemas:
return {**schemas[schema_id], "id": schema_id}
return None
2025-03-03 17:50:11 -03:00
2025-03-03 15:35:24 -03:00
2025-03-03 17:50:11 -03:00
def create_schema(schema_data, user_id):
2025-03-03 15:35:24 -03:00
"""
Crear un nuevo esquema.
2025-03-03 17:50:11 -03:00
2025-03-03 15:35:24 -03:00
Args:
schema_data (dict): Datos del esquema
2025-03-03 17:50:11 -03:00
user_id (str): ID del usuario que crea el esquema
2025-03-03 15:35:24 -03:00
Returns:
2025-03-03 17:50:11 -03:00
tuple: (éxito, mensaje)
2025-03-03 15:35:24 -03:00
"""
schemas = load_schemas()
2025-03-03 17:50:11 -03:00
# Verificar si ya existe un esquema con ese código
schema_id = schema_data["codigo"]
if schema_id in schemas:
return False, f"Ya existe un esquema con el código {schema_id}."
# Añadir metadatos
schema_data["fecha_creacion"] = datetime.now(pytz.UTC).isoformat()
schema_data["creado_por"] = user_id
# Guardar esquema
schemas[schema_id] = schema_data
save_schemas(schemas)
2025-03-03 17:50:11 -03:00
return True, f"Esquema '{schema_data['descripcion']}' creado correctamente."
def update_schema(schema_id, schema_data):
"""Update an existing schema."""
schemas = load_schemas()
2025-03-03 17:50:11 -03:00
if schema_id not in schemas:
return False
2025-03-03 17:50:11 -03:00
# Update modification timestamp
schema_data["updated_at"] = datetime.now().isoformat()
2025-03-03 17:50:11 -03:00
# Remove id from data before saving (it's used as the key)
data_to_save = {k: v for k, v in schema_data.items() if k != "id"}
2025-03-03 17:50:11 -03:00
schemas[schema_id] = data_to_save
return save_schemas(schemas)
2025-03-03 17:50:11 -03:00
def delete_schema(schema_id):
2025-03-03 15:35:24 -03:00
"""
Eliminar un esquema.
2025-03-03 17:50:11 -03:00
2025-03-03 15:35:24 -03:00
Args:
2025-03-03 17:50:11 -03:00
schema_id (str): ID del esquema a eliminar
2025-03-03 15:35:24 -03:00
Returns:
2025-03-03 17:50:11 -03:00
tuple: (éxito, mensaje)
2025-03-03 15:35:24 -03:00
"""
schemas = load_schemas()
2025-03-03 17:50:11 -03:00
2025-03-03 15:35:24 -03:00
# Verificar si existe el esquema
2025-03-03 17:50:11 -03:00
if schema_id not in schemas:
return False, f"No existe un esquema con el código {schema_id}."
# Verificar si el esquema está en uso
# [Implementar verificación si el esquema está asociado a proyectos]
2025-03-03 15:35:24 -03:00
# Eliminar esquema
2025-03-03 17:50:11 -03:00
schema_desc = schemas[schema_id].get("descripcion", schema_id)
del schemas[schema_id]
save_schemas(schemas)
2025-03-03 17:50:11 -03:00
return True, f"Esquema '{schema_desc}' eliminado correctamente."
2025-03-03 15:35:24 -03:00
def initialize_default_schemas():
"""Initialize default schemas if none exist."""
schemas = load_schemas()
if not schemas:
default_schemas = {
"default": {
"name": "Documento Estándar",
"description": "Esquema básico para documentos",
"fields": [
{"name": "title", "type": "text", "required": True},
{"name": "content", "type": "textarea", "required": True},
{"name": "tags", "type": "tags", "required": False},
],
"created_by": "system",
"created_at": datetime.now().isoformat(),
},
"report": {
"name": "Informe",
"description": "Esquema para informes formales",
"fields": [
{"name": "title", "type": "text", "required": True},
{"name": "summary", "type": "textarea", "required": True},
{"name": "body", "type": "richtext", "required": True},
{"name": "date", "type": "date", "required": True},
{"name": "author", "type": "text", "required": True},
],
"created_by": "system",
"created_at": datetime.now().isoformat(),
},
2025-03-03 17:50:11 -03:00
}
save_schemas(default_schemas)
2025-03-03 17:50:11 -03:00
def get_schema_document_types(schema_id):
"""
Obtener los tipos de documentos definidos en un esquema.
Args:
schema_id (str): ID del esquema
Returns:
list: Lista de tipos de documentos en el esquema, o lista vacía si no existe
"""
schema = get_schema_by_id(schema_id)
if not schema or "documentos" not in schema:
return []
return schema["documentos"]