GUÍA DE INTEGRACIÓN JIRA Y XRAY - HAKALAB FRAMEWORK v1.2.23+
CONFIGURACIÓN AUTOMÁTICA SIMPLIFICADA

=============================================================================
NUEVA FILOSOFÍA: CONFIGURACIÓN AUTOMÁTICA
=============================================================================

El framework ahora detecta automáticamente si Jira/Xray está habilitado y configura toda la integración SIN CÓDIGO ADICIONAL. Solo necesitas:

1. ✅ Configurar variables de entorno en .env
2. ✅ Usar el template simple de environment.py
3. ✅ ¡Listo! Todo funciona automáticamente

=============================================================================
FUNCIONALIDADES
=============================================================================

SOLO JIRA (Reglas 3 y 4):
- Adjuntar reportes HTML: Si el tag del feature (@PROJ-123) coincide con una issue de Jira, se adjunta automáticamente el reporte HTML
- Comentario personalizable: Se agrega un comentario configurable a la issue
- Validación automática: Si el tag no coincide con ninguna issue, no se realizan acciones

JIRA + XRAY CLOUD (Regla 5):
- Test Executions automáticos: Se crea UN Test Execution por feature con TODOS los tests
- Flujo optimizado: Una sola llamada API crea el Test Execution, adjunta todos los tests y actualiza sus estados
- Asociación automática: Los escenarios con tags válidos se incluyen automáticamente
- Estados correctos: Mapeo automático (passed/failed/skipped)
- Vinculación a HU: Test Execution se vincula automáticamente a la Historia de Usuario del feature
- Validación de tipos: Solo issues de tipo "Test" se procesan en Xray

=============================================================================
CONFIGURACIÓN AUTOMÁTICA
=============================================================================

1. VARIABLES DE ENTORNO (.env)
-------------------------------

# Integración Jira/Xray
JIRA_ENABLED=true                           # true=habilitar Jira, false=deshabilitar completamente
JIRA_URL=https://hakalab.atlassian.net
JIRA_EMAIL=felipe.farias@hakalab.com
JIRA_TOKEN=ATATT3xFfGF0DWFjw9A1O4PHPyHbOz0Ntqaj7-yWjwm0w5OernZnl0OtsXfxK1sd9foBaPKUY90WLSCseC8OS5dHmqWaV0PKTOqDKj_SIq4R_n-HHUVBzb0dRCUS2Hwv6ZjQE6LS02dc5vLNYQZuxS941J6bwRyJSgMF28ZMyrjzciCjtDSWm7k=1E898852
JIRA_PROJECT=PROD                           # Clave del proyecto (ej: PROJ, TEST, QA)
JIRA_COMMENT_MESSAGE=Reporte prueba de QA   # Mensaje para comentarios

# Configuración de Xray (OPCIONAL, requiere Jira configurado)
XRAY_ENABLED=true                          # true=habilitar Xray, false=solo Jira
XRAY_TEST_PLAN=                            # Opcional: Test Plan para asociar executions (ej: PROD-123)

# Configuración de Xray Cloud API (token directo)
XRAY_AUTHORIZATION_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZW5hbnQiOiIyNjI1MGIzNC04YTMyLTNiZWMtOGI1MC04MjljZGJkNmMwMDciLCJhY2NvdW50SWQiOiI1ZmIyOTFiYWRkMGM1OTAwNzU5MWVhOWYiLCJpc1hlYSI6ZmFsc2UsImlhdCI6MTc2Nzk3MTg2NSwiZXhwIjoxNzY4MDU4MjY1LCJhdWQiOiIzRUJBM0IyRjA2MEI0Q0Q3QjRFQzE4NzgwQ0M1MDBFNyIsImlzcyI6ImNvbS54cGFuZGl0LnBsdWdpbnMueHJheSIsInN1YiI6IjNFQkEzQjJGMDYwQjRDRDdCNEVDMTg3ODBDQzUwMEU3In0.7HStiUpL2C7edzUDALpPHFQfJOxn8WzD6DLT3BLxva0
XRAY_BASE_URL=https://xray.cloud.getxray.app

