New post

Rechercher

Article
· May 3, 2024 6m read

Tasks flow with InterSystems IRIS Workflow Engine - Configuration

In our previous article we presented the general concepts as well as the problem that we wanted to solve by using the task engine integrated in InterSystems IRIS, in today's article we will see how we configure an interoperability production to provide a solution.

Workflow Engine Configuration

First we are going to define the roles of the tasks that we are going to manage, in our example we are going to define two types:

  • AutomaticBloodPressureRole: to create automatic tasks that will have no intervention from the user.
  • ManualBloodPressureRole: to create those tasks that the user must manually validate.

It will not be necessary to assign users to these roles since we will do it later as we go along as we receive HL7 messages from different patients.

We also do not need to add IRIS users to the Workflow since we will do it by code from production.

Production setup

For our example we are going to create a production within a NAMESPACE created ad-hoc and which we have called WORKFLOW. It will be in this production where we will include the business components that we need.

Let's start by explaining the simplest components:

Business Services

  • HL7_File_IN: responsible for collecting HL7 files from a specific server path that will simulate receiving messaging from a medical device.

Business Operations

  • AutomaticBloodPressureRole:component of the class EnsLib.Workflow.Operation, with the name of one of the defined roles that we will use to generate in our Workflow the tasks that will not involve direct interaction with the user.
  • ManualBloodPressureRole: similar to the previous Business Operation, but in this case the tasks we generate will require the user to intervene directly to close them.

Let's now see in detail the Business Process that will manage the flow of information and the creation and management of the tasks involved in our cycle.

Workflow.BP.BloodPressurePlan

This Business Process is of the BPL type and will be responsible for creating the tasks involved in patient care and capturing the response, both from the patient and from the medical device that will send the information related to blood pressure levels.

Start of the process:

In this part the flow does the following:

  1. Checking user: checks the user received in the received ADT^A08 message and if it exists, continues moving through the flow, otherwise it creates the user in IRIS and assigns it to the roles defined in the workflow. To assign users to the role, it runs the following command:
    /// Workflow user creation
    set sc = ##class(EnsLib.Workflow.UserDefinition).CreateUser(username)
    /// Assigning Workflow user to the role
    set sc = ##class(EnsLib.Workflow.RoleDefinition).AddUserToRole(role, username)
  2. Get automatic task: Since in this flow we are going to manage both automatic and manual tasks, we must check if there are pending automatic tasks for the user for the patient received. This is relevant since if there are pending automatic tasks it means that we have had a previous reading whose values exceed normal levels. We will do the checking directly on the TaskResponse table where all the created tasks are saved, the query will be as follows:
    &sql(SELECT ID INTO :taskId FROM EnsLib_Workflow.TaskResponse WHERE TaskStatus_AssignedTo = :username AND TaskStatus_IsComplete = 0 AND %RoleName = :role)
  3. Getting count of OBX: we retrieve the number of OBX segments from our HL7 message.
  4. Check OBX values: we go through the OBX segments and extract only the data related to blood pressure.
  5. Pending tasks?: As we said in point 2, we check if we have a pending automatic task or not.

First blood pressure reading:

In this part of the flow we will deal with those messages that are not generated by a first reading that exceeds the defined maximum blood pressure levels.

  1. Check pressure: We check if blood pressure levels exceed pre-established limits; if they do not, the process will conclude without the need to do anything else. Otherwise it will be necessary to create the necessary tasks.
  2. Create manual task: The blood pressure has exceeded the defined safety levels, so it will be necessary to create a manual task in which we will inform the patient of the situation, indicating that they must take a second reading. Let's see the configuration of this activity.     
    1. We will invoke the Business Operation ManualBloodPressureRole which will be in charge of generating the task by passing it a message of type EnsLib.Workflow.TaskRequest.
    2. We will define the actions that the patient can perform separated by commas in callrequest.%Actions, in this case we have only defined the "Accept" action.
    3. We configure the message that will be shown to the patient in callrequest.%Message.
    4. We assign the patient the created task by defining her username in callrequest.%UserName.
    5. Finally we will indicate a subject or title in callequest.%Subject and a priority (between 1 and 3) in callrequest.%Priority.
  3. Create auto task: similar to the previous activity configuration, but this time we will send it to the Business Operation AutomaticBloodPressureRole. This task will be the one that will be kept waiting for the patient's second blood pressure reading and will be the one that will cause any new message received by production for this patient not to generate new tasks by obtaining a false in the Pending task? activity.
  4. Wait for tasks: This activity will keep the task flow on hold until the task and manual are completed, that is, until the patient closes the alarm created by ManualBloodPressureRole and the IRIS production receives a second message from the medical device.
  5. Check if warning: We will get to this activity once the previous pending tasks have been closed. At this point we will check if the closing of the automatic task has received a new reading with levels that exceed the maximum configured blood pressure values (the task will be closed with a warning action) or not. If the measurement is less than the maximum values, the process will conclude. If the measurements exceed the maximum values, you will move on to the next activity.
  6. Warning task for doctor: A manual task is created to inform the doctor assigned to the patient that the patient may be suffering a crisis.
  7. Warning task for patient: we inform the patient with a new manual task that his doctor has been informed of the situation.

