scieee AI-readable full text Open interactive document viewer

Social Resilience Platform (SRP) diseño de un sistema de toma de decisiones

Gómez Benegas, Francisco Manuel

Abstract

Resilience se asocia a la contignencia necesaria para resolver las catàstrofes generades por agentes naturales. El proyecto nace de la idea de generar un módulo de Resilience para ser incluído en una Plataforma Inteligente que provee Servicios a la ciudadanía de una ciudad. Cuando sucede un desastre natural se debe iniciar un dispósitivo de medios que lleve al control y la sanación de los resultados catastróficos provocados. El módulo Resilience pretende poner a disposicion de los Expertos en la materia motores inteligentes para monitoritzar las acciones necesarias para cada evento y abrir la posibilidad a la ciutadania a poder col·laborar e incluso poder hacer seguimiento de estos eventos a través de la información compartida para que pueda estar enterado en tiempo real de los que està ocurriendo en cada momento.

Full text

i PROJECTE FI DE CARRERA TÍTOL: S ocial Resilience Platform (SRP) Diseño de un sistema de toma de decisiones AUTOR: FRANCISCO MANUEL GOMEZ BENEGAS TITULACIÓ: INGENIERIA TÈCNICA D’INFORMÀTICA DE GESTIÓ DIRECTOR: SERGI SANCHEZ DEPARTAMENT: 701 – ARQUITECTURA DE COMPUTADORS DATA: 15/Juliol/2014 ii TÍTOL: Social Resilience Platform (SRM) Diseño de un sistema de toma de decisiones COGNOMS: GOMEZ BENEGAS NOM: FCO MANUEL TITULACIÓ: INGENIERIA TÈCNICA D’INFORMÀTICA DE GESTIÓ ESPECIALITAT: INFORMATICA PLA: VELL DIRECTOR: SERGI SANCHEZ DEPARTAMENT: 701 – ARQUITECTURA DE COMPUTADORS QUALIFICACIÓ DEL PFC TRIBUNAL PRESIDENT SECRETARI VOCAL DATA DE LECTURA: iii Aquest Projecte té en compte aspectes mediambientals: Sí PROJECTE FI DE CARRERA RESUM (màxim 50 línies) Resilience se asocia a la contignencia necesaria para resolver las catàstrofes generades por agentes naturales. El proyecto nace de la idea de generar un módulo de Resilience para ser incluído en una Plataforma Inteligente que provee Servicios a la ciudadanía de una ciudad. Cuando sucede un desastre natural se debe iniciar un dispósitivo de medios que lleve al control y la sanación de los resultados catastróficos provocados. El módulo Resilience pretende poner a disposicion de los Expertos en la materia motores inteligentes para monitoritzar las acciones necesarias para cada evento y abrir la posibilidad a la ciutadania a poder col·laborar e incluso poder hacer seguimiento de estos eventos a través de la información compartida para que pueda estar enterado en tiempo real de los que està ocurriendo en cada momento. Paraules clau (màxim 10): Resilience Eventos Plataforma Global Trazabilidad Algoritmos Inteligentes Plataforma Ciudadana Ayuda Ciudadana iv PROYECTO FIN DE CARRERA MODULO RESILIENCE (PLATAFORMA INTELIGENTE PARA UNA CIUDAD) MEMORIA DEL PROYECTO v T TA AB BL LA A D DE E C CO ON NT TE EN NI ID DO O TRIBUNAL ................................................................................................................................................. II 1. INTRODUCCION ................................................................................................................................ 7 2. OBJETIVOS ......................................................................................................................................... 9 3. MAPA CONCEPTUAL DE LA MEMORIA ................................................................................... 10 4. ESTADO DEL ARTE ......................................................................................................................... 11 5. BLOQUES DEL MODULO .............................................................................................................. 12 5.1 TIPOS DE USUARIO .................................................................................................................. 12 5.2 SECCIONES ................................................................................................................................ 13 5.3 PANTALLA RESPONSABLE DEL EVENTO............................................................................ 16 5.4 PANTALLA AYUDA CIUDADANA .......................................................................................... 18 6. ACCIONES DEL MODULO ............................................................................................................. 19 6.1 USUARIO REGISTRADO – SERVICIO CIUDAD ..................................................................... 19 6.2 USUARIO NO REGISTRADO – COLABORACION CIUDADANA......................................... 19 6.3 USUARIO REGISTRADO – RESPONSABLE DEL EVENTO .................................................. 19 6.4 EVENTOS .................................................................................................................................... 20 6.5 EJEMPLO DE APLICACIÓN DEL MÓDULO ........................................................................... 20 7. HERRAMIENTAS USADAS ............................................................................................................ 24 8. FORMATO DE LA BASE DE DATOS ............................................................................................ 25 8.1 EXPLICACION DE LA ESTRUCTURA DE BASE DE DATOS ................................................ 25 8.1.1 CONCEPTO ASOCIADO A CADA TABLA .......................................................................... 25 9. ALGORITMO BÚSQUEDA NECESIDAD INICIAL DE BASE ................................................... 35 9.1 INTRODUCCION ........................................................................................................................ 35 9.2 ENTIDADES RELACIONADAS ................................................................................................ 35 9.3 PSEUDOCÓDIGO ....................................................................................................................... 36 10. ALGORITMO CUBRIR NECESIDAD........................................................................................ 38 10.1 INTRODUCCION ........................................................................................................................ 38 10.2 ENTIDADES RELACIONADAS ................................................................................................ 38 10.3 PSEUDOCÓDIGO ....................................................................................................................... 39 11. ALGORITMO VERIFICAR NECESIDADES CUBIERTAS .................................................... 41 11.1 INTRODUCCION ........................................................................................................................ 41 11.1.1 PREMISA 1 ........................................................................................................................... 41 11.1.2 PREMISA 2 ........................................................................................................................... 41 11.1.3 PREMISA 3 ........................................................................................................................... 41 11.2 ENTIDADES RELACIONADAS ................................................................................................ 41 11.3 PSEUDOCÓDIGO ....................................................................................................................... 42 12. ESTUDIO SOCIO-ECONOMICO ............................................................................................... 43 12.1 ESTUDIO SOCIOLÓGICO .................................................................................................................. 43 12.2 ESTUDIO ECONÓMICO .................................................................................................................... 43 vi 13. CONCLUSIONES .......................................................................................................................... 44 14. FUTURAS MEJORAS ................................................................................................................... 46 14.1 APLICACIÓN EN CODIGO NATIVO DE TABLETS/SMARTPHONES ................................. 46 14.2 BASE DE DATOS DE ARCHIVO (ARCHIVE DATABASE) .................................................... 46 14.3 AUTOMATIZACION DEL MÉTODO DE CREACION DE EVENTOS .................................... 46 14.4 DIRIGIR INFO ADHOC A EVENTOS ........................................................................................ 46 14.5 CIRCUITO INTERNO DE MENSAJERIA Y/O CHAT. ............................................................. 47 14.6 INTEGRACION CON GOOGLE MAPS ..................................................................................... 47 14.7 INTERRELACION DE DATOS / INDICADORES ..................................................................... 47 14.8 VARIOS RESPONSABLES PARA EL MISMO EVENTO ......................................................... 46 15. APENDICES ................................................................................................................................... 48 15.1 MANUAL DE USUARIO ............................................................................................................ 48 15.1.1 PARTES DE LA PANTALLA ................................................................................................ 48 15.1.2 MENU PRINCIPAL .............................................................................................................. 49 15.1.3 TRABAJO DENTRO DE UN EVENTO ................................................................................ 50 15.1.4 GESTIÓN DE CATEGORIAS ............................................................................................... 56 15.2 ESPECIFICACION FUNCIONAL............................................................................................... 58 15.2.1 LA BASE DE DATOS ........................................................................................................... 58 15.2.2 MENU PRINCIPAL .............................................................................................................. 59 15.2.3 ESTRUCTURA DEL EVENTO ............................................................................................. 60 15.2.4 CANTIDADES ...................................................................................................................... 60 15.2.5 LA PANTALLA Y LA ASOCIACION CON LAS ACCIONES ................................................ 62 15.2.6 GLOSARIO DE ACCIONES ................................................................................................. 64 15.3 SCRIPTS CREACION BASE DE DATOS ................................................................................ 128 15.3.1 TABLA ADHOC INFO ....................................................................................................... 128 15.3.2 TABLA CATEGORY ........................................................................................................... 128 15.3.3 TABLA CATEGORY_EQUIVALENCE ............................................................................... 128 15.3.4 TABLA EVENT ................................................................................................................... 129 15.3.5 TABLA EVENT_CATEGORY_EQUIVALENCE ................................................................. 129 15.3.6 TABLA EVENT_DECISION_LOG ..................................................................................... 130 15.3.7 TABLA EVENT_RESOUCE ................................................................................................ 130 15.3.8 TABLA EVENT_STAGE ..................................................................................................... 130 15.3.9 TABLA EVENT_STAGE_DECISION_LOG ....................................................................... 131 15.3.10 TABLA EVENT_STAGE_NEED ..................................................................................... 131 15.3.11 TABLA EVENT_STAGE_NEED_RESOURCE ............................................................... 131 15.3.12 TABLA EVENT_STAGE_OPERATION .......................................................................... 132 15.3.13 TABLA SERVICE ............................................................................................................ 132 PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 7 of 133 1. INTRODUCCION El proyecto se engloba dentro del marco de una Plataforma Global enfocada a ofrecer servicios a los ciudadanos. La plataforma pretende brindar oportunidades a los ciudadanos a través de módulos que permita poner a disposición los servicios de la ciudad, así como ayudar a través de decisiones inteligentes a hacer uso de estos servicios y facilitarle la toma de decisiones ya sea a través de sugerencias o a través de la información que el usuario va proporcionando a su perfil de usuario e incluso a través de las decisiones tomadas en el pasado y la evaluación que haga de estas experiencias. Dentro de esta Plataforma Global se incluye el módulo Resilience al cual se enfoca este proyecto de fin de carrera. Primero vamos a introducir el concepto al cual aplica este proyecto y a continuación situar la primera perspectiva en base a la cual se pretende encarar el proyecto en la fase inicial. La madurez de la idea inicial se desarrolla en los siguientes apartados hasta llegar a las conclusiones tomadas una vez el proyecto se ha desarrollado y se tiene una mayor perspectiva sobre lo que parte como idea inicial hasta que se consolida como una idea madura y llevada a cabo. El término Resilience puede ser traducido con varios nombres en castellano. La aserción más correcta en términos tecnológicos es “poder de recuperación” o contingencia. Si bien el ser humano aún no ha encontrado mecanismos como para evitar fenómenos naturales, por ende los desastres, a través de programas de Resilience se pretende definir planes de contingencia que puedan moderar los efectos negativos resultado de un desastre natural. El creciente número de desastres naturales, sobretodo el creciente nivel de impacto que estos desastres están generando y haciendo una asociación a factores como son el Cambio Climático, está generando una mayor conciencia social y gubernamental en términos de Resilience. Unidos los factores anteriormente descritos a la cotidianidad que está tomando cada vez de forma más creciente el uso de tecnología en tiempo real por cualquier persona del mundo a través de teléfonos inteligentes, tabletas y promovido por la irrupción de aplicaciones nombradas ‘Social Media’, la convicción de que el propio ciudadano puede ser un factor importante a la hora de colaborar, ya sea a través de proveer información o aportar ayuda humanitaria, las plataformas Resilience basan su objetivo en proveer todo tipo de información que permita tomar decisiones que puedan resolver un desastre acaecido. Quizás el mayor valedor del término Resilience pueda ser el Presidente de los Estados Unidos, Barack Obama que incluyó el término Resilience dentro de los puntos en los que trabajaría para asegurar el bienestar del pueblo unido a otros puntos relacionados con el terrorismo, la seguridad policial o el control de migraciones. Varios conceptos se están relacionando de forma creciente con este concepto. El ejemplo más importante es el considerar la conciencia emergente en cuanto a Resilience a través de generar lo que se denomina “ciudades inteligentes” buscando la sostenibilidad y la estructuración que colabore ya no sólo a proveer servicios al ciudadano sino también localizados de tal forma que puedan ser más eficientes en caso de producirse alguna catástrofe natural. Otro término acuñado por la tecnología es el de Resilient que está vinculado a los sistemas de contingencia, es decir, buscar lugares donde se puedan construir edificios tecnológicos para ubicar sistemas espejo o backups de un sistema que pueda estar sujeto a catástrofes naturales que conllevarían la destrucción masiva de la información corporativa. Siendo un concepto emergente y que ha sido enfocado de diferentes formas por los aplicativos que actualmente hay en el mercado para estos propósitos, a través de la desgracia que supone que ocurran desastres naturales el lado positivo nos lleva a que desastres como el ocurrido en Haití han sido monitorizados a través de aplicativos de este tipo lo cual es una buena noticia para que, si bien no podamos seguir evitándolos al menos si podamos minimizar el impacto de los desastres naturales a través de soluciones informáticas aplicadas a Resilience. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 8 of 133 Varias son las premisas que se comparten a modo de requisitos o sugerencias iniciales para que el módulo sea acorde a la petición llegada. En un primer momento y como factor importante es el hecho de que se pretende un módulo donde a parte del desarrollo de las actividades de profesionales o expertos en la materia, también debe tener una alta dosis de participación por parte de los ciudadanos, de esta forma se pretende que el módulo permita gestionar la información de tal forma que se pueda compartir información que se considera de carácter público a la vez que debe asegurar que cierta información que se considere de índole secreto o reservado no tiene que llegar a ojos del público común. Otro motivo por el cual se busca el acercamiento del módulo al público es el hecho de conseguir la ayuda ciudadana en cuanto a un aspecto o recurso importante a la hora de poder enfocar un evento o catástrofe acontecido, en la era del Social Media cada vez se considera más crucial el disponer de Ayuda Ciudadana siempre y cuando ésta se preste a la ayuda. Son un recurso valioso que está oculto y que, si son informados y la forma de poder ofrecerse es sencilla, es un recurso a tener en cuenta. Otro punto importante es la recopilación de los Servicios Permanentes de que disponen las entidades públicas y que estén a disposición de colaborar. Cuando se debe actuar es importante que se pueda saber con qué se puede contar y para tener una imagen lo más realista posible se requiere que la información no solo sea información sino que esté ordenada de una forma eficiente que permita ser leída por otras personas y no solo las que trabajan en estas areas. Estamos hablando de un trabajo a realizar por un grupo de diferentes personas con lo cual la información debe ir reglada de tal forma que se consiga hacer más eficiente el tiempo de todos y cada uno de los participantes. Una vez tenemos situados los dos motores que nos van a proporcionar recursos para ser usados en los eventos es cuestión de ir al grueso de lo que es el trabajo a realizar dentro del módulo. La figura o rol importante dentro del módulo es la del Responsable del Evento. El Responsable del Evento es la persona asignada para coordinar el evento acaecido. Nadie que no sea el Responsable asginado al Evento puede tomar acción alguna dentro de un Evento. A grosso modo podemos pensar en un evento como la entidad superior dentro del módulo que se asocia a un hecho acaecido en forma de catástrofe natural. Una vez ocurre una catástrofe deberemos crear un evento en el módulo para recopilar toda la información referente al plan de contingencia a aplicar para resolver la situación. El módulo contempla que un evento se resuelve a través de dos objetos principales, recursos y operativas. De un modo se debe asignar recursos a una determinada acción que a su vez requerirá de una operativa a ser seguida por el bien de resolver el evento. Esta lectura simplista resume la idea inicial de lo que se desea cubrir a través del módulo. Para poder llegar a resolver esta situación vamos a tener que contar con varios obstáculos o detalles que van a hacer que esta idea inicial no sea tan simplista como pueda parecer, todos los detalles están descritos dentro de esta memoria en los respectivos apartados. Otro aspecto importante del módulo es aportar motores de inteligencia que hagan más efectivo el esfuerzo y el tiempo del Responsable del Evento quien, a fin de cuentas, va a ser el gran usuario del módulo a la vez que, esperamos, el gran beneficiado de poder disponer de nuestro módulo de Resilience. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 9 of 133 2. OBJETIVOS Por un lado están los objetivos por los cuales se realiza este proyecto y por otro lado están los objetivos del propio proyecto. A nivel personal, los motivos por los cuales decido tomar este proyecto son varios. El más importante está relacionado con el reto que supone conocer un área nuevo y poco desarrollado a nivel de proyectos informáticos lo cual supone un reto en cuanto a adquirir nuevos conocimientos que permitan fomentar el análisis y desarrollo de una primera fase de un proyecto que se considera interesante y con muchas oportunidades para su desarrollo a través de futuras mejoras. Realizar un proyecto donde se comienza con referencias funcionales pero sin referencias técnicas sobre cómo debe ser desarrollada la idea a nivel de arquitectura y teniendo en cuenta los limitantes de tiempo a los que está sujeto un proyecto de este tipo lo hacen también ser pensado como un reto. Otra de las máximas que es un objetivo, marcado así desde el inicio, es la idea de realizar la base de un módulo ampliable en fases futuras, lo cual supone un reto pues la arquitectura en la cual se base el proyecto debe ser lo suficientemente flexible como para que futuras ampliaciones no supongan un gran impacto sobre el paradigma inicial. Los objetivos del módulo pasan por realizar una arquitectura soportable por aplicaciones para entorno Web e incluso aplicaciones nativas para tabletas o teléfonos inteligentes ya que uno de los objetivos máximos es ofrecer la posibilidad a los ciudadanos de poder ver eventos gestionados a través del módulo e incluso hacerles partícipes a través de la colaboración o ayuda ciudadana. Otro objetivo es que el módulo pueda tomar información al respecto de los servicios que tiene disponibles la ciudad para ser usados de una u otra forma en los eventos para llegar a completarlos de forma satisfactoria. Si bien el gran usuario del módulo será el Responsable asignado a cada evento, se marcan como objetivos iniciales el proveer de motores inteligentes que le permitan cubrir las necesidades del evento, así como el proveer un nivel de confianza basado en eventos históricos para que sus decisiones estén encaradas a conseguir el éxito de cada evento. PARTES DEL MODULO El módulo está dividido de tal forma que haya un área donde se puedan dar de alta los recursos de que se disponen para poder ser usados en los eventos. Debe haber un lugar para poder dar de alta datos maestros que se requieran para el manejo del módulo, datos como pueden ser categorías, usuarios etc ... La parte más importante del módulo es la dedicada a la gestión de los propios eventos. Es el gran objetivo del módulo con lo cual la mayoría de herramientas, objetos y la gestión de ellos va a ser enfocado a esta área. Si bien debe haber un área para la gestión de eventos que están ocurriendo, finalmente se pretende que haya una parte que permita la revisión de eventos históricos que, a su vez, permita revisar todo lo referente a decisiones tomadas en el pasado e incluso la posibilidad de poder recopilar decisiones que puedan ser aportadas para ayudar a resolver de forma sistemática y exitosa futuros eventos semejantes. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 16 of 133 5.3 PANTALLA RESPONSABLE DEL EVENTO Vamos a explicar el diseño o prototipo en el que se enfoca esta primera versión del módulo Resilience en cuanto a la pantalla que debería tener a su disposición el Responsable del Evento para realizar sus tareas de gestión. BLOQUE AZUL EVENTOS ASIGNADOS A MI: Permite al Responsable de Eventos ver todos los eventos que tiene asignados en este momento. BLOQUE VERDE BUSCAR INFO ADHOC PARA AÑADIR AL EVENTO: Permite al Responsable buscar recursos para añadir al evento de entre la añadida por la ayuda ciudadana. BUSCAR INFO SERVICIOS PARA AÑADIR AL EVENTO: Permite al Responsable buscar recursos para añadir al evento de entre los servicios oficiales. EQUIVALENCIA CATEGORIAS: Permite crear categorías, equivalencia de categorías y añadirlas al evento. CONSULTAR EVENTOS HISTORICOS: Permite al Responsable consultar eventos ocurridos en el pasado. BLOQUE MARRON PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 17 of 133 VERIFICAR TODAS LAS NECESIDADES CUBIERTAS: Permite al Responsable ejecutar el algoritmo que le colabore a todas las necesidades y/o operaciones del evento que no fueron cubiertas. BLOQUE NARANJA. EVENTO INFO GENERAL EVENTO: Permite al Responsable añadir información general del evento (Fecha de Inicio, Fecha de Fin, Descripción del evento etc …) RECURSOS DEL EVENTO: Permite al Responsable consultar la info adoc y servicios que asignó al evento previamente. CATEGORÍAS EQUIVALENTES DE MI EVENTO: Permite consultar las equivalencias de categorías que el responsable de evento asignó al evento en curso. REGISTRO DECISION EVENTO: Permite al Responsable la gestión de las decisiones de evento, registrar nuevas decisiones así como consultar las anteriormente entradas. BLOQUE NARANJA. ETAPAS DE EVENTO OPERACIONES: Permite al Responsable la gestión de las operaciones. Registrar operaciones, darlas por completadas y la consulta de todas las operaciones que se asignaron a una etapa. REGISTRO DECISION: Permite al Responsable la gestión de las decisiones de etapa, registrar nuevas decisiones así como consultar las anteriormente entradas. NECESIDADES: : Permite al Responsable la gestión de las necesidades. Registrar necesidades, darlas por completadas y la consulta de todas las necesidades que se asignaron a un evento. RECURSOS: Permite al Responsable la gestión de los recursos para cubrir la necesidad marcada para una etapa de evento. Asociar recursos del evento para la etapa y la consulta de todos los recursos que se asignaron a una etapa AYUDA A CUBRIR NECESIDADES: Permite al Responsable ejecutar el algoritmo que le colabore a buscar recursos del evento que estén activos para poder cubrir las necesidades que aun no estén cubiertas. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 18 of 133 5.4 PANTALLA AYUDA CIUDADANA A continuación vamos a presentar la idea de pantalla que debería presentarse al ciudadana para ofrecerse como Ayuda Ciudadana para colaborar. La estrategia está basada en intentar captar la máxima información posible sin que para ello el ciudadano tenga que dedicar mucho tiempo, de ser así puede ser contraproducente y puede resultar en que prefiera desisitir de la idea de colaborar. El usuario que quiera colaborar tendrá un formulario que pretende contener pocos campos para que el proceso sea ligero para el ciudadano pero que aporte la máxima información posible. EVENTO: Se trata de una lista desplegable que contiene los eventos activos + una opción llamada “DESCONOCIDO” por si el ciudadano no puede encontrar el evento al cual desea colaborar. CATEGORIA: Se trata de una lista desplegable con las diferentes categorías de que consta el sistema + una opción llamada “OTROS” por si el ciudadano no puede encontrar el evento al cual desea colaborar. INSERTAR INFORMACION: Es un botón que desplegará una pantalla que permita al ciudadano entrar toda la información que desee compartir, desde sus datos personales hasta información al respecto de la información que desee compartir con el nivel de detalle que desee. INSERTAR FOTO: Es un botón que debe permitir al ciudadano buscar foto(s) en su dispositivo que sea(n) la(s) que quiere compartir. PUBLICACION: Boton de selección, permitirá indicar al ciudadano si la información que quiere compartir puede tratarse como información Pública o Privada siendo Privada por defecto. COMPARTIR: Es un botón mediante el cual el ciudadano da por completa la información y es enviado al sistema. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 19 of 133 6. ACCIONES DEL MODULO Si bien en el apartado anterior se ilustró la parte de modelo de negocio al respecto de cómo debe llevarse a cabo el diseño del módulo es en este apartado donde vamos a ir más allá y vamos a entrar en el detalle de todas y cada una de las acciones que debe proveer el módulo a modo de herramientas o funcionalidades estableciendo los objetivos de cada una de las acciones. Las acciones del módulo vienen dadas en base a los perfiles de usuario. Además de definir acciones esta documentación va a definir los objetivos y responsabilidades esperadas para cada uno de los perfiles de usuario con el objetivo de asegurar la eficiencia del módulo 6.1 USUARIO REGISTRADO – SERVICIO CIUDAD OBJETIVO: • Proveer información de servicios que pueden colaborar o ser usados para un evento. • Deberá mantener actualizada la información (Ejemplo: El equipo de policías puede incrementar) • Cuanto más detallado mejor (Ejemplo: Indicar que un ambulatorio dispone de 2 médicos especialistas no es igual de eficiente que indicar que se trata de un traumatólogo y un neurólogo). • Su función en los eventos es estrictamente de aportar información, no toma decisiones. • Información base de que dispone el responsable de un evento para saber si los servicios a disposición de la ciudad son suficientes para subsanar el evento acaecido o si por el contrario deba pedir servicios extra a otros municipio, países o ayuda ciudadana • La información de servicios de la ciudad, debe ser mantenida actualizada y bien categorizada para que su uso sea lo más eficiente posible • Esta información deberá aportarla los usuarios registrados de la plataforma. 6.2 USUARIO NO REGISTRADO – COLABORACION CIUDADANA OBJETIVO: • Cualquier ciudadano podrá aportar la información que vea oportuno compartir. • La información puede ser anónima (¿Se puede ‘usar’ información sobre geo-localización sin la aceptación del interesado? ¿Es legal?) • Cada información Ad-hoc deberá ser asociada a un evento ( a ser confirmado/decidido con el tutor) • La información ad-hoc es añadida a un apartado de pre-información del evento • La información ad-hoc siempre será de tipo “público” (a ser confirmado con el tutor) 6.3 USUARIO REGISTRADO – RESPONSABLE DEL EVENTO OBJETIVO: • Es quien decide que la información, tanto de servicios permanentes como la ad-hoc, va a formar parte del evento. • Al comenzar un evento se encontrará un panel vacío que deberá rellenar a través de añadir servicios permanentes + confirmar que la información ad-hoc es útil para el evento (Evitar información masiva poco eficiente o duplicada o fuentes no confiables etc ..) • Deberá categorizar la información • Podrá Activar/desactivar información, sin con ello tener que ‘borrarla-tener que volverla añadir’ PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 20 of 133 • Podría generar varias vistas de la información (filtros) • Crear vistas ad-hoc (filtros pre-fijados) con la misma información visualizada de diferentes puntos de vista o enfoques • Dispondrá un panel de ‘Conclusiones’ que será resuelto a modo de ‘notas del responsable’. • Dispondrá de un panel de búsqueda de ‘eventos pasados’ para poder consultar qué información dispuso el evento y cuáles fueron las actuaciones realizadas para subsanarlo 6.4 EVENTOS OBJETIVO: • Público Vs Privado: Sólo para evitar que los usuarios puedan disponer de información privada como puede ser el teléfono de contacto de un doctor de un servicio permanente de la ciudad o datos sobre el jefe de la Policía Municipal etc … • El responsable dará de alta las necesidades del evento. • El responsable confirmará qué info Ad-hoc quiere añadir al evento pudiéndose de esta forma descartar la no relevante o la repetida (varios ciudadanos pueden colaborar con información respecto al mismo hecho y la duplicidad se considere reiteración) • El responsable confirmará qué servicios permanentes considera relevantes para el evento en curso • El responsable podrá añadir el registro de conclusiones tomadas para el evento en curso o a nivel más particular para las etapas del evento, se guardará traza respecto al momento en el cual las decisiones fueron tomadas, de esta forma se podrá mantener una trazabilidad de cuales fueron los pasos o decisiones realizadas para el evento en orden cronológico, información que será un aporte valioso tanto a la hora de extraer conclusiones como a la hora de poder llevar a cabo un evento similar consultando el histórico de eventos. • El módulo pondrá a disposición del responsable del evento varios algoritmos con el objetivo de agilizar la construcción o de la toma de decisiones que aseguren que las necesidades son cubiertas: o Algoritmo Búsqueda Necesidad Inicial de Base: Permitirá añadir una estructura inicial a una etapa de nueva creación compuesta por las necesidades y las operativas a través del uso de la información histórica. o Algoritmo Cubrir Necesidades: Sugerirá cómo cubrir con los recursos existentes todas las necesidades dadas de alta y que no se consideren cubiertas. o Algoritmo Verificación Necesidades Cubiertas: Complementario al algoritmo anterior va a permitir al responsable verificar que no quedó ninguna necesidad u operativa sin ser cubierta. • Añadir Categorías Equivalentes al evento. Esta acción se considera vital para que Algoritmo Cubrir Necesidades pueda realizar un mayor apoyo al responsable del evento en este menester. 6.5 EJEMPLO DE APLICACIÓN DEL MÓDULO 1. Registrar los usuarios. De alguna forma al menos se deberá definir que usuarios de la Plataforma Global podrán ser “Responsables de Evento” 2. Servicios. Los servicios son información que se considera dato maestro. La importancia de tenerla bien categorizada y actualizada en cuanto al mantenimiento. Los servicios se pueden “activar/desactivar” en función de las eventualidades y se podrán marcar como “obsoletos” una vez se considere que este servicio ya no existe y no volverá a existir, el módulo no deberá permitir borrar servicios que hayan sido usados en algún evento para evitar la pérdida de la trazabilidad, es por esto que existe la posibilidad de marcar como obsoleto. Como los servicios, al ser añadidos a una etapa de evento, se clonan en el evento el hecho de que la información sufra cambios considerables con respecto a los datos anteriores no deberá influir a la trazabilidad de la información. Por ejemplo, si en 2010 se tenía 1 ambulatorio y en 2015 se disponía de 2 ambulatorios, el hecho de clonar la información permitirá saber que en el periodo comprendido entre 2010 y 2015 las decisiones se tomaron en función de disponer sólo 1 ambulatorio. 3. Información Ad-hoc. La colaboración ciudadana estará siempre disponible, lo que no puede asegurarse es la calidad de la información que nos proporcione que puede ser incompleta o poco confiable. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 21 of 133 Sin duda esta información seguramente será la que precipite a la creación de eventos o al menos se presagia que sea uno de los motores activos que permitan la detección de nuevos eventos. 4. Categorías. El módulo debería incorporar dos vías para crear categorías, ya sean a través de entrar en la lista de categorías directamente o cuando se estén dando de alta Servicios o se asignen Servicios/Información Ad-hoc a una etapa del evento. El concepto del módulo pasa por hacer ágil y amigable la ardua tarea del responsable del evento con lo cual debe intentar “no marerarlo” en tareas que puedan impactar negativamente en su motivación. 5. Categorías Equivalentes. Siguiendo la filosofía anteriormente descrita el módulo deberá incorporar la posibilidad de añadir información en este diccionario en varias áreas de trabajo del módulo. 6. Creación del evento. Comienza la acción, se ha detectado un evento y se debe comenzar a aplicar el módulo para gestionar el evento ocurrido. 7. Creando la primera etapa. Todo evento se compone de al menos una etapa. El módulo incorpora un algoritmo para hacer más ágil esta tarea. A parte del beneficio en cuanto a la agilidad, el otro beneficio de usar este algoritmo se basa en el grado de probabilidad de éxito que nos va a proporcionar el asignar unas necesidades y operativa que ya se usó con éxito en un evento histórico o al menos nos va a permitir tener datos de referencia que nos va a permitir ganar en confianza en que la decisión puede entrar dentro de los parámetros que puedan dar una alta probabilidad de éxito ya que hay que tener en cuenta que por muy parecidos que puedan parecer dos eventos siempre hay factores externos que son dinámicos y que pueden hacer imposible que la misma solución pueda aplicarse dos veces con el mismo resultado de éxito. Ejemplos: • Geográficos. No es lo mismo apagar un fuego de dimensiones parecidas en una zona fría (Noruega) que en una zona caliente (Marruecos) • Servicios. En la misma ciudad ocurre en el mismo edificio el mismo evento dos veces pero los servicios disponibles para afrontar el evento en ambos casos no son los mismos. • Operativas. Las personas que forman parte de los servicios de dos países diferentes pueden tener cualificaciones distintas aún y siendo considerados de la misma categoría. 8. Modelando la etapa a nuestra realidad. Tanto si creamos la etapa sin usar el algoritmo como si decidimos usarlo, es momento de modificar las necesidades y operativas que vamos a requerir para poder comenzar a afrontar esta primera etapa. 9. Nuestro evento requiere de varias acciones. Ya sea porque debamos preparar varios operativos en paralelo que no están relacionados entre sí y por ello no queremos mezclarlos o porque tenemos claro que para resolver el evento vamos a tener que dividirlo por fases ya sea porque los recursos pueden llegar escalonados o porque nos sea más sencillo gestionar el evento como un conjunto de decisiones aisladas que nos deben proporcionar una solución conjunta. El objetivo de este punto es añadir tantas etapas como veamos oportuno que vamos a necesitar y como haremos a futuro una vez vayamos madurando las soluciones para resolver el evento. Seguramente a la vez que realizamos este despliegue será buena idea registrar todas estas decisiones en el registro de decisiones a nivel de evento para poder incluso usarlo a modo de notas que a futuro nos provea de información y así evitar el olvido en esta vorágine de tener que estar al pendiente de tanta información y personas sobre todo en eventos de gran escala. 10. Vamos a ver de qué recursos dispongo. Es momento de comenzar a cubrir las necesidades de cada etapa del evento, para ello voy a tener que revisar qué recursos me proporciona el diccionario de Servicios y también toda la información que me ha proporcionado el conjunto civil. La ciudadanía puede proveerme de recursos y también de “sólo” información. La información se añadirá como recurso de igual forma. Voy a asignar al evento toda la información que vea importante. 11. Voy a distribuir los recursos en las necesidades. Una vez ya tengo la primera aproximación de los recursos que creo oportuno que me van a ayudar en mi evento es momento de ‘usarlos’ para ir cubriendo mis necesidades. Seguramente a la vez que voy realizando esta acción voy a ir añadiendo decisiones o notas en el registro de decisiones de cada una de las etapas. 12. Voy a hacer que el módulo me ayude en la asignación de recursos a mis etapas de evento. En estos momentos me va a poder ayudar pero solo con las relaciones necesidad-recurso del tipo directo pues no he añadido categorías equivalentes a mi evento. De igual manera seguro que la tarea que realicé en el punto 10 de forma manual me la va a permitir realizar de una forma más ágil el algoritmo. Lo ejecutamos y efectivamente vi que me había dejado recursos sin asignar de los que disponía. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 22 of 133 13. Voy a ver si ya he cubierto las necesidades. Aún no trabajé con las operativas de las etapas con lo cual es evidente que el Algoritmo de Verificación de Necesidades Cubiertas me va a marcar que todas las operativas están pendientes de ser cubiertas, además me ha dado la lista de necesidades que o bien no tienen recursos asignados o los recursos asignados son insuficientes, comienza el juego. 14. Categorías equivalentes. Vamos a ver qué categorías equivalentes puedo incorporar a mi evento del diccionario existente o directamente voy a crear las que crea necesarias y que no existan en el diccionario, a futuro y a medida que vea que las equivalencias has dado un resultado exitoso procederé a añadirlas al diccionario. Por ahora solo añado categorías equivalentes para que el algoritmo pueda ayudarme en un rango mayor. 15. Algoritmo Cubrir Necesidades. Vamos a ver si la suerte me acompaña y ahora puedo cubrir las necesidades no cubiertas hasta la fecha, añadiendo categorías equivalentes estoy seguro que el avance será significativo en esta tarea compleja. 16. Comencemos a desplegar operativas. Las operativas solo requieren que se marquen como Cubiertas. Así el algoritmo las descartará por darlas por cubiertas. 17. Registro de Decisiones. Es momento de registrar más decisiones en cada etapa del evento para dejar latente la estrategia en la que he podido cubrir más necesidades, es decir, a través de añadir categorías equivalentes. 18. Voy a verificar que los recursos que estoy usando están disponibles. La información de contacto de los Servicios Permanentes no está guardada dentro del evento pero como el módulo me han dicho que guarda trazabilidad entre el recurso del evento y el servicio que lo proporciona pues tengo un botón que me da la información de contacto de cada servicio. Voy a llamar o enviar correos para que me confirmen que la base de datos está actualizada. 19. Comienza la acción. Vamos a tener que comenzar a desplegar la(s) primera(s) etapas para ir resolviendo el evento. Del nivel de éxito e incluso del porcentaje de resolución del evento voy a tener que afinar las etapas que tenía preestablecidas o, directamente, crear de nuevas. 20. Etapa Completada. He completado una de mis etapas u operaciones. Al final no fue necesario el uso de las necesidades que me sugirió el evento histórico que tomé por referencia. De esta forma, en mi caso específico, fui igual de eficiente con menos recursos, no quiere decir que la próxima vez usando los mismos recursos que yo se pueda resolver, lo que sí es posible es que el evento que tomé como referencia tenía un margen más amplio de necesitar menos recursos o almenos en mi caso específico. A la vez que modifico la información de mi etapa para que queden los recursos que realmente utilicé voy a registrar más conclusiones tanto de evento como en esta etapa para explicar los motivos por los cuales en mi caso he podido ser más eficiente que en la etapa tomada por referencia. Como me han dicho que el simple hecho de haber tomada esta etapa como referencia ya hace que el módulo tenga la trazabilidad con respecto a esta etapa, en cualquier momento tanto yo como cualquier persona que habrá mi evento a modo de lectura podrá tener una comparativa entre la etapa referencia y la etapa de mi evento. Voy a marcar como completada esta etapa para que los algoritmos inteligentes del módulo ya no la tengan en cuenta a la hora de sus ayudas y comprobaciones. 21. Evolución del evento. Las tareas anteriormente descritas se vuelven a aplicar repetidamente para seguir con el control del evento. 22. Conclusiones sobre la plataforma. He necesitado un tiempo para familiarizarme con el módulo pero una vez ya me he sentido cómodo puedo extraer varias conclusiones: a. Yo tomo las decisiones. El módulo me ha facilitado la forma de poder ir modelando mi evento pero al final soy yo, como experto, el que toma las decisiones definitivas. Alguien podría pensar que sería mejor que el módulo tomara decisiones de forma automática pero yo creo que hay factores externos que hace que aún y que el mismo evento se produzca dos veces en condiciones similares siempre están sujetos a situaciones propias que los hacen aproximados pero no idénticos. b. Probabilidad de éxito. El hecho de estar relacionado con el histórico me permite tener unas referencias tanto de los casos con éxito como de casos negativos lo cual es una referencia interesante a la hora de aportarme un nivel de seguridad a la hora de tener una referencia en cuanto a la probabilidad de éxito. c. Mis cálculos propios. La flexibilidad de que pueda crear tantas categorías, que pueda adaptar la categoría de los recursos dentro de mi evento sin tener que por ello modificar el servicio/adhoc original me permite una personalización propia de los datos sin desvirtuar la información inicial. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 23 of 133 d. Flexibilidad en el planteamiento. El hecho de que pueda crear tantas etapas como desee sin que haya un procedimiento estricto que marque cómo deben aplicarse las etapas me aporta un amplio abanico de posibilidades o escenarios donde aplicar el módulo de formas dispares. e. Histórico. El hecho de poder ver eventos históricos, de poder tomar etapas de referencia para crear mis etapas, poder ver el diario de registro de decisiones tanto de eventos como de etapas de evento me permite no solo ver la información sino también poder hacerme una idea de cuál fue la operativa aplicada por el responsable del evento, evidentemente, si el responsable ha llevado un registro de decisiones de forma eficiente y pensando en colaborar a la comunidad de la que formo parte. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 24 of 133 7. HERRAMIENTAS USADAS Una parte importante a la hora de realizar el módulo es la decisión al respecto de la tecnología con la que va a ser desarrollado. En este sentido, además, hay que tener en cuenta que se trata de un módulo que debe formar parte de una Plataforma Global con lo cual se debe buscar un consenso para asegurar la compatibilidad entre las partes. La suerte es que actualmente la Plataforma Global no existe pero sí el proyectista que la va a realizar con lo cual se ha podido llegar a un consenso donde el módulo Resilience también ha sido partícipe en la elección de las herramientas y no tener que usar unas herramientas por imposición de La Plataforma. Finalmente estas son las herramientas que han sido elegidas y a continuación se explica en detalle los motivos que han promovido tales decisiones y las alternativas barajadas. • Tecnología de Base de Datos: MySql. • Lenguaje de programación del Front-End: PHP, CSS, HTML. • Lenguaje de programación para lógica compleja: JavaScript. El motivo principal que ha derivado a usar estas herramientas ha sido el consenso al cual se ha llegado a la hora de definir unas herramientas viables para todas las partes de la Plataforma de Ciudad Inteligente que englobará, entre otros módulos, el módulo Resilience objeto de este Proyecto de Fin de Carrera. MySql Los candidatos para la base de datos fueron: Oracle/SQL*SERVER/MySql. Partiendo de que las tres soluciones podrían ser igual de válidas para la solución inicial de todas las partes de la plataforma, el argumento diferencial que decantó la decisión a favor de MySql fue el hecho de que MySql es un gestor de bases de datos considerado “Open Source”, es decir, su licenciamiento de uso es gratuito. DRUPAL (PHP/CSS/HTML) Un requisito importante a la hora de buscar un lenguaje de programación para realizar el diseño o Front-End de La Plataforma se focaliza en buscar una solución Web que pueda ser compatible con tabletas y teléfonos inteligentes, ya sea mediante uso del navegador o incluso realizando una versión de La Plataforma o algún módulo a través de aplicaciones nativas ya sea en IOS o Android. Los candidatos fueron ASP y PHP, en ambos casos el formato es HTML y el uso de CSS es igual de compatible. El hecho de que es reconocido PHP como el lenguaje ideal para trabajar con MySql fue el motivo de peso que decantó la balanza a favor de PHP. Para conseguir una plataforma con aspecto profesional y basado en dar un mismo formato tanto a la plataforma como a los diferentes módulos se contempla la posibilidad de usar una plataforma de generación de contenidos Web y basado en la experiencia de algunos de los proyectistas se decide el uso de Drupal como solución a ser usada. JavaScript El hecho de haber seleccionado PHP en el apartado anterior desencadenó la selección de JavaScript como lenguaje de programación para la lógica compleja ya que PHP es JavaScript. La alternativa a JavaScript era VBScript si se hubiera seleccionado ASP como el lenguaje de programación para el diseño del Front-End. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 25 of 133 8. FORMATO DE LA BASE DE DATOS Una parte importante a nivel arquitectónico la forma la base de datos y el modo en que la información va a ser estructurada en ésta. Dos han sido las máximas para diseñar la base de datos, por un lado una nomenclatura que asegure claridad a la hora de asociar la información de una forma simple y por otro lado dejar abierta la posibilidad a un crecimiento a través de incorporar nuevas mejoras o herramientas a futuro en una base sólida y modulable. La Estructura de la base de datos se compone de las siguientes tablas: NOTA: La estructura de tablas y campos de la base de datos se ha definido en inglés a petición expresa del departamento que se ha dirigido el proyecto. 8.1 EXPLICACION DE LA ESTRUCTURA DE BASE DE DATOS A continuación vamos a explicar el objetivo de todas y cada una de las tablas que forman parte de la base de datos. Una vez explicado el objetivo de todas las tablas se va a compartir el diseño técnico que se ha realizado a todas y cada una de las tablas explicando el cometido de todos y cada uno de los campos que forman parte de las tablas. 8.1.1 CONCEPTO ASOCIADO A CADA TABLA SERVICE y ADHOC INFO son los recursos de que dispone el responsable del evento para cubrir las necesidades. Inicialmente esta información no pertenece al evento pero está disponible para ello, en cuanto el responsable considera que la información debe ser tomada en cuenta en una etapa del evento es cuando la información se añade de la forma EVENT STAGE NEED RESOURCE donde se seguirá teniendo la trazabilidad de a qué registro en SERVICE o AD-HOC INFO se referencia y una vez en EVENT STAGE NEED RESOUCE siempre se sabrá si un recurso es de tipo SERVICE o AD-HOC mediante la tipificación de la información. CATEGORY es el diccionario para categorizar los recursos y las necesidades PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 32 of 133 EQ_CAT_03 LIST Tercera unidad equivalente EQ_CAT_03_Q DATE DEFAULT = NOW Cantidad a usar de esta tercera categoría equivalente. EQ_CAT_03_UOM TEXT USER Unidad de Medida en que se expresa la cantidad de esta tercera categoría equivalente. ADDED_DATE DATE DEFAULT = NOW Fecha en que se añadio la equivalencia al evento. ADDED_BY TEXT USER Usuario que añadio la equivalencia al evento. MOD_DATE DATE DEFAULT = NOW Fecha de la última modificación de esta equivalencia dentro del evento. MOD_BY TEXT USER Usuario que realizó la última modificación de esta equivalencia dentro del evento. ID_EVENT INTEGER Evento al cual está asignada 8.1.1.9 EVENT STAGE TABLE USER SYSTEM DATATYP E DEFINITION EXPLANATION ID_EVENT INTEGER PRIMARY KEY Evento al cual se añade la etapa ID_EV_STAGE INTEGER PRIMARY KEY Identificador unívoco CREATED_DATE DATE DEFAULT = NOW Fecha de Creación de la Etapa CREATED_BY TEXT DEFAULT = USER Usuario que creó la Etapa. RELATED_STAGE INTEGER FOREIGN KEY Etapa que se tomó de referencia en la creación (0 si se creó sin usar referencia) INI_DATE DATE Fecha de Inicio END_DATE DATE Fecha de Fin DESCRIPTION TEXT Descripción breve de la Etapa COMPLETED BOOLEAN DEFAULT = FALSE Poder dar por cerradas etapas, sobretodo para que los algoritmos reduzcan el ámbito donde aplicar la lógica a solo Etapas en curso o no completadas. CONCLUSION TEXT Resumida la conclusión que da el responsable sobre esta Etapa una vez completada. SUCCESS BOOLEAN DEFAULT= FALSE Al final habrá que indicar si hubo éxito o fracaso en esta Etapa. 8.1.1.10 EVENT STAGE OPERATION TABLE USER SYSTEM DATATYP E DEFINITION EXPLANATION ID_EVENT INTEGER PRIMARY KEY Evento al cual se añade ID_EV_STAGE INTEGER PRIMARY KEY Etapa a la cual se añade ID_EV_ST_OPER INTEGER PRIMARY KEY Identificador unívoco CREATED_DATE DATE DEFAULT = NOW Fecha de Creación de la Etapa CREATED_BY TEXT DEFAULT = USER Usuario que creó la Etapa. DESCRIPTION TEXT Descripción breve de la Etapa COMPLETED BOOLEAN DEFAULT = FALSE Poder dar por cerradas operativas, sobretodo para que los algoritmos reduzcan el ámbito donde aplicar la lógica a solo necesidades/operativas en curso o no completadas. NOTE TEXT Observaciones que desee anotar el Responsable del Evento. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 33 of 133 8.1.1.11 EVENT STAGE NEED TABLE USER SYSTEM DATATYPE DEFINITION EXPLANATION ID_EVENT INTEGER PRIMARY KEY Evento al cual se añade ID_EV_STAGE INTEGER PRIMARY KEY Etapa a la cual se añade ID_EV_ST_NEED INTEGER PRIMARY KEY Identificador unívoco CREATED_DATE DATE DEFAULT = NOW Fecha de Creación de la Etapa CREATED_BY TEXT DEFAULT = USER Usuario que creó la Etapa. NEED_CATEGORY LIST Descripción breve de la Etapa NEED_Q REAL Cantidad de Necesidad Requerida NEED_UOM Unidad de Medida en que se expresa la Cantidad de Necesidad Requerida COMPLETED BOOLEAN DEFAULT = FALSE Poder dar por cerradas necesidades, sobre todo para que los algoritmos reduzcan el ámbito donde aplicar la lógica a solo necesidades/operativas en curso o no completadas. NOTE TEXT Observaciones que desee anotar el Responsable del Evento. 8.1.1.12 EVENT STAGE NEED RESOURCE TABLE USER SYSTEM DATATYPE DEFINITION EXPLANATION ID_EVENT INTEGER PRIMARY KEY Evento al cual se añade ID_EV_STAGE INTEGER PRIMARY KEY Etapa a la que se añade ID_EV_ST_NEED INTEGER PRIMARY KEY Necesidad a la que se añade ID_EV_ST_NEED_RES PRIMARY KEY Identificador unívoco ID_EV_RES INTEGER FOREIGN KEY Referencia al recurso de la tabla EVENT RESOURCE que se ha usado para esta necesidad. ID_EV_RES_OBJ_CLASS TEXT Para que dentro de esta pantalla el usuario pueda saber si importó un Servicio o una Info Ad-Hoc. Esta info se hereda de EVENT RESOURCE ID_EV_RES_CAT TEXT DEFAULT = EVENT RESOURCE.RES_CA T Categoría original del recurso referenciado CREATED_DATE DATE DEFAULT = NOW Fecha de Creación de la Etapa CREATED_BY TEXT DEFAULT = USER Usuario que creó la Etapa. RES_CATEGORY LIST DEFAULT = ID_EV_RES_CAT Categoría RES_Q REAL Cantidad de Necesidad Requerida RES_UOM Unidad de Medida en que se expresa la Cantidad de Necesidad Requerida NOTE TEXT Observaciones que desee anotar el Responsable del Evento. FUNGIBLE BOOLEAN Servicios Fungibles son aquellos que se gastan con su uso. No fungibles son los que pueden ser usados nuevamente tras su uso. CURRENT_QUANTITY INTEGER Cantidad disponible, es decir que no está siendo usada actualmente y puede ser usada para otra necesidad paralela. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 34 of 133 8.1.1.13 EVENT STAGE DECISION LOG TABLE USER SYSTEM DATATYPE DEFINITION EXPLANATION ID_EVENT INTEGER PRIMARY KEY Evento al que pertenece ID_EV_STAGE INTEGER PRIMARY KEY Etapa a la que pertenece ID_EV_ST_DECISION INTEGER PRIMARY_KEY Identificador Unívoco DECISION_TYPE LIST NOTA/DECISION/REACCION/CONSEJ O Tipo de Decision DECISION TEXT La decisión tomada. SUCCESS BOOLEAN DEFAULT= FALSE Al final habrá que indicar si hubo éxito o fracaso en este evento CREATED_DATE DATE DEFAULT = NOW Fecha de Creación del Evento CREATED_BY TEXT DEFAULT = USER Usuario que creó el Evento. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 35 of 133 9. ALGORITMO BÚSQUEDA NECESIDAD INICIAL DE BASE El módulo incluye una serie de algoritmos que provean de automatismos a la gestión de varias partes del evento donde se pueda extraer un rendimiento óptimo y mayor eficiencia al sistema. Uno de estos lugares es justamente el decidir cuál es la necesidad para mi evento. Es interesante poder ver en el histórico cómo se ha resuelto una problemática similar y evaluar las diferencias entre los casos de éxito y fracaso también me puede proporcionar una visión más realista sobre los detalles o las consecuencias de aplicarlo de una forma u otra. Es evidente que los eventos por muy parecidos que puedan parecer están sujetos a disparidad de variables que hace complejo el poder aplicar un mismo procedimiento en dos lugares distintos o ya sea porque están sujetos a condiciones que alteran la similitud. Sea como fuere disponer de una herramienta que permita buscar un punto inicial basado en las experiencias acaecidas puede ser útil para ponernos en situación y de esta forma buscar una probabilidad de éxito para nuestro caso. 9.1 INTRODUCCION El objetivo de este algoritmo es permitir al responsable del evento buscar una etapa que sea similar a la que necesita resolver consultando el histórico de eventos del sistema. El algoritmo mostrará un formulario para realizar la búsqueda de etapas al responsable y mostrará las que coincidan con su búsqued, Además la búsqueda mostrará el dato de si la etapa y el evento resultaron en éxito o fallo. El responsable del evento podrá ver el detalle de la información de la etapa y/o del evento para así poder decidir si la coincidencia es alta. El responsable seleccionará etapa(s) y confirmará que las quiere ‘clonar’ en su evento. El sistema tomará los datos de Evento Etapa Necesidad y Evento Etapa Operación y los añadirá al evento en curso, además los vinculará con su etapa de origen para que se tenga la trazabilidad de cuál fue la etapa que se tomó de referencia en el momento de la creación. Las etapas referencias no se verán alteradas como consecuencia de este algoritmo, es decir, serán de sólo lectura. Cabe mencionar que, aunque no sea el alcance de este algoritmo, una vez creadas las etapas y aunque sean creadas a través de una referencia, la información podrá ser modificada adaptándola a la necesidad del evento en curso. 9.2 ENTIDADES RELACIONADAS EVENT STAGE: La etapa que contiene necesidades y operaciones. EVENT STAGE NEED: Las necesidades de la etapa. EVENT STAGE OPERATION: Las operaciones de la etapa. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 36 of 133 9.3 PSEUDOCÓDIGO '******* Algoritmo Busqueda Necesidad de Base Preguntar al usuario “Crear Etapa vacía>” o “<Buscar Etapa Referencia” Si Selecciona “Crear Etapa Vacía” Crear Registro en <EVENT STAGE> vacío Fin Fin Si Ejecutar motor de búsqueda de <EVENT STAGE> coincidentes Si la búsqueda retorna cero coincidencias Mientras no retorne coincidencias Preguntar al usuario si cambiar búsqueda o cancelar el proceso de creación Si selecciona cancelar Fin Fin Si Si selecciona cambiar búsqueda Ejecutar motor de búsqueda de <EVENT STAGE> concidentes Si la búsqueda retorna <EVENT STAGE> concidentes Salir del Mientras Fin Si Fin Si Fin Mientras Fin Si Si la búsqueda retorna <EVENT STAGE> coicidentes Mientras el usuario no seleccione <EVENT STAGE> referencia y pulse el botón “Usar” Mostrar las <EVENT STAGE> coincidentes con el filtro al usuario Si el usuario selecciona almenos una <EVENT STAGE> y pulsa el botón “Usar” Para todas las <EVENT STAGE> seleccionadas Crear <EVENT STAGE> Nueva Asociada al <EVENT STAGE> actual Vincular a modo de referencia la nueva <EVENT STAGE> creada con la <EVENT STAGE> referencia. Leer tabla <EVENT STAGE NEED> de la <EVENT STAGE> referencia y clonar la información en la <EVENT STAGE> nueva en la tabla <EVENT STAGE NEED> Leer tabla <EVENT STAGE OPERATION> de la <EVENT STAGE> referencia y clonar la información en la <EVENT STAGE> nueva en la tabla <EVENT STAGE OPERATION> Mensaje informativo de que la <EVENT STAGE> ha sido usada como referencia y la creación fue exitosa Fin Fin Para Fin Si Si el usuario no selecciona una <EVENT STAGE> y pulsa el botón “Usar” PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 37 of 133 Notificar al usuario que debe seleccionar almenos una <EVENT STAGE> antes de pulsar el Botón “Usar” Fin Si Si el usuario pulsa el botón “Cancelar” Fin Fin Si Fin Mientras Fin Si Fin PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 38 of 133 10. ALGORITMO CUBRIR NECESIDAD Se trata del algoritmo más complejo y por ende el que más beneficio puede aportar al Responsable del Evento. El algoritmo va a verificar que toda la necesidad marcada está cubierta y de no ser así va a proponer recursos asignados al evento que pueden ser usados para cubrir esta necesidad hasta que, a través de asignar recursos, se cubran las necesidad y de esta forma se pueda dar por completada la actividad de cubrir la necesidad. 10.1 INTRODUCCION El Responsable del Evento ha tenido previamente que localizar y añadir al evento dos entidades: • EVENTO_NECESIDAD: Son las necesidades identificadas para este evento, es decir, el objetivo a cubrir para poder resolver el evento ocasionado. • EVENTO_INFO: Son los servicios tanto oficiales como sociales de los cuales se dispone para resolver el evento ocasionado. El primer objetivo del Algoritmo consiste en detectar que todas las NECESIDADES dispongan de al menos 1 INFO que esté vinculada a esta NECESIDAD, de no ser así se considera que la NECESIDAD no está cubierta con lo cual la resolución del evento queda en entredicho. El segundo punto objetivo del Algoritmo consistirá en detectar si hay suficientes INFO para cubrir las NECESIDADES. Ejemplo: Si tengo 1 camión de bomberos pero la necesidad está marcada en 4 el algoritmo deberá detectar que hay INFO insuficiente para esta NECESIDAD La tercera tarea del algoritmo consistirá en buscar recursos asignados al evento que puedan ser usados para cubrir las necesidades que se detecten como no cubiertas. Para realizar esta tarea el algoritmo se va a basar en la categorización tanto de las necesidades como de los recursos ya sea de forma directa (misma categoría) o de forma indirecta (a través de buscar equivalencias entre categorías). 10.2 ENTIDADES RELACIONADAS EVENT STAGE: La etapa que contiene necesidades y operaciones. EVENT STAGE NEED: Las necesidades de la etapa. EVENT STAGE NEED RESOURCE: Los recursos asociados a las necesidades para cubrirlas. EVENT STAGE OPERATION: Las operaciones de la etapa. EVENT RESOURCE: Son todos los recursos de que dispone el evento, se trata de servicios permanentes + ayuda ciudadana. EVENT CATEGORY EQUIVALENCE: Es la tabla de equivalencias entre necesidades (por categoría) y los recursos (por categorías) que sin ser directamente la misma necesidad pueden cubrir una necesidad a un nivel similar. EVENT STAGE NEED FOR COVERING: Es una tabla temporal que se genera en memoria para que el algoritmo recopile toda la información existente y pueda analizar si es suficiente para cubrir las necesidades de la etapa. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 39 of 133 10.3 PSEUDOCÓDIGO El Responsable de Evento selecciona una <EVENT STAGE> para ejecutar el proceso. Si la <EVENT STAGE> tiene el campo <EVENT STAGE.Completado> a Verdadero Mensaje a usuario avisando que la etapa que esta cubierta Fin Fin Si Leer de <EVENT STAGE NEED> todas las necesidades cuyo campo <EVENT STAGE NEED.Completado> tenga valor Falso Crear tabla_temporal <EVENT STAGE NEED FOR COVERING> Para cada <EVENT STAGE NEED> Si Registro en < EVENT STAGE NEED FOR COVERING > NO Existe Añadir < EVENT STAGE NEED > inicializado a Cero la < EVENT STAGE NEED .Q COVERED > y añadiendo las unidades de < EVENT STAGE NEED .Q NEED> Para todos los registros de < EVENT STAGE NEED RESOURCE> asociados a <EVENT STAGE NEED> Comparar Categoria de < EVENT STAGE NEED RESOURCE> con la de <EVENT STAGE NEED> Si < EVENT STAGE NEED RESOURCE> = <EVENT STAGE NEED> Sumar < EVENT STAGE NEED RESOURCE.Q> a la < EVENT STAGE NEED .Q COVERED> Else Buscar Equivalencia entre < EVENT STAGE NEED RESOURCE.CAT> y <EVENT STAGE NEED.CAT> en <EVENT CATEGORY EQUIVALENCE> Sumar < EVENT STAGE NEED RESOURCE.Q> a la < EVENT STAGE NEED .Q COVERED> segun la equivalencia entre categorías. Fin Si Fin Para Si Todos <EVENT STAGE NEED FOR COVERING.Q NEED> <= <EVENT STAGE NEED FOR COVERING.Q COVERED> Si Todos <EVENT STAGE OPERATION> están completados Mensaje “Todas las necesidades están cubiertas, ehhorabuena puede marcar como completada la etapa” Fin Else Mensaje “Todas las necesidades están cubiertas pero le quedan operaciones por completar. Fin Fin Si Fin Si Para todo registro en <EVENT STAGE NEED FOR COVERING> donde <EVENT STAGE NEED FOR COVERING.Q NEED> > <EVENT STAGE NEED FOR COVERING.Q COVERED> Buscar <EVENT STAGE NEED FOR COVERING.CATEGORY> Buscar todas las <EVENT STAGE CATEGORY EQUIVALENCE> para la categoría del registro actual Buscar todas las <EVENT RESOURCE> cuya <EVENT RESOURCE.CATEGORY> sea la categoría del registro actual o sus equivalencias. Mostrar al usuario todas las <EVENT RESOURCE> detectadas al usuario para que seleccione cuales añadir PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 40 of 133 Si usuario selecciona <EVENT RESOURCE> Para cada <EVENT RESOURCE> seleccionado por el usuario Añadir <EVENT RESOURCE> en <EVENT STAGE NEED RESOUCE> para la etapa Añadir la cantidad de recurso que cubre en <EVENT STAGE NEED FOR COVERING.Q COVERED> Fin Para Si donde <EVENT STAGE NEED FOR COVERING.Q NEED> <= <EVENT STAGE NEED FOR COVERING.Q COVERED> Marcar <EVENT STAGE NEED> a <EVENT STAGE NEED.Completado> a verdadero Fin Si Fin Si Fin Para Si existen registros en <EVENT STAGE NEED FOR COVERING> donde <EVENT STAGE NEED FOR COVERING.Q NEED> > <EVENT STAGE NEED FOR COVERING.Q COVERED> Mensaje “Han quedad o las siguientes necesidades pendientes de ser cubiertas” + Registros en <EVENT STAGE NEED FOR COVERING> sin cubrir su necesidad. Fin Else Si Todos <EVENT STAGE OPERATION> están completados Mensaje “Todas las necesidades están cubiertas, ehhorabuena puede marcar como completada la etapa” Fin Else Mensaje “Todas las necesidades están cubiertas pero le quedan operaciones por completer. Fin Fin Si Fin Si Fin PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 41 of 133 11. ALGORITMO VERIFICAR NECESIDADES CUBIERTAS Cuando estás trabajando en un evento a veces es necesario tener una forma rápida de poder saber cuáles son las actividades que están en curso y de esta forma focalizar los esfuerzos en ellas para así poder completar las actividades relativas a un evento. 11.1 INTRODUCCION ¿CÓMO ACTÚA EL ALGORITMO? 11.1.1 PREMISA 1 Las etapas que se han marcado por el Responsable de Evento como ya completadas se obvian y por tanto sus necesidades no se evalúan si están cubiertas pues se consideran completadas. 11.1.2 PREMISA 2 Detectar que todas las EVENT STAGE NEED dispongan de al menos 1 EVENT STAGE NEED RESOURCE que esté vinculada a esta EVENT STAGE NEED, de no ser así se considera que la EVENT STAGE NEED no está cubierta con lo cual la resolución del evento queda en entredicho. Ejemplo: Un EVENT STAGE NEED para el evento son 5 bomberos. A esta necesidad no se le ha asociado ningún EVENT STAGE NEED RESOURCE todavía. El resultado es evidente, la necesidad no ha sido cubierta. 11.1.3 PREMISA 3 Detectar que todas las EVENT STAGE NEED no solo dispongan de EVENT STAGE NEED RESOURCE asociados sino que la cantidad de EVENT STAGE NEED RESOURCE asociados cubran la necesidad marcada de no ser así se considera que EVENT STAGE NEED no está cubierto con lo cual la resolución del evento está en entredicho. Ejemplo: Un EVENT STAGE NEED para el evento son 5 bomberos. Si los EVENT STAGE NEED RESOURCE asociados a este EVENT STAGE NEED solo cubren entre 1 y 4 bomberos el resultado es evidente, la necesidad no ha sido cubierta en su totalidad. 11.2 ENTIDADES RELACIONADAS EVENT STAGE NEED: Necesidades a ser cubiertas para completar la etapa. EVENT STAGE OPERATION: Operaciones a ser completadas para completar la etapa. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 48 of 133 15. APENDICES 15.1 MANUAL DE USUARIO 15.1.1 PARTES DE LA PANTALLA La pantalla está vinculada, en especial, al manejo del rol de Responsable de Evento. La pantalla, con un evento abierto para su gestión, se muestra con el siguiente aspecto: PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 49 of 133 15.1.2 MENU PRINCIPAL Ayuda Ciudadana : Permite abrir los registros de Ayuda Ciudadana que actualmente tenemos en el sistema y que son candidatos para poder ser asignados a necesidades para, de esta ma nera, cubrirlas. Aunque la tarea del Responsable de Evento no es dar de alta Ayuda Ciudadana sino más bien la asignación de esta, se ha añadido un botón para dar de alta nuevos registros en Ayuda Ciudadana. A su vez, si un evento está abierto en pantalla y seleccionando registros de Ayuda Ciudadana, los recursos son asignados automáticamente al evento para así poder ser usados para cubrir las necesidades de sus etapas. Servicios de la Ciudad : Siguiendo la misma filosofía de Ayuda Ciudadanda esta opción permite abrir los registros de Servicios de la Ciudad que actualmente tenemos en el sistema y asignarlos automáticamente al evento seleccionado para así poder ser usados para cubrir las necesidades de sus etapas. Seleccionar Evento: Permite seleccionar un evento existente para abrirlo en pantalla. Además de poder crear eventos nuevos. Categorías: Permite mostrar el total de categorías que existen en el diccionario de categorías, así como añadir nuevas. Equivalencia Categorías: Permite mostrar el diccionario de categorías consideradas como equivalentes, así como el detalle en cuanto a las cantidades entre categorías para establecer el equivalente, las categorías seleccionadas serán enviadas al evento seleccionado para que así los algoritmos de lógica las teng an en cuenta a la hora tanto de evaluar qué recursos sugerir para cubrir necesidades como también para analizar si una necesidad ha sido cubierta en su totalidad. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 50 of 133 15.1.3 TRABAJO DENTRO DE UN EVENTO 15.1.3.1 CONCEPTOS BÁSICOS Una evento consta de etapa(s) y cada etapa, a su vez, consta de operativas y necesidades a cubrir. Un evento se considera completado sólo en el caso de que todas sus etapas están completadas. Para completar cada etapa, a su vez, todas las operativas y necesidades a cubrir debe estar completadas. Para completar una operativa no hay restricciones, pero si deben ser marcadas como completadas. El sistema espera que una necesidad esté cubierta al 100% para poder marcar como completada una necesidad. Debido a la diversidad de necesidades a cubrir, el sistema permitirá al responsable del evento marcar como completada una necesidad cuyos recursos asignados para cubrirla no permitan al sistema dictaminar que la necesidad está cubierta, pero es obligatorio que usando ambos caminos la necesidad debe ser marcada como completada. Sabemos que un objeto está completado o no completado en función del valor que tiene la columna Hecho en cada una de las partes donde esta columna está incluida. Sólo los recursos, ya sean de Ayuda Ciudadana o Servicios de la Ciudad, y las categorías equivalentes asociadas a un evento son tenidas en cuenta a la hora del análisis lógico y la ayuda lógica que el módulo provee al Responsable del Evento para el análisis respecto a cubrir necesidades. Es importante asignar recursos y categorías equivalentes al evento. 15.1.3.2 LA FUNCIONALIDAD 15.1.3.2.1 ABRIR UN EVENTO Abrimos un evento pulsando la opción de menú del menú principal “Seleccionar Evento” Si ya tenemos abierto en pantalla un evento, a modo de seguridad, el sistema nos informará a modo de confirmación de si queremos proceder con la acción de abrir un nuevo evento en pantalla reemplazando de este modo el evento que está actualmente abierto en pantalla. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 51 of 133 Una vez seleccionado un evento podremos ver el área de acción con respecto al evento en la parte superior de la pantalla. 15.1.3.2.2 EL OBJETO EVENTO 15.1.3.2.2.1 INFORMACION DE EVENTO • La tabla muestra la información del evento (Descripción, Responsable Asignado, Fechas de Inicio y Fin, Fecha y Persona que lo creó, Éxito, Público) • El icono asociado a Éxito es pulsable. Si pulsamos revertimos la decisión entre Éxito/Fracaso con respecto al valor actual. Por defecto el valor es Fracaso. • Los dos iconos representados por un calendario nos permiten definir las Fechas de Inicio (el primero) y la de Fin (el segundo). 15.1.3.2.2.2 CATEGORÍAS EQUIVALENTES ASOCIADAS A UN EVENTO Existe un diccionario de Categorías Equivalentes. Para que el sistema contemple una Categoría Equivalente para un evento se deberá asignar al evento en cuestión. Se pueden visualizar las Categorías Equivalentes asociadas a un evento. • Asignando Categorías Equivalentes a un Evento: Deberemos tener un evento abierto en pantalla, pulsamos la opción de menú del menú principal llamada Categoría Equivalente y nos aparecerá el diccionario de Categorías Equivalentes, seleccionamos las que queremos añadir al evento y pulsando el botón Ok el sistema nos pedirá confirmar que queremos añadirlas al evento. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 52 of 133 • Pulsando el botón Categorías Equivalentes podremos ver las Categorías Equivalentes asociadas al evento . 15.1.3.2.2.3 RECURSOS DEL EVENTO • Para añadir recursos a un evento, siguiendo la filosofía descrita en Categorías Equivalentes, pulsaremos los botones Ayuda Ciudadana y Servicios de la Ciudad para añadir recursos al evento. • Pulsando el botón Recursos del Evento podremos ver los recursos asociados al evento . La columna Object Class nos permitirá saber si se trata de un recurso de tipo Ayuda Ciudadana (AdHoc) o Servicio de la Ciudad (Service). 15.1.3.2.2.4 DECISIONES DEL EVENTO • Para añadir nuevas notas al evento pulsaremos el botón Nueva Decisión de Evento. El sistema abrirá una pantalla para que podamos entrar la nota, pulsando el botón Ok la nota será añadida al evento. • Pulsando el botón Decisiones Registradas podremos ver todas las notas asociadas a modo de Decisiones al evento. 15.1.3.2.2.5 AÑADIR ETAPA • Pulsamos el botón Añadir Etapa para añadir etapas a un evento . El sistema mostrará la lista de Etapas existentes en otros eventos para seleccionar una etapa como base. Seleccionamos la etapa y automáticamente es añadida al evento. NOTA: Las etapas se pueden modificar para adaptarlas a la necesidad concreta del evento que estamos realizando, es decir, podemos manipular las operativas y necesidades necesarias para nuestro evento. Los recursos asignados a las necesidades de la etapa usada como punto de inicio no son pasadas a nuestra etapa, de esta forma deberemos cubrir las necesidades desde el inicio de las diferentes formas que se describirán a continuación. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 53 of 133 • Las etapas asignadas a un evento son listadas en la segunda tabla de la pantalla cuyo título es Tabla de Etapas del Evento. 15.1.3.2.2.6 VERIFICAR SI TODAS LAS NECESIDADES FUERON CUBIERTAS • El sistema permite saber si todas las etapas fueron marcadas como cubietas pulsando el botón . • Si todas las etapas estuvieran completadas mostrará un mensaje de enhorabuena, de no ser así mostrará la lista de etapas que aún están en curso. 15.1.3.2.3 EL OBJETO ETAPA El sistema permite asociar varias etapas a un mismo evento. El objetivo de esta funcionalidad es añadir un nivel más que permita realizar operativas en paralelo e incluso operativas cronológicamente seriadas pero donde se pueda tener en cuenta las limitaciones temporales que pueden condicionar al uso de servicios o ayuda ciudadana que solo puede estar disponible eventualmente. Las etapas están formadas por la información propia de la etapa, así como 2 estructuras hijas en paralelo que corresponden a las operativas y las necesidades de la etapa. 15.1.3.2.3.1 INFORMACION DE ETAPA • La conforman la descripción de la Etapa, las Fechas de Inicio y Fin, así como la fecha y la persona que la creó, si está completada o en curso y si fue un éxito. • Un evento puede tener varias etapas. Para trabajar con una etapa a nivel de operativas y necesidades deberemos seleccionarla pulsando el icono que precede a cada registro en la tabla. Sabremos visualmente cual es la etapa que tenemos seleccionada a través del icono que le precede . • Pulsamos el botón de la columna Hecho para pasar una etapa de En Curso (OFF) a Completada (ON) o viceversa. Cuando pulsamos el botón para pasar una etapa a Completada el sistema verificará si efectivamente se puede realizar esta acción. La verificación consiste en verificar que tanto las operativas como las necesidades asignadas a esta etapa están completadas, de ser así la marcará como completada y si quedara algún pendiente mostrará un mensaje al Responsable del Evento dejando constancia de cuales son las operativas y/o necesidades que no le permiten dar por completada esta etapa. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 54 of 133 • El icono asociado a Éxito es pulsable. Si pulsamos revertimos la decisión entre Éxito/Fracaso con respecto al valor actual. Por defecto el valor es Fracaso. • Los calendarios nos dan la posibilidad de cambiar la fecha de inicio o la fecha de fin de la etapa . • Podemos borrar una etapa pulsando el último icono de la tabla . 15.1.3.2.3.2 DECISIONES DE LA ETAPA • Las etapas pueden tener notas a modo de decisiones asociadas. Estas notas son a nivel de etapa, el mecanismo es similar al usado para el registro de decisiones del evento. La diferencia entre ambos objetos es que se consideran las notas o decisiones al nivel del evento como globales del evento y las que se añaden a nivel de etapa como específicas para la etapa en cuestión. • Para añadir nuevas notas a la etapa pulsaremos el botón Nueva Decisión de Etapa. El sistema abrirá una pantalla para que podamos entrar la nota, pulsando el botón Ok la nota será añadida a la etapa. • Pulsando el botón Decisiones Registradas podremos ver todas las notas asociadas a modo de Decisiones al evento. 15.1.3.2.4 EL OBJETO OPERATIVA Las operativas permiten gestionar los protocolos de actuación que deben ser ejecutados para asegurar que la etapa se puede completar de forma satisfactoria. Cada etapa va a tener asociadas sus propias operativas. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 55 of 133 15.1.3.2.4.1 INFORMACION OPERATIVA • La conforman la descripción de la Operativa, la Fecha de Creación, así como la persona que la creó, si está completada o en curso y la nota con el procedimiento a realizar. • Pulsamos el botón de la columna Hecho para pasar una etapa de En Curso (OFF) a Completada (ON) o viceversa. • Pulsamos el icono de la columna Nota para añadir o editar el procedimiento asignado a la operativa • Podemos borrar una operativa pulsando el último icono de la tabla . 15.1.3.2.4.2 AÑADIR OPERATIVAS Pulsamos el icono que acompaña al título de la tabla para añadir operativas . 15.1.3.2.5 EL OBJETO NECESIDAD Las necesidades permiten gestionar los recursos que deben ser usados para asegurar que la etapa se puede completar de forma satisfactoria. Cada etapa va a tener asociadas sus propias necesidades y cada necesidad va a tener asociada, a su vez, los recursos asignadas para cubrirla y por ende que se pueda dar por completada. 15.1.3.2.5.1 INFORMACION NECESIDAD • La conforman la Fecha de Creación, así como la persona que la creó, la categoría-cantidad-unidad de medida que describen de qué se trata y la columna de Estado. • Podemos borrar una operativa pulsando el penúltimo icono de la tabla . • Podemos modificar la información de Categoría-Cantidad-Unidad de Medida de una necesidad pulsando el último icono de la tabla . Al pulsarlo abrirá una pantalla para realizar este cometido. 15.1.3.2.5.2 COMPLETAR NECESIDAD • Si una necesidad está en Curso y decidimos pasarla a Completado , el sistema automáticamente va a evaluar si los recursos asignados a esta necesidad cubren la necesidad indicada. De esta forma varias situaciones se pueden dar: PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 56 of 133 o Los recursos asignados cubren la necesidad estipulada: En este caso el sistema pasará la necesidad a Completado. o Los recursos asignados no cubren la necesidad estipulada: En este caso el sistema mostrará un mensaje alertando de la situación al Responsable del Evento y dará diferentes alternativas para afrontar la situación:  Ayúdame a cubrirla: Si decidimos tomar este camino el sistema nos mostrará los recursos de que dispone el evento que sean directamente asociados para cubrir esta necesidad, es decir, recursos cuya categoría coincida con la categoría asociada a la necesidad o categorías equivalentes en función a la tabla de equivalencias que se han asociado al evento previamente. Una vez seleccionado un recurso el sistema volverá a calcular si con el recurso añadido ya se cubre la necesidad y en tal caso indicará que la necesidad se puede dar por completada, acción que realizará el sistema de manera automática. Si el recurso asignado aún no llega a cubrir la necesidad el mensaje volverá a mostrarse para que decidamos si queremos realizar la acción recursivamente hasta cubrirla u optar por otro de los caminos.  Confirma aún y sin cubrir la necesidad: El sistema está creado para apoyar en la medida de lo posible y en base a la información, a veces la información puede ser tan compleja que solo se pueda realizar completar una necesidad en base a la experiencia del Responsable del Evento y no basado en la información asociada al evento, en estos casos complejos el sistema debe permitir dar por completada una necesidad aún y teniendo en cuenta que la información no acorde para poder interpretarlo como tal, en estos casos se completa la necesidad en base al juicio del Responsable del Evento.  Abortar: Permite abortar la acción y decidir más adelante qué hacer para poder marcar como completada la necesidad. 15.1.3.2.5.3 AÑADIR NECESIDADES • Pulsamos el icono que acompaña al título de la tabla para añadir más necesidades . 15.1.3.2.5.4 CUBRIR LA NECESIDAD MANUALMENTE • Pulsamos el botón Asignar Recurso a la Necesidad . El sistema nos va a mostrar la lista de recursos asignados al evento y que están disponibles, independientemente de la categoría de los recursos y nos va a permitir asignar cualquier recurso a la necesidad seleccionada. 15.1.4 GESTIÓN DE CATEGORIAS El sistema tiene dos algoritmos lógicos que calculan por un lado si la necesidad está cubierta y por otro lado ayudar a cubrir la necesidad en base a los recursos asociados al evento. Para poder aplicar esta lógica la información está categorizada y es en base a la categoría de cada recurso y de cada necesidad que los algoritmos pueden ofrecernos esta ergonomía. La relación Necesidad-Recurso se puede realizar de dos modos: PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 57 of 133 • Modo simple: Es una relación directa, es decir, necesito POLICIAS y tengo como recursos POLICIAS. • Modo complejo: ES una relación indirecta, en este caso debemos asociar una categoría como equivalente para otro categoría e incluso la cantidad de una categoría que se requiere para cubrir la cantidad de la otra categoría. Para establecer estas relaciones el sistema nos ofrece el concepto de Categoría Equivalente. Vamos a explicar a través de un ejemplo cómo aplica las equivalencias: o Tenemos una necesidad de 2 BOMBEROS (Personas) o Disponemos de: 1 BOMBERO (Personas) y 5 POLICIAS (Personas). o Asignamos el bombero a la necesidad y de esta forma estamos pendientes de 1 Bombero para poder cubrir la necesidad. o Debemos buscar en el diccionario de equivalencias alguna equivalencia donde intervengan Bomberos como categoría origen. Encontramos una equivalencia que indica que 1 BOMBERO (Personas) tiene como equivalencia 3 POLICIAS (Personas). o Asignamos esta equivalencia al evento. o Acto seguido podemos asignar 3 POLICIAS (Personas) a nuestra necesidad y el sistema automáticamente entenderá que 1 BOMBERO (Personas) + 3 POLICIAS (Personas) es equivalente a 2 BOMBEROS (Personas). PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 64 of 133 15.2.5.1.4 NEW_SERVICE 15.2.5.1.5 PFC_CAT 15.2.6 GLOSARIO DE ACCIONES Separados por grupos de acción a continuación se listan las acciones con el código sugerido que incluye comentarios que describen el objetivo de todas las partes del código. 15.2.6.1 CATEGORIA 15.2.6.1.1 AÑADIR CATEGORIA NOMBRE: PFC_CATEGORY_NEW ' New Category is the from displayed to be filled by the user, internally each field is called matching the ‘ CATEGORY table fields name. status = UserDialog("NEW_CATEGORY", "valuesArray", , , "F", "T") If ( not(status) ) Then RETURN ENDIF ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 65 of 133 Endif ' Set createdBy to the current user connected to the system. createdBy = USER ' Set CreatedDate to the current datetime createdDate = OdbcDateTimeStamp(DateTime()) ' As userDialog instruction returns the fields and values in two array objects, the fields array is converted to one string where the fields are concatenated between "," as expected in the Insert SQL Statement fieldNamesStr = ArrayToCSVString(fieldNames, ",") valuesArrayStr = "" ' Count fields in the form and apply any transformation when required by any field. contFieldsInt = UBound(valuesArray, 1) For icontFieldsInt = 1 To contFieldsInt ' If value is true then it has to be replaced by T (the equivalent string for boolean True value) If ( valuesArray[icontFieldsInt] = true ) Then valuesArray[icontFieldsInt] = "T" ENDIF ' If value is false then it has to be replaced by F (the equivalent string for boolean False value) If ( valuesArray[icontFieldsInt] = false ) Then valuesArray[icontFieldsInt] = "F" ENDIF ' Ass all fields in the form are texts then put the value between single quote chars. valuesArrayStr = valuesArrayStr + "'" + valuesArray[icontFieldsInt], "' " ' If field is not the last one then put a comma char when adding to the values String that will be used for the Insert SQL Statement. If ( icontFieldsInt < contFieldsInt ) Then valuesArrayStr = valuesArrayStr + " , " Endif Next ' Build the Insert SQL Statement using the Fields and Values Strings created lines above and run the statement. qryStr = "Insert Into city_platform.category (" + fieldNamesStr + ") VALUES " qryStr = qryStr + " (" + valuesArrayStr + " )" status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' If the Insert Statement returns error then displays the error message and the query to review the syntaxis. If ( not(status) ) Then msgboxHTML(lastError + "<br><br>" + qryStr) status = ODBCclose(linkName) Return Endif ' Commit the changes qryStr = "COMMIT" status = ODBCquery(linkName,qryStr, "newEventResourceArray") status = ODBCclose(linkName) 'End PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 66 of 133 Return 15.2.6.1.2 MOSTRAR CATEGORIAS EXISTENTES NOMBRE: PFC_CATEGORY ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Run the query to return all existing categories qryStr = "Select * from city_platform.Category " status = ODBCquery(linkName,qryStr, "adhocInfoArray") status = ODBCcolumns(linkName, "headerArray") 'End status = ODBCclose(linkName) RETURN 15.2.6.2 CATEGORIA EQUIVALENTE 15.2.6.2.1 AÑADIR CATEGORÍA EQUIVALENTE NOMBRE: PFC_CATEGORY_EQUIVALENCE_NEW ' NEW_CAT_EQUIV is the form displayed to be filled by the user, internally each field is called matching ‘ the CATEGORY_EQUIVALENCE table fields name. status = UserDialog("NEW_CAT_EQUIV", "valuesArray", , , "F", "T") If ( not(status) ) Then RETURN ENDIF ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Get the current max ID_CAT_EQUIV to apply the next value to this new record qryStr = "Select MAX(ID_CAT_EQUIV) from city_platform.category_equivalence " status = ODBCquery(linkName,qryStr, "currentCatEquivArray") status = ODBCcolumns(linkName, "headerArray") newServiceIdInt = currentCatEquivArray[1, 1] ' If the table is empty then set ID_CAT_EQUIV to zero If ( isEmpty(newServiceIdInt) ) Then PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 67 of 133 newServiceIdInt = 0 Endif ' Initialize CreatedBy with the current user connected to the system createdBy = USER ' Initialize CreatedDate with the current datetime createdDate = OdbcDateTimeStamp(DateTime()) ' Assign a new id for the record to be created newServiceIdInt = newServiceIdInt + 1 'fieldsArray and valuesArray are the arrays where fields and values are stored ' Convert fields Array to String using comma as separator between field names ' as expected by the Insert SQL Statement fieldNamesStr = ArrayToCSVString(fieldNames, ",") ' Creates the string for the values contained in the values Array valuesArrayStr = "" ' Count positions in the values array to adapt values to the SQL Statement. contFieldsInt = UBound(valuesArray, 1) For icontFieldsInt = 1 To contFieldsInt ' If value is true then it has to be replaced by T (the equivalent string for boolean True value) If ( valuesArray[icontFieldsInt] = true ) Then valuesArray[icontFieldsInt] = "T" ENDIF ' If value is false then it has to be replaced by F (the equivalent string for boolean False value) If ( valuesArray[icontFieldsInt] = false ) Then valuesArray[icontFieldsInt] = "F" ENDIF ' Put value between single quotes for the text fields. If ( (icontFieldsInt <> 2) And (icontFieldsInt <> 5) And (icontFieldsInt <> 8) And (icontFieldsInt <> 11)) Then valuesArrayStr = valuesArrayStr + "'" + valuesArray[icontFieldsInt], "' " Else valuesArrayStr = valuesArrayStr + "" + valuesArray[icontFieldsInt], " " ENDIF ' If field is not the last one then put a comma char when adding to the values String that will be used for the Insert SQL Statement. If ( icontFieldsInt < contFieldsInt ) Then valuesArrayStr = valuesArrayStr + " , " Endif Next ' Build the Insert SQL Statement using the Fields and Values Strings created lines above and run the statement. qryStr = "Insert Into city_platform.category_equivalence (ID_CAT_EQUIV, " + fieldNamesStr + ") VALUES " qryStr = qryStr + " (" + newServiceIdInt + ", " + valuesArrayStr + " )" status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' Trap the error and display it with the query in case of any error running the SQL statement If ( not(status) ) Then PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 68 of 133 msgboxHTML(lastError + "<br><br>" + qryStr) Return Endif ' Commit the changes qryStr = "COMMIT" status = ODBCquery(linkName,qryStr, "newEventResourceArray") status = ODBCclose(linkName) ' End Return 15.2.6.2.2 VER LISTA DE CATEGORIAS EQUIVALENTES Y ASIGNARLAS A EVENTO NOMBRE: PFC_CATEGORY_EQUIVALENCE ' Get Event currently opened on screen to assign the records currentEventStr = GetGlobalVariable(globalCurrentEventStr) ' Open the database connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Get the Category Equivalence from the database by running a db query qryStr = "Select * from city_platform.Category_Equivalence " status = ODBCquery(linkName,qryStr, "adhocInfoArray") status = ODBCcolumns(linkName, "headerArray") ' Get the counter contRecordInt = UBound(adhocInfoArray, 1) ' If counter is set to zero then display a message because no category equivalence are found by now and abort this process If ( contRecordInt = 0 ) Then msgbox("No hay registros en Equivalencia de Categorías") status = ODBCclose(linkName) Return Endif ' Display the category equivalence and let the user select the ones to be added to the current event numSelecti ons = MultiColumnSelectFromArray(adhocInfoArray, "Seleccione Equivalencia de Categoría para añadir a su evento", "selectionArray", headerArray) If ( numSelections = 0 ) Then status = ODBCclose(linkName) Return Endif ' Ask the user to confirm the process about insert the selected category equivalences to the current event answer = PromptForYesNo("¿Está seguro de añadir los " + str(numSelections) + " datos seleccionados al evento " + "?") PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 69 of 133 ' If no event currently opened on the screen display a message because the records can not be added to any event and abort this process If ( isEmpty(currentEventStr) ) Then msgbox("Debe seleccionar un evento para poder asignarle Equivalencia de Categoría") status = ODBCclose(linkName) Return Endif ' If no event currently opened on the screen display a message because the records can not be added to any event and abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento para poder asignarle Equivalencia de Categoría") status = ODBCclose(linkName) Return Endif ' Get the max ID_EV_EQUIV for the Event Category Equivalence table to add the new ones consecutively. qryStr = "Select MAX(ID_EV_EQUIV) from city_platform.event_category_equivalence " status = ODBCquery(linkName,qryStr, "eventResourceArray") eventResourceRecordInt = eventResourceArray[1, 1] ' In case no category equivalences were added to any event previously then initialized the counter to zero If ( isEmpty(eventResourceRecordInt) ) Then eventResourceRecordInt = 0 ENDIF For inumSelections = 1 To numSelections ' Get values from the selection array to build the Insert SQL Statement per each selected record. idCatEquivInt = selectionArray[inumSelections, 1] primaryCatStr = selectionArray[inumSelections, 2] primaryQInt = selectionArray[inumSelections, 3] primaryUOMStr = selectionArray[inumSelections, 4] eqCatStr = selectionArray[inumSelections, 5] eqQInt = selectionArray[inumSelections, 6] eqUOMStr = selectionArray[inumSelections, 7] ' Initialize addedByStr with the current user connected to the system addedByStr = USER ' Initialize addedDate with the current datetime addedDate = OdbcDateTimeStamp(DateTime()) ' Increase the ID per each record to be added eventResourceRecordInt = eventResourceRecordInt + 1 'Build the Insert SQL Statement to add the category equivalence to the Event qryStr = "Insert Into city_platform.event_category_equivalence (ID_EV_EQUIV, ID_EVENT, ID_CAT_EQUIV, PRIMARY_CAT, PRIMARY_CAT_Q, PRMARY_CAT_UOM, EQ_CAT_01, EQ_CAT_01_Q, EQ_CAT_01_UOM, ADDED_DATE, ADDED_BY) VALUES " qryStr = qryStr + " (" + eventResourceRecordInt + ", " + currentEventStr + ", " + idCatEquivInt + ", '" + primaryCatStr + "', " + primaryQInt + ", '" + primaryUOMStr + "', '" + eqCatStr + "', " + eqQInt + ", '" + eqUOMStr + "', " + addedDate + ", '" + addedByStr + "' " + " )" status = ODBCquery(linkName,qryStr, "newEventResourceArray") 'Trap the error and display it to the user in case of any error inserting records PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 70 of 133 If ( not(status) ) Then msgboxHTML(lastError + "<br><br>" + qryStr) status = ODBCclose(linkName) Return Endif Next inumSelections ' Commit the changes qryStr = "COMMIT" status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' End status = ODBCclose(linkName) Return 15.2.6.3 ADHOC INFO (Ayuda Ciudadana) 15.2.6.3.1 AÑADIR ADHOC INFO NOMBRE: PFC_INFO_ADHOC_NEW ' NEW_ADHOC is the form displayed to be filled by the user, internally each field is called matching ' the INFO_ADHOC table fields name. status = UserDialog("NEW_ADHOC", "valuesArray", , , "F", "T") If ( not(status) ) Then RETURN ENDIF ' Open database connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Get the current max ID_ADHOC to apply the next value to the new record qryStr = "Select MAX(ID_ADHOC) from city_platform.adhoc_info " status = ODBCquery(linkName,qryStr, "currentAdhocArray") status = ODBCcolumns(linkName, "headerArray") newAdhocIdInt = currentAdhocArray[1, 1] ' Initialize CreatedBy with the current user connected to the system createdBy = USER ' Initialize CreatedDate with the current datetime createdDate = OdbcDateTimeStamp(DateTime()) ' Assign a new id for the record to be created newAdhocIdInt = newAdhocIdInt + 1 'fieldsArray and valuesArray are the arrays where fields and values are stored PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 71 of 133 ' Convert fields Array to String using comma as separator between field names ' as expected by the Insert SQL Statement fieldNamesStr = ArrayToCSVString(fieldNames, ",") ' Creates the string for the values contained in the values Array valuesArrayStr = "" ' Count positions in the values array to adapt values to the SQL Statement. contFieldsInt = UBound(valuesArray, 1) For icontFieldsInt = 1 To contFieldsInt ' If value is true then it has to be replaced by T (the equivalent string for boolean True value) If ( valuesArray[icontFieldsInt] = true ) Then valuesArray[icontFieldsInt] = "T" ENDIF ' If value is false then it has to be replaced by F (the equivalent string for boolean False value) If ( valuesArray[icontFieldsInt] = false ) Then valuesArray[icontFieldsInt] = "F" ENDIF ' Put value between single quotes for the text fields. valuesArrayStr = valuesArrayStr + "'" + valuesArray[icontFieldsInt], "' " ' If field is not the last one then put a comma char when adding to the values String that will be used for the Insert SQL Statement. If ( icontFieldsInt < contFieldsInt ) Then valuesArrayStr = valuesArrayStr + " , " Endif Next ' Build the Insert SQL Statement using the Fields and Values Strings created lines above and run the statement. qryStr = "Insert Into city_platform.adhoc_info (ID_ADHOC, " + fieldNamesStr + ") VALUES " qryStr = qryStr + " (" + newAdhocIdInt + ", " + valuesArrayStr + " )" status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' Trap the error and display it with the query in case of any error running the SQL statement If ( not(status) ) Then msgboxHTML(lastError + "<br><br>" + qryStr) status = ODBCclose(linkName) Return Endif ' Commit changes in the database qryStr = "COMMIT" status = ODBCquery(linkName,qryStr, "newEventResourceArray") 'End status = ODBCclose(linkName) Return PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 72 of 133 15.2.6.3.2 VER LISTA DE ADHOC INFO Y AÑADIRLA A UN EVENTO NOMBRE: PFC_INFO_ADHOC ' Get the Event currently opened on screen to add the selected records currentEventStr = GetGlobalVariable(globalCurrentEventStr) ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Get existing records on the ADHOC_INFO table. Just the active ones qryStr = "Select * from city_platform.adhoc_info Where Obsolete = 'F' And Active = 'T' " status = ODBCquery(linkName,qryStr, "adhocInfoArray") status = ODBCcolumns(linkName, "headerArray") ' Counter of the returned records contRecordInt = UBound(adhocInfoArray, 1) ' If no records found then display a message and abort this process If ( contRecordInt = 0 ) Then msgbox("No hay registros en Adhoc Info") status = ODBCclose(linkName) Return Endif ' Display the category equivalence and let the user select the ones to be added to the current event numSelections = MultiColumnSelectFromArray(adhocInfoArray, "Seleccione Adhoc Info para añadir a su evento", "selectionArray", headerArray) ' If no records selected then abort this process If ( numSelections = 0 ) Then status = ODBCclose(linkName) Return Endif ' Ask the user to confirm the process about insert the selected category equivalences to the current event answer = PromptForYesNo("¿Está seguro de añadir los " + str(numSelections) + " datos seleccionados al evento " + "?") IF ( answer <> "Yes" ) Then status = ODBCclose(linkName) RETURN ENDIF ' If no event currently opened on the screen display a message because the records can not be added to any event and abort this process If ( isEmpty(currentEventStr) ) Then msgbox("Debe seleccionar un evento para poder asignarle Adhoc Info") status = ODBCclose(linkName) Return Endif PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 73 of 133 ' If no event currently opened on the screen display a message because the records can not be added to any event and abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento para poder asignarle Adhoc Info") status = ODBCclose(linkName) Return Endif ' Get the max ID_EV_RES for the Event Resource table to add the new ones consecutively. qryStr = "Select MAX(ID_EV_RES) from city_platform.event_resource " status = ODBCquery(linkName,qryStr, "eventResourceArray") eventResourceRecordInt = eventResourceArray[1, 1] For inumSelections = 1 To numSelections ' Get values from the selection array to build the Insert SQL Statement per each selected record. resourceId = selectionArray[inumSelections, 1] resCategoryStr = selectionArray[inumSelections, 3] resQInt = selectionArray[inumSelections, 4] resUOMStr = selectionArray[inumSelections, 5] noteStr = selectionArray[inumSelections, 7] publicStr = selectionArray[inumSelections, 13] fungibleB = selectionArray[inumSelections, 14] currentQuantityInt = selectionArray[inumSelections, 15] 'To be added as Event Resource, ask the user for the quantity to be used where 0 is the mininum value and the current quantity is the maximum value. newQuantityInt = PromptForInteger(0, currentQuantityInt, currentQuantityInt, "Indique cantidad a añadir") 'If no quantity specified by the user then abort this process If ( NotEmpty(currentQuantityInt) ) Then ' Initialize addedByStr with the current user connected to the system addedByStr = USER ' Initialize addedDate with the current datetime addedDate = OdbcDateTimeStamp(DateTime()) 'All AdHoc Info resources are added with Resource Class set to ADHOC and Resource Id linked to the selected Adhoc Info record. ' Increase the ID per each record to be added eventResourceRecordInt = eventResourceRecordInt + 1 ' Build the Insert SQL Statement qryStr = "Insert Into city_platform.event_resource (ID_EV_RES, ID_EVENT, RESOURCE_CLASS, RESOURCE_ID, ACTIVE, OBSOLETE, PUBLIC, SECURITY_GROUP, NOTE, ADDED_BY, RES_CATEGORY, RES_Q, RES_UOM, FUNGIBLE, CURRENT_QUANTITY) VALUES " qryStr = qryStr + " (" + eventResourceRecordInt + ", " + currentEventStr + ", " + "'ADHOC'" + ", " + resourceId + ", " + "'T', 'F', '" + publicStr + "', 'GLOBAL', '" + noteStr + "', '"+ addedByStr + "'" + ", '" + resCategoryStr + "', " + resQInt + ", '" + resUOMStr + "' , '" + fungibleB + "'," + newQuantityInt + ")" status = ODBCquery(linkName,qryStr, "newEventResourceArray") PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 80 of 133 ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Get all existing events in the database qryStr = "Select * from city_platform.Event" status = ODBCquery(linkName,qryStr, "eventArray") status = ODBCcolumns(linkName, "headerArray") ' Event counter contRecordInt = UBound(eventArray, 1) ' If counter is set to zero then they are no events in the database so notify it to the user and abort this process If ( contRecordInt = 0 ) Then msgbox("No hay registros en Eventos") Return Endif ' Display the list of events to let the user selects an event to be opened. numSelections = MultiColumnSelectFromArray(eventArray, "Seleccione Adhoc Info para añadir a su evento", "selectionArray", headerArray) ' If no selections then abort this process If ( numSelections = 0 ) Then Return Endif ' Get ID and Description from the selected event currentEventStr = selectionArray[1,1] currentEventDescriptionStr = selectionArray[1,7] ' Set the global system variables pointing to the event selected status = SetGlobalVariable(globalCurrentEventStr, currentEventStr) status = SetGlobalVariable(globalCurrentEventDescriptionStr, currentEventDescriptionStr) ' Initialize to NULL the global system variables related to the Event Stage as the user will have to select an event stage using the interface if so. status = SetGlobalVariable(globalCurrentEventStageStr, ERROR) status = SetGlobalVariable(globalCurrentEventStageNeedStr, ERROR) status = RefreshVisualWorkflow("EVENTOS") ‘ End Return 15.2.6.5.3 REGISTRAR NUEVA DECISION DE EVENTO NOMBRE: PFC_EVENT_DECISION_NEW PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 81 of 133 ' Get the event currently opened on screen currentEventStr = GetGlobalVariable(globalCurrentEventStr) ' If no event opened then this action can not be performed so abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' If no event opened then this action can not be performed so abort this process If ( isEmpty(currentEventStr) ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Open a prompt to let the user set the note. This prompt is limited up to 200 chars. newDecisionStr = PromptForLongText("Entre un registro de decision", "", 200) ' If no note was entered then abort this process If ( isEmpty(newDecisionStr) ) Then msgbox("Registro de decisión abortado por el usuario") Return Endif ' Set internal variable values decisionTypeStr = "NOTA" successStr = "F" createdByStr = USER createdDate = OdbcDateTimeStamp(DateTime()) ' Get MAX ID_EV_DECISION value to set the new record ID value qryStr = "Select MAX(ID_EV_DECISION) from city_platform.event_decision_log " status = ODBCquery(linkName,qryStr, "currentEventDecisionArray") status = ODBCcolumns(linkName, "headerArray") newEventDecisionIdInt = currentEventDecisionArray[1, 1] ' Set the new record ID value newEventDecisionIdInt = newEventDecisionIdInt + 1 ' Build the Insert SQL Statement and run it qryStr = "Insert Into city_platform.event_decision_log (ID_EVENT, ID_EV_DECISION, DECISION_TYPE, DECISION, SUCCESS, CREATED_BY, CREATED_DATE) VALUES " qryStr = qryStr + " (" + currentEventStr + ", " + newEventDecisionIdInt + ", '" + decisionTypeStr + "' , '" + newDecisionStr + "', '" + successStr + "', '" + createdByStr + "', " + createdDate + ") " status = ODBCquery(linkName,qryStr, "newEventResourceArray") 'Trap the error and show it to the user if so If ( not(status) ) Then msgboxHTML(lastError + "<br><br>" + qryStr) PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 82 of 133 Return Endif ' Commit Changes qryStr = "COMMIT" status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' End Return 15.2.6.5.4 VER LISTADO DE DECISIONES DE UN EVENTO NOMBRE: PFC_EVENT_DECISION ' Get the event currently opened on screen currentEventStr = GetGlobalVariable(globalCurrentEventStr) ' If no event opened then this action can not be performed so abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Build the query to get the decision logs for the selected event and run the query qryStr = "Select * from city_platform.event_decision_log Where ID_EVENT=" + currentEventStr status = ODBCquery(linkName,qryStr, "eventResourceArray") status = ODBCcolumns(linkName, "headerArray") ' Counter about the existing decisions for the selected event contRecordInt = UBound(eventResourceArray, 1) ' If counter is set to zero then this event has no decisions by now so display a message to notify that to the user and abort the process If ( contRecordInt = 0 ) Then msgbox("Todavía no hay registro de decisiones asignados al evento") Return Endif ' Display the list of decisions for the selected event numSelections = MultiColumnSelectFromArray(eventResourceArray, "Registro de decisiones", "selectionArray", headerArray) ' End Return PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 83 of 133 15.2.6.5.5 VER LISTA DE RECURSOS ASIGNADOS A UN EVENTO Y PERMITIR MODIFICARLOS NOMBRE: PFC_EVENT_RESOURCES ' Get the event currently opened on screen currentEventStr = GetGlobalVariable(globalCurrentEventStr) ' If no event opened then this action can not be performed so abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' To be easier sort the fields displayed on the list an array is created adding sortly the fields as they have to be displayed on the list. clearArray("selectFieldArray") i = 1 selectFieldArray[i] = "ID_EV_RES" i = i + 1 selectFieldArray[i] = "RESOURCE_CLASS" i = i + 1 selectFieldArray[i] = "RESOURCE_ID" i = i + 1 selectFieldArray[i] = "RES_CATEGORY" i = i + 1 selectFieldArray[i] = "RES_Q" i = i + 1 selectFieldArray[i] = "RES_UOM" i = i + 1 selectFieldArray[i] = "CURRENT_QUANTITY" i = i + 1 selectFieldArray[i] = "FUNGIBLE" i = i + 1 selectFieldArray[i] = "NOTE" i = i + 1 selectFieldArray[i] = "ACTIVE" i = i + 1 selectFieldArray[i] = "OBSOLETE" i = i + 1 selectFieldArray[i] = "PUBLIC" i = i + 1 selectFieldArray[i] = "ADDED_DATE" i = i + 1 selectFieldArray[i] = "ADDED_BY" i = i + 1 ' Convert the array to string separated by comma char as expected by the query SQL Statement PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 84 of 133 selectFieldArrayStr = ArrayToCSVString(selectFieldArray, ", ") ' Build the Select SQL Statement and run the query on the database qryStr = "Select " + selectFieldArrayStr + " from city_platform.event_resource Where ID_EVENT=" + currentEventStr status = ODBCquery(linkName,qryStr, "eventResourceArray") status = ODBCcolumns(linkName, "headerArray") ' Get counter from the records returned by the query contRecordInt = UBound(eventResourceArray, 1) ' If no records returned then this event has no resources already assigned If ( contRecordInt = 0 ) Then msgbox("Todavía no hay recursos asignados al evento") Return Endif ' Display the Event Resources as a list and let the user select any record to be updated. numSelections = MultiColumnSelectFromArray(eventResourceArray, "Seleccione Adhoc Info para añadir a su evento", "selectionArray", headerArray) ' If no records selected then abort this process If ( numSelections = 0 ) Then Return Endif IF ( numSelections > 0 ) Then ' PFC_CAT is a form to let the user view the current info from the selected resource (fields is an array with the fields name and default values is an array with the values) and modify the info templateStr = "PFC_CAT" fields[1] = "ID" fields[2] = "RES_CATEGORY" fields[3] = "RES_Q" fields[4] = "RES_UOM" fields[5] = "ACTIVE" fields[6] = "FUNGIBLE" fields[7] = "CURRENT_QUANTITY" oldQuantityInt = selectionArray[1, 7] resourceClassStr = selectionArray[1, 2] resourceIdInt = selectionArray[1, 3] defaultValues[1] = selectionArray[1, 1] defaultValues[2] = selectionArray[1, 4] defaultValues[3] = selectionArray[1, 5] defaultValues[4] = selectionArray[1, 6] defaultValues[5] = selectionArray[1, 10] defaultValues[6] = selectionArray[1, 8] defaultValues[7] = selectionArray[1, 7] ' Display the form PFC_CAT status = UserDialog(templateStr, "valuesArray", fields, defaultValues, "F", "T") ' If the user cancel the form then abort this process PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 85 of 133 If ( not(status) ) Then RETURN ENDIF fungibleB = valuesArray[6] fungibleB = str(fungibleB) fungibleB = uCase(fungibleB) ' Build the Update SQL Statement with the info once the user modified it. qryStr = "" qryStr = qryStr + " Update city_platform.event_resource " qryStr = qryStr + " Set RES_CATEGORY ='" + valuesArray[2] + "' " qryStr = qryStr + " , RES_UOM ='" + valuesArray[4] + "' " qryStr = qryStr + " , ACTIVE ='" + valuesArray[5] + "' " qryStr = qryStr + " , FUNGIBLE ='" + fungibleB + "' " qryStr = qryStr + " , CURRENT_QUANTITY =" + valuesArray[7] + " " qryStr = qryStr + " Where ID_EV_RES=" + valuesArray[1] status = ODBCquery(linkName,qryStr, "eventResourceArray") newQuantityInt = valuesArray[7] newQuantityInt = val(newQuantityInt) oldQuantityInt = val(oldQuantityInt) ' If Quantity field was modified then it forces an update on the source resource record. If ( oldQuantityInt <> newQuantityInt ) Then ' Resources can be AdHoc Info or Services so check the Resource Class value because depending on that the source resource belongs to the ADHOC_INFO or SERVICE table If ( resourceClassStr = "ADHOC" ) Then tableNameStr = "ADHOC_INFO" tableKeyFieldStr = "ID_ADHOC" ELSE tableNameStr = "SERVICE" tableKeyFieldStr = "ID_SERVICE" ENDIF ' Calculate the change in terms of current quantity to be applied to the source resource newCurrentQuantityInt = oldQuantityInt - newQuantityInt ' If new quantity for the Event Resource is less than the current value then the quantity on the resouce has to be increased otherwise decreased. IF ( newCurrentQuantityInt > 0 ) Then sqlMathSymbolStr = " + " ELSE sqlMathSymbolStr = " " ENDIF ' Build the Update SQL Statement qryStr = "" qryStr = qryStr + " Update city_platform." + tableNameStr qryStr = qryStr + " Set CURRENT_QUANTITY = CURRENT_QUANTITY " + sqlMathSymbolStr + newCurrentQuantityInt qryStr = qryStr + " Where " + tableKeyFieldStr + "=" + resourceIdInt status = ODBCquery(linkName,qryStr, "eventResourceArray") PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 86 of 133 ' Trap the error and display it to the user if so If ( not(status) ) Then MsgboxHtml(lastError + "<br>" + qryStr, , ) ELSE MsgboxHtml("Hecho" + "<br>" + qryStr, , ) ENDIF ENDIF Endif 'End Return 15.2.6.5.6 VER CATEGORIAS EQUIVALENTES ASIGNADAS A UN EVENTO NOMBRE: PFC_EVENT_CATEGORY_EQUIVALENCE ' Get the event currently opened on screen currentEventStr = GetGlobalVariable(globalCurrentEventStr) ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Build and run the Select SQL Statement for the current event qryStr = "Select * from city_platform.Event_Category_Equivalence Where ID_EVENT=" + currentEventStr status = ODBCquery(linkName,qryStr, "adhocInfoArray") status = ODBCcolumns(linkName, "headerArray") ' Counter about category equivalence already assigned to the current event contRecordInt = UBound(adhocInfoArray, 1) ' If no Category Equivalence assigned to the event then notify it to the user and abort this process If ( contRecordInt = 0 ) Then msgbox("No hay registros en Equivalencia de Categorías para este evento") Return Endif ' Display the event category equivalences list to the user numSelections = MultiColumnSelectFromArray(adhocInfoArray, "Seleccione Equivalencia de Categorías para este evento", "selectionArray", headerArray) ' End Return 15.2.6.5.7 MODIFICAR INFORMACIÓN DE UN EVENTO NOMBRE: PFC_EVENT_ACTION ' This code is common for each action related to modify any info on the Event Record. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 87 of 133 ' The variable called vwSelectedRowIndex identifies which is the field the user decided to update ' So the Case Structure contains a specific code per each field ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif SELECTCASE vwSelectedRowIndex CASE 5 ' Switch the Completed field value ' Get the Current Event opened on screen and the Completed field value currentEventStr = GetGlobalVariable("globalCurrentEventStr") completed = vwSelectedRowArray[4] ' Build a Select SQL Statement on the child table called Event_Stage to check if any Event Stage for this event is NOT currently set to Completed qryStr = "Select * from city_platform.event_stage Where ID_EVENT = " + currentEventStr + " And Completed <> 'T' " status = ODBCquery(linkName,qryStr, "eventStageArray") status = ODBCcolumns(linkName, "headerArray") ' Get counter for the previous query contRecordInt = UBound(eventStageArray, 1) ' If the counter is set to zero then the event can be switched to Completed othewise the list of event statges in progress are listed to the list and this process is aborted If ( contRecordInt = 0 ) Then msgbox("Enhorabuena! Todas las etapas están cubiertas") ELSE numSelections = Multi ColumnSelectFromArray(eventStageArray, "Estas son las etapas incubiertas. Seleccione la que desee cubrir", "selectionArray", headerArray) Return Endif ' If the event is currently in progress then it is switched to completed. If currently Completed then switched to In Progress. If ( completed = "F" ) Then qryStr = " Update EVENT SET COMPLETED='T' Where ID_EVENT = " + currentEventStr ELSE qryStr = " Update EVENT SET COMPLETED='F' Where ID_EVENT = " + currentEventStr ENDIF status = ODBCquery(linkName,qryStr, "resourceNotFungibleArray") If ( not(status) ) Then msgboxhtml(lastError + "<br>" + qryStr ) RETURN ENDIF ' NOW it is time to return the non fungible resources assigned to this event as they were locked to be used by this event but now they can be re-asssigned to other events if this event is moved from In Progress to PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 88 of 133 Completed. ' If this event is moved from Completed to In Progress then the resources will be re-assigned to the event and decreased from the source resources ' Build the Select SQL Statement returning just the nont fungible (FUNGIBLE=F) assigned to this event qryStr = "" qryStr = qryStr + " Select RESOURCE_ID, RESOURCE_CLASS, CURRENT_QUANTITY, RES_CATEGORY, RES_UOM " qryStr = qryStr + " From EVENT_RESOURCE" qryStr = qryStr + " Where ID_EVENT = " + currentEventStr + " And FUNGIBLE ='F' " status = ODBCquery(linkName,qryStr, "resourceNotFungibleArray") ' If any error running the query then trap the error and abort this process If ( not(status) ) Then msgboxhtml(lastError + "<br>" + qryStr ) RETURN ENDIF ' Counter about records returned contRecordInt = UBound(resourceNotFungibleArray, 1) ' Just in case records returned by the previous query actions has to be performed otherwise notify the user and abort the process If ( contRecordInt > 0 ) Then ' Depending on the movement type (In Progress to Completed // Completed to In Progress) the message title will be one or another. If ( completed = "F" ) Then msgStr = "Los siguientes recursos no fungibles han sido retornados a las tablas maestras: <br><br>" ELSE msgStr = "Los siguientes recursos del evento no fungibles han sido reasignados a este evento: <br><br>" ENDIF ' Create a dynamic html table populated by each record in the For Structure so here just the table header part is created msgStr = msgStr + "<table class=" + chr(34) + "vw_table" + chr(34) + " id=" + chr(34) + "vweventos_devent_info_table" + chr(34) + "name=" + chr(34) + "EVENT_INFO" + chr(34) + " datavw_detail=" + chr(34) + "EVENT_INFO" + chr(34) + ">" msgStr = msgStr + "<thead><tr><th>Clase</th><th>Categoría</th><th>Cantidad devuelta</th><th>Unidad de Medida</th></tr></thead>" msgStr = msgStr + "<tbody><tr data-vw_linkname=" + chr(34) + "14/06/2014 13:48:29F" + chr(34) + "> " ELSE msgbox("No había recursos no fungibles") ENDIF ' Run this code for each non fungible record returned by the query For icontRecordInt = 1 To contRecordInt ' Get the current record info eventResouceIdInt = resourceNotFungibleArray[icontRecordInt, 1] eventResouceClassInt = resourceNotFungibleArray[icontRecordInt, 2] eventResouceQuantityInt = resourceNotFungibleArray[icontRecordInt, 3] eventResouceCategoryStr = resourceNotFungibleArray[icontRecordInt, 4] PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 89 of 133 eventResouceUOMStr = resourceNotFungibleArray[icontRecordInt, 5] ' Depending on the Resource Class the change will apply to the ADHOC_INFO or SERVICE table so check and use one table or the other and its key field name IF (eventResouceClassInt = "ADHOC" ) Then tableNameStr = "ADHOC_INFO" tableKeyFieldStr = "ID_ADHOC" ELSE tableNameStr = "SERVICE" tableKeyFieldStr = "ID_SERVICE" ENDIF ' Build the Query to apply the change on the source resource qryStr = "" qryStr = qryStr + " Update city_platform." + tableNameStr If ( completed = "F" ) Then qryStr = qryStr + " SET CURRENT_QUANTITY = CURRENT_QUANTITY + " + eventResouceQuantityInt ELSE qryStr = qryStr + " SET CURRENT_QUANTITY = CURRENT_QUANTITY - " + eventResouceQuantityInt ENDIF qryStr = qryStr + " Where " + tableKeyFieldStr + "=" + eventResouceIdInt status = ODBCquery(linkName,qryStr, "eventResourceArray") ' Add the recorf info to the dynamic html table msgStr = msgStr + "<td>" + eventResouceClassInt +"< /td><td>" + eventResouceCategoryStr + "</td><td>" + eventResouceQuantityInt + "</td><td>" + eventResouceUOMStr + "</td></tr>" Next icontRecordInt ' Close the dynamic html table msgStr = msgStr + "</tbody></table>" ' Display the dynamic html table to the user in order to notify which are the resources returned or reassigned. If ( contRecordInt > 0 ) Then MsgboxHtml(msgStr , , ) ENDIF 'End RETURN CASE 8 ' Switch the Success Field value ' Get event currently opened on screen and its current success field value idEventId = GetGlobalVariable("globalCurrentEventStr") success = vwSelectedRowArray[3] ' Build the Update SQL Statement. qryStr = "" qryStr = qryStr + " Update city_platform.event " ' Switch the field value to F if it's currently T or to T if currently F. If ( success = "T" ) Then PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 96 of 133 linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif SELECTCASE vwSelectedRowIndex CASE 1 ' Select the event stage record ' Set the Global System Variable pointing to this event stage record status = SetGlobalVariable(globalCurrentEventStageStr, parameterValue) status = SetGlobalVariable(globalCurrentEventStageNeedStr, ERROR) CASE 7 ' Switch the Completed field value ' Get the Current Event opened on screen and the Completed field value currentEventStr = GetGlobalVariable(globalCurrentEventStr) 'Select values from the selected event stage record currentEventStageStr = vwSelectedRowArray[1] completed = vwSelectedRowArray[2] ' If the event is currently in progress then check if it can be turn to Completed If ( completed = "F" ) Then ' Build a query by a union of EVENT_STAGE_NEED and EVENT_STAGE_OPERATION tables where records belonging to this current and any of them is currently in progress. qryStr = "" qryStr = qryStr + " ( Select CONCAT('Necesidad: ', NEED_CATEGORY) From event_stage_need Where Completed <>'T' And ID_EVENT =" + currentEventStr + " And ID_EV_STAGE =" + currentEventStageStr + " ) " qryStr = qryStr + " UNION " qryStr = qryStr + " ( Select CONCAT('Operativa: ', DESCRIPTION) From event_stage_operation Where Completed <>'T' And ID_EVENT =" + currentEventStr + " And ID_EV_STAGE =" + currentEventStageStr + " ) " ' Run the query clearArray("eventNotCompletedArray") status = ODBCquery(linkName,qryStr, "eventNotCompletedArray") ' Counter for the previous query contRecordInt = Ubound(eventNotCompletedArray, 1) ' If counter is not set to zero then they exist in progress records so display the list to the user and abort this process as the change can not be applied If ( contRecordInt > 0 ) Then eventNotCompletedArrayStr = ArrayToCSVString(eventNotCompletedArray, "<br>") msgboxhtml("Existen " + str(contRecordInt) + " actividades entre necesidades y operaciones sin completar" + "<br><br><font color=" + chr(34) + "red" + chr(34) + ">" + eventNotCompletedArrayStr) Return Endif Endif ' Build the Update SQL Statement to apply the change. ' If the event is currently in progress then it is switched to completed. If currently Completed then PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 97 of 133 switched to In Progress. qryStr = "" qryStr = qryStr + " Update city_platform.event_stage " If ( completed = "T" ) Then qryStr = qryStr + " Set Completed = 'F' " Else qryStr = qryStr + " Set Completed = 'T' " Endif qryStr = qryStr + " Where ID_EV_STAGE = " + currentEventStageStr status = ODBCquery(linkName,qryStr, "eventStageArray") CASE 8 ' Switch the Success Field value ' Get values from the selected event stage record. idEvStageId = vwSelectedRowArray[1] success = vwSelectedRowArray[5] ' Build the Update SQL Statement. qryStr = "" qryStr = qryStr + " Update city_platform.event_stage " ' Switch the field value to F if it's currently T or to T if currently F. If ( success = "T" ) Then qryStr = qryStr + " Set Success = 'F' " Else qryStr = qryStr + " Set Success = 'T' " Endif qryStr = qryStr + " Where ID_EV_STAGE = " + idEvStageId ' Run the Update SQL Statement status = ODBCquery(linkName,qryStr, "eventStageArray") CASE 9 ' Change Initial Date field value ' Get values from the selected event stage record. idEvStageId = vwSelectedRowArray[1] currentDate = vwSelectedRowArray[3] ' Assign current date time to that variable if event has currently no ini_Date value if ( isEmpty(currentDate) ) Then currentDate = datetime() Endif ' Prompt a Calendar to let the user set new Ini Date value, current Ini Date will be assigned to the prompt by default dt = PromptForDateTime("Seleccione Fecha Inicio", currentDate) dt = OdbcDateTimeStamp(dt) ' Build the Update SQL Statement to apply the change qryStr = "" qryStr = qryStr + " Update city_platform.event_stage " qryStr = qryStr + " Set INI_DATE = " + dt qryStr = qryStr + " Where ID_EV_STAGE = " + idEvStageId ' Run the Update SQL Statement PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 98 of 133 status = ODBCquery(linkName,qryStr, "eventStageArray") CASE 10 ' Change End Date field value ' Get values from the selected event stage record. idEvStageId = vwSelectedRowArray[1] currentDate = vwSelectedRowArray[4] ' Assign current date time to that variable if event has currently no ini_Date value if ( isEmpty(currentDate) ) Then currentDate = datetime() Endif ' Prompt a Calendar to let the user set new Ini Date value, current Ini Date will be assigned to the prompt by default dt = PromptForDateTime("Seleccione Fecha Inicio", currentDate) dt = OdbcDateTimeStamp(dt) ' Build the Update SQL Statement to apply the change qryStr = "" qryStr = qryStr + " Update city_platform.event_stage " qryStr = qryStr + " Set END_DATE = " + dt qryStr = qryStr + " Where ID_EV_STAGE = " + idEvStageId ' Run the Update SQL Statement status = ODBCquery(linkName,qryStr, "eventStageArray") CASE 11 ' Delete the selected Event Stage ' Get values from the selected event stage record. idEvStageId = vwSelectedRowArray[1] ' Ask user to confirm the action has to be performed answer = PromptForYesNo("¿Está seguro que desea borrar?") If ( answer <> "Yes") Then RETURN ENDIF ' Build and run the Delete SQL Statement to delete the Event Stage Need Resource records assigned to this event stage qryStr = "" qryStr = qryStr + " Delete From city_platform.event_stage_need_resource " qryStr = qryStr + " Where ID_EV_STAGE = " + idEvStageId status = ODBCquery(linkName,qryStr, "eventStageArray") ' Build and run the Delete SQL Statement to delete the Event Stage Need records assigned to this event stage qryStr = "" qryStr = qryStr + " Delete From city_platform.event_stage_need " qryStr = qryStr + " Where ID_EV_STAGE = " + idEvStageId status = ODBCquery(linkName,qryStr, "eventStageArray") ' Build and run the Delete SQL Statement to delete the Event Stage Operation records assigned to this event stage qryStr = "" PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 99 of 133 qryStr = qryStr + " Delete From city_platform.event_stage_operation " qryStr = qryStr + " Where ID_EV_STAGE = " + idEvStageId status = ODBCquery(linkName,qryStr, "eventStageArray") ' Build and run the Delete SQL Statement to delete the Event Stage Decision Log records assigned to this event stage qryStr = "" qryStr = qryStr + " Delete From city_platform.event_stage_decision_log " qryStr = qryStr + " Where ID_EV_STAGE = " + idEvStageId status = ODBCquery(linkName,qryStr, "eventStageArray") ' And Finally build and run the Delete SQL Statement to delete the Event Stage record assigned to this event stage qryStr = "" qryStr = qryStr + " Delete From city_platform.event_stage " qryStr = qryStr + " Where ID_EV_STAGE = " + idEvStageId status = ODBCquery(linkName,qryStr, "eventStageArray") CASE ELSE 'No action linked to this field. msgbox("Columna no reconocida para accion") Return ENDSELECT status = RefreshVisualWorkflow("EVENTOS") 'End Return 15.2.6.6.3 LISTA DE DECISIONES DE UNA ETAPA DE EVENTO NOMBRE: PFC_EVENT_STAGE_DECISION ' Get current event and event stage currentEventStr = GetGlobalVariable(globalCurrentEventStr) currentEventStageStr = GetGlobalVariable(globalCurrentEventStageStr) ' IF no event opened then abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' If no event stage selected then abort this proces If ( currentEventStageStr = ERROR ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 100 of 133 Endif ' Build and run the Select SQL Statement to get the decision logs for this event stage qryStr = "Select * from city_platform.event_Stage_decision_log Where ID_EVENT=" + currentEventStr + " And ID_EV_STAGE=" + currentEventStageStr status = ODBCquery(linkName,qryStr, "eventResourceArray") status = ODBCcolumns(linkName, "headerArray") ' Counter for the previous query contRecordInt = UBound(eventResourceArray, 1) ' If counter is set to zero then this event stage has no decision logs assigned to If ( contRecordInt = 0 ) Then msgbox("Todavía no hay registro de decisiones asignados a la etapa") Return Endif 'Display the list of Decision logs for this event stage numSelections = MultiColumnSelectFromArray(eventResourceArray, "Registro de decisiones de etapa", "selectionArray", headerArray) 'End Return 15.2.6.6.4 AÑADIR NUEVA DECISION A ETAPA DE EVENTO NOMBRE: PFC_EVENT_STAGE_DECISION_NEW ' Get current event and event stage currentEventStr = GetGlobalVariable(globalCurrentEventStr) currentEventStageStr = GetGlobalVariable(globalCurrentEventStageStr) ' IF no event opened then abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' IF no event opened then abort this process If ( currentEventStageStr = ERROR ) Then msgbox("Debe seleccionar una etapa de evento previamente") Return Endif ' IF no event opened then abort this process If ( isEmpty(currentEventStr) ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 101 of 133 If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Prompt a dialog to let user enter the decision. Text is limited up to 200 chars. newDecisionStr = PromptForLongText("Entre un registro de decision", "", 200) ' If no Decision entered then abort this process If ( isEmpty(newDecisionStr) ) Then msgbox("Registro de decisión abortado por el usuario") Return Endif ' Set variable values to be used for the inserting decisionTypeStr = "NOTA" successStr = "F" createdByStr = USER createdDate = OdbcDateTimeStamp(DateTime()) ' Get MAX ID_EV_ST_DECISION value qryStr = "Select MAX(ID_EV_ST_DECISION) from city_platform.event_stage_decision_log " status = ODBCquery(linkName,qryStr, "currentEventStageDecisionArray") status = ODBCcolumns(linkName, "headerArray") newEventStageDecisionIdInt = currentEventStageDecisionArray[1, 1] ' Create ID for the new record newEventStageDecisionIdInt = newEventStageDecisionIdInt + 1 ' Build the Insert SQL Statement and run it qryStr = "Insert Into city_platform.event_stage_decision_log (ID_EVENT, ID_EV_STAGE, ID_EV_ST_DECISION, DECISION_TYPE, DECISION, SUCCESS, CREATED_BY, CREATED_DATE) VALUES " qryStr = qryStr + " (" + currentEventStr + ", " + currentEventStageStr + ", " + newEventStageDecisionIdInt + ", '" + decisionTypeStr + "' , '" + newDecisionStr + "', '" + successStr + "', '" + createdByStr + "', " + createdDate + ") " status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' In case of any error trap the error and display it to the user If ( not(status) ) Then msgboxHTML(lastError + "<br><br>" + qryStr) Return Endif ' Commit Changes qryStr = "COMMIT" status = ODBCquery(linkName,qryStr, "newEventResourceArray") 'End Return PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 102 of 133 15.2.6.7 OPERACIONES DE LA ETAPA DE UN EVENTO 15.2.6.7.1 CREAR NUEVA OPERACIÓN NOMBRE: PFC_EVENT_STAGE_OPERATION_NEW ' Get current event and event stage currentEventStr = GetGlobalVariable(globalCurrentEventStr) currentEventStageStr = GetGlobalVariable(globalCurrentEventStageStr) ' IF no event opened then abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' IF no event opened then abort this process If ( currentEventStageStr = ERROR ) Then msgbox("Debe seleccionar una etapa de evento previamente") Return Endif ' IF no event opened then abort this process If ( isEmpty(currentEventStr) ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' Prompt a dialog to let user enter the Operation Name. Text is limited up to 45 chars. descriptionStr = PromptForLongText("Añada un nombre de operacion", "", 45) ' If no Operation Name entered then abort this process If ( isEmpty(descriptionStr) ) Then msgbox("Creacion abortada por el usuario") Return Endif ' Open Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Get MAX ID_EV_ST_OPER value qryStr = "Select MAX(ID_EV_ST_OPER) from city_platform.event_stage_operation " status = ODBCquery(linkName,qryStr, "currentEventStageOperationArray") status = ODBCcolumns(linkName, "headerArray") newEventStageOperationIdInt = currentEventStageOperationArray[1, 1] ' Set new ID for the new record newEventStageOperationIdInt = newEventStageOperationIdInt + 1 PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 103 of 133 ' Initialize variable values to be used in the inserting createdBy = USER createdDate = OdbcDateTimeStamp(DateTime()) ' Build the Insert SQL Statement and run it qryStr = "Insert Into city_platform.event_stage_operation (ID_EVENT, ID_EV_STAGE, ID_EV_ST_OPER, CREATED_BY, DESCRIPTION, COMPLETED, NOTE, CREATED_DATE) VALUES " qryStr = qryStr + " (" + currentEventStr + ", " + currentEventStageStr + ", " + newEventStageOperationIdInt + ", '" + createdBy + "', '" + descriptionStr + "', " + "'F' " + ", '" + "''" + "', " + createdDate + " )" status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' In case of any error trap the error and display it to the user If ( not(status) ) Then msgboxHTML(lastError + "<br><br>" + qryStr) Return Endif ' Refresh the window status = RefreshVisualWorkflow("EVENTOS") ' End Return 15.2.6.7.2 ACCIONES AL RESPECTO DE UNA OPERACIÓN DE UNA ETAPA DE EVENTO NOMBRE: PFC_EVENT_STAGE_OPERATION_ACTION ' This code is common for each action related to modify any info on the Event Record. ' The variable called vwSelectedRowIndex identifies which is the field the user decided to update ' So the Case Structure contains a specific code per each field ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif SELECTCASE vwSelectedRowIndex CASE 4 ' Switch the Completed field value ' Get the Current Operation selected and the Completed field value idEvStageOperationId = vwSelectedRowArray[3] operationCompleted = vwSelectedRowArray[4] ' Build the Update SQL Statement qryStr = "" qryStr = qryStr + " Update city_platform.event_stage_Operation " ' If the event is currently in progress then it is switched to completed. If currently Completed then switched to In Progress. If ( operationCompleted = "T" ) Then qryStr = qryStr + " Set Completed = 'F' " PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 104 of 133 Else qryStr = qryStr + " Set Completed = 'T' " Endif qryStr = qryStr + " Where ID_EV_ST_OPER = " + idEvStageOperationId CASE 6 ' Update the Operation Note field ' Get the Current Operation selected and the current note field value idEvStageOperationId = vwSelectedRowArray[3] currentNote = vwSelectedRowArray[2] ' Prompt a dialog to let the user modify the existing Operation Note, the text is limited up to 200 chars. newNote = PromptForLongText("Nota de operación", currentNote, 200) ' Build the Update SQL Statement qryStr = "" qryStr = qryStr + " Update city_platform.event_stage_Operation " qryStr = qryStr + " Set NOTE = '" + newNote + "' " qryStr = qryStr + " Where ID_EV_ST_OPER = " + idEvStageOperationId ' Perform the query in the database status = ODBCquery(linkName,qryStr, "eventStageArray") CASE 7 ' Remove selected Operation ' Get the Current Operation ID selected idEvStageOperationId = vwSelectedRowArray[3] ' Ask the user to confirm if the action has to be applied answer = PromptForYesNo("¿Está seguro que desea borrar?") If ( answer <> "Yes") Then RETURN ENDIF ' Build the Delete SQL Statement qryStr = "" qryStr = qryStr + " Delete from city_platform.event_stage_Operation " qryStr = qryStr + " Where ID_EV_ST_OPER = " + idEvStageOperationId ' Perform the query in the database status = ODBCquery(linkName,qryStr, "eventStageArray") CASE ELSE ' This field has no action linked msgbox("Columna no reconocida para accion") Return ENDSELECT ' Refresh the window status = RefreshVisualWorkflow("EVENTOS") ' End Return PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 105 of 133 15.2.6.8 NECESIDADES DE LA ETAPA DE UN EVENTO 15.2.6.8.1 CREAR NUEVA NECESIDAD NOMBRE: PFC_EVENT_STAGE_NEED_NEW ' Get current event and event stage currentEventStr = GetGlobalVariable(globalCurrentEventStr) currentEventStageStr = GetGlobalVariable(globalCurrentEventStageStr) ' IF no event opened then abort this process If ( currentEventStr = ERROR ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' IF no event opened then abort this process If ( currentEventStageStr = ERROR ) Then msgbox("Debe seleccionar una etapa de evento previamente") Return Endif ' IF no event opened then abort this process If ( isEmpty(currentEventStr) ) Then msgbox("Debe seleccionar un evento previamente") Return Endif ' PFC_CAT is a form having the fields in use for this operation templateStr = "PFC_CAT" fields[1] = "ID" fields[2] = "RES_CATEGORY" fields[3] = "RES_Q" fields[4] = "RES_UOM" defaultValues[1] = currentEventStageStr defaultValues[2] = "" defaultValues[3] = "" defaultValues[4] = "" ' Open the PFC_CAT form to let the user specify the info status = UserDialog(templateStr, "valuesArray", fields, defaultValues, "F", "T") If ( not(status) ) Then RETURN ENDIF ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 112 of 133 currentEventStr + " And ID_EV_ST_NEED = " + currentEventStageNeedStr qryStr = qryStr + " And Res_Category ='" + currentEventStageCategoryStr + "' " ' Perform the query status = ODBCquery(linkName,qryStr, "eventStageNeedResourcePrimaryCatArray") eventStageResourcePrimaryCatQInt = eventStageNeedResourcePrimaryCatArray[1, 1] ' If no records found then set the sum to zero If ( isEmpty(eventStageResourcePrimaryCatQInt) ) Then eventStageResourcePrimaryCatQInt = 0 Endif ' Get the sum of resources assigned to this need non matching category and applying the conversion factor in each case qryStr = "" qryStr = qryStr + " Select (evRes.Res_Q / (Eq_Cat_01_q * Primary_Cat_Q)), evRes.Res_Category, evRes.Res_Q, catEquiv.Primary_Cat, catEquiv.Primary_Cat_Q, catEquiv.Eq_Cat_01, catEquiv.Eq_Cat_01_q From event_stage_need_Resource evRes, event_category_equivalence catEquiv Where evRes.ID_EVENT =" + currentEventStr + " And catEquiv.ID_EVENT=" + currentEventStr + " And ID_EV_ST_NEED = " + currentEventStageNeedStr qryStr = qryStr + " And evRes.Res_Category = catEquiv.Eq_Cat_01 And catEquiv.Primary_Cat ='" + currentEventStageCategoryStr + "' " ' Perform the query status = ClearArray("eventStageNeedResourceEqCatArray") status = ODBCquery(linkName,qryStr, "eventStageNeedResourceEqCatArray") ' If no records found then initialize the variable to zero otherwise then sum the values per each record returned by the query If ( isEmpty(eventStageNeedResourceEqCatArray) ) Then eventStageResourceEqCatQInt = 0 ELSE contEventStageResourceEqCatQInt = Ubound(eventStageNeedResourceEqCatArray, 1) status = ArrayConvertToSingleDim(eventStageNeedResourceEqCatArray, "eventStageNeedResourceEqCatQArray", 1) eventStageResourceEqCatQInt = Sum(eventStageNeedResourceEqCatQArray) Endif ' The current covered quantity is the sum of the quantities covered by resources matching category and the quantities covered by resources matching category equivalences coveredQInt = eventStageResourcePrimaryCatQInt + eventStageResourceEqCatQInt ' If the current Quantity is equal or more than the quantity expected by the need then return If ( coveredQInt >= currentEventStageQInt ) Then RETURN ENDIF ' If any piece of quantity is not covered then the process will ask the user about how to continue. ' Help the user to cover the need: In that case, the system will get the event resource which can be used to cover this need ' Set to completed the need although it is not covered. In that case the system will update the need from In Progress to Completed in spite it is not covered ' Abort this process. Stop the process ' If the user select the first option then the system will re-calculate the covered quantity and if not covered then the process will start a loop where same process will be applied once and again. PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 113 of 133 While ( coveredQInt < currentEventStageQInt ) ' If the current Quantity is equal or more than the quantity expected by the need then return (on the loop) If ( coveredQInt >= currentEventStageQInt ) Then status = RefreshVisualWorkflow("EVENTOS") RETURN ENDIF ' Display a message explaining which is the quantity assigned to this need and how many of them are currently being covered and ask about the way to follow from the options explained above titleStr = "La necesidad necesita " + str(currentEventStageQInt) + " de los cuales solo han sido cubiertas " + coveredQInt + ".<br> ¿Desea continuar completando la necesidad de todos modos?" buttonLabelsArray[1] = "Ayudame a cubrirla" buttonLabelsArray[2] = "Confirma aún y sin cubrir" buttonLabelsArray[3] = "Abortar" ' Prompt the dialog to let the user select the way buttonIndex = OpenHtmlDisplayDialog(titleStr, 550, 200, buttonLabelsArray) SELECTCASE buttonIndex CASE 1 ' Help the user to cover the need ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Get the Event Resources that can help the user to cover the quantity by joining resources matching category and the ones matching by any event Category Equivalence qryStr = "" qryStr = qryStr + "( Select * from city_platform.event_resource Where ID_EVENT=" + currentEventStr + " And Active='T' And RES_CATEGORY='" + currentEventStageCategoryStr + "' )" qryStr = qryStr + " UNION " qryStr = qryStr + "( Select * from city_platform.event_resource Where ID_EVENT=" + currentEventStr + " And Active='T' And RES_CATEGORY IN (SELECT EQ_CAT_01 from event_category_equivalence where primary_cat ='" + currentEventStageCategoryStr + "' ))" ' Perform the query status = ODBCquery(linkName,qryStr, "eventResourceArray") status = ODBCcolumns(linkName, "headerArray") contRecordInt = UBound(eventResourceArray, 1) ' If the query returns no records then it is because the event has no resources assigned and good to cover that need so the process has to be aborted If ( contRecordInt = 0 ) Then msgbox("Todavía no hay recursos asignados al evento") Abort() Endif ' Display the Event Resources returned by the query and let the user make the choice on them PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 114 of 133 numSelections = MultiColumnSelectFromArray(eventResourceArray, "Seleccione Recurso para añadir a su necesidad", "selectionArray", headerArray) ' If no resources selected then abort this process If ( numSelections = 0 ) Then Abort() Endif ' Get the MAX ID_EV_ST_NEED_RES value qryStr = "Select MAX(ID_EV_ST_NEED_RES) from city_platform.event_stage_need_resource " status = ODBCquery(linkName,qryStr, "currentEventStageNeedResourceArray") status = ODBCcolumns(linkName, "headerArray") newEventStageNeedResourceIdInt = currentEventStageNeedResourceArray[1, 1] ' Just one record selected will be taken numSelections = 1 For inumSelections = 1 To numSelections ' Create the ID for the new record newEventStageNeedResourceIdInt = newEventStageNeedResourceIdInt + 1 ' Get the info from the selected record and initialize variables to be used in the inserting idEvRes = selectionArray[inumSelections, 1] objectClass = selectionArray[inumSelections, 3] resCat = selectionArray[inumSelections, 14] resQ = selectionArray[inumSelections, 15] resUOM = selectionArray[inumSelections, 16] createdBy = USER createdDate = OdbcDateTimeStamp(DateTime()) ' Increase the Covered Quantity coveredQInt = coveredQInt + val(resQ) ' Build the insert SQL Statement to assign the resource to this need and perform the statement in the database qryStr = "Insert I nto city_platform.event_stage_need_resource (ID_EVENT, ID_EV_STAGE, ID_EV_ST_NEED, ID_EV_ST_NEED_RES, ID_EV_RES, ID_EV_RES_OBJ_CLASS, ID_EV_RES_CAT, CREATED_BY, CREATED_DATE, RES_CATEGORY, RES_Q, RES_UOM) VALUES " qryStr = qryStr + " (" + currentEventStr + ", " + currentEventStageStr + ", " + currentEventStageNeedStr + ", " + newEventStageNeedResourceIdInt qryStr = qryStr + ", " + idEvRes + ", '" + objectClass + "', '" + resCat + "', '" + createdBy + "', " + createdDate + ", '" + resCat + "', " + resQ + ", '" + resUOM + "'" qryStr = qryStr + ")" status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' If any error issued on running the query show it to the user and abort this process If ( not(status) ) Then msgboxHTML(lastError + "<br><br>" + qryStr) Abort() Endif ' Commit Changes qryStr = "COMMIT" PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 115 of 133 status = ODBCquery(linkName,qryStr, "newEventResourceArray") Next inumSelections CASE 2 ' Return to let the other fucntion update the Completed field value coveredQInt = currentEventStageQInt RETURN CASE 3 ' Abort both processes RETURN status = RefreshVisualWorkflow("EVENTOS") Wait(2) Abort() CASE ELSE ' Unknown action status = RefreshVisualWorkflow("EVENTOS") Abort() ENDSELECT Wend 'End RETURN 15.2.6.9 RECURSO ASOCIADO A UNA NECESIDAD DE ETAPA DE EVENTO 15.2.6.9.1 AÑADIR RECURSO DE FORMA MANUAL NOMBRE: PFC_EVENT_STAGE_NEED_RESOURCE_ADD ' Get the current Event, Stage and Need selected currentEventStr = GetGlobalVariable(globalCurrentEventStr) currentEventStageStr = GetGlobalVariable(globalCurrentEventStageStr) currentEventStageNeedStr = GetGlobalVariable(globalCurrentEventStageNeedStr) currentEventDescriptionStr = GetGlobalVariable(globalCurrentEventDescriptionStr) ' If no event selected the abort this process If ( currentEventStr = ERROR ) Then Msgbox("Seleccione Evento previamente") Return Endif ' If no event selected the abort this process If ( currentEventStageStr = ERROR ) Then Msgbox("Seleccione Etapa de Evento previamente") Return Endif ' If no event selected the abort this process If ( currentEventStageNeedStr = ERROR ) Then Msgbox("Seleccione Necesidad a cubrir previamente") Return Endif PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 116 of 133 ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Build the Select SQL Statement to get the Event resources for the current Event and being Active qryStr = "Select * from city_platform.event_reso urce Where ID_EVENT=" + currentEventStr + " And Active='T' " ' Perform the query status = ODBCquery(linkName,qryStr, "eventResourceArray") status = ODBCcolumns(linkName, "headerArray") ' Counter for the previous query contRecordInt = UBound(eventResourceArray, 1) ' If no resources assigned to the event then abort this process If ( contRecordInt = 0 ) Then msgbox("Todavía no hay recursos asignados al evento") Return Endif ' Display the list of Event Resources to the user to let him make the choice numSelections = MultiColumnSelectFromArray(eventResourceArray, "Seleccione Recurso para añadir a su necesidad", "selectionArray", headerArray) ' If no records selected then abort this process If ( numSelections = 0 ) Then Return Endif ' Get MAX ID_EV_ST_NEED_RES value qryStr = "Select MAX(ID_EV_ST_NEED_RES) from city_platform.event_stage_need_resource " 'Where ID_EVENT=" + currentEventStr status = ODBCquery(linkName,qryStr, "currentEventStageNeedResourceArray") status = ODBCcolumns(linkName, "headerArray") newEventStageNeedResourceIdInt = currentEventStageNeedResourceArray[1, 1] numSelections = 1 For inumSelections = 1 To numSelections ' Set the ID for the new record newEventStageNeedResourceIdInt = newEventStageNeedResourceIdInt + 1 ' Get info from the selected record and initialize variable values for the inserting statement idEvRes = selectionArray[inumSelections, 1] objectClass = selectionArray[inumSelections, 3] resCat = selectionArray[inumSelections, 14] currentResQ = selectionArray[inumSelections, 18] resUOM = selectionArray[inumSelections, 16] createdBy = USER PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 117 of 133 createdDate = OdbcDateTimeStamp(DateTime()) ' Ask user about quantity to be used. the minimum value will be zero and the maximum will be the current available quantity from the record resQ = PromptForInteger(0, currentResQ, currentResQ, "Indique cantidad a asignar a esta necesidad") ' Build the Insert SQL Statement qryStr = "Insert Into city_platform.event_stage_need_resource (ID_EVENT, ID_EV_STAGE, ID_ EV_ST_NEED, ID_EV_ST_NEED_RES, ID_EV_RES, ID_EV_RES_OBJ_CLASS, ID_EV_RES_CAT, CREATED_BY, CREATED_DATE, RES_CATEGORY, RES_Q, RES_UOM) VALUES " qryStr = qryStr + " (" + currentEventStr + ", " + currentEventStageStr + ", " + currentEventStageNeedStr + ", " + newEventStageNeedResourceIdInt qryStr = qryStr + ", " + idEvRes + ", '" + objectClass + "', '" + resCat + "', '" + createdBy + "', " + createdDate + ", '" + resCat + "', " + resQ + ", '" + resUOM + "'" qryStr = qryStr + ")" ' Perform the query status = ODBCquery(linkName,qryStr, "newEventResourceArray") ' In case of any error issued trap and show it to the user and abort this process If ( not(status) ) Then msgboxHTML(lastError + "<br><br>" + qryStr) Return Endif ' Calculate the new available quantity for the selected event resource newCurrentQuantityInt = val(currentResQ) - val(resQ) ' Build the Update SQL Statement to change the current available quantity for the selected event resource qryStr = "" qryStr = qryStr + " Update city_platform.event_resource" qryStr = qryStr + " Set CURRENT_QUANTITY =" + newCurrentQuantityInt qryStr = qryStr + " Where ID_EVENT=" + currentEventStr + " And ID_EV_RES=" + idEvRes status = ODBCquery(linkName,qryStr, "eventResourceArray") ' Commit Changes qryStr = "COMMIT" status = ODBCquery(linkName,qryStr, "newEventResourceArray") Next inumSelections ' Display a message to the user msgbox("Recurso(s) asignados") ' End Return 15.2.6.9.2 ACCIONES SOBRE UN RECURSO ASIGNADO A UNA NECESIDAD NOMBRE: PFC_EVENT_STAGE_NEED_RESOURCE_ACTION PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 118 of 133 'This function is an internal function to be called by the Event Stage Need Action function as part of the switching Completed field value ' So this function can stop in two ways: Abort and Return. ' If Return then returns the control to the function which call it and continue with the action performed ' If Abort then aborts both functions, this function and the function which call it. ' Get current Event, Stage and need selected currentEventStr = GetGlobalVariable(globalCurrentEventStr) currentEventStageStr = GetGlobalVariable(globalCurrentEventStageStr) currentEventStageNeedStr = GetGlobalVariable(globalCurrentEventStageNeedStr) SELECTCASE vwSelectedRowIndex CASE 8 ' Update the note ' Get the id for the selected need resource and its current note idEvStageNeedResId = vwSelectedRowArray[4] currentNoteStr = vwSelectedRowArray[5] ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Prompt a form to let the user change the current need resource not. The text size is limited up to 45 chars. newNoteStr = PromptForLongText("Indique la nota", currentNoteStr, 45) ' Build the Update SQL Statement to apply the change qryStr = "" qryStr = qryStr + " Update city_platform.event_stage_need_resource " qryStr = qryStr + " Set Note = '" + newNoteStr + "' " qryStr = qryStr + " Where ID_EV_ST_NEED_RES = " + idEvStageNeedResId ' Perforrm the update status = ODBCquery(linkName,qryStr, "eventStageArray") CASE 9 'Update need resource properties ' Get the id for the selected need resource and its current note idEvStageNeedResId = vwSelectedRowArray[4] ' PFC_CAT is a form contained the fields that user can modify templateStr = "PFC_CAT" fields[1] = "ID" fields[2] = "RES_CATEGORY" fields[3] = "RES_Q" fields[4] = "RES_UOM" defaultValues[1] = vwSelectedRowArray[4] defaultValues[2] = vwSelectedRowArray[1] defaultValues[3] = vwSelectedRowArray[2] defaultValues[4] = vwSelectedRowArray[3] PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 119 of 133 ' Open the form to let the user modify the information status = UserDialog(templateStr, "valuesArray", fields, defaultValues, "F", "T") If ( not(status) ) Then RETURN ENDIF ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Build the Update SQL Statement to apply the changes qryStr = "" qryStr = qryStr + " Update city_platform.event_stage_need_resource " qryStr = qryStr + " Set RES_CATEGORY ='" + valuesArray[2] + "' " qryStr = qryStr + " , RES_Q =" + valuesArray[3] + " " qryStr = qryStr + " , RES_UOM ='" + valuesArray[4] + "' " qryStr = qryStr + " Where ID_EV_ST_NEED_RES=" + valuesArray[1] ' Perform the update status = ODBCquery(linkName,qryStr, "eventResourceArray") CASE 10 ' Remove the selected resource from its need ' Ask the user to confirm before perform the action answer = PromptForYesNo("¿Está seguro que desea borrar?") If ( answer <> "Yes") Then RETURN ENDIF ' Get the id for the selected need resource and its current note idEvStageNeedResId = vwSelectedRowArray[4] ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' Build the Delete SQL Statement to remove the resource from its need qryStr = "" qryStr = qryStr + " Delete from city_platform.event_stage_need_resource " qryStr = qryStr + " Where ID_EV_ST_NEED_RES = " + idEvStageNeedResId ' Perform the delete status = ODBCquery(linkName,qryStr, "eventStageArray") CASE ELSE ' Any other field has no action linked to msgbox("Columna no reconocida para accion") Return ENDSELECT PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 120 of 133 ' Refresh the window status = RefreshVisualWorkflow("EVENTOS") ' End Return 15.2.6.10 ACCIONES PARA POBLAR LAS TABLAS DE LA PANTALLA 15.2.6.10.1 TABLA EVENTO NOMBRE: PFC_EVENT_TBL_INFO ' Get the current Event and Description currentEventStr = GetGlobalVariable(globalCurrentEventStr) currentEventDescriptionStr = GetGlobalVariable(globalCurrentEventDescriptionStr) ' If no event selected then abort this process If ( currentEventStr = ERROR ) Then eventArray[1, 1] = "" Return Endif ' Open the Database Connection linkName = "Resilience" status = ODBCclose(linkName) If ( not(IsODBCopen(linkName)) ) Then status = ODBCOPEN(linkName,"RESILIENCE","root","manager","F") Endif ' To be easier sort the fields displayed on the list an array is created adding sortly the fields as they have to be displayed on the list. clearArray("selectFieldArray") i = 1 selectFieldArray[i] = "DESCRIPTION" i = i + 1 selectFieldArray[i] = "EV_RESPONSIBLE" i = i + 1 selectFieldArray[i] = "INI_DATE" i = i + 1 selectFieldArray[i] = "END_DATE" i = i + 1 selectFieldArray[i] = "IF (COMPLETED ='T'" + " , '" + "images/R esilience/overrideon.png" + "', '" + "images/Resilience/overrideoff.png" + "') AS ICON" i = i + 1 selectFieldArray[i] = "CREATED_DATE" i = i + 1 selectFieldArray[i] = "CREATED_BY" i = i + 1 selectFieldArray[i] = "IF (SUCCESS ='T'" + " , '" + "images/Resil ience/approve.gif" + "', '" + "images/Resilience/redx.gif" + "') AS ICON" i = i + 1 PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 121 of 133 selectFieldArray[i] = "PUBLIC" i = i + 1 selectFieldArray[i] = "'images/Resilience/calendar.png'" i = i + 1 selectFieldArray[i] = "'images/Resilience/calendar.png'" i = i + 1 selectFieldArray[i] = "SUCCESS" i = i + 1 selectFieldArray[i] = "COMPLETED" i = i + 1 ' Convert the array to string separated by comma char as expected by the query SQL Statement selectFieldArrayStr = ArrayToCSVString(selectFieldArray, ", ") ' Build the Select SQL Statement and run the query on the database qryStr = "Select " + selectFieldArrayStr + " from city_platform.Event Where ID_EVENT =" + currentEventStr status = ODBCquery(linkName,qryStr, "eventArray") status = ODBCcolumns(linkName, "headerArray") headerArrayStr = ArrayToCSVString(headerArray, ", ") ' Get counter from the records returned by the query contRecordInt = UBound(eventArray, 1) ' If no records returned then this event has no resources already assigned If ( contRecordInt = 0 ) Then msgbox("No hay registros en Eventos") Return Endif 'Return the records returned by the query Return eventArray 15.2.6.10.2 TABLA ETAPAS DE UN EVENTO NOMBRE: PFC_EVENT_TBL_STAGES ' Set the fileName for the selected record recordSelectedStr = "recordSelected.gif" recordStr = "record.gif" ' Get the Current Event, Stage and need currentEventStr = GetGlobalVariable(globalCurrentEventStr) currentEventStageStr = GetGlobalVariable(globalCurrentEventStageStr) currentEventDescriptionStr = GetGlobalVariable(globalCurrentEventDescriptionStr) ' If no event selected then abort this process If ( currentEventStr = ERROR ) Then eventArray[1, 1] = "" Return Endif ' If no event selected then abort this process PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 128 of 133 15.3 SCRIPTS CREACION BASE DE DATOS A continuación vamos a encontrar los scripts que nos van a permitir construir la base de datos para el motor de base de datos MySql.que es el seleccionado para este módulo. 15.3.1 TABLA ADHOC INFO delimiter $$ CREATE TABLE `adhoc_info` ( `ID_ADHOC` int(11) NOT NULL, `EVENT` varchar(10) DEFAULT NULL, `CATEGORY` varchar(45) DEFAULT NULL, `QUANTITY` int(11) DEFAULT NULL, `UOM` varchar(45) DEFAULT NULL, `PICTURE` mediumblob, `NOTE` varchar(255) DEFAULT NULL, `IP` varchar(10) DEFAULT NULL, `LOCATION` varchar(45) DEFAULT NULL, `LOG_DATE` datetime DEFAULT NULL, `CONFIRMED` varchar(1) DEFAULT 'F', `RESOURCE_CLASS` varchar(10) DEFAULT 'ADHOC', `PUBLIC` varchar(1) DEFAULT 'T', `FUNGIBLE` varchar(1) DEFAULT 'T', `CURRENT_QUANTITY` int(11) DEFAULT NULL, PRIMARY KEY (`ID_ADHOC`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.2 TABLA CATEGORY delimiter $$ CREATE TABLE `category` ( `CAT_NAME` varchar(20) NOT NULL, `DESCRIPTION` varchar(45) DEFAULT NULL, `ACTIVE` varchar(1) DEFAULT 'F', `RELATED_CAT_1` varchar(20) DEFAULT NULL, `RELATED_CAT_2` varchar(20) DEFAULT NULL, `LOG_DATE` datetime DEFAULT NULL, `LOG_BY` varchar(20) DEFAULT NULL, `MOD_DATE` datetime DEFAULT NULL, `MOD_BY` varchar(20) DEFAULT NULL, PRIMARY KEY (`CAT_NAME`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.3 TABLA CATEGORY_EQUIVALENCE delimiter $$ CREATE TABLE `category_equivalence` ( `ID_CAT_EQUIV` int(11) NOT NULL, `PRIMARY_CAT` varchar(20) DEFAULT NULL, `PRIMARY_CAT_Q` int(11) DEFAULT '0', `PRIMARY_CAT_UOM` varchar(20) DEFAULT NULL, `EQ_CAT_01` varchar(20) DEFAULT NULL, `EQ_CAT_01_Q` int(11) DEFAULT '0', PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 129 of 133 `EQ_CAT_01_UOM` varchar(20) DEFAULT NULL, `EQ_CAT_02` varchar(20) DEFAULT NULL, `EQ_CAT_02_Q` int(11) DEFAULT '0', `EQ_CAT_02_UOM` varchar(20) DEFAULT NULL, `EQ_CAT_03` varchar(20) DEFAULT NULL, `EQ_CAT_03_Q` int(11) DEFAULT '0', `EQ_CAT_03_UOM` varchar(20) DEFAULT NULL, PRIMARY KEY (`ID_CAT_EQUIV`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.4 TABLA EVENT delimiter $$ CREATE TABLE `event` ( `ID_EVENT` int(11) NOT NULL, `INI_DATE` datetime DEFAULT NULL, `END_DATE` datetime DEFAULT NULL, `CREATED_DATE` datetime DEFAULT NULL, `CREATED_BY` varchar(20) DEFAULT NULL, `EV_RESPONSIBLE` varchar(45) DEFAULT NULL, `DESCRIPTION` varchar(45) DEFAULT NULL, `NOTE` varchar(45) DEFAULT NULL, `CONCLUSION` varchar(45) DEFAULT NULL, `SUCCESS` varchar(1) DEFAULT 'F', `PUBLIC` varchar(1) DEFAULT 'F', `COMPLETED` varchar(1) DEFAULT 'F', PRIMARY KEY (`ID_EVENT`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.5 TABLA EVENT_CATEGORY_EQUIVALENCE delimiter $$ CREATE TABLE `event_category_equivalence` ( `ID_EV_EQUIV` int(11) NOT NULL, `ID_CAT_EQUIV` int(11) NOT NULL, `PRIMARY_CAT` varchar(20) DEFAULT NULL, `PRIMARY_CAT_Q` int(11) DEFAULT NULL, `PRMARY_CAT_UOM` varchar(20) DEFAULT NULL, `EQ_CAT_01` varchar(20) DEFAULT NULL, `EQ_CAT_01_Q` int(11) DEFAULT NULL, `EQ_CAT_01_UOM` varchar(20) DEFAULT NULL, `EQ_CAT_02` varchar(20) DEFAULT NULL, `EQ_CAT_02_Q` int(11) DEFAULT NULL, `EQ_CAT_02_UOM` varchar(20) DEFAULT NULL, `EQ_CAT_03` varchar(20) DEFAULT NULL, `EQ_CAT_03_Q` int(11) DEFAULT NULL, `EQ_CAT_03_UOM` varchar(20) DEFAULT NULL, `ADDED_DATE` datetime DEFAULT NULL, `ADDED_BY` varchar(20) DEFAULT NULL, `MOD_DATE` datetime DEFAULT NULL, `MOD_BY` varchar(20) DEFAULT NULL, `ID_EVENT` int(11) DEFAULT NULL, PRIMARY KEY (`ID_EV_EQUIV`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 130 of 133 15.3.6 TABLA EVENT_DECISION_LOG delimiter $$ CREATE TABLE `event_decision_log` ( `ID_EV_DECISION` int(11) NOT NULL, `ID_EVENT` int(11) DEFAULT NULL, `DECISION_TYPE` varchar(20) DEFAULT NULL, `DECISION` varchar(200) DEFAULT NULL, `SUCCESS` varchar(1) DEFAULT NULL, `CREATED_DATE` datetime DEFAULT NULL, `CREATED_BY` varchar(20) DEFAULT NULL, PRIMARY KEY (`ID_EV_DECISION`), KEY `EVENT` (`ID_EVENT`), KEY `EVENT_dec` (`ID_EVENT`), CONSTRAINT `EVENT_dec` FOREIGN KEY (`ID_EVENT`) REFERENCES `event` (`ID_EVENT`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.7 TABLA EVENT_RESOUCE delimiter $$ CREATE TABLE `event_resource` ( `ID_EV_RES` int(11) NOT NULL, `ID_EVENT` int(11) DEFAULT NULL, `RESOURCE_CLASS` varchar(20) DEFAULT NULL, `RESOURCE_ID` int(11) DEFAULT NULL, `ACTIVE` varchar(1) DEFAULT 'T', `OBSOLETE` varchar(1) DEFAULT 'F', `PUBLIC` varchar(1) DEFAULT 'F', `SECURITY_GROUP` varchar(20) DEFAULT NULL, `NOTE` varchar(45) DEFAULT NULL, `ADDED_DATE` datetime DEFAULT NULL, `ADDED_BY` varchar(20) DEFAULT NULL, `MOD_DATE` datetime DEFAULT NULL, `MOD_BY` varchar(20) DEFAULT NULL, `RES_CATEGORY` varchar(45) DEFAULT NULL, `RES_Q` int(11) DEFAULT NULL, `RES_UOM` varchar(45) DEFAULT NULL, `FUNGIBLE` varchar(1) DEFAULT 'T', `CURRENT_QUANTITY` int(11) DEFAULT NULL, PRIMARY KEY (`ID_EV_RES`), KEY `EVENT_res` (`ID_EVENT`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.8 TABLA EVENT_STAGE delimiter $$ CREATE TABLE `event_stage` ( `ID_EVENT` int(11) NOT NULL, `ID_EV_STAGE` int(11) NOT NULL, `CREATED_DATE` datetime DEFAULT NULL, `CREATED_BY` varchar(20) DEFAULT NULL, `RELATED_STAGE` int(11) DEFAULT NULL, `INI_DATE` datetime DEFAULT NULL, `END_DATE` datetime DEFAULT NULL, `DESCRIPTION` varchar(45) DEFAULT NULL, `COMPLETED` varchar(1) DEFAULT 'F', `CONCLUSION` varchar(45) DEFAULT NULL, `SUCCESS` varchar(1) DEFAULT 'F', PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 131 of 133 PRIMARY KEY (`ID_EV_STAGE`), KEY `EVENT_stage` (`ID_EVENT`), CONSTRAINT `EVENT_stage` FOREIGN KEY (`ID_EVENT`) REFERENCES `event` (`ID_EVENT`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.9 TABLA EVENT_STAGE_DECISION_LOG delimiter $$ CREATE TABLE `event_stage_decision_log` ( `ID_EVENT` int(11) DEFAULT NULL, `ID_EV_STAGE` int(11) NOT NULL, `ID_EV_ST_DECISION` int(11) NOT NULL, `DECISION_TYPE` varchar(20) DEFAULT NULL, `DECISION` varchar(200) DEFAULT NULL, `SUCCESS` varchar(1) DEFAULT NULL, `CREATED_DATE` datetime DEFAULT NULL, `CREATED_BY` varchar(20) DEFAULT NULL, PRIMARY KEY (`ID_EV_ST_DECISION`), KEY `EVENT` (`ID_EVENT`), KEY `EVENT_dec` (`ID_EV_STAGE`), KEY `EVENT_ST_stage` (`ID_EV_STAGE`), CONSTRAINT `EVENT_ST_dec` FOREIGN KEY (`ID_EVENT`) REFERENCES `event` (`ID_EVENT`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `EVENT_ST_stage` FOREIGN KEY (`ID_EV_STAGE`) REFERENCES `event_stage` (`ID_EV_STAGE`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.10 TABLA EVENT_STAGE_NEED delimiter $$ CREATE TABLE `event_stage_need` ( `ID_EVENT` int(11) NOT NULL, `ID_EV_STAGE` int(11) NOT NULL, `ID_EV_ST_NEED` int(11) NOT NULL, `CREATED_DATE` datetime DEFAULT NULL, `CREATED_BY` varchar(20) DEFAULT NULL, `NEED_CATEGORY` varchar(20) DEFAULT NULL, `NEED_Q` int(11) DEFAULT NULL, `NEED_UOM` varchar(20) DEFAULT NULL, `COMPLETED` varchar(1) DEFAULT 'F', `NOTE` varchar(45) DEFAULT NULL, PRIMARY KEY (`ID_EV_ST_NEED`), KEY `EVENT` (`ID_EVENT`), KEY `EVENT_STAGE_NEED` (`ID_EV_STAGE`), CONSTRAINT `EVENT` FOREIGN KEY (`ID_EVENT`) REFERENCES `event` (`ID_EVENT`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `EVENT_STAGE_NEED` FOREIGN KEY (`ID_EV_STAGE`) REFERENCES `event_stage` (`ID_EV_STAGE`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.11 TABLA EVENT_STAGE_NEED_RESOURCE delimiter $$ CREATE TABLE `event_stage_need_resource` ( `ID_EVENT` int(11) NOT NULL, `ID_EV_STAGE` int(11) NOT NULL, `ID_EV_ST_NEED` int(11) NOT NULL, `ID_EV_ST_NEED_RES` int(11) NOT NULL, PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 132 of 133 `ID_EV_RES` int(11) NOT NULL, `ID_EV_RES_OBJ_CLASS` varchar(20) NOT NULL, `ID_EV_RES_CAT` varchar(20) NOT NULL, `CREATED_DATE` datetime DEFAULT NULL, `CREATED_BY` varchar(20) DEFAULT NULL, `RES_CATEGORY` varchar(20) DEFAULT NULL, `RES_Q` int(11) DEFAULT NULL, `RES_UOM` varchar(20) DEFAULT NULL, `NOTE` varchar(45) DEFAULT NULL, `FUNGIBLE` varchar(1) DEFAULT 'T', `CURRENT_QUANTITY` int(11) DEFAULT NULL, PRIMARY KEY (`ID_EV_ST_NEED_RES`), KEY `EVENT_need_res` (`ID_EVENT`), KEY `EVENT_STAGE_need_res` (`ID_EV_STAGE`), KEY `EVENT_STAGE_NEED_need_res` (`ID_EV_ST_NEED`), CONSTRAINT `EVENT_need_res` FOREIGN KEY (`ID_EVENT`) REFERENCES `event` (`ID_EVENT`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `EVENT_STAGE_NEED_need_res` FOREIGN KEY (`ID_EV_ST_NEED`) REFERENCES `event_stage_need` (`ID_EV_ST_NEED`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `EVENT_STAGE_need_res` FOREIGN KEY (`ID_EV_STAGE`) REFERENCES `event_stage` (`ID_EV_STAGE`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.12 TABLA EVENT_STAGE_OPERATION delimiter $$ CREATE TABLE `event_stage_operation` ( `ID_EVENT` int(11) NOT NULL, `ID_EV_STAGE` int(11) NOT NULL, `ID_EV_ST_OPER` int(11) NOT NULL, `CREATED_DATE` datetime DEFAULT NULL, `CREATED_BY` varchar(20) DEFAULT NULL, `DESCRIPTION` varchar(45) DEFAULT NULL, `COMPLETED` varchar(1) DEFAULT 'F', `NOTE` varchar(45) DEFAULT NULL, PRIMARY KEY (`ID_EV_ST_OPER`), KEY `EVENT_st_oper` (`ID_EVENT`), KEY `EVENT_STAGE_oper` (`ID_EV_STAGE`), CONSTRAINT `EVENT_STAGE_oper` FOREIGN KEY (`ID_EV_STAGE`) REFERENCES `event_stage` (`ID_EV_STAGE`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `EVENT_st_oper` FOREIGN KEY (`ID_EVENT`) REFERENCES `event` (`ID_EVENT`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ 15.3.13 TABLA SERVICE delimiter $$ CREATE TABLE `service` ( `ID_SERVICE` int(11) NOT NULL, `CATEGORY` varchar(10) DEFAULT NULL, `QUANTITY` int(11) DEFAULT NULL, `UOM` varchar(45) DEFAULT NULL, `ACTIVE` varchar(1) DEFAULT 'T', `OBSOLETE` varchar(1) DEFAULT 'F', `PUBLIC` varchar(1) DEFAULT 'F', `CONTACT_DATA` varchar(100) DEFAULT NULL, PFC RESILIENCE - MEMORIA DEL PROYECTO _______________________________________________________________________________________ Page 133 of 133 `DESCRIPTION` varchar(100) DEFAULT NULL, `LOG_DATE` datetime DEFAULT NULL, `LOG_BY` varchar(45) DEFAULT NULL, `MOD_DATE` datetime DEFAULT NULL, `MOD_BY` varchar(45) DEFAULT NULL, `RESOURCE_CLASS` varchar(10) DEFAULT 'SERVICE', `FUNGIBLE` varchar(1) DEFAULT 'T', `CURRENT_QUANTITY` int(11) DEFAULT NULL, PRIMARY KEY (`ID_SERVICE`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$