2. USAR TEMPLATE SIMPLE
------------------------

Copia el template environment_simple.py a tu proyecto como features/environment.py:

"""
Environment.py SIMPLE para Hakalab Framework
Configuración automática de todas las integraciones
"""
from hakalab_framework import (
    setup_framework_context,
    setup_scenario_context
)
from hakalab_framework.core.screenshot_manager import take_screenshot_on_failure, take_screenshot
from hakalab_framework.core.behave_html_integration import (
    setup_html_reporting,
    before_feature_html,
    after_feature_html,
    before_scenario_html,
    after_scenario_html,
    after_step_html,
    generate_html_report
)
from hakalab_framework.core.environment_config import (
    auto_before_feature,
    auto_after_scenario,
    auto_after_feature,
    auto_after_all
)
from hakalab_framework.steps import *

def before_all(context):
    """Configuración inicial - Framework + HTML Reporter + Auto Jira/Xray"""
    try:
        from hakalab_framework.core.screenshot_manager import cleanup_directories
        cleanup_directories()
        
        # Configurar framework (incluye auto-detección de Jira/Xray)
        setup_framework_context(context)
        setup_html_reporting(context)
        
        print("✅ Framework configurado correctamente")
    except Exception as e:
        print(f"❌ Error en before_all: {e}")
        raise

def before_feature(context, feature):
    try:
        before_feature_html(context, feature)
        auto_before_feature(context, feature)  # Auto Jira/Xray
    except Exception as e:
        print(f"⚠️ Error en before_feature: {e}")

def before_scenario(context, scenario):
    try:
        setup_scenario_context(context, scenario)
        before_scenario_html(context, scenario)
        print(f"🚀 Iniciando escenario: {scenario.name}")
    except Exception as e:
        print(f"❌ Error en before_scenario: {e}")
        raise

def after_step(context, step):
    try:
        after_step_html(context, step)
        import os
        capture_framework_steps = os.getenv('CAPTURE_FRAMEWORK_STEPS', 'false').lower() == 'true'
        if capture_framework_steps and hasattr(context, 'page') and context.page:
            step_name = step.name.replace(' ', '_').replace('"', '').replace("'", '')
            screenshot_name = f"framework_step_{step.line}_{step_name[:50]}"
            take_screenshot(context, screenshot_name)
    except Exception as e:
        print(f"⚠️ Error en after_step: {e}")

def after_scenario(context, scenario):
    try:
        after_scenario_html(context, scenario)
        take_screenshot_on_failure(context, scenario)
        auto_after_scenario(context, scenario)  # Auto Jira/Xray
    except Exception as e:
        print(f"⚠️ Error en after_scenario: {e}")

    try:
        if hasattr(context, 'page') and context.page:
            context.page.close()
            context.page = None
    except:
        pass

def after_feature(context, feature):
    try:
        after_feature_html(context, feature)
        auto_after_feature(context, feature)  # Auto Jira/Xray
    except Exception as e:
        print(f"⚠️ Error en after_feature: {e}")

def after_all(context):
    try:
        if hasattr(context, 'framework_config') and context.framework_config:
            context.framework_config.cleanup()
            print("✅ Playwright cerrado correctamente")
    except Exception as e:
        print(f"⚠️ Error cerrando Playwright: {e}")

    try:
        report_path = generate_html_report(context)
        if report_path:
            print(f"🎨 Reporte HTML personalizado: {report_path}")
            context.html_report_path = report_path
    except Exception as e:
        print(f"⚠️ Error generando reporte HTML: {e}")

    try:
        from hakalab_framework.core.screenshot_manager import get_screenshots_summary
        summary = get_screenshots_summary()
        if summary["total"] > 0:
            print(f"📸 Screenshots generados: {summary['total']} total, {summary['failed']} fallos")
    except Exception as e:
        print(f"⚠️ Error obteniendo resumen de screenshots: {e}")

    auto_after_all(context)  # Auto Jira/Xray

3. ¡LISTO!
----------

Con esta configuración:
- ✅ El framework detecta automáticamente si JIRA_ENABLED=true
- ✅ Configura toda la integración Jira/Xray sin código adicional
- ✅ Mantiene la simplicidad del framework
- ✅ Funciona exactamente igual que antes
- ✅ CERO configuración manual de hooks