Second blood pressure reading

This part of the flow will only be accessed when there is a previously created automatic task that has not been completed.

  1. Check pressure: We again validate for the message received whether the blood pressure values exceed the limit or not.
  2. Close normal task: If the levels do not exceed the maximum values, we will close the pending task with the CompleteTask method provided by the EnsLib.Workflow.TaskResponse class that our task instantiates. The parameter used will indicate the action taken, in this case we will indicate that it is a false alarm by passing the value FalseAlarm, we could define any other one we want.
  3. Close warning task:Same as in the previous case, with the difference that in this case the action that we pass to the Workflow engine will be Warning and that it will be the value that the "Check if warning" activity that we have seen previously will check.

As you can see in the following diagram (it is not literal but you can get an idea of how it will work), our task flow will work with 2 "threads" or "processes":

The first thread/process will remain open in case it is necessary to wait for a second reading and it will be the second thread/process that will cause the reactivation of the first open thread upon receiving said second reading, thus concluding the defined task flow.

Conclusion

As you can see, configuring a task flow in a BPL is quite simple, and you can simulate automatic and manual tasks without much complication. In the next and last article we will see how users can interact with their tasks from an external application.

Thank you all for your attention!

Discussion (0)1
Log in or sign up to continue
Article
· May 3, 2024 6m read

Flujos de tareas con InterSystems IRIS Workflow Engine - Configuración

En nuestro artículo anterior presentábamos los conceptos generales así como la problemática que queríamos resolver mediante el uso del motor de tareas integrado en InterSystems IRIS, en el artículo de hoy veremos como configuramos una producción de interoperabilidad para proveer una solución.

Configuración del motor de Workflow

Primeramente vamos a definir los roles de las tareas que vamos a manejar, en nuestro ejemplo vamos a definir dos tipos:

  • AutomaticBloodPressureRole: que utilizaremos para crear las tareas automáticas que no tendrán intervención por parte del usuario.
  • ManualBloodPressureRole: para aquellas tareas que el usuario deberá validar.

No será necesario asignar a estos roles los usuarios ya que lo haremos posterior sobre la marcha conforme vayamos recibiendo mensajes de HL7 de diferentes pacientes.

Tampoco necesitamos añadir usuarios de IRIS al Workflow ya que lo haremos por código desde la producción.

Configuración de la producción

Para nuestro ejemplo vamos a crear una producción dentro de un NAMESPACE creado ad-hoc y al que hemos llamado WORKFLOW. Será en esta producción donde incluiremos los componentes del negocio que necesitemos.

Empecemos explicando los componentes más sencillos:

Business Services

  • HL7_File_IN: encargado de recoger los archivos HL7 de una ruta específica del servidor que simularán la recepción de mensajería desde un dispositivo médico.

Business Operations

  • AutomaticBloodPressureRole: componente de la clase EnsLib.Workflow.Operation, con el nombre de uno de los roles definidos y que usaremos para generar en nuestro Workflow las tareas que no implicarán interacción directa con el usuario.
  • ManualBloodPressureRole: similiar al Business Operation anterior, pero en este caso las tareas que generemos requerirán que el usuario intervenga directamente para su cierre.

Veamos ahora en detalle el Business Process que gestionará el flujo de información y la creación y gestión de las tareas implicadas en nuestro ciclo.

Workflow.BP.BloodPressurePlan

Este Business Process es del tipo BPL y será el responsable de la creación de las tareas implicadas en el cuidado del paciente y en la captura de la respuesta, tanto del paciente como del dispositivo médico que remitirá la información relativa a los niveles de presión arterial.

Inicio del proceso:

En esta parte el flujo hace lo siguiente:

  1. Checking user: comprueba el usuario recibido en el mensaje ADT^A08 recibido y si existe, continúa avanzando por el flujo, si no crea al usuario en IRIS y lo asigna a los roles definidos en el workflow. Para asignar los usuarios al rol ejecuta el siguiente comando:
    /// Workflow user creation
    set sc = ##class(EnsLib.Workflow.UserDefinition).CreateUser(username)
    /// Assigning Workflow user to the role
    set sc = ##class(EnsLib.Workflow.RoleDefinition).AddUserToRole(role, username)
  2. Get automatic task: dado que en este flujo vamos a gestionar tareas tanto automáticas como manuales debemos comprobar si para el paciente recibido existen tareas automáticas pendientes para el usuario. Esto es relevante ya que si existen tareas automáticas pendientes significa que hemos tenido una lectura previa cuyos valores superan los niveles de normales. La comprobación la haremos directamente sobre la tabla de TaskResponse donde se guardan todas las tareas creadas, la consulta será la siguiente:
    &sql(SELECT ID INTO :taskId FROM EnsLib_Workflow.TaskResponse WHERE TaskStatus_AssignedTo = :username AND TaskStatus_IsComplete = 0 AND %RoleName = :role)
  3. Getting count of OBX: recuperamos el número de segmentos OBX de nuestro mensaje de HL7.
  4. Check OBX values: recorremos los segmentos OBX y extraemos únicamente los datos relativos a la presión arterial.
  5. Pending tasks?: como hemos dicho en el punto 2, comprobamos si tenemos una tarea automática pendiente o no.

Primera lectura de presión arterial:

En esta parte del flujo trataremos aquellos mensajes que no vienen generados por una primera lectura que supere los niveles de presión arterial máximos definidos.

  1. Check pressure: comprobamos si los niveles de presión arterial superan unos límites preestablecidos, si no lo superan el proceso concluirá sin necesidad de hacer nada más. En caso contrario será necesario crear las tareas necesarias.
  2. Create manual task: la presión arterial ha superado los niveles de seguridad definidos por lo que será necesario crear una tarea manual en la que informaremos al paciente de la situación indicándole que deberá tomarte una segunda lectura, veamos la configuración de esta actividad.  
    1. Invocaremos al Business Operation ManualBloodPressureRole que será el encargado de generar la tarea pasándole un mensaje de tipo EnsLib.Workflow.TaskRequest.
    2. Definiremos las acciones que podrá realizar el paciente separadas por comas en callrequest.%Actions, en este caso sólo hemos definido la acción "Accept".
    3. Configuramos el mensaje que se mostrará al paciente en callrequest.%Message.
    4. Le asignamos al paciente la tarea creada definiendo su nombre de usuario en callrequest.%UserName.
    5. Finalmente le indicaremos un asunto o título en callequest.%Subject y una prioridad (entre 1 y 3) en callrequest.%Priority.
  3. Create auto task: similar a la configuración de la actividad anterior, pero en esta ocasión lo enviaremos al Business Operation AutomaticBloodPressureRole. Esta tarea será la que se mantendrá a la espera de la segunda lectura de la presión arterial del paciente y será la que provoque que cualquier nuevo mensaje recibido por la producción para este paciente no genere nuevas tareas al obtener un false en la actividad de Pending task?
  4. Wait for tasks: esta actividad mantendrá el flujo de tareas en espera hasta que la tarea y manual sean finalizadas, es decir, hasta que el paciente cierre la alarma creada por ManualBloodPressureRole y la producción de IRIS reciba un segundo mensaje por parte del dispositivo médico.
  5. Check if warning: llegaremos a esta actividad una vez que se hayan cerrado las tareas pendientes anteriores. En este punto comprobaremos si el cierre de la tarea automática ha recibido una nueva lectura con niveles que superan los valores máximos de presión arterial configurados (la tarea se cerrará con una acción de warning) o no. En el caso de que la medida sea inferior a los valores máximos concluirá el proceso. Si las medidas superan los valores máximos pasará a la siguiente actividad.
  6. Warning task for doctor: se crea una tarea manual para informar al médico asignado al paciente que este puede estar sufriendo una crisis.
  7. Warning task for patient: informamos al paciente con una nueva tarea manual que su médico ha sido informado de la situación.

Segunda lectura de presión arterial

A esta parte del flujo sólo se accederá cuando exista una tarea automática previamente creada y que no haya sido finalizada. 

  1. Check pressure: nuevamente validamos para el mensaje recibido si los valores de presión arterial superan o no el límite.
  2. Close normal task: si los niveles no superan los valores máximos cerraremos la tarea pendiente con el método CompleteTask proporcionado por la clase EnsLib.Workflow.TaskResponse que nuestra tarea instancia. El parámetro usado indicará la acción tomada, en este caso indicaremos que es una falsa alarma pasando el valor FalseAlarm, podríamos definir cualquier otro que deseemos.
  3. Close warning task: igual que en el caso anterior, con la diferencia de que en este caso la acción que le pasamos al motor de Workflow será Warning y que será el valor que la actividad "Check if warning" que hemos visto anteriormente comprobará.