=============================================================================
USO DE TAGS
=============================================================================

FORMATO DE TAGS:
Los tags deben seguir el formato: @PROJECT-NUMBER

Ejemplos válidos:
@PROD-123    # Issue del proyecto PROD con número 123
@TEST-456    # Issue del proyecto TEST con número 456
@QA-789      # Issue del proyecto QA con número 789

Ejemplos inválidos:
@feature-login     # No sigue formato PROJECT-NUMBER
@PROD123          # Falta el guión
@123              # Falta el proyecto

TAGS EN FEATURES (Historia de Usuario):
@PROD-90
Feature: Prueba flujo correcto
  # El reporte HTML se adjuntará a la issue PROD-90
  # El Test Execution se vinculará a esta Historia de Usuario

TAGS EN SCENARIOS (Tests en Xray):
@PROD-91
Scenario: Primer test del flujo correcto
  # Este escenario se asociará al Test PROD-91 en Xray
  # PROD-91 DEBE ser una issue de tipo "Test"

@PROD-92
Scenario: Segundo test del flujo correcto
  # Este escenario se asociará al Test PROD-92 en Xray
  # PROD-92 DEBE ser una issue de tipo "Test"

=============================================================================
ENVIRONMENT.PY SIMPLE
=============================================================================

CONFIGURACIÓN AUTOMÁTICA:
El framework ahora maneja automáticamente toda la integración Jira/Xray. Solo necesitas usar las funciones auto_* que detectan y ejecutan los hooks apropiados:

# Importar funciones automáticas
from hakalab_framework.core.environment_config import (
    auto_before_feature,
    auto_after_scenario,
    auto_after_feature,
    auto_after_all
)

def before_feature(context, feature):
    # HTML reporting
    before_feature_html(context, feature)
    
    # Auto-hooks (incluye Jira/Xray si está habilitado)
    auto_before_feature(context, feature)

def after_scenario(context, scenario):
    # HTML reporting y screenshots
    after_scenario_html(context, scenario)
    take_screenshot_on_failure(context, scenario)
    
    # Auto-hooks (incluye Jira/Xray si está habilitado)
    auto_after_scenario(context, scenario)

def after_feature(context, feature):
    # HTML reporting
    after_feature_html(context, feature)
    
    # Auto-hooks (incluye Jira/Xray si está habilitado)
    auto_after_feature(context, feature)

def after_all(context):
    # Generar reporte HTML
    report_path = generate_html_report(context)
    if report_path:
        context.html_report_path = report_path
    
    # Auto-hooks (incluye Jira/Xray si está habilitado)
    auto_after_all(context)

¿QUÉ HACE AUTOMÁTICAMENTE?
Cuando JIRA_ENABLED=true, el framework:

1. Before All: Verifica conexiones con Jira/Xray
2. Before Feature: Inicializa recopilación de datos
3. After Scenario: Recopila resultados de cada escenario
4. After Feature: Guarda información para procesamiento posterior
5. After All: 
   - Procesa tags del feature para Jira (adjunta reporte)
   - Crea Test Execution en Xray con TODOS los tests
   - Vincula Test Execution a Historia de Usuario

CONFIGURACIÓN MANUAL (AVANZADA):
Si necesitas control total, puedes usar el template environment_with_jira_xray.py que requiere importar y configurar manualmente todos los hooks de Jira/Xray.

=============================================================================
FLUJO DE TRABAJO AUTOMÁTICO
=============================================================================

PROCESO COMPLETO (Nuevo Flujo Optimizado):

1. Before All: Verificar conexiones con Jira/Xray
2. Before Feature: Inicializar recopilación de datos
3. After Scenario: Recopilar resultados de cada escenario
4. After Feature: Guardar información para procesamiento posterior
5. After All: 
   - Generar reporte HTML
   - Procesar tags del feature para Jira (adjuntar reporte)
   - Crear Test Execution en Xray con TODOS los tests en UNA sola llamada
   - Vincular Test Execution a Historia de Usuario

FLUJO XRAY OPTIMIZADO:
El nuevo flujo utiliza una sola llamada API que:

1. Crea el Test Execution
2. Adjunta TODOS los tests del feature
3. Actualiza los estados de todos los tests
4. Vincula el Test Execution a la Historia de Usuario

Ejemplo JSON:
{
  "tests": [
    {
      "testKey": "PROD-91",
      "start": "2026-01-09T13:25:04+01:00",
      "finish": "2026-01-09T13:25:34+01:00",
      "comment": "Execution from Prueba flujo correcto",
      "status": "passed"
    },
    {
      "testKey": "PROD-92",
      "start": "2026-01-09T13:25:04+01:00",
      "finish": "2026-01-09T13:25:34+01:00",
      "comment": "Execution from Prueba flujo correcto",
      "status": "passed"
    }
  ]
}

MAPEO DE ESTADOS:
Estado Behave | Estado Xray | Descripción
passed        | passed      | Escenario ejecutado exitosamente
failed        | failed      | Escenario falló durante ejecución
skipped       | skipped     | Escenario saltado
undefined     | skipped     | Steps no implementados
pending       | skipped     | Escenario marcado como pendiente

=============================================================================
STEPS ESPECÍFICOS
=============================================================================

VERIFICACIÓN DE CONFIGURACIÓN:
# Verificar conexión con Jira
Given verifico la conexión con Jira

# Verificar configuración de Xray
Given verifico la configuración de Xray

# Mostrar información de integración
When muestro información de la integración Jira/Xray

GESTIÓN DE ISSUES:
# Verificar que una issue existe
Given verifico que la issue "PROD-123" existe en Jira

# Verificar que es de tipo Test (para Xray)
Given verifico que el test "PROD-456" es de tipo Test en Jira

# Agregar comentario a issue
When agrego un comentario "Prueba completada" a la issue "PROD-123"

# Adjuntar archivo a issue
When adjunto el archivo "reports/report.html" a la issue "PROD-123"

BÚSQUEDAS JQL:
# Buscar issues con JQL
When busco issues en Jira con JQL "project = PROD AND issuetype = Test"

# Verificar resultados
Then verifico que la búsqueda JQL encontró "5" issues

=============================================================================
EJEMPLOS PRÁCTICOS
=============================================================================

EJEMPLO 1: Solo Jira
--------------------

# language: es
@PROD-123
Feature: Login de usuarios
  # El reporte HTML se adjuntará automáticamente a PROD-123
  
  Scenario: Login exitoso
    Given voy a la url "${BASE_URL}/login"
    When relleno el campo "username" con "${USERNAME}" con identificador "name"
    And relleno el campo "password" con "${PASSWORD}" con identificador "name"
    And hago click en el elemento "login_button" con identificador "id"
    Then debería ver el texto "Bienvenido"

Resultado:
- ✅ Reporte HTML adjuntado a issue PROD-123
- ✅ Comentario "Reporte prueba de QA" agregado

EJEMPLO 2: Jira + Xray (Flujo Optimizado)
------------------------------------------

# language: es
@PROD-90
Feature: Prueba flujo correcto
  Como usuario del framework
  Quiero probar el flujo correcto de Xray
  Para verificar que se crea UN Test Execution con TODOS los tests

  @PROD-91
  Scenario: Primer test del flujo correcto
    When I go to the url "https://example.com"
    And I take a screenshot with name "flow1"

  @PROD-92
  Scenario: Segundo test del flujo correcto
    When I go to the url "https://httpbin.org"
    And I take a screenshot with name "flow2"

Resultado:
- ✅ Reporte HTML adjuntado a issue PROD-90
- ✅ UN Test Execution creado (ej: PROD-144)
- ✅ TODOS los tests incluidos en UNA llamada: PROD-91, PROD-92
- ✅ Estados actualizados: PROD-91=passed, PROD-92=passed
- ✅ Test Execution vinculado a HU: PROD-144 → PROD-90

EJEMPLO 3: Verificación Manual
------------------------------