Como veis en el siguiente diagrama (no es literal pero os podeis hacer una idea de como funcionará), nuestro flujo de tareas va a trabajar con 2 "hilos" o procesos:

El primer hilo/proceso se mantendrá abierto en caso de que sea necesario esperar a una segunda lectura y será el segundo hilo/proceso será el que provoque la reactivación del primer hilo abierto al recibir dicha segunda lectura, concluyendo así el flujo de tareas definido.

Conclusión

Como podéis ver la configuración de un flujo de tareas en un BPL es bastante sencillo, pudiendo simular tareas automáticas y manuales sin mucha complicación. En el próximo y último artículo veremos como pueden los usuarios interactuar con sus tareas desde una aplicación externa.

¡Gracias a todos por vuestra atención!

Discussion (0)1
Log in or sign up to continue
Announcement
· May 3, 2024

Concurso de Vector Search, GenAI y ML de InterSystems

¡Hola Comunidad!

¡Tenemos más noticias emocionantes! El nuevo concurso de programación en línea de InterSystems dedicado a la IA generativa, la búsqueda vectorial y el aprendizaje automático está activo. 

🏆 InterSystems Vector Search, GenAI and ML Contest 🏆

Duración: 22 de abril - 19 de mayo, 2024

Fondo de premios: $14,000


El tema:

Desarrolla cualquier solución utilizando InterSystems IRIS o InterSystems IRIS for Health o IRIS Cloud SQL que utilice IA generativa y/o aprendizaje automático.

Para hacerlo aún más interesante, ¡los autores de los proyectos más innovadores que aprovechen el poder de la búsqueda vectorial (Vector Search) serán invitados a la Global Summit 2024* (hasta 3 personas)!

* Los desarrolladores invitados recibirán una entrada gratuita a la Global Summit y una estancia gratuita en un hotel del 8 al 13 de junio de 2024.

Requisitos generales:

  1. La aplicación o biblioteca deben ser completamente funcional. No debe ser una importación o una interfaz directa para una biblioteca ya existente en otro lenguaje (excepto para C++, donde realmente se necesita mucho trabajo para crear una interfaz para IRIS). No debe ser un copia-pega de una aplicación o biblioteca existente.
  2. Aplicaciones aceptadas: aplicaciones nuevas para Open Exchange o ya existentes, pero con una mejora significativa. Nuestro equipo revisará todas las aplicaciones antes de aprobarlas para el concurso.
  3. La aplicación debe funcionar con IRIS Community Edition o IRIS for Health Community Edition. Ambas pueden descargarse como versiones host (Mac, Windows) desde el sitio de evaluación, o pueden utilizarse en forma de contenedores extraídos de InterSystems Container Registry o Community Containers: intersystemsdc/iris-community:latest o intersystemsdc/irishealth-community:latest.  
  4. La aplicación debe ser de código abierto y estar publicada en GitHub. 
  5. El archivo README de la aplicación debe estar en inglés, contener los pasos de instalación y el vídeo de demostración o una descripción del funcionamiento de la aplicación.
  6. Sólo se admiten 3 propuestas de un desarrollador.

NOTA. Nuestros expertos tendrán la última palabra sobre si la aplicación se aprueba o no para el concurso basándose en los criterios de complejidad y utilidad. Su decisión es inapelable.

 

Premios

1. Nominación de expertos: un jurado especialmente seleccionado determinará los ganadores:

🥇 1er lugar - $5,000 

🥈 2do lugar - $3,000 

🥉 3er lugar - $1,500

🏅 4to lugar - $750

🏅 5to lugar - $500

🌟 6-10to lugar - $100

2. Ganadores comunitarios: las candidaturas que reciban más votos en total:

🥇 1er lugar - $1,000 

🥈 2do lugar - $750 

🥉 3er lugar - $500

🏅 4to lugar - $300

🏅 5to lugar - $200

Si varios participantes obtienen la misma cantidad de votos, todos ellos se consideran ganadores, y el premio en metálico se reparte entre los ganadores. 

¿Quién puede participar?

Cualquier miembro de la comunidad de desarrolladores, excepto empleados de InterSystems (se permiten contratistas de ISC). ¡Crea una cuenta!

Los desarrolladores pueden trabajar en equipo para crear una aplicación colaborativa. Se permiten de 2 a 5 desarrolladores en un equipo.