# language: es
Feature: Verificación de integración Jira/Xray
  
  Scenario: Validar configuración
    Given verifico la conexión con Jira
    And verifico la configuración de Xray
    When muestro información de la integración Jira/Xray
    And verifico que la issue "PROD-90" existe en Jira
    And verifico que el test "PROD-91" es de tipo Test en Jira
    Then busco issues en Jira con JQL "project = PROD AND issuetype = Test"
    And verifico que la búsqueda JQL encontró "10" issues

=============================================================================
TROUBLESHOOTING
=============================================================================

ERRORES COMUNES:

1. "Jira deshabilitado"
   # Verificar variable de control
   JIRA_ENABLED=true

2. "Jira no está configurado"
   # Verificar variables de entorno
   echo $JIRA_URL
   echo $JIRA_EMAIL
   echo $JIRA_TOKEN
   echo $JIRA_PROJECT

3. "Error de conexión con Jira"
   - Verificar que la URL es correcta
   - Verificar que el token API es válido
   - Verificar permisos del usuario en el proyecto

4. "Issue no encontrada"
   - Verificar que el tag sigue el formato correcto: @PROJECT-NUMBER
   - Verificar que la issue existe en el proyecto configurado
   - Verificar permisos de lectura en la issue

5. "Xray requiere XRAY_AUTHORIZATION_TOKEN configurado"
   - Obtener token de autorización de Xray Cloud
   - Configurar XRAY_AUTHORIZATION_TOKEN
   - Establecer XRAY_ENABLED=true

6. "Issue no es de tipo Test"
   - Verificar que la issue en Jira es de tipo "Test"
   - Solo issues de tipo "Test" se procesan en Xray

DEBUG:
# Mostrar información detallada
When muestro información de la integración Jira/Xray

# Verificar issue específica
Given verifico que la issue "PROD-90" existe en Jira
And verifico que el test "PROD-91" es de tipo Test en Jira

# Buscar issues del proyecto
When busco issues en Jira con JQL "project = ${JIRA_PROJECT}"

LOGS ÚTILES:
Los logs muestran información detallada del proceso:

🔗 Iniciando integración con Jira
✅ Conexión exitosa con Jira. Usuario: Felipe Farías
✅ Conexión con Jira establecida
🔗 Xray habilitado
📋 Procesando integración para feature: Prueba flujo correcto
🔍 Procesando tag PROD-90 como issue PROD-90
✅ Archivo test_report_20260109_133546.html adjuntado a issue PROD-90
✅ Comentario agregado a issue PROD-90
📊 Jira: 1/1 reportes adjuntados exitosamente
🧪 Procesando integración con Xray...
🔄 Creando Test Execution con 2 tests en una sola llamada...
📤 Enviando 2 tests a Xray...
✅ Test Execution creado: PROD-144
📊 Tests incluidos y actualizados: PROD-91, PROD-92
🔗 Vinculando Test Execution PROD-144 a HU PROD-90...
🔗 Test Execution PROD-144 vinculado a Historia de Usuario: PROD-90
✅ Test Execution creado y actualizado (legacy): PROD-144

=============================================================================
VERSIÓN DEL FRAMEWORK
=============================================================================

Hakalab Framework v1.2.23+
- ✅ Integración completa con Jira
- ✅ Integración optimizada con Xray Cloud
- ✅ Flujo optimizado: Una sola llamada API para crear Test Execution con todos los tests
- ✅ Estados correctos: passed/failed/skipped
- ✅ Vinculación automática: Test Execution → Historia de Usuario
- ✅ Adjunto automático de reportes HTML
- ✅ Validación de tipos de issues
- ✅ Control de habilitación/deshabilitación
- ✅ Steps específicos para gestión manual
- ✅ CONFIGURACIÓN AUTOMÁTICA: Detección automática de Jira/Xray habilitado
- ✅ SIMPLICIDAD TOTAL: Solo configurar .env y usar template simple

Esta integración permite una trazabilidad completa entre tus pruebas automatizadas y tu gestión de proyectos en Jira/Xray, automatizando completamente el reporte de resultados con un flujo optimizado que crea Test Executions con todos los tests en una sola operación, manteniendo la filosofía de simplicidad del framework.