No olvidéis destacar a los miembros de vuestro equipo en el README de vuestra aplicación - Perfiles de usuario de la Comunidad de Desarrolladores.

Fechas límite importantes:

🛠 Fase de desarrollo y registro de la aplicación:

  • 22 de abril, 2024 (00:00 EST): Inicio concurso.
  • 12 de Mayo, 2024 (23:59 EST): Fecha límite de presentación.

 Período de votación:

  • 13 de mayo, 2024 (00:00 EST): Inicio de la votación.
  • 19 de mayo, 2024 (23:59 EST): Final de la votación.

Nota: Los desarrolladores pueden mejorar sus aplicaciones durante todo el periodo de inscripción y votación.

    Recursos útiles:

    ✓ Documentación:

    ✓ Ejemplos de aplicaciones y bibliotecas:

    ✓ Cursos online:

    ✓ Vídeos:

    ✓ Para iniciados con IRIS:

    ✓ Para iniciados con ObjectScript Package Manager (IPM):

    ✓ Cómo presentar tu aplicación al concurso:

    ¿Necesitas ayuda?

    Únete al canal del concurso en el servidor de Discord de InterSystems o habla con nosotros en el comentario de este post. 

    Estamos esperando TU proyecto: ¡participa en nuestro maratón de codificación para ganar! 


    Al participar en este concurso, aceptas las condiciones del concurso aquí expuestas. Por favor, léelas atentamente antes de continuar

    Discussion (0)1
    Log in or sign up to continue
    Announcement
    · May 3, 2024

    Ya está aquí el resumen del mes de abril, 2024

    ¿No habéis podido entrar en la Comunidad todo lo que os gustaría? ¡No os preocupéis! Os traemos un resumen de todo lo que hemos publicado en el mes. Seguid leyendo y no os lo perdáis ⬇️⬇️
    Estadísticas generales
    ✓ publicaciones nuevas:
     10 artículos
     10 anuncios
     2 nuevas preguntas
    Top 10 Publicaciones más vistas
    Introducción a Kubernetes
    Por Luis Angel Pérez Ramos
    Top 5 Autores más populares
    Todos los artículos
    #InterSystems IRIS
    QuinielaML - Predicciones de la 49ª jornada de la Quiniela
    Por Luis Angel Pérez Ramos
    Conectar Microsoft Excel a InterSystems IRIS mediante ODBC (Windows)
    Por Alberto Fuentes
    QuinielaML - Predicciones de la 51ª jornada de la Quiniela
    Por Luis Angel Pérez Ramos
    QuinielaML - Predicciones de la 53ª jornada de la Quiniela
    Por Luis Angel Pérez Ramos
    Cómo instalar soluciones ObjectScript sin código fuente o en modo de despliegue mediante el gestor de paquetes IPM
    Por Alberto Fuentes
    QuinielaML - Predicciones de la 54ª jornada de la Quiniela
    Por Luis Angel Pérez Ramos
    Comprobación de Versión en objetos. "ERROR:5800"
    Por Ricardo Paiva
    Rastreos de OpenTelemetry implementados por Servicios Web SOAP en IRIS
    Por Jose-Tomas Salvador
    Flujos de tareas con InterSystems IRIS Workflow Engine - Introducción
    Por Luis Angel Pérez Ramos
     
    #Otro
    Introducción a Kubernetes
    Por Luis Angel Pérez Ramos
     
    Todos los anuncios
    #InterSystems IRIS
     
    #Comunidad de Desarrolladores Oficial
     
    #Otro
     
    #InterSystems Official
     
    #HealthShare
     
    #Global Masters
     
    Todas las preguntas
    abril, 2024Month at a GlanceInterSystems Developer Community
    Discussion (0)1
    Log in or sign up to continue
    Announcement
    · May 3, 2024

    [Vidéo] Présentation des services cloud d'InterSystems

    Salut la Communauté!

    Profitez de regarder la nouvelle vidéo sur la chaîne Youtube d'InterSystems France

    📺 Présentation des services cloud d'InterSystems

    Découvrez comment les services cloud d'InterSystems fournissent des solutions ciblées et sans barrières à un large éventail de problèmes. Découvrez comment vous pouvez simplifier votre infrastructure, accélérer le développement d'applications et réduire les frais généraux liés aux opérations et à la maintenance quotidiennes à l'aide de ces services.

    Cette vidéo est doublée grâce à Bard, l'intelligence artificielle de Google. 

    N'oubliez pas à partager vos réflexions et impressions dans des commentaires après avoir regardé cette vidéo !

    Discussion (0)1
    Log in or sign up to continue